Files
Heimdall/src/Heimdall.Infrastructure/DependencyInjection.cs
T
Arnaud Dartois d67cbd64cc refactor(cqrs): cleanup old service layer, preserve discovery/assignment services for handlers
- Remove 13 old service interfaces from Application/Services
- Remove 13 old service implementations from Infrastructure/Services
- Remove old SnapshotService (no CQRS replacement needed)
- Update Infrastructure DI to register only CQRS-compatible services
- Preserve CameraEventService + PersonService for existing tests
- Clean up duplicate IUserRepository registration
2026-07-22 20:00:49 +00:00

134 lines
6.1 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")));
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");
}
else
{
// Production: Keys are persisted to /var/lib/heimdall/dp-keys via a Docker volume.
// Without the volume, container restart permanently breaks credential decryption.
var dpDir = new DirectoryInfo("/var/lib/heimdall/dp-keys");
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, ""));
}
#pragma warning disable SYSLIB0057 // X509Certificate2(string, string) is obsolete — X509CertificateLoader not available in this SDK
var dpCert = new X509Certificate2(certFile.FullName, "");
#pragma warning restore SYSLIB0057
dpBuilder.ProtectKeysWithCertificate(dpCert);
}
// JWT
services.AddScoped<IJwtService, JwtService>();
// Credential encryption
services.AddScoped<ICredentialProtector, DataProtectorCredentialProtector>();
// 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>();
return services;
}
}