From 53b6240a3ecb1e812ef8c168fbf4bfec56a3567e Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sun, 9 Aug 2026 23:43:11 +0200 Subject: [PATCH] =?UTF-8?q?fix(auth):=20r=C3=A9pare=20l'authentification?= =?UTF-8?q?=20de=20bout=20en=20bout=20(cookie=20+=20JWT=20+=20rendu=20Blaz?= =?UTF-8?q?or)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- Heimdall.slnx | 1 + .../Validators/UpdateUserValidator.cs | 4 +- .../DependencyInjection.cs | 11 +- src/Heimdall.Web/Components/App.razor | 2 +- .../Components/Layout/MainLayout.razor | 1 + .../Components/Layout/MudBlazorLayout.razor | 1 + .../Controllers/AuthController.cs | 10 +- .../Controllers/SettingsController.cs | 2 +- src/Heimdall.Web/Program.cs | 308 +++++++++++------- src/Heimdall.Web/Services/AuthState.cs | 28 ++ .../Services/HeimdallAuthStateProvider.cs | 36 +- .../Services/SameOriginHttpMessageHandler.cs | 138 ++++++++ .../Services/TokenRefreshHandler.cs | 11 +- src/Heimdall.Web/appsettings.json | 3 - .../SystemMetricsProviderTests.cs | 5 +- tests/Heimdall.E2E.Tests/E2ETestBase.cs | 119 ++++++- .../Heimdall.E2E.Tests.csproj | 5 + .../Heimdall.E2E.Tests/Pages/AuthFlowTests.cs | 153 +++++++++ .../Pages/UserManagementTests.cs | 154 +++++++++ tests/Heimdall.E2E.Tests/SmokeTests.cs | 126 +++++++ tests/Heimdall.E2E.Tests/xunit.runner.json | 6 + .../Controllers/AgentsControllerTests.cs | 3 +- .../Controllers/AuthControllerTests.cs | 2 +- .../Controllers/AuthFlowTests.cs | 2 +- .../Controllers/SettingsControllerTests.cs | 10 +- .../Controllers/TestHelpers.cs | 4 +- .../Services/TokenRefreshHandlerTests.cs | 11 +- 27 files changed, 993 insertions(+), 163 deletions(-) create mode 100644 src/Heimdall.Web/Services/SameOriginHttpMessageHandler.cs create mode 100644 tests/Heimdall.E2E.Tests/Pages/AuthFlowTests.cs create mode 100644 tests/Heimdall.E2E.Tests/Pages/UserManagementTests.cs create mode 100644 tests/Heimdall.E2E.Tests/SmokeTests.cs create mode 100644 tests/Heimdall.E2E.Tests/xunit.runner.json diff --git a/Heimdall.slnx b/Heimdall.slnx index 9b1e549..bef2c7d 100644 --- a/Heimdall.slnx +++ b/Heimdall.slnx @@ -14,6 +14,7 @@ + diff --git a/src/Heimdall.Application/Validators/UpdateUserValidator.cs b/src/Heimdall.Application/Validators/UpdateUserValidator.cs index 08e4432..5981e81 100644 --- a/src/Heimdall.Application/Validators/UpdateUserValidator.cs +++ b/src/Heimdall.Application/Validators/UpdateUserValidator.cs @@ -10,7 +10,7 @@ public class UpdateUserValidator : AbstractValidator 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'")); } } diff --git a/src/Heimdall.Infrastructure/DependencyInjection.cs b/src/Heimdall.Infrastructure/DependencyInjection.cs index facb76c..5a7ee2a 100644 --- a/src/Heimdall.Infrastructure/DependencyInjection.cs +++ b/src/Heimdall.Infrastructure/DependencyInjection.cs @@ -37,7 +37,8 @@ public static class DependencyInjection npgsql.MigrationsHistoryTable("__EFMigrationsHistory", "public"))); services.AddDbContextFactory(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(sp => sp.GetRequiredService()); @@ -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("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"); diff --git a/src/Heimdall.Web/Components/App.razor b/src/Heimdall.Web/Components/App.razor index b34ffff..7e9b377 100644 --- a/src/Heimdall.Web/Components/App.razor +++ b/src/Heimdall.Web/Components/App.razor @@ -18,7 +18,7 @@ - +
diff --git a/src/Heimdall.Web/Components/Layout/MainLayout.razor b/src/Heimdall.Web/Components/Layout/MainLayout.razor index 0822abb..5a52423 100644 --- a/src/Heimdall.Web/Components/Layout/MainLayout.razor +++ b/src/Heimdall.Web/Components/Layout/MainLayout.razor @@ -5,6 +5,7 @@ @inject IJSRuntime JsRuntime + diff --git a/src/Heimdall.Web/Components/Layout/MudBlazorLayout.razor b/src/Heimdall.Web/Components/Layout/MudBlazorLayout.razor index f22e477..4239326 100644 --- a/src/Heimdall.Web/Components/Layout/MudBlazorLayout.razor +++ b/src/Heimdall.Web/Components/Layout/MudBlazorLayout.razor @@ -1,6 +1,7 @@ @inherits LayoutComponentBase + diff --git a/src/Heimdall.Web/Controllers/AuthController.cs b/src/Heimdall.Web/Controllers/AuthController.cs index 7823008..c4f233a 100644 --- a/src/Heimdall.Web/Controllers/AuthController.cs +++ b/src/Heimdall.Web/Controllers/AuthController.cs @@ -120,7 +120,7 @@ public class AuthController : ControllerBase } /// Change the current user's password. - [Authorize] + [Authorize(AuthenticationSchemes = "JwtBearer")] [HttpPost("change-password")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] @@ -150,7 +150,7 @@ public class AuthController : ControllerBase } /// Register an admin user. Requires Admin role + feature flag auth.admin-registration.enabled. - [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 } /// Enable 2FA for the current user. Returns the shared key and QR code URI for setup. - [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 } /// Disable 2FA for the current user. - [Authorize] + [Authorize(AuthenticationSchemes = "JwtBearer")] [HttpPost("2fa/disable")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] @@ -281,7 +281,7 @@ public class AuthController : ControllerBase } /// Logout — revoke the current refresh token. - [Authorize] + [Authorize(AuthenticationSchemes = "JwtBearer")] [HttpPost("logout")] [ProducesResponseType(StatusCodes.Status200OK)] public async Task Logout([FromBody] LogoutRequest request, CancellationToken ct) diff --git a/src/Heimdall.Web/Controllers/SettingsController.cs b/src/Heimdall.Web/Controllers/SettingsController.cs index bf36583..4da0759 100644 --- a/src/Heimdall.Web/Controllers/SettingsController.cs +++ b/src/Heimdall.Web/Controllers/SettingsController.cs @@ -21,7 +21,7 @@ namespace Heimdall.Api.Controllers; [ApiController] [Route("api/settings")] -[Authorize] +[Authorize(AuthenticationSchemes = "JwtBearer")] [EnableRateLimiting("Api")] public class SettingsController : ControllerBase { diff --git a/src/Heimdall.Web/Program.cs b/src/Heimdall.Web/Program.cs index 5d1b4b9..f70b335 100644 --- a/src/Heimdall.Web/Program.cs +++ b/src/Heimdall.Web/Program.cs @@ -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("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>(); - var db = scope.ServiceProvider.GetRequiredService(); - 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>(); - var userManager = seedScope.ServiceProvider - .GetRequiredService>(); - - 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(); - 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("Seed:DemoOnStartup", false)) - { - var adminLogin = builder.Configuration.GetValue("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("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; } + /// + /// Applies pending EF migrations with retry/backoff. Shared between the + /// normal entry point and test hosts (E2E) so both boot paths behave identically. + /// + 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>(); + var db = scope.ServiceProvider.GetRequiredService(); + 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; + } + } + } + } + + /// + /// Seeds Identity roles, default groups and (optionally) the demo admin + demo site. + /// Idempotent — safe to call on every startup and from test hosts. + /// + public static async Task SeedAsync(WebApplication app, IConfiguration configuration) + { + using var seedScope = app.Services.CreateScope(); + var roleManager = seedScope.ServiceProvider + .GetRequiredService>(); + var userManager = seedScope.ServiceProvider + .GetRequiredService>(); + + 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(); + 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("Seed:DemoOnStartup", false)) + { + var adminLogin = configuration.GetValue("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("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()); + options.Filters.Add()) + // 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(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(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(); builder.Services.AddTransient(); - var apiBaseUrl = builder.Configuration.GetValue("ApiBaseUrl") - ?? Environment.GetEnvironmentVariable("API_BASE_URL") - ?? "http://localhost:8080"; + builder.Services.AddTransient(); + 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(); + }) + .AddHttpMessageHandler() + .AddHttpMessageHandler(); + if (apiBaseUrlConfigured) + Console.WriteLine($"[DIAG] ApiBaseUrl: {apiBaseUrl} (explicit)"); + else + Console.WriteLine("[DIAG] ApiBaseUrl: same-origin (no explicit config)"); builder.Services.AddScoped(); } @@ -488,6 +556,18 @@ public partial class Program { app.MapHub("/hubs/notifications"); app.MapHub("/hubs/admin"); + // Diagnostic: log all mapped endpoints so E2E host mapping issues are visible. + if (app.Environment.IsEnvironment("Testing")) + { + var dataSource = app.Services.GetRequiredService(); + 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(); diff --git a/src/Heimdall.Web/Services/AuthState.cs b/src/Heimdall.Web/Services/AuthState.cs index fed548f..0feb287 100644 --- a/src/Heimdall.Web/Services/AuthState.cs +++ b/src/Heimdall.Web/Services/AuthState.cs @@ -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(); } + /// + /// 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. + /// + 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; diff --git a/src/Heimdall.Web/Services/HeimdallAuthStateProvider.cs b/src/Heimdall.Web/Services/HeimdallAuthStateProvider.cs index a29d4d3..86dcc2e 100644 --- a/src/Heimdall.Web/Services/HeimdallAuthStateProvider.cs +++ b/src/Heimdall.Web/Services/HeimdallAuthStateProvider.cs @@ -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 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(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) diff --git a/src/Heimdall.Web/Services/SameOriginHttpMessageHandler.cs b/src/Heimdall.Web/Services/SameOriginHttpMessageHandler.cs new file mode 100644 index 0000000..0bca067 --- /dev/null +++ b/src/Heimdall.Web/Services/SameOriginHttpMessageHandler.cs @@ -0,0 +1,138 @@ +using Microsoft.AspNetCore.Hosting.Server; +using Microsoft.AspNetCore.Hosting.Server.Features; + +namespace Heimdall.Web.Services; + +/// +/// 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). +/// +public static class ApiBaseUrlResolver +{ + /// Placeholder used when no explicit base URL is configured; the + /// SameOriginHttpMessageHandler rewrites it to the request origin. + public const string PlaceholderBase = "http://heimdall.local/"; + + /// True when an explicit base URL is configured (config or env). + public static bool IsConfigured(IConfiguration configuration) => + !string.IsNullOrWhiteSpace(ResolveConfigured(configuration)); + + /// Returns the explicitly configured URL, or null when unset. + public static string? ResolveConfigured(IConfiguration configuration) => + configuration.GetValue("ApiBaseUrl") + ?? Environment.GetEnvironmentVariable("API_BASE_URL"); + + /// + /// 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). + /// + public static string? ResolveOrigin(IHttpContextAccessor httpContextAccessor) + { + var http = httpContextAccessor.HttpContext; + if (http is null) + return null; + return $"{http.Request.Scheme}://{http.Request.Host}"; + } + + /// + /// 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. + /// + public static string? ResolveFromServer(IServer server) + { + try + { + var addresses = server.Features.Get()?.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; + } + } + + /// + /// 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. + /// + 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/"; + } +} + +/// +/// DelegatingHandler that rewrites requests to the current request origin when +/// no explicit ApiBaseUrl is configured. The named HttpClient is registered +/// with 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. +/// +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 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); + } +} diff --git a/src/Heimdall.Web/Services/TokenRefreshHandler.cs b/src/Heimdall.Web/Services/TokenRefreshHandler.cs index 793cbc6..2c9b1f8 100644 --- a/src/Heimdall.Web/Services/TokenRefreshHandler.cs +++ b/src/Heimdall.Web/Services/TokenRefreshHandler.cs @@ -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("ApiBaseUrl") - ?? Environment.GetEnvironmentVariable("API_BASE_URL") - ?? "http://localhost:8080"; + _httpContextAccessor = httpContextAccessor; + _configuration = configuration; } protected override async Task 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", diff --git a/src/Heimdall.Web/appsettings.json b/src/Heimdall.Web/appsettings.json index b66115f..b260b45 100644 --- a/src/Heimdall.Web/appsettings.json +++ b/src/Heimdall.Web/appsettings.json @@ -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": "" } diff --git a/tests/Heimdall.Agent.Tests/SystemMetricsProviderTests.cs b/tests/Heimdall.Agent.Tests/SystemMetricsProviderTests.cs index ac6b2dd..2ce1951 100644 --- a/tests/Heimdall.Agent.Tests/SystemMetricsProviderTests.cs +++ b/tests/Heimdall.Agent.Tests/SystemMetricsProviderTests.cs @@ -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(); } diff --git a/tests/Heimdall.E2E.Tests/E2ETestBase.cs b/tests/Heimdall.E2E.Tests/E2ETestBase.cs index a405fc0..415ede2 100644 --- a/tests/Heimdall.E2E.Tests/E2ETestBase.cs +++ b/tests/Heimdall.E2E.Tests/E2ETestBase.cs @@ -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"); + + /// Seeded admin account (see Seed:AdminLogin/Seed:AdminPassword in-memory config). + protected const string AdminEmail = "admin@heimdall.test"; + protected const string AdminPassword = "AdminDev123!"; + + /// + /// 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. + /// + 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)); + } + + /// + /// Navigates to a page and waits for the Blazor circuit so forms are interactive. + /// + 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); + } + + /// + /// Logs in through the real Blazor UI. Navigates to /login, fills the form, + /// submits, and waits for the redirect to the dashboard. + /// + 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 }); + } + + /// + /// 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). + /// + protected async Task 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(); + 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("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(); + 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 { diff --git a/tests/Heimdall.E2E.Tests/Heimdall.E2E.Tests.csproj b/tests/Heimdall.E2E.Tests/Heimdall.E2E.Tests.csproj index b9c058d..c0c6208 100644 --- a/tests/Heimdall.E2E.Tests/Heimdall.E2E.Tests.csproj +++ b/tests/Heimdall.E2E.Tests/Heimdall.E2E.Tests.csproj @@ -13,10 +13,15 @@ + + + + + diff --git a/tests/Heimdall.E2E.Tests/Pages/AuthFlowTests.cs b/tests/Heimdall.E2E.Tests/Pages/AuthFlowTests.cs new file mode 100644 index 0000000..005865e --- /dev/null +++ b/tests/Heimdall.E2E.Tests/Pages/AuthFlowTests.cs @@ -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; + +/// +/// 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). +/// +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"); + } +} diff --git a/tests/Heimdall.E2E.Tests/Pages/UserManagementTests.cs b/tests/Heimdall.E2E.Tests/Pages/UserManagementTests.cs new file mode 100644 index 0000000..6bb210f --- /dev/null +++ b/tests/Heimdall.E2E.Tests/Pages/UserManagementTests.cs @@ -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; + +/// +/// User-management tests driven through the real Blazor UI (/users): +/// list, create, edit roles, lock/unlock, reset password — as the seeded admin. +/// +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 }); + } +} diff --git a/tests/Heimdall.E2E.Tests/SmokeTests.cs b/tests/Heimdall.E2E.Tests/SmokeTests.cs new file mode 100644 index 0000000..7fe1f6c --- /dev/null +++ b/tests/Heimdall.E2E.Tests/SmokeTests.cs @@ -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; + +/// +/// Quick smoke checks that the E2E host itself is reachable and serves +/// the expected routes (used to distinguish host/boot problems from test bugs). +/// +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(); + 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(); + 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("() => ({ hasBlazor: typeof window.Blazor !== 'undefined', hasInternal: !!(window.Blazor && window.Blazor._internal), markers: document.body.innerHTML.match(//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("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); + } +} diff --git a/tests/Heimdall.E2E.Tests/xunit.runner.json b/tests/Heimdall.E2E.Tests/xunit.runner.json new file mode 100644 index 0000000..c315589 --- /dev/null +++ b/tests/Heimdall.E2E.Tests/xunit.runner.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://xunit.net/schema/current/xunit.runner.schema.json", + "parallelizeAssembly": false, + "parallelizeTestCollections": false, + "maxParallelThreads": 1 +} diff --git a/tests/Heimdall.IntegrationTests/Controllers/AgentsControllerTests.cs b/tests/Heimdall.IntegrationTests/Controllers/AgentsControllerTests.cs index 90510d1..3ae28a9 100644 --- a/tests/Heimdall.IntegrationTests/Controllers/AgentsControllerTests.cs +++ b/tests/Heimdall.IntegrationTests/Controllers/AgentsControllerTests.cs @@ -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); diff --git a/tests/Heimdall.IntegrationTests/Controllers/AuthControllerTests.cs b/tests/Heimdall.IntegrationTests/Controllers/AuthControllerTests.cs index 491ba9c..d291b3f 100644 --- a/tests/Heimdall.IntegrationTests/Controllers/AuthControllerTests.cs +++ b/tests/Heimdall.IntegrationTests/Controllers/AuthControllerTests.cs @@ -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" }) diff --git a/tests/Heimdall.IntegrationTests/Controllers/AuthFlowTests.cs b/tests/Heimdall.IntegrationTests/Controllers/AuthFlowTests.cs index ac133cd..82b6fd0 100644 --- a/tests/Heimdall.IntegrationTests/Controllers/AuthFlowTests.cs +++ b/tests/Heimdall.IntegrationTests/Controllers/AuthFlowTests.cs @@ -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" }); diff --git a/tests/Heimdall.IntegrationTests/Controllers/SettingsControllerTests.cs b/tests/Heimdall.IntegrationTests/Controllers/SettingsControllerTests.cs index c099da0..08d1fb8 100644 --- a/tests/Heimdall.IntegrationTests/Controllers/SettingsControllerTests.cs +++ b/tests/Heimdall.IntegrationTests/Controllers/SettingsControllerTests.cs @@ -66,11 +66,15 @@ public class SettingsControllerTests : PostgresTestBase return client; } + /// + /// Bootstrap an admin token: the first registered user becomes Admin + /// automatically. (register-admin itself requires an existing admin token.) + /// private async Task 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" }); diff --git a/tests/Heimdall.IntegrationTests/Controllers/TestHelpers.cs b/tests/Heimdall.IntegrationTests/Controllers/TestHelpers.cs index 043278e..5acb60f 100644 --- a/tests/Heimdall.IntegrationTests/Controllers/TestHelpers.cs +++ b/tests/Heimdall.IntegrationTests/Controllers/TestHelpers.cs @@ -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" }); } } } diff --git a/tests/Heimdall.Web.Tests/Services/TokenRefreshHandlerTests.cs b/tests/Heimdall.Web.Tests/Services/TokenRefreshHandlerTests.cs index 215d4b9..7a52e83 100644 --- a/tests/Heimdall.Web.Tests/Services/TokenRefreshHandlerTests.cs +++ b/tests/Heimdall.Web.Tests/Services/TokenRefreshHandlerTests.cs @@ -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(null!, _authState); + var authStateProvider = Substitute.For( + new ProtectedSessionStorage(Substitute.For(), Substitute.For()), + _authState, + Substitute.For()); var config = Substitute.For(); config.GetValue("ApiBaseUrl").Returns("http://localhost:8080"); - _handler = new TokenRefreshHandler(_authState, authStateProvider, config); + _handler = new TokenRefreshHandler(_authState, authStateProvider, Substitute.For(), config); var pipeline = _innerHandler.CreatePipeline(_handler); _httpClient = new HttpClient(pipeline) { BaseAddress = new Uri("http://localhost:8080/") };