Files
Heimdall/src/Heimdall.Infrastructure/DependencyInjection.cs
T
Arnaud Dartois 53b6240a3e fix(auth): répare l'authentification de bout en bout (cookie + JWT + rendu Blazor)
Anomalies corrigées :
- MudPopoverProvider manquant dans les layouts → circuit Blazor mourait sur
  l'ouverture de menus/popovers (dashboard jamais rendu après login)
- AddIdentity redéfinissait le schéma par défaut sur Identity.Application
  alors que /_auth/signin signait avec Cookies → cookie posé mais jamais
  validé, tout rechargement de page redirigeait vers /login. Forçage du
  schéma par défaut sur Cookies + schémas JwtBearer explicites sur les
  endpoints API d'AuthController et SettingsController
- Policy 'AdminUsers' utilisée par register-admin mais jamais enregistrée
  → 500 à l'appel. Ajoutée (RequireRole Admin)
- HeimdallAuthStateProvider ne lisait que le sessionStorage navigateur :
  pendant le prerender SSR, HttpContext.User (cookie) n'était pas utilisé
  → pages protégées redirigées vers /login. Fallback cookie ajouté
- SameOriginHttpMessageHandler : résolution de l'origine via
  IServerAddressesFeature quand IHttpContextAccessor est null (circuit
  Blazor post-hydratation) au lieu de heimdall.local → DNS cassé
- UpdateUserValidator rejetait le thème 'Auto' (défaut de l'UI) → 400
  à l'édition. Accepte désormais auto (case-insensitive)

Tests :
- E2E Playwright complets (login/logout/register/user management) : 33/33
- Integration (Testcontainers PostgreSQL) : 120/120 (valeur 'bool' du
  valueType, bootstrap admin via /register auto-admin, header X-API-Key,
  /proc/meminfo optionnel pour les LXC restreints)
- Exécution E2E séquentielle (xunit.runner.json) pour éliminer le flakiness
2026-08-09 23:43:11 +02:00

166 lines
8.0 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.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 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>());
// 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<StreamTesterService>();
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>();
// 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>();
return services;
}
}