Files
Heimdall/src/Heimdall.Web/Program.cs
T
arnaud.dartois 1d60f04691
Heimdall Gitea / Detect CI scope (push) Successful in 33s
Heimdall Gitea / Build and tests (push) Successful in 26m42s
Heimdall Gitea / Publish versioned release (push) Skipped
Heimdall Gitea / Build and scan server image (push) Successful in 8m45s
Heimdall Gitea / Build and scan agent image (push) Successful in 9m14s
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Successful in 19m34s
Heimdall Gitea / Publish Docker Hub latest tags (push) Successful in 1m37s
Heimdall Gitea / CI policy (push) Successful in 2s
fix(auth): safely report cookie sign-in failures (#310)
## Résumé
Le flux navigateur reçoit maintenant un résultat HTTP explicite du pont cookie; les échecs de cookie sont diagnostiqués sans exposer les messages d’exception ni les données de session. La validation 2FA par code de récupération recharge également l’utilisateur après rotation du security stamp avant d’émettre la session.

## Issue
Refs #304 — l’observation GlitchTip post-déploiement reste nécessaire avant résolution.

## Travail effectué
- `/_auth/signin` renvoie des erreurs génériques et journalise uniquement l’étape et le type d’exception.
- Le pont JavaScript retourne le statut HTTP; les interruptions de circuit sont distinctes des réponses non-2xx.
- Suppression des adresses e-mail des journaux auth/2FA.
- Correction du chemin code de récupération 2FA pour émettre un jeton cohérent avec le security stamp actualisé.
- Ajout de tests unitaires et d’intégration; documentation dans `skills/heimdall-identity/SKILL.md`.

## Preuves
- `dotnet restore tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj --locked-mode` — réussi.
- `dotnet restore tests/Heimdall.IntegrationTests/Heimdall.IntegrationTests.csproj --locked-mode` — réussi.
- `AuthHelperTests` — 6/6 réussis.
- Tests d’intégration ciblés 2FA/recovery-cookie/TOTP-cookie/token malformé — 3/3 réussis.
- Acceptance Compose source-built `heimdall-auth-cookie-20261108170745-28547` — bootstrap 200, TOTP 200, cookie sign-in 200, API avec cookie 200, jeton malformé 401 générique, secrets absents des logs. Nettoyage vérifié: conteneurs/volumes/réseau absents et tag `heimdall:heimdall-auth-cookie-20261108170745-28547-central` supprimé.
- Analyse de l’événement GlitchTip: le circuit navigateur se déconnecte avant toute trace HTTP observée de `/_auth/signin`; la cause de cette occurrence production reste donc non démontrée. La correction améliore la visibilité sûre et le flux synthétique, sans prétendre reproduire cet événement.

## À suivre
Après déploiement de ce commit, observer GlitchTip pendant au moins sept jours et vérifier si HEIMDALL-DU réapparaît. Ne pas résoudre l’issue avant cette preuve réelle.

Reviewed-on: #310
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-08 20:03:03 +01:00

1081 lines
52 KiB
C#

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 Microsoft.AspNetCore.StaticFiles;
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<bool?>("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))
{
await Program.ConfigureRecurringJobsAsync(app.Services, app.Lifetime.ApplicationStopping);
}
// ── 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<Program>
// works in integration tests.
public partial class Program
{
private const string TestingEnvironment = "Testing";
private const int RecurringJobRegistrationAttempts = 5;
// SonarQube S1118: partial class used by WebApplicationFactory needs a constructor.
protected Program() { }
internal static async Task ConfigureRecurringJobsAsync(IServiceProvider services, CancellationToken cancellationToken)
{
var retryDelay = TimeSpan.FromSeconds(2);
var logger = services.GetRequiredService<ILogger<Program>>();
for (var attempt = 1; attempt <= RecurringJobRegistrationAttempts; attempt++)
{
cancellationToken.ThrowIfCancellationRequested();
try
{
using var scope = services.CreateScope();
var manager = scope.ServiceProvider.GetRequiredService<IRecurringJobManager>();
Heimdall.Infrastructure.BackgroundJobs.JobSetup.ConfigureRecurringJobs(manager);
return;
}
catch (Hangfire.PostgreSql.PostgreSqlDistributedLockException ex)
when (attempt < RecurringJobRegistrationAttempts)
{
logger.LogWarning(ex,
"Recurring Hangfire job registration hit a distributed lock (attempt {Attempt}/{MaxAttempts}); retrying in {DelaySeconds}s.",
attempt, RecurringJobRegistrationAttempts, retryDelay.TotalSeconds);
await Task.Delay(retryDelay, cancellationToken);
retryDelay = TimeSpan.FromSeconds(Math.Min(retryDelay.TotalSeconds * 2, 16));
}
}
}
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
};
/// <summary>
/// Creates a configured WebApplication suitable for testing.
/// Used by E2E tests to start a real Kestrel server.
/// </summary>
public static WebApplication CreateTestApplication(string[]? args = null, Action<WebApplicationBuilder>? 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;
}
/// <summary>
/// Applies pending EF migrations with retry/backoff. Shared between the
/// normal entry point and test hosts (E2E) so both boot paths behave identically.
/// </summary>
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<ILogger<Program>>();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
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;
}
}
}
}
/// <summary>
/// Seeds Identity roles, default groups and (optionally) the demo admin + demo site.
/// Idempotent — safe to call on every startup and from test hosts.
/// </summary>
public static async Task SeedAsync(WebApplication app, IConfiguration configuration)
{
using var seedScope = app.Services.CreateScope();
var roleManager = seedScope.ServiceProvider
.GetRequiredService<Microsoft.AspNetCore.Identity.RoleManager<Heimdall.Infrastructure.Identity.IdentityAppRole>>();
var userManager = seedScope.ServiceProvider
.GetRequiredService<Microsoft.AspNetCore.Identity.UserManager<Heimdall.Infrastructure.Identity.IdentityAppUser>>();
var groupDb = seedScope.ServiceProvider.GetRequiredService<AppDbContext>();
await SeedRolesAsync(roleManager);
await seedScope.ServiceProvider.GetRequiredService<IRolePermissionService>()
.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<Heimdall.Infrastructure.Identity.IdentityAppRole> 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<HashSet<string>> GetExistingSettingKeysAsync(AppDbContext groupDb) =>
new(
await groupDb.AppSettings.Select(s => s.Key).ToListAsync(),
StringComparer.OrdinalIgnoreCase);
private static async Task SeedStorageSettingsAsync(AppDbContext groupDb, HashSet<string> existingKeys)
{
var defaults = new Dictionary<string, string?>
{
["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<string> 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<string, string?>
{
["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<Heimdall.Infrastructure.Identity.IdentityAppUser> userManager,
AppDbContext groupDb)
{
if (!configuration.GetValue<bool>("Seed:DemoOnStartup", false))
return;
var adminLogin = configuration.GetValue<string>("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<string>("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<bool>("Seed:DemoOnStartup", false) ? "enabled" : "disabled (set Seed:DemoOnStartup=true to enable)")}");
builder.Services.AddLocalization(options => options.ResourcesPath = "Localization");
builder.Services.AddScoped<UiLanguageService>();
builder.Services.AddScoped<UiText>();
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<AuthState>();
}
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<HttpContext, string>(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<Heimdall.Api.Security.ResourceAccess>();
builder.Services.AddSingleton<Heimdall.Api.Security.LiveMediaTickets>();
builder.Services.AddSingleton<Heimdall.Api.Security.LiveMediaSessionLimiter>();
builder.Services.AddSingleton<Heimdall.Api.Security.LiveSubscriptions>();
builder.Services.AddControllers(options =>
{
options.Filters.Add<Heimdall.Api.Filters.ExceptionFilter>();
options.Filters.Add<Heimdall.Api.Security.ResourceAccessFilter>();
})
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.Converters.Add(
new System.Text.Json.Serialization.JsonStringEnumConverter());
})
.AddApplicationPart(typeof(Program).Assembly);
builder.Services.AddFluentValidationAutoValidation();
builder.Services.Configure<Microsoft.AspNetCore.Http.Json.JsonOptions>(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<IEventBroadcastService, EventBroadcastService>();
builder.Services.AddScoped<IConfigBroadcastService, ConfigBroadcastService>();
builder.Services.AddScoped<IMonitoringBroadcastService, MonitoringBroadcastService>();
builder.Services.AddScoped<INotificationBroadcastService, NotificationBroadcastService>();
builder.Services.AddScoped<IAdminBroadcastService, AdminBroadcastService>();
}
private static void ConfigureAuthScheme(WebApplicationBuilder builder)
{
builder.Services.Configure<Microsoft.AspNetCore.Authentication.AuthenticationOptions>(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<HeimdallApiClient>();
builder.Services.AddScoped<NotificationsHubClient>();
builder.Services.AddScoped<TokenRefreshHandler>(sp =>
{
var handler = ActivatorUtilities.CreateInstance<TokenRefreshHandler>(sp);
var origin = ActivatorUtilities.CreateInstance<SameOriginHttpMessageHandler>(sp);
origin.InnerHandler = sp.GetRequiredService<IHttpMessageHandlerFactory>().CreateHandler("HeimdallApi");
handler.InnerHandler = origin;
return handler;
});
builder.Services.AddTransient<SameOriginHttpMessageHandler>();
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<ApiKeyAuthenticationOptions, ApiKeyAuthenticationHandler>("ApiKey", null);
ConfigureAuthorizationPolicies(builder);
builder.Services.AddCascadingAuthenticationState();
builder.Services.AddScoped<HeimdallAuthStateProvider>();
builder.Services.AddScoped<AuthenticationStateProvider>(
sp => sp.GetRequiredService<HeimdallAuthStateProvider>());
}
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<ILogger<Program>>();
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<ILogger<Program>>();
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<bool> ValidateAccountSessionAsync(ClaimsPrincipal principal, HttpContext http) =>
Heimdall.Application.Auth.Services.AccountSessionPolicy.IsValidLiveAsync(principal,
http.RequestServices.GetRequiredService<Heimdall.Application.Services.IIdentityAccountService>(),
http.RequestServices.GetRequiredService<Heimdall.Application.Common.IApplicationDbContext>(), 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<string, object?>)?.Remove("password");
if (sentryEvent.Extra?.ContainsKey("token") == true)
(sentryEvent.Extra as IDictionary<string, object?>)?.Remove("token");
if (sentryEvent.Extra?.ContainsKey("secret") == true)
(sentryEvent.Extra as IDictionary<string, object?>)?.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();
}
var staticFileContentTypes = new FileExtensionContentTypeProvider();
staticFileContentTypes.Mappings[".py"] = "text/x-python";
app.UseStaticFiles(new StaticFileOptions
{
ContentTypeProvider = staticFileContentTypes,
});
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);
// Unknown browser routes have no endpoint and cannot start the interactive
// Blazor circuit. Render the same localized NotFound content as a static
// 404 document; preserve native API, hub, health, Hangfire, and asset errors.
app.UseStatusCodePages(async statusCodeContext =>
{
var context = statusCodeContext.HttpContext;
var path = context.Request.Path;
var isNonUiResponse = path.StartsWithSegments("/api")
|| path.StartsWithSegments("/hubs")
|| path.StartsWithSegments("/healthz")
|| path.StartsWithSegments("/hangfire")
|| Path.HasExtension(path.Value)
|| !context.Request.Headers.Accept.Any(value =>
value?.Contains("text/html", StringComparison.OrdinalIgnoreCase) == true);
if (context.Response.StatusCode != StatusCodes.Status404NotFound || isNonUiResponse) return;
var text = context.RequestServices.GetRequiredService<UiText>();
var encoder = System.Text.Encodings.Web.HtmlEncoder.Default;
var title = encoder.Encode(text["NotFoundPage_Title"]);
var message = encoder.Encode(text["NotFoundPage_Body"]);
var back = encoder.Encode(text["NotFoundPage_Back"]);
context.Response.ContentType = "text/html; charset=utf-8";
var document = $$"""
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>{{title}}</title>
<style>
body { margin: 0; background: #101828; color: #f9fafb; font: 16px Inter, system-ui, sans-serif; }
main { box-sizing: border-box; max-width: 48rem; margin: 12vh auto; padding: 2rem; }
h1 { color: #60a5fa; font-size: 2.5rem; }
p { color: #cbd5e1; line-height: 1.6; }
a { display: inline-block; margin-top: 1rem; padding: .75rem 1rem; border-radius: .5rem; background: #2563eb; color: white; text-decoration: none; }
</style>
</head>
<body>
<main>
<h1>{{title}}</h1>
<p>{{message}}</p>
<a href="/dashboard">{{back}}</a>
</main>
</body>
</html>
""";
await context.Response.WriteAsync(document);
});
// 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<App>().AddInteractiveServerRenderMode();
app.MapControllers();
app.MapHub<ConfigHub>("/hubs/config");
app.MapHub<EventsHub>("/hubs/events");
app.MapHub<MonitoringHub>("/hubs/monitoring");
app.MapHub<NotificationsHub>("/hubs/notifications");
app.MapHub<AdminHub>("/hubs/admin");
// Diagnostic: log all mapped endpoints so E2E host mapping issues are visible.
if (app.Environment.IsEnvironment(TestingEnvironment))
{
var dataSource = app.Services.GetRequiredService<Microsoft.AspNetCore.Routing.EndpointDataSource>();
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<Program> logger) =>
{
if (string.IsNullOrEmpty(request.AccessToken))
return Results.BadRequest(new { error = "AccessToken is required" });
var failureStage = "token validation";
try
{
var handler = new JwtSecurityTokenHandler();
var principal = handler.ValidateToken(request.AccessToken,
GetJwtValidationParameters(jwtKey, jwtIssuer, jwtAudience), out _);
failureStage = "account session validation";
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<Claim>
{
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);
failureStage = "cookie issuance";
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 (SecurityTokenException ex)
{
logger.LogWarning("Cookie sign-in rejected a token (error type {ErrorType})", ex.GetType().Name);
return Results.Unauthorized();
}
catch (ArgumentException ex) when (failureStage == "token validation")
{
logger.LogWarning("Cookie sign-in rejected a token (error type {ErrorType})", ex.GetType().Name);
return Results.Unauthorized();
}
catch (Exception ex)
{
logger.LogError("Cookie sign-in failed during {FailureStage} (error type {ErrorType})",
failureStage, ex.GetType().Name);
return Results.Problem(
statusCode: StatusCodes.Status500InternalServerError,
title: "Authentication session could not be created");
}
});
app.MapPost("/_auth/signout", async (HttpContext httpContext, ILogger<Program> logger) =>
{
await httpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Results.Ok();
});
}
/// <summary>
/// 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.
/// </summary>
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);
}
/// <summary>
/// Lit le toggle global sentry.enabled en base (défaut true). Table absente
/// au premier démarrage ou DB indisponible -> activé (comportement sûr).
/// </summary>
private static bool IsSentryEnabledFromDb(IServiceCollection services)
{
try
{
using var sp = services.BuildServiceProvider();
using var scope = sp.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<Heimdall.Infrastructure.Data.AppDbContext>();
return db.AppSettings.AsNoTracking()
.FirstOrDefault(s => s.Key == "sentry.enabled")?.Value != "false";
}
catch
{
return true;
}
}
}