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
174 lines
5.6 KiB
C#
174 lines
5.6 KiB
C#
using System.Net.Http.Headers;
|
|
using System.Net.Http.Json;
|
|
using Heimdall.IntegrationTests.Factories;
|
|
using Shouldly;
|
|
|
|
namespace Heimdall.IntegrationTests.Controllers;
|
|
|
|
public class AuthControllerTests : PostgresTestBase
|
|
{
|
|
private HttpClient? _client;
|
|
private HttpClient Client => _client ?? throw new InvalidOperationException("Client not initialized");
|
|
private static readonly SemaphoreSlim _seedLock = new(1, 1);
|
|
private static bool _seeded;
|
|
|
|
public AuthControllerTests(PostgreSqlContainerFixture postgres) : base(postgres) { }
|
|
|
|
/// <summary>
|
|
/// Clear static cache and create HTTP client AFTER DB reset.
|
|
/// Creating Factory.CreateClient() before InitializeAsync would start the
|
|
/// server (with role seeding) but then ResetDatabaseAsync() truncates the
|
|
/// seeded roles — causing "Role ADMIN does not exist" on first request.
|
|
/// </summary>
|
|
public override async Task InitializeAsync()
|
|
{
|
|
await base.InitializeAsync();
|
|
_seeded = false;
|
|
_client = Factory.CreateClient();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Seeds the public registration setting so non-first-user registrations work.
|
|
/// Registers the first admin user and creates the AppSetting via the API.
|
|
/// Runs once per test class (factory is shared).
|
|
/// </summary>
|
|
private async Task EnsurePublicRegistrationAsync()
|
|
{
|
|
if (_seeded) return;
|
|
await _seedLock.WaitAsync();
|
|
try
|
|
{
|
|
if (_seeded) return;
|
|
|
|
// First registration is auto-admin (no prior users in the DB)
|
|
var adminEmail = $"admin-{Guid.NewGuid()}@heimdall.test";
|
|
var regResponse = await Client.PostAsJsonAsync("api/auth/register", new
|
|
{
|
|
email = adminEmail,
|
|
password = "TestPassword123!",
|
|
displayName = "Admin"
|
|
});
|
|
regResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
|
|
|
|
// Extract access token from the registration response
|
|
var authResult = await regResponse.Content.ReadFromJsonAsync<AuthTestResponse>();
|
|
authResult.ShouldNotBeNull();
|
|
|
|
// Use admin token to create the public registration setting
|
|
var request = new HttpRequestMessage(HttpMethod.Post, "api/settings")
|
|
{
|
|
Content = JsonContent.Create(new
|
|
{
|
|
key = "auth.public-registration.enabled",
|
|
value = "true",
|
|
valueType = "bool",
|
|
category = "Auth",
|
|
description = "Enable public registration"
|
|
})
|
|
};
|
|
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
|
|
var settingResponse = await Client.SendAsync(request);
|
|
|
|
_seeded = true;
|
|
}
|
|
finally
|
|
{
|
|
_seedLock.Release();
|
|
}
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Register_ValidRequest_ReturnsOk()
|
|
{
|
|
await EnsurePublicRegistrationAsync();
|
|
|
|
var response = await Client.PostAsJsonAsync("api/auth/register", new
|
|
{
|
|
email = $"test-{Guid.NewGuid()}@heimdall.test",
|
|
password = "TestPassword123!",
|
|
displayName = "Test User"
|
|
});
|
|
|
|
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Register_DuplicateEmail_ReturnsConflict()
|
|
{
|
|
await EnsurePublicRegistrationAsync();
|
|
|
|
var email = $"dup-{Guid.NewGuid()}@heimdall.test";
|
|
|
|
var first = await Client.PostAsJsonAsync("api/auth/register", new
|
|
{
|
|
email,
|
|
password = "TestPassword123!",
|
|
displayName = "User 1"
|
|
});
|
|
first.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
|
|
|
|
var second = await Client.PostAsJsonAsync("api/auth/register", new
|
|
{
|
|
email,
|
|
password = "TestPassword123!",
|
|
displayName = "User 2"
|
|
});
|
|
|
|
second.StatusCode.ShouldBe(System.Net.HttpStatusCode.Conflict);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Login_ValidCredentials_ReturnsOk()
|
|
{
|
|
await EnsurePublicRegistrationAsync();
|
|
|
|
var email = $"login-{Guid.NewGuid()}@heimdall.test";
|
|
await Client.PostAsJsonAsync("api/auth/register", new
|
|
{
|
|
email,
|
|
password = "TestPassword123!",
|
|
displayName = "Login User"
|
|
});
|
|
|
|
var response = await Client.PostAsJsonAsync("api/auth/login", new
|
|
{
|
|
email,
|
|
password = "TestPassword123!"
|
|
});
|
|
|
|
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Login_InvalidPassword_ReturnsUnauthorized()
|
|
{
|
|
await EnsurePublicRegistrationAsync();
|
|
|
|
var email = $"badpwd-{Guid.NewGuid()}@heimdall.test";
|
|
await Client.PostAsJsonAsync("api/auth/register", new
|
|
{
|
|
email,
|
|
password = "TestPassword123!",
|
|
displayName = "Bad Pwd User"
|
|
});
|
|
|
|
var response = await Client.PostAsJsonAsync("api/auth/login", new
|
|
{
|
|
email,
|
|
password = "WrongPassword!"
|
|
});
|
|
|
|
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.Unauthorized);
|
|
}
|
|
|
|
/// <summary>DTO matching the API auth response for extracting the access token.</summary>
|
|
private sealed record AuthTestResponse(
|
|
string AccessToken,
|
|
string RefreshToken,
|
|
DateTime ExpiresAt,
|
|
bool Requires2fa,
|
|
UserInfo? User);
|
|
|
|
private sealed record UserInfo(Guid Id, string Email, string DisplayName, IList<string>? Roles);
|
|
}
|