From 78ff15799e3c7b1587e9bb5a7638814be8fc0c90 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Thu, 12 Nov 2026 05:00:00 +0100 Subject: [PATCH] =?UTF-8?q?[Auth]=20Couvrir=20le=20cookie=20navigateur=20a?= =?UTF-8?q?pr=C3=A8s=202FA=20(#330)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Arnaud Dartois --- skills/heimdall-identity/SKILL.md | 3 +- skills/heimdall-identity/acceptance.sh | 94 +++++++++++++----- .../Heimdall.E2E.Tests/Pages/AuthFlowTests.cs | 95 +++++++++++++++++++ 3 files changed, 168 insertions(+), 24 deletions(-) diff --git a/skills/heimdall-identity/SKILL.md b/skills/heimdall-identity/SKILL.md index 846b96d..c2324ea 100644 --- a/skills/heimdall-identity/SKILL.md +++ b/skills/heimdall-identity/SKILL.md @@ -16,6 +16,7 @@ Read `AGENTS.md`, the focused Gitea issue and [the Gitea ticket workflow](../git - 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. - The Blazor cookie bridge runs through `heimdallAuth.signIn` → `POST /_auth/signin`. Have JavaScript return only the HTTP status code (or `0` for a network failure); classify `JSDisconnectedException` separately from non-2xx responses. Log only the failure stage, HTTP status, or exception type—never exception messages, emails, user IDs, access tokens, cookies, or request bodies. Return generic public errors from the endpoint. Integration coverage should verify a successful 2FA response can create a usable cookie and that malformed tokens reveal no validation details. +- For cookie failures reported after 2FA, inspect only sanitized event breadcrumbs around the JS bridge; distinguish a circuit/WebSocket disconnect from a `/_auth/signin` HTTP rejection, and do not infer cookie serialization failure when the event has no exception. Keep a Playwright E2E path that submits an authenticator code through `/login`, observes the real HttpOnly auth cookie, and proves that cookie authorizes `/api/users/me`; remove the temporary Identity account in `finally`. - 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. @@ -29,7 +30,7 @@ Read `AGENTS.md`, the focused Gitea issue and [the Gitea ticket workflow](../git - 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. - For account-creation password regressions, cover the real `/users` dialog for Viewer and Supervisor with the role selected both before and after password entry. Confirm the new account's email through the admin row action, then authenticate through `/api/auth/login` using the exact synthetic password entered in the form; assert only the status/token presence and never log the password. Keep this as a Playwright E2E test under the `E2E` collection. -- The account-creation disposable Compose acceptance must use a unique project, generated PostgreSQL/JWT credentials, a free loopback port, and a project-specific Central image tag. Build from the checkout, wait for `/healthz`, then run the create/confirm/login HTTP API path against that stack; the separate Playwright E2E test covers UI role selection. Teardown only that Compose project and verify its containers, volumes, and network are gone; remove and verify absence of the exact Central tag while retaining PostgreSQL and other shared base images. +- The disposable Compose recipe defaults to the account-creation path; `HEIMDALL_ACCEPTANCE_FLOW=2fa-cookie` runs the complete authenticator challenge → `/_auth/signin` → cookie-authorized `/api/users/me` path. Each invocation uses a unique project, generated PostgreSQL/JWT credentials, a free loopback port, and a project-specific Central image tag. Build from the checkout and wait for `/healthz`; the separate Playwright E2E test covers the real browser UI bridge. Teardown only that Compose project and verify its containers, volumes, and network are gone; remove and verify absence of the exact Central tag while retaining PostgreSQL and other shared base images. - 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. Useful official references: [ASP.NET Core Identity configuration](https://learn.microsoft.com/aspnet/core/security/authentication/identity-configuration), [Two-factor authentication](https://learn.microsoft.com/aspnet/core/security/authentication/identity-enable-qrcodes), and [Data Protection](https://learn.microsoft.com/aspnet/core/security/data-protection/introduction). diff --git a/skills/heimdall-identity/acceptance.sh b/skills/heimdall-identity/acceptance.sh index 95c9c92..653cc7f 100755 --- a/skills/heimdall-identity/acceptance.sh +++ b/skills/heimdall-identity/acceptance.sh @@ -3,7 +3,12 @@ set -Eeuo pipefail repo_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) suffix="$(date -u +%Y%m%d%H%M%S)-$(od -An -N5 -tx1 /dev/urandom | tr -d ' \\n')" -project="heimdall-auth-create-${suffix}" +flow="${HEIMDALL_ACCEPTANCE_FLOW:-create-login}" +if [[ "$flow" != "create-login" && "$flow" != "2fa-cookie" ]]; then + echo 'HEIMDALL_ACCEPTANCE_FLOW must be create-login or 2fa-cookie' >&2 + exit 2 +fi +project="heimdall-auth-${flow}-${suffix}" central_image="heimdall:${project}-central" temp_dir=$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX") env_file="$temp_dir/acceptance.env" @@ -101,34 +106,77 @@ until curl -fsS "$base_url/healthz" >/dev/null 2>&1; do done printf 'Central /healthz: HTTP 200\n' -BASE_URL="$base_url" ACCEPTANCE_ADMIN_PASSWORD="$admin_password" python3 - <<'PY' -import json, os, secrets, urllib.error, urllib.request +BASE_URL="$base_url" ACCEPTANCE_ADMIN_PASSWORD="$admin_password" ACCEPTANCE_FLOW="$flow" python3 - <<'PY' +import base64, hashlib, hmac, json, os, secrets, time, urllib.error, urllib.request base=os.environ['BASE_URL'] -def post(path, body, token=None): +flow=os.environ['ACCEPTANCE_FLOW'] +def request(method, path, body=None, token=None, cookie=None): headers={'Content-Type':'application/json'} if token: headers['Authorization']='Bearer '+token - req=urllib.request.Request(base+path, data=json.dumps(body).encode(), headers=headers, method='POST') + if cookie: headers['Cookie']=cookie + data=json.dumps(body).encode() if body is not None else None + req=urllib.request.Request(base+path, data=data, headers=headers, method=method) try: with urllib.request.urlopen(req, timeout=20) as response: - return response.status, response.read() + return response.status, response.read(), response.headers except urllib.error.HTTPError as error: - return error.code, error.read() -status, _=post('/api/auth/bootstrap-admin', {'email':'acceptance-admin@heimdall.test','password':os.environ['ACCEPTANCE_ADMIN_PASSWORD'],'displayName':'Disposable Acceptance Admin'}) + return error.code, error.read(), error.headers +def post(path, body, token=None): + status, payload, _=request('POST', path, body, token) + return status, payload +def totp(key): + secret=base64.b32decode(key.upper()+'='*((8-len(key)%8)%8)) + counter=int(time.time())//30 + digest=hmac.new(secret, counter.to_bytes(8,'big'), hashlib.sha1).digest() + offset=digest[-1]&15 + value=int.from_bytes(digest[offset:offset+4], 'big')&0x7fffffff + return f'{value%1000000:06d}' +status, bootstrap_payload, _=request('POST','/api/auth/bootstrap-admin', {'email':'acceptance-admin@heimdall.test','password':os.environ['ACCEPTANCE_ADMIN_PASSWORD'],'displayName':'Disposable Acceptance Admin'}) if status != 200: raise SystemExit(f'Admin bootstrap failed: HTTP {status}') -status, payload=post('/api/auth/login', {'email':'acceptance-admin@heimdall.test','password':os.environ['ACCEPTANCE_ADMIN_PASSWORD']}) -if status != 200: - raise SystemExit(f'Admin login failed: HTTP {status}') -admin=json.loads(payload)['accessToken'] -for role in ('Viewer','Supervisor'): - email=f'{role.lower()}-{secrets.token_hex(8)}@heimdall.test' - password='CreateLogin!'+secrets.token_urlsafe(18)+'A1' - status, payload=post('/api/users', {'email':email,'password':password,'displayName':f'Acceptance {role}','roles':[role]}, admin) - if status not in (200,201): raise SystemExit(f'{role} create failed: HTTP {status}') - user_id=json.loads(payload)['id'] - status,_=post(f'/api/users/{user_id}/confirm-email', {}, admin) - if status != 200: raise SystemExit(f'{role} email confirmation failed: HTTP {status}') +if flow == 'create-login': + status, payload=post('/api/auth/login', {'email':'acceptance-admin@heimdall.test','password':os.environ['ACCEPTANCE_ADMIN_PASSWORD']}) + if status != 200: raise SystemExit(f'Admin login failed: HTTP {status}') + admin=json.loads(payload)['accessToken'] + for role in ('Viewer','Supervisor'): + email=f'{role.lower()}-{secrets.token_hex(8)}@heimdall.test' + password='CreateLogin!'+secrets.token_urlsafe(18)+'A1' + status, payload=post('/api/users', {'email':email,'password':password,'displayName':f'Acceptance {role}','roles':[role]}, admin) + if status not in (200,201): raise SystemExit(f'{role} create failed: HTTP {status}') + user_id=json.loads(payload)['id'] + status,_=post(f'/api/users/{user_id}/confirm-email', {}, admin) + if status != 200: raise SystemExit(f'{role} email confirmation failed: HTTP {status}') + status,payload=post('/api/auth/login', {'email':email,'password':password}) + if status != 200: raise SystemExit(f'{role} first login failed: HTTP {status}') + if not json.loads(payload).get('accessToken'): raise SystemExit(f'{role} login returned no access token') + print(f'{role}: create, admin email confirmation, and first login passed (HTTP 200)') +else: + admin=json.loads(bootstrap_payload)['accessToken'] + email='acceptance-admin@heimdall.test' + password=os.environ['ACCEPTANCE_ADMIN_PASSWORD'] + status,payload=post('/api/auth/2fa/enable', {'currentPassword':password}, admin) + if status != 200: raise SystemExit(f'2FA enrollment initialization failed: HTTP {status}') + shared_key=json.loads(payload)['sharedKey'] + # ResetAuthenticatorKey rotates the security stamp; renew the setup session + # before the authenticated confirmation call. status,payload=post('/api/auth/login', {'email':email,'password':password}) - if status != 200: raise SystemExit(f'{role} first login failed: HTTP {status}') - if not json.loads(payload).get('accessToken'): raise SystemExit(f'{role} login returned no access token') - print(f'{role}: create, admin email confirmation, and first login passed (HTTP 200)') + if status != 200: raise SystemExit(f'2FA setup session renewal failed: HTTP {status}') + admin=json.loads(payload)['accessToken'] + status,_=post('/api/auth/2fa/enable/confirm', {'code':totp(shared_key)}, admin) + if status != 200: raise SystemExit(f'2FA enrollment confirmation failed: HTTP {status}') + status,payload=post('/api/auth/login', {'email':email,'password':password}) + if status != 200: raise SystemExit(f'2FA password challenge failed: HTTP {status}') + challenge=json.loads(payload) + if not challenge.get('requires2fa') or not challenge.get('challengeId'): + raise SystemExit('2FA login did not return an authenticator challenge') + status,payload=post('/api/auth/2fa/verify', {'challengeId':challenge['challengeId'],'code':totp(shared_key)}) + if status != 200: raise SystemExit(f'2FA verification failed: HTTP {status}') + access_token=json.loads(payload)['accessToken'] + status,_,headers=request('POST','/_auth/signin', {'accessToken':access_token}) + if status != 200: raise SystemExit(f'2FA cookie sign-in failed: HTTP {status}') + set_cookie=headers.get('Set-Cookie','').split(';',1)[0] + if not set_cookie.startswith('.Heimdall.Auth='): + raise SystemExit('2FA cookie sign-in returned no auth cookie') + status,_,_=request('GET','/api/users/me',cookie=set_cookie) + if status != 200: raise SystemExit(f'2FA auth cookie did not authorize current-user endpoint: HTTP {status}') + print('2FA authenticator challenge, cookie issuance, and cookie-authenticated /api/users/me passed (HTTP 200)') PY diff --git a/tests/Heimdall.E2E.Tests/Pages/AuthFlowTests.cs b/tests/Heimdall.E2E.Tests/Pages/AuthFlowTests.cs index f21a7ce..c3c7637 100644 --- a/tests/Heimdall.E2E.Tests/Pages/AuthFlowTests.cs +++ b/tests/Heimdall.E2E.Tests/Pages/AuthFlowTests.cs @@ -1,4 +1,6 @@ +using System.Buffers.Binary; using System.Net.Http.Json; +using System.Security.Cryptography; using Heimdall.Domain.Entities; using Heimdall.TestCommon; using Microsoft.AspNetCore.Identity; @@ -83,6 +85,73 @@ public class AuthFlowTests : E2ETestBase navCount.ShouldBeGreaterThanOrEqualTo(1); } + [Fact] + public async Task Authenticator_2fa_login_creates_a_usable_browser_cookie() + { + const string password = "BrowserTwoFactorPass123!"; + var email = $"e2e-2fa-{Guid.NewGuid():N}@heimdall.test"; + IdentityAppUser? user = null; + + try + { + using (var scope = App.Services.CreateScope()) + { + var users = scope.ServiceProvider.GetRequiredService>(); + 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(); + (await users.ResetAuthenticatorKeyAsync(user)).Succeeded.ShouldBeTrue(); + (await users.SetTwoFactorEnabledAsync(user, true)).Succeeded.ShouldBeTrue(); + } + + await GotoWithCircuitAsync("/login"); + await Page.FillAsync("input[autocomplete='email']", email); + await Page.FillAsync("input[autocomplete='current-password']", password); + await Page.ClickAsync("button:has-text('Se connecter')"); + var codeInput = Page.Locator("input[autocomplete='one-time-code']"); + await codeInput.WaitForAsync(new() { Timeout = 15000 }); + + string authenticatorKey; + using (var scope = App.Services.CreateScope()) + { + var users = scope.ServiceProvider.GetRequiredService>(); + var storedUser = await users.FindByIdAsync(user!.Id.ToString()); + authenticatorKey = (await users.GetAuthenticatorKeyAsync(storedUser!))!; + } + + await codeInput.FillAsync(GenerateTotp(authenticatorKey)); + await Page.ClickAsync("button:has-text('Vérifier')"); + await Page.WaitForURLAsync("**/dashboard**", new() { Timeout = 20000 }); + await Page.WaitForSelectorAsync("text=Bienvenue", new() { Timeout = 15000 }); + + var cookies = await Page.Context.CookiesAsync([BaseUrl]); + var authCookie = cookies.SingleOrDefault(cookie => cookie.Name == ".Heimdall.Auth"); + authCookie.ShouldNotBeNull(); + + using var authenticated = new HttpClient(); + authenticated.DefaultRequestHeaders.Add("Cookie", $".Heimdall.Auth={authCookie!.Value}"); + var response = await authenticated.GetAsync($"{BaseUrl}/api/users/me"); + response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + } + finally + { + if (user is not null) + { + using var scope = App.Services.CreateScope(); + var users = scope.ServiceProvider.GetRequiredService>(); + var storedUser = await users.FindByIdAsync(user.Id.ToString()); + if (storedUser is not null) + (await users.DeleteAsync(storedUser)).Succeeded.ShouldBeTrue(); + } + } + } + [Fact] public async Task Login_with_wrong_password_shows_error() { @@ -153,4 +222,30 @@ public class AuthFlowTests : E2ETestBase } private sealed record BootstrapStatus(bool SetupRequired); + +#pragma warning disable CA5350 + private static string GenerateTotp(string base32Key) + { + const string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; + var key = new List(); + 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 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 }