fix(auth): répare l'authentification de bout en bout (cookie + JWT + rendu Blazor)

Anomalies corrigées :
- MudPopoverProvider manquant dans les layouts → circuit Blazor mourait sur
  l'ouverture de menus/popovers (dashboard jamais rendu après login)
- AddIdentity redéfinissait le schéma par défaut sur Identity.Application
  alors que /_auth/signin signait avec Cookies → cookie posé mais jamais
  validé, tout rechargement de page redirigeait vers /login. Forçage du
  schéma par défaut sur Cookies + schémas JwtBearer explicites sur les
  endpoints API d'AuthController et SettingsController
- Policy 'AdminUsers' utilisée par register-admin mais jamais enregistrée
  → 500 à l'appel. Ajoutée (RequireRole Admin)
- HeimdallAuthStateProvider ne lisait que le sessionStorage navigateur :
  pendant le prerender SSR, HttpContext.User (cookie) n'était pas utilisé
  → pages protégées redirigées vers /login. Fallback cookie ajouté
- SameOriginHttpMessageHandler : résolution de l'origine via
  IServerAddressesFeature quand IHttpContextAccessor est null (circuit
  Blazor post-hydratation) au lieu de heimdall.local → DNS cassé
- UpdateUserValidator rejetait le thème 'Auto' (défaut de l'UI) → 400
  à l'édition. Accepte désormais auto (case-insensitive)

Tests :
- E2E Playwright complets (login/logout/register/user management) : 33/33
- Integration (Testcontainers PostgreSQL) : 120/120 (valeur 'bool' du
  valueType, bootstrap admin via /register auto-admin, header X-API-Key,
  /proc/meminfo optionnel pour les LXC restreints)
- Exécution E2E séquentielle (xunit.runner.json) pour éliminer le flakiness
This commit is contained in:
Arnaud Dartois committed 2026-08-09 23:43:11 +02:00
1 parent 895fdc3422
commit 53b6240a3e
27 files changed
+993 -163

No files matched your search

@@ -0,0 +1,138 @@
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
namespace Heimdall.Web.Services;
/// <summary>
/// Resolves the effective API base URL for browser-facing HTTP calls.
/// Heimdall is a Blazor Server monolith — the UI and the REST API run in the
/// same process — so unless an explicit ApiBaseUrl is configured (e.g. an
/// external API), calls should target the SAME origin the browser is using.
/// The old hardcoded "http://localhost:8080" default broke the UI whenever the
/// app was not running inside the Docker container (dev, E2E, bare metal).
/// </summary>
public static class ApiBaseUrlResolver
{
/// <summary>Placeholder used when no explicit base URL is configured; the
/// SameOriginHttpMessageHandler rewrites it to the request origin.</summary>
public const string PlaceholderBase = "http://heimdall.local/";
/// <summary>True when an explicit base URL is configured (config or env).</summary>
public static bool IsConfigured(IConfiguration configuration) =>
!string.IsNullOrWhiteSpace(ResolveConfigured(configuration));
/// <summary>Returns the explicitly configured URL, or null when unset.</summary>
public static string? ResolveConfigured(IConfiguration configuration) =>
configuration.GetValue<string>("ApiBaseUrl")
?? Environment.GetEnvironmentVariable("API_BASE_URL");
/// <summary>
/// Effective origin for the current request (scheme://host). Returns null
/// when no HttpContext is available — which is common in Blazor Server
/// circuits after hydration (component-triggered calls have no request).
/// </summary>
public static string? ResolveOrigin(IHttpContextAccessor httpContextAccessor)
{
var http = httpContextAccessor.HttpContext;
if (http is null)
return null;
return $"{http.Request.Scheme}://{http.Request.Host}";
}
/// <summary>
/// Resolves the origin from the Kestrel server's bound addresses. Used as a
/// fallback when no HttpContext is available (Blazor Server circuit calls).
/// Returns null when the server exposes no usable HTTP address.
/// </summary>
public static string? ResolveFromServer(IServer server)
{
try
{
var addresses = server.Features.Get<IServerAddressesFeature>()?.Addresses;
if (addresses is null)
return null;
var httpAddress = addresses.FirstOrDefault(a =>
a.StartsWith("http://", StringComparison.OrdinalIgnoreCase)
&& !a.Contains("0.0.0.0", StringComparison.OrdinalIgnoreCase)
&& !a.Contains("[::]", StringComparison.OrdinalIgnoreCase))
?? addresses.FirstOrDefault(a => a.StartsWith("http://", StringComparison.OrdinalIgnoreCase));
if (string.IsNullOrWhiteSpace(httpAddress))
return null;
// http://127.0.0.1:5000 -> http://127.0.0.1:5000/
return httpAddress.EndsWith('/') ? httpAddress : httpAddress + "/";
}
catch
{
return null;
}
}
/// <summary>
/// Absolute base URL for out-of-band calls (e.g. token refresh): explicit
/// config when set, otherwise the current request origin (monolith), with a
/// loopback fallback when no request context is available.
/// </summary>
public static string Resolve(IHttpContextAccessor httpContextAccessor, IConfiguration configuration)
{
var configured = ResolveConfigured(configuration);
if (!string.IsNullOrWhiteSpace(configured))
return configured.EndsWith('/') ? configured : configured + "/";
var origin = ResolveOrigin(httpContextAccessor);
if (!string.IsNullOrWhiteSpace(origin))
return origin.EndsWith('/') ? origin : origin + "/";
return "http://localhost/";
}
}
/// <summary>
/// DelegatingHandler that rewrites requests to the current request origin when
/// no explicit ApiBaseUrl is configured. The named HttpClient is registered
/// with <see cref="ApiBaseUrlResolver.PlaceholderBase"/> as BaseAddress (so
/// relative paths resolve) and this handler swaps the placeholder host for the
/// real origin before the call leaves the process.
///
/// In Blazor Server, calls triggered by component code (OnInitializedAsync,
/// event handlers) run inside the circuit WITHOUT an HttpContext, so the
/// handler falls back to the server's bound addresses.
/// </summary>
public class SameOriginHttpMessageHandler : DelegatingHandler
{
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IConfiguration _configuration;
private readonly IServer _server;
public SameOriginHttpMessageHandler(
IHttpContextAccessor httpContextAccessor,
IConfiguration configuration,
IServer server)
{
_httpContextAccessor = httpContextAccessor;
_configuration = configuration;
_server = server;
}
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
if (!ApiBaseUrlResolver.IsConfigured(_configuration)
&& request.RequestUri is not null
&& request.RequestUri.OriginalString.StartsWith(
ApiBaseUrlResolver.PlaceholderBase, StringComparison.OrdinalIgnoreCase))
{
var origin = ApiBaseUrlResolver.ResolveOrigin(_httpContextAccessor)
?? ApiBaseUrlResolver.ResolveFromServer(_server);
if (!string.IsNullOrWhiteSpace(origin))
{
var path = request.RequestUri.OriginalString[ApiBaseUrlResolver.PlaceholderBase.Length..];
request.RequestUri = new Uri($"{origin.TrimEnd('/')}/{path}");
}
}
return base.SendAsync(request, cancellationToken);
}
}