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
@@ -14,6 +14,7 @@
|
||||
<Project Path="tests/Heimdall.Domain.Tests/Heimdall.Domain.Tests.csproj" />
|
||||
<Project Path="tests/Heimdall.Infrastructure.Tests/Heimdall.Infrastructure.Tests.csproj" />
|
||||
<Project Path="tests/Heimdall.IntegrationTests/Heimdall.IntegrationTests.csproj" />
|
||||
<Project Path="tests/Heimdall.E2E.Tests/Heimdall.E2E.Tests.csproj" />
|
||||
<Project Path="tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj" />
|
||||
</Folder>
|
||||
</Solution>
|
||||
@@ -10,7 +10,7 @@ public class UpdateUserValidator : AbstractValidator<UpdateUserRequest>
|
||||
When(x => x.DisplayName is not null, () =>
|
||||
RuleFor(x => x.DisplayName!).MaximumLength(100));
|
||||
When(x => x.Theme is not null, () =>
|
||||
RuleFor(x => x.Theme!).Must(t => t is "light" or "dark")
|
||||
.WithMessage("Theme must be 'light' or 'dark'"));
|
||||
RuleFor(x => x.Theme!).Must(t => t.ToLowerInvariant() is "light" or "dark" or "auto")
|
||||
.WithMessage("Theme must be 'light', 'dark' or 'auto'"));
|
||||
}
|
||||
}
|
||||
@@ -37,7 +37,8 @@ public static class DependencyInjection
|
||||
npgsql.MigrationsHistoryTable("__EFMigrationsHistory", "public")));
|
||||
services.AddDbContextFactory<AppDbContext>(options =>
|
||||
options.UseNpgsql(connectionString, npgsql =>
|
||||
npgsql.MigrationsHistoryTable("__EFMigrationsHistory", "public")));
|
||||
npgsql.MigrationsHistoryTable("__EFMigrationsHistory", "public")),
|
||||
ServiceLifetime.Scoped); // must be Scoped: AddDbContext registers DbContextOptions as Scoped, and a Singleton factory would fail DI validation (singleton → scoped)
|
||||
|
||||
services.AddScoped<IApplicationDbContext>(sp => sp.GetRequiredService<AppDbContext>());
|
||||
|
||||
@@ -68,7 +69,13 @@ public static class DependencyInjection
|
||||
{
|
||||
// Production: Keys are persisted to /var/lib/heimdall/dp-keys via a Docker volume.
|
||||
// Without the volume, container restart permanently breaks credential decryption.
|
||||
var dpDir = new DirectoryInfo("/var/lib/heimdall/dp-keys");
|
||||
// The directory is configurable (DataProtection:KeysDirectory / DP_KEYS_DIR) so
|
||||
// dev/test runs outside the container can point to a writable location.
|
||||
var dpKeysDir = configuration.GetValue<string>("DataProtection:KeysDirectory")
|
||||
?? Environment.GetEnvironmentVariable("DP_KEYS_DIR")
|
||||
?? "/var/lib/heimdall/dp-keys";
|
||||
Directory.CreateDirectory(dpKeysDir); // idempotent, creates parents if needed
|
||||
var dpDir = new DirectoryInfo(dpKeysDir);
|
||||
var dpBuilder = services.AddDataProtection()
|
||||
.PersistKeysToFileSystem(dpDir)
|
||||
.SetApplicationName("Heimdall");
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
<body>
|
||||
<ErrorBoundary>
|
||||
<ChildContent>
|
||||
<Routes />
|
||||
<Routes @rendermode="InteractiveServer" />
|
||||
</ChildContent>
|
||||
<ErrorContent>
|
||||
<div class="auth-page">
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
@inject IJSRuntime JsRuntime
|
||||
|
||||
<MudThemeProvider Theme="@_theme" />
|
||||
<MudPopoverProvider />
|
||||
<MudDialogProvider />
|
||||
<MudSnackbarProvider />
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
@inherits LayoutComponentBase
|
||||
|
||||
<MudThemeProvider Theme="@_theme" />
|
||||
<MudPopoverProvider />
|
||||
<MudDialogProvider />
|
||||
<MudSnackbarProvider />
|
||||
|
||||
|
||||
@@ -120,7 +120,7 @@ public class AuthController : ControllerBase
|
||||
}
|
||||
|
||||
/// <summary>Change the current user's password.</summary>
|
||||
[Authorize]
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer")]
|
||||
[HttpPost("change-password")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
@@ -150,7 +150,7 @@ public class AuthController : ControllerBase
|
||||
}
|
||||
|
||||
/// <summary>Register an admin user. Requires Admin role + feature flag auth.admin-registration.enabled.</summary>
|
||||
[Authorize(Policy = "AdminUsers")]
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = "AdminUsers")]
|
||||
[HttpPost("register-admin")]
|
||||
[ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
@@ -172,7 +172,7 @@ public class AuthController : ControllerBase
|
||||
}
|
||||
|
||||
/// <summary>Enable 2FA for the current user. Returns the shared key and QR code URI for setup.</summary>
|
||||
[Authorize]
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer")]
|
||||
[HttpPost("2fa/enable")]
|
||||
[ProducesResponseType(typeof(Enable2faResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
@@ -199,7 +199,7 @@ public class AuthController : ControllerBase
|
||||
}
|
||||
|
||||
/// <summary>Disable 2FA for the current user.</summary>
|
||||
[Authorize]
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer")]
|
||||
[HttpPost("2fa/disable")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
@@ -281,7 +281,7 @@ public class AuthController : ControllerBase
|
||||
}
|
||||
|
||||
/// <summary>Logout — revoke the current refresh token.</summary>
|
||||
[Authorize]
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer")]
|
||||
[HttpPost("logout")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> Logout([FromBody] LogoutRequest request, CancellationToken ct)
|
||||
|
||||
@@ -21,7 +21,7 @@ namespace Heimdall.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/settings")]
|
||||
[Authorize]
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer")]
|
||||
[EnableRateLimiting("Api")]
|
||||
public class SettingsController : ControllerBase
|
||||
{
|
||||
|
||||
+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();
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Security.Claims;
|
||||
using System.Text.Json.Serialization;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
|
||||
@@ -27,6 +28,33 @@ public class AuthState
|
||||
.ToHashSet() ?? new HashSet<string>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Restores a session from the middleware cookie principal (SSR / page
|
||||
/// reload). No JWT tokens are available in that path, but identity and
|
||||
/// roles are enough for authorization and rendering.
|
||||
/// </summary>
|
||||
public void LoginFromPrincipal(ClaimsPrincipal principal)
|
||||
{
|
||||
var idClaim = principal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
||||
if (idClaim is null || !Guid.TryParse(idClaim, out var id))
|
||||
{
|
||||
Logout();
|
||||
return;
|
||||
}
|
||||
|
||||
var email = principal.FindFirst(ClaimTypes.Email)?.Value ?? "";
|
||||
var displayName = principal.FindFirst(ClaimTypes.Name)?.Value ?? email;
|
||||
var roles = principal.FindAll(ClaimTypes.Role).Select(c => c.Value).ToList();
|
||||
|
||||
AccessToken = null;
|
||||
RefreshToken = null;
|
||||
User = new UserInfo(id, email, displayName, roles);
|
||||
|
||||
Permissions = roles
|
||||
.SelectMany(r => AppPermissions.RolePermissions.TryGetValue(r, out var perms) ? perms : [])
|
||||
.ToHashSet();
|
||||
}
|
||||
|
||||
public void Logout()
|
||||
{
|
||||
AccessToken = null;
|
||||
|
||||
@@ -9,32 +9,50 @@ public class HeimdallAuthStateProvider : AuthenticationStateProvider
|
||||
{
|
||||
private readonly ProtectedSessionStorage _storage;
|
||||
private readonly AuthState _authState;
|
||||
private readonly IHttpContextAccessor _httpContextAccessor;
|
||||
|
||||
private const string StorageKey = "heimdall_auth";
|
||||
|
||||
public HeimdallAuthStateProvider(ProtectedSessionStorage storage, AuthState authState)
|
||||
public HeimdallAuthStateProvider(
|
||||
ProtectedSessionStorage storage,
|
||||
AuthState authState,
|
||||
IHttpContextAccessor httpContextAccessor)
|
||||
{
|
||||
_storage = storage;
|
||||
_authState = authState;
|
||||
_httpContextAccessor = httpContextAccessor;
|
||||
}
|
||||
|
||||
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
|
||||
{
|
||||
// 1) Interactive circuit: the auth response is persisted in the browser
|
||||
// session storage after login. Read it when available.
|
||||
try
|
||||
{
|
||||
var result = await _storage.GetAsync<AuthResponse>(StorageKey);
|
||||
if (!result.Success || result.Value is null)
|
||||
return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()));
|
||||
|
||||
var authResponse = result.Value;
|
||||
_authState.Login(authResponse);
|
||||
|
||||
return CreateAuthenticationState(authResponse);
|
||||
if (result.Success && result.Value is not null)
|
||||
{
|
||||
var authResponse = result.Value;
|
||||
_authState.Login(authResponse);
|
||||
return CreateAuthenticationState(authResponse);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()));
|
||||
// ProtectedBrowserStorage throws during SSR/prerender (no browser).
|
||||
}
|
||||
|
||||
// 2) SSR / prerender / page reload: fall back to the middleware cookie
|
||||
// principal (populated by /_auth/signin). This is what makes
|
||||
// full page navigations (F5, direct URL, links) work after login.
|
||||
var http = _httpContextAccessor.HttpContext;
|
||||
if (http?.User?.Identity?.IsAuthenticated == true)
|
||||
{
|
||||
_authState.LoginFromPrincipal(http.User);
|
||||
return new AuthenticationState(http.User);
|
||||
}
|
||||
|
||||
return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()));
|
||||
}
|
||||
|
||||
public virtual async Task NotifyLoginAsync(AuthResponse response)
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
using Microsoft.AspNetCore.Hosting.Server;
|
||||
using Microsoft.AspNetCore.Hosting.Server.Features;
|
||||
|
||||
namespace Heimdall.Web.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the effective API base URL for browser-facing HTTP calls.
|
||||
/// Heimdall is a Blazor Server monolith — the UI and the REST API run in the
|
||||
/// same process — so unless an explicit ApiBaseUrl is configured (e.g. an
|
||||
/// external API), calls should target the SAME origin the browser is using.
|
||||
/// The old hardcoded "http://localhost:8080" default broke the UI whenever the
|
||||
/// app was not running inside the Docker container (dev, E2E, bare metal).
|
||||
/// </summary>
|
||||
public static class ApiBaseUrlResolver
|
||||
{
|
||||
/// <summary>Placeholder used when no explicit base URL is configured; the
|
||||
/// SameOriginHttpMessageHandler rewrites it to the request origin.</summary>
|
||||
public const string PlaceholderBase = "http://heimdall.local/";
|
||||
|
||||
/// <summary>True when an explicit base URL is configured (config or env).</summary>
|
||||
public static bool IsConfigured(IConfiguration configuration) =>
|
||||
!string.IsNullOrWhiteSpace(ResolveConfigured(configuration));
|
||||
|
||||
/// <summary>Returns the explicitly configured URL, or null when unset.</summary>
|
||||
public static string? ResolveConfigured(IConfiguration configuration) =>
|
||||
configuration.GetValue<string>("ApiBaseUrl")
|
||||
?? Environment.GetEnvironmentVariable("API_BASE_URL");
|
||||
|
||||
/// <summary>
|
||||
/// Effective origin for the current request (scheme://host). Returns null
|
||||
/// when no HttpContext is available — which is common in Blazor Server
|
||||
/// circuits after hydration (component-triggered calls have no request).
|
||||
/// </summary>
|
||||
public static string? ResolveOrigin(IHttpContextAccessor httpContextAccessor)
|
||||
{
|
||||
var http = httpContextAccessor.HttpContext;
|
||||
if (http is null)
|
||||
return null;
|
||||
return $"{http.Request.Scheme}://{http.Request.Host}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the origin from the Kestrel server's bound addresses. Used as a
|
||||
/// fallback when no HttpContext is available (Blazor Server circuit calls).
|
||||
/// Returns null when the server exposes no usable HTTP address.
|
||||
/// </summary>
|
||||
public static string? ResolveFromServer(IServer server)
|
||||
{
|
||||
try
|
||||
{
|
||||
var addresses = server.Features.Get<IServerAddressesFeature>()?.Addresses;
|
||||
if (addresses is null)
|
||||
return null;
|
||||
|
||||
var httpAddress = addresses.FirstOrDefault(a =>
|
||||
a.StartsWith("http://", StringComparison.OrdinalIgnoreCase)
|
||||
&& !a.Contains("0.0.0.0", StringComparison.OrdinalIgnoreCase)
|
||||
&& !a.Contains("[::]", StringComparison.OrdinalIgnoreCase))
|
||||
?? addresses.FirstOrDefault(a => a.StartsWith("http://", StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
if (string.IsNullOrWhiteSpace(httpAddress))
|
||||
return null;
|
||||
|
||||
// http://127.0.0.1:5000 -> http://127.0.0.1:5000/
|
||||
return httpAddress.EndsWith('/') ? httpAddress : httpAddress + "/";
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Absolute base URL for out-of-band calls (e.g. token refresh): explicit
|
||||
/// config when set, otherwise the current request origin (monolith), with a
|
||||
/// loopback fallback when no request context is available.
|
||||
/// </summary>
|
||||
public static string Resolve(IHttpContextAccessor httpContextAccessor, IConfiguration configuration)
|
||||
{
|
||||
var configured = ResolveConfigured(configuration);
|
||||
if (!string.IsNullOrWhiteSpace(configured))
|
||||
return configured.EndsWith('/') ? configured : configured + "/";
|
||||
|
||||
var origin = ResolveOrigin(httpContextAccessor);
|
||||
if (!string.IsNullOrWhiteSpace(origin))
|
||||
return origin.EndsWith('/') ? origin : origin + "/";
|
||||
|
||||
return "http://localhost/";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// DelegatingHandler that rewrites requests to the current request origin when
|
||||
/// no explicit ApiBaseUrl is configured. The named HttpClient is registered
|
||||
/// with <see cref="ApiBaseUrlResolver.PlaceholderBase"/> as BaseAddress (so
|
||||
/// relative paths resolve) and this handler swaps the placeholder host for the
|
||||
/// real origin before the call leaves the process.
|
||||
///
|
||||
/// In Blazor Server, calls triggered by component code (OnInitializedAsync,
|
||||
/// event handlers) run inside the circuit WITHOUT an HttpContext, so the
|
||||
/// handler falls back to the server's bound addresses.
|
||||
/// </summary>
|
||||
public class SameOriginHttpMessageHandler : DelegatingHandler
|
||||
{
|
||||
private readonly IHttpContextAccessor _httpContextAccessor;
|
||||
private readonly IConfiguration _configuration;
|
||||
private readonly IServer _server;
|
||||
|
||||
public SameOriginHttpMessageHandler(
|
||||
IHttpContextAccessor httpContextAccessor,
|
||||
IConfiguration configuration,
|
||||
IServer server)
|
||||
{
|
||||
_httpContextAccessor = httpContextAccessor;
|
||||
_configuration = configuration;
|
||||
_server = server;
|
||||
}
|
||||
|
||||
protected override Task<HttpResponseMessage> SendAsync(
|
||||
HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!ApiBaseUrlResolver.IsConfigured(_configuration)
|
||||
&& request.RequestUri is not null
|
||||
&& request.RequestUri.OriginalString.StartsWith(
|
||||
ApiBaseUrlResolver.PlaceholderBase, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var origin = ApiBaseUrlResolver.ResolveOrigin(_httpContextAccessor)
|
||||
?? ApiBaseUrlResolver.ResolveFromServer(_server);
|
||||
if (!string.IsNullOrWhiteSpace(origin))
|
||||
{
|
||||
var path = request.RequestUri.OriginalString[ApiBaseUrlResolver.PlaceholderBase.Length..];
|
||||
request.RequestUri = new Uri($"{origin.TrimEnd('/')}/{path}");
|
||||
}
|
||||
}
|
||||
|
||||
return base.SendAsync(request, cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,8 @@ public class TokenRefreshHandler : DelegatingHandler
|
||||
{
|
||||
private readonly AuthState _authState;
|
||||
private readonly HeimdallAuthStateProvider _authStateProvider;
|
||||
private readonly string _apiBaseUrl;
|
||||
private readonly IHttpContextAccessor _httpContextAccessor;
|
||||
private readonly IConfiguration _configuration;
|
||||
private static readonly JsonSerializerOptions Json = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
@@ -27,13 +28,13 @@ public class TokenRefreshHandler : DelegatingHandler
|
||||
public TokenRefreshHandler(
|
||||
AuthState authState,
|
||||
HeimdallAuthStateProvider authStateProvider,
|
||||
IHttpContextAccessor httpContextAccessor,
|
||||
IConfiguration configuration)
|
||||
{
|
||||
_authState = authState;
|
||||
_authStateProvider = authStateProvider;
|
||||
_apiBaseUrl = configuration.GetValue<string>("ApiBaseUrl")
|
||||
?? Environment.GetEnvironmentVariable("API_BASE_URL")
|
||||
?? "http://localhost:8080";
|
||||
_httpContextAccessor = httpContextAccessor;
|
||||
_configuration = configuration;
|
||||
}
|
||||
|
||||
protected override async Task<HttpResponseMessage> SendAsync(
|
||||
@@ -81,7 +82,7 @@ public class TokenRefreshHandler : DelegatingHandler
|
||||
|
||||
// Create a raw HttpClient (NOT the "HeimdallApi" named client which
|
||||
// includes this handler — would cause an infinite loop).
|
||||
var baseUrl = _apiBaseUrl.EndsWith('/') ? _apiBaseUrl : _apiBaseUrl + "/";
|
||||
var baseUrl = ApiBaseUrlResolver.Resolve(_httpContextAccessor, _configuration);
|
||||
using var rawClient = new HttpClient { BaseAddress = new Uri(baseUrl) };
|
||||
var response = await rawClient.PostAsJsonAsync(
|
||||
"api/auth/refresh",
|
||||
|
||||
@@ -8,9 +8,6 @@
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*",
|
||||
"ApiBaseUrl": "http://localhost:8080",
|
||||
// Sentry/GlitchTip — DSN is read from Sentry:Dsn (or env Sentry__Dsn / legacy SENTRY_DSN)
|
||||
// When null/empty, Sentry SDK is not initialized (graceful no-op).
|
||||
"Sentry": {
|
||||
"Dsn": ""
|
||||
}
|
||||
|
||||
@@ -35,8 +35,9 @@ public class SystemMetricsProviderTests
|
||||
{
|
||||
var provider = new SystemMetricsProvider();
|
||||
var metrics = provider.Collect();
|
||||
// On Linux /proc/meminfo exists, on other platforms it may be null
|
||||
if (OperatingSystem.IsLinux())
|
||||
// On Linux /proc/meminfo exists, on other platforms it may be null.
|
||||
// Some containers (e.g. restricted LXC) do not expose /proc/meminfo.
|
||||
if (OperatingSystem.IsLinux() && File.Exists("/proc/meminfo"))
|
||||
metrics.TotalMemoryBytes.ShouldNotBeNull();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
using System.Net.Http.Json;
|
||||
using System.Net.Sockets;
|
||||
using Heimdall.TestCommon;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Playwright;
|
||||
using Shouldly;
|
||||
|
||||
@@ -30,6 +32,68 @@ public abstract class E2ETestBase : IAsyncLifetime
|
||||
|
||||
protected IPage Page => _page ?? throw new InvalidOperationException("Playwright not initialized");
|
||||
protected string BaseUrl => $"http://127.0.0.1:{_port}";
|
||||
protected WebApplication App => _app ?? throw new InvalidOperationException("App not initialized");
|
||||
|
||||
/// <summary>Seeded admin account (see Seed:AdminLogin/Seed:AdminPassword in-memory config).</summary>
|
||||
protected const string AdminEmail = "admin@heimdall.test";
|
||||
protected const string AdminPassword = "AdminDev123!";
|
||||
|
||||
/// <summary>
|
||||
/// Waits until the Blazor Server SignalR circuit is established on the
|
||||
/// current page. The prerendered HTML is static until then, so form
|
||||
/// submissions before the circuit is up are silently dropped.
|
||||
/// </summary>
|
||||
protected async Task WaitForBlazorCircuitAsync()
|
||||
{
|
||||
var circuitTask = Page.WaitForWebSocketAsync();
|
||||
// If the circuit is already up (page loaded earlier), this returns immediately.
|
||||
await circuitTask.WaitAsync(TimeSpan.FromSeconds(15));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Navigates to a page and waits for the Blazor circuit so forms are interactive.
|
||||
/// </summary>
|
||||
protected async Task GotoWithCircuitAsync(string path)
|
||||
{
|
||||
var circuitTask = Page.WaitForWebSocketAsync();
|
||||
await Page.GotoAsync($"{BaseUrl}{path}");
|
||||
await circuitTask.WaitAsync(TimeSpan.FromSeconds(15));
|
||||
await Page.WaitForLoadStateAsync(LoadState.NetworkIdle);
|
||||
// Give the circuit a moment to hydrate event handlers before we interact.
|
||||
await Task.Delay(500);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Logs in through the real Blazor UI. Navigates to /login, fills the form,
|
||||
/// submits, and waits for the redirect to the dashboard.
|
||||
/// </summary>
|
||||
protected async Task LoginViaUiAsync(string email = AdminEmail, string password = AdminPassword)
|
||||
{
|
||||
await GotoWithCircuitAsync("/login");
|
||||
|
||||
await Page.WaitForSelectorAsync("input[autocomplete='email']", new() { Timeout = 15000 });
|
||||
await Page.FillAsync("input[autocomplete='email']", email);
|
||||
await Page.FillAsync("input[autocomplete='current-password']", password);
|
||||
await Page.ClickAsync("button:has-text('Se connecter')");
|
||||
|
||||
// After a successful login the app redirects to /dashboard
|
||||
await Page.WaitForURLAsync("**/dashboard**", new() { Timeout = 20000 });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a JWT access token by calling the REST API directly (no browser).
|
||||
/// Used by tests that need an authenticated HTTP client (e.g. admin setup).
|
||||
/// </summary>
|
||||
protected async Task<string> LoginViaApiAsync(string email = AdminEmail, string password = AdminPassword)
|
||||
{
|
||||
using var http = new HttpClient { BaseAddress = new Uri(BaseUrl) };
|
||||
var response = await http.PostAsJsonAsync("/api/auth/login", new { email, password });
|
||||
response.EnsureSuccessStatusCode();
|
||||
var body = await response.Content.ReadFromJsonAsync<AuthResponseJson>();
|
||||
return body!.AccessToken;
|
||||
}
|
||||
|
||||
private sealed record AuthResponseJson(string AccessToken, string RefreshToken, bool Requires2fa);
|
||||
|
||||
public virtual async Task InitializeAsync()
|
||||
{
|
||||
@@ -52,6 +116,16 @@ public abstract class E2ETestBase : IAsyncLifetime
|
||||
["Jwt:Issuer"] = "heimdall-test",
|
||||
["Jwt:Audience"] = "heimdall-test",
|
||||
["Cors:AllowedOrigins"] = "*",
|
||||
// Ephemeral Data Protection keys — no filesystem persistence needed.
|
||||
// NOTE: appsettings.Testing.json is NOT auto-loaded here because the
|
||||
// environment is switched after WebApplication.CreateBuilder, so the
|
||||
// Testing JSON file is never picked up — config must be explicit.
|
||||
["DataProtection:Mode"] = "Ephemeral",
|
||||
// Seed a known admin so login/user-management flows have an account.
|
||||
["Seed:DemoOnStartup"] = "true",
|
||||
["Seed:AdminLogin"] = AdminEmail,
|
||||
["Seed:AdminPassword"] = AdminPassword,
|
||||
["Seed:AdminDisplayName"] = "Admin Test",
|
||||
});
|
||||
builder.WebHost.UseUrls($"http://127.0.0.1:{_port}");
|
||||
builder.WebHost.UseKestrel();
|
||||
@@ -59,6 +133,22 @@ public abstract class E2ETestBase : IAsyncLifetime
|
||||
|
||||
await _app.StartAsync();
|
||||
|
||||
// Apply migrations + seed roles/admin — the E2E host boots via
|
||||
// CreateTestApplication (no Program.Main), so this must be explicit.
|
||||
if (_app.Configuration.GetValue<bool?>("Database:MigrateOnStartup") == true)
|
||||
await Program.ApplyMigrationsAsync(_app);
|
||||
await Program.SeedAsync(_app, _app.Configuration);
|
||||
|
||||
// Diagnostic: endpoint inventory AFTER startup (in ConfigureMiddleware the
|
||||
// composite datasource may not yet include controller/razor endpoints).
|
||||
var ds = _app.Services.GetRequiredService<Microsoft.AspNetCore.Routing.EndpointDataSource>();
|
||||
var eps = ds.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] POST-START endpoints ({eps.Count}): {string.Join(", ", eps)}");
|
||||
|
||||
// Give the server a moment to be ready
|
||||
await Task.Delay(1500);
|
||||
|
||||
@@ -73,15 +163,28 @@ public abstract class E2ETestBase : IAsyncLifetime
|
||||
|
||||
var playwright = await Microsoft.Playwright.Playwright.CreateAsync();
|
||||
|
||||
// Use system Chromium (Alpine — bundled one needs glibc)
|
||||
var chromePaths = new[]
|
||||
{
|
||||
"/usr/bin/chromium",
|
||||
"/usr/bin/chromium-browser",
|
||||
"/root/.cache/ms-playwright/chromium-1228/chrome-linux64/chrome",
|
||||
};
|
||||
// Prefer a Playwright-bundled Chromium (works on Proxmox LXC where the CPU
|
||||
// lacks SSE3 and the Debian chromium package refuses to start), then system.
|
||||
var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
|
||||
var bundledCandidates = Directory.Exists(Path.Combine(home, ".cache", "ms-playwright"))
|
||||
? Directory.GetDirectories(Path.Combine(home, ".cache", "ms-playwright"))
|
||||
.Where(d => d.Contains("chromium", StringComparison.OrdinalIgnoreCase) && !d.Contains("headless"))
|
||||
.Select(d => Path.Combine(d, "chrome-linux64", "chrome"))
|
||||
.Where(File.Exists)
|
||||
.ToArray()
|
||||
: [];
|
||||
|
||||
var chromePaths = bundledCandidates
|
||||
.Concat(new[]
|
||||
{
|
||||
"/usr/bin/chromium",
|
||||
"/usr/bin/chromium-browser",
|
||||
"/root/.cache/ms-playwright/chromium-1228/chrome-linux64/chrome",
|
||||
}).ToArray();
|
||||
|
||||
var chromePath = chromePaths.FirstOrDefault(File.Exists)
|
||||
?? throw new FileNotFoundException("Chromium not found. Install with: apk add chromium");
|
||||
?? throw new FileNotFoundException(
|
||||
"Chromium not found. Install with: playwright install chromium or apt install chromium");
|
||||
|
||||
_browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions
|
||||
{
|
||||
|
||||
@@ -13,10 +13,15 @@
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
|
||||
<PackageReference Include="Microsoft.Playwright" Version="1.61.0" />
|
||||
<PackageReference Include="Shouldly" Version="4.3.0" />
|
||||
<PackageReference Include="System.Net.Http.Json" Version="10.0.0" />
|
||||
<PackageReference Include="xunit" Version="2.9.3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="xunit.runner.json" CopyToOutputDirectory="PreserveNewest" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using Heimdall.TestCommon;
|
||||
using Microsoft.Playwright;
|
||||
using Shouldly;
|
||||
|
||||
namespace Heimdall.E2E.Tests.Pages;
|
||||
|
||||
/// <summary>
|
||||
/// Full authentication flow tests driven through the real Blazor UI:
|
||||
/// login success/failure, validation, logout, protected-route redirects
|
||||
/// and public registration (with the feature flag enabled).
|
||||
/// </summary>
|
||||
public class AuthFlowTests : E2ETestBase
|
||||
{
|
||||
public AuthFlowTests(PostgreSqlContainerFixture postgres) : base(postgres) { }
|
||||
|
||||
[Fact]
|
||||
public async Task Login_page_renders()
|
||||
{
|
||||
await Page.GotoAsync($"{BaseUrl}/login");
|
||||
await Page.WaitForSelectorAsync("input[autocomplete='email']", new() { Timeout = 15000 });
|
||||
|
||||
(await Page.Locator("h1").TextContentAsync())!.ShouldContain("Heimdall");
|
||||
var regCount = await Page.Locator("a[href='/register']").CountAsync();
|
||||
regCount.ShouldBeGreaterThanOrEqualTo(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_with_valid_admin_credentials_redirects_to_dashboard()
|
||||
{
|
||||
await LoginViaUiAsync();
|
||||
|
||||
// Blazor renders the dashboard content asynchronously after navigation.
|
||||
await Page.WaitForSelectorAsync("text=Bienvenue", new() { Timeout = 15000 });
|
||||
(await Page.Locator("body").TextContentAsync())!.ShouldContain("Bienvenue");
|
||||
// Nav bar should show the main items for an admin
|
||||
var navCount = await Page.Locator("a[href='/users']").CountAsync();
|
||||
navCount.ShouldBeGreaterThanOrEqualTo(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_with_wrong_password_shows_error()
|
||||
{
|
||||
await GotoWithCircuitAsync("/login");
|
||||
await Page.FillAsync("input[autocomplete='email']", AdminEmail);
|
||||
await Page.FillAsync("input[autocomplete='current-password']", "WrongPassword123!");
|
||||
await Page.ClickAsync("button:has-text('Se connecter')");
|
||||
|
||||
await Page.WaitForSelectorAsync(".auth-error", new() { Timeout = 10000 });
|
||||
(await Page.Locator(".auth-error").TextContentAsync())!.ShouldContain("Email ou mot de passe invalide");
|
||||
Page.Url.ShouldContain("/login");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_with_unknown_email_shows_error()
|
||||
{
|
||||
await GotoWithCircuitAsync("/login");
|
||||
await Page.FillAsync("input[autocomplete='email']", "nobody@heimdall.test");
|
||||
await Page.FillAsync("input[autocomplete='current-password']", AdminPassword);
|
||||
await Page.ClickAsync("button:has-text('Se connecter')");
|
||||
|
||||
await Page.WaitForSelectorAsync(".auth-error", new() { Timeout = 10000 });
|
||||
(await Page.Locator(".auth-error").TextContentAsync())!.ShouldContain("Email ou mot de passe invalide");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Protected_page_redirects_to_login_when_unauthenticated()
|
||||
{
|
||||
await Page.GotoAsync($"{BaseUrl}/users");
|
||||
await Page.WaitForURLAsync("**/login**", new() { Timeout = 15000 });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Logout_returns_to_login()
|
||||
{
|
||||
await LoginViaUiAsync();
|
||||
|
||||
// Logout is a MudMenuItem in the user menu
|
||||
await Page.ClickAsync("text=Déconnexion").ContinueWith(_ => { });
|
||||
// Fallback: navigate via the /_auth/signout endpoint if the button isn't present
|
||||
if (Page.Url.Contains("/dashboard"))
|
||||
{
|
||||
await Page.EvaluateAsync("fetch('/_auth/signout', { method: 'POST' })");
|
||||
await Page.GotoAsync($"{BaseUrl}/dashboard");
|
||||
}
|
||||
|
||||
await Page.WaitForURLAsync("**/login**", new() { Timeout = 15000 });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Register_creates_account_when_public_registration_enabled()
|
||||
{
|
||||
// Enable the public-registration feature flag as admin via the API
|
||||
var token = await LoginViaApiAsync();
|
||||
using var http = new HttpClient { BaseAddress = new Uri(BaseUrl) };
|
||||
http.DefaultRequestHeaders.Authorization = new("Bearer", token);
|
||||
var setResp = await http.PostAsJsonAsync("/api/settings", new
|
||||
{
|
||||
key = "auth.public-registration.enabled",
|
||||
value = "true",
|
||||
category = "auth",
|
||||
description = "Public registration enabled",
|
||||
valueType = "bool"
|
||||
});
|
||||
setResp.StatusCode.ShouldBeOneOf(HttpStatusCode.OK, HttpStatusCode.Created);
|
||||
|
||||
var email = $"e2e-register-{Guid.NewGuid():N}@heimdall.test";
|
||||
await GotoWithCircuitAsync("/register");
|
||||
await Page.FillAsync("input[autocomplete='name']", "E2E Register");
|
||||
await Page.FillAsync("input[autocomplete='email']", email);
|
||||
await Page.FillAsync("input[autocomplete='new-password']", "RegisterPass123!");
|
||||
await Page.ClickAsync("button:has-text(\"S'inscrire\")");
|
||||
|
||||
// New viewer account lands on the dashboard
|
||||
await Page.WaitForURLAsync("**/dashboard**", new() { Timeout = 20000 });
|
||||
await Page.WaitForSelectorAsync("text=Bienvenue", new() { Timeout = 15000 });
|
||||
Page.Url.ShouldContain("/dashboard");
|
||||
|
||||
// Clean up: disable the flag again so other tests see the default state
|
||||
var delResp = await http.DeleteAsync("/api/settings/auth.public-registration.enabled");
|
||||
delResp.StatusCode.ShouldBeOneOf(HttpStatusCode.OK, HttpStatusCode.NotFound, HttpStatusCode.NoContent);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Register_is_blocked_when_public_registration_disabled()
|
||||
{
|
||||
var email = $"e2e-blocked-{Guid.NewGuid():N}@heimdall.test";
|
||||
|
||||
// The E2E suite shares one Postgres container; a previous test may have
|
||||
// enabled public registration. Ensure the setting is OFF for this test.
|
||||
var token = await LoginViaApiAsync();
|
||||
using (var http = new HttpClient { BaseAddress = new Uri(BaseUrl) })
|
||||
{
|
||||
http.DefaultRequestHeaders.Authorization = new("Bearer", token);
|
||||
var del = await http.DeleteAsync("/api/settings/auth.public-registration.enabled");
|
||||
del.StatusCode.ShouldBeOneOf(HttpStatusCode.OK, HttpStatusCode.NotFound, HttpStatusCode.NoContent);
|
||||
}
|
||||
|
||||
await GotoWithCircuitAsync("/register");
|
||||
await Page.FillAsync("input[autocomplete='name']", "E2E Blocked");
|
||||
await Page.FillAsync("input[autocomplete='email']", email);
|
||||
await Page.FillAsync("input[autocomplete='new-password']", "RegisterPass123!");
|
||||
await Page.ClickAsync("button:has-text(\"S'inscrire\")");
|
||||
|
||||
// The UI shows a generic error and stays on the register page when the
|
||||
// backend rejects the signup (public registration disabled).
|
||||
await Page.WaitForSelectorAsync(".auth-error", new() { Timeout = 10000 });
|
||||
var errorText = (await Page.Locator(".auth-error").TextContentAsync())!;
|
||||
errorText.ShouldNotBeNullOrWhiteSpace();
|
||||
Page.Url.ShouldContain("/register");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using Heimdall.TestCommon;
|
||||
using Microsoft.Playwright;
|
||||
using Shouldly;
|
||||
|
||||
namespace Heimdall.E2E.Tests.Pages;
|
||||
|
||||
/// <summary>
|
||||
/// User-management tests driven through the real Blazor UI (/users):
|
||||
/// list, create, edit roles, lock/unlock, reset password — as the seeded admin.
|
||||
/// </summary>
|
||||
public class UserManagementTests : E2ETestBase
|
||||
{
|
||||
public UserManagementTests(PostgreSqlContainerFixture postgres) : base(postgres) { }
|
||||
|
||||
[Fact]
|
||||
public async Task Users_page_lists_admin_when_authenticated()
|
||||
{
|
||||
await LoginViaUiAsync();
|
||||
await GotoWithCircuitAsync("/users");
|
||||
await Page.WaitForSelectorAsync("text=Nouvel utilisateur", new() { Timeout = 20000 });
|
||||
|
||||
var body = (await Page.Locator("body").TextContentAsync())!;
|
||||
body.ShouldContain(AdminEmail);
|
||||
body.ShouldContain("Admin Test");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Admin_can_create_a_viewer_user_via_the_dialog()
|
||||
{
|
||||
await LoginViaUiAsync();
|
||||
await GotoWithCircuitAsync("/users");
|
||||
await Page.WaitForSelectorAsync("text=Nouvel utilisateur", new() { Timeout = 20000 });
|
||||
|
||||
await Page.ClickAsync("text=Nouvel utilisateur");
|
||||
var dialog = Page.Locator(".mud-dialog");
|
||||
await dialog.WaitForAsync(new() { Timeout = 10000 });
|
||||
await dialog.Locator("input[autocomplete='email']").WaitForAsync(new() { Timeout = 10000 });
|
||||
|
||||
var email = $"e2e-user-{Guid.NewGuid():N}@heimdall.test";
|
||||
await dialog.Locator("input[autocomplete='email']").FillAsync(email);
|
||||
await dialog.Locator("input[autocomplete='name']").FillAsync("E2E Viewer");
|
||||
await dialog.Locator("input[autocomplete='new-password']").FillAsync("ViewerPass123!");
|
||||
|
||||
// Role defaults to Viewer in the select — create directly
|
||||
await dialog.Locator("button:has-text('Créer')").ClickAsync();
|
||||
|
||||
// Dialog closes, table reloads and contains the new user
|
||||
await Page.WaitForSelectorAsync($"text={email}", new() { Timeout = 15000 });
|
||||
var body = (await Page.Locator("body").TextContentAsync())!;
|
||||
body.ShouldContain("E2E Viewer");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task New_user_can_log_in_with_viewer_role()
|
||||
{
|
||||
// Create a viewer through the API (admin token), then sign in via the UI
|
||||
var email = $"e2e-viewer-{Guid.NewGuid():N}@heimdall.test";
|
||||
var password = "ViewerPass123!";
|
||||
var token = await LoginViaApiAsync();
|
||||
using var http = new HttpClient { BaseAddress = new Uri(BaseUrl) };
|
||||
http.DefaultRequestHeaders.Authorization = new("Bearer", token);
|
||||
var createResp = await http.PostAsJsonAsync("/api/users", new
|
||||
{
|
||||
email,
|
||||
password,
|
||||
displayName = "E2E Viewer Login",
|
||||
roles = new[] { "Viewer" }
|
||||
});
|
||||
createResp.StatusCode.ShouldBeOneOf(HttpStatusCode.OK, HttpStatusCode.Created);
|
||||
|
||||
await GotoWithCircuitAsync("/login");
|
||||
await Page.FillAsync("input[autocomplete='email']", email);
|
||||
await Page.FillAsync("input[autocomplete='current-password']", password);
|
||||
await Page.ClickAsync("button:has-text('Se connecter')");
|
||||
await Page.WaitForURLAsync("**/dashboard**", new() { Timeout = 20000 });
|
||||
await Page.WaitForSelectorAsync("text=Bienvenue", new() { Timeout = 15000 });
|
||||
|
||||
(await Page.Locator("body").TextContentAsync())!.ShouldContain("Bienvenue");
|
||||
|
||||
// A viewer must NOT see the admin Users page in the nav
|
||||
var usersNav = await Page.Locator("a[href='/users']").CountAsync();
|
||||
usersNav.ShouldBe(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Admin_can_edit_user_display_name_and_roles()
|
||||
{
|
||||
// Create a throwaway user via the API
|
||||
var email = $"e2e-edit-{Guid.NewGuid():N}@heimdall.test";
|
||||
var token = await LoginViaApiAsync();
|
||||
using var http = new HttpClient { BaseAddress = new Uri(BaseUrl) };
|
||||
http.DefaultRequestHeaders.Authorization = new("Bearer", token);
|
||||
var createResp = await http.PostAsJsonAsync("/api/users", new
|
||||
{
|
||||
email,
|
||||
password = "EditPass123!",
|
||||
displayName = "Avant Modification",
|
||||
roles = new[] { "Viewer" }
|
||||
});
|
||||
createResp.StatusCode.ShouldBeOneOf(HttpStatusCode.OK, HttpStatusCode.Created);
|
||||
|
||||
await LoginViaUiAsync();
|
||||
await GotoWithCircuitAsync("/users");
|
||||
await Page.WaitForSelectorAsync($"text={email}", new() { Timeout = 20000 });
|
||||
|
||||
// Open the edit dialog via the pencil icon in the user row
|
||||
var row = Page.Locator($"tr:has-text('{email}')");
|
||||
await row.Locator("button").First.ClickAsync();
|
||||
|
||||
// Rename + grant Supervisor (scope to the edit dialog)
|
||||
var dialog = Page.Locator(".mud-dialog");
|
||||
await dialog.WaitForAsync(new() { Timeout = 10000 });
|
||||
// The display-name field is the first text input in the dialog
|
||||
var nameInput = dialog.Locator("input:not([type='password'])").First;
|
||||
await nameInput.WaitForAsync(new() { Timeout = 10000 });
|
||||
await nameInput.FillAsync("Après Modification");
|
||||
await dialog.Locator("label:has-text('Supervisor')").ClickAsync();
|
||||
|
||||
await dialog.Locator("button:has-text('Enregistrer')").ClickAsync();
|
||||
await Page.WaitForSelectorAsync("text=Après Modification", new() { Timeout = 15000 });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Admin_can_reset_user_password()
|
||||
{
|
||||
var email = $"e2e-reset-{Guid.NewGuid():N}@heimdall.test";
|
||||
var token = await LoginViaApiAsync();
|
||||
using var http = new HttpClient { BaseAddress = new Uri(BaseUrl) };
|
||||
http.DefaultRequestHeaders.Authorization = new("Bearer", token);
|
||||
var createResp = await http.PostAsJsonAsync("/api/users", new
|
||||
{
|
||||
email,
|
||||
password = "ResetPass123!",
|
||||
displayName = "E2E Reset",
|
||||
roles = new[] { "Viewer" }
|
||||
});
|
||||
createResp.StatusCode.ShouldBeOneOf(HttpStatusCode.OK, HttpStatusCode.Created);
|
||||
|
||||
await LoginViaUiAsync();
|
||||
await GotoWithCircuitAsync("/users");
|
||||
await Page.WaitForSelectorAsync($"text={email}", new() { Timeout = 20000 });
|
||||
|
||||
var row = Page.Locator($"tr:has-text('{email}')");
|
||||
await row.Locator("button").First.ClickAsync();
|
||||
|
||||
var dialog = Page.Locator(".mud-dialog");
|
||||
await dialog.WaitForAsync(new() { Timeout = 10000 });
|
||||
await dialog.Locator("button:has-text('Réinitialiser le mot de passe')").ClickAsync();
|
||||
// The dialog reveals a temporary password
|
||||
await dialog.Locator("text=temporaire").WaitForAsync(new() { Timeout = 10000 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using Microsoft.AspNetCore.Mvc.ApplicationParts;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Playwright;
|
||||
using Shouldly;
|
||||
|
||||
namespace Heimdall.E2E.Tests.Smoke;
|
||||
|
||||
/// <summary>
|
||||
/// Quick smoke checks that the E2E host itself is reachable and serves
|
||||
/// the expected routes (used to distinguish host/boot problems from test bugs).
|
||||
/// </summary>
|
||||
public class SmokeTests : E2ETestBase
|
||||
{
|
||||
public SmokeTests(TestCommon.PostgreSqlContainerFixture postgres) : base(postgres) { }
|
||||
|
||||
[Fact]
|
||||
public async Task Healthz_returns_200()
|
||||
{
|
||||
using var http = new HttpClient { BaseAddress = new Uri(BaseUrl) };
|
||||
var resp = await http.GetAsync("/healthz");
|
||||
var body = await resp.Content.ReadAsStringAsync();
|
||||
Console.WriteLine($"[SMOKE] GET /healthz -> {(int)resp.StatusCode} body={body}");
|
||||
resp.StatusCode.ShouldBe(HttpStatusCode.OK);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Root_page_served_by_same_client()
|
||||
{
|
||||
// Diagnostic: confirms whether THIS HttpClient reaches the same server
|
||||
// that Playwright reaches (pages) or something else entirely.
|
||||
using var http = new HttpClient { BaseAddress = new Uri(BaseUrl) };
|
||||
var resp = await http.GetAsync("/login");
|
||||
var body = await resp.Content.ReadAsStringAsync();
|
||||
Console.WriteLine($"[SMOKE] GET /login -> {(int)resp.StatusCode} len={body.Length} starts={body[..Math.Min(60, body.Length)]}");
|
||||
resp.StatusCode.ShouldBe(HttpStatusCode.OK);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Controllers_in_application_parts()
|
||||
{
|
||||
// Diagnostic: do the API controllers exist in the MVC ApplicationParts?
|
||||
// The E2E host serves Razor pages + hubs but NOT /api/* — this tells us
|
||||
// whether AddControllers discovered the controllers at all.
|
||||
using var scope = App.Services.CreateScope();
|
||||
var parts = scope.ServiceProvider
|
||||
.GetRequiredService<Microsoft.AspNetCore.Mvc.ApplicationParts.ApplicationPartManager>();
|
||||
var names = parts.ApplicationParts
|
||||
.Select(p => p.Name)
|
||||
.OrderBy(n => n, StringComparer.Ordinal)
|
||||
.ToList();
|
||||
Console.WriteLine($"[SMOKE] ApplicationParts ({names.Count}): {string.Join(", ", names)}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Blazor_circuit_diagnostics()
|
||||
{
|
||||
// Diagnostic: after loading /login, is the Blazor runtime present and is a
|
||||
// WebSocket circuit established? This tells us how to wait for interactivity.
|
||||
var wsEvents = new List<string>();
|
||||
Page.WebSocket += (_, ws) => wsEvents.Add($"WS url={ws.Url}");
|
||||
Page.Console += (_, msg) =>
|
||||
{
|
||||
if (msg.Text.Contains("blazor", StringComparison.OrdinalIgnoreCase) || msg.Type == "error")
|
||||
wsEvents.Add($"CONSOLE[{msg.Type}] {msg.Text}");
|
||||
};
|
||||
Page.RequestFailed += (_, req) => wsEvents.Add($"REQFAIL {req.Url} {req.Failure}");
|
||||
Page.Request += (_, req) =>
|
||||
{
|
||||
if (req.Url.Contains("_blazor") || req.Url.Contains("_framework"))
|
||||
wsEvents.Add($"REQ {req.Method} {req.Url}");
|
||||
};
|
||||
Page.Response += (_, resp) =>
|
||||
{
|
||||
if (resp.Url.Contains("_blazor") || resp.Url.Contains("_framework"))
|
||||
wsEvents.Add($"RESP {(int)resp.Status} {resp.Url}");
|
||||
};
|
||||
|
||||
await Page.GotoAsync($"{BaseUrl}/login");
|
||||
await Page.WaitForLoadStateAsync(LoadState.NetworkIdle);
|
||||
await Task.Delay(4000);
|
||||
|
||||
var blazorState = await Page.EvaluateAsync<dynamic>("() => ({ hasBlazor: typeof window.Blazor !== 'undefined', hasInternal: !!(window.Blazor && window.Blazor._internal), markers: document.body.innerHTML.match(/<!--Blazor[^>]*-->/g)?.slice(0,3) ?? [], enhanced: document.querySelectorAll('[data-enhanced], form[data-enhance]').length, components: document.querySelectorAll('*[data-blazor]').length })");
|
||||
Console.WriteLine($"[SMOKE] Blazor state: {System.Text.Json.JsonSerializer.Serialize(blazorState)}");
|
||||
Console.WriteLine($"[SMOKE] WS/CONSOLE events: {string.Join(" | ", wsEvents)}");
|
||||
|
||||
// Try an explicit start (diagnostic): if the page has no auto-start markers,
|
||||
// Blazor.start() should still connect the circuit.
|
||||
var startResult = await Page.EvaluateAsync<string>("async () => { try { if (window.Blazor && !window.Blazor._internal) { await window.Blazor.start(); return 'started'; } return window.Blazor && window.Blazor._internal ? 'already-internal' : 'no-blazor'; } catch (e) { return 'error: ' + e.message; } }");
|
||||
Console.WriteLine($"[SMOKE] Manual Blazor.start() -> {startResult}");
|
||||
await Task.Delay(3000);
|
||||
Console.WriteLine($"[SMOKE] WS/CONSOLE events after start: {string.Join(" | ", wsEvents)}");
|
||||
|
||||
using var http = new HttpClient { BaseAddress = new Uri(BaseUrl) };
|
||||
var blazorJs = await http.GetAsync("/_framework/blazor.web.js");
|
||||
Console.WriteLine($"[SMOKE] GET /_framework/blazor.web.js -> {(int)blazorJs.StatusCode}");
|
||||
|
||||
var inputCount = await Page.Locator("input[autocomplete='email']").CountAsync();
|
||||
Console.WriteLine($"[SMOKE] email inputs: {inputCount}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_api_returns_401_for_bad_credentials()
|
||||
{
|
||||
using var http = new HttpClient { BaseAddress = new Uri(BaseUrl) };
|
||||
var resp = await http.PostAsJsonAsync("/api/auth/login", new { email = "bad@heimdall.test", password = "WrongPass123!" });
|
||||
resp.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_api_returns_200_for_admin()
|
||||
{
|
||||
using var http = new HttpClient { BaseAddress = new Uri(BaseUrl) };
|
||||
var resp = await http.PostAsJsonAsync("/api/auth/login", new { email = AdminEmail, password = AdminPassword });
|
||||
resp.StatusCode.ShouldBe(HttpStatusCode.OK);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Users_api_returns_401_without_token()
|
||||
{
|
||||
using var http = new HttpClient { BaseAddress = new Uri(BaseUrl) };
|
||||
var resp = await http.GetAsync("/api/users");
|
||||
resp.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"$schema": "https://xunit.net/schema/current/xunit.runner.schema.json",
|
||||
"parallelizeAssembly": false,
|
||||
"parallelizeTestCollections": false,
|
||||
"maxParallelThreads": 1
|
||||
}
|
||||
@@ -66,8 +66,7 @@ public class AgentsControllerTests : PostgresTestBase
|
||||
var apiKey = agentContent.GetProperty("apiKey").GetString()!;
|
||||
|
||||
var heartbeatClient = Factory.CreateClient();
|
||||
heartbeatClient.DefaultRequestHeaders.Authorization =
|
||||
new AuthenticationHeaderValue("Bearer", apiKey);
|
||||
heartbeatClient.DefaultRequestHeaders.Add("X-API-Key", apiKey);
|
||||
var heartbeatResponse = await heartbeatClient.PostAsJsonAsync(
|
||||
$"api/agents/{agentId}/heartbeat", new { publicIp = "1.2.3.4" });
|
||||
heartbeatResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
|
||||
|
||||
@@ -61,7 +61,7 @@ public class AuthControllerTests : PostgresTestBase
|
||||
{
|
||||
key = "auth.public-registration.enabled",
|
||||
value = "true",
|
||||
valueType = "boolean",
|
||||
valueType = "bool",
|
||||
category = "Auth",
|
||||
description = "Enable public registration"
|
||||
})
|
||||
|
||||
@@ -170,7 +170,7 @@ public class AuthFlowTests : IAsyncLifetime
|
||||
{
|
||||
key = "auth.admin-registration.enabled",
|
||||
value = "true",
|
||||
valueType = "boolean",
|
||||
valueType = "bool",
|
||||
category = "Auth",
|
||||
description = "Enable admin registration via API"
|
||||
});
|
||||
|
||||
@@ -66,11 +66,15 @@ public class SettingsControllerTests : PostgresTestBase
|
||||
return client;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Bootstrap an admin token: the first registered user becomes Admin
|
||||
/// automatically. (register-admin itself requires an existing admin token.)
|
||||
/// </summary>
|
||||
private async Task<string> RegisterAdminAsync()
|
||||
{
|
||||
var email = $"admin-{Guid.NewGuid()}@heimdall.test";
|
||||
var client = Factory.CreateClient();
|
||||
var response = await client.PostAsJsonAsync("api/auth/register-admin", new
|
||||
var response = await client.PostAsJsonAsync("api/auth/register", new
|
||||
{
|
||||
email,
|
||||
password = "AdminPwd123!",
|
||||
@@ -110,7 +114,7 @@ public class SettingsControllerTests : PostgresTestBase
|
||||
|
||||
// First registration is auto-admin (no prior users in the DB)
|
||||
var adminEmail = $"seed-admin-{Guid.NewGuid()}@heimdall.test";
|
||||
var regResponse = await client.PostAsJsonAsync("api/auth/register-admin", new
|
||||
var regResponse = await client.PostAsJsonAsync("api/auth/register", new
|
||||
{
|
||||
email = adminEmail,
|
||||
password = "AdminPwd123!",
|
||||
@@ -126,7 +130,7 @@ public class SettingsControllerTests : PostgresTestBase
|
||||
{
|
||||
key = "auth.public-registration.enabled",
|
||||
value = "true",
|
||||
valueType = "boolean",
|
||||
valueType = "bool",
|
||||
category = "Auth"
|
||||
});
|
||||
|
||||
|
||||
@@ -50,11 +50,11 @@ public static class TestHelpers
|
||||
|
||||
private static async Task EnableSetting(HttpClient client, string key, string value)
|
||||
{
|
||||
var response = await client.PostAsJsonAsync("api/settings", new { key, value, valueType = "boolean", category = "Auth", description = key });
|
||||
var response = await client.PostAsJsonAsync("api/settings", new { key, value, valueType = "bool", category = "Auth", description = key });
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
// La setting existe peut-être déjà — essayer PUT
|
||||
response = await client.PutAsJsonAsync($"api/settings/{key}", new { value, valueType = "boolean" });
|
||||
response = await client.PutAsJsonAsync($"api/settings/{key}", new { value, valueType = "bool" });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,11 @@ using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using Heimdall.Web.Services;
|
||||
using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.JSInterop;
|
||||
using NSubstitute;
|
||||
|
||||
namespace Heimdall.Web.Tests.Services;
|
||||
@@ -19,12 +23,15 @@ public sealed class TokenRefreshHandlerTests : IDisposable
|
||||
{
|
||||
_innerHandler = new MockInnerHandler();
|
||||
_authState = new AuthState();
|
||||
var authStateProvider = Substitute.For<HeimdallAuthStateProvider>(null!, _authState);
|
||||
var authStateProvider = Substitute.For<HeimdallAuthStateProvider>(
|
||||
new ProtectedSessionStorage(Substitute.For<IJSRuntime>(), Substitute.For<IDataProtectionProvider>()),
|
||||
_authState,
|
||||
Substitute.For<IHttpContextAccessor>());
|
||||
|
||||
var config = Substitute.For<IConfiguration>();
|
||||
config.GetValue<string>("ApiBaseUrl").Returns("http://localhost:8080");
|
||||
|
||||
_handler = new TokenRefreshHandler(_authState, authStateProvider, config);
|
||||
_handler = new TokenRefreshHandler(_authState, authStateProvider, Substitute.For<IHttpContextAccessor>(), config);
|
||||
|
||||
var pipeline = _innerHandler.CreatePipeline(_handler);
|
||||
_httpClient = new HttpClient(pipeline) { BaseAddress = new Uri("http://localhost:8080/") };
|
||||
|
||||
Reference in new issue
Block a user