using Sentry.AspNetCore; using System.Globalization; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; using FluentValidation.AspNetCore; using Heimdall.Application; using Heimdall.Application.Metrics; using Heimdall.Application.Services; using Heimdall.Infrastructure; using Heimdall.Infrastructure.Data; using Heimdall.Infrastructure.BackgroundJobs; using Heimdall.Infrastructure.Security; using Heimdall.Web.Components; using Heimdall.Api.Hubs; using Heimdall.Api; using Heimdall.Web.Services; using Heimdall.Web; using Hangfire; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Localization; using Microsoft.AspNetCore.Components.Authorization; using Microsoft.AspNetCore.RateLimiting; using Microsoft.AspNetCore.Routing; using OpenTelemetry.Metrics; using Microsoft.EntityFrameworkCore; using Microsoft.IdentityModel.Tokens; using MudBlazor.Services; using System.Threading.RateLimiting; using Scalar.AspNetCore; var builder = WebApplication.CreateBuilder(args); // ── Use shared service configuration ────────────────────────────── Program.ConfigureServices(builder); var app = builder.Build(); // ── Use shared middleware configuration ─────────────────────────── Program.ConfigureMiddleware(app); // ── Apply pending database migrations ──────────────────────────────── // Retry with exponential backoff to handle container startup races where // PostgreSQL accepts TCP connections but isn't ready to serve queries yet. // Migrations run by default in every environment EXCEPT Testing // (appsettings.Testing.json sets Database:MigrateOnStartup=false; test // factories opt back in explicitly when they need the schema). var migrateOnStartup = builder.Configuration.GetValue("Database:MigrateOnStartup") ?? !app.Environment.IsEnvironment(TestingEnvironment); if (migrateOnStartup) { await Program.ApplyMigrationsAsync(app); } // ── Register recurring Hangfire jobs (heartbeat monitor, agent failover) ── var isTesting = app.Environment.IsEnvironment(TestingEnvironment); var pgConnStr = Environment.GetEnvironmentVariable("DATABASE_URL") ?? app.Configuration.GetConnectionString("Default"); if (!isTesting && !string.IsNullOrEmpty(pgConnStr)) { using (var scope = app.Services.CreateScope()) { var manager = scope.ServiceProvider.GetRequiredService(); Heimdall.Infrastructure.BackgroundJobs.JobSetup.ConfigureRecurringJobs(manager); } } // ── Seed Identity roles (required in ALL environments, including Testing) ─ // This must run before any user registration — AuthService.AddToRoleAsync // throws "Role X does not exist" if the role hasn't been created yet. await Program.SeedAsync(app, builder.Configuration); app.Run(); // ─── DTO for the cookie sign-in request ─────────────────────────── internal sealed record SignInRequest( string AccessToken); // Partial class declaration so WebApplicationFactory // works in integration tests. public partial class Program { private const string TestingEnvironment = "Testing"; // SonarQube S1118: partial class used by WebApplicationFactory needs a constructor. protected Program() { } private static string ResolveCategory(string key) { if (key.StartsWith("ntfy.", StringComparison.Ordinal) || key.StartsWith("email.", StringComparison.Ordinal)) return "integrations"; if (key.StartsWith("ai.", StringComparison.Ordinal)) return "ai"; return "agent"; } private static string FormatSentryStatus(bool enabled, string? dsn) { if (!enabled) return "DISABLED (toggle sentry.enabled=false — redémarrage requis)"; if (string.IsNullOrEmpty(dsn)) return "NOT CONFIGURED — errors will NOT be reported to GlitchTip"; var atIndex = dsn.IndexOf('@'); return $"configured ({dsn[..atIndex]}@...)"; } // Shared JWT validation parameters — single source of truth for auth. internal static TokenValidationParameters GetJwtValidationParameters(string key, string issuer, string audience) => new() { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)), ValidateIssuer = true, ValidIssuer = issuer, ValidateAudience = true, ValidAudience = audience, ValidateLifetime = true, ClockSkew = TimeSpan.Zero }; /// /// Creates a configured WebApplication suitable for testing. /// Used by E2E tests to start a real Kestrel server. /// public static WebApplication CreateTestApplication(string[]? args = null, Action? configure = null) { var builder = WebApplication.CreateBuilder(args ?? []); // Under xUnit the entry assembly is "testhost", so the framework would // look for "testhost.staticwebassets.runtime.json" and serve none of the // Blazor framework files (_framework/blazor.web.js etc.). Pin the app name // to Heimdall.Web and load the static web assets manifest copied next to // the test assembly so the Blazor runtime, MudBlazor CSS and wwwroot serve. builder.Environment.ApplicationName = "Heimdall.Web"; builder.WebHost.UseStaticWebAssets(); // Allow test-specific overrides BEFORE service configuration // (so config values are available when services read them) configure?.Invoke(builder); // Apply the standard service configuration ConfigureServices(builder); var app = builder.Build(); ConfigureMiddleware(app); return app; } /// /// Applies pending EF migrations with retry/backoff. Shared between the /// normal entry point and test hosts (E2E) so both boot paths behave identically. /// public static async Task ApplyMigrationsAsync(WebApplication app) { // Use a 5-minute overall timeout so startup doesn't hang indefinitely // if the database is unreachable. Each retry respects this token. using var migrationCts = new CancellationTokenSource(TimeSpan.FromMinutes(5)); var migrationCt = migrationCts.Token; using (var scope = app.Services.CreateScope()) { var logger = scope.ServiceProvider.GetRequiredService>(); var db = scope.ServiceProvider.GetRequiredService(); var maxRetries = 5; var retryDelay = TimeSpan.FromSeconds(2); for (var attempt = 1; attempt <= maxRetries; attempt++) { try { migrationCt.ThrowIfCancellationRequested(); logger.LogInformation("Applying database migrations (attempt {Attempt}/{MaxRetries})...", attempt, maxRetries); // Suppress EF Core model validation warnings (10622) about required navigations with global query filters // These warnings are promoted to exceptions when the model has pending changes; suppress them here // to allow migrations to proceed. Matching query filters are defined in OnModelCreating. await db.Database.MigrateAsync(migrationCt); logger.LogInformation("Database migrations applied successfully"); break; } catch (OperationCanceledException) { logger.LogCritical("Database migration timed out after 5 minutes."); throw; } catch (Exception ex) when (attempt < maxRetries) { logger.LogWarning(ex, "Database migration attempt {Attempt}/{MaxRetries} failed. Retrying in {Delay}s...", attempt, maxRetries, retryDelay.TotalSeconds); await Task.Delay(retryDelay, migrationCt); retryDelay = TimeSpan.FromSeconds(retryDelay.TotalSeconds * 2); } catch (Exception ex) { logger.LogCritical(ex, "Failed to apply database migrations after {MaxRetries} attempts.", maxRetries); throw; } } } } /// /// Seeds Identity roles, default groups and (optionally) the demo admin + demo site. /// Idempotent — safe to call on every startup and from test hosts. /// public static async Task SeedAsync(WebApplication app, IConfiguration configuration) { using var seedScope = app.Services.CreateScope(); var roleManager = seedScope.ServiceProvider .GetRequiredService>(); var userManager = seedScope.ServiceProvider .GetRequiredService>(); var groupDb = seedScope.ServiceProvider.GetRequiredService(); await SeedRolesAsync(roleManager); await seedScope.ServiceProvider.GetRequiredService() .EnsureDefaultsAsync(CancellationToken.None); await SeedGroupsAsync(groupDb); var existingKeys = await GetExistingSettingKeysAsync(groupDb); await SeedStorageSettingsAsync(groupDb, existingKeys); await SeedIntegrationSettingsAsync(groupDb, existingKeys); await MigrateLegacySentryKeysAsync(groupDb); await SeedDemoDataAsync(configuration, userManager, groupDb); } private static async Task SeedRolesAsync(Microsoft.AspNetCore.Identity.RoleManager roleManager) { foreach (var roleName in AppRoles.All) { if (!await roleManager.RoleExistsAsync(roleName)) { await roleManager.CreateAsync(new Heimdall.Infrastructure.Identity.IdentityAppRole(roleName)); } } } private static async Task SeedGroupsAsync(AppDbContext groupDb) { var defaultGroups = new[] { "Administrateurs", "Superviseurs", "Visiteurs", "Techniciens" }; foreach (var groupName in defaultGroups) { if (!await groupDb.Groups.AnyAsync(g => g.Name == groupName)) { groupDb.Groups.Add(new Heimdall.Domain.Entities.Group(groupName, groupName switch { "Administrateurs" => "Accès complet à toutes les fonctionnalités", "Superviseurs" => "Gestion des sites, caméras et événements", "Visiteurs" => "Consultation en lecture seule", "Techniciens" => "Maintenance technique et support", _ => null })); } } await groupDb.SaveChangesWithRetryAsync(); } private static async Task> GetExistingSettingKeysAsync(AppDbContext groupDb) => new( await groupDb.AppSettings.Select(s => s.Key).ToListAsync(), StringComparer.OrdinalIgnoreCase); private static async Task SeedStorageSettingsAsync(AppDbContext groupDb, HashSet existingKeys) { var defaults = new Dictionary { ["storage.provider"] = "Local", ["storage.local.path"] = Environment.GetEnvironmentVariable("STORAGE__LOCAL__PATH") ?? "./data/storage", ["storage.s3.endpoint"] = Environment.GetEnvironmentVariable("ALARIK_ENDPOINT") ?? Environment.GetEnvironmentVariable("S3_ENDPOINT"), ["storage.s3.bucket"] = Environment.GetEnvironmentVariable("S3_BUCKET") ?? "heimdall", ["storage.s3.accessKey"] = Environment.GetEnvironmentVariable("S3_ACCESS_KEY"), ["storage.s3.secretKey"] = Environment.GetEnvironmentVariable("S3_SECRET_KEY"), ["storage.s3.region"] = Environment.GetEnvironmentVariable("S3_REGION") ?? "us-east-1", }; foreach (var (key, value) in defaults) { if (existingKeys.Contains(key)) continue; groupDb.AppSettings.Add(new Heimdall.Domain.Entities.AppSetting( key, value ?? string.Empty, "storage", key switch { "storage.provider" => "Provider de stockage actif (Local | S3)", "storage.local.path" => "Chemin racine du stockage local", "storage.s3.endpoint" => "Endpoint S3 (Alarik/MinIO)", "storage.s3.bucket" => "Bucket S3", "storage.s3.accessKey" => "Clé d'accès S3", "storage.s3.secretKey" => "Clé secrète S3", "storage.s3.region" => "Région S3", _ => key }, agentScoped: false)); } await groupDb.SaveChangesWithRetryAsync(); } private static async Task SeedIntegrationSettingsAsync(AppDbContext groupDb, HashSet existingKeys) { var heartbeatInterval = Environment.GetEnvironmentVariable("HEARTBEAT__INTERVAL_SECONDS"); if (!int.TryParse(heartbeatInterval, out var heartbeatSeconds) || heartbeatSeconds is < 5 or > 300) heartbeatInterval = "30"; var defaults = new Dictionary { ["ntfy.baseUrl"] = string.Empty, ["ntfy.token"] = string.Empty, ["email.fromAddress"] = string.Empty, ["email.fromName"] = "Heimdall", ["email.smtpHost"] = string.Empty, ["email.smtpPort"] = "587", ["email.username"] = string.Empty, ["email.password"] = string.Empty, ["email.useSsl"] = "true", ["ai.cpaiUrl"] = Environment.GetEnvironmentVariable("CPAI_URL"), ["ai.ollamaUrl"] = string.Empty, ["updates.releaseapiurl"] = string.Empty, ["ai.detection.enabled"] = Environment.GetEnvironmentVariable("AI__DETECTION__ENABLED") ?? "true", ["log.level"] = Environment.GetEnvironmentVariable("LOG__LEVEL") ?? "info", ["log.retentionDays"] = Environment.GetEnvironmentVariable("LOG__RETENTION_DAYS") ?? "7", ["heartbeat.interval.seconds"] = heartbeatInterval, ["sentry.enabled"] = "true", }; var existingHeartbeatSetting = await groupDb.AppSettings .FirstOrDefaultAsync(setting => setting.Key == "heartbeat.interval.seconds"); if (existingHeartbeatSetting is not null && (!int.TryParse(existingHeartbeatSetting.Value, out var storedHeartbeatSeconds) || storedHeartbeatSeconds is < 5 or > 300)) existingHeartbeatSetting.UpdateValue(heartbeatInterval); foreach (var (key, value) in defaults) { if (existingKeys.Contains(key)) continue; var agentScoped = !(key.StartsWith("ntfy.", StringComparison.Ordinal) || key.StartsWith("email.", StringComparison.Ordinal) || key.StartsWith("sentry.", StringComparison.Ordinal) || key.StartsWith("updates.", StringComparison.Ordinal)); var category = ResolveCategory(key); groupDb.AppSettings.Add(new Heimdall.Domain.Entities.AppSetting( key, value ?? string.Empty, category, key switch { "ntfy.baseUrl" => "Serveur ntfy (URL de base)", "ntfy.token" => "Token d'accès ntfy", "email.fromAddress" => "Adresse expéditrice des emails", "email.fromName" => "Nom expéditeur des emails", "email.smtpHost" => "Serveur SMTP", "email.smtpPort" => "Port SMTP", "email.username" => "Utilisateur SMTP", "email.password" => "Mot de passe SMTP", "email.useSsl" => "Utiliser SSL/TLS pour SMTP", "ai.cpaiUrl" => "URL CodeProject.AI", "ai.ollamaUrl" => "URL Ollama", "updates.releaseapiurl" => "API des versions Heimdall (HTTPS)", "ai.detection.enabled" => "Détection IA activée par défaut", "log.level" => "Niveau de log global (agents + central)", "log.retentionDays" => "Rétention des logs agents (jours)", "heartbeat.interval.seconds" => "Intervalle de heartbeat des agents (secondes)", "sentry.enabled" => "Autoriser l'envoi des erreurs vers GlitchTip (nécessite un redémarrage)", _ => key }, agentScoped)); } await groupDb.SaveChangesWithRetryAsync(); } private static async Task MigrateLegacySentryKeysAsync(AppDbContext groupDb) { await groupDb.AppSettings .Where(s => s.Key.StartsWith("ntfy.") || s.Key.StartsWith("email.") || s.Key.StartsWith("storage.") || s.Key.StartsWith("sentry.")) .ExecuteUpdateAsync(s => s.SetProperty(x => x.AgentScoped, false)); var legacySentryDsn = await groupDb.AppSettings .FirstOrDefaultAsync(s => s.Key == "sentry.dsn"); if (legacySentryDsn is not null) groupDb.AppSettings.Remove(legacySentryDsn); await groupDb.SaveChangesWithRetryAsync(); } private static async Task SeedDemoDataAsync( IConfiguration configuration, Microsoft.AspNetCore.Identity.UserManager userManager, AppDbContext groupDb) { if (!configuration.GetValue("Seed:DemoOnStartup", false)) return; var adminLogin = configuration.GetValue("Seed:AdminLogin") ?? Environment.GetEnvironmentVariable("SEED__ADMIN_LOGIN") ?? "admin@heimdall.test"; var testAdmin = await userManager.FindByEmailAsync(adminLogin); if (testAdmin is null) { testAdmin = new Heimdall.Infrastructure.Identity.IdentityAppUser { UserName = adminLogin, Email = adminLogin, DisplayName = configuration.GetValue("Seed:AdminDisplayName") ?? Environment.GetEnvironmentVariable("SEED__ADMIN_DISPLAYNAME") ?? "Admin" }; var adminPassword = configuration["Seed:AdminPassword"] ?? Environment.GetEnvironmentVariable("SEED__ADMIN_PASSWORD") ?? throw new InvalidOperationException("Seed:AdminPassword is required in config or SEED__ADMIN_PASSWORD env var. Set this env var to create the demo admin on startup."); var created = await userManager.CreateAsync(testAdmin, adminPassword); if (!created.Succeeded) throw new InvalidOperationException("Configured demo administrator could not be created: " + string.Join(',', created.Errors.Select(e => e.Code))); var assigned = await userManager.AddToRoleAsync(testAdmin, AppRoles.Admin); if (!assigned.Succeeded) { await userManager.DeleteAsync(testAdmin); throw new InvalidOperationException("Configured demo administrator role could not be assigned: " + string.Join(',', assigned.Errors.Select(e => e.Code))); } } var demoSite = await groupDb.Sites.FirstOrDefaultAsync(s => s.Name == "Site Démo"); if (demoSite is null) { demoSite = new Heimdall.Domain.Entities.Site("Site Démo", "Paris", "Europe/Paris"); groupDb.Sites.Add(demoSite); await groupDb.SaveChangesWithRetryAsync(); } } internal static void ConfigureServices(WebApplicationBuilder builder) { Console.WriteLine($"[DIAG] Environment: {builder.Environment.EnvironmentName}"); Console.WriteLine($"[DIAG] Data Protection keys dir: /var/lib/heimdall/dp-keys"); Console.WriteLine($"[DIAG] Demo seeding: {(builder.Configuration.GetValue("Seed:DemoOnStartup", false) ? "enabled" : "disabled (set Seed:DemoOnStartup=true to enable)")}"); builder.Services.AddLocalization(options => options.ResourcesPath = "Localization"); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddRazorComponents() .AddInteractiveServerComponents(); builder.Services.AddMemoryCache(); ConfigureAuthentication(builder); ConfigureMudAndRateLimiting(builder); ConfigureControllers(builder); ConfigureSignalR(builder); // ── OpenTelemetry metrics (spec 13.1) ────────────────────────────── // Expose Heimdall metrics via Prometheus /metrics endpoint. // Auto-instruments ASP.NET Core HTTP request metrics. builder.Services.AddOpenTelemetry() .WithMetrics(metrics => { metrics.AddPrometheusExporter(); metrics.AddAspNetCoreInstrumentation(); metrics.AddMeter(HeimdallMetrics.MeterName); metrics.AddMeter(Heimdall.Infrastructure.Metrics.HangfireJobMetrics.MeterName); metrics.AddMeter(Heimdall.Infrastructure.Metrics.NotificationOutboxMetrics.MeterName); }); builder.Services.AddApplication(); builder.Services.AddInfrastructure(builder.Configuration); ConfigureSentry(builder); ConfigureAuthScheme(builder); ConfigureBackgroundJobs(builder); ConfigureHttpClients(builder); builder.Services.AddScoped(); } private static void ConfigureMudAndRateLimiting(WebApplicationBuilder builder) { builder.Services.AddMudServices(config => { config.SnackbarConfiguration.PositionClass = "mud-alert-center-top"; config.SnackbarConfiguration.PreventDuplicates = true; config.SnackbarConfiguration.ShowCloseIcon = true; config.SnackbarConfiguration.VisibleStateDuration = 4000; }); builder.Services.AddRateLimiter(options => { options.RejectionStatusCode = 429; // Spec §4.3 / §2082: Auth 5 tent/15min par IP, API 100 req/min, Snapshot 1000 req/min par Agent. // Global limiter partitions by client IP (via X-Forwarded-For behind reverse proxy), // then per-endpoint named policies enforce their own limits. options.GlobalLimiter = PartitionedRateLimiter.Create(ctx => RateLimitPartition.Get(GetClientIp(ctx), _ => new FixedWindowRateLimiter(new FixedWindowRateLimiterOptions { PermitLimit = 100, QueueLimit = 0, Window = TimeSpan.FromMinutes(1), }))); options.AddFixedWindowLimiter("Auth", opt => { opt.PermitLimit = 5; opt.Window = TimeSpan.FromMinutes(15); opt.QueueLimit = 0; }); options.AddFixedWindowLimiter("Api", opt => { opt.PermitLimit = 100; opt.Window = TimeSpan.FromMinutes(1); opt.QueueLimit = 0; }); options.AddFixedWindowLimiter("TwoFactor", opt => { opt.PermitLimit = 5; opt.Window = TimeSpan.FromMinutes(1); opt.QueueLimit = 0; }); options.AddFixedWindowLimiter("Snapshot", opt => { opt.PermitLimit = 1000; opt.Window = TimeSpan.FromMinutes(1); opt.QueueLimit = 0; }); }); } private static string GetClientIp(HttpContext ctx) { // X-Forwarded-For: client, proxy1, proxy2 - take the first (leftmost) entry. var forwarded = ctx.Request.Headers["X-Forwarded-For"].FirstOrDefault(); if (!string.IsNullOrEmpty(forwarded)) { var ip = forwarded.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)[0]; if (!string.IsNullOrEmpty(ip)) return ip; } return ctx.Connection.RemoteIpAddress?.ToString() ?? "unknown"; } private static void ConfigureControllers(WebApplicationBuilder builder) { builder.Services.AddScoped(); builder.Services.AddSingleton(); builder.Services.AddControllers(options => { options.Filters.Add(); options.Filters.Add(); }) .AddJsonOptions(options => { options.JsonSerializerOptions.Converters.Add( new System.Text.Json.Serialization.JsonStringEnumConverter()); }) .AddApplicationPart(typeof(Program).Assembly); builder.Services.AddFluentValidationAutoValidation(); builder.Services.Configure(opts => opts.SerializerOptions.Converters.Add(new System.Text.Json.Serialization.JsonStringEnumConverter())); builder.Services.AddOpenApi(); } private static void ConfigureSignalR(WebApplicationBuilder builder) { builder.Services.AddSignalR(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); } private static void ConfigureAuthScheme(WebApplicationBuilder builder) { builder.Services.Configure(options => { options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; }); builder.Services.ConfigureApplicationCookie(options => { options.LoginPath = "/login"; options.LogoutPath = "/_auth/signout"; options.AccessDeniedPath = "/not-found"; options.Cookie.Name = ".Heimdall.Auth"; options.Cookie.HttpOnly = true; options.Cookie.SameSite = SameSiteMode.Lax; options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest; options.ExpireTimeSpan = TimeSpan.FromDays(7); options.SlidingExpiration = false; }); } private static void ConfigureBackgroundJobs(WebApplicationBuilder builder) { var isTesting = builder.Environment.IsEnvironment(TestingEnvironment); var connectionString = Environment.GetEnvironmentVariable("DATABASE_URL") ?? builder.Configuration.GetConnectionString("Default"); if (!isTesting && !string.IsNullOrEmpty(connectionString)) builder.Services.AddBackgroundJobs(builder.Configuration); } private static void ConfigureHttpClients(WebApplicationBuilder builder) { builder.Services.AddHttpContextAccessor(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(sp => { var handler = ActivatorUtilities.CreateInstance(sp); var origin = ActivatorUtilities.CreateInstance(sp); origin.InnerHandler = sp.GetRequiredService().CreateHandler("HeimdallApi"); handler.InnerHandler = origin; return handler; }); builder.Services.AddTransient(); builder.Services.AddHttpClient("HeimdallRefresh") .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { UseCookies = false }); var apiBaseUrlConfigured = ApiBaseUrlResolver.IsConfigured(builder.Configuration); var apiBaseUrl = apiBaseUrlConfigured ? ApiBaseUrlResolver.ResolveConfigured(builder.Configuration)! : ApiBaseUrlResolver.PlaceholderBase; builder.Services.AddHttpClient("HeimdallApi", client => { var baseUrl = apiBaseUrl.EndsWith('/') ? apiBaseUrl : apiBaseUrl + "/"; client.BaseAddress = new Uri(baseUrl); client.Timeout = TimeSpan.FromSeconds(30); }).ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { UseCookies = false }); if (apiBaseUrlConfigured) Console.WriteLine($"[DIAG] ApiBaseUrl: {apiBaseUrl} (explicit)"); else Console.WriteLine("[DIAG] ApiBaseUrl: same-origin (no explicit config)"); } private static void ConfigureAuthentication(WebApplicationBuilder builder) { var jwtKey = builder.Configuration["Jwt:Key"] ?? Environment.GetEnvironmentVariable("JWT__KEY") ?? throw new InvalidOperationException("JWT:Key is not configured"); var jwtIssuer = builder.Configuration["Jwt:Issuer"] ?? Environment.GetEnvironmentVariable("JWT__ISSUER") ?? "heimdall"; var jwtAudience = builder.Configuration["Jwt:Audience"] ?? Environment.GetEnvironmentVariable("JWT__AUDIENCE") ?? "heimdall-api"; var authBuilder = builder.Services .AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme); ConfigureCookieAuthentication(authBuilder); ConfigureJwtBearerAuthentication(authBuilder, jwtKey, jwtIssuer, jwtAudience); authBuilder.AddScheme("ApiKey", null); ConfigureAuthorizationPolicies(builder); builder.Services.AddCascadingAuthenticationState(); builder.Services.AddScoped(); builder.Services.AddScoped( sp => sp.GetRequiredService()); } private static void ConfigureCookieAuthentication(AuthenticationBuilder authBuilder) { authBuilder.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => { options.LoginPath = "/login"; options.LogoutPath = "/_auth/signout"; options.AccessDeniedPath = "/not-found"; options.Cookie.Name = AuthState.AuthCookieName; options.Cookie.HttpOnly = true; options.Cookie.SameSite = SameSiteMode.Lax; // Use SameAsRequest to support both HTTP and HTTPS deployments // In production with HTTPS, the cookie will still be secure options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest; options.ExpireTimeSpan = TimeSpan.FromDays(7); options.SlidingExpiration = false; // Add logging events options.Events = new CookieAuthenticationEvents { OnValidatePrincipal = async context => { if (!await ValidateAccountSessionAsync(context.Principal!, context.HttpContext)) context.RejectPrincipal(); }, OnRedirectToLogin = context => { var logger = context.HttpContext.RequestServices.GetRequiredService>(); logger.LogWarning("Redirect to login: {Path} -> {LoginPath}", context.Request.Path, options.LoginPath); // API requests (JSON or /api/*) must get a 401, not a // browser redirect — otherwise unauthenticated API calls // silently follow the redirect and report 200. if (IsApiRequest(context.Request)) { context.Response.StatusCode = StatusCodes.Status401Unauthorized; return Task.CompletedTask; } context.Response.Redirect(context.RedirectUri); return Task.CompletedTask; }, OnRedirectToAccessDenied = context => { var logger = context.HttpContext.RequestServices.GetRequiredService>(); logger.LogWarning("Access denied: {Path} -> {AccessDeniedPath}", context.Request.Path, options.AccessDeniedPath); if (IsApiRequest(context.Request)) { context.Response.StatusCode = StatusCodes.Status403Forbidden; return Task.CompletedTask; } context.Response.Redirect(context.RedirectUri); return Task.CompletedTask; } }; }); } private static Task ValidateAccountSessionAsync(ClaimsPrincipal principal, HttpContext http) => Heimdall.Application.Auth.Services.AccountSessionPolicy.IsValidAsync(principal, http.RequestServices.GetRequiredService(), http.RequestServices.GetRequiredService(), http.RequestAborted); private static void ConfigureJwtBearerAuthentication(AuthenticationBuilder authBuilder, string jwtKey, string jwtIssuer, string jwtAudience) { authBuilder.AddJwtBearer("JwtBearer", options => { options.TokenValidationParameters = GetJwtValidationParameters(jwtKey, jwtIssuer, jwtAudience); options.Events = new JwtBearerEvents { OnTokenValidated = async context => { if (!await ValidateAccountSessionAsync(context.Principal!, context.HttpContext)) context.Fail("Session revoked"); }, OnMessageReceived = context => { var accessToken = context.Request.Query["access_token"]; var path = context.HttpContext.Request.Path; if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/hubs")) context.Token = accessToken; return Task.CompletedTask; } }; }); } private static void ConfigureAuthorizationPolicies(WebApplicationBuilder builder) { builder.Services.AddAuthorizationCore(options => { var allPermissions = AppPermissions.RolePermissions.Values.SelectMany(p => p).Distinct(); foreach (var permission in allPermissions) options.AddPolicy(permission, policy => policy.RequireClaim("permission", permission)); // Legacy role-based policy retained for administrative endpoints. options.AddPolicy("AdminUsers", policy => policy.RequireRole(AppRoles.Admin)); }); } private static void ConfigureSentry(WebApplicationBuilder builder) { var sentryDsn = builder.Configuration["Sentry:Dsn"] ?? Environment.GetEnvironmentVariable("SENTRY_DSN"); var isTestingEnv = builder.Environment.IsEnvironment(TestingEnvironment); var sentryEnabled = !isTestingEnv && IsSentryEnabledFromDb(builder.Services); if (sentryEnabled && !string.IsNullOrEmpty(sentryDsn)) { builder.WebHost.UseSentry((SentryAspNetCoreOptions options) => ConfigureSentryOptions(options, builder, sentryDsn)); } var sentryStatus = FormatSentryStatus(sentryEnabled, sentryDsn); Console.WriteLine($"[DIAG] Sentry/GlitchTip DSN: {sentryStatus}"); } private static void ConfigureSentryOptions(SentryAspNetCoreOptions options, WebApplicationBuilder builder, string sentryDsn) { options.Dsn = sentryDsn; options.Release = builder.Configuration["Sentry:Release"] ?? Environment.GetEnvironmentVariable("SENTRY_RELEASE"); options.SampleRate = 1.0f; options.AttachStacktrace = true; options.MaxBreadcrumbs = 100; options.MinimumBreadcrumbLevel = LogLevel.Debug; options.MinimumEventLevel = LogLevel.Error; options.TracesSampleRate = double.Parse( builder.Configuration["Sentry:TracesSampleRate"] ?? "0.05", System.Globalization.CultureInfo.InvariantCulture); options.MaxRequestBodySize = Sentry.Extensibility.RequestSize.Small; options.EnableLogs = true; options.AutoSessionTracking = false; options.SendDefaultPii = false; options.ServerName = null; options.CaptureBlockingCalls = true; options.CaptureFailedRequests = true; options.IncludeActivityData = true; options.StackTraceMode = Sentry.StackTraceMode.Enhanced; options.SetBeforeSend(static (sentryEvent, _) => { sentryEvent.ServerName = null; if (sentryEvent.Extra?.ContainsKey("password") == true) (sentryEvent.Extra as IDictionary)?.Remove("password"); if (sentryEvent.Extra?.ContainsKey("token") == true) (sentryEvent.Extra as IDictionary)?.Remove("token"); if (sentryEvent.Extra?.ContainsKey("secret") == true) (sentryEvent.Extra as IDictionary)?.Remove("secret"); return sentryEvent; }); options.SetBeforeBreadcrumb(breadcrumb => breadcrumb.Category == "Microsoft.AspNetCore.RateLimiting" ? null : breadcrumb); } internal static void ConfigureMiddleware(WebApplication app) { if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error", createScopeForErrors: true); app.UseHsts(); } // Only enable HTTPS redirection if HTTPS is actually configured on Kestrel. // In production behind a reverse proxy (nginx, Traefik, Caddy), TLS is // terminated at the proxy level — Kestrel runs on HTTP internally, so // this block is intentionally skipped (ASPNETCORE_URLS has no https://). // The proxy handles the HTTP to HTTPS redirect. var urls = Environment.GetEnvironmentVariable("ASPNETCORE_URLS") ?? ""; if (urls.Contains("https://", StringComparison.OrdinalIgnoreCase)) { app.UseHttpsRedirection(); } app.UseStaticFiles(); app.UseAuthentication(); app.UseAuthorization(); app.UseAntiforgery(); // Localization: determine culture from query string, cookie, or Accept-Language header var supportedCultures = new[] { "fr", "en" }; var localizationOptions = new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture("fr"), SupportedCultures = supportedCultures.Select(c => new CultureInfo(c)).ToList(), SupportedUICultures = supportedCultures.Select(c => new CultureInfo(c)).ToList(), }; localizationOptions.RequestCultureProviders.Insert(0, new QueryStringRequestCultureProvider()); localizationOptions.RequestCultureProviders.Insert(1, new CookieRequestCultureProvider()); app.UseRequestLocalization(localizationOptions); // Hangfire dashboard — Admin uniquement (policy AdminJobs). // MapHangfireDashboard est utilisé car UseHangfireDashboard avec // DashboardOptions.Authorization n'existe pas pour les policies ASP.NET. // Skip en Testing : Hangfire y est désactivé (pas de AddHangfire). if (!app.Environment.IsEnvironment(TestingEnvironment)) { app.MapHangfireDashboard("/hangfire", new DashboardOptions { Authorization = [ new HangfireAdminAuthorizationFilter(), ], }); } app.MapRazorComponents().AddInteractiveServerRenderMode(); app.MapControllers(); app.MapHub("/hubs/config"); app.MapHub("/hubs/events"); app.MapHub("/hubs/monitoring"); app.MapHub("/hubs/notifications"); app.MapHub("/hubs/admin"); // Diagnostic: log all mapped endpoints so E2E host mapping issues are visible. if (app.Environment.IsEnvironment(TestingEnvironment)) { var dataSource = app.Services.GetRequiredService(); var endpoints = dataSource.Endpoints .Select(e => e is Microsoft.AspNetCore.Routing.RouteEndpoint re ? re.RoutePattern.RawText : e.ToString()) .Where(s => !string.IsNullOrEmpty(s)) .OrderBy(s => s, StringComparer.Ordinal) .ToList(); Console.WriteLine($"[DIAG] Mapped endpoints ({endpoints.Count}): {string.Join(", ", endpoints)}"); } if (app.Environment.IsDevelopment()) { app.MapOpenApi(); app.MapScalarApiReference(); } var allowedOrigins = app.Configuration["Cors:AllowedOrigins"]?.Split(',') ?? ["https://localhost:5001"]; app.UseCors(options => { var isWildcard = allowedOrigins.Length == 1 && allowedOrigins[0] == "*"; if (isWildcard) { options.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod(); } else { options.WithOrigins(allowedOrigins).AllowCredentials() .AllowAnyHeader().WithMethods("GET", "POST", "PUT", "DELETE", "PATCH"); } }); app.UseRateLimiter(); // ── Prometheus metrics endpoint (spec 13.1) ──────────────────────── // /metrics — scraped by Prometheus. No auth (internal network only). app.MapPrometheusScrapingEndpoint("/metrics"); MapAuthEndpoints(app); } internal static void MapAuthEndpoints(WebApplication app) { var jwtKey = app.Configuration["Jwt:Key"] ?? Environment.GetEnvironmentVariable("JWT__KEY") ?? ""; var jwtIssuer = app.Configuration["Jwt:Issuer"] ?? Environment.GetEnvironmentVariable("JWT__ISSUER") ?? "heimdall"; var jwtAudience = app.Configuration["Jwt:Audience"] ?? Environment.GetEnvironmentVariable("JWT__AUDIENCE") ?? "heimdall-api"; app.MapPost("/_auth/signin", async (HttpContext httpContext, SignInRequest request, ILogger logger) => { if (string.IsNullOrEmpty(request.AccessToken)) return Results.BadRequest(new { error = "AccessToken is required" }); try { var handler = new JwtSecurityTokenHandler(); var principal = handler.ValidateToken(request.AccessToken, GetJwtValidationParameters(jwtKey, jwtIssuer, jwtAudience), out _); if (!await ValidateAccountSessionAsync(principal, httpContext)) return Results.Unauthorized(); var userId = principal.FindFirst(ClaimTypes.NameIdentifier)?.Value; var email = principal.FindFirst(ClaimTypes.Email)?.Value; var displayName = principal.FindFirst(ClaimTypes.Name)?.Value; if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(email)) return Results.BadRequest(new { error = "Invalid token: missing user claims" }); var claims = new List { new(ClaimTypes.NameIdentifier, userId), new(ClaimTypes.Email, email), new(ClaimTypes.Name, displayName ?? email), }; claims.Add(new Claim(Heimdall.Application.Auth.Services.AccountSessionPolicy.StampClaim, principal.FindFirstValue(Heimdall.Application.Auth.Services.AccountSessionPolicy.StampClaim)!)); claims.Add(new Claim(Heimdall.Application.Auth.Services.AccountSessionPolicy.StartedClaim, principal.FindFirstValue(Heimdall.Application.Auth.Services.AccountSessionPolicy.StartedClaim)!)); foreach (var role in principal.FindAll(ClaimTypes.Role)) claims.Add(new Claim(ClaimTypes.Role, role.Value)); foreach (var permission in principal.FindAll("permission")) claims.Add(new Claim("permission", permission.Value)); var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), new AuthenticationProperties { IsPersistent = false, AllowRefresh = false, ExpiresUtc = DateTimeOffset.Parse(principal.FindFirstValue(Heimdall.Application.Auth.Services.AccountSessionPolicy.StartedClaim)!, System.Globalization.CultureInfo.InvariantCulture).AddDays(7) }); return Results.Ok(); } catch (SecurityTokenExpiredException) { return Results.Unauthorized(); } catch (Exception ex) { return Results.BadRequest(new { error = $"Token validation failed: {ex.Message}" }); } }); app.MapPost("/_auth/signout", async (HttpContext httpContext, ILogger logger) => { await httpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); return Results.Ok(); }); } /// /// True for JSON/API requests (Accept: application/json or an /api/* path). /// Used by the cookie challenge handlers to return 401/403 instead of a /// browser redirect — API clients must not be silently redirected to /login. /// private static bool IsApiRequest(HttpRequest request) { if (request.Path.StartsWithSegments("/api")) return true; var accept = request.Headers.Accept.ToString(); return accept.Contains("application/json", StringComparison.OrdinalIgnoreCase); } /// /// Lit le toggle global sentry.enabled en base (défaut true). Table absente /// au premier démarrage ou DB indisponible -> activé (comportement sûr). /// private static bool IsSentryEnabledFromDb(IServiceCollection services) { try { using var sp = services.BuildServiceProvider(); using var scope = sp.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); return db.AppSettings.AsNoTracking() .FirstOrDefault(s => s.Key == "sentry.enabled")?.Value != "false"; } catch { return true; } } }