docs(19.6): security review and validation map

- 19.6-SECURITY-REVIEW.md: T-19.6-01..38 mapped to their tests or accepted
  dispositions, the D-14 passkey section, D-18 hardening, ASVS notes, log
  sweep, residual risks and open finding F-1 (activate-by-code)
- 19.6-VALIDATION.md: validated, one row per task of plans 01-04 with its
  gate stage and tests
This commit is contained in:
2026-10-26 14:59:56 +01:00
parent ea4680eebe
commit 692beb5538
2 changed files with 208 additions and 24 deletions

View File

@@ -0,0 +1,163 @@
# Phase 19.6 Security Review: second factors and device login
**Date:** 2026-10-26
**Level:** OWASP ASVS L1 (RESEARCH "Security Domain"), block on high; D-14 asks for an explicit review of passwordless passkey login.
**Scope:** this phase's sm-user-plugin additions (login gates, the login event, the password-change hook, the Reset 2FA slot, device authorization), the new `sm-mfa-plugin` (gate, challenge store, TOTP and QR, recovery and email codes, failure cap, trusted devices, settings, admin reset, WebAuthn second factor, passwordless passkeys), the social-login gate call in `sm-sociallogin-plugin`, the adoption in sm-demo-app, sm-bm-app and fonoteka.go, and this plan's gate.
**Threats reviewed:** T-19.6-01..T-19.6-38 and the four T-19.6-SC rows of the threat models of plans 01, 02, 03 and 04, plus RESEARCH's Security Domain table and Assumptions A1-A13.
**Result:** every threat is closed by a test that fails when the mitigation is removed, or accepted with a reason. One defect found by the new tests was fixed in its own commit (sm-mfa-plugin `71d8f27`, T-19.6-24). One new finding, **F-1** (activate-by-code mints a token without the second factor when `require_activation` is off), contradicts the reason plan 01 recorded for an accepted mint path; it is open and raised at plan 04's Task 5 checkpoint. T-19.6-37 stays open until the Task 5 reply (one post-release fix to release).
Repositories and abbreviations: **F** = summercms.go, **U** = sm-user-plugin (`fonoteka.go/plugins/golem15/user`), **M** = `sm-mfa-plugin`, **S** = `sm-sociallogin-plugin`, **D** = sm-demo-app (with `vue-demo-app`), **B** = sm-bm-app, **A** = the fonoteka.go workspace.
## Method
1. For each threat, read the code that implements the mitigation and find the test that fails without it. Where a test was missing, plan 04 added it (Tasks 2 and 3) in the owning repository.
2. Mutation checks on the race- and security-sensitive mitigations, each reverted after the run:
- M `classes/challenge.go` `CompleteChallenge` without `AND completed_at IS NULL`: `TestChallengeLifecycle` fails (racing TOTP and recovery verifications mint more than one token).
- M `classes/email.go` `SendEmailCode` without `AND email_sends < 3`: `TestEmailCode` fails.
- M `classes/gate.go` with social sign-ins always allowed: `TestGate` and `TestEveryLoginPathIsGated` fail.
- M `classes/passwordless.go` `passkeyUser` without the `passwordless` column check: `TestPasswordless` fails.
- M `models/settings.go` without the empty-list normalization: `TestSettings` fails.
- U `controllers/devices.go` hand-over UPDATE without `AND status = 'confirmed'`: `TestDeviceHandOverConcurrent` fails.
- U `controllers/devices.go` authorize UPDATE without the pending-only and `user_id` guard: `TestDeviceAuthorize` fails.
- The PHP map: a renamed Go test, a renamed subtest and an extra listed method each fail `TestPHPMethodMap`.
3. Sweeps: every non-test log call of M and of U's device controller (section "Log calls"); every token mint site of U and M (`TestEveryLoginPathIsGated/mint_sites`); the response bodies of RESEARCH Q4's two tables (`TestPHPErrorBodies`).
4. Run the whole gate: `scripts/check-phase19.6.sh --all` on a Docker host.
## Defects fixed during this plan
| Commit | Repo | Threat | Found by | Fix |
|--------|------|--------|----------|-----|
| 71d8f27 | M | T-19.6-24 | `TestSettings/form_round_trip_keeps_the_configuration` | The settings form shows a NULL `two_factor_available_methods` as an empty taglist and sends it back as `[]` on every save, so saving the form once (for example to turn trusted devices on) stored `[]` and made every method unavailable: TOTP setup answered 403, and no user could enable a second factor. An empty list is now an empty value: `Settings.BeforeValidate` stores it as NULL and the overlay ignores an empty stored list (methods and enforce groups), as the README already promised. README and the en and pl comments updated. |
The fix is a production change after plan 03's release (sm-mfa-plugin v0.1.0); it reaches the applications only through a patch release (T-19.6-37, plan 04 Tasks 5 and 6).
## Threat register
| Threat | Component | Mitigation as built | Implementation | Test (repo) | Status |
|--------|-----------|---------------------|----------------|-------------|--------|
| T-19.6-01 | login gate consultation | `Login` asks `CheckLoginGates` after the ban check, password, activation, throttle record and rehash; a result returns its status and body before restore, last_seen, mint and event; a gate error answers the opaque 500. | U `controllers/api_controller.go` `Login`; `controllers/login_gates.go`; `classes/login_gate.go` | `TestLoginGates` (order, first result or error wins, nil registry, concurrent Add and Check under `-race`), `TestLoginGateOrder` (refused first factors never reach a gate, answers pass through, no event, no last_seen), `TestLoginGateSmoke/gate_error` (U) | closed |
| T-19.6-02 | restore of a soft-deleted account before the second factor (Pitfall 21, D-18 A10) | The restore and its reactivate mail run after the gates; the gate sees the account still deleted. | U `Login`; M `classes/login.go` `CompleteLoginAs` (FinishLogin after the factor) | `TestLoginGateOrder/challenged_soft_deleted_stays_deleted`, `allowed_soft_deleted_restored_once` (U); `TestGate/deactivated_user_is_challenged_and_stays_deactivated` (M); `TestSocialGate/challenge_status_200` (S) | closed |
| T-19.6-03 | trusted devices surviving a password change (D-07) | Reset, own change and admin set fire `AccessRevokedEvent` (`PasswordChanged()` true) inside the write's transaction; M deletes the user's trusted devices on `ev.Tx`; a listener error rolls the write back; the rehash and a ban fire no password change. | U `controllers/api_controller.go` `ResetPassword`, `ChangePassword`; `controllers/users_admin_controller.go` `FormBeforeUpdate`; M `classes/admin.go` `OnAccessRevoked` | `TestPasswordChangedSources` (each source once, in the transaction, rollback, rehash and registration fire none) (U); `TestRevocation` (all three sources delete devices, rehash and ban keep them) (M) | closed |
| T-19.6-04 | Reset 2FA record action (D-15) | Permission `golem15.users.reset_two_factor` (no default role), danger confirmation, offered only with a published `TwoFactorAdmin` that reports a factor, `Run` only in cabana's transaction, Reset's error rolls back. | U `controllers/users_admin_controller.go` `resetTwoFactorAction`; M `classes/admin.go` `Admin` | `TestResetTwoFactorAction` (U); `TestAdminReset` (end to end through the Users screen, rollback on a failing listener) (M) | closed |
| T-19.6-05 | short-code guessing to bind a victim's pending device | 31^8 codes from crypto/rand without modulo bias, 5-minute TTL, user-api bucket, guarded pending-to-confirmed UPDATE requiring `user_id` NULL or the caller. | U `classes/device_auth.go` `NewDeviceShortCode`; `controllers/devices.go` `DeviceAuthorize` | `TestDeviceCodes` (distribution over 10,000 draws), `TestDeviceAuthorize` (bound to another user, concurrent authorizes by two users bind one) (U) | closed (mutation-checked) |
| T-19.6-06 | device-code phishing | D-12c keeps PHP's rule (any signed-in session may authorize); the device list shows name and address, revoke signs the device out at once. | U `controllers/devices.go` | `TestDeviceListAndRevoke` (U) | accepted (D-12c): the frontend must show device name and address before confirming |
| T-19.6-07 | device hand-over race | One guarded confirmed-to-used UPDATE; a poll that loses drops its minted token unsent. | U `controllers/devices.go` `handOverDevice` | `TestDeviceHandOverConcurrent` (50 polls, one token, one login event), `TestDeviceFlowSmoke` (U) | closed (mutation-checked) |
| T-19.6-08 | revoked device keeps refreshing (RESEARCH Q7) | Refresh hands the row's `jwt_jti` to the new token; revoke blacklists the current jti for the whole refresh window. | U `controllers/api_controller.go` `Refresh`; `classes/device_auth.go` `HandOverDeviceJTI`; `controllers/devices.go` `DeviceDestroy` | `TestDeviceRevokeAfterRefresh` (one and two refreshes, the lineage signed out, the blacklist entry outlives the window, a failed refresh leaves the row) (U) | closed; the `blacklist_grace` fork is a residual risk (below) |
| T-19.6-09 | device tokens at rest and in URLs | Only the SHA-256 hex is stored; the session JWT is never stored (only its jti); the framework access log records no path. | U `controllers/devices.go`; F `modules/surf/accesslog.go` | `TestDeviceTokensAtRest`, `TestDeviceStatus/unknown` (the hash is no token) (U) | closed; reverse-proxy logging of `devices/status/{token}` is a residual risk (README) |
| T-19.6-10 | unauthenticated initiate filling the table (Pitfall 16) | user-api bucket and a cleanup of at most 500 stale pending or expired sessions per initiate. | U `controllers/devices.go` `DeviceInitiate` | `TestDeviceInitiate/cleanup_is_bounded` (U) | closed |
| T-19.6-11 | attacker-chosen `device_name` (Pitfall 14) | At most 255 characters (runes) with PHP's 422; rendered as text by clients. | U `DeviceInitiate` | `TestDeviceInitiate/device_name` (U) | closed |
| T-19.6-12 | core plugin contract (19.4 D-05) | Additive exports, routes, config keys and one added migration. | U commits `8501f34`..`3b22134` | gate `--userplugin` (no exported declaration removed or changed since `50da92c`, only `202610260001_create_device_auth_sessions` added under `updates/`), `--fonoteka` (F) | closed |
| T-19.6-SC (plan 01) | Go module installs | None in U; approved pins for M. | F `.planning/notes/2026-10-21-mfa-otp-webauthn.md` | gate `--docs` (note and STACK rows), `--fonoteka` (no second-factor module in the workspace graph) (F) | closed |
| T-19.6-13 | TOTP and email brute force across challenges and addresses (Pitfall 1) | 2fa-verify bucket (10 a minute per client address), five attempts a challenge, the per-user failure cap counted from challenge rows (10 in 15 minutes, D-18 A6). | M `buckets.go`; `classes/challenge.go` `FailureCapReached`; `controllers/challenge.go` `attempt` | `TestFailureCap` (formula, window, in-flight attempt, refusal at login and on every verify route even with a correct factor, configured cap), `TestChallengeLifecycle/five_attempts_across_routes`, `TestRoutesAndBuckets` (11th request 429, keyed per client) (M) | closed |
| T-19.6-14 | parallel verifies (attempt bypass, double mint) | Guarded attempt increment and one guarded completion UPDATE in the transaction that consumes the factor. | M `classes/challenge.go` `BeginAttempt`, `CompleteChallenge` | `TestChallengeLifecycle/one_completion_when_factors_race` (20 TOTP and recovery verifications, one token, at most one code spent), `TestChallengeSmoke/parallel_verify`, `TestRecovery/single_use_under_concurrency` (M) | closed (mutation-checked) |
| T-19.6-15 | TOTP replay inside the window (Pitfall 5) | Last accepted step in metadata, accepted by a guarded UPDATE; a step at or below it is refused. | M `classes/totp.go` `VerifyTOTP`; `classes/methods.go` `AcceptTOTPCounter` | `TestTOTP/replay`, `TestTracerSmoke` (M) | closed |
| T-19.6-16 | email downgrade of a TOTP-only user (Pitfall 10, A8) | `email/send` and `verify method=email` only while the email method is enabled; otherwise the generic 401. | M `classes/email.go` `SendEmailCode`; `controllers/challenge.go` `verifyEmail` | `TestEmailCode/gating`, `TestPHPErrorBodies` (M) | closed |
| T-19.6-17 | mail bombing through email/send | At most 3 sends a challenge in one guarded UPDATE, the bucket and the failure cap. | M `SendEmailCode` | `TestEmailCode/sends_replace_and_cap`, `TestFailureCap/refused_everywhere_at_the_cap` (M) | closed (mutation-checked) |
| T-19.6-18 | secrets at rest (D-06) | SHA-256 hex for challenge and trusted tokens, `lagoon.Encrypted` TOTP secret, bcrypt recovery and email codes; models hide the columns from JSON. | M `classes/challenge.go`, `classes/trusted.go`, `classes/methods.go` `EnableMethod`, `classes/recovery.go`, `classes/email.go` | `TestTokensAtRest` (M) | closed |
| T-19.6-19 | logs and error strings | No code, token, secret or password in a log line; 500 answers opaque. | M, U (section "Log calls") | `TestEmailCode/never_logged` (no mailed code or challenge token in any app or default log line, a failing listener forcing log lines) (M) | closed |
| T-19.6-20 | stolen trusted-device token | SHA-256 at rest, bound to the user, 30-day expiry, off by default, revoked by any password change, the last method's removal and the revoke routes; a social sign-in is never skipped (A7). | M `classes/trusted.go`, `classes/gate.go` | `TestTrustedDevice` (foreign, unknown, malformed, expired tokens and the setting off are challenged; social never skipped), `TestRevocation` (M) | closed |
| T-19.6-21 | management routes touching another user's rows | Every query scoped by the JWT user; `{id}` routes constrained to digits; 404 for foreign ids. | M `routes.go`, `controllers/management.go`, `controllers/webauthn.go` | `TestRoutesAndBuckets` (jwt.auth on every management route), `TestWebAuthn/delete_scoped_to_the_owner` (foreign 404, the router's 404 for non-numeric ids), `TestTrustedSettingsSmoke/revoke_routes` (M) | closed |
| T-19.6-22 | recovery codes after creation | Shown once (first set D-19, regenerate); the count route needs the password and shows a count only. | M `controllers/management.go` | `TestRecovery/first_set_only_when_created`, `count_route`, `regenerate` (M) | closed |
| T-19.6-23 | bcrypt CPU per wrong recovery code (Pitfall 9) | Input normalized and capped at 32 characters, first match wins, the bucket and the cap. | M `classes/recovery.go` `NormalizeRecoveryCode` | `TestRecoveryCodeFormat`, `TestRecovery/normalization_through_the_route` (M) | closed |
| T-19.6-24 | settings values (USER-005 type confusion, unknown methods or groups) | Typed mode with an exact allow-list in `Rules`, method and group allow-lists in `BeforeValidate`, a stored unknown mode behaves as optional, an empty list falls back to the configuration (`71d8f27`). | M `models/settings.go`, `classes/config.go` | `TestSettings` (overlay per key, rules, allow-lists, form round trip), `TestPHPUser005` (M) | fixed in commit 71d8f27 (with its test) |
| T-19.6-25 | client-chosen TOTP secret at confirm | Only for the caller's own account; base32 and 16-64 characters validated; a current code from the secret is required. | M `controllers/management.go` `TOTPConfirm` | `TestPHPErrorBodies` (format and code refusals) (M) | accepted (PHP parity) |
| T-19.6-SC (plan 02) | Go module installs | pquerna/otp v1.5.0 and boombuler/barcode v1.1.0 after the recorded approval; no archived YAML module. | M `go.mod` | gate `--mfa` (pins, `go list -deps` free of `gopkg.in/yaml.v3`) (F) | closed |
| T-19.6-26 | WebAuthn challenge supplied by the client (Pitfall 6) | Registration and passkey state server-side in cooler, consumed with `Pull` and scoped to the user; the login challenge on the challenge row; the client's challenge only a lookup key. | M `classes/webauthn.go` `BeginRegistration`, `FinishRegistration`, `BeginAssertion`, `FinishAssertion`; `classes/passwordless.go` | `TestWebAuthnShapes/registration_state` (used once, another user's state refused), `TestWebAuthn/registration`, `assertion_options` (M) | closed |
| T-19.6-27 | passkey login with a second-factor credential (D-14) | `passwordless` set only for a requested, user-verified, credProps-rk credential; `ValidatePasskeyLogin` with UV required; the handler checks enabled, passwordless and the user handle. | M `classes/webauthn.go` `FinishRegistration`; `classes/passwordless.go` | `TestPasswordless`, `TestWebAuthnShapes/passkey_flag` (M); section "D-14" | closed (mutation-checked) |
| T-19.6-28 | cloned authenticator | The record written back after every assertion (sign count, flags) with a guarded UPDATE; a clone warning and a backup-eligibility change refuse. | M `classes/webauthn.go` `VerifyAssertion`, `RecordAssertion` | `TestWebAuthn/assertions` (clone and BE change refused, the stored record unchanged), `TestWebAuthnCeremonySmoke` (M) | closed |
| T-19.6-29 | RP ID or origin misconfiguration (Pitfall 7) | Explicit `webauthn.rp_id` and `origins` with app.url and frontend_url defaults; an IP host or no origin makes WebAuthn unavailable; the library checks origin and the RP ID hash. | M `classes/config.go` `loadWebAuthnConfig`; `classes/webauthn.go` `webAuthnFromConfig` | `TestWebAuthnShapes` (IP host, IP RP ID, no origin), `TestWebAuthn` (foreign origin at registration and assertion), `TestPasswordless/refused_foreign_origin` (M) | closed |
| T-19.6-30 | social sign-in bypassing an enabled second factor (D-09) | sociallogin's `signIn` asks the gates with source social before FinishLogin and any token; a challenge replaces the token in both completions; refusals and errors fail closed; a link stays ungated. | S `classes/flow.go` `signIn`; M `classes/gate.go` | `TestSocialGate` (existing identity, verified email match, new account; no cookie, no SignedInEvent; refusals; error; link) (S); `TestEveryLoginPathIsGated/social_sign_in` (M) | closed (mutation-checked on M's gate) |
| T-19.6-31 | passkey login of a banned, suspended or inactive account | Activation, `ThrottleStates` (anywhere) and `RejectIfThrottled` (this address) before any token; one generic body. | M `classes/passwordless.go` `FinishPasswordless` | `TestPasswordless/refused_banned`, `refused_suspended`, `refused_not_activated` (M) | closed |
| T-19.6-32 | remote operations of plan 03 | Blocking decision first, fetch and range check before every push, no force, no deploy, fonoteka.go never pushed. | 19.6-03-SUMMARY.md "Remote operations" | process control | accepted (process; recorded in plan 03) |
| T-19.6-33 | demo rendering the server's QR SVG | Rendered through an image data URL, never `v-html`; the helper escapes markup. | D `vue-demo-app/app/lib/twoFactor.ts` `svgDataUrl` | `twoFactor.test.ts` (`svgDataUrl` keeps no `<`), gate `--demo-web` (D) | closed |
| T-19.6-34 | WebAuthn user handle from the numeric user id (A4) | PHP-compatible 8-byte big-endian handle so imported passkeys keep mapping. | M `classes/webauthn.go` `UserHandle` | `TestWebAuthnShapes/user_handle` (M) | accepted: it reveals only an internal id to the user's own authenticator |
| T-19.6-35 | ceremony state in the memory cooler on several instances (A11) | Documented: multi-instance applications use the Redis cooler; a ceremony that reaches another instance fails closed. | M README | `TestPasswordless/refused_challenges_and_bodies` (unknown state refused) (M) | accepted (README) |
| T-19.6-SC (plan 03) | Go module installs | go-webauthn v0.18.2 after the recorded approval; fonoteka.go's graph has no go-webauthn. | M `go.mod`; A `go.mod` | gate `--mfa`, `--fonoteka` (F) | closed |
| T-19.6-36 | the gate's verdict | The `go test -json` detector fails on fail, skip, zero matches, "no tests to run" and missing names; a subtest pass never counts for its parent; the vitest detector needs the named file; docker NOT RUN explicit and fatal with `PHASE196_REQUIRE_DOCKER=1`. | F `scripts/check-phase19.6.sh` | `scripts/check-phase19.6.sh --self-test` (planted output for every detector, the additive, pin and migration checks, the docker rule on a faked PATH) (F) | closed |
| T-19.6-37 | post-release fixes not reaching the applications | Task 4's table lists every production fix against every pin; Task 6 releases in D-17 order under the Task 5 reply and checks each pin with `merge-base --is-ancestor`; hold writes a todo. | 19.6-04-SUMMARY.md "Post-release fixes" | Task 6 merge-base checks | **open**: one row (M `71d8f27`) awaits the Task 5 reply |
| T-19.6-38 | a token mint path that skips the second factor (assumption-delta debt) | Every mint site of U and M listed with its reason and checked against the source; every first-factor path of a TOTP user driven to a challenge; passkey and device poll mint only through their own proof. | M `login_paths_test.go` | `TestEveryLoginPathIsGated` (M) | closed for the listed paths; **open finding F-1** for activate-by-code (below) |
| T-19.6-SC (plan 04) | Go module installs | Plan 04 installs no module: no go.mod of U, M or S changed since the releases. | U, M, S `go.mod` | gate `--mfa` pins; `git diff` of the go.mod files since the release tags is empty | closed |
## D-14: passwordless passkey login
Passkey sign-in issues a session token without a password and without a second challenge, so each rule below is pinned by a subtest that fails when the rule goes.
| Rule | As built | Pinned by |
|------|----------|-----------|
| Setting default | `two_factor_passwordless_login` defaults to false (config and settings); both routes answer 403 `Passwordless login is not available.` while it is off, and also while `two_factor_mode` is disabled (fail closed). | `TestSettings/config_defaults_and_validation`, `TestPasswordless/off_or_mode_disabled`, `TestPasswordlessSmoke/setting_off` |
| Credential eligibility | Only a credential registered as a passkey qualifies: `passwordless` is set when the registration asked for one (and only while the setting is on), the authenticator verified the user and the browser's credProps reported a resident key. A second-factor key, or a requested passkey without credProps, stays a second factor. | `TestWebAuthnShapes/passkey_flag`, `TestPasswordless/refused_second_factor_key`, `TestPasswordlessSmoke/second_factor_key_refused` |
| User verification at registration | Passkey creation options require a resident key and user verification and ask for credProps; a registration without UV is refused. | `TestWebAuthnShapes/passkey_creation_options`, `passkey_flag/requested_without_uv` |
| User verification at login | The request options require UV and allow no credential list (discoverable); `ValidatePasskeyLogin` runs with UV required. | `TestWebAuthnShapes/passkey_request_options`, `TestPasswordless/refused_uv_missing` |
| User-handle binding | The assertion's user handle must be the credential owner's 8-byte handle; another user's handle or none is refused. | `TestPasswordless/refused_other_users_handle`, `refused_no_handle` |
| Enabled and ownership checks | The credential row must exist, be enabled and be a passkey; a disabled or removed credential is refused. | `TestPasswordless/refused_disabled_credential`, `refused_removed_credential` |
| Activation, ban and suspension | The owner must be activated and neither banned nor suspended, from any address (`ThrottleStates`) or this one (`RejectIfThrottled`). | `TestPasswordless/refused_not_activated`, `refused_banned`, `refused_suspended` |
| Generic failures | Every refusal answers the same 401 `{"error":"WebAuthn verification failed."}`; no reason leaks. | every `TestPasswordless/refused_*` subtest compares the body byte for byte |
| Single-use state | The passkey ceremony state is pulled from cooler once; a reused, unknown or over-long challenge, and a state spent by an unparsable attempt, are refused. Multi-instance caveat: with the memory cooler a ceremony must stay on one instance (README, T-19.6-35). | `TestPasswordless/refused_challenges_and_bodies`, `TestPasswordlessSmoke/state_once` |
| Origin and RP ID | go-webauthn checks the client origin against `webauthn.origins` and the RP ID hash against `webauthn.rp_id`. | `TestPasswordless/refused_foreign_origin`, `TestWebAuthnShapes` |
| Clone and backup-eligibility refusal | A clone warning refuses the sign-in and logs the credential row id; a changed BE flag is refused by the library (pinned on the second-factor path, which shares `ValidateLogin`'s flag checks). | `TestPasswordless/signs_in_without_a_second_challenge` (clone), `TestWebAuthn/assertions` (BE) |
| Rate limiting | Both passkey routes sit in the 2fa-verify bucket (10 a minute per client address). | `TestRoutesAndBuckets` |
| Deactivated-account restore | A deactivated owner is restored through golem15.user's `FinishLogin` with one reactivate mail: the passkey is both factors, so the restore follows a full sign-in (D-18 A10 holds). | `TestPasswordless/deactivated_owner_restored_and_mailed` |
| Logging | Only the clone warning logs (credential row id and user id); no assertion, challenge or token. | section "Log calls" |
| No second challenge | A passkey with user verification is both factors (D-14): a user with TOTP gets a token, no challenge row is created, the login event's source is `passkey`, and the gate never challenges source passkey. | `TestPasswordless/signs_in_without_a_second_challenge`, `TestGate/sources`, `TestEveryLoginPathIsGated/passkey_only_with_its_assertion` |
## D-18 hardening
| Item | As built | Pinned by |
|------|----------|-----------|
| A6 per-user failure cap | 10 failures in 15 minutes (configurable) from challenge rows, across instances and addresses; refuses new challenges and every verify route with their generic answers; the caller's in-flight attempt is not a failure. | `TestFailureCap` |
| A8 email only when enabled, 3 sends | `email/send` and email verification need the enabled email method; three sends a challenge, each replacing the code. | `TestEmailCode/gating`, `sends_replace_and_cap` |
| A9 promised lifetime | The mail promises min(email code TTL, the challenge's remaining minutes), rounded up, at least 1; the code dies with the challenge. | `TestEmailExpiryMinutes`, `TestEmailCode/expiry_capped_by_the_challenge`, `code_dies_with_the_challenge` |
| A10 restore after the gate | Password, social and passkey sign-ins restore a deactivated account only after the second factor (or the passkey). | `TestLoginGateOrder`, `TestGate/deactivated_user_is_challenged_and_stays_deactivated`, `TestSocialGate/challenge_status_200`, `TestPasswordless/deactivated_owner_restored_and_mailed` |
## ASVS L1 notes (RESEARCH Security Domain)
- **V2 Authentication.** TOTP with a one-step window and per-step replay refusal (`TestTOTP`); WebAuthn with server-side state, UV rules and clone and BE refusal (`TestWebAuthn`, `TestPasswordless`); bcrypt recovery and email codes (`TestTokensAtRest`); the per-IP bucket and the per-user cap (`TestRoutesAndBuckets`, `TestFailureCap`); guarded attempt counter (`TestChallengeLifecycle`).
- **V3 Session management.** Challenge tokens 64 characters, SHA-256 at rest, five minutes, one completion; the device JWT handed over once, followed through refresh and blacklisted on revoke (`TestDeviceHandOverConcurrent`, `TestDeviceRevokeAfterRefresh`); `tokens_valid_after` on password change (unchanged).
- **V4 Access control.** jwt.auth on every management route, every row query scoped by user, digit-constrained ids (`TestRoutesAndBuckets`, `TestWebAuthn/delete_scoped_to_the_owner`); the admin reset behind its own permission (`TestAdminReset`, `TestResetTwoFactorAction`).
- **V5 Validation.** Laravel's rules with Winter's English messages and PHP's 422 shapes (`TestPHPErrorBodies`); base32 and length checks on the TOTP secret; length caps on `device_name`, recovery input and the WebAuthn challenge echo.
- **V6 Cryptography.** Libraries only (pquerna/otp, go-webauthn, boombuler/barcode for the matrix); `crypto/rand` for tokens and codes (`TestDeviceCodes`, `TestRecoveryCodeFormat`); `lagoon.Encrypted` for the TOTP secret.
- **V7 Errors and logging.** Generic 401 bodies; no code, token, secret or assertion in a log line (`TestEmailCode/never_logged`, section "Log calls"); `Registration failed:` with fixed reasons.
## Log calls
Every non-test log call of M and of U's device and gate controllers, with what it carries:
| Where | Message | Attributes |
|-------|---------|------------|
| M `controllers/helpers.go` `serverError` | `golem15.mfa: <what>` | `err` (a database or library error; handlers pass no token, code or secret into it) |
| M `controllers/challenge.go` | verified and failed event listener | `user_id`, the listener's `err` |
| M `classes/gate.go` | challenged event listener | `user_id`, `err` |
| M `classes/login.go` | login event listener | `user_id`, `err` |
| M `classes/webauthn.go` | credential without a record; record does not decode; clone warning | `credential_row`, `user_id` |
| M `classes/passwordless.go` | clone warning, passkey sign-in refused | `credential_row`, `user_id` |
| U `controllers/devices.go` | session cleanup; store device session; finish device login; login event listener; revoke device session | `err`, `user_id` |
| U `controllers/api_controller.go` `Login` | login gate | `user_id`, `err` |
None carries a token, code, secret, password, assertion or the device token. `TestEmailCode/never_logged` checks the mailed codes and the challenge token against every app and default log line of a run that forces the failure paths to log.
## Residual risks
- **Device-code phishing (D-12c):** an attacker can show a victim a QR or short code; the frontend must show the device name and address before confirming. Accepted by decision.
- **`blacklist_grace` forks (Pitfall 15):** with a grace above 0, two concurrent refreshes of one device token both succeed and only one new jti is followed, so a revoke misses the other fork until it expires; the default grace is 0 and a password change ends both.
- **Memory cooler (A11):** WebAuthn ceremonies need one instance or the Redis cooler (README).
- **Numeric user handle (A4):** the handle reveals the internal user id to the user's own authenticator.
- **Reverse proxies** may log `devices/status/{token}`; the token lives five minutes and is single use.
- **JSON key order:** multi-key success bodies (the login challenge, `status`, `totp/setup`, `email/send`, the register answers) carry PHP's keys in Go's sorted order, not PHP's insertion order. JSON clients do not depend on key order, and the error bodies (single key or alphabetical in PHP too) and the 422 bodies (ordered explicitly) are byte-identical; recorded, not changed.
- **Route constraint ordering (framework):** surf checks a `{id}` digit constraint inside the route's middleware, so an unauthenticated `DELETE …/trusted-devices/abc` answers jwt.auth's 401 where Laravel answered 404; with a session it is the router's 404. No information leaks either way.
## Open findings
### F-1: activate-by-code mints a session without the second factor when `require_activation` is off
- **What:** plan 01's assumption-delta decision accepts `POST /_user/api/v1/activate-by-code` as an ungated mint because "a new or not-yet-activated account cannot have 2FA yet". That holds with the default `golem15.user.activation.require_activation: true` (a not-activated account cannot sign in). With `require_activation: false` and `activate_mode: user`, a not-activated account signs in with its password, can enable TOTP, and a later `activate-by-code` with the mailed activation code answers `{"message":"Account activated","token":…}` without a challenge.
- **Reproduced:** on this host through the mfa test harness (register in mode user, password login, TOTP setup and confirm, password login now challenged, `IssueActivationCode`, activate-by-code answers 200 with a token).
- **Impact:** low. It needs a non-default configuration, a user who enabled a second factor before activating, and an attacker holding that user's unexpired activation code (their mailbox). It lets the mailbox alone stand in for the second factor, which a password reset does not (a reset mints no token).
- **Options (raised at plan 04 Task 5):**
(a) fix in sm-user-plugin: after the code verifies, `ActivateByCode` asks the login gates (for example with source password, so sm-mfa-plugin v0.1.0's gate challenges it) and answers the gate's body instead of the token; the account is still activated. A patch release of sm-user-plugin and pointer bumps in sm-demo-app, sm-bm-app and fonoteka.go.
(b) accept with the corrected reason ("only with `require_activation: false`; the mailed code stands in for the second factor") recorded in plan 01's decision and the README.
(c) defer to a todo for a later phase.
- **Pinned now:** `TestEveryLoginPathIsGated/mint_sites` lists `ActivateByCode` with a pointer to this finding, so any change to the mint sites fails until the list is updated.
## Sign-off
Every T-19.6 threat of plans 01-04 is closed by a passing test, accepted with its reason, or open with its decision pending at Task 5 (T-19.6-37, F-1 under T-19.6-38). `scripts/check-phase19.6.sh --all` result: see 19.6-04-SUMMARY.md.

View File

@@ -3,10 +3,11 @@ phase: "19.6"
slug: "two-factor-auth-and-device-flow-in-sm-user-plugin"
# status lifecycle: draft (seeded by plan-phase) → validated (set by validate-phase §6)
# audit-milestone §5.5 distinguishes NOT-VALIDATED (draft) from PARTIAL (validated + nyquist_compliant: false) (#2117)
status: draft
nyquist_compliant: false
wave_0_complete: false
status: validated
nyquist_compliant: true
wave_0_complete: true
created: "2026-10-21"
validated: "2026-10-26"
---
# Phase 19.6 — Validation Strategy
@@ -19,30 +20,49 @@ created: "2026-10-21"
| Property | Value |
|----------|-------|
| **Framework** | Go `testing` + `httptest`; testcontainers-go Postgres (DB tests skip under `-short`) |
| **Config file** | none — Wave 0 adds `sm-mfa-plugin/testmain_test.go` and `harness_test.go` (copied from `sm-sociallogin-plugin`) |
| **Framework** | Go `testing` + `httptest`; testcontainers-go Postgres (DB tests skip under `-short`); vitest for `vue-demo-app` |
| **Config file** | none: `sm-mfa-plugin/testmain_test.go` and `harness_test.go` (Wave 0, plan 02), sm-user-plugin's `session_test.go` and `admin_harness_test.go` |
| **Quick run command** | `go -C ../sm-mfa-plugin test -short ./...` and `go -C ../fonoteka.go test -short ./plugins/golem15/user/...` |
| **Full suite command** | `scripts/check-phase19.6.sh` (go, userplugin, mfa, sociallogin, demo, bm, fonoteka, docker, docs stages) |
| **Estimated runtime** | ~180 seconds (full, with Docker) |
| **Full suite command** | `scripts/check-phase19.6.sh --all` (self-test, go, userplugin, mfa, sociallogin, demo, demo-web, bm, fonoteka, docs, then docker) |
| **Estimated runtime** | about 6 minutes for `--all` with Docker on this host |
---
## Sampling Rate
- **After every task commit:** `go vet ./...` + `go test -short ./...` of the touched repo
- **After every plan wave:** full suites (Docker) of every touched repo
- **Before `/msd-verify-work`:** `scripts/check-phase19.6.sh` must be green
- **After every task commit:** `go vet ./...` + `go test -short ./...` of the touched repository
- **After every plan wave:** full suites (Docker) of every touched repository
- **Before `/msd-verify-work`:** `scripts/check-phase19.6.sh --all` must be green
- **Max feedback latency:** 60 seconds for the short loop
---
## Per-Task Verification Map
Decision → test map is in `19.6-RESEARCH.md` § Validation Architecture; the planner assigns task IDs.
Gate stages are `scripts/check-phase19.6.sh --<stage>`; a test named under a stage is required by name there (a skip or a missing name fails the stage). U = sm-user-plugin, M = sm-mfa-plugin, S = sm-sociallogin-plugin, D = sm-demo-app, B = sm-bm-app, A = the fonoteka.go workspace.
| Task ID | Plan | Wave | Requirement | Threat Ref | Secure Behavior | Test Type | Automated Command | File Exists | Status |
| Task ID | Plan | Wave | Requirement | Threat Ref | Secure Behavior | Test Type | Automated Command (gate stage: tests) | File Exists | Status |
|---------|------|------|-------------|------------|-----------------|-----------|-------------------|-------------|--------|
| 19.6-XX-XX | TBD | TBD | D-XX | T-19.6-XX | per RESEARCH map | unit/integration | per RESEARCH map | ❌ W0 | ⬜ pending |
| 19.6-01-01 | 01 | 1 | D-02, D-04, D-18 A10 | T-19.6-01, T-19.6-02 | Password login asks the gates before restore and mint; a gate error fails closed; the library note names the pins | unit + integration | `check-phase19.6.sh --userplugin`: TestLoginGatesSmoke, TestLoginGates (also `-race`); `--docker`: TestLoginGateSmoke, TestLoginGateOrder (U); `--docs`: the note and STACK rows | ✅ | ✅ green |
| 19.6-01-02 | 01 | 1 | D-07, D-15 | T-19.6-03, T-19.6-04 | Password writes fire the revocation event in their transaction; Reset 2FA only with a service and the permission | integration | `check-phase19.6.sh --docker`: TestPasswordChangedEventSmoke, TestPasswordChangedSources, TestResetTwoFactorSlotSmoke, TestResetTwoFactorAction (U) | ✅ | ✅ green |
| 19.6-01-03 | 01 | 1 | D-11, D-12a, D-12c, D-06, D-16 | T-19.6-05, T-19.6-07, T-19.6-09, T-19.6-10, T-19.6-11 | Device initiate, status and authorize with hashed tokens, one-time hand-over, bounded cleanup | unit + integration | `--userplugin`: TestDeviceCodesSmoke, TestDeviceCodes, TestDeviceAuthURL, TestDeviceDisplayName; `--docker`: TestDeviceFlowSmoke, TestDeviceInitiate, TestDeviceStatus, TestDeviceAuthorize, TestDeviceHandOverConcurrent, TestDeviceTokensAtRest, TestDeviceAuthSessionsMigration (U) | ✅ | ✅ green |
| 19.6-01-04 | 01 | 1 | D-12b | T-19.6-08 | Device list and revoke; the jti follows refresh | integration | `--docker`: TestDeviceRevokeSmoke, TestDeviceListAndRevoke, TestDeviceRevokeAfterRefresh (U) | ✅ | ✅ green |
| 19.6-01-05 | 01 | 1 | D-04 | T-19.6-SC | Human package check before any install | manual (checkpoint) | reply "approved" (19.6-01-SUMMARY.md); `--mfa` pins, `--fonoteka` module check | ✅ | ✅ green |
| 19.6-02-01 | 02 | 2 | SC-2, D-04, D-05, D-06 | T-19.6-13, T-19.6-15, T-19.6-18 | TOTP with QR SVG, challenge instead of a token, replay refused, 2fa-verify bucket | unit + integration | `--mfa`: TestQRSVGSmoke, TestTOTP, TestQRSVG, TestRoutesAndBuckets; `--docker`: TestTracerSmoke, TestGate, TestChallengeLifecycle, TestTokensAtRest, TestPHPErrorBodies (M) | ✅ | ✅ green |
| 19.6-02-02 | 02 | 2 | D-05, D-18 A6, A8, A9, D-19 | T-19.6-13, T-19.6-14, T-19.6-16, T-19.6-17, T-19.6-22, T-19.6-23 | Recovery codes once, email codes only when enabled with a send cap and a capped lifetime, the per-user failure cap | unit + integration | `--mfa`: TestRecoveryCodeFormat, TestMaskEmail, TestEmailExpiryMinutes; `--docker`: TestChallengeSmoke, TestRecovery, TestEmailCode, TestFailureCap (M) | ✅ | ✅ green |
| 19.6-02-03 | 02 | 2 | D-07, D-10, D-12, D-13, D-15, D-16 | T-19.6-03, T-19.6-20, T-19.6-21, T-19.6-24 | Trusted devices revoked on every password change and the last method; settings per request with allow-lists; admin reset | integration | `--docker`: TestTrustedSettingsSmoke, TestTrustedDevice, TestRevocation, TestSettings, TestStatusShape, TestAdminReset, TestMigrations (M); `--mfa`: TestPHPMethodMap, TestPHPUser005 | ✅ | ✅ green |
| 19.6-03-01 | 03 | 3 | SC-1, D-08, D-16 | T-19.6-26, T-19.6-28, T-19.6-29 | WebAuthn second factor with server-side state, clone and BE refusal, origin and RP checks | unit + integration | `--mfa`: TestWebAuthnCeremonySmoke, TestWebAuthnShapes; `--docker`: TestWebAuthnSmoke, TestWebAuthn (M) | ✅ | ✅ green |
| 19.6-03-02 | 03 | 3 | D-14, D-09 | T-19.6-27, T-19.6-30, T-19.6-31 | Passkeys only for eligible credentials and allowed owners; social sign-in through the gate | integration | `--docker`: TestPasswordlessSmoke, TestPasswordless, TestEveryLoginPathIsGated (M); TestSocialGateSmoke, TestSocialGate (S) | ✅ | ✅ green |
| 19.6-03-03 | 03 | 3 | D-20 | T-19.6-33 | Demo TOTP setup and challenge; the QR rendered as an image data URL | unit | `check-phase19.6.sh --demo-web`: `app/lib/twoFactor.test.ts` (D) | ✅ | ✅ green |
| 19.6-03-04 | 03 | 3 | D-17 | T-19.6-32 | Go-ahead before any push, tag or repository creation | manual (checkpoint) | reply recorded in 19.6-03-SUMMARY.md | ✅ | ✅ green |
| 19.6-03-05 | 03 | 3 | D-17 | T-19.6-32 | Releases in D-17 order, no force-push | manual + gate | `--mfa` (go.mod pins), `--sociallogin`; ls-remote checks in 19.6-03-SUMMARY.md | ✅ | ✅ green |
| 19.6-03-06 | 03 | 3 | D-17, D-01 | T-19.6-12, T-19.6-SC | Demo and bm mount mfa; fonoteka.go builds at the new pointer without second-factor modules | integration | `--demo`: TestBootAllPlugins, TestGoModRequiresTags, TestMFAMounted; `--bm`: TestSocialLoginMounted, TestMFAMounted; `--fonoteka` (no golem15.mfa mount, no go-webauthn, pquerna or boombuler module) | ✅ | ✅ green |
| 19.6-04-01 | 04 | 4 | SC-4 | T-19.6-36 | The gate fails closed on a failed, skipped, missing or unrun test | unit (script) | `check-phase19.6.sh --self-test` | ✅ | ✅ green |
| 19.6-04-02 | 04 | 4 | SC-4, D-02, D-07, D-11, D-12a, D-12b, D-12c, D-15, D-16, D-18 | T-19.6-01..T-19.6-12 | Every user-plugin seam and device-flow state pinned by name | unit + integration | `--userplugin` and `--docker` (rows 19.6-01-01..04) | ✅ | ✅ green |
| 19.6-04-03 | 04 | 4 | SC-4, D-05..D-10, D-12..D-16, D-18, D-19 | T-19.6-13..T-19.6-31, T-19.6-38 | Every second-factor decision, every PHP body and the login-path invariant pinned by name | unit + integration | `--mfa`, `--sociallogin` and `--docker` (rows 19.6-02-01..19.6-03-02) | ✅ | ✅ green |
| 19.6-04-04 | 04 | 4 | SC-4, D-14 | all T-19.6 | PHP security test mapped; security review with the D-14 section; the whole gate green | unit + review | `check-phase19.6.sh --all`; `--mfa`: TestPHPMethodMap, TestPHPUser005; 19.6-SECURITY-REVIEW.md | ✅ | ✅ green |
| 19.6-04-05 | 04 | 4 | D-17 | T-19.6-37 | Go-ahead before releasing post-release fixes | manual (checkpoint) | reply recorded in 19.6-04-SUMMARY.md | ✅ | ⬜ pending (awaiting the reply) |
| 19.6-04-06 | 04 | 4 | D-17 | T-19.6-37 | Each post-release fix reaches every pin (`merge-base --is-ancestor`) or is a tracked todo | integration + manual | `check-phase19.6.sh --demo`, `--bm`, `--fonoteka` at the final pins | ✅ | ⬜ pending (after Task 5) |
*Status: ⬜ pending · ✅ green · ❌ red · ⚠️ flaky*
@@ -50,10 +70,10 @@ Decision → test map is in `19.6-RESEARCH.md` § Validation Architecture; the p
## Wave 0 Requirements
- [ ] `sm-mfa-plugin/testmain_test.go`, `harness_test.go` — boot `golem15.user` + `golem15.mfa`
- [ ] WebAuthn fixtures — recorded attestation/assertion JSON or a virtual authenticator
- [ ] Clock injection for TOTP tests
- [ ] user-plugin harness helper for device-flow tests
- [x] `sm-mfa-plugin/testmain_test.go`, `harness_test.go` — boot `golem15.user` + `golem15.mfa` (plan 02)
- [x] WebAuthn fixtures — a virtual authenticator (`webauthn_authenticator_test.go`, plan 03)
- [x] Clock injection for TOTP tests — `VerifyTOTP(secret, code, at, lastCounter)` with pquerna's `GenerateCodeCustom` at chosen times (`TestTOTP`)
- [x] user-plugin harness helper for device-flow tests — `session_test.go` and `admin_harness_test.go` helpers plus `device_flow_smoke_test.go`'s device helpers
---
@@ -62,16 +82,17 @@ Decision → test map is in `19.6-RESEARCH.md` § Validation Architecture; the p
| Behavior | Requirement | Why Manual | Test Instructions |
|----------|-------------|------------|-------------------|
| WebAuthn registration and login in a real browser | D-08 / SC-1 | Browser authenticator ceremony cannot run in `go test` | Register a passkey on the demo instance over HTTPS with a hostname RP ID, then sign in with it |
| Demo TOTP screens in a browser | D-20 | Look and flow of the Nuxt pages | On the deployed demo: enable TOTP from the QR, keep the recovery codes, sign out, answer the challenge with a code and with a recovery code |
---
## Validation Sign-Off
- [ ] All tasks have `<automated>` verify or Wave 0 dependencies
- [ ] Sampling continuity: no 3 consecutive tasks without automated verify
- [ ] Wave 0 covers all MISSING references
- [ ] No watch-mode flags
- [ ] Feedback latency < 60s
- [ ] `nyquist_compliant: true` set in frontmatter
- [x] All tasks have `<automated>` verify or Wave 0 dependencies
- [x] Sampling continuity: no 3 consecutive tasks without automated verify
- [x] Wave 0 covers all MISSING references
- [x] No watch-mode flags
- [x] Feedback latency < 60s
- [x] `nyquist_compliant` set to true in the frontmatter
**Approval:** pending
**Approval:** validated 2026-10-26 (plan 19.6-04, `check-phase19.6.sh --all`); Tasks 5 and 6 of plan 04 await the release decision.