From f632fee7d8fc3390590a13632e18cf1541219ed2 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Fri, 6 Nov 2026 21:04:42 +0100 Subject: [PATCH] fix(auth): streamline cookie session validation (#232) --- skills/heimdall-identity/SKILL.md | 2 ++ src/Heimdall.Web/Program.cs | 4 ++-- .../Controllers/AuthSessionSecurityTests.cs | 3 +++ 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/skills/heimdall-identity/SKILL.md b/skills/heimdall-identity/SKILL.md index 651b202..d644e54 100644 --- a/skills/heimdall-identity/SKILL.md +++ b/skills/heimdall-identity/SKILL.md @@ -14,6 +14,7 @@ Read `AGENTS.md`, the focused Gitea issue and [the Gitea ticket workflow](../git - Keep bootstrap one-time and PostgreSQL-serializable. Anonymous registration stays disabled after bootstrap; role and account creation failures must not be reported as success. - Keep public login/reset responses generic so they do not reveal account existence, lockout state, or Identity policy details. Logs must not contain emails, passwords, tokens, authenticator keys, recovery codes, or Identity error descriptions; log safe error codes only when needed. - Rotate `SecurityStamp` after password changes/resets, email or role changes, lock/unlock, and 2FA changes. Verify existing cookies, JWTs, and refresh tokens are rejected after the change. +- Cookie principal validation runs on every authenticated HTTP request. Keep it asynchronous and use `AccountSessionPolicy.IsValidLiveAsync` with `IIdentityAccountService.GetSessionRecordAsync` plus an `IApplicationDbContext` projection; this bypasses Identity's tracked-user cache and avoids repeated `UserManager` database round trips while preserving fresh security-stamp, lockout, and email-confirmation checks. Do not replace it with claims-only validation. - Enroll an authenticator in two steps: create/show the setup key while 2FA remains disabled; renew the user's access token and cookie after Identity rotates the security stamp; verify a TOTP code before enabling 2FA and creating one-time recovery codes. Persist only hashes of recovery codes, redeem each atomically once, and clear them when 2FA is disabled. - Check every `IdentityResult` before proceeding. Avoid partial account creation; clean up the created user if role assignment fails. - Keep first-account provisioning on `/setup` → `/api/auth/bootstrap-admin`; later accounts and role assignment use `/users` → `/api/users`. Do not reintroduce a second Admin-registration endpoint. @@ -23,6 +24,7 @@ Read `AGENTS.md`, the focused Gitea issue and [the Gitea ticket workflow](../git - Configure Identity options explicitly and review changes to password, unique email, confirmed email, lockout, cookie, token-provider, and Data Protection behavior. - CI installs Chromium through the Playwright CLI already copied beside the Release E2E test assembly (`node tests/Heimdall.E2E.Tests/bin/Release/net10.0/.playwright/package/cli.js install --with-deps chromium`). This keeps browser tooling on the test project's locked Playwright dependency graph and avoids an independently restored C# script project. - Keep PostgreSQL-specific transaction and concurrency guarantees in Infrastructure. Use relational integration tests for bootstrap races, recovery-code redemption, session revocation, and migration compatibility. +- For cookie session validation changes, prove a freshly issued cookie succeeds before account mutation and fails afterward for lockout, role/security-stamp, email, and password changes. Treat GlitchTip blocking warnings as hypotheses: inspect the full async stack and do not claim a synchronous block solely from the warning title. - For behavior changes, update FR/EN resources and UI/API contracts, add focused tests, update the Gitea issue, and run the disposable Compose acceptance recipe with unique credentials, ports, volumes, project name, and network. - Acceptance must exercise bootstrap through the setup UI, user lifecycle and role editing through `/users`, permission editing through `/admin/claims`, and verify the resulting JWT/API allow and deny decisions. Check that stale sessions fail after a role/permission change and that the last usable Admin cannot be demoted, deleted, or locked. - Record a project-unique tag for each source-built Central acceptance image and install an EXIT cleanup trap before build/start. After scoped Compose teardown, verify zero containers/volumes/networks and remove/verify absence of each exact local tag even on failure. Keep shared upstream base images, preserve test exit status, report cleanup failures, and avoid `--rmi all` or broad image-prune commands. diff --git a/src/Heimdall.Web/Program.cs b/src/Heimdall.Web/Program.cs index 3da4448..82037bd 100644 --- a/src/Heimdall.Web/Program.cs +++ b/src/Heimdall.Web/Program.cs @@ -691,9 +691,9 @@ public partial class Program } private static Task ValidateAccountSessionAsync(ClaimsPrincipal principal, HttpContext http) => - Heimdall.Application.Auth.Services.AccountSessionPolicy.IsValidAsync(principal, + Heimdall.Application.Auth.Services.AccountSessionPolicy.IsValidLiveAsync(principal, http.RequestServices.GetRequiredService(), - http.RequestServices.GetRequiredService(), http.RequestAborted); + http.RequestServices.GetRequiredService(), http.RequestAborted); private static void ConfigureJwtBearerAuthentication(AuthenticationBuilder authBuilder, string jwtKey, string jwtIssuer, string jwtAudience) { diff --git a/tests/Heimdall.IntegrationTests/Controllers/AuthSessionSecurityTests.cs b/tests/Heimdall.IntegrationTests/Controllers/AuthSessionSecurityTests.cs index 45e2598..87fcd1e 100644 --- a/tests/Heimdall.IntegrationTests/Controllers/AuthSessionSecurityTests.cs +++ b/tests/Heimdall.IntegrationTests/Controllers/AuthSessionSecurityTests.cs @@ -91,6 +91,9 @@ public sealed class AuthSessionSecurityTests(PostgreSqlContainerFixture postgres 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();