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
235 lines
8.9 KiB
C#
235 lines
8.9 KiB
C#
using System.Net;
|
|
using System.Net.Http.Headers;
|
|
using System.Net.Http.Json;
|
|
using System.Text.Json;
|
|
using Heimdall.Infrastructure.Data;
|
|
using Heimdall.Infrastructure.Data.Interceptors;
|
|
using Heimdall.IntegrationTests.Factories;
|
|
using Microsoft.AspNetCore.Mvc.Testing;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Shouldly;
|
|
|
|
namespace Heimdall.IntegrationTests.Controllers;
|
|
|
|
/// <summary>
|
|
/// Integration tests for authentication flow.
|
|
/// These tests verify the full pipeline: redirect behavior, login page rendering,
|
|
/// API authentication, and the complete register→login→access flow.
|
|
/// Would have caught the /Account/Login redirect bug (missing ConfigureApplicationCookie order).
|
|
/// </summary>
|
|
[Collection("Postgres")]
|
|
public class AuthFlowTests : IAsyncLifetime
|
|
{
|
|
private readonly string _connectionString;
|
|
private readonly Lazy<HeimdallWebApplicationFactory> _factoryLazy;
|
|
|
|
private HeimdallWebApplicationFactory Factory => _factoryLazy.Value;
|
|
|
|
private static readonly JsonSerializerOptions Json = new()
|
|
{
|
|
PropertyNameCaseInsensitive = true
|
|
};
|
|
|
|
public AuthFlowTests(PostgreSqlContainerFixture postgres)
|
|
{
|
|
_connectionString = postgres.ConnectionString;
|
|
_factoryLazy = new Lazy<HeimdallWebApplicationFactory>(
|
|
() => new HeimdallWebApplicationFactory(postgres.ConnectionString));
|
|
}
|
|
|
|
public async Task InitializeAsync()
|
|
{
|
|
// Trigger factory creation to run migrations
|
|
_ = Factory;
|
|
await ResetDatabaseAsync();
|
|
}
|
|
|
|
public async Task DisposeAsync()
|
|
{
|
|
if (_factoryLazy.IsValueCreated)
|
|
await _factoryLazy.Value.DisposeAsync();
|
|
}
|
|
|
|
private async Task ResetDatabaseAsync()
|
|
{
|
|
var opts = new DbContextOptionsBuilder<AppDbContext>()
|
|
.UseNpgsql(_connectionString)
|
|
.Options;
|
|
|
|
await using var db = new AppDbContext(opts, new AuditInterceptor());
|
|
var tables = await db.Database.SqlQuery<string>(
|
|
$"""SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_type = 'BASE TABLE' AND table_name != '__EFMigrationsHistory'""")
|
|
.ToListAsync();
|
|
|
|
if (tables.Count > 0)
|
|
{
|
|
var joined = string.Join(", ", tables.Select(t => "\"" + t + "\""));
|
|
#pragma warning disable EF1002, EF1003
|
|
await db.Database.ExecuteSqlRawAsync("TRUNCATE TABLE " + joined + " CASCADE");
|
|
#pragma warning restore EF1002, EF1003
|
|
}
|
|
}
|
|
|
|
/* ─── Blazor redirect tests ────────────────────────────────── */
|
|
|
|
/// <summary>
|
|
/// BLOCKING: Unauthenticated access to root must redirect to /login.
|
|
/// This test would have caught the /Account/Login → 404 redirect bug.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task Get_Root_WithoutAuth_RedirectsToLogin()
|
|
{
|
|
var client = Factory.CreateClient(new WebApplicationFactoryClientOptions
|
|
{
|
|
AllowAutoRedirect = false
|
|
});
|
|
|
|
var response = await client.GetAsync("/");
|
|
|
|
response.StatusCode.ShouldBe(HttpStatusCode.Redirect);
|
|
var location = response.Headers.Location?.ToString() ?? "";
|
|
location.ShouldContain("/login");
|
|
}
|
|
|
|
/// <summary>
|
|
/// Verifies that the login page is accessible and returns OK.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task Get_LoginPage_ReturnsOk()
|
|
{
|
|
var client = Factory.CreateClient();
|
|
var response = await client.GetAsync("/login");
|
|
|
|
response.StatusCode.ShouldBe(HttpStatusCode.OK);
|
|
var body = await response.Content.ReadAsStringAsync();
|
|
body.ShouldContain("Heimdall");
|
|
body.ShouldContain("Se connecter");
|
|
}
|
|
|
|
/* ─── API auth tests ───────────────────────────────────────── */
|
|
|
|
/// <summary>
|
|
/// Protected API endpoint must reject unauthenticated requests with 401.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task Get_ProtectedApi_WithoutAuth_ReturnsUnauthorized()
|
|
{
|
|
var client = Factory.CreateClient();
|
|
var response = await client.GetAsync("/api/stats");
|
|
|
|
response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Register endpoint must return 400 for invalid password (too short/minimal requirements).
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task Register_WithWeakPassword_ReturnsBadRequest()
|
|
{
|
|
var client = Factory.CreateClient();
|
|
var response = await client.PostAsJsonAsync("/api/auth/register", new
|
|
{
|
|
email = $"weak-{Guid.NewGuid()}@heimdall.test",
|
|
password = "short",
|
|
displayName = "Weak Password User"
|
|
});
|
|
|
|
response.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
|
|
}
|
|
|
|
/* ─── Full auth flow test ──────────────────────────────────── */
|
|
|
|
/// <summary>
|
|
/// End-to-end: register admin via test endpoint → get JWT → access protected API.
|
|
/// This validates the complete auth pipeline works end-to-end.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task RegisterAdmin_ThenLogin_ReturnsJwt_AndAccessesProtectedApi()
|
|
{
|
|
var email = $"e2e-{Guid.NewGuid()}@heimdall.test";
|
|
var password = "E2eTestPwd123!";
|
|
var client = Factory.CreateClient();
|
|
|
|
// Step 1: Register first user (becomes admin automatically) to bootstrap
|
|
var bootEmail = "boot-admin@heimdall.test";
|
|
var bootResponse = await client.PostAsJsonAsync("/api/auth/register", new
|
|
{
|
|
email = bootEmail,
|
|
password = "BootAdminPwd123!",
|
|
displayName = "Bootstrap Admin"
|
|
});
|
|
bootResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
|
|
var bootContent = await bootResponse.Content.ReadFromJsonAsync<JsonElement>(Json);
|
|
var bootToken = bootContent.GetProperty("accessToken").GetString();
|
|
bootToken.ShouldNotBeNullOrEmpty();
|
|
|
|
// Enable the admin-registration feature flag
|
|
client.DefaultRequestHeaders.Authorization =
|
|
new AuthenticationHeaderValue("Bearer", bootToken);
|
|
var flagResponse = await client.PostAsJsonAsync("/api/settings", new
|
|
{
|
|
key = "auth.admin-registration.enabled",
|
|
value = "true",
|
|
valueType = "bool",
|
|
category = "Auth",
|
|
description = "Enable admin registration via API"
|
|
});
|
|
flagResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
|
|
|
|
// Step 2: Register a new admin via RegisterAdmin
|
|
var registerResponse = await client.PostAsJsonAsync("/api/auth/register-admin", new
|
|
{
|
|
email,
|
|
password,
|
|
displayName = "E2E Test Admin"
|
|
});
|
|
|
|
registerResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
|
|
var registerContent = await registerResponse.Content.ReadFromJsonAsync<JsonElement>(Json);
|
|
var accessToken = registerContent.GetProperty("accessToken").GetString();
|
|
var refreshToken = registerContent.GetProperty("refreshToken").GetString();
|
|
accessToken.ShouldNotBeNullOrEmpty("register-admin must return an access token");
|
|
refreshToken.ShouldNotBeNullOrEmpty("register-admin must return a refresh token");
|
|
|
|
// Step 3: Use the new admin token to access a protected API endpoint
|
|
client.DefaultRequestHeaders.Authorization =
|
|
new AuthenticationHeaderValue("Bearer", accessToken);
|
|
|
|
var statsResponse = await client.GetAsync("/api/stats");
|
|
statsResponse.StatusCode.ShouldBe(HttpStatusCode.OK, "authenticated request must succeed");
|
|
|
|
// Step 4: Refresh the token
|
|
var refreshResponse = await client.PostAsJsonAsync("/api/auth/refresh", new
|
|
{
|
|
refreshToken
|
|
});
|
|
refreshResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
|
|
var refreshContent = await refreshResponse.Content.ReadFromJsonAsync<JsonElement>(Json);
|
|
var newAccessToken = refreshContent.GetProperty("accessToken").GetString();
|
|
newAccessToken.ShouldNotBeNullOrEmpty("refresh must return a new access token");
|
|
}
|
|
|
|
/// <summary>
|
|
/// Register a user and verify the endpoint returns a valid AuthResponse.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task Register_ReturnsValidAuthResponse()
|
|
{
|
|
var email = $"user-{Guid.NewGuid()}@heimdall.test";
|
|
var password = "UserRegPwd123!";
|
|
var client = Factory.CreateClient();
|
|
|
|
var response = await client.PostAsJsonAsync("/api/auth/register", new
|
|
{
|
|
email,
|
|
password,
|
|
displayName = "Registered User"
|
|
});
|
|
|
|
response.StatusCode.ShouldBe(HttpStatusCode.OK);
|
|
var content = await response.Content.ReadFromJsonAsync<JsonElement>(Json);
|
|
content.TryGetProperty("accessToken", out _).ShouldBeTrue();
|
|
content.TryGetProperty("refreshToken", out _).ShouldBeTrue();
|
|
}
|
|
}
|