Files
Arnaud Dartois a4503e76ac fix(ci): répare 31 tests cassés — 401 API, login prerender off, culture bUnit
Trois régressions distinctes cassent la CI depuis le run 207 :

1. Auth API (29 tests d'intégration) : depuis 16d739e, les contrôleurs
   acceptent JwtBearer+Cookies ; le challenge par défaut étant le cookie,
   les requêtes API non authentifiées étaient redirigées 302 vers /login
   au lieu de répondre 401/403 (le client de test suivait → 200 OK).
   → IsApiRequest() dans OnRedirectToLogin/OnRedirectToAccessDenied :
     requête /api/* ou Accept: application/json → 401/403 direct.

2. Get_LoginPage_ReturnsOk : depuis db703be (prerender:false), /login sert
   le shell Blazor sans le contenu du composant en SSR. Le test vérifie
   désormais le shell (_framework/blazor.web.js) au lieu de 'Se connecter'.

3. Tests bUnit (2) : le runner CI a une locale fr-FR → {Confidence:P0}
   rend '87 %' au lieu de '87%'. MudTestBase force en-US (statique +
   thread courant) pour un rendu déterministe partout.

Vérifié : 1042/1042 tests verts, y compris sous LANG=fr_FR.UTF-8.
2026-08-11 12:35:45 +02:00

238 lines
9.1 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");
// Prerender is disabled (InteractiveServerRenderMode prerender:false),
// so the static shell is served and the Login component content only
// appears after the SignalR circuit connects. Assert the Blazor shell.
body.ShouldContain("_framework/blazor.web.js");
}
/* ─── 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();
}
}