2026-07-19 19:33:10 +00:00
using System.IO ;
2026-07-20 14:07:27 +00:00
using System.Security.Cryptography ;
using System.Security.Cryptography.X509Certificates ;
2026-07-22 19:43:13 +00:00
using Heimdall.Application.Common ;
using Heimdall.Application.Common.Persistence ;
2026-08-12 08:45:18 +02:00
using Heimdall.Application.Discovery ;
2026-07-16 20:53:56 +00:00
using Heimdall.Application.Services ;
using Heimdall.Domain.Entities ;
using Heimdall.Infrastructure.Data ;
2026-07-19 19:58:45 +00:00
using Heimdall.Infrastructure.Data.Interceptors ;
2026-07-22 19:43:13 +00:00
using Heimdall.Infrastructure.Persistence ;
2026-07-16 20:53:56 +00:00
using Heimdall.Infrastructure.Security ;
using Heimdall.Infrastructure.Services ;
2026-07-19 12:00:16 +00:00
using Heimdall.Infrastructure.Services.Discovery ;
2026-08-12 10:14:40 +02:00
using Heimdall.Infrastructure.Storage ;
2026-10-11 21:23:16 +02:00
using Heimdall.Mdns ;
2026-07-19 19:33:10 +00:00
using Microsoft.AspNetCore.DataProtection ;
2026-07-16 20:53:56 +00:00
using Microsoft.AspNetCore.Identity ;
using Microsoft.EntityFrameworkCore ;
using Microsoft.Extensions.Configuration ;
using Microsoft.Extensions.DependencyInjection ;
namespace Heimdall.Infrastructure ;
public static class DependencyInjection
{
public static IServiceCollection AddInfrastructure (
this IServiceCollection services ,
2026-07-21 07:23:33 +00:00
IConfiguration configuration )
2026-07-16 20:53:56 +00:00
{
2026-07-20 09:50:43 +00:00
// EF Core interceptor (registered as singleton — it is stateless)
2026-07-19 19:58:45 +00:00
services . AddSingleton < AuditInterceptor >();
2026-07-21 12:19:43 +00:00
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 =>
2026-08-09 23:43:11 +02:00
npgsql . MigrationsHistoryTable ( "__EFMigrationsHistory" , "public" )),
ServiceLifetime . Scoped ); // must be Scoped: AddDbContext registers DbContextOptions as Scoped, and a Singleton factory would fail DI validation (singleton → scoped)
2026-07-16 20:53:56 +00:00
2026-07-22 19:43:13 +00:00
services . AddScoped < IApplicationDbContext >( sp => sp . GetRequiredService < AppDbContext >());
2026-08-12 10:14:40 +02:00
// 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 >());
2026-10-22 19:58:05 +02:00
services . AddScoped < IStorageObjectDeletion >( sp => sp . GetRequiredService < StorageProviderFactory >());
2026-08-12 10:14:40 +02:00
2026-08-12 09:54:37 +02:00
// Health checks (spec 13.2) — PostgreSQL + dépendances optionnelles.
services . AddHealthChecks ()
. AddDbContextCheck < AppDbContext >( "postgres" , tags : [ "ready" , "live" ])
. AddCheck < Infrastructure . HealthChecks . AlarikHealthCheck >( "alarik" , tags : [ "ready" ])
. AddCheck < Infrastructure . HealthChecks . AiHealthCheck >( "codeproject-ai" , tags : [ "live" ]);
2026-07-16 20:53:56 +00:00
// Identity
services . AddIdentity < AppUser , AppRole >( options =>
{
options . Password . RequiredLength = 12 ;
options . Password . RequireDigit = true ;
options . Password . RequireLowercase = true ;
2026-07-21 08:47:24 +00:00
options . Password . RequireUppercase = true ;
options . Password . RequireNonAlphanumeric = true ;
2026-07-16 20:53:56 +00:00
options . Lockout . MaxFailedAccessAttempts = 5 ;
options . Lockout . DefaultLockoutTimeSpan = TimeSpan . FromMinutes ( 15 );
})
. AddEntityFrameworkStores < AppDbContext >()
. AddDefaultTokenProviders ();
2026-07-17 20:07:03 +00:00
// Data Protection (for camera credential encryption)
2026-07-21 07:23:33 +00:00
var dpMode = configuration . GetValue < string >( "DataProtection:Mode" ) ?? "Persisted" ;
if ( dpMode == "Ephemeral" )
2026-07-20 14:07:27 +00:00
{
2026-07-20 15:44:20 +00:00
// Tests: use ephemeral keys (no persistence, no certificate encryption)
services . AddDataProtection ()
. SetApplicationName ( "Heimdall" );
2026-07-29 14:20:14 +00:00
Console . WriteLine ( "[DIAG] Data Protection: mode=Ephemeral (no key persistence)" );
2026-07-20 14:07:27 +00:00
}
2026-07-20 15:44:20 +00:00
else
{
// Production: Keys are persisted to /var/lib/heimdall/dp-keys via a Docker volume.
// Without the volume, container restart permanently breaks credential decryption.
2026-08-09 23:43:11 +02:00
// 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 );
2026-07-20 15:44:20 +00:00
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 , "" ));
2026-07-29 14:20:14 +00:00
Console . WriteLine ( $"[DIAG] Data Protection: new self-signed cert generated at {certFile.FullName}" );
2026-07-20 15:44:20 +00:00
}
2026-07-20 14:07:27 +00:00
#pragma warning disable SYSLIB0057 // X509Certificate2(string, string) is obsolete — X509CertificateLoader not available in this SDK
2026-07-20 19:58:32 +00:00
var dpCert = new X509Certificate2 ( certFile . FullName , "" );
2026-07-29 14:20:14 +00:00
Console . WriteLine ( $"[DIAG] Data Protection: mode=Persisted, keys dir={dpDir.FullName}, cert exists={certFile.Exists}" );
2026-07-20 14:07:27 +00:00
#pragma warning restore SYSLIB0057
2026-07-20 15:44:20 +00:00
dpBuilder . ProtectKeysWithCertificate ( dpCert );
}
2026-07-20 14:07:27 +00:00
2026-07-16 20:53:56 +00:00
// JWT
services . AddScoped < IJwtService , JwtService >();
2026-07-17 20:07:03 +00:00
// Credential encryption
services . AddScoped < ICredentialProtector , DataProtectorCredentialProtector >();
2026-07-22 20:05:59 +00:00
// 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 >();
2026-07-22 19:43:13 +00:00
// Data access
services . AddScoped < IUserRepository , UserRepository >();
2026-07-22 20:00:49 +00:00
// Camera discovery services (used by CQRS handlers)
2026-07-19 12:00:16 +00:00
services . AddHttpClient ( "Discovery" , client =>
{
client . DefaultRequestHeaders . ConnectionClose = true ;
});
2026-10-11 21:23:16 +02:00
services . AddSingleton < IMdnsClient , MdnsClient >();
2026-07-19 12:00:16 +00:00
services . AddSingleton < StreamTesterService >();
2026-08-12 08:45:18 +02:00
services . AddSingleton < ICameraDatabase , SqliteCameraDatabase >();
2026-07-19 12:00:16 +00:00
services . AddTransient < IOnvifProbeService , OnvifProbeService >();
services . AddTransient < IMdnsProbeService , MdnsProbeService >();
services . AddTransient < IHttpProbeService , HttpProbeService >();
services . AddTransient < IArpProbeService , ArpProbeService >();
services . AddTransient < IPortScanService , PortScanService >();
services . AddTransient < ICameraDiscoveryService , CameraDiscoveryService >();
2026-07-19 12:20:07 +00:00
services . AddTransient < DiscoveryCoordinatorService >();
2026-07-22 20:00:49 +00:00
// Camera assignment service (used by CQRS handlers)
2026-07-19 12:20:07 +00:00
services . AddScoped < ICameraAssignmentService , CameraAssignmentService >();
2026-07-19 12:00:16 +00:00
2026-08-27 20:28:41 +02:00
// Camera access control (used by CQRS handlers and MonitoringHub)
services . AddScoped < ICameraAccessService , CameraAccessService >();
2026-08-26 23:44:38 +02:00
// Analysis job scheduler (capability + affinity + load routing)
services . AddScoped < IAnalysisJobSchedulerService , AnalysisJobSchedulerService >();
2026-07-26 20:45:35 +00:00
// Notification services
services . AddScoped < INotificationService , NotificationService >();
services . AddSingleton < INotificationRateLimiter , NotificationRateLimiter >();
services . AddScoped < IEmailService , EmailService >();
2026-07-27 04:56:16 +00:00
services . AddScoped < INtfyService , NtfyService >();
services . AddHttpClient ( "Ntfy" , client =>
2026-07-26 20:45:35 +00:00
{
client . Timeout = TimeSpan . FromSeconds ( 10 );
});
2026-07-28 14:52:52 +00:00
// Error reporting (Sentry/GlitchTip via IErrorReporter abstraction)
services . AddScoped < IErrorReporter , SentryErrorReporter >();
2026-08-20 18:14:18 +02:00
// HaveIBeenPwned — password breach check (k-anonymity, fail-open on error)
services . AddPwnedServices ( configuration );
services . AddScoped < IPasswordBreachChecker , HaveIBeenPwnedBreachChecker >();
2026-07-16 20:53:56 +00:00
return services ;
}
}