2026-07-28 14:52:52 +00:00
using Sentry.AspNetCore ;
2026-07-20 09:50:43 +00:00
using System.IdentityModel.Tokens.Jwt ;
2026-07-16 21:19:16 +00:00
using System.Security.Claims ;
2026-07-20 09:50:43 +00:00
using System.Text ;
2026-07-20 20:22:30 +00:00
using FluentValidation.AspNetCore ;
2026-07-20 17:22:56 +00:00
using Heimdall.Application ;
2026-07-20 20:22:30 +00:00
using Heimdall.Application.Services ;
2026-07-20 17:22:56 +00:00
using Heimdall.Infrastructure ;
2026-07-20 17:12:16 +00:00
using Heimdall.Infrastructure.Data ;
2026-07-22 19:54:55 +00:00
using Heimdall.Infrastructure.BackgroundJobs ;
2026-07-19 07:04:25 +00:00
using Heimdall.Infrastructure.Security ;
2026-07-16 19:09:28 +00:00
using Heimdall.Web.Components ;
2026-07-20 20:22:30 +00:00
using Heimdall.Api.Hubs ;
2026-08-12 09:43:45 +02:00
using Heimdall.Api ;
2026-07-16 21:19:16 +00:00
using Heimdall.Web.Services ;
2026-07-20 17:22:56 +00:00
using Hangfire ;
2026-07-18 20:59:38 +00:00
using Microsoft.AspNetCore.Authentication ;
using Microsoft.AspNetCore.Authentication.Cookies ;
2026-07-20 20:22:30 +00:00
using Microsoft.AspNetCore.Authentication.JwtBearer ;
2026-07-16 21:19:16 +00:00
using Microsoft.AspNetCore.Components.Authorization ;
2026-07-20 20:22:30 +00:00
using Microsoft.AspNetCore.RateLimiting ;
2026-07-20 17:22:56 +00:00
using Microsoft.EntityFrameworkCore ;
2026-07-20 09:50:43 +00:00
using Microsoft.IdentityModel.Tokens ;
2026-07-16 21:19:16 +00:00
using MudBlazor.Services ;
2026-07-20 20:22:30 +00:00
using Scalar.AspNetCore ;
2026-07-16 19:09:28 +00:00
var builder = WebApplication . CreateBuilder ( args );
2026-07-23 18:12:47 +00:00
// ── Use shared service configuration ──────────────────────────────
Program . ConfigureServices ( builder );
2026-07-16 21:19:16 +00:00
2026-07-16 19:09:28 +00:00
var app = builder . Build ();
2026-07-23 18:12:47 +00:00
// ── Use shared middleware configuration ───────────────────────────
Program . ConfigureMiddleware ( app );
2026-07-18 20:59:38 +00:00
2026-07-20 17:22:56 +00:00
// ── 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.
2026-08-09 23:43:11 +02:00
// 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).
2026-07-21 09:46:33 +00:00
var migrateOnStartup = builder . Configuration . GetValue < bool? >( "Database:MigrateOnStartup" )
2026-08-09 23:43:11 +02:00
?? ! app . Environment . IsEnvironment ( "Testing" );
2026-07-21 07:23:33 +00:00
if ( migrateOnStartup )
2026-07-20 17:22:56 +00:00
{
2026-08-09 23:43:11 +02:00
await Program . ApplyMigrationsAsync ( app );
2026-07-21 09:57:22 +00:00
}
2026-07-20 17:22:56 +00:00
2026-07-21 09:57:22 +00:00
// ── Register recurring Hangfire jobs (heartbeat monitor, agent failover) ──
2026-07-23 18:12:47 +00:00
var isTesting = app . Environment . IsEnvironment ( "Testing" );
var pgConnStr = Environment . GetEnvironmentVariable ( "DATABASE_URL" ) ?? app . Configuration . GetConnectionString ( "Default" );
if (! isTesting && ! string . IsNullOrEmpty ( pgConnStr ))
2026-07-21 09:57:22 +00:00
{
2026-07-20 20:32:32 +00:00
using ( var scope = app . Services . CreateScope ())
{
var manager = scope . ServiceProvider . GetRequiredService < IRecurringJobManager >();
2026-07-22 19:54:55 +00:00
Heimdall . Infrastructure . BackgroundJobs . JobSetup . ConfigureRecurringJobs ( manager );
2026-07-20 20:32:32 +00:00
}
2026-07-20 17:22:56 +00:00
}
2026-07-21 06:29:51 +00:00
// ── 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.
2026-08-09 23:43:11 +02:00
await Program . SeedAsync ( app , builder . Configuration );
2026-07-21 06:29:51 +00:00
2026-07-16 19:09:28 +00:00
app . Run ();
2026-07-18 20:59:38 +00:00
// ─── DTO for the cookie sign-in request ───────────────────────────
internal sealed record SignInRequest (
2026-07-20 09:50:43 +00:00
string AccessToken );
2026-07-20 20:32:32 +00:00
// Partial class declaration so WebApplicationFactory<Program>
// works in integration tests.
2026-07-23 18:12:47 +00:00
public partial class Program {
// 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 ?? []);
2026-08-09 23:43:11 +02:00
// 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 ();
2026-07-23 18:12:47 +00:00
// 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 ;
}
2026-08-09 23:43:11 +02:00
/// <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 );
db . Database . Migrate ();
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 . Domain . Entities . AppRole >>();
var userManager = seedScope . ServiceProvider
. GetRequiredService < Microsoft . AspNetCore . Identity . UserManager < Heimdall . Domain . Entities . AppUser >>();
foreach ( var roleName in AppRoles . All )
{
if (! await roleManager . RoleExistsAsync ( roleName ))
{
await roleManager . CreateAsync ( new Heimdall . Domain . Entities . AppRole ( roleName ));
}
}
// Seed default groups (idempotent)
var groupDb = seedScope . ServiceProvider . GetRequiredService < AppDbContext >();
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 ();
2026-08-12 10:14:40 +02:00
// Seed des paramètres de stockage (idempotent) — source de vérité DB,
// valeur initiale depuis env pour migration douce (ticket #78/#80).
var storageDefaults = new Dictionary < string , string? >
{
["storage.provider"] = Environment . GetEnvironmentVariable ( "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" ,
};
2026-08-12 11:37:23 +02:00
// Clés existantes en mémoire (casse ignorée) — le constructeur
// AppSetting lower-case les clés (accessKey → accesskey), et
// string.Equals(OrdinalIgnoreCase) n'est pas traduisible par EF :
// le check idempotent se fait donc côté client sur un HashSet.
var existingAppSettingKeys = new HashSet < string >(
await groupDb . AppSettings . Select ( s => s . Key ). ToListAsync (),
StringComparer . OrdinalIgnoreCase );
2026-08-12 10:14:40 +02:00
foreach ( var ( key , value ) in storageDefaults )
{
2026-08-12 11:37:23 +02:00
if ( existingAppSettingKeys . Contains ( key ))
2026-08-12 10:14:40 +02:00
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
}));
}
await groupDb . SaveChangesWithRetryAsync ();
2026-08-12 10:20:55 +02:00
// Seed des paramètres d'intégration (idempotent) — source de vérité DB,
// valeur initiale depuis env pour migration douce (ticket #80).
var integrationDefaults = new Dictionary < string , string? >
{
["ntfy.baseUrl"] = Environment . GetEnvironmentVariable ( "NTFY__BASE_URL" ) ?? "https://ntfy.sh" ,
["ntfy.token"] = Environment . GetEnvironmentVariable ( "NTFY__TOKEN" ),
["email.fromAddress"] = Environment . GetEnvironmentVariable ( "EMAIL__FROM_ADDRESS" ),
["email.fromName"] = Environment . GetEnvironmentVariable ( "EMAIL__FROM_NAME" ),
["email.smtpHost"] = Environment . GetEnvironmentVariable ( "EMAIL__SMTP_HOST" ),
["email.smtpPort"] = Environment . GetEnvironmentVariable ( "EMAIL__SMTP_PORT" ) ?? "587" ,
["email.username"] = Environment . GetEnvironmentVariable ( "EMAIL__USERNAME" ),
["email.password"] = Environment . GetEnvironmentVariable ( "EMAIL__PASSWORD" ),
["email.useSsl"] = Environment . GetEnvironmentVariable ( "EMAIL__USE_SSL" ) ?? "true" ,
["ai.cpaiUrl"] = Environment . GetEnvironmentVariable ( "CPAI_URL" ),
["ai.ollamaUrl"] = Environment . GetEnvironmentVariable ( "OLLAMA_URL" ),
2026-08-12 10:46:09 +02:00
["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"] = Environment . GetEnvironmentVariable ( "HEARTBEAT__INTERVAL_SECONDS" ) ?? "30" ,
["sentry.dsn"] = Environment . GetEnvironmentVariable ( "SENTRY_DSN" ),
2026-08-12 10:20:55 +02:00
};
foreach ( var ( key , value ) in integrationDefaults )
{
2026-08-12 11:37:23 +02:00
if ( existingAppSettingKeys . Contains ( key ))
2026-08-12 10:20:55 +02:00
continue ;
groupDb . AppSettings . Add ( new Heimdall . Domain . Entities . AppSetting (
2026-08-12 10:46:09 +02:00
key , value ?? string . Empty ,
key . StartsWith ( "ntfy." , StringComparison . Ordinal ) || key . StartsWith ( "email." , StringComparison . Ordinal )
? "integrations" : key . StartsWith ( "ai." , StringComparison . Ordinal ) ? "ai" : "agent" ,
2026-08-12 10:20:55 +02:00
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" ,
2026-08-12 10:46:09 +02:00
"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.dsn" => "DSN Sentry/GlitchTip (diagnostic)" ,
2026-08-12 10:20:55 +02:00
_ => key
}));
}
await groupDb . SaveChangesWithRetryAsync ();
2026-08-09 23:43:11 +02:00
// Seed demo admin + demo site when explicitly enabled (dev & E2E hosts)
if ( configuration . GetValue < bool >( "Seed:DemoOnStartup" , false ))
{
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 . Domain . Entities . AppUser
{
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." );
await userManager . CreateAsync ( testAdmin , adminPassword );
await userManager . AddToRoleAsync ( testAdmin , AppRoles . Admin );
}
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 ();
}
}
}
2026-07-23 18:12:47 +00:00
internal static void ConfigureServices ( WebApplicationBuilder builder )
{
2026-07-28 14:37:52 +00:00
// ── Sentry (GlitchTip) — error tracking, performance & structured logs ──
2026-07-28 10:14:34 +00:00
// Primary: Sentry:Dsn from appsettings.json or env var Sentry__Dsn
// Fallback: legacy SENTRY_DSN env var (Docker backward compat)
// Neither set → DSN is null → Sentry SDK no-ops gracefully
var sentryDsn = builder . Configuration [ "Sentry:Dsn" ]
?? Environment . GetEnvironmentVariable ( "SENTRY_DSN" );
if (! string . IsNullOrEmpty ( sentryDsn ))
2026-07-23 18:12:47 +00:00
{
2026-07-28 14:52:52 +00:00
builder . WebHost . UseSentry (( SentryAspNetCoreOptions options ) =>
2026-07-23 18:12:47 +00:00
{
options . Dsn = sentryDsn ;
2026-07-28 14:37:52 +00:00
// ── Env & Release ────────────────────────────────────────
// Environment is auto-read from IHostingEnvironment
// Release should be explicitly set (e.g. "heimdall@1.2.3")
options . Release = builder . Configuration [ "Sentry:Release" ]
?? Environment . GetEnvironmentVariable ( "SENTRY_RELEASE" );
// ── Error sampling ──────────────────────────────────────
options . SampleRate = 1.0f ; // 100% errors (adjust if volume too high)
options . AttachStacktrace = true ; // Stack traces even on CaptureMessage
options . MaxBreadcrumbs = 100 ; // Breadcrumb buffer size
2026-07-23 18:12:47 +00:00
options . MinimumBreadcrumbLevel = LogLevel . Debug ;
options . MinimumEventLevel = LogLevel . Error ;
2026-07-28 14:37:52 +00:00
// ── Tracing (Performance) ───────────────────────────────
// GlitchTip counts every transaction as an event.
// 0.05 = 5% sample = good signal-to-noise in production.
options . TracesSampleRate = double . Parse (
2026-07-28 14:52:52 +00:00
builder . Configuration [ "Sentry:TracesSampleRate" ] ?? "0.05" ,
System . Globalization . CultureInfo . InvariantCulture );
2026-07-28 14:37:52 +00:00
// ── Request body capture ────────────────────────────────
2026-07-28 10:14:34 +00:00
options . MaxRequestBodySize = Sentry . Extensibility . RequestSize . Small ;
2026-07-28 14:37:52 +00:00
// ── Structured logs (v5.14+) ────────────────────────────
// Enables SentrySdk.Logger.LogInfo() etc.
options . EnableLogs = true ;
// ── GlitchTip-specific: disable unsupported features ────
// Release Health / Sessions are NOT supported by GlitchTip
options . AutoSessionTracking = false ;
// ── PII & GDPR ──────────────────────────────────────────
options . SendDefaultPii = false ; // Explicit RGPD-safe default
options . ServerName = null ; // Never send hostname
// ── Enhanced diagnostics ────────────────────────────────
options . CaptureBlockingCalls = true ; // Detect .Result / .Wait()
options . CaptureFailedRequests = true ; // Capture HttpClient 4xx/5xx
options . IncludeActivityData = true ; // DiagnosticSource Activity
// ── Stack traces ────────────────────────────────────────
options . StackTraceMode = Sentry . StackTraceMode . Enhanced ;
// ── BeforeSend — scrub PII before it leaves the SDK ────
options . SetBeforeSend (( sentryEvent , hint ) =>
{
// Never send server name (already null above, belt-and-suspenders)
sentryEvent . ServerName = null ;
// Remove sensitive extras
if ( sentryEvent . Extra ?. ContainsKey ( "password" ) == true )
2026-07-28 14:52:52 +00:00
( sentryEvent . Extra as IDictionary < string , object? >)?. Remove ( "password" );
2026-07-28 14:37:52 +00:00
if ( sentryEvent . Extra ?. ContainsKey ( "token" ) == true )
2026-07-28 14:52:52 +00:00
( sentryEvent . Extra as IDictionary < string , object? >)?. Remove ( "token" );
2026-07-28 14:37:52 +00:00
if ( sentryEvent . Extra ?. ContainsKey ( "secret" ) == true )
2026-07-28 14:52:52 +00:00
( sentryEvent . Extra as IDictionary < string , object? >)?. Remove ( "secret" );
2026-07-28 14:37:52 +00:00
return sentryEvent ;
});
// ── BeforeBreadcrumb — filter noisy breadcrumbs ────────
options . SetBeforeBreadcrumb ( breadcrumb
=> breadcrumb . Category == "Microsoft.AspNetCore.RateLimiting"
? null
: breadcrumb );
2026-07-23 18:12:47 +00:00
});
}
2026-07-29 14:20:14 +00:00
// ── Startup diagnostics ────────────────────────────────────────
var sentryStatus = string . IsNullOrEmpty ( sentryDsn )
? "NOT CONFIGURED — errors will NOT be reported to GlitchTip"
: "configured (" + sentryDsn [.. sentryDsn . IndexOf ( '@' )] + "@...)" ;
Console . WriteLine ( $"[DIAG] Sentry/GlitchTip DSN: {sentryStatus}" );
Console . WriteLine ( $"[DIAG] Environment: {builder.Environment.EnvironmentName}" );
Console . WriteLine ( $"[DIAG] Data Protection keys dir: /var/lib/heimdall/dp-keys" );
2026-07-29 14:48:08 +00:00
Console . WriteLine ( $"[DIAG] Demo seeding: {(builder.Configuration.GetValue<bool>(" Seed : DemoOnStartup ", false) ? " enabled " : " disabled ( set Seed : DemoOnStartup = true to enable ) ")}" );
2026-07-29 14:20:14 +00:00
2026-07-23 18:12:47 +00:00
builder . Services . AddRazorComponents ()
. AddInteractiveServerComponents ();
2026-08-09 23:43:11 +02:00
// In-memory cache — required by INotificationRateLimiter (singleton)
builder . Services . AddMemoryCache ();
2026-07-23 18:12:47 +00:00
// ── Authentication ──────────────────────────────────────────────
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" ;
builder . Services . AddAuthentication ( CookieAuthenticationDefaults . AuthenticationScheme )
. AddCookie ( CookieAuthenticationDefaults . AuthenticationScheme , options =>
{
options . LoginPath = "/login" ;
options . LogoutPath = "/_auth/signout" ;
options . AccessDeniedPath = "/not-found" ;
2026-08-11 11:59:18 +02:00
options . Cookie . Name = AuthState . AuthCookieName ;
2026-07-23 18:12:47 +00:00
options . Cookie . HttpOnly = true ;
options . Cookie . SameSite = SameSiteMode . Lax ;
2026-07-24 13:52:22 +00:00
// Use SameAsRequest to support both HTTP and HTTPS deployments
// In production with HTTPS, the cookie will still be secure
options . Cookie . SecurePolicy = CookieSecurePolicy . SameAsRequest ;
2026-07-23 18:12:47 +00:00
options . ExpireTimeSpan = TimeSpan . FromDays ( 7 );
options . SlidingExpiration = true ;
2026-07-24 19:29:02 +00:00
2026-07-24 18:25:33 +00:00
// Add logging events
options . Events = new CookieAuthenticationEvents
{
OnRedirectToLogin = context =>
{
var logger = context . HttpContext . RequestServices . GetRequiredService < ILogger < Program >>();
2026-07-24 19:29:02 +00:00
logger . LogWarning ( "Redirect to login: {Path} -> {LoginPath}" ,
2026-07-24 18:25:33 +00:00
context . Request . Path , options . LoginPath );
2026-08-11 12:35:45 +02:00
// 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 ;
}
2026-07-24 18:25:33 +00:00
context . Response . Redirect ( context . RedirectUri );
return Task . CompletedTask ;
},
OnRedirectToAccessDenied = context =>
{
var logger = context . HttpContext . RequestServices . GetRequiredService < ILogger < Program >>();
2026-07-24 19:29:02 +00:00
logger . LogWarning ( "Access denied: {Path} -> {AccessDeniedPath}" ,
2026-07-24 18:25:33 +00:00
context . Request . Path , options . AccessDeniedPath );
2026-08-11 12:35:45 +02:00
if ( IsApiRequest ( context . Request ))
{
context . Response . StatusCode = StatusCodes . Status403Forbidden ;
return Task . CompletedTask ;
}
2026-07-24 18:25:33 +00:00
context . Response . Redirect ( context . RedirectUri );
return Task . CompletedTask ;
},
OnValidatePrincipal = context =>
{
var logger = context . HttpContext . RequestServices . GetRequiredService < ILogger < Program >>();
logger . LogDebug ( "Validating principal for {Path}" , context . HttpContext . Request . Path );
return Task . CompletedTask ;
}
};
2026-07-23 18:12:47 +00:00
})
. AddJwtBearer ( "JwtBearer" , options =>
{
options . TokenValidationParameters = GetJwtValidationParameters ( jwtKey , jwtIssuer , jwtAudience );
options . Events = new JwtBearerEvents
{
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 ;
}
};
})
. AddScheme < ApiKeyAuthenticationOptions , ApiKeyAuthenticationHandler >( "ApiKey" , null );
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 ));
2026-08-09 23:43:11 +02:00
// Policy used by AuthController (register-admin, user management).
// Not a permission claim but a role-based gate for admin-only actions.
options . AddPolicy ( "AdminUsers" , policy => policy . RequireRole ( AppRoles . Admin ));
2026-07-23 18:12:47 +00:00
});
builder . Services . AddCascadingAuthenticationState ();
builder . Services . AddScoped < HeimdallAuthStateProvider >();
builder . Services . AddScoped < AuthenticationStateProvider >(
sp => sp . GetRequiredService < HeimdallAuthStateProvider >());
// ── MudBlazor ─────────────────────────────────────────────────────
builder . Services . AddMudServices ( config =>
{
config . SnackbarConfiguration . PositionClass = "mud-alert-center-top" ;
config . SnackbarConfiguration . PreventDuplicates = true ;
config . SnackbarConfiguration . ShowCloseIcon = true ;
config . SnackbarConfiguration . VisibleStateDuration = 4000 ;
});
// ── Rate Limiting ───────────────────────────────────────────────
builder . Services . AddRateLimiter ( options =>
{
options . RejectionStatusCode = 429 ;
options . AddFixedWindowLimiter ( "Auth" , opt => { opt . PermitLimit = 10 ; opt . Window = TimeSpan . FromMinutes ( 1 ); opt . QueueLimit = 0 ; });
options . AddFixedWindowLimiter ( "Api" , opt => { opt . PermitLimit = 200 ; opt . Window = TimeSpan . FromMinutes ( 1 ); opt . QueueLimit = 0 ; });
2026-08-09 23:43:11 +02:00
// 2FA codes are high-value, low-volume: tighter limit than the login endpoint.
options . AddFixedWindowLimiter ( "TwoFactor" , opt => { opt . PermitLimit = 5 ; opt . Window = TimeSpan . FromMinutes ( 1 ); opt . QueueLimit = 0 ; });
2026-07-23 18:12:47 +00:00
});
// ── Controllers (REST API) ────────────────────────────────────────
builder . Services . AddControllers ( options =>
2026-08-09 23:43:11 +02:00
options . Filters . Add < Heimdall . Api . Filters . ExceptionFilter >())
2026-08-10 10:40:17 +02:00
. AddJsonOptions ( options =>
{
// Serialize enums as strings in API responses (e.g. Agent.Status,
// Camera.Status) — otherwise the Blazor client fails to parse
// numeric enum values into its string-typed models.
options . JsonSerializerOptions . Converters . Add (
new System . Text . Json . Serialization . JsonStringEnumConverter ());
})
2026-08-09 23:43:11 +02:00
// Explicitly register the Web assembly as an application part.
// AddMvcCore only auto-discovers Assembly.GetEntryAssembly(), which is
// the test host ("testhost") when CreateTestApplication runs under
// xUnit — without this, no /api/* controller is ever mapped in E2E.
. AddApplicationPart ( typeof ( Program ). Assembly );
2026-07-23 18:12:47 +00:00
builder . Services . AddFluentValidationAutoValidation ();
builder . Services . Configure < Microsoft . AspNetCore . Http . Json . JsonOptions >( opts =>
opts . SerializerOptions . Converters . Add ( new System . Text . Json . Serialization . JsonStringEnumConverter ()));
builder . Services . AddSignalR ();
builder . Services . AddScoped < IEventBroadcastService , EventBroadcastService >();
builder . Services . AddScoped < IConfigBroadcastService , ConfigBroadcastService >();
2026-07-26 20:45:35 +00:00
builder . Services . AddScoped < IMonitoringBroadcastService , MonitoringBroadcastService >();
builder . Services . AddScoped < INotificationBroadcastService , NotificationBroadcastService >();
builder . Services . AddScoped < IAdminBroadcastService , AdminBroadcastService >();
2026-07-23 18:12:47 +00:00
builder . Services . AddOpenApi ();
// ── Application & Infrastructure layers ──────────────────────────
builder . Services . AddApplication ();
builder . Services . AddInfrastructure ( builder . Configuration );
2026-08-09 23:43:11 +02:00
// AddIdentity (inside AddInfrastructure) sets Identity.Application as the
// default authenticate/challenge scheme. But /_auth/signin signs the
// ".Heimdall.Auth" cookie with the "Cookies" scheme. If the default stays
// on Identity.Application, UseAuthentication tries to validate the ticket
// with a DIFFERENT Data Protection purpose -> the cookie is never accepted
// and full page reloads always bounce back to /login.
builder . Services . Configure < Microsoft . AspNetCore . Authentication . AuthenticationOptions >( options =>
{
options . DefaultAuthenticateScheme = CookieAuthenticationDefaults . AuthenticationScheme ;
options . DefaultChallengeScheme = CookieAuthenticationDefaults . AuthenticationScheme ;
options . DefaultSignInScheme = CookieAuthenticationDefaults . AuthenticationScheme ;
});
2026-07-24 19:29:02 +00:00
// Configure Identity cookie AFTER AddInfrastructure (which calls AddIdentity)
// AddIdentity sets default paths (/Account/Login) that must be overridden
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 = true ;
});
2026-07-23 18:12:47 +00:00
// ── Background jobs (skipped in Testing) ────────────────────────
var isTesting = builder . Environment . IsEnvironment ( "Testing" );
var connectionString = Environment . GetEnvironmentVariable ( "DATABASE_URL" )
?? builder . Configuration . GetConnectionString ( "Default" );
if (! isTesting && ! string . IsNullOrEmpty ( connectionString ))
builder . Services . AddBackgroundJobs ( builder . Configuration );
// ── HTTP client ──────────────────────────────────────────────────
2026-08-09 23:43:11 +02:00
// Blazor Server monolith: the UI and the API run in the same process,
// so requests target the SAME origin as the browser by default. An
// explicit ApiBaseUrl (config/env) overrides that for external APIs.
builder . Services . AddHttpContextAccessor ();
2026-07-23 18:12:47 +00:00
builder . Services . AddScoped < HeimdallApiClient >();
2026-08-10 22:49:37 +02:00
builder . Services . AddScoped < NotificationsHubClient >();
2026-07-23 18:12:47 +00:00
builder . Services . AddTransient < TokenRefreshHandler >();
2026-08-09 23:43:11 +02:00
builder . Services . AddTransient < SameOriginHttpMessageHandler >();
var apiBaseUrlConfigured = ApiBaseUrlResolver . IsConfigured ( builder . Configuration );
var apiBaseUrl = apiBaseUrlConfigured
? ApiBaseUrlResolver . ResolveConfigured ( builder . Configuration )!
: ApiBaseUrlResolver . PlaceholderBase ;
2026-07-23 18:12:47 +00:00
builder . Services . AddHttpClient ( "HeimdallApi" , client =>
{
2026-07-27 18:43:25 +00:00
var baseUrl = apiBaseUrl . EndsWith ( '/' ) ? apiBaseUrl : apiBaseUrl + "/" ;
client . BaseAddress = new Uri ( baseUrl );
2026-07-23 18:12:47 +00:00
client . Timeout = TimeSpan . FromSeconds ( 30 );
2026-08-09 23:43:11 +02:00
})
. AddHttpMessageHandler < TokenRefreshHandler >()
. AddHttpMessageHandler < SameOriginHttpMessageHandler >();
if ( apiBaseUrlConfigured )
Console . WriteLine ( $"[DIAG] ApiBaseUrl: {apiBaseUrl} (explicit)" );
else
Console . WriteLine ( "[DIAG] ApiBaseUrl: same-origin (no explicit config)" );
2026-07-23 18:12:47 +00:00
builder . Services . AddScoped < AuthState >();
}
internal static void ConfigureMiddleware ( WebApplication app )
{
if (! app . Environment . IsDevelopment ())
{
app . UseExceptionHandler ( "/Error" , createScopeForErrors : true );
app . UseHsts ();
}
2026-07-26 19:49:42 +00:00
// 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.
2026-07-24 13:52:22 +00:00
var urls = Environment . GetEnvironmentVariable ( "ASPNETCORE_URLS" ) ?? "" ;
if ( urls . Contains ( "https://" , StringComparison . OrdinalIgnoreCase ))
{
app . UseHttpsRedirection ();
}
2026-07-23 18:12:47 +00:00
app . UseStaticFiles ();
app . UseAuthentication ();
app . UseAuthorization ();
app . UseAntiforgery ();
2026-08-12 09:43:45 +02:00
// Hangfire dashboard — Admin uniquement (policy AdminJobs).
// MapHangfireDashboard est utilisé car UseHangfireDashboard avec
// DashboardOptions.Authorization n'existe pas pour les policies ASP.NET.
2026-08-12 09:54:37 +02:00
// Skip en Testing : Hangfire y est désactivé (pas de AddHangfire).
if (! app . Environment . IsEnvironment ( "Testing" ))
2026-08-12 09:43:45 +02:00
{
2026-08-12 09:54:37 +02:00
app . MapHangfireDashboard ( "/hangfire" , new DashboardOptions
{
Authorization =
[
new HangfireAdminAuthorizationFilter(),
] ,
});
}
2026-08-12 09:43:45 +02:00
2026-07-23 18:12:47 +00:00
app . MapRazorComponents < App >(). AddInteractiveServerRenderMode ();
app . MapControllers ();
app . MapHub < ConfigHub >( "/hubs/config" );
app . MapHub < EventsHub >( "/hubs/events" );
2026-07-26 20:45:35 +00:00
app . MapHub < MonitoringHub >( "/hubs/monitoring" );
app . MapHub < NotificationsHub >( "/hubs/notifications" );
app . MapHub < AdminHub >( "/hubs/admin" );
2026-07-23 18:12:47 +00:00
2026-08-09 23:43:11 +02:00
// Diagnostic: log all mapped endpoints so E2E host mapping issues are visible.
if ( app . Environment . IsEnvironment ( "Testing" ))
{
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)}" );
}
2026-07-23 18:12:47 +00:00
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 ();
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" });
try
{
var handler = new JwtSecurityTokenHandler ();
var principal = handler . ValidateToken ( request . AccessToken ,
GetJwtValidationParameters ( jwtKey , jwtIssuer , jwtAudience ), out _ );
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 ),
};
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 ));
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 < Program > logger ) =>
{
await httpContext . SignOutAsync ( CookieAuthenticationDefaults . AuthenticationScheme );
return Results . Ok ();
});
}
2026-08-11 12:35:45 +02:00
/// <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 );
}
2026-07-23 18:12:47 +00:00
}