Files
arnaud.dartois 1d60f04691
Heimdall Gitea / Detect CI scope (push) Successful in 33s
Heimdall Gitea / Build and tests (push) Successful in 26m42s
Heimdall Gitea / Publish versioned release (push) Skipped
Heimdall Gitea / Build and scan server image (push) Successful in 8m45s
Heimdall Gitea / Build and scan agent image (push) Successful in 9m14s
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Successful in 19m34s
Heimdall Gitea / Publish Docker Hub latest tags (push) Successful in 1m37s
Heimdall Gitea / CI policy (push) Successful in 2s
fix(auth): safely report cookie sign-in failures (#310)
## Résumé
Le flux navigateur reçoit maintenant un résultat HTTP explicite du pont cookie; les échecs de cookie sont diagnostiqués sans exposer les messages d’exception ni les données de session. La validation 2FA par code de récupération recharge également l’utilisateur après rotation du security stamp avant d’émettre la session.

## Issue
Refs #304 — l’observation GlitchTip post-déploiement reste nécessaire avant résolution.

## Travail effectué
- `/_auth/signin` renvoie des erreurs génériques et journalise uniquement l’étape et le type d’exception.
- Le pont JavaScript retourne le statut HTTP; les interruptions de circuit sont distinctes des réponses non-2xx.
- Suppression des adresses e-mail des journaux auth/2FA.
- Correction du chemin code de récupération 2FA pour émettre un jeton cohérent avec le security stamp actualisé.
- Ajout de tests unitaires et d’intégration; documentation dans `skills/heimdall-identity/SKILL.md`.

## Preuves
- `dotnet restore tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj --locked-mode` — réussi.
- `dotnet restore tests/Heimdall.IntegrationTests/Heimdall.IntegrationTests.csproj --locked-mode` — réussi.
- `AuthHelperTests` — 6/6 réussis.
- Tests d’intégration ciblés 2FA/recovery-cookie/TOTP-cookie/token malformé — 3/3 réussis.
- Acceptance Compose source-built `heimdall-auth-cookie-20261108170745-28547` — bootstrap 200, TOTP 200, cookie sign-in 200, API avec cookie 200, jeton malformé 401 générique, secrets absents des logs. Nettoyage vérifié: conteneurs/volumes/réseau absents et tag `heimdall:heimdall-auth-cookie-20261108170745-28547-central` supprimé.
- Analyse de l’événement GlitchTip: le circuit navigateur se déconnecte avant toute trace HTTP observée de `/_auth/signin`; la cause de cette occurrence production reste donc non démontrée. La correction améliore la visibilité sûre et le flux synthétique, sans prétendre reproduire cet événement.

## À suivre
Après déploiement de ce commit, observer GlitchTip pendant au moins sept jours et vérifier si HEIMDALL-DU réapparaît. Ne pas résoudre l’issue avant cette preuve réelle.

Reviewed-on: #310
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-08 20:03:03 +01:00

217 lines
11 KiB
C#

using System.Buffers.Binary;
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Security.Cryptography;
using Heimdall.Application.Auth.Services;
using Heimdall.Application.DTOs;
using Heimdall.Application.Users.Commands.AssignRoles;
using Heimdall.Application.Users.Commands.LockUser;
using Heimdall.Domain.Entities;
using Heimdall.Infrastructure.Data;
using Heimdall.IntegrationTests.Factories;
using MediatR;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Shouldly;
using Heimdall.Infrastructure.Identity;
namespace Heimdall.IntegrationTests.Controllers;
[Collection("Postgres")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1001:Types that own disposable fields should be disposable", Justification = "xUnit invokes IAsyncLifetime.DisposeAsync to dispose the client and application factory.")]
public sealed class AuthSessionSecurityTests(PostgreSqlContainerFixture postgres) : IAsyncLifetime
{
private HeimdallWebApplicationFactory _factory = null!;
private HttpClient _client = null!;
private readonly string _email = $"auth-{Guid.NewGuid():N}@example.test";
private Guid _userId;
private const string Password = "Correct-password-123!";
public async Task InitializeAsync()
{
_factory = new HeimdallWebApplicationFactory(postgres.ConnectionString);
_client = _factory.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false, HandleCookies = false });
using var scope = _factory.Services.CreateScope();
var users = scope.ServiceProvider.GetRequiredService<UserManager<IdentityAppUser>>();
var user = new IdentityAppUser { Id = Guid.NewGuid(), Email = _email, UserName = _email, EmailConfirmed = true };
(await users.CreateAsync(user, Password)).Succeeded.ShouldBeTrue();
(await users.AddToRoleAsync(user, "Viewer")).Succeeded.ShouldBeTrue();
_userId = user.Id;
}
public async Task DisposeAsync()
{
_client.Dispose();
await _factory.DisposeAsync();
}
private async Task<AuthResponse> LoginAsync()
{
var response = await _client.PostAsJsonAsync("/api/auth/login", new { email = _email, password = Password });
response.StatusCode.ShouldBe(HttpStatusCode.OK);
response.Headers.Contains("Set-Cookie").ShouldBeFalse();
return (await response.Content.ReadFromJsonAsync<AuthResponse>())!;
}
[Fact]
public async Task Http_2fa_requires_password_challenge_and_rejects_replay()
{
var code = "ABCDE";
using (var scope = _factory.Services.CreateScope())
{
var users = scope.ServiceProvider.GetRequiredService<UserManager<IdentityAppUser>>();
var user = (await users.FindByIdAsync(_userId.ToString()))!;
await users.ResetAuthenticatorKeyAsync(user);
await users.SetTwoFactorEnabledAsync(user, true);
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
db.UserRecoveryCodes.Add(new UserRecoveryCode(_userId, RecoveryCodeService.Hash(code)));
await db.SaveChangesAsync();
}
var bypass = await _client.PostAsJsonAsync("/api/auth/2fa/verify", new { email = _email, code });
bypass.IsSuccessStatusCode.ShouldBeFalse();
var challenge = await LoginAsync();
challenge.Requires2fa.ShouldBeTrue();
challenge.AccessToken.ShouldBeEmpty();
var response = await _client.PostAsJsonAsync("/api/auth/2fa/verify", new { challengeId = challenge.ChallengeId, code });
response.StatusCode.ShouldBe(HttpStatusCode.OK);
var verifiedSession = (await response.Content.ReadFromJsonAsync<AuthResponse>())!;
verifiedSession.AccessToken.ShouldNotBeNullOrEmpty();
var cookieResponse = await _client.PostAsJsonAsync("/_auth/signin", new { accessToken = verifiedSession.AccessToken });
cookieResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
await AssertCookieSessionAsync(cookieResponse);
var replay = await _client.PostAsJsonAsync("/api/auth/2fa/verify", new { challengeId = challenge.ChallengeId, code });
replay.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
}
[Fact]
public async Task Authenticator_2fa_success_emits_token_accepted_by_cookie_signin()
{
string code;
using (var scope = _factory.Services.CreateScope())
{
var users = scope.ServiceProvider.GetRequiredService<UserManager<IdentityAppUser>>();
var user = (await users.FindByIdAsync(_userId.ToString()))!;
(await users.ResetAuthenticatorKeyAsync(user)).Succeeded.ShouldBeTrue();
(await users.SetTwoFactorEnabledAsync(user, true)).Succeeded.ShouldBeTrue();
var key = await users.GetAuthenticatorKeyAsync(user);
code = GenerateTotp(key!);
(await users.VerifyTwoFactorTokenAsync(user, TokenOptions.DefaultAuthenticatorProvider, code)).ShouldBeTrue();
}
var challenge = await LoginAsync();
challenge.Requires2fa.ShouldBeTrue();
var verification = await _client.PostAsJsonAsync("/api/auth/2fa/verify", new
{
challengeId = challenge.ChallengeId,
code
});
verification.StatusCode.ShouldBe(HttpStatusCode.OK, await verification.Content.ReadAsStringAsync());
var session = (await verification.Content.ReadFromJsonAsync<AuthResponse>())!;
session.AccessToken.ShouldNotBeNullOrEmpty();
var cookieResponse = await _client.PostAsJsonAsync("/_auth/signin", new { accessToken = session.AccessToken });
cookieResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
await AssertCookieSessionAsync(cookieResponse);
}
[Fact]
public async Task Cookie_signin_rejects_malformed_tokens_without_returning_validation_details()
{
var response = await _client.PostAsJsonAsync("/_auth/signin", new { accessToken = "not-a-jwt" });
response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
var body = await response.Content.ReadAsStringAsync();
body.ShouldNotContain("not-a-jwt");
body.ShouldNotContain("IDX");
}
private async Task AssertCookieSessionAsync(HttpResponseMessage cookieResponse)
{
var cookie = cookieResponse.Headers.GetValues("Set-Cookie")
.Single(value => value.StartsWith(".Heimdall.Auth=", StringComparison.Ordinal)).Split(';')[0];
var authenticatedRequest = new HttpRequestMessage(HttpMethod.Get, "/api/users/me");
authenticatedRequest.Headers.Add("Cookie", cookie);
(await _client.SendAsync(authenticatedRequest)).StatusCode.ShouldBe(HttpStatusCode.OK);
}
#pragma warning disable CA5350
private static string GenerateTotp(string base32Key)
{
const string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
var key = new List<byte>();
var buffer = 0;
var bits = 0;
foreach (var character in base32Key.TrimEnd('='))
{
buffer = (buffer << 5) | alphabet.IndexOf(character);
bits += 5;
if (bits < 8) continue;
bits -= 8;
key.Add((byte)(buffer >> bits));
}
Span<byte> message = stackalloc byte[8];
BinaryPrimitives.WriteInt64BigEndian(message, DateTimeOffset.UtcNow.ToUnixTimeSeconds() / 30);
var hash = HMACSHA1.HashData(key.ToArray(), message);
var offset = hash[^1] & 0x0f;
var binary = ((hash[offset] & 0x7f) << 24) | (hash[offset + 1] << 16)
| (hash[offset + 2] << 8) | hash[offset + 3];
return (binary % 1_000_000).ToString("D6", System.Globalization.CultureInfo.InvariantCulture);
}
#pragma warning restore CA5350
[Theory]
[InlineData("lock")]
[InlineData("roles")]
[InlineData("password")]
[InlineData("email")]
public async Task Existing_jwt_cookie_and_refresh_are_revoked_by_account_change(string change)
{
var auth = await LoginAsync();
var signin = await _client.PostAsJsonAsync("/_auth/signin", new { accessToken = auth.AccessToken });
signin.StatusCode.ShouldBe(HttpStatusCode.OK);
var cookie = signin.Headers.GetValues("Set-Cookie").Single(x => x.StartsWith(".Heimdall.Auth=", StringComparison.Ordinal)).Split(';')[0];
var validCookieRequest = new HttpRequestMessage(HttpMethod.Get, "/api/users/me");
validCookieRequest.Headers.Add("Cookie", cookie);
(await _client.SendAsync(validCookieRequest)).StatusCode.ShouldBe(HttpStatusCode.OK);
using (var scope = _factory.Services.CreateScope())
{
var sender = scope.ServiceProvider.GetRequiredService<ISender>();
if (change == "lock") (await sender.Send(new LockUserCommand(_userId))).IsSuccess.ShouldBeTrue();
else if (change == "roles") (await sender.Send(new AssignRolesCommand(_userId, ["Supervisor"]))).IsSuccess.ShouldBeTrue();
else
{
var users = scope.ServiceProvider.GetRequiredService<UserManager<IdentityAppUser>>();
var user = (await users.FindByIdAsync(_userId.ToString()))!;
if (change == "email")
{
var update = await users.SetEmailAsync(user, $"changed-{_email}");
update.Succeeded.ShouldBeTrue();
await users.UpdateSecurityStampAsync(user);
}
else
{
var token = await users.GeneratePasswordResetTokenAsync(user);
var reset = await users.ResetPasswordAsync(user, token, "Changed-password-123!");
reset.Succeeded.ShouldBeTrue();
await users.UpdateSecurityStampAsync(user);
}
}
}
var refresh = await _client.PostAsJsonAsync("/api/auth/refresh", new { refreshToken = auth.RefreshToken });
refresh.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
var bearer = new HttpRequestMessage(HttpMethod.Get, "/api/users/me");
bearer.Headers.Authorization = new AuthenticationHeaderValue("Bearer", auth.AccessToken);
(await _client.SendAsync(bearer)).StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
var withCookie = new HttpRequestMessage(HttpMethod.Get, "/api/users/me");
withCookie.Headers.Add("Cookie", cookie);
(await _client.SendAsync(withCookie)).StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
(await _client.PostAsJsonAsync("/_auth/signin", new { accessToken = auth.AccessToken })).StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
}
}