Files
Heimdall/tests/Heimdall.E2E.Tests/SmokeTests.cs
T
Arnaud Dartois 53b6240a3e 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
2026-08-09 23:43:11 +02:00

127 lines
6.0 KiB
C#

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);
}
}