2026-07-28 14:52:52 +00:00
using Sentry.AspNetCore ;
2026-10-10 22:55:26 +02:00
using System.Globalization ;
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-08-20 18:22:37 +02:00
using Heimdall.Application.Metrics ;
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-08-28 01:11:12 +02:00
using Heimdall.Web ;
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-10-10 22:55:26 +02:00
using Microsoft.AspNetCore.Localization ;
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-10-10 22:55:26 +02:00
using Microsoft.AspNetCore.Routing ;
2026-11-06 09:41:48 +01:00
using Microsoft.AspNetCore.StaticFiles ;
2026-10-10 22:55:26 +02:00
using OpenTelemetry.Metrics ;
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-10-10 22:55:26 +02:00
using System.Threading.RateLimiting ;
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-20 14:13:06 +02:00
?? ! app . Environment . IsEnvironment ( TestingEnvironment );
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-08-20 14:13:06 +02:00
var isTesting = app . Environment . IsEnvironment ( TestingEnvironment );
2026-07-23 18:12:47 +00:00
var pgConnStr = Environment . GetEnvironmentVariable ( "DATABASE_URL" ) ?? app . Configuration . GetConnectionString ( "Default" );
if (! isTesting && ! string . IsNullOrEmpty ( pgConnStr ))
2026-07-21 09:57:22 +00:00
{
2026-11-07 09:25:12 +01:00
await Program . ConfigureRecurringJobsAsync ( app . Services , app . Lifetime . ApplicationStopping );
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-08-12 20:05:12 +02:00
public partial class Program
{
2026-08-20 14:13:06 +02:00
private const string TestingEnvironment = "Testing" ;
2026-11-07 09:25:12 +01:00
private const int RecurringJobRegistrationAttempts = 5 ;
2026-08-20 14:13:06 +02:00
// SonarQube S1118: partial class used by WebApplicationFactory needs a constructor.
protected Program () { }
2026-11-07 09:25:12 +01:00
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 ));
}
}
}
2026-08-20 14:13:06 +02:00
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]}@...)" ;
}
2026-07-23 18:12:47 +00:00
// 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 );
2026-09-01 10:18:43 +02:00
// 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.
2026-08-20 14:13:06 +02:00
await db . Database . MigrateAsync ( migrationCt );
2026-08-09 23:43:11 +02:00
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
2026-11-04 13:33:30 +01:00
. GetRequiredService < Microsoft . AspNetCore . Identity . RoleManager < Heimdall . Infrastructure . Identity . IdentityAppRole >>();
2026-08-09 23:43:11 +02:00
var userManager = seedScope . ServiceProvider
2026-11-04 13:33:30 +01:00
. GetRequiredService < Microsoft . AspNetCore . Identity . UserManager < Heimdall . Infrastructure . Identity . IdentityAppUser >>();
2026-08-20 14:13:06 +02:00
var groupDb = seedScope . ServiceProvider . GetRequiredService < AppDbContext >();
2026-08-09 23:43:11 +02:00
2026-08-20 14:13:06 +02:00
await SeedRolesAsync ( roleManager );
2026-11-04 13:33:30 +01:00
await seedScope . ServiceProvider . GetRequiredService < IRolePermissionService >()
. EnsureDefaultsAsync ( CancellationToken . None );
2026-08-20 14:13:06 +02:00
await SeedGroupsAsync ( groupDb );
var existingKeys = await GetExistingSettingKeysAsync ( groupDb );
await SeedStorageSettingsAsync ( groupDb , existingKeys );
await SeedIntegrationSettingsAsync ( groupDb , existingKeys );
await MigrateLegacySentryKeysAsync ( groupDb );
await SeedDemoDataAsync ( configuration , userManager , groupDb );
}
2026-11-04 13:33:30 +01:00
private static async Task SeedRolesAsync ( Microsoft . AspNetCore . Identity . RoleManager < Heimdall . Infrastructure . Identity . IdentityAppRole > roleManager )
2026-08-20 14:13:06 +02:00
{
2026-08-09 23:43:11 +02:00
foreach ( var roleName in AppRoles . All )
{
if (! await roleManager . RoleExistsAsync ( roleName ))
{
2026-11-04 13:33:30 +01:00
await roleManager . CreateAsync ( new Heimdall . Infrastructure . Identity . IdentityAppRole ( roleName ));
2026-08-09 23:43:11 +02:00
}
}
2026-08-20 14:13:06 +02:00
}
2026-08-09 23:43:11 +02:00
2026-08-20 14:13:06 +02:00
private static async Task SeedGroupsAsync ( AppDbContext groupDb )
{
2026-08-09 23:43:11 +02:00
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-20 14:13:06 +02:00
}
2026-08-09 23:43:11 +02:00
2026-08-20 14:13:06 +02:00
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? >
2026-08-12 10:14:40 +02:00
{
2026-10-26 06:26:00 +01:00
["storage.provider"] = "Local" ,
2026-08-12 10:14:40 +02:00
["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-20 14:13:06 +02:00
foreach ( var ( key , value ) in defaults )
2026-08-12 10:14:40 +02:00
{
2026-08-20 14:13:06 +02:00
if ( existingKeys . Contains ( key )) continue ;
2026-08-12 10:14:40 +02:00
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
2026-08-12 12:18:52 +02:00
},
agentScoped : false ));
2026-08-12 10:14:40 +02:00
}
await groupDb . SaveChangesWithRetryAsync ();
2026-08-20 14:13:06 +02:00
}
2026-08-12 10:14:40 +02:00
2026-08-20 14:13:06 +02:00
private static async Task SeedIntegrationSettingsAsync ( AppDbContext groupDb , HashSet < string > existingKeys )
{
2026-10-25 02:55:31 +02:00
var heartbeatInterval = Environment . GetEnvironmentVariable ( "HEARTBEAT__INTERVAL_SECONDS" );
if (! int . TryParse ( heartbeatInterval , out var heartbeatSeconds ) || heartbeatSeconds is < 5 or > 300 )
heartbeatInterval = "30" ;
2026-08-20 14:13:06 +02:00
var defaults = new Dictionary < string , string? >
2026-08-12 10:20:55 +02:00
{
2026-10-26 06:26:00 +01:00
["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" ,
2026-08-12 10:20:55 +02:00
["ai.cpaiUrl"] = Environment . GetEnvironmentVariable ( "CPAI_URL" ),
2026-10-26 06:26:00 +01:00
["ai.ollamaUrl"] = string . Empty ,
["updates.releaseapiurl"] = string . Empty ,
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" ,
2026-10-25 02:55:31 +02:00
["heartbeat.interval.seconds"] = heartbeatInterval ,
2026-08-12 12:18:52 +02:00
["sentry.enabled"] = "true" ,
2026-08-12 10:20:55 +02:00
};
2026-10-25 02:55:31 +02:00
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 );
2026-08-20 14:13:06 +02:00
foreach ( var ( key , value ) in defaults )
2026-08-12 10:20:55 +02:00
{
2026-08-20 14:13:06 +02:00
if ( existingKeys . Contains ( key )) continue ;
2026-08-12 12:18:52 +02:00
var agentScoped = !( key . StartsWith ( "ntfy." , StringComparison . Ordinal )
|| key . StartsWith ( "email." , StringComparison . Ordinal )
2026-10-26 06:26:00 +01:00
|| key . StartsWith ( "sentry." , StringComparison . Ordinal )
|| key . StartsWith ( "updates." , StringComparison . Ordinal ));
2026-08-20 14:13:06 +02:00
var category = ResolveCategory ( key );
2026-08-12 10:20:55 +02:00
groupDb . AppSettings . Add ( new Heimdall . Domain . Entities . AppSetting (
2026-08-12 10:46:09 +02:00
key , value ?? string . Empty ,
2026-08-20 14:13:06 +02:00
category ,
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-10-26 06:26:00 +01:00
"updates.releaseapiurl" => "API des versions Heimdall (HTTPS)" ,
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)" ,
2026-08-12 12:18:52 +02:00
"sentry.enabled" => "Autoriser l'envoi des erreurs vers GlitchTip (nécessite un redémarrage)" ,
2026-08-12 10:20:55 +02:00
_ => key
2026-08-12 12:18:52 +02:00
},
agentScoped ));
2026-08-12 10:20:55 +02:00
}
await groupDb . SaveChangesWithRetryAsync ();
2026-08-20 14:13:06 +02:00
}
2026-08-12 10:20:55 +02:00
2026-08-20 14:13:06 +02:00
private static async Task MigrateLegacySentryKeysAsync ( AppDbContext groupDb )
{
2026-08-12 12:18:52 +02:00
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 ();
2026-08-20 14:13:06 +02:00
}
2026-08-12 12:18:52 +02:00
2026-08-20 14:13:06 +02:00
private static async Task SeedDemoDataAsync (
IConfiguration configuration ,
2026-11-04 13:33:30 +01:00
Microsoft . AspNetCore . Identity . UserManager < Heimdall . Infrastructure . Identity . IdentityAppUser > userManager ,
2026-08-20 14:13:06 +02:00
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 )
2026-08-09 23:43:11 +02:00
{
2026-11-04 13:33:30 +01:00
testAdmin = new Heimdall . Infrastructure . Identity . IdentityAppUser
2026-08-09 23:43:11 +02:00
{
2026-08-20 14:13:06 +02:00
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." );
2026-11-04 13:33:30 +01:00
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 )));
}
2026-08-20 14:13:06 +02:00
}
2026-08-09 23:43:11 +02:00
2026-08-20 14:13:06 +02:00
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-08-09 23:43:11 +02:00
}
}
2026-07-23 18:12:47 +00:00
internal static void ConfigureServices ( WebApplicationBuilder builder )
{
2026-07-29 14:20:14 +00:00
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-10-10 22:55:26 +02:00
builder . Services . AddLocalization ( options => options . ResourcesPath = "Localization" );
2026-10-25 04:19:19 +01:00
builder . Services . AddScoped < UiLanguageService >();
builder . Services . AddScoped < UiText >();
2026-10-10 22:55:26 +02:00
2026-07-23 18:12:47 +00:00
builder . Services . AddRazorComponents ()
. AddInteractiveServerComponents ();
2026-08-09 23:43:11 +02:00
builder . Services . AddMemoryCache ();
2026-08-20 14:13:06 +02:00
ConfigureAuthentication ( builder );
ConfigureMudAndRateLimiting ( builder );
ConfigureControllers ( builder );
ConfigureSignalR ( builder );
2026-08-20 18:22:37 +02:00
// ── 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 );
2026-10-26 14:42:06 +01:00
metrics . AddMeter ( Heimdall . Infrastructure . Metrics . HangfireJobMetrics . MeterName );
2026-10-26 15:14:29 +01:00
metrics . AddMeter ( Heimdall . Infrastructure . Metrics . NotificationOutboxMetrics . MeterName );
2026-08-20 18:22:37 +02:00
});
2026-08-20 14:13:06 +02:00
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 ;
2026-08-20 18:14:18 +02:00
// 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 ; });
2026-08-20 14:13:06 +02:00
options . AddFixedWindowLimiter ( "TwoFactor" , opt => { opt . PermitLimit = 5 ; opt . Window = TimeSpan . FromMinutes ( 1 ); opt . QueueLimit = 0 ; });
2026-08-20 18:14:18 +02:00
options . AddFixedWindowLimiter ( "Snapshot" , opt => { opt . PermitLimit = 1000 ; opt . Window = TimeSpan . FromMinutes ( 1 ); opt . QueueLimit = 0 ; });
2026-08-20 14:13:06 +02:00
});
}
2026-08-20 18:14:18 +02:00
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" ;
}
2026-08-20 14:13:06 +02:00
private static void ConfigureControllers ( WebApplicationBuilder builder )
{
2026-10-20 07:16:44 +02:00
builder . Services . AddScoped < Heimdall . Api . Security . ResourceAccess >();
2026-11-06 11:14:49 +01:00
builder . Services . AddSingleton < Heimdall . Api . Security . LiveMediaTickets >();
builder . Services . AddSingleton < Heimdall . Api . Security . LiveMediaSessionLimiter >();
2026-10-20 07:16:44 +02:00
builder . Services . AddSingleton < Heimdall . Api . Security . LiveSubscriptions >();
2026-08-20 14:13:06 +02:00
builder . Services . AddControllers ( options =>
2026-10-20 07:16:44 +02:00
{
options . Filters . Add < Heimdall . Api . Filters . ExceptionFilter >();
options . Filters . Add < Heimdall . Api . Security . ResourceAccessFilter >();
})
2026-08-20 14:13:06 +02:00
. 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 );
2026-10-20 07:21:28 +02:00
options . SlidingExpiration = false ;
2026-08-20 14:13:06 +02:00
});
}
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 >();
2026-10-20 07:21:28 +02:00
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 ;
});
2026-08-20 14:13:06 +02:00
builder . Services . AddTransient < SameOriginHttpMessageHandler >();
2026-10-20 07:21:28 +02:00
builder . Services . AddHttpClient ( "HeimdallRefresh" )
. ConfigurePrimaryHttpMessageHandler (() => new HttpClientHandler { UseCookies = false });
2026-08-20 14:13:06 +02:00
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 );
2026-10-20 07:21:28 +02:00
}). ConfigurePrimaryHttpMessageHandler (() => new HttpClientHandler { UseCookies = false });
2026-08-20 14:13:06 +02:00
if ( apiBaseUrlConfigured )
Console . WriteLine ( $"[DIAG] ApiBaseUrl: {apiBaseUrl} (explicit)" );
else
Console . WriteLine ( "[DIAG] ApiBaseUrl: same-origin (no explicit config)" );
}
private static void ConfigureAuthentication ( WebApplicationBuilder builder )
{
2026-07-23 18:12:47 +00:00
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" ;
2026-08-20 18:14:11 +02:00
var authBuilder = builder . Services
. AddAuthentication ( CookieAuthenticationDefaults . AuthenticationScheme );
ConfigureCookieAuthentication ( authBuilder );
ConfigureJwtBearerAuthentication ( authBuilder , jwtKey , jwtIssuer , jwtAudience );
authBuilder . AddScheme < ApiKeyAuthenticationOptions , ApiKeyAuthenticationHandler >( "ApiKey" , null );
2026-07-24 19:29:02 +00:00
2026-08-20 18:14:11 +02:00
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 );
2026-10-20 07:21:28 +02:00
options . SlidingExpiration = false ;
2026-08-20 18:14:11 +02:00
// Add logging events
options . Events = new CookieAuthenticationEvents
{
2026-10-20 07:21:28 +02:00
OnValidatePrincipal = async context =>
{
if (! await ValidateAccountSessionAsync ( context . Principal !, context . HttpContext ))
context . RejectPrincipal ();
},
2026-08-20 18:14:11 +02:00
OnRedirectToLogin = context =>
2026-07-24 18:25:33 +00:00
{
2026-08-20 18:14:11 +02:00
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 ))
2026-07-24 18:25:33 +00:00
{
2026-08-20 18:14:11 +02:00
context . Response . StatusCode = StatusCodes . Status401Unauthorized ;
2026-07-24 18:25:33 +00:00
return Task . CompletedTask ;
}
2026-08-20 18:14:11 +02:00
context . Response . Redirect ( context . RedirectUri );
return Task . CompletedTask ;
},
OnRedirectToAccessDenied = context =>
2026-07-23 18:12:47 +00:00
{
2026-08-20 18:14:11 +02:00
var logger = context . HttpContext . RequestServices . GetRequiredService < ILogger < Program >>();
logger . LogWarning ( "Access denied: {Path} -> {AccessDeniedPath}" ,
context . Request . Path , options . AccessDeniedPath );
if ( IsApiRequest ( context . Request ))
2026-07-23 18:12:47 +00:00
{
2026-08-20 18:14:11 +02:00
context . Response . StatusCode = StatusCodes . Status403Forbidden ;
2026-07-23 18:12:47 +00:00
return Task . CompletedTask ;
}
2026-08-20 18:14:11 +02:00
context . Response . Redirect ( context . RedirectUri );
return Task . CompletedTask ;
}
};
});
}
2026-07-23 18:12:47 +00:00
2026-10-20 07:21:28 +02:00
private static Task < bool > ValidateAccountSessionAsync ( ClaimsPrincipal principal , HttpContext http ) =>
2026-11-07 08:35:19 +01:00
Heimdall . Application . Auth . Services . AccountSessionPolicy . IsValidLiveAsync ( principal ,
2026-11-04 13:33:30 +01:00
http . RequestServices . GetRequiredService < Heimdall . Application . Services . IIdentityAccountService >(),
2026-11-07 08:35:19 +01:00
http . RequestServices . GetRequiredService < Heimdall . Application . Common . IApplicationDbContext >(), http . RequestAborted );
2026-10-20 07:21:28 +02:00
2026-08-20 18:14:11 +02:00
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
{
2026-10-20 07:21:28 +02:00
OnTokenValidated = async context =>
{
if (! await ValidateAccountSessionAsync ( context . Principal !, context . HttpContext ))
context . Fail ( "Session revoked" );
},
2026-08-20 18:14:11 +02:00
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 )
{
2026-07-23 18:12:47 +00:00
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
2026-11-04 13:33:30 +01:00
// Legacy role-based policy retained for administrative endpoints.
2026-08-09 23:43:11 +02:00
options . AddPolicy ( "AdminUsers" , policy => policy . RequireRole ( AppRoles . Admin ));
2026-07-23 18:12:47 +00:00
});
2026-08-20 14:13:06 +02:00
}
2026-07-23 18:12:47 +00:00
2026-08-20 14:13:06 +02:00
private static void ConfigureSentry ( WebApplicationBuilder builder )
{
2026-08-12 12:18:52 +02:00
var sentryDsn = builder . Configuration [ "Sentry:Dsn" ]
?? Environment . GetEnvironmentVariable ( "SENTRY_DSN" );
2026-08-20 14:13:06 +02:00
var isTestingEnv = builder . Environment . IsEnvironment ( TestingEnvironment );
2026-08-18 08:22:47 +02:00
var sentryEnabled = ! isTestingEnv && IsSentryEnabledFromDb ( builder . Services );
2026-08-12 12:18:52 +02:00
if ( sentryEnabled && ! string . IsNullOrEmpty ( sentryDsn ))
{
2026-08-20 14:13:06 +02:00
builder . WebHost . UseSentry (( SentryAspNetCoreOptions options ) => ConfigureSentryOptions ( options , builder , sentryDsn ));
2026-08-12 12:18:52 +02:00
}
2026-08-20 14:13:06 +02:00
var sentryStatus = FormatSentryStatus ( sentryEnabled , sentryDsn );
2026-08-12 12:18:52 +02:00
Console . WriteLine ( $"[DIAG] Sentry/GlitchTip DSN: {sentryStatus}" );
2026-08-20 14:13:06 +02:00
}
2026-08-12 12:18:52 +02:00
2026-08-20 14:13:06 +02:00
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 , _ ) =>
2026-08-09 23:43:11 +02:00
{
2026-08-20 14:13:06 +02:00
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 ;
2026-08-09 23:43:11 +02:00
});
2026-08-20 14:13:06 +02:00
options . SetBeforeBreadcrumb ( breadcrumb
=> breadcrumb . Category == "Microsoft.AspNetCore.RateLimiting"
? null
: breadcrumb );
2026-07-23 18:12:47 +00:00
}
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-11-06 09:41:48 +01:00
var staticFileContentTypes = new FileExtensionContentTypeProvider ();
staticFileContentTypes . Mappings [ ".py" ] = "text/x-python" ;
app . UseStaticFiles ( new StaticFileOptions
{
ContentTypeProvider = staticFileContentTypes ,
});
2026-07-23 18:12:47 +00:00
app . UseAuthentication ();
app . UseAuthorization ();
app . UseAntiforgery ();
2026-10-10 22:55:26 +02:00
// 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 );
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).
2026-08-20 14:13:06 +02:00
if (! app . Environment . IsEnvironment ( TestingEnvironment ))
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.
2026-08-20 14:13:06 +02:00
if ( app . Environment . IsEnvironment ( TestingEnvironment ))
2026-08-09 23:43:11 +02:00
{
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 ();
2026-08-20 18:22:37 +02:00
// ── Prometheus metrics endpoint (spec 13.1) ────────────────────────
// /metrics — scraped by Prometheus. No auth (internal network only).
app . MapPrometheusScrapingEndpoint ( "/metrics" );
2026-07-23 18:12:47 +00:00
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 _ );
2026-10-20 07:21:28 +02:00
if (! await ValidateAccountSessionAsync ( principal , httpContext ))
return Results . Unauthorized ();
2026-07-23 18:12:47 +00:00
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 ),
};
2026-10-20 07:21:28 +02:00
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 )!));
2026-07-23 18:12:47 +00:00
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 );
2026-10-20 07:21:28 +02:00
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 )
});
2026-07-23 18:12:47 +00:00
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-08-12 12:18:52 +02:00
/// <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 ;
}
}
2026-07-23 18:12:47 +00:00
}