fix(auth): répare l'authentification de bout en bout (cookie + JWT + rendu Blazor)
Anomalies corrigées : - MudPopoverProvider manquant dans les layouts → circuit Blazor mourait sur l'ouverture de menus/popovers (dashboard jamais rendu après login) - AddIdentity redéfinissait le schéma par défaut sur Identity.Application alors que /_auth/signin signait avec Cookies → cookie posé mais jamais validé, tout rechargement de page redirigeait vers /login. Forçage du schéma par défaut sur Cookies + schémas JwtBearer explicites sur les endpoints API d'AuthController et SettingsController - Policy 'AdminUsers' utilisée par register-admin mais jamais enregistrée → 500 à l'appel. Ajoutée (RequireRole Admin) - HeimdallAuthStateProvider ne lisait que le sessionStorage navigateur : pendant le prerender SSR, HttpContext.User (cookie) n'était pas utilisé → pages protégées redirigées vers /login. Fallback cookie ajouté - SameOriginHttpMessageHandler : résolution de l'origine via IServerAddressesFeature quand IHttpContextAccessor est null (circuit Blazor post-hydratation) au lieu de heimdall.local → DNS cassé - UpdateUserValidator rejetait le thème 'Auto' (défaut de l'UI) → 400 à l'édition. Accepte désormais auto (case-insensitive) Tests : - E2E Playwright complets (login/logout/register/user management) : 33/33 - Integration (Testcontainers PostgreSQL) : 120/120 (valeur 'bool' du valueType, bootstrap admin via /register auto-admin, header X-API-Key, /proc/meminfo optionnel pour les LXC restreints) - Exécution E2E séquentielle (xunit.runner.json) pour éliminer le flakiness
This commit is contained in:
1 parent
895fdc3422
commit
53b6240a3e
27 files changed
+993
-163
No files matched your search
+194
-114
@@ -37,54 +37,14 @@ 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.
|
||||
// In Production/Staging: migrations run by default (auto=true).
|
||||
// In Testing: disabled (set Seed:DemoOnStartup=true to enable) via Database:MigrateOnStartup=false config.
|
||||
// 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.IsProduction();
|
||||
?? !app.Environment.IsEnvironment("Testing");
|
||||
if (migrateOnStartup)
|
||||
{
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
await Program.ApplyMigrationsAsync(app);
|
||||
}
|
||||
|
||||
// ── Register recurring Hangfire jobs (heartbeat monitor, agent failover) ──
|
||||
@@ -102,70 +62,7 @@ if (!isTesting && !string.IsNullOrEmpty(pgConnStr))
|
||||
// ── 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.
|
||||
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();
|
||||
|
||||
// Seed demo admin + demo site in Development only
|
||||
if (builder.Configuration.GetValue<bool>("Seed:DemoOnStartup", false))
|
||||
{
|
||||
var adminLogin = builder.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 = builder.Configuration.GetValue<string>("Seed:AdminDisplayName") ?? Environment.GetEnvironmentVariable("SEED__ADMIN_DISPLAYNAME") ?? "Admin"
|
||||
};
|
||||
var adminPassword = builder.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();
|
||||
}
|
||||
}
|
||||
}
|
||||
await Program.SeedAsync(app, builder.Configuration);
|
||||
|
||||
app.Run();
|
||||
|
||||
@@ -198,6 +95,14 @@ public partial class Program {
|
||||
{
|
||||
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);
|
||||
@@ -210,6 +115,130 @@ public partial class Program {
|
||||
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);
|
||||
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();
|
||||
|
||||
// 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal static void ConfigureServices(WebApplicationBuilder builder)
|
||||
{
|
||||
// ── Sentry (GlitchTip) — error tracking, performance & structured logs ──
|
||||
@@ -305,6 +334,9 @@ public partial class Program {
|
||||
builder.Services.AddRazorComponents()
|
||||
.AddInteractiveServerComponents();
|
||||
|
||||
// In-memory cache — required by INotificationRateLimiter (singleton)
|
||||
builder.Services.AddMemoryCache();
|
||||
|
||||
// ── Authentication ──────────────────────────────────────────────
|
||||
var jwtKey = builder.Configuration["Jwt:Key"]
|
||||
?? Environment.GetEnvironmentVariable("JWT__KEY")
|
||||
@@ -376,6 +408,10 @@ public partial class Program {
|
||||
var allPermissions = AppPermissions.RolePermissions.Values.SelectMany(p => p).Distinct();
|
||||
foreach (var permission in allPermissions)
|
||||
options.AddPolicy(permission, policy => policy.RequireClaim("permission", permission));
|
||||
|
||||
// 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));
|
||||
});
|
||||
builder.Services.AddCascadingAuthenticationState();
|
||||
|
||||
@@ -398,11 +434,18 @@ public partial class Program {
|
||||
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; });
|
||||
// 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; });
|
||||
});
|
||||
|
||||
// ── Controllers (REST API) ────────────────────────────────────────
|
||||
builder.Services.AddControllers(options =>
|
||||
options.Filters.Add<Heimdall.Api.Filters.ExceptionFilter>());
|
||||
options.Filters.Add<Heimdall.Api.Filters.ExceptionFilter>())
|
||||
// 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);
|
||||
builder.Services.AddFluentValidationAutoValidation();
|
||||
builder.Services.Configure<Microsoft.AspNetCore.Http.Json.JsonOptions>(opts =>
|
||||
opts.SerializerOptions.Converters.Add(new System.Text.Json.Serialization.JsonStringEnumConverter()));
|
||||
@@ -418,6 +461,19 @@ public partial class Program {
|
||||
builder.Services.AddApplication();
|
||||
builder.Services.AddInfrastructure(builder.Configuration);
|
||||
|
||||
// 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;
|
||||
});
|
||||
|
||||
// Configure Identity cookie AFTER AddInfrastructure (which calls AddIdentity)
|
||||
// AddIdentity sets default paths (/Account/Login) that must be overridden
|
||||
builder.Services.ConfigureApplicationCookie(options =>
|
||||
@@ -441,17 +497,29 @@ public partial class Program {
|
||||
builder.Services.AddBackgroundJobs(builder.Configuration);
|
||||
|
||||
// ── HTTP client ──────────────────────────────────────────────────
|
||||
// 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();
|
||||
builder.Services.AddScoped<HeimdallApiClient>();
|
||||
builder.Services.AddTransient<TokenRefreshHandler>();
|
||||
var apiBaseUrl = builder.Configuration.GetValue<string>("ApiBaseUrl")
|
||||
?? Environment.GetEnvironmentVariable("API_BASE_URL")
|
||||
?? "http://localhost:8080";
|
||||
builder.Services.AddTransient<SameOriginHttpMessageHandler>();
|
||||
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);
|
||||
}).AddHttpMessageHandler<TokenRefreshHandler>();
|
||||
})
|
||||
.AddHttpMessageHandler<TokenRefreshHandler>()
|
||||
.AddHttpMessageHandler<SameOriginHttpMessageHandler>();
|
||||
if (apiBaseUrlConfigured)
|
||||
Console.WriteLine($"[DIAG] ApiBaseUrl: {apiBaseUrl} (explicit)");
|
||||
else
|
||||
Console.WriteLine("[DIAG] ApiBaseUrl: same-origin (no explicit config)");
|
||||
|
||||
builder.Services.AddScoped<AuthState>();
|
||||
}
|
||||
@@ -488,6 +556,18 @@ public partial class Program {
|
||||
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("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)}");
|
||||
}
|
||||
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
app.MapOpenApi();
|
||||
|
||||
Reference in new issue
Block a user