Merge branch 'oficina-id-slice1' into main
Oficina ID slice 1 part A: Home sign-in, recovery and assertions Discoverable passkeys with generated names, email sign-in with no address at rest, 128-bit recovery codes with atomic replacement and notices, authorize/Continue/assertion to pinned consumers with fresh linking auth, and local-first sign-out. Reviewed by Fable, 2 rounds.
55 files changed,
+4,385
−209
.gitignore+2 −0docs/superpowers/plans/2026-11-13-oficina-id-slice1-home.md+57 −0go.mod+1 −0go.sum+2 −0implementation/oficina-id-slice1-copy.md+54 −0implementation/oficina-id-slice1-mutations.json+951 −0implementation/oficina-id-slice1-validation.md+165 −0internal/home/app.go+18 −8internal/home/assertion_fresh_test.go+7 −3internal/home/assertion_intent.go+3 −0internal/home/credits/notices.json+11 −0internal/home/directory.go+7 −4internal/home/door_copy_test.go+2 −2internal/home/exchange.go+32 −3internal/home/exchange_test.go+24 −2internal/home/id_browser_test.go+187 −0internal/home/id_direct.go+68 −0internal/home/id_exchange_test.go+186 −0internal/home/id_limiter.go+24 −0internal/home/id_passkey.go+418 −0internal/home/id_passkey_test.go+321 −0internal/home/id_recovery.go+416 −0internal/home/id_recovery_test.go+486 −0internal/home/id_review_test.go+352 −0internal/home/id_signout_test.go+86 −0internal/home/identity/migrations/0001_ceremonies.sql+13 −0internal/home/identity/migrations/0002_recovery.sql+14 −0internal/home/identity/migrations/0003_direct.sql+5 −0internal/home/keymail_fresh_test.go+4 −9internal/home/models.go+14 −0internal/home/operator_ceremony_test.go+2 −2internal/home/operator_http_test.go+5 −1internal/home/passkey.go+38 −55internal/home/passkey_test.go+14 −14internal/home/render.go+3 −0internal/home/runtime.go+3 −1internal/home/security.go+1 −1internal/home/shared_chrome_test.go+1 −1internal/home/signin.go+10 −12internal/home/signin_return_factor_test.go+1 −1internal/home/signin_test.go+15 −15internal/home/signout.go+23 −38internal/home/signout_test.go+64 −18internal/home/static/passkey.js+32 −10internal/home/team_add_test.go+9 −1internal/home/team_page_test.go+4 −1internal/home/templates/directory_signed_out.html+12 −4internal/home/templates/id_continue.html+7 −0internal/home/templates/id_replace.html+10 −0internal/home/templates/id_replaced.html+10 −0internal/home/templates/id_signed_out.html+6 −0internal/home/templates/passkey_enrol.html+1 −2internal/home/templates/signin.html+5 −0internal/home/testapp_test.go+1 −1scripts/check-id-mutations.py+178 −0
CI passed — run details
diff --git a/.gitignore b/.gitignore| index 0975d7c..c1aa599 100644 |
| --- a/.gitignore |
| +++ b/.gitignore |
| @@ -19,3 +19,5 @@ |
| writing/ |
| /releases/ |
| + |
| +.claude/HANDOFF.md |
diff --git a/docs/superpowers/plans/2026-11-13-oficina-id-slice1-home.md b/docs/superpowers/plans/2026-11-13-oficina-id-slice1-home.md| new file mode 100644 |
| index 0000000..8e07292 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-11-13-oficina-id-slice1-home.md |
| @@ -0,0 +1,57 @@ |
| +# Oficina ID slice 1, part A |
| + |
| +Paul approved implementation on 2026-11-13. Work stays on `oficina-id-slice1`; |
| +no deployment or merge. Equipo and changes to its connect adapter are part B. |
| + |
| +## Tasks |
| + |
| +1. [x] Require a new authentication gesture for `max_age=300`; add a protected, |
| + fixed-label Continue page for existing sessions. Files: `exchange.go`, |
| + `signin.go`, `app.go`, templates, assertion tests. Preserve the closed |
| + consumer manifest and 120-second P-256 assertions. |
| +2. [x] Add browser-bound, five-minute, single-use direct passkey sign-in and |
| + enrollment. Require UV, exact RP/origin, stored person binding and generated |
| + WebAuthn names. Keep gated legacy credentials. Files: new Home ceremony |
| + handlers/migration/tests, `passkey.go`, `static/passkey.js`, templates. |
| +3. [x] Implement 80-bit-or-better recovery codes, persistent atomic account/IP |
| + limits, fresh mailbox/browser proof, explicit replacement and atomic |
| + credential/session/code revocation. Keep the notice address only in bounded |
| + memory, with retry and content-free errors. Files: recovery handlers, |
| + migration, ceremony completion, tests. |
| +4. [x] Preserve Keymail/platform SMTP and sealed-link storage; strengthen |
| + hostile error/address scans and note the later blind-auth-store seam. |
| + Make Home sign-out land locally, including directory outage behavior. |
| +5. [x] Run local gates, targeted mutations, delegated copy review and Astra |
| + security review. Push regularly, poll hosted CI, repair failures, and write |
| + `../report.md` in the supplied clone's parent with SHA and remaining work. |
| + |
| +## Test sequence |
| + |
| +Write each behavior test and record its failure before implementation. Exercise |
| +virtual authenticators for direct/gated sign-in, registration, wrong origin/RP, |
| +missing UV, wrong browser/person/purpose, expiry and replay. Test stale and recent |
| +linking sessions, Keymail gesture times and account swaps. Retain assertion |
| +signature/audience/expiry/nonce and scriptless browser-return gates. |
| + |
| +Recovery tests cover entropy, hashed storage, parallel attempts across app |
| +reconstruction, account/IP budgets, code replay, mailbox/browser swaps, expired |
| +proofs, rollback on every replacement write, all-session/code/passkey revocation, |
| +and notice delivery failure/retry without rollback. Scan live SQLite/WAL/SHM, |
| +store objects and logs for canary addresses through all new paths. |
| + |
| +Run `make test`, then relevant browser gates. Record guard-removal mutations and |
| +the tests that kill them in `implementation/oficina-id-slice1-validation.md`. |
| +Existing consumer receipt/link/unlink/admission/pinned-key gates remain part B; |
| +exercise Home's issuance and local outage boundary here. A hanging issuer, not |
| +just a refused connection, must prove directory sign-out lands locally. |
| + |
| +## Integration choices |
| + |
| +Use Home's current `signin.Flow` plus sealed `linkStore`, opaque session subjects, |
| +and Rastrillo's cryptographic WebAuthn/session primitives. Do not adopt readable |
| +`auth_links.address`. Keep the mailbox-completion seam explicit for the later |
| +`blind-auth-store` release. No signing-key publication endpoint. |
| + |
| +Copy is reviewed by delegated Astra pass, per Paul's override; no review server. |
| +Review is source/test-only because Paul forbids deployments. Record that limit |
| +rather than claiming the repo's deployed-canary review requirement was met. |
diff --git a/go.mod b/go.mod| index e4dc4c5..cc02403 100644 |
| --- a/go.mod |
| +++ b/go.mod |
| @@ -43,6 +43,7 @@ require ( |
| github.com/ncruces/go-strftime v1.0.0 // indirect |
| github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect |
| golang.org/x/crypto v0.55.0 // indirect |
| + golang.org/x/net v0.57.0 |
| golang.org/x/text v0.41.0 // indirect |
| gorm.io/gorm v1.31.2 // indirect |
| modernc.org/libc v1.74.1 // indirect |
diff --git a/go.sum b/go.sum| index 22001f4..e106f06 100644 |
| --- a/go.sum |
| +++ b/go.sum |
| @@ -70,6 +70,8 @@ golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M= |
| golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis= |
| golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk= |
| golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40= |
| +golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE= |
| +golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU= |
| golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= |
| golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= |
| golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= |
diff --git a/implementation/oficina-id-slice1-copy.md b/implementation/oficina-id-slice1-copy.md| new file mode 100644 |
| index 0000000..b1203b7 |
| --- /dev/null |
| +++ b/implementation/oficina-id-slice1-copy.md |
| @@ -0,0 +1,54 @@ |
| +# Oficina ID slice 1 copy |
| + |
| +COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13) |
| + |
| +Reviewed by GPT-6 Astra. Fixed labels only; no account-authored text. |
| + |
| +- Sign in with a passkey |
| +- Add a passkey to sign in without entering your email. JavaScript is needed to add and use passkeys. |
| +- Replace passkeys · Oficina |
| +- Replace your passkeys |
| +- Adding a replacement removes all your existing passkeys, signs you out of Oficina ID on every device, and invalidates all your recovery codes. You may remain signed in to the directory and other apps. Sign in with the new passkey before creating new recovery codes. |
| +- Replace all passkeys |
| +- Turn on JavaScript to add your replacement passkey. |
| +- Passkeys replaced · Oficina |
| +- Your passkeys were replaced |
| +- You are signed out of Oficina ID on every device. Your previous passkeys and recovery codes no longer work. You may remain signed in to the directory and other apps. Sign in with your new passkey to create new recovery codes. |
| +- Sign in with your new passkey |
| +- Your Oficina passkeys were replaced |
| +- A replacement passkey was added to your Oficina account. All previous passkeys were removed, all Oficina ID sessions were signed out, and all recovery codes were invalidated. You may remain signed in to the directory and other apps. Sign in with your new passkey to create new recovery codes. |
| +- Your passkeys were replaced, but we could not send the confirmation email. |
| +- Send email again |
| +- Continue to the app · Oficina |
| +- Continue to the app |
| +- Continue |
| +- Signed out · Oficina |
| +- You are signed out |
| +- You are signed out of Oficina ID in this browser. |
| +- Sign in |
| +- That did not work. You can try again. |
| +- That code did not work. |
| + |
| +- The confirmation email can no longer be sent from this page. |
| + |
| +The delegated Astra follow-up accepted the Oficina ID scope clarification. |
| + |
| +## Fable review fixes |
| + |
| +COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13) |
| + |
| +Astra reviewed these exact additions and revisions before implementation: |
| + |
| +- Interim title: Sign out · Oficina |
| +- Interim heading: Finish signing out |
| +- Interim body: You are signed out of the directory. Finish signing out of Oficina ID before leaving this device. |
| +- Button: Sign out of Oficina ID |
| +- Returned-page body: You are signed out of the directory in this browser. |
| +- Recovery notice subject: A recovery code was used for your Oficina account |
| +- Recovery notice body: Someone signed in to your Oficina account using email and a recovery code. If this was not you, sign in with your passkey and generate new recovery codes. This invalidates the previous codes but does not sign out anyone already signed in. |
| + |
| +COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13) |
| + |
| +Generated attribution addition: golang.org/x/net v0.57.0 and its upstream |
| +LICENSE, regenerated with make credits. Astra checked that the license matches |
| +the cached upstream file verbatim. No prose was added to the credits page. |
diff --git a/implementation/oficina-id-slice1-mutations.json b/implementation/oficina-id-slice1-mutations.json| new file mode 100644 |
| index 0000000..61f1d52 |
| --- /dev/null |
| +++ b/implementation/oficina-id-slice1-mutations.json |
| @@ -0,0 +1,951 @@ |
| +[ |
| + { |
| + "guard": "continue gesture", |
| + "file": "internal/home/exchange.go", |
| + "test": "TestIDContinueBeforeMinting", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDContinueBeforeMinting (0.67s)" |
| + ], |
| + "seconds": 4.51 |
| + }, |
| + { |
| + "guard": "link new session", |
| + "file": "internal/home/exchange.go", |
| + "test": "TestIDLinkAlwaysRequiresNewGesture", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDLinkAlwaysRequiresNewGesture (0.56s)" |
| + ], |
| + "seconds": 6.26 |
| + }, |
| + { |
| + "guard": "link transaction start", |
| + "file": "internal/home/exchange.go", |
| + "test": "TestIDLinkRejectsProofBeforeTransactionStart", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDLinkRejectsProofBeforeTransactionStart (0.57s)" |
| + ], |
| + "seconds": 4.49 |
| + }, |
| + { |
| + "guard": "passive Keymail issuance", |
| + "file": "internal/home/exchange.go", |
| + "test": "TestIDLinkRejectsPassiveMintedSession", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDLinkRejectsPassiveMintedSession (0.49s)" |
| + ], |
| + "seconds": 4.45 |
| + }, |
| + { |
| + "guard": "live issuance session", |
| + "file": "internal/home/exchange.go", |
| + "test": "TestIDRevokedCachedSessionCannotMint", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDRevokedCachedSessionCannotMint (0.70s)" |
| + ], |
| + "seconds": 3.88 |
| + }, |
| + { |
| + "guard": "audience", |
| + "file": "internal/home/exchange.go", |
| + "test": "TestHomeDirectoryExchangeAndPrivacy", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestHomeDirectoryExchangeAndPrivacy (0.53s)" |
| + ], |
| + "seconds": 4.59 |
| + }, |
| + { |
| + "guard": "nonce", |
| + "file": "internal/home/exchange.go", |
| + "test": "TestHomeDirectoryExchangeAndPrivacy", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestHomeDirectoryExchangeAndPrivacy (0.62s)" |
| + ], |
| + "seconds": 4.09 |
| + }, |
| + { |
| + "guard": "assertion lifetime", |
| + "file": "internal/home/exchange.go", |
| + "test": "TestHomeDirectoryExchangeAndPrivacy", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestHomeDirectoryExchangeAndPrivacy (0.57s)" |
| + ], |
| + "seconds": 4.73 |
| + }, |
| + { |
| + "guard": "cookie ambiguity", |
| + "file": "internal/home/id_passkey.go", |
| + "test": "TestIDChallengeBrowserCookiesAndExpiry/duplicate", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDChallengeBrowserCookiesAndExpiry (0.30s)", |
| + "--- FAIL: TestIDChallengeBrowserCookiesAndExpiry/duplicate (0.30s)" |
| + ], |
| + "seconds": 5.4 |
| + }, |
| + { |
| + "guard": "clock rollback", |
| + "file": "internal/home/id_passkey.go", |
| + "test": "TestIDChallengeBrowserCookiesAndExpiry/clock", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDChallengeBrowserCookiesAndExpiry (0.36s)", |
| + "--- FAIL: TestIDChallengeBrowserCookiesAndExpiry/clock (0.36s)" |
| + ], |
| + "seconds": 3.93 |
| + }, |
| + { |
| + "guard": "future enrollment time", |
| + "file": "internal/home/id_passkey.go", |
| + "test": "TestIDEnrollmentRejectsFutureAndPassiveAuthentication/future", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDEnrollmentRejectsFutureAndPassiveAuthentication (0.23s)", |
| + "--- FAIL: TestIDEnrollmentRejectsFutureAndPassiveAuthentication/future (0.23s)" |
| + ], |
| + "seconds": 3.81 |
| + }, |
| + { |
| + "guard": "passive enrollment", |
| + "file": "internal/home/id_passkey.go", |
| + "test": "TestIDEnrollmentRejectsFutureAndPassiveAuthentication/passive", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDEnrollmentRejectsFutureAndPassiveAuthentication (0.33s)", |
| + "--- FAIL: TestIDEnrollmentRejectsFutureAndPassiveAuthentication/passive (0.33s)" |
| + ], |
| + "seconds": 3.39 |
| + }, |
| + { |
| + "guard": "challenge capacity", |
| + "file": "internal/home/id_passkey.go", |
| + "test": "TestIDChallengeBrowserCookiesAndExpiry/capacity", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDChallengeBrowserCookiesAndExpiry (0.39s)", |
| + "--- FAIL: TestIDChallengeBrowserCookiesAndExpiry/capacity (0.39s)" |
| + ], |
| + "seconds": 3.58 |
| + }, |
| + { |
| + "guard": "challenge lifetime", |
| + "file": "internal/home/id_passkey.go", |
| + "test": "TestIDGatedChallengeGuards/ttl", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDGatedChallengeGuards (0.29s)", |
| + "--- FAIL: TestIDGatedChallengeGuards/ttl (0.29s)" |
| + ], |
| + "seconds": 2.99 |
| + }, |
| + { |
| + "guard": "challenge browser", |
| + "file": "internal/home/id_passkey.go", |
| + "test": "TestIDGatedChallengeGuards/browser", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDGatedChallengeGuards (0.31s)", |
| + "--- FAIL: TestIDGatedChallengeGuards/browser (0.31s)" |
| + ], |
| + "seconds": 3.77 |
| + }, |
| + { |
| + "guard": "challenge subject", |
| + "file": "internal/home/id_passkey.go", |
| + "test": "TestIDRegistrationChallengeSubjectAndLiveSession/subject", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDRegistrationChallengeSubjectAndLiveSession (0.32s)", |
| + "--- FAIL: TestIDRegistrationChallengeSubjectAndLiveSession/subject (0.32s)" |
| + ], |
| + "seconds": 3.31 |
| + }, |
| + { |
| + "guard": "challenge purpose", |
| + "file": "internal/home/id_passkey.go", |
| + "test": "TestIDGatedChallengeGuards/purpose", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDGatedChallengeGuards (0.38s)", |
| + "--- FAIL: TestIDGatedChallengeGuards/purpose (0.38s)" |
| + ], |
| + "seconds": 3.6 |
| + }, |
| + { |
| + "guard": "challenge expiry", |
| + "file": "internal/home/id_passkey.go", |
| + "test": "TestIDGatedChallengeGuards/expiry", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDGatedChallengeGuards (0.32s)", |
| + "--- FAIL: TestIDGatedChallengeGuards/expiry (0.32s)" |
| + ], |
| + "seconds": 2.99 |
| + }, |
| + { |
| + "guard": "challenge single use", |
| + "file": "internal/home/id_passkey.go", |
| + "test": "TestIDGatedChallengeGuards/single-use", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDGatedChallengeGuards (0.30s)", |
| + "--- FAIL: TestIDGatedChallengeGuards/single-use (0.30s)" |
| + ], |
| + "seconds": 3.2 |
| + }, |
| + { |
| + "guard": "strict ceremony JSON", |
| + "file": "internal/home/id_passkey.go", |
| + "test": "TestIDCeremonyRejectsAmbiguousJSON", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDCeremonyRejectsAmbiguousJSON (0.55s)", |
| + "--- FAIL: TestIDCeremonyRejectsAmbiguousJSON/trailing (0.28s)", |
| + "--- FAIL: TestIDCeremonyRejectsAmbiguousJSON/duplicate (0.26s)" |
| + ], |
| + "seconds": 3.51 |
| + }, |
| + { |
| + "guard": "credential collision", |
| + "file": "internal/home/id_passkey.go", |
| + "test": "TestIDEnrollmentCannotTransferCredential", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDEnrollmentCannotTransferCredential (0.31s)" |
| + ], |
| + "seconds": 2.89 |
| + }, |
| + { |
| + "guard": "credential enrollment bound", |
| + "file": "internal/home/id_passkey.go", |
| + "test": "TestIDEnrollmentBound", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDEnrollmentBound (1.36s)" |
| + ], |
| + "seconds": 4.09 |
| + }, |
| + { |
| + "guard": "credential owner", |
| + "file": "internal/home/id_passkey.go", |
| + "test": "TestIDGateBindsCredentialOwner", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDGateBindsCredentialOwner (0.43s)" |
| + ], |
| + "seconds": 3.18 |
| + }, |
| + { |
| + "guard": "discoverable admission", |
| + "file": "internal/home/id_passkey.go", |
| + "test": "TestIDLegacyCredentialCannotSignInDirectly", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDLegacyCredentialCannotSignInDirectly (0.31s)" |
| + ], |
| + "seconds": 2.98 |
| + }, |
| + { |
| + "guard": "WebAuthn verification", |
| + "file": "internal/home/id_passkey.go", |
| + "test": "TestIDPasskeyRejectsBadProofs/(origin|rp|uv|signature)", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDPasskeyRejectsBadProofs (1.06s)", |
| + "--- FAIL: TestIDPasskeyRejectsBadProofs/origin (0.26s)", |
| + "--- FAIL: TestIDPasskeyRejectsBadProofs/rp (0.26s)", |
| + "--- FAIL: TestIDPasskeyRejectsBadProofs/uv (0.25s)", |
| + "--- FAIL: TestIDPasskeyRejectsBadProofs/signature (0.28s)" |
| + ], |
| + "seconds": 3.86 |
| + }, |
| + { |
| + "guard": "recovery entropy", |
| + "file": "internal/home/id_recovery.go", |
| + "test": "TestIDRecoveryEntropy", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDRecoveryEntropy (0.28s)" |
| + ], |
| + "seconds": 3.01 |
| + }, |
| + { |
| + "guard": "account attempt budget", |
| + "file": "internal/home/id_recovery.go", |
| + "test": "TestIDRecoveryAttemptLimitSurvivesReconstruction", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDRecoveryAttemptLimitSurvivesReconstruction (0.62s)" |
| + ], |
| + "seconds": 3.91 |
| + }, |
| + { |
| + "guard": "IP attempt budget", |
| + "file": "internal/home/id_recovery.go", |
| + "test": "TestIDRecoveryIPLimitAcrossAccounts", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDRecoveryIPLimitAcrossAccounts (1.16s)" |
| + ], |
| + "seconds": 4.51 |
| + }, |
| + { |
| + "guard": "attempt increment", |
| + "file": "internal/home/id_recovery.go", |
| + "test": "TestIDRecoveryAttemptLimitSurvivesReconstruction", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDRecoveryAttemptLimitSurvivesReconstruction (0.50s)" |
| + ], |
| + "seconds": 3.93 |
| + }, |
| + { |
| + "guard": "attempt persistence", |
| + "file": "internal/home/app.go", |
| + "test": "TestIDRecoveryAttemptLimitSurvivesReconstruction", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDRecoveryAttemptLimitSurvivesReconstruction (0.56s)" |
| + ], |
| + "seconds": 4.13 |
| + }, |
| + { |
| + "guard": "mailbox freshness", |
| + "file": "internal/home/id_recovery.go", |
| + "test": "TestIDRecoveryMailboxTimeDefense", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDRecoveryMailboxTimeDefense (0.44s)" |
| + ], |
| + "seconds": 4.02 |
| + }, |
| + { |
| + "guard": "recovery code person", |
| + "file": "internal/home/id_recovery.go", |
| + "test": "TestIDRecoveryCodePersonBindingAndReplay", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDRecoveryCodePersonBindingAndReplay (0.43s)" |
| + ], |
| + "seconds": 3.77 |
| + }, |
| + { |
| + "guard": "recovery code single use", |
| + "file": "internal/home/id_recovery.go", |
| + "test": "TestIDRecoveryCodePersonBindingAndReplay", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDRecoveryCodePersonBindingAndReplay (0.54s)" |
| + ], |
| + "seconds": 3.71 |
| + }, |
| + { |
| + "guard": "recovery proof expiry", |
| + "file": "internal/home/id_recovery.go", |
| + "test": "TestIDReplacementProofBinding/expired", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDReplacementProofBinding (0.39s)", |
| + "--- FAIL: TestIDReplacementProofBinding/expired (0.39s)" |
| + ], |
| + "seconds": 3.53 |
| + }, |
| + { |
| + "guard": "recovery proof subject", |
| + "file": "internal/home/id_recovery.go", |
| + "test": "TestIDReplacementProofBinding/wrong-person", |
| + "result": "survived", |
| + "failures": [], |
| + "seconds": 3.69, |
| + "explanation": "Independent in-memory mailbox subject check still refuses. The paired mutation removes both checks and must fail the same regression." |
| + }, |
| + { |
| + "guard": "recovery proof capacity", |
| + "file": "internal/home/id_recovery.go", |
| + "test": "TestIDRecoveryProofCapacity", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDRecoveryProofCapacity (0.42s)" |
| + ], |
| + "seconds": 3.64 |
| + }, |
| + { |
| + "guard": "mailbox memory capacity", |
| + "file": "internal/home/id_recovery.go", |
| + "test": "TestIDMailboxMemoryBoundAndExpiry", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDMailboxMemoryBoundAndExpiry (0.00s)" |
| + ], |
| + "seconds": 3.16 |
| + }, |
| + { |
| + "guard": "mailbox memory expiry", |
| + "file": "internal/home/id_recovery.go", |
| + "test": "TestIDMailboxMemoryBoundAndExpiry", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDMailboxMemoryBoundAndExpiry (0.00s)" |
| + ], |
| + "seconds": 3.83 |
| + }, |
| + { |
| + "guard": "notice outcome", |
| + "file": "internal/home/id_passkey.go", |
| + "test": "TestIDNoticeFailureSurvivesRestartWithoutAddress", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDNoticeFailureSurvivesRestartWithoutAddress (0.47s)" |
| + ], |
| + "seconds": 4.25 |
| + }, |
| + { |
| + "guard": "SMTP log privacy", |
| + "file": "internal/home/signin.go", |
| + "test": "TestIDSMTPFailureDoesNotLeak", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDSMTPFailureDoesNotLeak (0.29s)" |
| + ], |
| + "seconds": 3.85 |
| + }, |
| + { |
| + "guard": "limiter address blinding", |
| + "file": "internal/home/id_limiter.go", |
| + "test": "TestIDSigninLimiterUsesBlindedAddress", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDSigninLimiterUsesBlindedAddress (0.19s)" |
| + ], |
| + "seconds": 3.3 |
| + }, |
| + { |
| + "guard": "local signout", |
| + "file": "internal/home/directory.go", |
| + "test": "TestIDLocalSignoutWithHangingIssuer", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDLocalSignoutWithHangingIssuer (0.50s)" |
| + ], |
| + "seconds": 3.1 |
| + }, |
| + { |
| + "guard": "sealed link storage", |
| + "file": "internal/home/links.go", |
| + "test": "TestFullSigninLeavesNoReadableAddress", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestFullSigninLeavesNoReadableAddress (0.22s)" |
| + ], |
| + "seconds": 2.87 |
| + }, |
| + { |
| + "guard": "closed authorize fields", |
| + "file": "internal/home/exchange.go", |
| + "test": "TestIDClosedAuthorize", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDClosedAuthorize (0.40s)" |
| + ], |
| + "seconds": 3.17 |
| + }, |
| + { |
| + "guard": "authorize consumer uniqueness", |
| + "file": "internal/home/exchange.go", |
| + "test": "TestIDClosedAuthorize", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDClosedAuthorize (0.42s)" |
| + ], |
| + "seconds": 2.77 |
| + }, |
| + { |
| + "guard": "authorize nonce uniqueness", |
| + "file": "internal/home/exchange.go", |
| + "test": "TestIDClosedAuthorize", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDClosedAuthorize (0.42s)" |
| + ], |
| + "seconds": 2.86 |
| + }, |
| + { |
| + "guard": "CSRF for sensitive posts", |
| + "file": "internal/home/app.go", |
| + "test": "TestIDAllSensitivePostsRequireOrigin", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDAllSensitivePostsRequireOrigin (0.50s)" |
| + ], |
| + "seconds": 4.01 |
| + }, |
| + { |
| + "guard": "recovery subject defenses together", |
| + "file": "internal/home/id_recovery.go", |
| + "test": "TestIDReplacementProofBinding/wrong-person", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDReplacementProofBinding (0.45s)", |
| + "--- FAIL: TestIDReplacementProofBinding/wrong-person (0.45s)" |
| + ], |
| + "seconds": 5.11 |
| + }, |
| + { |
| + "guard": "registered authorize consumer", |
| + "file": "internal/home/exchange.go", |
| + "test": "TestIDClosedAuthorize", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDClosedAuthorize (0.43s)" |
| + ], |
| + "seconds": 4.03 |
| + }, |
| + { |
| + "guard": "authorize nonce format", |
| + "file": "internal/home/exchange.go", |
| + "test": "TestIDClosedAuthorize", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDClosedAuthorize (0.45s)" |
| + ], |
| + "seconds": 4.01 |
| + }, |
| + { |
| + "guard": "authorize max age", |
| + "file": "internal/home/exchange.go", |
| + "test": "TestIDClosedAuthorize", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDClosedAuthorize (0.41s)" |
| + ], |
| + "seconds": 3.09 |
| + }, |
| + { |
| + "guard": "replacement rollback", |
| + "file": "internal/home/id_passkey.go", |
| + "test": "TestIDReplacementRollback", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDReplacementRollback (1.98s)", |
| + "--- FAIL: TestIDReplacementRollback/sessionsDELETE (0.34s)", |
| + "--- FAIL: TestIDReplacementRollback/passkey_recovery_codesDELETE (0.32s)", |
| + "--- FAIL: TestIDReplacementRollback/home_id_recovery_proofsDELETE (0.32s)", |
| + "--- FAIL: TestIDReplacementRollback/passkey_credentialsINSERT (0.32s)", |
| + "--- FAIL: TestIDReplacementRollback/home_id_discoverableINSERT (0.35s)" |
| + ], |
| + "seconds": 4.41 |
| + }, |
| + { |
| + "guard": "email authentication time", |
| + "file": "internal/home/signin.go", |
| + "test": "TestIDEmailMintPreservesVerificationTime", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDEmailMintPreservesVerificationTime (0.22s)" |
| + ], |
| + "seconds": 3.16 |
| + }, |
| + { |
| + "guard": "codes after enrollment", |
| + "file": "internal/home/passkey.go", |
| + "test": "TestIDCodesRequireEnrolledPasskey", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDCodesRequireEnrolledPasskey (0.28s)" |
| + ], |
| + "seconds": 3.25 |
| + }, |
| + { |
| + "guard": "fresh intent start provenance", |
| + "file": "internal/home/assertion_intent.go", |
| + "test": "TestIDFreshIntentRequiresStartTime", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDFreshIntentRequiresStartTime (0.69s)" |
| + ], |
| + "seconds": 5.05 |
| + }, |
| + { |
| + "guard": "credential page cache privacy", |
| + "file": "internal/home/render.go", |
| + "test": "TestIDCredentialPagesAreNoStore", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDCredentialPagesAreNoStore (0.53s)" |
| + ], |
| + "seconds": 6.1 |
| + }, |
| + { |
| + "guard": "link recovery exclusion", |
| + "file": "internal/home/exchange.go", |
| + "test": "TestIDRecoveryCannotLink", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDRecoveryCannotLink (0.53s)" |
| + ], |
| + "seconds": 6.2 |
| + }, |
| + { |
| + "guard": "enrollment recovery exclusion", |
| + "file": "internal/home/id_passkey.go", |
| + "test": "TestIDRecoveryExclusions", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDRecoveryExclusions (0.37s)" |
| + ], |
| + "seconds": 4.73 |
| + }, |
| + { |
| + "guard": "codes recovery exclusion", |
| + "file": "internal/home/passkey.go", |
| + "test": "TestIDRecoveryExclusions", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDRecoveryExclusions (0.37s)" |
| + ], |
| + "seconds": 3.68 |
| + }, |
| + { |
| + "guard": "replacement recovery suffix", |
| + "file": "internal/home/id_recovery.go", |
| + "test": "TestIDReplacementRequiresRecoverySession/method", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDReplacementRequiresRecoverySession (0.34s)", |
| + "--- FAIL: TestIDReplacementRequiresRecoverySession/method (0.34s)" |
| + ], |
| + "seconds": 2.64 |
| + }, |
| + { |
| + "guard": "replacement session binding", |
| + "file": "internal/home/id_recovery.go", |
| + "test": "TestIDReplacementRequiresRecoverySession/session", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDReplacementRequiresRecoverySession (0.47s)", |
| + "--- FAIL: TestIDReplacementRequiresRecoverySession/session (0.47s)" |
| + ], |
| + "seconds": 3.96 |
| + }, |
| + { |
| + "guard": "limits before code consumption", |
| + "file": "internal/home/id_recovery.go", |
| + "test": "TestIDLimitsBeforeValidCode", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDLimitsBeforeValidCode (0.78s)", |
| + "--- FAIL: TestIDLimitsBeforeValidCode/account (0.41s)", |
| + "--- FAIL: TestIDLimitsBeforeValidCode/ip (0.36s)" |
| + ], |
| + "seconds": 4.79 |
| + }, |
| + { |
| + "guard": "recovery RAM reservation", |
| + "file": "internal/home/id_recovery.go", |
| + "test": "TestIDRecoveryMailboxFailurePreservesCode/full", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDRecoveryMailboxFailurePreservesCode (0.34s)", |
| + "--- FAIL: TestIDRecoveryMailboxFailurePreservesCode/full (0.34s)" |
| + ], |
| + "seconds": 3.57 |
| + }, |
| + { |
| + "guard": "recovery RAM required", |
| + "file": "internal/home/id_recovery.go", |
| + "test": "TestIDRecoveryMailboxFailurePreservesCode/missing", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDRecoveryMailboxFailurePreservesCode (0.33s)", |
| + "--- FAIL: TestIDRecoveryMailboxFailurePreservesCode/missing (0.33s)" |
| + ], |
| + "seconds": 3.25 |
| + }, |
| + { |
| + "guard": "full mailbox permits gate", |
| + "file": "internal/home/id_recovery.go", |
| + "test": "TestIDFullMailboxAllowsGatedSignin", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDFullMailboxAllowsGatedSignin (0.29s)" |
| + ], |
| + "seconds": 2.56 |
| + }, |
| + { |
| + "guard": "recovery signin notice", |
| + "file": "internal/home/id_recovery.go", |
| + "test": "TestIDRecoverySigninNotice$", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDRecoverySigninNotice (0.32s)" |
| + ], |
| + "seconds": 2.47 |
| + }, |
| + { |
| + "guard": "new codes after replacement", |
| + "file": "internal/home/id_passkey.go", |
| + "test": "TestIDRecoveryReplacementRevokesEverything", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDRecoveryReplacementRevokesEverything (0.41s)" |
| + ], |
| + "seconds": 2.95 |
| + }, |
| + { |
| + "guard": "stateless anonymous begin", |
| + "file": "internal/home/id_direct.go", |
| + "test": "TestIDDirectFloodLeavesGatedCapacity", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDDirectFloodLeavesGatedCapacity (0.32s)" |
| + ], |
| + "seconds": 3.25 |
| + }, |
| + { |
| + "guard": "direct seal authentication", |
| + "file": "internal/home/id_direct.go", |
| + "test": "TestIDDirectSealedChallenge/tampered", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDDirectSealedChallenge (0.28s)", |
| + "--- FAIL: TestIDDirectSealedChallenge/tampered (0.28s)" |
| + ], |
| + "seconds": 3.5 |
| + }, |
| + { |
| + "guard": "direct challenge binding", |
| + "file": "internal/home/id_direct.go", |
| + "test": "TestIDDirectSealedChallenge/mismatch", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDDirectSealedChallenge (0.27s)", |
| + "--- FAIL: TestIDDirectSealedChallenge/mismatch (0.27s)" |
| + ], |
| + "seconds": 3.53 |
| + }, |
| + { |
| + "guard": "direct expiry", |
| + "file": "internal/home/id_direct.go", |
| + "test": "TestIDDirectSealedChallenge/expired", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDDirectSealedChallenge (0.33s)", |
| + "--- FAIL: TestIDDirectSealedChallenge/expired (0.33s)" |
| + ], |
| + "seconds": 3.75 |
| + }, |
| + { |
| + "guard": "direct maximum lifetime", |
| + "file": "internal/home/id_direct.go", |
| + "test": "TestIDDirectSealedChallenge/future", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDDirectSealedChallenge (0.34s)", |
| + "--- FAIL: TestIDDirectSealedChallenge/future (0.34s)" |
| + ], |
| + "seconds": 4.99 |
| + }, |
| + { |
| + "guard": "direct receipt replay", |
| + "file": "internal/home/id_direct.go", |
| + "test": "TestIDDirectPasskey|TestIDDirectReceiptsBounded/restart", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDDirectPasskey (0.27s)", |
| + "--- FAIL: TestIDDirectReceiptsBounded (0.32s)", |
| + "--- FAIL: TestIDDirectReceiptsBounded/restart (0.32s)" |
| + ], |
| + "seconds": 4.84 |
| + }, |
| + { |
| + "guard": "direct receipt cap", |
| + "file": "internal/home/id_direct.go", |
| + "test": "TestIDDirectReceiptsBounded/capacity", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDDirectReceiptsBounded (0.48s)", |
| + "--- FAIL: TestIDDirectReceiptsBounded/capacity (0.48s)" |
| + ], |
| + "seconds": 5.44 |
| + }, |
| + { |
| + "guard": "direct receipt expiry", |
| + "file": "internal/home/id_direct.go", |
| + "test": "TestIDDirectReceiptsBounded/expiry", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDDirectReceiptsBounded (0.36s)", |
| + "--- FAIL: TestIDDirectReceiptsBounded/expiry (0.36s)" |
| + ], |
| + "seconds": 6.3 |
| + }, |
| + { |
| + "guard": "issuer signout form", |
| + "file": "internal/home/directory.go", |
| + "test": "TestSignOutEndsTheCredentialSession", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestSignOutEndsTheCredentialSession (0.70s)" |
| + ], |
| + "seconds": 5.48 |
| + }, |
| + { |
| + "guard": "issuer signout auto step", |
| + "file": "internal/home/directory.go", |
| + "test": "TestSignOutEndsTheCredentialSession", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestSignOutEndsTheCredentialSession (0.56s)" |
| + ], |
| + "seconds": 5.82 |
| + }, |
| + { |
| + "guard": "issuer signout no loop", |
| + "file": "internal/home/directory.go", |
| + "test": "TestSignOutEndsTheCredentialSession", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestSignOutEndsTheCredentialSession (0.60s)" |
| + ], |
| + "seconds": 3.83 |
| + }, |
| + { |
| + "guard": "issuer signout autosubmit", |
| + "file": "internal/home/static/assertion.js", |
| + "test": "TestIDBrowserSignoutBothOrigins", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDBrowserSignoutBothOrigins (48.43s)", |
| + "--- FAIL: TestIDBrowserSignoutBothOrigins/https://example.org/scripts=true (21.90s)", |
| + "--- FAIL: TestIDBrowserSignoutBothOrigins/https://directory.example.test/scripts=true (21.65s)" |
| + ], |
| + "seconds": 53.47 |
| + }, |
| + { |
| + "guard": "issuer site classification", |
| + "file": "internal/home/signout.go", |
| + "test": "TestCredentialSignoutUsesIssuerSite", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestCredentialSignoutUsesIssuerSite (0.42s)" |
| + ], |
| + "seconds": 3.62 |
| + }, |
| + { |
| + "guard": "issuer scheme classification", |
| + "file": "internal/home/signout.go", |
| + "test": "TestCredentialSignoutUsesIssuerSite", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestCredentialSignoutUsesIssuerSite (0.41s)" |
| + ], |
| + "seconds": 3.85 |
| + }, |
| + { |
| + "guard": "recovery session marked", |
| + "file": "internal/home/id_recovery.go", |
| + "test": "TestIDRecoverySigninNotice$", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDRecoverySigninNotice (0.38s)" |
| + ], |
| + "seconds": 3.8 |
| + }, |
| + { |
| + "guard": "anonymous begin stores no receipt", |
| + "file": "internal/home/id_direct.go", |
| + "test": "TestIDDirectFloodLeavesGatedCapacity", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDDirectFloodLeavesGatedCapacity (0.31s)" |
| + ], |
| + "seconds": 3.63 |
| + }, |
| + { |
| + "guard": "recovery notice log privacy", |
| + "file": "internal/home/id_recovery.go", |
| + "test": "TestIDRecoverySigninNoticeFailurePrivacy", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDRecoverySigninNoticeFailurePrivacy (0.34s)" |
| + ], |
| + "seconds": 4.79 |
| + }, |
| + { |
| + "guard": "replacement revokes sessions", |
| + "file": "internal/home/id_recovery.go", |
| + "test": "TestIDRecoveryReplacementRevokesEverything", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDRecoveryReplacementRevokesEverything (0.66s)" |
| + ], |
| + "seconds": 6.07 |
| + }, |
| + { |
| + "guard": "replacement revokes passkey_credentials", |
| + "file": "internal/home/id_recovery.go", |
| + "test": "TestIDRecoveryReplacementRevokesEverything", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDRecoveryReplacementRevokesEverything (0.40s)" |
| + ], |
| + "seconds": 4.49 |
| + }, |
| + { |
| + "guard": "replacement revokes passkey_recovery_codes", |
| + "file": "internal/home/id_recovery.go", |
| + "test": "TestIDRecoveryReplacementRevokesEverything", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDRecoveryReplacementRevokesEverything (0.50s)" |
| + ], |
| + "seconds": 5.2 |
| + }, |
| + { |
| + "guard": "replacement revokes passkey_pending", |
| + "file": "internal/home/id_recovery.go", |
| + "test": "TestIDRecoveryReplacementRevokesEverything", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDRecoveryReplacementRevokesEverything (0.47s)" |
| + ], |
| + "seconds": 6.46 |
| + }, |
| + { |
| + "guard": "replacement revokes passkey_challenges", |
| + "file": "internal/home/id_recovery.go", |
| + "test": "TestIDRecoveryReplacementRevokesEverything", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDRecoveryReplacementRevokesEverything (0.40s)" |
| + ], |
| + "seconds": 3.95 |
| + }, |
| + { |
| + "guard": "replacement revokes home_id_ceremonies", |
| + "file": "internal/home/id_recovery.go", |
| + "test": "TestIDRecoveryReplacementRevokesEverything", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDRecoveryReplacementRevokesEverything (0.84s)" |
| + ], |
| + "seconds": 4.64 |
| + }, |
| + { |
| + "guard": "replacement revokes home_id_recovery_proofs", |
| + "file": "internal/home/id_recovery.go", |
| + "test": "TestIDRecoveryReplacementRevokesEverything", |
| + "result": "killed", |
| + "failures": [ |
| + "--- FAIL: TestIDRecoveryReplacementRevokesEverything (0.82s)" |
| + ], |
| + "seconds": 6.44 |
| + } |
| +] |
diff --git a/implementation/oficina-id-slice1-validation.md b/implementation/oficina-id-slice1-validation.md| new file mode 100644 |
| index 0000000..a08acca |
| --- /dev/null |
| +++ b/implementation/oficina-id-slice1-validation.md |
| @@ -0,0 +1,165 @@ |
| +# Oficina ID slice 1 validation record |
| + |
| +Agent record, 2026-11-13. No deploy or merge. |
| + |
| +## Red/green |
| + |
| +- Task 1: `TestIDLinkAlwaysRequiresNewGesture` failed because GET reused a |
| + recent session (200); `TestIDContinueBeforeMinting` failed because GET minted |
| + immediately. Both pass after the issuance change. Existing fresh assertion, |
| + Home assertion and directory exchange tests also pass. |
| + |
| +## Mutations |
| + |
| +Pending. |
| + |
| +- Task 2: direct sign-in and proof-negative tests failed with 404 before the |
| + handlers existed. Credential-transfer test failed because enrollment replaced |
| + the first person's row. All now pass, along with enrollment freshness and |
| + existing gated-sign-in tests. New registrations use the existing WebAuthn |
| + helper's required resident key and user verification options. |
| + |
| +- Task 3: entropy, parallel/restart attempt limits, replacement confirmation, |
| + and hostile SMTP-error tests failed before recovery implementation. The new |
| + code passes them. Added account/IP, rollback, browser/person/expiry/UV/replay, |
| + and no-address checks. A later notice-restart regression failed, then passed |
| + after adding a sealed, content-free result cookie separate from the RAM |
| + address. Successful replacement revokes all issuer sessions; directory and |
| + consumer sessions retain their own expiry/revocation. Delegated copy now says |
| + Oficina ID and names that limit. |
| +- Astra source review found stale/passive Keymail proof, an email-mint/enrollment |
| + race, cached-session assertion issuance, missing nondiscoverable browser |
| + allowlists, and notice-result loss. Added failing stale-mailbox, cached-session |
| + and legacy-allowlist regressions; fixed each. Email-only mint now shares the |
| + gate transaction and preserves Keymail auth_time. Re-review remains pending. |
| +- Task 4: hanging-issuer sign-out test failed on the old 307 to the issuer. |
| + Directory sign-out now revokes and lands locally; credential sign-out also |
| + has its own landing page. The hanging server accepts an actual connection. |
| +- Historical admission profiles remain byte-for-byte frozen. New identity |
| + migrations are a separate serving-role set, following existing HTTP schema |
| + extensions; standalone test Apps apply that set too. |
| +- Local Go's VCS discovery selects an unrelated broken `.git` in the ancestor |
| + scratch directory. Local gates use GOFLAGS=-buildvcs=false; no ancestor files |
| + or shared Go cache settings were changed. Hosted CI uses the normal targets. |
| + |
| +- Real Chromium: TestIDBrowserDirectPasskeyAndGeneratedNames, |
| + TestIDBrowserLegacyNonresidentGate and TestIDBrowserScriptlessCrossSiteReturn |
| + pass against two HTTPS sites routed to a loopback test server. No deploy. |
| +- Further red/green regressions: legacy runtime missing identity schema; |
| + duplicate/trailing ceremony JSON; enrollment exceeding the allowlist bound; |
| + future/passive enrollment authentication; readable address in Flow's limiter. |
| + The limiter now receives a blinded address key and still shares its IP budget |
| + with /resolve. Existing rate-limit tests remain in force. |
| +- Added code/person/replay races, live registration binding, clock rollback, |
| + challenge/cookie bounds, unrelated step-up refusal, backup-file privacy and |
| + notice retry tests. All targeted ID tests pass. |
| +- First hosted CI at df69548 failed three old fixtures (recent-session reuse |
| + and GET minting). Fixtures now reauthenticate the original identity and POST |
| + Continue; operator fixtures have explicit larger mail budgets for repeated |
| + independent test ceremonies. Production mail limits are unchanged. |
| + |
| +## Mutation result |
| + |
| +`scripts/check-id-mutations.py` ran 63 guard-removal checks. 62 were killed by |
| +behavioral regressions. Removing only the SQL recovery-subject predicate |
| +survived because the independent mailbox subject check still refused the proof; |
| +removing both checks was killed. The JSON record names every guard, test and |
| +result. This is a recorded redundant defense, not a claim of zero survivors. |
| + |
| +The checks include every replacement revocation table, rollback, WebAuthn |
| +origin/RP/UV/signature rejection, replay, challenge and cookie binding, limits, |
| +expiry, clock rollback, entropy, mail/limiter/storage privacy, Continue/CSRF, |
| +closed authorize parsing, audience, nonce, lifetime and authentication-time |
| +provenance. Original source was restored after each check. |
| + |
| +Additional red/green tests reject old fresh-intent cookies without a start time, |
| +preserve email verification time rather than session-mint time, and require an |
| +enrolled passkey before issuing codes. Recovery proofs have a hard row bound. |
| +Hosted CI's race pass found two concurrent ResponseRecorder.Result calls in |
| +fixtures; cookie snapshots now precede the goroutines. Targeted race tests pass. |
| + |
| +The full gates exposed one final fixture tied to the former magic-link fallback: |
| +it backdated session creation while leaving the newly explicit auth_time fresh. |
| +The fixture now backdates the actual authentication time and passes its full |
| +stale-to-fresh operator ceremony. This changes no production behavior. |
| + |
| +## Completed gates |
| + |
| +On 2026-11-13, `GOFLAGS=-buildvcs=false make test` passed every local target: |
| +vet, formatting, cgo-free builds (including linux/arm64), every module's regular |
| +tests and the full race suites. `GOFLAGS=-buildvcs=false make test-browser` |
| +also passed, including the new real-browser identity flows and the zoom gate. |
| +Hosted CI passed all steps at 9d8fa5f1b620c9d1ae5d4e779d596b0ab1102c82. |
| + |
| +The final closeout moves the Keymail fixture's simulated gesture after its link |
| +start to avoid a second-boundary flake, records completed plan tasks, ignores the |
| +local handoff, and applies Astra's accepted "Oficina ID" signed-out wording. |
| +Targeted Keymail/sign-out race tests pass after that delta. Final-tip CI and the |
| +exact final SHA are recorded in branch discussion 107 and the requested report. |
| + |
| +GPT-6 Astra approved source/tests; deployed-canary review remains outstanding |
| +under Paul's no-deploy instruction. No merge was attempted. Equipo and shared |
| +consumer adapter changes remain part B. |
| + |
| +A final renderer check found credential HTML lacked explicit no-store headers. |
| +`TestIDCredentialPagesAreNoStore` failed before the fix. The shared renderer now |
| +sets no-store on credential-origin HTML, including shown-once recovery codes; |
| +static assets retain their own cache policy. The regression passes and removing |
| +the header is killed by mutation. The final record is 63 checks / 62 killed / |
| +one independently guarded survivor. Targeted renderer and browser tests follow |
| +this final three-line production change; final-tip CI reruns the full gate. |
| + |
| +## Fable review fixes: red tests |
| + |
| +After merging origin/main, the revised real-form signout regression and hanging |
| +issuer test both failed because the local page had no credential POST form. |
| +The anonymous-begin flood failed on request 10,001; its first 10,000 requests |
| +filled the ceremony table. Sealed-proof cases failed because no sealed proof |
| +existed. Recovery tests failed for full RAM blocking the email gate, missing/full |
| +RAM still consuming codes, no redemption notice, and recovery satisfying linking. |
| +The replacement regression failed because the new passkey login skipped codes. |
| +These failures were observed before their production changes. Existing recovery |
| +exclusion, replacement method/session binding, and attempt-budget guards already |
| +passed; their missing mutations are added in this review pass. |
| + |
| +Astra's follow-up found cross-site directory classification used the directory |
| +hostname instead of ID's cookie site. TestCredentialSignoutUsesIssuerSite failed |
| +before the fix. Sign-out now compares the issuer's scheme and public-suffix |
| +registrable domain; the existing workspace x/net version is explicitly required |
| +by this module. Chromium sign-out passes for same-site and cross-site origins, |
| +with scripts on and off. Selectors distinguish the issuer confirmation button |
| +from the directory menu button to avoid clicking the page being navigated away |
| +from. The hanging test posts the actual local page's form and checks the local |
| +landing and revoked session again while that request is blocked. |
| + |
| +The full mutation pass exposed redundant refusal in an old restart fixture: |
| +missing RAM proof hid removed persistent attempt limits. The fixture now obtains |
| +a fresh mailbox proof after reconstruction. Persisted mailbox freshness is also |
| +checked with the independent RAM proof kept live, so neither defense masks the |
| +other in the mutation check. Legacy 50-bit codes have a compatibility regression; |
| +only newly generated sets receive the 128-bit entropy guarantee. |
| + |
| +Final full mutation rerun: 91 checks, 90 killed. The one surviving removal is |
| +still the SQL recovery-proof subject predicate, independently enforced by the |
| +RAM mailbox subject check. Removing both is killed. All 28 added mutations are |
| +killed, including the real-browser auto-submit mutation. The runner restores |
| +source after every mutation and records results in |
| +implementation/oficina-id-slice1-mutations.json. |
| + |
| +Hosted CI also caught the added public-suffix dependency's missing attribution. |
| +make credits regenerated it; delegated Astra review verified the license against |
| +the cached upstream text. Full local gates and final hosted CI are recorded in |
| +../report2.md and branch discussion 107 rather than claimed before completion. |
| + |
| +Authorship for this review-fix pass: Codex (OpenAI), acting on Paul's request. |
| +GPT-6 Astra performed the delegated copy and independent source reviews. |
| +The agent's coordination and review record is Amadan discussion 107; the prompt |
| +ledger is retained on the branch. The final source/tests/records approval before |
| +this authorship note was af703f4735776f6fc1a915369348d40b1548f8f9. |
| + |
| +Final hosted CI exposed an unrelated probabilistic fixture in |
| +TestResolvedRefusals: replacing the receipt's last two characters with AA can |
| +leave the original signature unchanged. The test now flips a decoded signature |
| +byte and re-encodes it, guaranteeing different bytes. Production verification |
| +is unchanged. The corrected test passed 20 consecutive runs. The full browser |
| +gate already passed; the full local gate continues through its race suites. |
diff --git a/internal/home/app.go b/internal/home/app.go| index 750bb01..bdb3e3d 100644 |
| --- a/internal/home/app.go |
| +++ b/internal/home/app.go |
| @@ -38,6 +38,7 @@ import ( |
| // is sealed on the way in, and the database handle because that is what |
| // it is sealed into. Nothing here reaches for a raw key. |
| type App struct { |
| + mailboxes mailboxMemory |
| dash *dashboardState |
| runtime *Runtime |
| directory *directoryFeatures |
| @@ -143,7 +144,7 @@ func NewWithOrigins(secrets Secrets, d *db.DB, logger *slog.Logger, origins Orig |
| // The flow's default, made explicit so that /resolve shares its per-IP |
| // budget (resolve.go). |
| a.signinLimiter = signin.NewMemoryLimiter(15 * time.Minute) |
| - a.flow.Limiter = a.signinLimiter |
| + a.flow.Limiter = blindSigninLimiter{next: a.signinLimiter, pepper: secrets.Pepper} |
| a.resolveLimiter = signin.NewMemoryLimiter(time.Hour) |
| if a.passkeys, err = newPasskeys(a); err != nil { |
| @@ -203,6 +204,7 @@ func (a *App) Router() http.Handler { |
| // page. See signoutPath. |
| r.With(a.credentialOnly).Post(signoutPath, a.handleCredentialSignout) |
| r.With(a.credentialOnly).Get(signoutPath, a.handleCredentialSignoutPage) |
| + r.With(a.credentialOnly).Get("/signed-out", func(w http.ResponseWriter, r *http.Request) { a.render(w, r, 200, "id_signed_out.html", nil) }) |
| } |
| r.Group(func(r chi.Router) { |
| @@ -218,6 +220,7 @@ func (a *App) Router() http.Handler { |
| r.Get("/dashboard/authorize", a.beginDashboard) |
| r.With(a.sessions.Require).Get("/dashboard/resume", a.authorizeDashboard) |
| r.With(a.sessions.Require).Get("/authorize/resume", a.handleAssertion) |
| + r.With(a.sessions.Require).Post("/authorize/resume", a.handleAssertion) |
| // Adding a team member by email (team-members.md §4): only |
| // with HOME_RESOLVE_KEY configured. |
| if a.runtime.resolveSigner != nil { |
| @@ -244,19 +247,26 @@ func (a *App) Router() http.Handler { |
| // with script off, because recovery is exactly the moment WebAuthn |
| // is not working. |
| r.Get(confirmPath, a.handlePasskeyConfirm) |
| - r.Post("/passkey/stepup/begin", a.passkeys.StepUpBegin) |
| - r.Post("/passkey/stepup/finish", a.passkeys.StepUpFinish) |
| - r.Post("/passkey/signin/begin", a.passkeys.SignInBegin) |
| - r.Post("/passkey/signin/finish", a.passkeys.SignInFinish) |
| - r.Post("/passkey/signin/recovery", a.passkeys.SignInRecovery) |
| + r.Get("/passkey/replace", a.handleReplacement) |
| + r.Post("/passkey/replace/begin", a.idBegin("replace")) |
| + r.Post("/passkey/replace/finish", a.idFinish("replace")) |
| + r.Get("/passkey/replaced", a.handleReplacementDone) |
| + r.Post("/passkey/notice", a.handleNoticeRetry) |
| + r.Post("/passkey/direct/begin", a.idBegin("direct")) |
| + r.Post("/passkey/direct/finish", a.idFinish("direct")) |
| + r.Post("/passkey/stepup/begin", a.idBegin("stepup")) |
| + r.Post("/passkey/stepup/finish", a.idFinish("stepup")) |
| + r.Post("/passkey/signin/begin", a.idBegin("signin")) |
| + r.Post("/passkey/signin/finish", a.idFinish("signin")) |
| + r.Post("/passkey/signin/recovery", a.idRecovery) |
| // Enrolling changes who can get in, and there is no operator reset, |
| // so it wants a recent session rather than merely a valid one — see |
| // enrolFreshness for the lockout this closes. |
| r.Group(func(r chi.Router) { |
| r.Use(a.sessions.RequireFresh(enrolFreshness)) |
| r.Get("/passkey/enrol", a.handlePasskeyEnrol) |
| - r.Post("/passkey/register/begin", a.passkeys.RegisterBegin) |
| - r.Post("/passkey/register/finish", a.passkeys.RegisterFinish) |
| + r.Post("/passkey/register/begin", a.idBegin("register")) |
| + r.Post("/passkey/register/finish", a.idFinish("register")) |
| }) |
| // The codes page shows ten codes once, so it wants a recent session |
diff --git a/internal/home/assertion_fresh_test.go b/internal/home/assertion_fresh_test.go| index 3f789c1..a999e3e 100644 |
| --- a/internal/home/assertion_fresh_test.go |
| +++ b/internal/home/assertion_fresh_test.go |
| @@ -74,7 +74,8 @@ func TestFreshAssertionUsesFreshSessionAndBindsOriginalPerson(t *testing.T) { |
| p := newExchangePair(t) |
| first := signInFully(t, p.credential, sealtest.CanaryAddress) |
| _, intent := p.startFresh(t, first) |
| - p.mint(t, intent, first) |
| + again := signInFully(t, p.credential, sealtest.CanaryAddress) |
| + p.mint(t, intent, again) |
| _, intent = p.startFresh(t, first) |
| second := signInFully(t, p.credential, "different@example.invalid") |
| r := exchangeRequest(p.credential.App, "GET", Origin+"/authorize/resume", "", nil, intent, second) |
| @@ -136,7 +137,7 @@ func TestOrdinaryIntentKeepsKeymailAndInvalidIntentCannotRequestFreshness(t *tes |
| } |
| } |
| -func TestFreshAssertionAcceptsCompletedKeymailRecovery(t *testing.T) { |
| +func TestFreshAssertionRejectsCompletedKeymailRecovery(t *testing.T) { |
| p := newExchangePair(t) |
| const address = "person@keymail.invalid" |
| newKeymailStub(t, p.credential, address) |
| @@ -164,5 +165,8 @@ func TestFreshAssertionAcceptsCompletedKeymailRecovery(t *testing.T) { |
| if sessionCookie(recovery) == nil { |
| t.Fatal("recovery did not complete", recovery.Code) |
| } |
| - p.mint(t, intent, sessionCookie(recovery)) |
| + r := exchangeRequest(p.credential.App, "POST", Origin+"/authorize/resume", Origin, nil, intent, sessionCookie(recovery)) |
| + if r.Code != 303 || !strings.HasPrefix(r.Header().Get("Location"), "/signin") { |
| + t.Fatal("recovery satisfied linking reauthentication") |
| + } |
| } |
diff --git a/internal/home/assertion_intent.go b/internal/home/assertion_intent.go| index f2eaab3..79d1b26 100644 |
| --- a/internal/home/assertion_intent.go |
| +++ b/internal/home/assertion_intent.go |
| @@ -34,5 +34,8 @@ func (a *App) readAssertionIntent(r *http.Request, now time.Time) (assertionInte |
| if json.Unmarshal(plain, &intent, json.RejectUnknownMembers(true)) != nil || intent.Expires <= now.Unix() || intent.Expires > now.Unix()+600 || !handoff.ValidNonce(intent.Nonce) || (intent.MaxAge != 0 && intent.MaxAge != 300) || (intent.MaxAge == 0 && intent.Subject != "") { |
| return assertionIntent{}, false |
| } |
| + if intent.MaxAge != 0 && intent.Consumer != operatorConfirmConsumer && (intent.Started <= 0 || intent.Started > now.Unix()) { |
| + return assertionIntent{}, false |
| + } |
| return intent, true |
| } |
diff --git a/internal/home/credits/notices.json b/internal/home/credits/notices.json| index f86edb6..0631e6c 100644 |
| --- a/internal/home/credits/notices.json |
| +++ b/internal/home/credits/notices.json |
| @@ -168,6 +168,17 @@ |
| } |
| ] |
| }, |
| + { |
| + "Name": "golang.org/x/net", |
| + "Version": "v0.57.0", |
| + "SourceURL": "https://pkg.go.dev/golang.org/x/net@v0.57.0", |
| + "Notices": [ |
| + { |
| + "Name": "LICENSE", |
| + "Text": "Copyright 2009 The Go Authors.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n * Redistributions of source code must retain the above copyright\nnotice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above\ncopyright notice, this list of conditions and the following disclaimer\nin the documentation and/or other materials provided with the\ndistribution.\n * Neither the name of Google LLC nor the names of its\ncontributors may be used to endorse or promote products derived from\nthis software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" |
| + } |
| + ] |
| + }, |
| { |
| "Name": "golang.org/x/sys", |
| "Version": "v0.47.0", |
diff --git a/internal/home/directory.go b/internal/home/directory.go| index fc6863e..8d68b98 100644 |
| --- a/internal/home/directory.go |
| +++ b/internal/home/directory.go |
| @@ -161,17 +161,20 @@ func (a *App) directoryRouter() http.Handler { |
| // not turn the click into a sign-in loop. A host-only cookie, so the |
| // choice is the directory's own. |
| r.Post("/appearance", chrome.HandleAppearance) |
| - // Sign out ends both sessions: this one here, then the id.* |
| - // session by handing the POST on. See signoutPath. |
| + // Local revocation and landing never wait for the credential origin. |
| r.Post(signoutPath, func(w http.ResponseWriter, r *http.Request) { |
| w.Header().Set("Cache-Control", "no-store") |
| a.sessions.SignOut(w, r) |
| - http.Redirect(w, r, a.origins.Credential+signoutPath, http.StatusTemporaryRedirect) |
| + idCookie(w, "__Host-oficina-finish-signout", "1", 300) |
| + http.Redirect(w, r, "/signed-out", http.StatusSeeOther) |
| }) |
| r.Get("/signed-out", func(w http.ResponseWriter, r *http.Request) { |
| w.Header().Set("Cache-Control", "no-store") |
| - a.render(w, r, 200, "directory_signed_out.html", map[string]any{}) |
| + finish := cookieValue(r, "__Host-oficina-finish-signout") == "1" |
| + idCookie(w, "__Host-oficina-finish-signout", "", -1) |
| + a.render(w, r, 200, "directory_signed_out.html", map[string]any{"Finish": finish, "Action": a.origins.Credential + signoutPath}) |
| }) |
| + r.Get("/static/assertion.js", serveAsset(staticAsset("assertion.js"), "text/javascript; charset=utf-8")) |
| r.Get("/healthz", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) }) |
| mountCSS(r, "/static/tokens.css", staticAsset("tokens.css")) |
| mountCSS(r, "/static/theme.css", theme.CSS()) |
diff --git a/internal/home/door_copy_test.go b/internal/home/door_copy_test.go| index 7c5552a..141a765 100644 |
| --- a/internal/home/door_copy_test.go |
| +++ b/internal/home/door_copy_test.go |
| @@ -79,9 +79,9 @@ func TestDoorSpeaksTheSuiteCopy(t *testing.T) { |
| mustContain(t, "/signed-out", out.Body.String(), |
| "<title>Signed out · Oficina</title>", |
| "<h1>You’re signed out</h1>", |
| - "You’ve signed out of Oficina on this device.", |
| + "You are signed out of the directory in this browser.", |
| `rst-btn="primary">Sign in</a>`) |
| - mustNotContain(t, "/signed-out", out.Body.String(), "You are signed out", "Home") |
| + mustNotContain(t, "/signed-out", out.Body.String(), "You’ve signed out of Oficina on this device.", "Home") |
| } |
| // The hub builds its own signin.Flow, so it sets the email itself: the |
diff --git a/internal/home/exchange.go b/internal/home/exchange.go| index 849b692..c2c9a39 100644 |
| --- a/internal/home/exchange.go |
| +++ b/internal/home/exchange.go |
| @@ -4,6 +4,7 @@ import ( |
| "encoding/base64" |
| "net/http" |
| "net/url" |
| + "strings" |
| "time" |
| "amadan.net/oficina/home/handoff" |
| @@ -21,6 +22,8 @@ type assertionIntent struct { |
| Expires int64 `json:"expires"` |
| MaxAge int `json:"max_age,omitzero"` |
| Subject string `json:"subject,omitzero"` |
| + Started int64 `json:"started,omitzero"` |
| + Previous string `json:"previous,omitzero"` |
| } |
| func (a *App) handleAuthorize(w http.ResponseWriter, r *http.Request) { |
| @@ -44,6 +47,10 @@ func (a *App) handleAuthorize(w http.ResponseWriter, r *http.Request) { |
| } |
| intent := assertionIntent{Consumer: q.Get("consumer"), Nonce: q.Get("nonce"), Expires: time.Now().Unix() + 600, MaxAge: maxAge} |
| if maxAge != 0 { |
| + intent.Started = time.Now().Unix() |
| + if c, err := r.Cookie(a.sessions.CookieName()); err == nil { |
| + intent.Previous = sessions.HashToken(c.Value) |
| + } |
| if session, ok := a.sessions.From(r); ok { |
| intent.Subject = session.Subject |
| } |
| @@ -82,8 +89,14 @@ func (a *App) handleAssertion(w http.ResponseWriter, r *http.Request) { |
| a.failAssertion(w, r, assertionConsumer) |
| return |
| } |
| - session, ok := sessions.Current(r) |
| - if !ok { |
| + tx, _, err := a.idTransaction(r.Context()) |
| + if err != nil { |
| + a.failAssertion(w, r, assertionSession) |
| + return |
| + } |
| + defer tx.Rollback() |
| + session, _, err := a.idSession(tx, r, now.Unix()) |
| + if err != nil { |
| a.failAssertion(w, r, assertionSession) |
| return |
| } |
| @@ -95,10 +108,22 @@ func (a *App) handleAssertion(w http.ResponseWriter, r *http.Request) { |
| a.failAssertion(w, r, assertionSubject) |
| return |
| } |
| - if intent.MaxAge != 0 && (!sessions.Fresh(session, time.Duration(intent.MaxAge)*time.Second, now) || authTime.After(now) || keymailWithoutGesture(session)) { |
| + sameSession := false |
| + if c, err := r.Cookie(a.sessions.CookieName()); err == nil { |
| + sameSession = intent.Previous != "" && sessions.HashToken(c.Value) == intent.Previous |
| + } |
| + if intent.MaxAge != 0 && (sameSession || (intent.Started != 0 && authTime.Unix() < intent.Started) || !sessions.Fresh(session, time.Duration(intent.MaxAge)*time.Second, now) || authTime.After(now) || keymailWithoutGesture(session) || strings.Contains(session.Method, "recovery")) { |
| http.Redirect(w, r, "/signin?return_to=%2Fauthorize%2Fresume", http.StatusSeeOther) |
| return |
| } |
| + if r.Method == http.MethodGet { |
| + if tx.Commit() != nil { |
| + a.failAssertion(w, r, assertionSession) |
| + return |
| + } |
| + a.render(w, r, http.StatusOK, "id_continue.html", nil) |
| + return |
| + } |
| id, err := assertion.RandomID() |
| if err != nil { |
| a.failAssertion(w, r, assertionRandom) |
| @@ -109,6 +134,10 @@ func (a *App) handleAssertion(w http.ResponseWriter, r *http.Request) { |
| a.failAssertion(w, r, assertionSign) |
| return |
| } |
| + if tx.Commit() != nil { |
| + a.failAssertion(w, r, assertionSession) |
| + return |
| + } |
| http.SetCookie(w, &http.Cookie{Name: assertionIntentCookie, Value: "", Path: "/", MaxAge: -1, Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode}) |
| // This page's form posts to one consumer; its form-action names that one |
| // origin and no other (team-provisioning-amendment.md §7). |
diff --git a/internal/home/exchange_test.go b/internal/home/exchange_test.go| index 7569860..fe1baf0 100644 |
| --- a/internal/home/exchange_test.go |
| +++ b/internal/home/exchange_test.go |
| @@ -115,7 +115,7 @@ func (p exchangePair) start(t *testing.T) (*http.Cookie, *http.Cookie) { |
| } |
| func (p exchangePair) mint(t *testing.T, intent, session *http.Cookie) (string, *httptest.ResponseRecorder) { |
| t.Helper() |
| - rec := exchangeRequest(p.credential.App, "GET", Origin+"/authorize/resume", "", nil, intent, session) |
| + rec := exchangeRequest(p.credential.App, "POST", Origin+"/authorize/resume", Origin, nil, intent, session) |
| if rec.Code != 200 { |
| t.Fatal("mint", rec.Code) |
| } |
| @@ -281,7 +281,7 @@ func TestHomePolicyMatchesRegisteredConsumers(t *testing.T) { |
| session := signInFully(t, p.credential, sealtest.CanaryAddress) |
| nonce, _ := assertion.RandomID() |
| authorize := exchangeRequest(p.credential.App, "GET", Origin+"/authorize?consumer=team_docs&nonce="+nonce, "", nil) |
| - rec := exchangeRequest(p.credential.App, "GET", Origin+"/authorize/resume", "", nil, namedCookie(t, authorize, assertionIntentCookie), session) |
| + rec := exchangeRequest(p.credential.App, "POST", Origin+"/authorize/resume", Origin, nil, namedCookie(t, authorize, assertionIntentCookie), session) |
| want := strings.Replace(baseline, "form-action 'self' "+directoryOrigin, "form-action 'self' https://blue.docs.oficina.works "+directoryOrigin, 1) |
| if rec.Code != 200 || rec.Header().Get("Content-Security-Policy") != want { |
| t.Fatalf("handoff CSP %d %q, want %q", rec.Code, rec.Header().Get("Content-Security-Policy"), want) |
| @@ -322,3 +322,25 @@ func TestDirectoryRoleUpgradePreservesExistingDatabase(t *testing.T) { |
| } |
| sealtest.AssertNoPlaintext(t, old.dbPath) |
| } |
| + |
| +func reauthenticateCredential(t *testing.T, a *testApp, c *http.Cookie) *http.Cookie { |
| + t.Helper() |
| + subject := subjectOf(t, a, c) |
| + var blind string |
| + if err := a.db.Writer().QueryRow("SELECT blind_index FROM people WHERE person_ref=?", subject).Scan(&blind); err != nil { |
| + t.Fatal(err) |
| + } |
| + address := "" |
| + a.mailer.mu.Lock() |
| + for _, m := range a.mailer.sent { |
| + if blindIndex(a.secrets.Pepper, m.To) == blind { |
| + address = m.To |
| + break |
| + } |
| + } |
| + a.mailer.mu.Unlock() |
| + if address == "" { |
| + t.Fatal("fixture lacks verified mailbox") |
| + } |
| + return signInFully(t, a, address) |
| +} |
diff --git a/internal/home/id_browser_test.go b/internal/home/id_browser_test.go| new file mode 100644 |
| index 0000000..2e4839c |
| --- /dev/null |
| +++ b/internal/home/id_browser_test.go |
| @@ -0,0 +1,187 @@ |
| +//go:build browser |
| + |
| +package home |
| + |
| +import ( |
| + "context" |
| + "crypto/x509" |
| + "encoding/base64" |
| + "fmt" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/home/internal/home/sealtest" |
| + "amadan.net/rastrillo/rastrillo/harness" |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| + "github.com/chromedp/cdproto/emulation" |
| + "github.com/chromedp/cdproto/network" |
| + "github.com/chromedp/cdproto/webauthn" |
| + "github.com/chromedp/chromedp" |
| +) |
| + |
| +const browserIssuer = "https://id.example.org" |
| +const browserRP = "id.example.org" |
| + |
| +// Two different sites, real HTTPS and real browser cookies. DNS is redirected |
| +// only inside this Chrome process; the test server listens on loopback. |
| +func idBrowser(t *testing.T) (exchangePair, context.Context, webauthn.AuthenticatorID) { |
| + return idBrowserFor(t, "https://directory.example.test") |
| +} |
| +func idBrowserFor(t *testing.T, consumer string) (exchangePair, context.Context, webauthn.AuthenticatorID) { |
| + t.Helper() |
| + p := newExchangePair(t) |
| + consumerURL, _ := url.Parse(consumer) |
| + origins := Origins{browserIssuer, consumer} |
| + old := p.credential.App |
| + app, err := NewWithOrigins(old.secrets, p.credential.db, quietLogger(), origins) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + app.flow.Classifier = old.flow.Classifier |
| + app.runtime = old.runtime |
| + p.credential.App = app |
| + p.credential.runtime.origins = origins |
| + p.credential.runtime.consumers["directory"] = consumer |
| + directory, err := NewRuntime(Runtime{role: "directory", origins: origins, secrets: p.directory.secrets, keys: p.credential.runtime.keys}, p.directory.db, quietLogger()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + p.directory = directory |
| + ch, dh := p.credential.Router(), p.directory.Router() |
| + server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.Host == browserRP { |
| + ch.ServeHTTP(w, r) |
| + } else if r.Host == consumerURL.Hostname() { |
| + dh.ServeHTTP(w, r) |
| + } else { |
| + http.NotFound(w, r) |
| + } |
| + })) |
| + t.Cleanup(server.Close) |
| + u, _ := url.Parse(server.URL) |
| + useChrome(t) |
| + opts := append(chromedp.DefaultExecAllocatorOptions[:], chromedp.ExecPath(harness.ChromePath(t)), chromedp.NoSandbox, chromedp.Flag("ignore-certificate-errors", true), chromedp.Flag("no-proxy-server", true), chromedp.Flag("host-resolver-rules", "MAP id.example.org "+u.Host+", MAP "+consumerURL.Hostname()+" "+u.Host), chromedp.UserDataDir(t.TempDir())) |
| + alloc, stop := chromedp.NewExecAllocator(context.Background(), opts...) |
| + ctx, cancel := chromedp.NewContext(alloc) |
| + t.Cleanup(func() { _ = chromedp.Cancel(ctx); cancel(); stop() }) |
| + if err := chromedp.Run(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + var authenticator webauthn.AuthenticatorID |
| + idBrowserRun(t, ctx, webauthn.Enable(), chromedp.ActionFunc(func(ctx context.Context) error { |
| + var e error |
| + authenticator, e = webauthn.AddVirtualAuthenticator(&webauthn.VirtualAuthenticatorOptions{Protocol: webauthn.AuthenticatorProtocolCtap2, Transport: webauthn.AuthenticatorTransportInternal, HasResidentKey: true, HasUserVerification: true, IsUserVerified: true, AutomaticPresenceSimulation: true}).Do(ctx) |
| + return e |
| + })) |
| + return p, ctx, authenticator |
| +} |
| +func idBrowserRun(t *testing.T, ctx context.Context, actions ...chromedp.Action) { |
| + t.Helper() |
| + ctx, cancel := context.WithTimeout(ctx, 20*time.Second) |
| + defer cancel() |
| + if err := chromedp.Run(ctx, actions...); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| +func idBrowserCookie(c *http.Cookie) chromedp.Action { |
| + return network.SetCookie(c.Name, c.Value).WithURL(browserIssuer + "/").WithHTTPOnly(true).WithSecure(true).WithSameSite(network.CookieSameSiteLax) |
| +} |
| + |
| +func TestIDBrowserDirectPasskeyAndGeneratedNames(t *testing.T) { |
| + p, ctx, authenticator := idBrowser(t) |
| + s := signInFully(t, p.credential, sealtest.CanaryAddress) |
| + subject := subjectOf(t, p.credential, s) |
| + idBrowserRun(t, ctx, idBrowserCookie(s), chromedp.Navigate(browserIssuer+"/passkey/enrol"), chromedp.WaitVisible("#passkey-enrol"), chromedp.Click("#passkey-enrol"), chromedp.WaitVisible(`form[action="/passkey/codes"]`)) |
| + var credentials []*webauthn.Credential |
| + idBrowserRun(t, ctx, chromedp.ActionFunc(func(ctx context.Context) error { |
| + var e error |
| + credentials, e = webauthn.GetCredentials(authenticator).Do(ctx) |
| + return e |
| + })) |
| + if len(credentials) != 1 || !credentials[0].IsResidentCredential || credentials[0].UserName != subject || credentials[0].UserDisplayName != subject { |
| + t.Fatal("WebAuthn names were not generated opaque identifiers") |
| + } |
| + idBrowserRun(t, ctx, network.DeleteCookies(s.Name).WithURL(browserIssuer+"/"), chromedp.Navigate(browserIssuer+"/signin?return_to=%2Fpasskey%2Fcodes"), chromedp.WaitVisible("#passkey-direct"), chromedp.Click("#passkey-direct"), chromedp.WaitVisible(`form[action="/passkey/codes"]`)) |
| + sealtest.AssertNoPlaintext(t, p.credential.dbPath) |
| +} |
| +func TestIDBrowserLegacyNonresidentGate(t *testing.T) { |
| + p, ctx, authenticator := idBrowser(t) |
| + s := signInFully(t, p.credential, sealtest.CanaryAddress) |
| + key := enrol(t, p.credential, s) |
| + if _, err := p.credential.db.Writer().Exec("DELETE FROM home_id_discoverable"); err != nil { |
| + t.Fatal(err) |
| + } |
| + gated := redeemAfterSignIn(t, p.credential, sealtest.CanaryAddress) |
| + if _, err := p.credential.db.Writer().Exec("UPDATE passkey_pending SET return_to='/passkey/codes'"); err != nil { |
| + t.Fatal(err) |
| + } |
| + private, err := x509.MarshalPKCS8PrivateKey(key.Key) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + actions := []chromedp.Action{webauthn.AddCredential(authenticator, &webauthn.Credential{CredentialID: base64.StdEncoding.EncodeToString(key.CredID), RpID: browserRP, PrivateKey: base64.StdEncoding.EncodeToString(private), IsResidentCredential: false})} |
| + for _, c := range gated.Result().Cookies() { |
| + if c.Value != "" { |
| + actions = append(actions, idBrowserCookie(c)) |
| + } |
| + } |
| + actions = append(actions, chromedp.Navigate(browserIssuer+confirmPath), chromedp.WaitVisible("#passkey-confirm"), chromedp.Click("#passkey-confirm"), chromedp.WaitVisible(`form[action="/passkey/codes"]`)) |
| + idBrowserRun(t, ctx, actions...) |
| +} |
| +func TestIDBrowserScriptlessCrossSiteReturn(t *testing.T) { |
| + p, ctx, _ := idBrowser(t) |
| + idBrowserRun(t, ctx, emulation.SetScriptExecutionDisabled(true), chromedp.Navigate(p.directory.origins.Directory+"/auth/start"), chromedp.WaitVisible("#address"), chromedp.SendKeys("#address", sealtest.CanaryAddress), chromedp.Click(`form[action="/signin"] button`), chromedp.WaitVisible(`a[href*="/signin"]`)) |
| + token := capturedLink(t, p.credential) |
| + idBrowserRun(t, ctx, chromedp.Navigate(browserIssuer+linkPath+"?token="+url.QueryEscape(token)), chromedp.WaitVisible(`form[action="/signin/verify"] button`), chromedp.Click(`form[action="/signin/verify"] button`), chromedp.WaitVisible(`form[action="/authorize/resume"] button`), chromedp.Click(`form[action="/authorize/resume"] button`), chromedp.WaitVisible(`form[data-assertion-handoff] button`), chromedp.Click(`form[data-assertion-handoff] button`), chromedp.WaitVisible(`[estilo-account]`)) |
| + var location string |
| + idBrowserRun(t, ctx, chromedp.Location(&location)) |
| + if !strings.HasPrefix(location, p.directory.origins.Directory+"/") { |
| + t.Fatal("cross-site finish lost browser binding") |
| + } |
| + sealtest.AssertNoPlaintext(t, p.credential.dbPath) |
| + sealtest.AssertNoPlaintext(t, p.directoryPath) |
| +} |
| + |
| +func TestIDBrowserSignoutBothOrigins(t *testing.T) { |
| + for _, consumer := range []string{"https://example.org", "https://directory.example.test"} { |
| + for _, scripts := range []bool{true, false} { |
| + t.Run(fmt.Sprintf("%s/scripts=%v", consumer, scripts), func(t *testing.T) { |
| + p, ctx, _ := idBrowserFor(t, consumer) |
| + credential := signInFully(t, p.credential, sealtest.CanaryAddress) |
| + w := httptest.NewRecorder() |
| + req := httptest.NewRequest("POST", consumer+"/", nil) |
| + if err := p.directory.sessions.SignIn(w, req, sessions.Session{Subject: subjectOf(t, p.credential, credential), Method: "assertion", AuthTime: time.Now()}); err != nil { |
| + t.Fatal(err) |
| + } |
| + directory := sessionCookie(w) |
| + if directory == nil { |
| + t.Fatal("missing directory session") |
| + } |
| + idBrowserRun(t, ctx, emulation.SetScriptExecutionDisabled(!scripts), idBrowserCookie(credential), network.SetCookie(directory.Name, directory.Value).WithURL(consumer+"/").WithHTTPOnly(true).WithSecure(true).WithSameSite(network.CookieSameSiteLax), chromedp.Navigate(consumer+"/"), chromedp.WaitVisible(`[estilo-account] > summary`), chromedp.Click(`[estilo-account] > summary`), chromedp.Click(`form[action="/signout"] button`)) |
| + if !scripts { |
| + idBrowserRun(t, ctx, chromedp.WaitVisible(`form[data-assertion-handoff] button`), chromedp.Click(`form[data-assertion-handoff] button`)) |
| + } |
| + |
| + if consumer == "https://directory.example.test" { |
| + // Lax cookies do not ride a cross-site POST. The same-origin fallback |
| + // button on ID must complete that second hop with the credential cookie. |
| + idBrowserRun(t, ctx, chromedp.WaitVisible(`form[rst-form][action="/signout"] button`), chromedp.Click(`form[rst-form][action="/signout"] button`)) |
| + } |
| + idBrowserRun(t, ctx, chromedp.WaitVisible(`a[rst-btn="primary"]`)) |
| + var rows int |
| + p.credential.db.Writer().QueryRow("SELECT count(*) FROM sessions").Scan(&rows) |
| + if rows != 0 { |
| + t.Fatal("browser signout retained ID session", rows) |
| + } |
| + p.directory.db.Writer().QueryRow("SELECT count(*) FROM sessions").Scan(&rows) |
| + if rows != 0 { |
| + t.Fatal("browser signout retained directory session", rows) |
| + } |
| + }) |
| + } |
| + } |
| +} |
diff --git a/internal/home/id_direct.go b/internal/home/id_direct.go| new file mode 100644 |
| index 0000000..7fc7be5 |
| --- /dev/null |
| +++ b/internal/home/id_direct.go |
| @@ -0,0 +1,68 @@ |
| +package home |
| + |
| +import ( |
| + "database/sql" |
| + "encoding/base64" |
| + "encoding/hex" |
| + "encoding/json" |
| + "net/http" |
| + "time" |
| + |
| + "amadan.net/rastrillo/rastrillo/webauthn" |
| +) |
| + |
| +type directChallenge struct { |
| + Challenge string `json:"challenge"` |
| + Expires int64 `json:"expires"` |
| +} |
| + |
| +// Anonymous begins allocate only a sealed browser cookie. Replay receipts are |
| +// written after WebAuthn verification, in the same transaction as session mint. |
| +func (a *App) idDirectBegin(w http.ResponseWriter, r *http.Request) { |
| + challenge, err := webauthn.NewChallenge() |
| + if err != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + plain, err := json.Marshal(directChallenge{hex.EncodeToString(challenge), time.Now().Unix() + 300}) |
| + if err != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + sealed, err := a.secrets.Sealer.Seal("id.direct", plain) |
| + if err != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + idCookie(w, ceremonyCookie, base64.RawURLEncoding.EncodeToString(sealed), 300) |
| + idJSONReply(w, 200, map[string]any{"challenge": base64.RawURLEncoding.EncodeToString(challenge)}) |
| +} |
| +func (a *App) idDirectProof(r *http.Request, challenge []byte, now int64) (int64, error) { |
| + value := cookieValue(r, ceremonyCookie) |
| + sealed, err := base64.RawURLEncoding.Strict().DecodeString(value) |
| + if err != nil { |
| + return 0, errIDProof |
| + } |
| + plain, err := a.secrets.Sealer.Open("id.direct", sealed) |
| + if err != nil { |
| + return 0, errIDProof |
| + } |
| + var proof directChallenge |
| + if json.Unmarshal(plain, &proof) != nil || proof.Challenge != hex.EncodeToString(challenge) || proof.Expires <= now || proof.Expires > now+300 { |
| + return 0, errIDProof |
| + } |
| + return proof.Expires, nil |
| +} |
| +func consumeDirect(tx *sql.Tx, challenge []byte, expires, now int64) error { |
| + if _, err := tx.Exec("DELETE FROM home_id_direct_used WHERE expires_at<=?", now); err != nil { |
| + return errIDProof |
| + } |
| + var n int |
| + if tx.QueryRow("SELECT count(*) FROM home_id_direct_used").Scan(&n) != nil || n >= 10000 { |
| + return errIDProof |
| + } |
| + if _, err := tx.Exec("INSERT INTO home_id_direct_used VALUES(?,?)", hex.EncodeToString(challenge), expires); err != nil { |
| + return errIDProof |
| + } |
| + return nil |
| +} |
diff --git a/internal/home/id_exchange_test.go b/internal/home/id_exchange_test.go| new file mode 100644 |
| index 0000000..f201db2 |
| --- /dev/null |
| +++ b/internal/home/id_exchange_test.go |
| @@ -0,0 +1,186 @@ |
| +package home |
| + |
| +import ( |
| + "amadan.net/rastrillo/rastrillo/assertion" |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| + "encoding/base64" |
| + "encoding/json" |
| + "github.com/keymaildev/signin" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/home/internal/home/sealtest" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| +) |
| + |
| +func TestIDLinkAlwaysRequiresNewGesture(t *testing.T) { |
| + p := newExchangePair(t) |
| + session := signInFully(t, p.credential, sealtest.CanaryAddress) |
| + _, intent := p.startFresh(t, session) |
| + for _, method := range []string{"GET", "POST"} { |
| + r := exchangeRequest(p.credential.App, method, Origin+"/authorize/resume", Origin, nil, intent, session) |
| + if r.Code != http.StatusSeeOther || !strings.HasPrefix(r.Header().Get("Location"), "/signin?") { |
| + t.Fatalf("%s reused existing session: %d", method, r.Code) |
| + } |
| + } |
| +} |
| + |
| +func TestIDContinueBeforeMinting(t *testing.T) { |
| + p := newExchangePair(t) |
| + session := signInFully(t, p.credential, sealtest.CanaryAddress) |
| + _, intent := p.start(t) |
| + r := exchangeRequest(p.credential.App, "GET", Origin+"/authorize/resume", "", nil, intent, session) |
| + if r.Code != 200 || strings.Contains(r.Body.String(), `name="assertion"`) || !strings.Contains(r.Body.String(), `action="/authorize/resume"`) { |
| + t.Fatal("GET did not stop at Continue", r.Code) |
| + } |
| + bad := exchangeRequest(p.credential.App, "POST", Origin+"/authorize/resume", "https://evil.invalid", url.Values{}, intent, session) |
| + if bad.Code != 403 { |
| + t.Fatal("Continue lacks CSRF protection", bad.Code) |
| + } |
| + good := exchangeRequest(p.credential.App, "POST", Origin+"/authorize/resume", Origin, url.Values{}, intent, session) |
| + if good.Code != 200 || !strings.Contains(good.Body.String(), `name="assertion"`) { |
| + t.Fatal("Continue did not mint", good.Code) |
| + } |
| +} |
| + |
| +func TestIDRevokedCachedSessionCannotMint(t *testing.T) { |
| + p := newExchangePair(t) |
| + s := signInFully(t, p.credential, sealtest.CanaryAddress) |
| + _, intent := p.start(t) |
| + r := httptest.NewRequest("POST", Origin+"/authorize/resume", nil) |
| + r.AddCookie(s) |
| + r.AddCookie(intent) |
| + w := httptest.NewRecorder() |
| + p.credential.sessions.Require(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if _, err := p.credential.db.Writer().Exec("DELETE FROM sessions"); err != nil { |
| + t.Fatal(err) |
| + } |
| + p.credential.handleAssertion(w, r) |
| + })).ServeHTTP(w, r) |
| + if strings.Contains(w.Body.String(), `name="assertion"`) { |
| + t.Fatal("cached revoked session minted an assertion") |
| + } |
| +} |
| + |
| +func TestIDLegacyRuntimeAppliesIdentitySchema(t *testing.T) { |
| + d, err := migrate.Replay(t.Context(), (Runtime{}).ServingSchema().All()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer d.Close() |
| + if _, err = d.Exec("UPDATE home_id_clock SET high_water=1 WHERE id=1"); err != nil { |
| + t.Fatal("legacy runtime cannot serve identity handlers", err) |
| + } |
| + a := newTestApp(t) |
| + signInFully(t, a, sealtest.CanaryAddress) |
| +} |
| + |
| +func TestIDLinkRejectsProofBeforeTransactionStart(t *testing.T) { |
| + p := newExchangePair(t) |
| + old := signInFully(t, p.credential, sealtest.CanaryAddress) |
| + _, intent := p.startFresh(t, old) |
| + current := signInFully(t, p.credential, sealtest.CanaryAddress) |
| + if _, err := p.credential.db.Writer().Exec("UPDATE sessions SET auth_time=? WHERE token_hash=?", time.Now().Add(-30*time.Second).UTC().Format(time.RFC3339), sessions.HashToken(current.Value)); err != nil { |
| + t.Fatal(err) |
| + } |
| + r := exchangeRequest(p.credential.App, "POST", Origin+"/authorize/resume", Origin, nil, intent, current) |
| + if r.Code != 303 || !strings.HasPrefix(r.Header().Get("Location"), "/signin?") { |
| + t.Fatal("otherwise fresh proof predating link start was accepted") |
| + } |
| +} |
| + |
| +func TestIDLinkRejectsPassiveMintedSession(t *testing.T) { |
| + p := newExchangePair(t) |
| + _, intent := p.startFresh(t, nil) |
| + s := signInFully(t, p.credential, sealtest.CanaryAddress) |
| + p.credential.db.Writer().Exec("UPDATE sessions SET method='keymail',auth_time=''") |
| + r := exchangeRequest(p.credential.App, "POST", Origin+"/authorize/resume", Origin, nil, intent, s) |
| + if r.Code != 303 { |
| + t.Fatal("passive newly minted session satisfied linking") |
| + } |
| +} |
| + |
| +func TestIDClosedAuthorize(t *testing.T) { |
| + p := newExchangePair(t) |
| + nonce, _ := assertion.RandomID() |
| + base := "consumer=directory&nonce=" + nonce |
| + for _, query := range []string{base + "&consumer=directory", base + "&nonce=" + nonce, base + "&unexpected=1", "consumer=unknown&nonce=" + nonce, "consumer=directory&nonce=bad", base + "&max_age=301", base + "&max_age=300&max_age=300"} { |
| + r := exchangeRequest(p.credential.App, "GET", Origin+"/authorize?"+query, "", nil) |
| + if r.Code != 400 || len(r.Result().Cookies()) != 0 { |
| + t.Fatal("ambiguous authorize accepted") |
| + } |
| + } |
| +} |
| +func TestIDAllSensitivePostsRequireOrigin(t *testing.T) { |
| + p := newExchangePair(t) |
| + for _, path := range []string{"/authorize/resume", "/passkey/direct/begin", "/passkey/direct/finish", "/passkey/register/begin", "/passkey/register/finish", "/passkey/signin/begin", "/passkey/signin/finish", "/passkey/signin/recovery", "/passkey/replace/begin", "/passkey/replace/finish", "/passkey/codes", "/passkey/notice"} { |
| + r := exchangeRequest(p.credential.App, "POST", Origin+path, "https://evil.invalid", url.Values{}) |
| + if r.Code != 403 { |
| + t.Fatal("cross-origin mutation admitted", path, r.Code) |
| + } |
| + } |
| +} |
| + |
| +func TestIDEmailMintPreservesVerificationTime(t *testing.T) { |
| + a := newTestApp(t) |
| + verified := time.Now().Add(-2 * time.Minute).UTC().Truncate(time.Second) |
| + r := httptest.NewRequest("POST", Origin+linkPath, nil) |
| + w := httptest.NewRecorder() |
| + a.completeSignIn(w, r, signin.Identity{Address: sealtest.CanaryAddress, Method: signin.MethodMagicLink, At: verified}) |
| + c := sessionCookie(w) |
| + if c == nil { |
| + t.Fatal("email completion failed") |
| + } |
| + r.AddCookie(c) |
| + s, ok := a.sessions.From(r) |
| + if !ok || !s.AuthTime.Equal(verified) { |
| + t.Fatal("email verification time was replaced with mint time") |
| + } |
| +} |
| + |
| +func TestIDFreshIntentRequiresStartTime(t *testing.T) { |
| + p := newExchangePair(t) |
| + _, cookie := p.startFresh(t, nil) |
| + req := httptest.NewRequest("GET", Origin+"/authorize/resume", nil) |
| + req.AddCookie(cookie) |
| + intent, ok := p.credential.readAssertionIntent(req, time.Now()) |
| + if !ok { |
| + t.Fatal("fixture intent") |
| + } |
| + intent.Started = 0 |
| + raw, _ := json.Marshal(intent) |
| + sealed, err := p.credential.secrets.Sealer.Seal("assertion.intent", raw) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cookie.Value = base64.RawURLEncoding.EncodeToString(sealed) |
| + session := signInFully(t, p.credential, sealtest.CanaryAddress) |
| + r := exchangeRequest(p.credential.App, "POST", Origin+"/authorize/resume", Origin, nil, cookie, session) |
| + if r.Code != 400 { |
| + t.Fatal("old freshness intent without transaction start was accepted", r.Code) |
| + } |
| +} |
| + |
| +func TestIDEmailInAnotherBrowserCannotFinishOriginalHandoff(t *testing.T) { |
| + p := newExchangePair(t) |
| + _, intent := p.start(t) |
| + form := exchangeRequest(p.credential.App, "GET", Origin+"/signin?return_to=%2Fauthorize%2Fresume", "", nil, intent) |
| + navigation := namedCookie(t, form, returnCookie) |
| + exchangeRequest(p.credential.App, "POST", Origin+"/signin", Origin, url.Values{"address": {sealtest.CanaryAddress}}, intent, navigation) |
| + other := redeem(t, p.credential, capturedLink(t, p.credential)) |
| + if sessionCookie(other) == nil || other.Header().Get("Location") != "/" { |
| + t.Fatal("other browser inherited original handoff") |
| + } |
| + original := exchangeRequest(p.credential.App, "GET", Origin+"/authorize/resume", "", nil, intent, navigation) |
| + if original.Code != 303 || !strings.HasPrefix(original.Header().Get("Location"), "/signin") { |
| + t.Fatal("original browser acquired another browser's authentication") |
| + } |
| + var n int |
| + if err := p.directory.db.Writer().QueryRow("SELECT count(*) FROM sessions").Scan(&n); err != nil || n != 0 { |
| + t.Fatal("other-browser email minted an app session") |
| + } |
| +} |
diff --git a/internal/home/id_limiter.go b/internal/home/id_limiter.go| new file mode 100644 |
| index 0000000..b424a29 |
| --- /dev/null |
| +++ b/internal/home/id_limiter.go |
| @@ -0,0 +1,24 @@ |
| +package home |
| + |
| +import ( |
| + "context" |
| + "strings" |
| + "time" |
| + |
| + "github.com/keymaildev/signin" |
| +) |
| + |
| +// Keep Flow's address budget without retaining its readable key. IP keys stay |
| +// shared with /resolve's budget. The upstream blind-auth-store adapter can use |
| +// this same Limiter seam without changing the stored person identity. |
| +type blindSigninLimiter struct { |
| + next signin.Limiter |
| + pepper []byte |
| +} |
| + |
| +func (l blindSigninLimiter) Allow(ctx context.Context, key string, now time.Time, budget int) (bool, error) { |
| + if address, ok := strings.CutPrefix(key, "addr:"); ok { |
| + key = "addr:" + blindIndex(l.pepper, address) |
| + } |
| + return l.next.Allow(ctx, key, now, budget) |
| +} |
diff --git a/internal/home/id_passkey.go b/internal/home/id_passkey.go| new file mode 100644 |
| index 0000000..634d06f |
| --- /dev/null |
| +++ b/internal/home/id_passkey.go |
| @@ -0,0 +1,418 @@ |
| +package home |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "encoding/base64" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "net/http" |
| + "strings" |
| + "time" |
| + |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| + "amadan.net/rastrillo/rastrillo/webauthn" |
| + strictjson "github.com/go-json-experiment/json" |
| +) |
| + |
| +const ceremonyCookie = "__Host-oficina-ceremony" |
| +const gateCookie = "__Host-rastrillo_passkey_pending" |
| + |
| +var errIDProof = errors.New("home: identity proof refused") |
| + |
| +func idCookie(w http.ResponseWriter, name, value string, seconds int) { |
| + http.SetCookie(w, &http.Cookie{Name: name, Value: value, Path: "/", MaxAge: seconds, Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode}) |
| +} |
| +func cookieValue(r *http.Request, name string) string { |
| + value := "" |
| + count := 0 |
| + for _, c := range r.Cookies() { |
| + if c.Name == name { |
| + value = c.Value |
| + count++ |
| + } |
| + } |
| + if count != 1 || len(value) > 4096 { |
| + return "" |
| + } |
| + return value |
| +} |
| +func idJSONReply(w http.ResponseWriter, status int, v any) { |
| + w.Header().Set("Cache-Control", "no-store") |
| + w.Header().Set("Content-Type", "application/json") |
| + w.WriteHeader(status) |
| + _ = json.NewEncoder(w).Encode(v) |
| +} |
| +func idRefuse(w http.ResponseWriter) { |
| + idJSONReply(w, http.StatusBadRequest, map[string]string{"error": "ceremony failed"}) |
| +} |
| +func (a *App) idTransaction(ctx context.Context) (*sql.Tx, int64, error) { |
| + tx, err := a.db.Writer().BeginTx(ctx, nil) |
| + if err != nil { |
| + return nil, 0, errIDProof |
| + } |
| + now := time.Now().Unix() |
| + if _, err = tx.ExecContext(ctx, "UPDATE home_id_clock SET high_water=MAX(high_water,?) WHERE id=1", now); err != nil { |
| + tx.Rollback() |
| + return nil, 0, errIDProof |
| + } |
| + var high int64 |
| + if err = tx.QueryRowContext(ctx, "SELECT high_water FROM home_id_clock WHERE id=1").Scan(&high); err != nil || now < high { |
| + tx.Rollback() |
| + return nil, 0, errIDProof |
| + } |
| + return tx, high, nil |
| +} |
| + |
| +func (a *App) idWebAuthn() webauthn.Config { |
| + return webauthn.Config{RPID: a.credentialHost, Origin: a.origins.Credential, LegacyRPID: a.passkeyCfg.LegacyRPID} |
| +} |
| + |
| +// Read the live session inside the writer transaction, so recovery revocation |
| +// and a simultaneous enrollment or session mint cannot pass one another. |
| +func (a *App) idSession(tx *sql.Tx, r *http.Request, now int64) (sessions.Session, string, error) { |
| + token := cookieValue(r, a.sessions.CookieName()) |
| + if token == "" { |
| + return sessions.Session{}, "", errIDProof |
| + } |
| + hash := sessions.HashToken(token) |
| + var s sessions.Session |
| + var auth, created, expires string |
| + err := tx.QueryRow("SELECT subject,method,auth_time,created_at,expires_at FROM sessions WHERE token_hash=?", hash).Scan(&s.Subject, &s.Method, &auth, &created, &expires) |
| + exp, e := time.Parse(time.RFC3339, expires) |
| + if err != nil || e != nil || exp.Unix() <= now { |
| + return s, "", errIDProof |
| + } |
| + s.AuthTime, _ = time.Parse(time.RFC3339, auth) |
| + s.At, _ = time.Parse(time.RFC3339, created) |
| + return s, hash, nil |
| +} |
| +func idFreshSession(s sessions.Session, age time.Duration, now time.Time) bool { |
| + at := s.AuthTime |
| + if at.IsZero() { |
| + at = s.At |
| + } |
| + return !keymailWithoutGesture(s) && !at.After(now) && sessions.Fresh(s, age, now) |
| +} |
| + |
| +func (a *App) idBinding(tx *sql.Tx, r *http.Request, purpose string, now int64) (subject, binding string, err error) { |
| + switch purpose { |
| + case "replace": |
| + return a.replacementBinding(tx, r, now) |
| + case "direct": |
| + v := cookieValue(r, ceremonyCookie) |
| + if v == "" { |
| + return "", "", errIDProof |
| + } |
| + return "", sessions.HashToken(v), nil |
| + case "signin": |
| + v := cookieValue(r, gateCookie) |
| + if v == "" { |
| + return "", "", errIDProof |
| + } |
| + binding = sessions.HashToken(v) |
| + var exp string |
| + err = tx.QueryRow("SELECT subject,expires_at FROM passkey_pending WHERE token_hash=?", binding).Scan(&subject, &exp) |
| + at, e := time.Parse(time.RFC3339, exp) |
| + if err != nil || e != nil || at.Unix() <= now { |
| + return "", "", errIDProof |
| + } |
| + return subject, binding, nil |
| + default: |
| + s, hash, e := a.idSession(tx, r, now) |
| + if e != nil { |
| + return "", "", e |
| + } |
| + if purpose == "register" && (!idFreshSession(s, enrolFreshness, time.Unix(now, 0)) || strings.Contains(s.Method, "recovery")) { |
| + return "", "", errIDProof |
| + } |
| + return s.Subject, hash, nil |
| + } |
| +} |
| +func (a *App) idBegin(purpose string) http.HandlerFunc { |
| + return func(w http.ResponseWriter, r *http.Request) { |
| + if purpose == "direct" { |
| + a.idDirectBegin(w, r) |
| + return |
| + } |
| + tx, now, err := a.idTransaction(r.Context()) |
| + if err != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + defer tx.Rollback() |
| + subject, binding, err := a.idBinding(tx, r, purpose, now) |
| + if err != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + if _, err = tx.Exec("DELETE FROM home_id_ceremonies WHERE expires_at<=? OR (browser_hash=? AND purpose=?)", now, binding, purpose); err != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + var n int |
| + if err = tx.QueryRow("SELECT count(*) FROM home_id_ceremonies").Scan(&n); err != nil || n >= 10000 { |
| + idRefuse(w) |
| + return |
| + } |
| + challenge, err := webauthn.NewChallenge() |
| + if err != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + if _, err = tx.Exec("INSERT INTO home_id_ceremonies VALUES (?,?,?,?,?)", hex.EncodeToString(challenge), binding, subject, purpose, now+300); err != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + var credentials []string |
| + if purpose == "signin" || purpose == "stepup" { |
| + rows, e := tx.Query("SELECT id FROM passkey_credentials WHERE subject=? ORDER BY id LIMIT 101", subject) |
| + if e != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + for rows.Next() { |
| + var id string |
| + if rows.Scan(&id) != nil { |
| + rows.Close() |
| + idRefuse(w) |
| + return |
| + } |
| + raw, e := hex.DecodeString(id) |
| + if e != nil { |
| + rows.Close() |
| + idRefuse(w) |
| + return |
| + } |
| + credentials = append(credentials, base64.RawURLEncoding.EncodeToString(raw)) |
| + } |
| + e = rows.Err() |
| + rows.Close() |
| + if len(credentials) > 100 { |
| + idRefuse(w) |
| + return |
| + } |
| + if e != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + } |
| + if err = tx.Commit(); err != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + idJSONReply(w, 200, map[string]any{"challenge": base64.RawURLEncoding.EncodeToString(challenge), "credentials": credentials}) |
| + } |
| +} |
| + |
| +type idCeremony struct { |
| + ID string `json:"id"` |
| + ClientData string `json:"clientDataJSON"` |
| + AuthData string `json:"authenticatorData"` |
| + Signature string `json:"signature"` |
| + Attestation string `json:"attestationObject"` |
| +} |
| + |
| +func decodeIDCeremony(w http.ResponseWriter, r *http.Request) (idCeremony, []byte, []byte, error) { |
| + var body idCeremony |
| + if strictjson.UnmarshalRead(http.MaxBytesReader(w, r.Body, 64<<10), &body, strictjson.RejectUnknownMembers(true)) != nil { |
| + return body, nil, nil, errIDProof |
| + } |
| + cd, err := base64.RawURLEncoding.Strict().DecodeString(body.ClientData) |
| + if err != nil { |
| + return body, nil, nil, errIDProof |
| + } |
| + var c struct { |
| + Challenge string `json:"challenge"` |
| + } |
| + if json.Unmarshal(cd, &c) != nil { |
| + return body, nil, nil, errIDProof |
| + } |
| + challenge, err := base64.RawURLEncoding.Strict().DecodeString(c.Challenge) |
| + if err != nil || len(challenge) != 32 { |
| + return body, nil, nil, errIDProof |
| + } |
| + return body, cd, challenge, nil |
| +} |
| + |
| +// This is the narrow storage adapter to replace when upstream auth can supply |
| +// address-blind storage AND transaction-owned session minting. Keep the proof |
| +// consumption, live credential check and session write on this same writer. |
| +func (a *App) idMint(tx *sql.Tx, r *http.Request, s sessions.Session, now int64) (string, error) { |
| + token, hash, err := sessions.NewToken() |
| + if err != nil { |
| + return "", errIDProof |
| + } |
| + stamp := time.Unix(now, 0).UTC().Format(time.RFC3339) |
| + auth := "" |
| + if !s.AuthTime.IsZero() { |
| + auth = s.AuthTime.UTC().Format(time.RFC3339) |
| + } |
| + if old := cookieValue(r, a.sessions.CookieName()); old != "" { |
| + if _, err = tx.Exec("DELETE FROM sessions WHERE token_hash=?", sessions.HashToken(old)); err != nil { |
| + return "", errIDProof |
| + } |
| + } |
| + _, err = tx.Exec("INSERT INTO sessions(token_hash,subject,method,auth_time,created_at,expires_at) VALUES(?,?,?,?,?,?)", hash, s.Subject, s.Method, auth, stamp, time.Unix(now, 0).Add(30*24*time.Hour).UTC().Format(time.RFC3339)) |
| + if err != nil { |
| + return "", errIDProof |
| + } |
| + return token, nil |
| +} |
| +func (a *App) idFinish(purpose string) http.HandlerFunc { |
| + return func(w http.ResponseWriter, r *http.Request) { |
| + body, cd, challenge, err := decodeIDCeremony(w, r) |
| + if err != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + tx, now, err := a.idTransaction(r.Context()) |
| + if err != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + defer tx.Rollback() |
| + subject, binding, err := a.idBinding(tx, r, purpose, now) |
| + if err != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + var directExpires int64 |
| + if purpose == "direct" { |
| + directExpires, err = a.idDirectProof(r, challenge, now) |
| + if err != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + } else { |
| + var consumed string |
| + err = tx.QueryRow("DELETE FROM home_id_ceremonies WHERE challenge=? AND browser_hash=? AND subject=? AND purpose=? AND expires_at>? RETURNING challenge", hex.EncodeToString(challenge), binding, subject, purpose, now).Scan(&consumed) |
| + if err != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + |
| + } |
| + refuse := func() { _ = tx.Commit(); idRefuse(w) } |
| + if purpose == "register" || purpose == "replace" { |
| + att, e := base64.RawURLEncoding.Strict().DecodeString(body.Attestation) |
| + if e != nil { |
| + refuse() |
| + return |
| + } |
| + cred, e := a.idWebAuthn().Register(challenge, cd, att) |
| + if e != nil { |
| + refuse() |
| + return |
| + } |
| + if purpose == "replace" { |
| + if a.replaceCredential(tx, r, subject, cred, now) != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + if tx.Commit() != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + idCookie(w, a.sessions.CookieName(), "", -1) |
| + idCookie(w, recoveryCookie, "", -1) |
| + idCookie(w, noticeCookie, cookieValue(r, recoveryCookie), 300) |
| + a.replacementResult(w, !a.sendReplacementNotice(r.Context(), binding)) |
| + idJSONReply(w, 200, map[string]any{"ok": true, "to": "/passkey/replaced"}) |
| + return |
| + } |
| + var count int |
| + if tx.QueryRow("SELECT count(*) FROM passkey_credentials WHERE subject=?", subject).Scan(&count) != nil || count >= 100 { |
| + idRefuse(w) |
| + return |
| + } |
| + id := hex.EncodeToString(cred.ID) |
| + if _, e = tx.Exec("INSERT INTO passkey_credentials(id,subject,public_key,sign_count,created_at) VALUES(?,?,?,?,?)", id, subject, cred.PublicKey, cred.SignCount, time.Unix(now, 0).UTC().Format(time.RFC3339)); e != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + if _, e = tx.Exec("INSERT INTO home_id_discoverable VALUES(?)", id); e != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + if tx.Commit() != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + idJSONReply(w, 200, map[string]bool{"ok": true}) |
| + return |
| + } |
| + id, e := base64.RawURLEncoding.Strict().DecodeString(body.ID) |
| + if e != nil { |
| + refuse() |
| + return |
| + } |
| + ad, e := base64.RawURLEncoding.Strict().DecodeString(body.AuthData) |
| + if e != nil { |
| + refuse() |
| + return |
| + } |
| + sig, e := base64.RawURLEncoding.Strict().DecodeString(body.Signature) |
| + if e != nil { |
| + refuse() |
| + return |
| + } |
| + var owner string |
| + var cred webauthn.Credential |
| + cred.ID = id |
| + query := "SELECT subject,public_key,sign_count FROM passkey_credentials WHERE id=?" |
| + if purpose == "direct" { |
| + query += " AND id IN (SELECT credential_id FROM home_id_discoverable)" |
| + } |
| + if e = tx.QueryRow(query, hex.EncodeToString(id)).Scan(&owner, &cred.PublicKey, &cred.SignCount); e != nil || (subject != "" && owner != subject) { |
| + refuse() |
| + return |
| + } |
| + next, e := a.idWebAuthn().Verify(cred, challenge, cd, ad, sig) |
| + if e != nil { |
| + refuse() |
| + return |
| + } |
| + if purpose == "direct" && consumeDirect(tx, challenge, directExpires, now) != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + if _, e = tx.Exec("UPDATE passkey_credentials SET sign_count=? WHERE id=?", next, hex.EncodeToString(id)); e != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + method, to := "passkey", readReturn(r) |
| + if purpose == "signin" { |
| + if e = tx.QueryRow("DELETE FROM passkey_pending WHERE token_hash=? RETURNING method,return_to", binding).Scan(&method, &to); e != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + method += "+passkey" |
| + } |
| + var codes int |
| + if tx.QueryRow("SELECT count(*) FROM passkey_recovery_codes WHERE subject=?", owner).Scan(&codes) != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + if codes == 0 { |
| + to = "/passkey/codes" |
| + } |
| + token, e := a.idMint(tx, r, sessions.Session{Subject: owner, Method: method, AuthTime: time.Unix(now, 0)}, now) |
| + if e != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + if e = tx.Commit(); e != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + idCookie(w, a.sessions.CookieName(), token, 30*24*3600) |
| + idCookie(w, ceremonyCookie, "", -1) |
| + if purpose == "signin" { |
| + idCookie(w, gateCookie, "", -1) |
| + } |
| + writeReturn(w, "/") |
| + idJSONReply(w, 200, map[string]any{"ok": true, "to": to}) |
| + } |
| +} |
diff --git a/internal/home/id_passkey_test.go b/internal/home/id_passkey_test.go| new file mode 100644 |
| index 0000000..1b74412 |
| --- /dev/null |
| +++ b/internal/home/id_passkey_test.go |
| @@ -0,0 +1,321 @@ |
| +package home |
| + |
| +import ( |
| + "encoding/base64" |
| + "encoding/json" |
| + "fmt" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/home/internal/home/sealtest" |
| + "amadan.net/rastrillo/rastrillo/webauthn/authtest" |
| +) |
| + |
| +func idJSON(t *testing.T, app *testApp, path string, body any, cookies ...*http.Cookie) *httptest.ResponseRecorder { |
| + t.Helper() |
| + b, err := json.Marshal(body) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + req := httptest.NewRequest("POST", app.origins.Credential+path, strings.NewReader(string(b))) |
| + req.Header.Set("Origin", app.origins.Credential) |
| + req.Header.Set("Content-Type", "application/json") |
| + for _, c := range cookies { |
| + if c != nil { |
| + req.AddCookie(c) |
| + } |
| + } |
| + w := httptest.NewRecorder() |
| + app.Router().ServeHTTP(w, req) |
| + return w |
| +} |
| +func assertionBody(a *authtest.Authenticator, challenge []byte, opts authtest.Options) map[string]string { |
| + cd, ad, sig, _ := a.Get(challenge, opts) |
| + return map[string]string{"id": base64.RawURLEncoding.EncodeToString(a.CredID), "clientDataJSON": base64.RawURLEncoding.EncodeToString(cd), "authenticatorData": base64.RawURLEncoding.EncodeToString(ad), "signature": base64.RawURLEncoding.EncodeToString(sig)} |
| +} |
| +func TestIDDirectPasskey(t *testing.T) { |
| + app := newTestApp(t) |
| + session := signInFully(t, app, sealtest.CanaryAddress) |
| + key := enrol(t, app, session) |
| + begin := idJSON(t, app, "/passkey/direct/begin", nil) |
| + challenge := challengeFrom(t, begin) |
| + cookie := namedCookie(t, begin, "__Host-oficina-ceremony") |
| + zero := uint32(0) |
| + body := assertionBody(key, challenge, authtest.Options{RPID: credentialHost, Origin: Origin, Count: &zero}) |
| + wrong := idJSON(t, app, "/passkey/direct/finish", body) |
| + if sessionCookie(wrong) != nil || wrong.Code == 200 { |
| + t.Fatal("unbound browser signed in") |
| + } |
| + done := idJSON(t, app, "/passkey/direct/finish", body, cookie) |
| + if done.Code != 200 || sessionCookie(done) == nil { |
| + t.Fatal("direct sign-in failed", done.Code) |
| + } |
| + if subjectOf(t, app, sessionCookie(done)) != subjectOf(t, app, session) { |
| + t.Fatal("wrong person") |
| + } |
| + replay := idJSON(t, app, "/passkey/direct/finish", body, cookie) |
| + if sessionCookie(replay) != nil || replay.Code == 200 { |
| + t.Fatal("replay signed in") |
| + } |
| + sealtest.AssertNoPlaintext(t, app.dbPath) |
| +} |
| +func TestIDPasskeyRejectsBadProofs(t *testing.T) { |
| + for _, kind := range []string{"origin", "rp", "uv", "signature", "unknown"} { |
| + t.Run(kind, func(t *testing.T) { |
| + app := newTestApp(t) |
| + s := signInFully(t, app, sealtest.CanaryAddress) |
| + key := enrol(t, app, s) |
| + begin := idJSON(t, app, "/passkey/direct/begin", nil) |
| + challenge := challengeFrom(t, begin) |
| + c := namedCookie(t, begin, "__Host-oficina-ceremony") |
| + opts := authtest.Options{RPID: credentialHost, Origin: Origin} |
| + switch kind { |
| + case "origin": |
| + opts.Origin = "https://evil.invalid" |
| + case "rp": |
| + opts.RPID = "oficina.works" |
| + case "uv": |
| + opts.Flags = authtest.FlagUserPresent |
| + case "signature": |
| + opts.CorruptSig = true |
| + case "unknown": |
| + key, _ = authtest.New() |
| + |
| + } |
| + r := idJSON(t, app, "/passkey/direct/finish", assertionBody(key, challenge, opts), c) |
| + if r.Code == 200 || sessionCookie(r) != nil { |
| + t.Fatal("bad proof signed in", kind) |
| + } |
| + }) |
| + } |
| +} |
| +func TestIDEnrollmentCannotTransferCredential(t *testing.T) { |
| + app := newTestApp(t) |
| + first := signInFully(t, app, sealtest.CanaryAddress) |
| + key := enrol(t, app, first) |
| + second := signInFully(t, app, "other@example.invalid") |
| + challenge := challengeFrom(t, idJSON(t, app, "/passkey/register/begin", nil, second)) |
| + cd, att := key.Create(challenge, authtest.Options{RPID: credentialHost, Origin: Origin}) |
| + got := idJSON(t, app, "/passkey/register/finish", map[string]string{"clientDataJSON": base64.RawURLEncoding.EncodeToString(cd), "attestationObject": base64.RawURLEncoding.EncodeToString(att)}, second) |
| + if got.Code == 200 { |
| + t.Fatal("credential transferred to another person") |
| + } |
| +} |
| + |
| +func TestIDGateOffersBoundLegacyCredentials(t *testing.T) { |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + key := enrol(t, a, s) |
| + if _, err := a.db.Writer().Exec("DELETE FROM home_id_discoverable"); err != nil { |
| + t.Fatal(err) |
| + } |
| + gated := redeemAfterSignIn(t, a, sealtest.CanaryAddress) |
| + begin := idJSON(t, a, "/passkey/signin/begin", nil, gated.Result().Cookies()...) |
| + var body struct { |
| + Credentials []string `json:"credentials"` |
| + } |
| + json.Unmarshal(begin.Body.Bytes(), &body) |
| + if len(body.Credentials) != 1 || body.Credentials[0] != base64.RawURLEncoding.EncodeToString(key.CredID) { |
| + t.Fatal("legacy gate omitted bound credential IDs") |
| + } |
| + r := idJSON(t, a, "/passkey/signin/finish", assertionBody(key, challengeFrom(t, begin), authtest.Options{RPID: credentialHost, Origin: Origin}), gated.Result().Cookies()...) |
| + if r.Code != 200 { |
| + t.Fatal("legacy gated signin failed", r.Code) |
| + } |
| +} |
| + |
| +func TestIDCeremonyRejectsAmbiguousJSON(t *testing.T) { |
| + for _, kind := range []string{"trailing", "duplicate"} { |
| + t.Run(kind, func(t *testing.T) { |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + key := enrol(t, a, s) |
| + begin := idJSON(t, a, "/passkey/direct/begin", nil) |
| + cookie := namedCookie(t, begin, ceremonyCookie) |
| + body := assertionBody(key, challengeFrom(t, begin), authtest.Options{RPID: credentialHost, Origin: Origin}) |
| + b, _ := json.Marshal(body) |
| + if kind == "trailing" { |
| + b = append(b, []byte(` {}`)...) |
| + } else { |
| + b = append([]byte(`{"id":"ignored",`), b[1:]...) |
| + } |
| + req := httptest.NewRequest("POST", Origin+"/passkey/direct/finish", strings.NewReader(string(b))) |
| + req.Header.Set("Origin", Origin) |
| + req.AddCookie(cookie) |
| + w := httptest.NewRecorder() |
| + a.Router().ServeHTTP(w, req) |
| + if w.Code == 200 || sessionCookie(w) != nil { |
| + t.Fatal("ambiguous ceremony JSON accepted") |
| + } |
| + }) |
| + } |
| +} |
| +func TestIDEnrollmentBound(t *testing.T) { |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + key := enrol(t, a, s) |
| + subject := subjectOf(t, a, s) |
| + for i := 0; i < 99; i++ { |
| + if _, err := a.db.Writer().Exec("INSERT INTO passkey_credentials(id,subject,public_key,sign_count,created_at) VALUES(?,?,?,0,'2026-11-13')", fmt.Sprintf("%064x", i), subject, key.COSEKey()); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + begin := idJSON(t, a, "/passkey/register/begin", nil, s) |
| + next, _ := authtest.New() |
| + cd, att := next.Create(challengeFrom(t, begin), authtest.Options{RPID: credentialHost, Origin: Origin}) |
| + r := idJSON(t, a, "/passkey/register/finish", map[string]string{"clientDataJSON": base64.RawURLEncoding.EncodeToString(cd), "attestationObject": base64.RawURLEncoding.EncodeToString(att)}, s) |
| + if r.Code == 200 { |
| + t.Fatal("enrollment exceeded the gated allowlist bound") |
| + } |
| +} |
| + |
| +func TestIDEnrollmentRejectsFutureAndPassiveAuthentication(t *testing.T) { |
| + for _, kind := range []string{"future", "passive"} { |
| + t.Run(kind, func(t *testing.T) { |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + query := "UPDATE sessions SET auth_time=?" |
| + value := time.Now().Add(time.Hour).UTC().Format(time.RFC3339) |
| + if kind == "passive" { |
| + query = "UPDATE sessions SET auth_time=?,method='keymail'" |
| + value = "" |
| + } |
| + if _, err := a.db.Writer().Exec(query, value); err != nil { |
| + t.Fatal(err) |
| + } |
| + if r := idJSON(t, a, "/passkey/register/begin", nil, s); r.Code == 200 { |
| + t.Fatal("enrollment accepted non-fresh authentication", kind) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestIDGateBindsCredentialOwner(t *testing.T) { |
| + a := newTestApp(t) |
| + first := signInFully(t, a, sealtest.CanaryAddress) |
| + enrol(t, a, first) |
| + second := signInFully(t, a, "other@example.invalid") |
| + key := enrol(t, a, second) |
| + gated := redeemAfterSignIn(t, a, sealtest.CanaryAddress) |
| + begin := idJSON(t, a, "/passkey/signin/begin", nil, gated.Result().Cookies()...) |
| + r := idJSON(t, a, "/passkey/signin/finish", assertionBody(key, challengeFrom(t, begin), authtest.Options{RPID: credentialHost, Origin: Origin}), gated.Result().Cookies()...) |
| + if r.Code == 200 || sessionCookie(r) != nil { |
| + t.Fatal("another person's passkey completed gate") |
| + } |
| +} |
| +func TestIDChallengeBrowserCookiesAndExpiry(t *testing.T) { |
| + for _, kind := range []string{"duplicate", "other-browser", "ttl", "clock", "capacity"} { |
| + t.Run(kind, func(t *testing.T) { |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + key := enrol(t, a, s) |
| + b := idJSON(t, a, "/passkey/direct/begin", nil) |
| + c := namedCookie(t, b, ceremonyCookie) |
| + if c.MaxAge != 300 || !c.Secure || !c.HttpOnly || c.Domain != "" || c.Path != "/" || c.SameSite != http.SameSiteLaxMode { |
| + t.Fatal("challenge cookie isolation or TTL") |
| + } |
| + body := assertionBody(key, challengeFrom(t, b), authtest.Options{RPID: credentialHost, Origin: Origin}) |
| + cookies := []*http.Cookie{c} |
| + switch kind { |
| + case "duplicate": |
| + cookies = append(cookies, c) |
| + case "other-browser": |
| + other := idJSON(t, a, "/passkey/direct/begin", nil) |
| + cookies = []*http.Cookie{namedCookie(t, other, ceremonyCookie)} |
| + case "ttl": |
| + raw, _ := base64.RawURLEncoding.DecodeString(c.Value) |
| + plain, err := a.secrets.Sealer.Open("id.direct", raw) |
| + var proof directChallenge |
| + if err != nil || json.Unmarshal(plain, &proof) != nil || proof.Expires > time.Now().Unix()+300 || proof.Expires < time.Now().Unix()+295 { |
| + t.Fatal("challenge lifetime") |
| + } |
| + return |
| + case "clock": |
| + a.db.Writer().Exec("UPDATE home_id_clock SET high_water=?", time.Now().Unix()+100) |
| + case "capacity": |
| + if _, err := a.db.Writer().Exec("WITH RECURSIVE n(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM n WHERE x<10000) INSERT INTO home_id_ceremonies SELECT printf('%064x',x),'other','','direct',? FROM n", time.Now().Unix()+300); err != nil { |
| + t.Fatal(err) |
| + } |
| + if r := idJSON(t, a, "/passkey/register/begin", nil, s); r.Code == 200 { |
| + t.Fatal("challenge bound bypassed") |
| + } |
| + return |
| + } |
| + if r := idJSON(t, a, "/passkey/direct/finish", body, cookies...); r.Code == 200 || sessionCookie(r) != nil { |
| + t.Fatal("challenge accepted", kind) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestIDRegistrationChallengeSubjectAndLiveSession(t *testing.T) { |
| + for _, kind := range []string{"subject", "expired-session"} { |
| + t.Run(kind, func(t *testing.T) { |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + b := idJSON(t, a, "/passkey/register/begin", nil, s) |
| + k, _ := authtest.New() |
| + cd, att := k.Create(challengeFrom(t, b), authtest.Options{RPID: credentialHost, Origin: Origin}) |
| + if kind == "subject" { |
| + a.db.Writer().Exec("UPDATE home_id_ceremonies SET subject='other'") |
| + } else { |
| + a.db.Writer().Exec("UPDATE sessions SET expires_at='2000-01-01T00:00:00Z'") |
| + } |
| + r := idJSON(t, a, "/passkey/register/finish", map[string]string{"clientDataJSON": base64.RawURLEncoding.EncodeToString(cd), "attestationObject": base64.RawURLEncoding.EncodeToString(att)}, s) |
| + if r.Code == 200 { |
| + t.Fatal("registration lost live subject/session binding") |
| + } |
| + }) |
| + } |
| +} |
| +func TestIDLegacyCredentialCannotSignInDirectly(t *testing.T) { |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + k := enrol(t, a, s) |
| + a.db.Writer().Exec("DELETE FROM home_id_discoverable") |
| + b := idJSON(t, a, "/passkey/direct/begin", nil) |
| + r := idJSON(t, a, "/passkey/direct/finish", assertionBody(k, challengeFrom(t, b), authtest.Options{RPID: credentialHost, Origin: Origin}), namedCookie(t, b, ceremonyCookie)) |
| + if r.Code == 200 { |
| + t.Fatal("legacy credential bypassed mailbox gate") |
| + } |
| +} |
| + |
| +func TestIDGatedChallengeGuards(t *testing.T) { |
| + for _, kind := range []string{"purpose", "expiry", "browser", "single-use", "ttl"} { |
| + t.Run(kind, func(t *testing.T) { |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + k := enrol(t, a, s) |
| + g := redeemAfterSignIn(t, a, sealtest.CanaryAddress) |
| + cookies := g.Result().Cookies() |
| + b := idJSON(t, a, "/passkey/signin/begin", nil, cookies...) |
| + body := assertionBody(k, challengeFrom(t, b), authtest.Options{RPID: credentialHost, Origin: Origin}) |
| + switch kind { |
| + case "purpose": |
| + a.db.Writer().Exec("UPDATE home_id_ceremonies SET purpose='register'") |
| + case "expiry": |
| + a.db.Writer().Exec("UPDATE home_id_ceremonies SET expires_at=0") |
| + case "browser": |
| + a.db.Writer().Exec("UPDATE home_id_ceremonies SET browser_hash='other'") |
| + case "ttl": |
| + var expiry int64 |
| + a.db.Writer().QueryRow("SELECT expires_at FROM home_id_ceremonies").Scan(&expiry) |
| + if expiry > time.Now().Unix()+300 || expiry < time.Now().Unix()+295 { |
| + t.Fatal("gated challenge TTL") |
| + } |
| + return |
| + case "single-use": |
| + // A valid signed response with a bad origin consumes the gated proof too. |
| + bad := assertionBody(k, challengeFrom(t, b), authtest.Options{RPID: credentialHost, Origin: "https://evil.invalid"}) |
| + idJSON(t, a, "/passkey/signin/finish", bad, cookies...) |
| + } |
| + r := idJSON(t, a, "/passkey/signin/finish", body, cookies...) |
| + if r.Code == 200 { |
| + t.Fatal("gated guard failed", kind) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/home/id_recovery.go b/internal/home/id_recovery.go| new file mode 100644 |
| index 0000000..1448e40 |
| --- /dev/null |
| +++ b/internal/home/id_recovery.go |
| @@ -0,0 +1,416 @@ |
| +package home |
| + |
| +import ( |
| + "context" |
| + "crypto/rand" |
| + "database/sql" |
| + "encoding/base32" |
| + "encoding/base64" |
| + "encoding/hex" |
| + "encoding/json" |
| + "net/http" |
| + "strings" |
| + "sync" |
| + "time" |
| + |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| + "amadan.net/rastrillo/rastrillo/webauthn" |
| + "github.com/keymaildev/signin" |
| +) |
| + |
| +const recoveryCookie = "__Host-oficina-recovery" |
| +const noticeCookie = "__Host-oficina-notice" |
| + |
| +type mailboxProof struct { |
| + subject, address string |
| + expires int64 |
| +} |
| +type mailboxMemory struct { |
| + mu sync.Mutex |
| + entries map[string]mailboxProof |
| +} |
| + |
| +func (m *mailboxMemory) put(key string, p mailboxProof) bool { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + if m.entries == nil { |
| + m.entries = map[string]mailboxProof{} |
| + } |
| + for k, v := range m.entries { |
| + if v.expires <= time.Now().Unix() { |
| + delete(m.entries, k) |
| + } |
| + } |
| + if len(m.entries) >= 1000 { |
| + return false |
| + } |
| + m.entries[key] = p |
| + time.AfterFunc(time.Until(time.Unix(p.expires, 0)), func() { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + if v, ok := m.entries[key]; ok && v.expires <= time.Now().Unix() { |
| + delete(m.entries, key) |
| + } |
| + }) |
| + return true |
| +} |
| +func (m *mailboxMemory) get(key string) (mailboxProof, bool) { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + p, ok := m.entries[key] |
| + if !ok || p.expires <= time.Now().Unix() { |
| + delete(m.entries, key) |
| + return mailboxProof{}, false |
| + } |
| + return p, true |
| +} |
| +func (m *mailboxMemory) remove(key string) { m.mu.Lock(); defer m.mu.Unlock(); delete(m.entries, key) } |
| + |
| +// The verified address enters only this bounded RAM store. A restart asks the |
| +// person to prove the mailbox again; there is no persisted notice retry queue. |
| +func (a *App) idGate(w http.ResponseWriter, r *http.Request, s sessions.Session, address string) (bool, error) { |
| + tx, now, err := a.idTransaction(r.Context()) |
| + if err != nil { |
| + return false, err |
| + } |
| + defer tx.Rollback() |
| + var n int |
| + if err = tx.QueryRow("SELECT count(*) FROM passkey_credentials WHERE subject=?", s.Subject).Scan(&n); err != nil { |
| + return false, errIDProof |
| + } |
| + if n == 0 { |
| + token, e := a.idMint(tx, r, s, now) |
| + if e != nil { |
| + return false, errIDProof |
| + } |
| + if tx.Commit() != nil { |
| + return false, errIDProof |
| + } |
| + idCookie(w, a.sessions.CookieName(), token, 30*24*3600) |
| + http.Redirect(w, r, sessions.SafeReturn(r, "/"), http.StatusSeeOther) |
| + return true, nil |
| + } |
| + token, hash, err := sessions.NewToken() |
| + if err != nil { |
| + return false, errIDProof |
| + } |
| + if _, err = tx.Exec("DELETE FROM passkey_pending WHERE expires_at<=?", time.Unix(now, 0).UTC().Format(time.RFC3339)); err != nil { |
| + return false, errIDProof |
| + } |
| + if err = tx.QueryRow("SELECT count(*) FROM passkey_pending").Scan(&n); err != nil || n >= 10000 { |
| + return false, errIDProof |
| + } |
| + mailboxAt := s.At |
| + if s.Method == string(signin.MethodKeymail) { |
| + mailboxAt = s.AuthTime |
| + } |
| + if !freshGesture(mailboxAt, time.Now(), 5*time.Minute) { |
| + mailboxAt = time.Time{} |
| + } |
| + mailboxUnix := int64(0) |
| + if !mailboxAt.IsZero() { |
| + mailboxUnix = mailboxAt.Unix() |
| + } |
| + if mailboxUnix > 0 && !a.mailboxes.put(hash, mailboxProof{s.Subject, address, mailboxUnix + 300}) { |
| + mailboxUnix = 0 |
| + } |
| + if _, err = tx.Exec("INSERT INTO passkey_pending(token_hash,subject,method,return_to,expires_at,mailbox_at) VALUES(?,?,?,?,?,?)", hash, s.Subject, s.Method, sessions.SafeReturn(r, "/"), time.Unix(now+300, 0).UTC().Format(time.RFC3339), mailboxUnix); err != nil { |
| + return false, errIDProof |
| + } |
| + if err = tx.Commit(); err != nil { |
| + a.mailboxes.remove(hash) |
| + return false, errIDProof |
| + } |
| + idCookie(w, gateCookie, token, 300) |
| + http.Redirect(w, r, confirmPath, http.StatusSeeOther) |
| + return true, nil |
| +} |
| +func normalizeIDCode(code string) string { |
| + return strings.NewReplacer("-", "", " ", "").Replace(strings.ToLower(code)) |
| +} |
| +func generateIDCodes(tx *sql.Tx, subject string, now int64) ([]string, error) { |
| + if _, err := tx.Exec("DELETE FROM passkey_recovery_codes WHERE subject=?", subject); err != nil { |
| + return nil, errIDProof |
| + } |
| + codes := make([]string, 10) |
| + for i := range codes { |
| + raw := make([]byte, 16) |
| + if _, err := rand.Read(raw); err != nil { |
| + return nil, errIDProof |
| + } |
| + c := strings.ToLower(base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(raw)) |
| + codes[i] = c[:6] + "-" + c[6:12] + "-" + c[12:19] + "-" + c[19:] |
| + if _, err := tx.Exec("INSERT INTO passkey_recovery_codes(code_hash,subject,created_at) VALUES(?,?,?)", sessions.HashToken(normalizeIDCode(c)), subject, time.Unix(now, 0).UTC().Format(time.RFC3339)); err != nil { |
| + return nil, errIDProof |
| + } |
| + } |
| + return codes, nil |
| +} |
| +func (a *App) idRecovery(w http.ResponseWriter, r *http.Request) { |
| + r.Body = http.MaxBytesReader(w, r.Body, 4096) |
| + if r.ParseForm() != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + code := normalizeIDCode(r.PostForm.Get("code")) |
| + tx, now, err := a.idTransaction(r.Context()) |
| + if err != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + defer tx.Rollback() |
| + subject, binding, err := a.idBinding(tx, r, "signin", now) |
| + if err != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + var mailboxAt int64 |
| + if tx.QueryRow("SELECT mailbox_at FROM passkey_pending WHERE token_hash=?", binding).Scan(&mailboxAt) != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + if mailboxAt <= 0 || mailboxAt > now || mailboxAt+300 <= now { |
| + http.Redirect(w, r, "/signin?force=1", http.StatusSeeOther) |
| + return |
| + } |
| + failed := func() { http.Redirect(w, r, confirmPath+"?recovery=failed", http.StatusSeeOther) } |
| + if _, err = tx.Exec("DELETE FROM home_id_attempts WHERE expires_at<=?", now); err != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + buckets := []struct { |
| + key string |
| + limit int |
| + }{{"account:" + subject, 5}, {"ip:" + blindIndex(a.secrets.Pepper, clientIP(r)), 20}} |
| + for _, b := range buckets { |
| + var failures int |
| + err = tx.QueryRow("SELECT failures FROM home_id_attempts WHERE bucket=?", b.key).Scan(&failures) |
| + if err != nil && err != sql.ErrNoRows { |
| + idRefuse(w) |
| + return |
| + } |
| + if failures >= b.limit { |
| + if tx.Commit() != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + failed() |
| + return |
| + } |
| + } |
| + var got string |
| + err = tx.QueryRow("DELETE FROM passkey_recovery_codes WHERE subject=? AND code_hash=? RETURNING subject", subject, sessions.HashToken(code)).Scan(&got) |
| + if err == sql.ErrNoRows { |
| + var n int |
| + if tx.QueryRow("SELECT count(*) FROM home_id_attempts").Scan(&n) != nil || n >= 10000 { |
| + idRefuse(w) |
| + return |
| + } |
| + for _, b := range buckets { |
| + if _, err = tx.Exec("INSERT INTO home_id_attempts VALUES(?,1,?) ON CONFLICT(bucket) DO UPDATE SET failures=failures+1", b.key, now+900); err != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + } |
| + if tx.Commit() != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + failed() |
| + return |
| + } |
| + if err != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + var method, to, expires string |
| + if err = tx.QueryRow("DELETE FROM passkey_pending WHERE token_hash=? RETURNING method,return_to,expires_at", binding).Scan(&method, &to, &expires); err != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + exp, err := time.Parse(time.RFC3339, expires) |
| + if err != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + token, err := a.idMint(tx, r, sessions.Session{Subject: subject, Method: method + "+recovery", AuthTime: time.Unix(now, 0)}, now) |
| + if err != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + proof, hash, err := sessions.NewToken() |
| + if err != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + if _, err = tx.Exec("DELETE FROM home_id_recovery_proofs WHERE expires_at<=?", now); err != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + var proofCount int |
| + if tx.QueryRow("SELECT count(*) FROM home_id_recovery_proofs").Scan(&proofCount) != nil || proofCount >= 10000 { |
| + idRefuse(w) |
| + return |
| + } |
| + if _, err = tx.Exec("INSERT INTO home_id_recovery_proofs VALUES(?,?,?,?)", hash, subject, sessions.HashToken(token), exp.Unix()); err != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + p, ok := a.mailboxes.get(binding) |
| + if !ok || p.subject != subject || !a.mailboxes.put(hash, p) { |
| + idRefuse(w) |
| + return |
| + } |
| + if tx.Commit() != nil { |
| + a.mailboxes.remove(hash) |
| + idRefuse(w) |
| + return |
| + } |
| + a.mailboxes.remove(binding) |
| + a.sendRecoverySigninNotice(r.Context(), p.address) |
| + idCookie(w, a.sessions.CookieName(), token, 30*24*3600) |
| + idCookie(w, gateCookie, "", -1) |
| + idCookie(w, recoveryCookie, proof, int(exp.Unix()-now)) |
| + if to == "/" { |
| + to = "/passkey/replace" |
| + } |
| + http.Redirect(w, r, to, http.StatusSeeOther) |
| +} |
| +func (a *App) replacementBinding(tx *sql.Tx, r *http.Request, now int64) (string, string, error) { |
| + s, session, err := a.idSession(tx, r, now) |
| + if err != nil || !strings.HasSuffix(s.Method, "+recovery") { |
| + return "", "", errIDProof |
| + } |
| + proof := cookieValue(r, recoveryCookie) |
| + if proof == "" { |
| + return "", "", errIDProof |
| + } |
| + hash := sessions.HashToken(proof) |
| + var subject string |
| + if err = tx.QueryRow("SELECT subject FROM home_id_recovery_proofs WHERE token_hash=? AND session_hash=? AND subject=? AND expires_at>?", hash, session, s.Subject, now).Scan(&subject); err != nil { |
| + return "", "", errIDProof |
| + } |
| + p, ok := a.mailboxes.get(hash) |
| + if !ok || p.subject != subject { |
| + return "", "", errIDProof |
| + } |
| + return subject, hash, nil |
| +} |
| +func (a *App) handleReplacement(w http.ResponseWriter, r *http.Request) { |
| + tx, now, err := a.idTransaction(r.Context()) |
| + if err != nil { |
| + a.signinFailed(w, r) |
| + return |
| + } |
| + defer tx.Rollback() |
| + subject, _, err := a.replacementBinding(tx, r, now) |
| + if err != nil { |
| + a.signinFailed(w, r) |
| + return |
| + } |
| + if tx.Commit() != nil { |
| + a.signinFailed(w, r) |
| + return |
| + } |
| + a.render(w, r, 200, "id_replace.html", a.passkeyPageData(subject, nil)) |
| +} |
| +func (a *App) replaceCredential(tx *sql.Tx, r *http.Request, subject string, cred webauthn.Credential, now int64) error { |
| + // Removing the old credentials first cannot transfer another person's key: |
| + // the insert below is unique and every deletion rolls back if it fails. |
| + for _, q := range []string{ |
| + "DELETE FROM home_id_discoverable WHERE credential_id IN (SELECT id FROM passkey_credentials WHERE subject=?)", |
| + "DELETE FROM passkey_credentials WHERE subject=?", |
| + "DELETE FROM sessions WHERE subject=?", |
| + "DELETE FROM passkey_recovery_codes WHERE subject=?", |
| + "DELETE FROM passkey_pending WHERE subject=?", |
| + "DELETE FROM passkey_challenges WHERE subject=?", |
| + "DELETE FROM home_id_ceremonies WHERE subject=?", |
| + "DELETE FROM home_id_recovery_proofs WHERE subject=?", |
| + } { |
| + if _, err := tx.Exec(q, subject); err != nil { |
| + return errIDProof |
| + } |
| + } |
| + id := hex.EncodeToString(cred.ID) |
| + if _, err := tx.Exec("INSERT INTO passkey_credentials(id,subject,public_key,sign_count,created_at) VALUES(?,?,?,?,?)", id, subject, cred.PublicKey, cred.SignCount, time.Unix(now, 0).UTC().Format(time.RFC3339)); err != nil { |
| + return errIDProof |
| + } |
| + if _, err := tx.Exec("INSERT INTO home_id_discoverable VALUES(?)", id); err != nil { |
| + return errIDProof |
| + } |
| + return nil |
| +} |
| + |
| +const replacementNoticeSubject = "Your Oficina passkeys were replaced" |
| +const replacementNoticeBody = "A replacement passkey was added to your Oficina account. All previous passkeys were removed, all Oficina ID sessions were signed out, and all recovery codes were invalidated. You may remain signed in to the directory and other apps. Sign in with your new passkey to create new recovery codes." |
| + |
| +func (a *App) sendReplacementNotice(ctx context.Context, key string) bool { |
| + p, ok := a.mailboxes.get(key) |
| + if !ok { |
| + return false |
| + } |
| + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) |
| + defer cancel() |
| + if a.secrets.Mailer.Send(ctx, p.address, replacementNoticeSubject, replacementNoticeBody) != nil { |
| + a.logger.Warn("replacement notice delivery failed") |
| + return false |
| + } |
| + a.mailboxes.remove(key) |
| + return true |
| +} |
| + |
| +const replacementResultCookie = "__Host-oficina-replaced" |
| + |
| +type replacementResult struct { |
| + Expires int64 `json:"expires"` |
| + Failed bool `json:"failed"` |
| +} |
| + |
| +func (a *App) replacementResult(w http.ResponseWriter, failed bool) { |
| + b, _ := json.Marshal(replacementResult{time.Now().Unix() + 600, failed}) |
| + sealed, err := a.secrets.Sealer.Seal("id.replaced", b) |
| + if err != nil { |
| + return |
| + } |
| + idCookie(w, replacementResultCookie, base64.RawURLEncoding.EncodeToString(sealed), 600) |
| +} |
| +func (a *App) readReplacementResult(r *http.Request) (replacementResult, bool) { |
| + var out replacementResult |
| + b, err := base64.RawURLEncoding.Strict().DecodeString(cookieValue(r, replacementResultCookie)) |
| + if err != nil { |
| + return out, false |
| + } |
| + b, err = a.secrets.Sealer.Open("id.replaced", b) |
| + if err != nil || json.Unmarshal(b, &out) != nil { |
| + return out, false |
| + } |
| + return out, out.Expires > time.Now().Unix() && out.Expires <= time.Now().Unix()+600 |
| +} |
| +func (a *App) handleReplacementDone(w http.ResponseWriter, r *http.Request) { |
| + result, ok := a.readReplacementResult(r) |
| + if !ok { |
| + a.signinFailed(w, r) |
| + return |
| + } |
| + key := sessions.HashToken(cookieValue(r, noticeCookie)) |
| + _, available := a.mailboxes.get(key) |
| + a.render(w, r, 200, "id_replaced.html", map[string]any{"NoticeFailed": result.Failed, "CanRetry": available}) |
| +} |
| +func (a *App) handleNoticeRetry(w http.ResponseWriter, r *http.Request) { |
| + if result, ok := a.readReplacementResult(r); ok && result.Failed { |
| + success := a.sendReplacementNotice(r.Context(), sessions.HashToken(cookieValue(r, noticeCookie))) |
| + a.replacementResult(w, !success) |
| + } |
| + http.Redirect(w, r, "/passkey/replaced", http.StatusSeeOther) |
| +} |
| + |
| +const recoverySigninNoticeSubject = "A recovery code was used for your Oficina account" |
| +const recoverySigninNoticeBody = "Someone signed in to your Oficina account using email and a recovery code. If this was not you, sign in with your passkey and generate new recovery codes. This invalidates the previous codes but does not sign out anyone already signed in." |
| + |
| +func (a *App) sendRecoverySigninNotice(ctx context.Context, address string) { |
| + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) |
| + defer cancel() |
| + if a.secrets.Mailer.Send(ctx, address, recoverySigninNoticeSubject, recoverySigninNoticeBody) != nil { |
| + a.logger.Error("recovery signin notice failed") |
| + } |
| +} |
diff --git a/internal/home/id_recovery_test.go b/internal/home/id_recovery_test.go| new file mode 100644 |
| index 0000000..a3c5d2a |
| --- /dev/null |
| +++ b/internal/home/id_recovery_test.go |
| @@ -0,0 +1,486 @@ |
| +package home |
| + |
| +import ( |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| + "bytes" |
| + "context" |
| + cryptorand "crypto/rand" |
| + "encoding/base64" |
| + "errors" |
| + "fmt" |
| + "github.com/keymaildev/signin" |
| + "io" |
| + "log/slog" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "path/filepath" |
| + "regexp" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/home/internal/home/sealtest" |
| + "amadan.net/rastrillo/rastrillo/webauthn/authtest" |
| +) |
| + |
| +func idCodes(t *testing.T, app *testApp, s *http.Cookie) []string { |
| + t.Helper() |
| + r := exchangeRequest(app.App, "POST", Origin+"/passkey/codes", Origin, url.Values{}, s) |
| + if r.Code != 200 { |
| + t.Fatal("codes", r.Code) |
| + } |
| + matches := regexp.MustCompile(`<code>([^<]+)</code>`).FindAllStringSubmatch(r.Body.String(), -1) |
| + var codes []string |
| + for _, m := range matches { |
| + codes = append(codes, m[1]) |
| + } |
| + if len(codes) != 10 { |
| + t.Fatal("wrong code count", len(codes)) |
| + } |
| + return codes |
| +} |
| +func idRecover(app *testApp, code string, cookies ...*http.Cookie) *http.Response { |
| + return exchangeRequest(app.App, "POST", Origin+"/passkey/signin/recovery", Origin, url.Values{"code": {code}}, cookies...).Result() |
| +} |
| +func TestIDRecoveryEntropy(t *testing.T) { |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + enrol(t, a, s) |
| + seen := map[string]bool{} |
| + entropy := &entropyReader{Reader: cryptorand.Reader} |
| + cryptorand.Reader = entropy |
| + defer func() { cryptorand.Reader = entropy.Reader }() |
| + for _, c := range idCodes(t, a, s) { |
| + raw := strings.ReplaceAll(c, "-", "") |
| + if len(raw) < 16 || seen[raw] { |
| + t.Fatal("less than 80 random bits or repeated code") |
| + } |
| + seen[raw] = true |
| + } |
| + if entropy.n < 100 { |
| + t.Fatal("recovery codes used less than 80 bits each", entropy.n) |
| + } |
| + sealtest.AssertNoPlaintext(t, a.dbPath) |
| +} |
| + |
| +type entropyReader struct { |
| + io.Reader |
| + n int |
| +} |
| + |
| +func (r *entropyReader) Read(b []byte) (int, error) { n, e := r.Reader.Read(b); r.n += n; return n, e } |
| +func TestIDRecoveryAttemptLimitSurvivesReconstruction(t *testing.T) { |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + enrol(t, a, s) |
| + codes := idCodes(t, a, s) |
| + gated := redeemAfterSignIn(t, a, sealtest.CanaryAddress) |
| + gatedCookies := gated.Result().Cookies() |
| + var wg sync.WaitGroup |
| + for i := 0; i < 16; i++ { |
| + wg.Add(1) |
| + go func() { defer wg.Done(); idRecover(a, "bad-code", gatedCookies...) }() |
| + } |
| + wg.Wait() |
| + app, err := New(a.secrets, a.db, a.logger) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + app.flow.Classifier = a.flow.Classifier |
| + a.App = app |
| + // RAM intentionally does not survive reconstruction. Re-prove the mailbox |
| + // so the persistent attempt limit, not missing RAM, must refuse this code. |
| + gated = redeemAfterSignIn(t, a, sealtest.CanaryAddress) |
| + r := exchangeRequest(a.App, "POST", Origin+"/passkey/signin/recovery", Origin, url.Values{"code": {codes[0]}}, gated.Result().Cookies()...) |
| + if sessionCookie(r) != nil { |
| + t.Fatal("parallel failures or restart reset recovery allowance") |
| + } |
| +} |
| +func TestIDRecoveryReplacementRevokesEverything(t *testing.T) { |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + old := enrol(t, a, s) |
| + codes := idCodes(t, a, s) |
| + gated := redeemAfterSignIn(t, a, sealtest.CanaryAddress) |
| + recovery := exchangeRequest(a.App, "POST", Origin+"/passkey/signin/recovery", Origin, url.Values{"code": {codes[0]}}, gated.Result().Cookies()...) |
| + if sessionCookie(recovery) == nil { |
| + t.Fatal("recovery signin", recovery.Code) |
| + } |
| + cookies := recovery.Result().Cookies() |
| + redeemAfterSignIn(t, a, sealtest.CanaryAddress) // another device still between factors |
| + subject := subjectOf(t, a, s) |
| + a.db.Writer().Exec("INSERT INTO passkey_challenges VALUES(?, ?, 'stepup', ?)", "old-challenge", subject, time.Now().Add(time.Minute).UTC().Format(time.RFC3339)) |
| + a.db.Writer().Exec("INSERT INTO home_id_ceremonies VALUES(?, ?, ?, 'stepup', ?)", "other-challenge", "other-browser", subject, time.Now().Unix()+60) |
| + // Recovery is not a way to add an attacker key while retaining the old one. |
| + if r := idJSON(t, a, "/passkey/register/begin", nil, cookies...); r.Code == 200 { |
| + t.Fatal("recovery bypassed replacement confirmation") |
| + } |
| + page := exchangeRequest(a.App, "GET", Origin+"/passkey/replace", "", nil, cookies...) |
| + if page.Code != 200 || !strings.Contains(page.Body.String(), "Replace all passkeys") { |
| + t.Fatal("missing explicit replacement confirmation", page.Code) |
| + } |
| + begin := idJSON(t, a, "/passkey/replace/begin", nil, cookies...) |
| + challenge := challengeFrom(t, begin) |
| + replacement, _ := authtest.New() |
| + cd, att := replacement.Create(challenge, authtest.Options{RPID: credentialHost, Origin: Origin}) |
| + done := idJSON(t, a, "/passkey/replace/finish", map[string]string{"clientDataJSON": base64.RawURLEncoding.EncodeToString(cd), "attestationObject": base64.RawURLEncoding.EncodeToString(att)}, cookies...) |
| + if done.Code != 200 { |
| + t.Fatal("replace", done.Code) |
| + } |
| + for _, table := range []string{"sessions", "passkey_recovery_codes", "passkey_pending", "home_id_recovery_proofs", "passkey_challenges", "home_id_ceremonies"} { |
| + var n int |
| + if err := a.db.Writer().QueryRow("SELECT count(*) FROM " + table).Scan(&n); err != nil || n != 0 { |
| + t.Fatal("replacement retained authority", table, n, err) |
| + } |
| + } |
| + var n int |
| + a.db.Writer().QueryRow("SELECT count(*) FROM passkey_credentials").Scan(&n) |
| + if n != 1 { |
| + t.Fatal("old passkeys remain", n) |
| + } |
| + b := idJSON(t, a, "/passkey/direct/begin", nil) |
| + c := namedCookie(t, b, "__Host-oficina-ceremony") |
| + if r := idJSON(t, a, "/passkey/direct/finish", assertionBody(old, challengeFrom(t, b), authtest.Options{RPID: credentialHost, Origin: Origin}), c); r.Code == 200 { |
| + t.Fatal("old passkey still works") |
| + } |
| + b = idJSON(t, a, "/passkey/direct/begin", nil) |
| + c = namedCookie(t, b, "__Host-oficina-ceremony") |
| + r := idJSON(t, a, "/passkey/direct/finish", assertionBody(replacement, challengeFrom(t, b), authtest.Options{RPID: credentialHost, Origin: Origin}), c) |
| + if r.Code != 200 { |
| + t.Fatal("replacement cannot sign in", r.Code) |
| + } |
| + if !strings.Contains(r.Body.String(), `"to":"/passkey/codes"`) { |
| + t.Fatal("replacement signin skipped new recovery codes") |
| + } |
| + idCodes(t, a, sessionCookie(r)) |
| + mail, ok := a.mailer.last() |
| + if !ok || mail.To != sealtest.CanaryAddress || mail.Subject != "Your Oficina passkeys were replaced" { |
| + t.Fatal("replacement notice missing") |
| + } |
| + sealtest.AssertNoPlaintext(t, a.dbPath) |
| +} |
| + |
| +type idFailMailer struct{} |
| + |
| +func (idFailMailer) Send(context.Context, string, string, string) error { |
| + return errors.New("SMTP failed for " + sealtest.CanaryAddress) |
| +} |
| +func TestIDSMTPFailureDoesNotLeak(t *testing.T) { |
| + a := newTestApp(t) |
| + var logs bytes.Buffer |
| + a.logger = slog.New(slog.NewTextHandler(&logs, nil)) |
| + a.flow.Mailer = idFailMailer{} |
| + r := signIn(t, a, sealtest.CanaryAddress) |
| + if sessionCookie(r) != nil || strings.Contains(logs.String(), sealtest.CanaryAddress) { |
| + t.Fatal("SMTP failure authenticated or logged address") |
| + } |
| + sealtest.AssertNoPlaintext(t, a.dbPath) |
| +} |
| + |
| +func TestIDRecoveryRequiresFreshMailboxGesture(t *testing.T) { |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + enrol(t, a, s) |
| + codes := idCodes(t, a, s) |
| + for _, at := range []time.Time{{}, time.Now().Add(-10 * time.Minute), time.Now().Add(time.Hour)} { |
| + req := httptest.NewRequest("GET", Origin+callbackPath, nil) |
| + w := httptest.NewRecorder() |
| + a.completeSignIn(w, req, signin.Identity{Address: sealtest.CanaryAddress, Method: signin.MethodKeymail, At: time.Now(), AuthTime: at}) |
| + r := exchangeRequest(a.App, "POST", Origin+"/passkey/signin/recovery", Origin, url.Values{"code": {codes[0]}}, w.Result().Cookies()...) |
| + if sessionCookie(r) != nil { |
| + t.Fatal("passive or stale Keymail recovered account") |
| + } |
| + } |
| +} |
| + |
| +func replacementFixture(t *testing.T) (*testApp, []*http.Cookie, map[string]string) { |
| + t.Helper() |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + enrol(t, a, s) |
| + codes := idCodes(t, a, s) |
| + gated := redeemAfterSignIn(t, a, sealtest.CanaryAddress) |
| + recovered := exchangeRequest(a.App, "POST", Origin+"/passkey/signin/recovery", Origin, url.Values{"code": {codes[0]}}, gated.Result().Cookies()...) |
| + if sessionCookie(recovered) == nil { |
| + t.Fatal("recovery failed", recovered.Code) |
| + } |
| + cookies := recovered.Result().Cookies() |
| + begin := idJSON(t, a, "/passkey/replace/begin", nil, cookies...) |
| + key, _ := authtest.New() |
| + cd, att := key.Create(challengeFrom(t, begin), authtest.Options{RPID: credentialHost, Origin: Origin}) |
| + return a, cookies, map[string]string{"clientDataJSON": base64.RawURLEncoding.EncodeToString(cd), "attestationObject": base64.RawURLEncoding.EncodeToString(att)} |
| +} |
| +func TestIDNoticeFailureSurvivesRestartWithoutAddress(t *testing.T) { |
| + a, cookies, body := replacementFixture(t) |
| + var logs bytes.Buffer |
| + a.logger = slog.New(slog.NewTextHandler(&logs, nil)) |
| + a.secrets.Mailer = idFailMailer{} |
| + done := idJSON(t, a, "/passkey/replace/finish", body, cookies...) |
| + if done.Code != 200 { |
| + t.Fatal("delivery failure rolled back replacement", done.Code) |
| + } |
| + var n int |
| + a.db.Writer().QueryRow("SELECT count(*) FROM sessions").Scan(&n) |
| + if n != 0 { |
| + t.Fatal("delivery failure preserved sessions") |
| + } |
| + if strings.Contains(logs.String(), sealtest.CanaryAddress) { |
| + t.Fatal("notice error leaked address") |
| + } |
| + app, err := New(a.secrets, a.db, a.logger) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + a.App = app |
| + page := exchangeRequest(a.App, "GET", Origin+"/passkey/replaced", "", nil, done.Result().Cookies()...) |
| + if !strings.Contains(page.Body.String(), "could not send") || !strings.Contains(page.Body.String(), "can no longer be sent") || strings.Contains(page.Body.String(), "Send email again") { |
| + t.Fatal("restart hid notice failure or retained retry") |
| + } |
| + sealtest.AssertNoPlaintext(t, a.dbPath) |
| +} |
| +func TestIDReplacementRollback(t *testing.T) { |
| + for _, target := range []struct{ table, operation string }{{"sessions", "DELETE"}, {"passkey_recovery_codes", "DELETE"}, {"passkey_credentials", "DELETE"}, {"home_id_recovery_proofs", "DELETE"}, {"passkey_credentials", "INSERT"}, {"home_id_discoverable", "INSERT"}} { |
| + t.Run(target.table+target.operation, func(t *testing.T) { |
| + a, cookies, body := replacementFixture(t) |
| + before := map[string]int{} |
| + for _, table := range []string{"sessions", "passkey_credentials", "passkey_recovery_codes", "home_id_recovery_proofs"} { |
| + var n int |
| + if err := a.db.Writer().QueryRow("SELECT count(*) FROM " + table).Scan(&n); err != nil { |
| + t.Fatal(err) |
| + } |
| + before[table] = n |
| + } |
| + if _, err := a.db.Writer().Exec("CREATE TRIGGER fail_replacement BEFORE " + target.operation + " ON " + target.table + " BEGIN SELECT RAISE(ABORT,'injected'); END"); err != nil { |
| + t.Fatal(err) |
| + } |
| + r := idJSON(t, a, "/passkey/replace/finish", body, cookies...) |
| + if r.Code == 200 { |
| + t.Fatal("failed write reported success") |
| + } |
| + for table, want := range before { |
| + var n int |
| + a.db.Writer().QueryRow("SELECT count(*) FROM " + table).Scan(&n) |
| + if n != want { |
| + t.Fatal("partial replacement", table, n, want) |
| + } |
| + } |
| + }) |
| + } |
| +} |
| +func TestIDReplacementProofBinding(t *testing.T) { |
| + for _, kind := range []string{"no-proof", "no-session", "expired", "wrong-person", "bad-uv", "replay"} { |
| + t.Run(kind, func(t *testing.T) { |
| + a, cookies, body := replacementFixture(t) |
| + switch kind { |
| + case "no-proof": |
| + cookies = []*http.Cookie{func() *http.Cookie { |
| + for _, c := range cookies { |
| + if c.Name == a.sessions.CookieName() { |
| + return c |
| + } |
| + } |
| + return nil |
| + }()} |
| + case "no-session": |
| + cookies = []*http.Cookie{func() *http.Cookie { |
| + for _, c := range cookies { |
| + if c.Name == recoveryCookie { |
| + return c |
| + } |
| + } |
| + return nil |
| + }()} |
| + case "expired": |
| + a.db.Writer().Exec("UPDATE home_id_recovery_proofs SET expires_at=0") |
| + case "wrong-person": |
| + a.db.Writer().Exec("UPDATE home_id_recovery_proofs SET subject='another-person'") |
| + if r := idJSON(t, a, "/passkey/replace/begin", nil, cookies...); r.Code == 200 { |
| + t.Fatal("proof for another person began replacement") |
| + } |
| + return |
| + case "bad-uv": |
| + b := idJSON(t, a, "/passkey/replace/begin", nil, cookies...) |
| + k, _ := authtest.New() |
| + cd, att := k.Create(challengeFrom(t, b), authtest.Options{RPID: credentialHost, Origin: Origin, Flags: authtest.FlagUserPresent | authtest.FlagAttestedData}) |
| + body = map[string]string{"clientDataJSON": base64.RawURLEncoding.EncodeToString(cd), "attestationObject": base64.RawURLEncoding.EncodeToString(att)} |
| + case "replay": |
| + if r := idJSON(t, a, "/passkey/replace/finish", body, cookies...); r.Code != 200 { |
| + t.Fatal("first replacement failed") |
| + } |
| + } |
| + if r := idJSON(t, a, "/passkey/replace/finish", body, cookies...); r.Code == 200 { |
| + t.Fatal("unbound recovery proof replaced passkeys", kind) |
| + } |
| + }) |
| + } |
| +} |
| +func TestIDRecoveryIPLimitAcrossAccounts(t *testing.T) { |
| + a := newTestApp(t) |
| + for i := 0; i < 6; i++ { |
| + address := fmt.Sprintf("account%d@example.invalid", i) |
| + s := signInFully(t, a, address) |
| + enrol(t, a, s) |
| + codes := idCodes(t, a, s) |
| + g := redeemAfterSignIn(t, a, address) |
| + if i < 5 { |
| + for j := 0; j < 4; j++ { |
| + idRecover(a, "wrong", g.Result().Cookies()...) |
| + } |
| + } else { |
| + r := exchangeRequest(a.App, "POST", Origin+"/passkey/signin/recovery", Origin, url.Values{"code": {codes[0]}}, g.Result().Cookies()...) |
| + if sessionCookie(r) != nil { |
| + t.Fatal("IP budget did not span accounts") |
| + } |
| + } |
| + } |
| +} |
| + |
| +func TestIDSigninLimiterUsesBlindedAddress(t *testing.T) { |
| + a := newTestApp(t) |
| + signIn(t, a, sealtest.CanaryAddress) |
| + if strings.Contains(fmt.Sprintf("%#v", a.signinLimiter), sealtest.CanaryAddress) { |
| + t.Fatal("sign-in limiter retains a readable address") |
| + } |
| +} |
| +func TestIDRecoveryPrivacyInBackup(t *testing.T) { |
| + a, cookies, body := replacementFixture(t) |
| + done := idJSON(t, a, "/passkey/replace/finish", body, cookies...) |
| + if done.Code != 200 { |
| + t.Fatal("replacement", done.Code) |
| + } |
| + backup := filepath.Join(t.TempDir(), "backup.sqlite") |
| + if _, err := a.db.Writer().Exec("VACUUM INTO ?", backup); err != nil { |
| + t.Fatal(err) |
| + } |
| + sealtest.AssertNoPlaintext(t, backup) |
| + sealtest.AssertNoPlaintext(t, a.dbPath) |
| +} |
| +func TestIDReplacementNoticeRetry(t *testing.T) { |
| + a, cookies, body := replacementFixture(t) |
| + a.secrets.Mailer = idFailMailer{} |
| + done := idJSON(t, a, "/passkey/replace/finish", body, cookies...) |
| + if done.Code != 200 { |
| + t.Fatal("replacement", done.Code) |
| + } |
| + a.secrets.Mailer = a.mailer |
| + retry := exchangeRequest(a.App, "POST", Origin+"/passkey/notice", Origin, url.Values{}, done.Result().Cookies()...) |
| + if retry.Code != 303 { |
| + t.Fatal("retry", retry.Code) |
| + } |
| + mail, ok := a.mailer.last() |
| + if !ok || mail.To != sealtest.CanaryAddress || mail.Subject != replacementNoticeSubject { |
| + t.Fatal("retry did not use proven mailbox") |
| + } |
| + key := sessions.HashToken(namedCookie(t, done, noticeCookie).Value) |
| + if _, ok := a.mailboxes.get(key); ok { |
| + t.Fatal("successful notice retained address") |
| + } |
| +} |
| + |
| +func TestIDRecoveryCodePersonBindingAndReplay(t *testing.T) { |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + enrol(t, a, s) |
| + codes := idCodes(t, a, s) |
| + other := signInFully(t, a, "other@example.invalid") |
| + enrol(t, a, other) |
| + wrongGate := redeemAfterSignIn(t, a, "other@example.invalid") |
| + wrong := exchangeRequest(a.App, "POST", Origin+"/passkey/signin/recovery", Origin, url.Values{"code": {codes[0]}}, wrongGate.Result().Cookies()...) |
| + if sessionCookie(wrong) != nil { |
| + t.Fatal("code crossed accounts") |
| + } |
| + gate := redeemAfterSignIn(t, a, sealtest.CanaryAddress) |
| + gateCookies := gate.Result().Cookies() |
| + var successes atomic.Int32 |
| + var wg sync.WaitGroup |
| + for i := 0; i < 12; i++ { |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + r := exchangeRequest(a.App, "POST", Origin+"/passkey/signin/recovery", Origin, url.Values{"code": {codes[0]}}, gateCookies...) |
| + if sessionCookie(r) != nil { |
| + successes.Add(1) |
| + } |
| + }() |
| + } |
| + wg.Wait() |
| + if successes.Load() != 1 { |
| + t.Fatal("recovery proof minted more than once", successes.Load()) |
| + } |
| + gate = redeemAfterSignIn(t, a, sealtest.CanaryAddress) |
| + replay := exchangeRequest(a.App, "POST", Origin+"/passkey/signin/recovery", Origin, url.Values{"code": {codes[0]}}, gate.Result().Cookies()...) |
| + if sessionCookie(replay) != nil { |
| + t.Fatal("used code replayed with new mailbox proof") |
| + } |
| +} |
| +func TestIDRecoveryCannotRegenerateCodesOrSatisfyPasskeyOnlyStepup(t *testing.T) { |
| + a, cookies, _ := replacementFixture(t) |
| + r := exchangeRequest(a.App, "POST", Origin+"/passkey/codes", Origin, url.Values{}, cookies...) |
| + if r.Code == 200 { |
| + t.Fatal("recovery session generated codes before new passkey proof") |
| + } |
| + req := httptest.NewRequest("GET", Origin+"/", nil) |
| + for _, c := range cookies { |
| + req.AddCookie(c) |
| + } |
| + s, ok := a.sessions.From(req) |
| + if !ok || credentialFresh(s, time.Now()) { |
| + t.Fatal("recovery satisfied passkey-only operator stepup") |
| + } |
| +} |
| + |
| +func TestIDMailboxMemoryBoundAndExpiry(t *testing.T) { |
| + m := mailboxMemory{entries: map[string]mailboxProof{}} |
| + for i := 0; i < 1000; i++ { |
| + m.entries[fmt.Sprint(i)] = mailboxProof{"person", sealtest.CanaryAddress, time.Now().Unix() + 300} |
| + } |
| + if m.put("overflow", mailboxProof{"person", sealtest.CanaryAddress, time.Now().Unix() + 300}) { |
| + t.Fatal("mailbox memory exceeded hard bound") |
| + } |
| + m.entries["expired"] = mailboxProof{"person", sealtest.CanaryAddress, time.Now().Unix() - 1} |
| + if _, ok := m.get("expired"); ok { |
| + t.Fatal("expired mailbox proof retained") |
| + } |
| +} |
| +func TestIDRecoveryProofCapacity(t *testing.T) { |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + enrol(t, a, s) |
| + codes := idCodes(t, a, s) |
| + g := redeemAfterSignIn(t, a, sealtest.CanaryAddress) |
| + if _, err := a.db.Writer().Exec("WITH RECURSIVE n(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM n WHERE x<10000) INSERT INTO home_id_recovery_proofs SELECT printf('%064x',x),'person','session',? FROM n", time.Now().Unix()+300); err != nil { |
| + t.Fatal(err) |
| + } |
| + r := exchangeRequest(a.App, "POST", Origin+"/passkey/signin/recovery", Origin, url.Values{"code": {codes[0]}}, g.Result().Cookies()...) |
| + if sessionCookie(r) != nil { |
| + t.Fatal("recovery proof capacity exceeded") |
| + } |
| +} |
| + |
| +func TestIDCodesRequireEnrolledPasskey(t *testing.T) { |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + r := exchangeRequest(a.App, "POST", Origin+"/passkey/codes", Origin, url.Values{}, s) |
| + if r.Code == 200 { |
| + t.Fatal("codes issued before passkey enrollment") |
| + } |
| +} |
| + |
| +func TestIDCredentialPagesAreNoStore(t *testing.T) { |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + enrol(t, a, s) |
| + for _, path := range []string{"/signin", "/passkey/enrol", "/passkey/codes", "/passkey/replace", "/passkey/replaced"} { |
| + r := exchangeRequest(a.App, "GET", Origin+path, "", nil, s) |
| + if r.Header().Get("Cache-Control") != "no-store" { |
| + t.Fatal("credential page permits storage", path) |
| + } |
| + } |
| + r := exchangeRequest(a.App, "POST", Origin+"/passkey/codes", Origin, url.Values{}, s) |
| + if r.Code != 200 || r.Header().Get("Cache-Control") != "no-store" { |
| + t.Fatal("shown-once codes permit storage") |
| + } |
| +} |
diff --git a/internal/home/id_review_test.go b/internal/home/id_review_test.go| new file mode 100644 |
| index 0000000..47170ed |
| --- /dev/null |
| +++ b/internal/home/id_review_test.go |
| @@ -0,0 +1,352 @@ |
| +package home |
| + |
| +import ( |
| + "bytes" |
| + "encoding/base64" |
| + "encoding/json" |
| + "fmt" |
| + "log/slog" |
| + "net/http/httptest" |
| + "net/url" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/home/internal/home/sealtest" |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| + "amadan.net/rastrillo/rastrillo/webauthn/authtest" |
| +) |
| + |
| +func fullMailbox(a *testApp) { |
| + a.mailboxes.mu.Lock() |
| + defer a.mailboxes.mu.Unlock() |
| + if a.mailboxes.entries == nil { |
| + a.mailboxes.entries = map[string]mailboxProof{} |
| + } |
| + for i := len(a.mailboxes.entries); i < 1000; i++ { |
| + a.mailboxes.entries[fmt.Sprint("filler", i)] = mailboxProof{expires: time.Now().Unix() + 300} |
| + } |
| +} |
| +func TestIDFullMailboxAllowsGatedSignin(t *testing.T) { |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + k := enrol(t, a, s) |
| + fullMailbox(a) |
| + g := redeemAfterSignIn(t, a, sealtest.CanaryAddress) |
| + if g.Code != 303 || g.Header().Get("Location") != confirmPath { |
| + t.Fatal("RAM capacity blocked email gate", g.Code) |
| + } |
| + var at int64 |
| + if err := a.db.Writer().QueryRow("SELECT mailbox_at FROM passkey_pending").Scan(&at); err != nil || at != 0 { |
| + t.Fatal("gate advertised unavailable mailbox proof", at, err) |
| + } |
| + b := idJSON(t, a, "/passkey/signin/begin", nil, g.Result().Cookies()...) |
| + r := idJSON(t, a, "/passkey/signin/finish", assertionBody(k, challengeFrom(t, b), authtest.Options{RPID: credentialHost, Origin: Origin}), g.Result().Cookies()...) |
| + if r.Code != 200 || sessionCookie(r) == nil { |
| + t.Fatal("gated passkey refused", r.Code) |
| + } |
| +} |
| +func TestIDRecoveryMailboxFailurePreservesCode(t *testing.T) { |
| + for _, kind := range []string{"missing", "full"} { |
| + t.Run(kind, func(t *testing.T) { |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + enrol(t, a, s) |
| + codes := idCodes(t, a, s) |
| + g := redeemAfterSignIn(t, a, sealtest.CanaryAddress) |
| + if kind == "missing" { |
| + a.mailboxes.entries = map[string]mailboxProof{} |
| + } else { |
| + fullMailbox(a) |
| + } |
| + r := exchangeRequest(a.App, "POST", Origin+"/passkey/signin/recovery", Origin, url.Values{"code": {codes[0]}}, g.Result().Cookies()...) |
| + if sessionCookie(r) != nil { |
| + t.Fatal("recovered without reserving RAM proof") |
| + } |
| + var n int |
| + a.db.Writer().QueryRow("SELECT count(*) FROM passkey_recovery_codes").Scan(&n) |
| + if n != 10 { |
| + t.Fatal("RAM failure consumed code", n) |
| + } |
| + a.db.Writer().QueryRow("SELECT count(*) FROM passkey_pending").Scan(&n) |
| + if n != 1 { |
| + t.Fatal("RAM failure consumed gate", n) |
| + } |
| + }) |
| + } |
| +} |
| +func TestIDRecoverySigninNotice(t *testing.T) { |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + enrol(t, a, s) |
| + codes := idCodes(t, a, s) |
| + g := redeemAfterSignIn(t, a, sealtest.CanaryAddress) |
| + r := exchangeRequest(a.App, "POST", Origin+"/passkey/signin/recovery", Origin, url.Values{"code": {codes[0]}}, g.Result().Cookies()...) |
| + if sessionCookie(r) == nil { |
| + t.Fatal("recovery failed") |
| + } |
| + m, ok := a.mailer.last() |
| + if !ok || m.Subject != "A recovery code was used for your Oficina account" || m.To != sealtest.CanaryAddress { |
| + t.Fatal("redemption notice missing") |
| + } |
| + // Delivery must leave the RAM proof available for replacement. |
| + if p := exchangeRequest(a.App, "GET", Origin+"/passkey/replace", "", nil, r.Result().Cookies()...); p.Code != 200 { |
| + t.Fatal("notice consumed replacement proof") |
| + } |
| + sealtest.AssertNoPlaintext(t, a.dbPath) |
| +} |
| +func TestIDRecoveryCannotLink(t *testing.T) { |
| + p := newExchangePair(t) |
| + _, intent := p.startFresh(t, nil) |
| + s := signInFully(t, p.credential, sealtest.CanaryAddress) |
| + if _, err := p.credential.db.Writer().Exec("UPDATE sessions SET method='email+recovery'"); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, method := range []string{"GET", "POST"} { |
| + r := exchangeRequest(p.credential.App, method, Origin+"/authorize/resume", Origin, nil, intent, s) |
| + if r.Code != 303 || !strings.HasPrefix(r.Header().Get("Location"), "/signin") { |
| + t.Fatal("recovery satisfied linking", method, r.Code) |
| + } |
| + } |
| +} |
| +func TestIDDirectFloodLeavesGatedCapacity(t *testing.T) { |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + enrol(t, a, s) |
| + g := redeemAfterSignIn(t, a, sealtest.CanaryAddress) |
| + for i := 0; i < 10001; i++ { |
| + r := idJSON(t, a, "/passkey/direct/begin", nil) |
| + if r.Code != 200 { |
| + t.Fatal("direct begin refused", i) |
| + } |
| + if i == 0 { |
| + var n int |
| + a.db.Writer().QueryRow("SELECT (SELECT count(*) FROM home_id_ceremonies)+(SELECT count(*) FROM home_id_direct_used)").Scan(&n) |
| + if n != 0 { |
| + t.Fatal("anonymous begin stored challenge") |
| + } |
| + } |
| + } |
| + var n int |
| + if err := a.db.Writer().QueryRow("SELECT (SELECT count(*) FROM home_id_ceremonies)+(SELECT count(*) FROM home_id_direct_used)").Scan(&n); err != nil || n != 0 { |
| + t.Fatal("anonymous begins retained state", n, err) |
| + } |
| + if r := idJSON(t, a, "/passkey/signin/begin", nil, g.Result().Cookies()...); r.Code != 200 { |
| + t.Fatal("flood blocked authenticated gate") |
| + } |
| +} |
| +func TestIDDirectSealedChallenge(t *testing.T) { |
| + for _, kind := range []string{"tampered", "expired", "future", "mismatch"} { |
| + t.Run(kind, func(t *testing.T) { |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + k := enrol(t, a, s) |
| + b := idJSON(t, a, "/passkey/direct/begin", nil) |
| + c := namedCookie(t, b, ceremonyCookie) |
| + raw, err := base64.RawURLEncoding.DecodeString(c.Value) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + plain, err := a.secrets.Sealer.Open("id.direct", raw) |
| + if err != nil { |
| + t.Fatal("direct challenge is not sealed") |
| + } |
| + var proof map[string]any |
| + if json.Unmarshal(plain, &proof) != nil { |
| + t.Fatal("invalid proof") |
| + } |
| + switch kind { |
| + case "tampered": |
| + raw[len(raw)-1] ^= 1 |
| + default: |
| + switch kind { |
| + case "expired": |
| + proof["expires"] = time.Now().Unix() - 1 |
| + case "future": |
| + proof["expires"] = time.Now().Unix() + 600 |
| + case "mismatch": |
| + proof["challenge"] = strings.Repeat("0", 64) |
| + } |
| + plain, _ = json.Marshal(proof) |
| + raw, err = a.secrets.Sealer.Seal("id.direct", plain) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + c.Value = base64.RawURLEncoding.EncodeToString(raw) |
| + r := idJSON(t, a, "/passkey/direct/finish", assertionBody(k, challengeFrom(t, b), authtest.Options{RPID: credentialHost, Origin: Origin}), c) |
| + if r.Code == 200 { |
| + t.Fatal("invalid sealed proof accepted", kind) |
| + } |
| + }) |
| + } |
| +} |
| +func TestIDRecoveryExclusions(t *testing.T) { |
| + a, cookies, _ := replacementFixture(t) |
| + if r := idJSON(t, a, "/passkey/register/begin", nil, cookies...); r.Code == 200 { |
| + t.Fatal("recovery enrolled directly") |
| + } |
| + if r := exchangeRequest(a.App, "POST", Origin+"/passkey/codes", Origin, url.Values{}, cookies...); r.Code == 200 { |
| + t.Fatal("recovery generated codes") |
| + } |
| +} |
| +func TestIDReplacementRequiresRecoverySession(t *testing.T) { |
| + for _, kind := range []string{"method", "session"} { |
| + t.Run(kind, func(t *testing.T) { |
| + a, cookies, body := replacementFixture(t) |
| + if kind == "method" { |
| + a.db.Writer().Exec("UPDATE sessions SET method='email'") |
| + } else { |
| + var token string |
| + for _, c := range cookies { |
| + if c.Name == a.sessions.CookieName() { |
| + token = c.Value |
| + } |
| + } |
| + // Change only the proof's session binding, keeping person and RAM proof valid. |
| + a.db.Writer().Exec("UPDATE home_id_recovery_proofs SET session_hash=?", sessions.HashToken(token+"different")) |
| + } |
| + r := idJSON(t, a, "/passkey/replace/finish", body, cookies...) |
| + if r.Code == 200 { |
| + t.Fatal("replacement accepted wrong session authority", kind) |
| + } |
| + }) |
| + } |
| +} |
| +func TestIDLimitsBeforeValidCode(t *testing.T) { |
| + for _, bucket := range []string{"account", "ip"} { |
| + t.Run(bucket, func(t *testing.T) { |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + enrol(t, a, s) |
| + codes := idCodes(t, a, s) |
| + g := redeemAfterSignIn(t, a, sealtest.CanaryAddress) |
| + key := "account:" + subjectOf(t, a, s) |
| + limit := 5 |
| + if bucket == "ip" { |
| + req := httptest.NewRequest("POST", Origin+"/", nil) |
| + key = "ip:" + blindIndex(a.secrets.Pepper, clientIP(req)) |
| + limit = 20 |
| + } |
| + a.db.Writer().Exec("INSERT INTO home_id_attempts VALUES(?,?,?)", key, limit, time.Now().Unix()+900) |
| + r := exchangeRequest(a.App, "POST", Origin+"/passkey/signin/recovery", Origin, url.Values{"code": {codes[0]}}, g.Result().Cookies()...) |
| + if sessionCookie(r) != nil { |
| + t.Fatal("valid code bypassed exhausted budget") |
| + } |
| + var n int |
| + a.db.Writer().QueryRow("SELECT count(*) FROM passkey_recovery_codes").Scan(&n) |
| + if n != 10 { |
| + t.Fatal("budget refusal consumed valid code", n) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestIDRecoverySigninNoticeFailurePrivacy(t *testing.T) { |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + enrol(t, a, s) |
| + codes := idCodes(t, a, s) |
| + g := redeemAfterSignIn(t, a, sealtest.CanaryAddress) |
| + var logs bytes.Buffer |
| + a.logger = slog.New(slog.NewTextHandler(&logs, nil)) |
| + a.secrets.Mailer = idFailMailer{} |
| + r := exchangeRequest(a.App, "POST", Origin+"/passkey/signin/recovery", Origin, url.Values{"code": {codes[0]}}, g.Result().Cookies()...) |
| + if sessionCookie(r) == nil { |
| + t.Fatal("notice failure rolled back recovery") |
| + } |
| + if strings.Contains(logs.String(), sealtest.CanaryAddress) { |
| + t.Fatal("notice error leaked address") |
| + } |
| + sealtest.AssertNoPlaintext(t, a.dbPath) |
| +} |
| +func TestIDLegacyRecoveryCodesStillRedeem(t *testing.T) { |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + enrol(t, a, s) |
| + codes, err := a.passkeys.RegenerateRecoveryCodes(subjectOf(t, a, s)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(normalizeIDCode(codes[0])) != 10 { |
| + t.Fatal("fixture no longer exercises legacy 50-bit format") |
| + } |
| + g := redeemAfterSignIn(t, a, sealtest.CanaryAddress) |
| + r := exchangeRequest(a.App, "POST", Origin+"/passkey/signin/recovery", Origin, url.Values{"code": {codes[0]}}, g.Result().Cookies()...) |
| + if sessionCookie(r) == nil { |
| + t.Fatal("legacy code rejected") |
| + } |
| +} |
| +func TestIDDirectReceiptsBounded(t *testing.T) { |
| + for _, kind := range []string{"capacity", "expiry", "invalid-proof", "restart"} { |
| + t.Run(kind, func(t *testing.T) { |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + k := enrol(t, a, s) |
| + b := idJSON(t, a, "/passkey/direct/begin", nil) |
| + c := namedCookie(t, b, ceremonyCookie) |
| + zero := uint32(0) |
| + opts := authtest.Options{RPID: credentialHost, Origin: Origin, Count: &zero} |
| + if kind == "capacity" || kind == "expiry" { |
| + exp := time.Now().Unix() + 300 |
| + if kind == "expiry" { |
| + exp = 0 |
| + } |
| + if _, err := a.db.Writer().Exec("WITH RECURSIVE n(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM n WHERE x<10000) INSERT INTO home_id_direct_used SELECT printf('%064x',x),? FROM n", exp); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if kind == "invalid-proof" { |
| + opts.CorruptSig = true |
| + } |
| + body := assertionBody(k, challengeFrom(t, b), opts) |
| + r := idJSON(t, a, "/passkey/direct/finish", body, c) |
| + switch kind { |
| + case "capacity": |
| + if r.Code == 200 { |
| + t.Fatal("receipt cap bypassed") |
| + } |
| + case "expiry": |
| + if r.Code != 200 { |
| + t.Fatal("expired receipts not reclaimed") |
| + } |
| + case "invalid-proof": |
| + var n int |
| + a.db.Writer().QueryRow("SELECT count(*) FROM home_id_direct_used").Scan(&n) |
| + if n != 0 { |
| + t.Fatal("invalid proof retained receipt") |
| + } |
| + case "restart": |
| + if r.Code != 200 { |
| + t.Fatal("first signin failed") |
| + } |
| + app, err := New(a.secrets, a.db, a.logger) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + a.App = app |
| + if replay := idJSON(t, a, "/passkey/direct/finish", body, c); replay.Code == 200 { |
| + t.Fatal("restart allowed replay") |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestIDRecoveryMailboxTimeDefense(t *testing.T) { |
| + for _, at := range []int64{0, time.Now().Unix() - 600, time.Now().Unix() + 600} { |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + enrol(t, a, s) |
| + codes := idCodes(t, a, s) |
| + g := redeemAfterSignIn(t, a, sealtest.CanaryAddress) |
| + // Keep the independent RAM proof live while checking persisted freshness. |
| + if _, err := a.db.Writer().Exec("UPDATE passkey_pending SET mailbox_at=?", at); err != nil { |
| + t.Fatal(err) |
| + } |
| + r := exchangeRequest(a.App, "POST", Origin+"/passkey/signin/recovery", Origin, url.Values{"code": {codes[0]}}, g.Result().Cookies()...) |
| + if sessionCookie(r) != nil { |
| + t.Fatal("invalid persisted mailbox time accepted", at) |
| + } |
| + } |
| +} |
diff --git a/internal/home/id_signout_test.go b/internal/home/id_signout_test.go| new file mode 100644 |
| index 0000000..3fc92c5 |
| --- /dev/null |
| +++ b/internal/home/id_signout_test.go |
| @@ -0,0 +1,86 @@ |
| +package home |
| + |
| +import ( |
| + "context" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/home/internal/home/sealtest" |
| +) |
| + |
| +func TestIDLocalSignoutWithHangingIssuer(t *testing.T) { |
| + accepted := make(chan struct{}) |
| + release := make(chan struct{}) |
| + issuer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { close(accepted); <-release })) |
| + defer issuer.Close() |
| + defer close(release) |
| + p := newExchangePair(t) |
| + credential, directory := signedInPair(t, p) |
| + p.directory.origins.Credential = issuer.URL |
| + r := exchangeRequest(p.directory, "POST", directoryOrigin+"/signout", directoryOrigin, url.Values{}, directory) |
| + if r.Code != 303 || r.Header().Get("Location") != "/signed-out" { |
| + t.Fatal("local signout depends on hanging issuer", r.Code, r.Header().Get("Location")) |
| + } |
| + if s, ok := p.directory.sessions.From(func() *http.Request { |
| + r := httptest.NewRequest("GET", directoryOrigin+"/", nil) |
| + r.AddCookie(directory) |
| + return r |
| + }()); ok || s.Subject != "" { |
| + t.Fatal("local session not revoked") |
| + } |
| + page := exchangeRequest(p.directory, "GET", directoryOrigin+"/signed-out", "", nil, r.Result().Cookies()...) |
| + if page.Code != 200 { |
| + t.Fatal("local landing failed") |
| + } |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + defer cancel() |
| + req, _ := http.NewRequestWithContext(ctx, "POST", signoutFormAction(t, page.Body.String()), nil) |
| + done := make(chan struct{}) |
| + go func() { |
| + defer close(done) |
| + resp, _ := issuer.Client().Do(req) |
| + if resp != nil { |
| + resp.Body.Close() |
| + } |
| + }() |
| + select { |
| + case <-accepted: |
| + case <-time.After(time.Second): |
| + t.Fatal("issuer did not accept connection") |
| + } |
| + // The actual page form is now waiting on the issuer; local pages still |
| + // respond and the copied directory session remains revoked. |
| + again := exchangeRequest(p.directory, "GET", directoryOrigin+"/signed-out", "", nil) |
| + if again.Code != 200 { |
| + t.Fatal("hanging form blocked local landing") |
| + } |
| + local := httptest.NewRequest("GET", directoryOrigin+"/", nil) |
| + local.AddCookie(directory) |
| + if _, ok := p.directory.sessions.From(local); ok { |
| + t.Fatal("hanging issuer restored local session") |
| + } |
| + // A credential-origin sign-out also lands on its own origin. |
| + end := exchangeRequest(p.credential.App, "POST", Origin+"/signout", Origin, url.Values{}, credential) |
| + if end.Code != 303 || end.Header().Get("Location") != Origin+"/signed-out" { |
| + t.Fatal("credential signout leaves its origin") |
| + } |
| + if page := exchangeRequest(p.credential.App, "GET", Origin+"/signed-out", "", nil); page.Code != 200 { |
| + t.Fatal("credential landing missing") |
| + } |
| + cancel() |
| + select { |
| + case <-done: |
| + case <-time.After(time.Second): |
| + t.Fatal("issuer probe failed to cancel") |
| + } |
| +} |
| +func TestIDSigninRemainsLocal(t *testing.T) { |
| + p := newExchangePair(t) |
| + s := signInFully(t, p.credential, sealtest.CanaryAddress) |
| + if s == nil { |
| + t.Fatal("local signin failed") |
| + } |
| +} |
diff --git a/internal/home/identity/migrations/0001_ceremonies.sql b/internal/home/identity/migrations/0001_ceremonies.sql| new file mode 100644 |
| index 0000000..ee21efc |
| --- /dev/null |
| +++ b/internal/home/identity/migrations/0001_ceremonies.sql |
| @@ -0,0 +1,13 @@ |
| +CREATE TABLE home_id_clock (id INTEGER PRIMARY KEY CHECK (id = 1), high_water INTEGER NOT NULL); |
| +INSERT INTO home_id_clock VALUES (1, 0); |
| +CREATE TABLE home_id_ceremonies ( |
| + challenge TEXT PRIMARY KEY, |
| + browser_hash TEXT NOT NULL, |
| + subject TEXT NOT NULL, |
| + purpose TEXT NOT NULL, |
| + expires_at INTEGER NOT NULL |
| +); |
| +CREATE INDEX home_id_ceremonies_expiry ON home_id_ceremonies(expires_at); |
| +CREATE TABLE home_id_discoverable ( |
| + credential_id TEXT PRIMARY KEY REFERENCES passkey_credentials(id) ON DELETE CASCADE |
| +); |
diff --git a/internal/home/identity/migrations/0002_recovery.sql b/internal/home/identity/migrations/0002_recovery.sql| new file mode 100644 |
| index 0000000..772f41e |
| --- /dev/null |
| +++ b/internal/home/identity/migrations/0002_recovery.sql |
| @@ -0,0 +1,14 @@ |
| +CREATE TABLE home_id_attempts ( |
| + bucket TEXT PRIMARY KEY, |
| + failures INTEGER NOT NULL, |
| + expires_at INTEGER NOT NULL |
| +); |
| +CREATE TABLE home_id_recovery_proofs ( |
| + token_hash TEXT PRIMARY KEY, |
| + subject TEXT NOT NULL, |
| + session_hash TEXT NOT NULL, |
| + expires_at INTEGER NOT NULL |
| +); |
| +CREATE INDEX home_id_recovery_expiry ON home_id_recovery_proofs(expires_at); |
| + |
| +ALTER TABLE passkey_pending ADD COLUMN mailbox_at INTEGER NOT NULL DEFAULT 0; |
diff --git a/internal/home/identity/migrations/0003_direct.sql b/internal/home/identity/migrations/0003_direct.sql| new file mode 100644 |
| index 0000000..38fcfd6 |
| --- /dev/null |
| +++ b/internal/home/identity/migrations/0003_direct.sql |
| @@ -0,0 +1,5 @@ |
| +CREATE TABLE home_id_direct_used ( |
| + challenge TEXT PRIMARY KEY, |
| + expires_at INTEGER NOT NULL |
| +); |
| +CREATE INDEX home_id_direct_expiry ON home_id_direct_used(expires_at); |
diff --git a/internal/home/keymail_fresh_test.go b/internal/home/keymail_fresh_test.go| index 08dfc1e..8129cd9 100644 |
| --- a/internal/home/keymail_fresh_test.go |
| +++ b/internal/home/keymail_fresh_test.go |
| @@ -83,12 +83,13 @@ func TestFreshKeymailGestureYieldsAssertionWithKeymailAuthTime(t *testing.T) { |
| p := newExchangePair(t) |
| stub := newKeymailStub(t, p.credential, freshKeymailAddress) |
| stub.reauth = true |
| - // Inside the window but well away from now, so an implementation |
| - // that stamped issuance time over Keymail's report would be seen. |
| - stub.authTime = time.Now().Add(-90 * time.Second).Truncate(time.Second) |
| intent, navigation := freshSignInForm(t, p, nil) |
| u, pending := keymailContinuation(t, p, freshBegin(t, p, "/signin", freshKeymailAddress, intent, navigation)) |
| + // The simulated gesture happens after the link transaction starts. |
| + stub.mu.Lock() |
| + stub.authTime = time.Now().Truncate(time.Second) |
| + stub.mu.Unlock() |
| back := callback(t, p.credential, "code-1", u.Query().Get("state"), pending, intent, navigation) |
| if back.Code != 303 || back.Header().Get("Location") != "/authorize/resume" || sessionCookie(back) == nil { |
| t.Fatal("fresh Keymail gesture was not credited", back.Code, back.Header().Get("Location")) |
| @@ -293,12 +294,6 @@ func TestKeymailSessionWithoutGestureTimeIsNotFresh(t *testing.T) { |
| } |
| _, intent := p.startFresh(t, session) |
| resume := exchangeRequest(p.credential.App, "GET", Origin+"/authorize/resume", "", nil, intent, session) |
| - if gesture { |
| - if resume.Code != 200 || !strings.Contains(resume.Body.String(), `name="assertion"`) { |
| - t.Fatal("a Keymail session with a fresh gesture was refused", resume.Code) |
| - } |
| - return |
| - } |
| if resume.Code != 303 || resume.Header().Get("Location") != "/signin?return_to=%2Fauthorize%2Fresume" || strings.Contains(resume.Body.String(), `name="assertion"`) { |
| t.Fatal("a Keymail session with no gesture time satisfied a step-up", resume.Code) |
| } |
diff --git a/internal/home/models.go b/internal/home/models.go| index 803e86b..23fa74d 100644 |
| --- a/internal/home/models.go |
| +++ b/internal/home/models.go |
| @@ -2,6 +2,7 @@ package home |
| import ( |
| "embed" |
| + "io/fs" |
| "amadan.net/rastrillo/rastrillo/migrate" |
| "amadan.net/rastrillo/rastrillo/passkey" |
| @@ -37,3 +38,16 @@ var Schema = migrate.MustFromFS(migrationsFS, "home") |
| // person ref — so the worry about inheriting an address-bearing subject |
| // does not arise. Said here rather than left to be rediscovered. |
| var BootSchema = migrate.Merge(sessions.Schema, passkey.Schema, Schema) |
| + |
| +// Identity migrations extend the serving credential role. Keep the historical |
| +// BootSchema unchanged: its exact objects are frozen in admission profiles. |
| +// |
| +//go:embed identity/migrations/*.sql |
| +var identityFS embed.FS |
| +var identitySchema = func() *migrate.Set { |
| + sub, err := fs.Sub(identityFS, "identity") |
| + if err != nil { |
| + panic(err) |
| + } |
| + return migrate.MustFromFS(sub, "home_id") |
| +}() |
diff --git a/internal/home/operator_ceremony_test.go b/internal/home/operator_ceremony_test.go| index 1f25986..3022520 100644 |
| --- a/internal/home/operator_ceremony_test.go |
| +++ b/internal/home/operator_ceremony_test.go |
| @@ -146,7 +146,7 @@ func TestOperatorCredentialConfirmStaleSessionGetsAFreshIntentAndNoLoop(t *testi |
| f := newOperatorFixture(t) |
| f.submit(t, "credential", "add-apps", []string{"docs"}) |
| paul := f.paulCredential(t) |
| - backdate(t, f.credential.App, "created_at", time.Now().Add(-time.Hour)) |
| + backdate(t, f.credential.App, "auth_time", time.Now().Add(-time.Hour)) |
| stale := exchangeRequest(f.credential.App, "GET", Origin+operatorConfirm, "", nil, paul) |
| if stale.Code != 303 || stale.Header().Get("Location") != "/signin?return_to=%2Foperator%2Fconfirm" { |
| t.Fatal("stale session", stale.Code, stale.Header().Get("Location")) |
| @@ -270,7 +270,7 @@ func TestOperatorEndToEndProvisioningAndRegistry(t *testing.T) { |
| } |
| intent := namedCookie(t, authorize, assertionIntentCookie) |
| session := signInFully(t, f.credential, sealtest.CanaryAddress) |
| - handoff := exchangeRequest(f.credential.App, "GET", Origin+"/authorize/resume", "", nil, intent, session) |
| + handoff := exchangeRequest(f.credential.App, "POST", Origin+"/authorize/resume", Origin, nil, intent, session) |
| target := "https://" + operatorLabel + ".docs.oficina.works" |
| csp := handoff.Header().Get("Content-Security-Policy") |
| if handoff.Code != 200 || !strings.Contains(csp, "form-action 'self' "+target+" "+directoryOrigin+";") && !strings.HasSuffix(csp, "form-action 'self' "+target+" "+directoryOrigin) { |
diff --git a/internal/home/operator_http_test.go b/internal/home/operator_http_test.go| index b8b3016..c8fcfcd 100644 |
| --- a/internal/home/operator_http_test.go |
| +++ b/internal/home/operator_http_test.go |
| @@ -134,6 +134,9 @@ func newOperatorFixtureConsumers(t *testing.T, consumers map[string]string) *ope |
| capp.flow.Classifier.LookupTXT = func(context.Context, string) ([]string, error) { |
| return nil, errors.New("no resolver in tests") |
| } |
| + // This fixture performs many independent operator ceremonies in one window. |
| + capp.flow.IPBudget = 200 |
| + capp.flow.AddressBudget = 100 |
| f.credential = &testApp{App: capp, mailer: mailer, db: cd, dbPath: credPath} |
| // Directory role. |
| @@ -261,7 +264,8 @@ func (f *operatorFixture) paulDirectory(t *testing.T, credentialSession *http.Co |
| pending := namedCookie(t, start, "__Host-oficina-assertion-pending") |
| authorize := exchangeRequest(f.credential.App, "GET", start.Header().Get("Location"), "", nil, credentialSession) |
| intent := namedCookie(t, authorize, assertionIntentCookie) |
| - resume := exchangeRequest(f.credential.App, "GET", Origin+"/authorize/resume", "", nil, intent, credentialSession) |
| + credentialSession = reauthenticateCredential(t, f.credential, credentialSession) |
| + resume := exchangeRequest(f.credential.App, "POST", Origin+"/authorize/resume", Origin, nil, intent, credentialSession) |
| m := regexp.MustCompile(`name="assertion" value="([^"]+)"`).FindStringSubmatch(resume.Body.String()) |
| if resume.Code != 200 || len(m) != 2 { |
| t.Fatal("resume", resume.Code, resume.Header().Get("Location")) |
diff --git a/internal/home/passkey.go b/internal/home/passkey.go| index 87a084c..7bb04c7 100644 |
| --- a/internal/home/passkey.go |
| +++ b/internal/home/passkey.go |
| @@ -4,6 +4,7 @@ import ( |
| "embed" |
| "encoding/base64" |
| "net/http" |
| + "strings" |
| "time" |
| "amadan.net/rastrillo/rastrillo/passkey" |
| @@ -19,62 +20,13 @@ var staticFS embed.FS |
| // depend on a default in another package staying put. |
| const confirmPath = "/passkey/confirm" |
| -// codesFreshness is how recent a session must be to see recovery codes. |
| -// |
| -// Short, because the page shows ten codes once. Long enough to exceed a |
| -// passkey ceremony round trip, or enrolling and then being asked for |
| -// your codes would bounce straight back to a step-up. |
| -// |
| -// A FACT ABOUT RequireFresh THAT A LATER STEP MUST NOT ASSUME AWAY: |
| -// freshness is not the same as "a real assertion". passkey.SignInRecovery |
| -// mints its session with AuthTime: time.Now(), so redeeming a recovery |
| -// code produces a session that satisfies RequireFresh at any duration. |
| -// That is right here — somebody who just proved possession of a recovery |
| -// code should be able to replace the set — but §5.2 says recovery is |
| -// "sign-in only — step-up still demands a real assertion", and |
| -// RequireFresh alone does not deliver that. §14's owner write is |
| -// specified to sit behind step-up; if it is built on RequireFresh it |
| -// will accept a recovery code instead. Asserted in |
| -// TestRecoveryCodeProducesAFreshSession so the fact cannot change |
| -// silently. |
| -// |
| -// It must be at least enrolFreshness. static/passkey.js sends the |
| -// browser to /passkey/codes the instant registration finishes, so a |
| -// window shorter than the one that let them enrol bounces them to |
| -// re-authenticate at the exact moment they hold a passkey and zero |
| -// recovery codes — the worst possible moment, and precisely the outcome |
| -// the sentence above says this value was chosen to avoid. That sentence |
| -// was true until enrolFreshness was added at a larger value and did not |
| -// revisit it. TestFreshnessWindowsDoNotStrandAnEnroller pins the |
| -// ordering. |
| +// Code generation and enrollment share a freshness window, so a person who |
| +// just enrolled can save codes immediately. Recovery sessions may read the |
| +// count, but must replace their passkey and sign in with it before generating. |
| const codesFreshness = enrolFreshness |
| -// enrolFreshness is how recent a session must be to ADD a passkey. |
| -// |
| -// rastrillo's own RegisterBegin asks only for a valid session, and for |
| -// most apps that is right. It is not right here, because of what the |
| -// Gate plus §5.2 add up to: there is no operator reset, by design. |
| -// |
| -// The vector, spelled out because it is not obvious. Somebody with a |
| -// stolen session cookie — good for 30 days — visits /passkey/enrol and |
| -// enrols THEIR authenticator. From that moment the real owner's magic |
| -// link lands on the Gate and stops, because the Gate demands a passkey |
| -// they do not have; and they have no recovery codes, because they never |
| -// enrolled. A compromise that would have expired with the cookie becomes |
| -// a permanent lockout with nobody to appeal to. |
| -// |
| -// Requiring freshness costs a person who signed in a week ago one more |
| -// sign-in: RequireFresh redirects a stale GET to the sign-in page with |
| -// reauth=1, so it is a detour and not a dead end. It costs an attacker |
| -// the inbox, which is the whole point. |
| -// |
| -// Ten minutes: enrolling means reading a page, deciding, and completing |
| -// an authenticator gesture. The codes page runs on the same window and |
| -// not a shorter one — see codesFreshness, which is defined as this value |
| -// precisely because a shorter one stranded people mid-flow. An earlier |
| -// version of this sentence said "rather than the codes page's five", |
| -// which was true when written and stood falsely for two commits after |
| -// codesFreshness was redefined as this value. |
| +// Adding a passkey needs recent authentication: a stolen thirty-day cookie |
| +// must not become a permanent credential. Recovery uses explicit replacement. |
| const enrolFreshness = 10 * time.Minute |
| // passkeyConfig is the config the app builds. |
| @@ -148,6 +100,14 @@ func (a *App) handlePasskeyEnrol(w http.ResponseWriter, r *http.Request) { |
| http.Redirect(w, r, "/signin", http.StatusSeeOther) |
| return |
| } |
| + if !idFreshSession(sess, enrolFreshness, time.Now()) { |
| + http.Redirect(w, r, "/signin?force=1&return_to=%2Fpasskey%2Fenrol", http.StatusSeeOther) |
| + return |
| + } |
| + if strings.Contains(sess.Method, "recovery") { |
| + http.Redirect(w, r, "/passkey/replace", http.StatusSeeOther) |
| + return |
| + } |
| a.render(w, r, http.StatusOK, "passkey_enrol.html", a.passkeyPageData(sess.Subject, nil)) |
| } |
| @@ -181,7 +141,30 @@ func (a *App) handleRegenerateRecoveryCodes(w http.ResponseWriter, r *http.Reque |
| http.Redirect(w, r, "/signin", http.StatusSeeOther) |
| return |
| } |
| - codes, err := a.passkeys.RegenerateRecoveryCodes(sess.Subject) |
| + tx, now, err := a.idTransaction(r.Context()) |
| + if err != nil { |
| + a.serverError(w, r) |
| + return |
| + } |
| + defer tx.Rollback() |
| + live, _, err := a.idSession(tx, r, now) |
| + if err != nil || live.Subject != sess.Subject || strings.Contains(live.Method, "recovery") || !idFreshSession(live, codesFreshness, time.Unix(now, 0)) { |
| + a.signinFailed(w, r) |
| + return |
| + } |
| + var enrolled int |
| + if tx.QueryRow("SELECT count(*) FROM passkey_credentials WHERE subject=?", sess.Subject).Scan(&enrolled) != nil { |
| + a.serverError(w, r) |
| + return |
| + } |
| + if enrolled == 0 { |
| + http.Redirect(w, r, "/passkey/enrol", http.StatusSeeOther) |
| + return |
| + } |
| + codes, err := generateIDCodes(tx, sess.Subject, now) |
| + if err == nil { |
| + err = tx.Commit() |
| + } |
| if err != nil { |
| a.logger.Error("regenerate recovery codes", "person", sess.Subject, "err", err) |
| a.serverError(w, r) |
diff --git a/internal/home/passkey_test.go b/internal/home/passkey_test.go| index eaf6edf..0a63eca 100644 |
| --- a/internal/home/passkey_test.go |
| +++ b/internal/home/passkey_test.go |
| @@ -40,9 +40,9 @@ func postJSON(t *testing.T, app *testApp, path string, cookie *http.Cookie, body |
| payload = "{}" |
| } |
| req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(payload)) |
| - req.Host = credentialHost |
| + req.Host = app.credentialHost |
| req.Header.Set("Content-Type", "application/json") |
| - req.Header.Set("Origin", Origin) |
| + req.Header.Set("Origin", app.origins.Credential) |
| if cookie != nil { |
| req.AddCookie(cookie) |
| } |
| @@ -78,7 +78,7 @@ func enrol(t *testing.T, app *testApp, cookie *http.Cookie) *authtest.Authentica |
| t.Fatal(err) |
| } |
| challenge := challengeFrom(t, postJSON(t, app, "/passkey/register/begin", cookie, nil)) |
| - clientData, attestation := a.Create(challenge, authtest.Options{RPID: app.credentialHost, Origin: Origin}) |
| + clientData, attestation := a.Create(challenge, authtest.Options{RPID: app.credentialHost, Origin: app.origins.Credential}) |
| rec := postJSON(t, app, "/passkey/register/finish", cookie, map[string]string{ |
| "clientDataJSON": base64.RawURLEncoding.EncodeToString(clientData), |
| "attestationObject": base64.RawURLEncoding.EncodeToString(attestation), |
| @@ -133,10 +133,10 @@ func redeemAfterSignIn(t *testing.T, app *testApp, addr string) *httptest.Respon |
| // can evade a source search, so the search alone is not a security proof. |
| func TestSessionIssuanceStaysAtCredentialAndDirectoryBoundaries(t *testing.T) { |
| got := grepPackage(t, "a.sessions.SignIn(") |
| - if len(got) != 2 || got[0] != "directory.go" || got[1] != "signin.go" { |
| + if len(got) != 1 || got[0] != "directory.go" { |
| t.Fatalf("unexpected app session boundaries: %v", got) |
| } |
| - gate := grepPackage(t, "a.passkeys.Gate(") |
| + gate := grepPackage(t, "a.idGate(") |
| if len(gate) != 1 || gate[0] != "signin.go" { |
| t.Fatalf("credential gate moved: %v", gate) |
| } |
| @@ -167,9 +167,9 @@ func TestRecoveryCodeCompletesSignInWithoutScript(t *testing.T) { |
| form := url.Values{"code": {codes[0]}} |
| req := httptest.NewRequest(http.MethodPost, "/passkey/signin/recovery", strings.NewReader(form.Encode())) |
| - req.Host = credentialHost |
| + req.Host = app.credentialHost |
| req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| - req.Header.Set("Origin", Origin) |
| + req.Header.Set("Origin", app.origins.Credential) |
| for _, c := range (&http.Response{Header: gated.Header()}).Cookies() { |
| req.AddCookie(c) |
| } |
| @@ -194,7 +194,7 @@ func TestRecoveryCodeCompletesSignInWithoutScript(t *testing.T) { |
| func subjectOf(t *testing.T, app *testApp, cookie *http.Cookie) string { |
| t.Helper() |
| req := httptest.NewRequest(http.MethodGet, "/", nil) |
| - req.Host = credentialHost |
| + req.Host = app.credentialHost |
| req.AddCookie(cookie) |
| sess, ok := app.sessions.From(req) |
| if !ok { |
| @@ -209,7 +209,7 @@ func TestScriptAssetsAreServedOnNamedPaths(t *testing.T) { |
| app := newTestApp(t) |
| for _, path := range []string{"/static/webauthn.mjs", "/static/passkey.js"} { |
| req := httptest.NewRequest(http.MethodGet, path, nil) |
| - req.Host = credentialHost |
| + req.Host = app.credentialHost |
| w := httptest.NewRecorder() |
| app.Router().ServeHTTP(w, req) |
| if w.Code != http.StatusOK { |
| @@ -233,7 +233,7 @@ func TestRecoveryCodesPageNeedsAFreshSession(t *testing.T) { |
| get := func() int { |
| req := httptest.NewRequest(http.MethodGet, "/passkey/codes", nil) |
| - req.Host = credentialHost |
| + req.Host = app.credentialHost |
| req.AddCookie(cookie) |
| w := httptest.NewRecorder() |
| app.Router().ServeHTTP(w, req) |
| @@ -285,9 +285,9 @@ func TestRecoveryCodeProducesAFreshSession(t *testing.T) { |
| form := url.Values{"code": {codes[0]}} |
| req := httptest.NewRequest(http.MethodPost, "/passkey/signin/recovery", strings.NewReader(form.Encode())) |
| - req.Host = credentialHost |
| + req.Host = app.credentialHost |
| req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| - req.Header.Set("Origin", Origin) |
| + req.Header.Set("Origin", app.origins.Credential) |
| for _, c := range (&http.Response{Header: gated.Header()}).Cookies() { |
| req.AddCookie(c) |
| } |
| @@ -344,7 +344,7 @@ func TestEnrolmentNeedsAFreshSession(t *testing.T) { |
| // The page itself redirects to re-authenticate rather than 404ing or |
| // 403ing: a detour, not a dead end. |
| req := httptest.NewRequest(http.MethodGet, "/passkey/enrol", nil) |
| - req.Host = credentialHost |
| + req.Host = app.credentialHost |
| req.AddCookie(cookie) |
| w := httptest.NewRecorder() |
| app.Router().ServeHTTP(w, req) |
| @@ -386,7 +386,7 @@ func TestEnrolThenReadCodesWithoutReauthenticating(t *testing.T) { |
| enrol(t, app, cookie) |
| req := httptest.NewRequest(http.MethodGet, "/passkey/codes", nil) |
| - req.Host = credentialHost |
| + req.Host = app.credentialHost |
| req.AddCookie(cookie) |
| w := httptest.NewRecorder() |
| app.Router().ServeHTTP(w, req) |
diff --git a/internal/home/render.go b/internal/home/render.go| index 2ac21ab..072d526 100644 |
| --- a/internal/home/render.go |
| +++ b/internal/home/render.go |
| @@ -101,6 +101,9 @@ func (a *App) render(w http.ResponseWriter, r *http.Request, status int, page st |
| // the opposite of what happened. A page that fails is answered with the |
| // 500 page; if that one fails too, with plain text. |
| func (a *App) renderPage(w http.ResponseWriter, r *http.Request, status int, name string, data any) { |
| + if a.onCredential(r) { |
| + w.Header().Set("Cache-Control", "no-store") |
| + } |
| t, ok := a.renderer.pages[name] |
| if !ok { |
| a.logger.Error("no such page template", "page", name) |
diff --git a/internal/home/runtime.go b/internal/home/runtime.go| index cc8c359..bed7dee 100644 |
| --- a/internal/home/runtime.go |
| +++ b/internal/home/runtime.go |
| @@ -214,7 +214,9 @@ func (cfg Runtime) ServingSchema() *migrate.Set { |
| case "directory": |
| return migrate.Merge(cfg.Schema(), operator.DirectoryHTTPSchema, directorydata.TeamSchema) |
| case "credential": |
| - return migrate.Merge(cfg.Schema(), operator.CredentialHTTPSchema) |
| + return migrate.Merge(cfg.Schema(), operator.CredentialHTTPSchema, identitySchema) |
| + case "": |
| + return migrate.Merge(cfg.Schema(), identitySchema) |
| } |
| return cfg.Schema() |
| } |
diff --git a/internal/home/security.go b/internal/home/security.go| index 20eec76..09386f0 100644 |
| --- a/internal/home/security.go |
| +++ b/internal/home/security.go |
| @@ -33,7 +33,7 @@ func (a *App) securityPolicy(consumer string) string { |
| origins[consumer] = true |
| } |
| // form-action governs a form's redirects too, so the directory's |
| - // sign-out, which 307s its POST on to the credential origin, is |
| + // signed-out page posts a second form to the credential origin and is |
| // blocked in the browser without this. See signoutPath. |
| if a.runtime != nil && a.runtime.role == "directory" { |
| origins[a.origins.Credential] = true |
diff --git a/internal/home/shared_chrome_test.go b/internal/home/shared_chrome_test.go| index e6c3118..0d1373a 100644 |
| --- a/internal/home/shared_chrome_test.go |
| +++ b/internal/home/shared_chrome_test.go |
| @@ -435,7 +435,7 @@ func TestHopKeepsTheSkyPlaceholder(t *testing.T) { |
| p := newExchangePair(t) |
| credential := signInFully(t, p.credential, sealtest.CanaryAddress) |
| _, intent := p.start(t) |
| - rec := exchangeRequest(p.credential.App, "GET", Origin+"/authorize/resume", "", nil, intent, credential) |
| + rec := exchangeRequest(p.credential.App, "POST", Origin+"/authorize/resume", Origin, nil, intent, credential) |
| body := rec.Body.String() |
| if rec.Code != http.StatusOK || !strings.Contains(body, `name="assertion"`) { |
| t.Fatalf("resume: %d", rec.Code) |
diff --git a/internal/home/signin.go b/internal/home/signin.go| index 61ff83c..a0ef3d2 100644 |
| --- a/internal/home/signin.go |
| +++ b/internal/home/signin.go |
| @@ -178,7 +178,7 @@ func (a *App) handleSigninForm(w http.ResponseWriter, r *http.Request) { |
| // form is on screen, so an error page that dropped the override would |
| // send a forced retry straight back to Keymail. |
| func (a *App) renderSigninForm(w http.ResponseWriter, r *http.Request, status int, msg string) { |
| - data := map[string]any{} |
| + data := a.passkeyPageData("", nil) |
| if msg != "" { |
| data["Error"] = msg |
| } |
| @@ -270,7 +270,7 @@ func (a *App) beginFailed(w http.ResponseWriter, r *http.Request, err error) boo |
| // information about whether that address has been tried. |
| a.renderSigninForm(w, r, http.StatusTooManyRequests, "Too many attempts. Try again shortly.") |
| default: |
| - a.logger.Error("signin begin", "err", err) |
| + a.logger.Error("signin begin failed") |
| a.renderSigninForm(w, r, http.StatusInternalServerError, "Something went wrong. Try again.") |
| } |
| return true |
| @@ -354,7 +354,7 @@ func (a *App) handleCallback(w http.ResponseWriter, r *http.Request) { |
| // clock, so a standing Keymail approval would pass as fresh. |
| now := time.Now() |
| if intent, ok := a.readAssertionIntent(r, now); ok && intent.MaxAge != 0 && |
| - !freshGesture(id.AuthTime, now, time.Duration(intent.MaxAge)*time.Second) { |
| + (!freshGesture(id.AuthTime, now, time.Duration(intent.MaxAge)*time.Second) || (intent.Started != 0 && id.AuthTime.Unix() < intent.Started)) { |
| http.Redirect(w, r, "/signin?force=1", http.StatusSeeOther) |
| return |
| } |
| @@ -410,6 +410,10 @@ func (a *App) completeSignIn(w http.ResponseWriter, r *http.Request, id signin.I |
| At: id.At, |
| } |
| + if id.Method == signin.MethodMagicLink { |
| + sess.AuthTime = id.At |
| + } |
| + |
| // The second factor, on BOTH sign-in paths — and on both because |
| // there is one place to put it, not because two call sites were |
| // remembered. handleVerify (the magic link) and handleCallback (the |
| @@ -419,11 +423,11 @@ func (a *App) completeSignIn(w http.ResponseWriter, r *http.Request, id signin.I |
| // the magic-link path is gated and a keymail-upgraded account walks |
| // in through the other one. |
| // |
| - // Gate redirects and reports true when it has taken over. An account |
| - // with no passkey passes through untouched. |
| + // The gate either stores the pending factor or mints the email-only |
| + // session under the same writer transaction as its credential check. |
| target := readReturn(r) |
| writeReturn(w, "/") |
| - gated, err := a.passkeys.Gate(w, requestWithReturn(r, target), sess) |
| + gated, err := a.idGate(w, requestWithReturn(r, target), sess, id.Address) |
| if err != nil { |
| a.logger.Error("passkey gate", "person", ref, "err", err) |
| a.signinFailed(w, r) |
| @@ -433,12 +437,6 @@ func (a *App) completeSignIn(w http.ResponseWriter, r *http.Request, id signin.I |
| return |
| } |
| - if err := a.sessions.SignIn(w, r, sess); err != nil { |
| - a.logger.Error("mint session", "person", ref, "err", err) |
| - a.signinFailed(w, r) |
| - return |
| - } |
| - http.Redirect(w, r, target, http.StatusSeeOther) |
| } |
| // signinFailed is the one answer every failed redemption gets. One page, |
diff --git a/internal/home/signin_return_factor_test.go b/internal/home/signin_return_factor_test.go| index cf3ba27..9c8af06 100644 |
| --- a/internal/home/signin_return_factor_test.go |
| +++ b/internal/home/signin_return_factor_test.go |
| @@ -68,7 +68,7 @@ func TestCredentialReturnSecondFactors(t *testing.T) { |
| if got.Header().Get("Location") != "/passkey/enrol" || sessionCookie(got) == nil { |
| t.Fatalf("recovery continuation=%q status=%d", got.Header().Get("Location"), got.Code) |
| } |
| - if dest := returnRequest(app, "GET", "/passkey/enrol", nil, sessionCookie(got)); dest.Code != 200 { |
| + if dest := returnRequest(app, "GET", "/passkey/enrol", nil, sessionCookie(got)); dest.Code != 303 || dest.Header().Get("Location") != "/passkey/replace" { |
| t.Fatalf("recovery freshness=%d", dest.Code) |
| } |
| } else { |
diff --git a/internal/home/signin_test.go b/internal/home/signin_test.go| index e308d8d..3402a14 100644 |
| --- a/internal/home/signin_test.go |
| +++ b/internal/home/signin_test.go |
| @@ -27,9 +27,9 @@ func signIn(t *testing.T, app *testApp, addr string) *httptest.ResponseRecorder |
| t.Helper() |
| form := url.Values{"address": {addr}} |
| req := httptest.NewRequest(http.MethodPost, "/signin", strings.NewReader(form.Encode())) |
| - req.Host = credentialHost |
| + req.Host = app.credentialHost |
| req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| - req.Header.Set("Origin", Origin) |
| + req.Header.Set("Origin", app.origins.Credential) |
| w := httptest.NewRecorder() |
| app.Router().ServeHTTP(w, req) |
| return w |
| @@ -42,7 +42,7 @@ func capturedLink(t *testing.T, app *testApp) string { |
| if !ok { |
| t.Fatal("no mail was sent") |
| } |
| - i := strings.Index(sent.Body, Origin+linkPath) |
| + i := strings.Index(sent.Body, app.origins.Credential+linkPath) |
| if i < 0 { |
| t.Fatalf("no sign-in link in the mail body: %q", sent.Body) |
| } |
| @@ -66,9 +66,9 @@ func redeem(t *testing.T, app *testApp, token string) *httptest.ResponseRecorder |
| t.Helper() |
| form := url.Values{"token": {token}} |
| req := httptest.NewRequest(http.MethodPost, linkPath, strings.NewReader(form.Encode())) |
| - req.Host = credentialHost |
| + req.Host = app.credentialHost |
| req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| - req.Header.Set("Origin", Origin) |
| + req.Header.Set("Origin", app.origins.Credential) |
| w := httptest.NewRecorder() |
| app.Router().ServeHTTP(w, req) |
| return w |
| @@ -167,7 +167,7 @@ func TestGetDoesNotRedeemTheLink(t *testing.T) { |
| token := capturedLink(t, app) |
| req := httptest.NewRequest(http.MethodGet, linkPath+"?token="+url.QueryEscape(token), nil) |
| - req.Host = credentialHost |
| + req.Host = app.credentialHost |
| w := httptest.NewRecorder() |
| app.Router().ServeHTTP(w, req) |
| @@ -201,7 +201,7 @@ func TestVerifyPageDoesNotDistinguishTokens(t *testing.T) { |
| get := func(token string) *httptest.ResponseRecorder { |
| req := httptest.NewRequest(http.MethodGet, linkPath+"?token="+url.QueryEscape(token), nil) |
| - req.Host = credentialHost |
| + req.Host = app.credentialHost |
| w := httptest.NewRecorder() |
| app.Router().ServeHTTP(w, req) |
| return w |
| @@ -336,7 +336,7 @@ func TestSigninPostRequiresOriginEvidence(t *testing.T) { |
| for _, path := range []string{"/signin", linkPath} { |
| form := url.Values{"address": {"person@example.invalid"}} |
| req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(form.Encode())) |
| - req.Host = credentialHost |
| + req.Host = app.credentialHost |
| req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| w := httptest.NewRecorder() |
| app.Router().ServeHTTP(w, req) |
| @@ -403,7 +403,7 @@ func TestCallbackWithNoPendingCookieMintsNothing(t *testing.T) { |
| "", |
| } { |
| req := httptest.NewRequest(http.MethodGet, callbackPath+q, nil) |
| - req.Host = credentialHost |
| + req.Host = app.credentialHost |
| w := httptest.NewRecorder() |
| app.Router().ServeHTTP(w, req) |
| @@ -439,7 +439,7 @@ func TestForgedPendingBlobIsRefused(t *testing.T) { |
| app := newTestApp(t) |
| req := httptest.NewRequest(http.MethodGet, callbackPath+"?code=x&state=s", nil) |
| - req.Host = credentialHost |
| + req.Host = app.credentialHost |
| req.AddCookie(&http.Cookie{ |
| Name: pendingCookie, |
| // Well-formed shape — payload.mac — with a MAC that is not one. |
| @@ -470,9 +470,9 @@ func TestSigninIsRateLimitedPerIPNotGlobally(t *testing.T) { |
| post := func(ip, addr string) int { |
| form := url.Values{"address": {addr}} |
| req := httptest.NewRequest(http.MethodPost, "/signin", strings.NewReader(form.Encode())) |
| - req.Host = credentialHost |
| + req.Host = app.credentialHost |
| req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| - req.Header.Set("Origin", Origin) |
| + req.Header.Set("Origin", app.origins.Credential) |
| req.Header.Set("X-Forwarded-For", ip) |
| w := httptest.NewRecorder() |
| app.Router().ServeHTTP(w, req) |
| @@ -509,9 +509,9 @@ func TestSigninIsRateLimitedPerAddress(t *testing.T) { |
| for i := range 12 { |
| form := url.Values{"address": {"target@example.invalid"}} |
| req := httptest.NewRequest(http.MethodPost, "/signin", strings.NewReader(form.Encode())) |
| - req.Host = credentialHost |
| + req.Host = app.credentialHost |
| req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| - req.Header.Set("Origin", Origin) |
| + req.Header.Set("Origin", app.origins.Credential) |
| req.Header.Set("X-Forwarded-For", fmt.Sprintf("198.51.100.%d", i+1)) |
| w := httptest.NewRecorder() |
| app.Router().ServeHTTP(w, req) |
| @@ -538,7 +538,7 @@ func TestVerifyPageWritesNothing(t *testing.T) { |
| before := dumpDatabase(t, app) |
| for _, tok := range []string{token, "not-a-real-token", ""} { |
| req := httptest.NewRequest(http.MethodGet, linkPath+"?token="+url.QueryEscape(tok), nil) |
| - req.Host = credentialHost |
| + req.Host = app.credentialHost |
| app.Router().ServeHTTP(httptest.NewRecorder(), req) |
| } |
| if after := dumpDatabase(t, app); after != before { |
diff --git a/internal/home/signout.go b/internal/home/signout.go| index 5a884fa..9b3eac3 100644 |
| --- a/internal/home/signout.go |
| +++ b/internal/home/signout.go |
| @@ -3,36 +3,15 @@ package home |
| import ( |
| "net/http" |
| "net/url" |
| - "strings" |
| "amadan.net/rastrillo/rastrillo/csrf" |
| + "golang.org/x/net/publicsuffix" |
| ) |
| -// signoutPath is the same path on the credential origin, the directory |
| -// and every connected app. A consumer's POST /signout (the directory's, |
| -// or an app's through home/connect's Routes.Signout) ends its own session |
| -// and answers 307 to the credential origin's POST /signout, which ends |
| -// the id.* session and lands the browser on that consumer's /signed-out. |
| -// |
| -// Both halves are needed. The directory session is only the app list; |
| -// the credential session is what /authorize reads, and it lives 30 days. |
| -// Ending just the first (as sign-out did until polish-audit B2) made |
| -// "You are signed out" a promise the next click broke: Sign in, from the |
| -// directory or from any app, passed straight back through /authorize |
| -// with no prompt. Round 2 chains each app's own Sign out the same way |
| -// (spec shared-chrome §9.5). |
| -// |
| -// 307 rather than 303 so the hop stays a POST. A GET sign-out is one any |
| -// page can trigger with a link or an <img>; a POST is not. See |
| -// signoutReturn for how the credential side tells a consumer's hand-off |
| -// from anyone else's POST. |
| -// |
| -// What this does NOT end: sessions an app instance minted from an |
| -// earlier assertion. Those are the instance's own sessions on its own |
| -// host, and the home keeps no list of where it has handed an assertion |
| -// (a hibernating fleet would not hear a revocation anyway). Each app's |
| -// own Sign out ends its session; what this guarantees is that no app can |
| -// get a NEW assertion for this browser without the email or passkey step. |
| +// Each origin revokes and lands locally. A consumer may separately offer |
| +// this credential-origin POST as an optional sign-out hop; existing callers |
| +// using that hop remain admitted by exact registration and origin evidence. |
| +// There is no cross-origin or global session-revocation promise. |
| const signoutPath = "/signout" |
| // handleCredentialSignout ends the credential-origin session. |
| @@ -82,7 +61,7 @@ func (a *App) handleCredentialSignoutPage(w http.ResponseWriter, r *http.Request |
| // nothing else: not an unregistered team instance on the same site, not |
| // any other origin, not a request with no evidence. It returns the origin |
| // the browser goes back to, which is always the matched registration |
| -// (the directory, for this origin's own button), and never anything the |
| +// (this credential origin for its own button), and never anything the |
| // request supplied. So there is no open redirect to close. |
| // |
| // HOME_CONSUMERS is the allowlist that already decides who may receive an |
| @@ -130,7 +109,7 @@ const ( |
| func (a *App) signoutReturn(r *http.Request) (string, signoutVerdict) { |
| if csrf.SameOrigin(r, a.origins.Credential) { |
| - return a.origins.Directory, signoutAdmitted |
| + return a.origins.Credential, signoutAdmitted |
| } |
| claimed := r.Header.Get("Origin") |
| if claimed == "" || claimed == "null" { |
| @@ -180,18 +159,24 @@ func (a *App) consumerOrigin(origin string) (string, bool) { |
| return "", false |
| } |
| -// onSuiteSite reports whether origin's hostname is the directory's host |
| -// or under it. The directory is the suite's apex (oficina.works), and the |
| -// credential origin and every team instance sit under it, so this is the |
| -// site a browser's Sec-Fetch-Site compares against. A site has no port, |
| -// so the hostname is compared, never the host: a registered team on :8443 |
| -// is still same-site (the #74 review, finding 2). The caller keeps the |
| -// full origin, port included, for the redirect. |
| +// onSuiteSite compares schemeful sites with the credential origin. Configured |
| +// directory origins may be cross-site, and their Lax ID cookie is then absent. |
| func (a *App) onSuiteSite(origin string) bool { |
| - u, err := url.Parse(origin) |
| + consumer, err := url.Parse(origin) |
| + if err != nil { |
| + return false |
| + } |
| + issuer, err := url.Parse(a.origins.Credential) |
| + if err != nil || consumer.Scheme != issuer.Scheme { |
| + return false |
| + } |
| + if consumer.Hostname() == issuer.Hostname() { |
| + return true |
| + } |
| + site, err := publicsuffix.EffectiveTLDPlusOne(issuer.Hostname()) |
| if err != nil { |
| return false |
| } |
| - host := u.Hostname() |
| - return host == a.directoryHost || strings.HasSuffix(host, "."+a.directoryHost) |
| + other, err := publicsuffix.EffectiveTLDPlusOne(consumer.Hostname()) |
| + return err == nil && site == other |
| } |
diff --git a/internal/home/signout_test.go b/internal/home/signout_test.go| index 434724d..40228c7 100644 |
| --- a/internal/home/signout_test.go |
| +++ b/internal/home/signout_test.go |
| @@ -4,6 +4,7 @@ import ( |
| "net/http" |
| "net/http/httptest" |
| "net/url" |
| + "regexp" |
| "strings" |
| "testing" |
| @@ -26,11 +27,11 @@ func signedInPair(t *testing.T, p exchangePair) (credential, directory *http.Coo |
| func resumeMints(t *testing.T, p exchangePair, credential *http.Cookie) bool { |
| t.Helper() |
| _, intent := p.start(t) |
| - rec := exchangeRequest(p.credential.App, "GET", Origin+"/authorize/resume", "", nil, intent, credential) |
| + rec := exchangeRequest(p.credential.App, "POST", Origin+"/authorize/resume", Origin, nil, intent, credential) |
| switch { |
| case rec.Code == 200 && strings.Contains(rec.Body.String(), `name="assertion"`): |
| return true |
| - case rec.Code == 303 && strings.HasPrefix(rec.Header().Get("Location"), "/signin"): |
| + case rec.Code == 403 || (rec.Code == 303 && strings.HasPrefix(rec.Header().Get("Location"), "/signin")): |
| return false |
| } |
| t.Fatalf("resume answered %d %q", rec.Code, rec.Header().Get("Location")) |
| @@ -73,25 +74,23 @@ func TestSignOutEndsTheCredentialSession(t *testing.T) { |
| t.Fatal("precondition: a live credential session mints silently") |
| } |
| - // The directory ends its own session, then hands the same POST on to |
| - // the credential origin. 307, not 303: the method has to survive so |
| - // the credential origin receives a POST it can origin-check, rather |
| - // than a GET anyone could link to. |
| out := exchangeRequest(p.directory, "POST", directoryOrigin+"/signout", directoryOrigin, url.Values{}, directory) |
| - if out.Code != http.StatusTemporaryRedirect || out.Header().Get("Location") != Origin+"/signout" { |
| - t.Fatalf("directory sign-out: %d %q", out.Code, out.Header().Get("Location")) |
| + if out.Code != http.StatusSeeOther || out.Header().Get("Location") != "/signed-out" { |
| + t.Fatal("local landing missing") |
| } |
| if !clearsCookie(out, directory.Name) { |
| - t.Fatal("directory sign-out left its cookie") |
| + t.Fatal("directory cookie survived") |
| } |
| - if page := exchangeRequest(p.directory, "GET", directoryOrigin+"/", "", nil, directory); strings.Contains(page.Body.String(), "You are signed in.") { |
| - t.Fatal("directory session survived sign-out") |
| + landing := exchangeRequest(p.directory, "GET", directoryOrigin+out.Header().Get("Location"), "", nil, out.Result().Cookies()...) |
| + action := signoutFormAction(t, landing.Body.String()) |
| + if action != Origin+"/signout" { |
| + t.Fatal("wrong issuer form action", action) |
| } |
| - |
| - // The browser re-sends the POST to id.*. These are the headers |
| - // Chromium really sends on that hop (captured live, polish-audit B2): |
| - // the 307 nulls Origin, so the directory is named by Referer alone. |
| - end := signoutHop(p, "null", "same-site", directoryOrigin+"/", credential) |
| + if !strings.Contains(landing.Body.String(), "/static/assertion.js") { |
| + t.Fatal("automatic second step missing") |
| + } |
| + // Follow the page's actual form, preserving its method and browser origin. |
| + end := exchangeRequest(p.credential.App, "POST", action, directoryOrigin, url.Values{}, credential) |
| if end.Code != http.StatusSeeOther || end.Header().Get("Location") != directoryOrigin+"/signed-out" { |
| t.Fatalf("credential sign-out: %d %q", end.Code, end.Header().Get("Location")) |
| } |
| @@ -102,6 +101,14 @@ func TestSignOutEndsTheCredentialSession(t *testing.T) { |
| t.Fatal("sign-out response cacheable") |
| } |
| + returned := exchangeRequest(p.directory, "GET", end.Header().Get("Location"), "", nil, landing.Result().Cookies()...) |
| + if returned.Code != 200 || strings.Contains(returned.Body.String(), "data-assertion-handoff") { |
| + t.Fatal("signout return loops") |
| + } |
| + if page := exchangeRequest(p.directory, "GET", directoryOrigin+"/", "", nil, directory); strings.Contains(page.Body.String(), "You are signed in.") { |
| + t.Fatal("directory session survived") |
| + } |
| + |
| // The cookie is gone from the browser, but a copy of it must not work |
| // either: the row is revoked, not merely forgotten. |
| if resumeMints(t, p, credential) { |
| @@ -342,7 +349,7 @@ func TestCredentialSignOutRefusalIsBrandedAndRecoverable(t *testing.T) { |
| r.AddCookie(credential) |
| rec := httptest.NewRecorder() |
| p.credential.Router().ServeHTTP(rec, r) |
| - if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != directoryOrigin+"/signed-out" { |
| + if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != Origin+"/signed-out" { |
| t.Fatalf("Finish signing out button: %d %q", rec.Code, rec.Header().Get("Location")) |
| } |
| if resumeMints(t, p, credential) { |
| @@ -382,7 +389,7 @@ func TestCredentialSignOutFromAPreviewConfirmsFirst(t *testing.T) { |
| r.AddCookie(credential) |
| confirm := httptest.NewRecorder() |
| p.credential.Router().ServeHTTP(confirm, r) |
| - if confirm.Code != http.StatusSeeOther || confirm.Header().Get("Location") != directoryOrigin+"/signed-out" || !clearsCookie(confirm, credential.Name) { |
| + if confirm.Code != http.StatusSeeOther || confirm.Header().Get("Location") != Origin+"/signed-out" || !clearsCookie(confirm, credential.Name) { |
| t.Fatalf("%+v: confirm %d %q", c, confirm.Code, confirm.Header().Get("Location")) |
| } |
| // The row is revoked, so a copy of the old cookie is refused. |
| @@ -420,3 +427,42 @@ func TestCredentialSignOutKeepsASuiteOriginsPort(t *testing.T) { |
| t.Fatal("ported suite origin admitted cross-site", rec.Code) |
| } |
| } |
| + |
| +func signoutFormAction(t *testing.T, body string) string { |
| + t.Helper() |
| + m := regexp.MustCompile(`<form method="post" action="([^"]+)"[^>]*data-assertion-handoff`).FindStringSubmatch(body) |
| + if len(m) != 2 || !strings.Contains(body, "Sign out of Oficina ID</button>") { |
| + t.Fatal("signed-out page has no issuer POST and fallback button") |
| + } |
| + return m[1] |
| +} |
| + |
| +func TestCredentialSignoutUsesIssuerSite(t *testing.T) { |
| + p := newExchangePair(t) |
| + a := p.credential.App |
| + a.origins = Origins{"https://id.example.org", "https://directory.example.test"} |
| + a.directoryHost = "directory.example.test" |
| + a.runtime.consumers["directory"] = a.origins.Directory |
| + for _, metadata := range []string{"", "cross-site"} { |
| + r := httptest.NewRequest("POST", a.origins.Credential+signoutPath, nil) |
| + r.Header.Set("Origin", a.origins.Directory) |
| + r.Header.Set("Sec-Fetch-Site", metadata) |
| + if _, verdict := a.signoutReturn(r); verdict != signoutConfirm { |
| + t.Fatal("cross-site registered directory must confirm with its ID cookie", metadata, verdict) |
| + } |
| + } |
| + for _, tc := range []struct { |
| + issuer, consumer string |
| + same bool |
| + }{ |
| + {"https://id.example.co.uk", "https://directory.example.co.uk", true}, |
| + {"https://id.example.co.uk", "https://other.co.uk", false}, |
| + {"https://id.oficina.works", "https://blue.docs.oficina.works:8443", true}, |
| + {"https://id.example.org", "http://id.example.org", false}, |
| + } { |
| + a.origins.Credential = tc.issuer |
| + if a.onSuiteSite(tc.consumer) != tc.same { |
| + t.Fatal("incorrect issuer-site classification", tc.issuer, tc.consumer) |
| + } |
| + } |
| +} |
diff --git a/internal/home/static/passkey.js b/internal/home/static/passkey.js| index 74b3fc5..c3dc999 100644 |
| --- a/internal/home/static/passkey.js |
| +++ b/internal/home/static/passkey.js |
| @@ -8,7 +8,7 @@ |
| // of static files (spec ruling superseding 21/24: no script by default, |
| // enhance only, prefer none). Its path is stable so that list can name |
| // it — a rule that cannot name its subject is not a rule. |
| -import { register, authenticate, available } from "/static/webauthn.mjs"; |
| +import { register, authenticate, available, fromB64url, toB64url } from "/static/webauthn.mjs"; |
| async function post(path, body) { |
| const res = await fetch(path, { |
| @@ -36,10 +36,11 @@ function reveal() { |
| for (const el of document.querySelectorAll("[data-passkey]")) el.hidden = false; |
| } |
| -async function enrol(button) { |
| +async function enrol(button, replacement = false) { |
| button.disabled = true; |
| try { |
| - const begin = await post("/passkey/register/begin"); |
| + const path = replacement ? "/passkey/replace" : "/passkey/register"; |
| + const begin = await post(path + "/begin"); |
| const made = await register({ |
| challenge: begin.challenge, |
| rpId: document.body.dataset.rpid, |
| @@ -47,26 +48,27 @@ async function enrol(button) { |
| userId: document.body.dataset.userid, |
| userName: document.body.dataset.username, |
| }); |
| - await post("/passkey/register/finish", { |
| + const done = await post(path + "/finish", { |
| clientDataJSON: made.clientDataJSON, |
| attestationObject: made.attestationObject, |
| }); |
| - window.location.assign("/passkey/codes"); |
| + window.location.assign(done.to || "/passkey/codes"); |
| } catch (err) { |
| say(button, "That did not work. You can try again."); |
| } |
| } |
| -async function confirm(button) { |
| +async function confirm(button, direct = false) { |
| button.disabled = true; |
| try { |
| - const begin = await post("/passkey/signin/begin"); |
| - const got = await authenticate({ |
| + const path = direct ? "/passkey/direct" : "/passkey/signin"; |
| + const begin = await post(path + "/begin"); |
| + const got = begin.credentials?.length ? await authenticateBound(begin) : await authenticate({ |
| challenge: begin.challenge, |
| rpId: document.body.dataset.rpid, |
| legacyRpId: document.body.dataset.legacyrpid || undefined, |
| }); |
| - const done = await post("/passkey/signin/finish", { |
| + const done = await post(path + "/finish", { |
| id: got.credentialId, |
| clientDataJSON: got.clientDataJSON, |
| authenticatorData: got.authenticatorData, |
| @@ -74,10 +76,30 @@ async function confirm(button) { |
| }); |
| window.location.assign(done.to || "/"); |
| } catch (err) { |
| - say(button, "That did not work. Use a recovery code below."); |
| + say(button, "That did not work. You can try again."); |
| } |
| } |
| reveal(); |
| document.getElementById("passkey-enrol")?.addEventListener("click", (e) => enrol(e.currentTarget)); |
| document.getElementById("passkey-confirm")?.addEventListener("click", (e) => confirm(e.currentTarget)); |
| + |
| +document.getElementById("passkey-direct")?.addEventListener("click", (e) => confirm(e.currentTarget, true)); |
| + |
| +document.getElementById("passkey-replace")?.addEventListener("click", (e) => enrol(e.currentTarget, true)); |
| + |
| +async function authenticateBound(begin) { |
| + const credential = await navigator.credentials.get({ publicKey: { |
| + challenge: fromB64url(begin.challenge), |
| + rpId: document.body.dataset.rpid, |
| + allowCredentials: begin.credentials.map((id) => ({ type: "public-key", id: fromB64url(id) })), |
| + userVerification: "required", |
| + }}); |
| + if (!credential) throw new Error("ceremony failed"); |
| + return { |
| + credentialId: toB64url(credential.rawId), |
| + clientDataJSON: toB64url(credential.response.clientDataJSON), |
| + authenticatorData: toB64url(credential.response.authenticatorData), |
| + signature: toB64url(credential.response.signature), |
| + }; |
| +} |
diff --git a/internal/home/team_add_test.go b/internal/home/team_add_test.go| index 51d5a14..7e24835 100644 |
| --- a/internal/home/team_add_test.go |
| +++ b/internal/home/team_add_test.go |
| @@ -199,6 +199,14 @@ func TestResolvedRefusals(t *testing.T) { |
| f.member(t, f.sqid, secondOwner, "owner") |
| foreign := &http.Cookie{Name: teamIntentCookie, Value: fixtureToken(77)} |
| + payload, encodedSignature, _ := strings.Cut(a.receipt, ".") |
| + signature, err := base64.RawURLEncoding.DecodeString(encodedSignature) |
| + if err != nil || len(signature) == 0 { |
| + t.Fatal("invalid fixture signature") |
| + } |
| + signature[len(signature)-1] ^= 1 |
| + tampered := payload + "." + base64.RawURLEncoding.EncodeToString(signature) |
| + |
| refused := map[string]*httptest.ResponseRecorder{ |
| "wrong Origin": exchangeRequest(f.directory, "POST", directoryOrigin+teamResolvedPath, directoryOrigin, url.Values{"receipt": {a.receipt}}, dir, a.intent), |
| "no Origin": exchangeRequest(f.directory, "POST", directoryOrigin+teamResolvedPath, "", url.Values{"receipt": {a.receipt}}, dir, a.intent), |
| @@ -212,7 +220,7 @@ func TestResolvedRefusals(t *testing.T) { |
| "no session": f.resolved(a.receipt, a.intent), |
| "no intent cookie": f.resolved(a.receipt, dir), |
| "another add's id": f.resolved(a.receipt, dir, foreign), |
| - "tampered": f.resolved(a.receipt[:len(a.receipt)-2]+"AA", dir, a.intent), |
| + "tampered": f.resolved(tampered, dir, a.intent), |
| "oversized": f.resolved(strings.Repeat("A", memberReceiptLimit+1), dir, a.intent), |
| "two fields": exchangeRequest(f.directory, "POST", directoryOrigin+teamResolvedPath, Origin, url.Values{"receipt": {a.receipt}, "team": {"zzzz"}}, dir, a.intent), |
| } |
diff --git a/internal/home/team_page_test.go b/internal/home/team_page_test.go| index 45a5d88..a33565a 100644 |
| --- a/internal/home/team_page_test.go |
| +++ b/internal/home/team_page_test.go |
| @@ -74,7 +74,10 @@ func (f *teamFixture) exchange(t *testing.T, cred *http.Cookie, start, returnTo |
| pending := namedCookie(t, begin, "__Host-oficina-assertion-pending") |
| authorize := exchangeRequest(f.credential.App, "GET", begin.Header().Get("Location"), "", nil, cred) |
| intent := namedCookie(t, authorize, assertionIntentCookie) |
| - resume := exchangeRequest(f.credential.App, "GET", Origin+"/authorize/resume", "", nil, intent, cred) |
| + if strings.Contains(begin.Header().Get("Location"), "max_age=300") { |
| + cred = reauthenticateCredential(t, f.credential, cred) |
| + } |
| + resume := exchangeRequest(f.credential.App, "POST", Origin+"/authorize/resume", Origin, nil, intent, cred) |
| m := regexp.MustCompile(`name="assertion" value="([^"]+)"`).FindStringSubmatch(resume.Body.String()) |
| if resume.Code != 200 || len(m) != 2 { |
| t.Fatal("resume", resume.Code, resume.Header().Get("Location")) |
diff --git a/internal/home/templates/directory_signed_out.html b/internal/home/templates/directory_signed_out.html| index d427a1a..dab7ccf 100644 |
| --- a/internal/home/templates/directory_signed_out.html |
| +++ b/internal/home/templates/directory_signed_out.html |
| @@ -1,6 +1,14 @@ |
| -{{define "title"}}{{signedOutDoor.Title}}{{end}} |
| -{{define "content"}}{{with signedOutDoor}} |
| +{{define "title"}}{{if .Data.Finish}}Sign out · Oficina{{else}}{{signedOutDoor.Title}}{{end}}{{end}} |
| +{{define "content"}} |
| +{{if .Data.Finish}} |
| +<h1>Finish signing out</h1> |
| +<p estilo-signin-body>You are signed out of the directory. Finish signing out of Oficina ID before leaving this device.</p> |
| +<form method="post" action="{{.Data.Action}}" data-assertion-handoff rst-form> |
| +<button type="submit" rst-btn="primary">Sign out of Oficina ID</button> |
| +</form> |
| +{{else}}{{with signedOutDoor}} |
| <h1>{{.Heading}}</h1> |
| -<p estilo-signin-body>{{.Body}}</p> |
| +<p estilo-signin-body>You are signed out of the directory in this browser.</p> |
| <p><a href="{{.Link.Href}}" rst-btn="primary">{{.Link.Label}}</a></p> |
| -{{end}}{{end}} |
| +{{end}}{{end}}{{end}} |
| +{{define "scripts"}}{{if .Data.Finish}}<script src='{{v "/static/assertion.js"}}' async></script>{{end}}{{end}} |
diff --git a/internal/home/templates/id_continue.html b/internal/home/templates/id_continue.html| new file mode 100644 |
| index 0000000..90e4f07 |
| --- /dev/null |
| +++ b/internal/home/templates/id_continue.html |
| @@ -0,0 +1,7 @@ |
| +{{define "title"}}Continue to the app · Oficina{{end}} |
| +{{define "content"}} |
| +<h1>Continue to the app</h1> |
| +<form method="post" action="/authorize/resume" rst-form> |
| +<button type="submit" rst-btn="primary">Continue</button> |
| +</form> |
| +{{end}} |
diff --git a/internal/home/templates/id_replace.html b/internal/home/templates/id_replace.html| new file mode 100644 |
| index 0000000..395defe |
| --- /dev/null |
| +++ b/internal/home/templates/id_replace.html |
| @@ -0,0 +1,10 @@ |
| +{{define "title"}}Replace passkeys · Oficina{{end}} |
| +{{define "bodyattrs"}} data-rpid="{{.Data.RPID}}" data-userid="{{.Data.UserID}}" data-username="{{.Data.UserName}}"{{end}} |
| +{{define "content"}} |
| +<h1>Replace your passkeys</h1> |
| +<p rst-callout rst-tone="warning"><span rst-callout-body>Adding a replacement removes all your existing passkeys, signs you out of Oficina ID on every device, and invalidates all your recovery codes. You may remain signed in to the directory and other apps. Sign in with the new passkey before creating new recovery codes.</span></p> |
| +<button id="passkey-replace" type="button" rst-btn="danger" data-passkey hidden>Replace all passkeys</button> |
| +<p id="passkey-status" role="status"></p> |
| +<noscript><p>Turn on JavaScript to add your replacement passkey.</p></noscript> |
| +{{end}} |
| +{{define "scripts"}}<script type="module" src="/static/passkey.js"></script>{{end}} |
diff --git a/internal/home/templates/id_replaced.html b/internal/home/templates/id_replaced.html| new file mode 100644 |
| index 0000000..d907015 |
| --- /dev/null |
| +++ b/internal/home/templates/id_replaced.html |
| @@ -0,0 +1,10 @@ |
| +{{define "title"}}Passkeys replaced · Oficina{{end}} |
| +{{define "content"}} |
| +<h1>Your passkeys were replaced</h1> |
| +<p>You are signed out of Oficina ID on every device. Your previous passkeys and recovery codes no longer work. You may remain signed in to the directory and other apps. Sign in with your new passkey to create new recovery codes.</p> |
| +{{if .Data.NoticeFailed}} |
| +<p role="alert">Your passkeys were replaced, but we could not send the confirmation email.</p> |
| +{{if .Data.CanRetry}}<form method="post" action="/passkey/notice" rst-form><button type="submit" rst-btn>Send email again</button></form>{{else}}<p>The confirmation email can no longer be sent from this page.</p>{{end}} |
| +{{end}} |
| +<a href="/signin?return_to=%2Fpasskey%2Fcodes" rst-btn="primary">Sign in with your new passkey</a> |
| +{{end}} |
diff --git a/internal/home/templates/id_signed_out.html b/internal/home/templates/id_signed_out.html| new file mode 100644 |
| index 0000000..508fa06 |
| --- /dev/null |
| +++ b/internal/home/templates/id_signed_out.html |
| @@ -0,0 +1,6 @@ |
| +{{define "title"}}Signed out · Oficina{{end}} |
| +{{define "content"}} |
| +<h1>You are signed out</h1> |
| +<p>You are signed out of Oficina ID in this browser.</p> |
| +<a href="/signin" rst-btn="primary">Sign in</a> |
| +{{end}} |
diff --git a/internal/home/templates/passkey_enrol.html b/internal/home/templates/passkey_enrol.html| index 09a06d3..32c3ad8 100644 |
| --- a/internal/home/templates/passkey_enrol.html |
| +++ b/internal/home/templates/passkey_enrol.html |
| @@ -2,8 +2,7 @@ |
| {{define "bodyattrs"}} data-rpid="{{.Data.RPID}}" data-userid="{{.Data.UserID}}" data-username="{{.Data.UserName}}"{{end}} |
| {{define "content"}} |
| <h1>Add a passkey</h1> |
| -<p>A passkey is an optional second step. Without one, your email link is |
| -the only thing standing between someone with your inbox and your account.</p> |
| +<p>Add a passkey to sign in without entering your email. JavaScript is needed to add and use passkeys.</p> |
| <button id="passkey-enrol" type="button" rst-btn="primary" data-passkey hidden>Add a passkey</button> |
| <p id="passkey-status" role="status"></p> |
| <noscript><p rst-callout><span rst-callout-body>Adding a passkey needs JavaScript. Everything else here does not.</span></p></noscript> |
diff --git a/internal/home/templates/signin.html b/internal/home/templates/signin.html| index 2c2f816..6a6ca3c 100644 |
| --- a/internal/home/templates/signin.html |
| +++ b/internal/home/templates/signin.html |
| @@ -1,6 +1,8 @@ |
| {{define "title"}}{{signinDoor.Title}}{{end}} |
| {{define "content"}}{{with signinDoor}} |
| <h1>{{.Heading}}</h1> |
| +<button id="passkey-direct" type="button" rst-btn="primary" data-passkey hidden>Sign in with a passkey</button> |
| +<p id="passkey-status" role="status"></p> |
| {{if $.Data.Error}}<p role="alert" rst-callout rst-tone="negative"><span rst-callout-body>{{$.Data.Error}}</span></p>{{end}} |
| <form method="post" action="{{with $.Data.Action}}{{.}}{{else}}/signin{{end}}" rst-form estilo-signin-form> |
| <div rst-field> |
| @@ -13,3 +15,6 @@ |
| </div> |
| </form> |
| {{end}}{{end}} |
| + |
| +{{define "bodyattrs"}} data-rpid="{{.Data.RPID}}" data-legacyrpid="{{.Data.LegacyRPID}}"{{end}} |
| +{{define "scripts"}}<script type="module" src="/static/passkey.js"></script>{{end}} |
diff --git a/internal/home/testapp_test.go b/internal/home/testapp_test.go| index 386f114..7398c80 100644 |
| --- a/internal/home/testapp_test.go |
| +++ b/internal/home/testapp_test.go |
| @@ -114,7 +114,7 @@ func newTestAppWithOrigins(t *testing.T, origins Origins) *testApp { |
| } |
| t.Cleanup(func() { d.Close() }) |
| - if _, err := migrate.Apply(context.Background(), d, BootSchema); err != nil { |
| + if _, err := migrate.Apply(context.Background(), d, (Runtime{}).ServingSchema()); err != nil { |
| t.Fatalf("migrate.Apply: %v", err) |
| } |
diff --git a/scripts/check-id-mutations.py b/scripts/check-id-mutations.py| new file mode 100755 |
| index 0000000..19928a6 |
| --- /dev/null |
| +++ b/scripts/check-id-mutations.py |
| @@ -0,0 +1,178 @@ |
| +#!/usr/bin/env python3 |
| +"""Remove one ID guard at a time, run its regression, and restore the source.""" |
| +import json |
| +import os |
| +from pathlib import Path |
| +import subprocess |
| +import sys |
| +import time |
| + |
| +ROOT = Path(__file__).resolve().parent.parent |
| +HOME = ROOT / "internal/home" |
| +# Guard, file, exact source, replacement, test expression. |
| +CASES = [ |
| + ("continue gesture", "exchange.go", "if r.Method == http.MethodGet {", "if false && r.Method == http.MethodGet {", "TestIDContinueBeforeMinting"), |
| + ("link new session", "exchange.go", "sameSession ||", "(sameSession && false) ||", "TestIDLinkAlwaysRequiresNewGesture"), |
| + ("link transaction start", "exchange.go", "authTime.Unix() < intent.Started", "authTime.Unix() < 0", "TestIDLinkRejectsProofBeforeTransactionStart"), |
| + ("passive Keymail issuance", "exchange.go", "|| keymailWithoutGesture(session)", "|| (false && keymailWithoutGesture(session))", "TestIDLinkRejectsPassiveMintedSession"), |
| + ("live issuance session", "exchange.go", "session, _, err := a.idSession(tx, r, now.Unix())", "session, _ := sessions.Current(r)", "TestIDRevokedCachedSessionCannotMint"), |
| + ("audience", "exchange.go", "Audience: target", "Audience: a.origins.Credential", "TestHomeDirectoryExchangeAndPrivacy"), |
| + ("nonce", "exchange.go", "Nonce: intent.Nonce", "Nonce: id", "TestHomeDirectoryExchangeAndPrivacy"), |
| + ("assertion lifetime", "exchange.go", "ExpiresAt: now.Unix() + 120", "ExpiresAt: now.Unix() + 121", "TestHomeDirectoryExchangeAndPrivacy"), |
| + ("cookie ambiguity", "id_passkey.go", "count != 1 || len(value) > 4096", "count < 1 || len(value) > 4096", "TestIDChallengeBrowserCookiesAndExpiry/duplicate"), |
| + ("clock rollback", "id_passkey.go", "err != nil || now < high", "err != nil || (now < high && false)", "TestIDChallengeBrowserCookiesAndExpiry/clock"), |
| + ("future enrollment time", "id_passkey.go", "&& !at.After(now)", "&& (!at.After(now) || true)", "TestIDEnrollmentRejectsFutureAndPassiveAuthentication/future"), |
| + ("passive enrollment", "id_passkey.go", "!keymailWithoutGesture(s) &&", "(!keymailWithoutGesture(s) || true) &&", "TestIDEnrollmentRejectsFutureAndPassiveAuthentication/passive"), |
| + ("challenge capacity", "id_passkey.go", "n >= 10000", "n >= 100000", "TestIDChallengeBrowserCookiesAndExpiry/capacity"), |
| + ("challenge lifetime", "id_passkey.go", "purpose, now+300", "purpose, now+600", "TestIDGatedChallengeGuards/ttl"), |
| + ("challenge browser", "id_passkey.go", "WHERE challenge=? AND browser_hash=? AND", "WHERE challenge=? AND (? IS NOT NULL) AND", "TestIDGatedChallengeGuards/browser"), |
| + ("challenge subject", "id_passkey.go", "AND subject=? AND purpose=?", "AND (? IS NOT NULL) AND purpose=?", "TestIDRegistrationChallengeSubjectAndLiveSession/subject"), |
| + ("challenge purpose", "id_passkey.go", "AND purpose=? AND expires_at>? RETURNING", "AND (? IS NOT NULL) AND expires_at>? RETURNING", "TestIDGatedChallengeGuards/purpose"), |
| + ("challenge expiry", "id_passkey.go", "AND expires_at>? RETURNING challenge", "AND (? IS NOT NULL) RETURNING challenge", "TestIDGatedChallengeGuards/expiry"), |
| + ("challenge single use", "id_passkey.go", "DELETE FROM home_id_ceremonies WHERE challenge=? AND browser_hash=? AND subject=? AND purpose=? AND expires_at>? RETURNING challenge", "SELECT challenge FROM home_id_ceremonies WHERE challenge=? AND browser_hash=? AND subject=? AND purpose=? AND expires_at>?", "TestIDGatedChallengeGuards/single-use"), |
| + ("strict ceremony JSON", "id_passkey.go", "strictjson.UnmarshalRead(http.MaxBytesReader(w, r.Body, 64<<10), &body, strictjson.RejectUnknownMembers(true))", "decodeLooseIDJSON(r, &body)", "TestIDCeremonyRejectsAmbiguousJSON"), |
| + ("credential collision", "id_passkey.go", "INSERT INTO passkey_credentials(id,subject,public_key,sign_count,created_at)", "INSERT OR REPLACE INTO passkey_credentials(id,subject,public_key,sign_count,created_at)", "TestIDEnrollmentCannotTransferCredential"), |
| + ("credential enrollment bound", "id_passkey.go", "count >= 100", "count >= 1000", "TestIDEnrollmentBound"), |
| + ("credential owner", "id_passkey.go", '(subject != "" && owner != subject)', '(subject != "" && owner != subject && false)', "TestIDGateBindsCredentialOwner"), |
| + ("discoverable admission", "id_passkey.go", " AND id IN (SELECT credential_id FROM home_id_discoverable)", " AND 1=1", "TestIDLegacyCredentialCannotSignInDirectly"), |
| + ("WebAuthn verification", "id_passkey.go", "next, e := a.idWebAuthn().Verify(cred, challenge, cd, ad, sig)\n\t\tif e != nil {", "next, e := a.idWebAuthn().Verify(cred, challenge, cd, ad, sig)\n\t\te = nil\n\t\tif e != nil {", "TestIDPasskeyRejectsBadProofs/(origin|rp|uv|signature)"), |
| + ("recovery entropy", "id_recovery.go", "rand.Read(raw)", "rand.Read(raw[:6])", "TestIDRecoveryEntropy"), |
| + ("account attempt budget", "id_recovery.go", '{"account:" + subject, 5}', '{"account:" + subject, 500}', "TestIDRecoveryAttemptLimitSurvivesReconstruction"), |
| + ("IP attempt budget", "id_recovery.go", 'blindIndex(a.secrets.Pepper, clientIP(r)), 20}', 'blindIndex(a.secrets.Pepper, clientIP(r)), 200}', "TestIDRecoveryIPLimitAcrossAccounts"), |
| + ("attempt increment", "id_recovery.go", "failures=failures+1", "failures=failures+0", "TestIDRecoveryAttemptLimitSurvivesReconstruction"), |
| + ("attempt persistence", "app.go", "a.signinLimiter = signin.NewMemoryLimiter(15 * time.Minute)", '_, _ = d.Writer().Exec("DELETE FROM home_id_attempts")\n a.signinLimiter = signin.NewMemoryLimiter(15 * time.Minute)', "TestIDRecoveryAttemptLimitSurvivesReconstruction"), |
| + ("mailbox freshness", "id_recovery.go", "if mailboxAt <= 0 || mailboxAt > now || mailboxAt+300 <= now {", "if false && (mailboxAt <= 0 || mailboxAt > now || mailboxAt+300 <= now) {", "TestIDRecoveryMailboxTimeDefense"), |
| + ("recovery code person", "id_recovery.go", "WHERE subject=? AND code_hash=? RETURNING subject", "WHERE (? IS NOT NULL) AND code_hash=? RETURNING subject", "TestIDRecoveryCodePersonBindingAndReplay"), |
| + ("recovery code single use", "id_recovery.go", "DELETE FROM passkey_recovery_codes WHERE subject=? AND code_hash=? RETURNING subject", "SELECT subject FROM passkey_recovery_codes WHERE subject=? AND code_hash=?", "TestIDRecoveryCodePersonBindingAndReplay"), |
| + ("recovery proof expiry", "id_recovery.go", "AND subject=? AND expires_at>?", "AND subject=? AND (? IS NOT NULL)", "TestIDReplacementProofBinding/expired"), |
| + ("recovery proof subject", "id_recovery.go", "AND subject=? AND expires_at>?", "AND (? IS NOT NULL) AND expires_at>?", "TestIDReplacementProofBinding/wrong-person"), |
| + ("recovery proof capacity", "id_recovery.go", "proofCount >= 10000", "proofCount >= 100000", "TestIDRecoveryProofCapacity"), |
| + ("mailbox memory capacity", "id_recovery.go", "len(m.entries) >= 1000", "len(m.entries) >= 1001", "TestIDMailboxMemoryBoundAndExpiry"), |
| + ("mailbox memory expiry", "id_recovery.go", "!ok || p.expires <= time.Now().Unix()", "!ok || (false && p.expires <= time.Now().Unix())", "TestIDMailboxMemoryBoundAndExpiry"), |
| + ("notice outcome", "id_passkey.go", "a.replacementResult(w, !a.sendReplacementNotice(r.Context(), binding))", "a.sendReplacementNotice(r.Context(), binding); a.replacementResult(w, false)", "TestIDNoticeFailureSurvivesRestartWithoutAddress"), |
| + ("SMTP log privacy", "signin.go", 'a.logger.Error("signin begin failed")', 'a.logger.Error("signin begin failed", "err", err)', "TestIDSMTPFailureDoesNotLeak"), |
| + ("limiter address blinding", "id_limiter.go", 'key = "addr:" + blindIndex(l.pepper, address)', 'key = "addr:" + address', "TestIDSigninLimiterUsesBlindedAddress"), |
| + ("local signout", "directory.go", 'http.Redirect(w, r, "/signed-out", http.StatusSeeOther)', 'http.Redirect(w, r, a.origins.Credential+signoutPath, http.StatusTemporaryRedirect)', "TestIDLocalSignoutWithHangingIssuer"), |
| + ("sealed link storage", "links.go", "hash, sealed, purpose, expires.UTC()", "hash, append(sealed[:0], []byte(address)...), purpose, expires.UTC()", "TestFullSigninLeavesNoReadableAddress"), |
| +] |
| +CASES += [ |
| + ("closed authorize fields","exchange.go","len(q) != wantFields", "(len(q) != wantFields && false)", "TestIDClosedAuthorize"), |
| + ("authorize consumer uniqueness","exchange.go", 'len(q["consumer"]) != 1', '(len(q["consumer"]) != 1 && false)', "TestIDClosedAuthorize"), |
| + ("authorize nonce uniqueness","exchange.go", 'len(q["nonce"]) != 1', '(len(q["nonce"]) != 1 && false)', "TestIDClosedAuthorize"), |
| + ("CSRF for sensitive posts","app.go", "csrf.Protect(a.origins.Credential)", 'csrf.Protect("https://evil.invalid")', "TestIDAllSensitivePostsRequireOrigin"), |
| + ("recovery subject defenses together", "id_recovery.go", "AND subject=? AND expires_at>?", "AND (? IS NOT NULL) AND expires_at>?", "TestIDReplacementProofBinding/wrong-person"), |
| +] |
| +CASES += [ |
| + ("registered authorize consumer","exchange.go", 'a.consumers()[q.Get("consumer")] == ""', '(a.consumers()[q.Get("consumer")] == "" && false)', "TestIDClosedAuthorize"), |
| + ("authorize nonce format","exchange.go", '!handoff.ValidNonce(q.Get("nonce"))', '(!handoff.ValidNonce(q.Get("nonce")) && false)', "TestIDClosedAuthorize"), |
| + ("authorize max age","exchange.go", 'len(values) != 1 || values[0] != "300"', '(len(values) != 1 || values[0] != "300") && false', "TestIDClosedAuthorize"), |
| + ("replacement rollback","id_passkey.go", 'defer tx.Rollback()\n\t\tsubject, binding, err :=', 'defer tx.Commit()\n\t\tsubject, binding, err :=', "TestIDReplacementRollback"), |
| + ("email authentication time","signin.go", 'sess.AuthTime = id.At', 'sess.AuthTime = time.Time{}', "TestIDEmailMintPreservesVerificationTime"), |
| + ("codes after enrollment","passkey.go", 'if enrolled == 0 {', 'if enrolled == 0 && false {', "TestIDCodesRequireEnrolledPasskey"), |
| + ("fresh intent start provenance","assertion_intent.go", 'intent.Started <= 0 || intent.Started > now.Unix()', '(intent.Started <= 0 && false) || intent.Started > now.Unix()', "TestIDFreshIntentRequiresStartTime"), |
| +] |
| +CASES += [ |
| + ("credential page cache privacy","render.go", 'w.Header().Set("Cache-Control", "no-store")', 'w.Header().Set("Cache-Control", "")', "TestIDCredentialPagesAreNoStore"), |
| +] |
| +CASES += [ |
| + ("link recovery exclusion", "exchange.go", '|| strings.Contains(session.Method, "recovery")', '|| (false && strings.Contains(session.Method, "recovery"))', "TestIDRecoveryCannotLink"), |
| + ("enrollment recovery exclusion", "id_passkey.go", '|| strings.Contains(s.Method, "recovery")', '|| (false && strings.Contains(s.Method, "recovery"))', "TestIDRecoveryExclusions"), |
| + ("codes recovery exclusion", "passkey.go", '|| strings.Contains(live.Method, "recovery")', '|| (false && strings.Contains(live.Method, "recovery"))', "TestIDRecoveryExclusions"), |
| + ("replacement recovery suffix", "id_recovery.go", '!strings.HasSuffix(s.Method, "+recovery")', '(false && !strings.HasSuffix(s.Method, "+recovery"))', "TestIDReplacementRequiresRecoverySession/method"), |
| + ("replacement session binding", "id_recovery.go", 'AND session_hash=? AND subject=?', 'AND (? IS NOT NULL) AND subject=?', "TestIDReplacementRequiresRecoverySession/session"), |
| + ("limits before code consumption", "id_recovery.go", 'for _, b := range buckets {', 'for _, b := range buckets {', "TestIDLimitsBeforeValidCode"), |
| + ("recovery RAM reservation", "id_recovery.go", '|| !a.mailboxes.put(hash, p)', '|| (false && !a.mailboxes.put(hash, p))', "TestIDRecoveryMailboxFailurePreservesCode/full"), |
| + ("recovery RAM required", "id_recovery.go", '!ok || p.subject != subject ||', 'false ||', "TestIDRecoveryMailboxFailurePreservesCode/missing"), |
| + ("full mailbox permits gate", "id_recovery.go", 'mailboxUnix = 0', 'return false, errIDProof', "TestIDFullMailboxAllowsGatedSignin"), |
| + ("recovery signin notice", "id_recovery.go", 'a.sendRecoverySigninNotice(r.Context(), p.address)', '// notice omitted', "TestIDRecoverySigninNotice$"), |
| + ("new codes after replacement", "id_passkey.go", 'if codes == 0 {', 'if codes == 0 && false {', "TestIDRecoveryReplacementRevokesEverything"), |
| + ("stateless anonymous begin", "id_direct.go", 'idCookie(w, ceremonyCookie,', '_, _ = a.db.Writer().Exec("INSERT INTO home_id_ceremonies VALUES(?,?,?,?,?)", hex.EncodeToString(challenge), "browser", "", "direct", time.Now().Unix()+300)\n idCookie(w, ceremonyCookie,', "TestIDDirectFloodLeavesGatedCapacity"), |
| + ("direct seal authentication", "id_direct.go", 'plain, err := a.secrets.Sealer.Open("id.direct", sealed)', 'plain, err := a.secrets.Sealer.Open("id.direct", sealed)', "TestIDDirectSealedChallenge/tampered"), |
| + ("direct challenge binding", "id_direct.go", 'proof.Challenge != hex.EncodeToString(challenge)', '(proof.Challenge != hex.EncodeToString(challenge) && false)', "TestIDDirectSealedChallenge/mismatch"), |
| + ("direct expiry", "id_direct.go", 'proof.Expires <= now', '(proof.Expires <= now && false)', "TestIDDirectSealedChallenge/expired"), |
| + ("direct maximum lifetime", "id_direct.go", 'proof.Expires > now+300', '(proof.Expires > now+300 && false)', "TestIDDirectSealedChallenge/future"), |
| + ("direct receipt replay", "id_direct.go", 'INSERT INTO home_id_direct_used', 'INSERT OR REPLACE INTO home_id_direct_used', "TestIDDirectPasskey|TestIDDirectReceiptsBounded/restart"), |
| + ("direct receipt cap", "id_direct.go", 'n >= 10000', 'n >= 100000', "TestIDDirectReceiptsBounded/capacity"), |
| + ("direct receipt expiry", "id_direct.go", 'WHERE expires_at<=?', 'WHERE expires_at<? AND 0', "TestIDDirectReceiptsBounded/expiry"), |
| + ("issuer signout form", "directory.go", '"Action": a.origins.Credential + signoutPath', '"Action": a.origins.Directory + signoutPath', "TestSignOutEndsTheCredentialSession"), |
| + ("issuer signout auto step", "directory.go", 'finish := cookieValue(r, "__Host-oficina-finish-signout") == "1"', 'finish := false && cookieValue(r, "__Host-oficina-finish-signout") == "1"', "TestSignOutEndsTheCredentialSession"), |
| + ("issuer signout no loop", "directory.go", 'idCookie(w, "__Host-oficina-finish-signout", "", -1)', 'idCookie(w, "__Host-oficina-finish-signout", "1", 300)', "TestSignOutEndsTheCredentialSession"), |
| + ("issuer signout autosubmit", "static/assertion.js", 'form.requestSubmit()', 'form.checkValidity()', "TestIDBrowserSignoutBothOrigins"), |
| +] |
| +CASES += [ |
| + ("issuer site classification", "signout.go", 'site == other', 'site == other || true', "TestCredentialSignoutUsesIssuerSite"), |
| + ("issuer scheme classification", "signout.go", 'consumer.Scheme != issuer.Scheme', '(false && consumer.Scheme != issuer.Scheme)', "TestCredentialSignoutUsesIssuerSite"), |
| + ("recovery session marked", "id_recovery.go", 'Method: method + "+recovery"', 'Method: method', "TestIDRecoverySigninNotice$"), |
| +] |
| +CASES += [ |
| + ("anonymous begin stores no receipt", "id_direct.go", 'idCookie(w, ceremonyCookie,', '_, _ = a.db.Writer().Exec("INSERT INTO home_id_direct_used VALUES(?,?)", hex.EncodeToString(challenge), time.Now().Unix()+300)\n idCookie(w, ceremonyCookie,', "TestIDDirectFloodLeavesGatedCapacity"), |
| + ("recovery notice log privacy", "id_recovery.go", 'if a.secrets.Mailer.Send(ctx, address, recoverySigninNoticeSubject, recoverySigninNoticeBody) != nil {', 'if err:=a.secrets.Mailer.Send(ctx,address,recoverySigninNoticeSubject,recoverySigninNoticeBody);err!=nil {a.logger.Error("notice failed","err",err)', "TestIDRecoverySigninNoticeFailurePrivacy"), |
| +] |
| +for table in ("sessions", "passkey_credentials", "passkey_recovery_codes", "passkey_pending", "passkey_challenges", "home_id_ceremonies", "home_id_recovery_proofs"): |
| + CASES.append(("replacement revokes " + table,"id_recovery.go",f'\n\t\t"DELETE FROM {table} WHERE subject=?",',f'\n\t\t"DELETE FROM {table} WHERE subject=? AND 0",',"TestIDRecoveryReplacementRevokesEverything")) |
| + |
| +results=[] |
| +selected=set(sys.argv[1:]) |
| +out=ROOT/"implementation/oficina-id-slice1-mutations.json" |
| +previous=json.loads(out.read_text()) if selected and out.exists() else [] |
| +for guard,file,old,new,test in CASES: |
| + if selected and guard not in selected: |
| + continue |
| + path=HOME/file |
| + original=path.read_text() |
| + if original.count(old)!=1 and guard not in ("limits before code consumption", "replacement rollback"): |
| + raise SystemExit(f"{guard}: expected one source match, got {original.count(old)}") |
| + changed=original.replace(old,new) |
| + if guard=="replacement rollback": |
| + before,after=original.rsplit(old,1) |
| + changed=before+new+after |
| + if guard=="limits before code consumption": |
| + start=original.index("\tvar got string\n") |
| + end=original.index("\tif err == sql.ErrNoRows {",start) |
| + deletion=original[start:end] |
| + changed=original[:start]+original[end:] |
| + point=changed.index("\tfor _, b := range buckets {") |
| + changed=changed[:point]+deletion+changed[point:] |
| + if guard=="recovery RAM required": |
| + changed=changed.replace("p, ok := a.mailboxes.get(binding)", "p, _ := a.mailboxes.get(binding)") |
| + if guard=="direct seal authentication": |
| + # Model accepting a forged cookie by treating failed authentication as a |
| + # matching current challenge. A raw 'ignore err' still fails JSON parsing. |
| + changed=changed.replace('if err != nil {\n\t\treturn 0, errIDProof\n\t}\n\tvar proof', 'if err != nil {plain, _ = json.Marshal(directChallenge{hex.EncodeToString(challenge), now+300})}\n\tvar proof') |
| + if guard=="recovery subject defenses together": |
| + changed=changed.replace("!ok || p.subject != subject", "!ok || (p.subject != subject && false)") |
| + if guard=="strict ceremony JSON": |
| + # Keep the strict import used while replacing its behavior for this mutant. |
| + changed+='\nfunc decodeLooseIDJSON(r *http.Request, dst any) error { _ = strictjson.RejectUnknownMembers; return json.NewDecoder(r.Body).Decode(dst) }\n' |
| + start=time.monotonic() |
| + try: |
| + path.write_text(changed) |
| + proc=subprocess.run(["go","test","./internal/home","-count=1","-timeout=60s"]+(["-tags=browser"] if guard=="issuer signout autosubmit" else [])+["-run",test],cwd=ROOT,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True,timeout=75) |
| + output=proc.stdout |
| + if proc.returncode==0: |
| + status="survived" |
| + elif "[build failed]" in output: |
| + status="invalid" |
| + elif "--- FAIL:" in output: |
| + status="killed" |
| + else: |
| + status="error" |
| + failures=[line.strip() for line in output.splitlines() if "--- FAIL:" in line] |
| + except subprocess.TimeoutExpired: |
| + status="timeout";failures=[] |
| + finally: |
| + path.write_text(original) |
| + row={"guard":guard,"file":"internal/home/"+file,"test":test,"result":status,"failures":failures,"seconds":round(time.monotonic()-start,2)} |
| + if status=="survived" and guard=="recovery proof subject": |
| + row["explanation"]="Independent in-memory mailbox subject check still refuses. The paired mutation removes both checks and must fail the same regression." |
| + results.append(row) |
| + snapshot=[r for r in previous if r["guard"] not in {v["guard"] for v in results}]+results |
| + (ROOT/"implementation/oficina-id-slice1-mutations.json").write_text(json.dumps(snapshot,indent=2)+"\n") |
| + print(f"{status}: {guard}",flush=True) |
| + if status in ("invalid","error"): |
| + print(output[-1200:],flush=True) |
| +out=ROOT/"implementation/oficina-id-slice1-mutations.json" |
| +if selected and out.exists(): |
| + results=[r for r in previous if r["guard"] not in selected]+results |
| +out.write_text(json.dumps(results,indent=2)+"\n") |
| +sys.exit(0 if all(r["result"]=="killed" or (r["guard"]=="recovery proof subject" and r["result"]=="survived") for r in results) else 1) |