Files
Heimdall/src/Heimdall.Infrastructure/DependencyInjection.cs
T
Arnaud Dartois 450e019617 feat(infra): intégration Sentry/GlitchTip complète
- Upgrade Sentry.AspNetCore v6.7.0 → v6.8.0
- Ajout Sentry base package à Infrastructure (pour SentryErrorReporter)
- Configuration SDK enrichie dans Web et Agent:
  - AutoSessionTracking=false (GlitchTip ne supporte pas)
  - EnableLogs=true (logs structurés)
  - CaptureBlockingCalls=true (détection .Result/.Wait())
  - CaptureFailedRequests=true (capture 4xx/5xx HttpClient)
  - IncludeActivityData=true (DiagnosticSource)
  - SetBeforeSend pour nettoyage PII (password, token, secret)
  - SetBeforeBreadcrumb pour filtrage breadcrumbs
  - SampleRate, AttachStacktrace, MaxBreadcrumbs configurés
  - Release depuis la config, Environment auto
  - StackTraceMode.Enhanced
  - double.Parse avec CultureInfo.InvariantCulture
  - UseSentry avec type explicite SentryAspNetCoreOptions
- Abstraction IErrorReporter dans Application (0 dép. Sentry)
- Implémentation SentryErrorReporter dans Infrastructure
- Enregistrement DI dans Infrastructure
- DSN de développement dans appsettings.Development.json
- .env.example avec Sentry__Dsn et Sentry__TracesSampleRate
2026-07-28 14:52:52 +00:00

156 lines
7.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")));
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>();
// 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;
}
}