Heimdall Gitea / Detect CI scope (pull_request) Successful in 1m27s
Heimdall Gitea / Build and tests (pull_request) Failing after 12m27s
Heimdall Gitea / Build and scan server image (pull_request) Skipped
Heimdall Gitea / Build and scan agent image (pull_request) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (pull_request) Skipped
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / Publish versioned release (pull_request) Skipped
Heimdall Gitea / CI policy (pull_request) Failing after 4s
207 lines
11 KiB
C#
207 lines
11 KiB
C#
using System.IO;
|
|
using System.Security.Cryptography;
|
|
using System.Security.Cryptography.X509Certificates;
|
|
using Heimdall.Application.Common;
|
|
using Heimdall.Application.Common.Persistence;
|
|
using Heimdall.Application.Discovery;
|
|
using Heimdall.Application.Services;
|
|
using Heimdall.Domain.Entities;
|
|
using Heimdall.Infrastructure.Data;
|
|
using Heimdall.Infrastructure.Data.Interceptors;
|
|
using Heimdall.Infrastructure.Persistence;
|
|
using Heimdall.Infrastructure.Security;
|
|
using Heimdall.Infrastructure.Services;
|
|
using Heimdall.Infrastructure.Services.Discovery;
|
|
using Heimdall.Infrastructure.Storage;
|
|
using Microsoft.AspNetCore.DataProtection;
|
|
using Microsoft.AspNetCore.Identity;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
|
using Heimdall.Infrastructure.Identity;
|
|
namespace Heimdall.Infrastructure;
|
|
|
|
public static class DependencyInjection
|
|
{
|
|
public static IServiceCollection AddInfrastructure(
|
|
this IServiceCollection services,
|
|
IConfiguration configuration)
|
|
{
|
|
// EF Core interceptor (registered as singleton — it is stateless)
|
|
services.AddSingleton<AuditInterceptor>();
|
|
|
|
var connectionString = Environment.GetEnvironmentVariable("DATABASE_URL")
|
|
?? configuration.GetConnectionString("Default")
|
|
?? throw new InvalidOperationException(
|
|
"Database connection string is not configured. Set DATABASE_URL env var or ConnectionStrings:Default.");
|
|
services.AddDbContext<AppDbContext>(options =>
|
|
options.UseNpgsql(connectionString, npgsql =>
|
|
npgsql.MigrationsHistoryTable("__EFMigrationsHistory", "public")));
|
|
services.AddDbContextFactory<AppDbContext>(options =>
|
|
options.UseNpgsql(connectionString, npgsql =>
|
|
npgsql.MigrationsHistoryTable("__EFMigrationsHistory", "public")),
|
|
ServiceLifetime.Scoped); // must be Scoped: AddDbContext registers DbContextOptions as Scoped, and a Singleton factory would fail DI validation (singleton → scoped)
|
|
|
|
services.AddScoped<IApplicationDbContext>(sp => sp.GetRequiredService<AppDbContext>());
|
|
services.AddScoped<IIdentityPersistenceContext>(sp => sp.GetRequiredService<AppDbContext>());
|
|
services.AddOptions<PlateOcrOptions>()
|
|
.Bind(configuration.GetSection(PlateOcrOptions.SectionName))
|
|
.Validate(options => options.IsValid(), "Plate OCR options are invalid")
|
|
.ValidateOnStart();
|
|
services.AddSingleton<ILicensePlateOcr, TesseractPlateOcr>();
|
|
services.AddScoped<ILicensePlateRecognitionService, LicensePlateRecognitionService>();
|
|
|
|
// Stockage (spec Phase 8) — provider résolu depuis les settings DB
|
|
// (storage.provider = Local | S3), factory scoped (lit la config à
|
|
// chaque résolution → changement UI sans redémarrage).
|
|
services.AddSingleton<StorageProviderFactory>();
|
|
services.AddScoped<IStorageProvider>(sp => sp.GetRequiredService<StorageProviderFactory>());
|
|
services.AddScoped<IStorageObjectDeletion>(sp => sp.GetRequiredService<StorageProviderFactory>());
|
|
|
|
// Health checks (spec 13.2) — PostgreSQL + dépendances optionnelles.
|
|
services.AddHealthChecks()
|
|
.AddDbContextCheck<AppDbContext>("postgres", tags: ["ready", "live"])
|
|
.AddCheck<Infrastructure.HealthChecks.StorageHealthCheck>(
|
|
"storage", failureStatus: Microsoft.Extensions.Diagnostics.HealthChecks.HealthStatus.Degraded,
|
|
tags: ["ready"], timeout: TimeSpan.FromSeconds(8))
|
|
.AddCheck<Infrastructure.HealthChecks.AiHealthCheck>("codeproject-ai", tags: ["live"]);
|
|
|
|
// Identity
|
|
services.AddIdentity<IdentityAppUser, IdentityAppRole>(options =>
|
|
{
|
|
options.User.RequireUniqueEmail = true;
|
|
options.SignIn.RequireConfirmedEmail = false; // Heimdall enforces the configurable policy at its auth boundary.
|
|
options.Lockout.AllowedForNewUsers = true;
|
|
options.Password.RequiredLength = 12;
|
|
options.Password.RequireDigit = true;
|
|
options.Password.RequireLowercase = true;
|
|
options.Password.RequireUppercase = true;
|
|
options.Password.RequireNonAlphanumeric = true;
|
|
options.Lockout.MaxFailedAccessAttempts = 5;
|
|
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15);
|
|
})
|
|
.AddEntityFrameworkStores<AppDbContext>()
|
|
.AddDefaultTokenProviders();
|
|
|
|
// Data Protection (for camera credential encryption)
|
|
var dpMode = configuration.GetValue<string>("DataProtection:Mode") ?? "Persisted";
|
|
if (dpMode == "Ephemeral")
|
|
{
|
|
// Tests: use ephemeral keys (no persistence, no certificate encryption)
|
|
services.AddDataProtection()
|
|
.SetApplicationName("Heimdall");
|
|
Console.WriteLine("[DIAG] Data Protection: mode=Ephemeral (no key persistence)");
|
|
}
|
|
else
|
|
{
|
|
// Production: Keys are persisted to /var/lib/heimdall/dp-keys via a Docker volume.
|
|
// Without the volume, container restart permanently breaks credential decryption.
|
|
// The directory is configurable (DataProtection:KeysDirectory / DP_KEYS_DIR) so
|
|
// dev/test runs outside the container can point to a writable location.
|
|
var dpKeysDir = configuration.GetValue<string>("DataProtection:KeysDirectory")
|
|
?? Environment.GetEnvironmentVariable("DP_KEYS_DIR")
|
|
?? "/var/lib/heimdall/dp-keys";
|
|
Directory.CreateDirectory(dpKeysDir); // idempotent, creates parents if needed
|
|
var dpDir = new DirectoryInfo(dpKeysDir);
|
|
var dpBuilder = services.AddDataProtection()
|
|
.PersistKeysToFileSystem(dpDir)
|
|
.SetApplicationName("Heimdall");
|
|
|
|
// Auto-bootstrap a self-signed certificate for key encryption.
|
|
// This prevents the "No XML encryptor configured" warning and ensures
|
|
// DP keys are encrypted at rest within the persistent volume.
|
|
var certFile = new FileInfo(Path.Combine(dpDir.FullName, "dp-cert.pfx"));
|
|
if (!certFile.Exists)
|
|
{
|
|
dpDir.Create();
|
|
using var rsa = RSA.Create(4096);
|
|
var req = new CertificateRequest(
|
|
"CN=Heimdall-DataProtection",
|
|
rsa,
|
|
HashAlgorithmName.SHA256,
|
|
RSASignaturePadding.Pkcs1);
|
|
req.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, false));
|
|
req.CertificateExtensions.Add(new X509KeyUsageExtension(
|
|
X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DataEncipherment, false));
|
|
req.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(
|
|
new OidCollection { new("1.3.6.1.4.1.311.80.1") }, false)); // Data Protection OID
|
|
using var cert = req.CreateSelfSigned(
|
|
DateTimeOffset.UtcNow.AddDays(-1),
|
|
DateTimeOffset.UtcNow.AddYears(10));
|
|
File.WriteAllBytes(certFile.FullName, cert.Export(X509ContentType.Pfx, ""));
|
|
Console.WriteLine($"[DIAG] Data Protection: new self-signed cert generated at {certFile.FullName}");
|
|
}
|
|
|
|
#pragma warning disable SYSLIB0057 // X509Certificate2(string, string) is obsolete — X509CertificateLoader not available in this SDK
|
|
var dpCert = new X509Certificate2(certFile.FullName, "");
|
|
Console.WriteLine($"[DIAG] Data Protection: mode=Persisted, keys dir={dpDir.FullName}, cert exists={certFile.Exists}");
|
|
#pragma warning restore SYSLIB0057
|
|
dpBuilder.ProtectKeysWithCertificate(dpCert);
|
|
}
|
|
|
|
// JWT
|
|
services.AddScoped<IJwtService, JwtService>();
|
|
|
|
// Credential encryption
|
|
services.AddScoped<ICredentialProtector, DataProtectorCredentialProtector>();
|
|
|
|
// Role permissions (used by CQRS auth handlers)
|
|
services.AddScoped<IRolePermissionService, RolePermissionService>();
|
|
|
|
// Auth data service (used by CQRS register/refresh/logout handlers)
|
|
services.AddScoped<IAuthDataService, AuthDataService>();
|
|
|
|
// Auth sign-in service (used by CQRS login handler)
|
|
services.AddScoped<IAuthSignInService, AuthSignInService>();
|
|
|
|
// Data access
|
|
services.AddScoped<IUserRepository, UserRepository>();
|
|
services.AddScoped<IIdentityAccountService, IdentityAccountService>();
|
|
|
|
// Camera discovery services (used by CQRS handlers)
|
|
services.AddHttpClient("Discovery", client =>
|
|
{
|
|
client.DefaultRequestHeaders.ConnectionClose = true;
|
|
});
|
|
services.AddSingleton<StreamTesterService>();
|
|
services.AddSingleton<ICameraDatabase, SqliteCameraDatabase>();
|
|
services.AddTransient<IOnvifProbeService, OnvifProbeService>();
|
|
services.AddTransient<IHttpProbeService, HttpProbeService>();
|
|
services.AddTransient<IArpProbeService, ArpProbeService>();
|
|
services.AddTransient<IPortScanService, PortScanService>();
|
|
services.AddTransient<ICameraDiscoveryService, CameraDiscoveryService>();
|
|
services.AddTransient<DiscoveryCoordinatorService>();
|
|
|
|
// Camera assignment service (used by CQRS handlers)
|
|
services.AddScoped<ICameraAssignmentService, CameraAssignmentService>();
|
|
|
|
// Camera access control (used by CQRS handlers and MonitoringHub)
|
|
services.AddScoped<ICameraAccessService, CameraAccessService>();
|
|
|
|
// Analysis job scheduler (capability + affinity + load routing)
|
|
services.AddScoped<IAnalysisJobSchedulerService, AnalysisJobSchedulerService>();
|
|
|
|
// Notification services
|
|
services.AddScoped<INotificationService, NotificationService>();
|
|
services.AddScoped<NotificationDeliveryProcessor>();
|
|
services.AddHostedService<BackgroundJobs.NotificationOutboxMetricsReporter>();
|
|
services.AddSingleton<INotificationRateLimiter, NotificationRateLimiter>();
|
|
services.AddScoped<IEmailService, EmailService>();
|
|
services.AddScoped<INtfyService, NtfyService>();
|
|
services.AddHttpClient("Ntfy", client =>
|
|
{
|
|
client.Timeout = TimeSpan.FromSeconds(10);
|
|
});
|
|
|
|
// Error reporting (Sentry/GlitchTip via IErrorReporter abstraction)
|
|
services.AddScoped<IErrorReporter, SentryErrorReporter>();
|
|
|
|
// HaveIBeenPwned — password breach check (k-anonymity, fail-open on error)
|
|
services.AddPwnedServices(configuration);
|
|
services.AddScoped<IPasswordBreachChecker, HaveIBeenPwnedBreachChecker>();
|
|
|
|
return services;
|
|
}
|
|
}
|