Files
Heimdall/src/Heimdall.Infrastructure/DependencyInjection.cs
T
Arnaud Dartois 58b6a1de9b feat(app): implement all open issues - camera access control, i18n, GPU, mDNS, site filtering
- Implement UserCameraAccess entity and CRUD API (issues #131, #133)
- Add CameraAccessPanel UI component for granular access management (issue #134)
- Implement camera toggle UI (issues #59, #199)
- Implement site filtering by user rights (issue #136)
- Implement Groups camera access assignment (issue #138)
- Implement audit logging for camera access changes (issue #140)
- Add comprehensive camera access test coverage (issue #141)
- Implement i18n/l10n localization infrastructure (issue #142)
- Implement OpenTelemetry metrics infrastructure (issue #14)
- Implement Agent GPU worker (issue #76)
- Implement Agent remote sensor mode (issue #75)
- Fix Docker GPU exposure in compose files (issues #76, #77)
- Fix mDNS divergence by extracting shared MdnsClient library (issue #81)
- Implement User email confirm/edit UI (issues #88, #89)
- Implement Persons UI (issue #11)
- Fix E2E test timing issues by increasing circuit delay

- Add MdnsClient library with unified unicast/multicast mDNS support
- Refactor MdnsProbeService and HomeKitMdnsProbe to use shared client
- Add GroupCameraAccess entity for group-based camera access
- Add comprehensive camera access test coverage
- Add i18n localization infrastructure with fr/en support
- Add Docker GPU exposure for NVIDIA/AMD/Intel
- Update Docker compose files with GPU device exposure
- Fix mDNS divergence between Central unicast and Agent multicast
- Fix E2E test timing issues with increased circuit delay

All 1700+ tests pass (unit + integration)
2026-10-11 21:23:16 +02:00

193 lines
9.5 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 Heimdall.Mdns;
using Microsoft.AspNetCore.DataProtection;
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,
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>());
// 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>());
// 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"]);
// Identity
services.AddIdentity<AppUser, AppRole>(options =>
{
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>();
// Camera discovery services (used by CQRS handlers)
services.AddHttpClient("Discovery", client =>
{
client.DefaultRequestHeaders.ConnectionClose = true;
});
services.AddSingleton<IMdnsClient, MdnsClient>();
services.AddSingleton<StreamTesterService>();
services.AddSingleton<ICameraDatabase, SqliteCameraDatabase>();
services.AddTransient<IOnvifProbeService, OnvifProbeService>();
services.AddTransient<IMdnsProbeService, MdnsProbeService>();
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.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;
}
}