fix(auth): streamline cookie session validation #273

Merged
arnaud.dartois merged 1 commits from fix/glitchtip-7424-session-policy into main 2026-11-07 08:35:20 +01:00
3 changed files with 7 additions and 2 deletions

No files matched your search

+2
View File
@@ -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.
+2 -2
View File
@@ -691,9 +691,9 @@ public partial class Program
}
private static Task<bool> ValidateAccountSessionAsync(ClaimsPrincipal principal, HttpContext http) =>
Heimdall.Application.Auth.Services.AccountSessionPolicy.IsValidAsync(principal,
Heimdall.Application.Auth.Services.AccountSessionPolicy.IsValidLiveAsync(principal,
http.RequestServices.GetRequiredService<Heimdall.Application.Services.IIdentityAccountService>(),
http.RequestServices.GetRequiredService<Heimdall.Application.Services.IAuthDataService>(), http.RequestAborted);
http.RequestServices.GetRequiredService<Heimdall.Application.Common.IApplicationDbContext>(), http.RequestAborted);
private static void ConfigureJwtBearerAuthentication(AuthenticationBuilder authBuilder, string jwtKey, string jwtIssuer, string jwtAudience)
{
@@ -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<ISender>();