Sign out all devices ends browser sessions; Fable's review fixes
Human
Prompt
Coordinator, 2026-11-14, answers and review on feat/oficina-id-native-a:
1. PAUL'S RULING: "Sign out all devices" also ends every Home browser session of that person (all id.* / directory browser sessions, including the one pressing the button — land them on a signed-out page). Add a test. Atomic with the grant revocation (one transaction) where the stores allow.
2. Keep the 60 passkey/begin per IP per 15 min limit; document it as an addition to the spec.
3. Keys cut off by sign-out-all/revoke/replacement count as new for the daily wrong-code cap.
4. Deriving the new keys from the pepper is acceptable if each is domain-separated; confirm and document what a pepper rotation would invalidate.
Also: when the per-address daily wrong-code cap blocks a new-device code sign-in, answer 429 {"error":"daily_limit"}; every other 429 a different value. Confirm {"error":"grant_ended"}. Add tests.
Fable reviewed @cdad4ed: APPROVE AFTER FIXES. 1 (must): native directory sessions are never fresh and are refused on browser routes. 2: returningKey — any live grant → returning; otherwise the most recently ENDED row decides. 3: sweep sealed addresses at boot and in verify/resend. 4: cheap mitigations for the fail-closed caps; document the residual. 5: note what pepper rotation changes.
Hub CI race step hit the 15-minute job limit: make slow tests fast.From this commit's own message. The prompt ledger has no entries for it — which is what a squashed, rebased or amended commit looks like, and what every commit looks like in a repo without a ledger.
Summary
Paul's ruling: Sign out all devices ends every grant and every id.* session (with half-finished sign-ins) in one transaction, then carries a signed receipt (an assertion for the directory whose nonce derives from its own jti) to oficina.works/auth/signed-out-all, which ends every directory session of the person in one transaction with the jti and lands on 'All devices are signed out'. 429 daily_limit only for the daily new-device wrong-code cap; everything else rate_limited. Review fixes: native directory sessions are stripped on every route but teams and their own sign-out, and teamFresh/directoryFresh never count them (1); returningKey: any live grant, else the most recently ended row (2); expired starts swept at boot and in verify/resend (3); per-person replay limit 300/min and a 250k table, per-network (/24, /48) start and begin buckets, 128-bit bucket keys and a 500k cap, one live native challenge per key, native capped at half the shared ceremonies table (4); HKDF labels and pepper-rotation consequences documented on nativeKey (5). The LRU test inserts its grants instead of signing in twenty times. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
16 files changed,
+674
−84
internal/home/app.go+3 −0internal/home/directory.go+9 −1internal/home/directory_native.go+38 −0internal/home/identity/migrations/0004_native.sql+2 −0internal/home/native.go+46 −15internal/home/native_code.go+65 −18internal/home/native_code_test.go+56 −3internal/home/native_grant_test.go+15 −14internal/home/native_passkey.go+26 −7internal/home/native_review_test.go+186 −0internal/home/native_revoke_test.go+89 −8internal/home/operator_confirm.go+3 −1internal/home/signout_all.go+128 −6internal/home/team_page.go+1 −1internal/home/templates/directory_signed_out.html+5 −1internal/home/templates/id_signout_all.html+2 −9
diff --git a/internal/home/app.go b/internal/home/app.go| index e76aba4..6695db6 100644 |
| --- a/internal/home/app.go |
| +++ b/internal/home/app.go |
| @@ -159,6 +159,9 @@ func NewWithOrigins(secrets Secrets, d *db.DB, logger *slog.Logger, origins Orig |
| if err := a.links.sweep(context.Background(), time.Now()); err != nil { |
| logger.Warn("sweeping expired sign-in links at boot", "err", err) |
| } |
| + if err := a.sweepNativeAtBoot(context.Background()); err != nil { |
| + logger.Warn("sweeping expired native codes at boot", "err", err) |
| + } |
| return a, nil |
| } |
diff --git a/internal/home/directory.go b/internal/home/directory.go| index a949e5b..13a4553 100644 |
| --- a/internal/home/directory.go |
| +++ b/internal/home/directory.go |
| @@ -94,6 +94,9 @@ func (a *App) directoryRouter() http.Handler { |
| r.Use(chooserNoStore) |
| r.Use(a.serveKnownHost) |
| r.Use(a.chooserCookies) |
| + // Before the session middleware: a native app's session is invisible to |
| + // every route but the native API it was minted for. |
| + r.Use(a.nativeSessionsStayNative) |
| r.Use(a.sessions.Middleware) |
| // After the session middleware, so a signed-in person's 404 shows their |
| // account menu (spec §3.3). |
| @@ -111,6 +114,9 @@ func (a *App) directoryRouter() http.Handler { |
| // browser evidence header instead. |
| r.Post(nativeExchangePath, a.directoryNativeExchange) |
| r.Post(nativeDirectorySignout, a.directoryNativeSignout) |
| + // "Sign out all devices" arrives from the credential origin as a |
| + // cross-origin POST with its own exact Origin check (signout_all.go). |
| + r.Post(signedOutAllPath, a.handleSignedOutAll) |
| r.Group(func(r chi.Router) { |
| r.Use(csrf.Protect(a.origins.Directory)) |
| for _, chooser := range a.directory.choosers { |
| @@ -177,8 +183,10 @@ func (a *App) directoryRouter() http.Handler { |
| r.Get("/signed-out", func(w http.ResponseWriter, r *http.Request) { |
| w.Header().Set("Cache-Control", "no-store") |
| finish := cookieValue(r, "__Host-oficina-finish-signout") == "1" |
| + all := cookieValue(r, "__Host-oficina-signed-out-all") == "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}) |
| + idCookie(w, "__Host-oficina-signed-out-all", "", -1) |
| + a.render(w, r, 200, "directory_signed_out.html", map[string]any{"Finish": finish && !all, "AllDevices": all, "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) }) |
diff --git a/internal/home/directory_native.go b/internal/home/directory_native.go| index fe5cda5..7bfeeba 100644 |
| --- a/internal/home/directory_native.go |
| +++ b/internal/home/directory_native.go |
| @@ -3,6 +3,7 @@ package home |
| import ( |
| "crypto/sha256" |
| "crypto/subtle" |
| + "database/sql" |
| "encoding/hex" |
| "errors" |
| "io" |
| @@ -228,3 +229,40 @@ func (a *App) directoryNativeSignout(w http.ResponseWriter, r *http.Request) { |
| func (a *App) handleNoTeamsHelp(w http.ResponseWriter, r *http.Request) { |
| a.render(w, r, http.StatusOK, "directory_no_teams.html", nil) |
| } |
| + |
| +// nativeSessionsStayNative confines a home-assertion-native directory |
| +// session to the routes a native app uses: the teams list and its own |
| +// sign-out. On any other route its cookie is removed from the request |
| +// before the session middleware runs, so a native session copied into a |
| +// browser — or carried by a forged same-origin POST — is simply signed out: |
| +// it sees the front page, passes no freshness check and makes no roster or |
| +// operator write. Its auth_time is a sign-in's, possibly code-only, and the |
| +// directory's browser routes trust auth_time for freshness. |
| +func (a *App) nativeSessionsStayNative(next http.Handler) http.Handler { |
| + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + name := a.sessions.CookieName() |
| + token := cookieValue(r, name) |
| + if token == "" || r.URL.Path == nativeTeamsPath || r.URL.Path == nativeDirectorySignout { |
| + next.ServeHTTP(w, r) |
| + return |
| + } |
| + var method string |
| + err := a.db.Writer().QueryRowContext(r.Context(), "SELECT method FROM sessions WHERE token_hash=?", sessions.HashToken(token)).Scan(&method) |
| + if err != nil && !errors.Is(err, sql.ErrNoRows) { |
| + http.Error(w, "Directory unavailable", http.StatusServiceUnavailable) |
| + return |
| + } |
| + if method != nativeSessionMethod { |
| + next.ServeHTTP(w, r) |
| + return |
| + } |
| + stripped := r.Clone(r.Context()) |
| + stripped.Header.Del("Cookie") |
| + for _, c := range r.Cookies() { |
| + if c.Name != name { |
| + stripped.AddCookie(c) |
| + } |
| + } |
| + next.ServeHTTP(w, stripped) |
| + }) |
| +} |
diff --git a/internal/home/identity/migrations/0004_native.sql b/internal/home/identity/migrations/0004_native.sql| index d2d475d..3520e23 100644 |
| --- a/internal/home/identity/migrations/0004_native.sql |
| +++ b/internal/home/identity/migrations/0004_native.sql |
| @@ -29,9 +29,11 @@ CREATE INDEX home_id_grants_ended ON home_id_grants(ended_at); |
| CREATE TABLE home_id_native_replay ( |
| jti_hash TEXT PRIMARY KEY, |
| grant_hash TEXT NOT NULL, |
| + person_ref TEXT NOT NULL, |
| expires_at INTEGER NOT NULL |
| ); |
| CREATE INDEX home_id_native_replay_grant ON home_id_native_replay(grant_hash, expires_at); |
| +CREATE INDEX home_id_native_replay_person ON home_id_native_replay(person_ref, expires_at); |
| CREATE INDEX home_id_native_replay_expiry ON home_id_native_replay(expires_at); |
| -- A live email code (§4). The address is sealed before it is written and the |
diff --git a/internal/home/native.go b/internal/home/native.go| index 3475ba3..784a417 100644 |
| --- a/internal/home/native.go |
| +++ b/internal/home/native.go |
| @@ -39,6 +39,7 @@ const ( |
| nativeProofSkew = 30 // |iat − now| allowed, seconds |
| nativeReplayHold = 61 // seconds a jti stays in the replay table: see below |
| nativeReplayPerMin = 120 // accepted calls per grant per minute |
| + nativePersonPerMin = 300 // and per person, across all their grants |
| nativeGrantIdleDays = 90 // a grant unused this long has expired |
| nativeGrantLife = 365 * day // absolute grant lifetime |
| nativeGrantKeep = 365 * day // how long an ended grant keeps its device key |
| @@ -48,8 +49,8 @@ const ( |
| ) |
| // nativeReplayCap is how many replay rows the table holds before it fails |
| -// closed. A variable only so a test can fill it without 100,000 inserts. |
| -var nativeReplayCap = 100000 |
| +// closed. A variable only so a test can fill it without 250,000 inserts. |
| +var nativeReplayCap = 250000 |
| // nativePlatforms is the closed set a device may report. It is self-reported |
| // and decides nothing; it exists so A2's Devices page can draw a fixed label. |
| @@ -236,9 +237,22 @@ func (a *App) verifyNativeProof(r *http.Request, body, key []byte, p nativeProof |
| hmac.Equal([]byte(p.BH), []byte(nb64.EncodeToString(bh[:]))) |
| } |
| -// nativeKey derives one purpose's Home-only key from the pepper. The pepper |
| -// never leaves Home, and each purpose gets its own HKDF output, so no two |
| -// uses of it share a key (§3: identity_id is an HMAC under a dedicated key). |
| +// nativeKey derives one purpose's Home-only key from the pepper: |
| +// HKDF-SHA256 (rastrillo crypto.Derive, salt nil) with the info label |
| +// "oficina-id/<purpose>/v1". The purposes are identity-id, native-code, |
| +// native-address, native-ip and native-bucket; distinct labels give |
| +// independent keys, none equal to the pepper the people index uses (§3: |
| +// identity_id is an HMAC under a dedicated key). Paul accepted deriving them |
| +// from HOME_PEPPER on 2026-11-14, on that domain separation. |
| +// |
| +// What rotating HOME_PEPPER would invalidate here, beyond the people index |
| +// it already orphans: every identity_id changes (a device's stored ID no |
| +// longer matches what a mint returns, so "Already signed in" detection |
| +// breaks until each device signs in again, and home_id_grants.identity_id |
| +// goes stale); every live code stops verifying (code_mac); and the native |
| +// rate-limit buckets and start uniqueness reset, because their keys are |
| +// blinded under it. Grants themselves survive: grant_hash is a plain |
| +// SHA-256 of the token. |
| func (a *App) nativeKey(purpose string) []byte { |
| return assertioncrypto.Derive(a.secrets.Pepper, "oficina-id/"+purpose+"/v1") |
| } |
| @@ -382,7 +396,19 @@ func (a *App) nativeAuthed(handle func(tx *sql.Tx, g nativeGrant, body []byte, n |
| nativeFail(w, http.StatusTooManyRequests, "rate_limited") |
| return |
| } |
| - res, err := tx.Exec("INSERT INTO home_id_native_replay VALUES(?,?,?) ON CONFLICT DO NOTHING", nativeHash(g.hash+"\x00"+p.JTI), g.hash, now+nativeReplayHold) |
| + // Per person as well, so one account's twenty grants cannot spend a |
| + // fifth of the table between them: filling it takes hundreds of |
| + // accounts, each behind its own mailbox. |
| + var theirs int |
| + if tx.QueryRow("SELECT count(*) FROM home_id_native_replay WHERE person_ref=?", g.person).Scan(&theirs) != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + if theirs >= nativePersonPerMin { |
| + nativeFail(w, http.StatusTooManyRequests, "rate_limited") |
| + return |
| + } |
| + res, err := tx.Exec("INSERT INTO home_id_native_replay(jti_hash,grant_hash,person_ref,expires_at) VALUES(?,?,?,?) ON CONFLICT DO NOTHING", nativeHash(g.hash+"\x00"+p.JTI), g.hash, g.person, now+nativeReplayHold) |
| if err != nil { |
| nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| return |
| @@ -483,26 +509,31 @@ func endPasskeylessGrants(tx *sql.Tx, person, except string, now int64) error { |
| return nil |
| } |
| -// returningKey reports §4's exemption: the device key's most recent grant |
| -// for this person is live, or ended by expiry, lru or enrolment. A key last |
| -// cut off by "Sign out all devices", Revoke or recovery replacement is not |
| -// returning — those are how a lost device is cut off. |
| +// returningKey reports §4's exemption. Any live grant for this (person, |
| +// key) makes it returning. Otherwise the most recently ENDED grant decides: |
| +// returning if it ended by expiry, lru or enrolment; not if by "Sign out all |
| +// devices", Revoke or recovery replacement — those are how a lost device is |
| +// cut off, and a later-created grant that happened to end earlier must not |
| +// undo that. |
| func returningKey(tx *sql.Tx, person, deviceKey string) (bool, error) { |
| if person == "" { |
| return false, nil |
| } |
| - var ended sql.NullInt64 |
| + var live int |
| + if err := tx.QueryRow("SELECT count(*) FROM home_id_grants WHERE person_ref=? AND device_key=? AND ended_at IS NULL", person, deviceKey).Scan(&live); err != nil { |
| + return false, errIDProof |
| + } |
| + if live > 0 { |
| + return true, nil // live, or lapsed and not yet swept: lapsing is expiry |
| + } |
| var reason sql.NullString |
| - err := tx.QueryRow("SELECT ended_at,end_reason FROM home_id_grants WHERE person_ref=? AND device_key=? ORDER BY created_at DESC LIMIT 1", person, deviceKey).Scan(&ended, &reason) |
| + err := tx.QueryRow("SELECT end_reason FROM home_id_grants WHERE person_ref=? AND device_key=? ORDER BY ended_at DESC, created_at DESC LIMIT 1", person, deviceKey).Scan(&reason) |
| if errors.Is(err, sql.ErrNoRows) { |
| return false, nil |
| } |
| if err != nil { |
| return false, errIDProof |
| } |
| - if !ended.Valid { |
| - return true, nil // live, or lapsed and not yet swept: lapsing is expiry |
| - } |
| switch reason.String { |
| case "expiry", "lru", "enrolment": |
| return true, nil |
diff --git a/internal/home/native_code.go b/internal/home/native_code.go| index 875b285..bc1d4c7 100644 |
| --- a/internal/home/native_code.go |
| +++ b/internal/home/native_code.go |
| @@ -24,7 +24,7 @@ const ( |
| nativeResendAfter = 30 // thirty seconds apart |
| nativePendingLife = 300 // a passkey-required pending lives five minutes |
| nativeLivePerIP = 20 |
| - nativeBucketCap = 200000 |
| + nativeBucketCap = 500000 |
| nativeWindow = 900 |
| nativeCodeSealScope = "native.code" |
| ) |
| @@ -42,16 +42,24 @@ type nativeLimit struct { |
| } |
| var ( |
| - startsPerAddress = nativeLimit{"start-addr-15m", 5, nativeWindow} |
| - startsPerAddressDay = nativeLimit{"start-addr-day", 20, day} |
| - startsPerIP = nativeLimit{"start-ip-15m", 20, nativeWindow} |
| - startsPerIPDay = nativeLimit{"start-ip-day", 200, day} |
| - startsPerAddressKey = nativeLimit{"start-key-15m", 5, nativeWindow} |
| - wrongPerAddressKey = nativeLimit{"wrong-key-15m", 5, nativeWindow} |
| - wrongNewKeysPerDay = nativeLimit{"wrong-new-day", 20, day} |
| - passkeyBeginsPerIP = nativeLimit{"passkey-ip-15m", 60, nativeWindow} |
| - errNativeLimited = errors.New("home: native limit reached") |
| - errNativeLimitedToday = errors.New("home: native daily limit reached") |
| + startsPerAddress = nativeLimit{"start-addr-15m", 5, nativeWindow} |
| + startsPerAddressDay = nativeLimit{"start-addr-day", 20, day} |
| + startsPerIP = nativeLimit{"start-ip-15m", 20, nativeWindow} |
| + startsPerIPDay = nativeLimit{"start-ip-day", 200, day} |
| + startsPerAddressKey = nativeLimit{"start-key-15m", 5, nativeWindow} |
| + wrongPerAddressKey = nativeLimit{"wrong-key-15m", 5, nativeWindow} |
| + wrongNewKeysPerDay = nativeLimit{"wrong-new-day", 20, day} |
| + passkeyBeginsPerIP = nativeLimit{"passkey-ip-15m", 60, nativeWindow} |
| + // Per network (IPv4 /24, IPv6 /48): rotating through a /64 allocation's |
| + // addresses, or a /48's /64s, does not buy a fresh allowance each time. |
| + startsPerNetDay = nativeLimit{"start-net-day", 1000, day} |
| + passkeyBeginsPerNet = nativeLimit{"passkey-net-15m", 300, nativeWindow} |
| + errNativeLimited = errors.New("home: native limit reached") |
| + // errNativeDailyLimit is only the per-address daily wrong-code cap for |
| + // new devices (§4, cost B): the client answers it with the spec's "use a |
| + // passkey or a device you've signed in on before" copy. Every other limit |
| + // is errNativeLimited. |
| + errNativeDailyLimit = errors.New("home: native daily wrong-code limit reached") |
| ) |
| const codeMailSubject = "Your Oficina ID code" |
| @@ -63,8 +71,10 @@ func codeMailBody(code string) string { |
| "If you didn't ask for it, ignore this email. Nobody can sign in without the code." |
| } |
| +// bucketKey is 128 bits of a keyed MAC: ample to keep buckets apart, and |
| +// half the bytes per row of the full MAC. |
| func (a *App) bucketKey(l nativeLimit, parts ...string) string { |
| - return l.prefix + ":" + a.nativeMAC("native-bucket", append([]string{l.prefix}, parts...)...) |
| + return l.prefix + ":" + a.nativeMAC("native-bucket", append([]string{l.prefix}, parts...)...)[:32] |
| } |
| // bucketFull reports whether a bucket has reached its limit in its window. |
| @@ -141,6 +151,19 @@ func nativeIPBucket(r *http.Request) string { |
| return ip.Mask(net.CIDRMask(64, 128)).String() + "/64" |
| } |
| +// nativeNetBucket is the wider network an address sits in: the IPv4 /24 or |
| +// the IPv6 /48. "" when no IP is known. |
| +func nativeNetBucket(r *http.Request) string { |
| + ip := net.ParseIP(clientIP(r)) |
| + if ip == nil { |
| + return "" |
| + } |
| + if v4 := ip.To4(); v4 != nil { |
| + return v4.Mask(net.CIDRMask(24, 32)).String() + "/24" |
| + } |
| + return ip.Mask(net.CIDRMask(48, 128)).String() + "/48" |
| +} |
| + |
| func newNativeCode() (string, error) { |
| n, err := rand.Int(rand.Reader, big.NewInt(1000000)) |
| if err != nil { |
| @@ -201,6 +224,21 @@ func (a *App) spendWebBudget(ctx context.Context, address string) bool { |
| return err == nil && ok |
| } |
| +// sweepNativeAtBoot drops expired starts, pendings and buckets at boot, as |
| +// the link store does, so a sealed address never outlives its code because |
| +// nobody started another one before a restart. |
| +func (a *App) sweepNativeAtBoot(ctx context.Context) error { |
| + tx, err := a.db.Writer().BeginTx(ctx, nil) |
| + if err != nil { |
| + return err |
| + } |
| + defer tx.Rollback() |
| + if err = sweepCodes(tx, time.Now().Unix()); err != nil { |
| + return err |
| + } |
| + return tx.Commit() |
| +} |
| + |
| func sweepCodes(tx *sql.Tx, now int64) error { |
| for _, q := range []string{ |
| "DELETE FROM home_id_native_starts WHERE expires_at<=?", |
| @@ -216,8 +254,8 @@ func sweepCodes(tx *sql.Tx, now int64) error { |
| func nativeLimitFail(w http.ResponseWriter, err error) { |
| switch { |
| - case errors.Is(err, errNativeLimitedToday): |
| - nativeFail(w, http.StatusTooManyRequests, "too_many_today") |
| + case errors.Is(err, errNativeDailyLimit): |
| + nativeFail(w, http.StatusTooManyRequests, "daily_limit") |
| case errors.Is(err, errNativeLimited): |
| nativeFail(w, http.StatusTooManyRequests, "rate_limited") |
| default: |
| @@ -307,7 +345,8 @@ func (a *App) nativeCodeStart(w http.ResponseWriter, r *http.Request) { |
| if ipBlind != "" { |
| buckets = append(buckets, |
| nativeBucket{a.bucketKey(startsPerIP, ipBlind), startsPerIP, errNativeLimited}, |
| - nativeBucket{a.bucketKey(startsPerIPDay, ipBlind), startsPerIPDay, errNativeLimited}) |
| + nativeBucket{a.bucketKey(startsPerIPDay, ipBlind), startsPerIPDay, errNativeLimited}, |
| + nativeBucket{a.bucketKey(startsPerNetDay, a.nativeMAC("native-ip", nativeNetBucket(r))), startsPerNetDay, errNativeLimited}) |
| } |
| if !returning { |
| // A new device's start is pointless once the address's new-device |
| @@ -318,12 +357,12 @@ func (a *App) nativeCodeStart(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| if full { |
| - nativeLimitFail(w, errNativeLimitedToday) |
| + nativeLimitFail(w, errNativeDailyLimit) |
| return |
| } |
| buckets = append(buckets, |
| nativeBucket{a.bucketKey(startsPerAddress, blind), startsPerAddress, errNativeLimited}, |
| - nativeBucket{a.bucketKey(startsPerAddressDay, blind), startsPerAddressDay, errNativeLimitedToday}) |
| + nativeBucket{a.bucketKey(startsPerAddressDay, blind), startsPerAddressDay, errNativeLimited}) |
| } |
| if err = checkThenSpend(tx, buckets, now); err != nil { |
| nativeLimitFail(w, err) |
| @@ -424,6 +463,10 @@ func (a *App) nativeCodeResend(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| defer tx.Rollback() |
| + if sweepCodes(tx, now) != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| s, found := loadStart(tx, in.Start, now) |
| if !found { |
| // Unknown, expired, used or dead after five wrong tries: one answer, |
| @@ -497,6 +540,10 @@ func (a *App) nativeCodeVerify(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| defer tx.Rollback() |
| + if sweepCodes(tx, now) != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| s, found := loadStart(tx, in.Start, now) |
| if !found { |
| nativeFail(w, http.StatusGone, "expired") |
| @@ -523,7 +570,7 @@ func (a *App) nativeCodeVerify(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| wrongKey := nativeBucket{a.bucketKey(wrongPerAddressKey, s.blind, s.deviceKey), wrongPerAddressKey, errNativeLimited} |
| - wrongNew := nativeBucket{a.bucketKey(wrongNewKeysPerDay, s.blind), wrongNewKeysPerDay, errNativeLimitedToday} |
| + wrongNew := nativeBucket{a.bucketKey(wrongNewKeysPerDay, s.blind), wrongNewKeysPerDay, errNativeDailyLimit} |
| guard := []nativeBucket{wrongKey} |
| if !returning { |
| guard = append(guard, wrongNew) |
diff --git a/internal/home/native_code_test.go b/internal/home/native_code_test.go| index c91d20b..140d848 100644 |
| --- a/internal/home/native_code_test.go |
| +++ b/internal/home/native_code_test.go |
| @@ -249,7 +249,7 @@ func TestNativeCodeDailyCapAndReturningKeys(t *testing.T) { |
| } |
| stranger := newDevice(t) |
| w := stranger.call(t, app, nativePrefix+"/code/start", map[string]string{"email": email, "device_key": stranger.public(), "platform": "macos"}, "") |
| - if w.Code != 429 || decodeReply(t, w)["error"] != "too_many_today" { |
| + if w.Code != 429 || decodeReply(t, w)["error"] != "daily_limit" { |
| t.Fatal("a new device started past the daily cap", w.Code, w.Body.String()) |
| } |
| app = app.restart(t) // a fresh web budget: only the native caps speak |
| @@ -262,13 +262,66 @@ func TestNativeCodeDailyCapAndReturningKeys(t *testing.T) { |
| if v := mine.verify(t, app, start, lastCode(t, app)); v.Code != 200 { |
| t.Fatal("a returning device could not verify", v.Code, v.Body.String()) |
| } |
| - } else if w.Code != 429 { |
| - t.Fatal("a cut-off device was treated as returning", w.Code) |
| + } else if w.Code != 429 || decodeReply(t, w)["error"] != "daily_limit" { |
| + t.Fatal("a cut-off device was treated as returning", w.Code, w.Body.String()) |
| } |
| }) |
| } |
| } |
| +// The 429 markers: daily_limit is only the daily wrong-code cap for new |
| +// devices, at start and at verify; every other limit is rate_limited. |
| +func TestNativeCode429Markers(t *testing.T) { |
| + app := newNativeApp(t) |
| + const email = "marker@example.invalid" |
| + waiting := newDevice(t) |
| + held := waiting.start(t, app, email) // a new device holding a live code |
| + for range 3 { |
| + a := newDevice(t) |
| + start := a.start(t, app, email) |
| + for range 5 { |
| + a.verify(t, app, start, "000000") |
| + } |
| + } |
| + // 15 wrong so far; five more from the waiting device fill the cap. |
| + for i := range 5 { |
| + if w := waiting.verify(t, app, held, "000000"); w.Code != 400 && lastCode(t, app) != "000000" { |
| + t.Fatal("wrong", i, w.Code) |
| + } |
| + } |
| + late := newDevice(t) |
| + w := late.call(t, app, nativePrefix+"/code/start", map[string]string{"email": email, "device_key": late.public(), "platform": "macos"}, "") |
| + if w.Code != 429 || decodeReply(t, w)["error"] != "daily_limit" { |
| + t.Fatal("start past the daily cap", w.Code, w.Body.String()) |
| + } |
| + // A verify past the cap, from a new device with a live start. |
| + app = app.restart(t) |
| + if _, err := app.db.Writer().Exec("DELETE FROM home_id_native_buckets WHERE bucket LIKE 'start-%'"); err != nil { |
| + t.Fatal(err) |
| + } |
| + other := newDevice(t) |
| + if _, err := app.db.Writer().Exec("UPDATE home_id_native_buckets SET count=count-1 WHERE bucket LIKE 'wrong-new-day:%'"); err != nil { |
| + t.Fatal(err) |
| + } |
| + start := other.start(t, app, email) |
| + if _, err := app.db.Writer().Exec("UPDATE home_id_native_buckets SET count=count+1 WHERE bucket LIKE 'wrong-new-day:%'"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if w := other.verify(t, app, start, lastCode(t, app)); w.Code != 429 || decodeReply(t, w)["error"] != "daily_limit" { |
| + t.Fatal("verify past the daily cap", w.Code, w.Body.String()) |
| + } |
| + // Any other limit: the per-address start window. |
| + app = newNativeApp(t) |
| + for range 5 { |
| + newDevice(t).start(t, app, "window@example.invalid") |
| + } |
| + app = app.restart(t) |
| + d := newDevice(t) |
| + if w := d.call(t, app, nativePrefix+"/code/start", map[string]string{"email": "window@example.invalid", "device_key": d.public(), "platform": "macos"}, ""); w.Code != 429 || decodeReply(t, w)["error"] != "rate_limited" { |
| + t.Fatal("window limit marker", w.Code, w.Body.String()) |
| + } |
| +} |
| + |
| // §13 Codes: an exempt key keeps its own limit. |
| func TestNativeCodeExemptKeyKeepsItsOwnLimit(t *testing.T) { |
| app := newNativeApp(t) |
diff --git a/internal/home/native_grant_test.go b/internal/home/native_grant_test.go| index 6bd9392..44dcf3c 100644 |
| --- a/internal/home/native_grant_test.go |
| +++ b/internal/home/native_grant_test.go |
| @@ -93,7 +93,7 @@ func TestNativeProofTableLimits(t *testing.T) { |
| } |
| other := newDevice(t) |
| grant2, _ := other.signInByCode(t, app, "m@example.invalid") |
| - if nativeReplayCap != 100000 { |
| + if nativeReplayCap != 250000 { |
| t.Fatal("the replay table's size moved", nativeReplayCap) |
| } |
| prev := nativeReplayCap |
| @@ -104,7 +104,7 @@ func TestNativeProofTableLimits(t *testing.T) { |
| t.Fatal(err) |
| } |
| for i := range nativeReplayCap { |
| - if _, err := tx.Exec("INSERT INTO home_id_native_replay VALUES(?,?,?)", fmt.Sprint("fill", i), "x", int64(1<<40)); err != nil { |
| + if _, err := tx.Exec("INSERT INTO home_id_native_replay VALUES(?,?,?,?)", fmt.Sprint("fill", i), "x", "p", int64(1<<40)); err != nil { |
| t.Fatal(err) |
| } |
| } |
| @@ -198,21 +198,22 @@ func TestNativeMintPolicyShared(t *testing.T) { |
| // §3: a 21st grant ends the least recently used; lapsed grants expire. |
| func TestNativeGrantLimitsAndExpiry(t *testing.T) { |
| app := newNativeApp(t) |
| - var grants []string |
| - for i := range nativeGrantsPerID + 1 { |
| - app = app.restart(t) // a fresh web budget for each start |
| - if _, err := app.db.Writer().Exec("DELETE FROM home_id_native_buckets"); err != nil { |
| + d := newDevice(t) |
| + first, _ := d.signInByCode(t, app, "many@example.invalid") |
| + var person string |
| + app.db.Writer().QueryRow("SELECT person_ref FROM home_id_grants").Scan(&person) |
| + // The oldest-used grant, then eighteen more used today: twenty live. |
| + if _, err := app.db.Writer().Exec("UPDATE home_id_grants SET last_used_day=?", dayOf(time.Now().Unix()-2*day)); err != nil { |
| + t.Fatal(err) |
| + } |
| + for i := range nativeGrantsPerID - 1 { |
| + if _, err := app.db.Writer().Exec("INSERT INTO home_id_grants(grant_hash,person_ref,identity_id,device_key,platform,method,auth_time,created_at,last_used_day,expires_at) VALUES(?,?,'i','k','macos','email',1,?,?,?)", |
| + fmt.Sprint("g", i), person, time.Now().Unix(), dayOf(time.Now().Unix()), time.Now().Unix()+day); err != nil { |
| t.Fatal(err) |
| } |
| - g, _ := newDevice(t).signInByCode(t, app, "many@example.invalid") |
| - if i == 0 { |
| - if _, err := app.db.Writer().Exec("UPDATE home_id_grants SET last_used_day=? WHERE grant_hash=?", dayOf(time.Now().Unix()-2*day), nativeHash(g)); err != nil { |
| - t.Fatal(err) |
| - } |
| - } |
| - grants = append(grants, g) |
| } |
| - if ended, reason := grantState(t, app, grants[0]); !ended || reason != "lru" { |
| + newDevice(t).signInByCode(t, app, "many@example.invalid") // the 21st |
| + if ended, reason := grantState(t, app, first); !ended || reason != "lru" { |
| t.Fatal("21st grant did not end the LRU", ended, reason) |
| } |
| if n := count(t, app, "SELECT count(*) FROM home_id_grants WHERE ended_at IS NULL"); n != nativeGrantsPerID { |
diff --git a/internal/home/native_passkey.go b/internal/home/native_passkey.go| index 42a675b..f0af7ea 100644 |
| --- a/internal/home/native_passkey.go |
| +++ b/internal/home/native_passkey.go |
| @@ -17,6 +17,10 @@ import ( |
| // grant instead of a cookie. |
| const nativeCeremonyPurpose = "native" |
| +// nativeCeremonyShare is the most of home_id_ceremonies' 10,000 rows native |
| +// challenges may hold. |
| +const nativeCeremonyShare = 5000 |
| + |
| // nativePasskeyBegin is POST passkey/begin {device_key, platform, pending?}. |
| // Without pending it is a discoverable sign-in that needs no email; with one |
| // it finishes a code sign-in on an enrolled account, and device_key must be |
| @@ -69,20 +73,35 @@ func (a *App) nativePasskeyBegin(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| if ip := nativeIPBucket(r); ip != "" { |
| - b := nativeBucket{a.bucketKey(passkeyBeginsPerIP, a.nativeMAC("native-ip", ip)), passkeyBeginsPerIP, errNativeLimited} |
| - if err = checkThenSpend(tx, []nativeBucket{b}, now); err != nil { |
| + bs := []nativeBucket{ |
| + {a.bucketKey(passkeyBeginsPerIP, a.nativeMAC("native-ip", ip)), passkeyBeginsPerIP, errNativeLimited}, |
| + {a.bucketKey(passkeyBeginsPerNet, a.nativeMAC("native-ip", nativeNetBucket(r))), passkeyBeginsPerNet, errNativeLimited}, |
| + } |
| + if err = checkThenSpend(tx, bs, now); err != nil { |
| nativeLimitFail(w, err) |
| return |
| } |
| } |
| - for _, q := range []string{"DELETE FROM home_id_ceremonies WHERE expires_at<=?", "DELETE FROM home_id_native_ceremonies WHERE expires_at<=?"} { |
| - if _, err = tx.Exec(q, now); err != nil { |
| + // One live challenge per device key: a new begin replaces the last, so |
| + // a key cannot hold more than one row. |
| + binding := nativeHash("native\x00" + key) |
| + for _, q := range []struct { |
| + sql string |
| + args []any |
| + }{ |
| + {"DELETE FROM home_id_ceremonies WHERE expires_at<=? OR (browser_hash=? AND purpose=?)", []any{now, binding, nativeCeremonyPurpose}}, |
| + {"DELETE FROM home_id_native_ceremonies WHERE expires_at<=? OR device_key=?", []any{now, key}}, |
| + } { |
| + if _, err = tx.Exec(q.sql, q.args...); err != nil { |
| nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| return |
| } |
| } |
| - var n int |
| - if tx.QueryRow("SELECT count(*) FROM home_id_ceremonies").Scan(&n) != nil || n >= 10000 { |
| + // The ceremonies table is shared with the web door. Native challenges |
| + // may take at most half of it, so a native flood cannot lock the web's |
| + // passkey sign-in out. |
| + var n, native int |
| + if tx.QueryRow("SELECT count(*), count(CASE WHEN purpose=? THEN 1 END) FROM home_id_ceremonies", nativeCeremonyPurpose).Scan(&n, &native) != nil || n >= 10000 || native >= nativeCeremonyShare { |
| nativeFail(w, http.StatusServiceUnavailable, "full") |
| return |
| } |
| @@ -92,7 +111,7 @@ func (a *App) nativePasskeyBegin(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| id := hex.EncodeToString(challenge) |
| - if _, err = tx.Exec("INSERT INTO home_id_ceremonies VALUES (?,?,?,?,?)", id, nativeHash("native\x00"+key), subject, nativeCeremonyPurpose, now+300); err != nil { |
| + if _, err = tx.Exec("INSERT INTO home_id_ceremonies VALUES (?,?,?,?,?)", id, binding, subject, nativeCeremonyPurpose, now+300); err != nil { |
| nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| return |
| } |
diff --git a/internal/home/native_review_test.go b/internal/home/native_review_test.go| new file mode 100644 |
| index 0000000..977cb98 |
| --- /dev/null |
| +++ b/internal/home/native_review_test.go |
| @@ -0,0 +1,186 @@ |
| +package home |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "net/http" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| +) |
| + |
| +// Review finding 1: a native directory session reads teams and nothing else. |
| +// Its auth_time is a (possibly code-only) sign-in's, and the directory's |
| +// browser routes trust auth_time for roster and operator freshness. |
| +func TestNativeDirectorySessionIsConfined(t *testing.T) { |
| + f := newMountedChooser(t) |
| + cred := f.p.credential |
| + d := newDevice(t) |
| + grant, _ := d.signInByCode(t, cred, "confined@example.invalid") |
| + var person string |
| + cred.db.Writer().QueryRow("SELECT person_ref FROM home_id_grants").Scan(&person) |
| + f.team(t, "AAA111", "blue", "Blue team", person) |
| + if _, err := f.p.directory.db.Writer().Exec("UPDATE memberships SET role='owner' WHERE person_ref=?", person); err != nil { |
| + t.Fatal(err) |
| + } |
| + verifier, challenge := verifierFor(50) |
| + token := decodeReply(t, d.assert(t, cred, grant, directoryOrigin, challenge))["assertion"].(string) |
| + out := decodeReply(t, directoryCall(t, f, "POST", nativeExchangePath, exchangeBody(token, verifier), nil, nil)) |
| + native := &http.Cookie{Name: out["name"].(string), Value: out["value"].(string)} |
| + |
| + if w := directoryCall(t, f, "GET", nativeTeamsPath, "", native, nil); w.Code != 200 { |
| + t.Fatal("the native route refused its own session", w.Code) |
| + } |
| + // Every browser route sees no session: the front page, not the |
| + // directory; no Team page; no account menu. |
| + home := exchangeRequest(f.p.directory, "GET", directoryOrigin+"/", "", nil, native) |
| + browser := exchangeRequest(f.p.directory, "GET", directoryOrigin+"/", "", nil, f.session(t, person)) |
| + if strings.Contains(home.Body.String(), "Sign out all devices") || home.Body.String() == browser.Body.String() { |
| + t.Fatal("a native session opened the directory") |
| + } |
| + if w := exchangeRequest(f.p.directory, "GET", directoryOrigin+teamPath+"?team=AAA111", "", nil, native); w.Code == 200 && strings.Contains(w.Body.String(), "Blue team") { |
| + t.Fatal("a native session opened the Team page") |
| + } |
| + // A forged same-origin roster write carries it in vain. |
| + exchangeRequest(f.p.directory, "POST", directoryOrigin+teamNamePath, directoryOrigin, map[string][]string{"team": {"AAA111"}, "name": {"Renamed"}}, native) |
| + if w := directoryCall(t, f, "GET", nativeTeamsPath, "", native, nil); !strings.Contains(w.Body.String(), `"name":"Blue team"`) { |
| + t.Fatal("a native session wrote the roster", w.Body.String()) |
| + } |
| + // And it is never fresh, whatever its auth_time. |
| + s := sessions.Session{Subject: person, Method: nativeSessionMethod, AuthTime: time.Now()} |
| + if teamFresh(s, time.Now()) || directoryFresh(s, time.Now()) { |
| + t.Fatal("a native session counts as fresh") |
| + } |
| + s.Method = "assertion" |
| + if !teamFresh(s, time.Now()) || !directoryFresh(s, time.Now()) { |
| + t.Fatal("control: a fresh browser session") |
| + } |
| + // Its own sign-out still works. |
| + if w := directoryCall(t, f, "POST", nativeDirectorySignout, "{}", native, nil); w.Code != 200 { |
| + t.Fatal(w.Code) |
| + } |
| + if w := directoryCall(t, f, "GET", nativeTeamsPath, "", native, nil); w.Code != 401 { |
| + t.Fatal("signed-out native session", w.Code) |
| + } |
| +} |
| + |
| +// Review finding 2: any live grant makes a key returning; otherwise the most |
| +// recently ENDED grant decides, not the most recently created one. |
| +func TestNativeReturningKeyRule(t *testing.T) { |
| + app := newNativeApp(t) |
| + insert := func(hash string, created int64, ended any, reason any) { |
| + t.Helper() |
| + if _, err := app.db.Writer().Exec("INSERT INTO home_id_grants(grant_hash,person_ref,identity_id,device_key,platform,method,auth_time,created_at,last_used_day,expires_at,ended_at,end_reason) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)", |
| + hash, "pr_person", "i", "key", "macos", "email", 1, created, dayOf(time.Now().Unix()), time.Now().Unix()+day, ended, reason); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + check := func(want bool) { |
| + t.Helper() |
| + tx, err := app.db.Writer().Begin() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer tx.Rollback() |
| + got, err := returningKey(tx, "pr_person", "key") |
| + if err != nil || got != want { |
| + t.Fatal("returning", got, want, err) |
| + } |
| + } |
| + // An older grant still live; a newer one cut off by sign-out-all. |
| + insert("a", 100, nil, nil) |
| + insert("b", 200, 300, "all_devices") |
| + check(true) |
| + // Nothing live: the newer-created grant ended by expiry first, the older |
| + // one was cut off later. The cut-off is the last word. |
| + if _, err := app.db.Writer().Exec("DELETE FROM home_id_grants"); err != nil { |
| + t.Fatal(err) |
| + } |
| + insert("c", 100, 500, "revoke") |
| + insert("d", 200, 300, "expiry") |
| + check(false) |
| + // And the other way round. |
| + if _, err := app.db.Writer().Exec("DELETE FROM home_id_grants"); err != nil { |
| + t.Fatal(err) |
| + } |
| + insert("e", 100, 300, "replacement") |
| + insert("f", 200, 500, "lru") |
| + check(true) |
| +} |
| + |
| +// Review finding 3: expired sealed addresses are swept at boot and by |
| +// verify and resend, not only by the next start. |
| +func TestNativeExpiredStartsSwept(t *testing.T) { |
| + app := newNativeApp(t) |
| + d := newDevice(t) |
| + d.start(t, app, "swept@example.invalid") |
| + if _, err := app.db.Writer().Exec("UPDATE home_id_native_starts SET expires_at=1"); err != nil { |
| + t.Fatal(err) |
| + } |
| + app.restart(t) |
| + if n := count(t, app, "SELECT count(*) FROM home_id_native_starts"); n != 0 { |
| + t.Fatal("boot left an expired sealed address", n) |
| + } |
| + start := d.start(t, app, "swept2@example.invalid") |
| + e := newDevice(t) |
| + e.start(t, app, "swept3@example.invalid") |
| + if _, err := app.db.Writer().Exec("UPDATE home_id_native_starts SET expires_at=1 WHERE device_key=?", e.public()); err != nil { |
| + t.Fatal(err) |
| + } |
| + d.verify(t, app, start, "000000") |
| + if n := count(t, app, "SELECT count(*) FROM home_id_native_starts WHERE device_key=?", e.public()); n != 0 { |
| + t.Fatal("verify left an expired sealed address", n) |
| + } |
| + if err := app.sweepNativeAtBoot(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// Review finding 4: rotating addresses inside one network buys nothing, and |
| +// a device key holds one live native challenge. |
| +func TestNativeNetworkBucketsAndBeginDedupe(t *testing.T) { |
| + a := httpRequestFrom("[2001:db8:7:1::1]:1") |
| + b := httpRequestFrom("[2001:db8:7:ffff::9]:1") |
| + c := httpRequestFrom("[2001:db8:8::1]:1") |
| + if nativeNetBucket(a) != nativeNetBucket(b) || nativeNetBucket(a) == nativeNetBucket(c) || nativeNetBucket(httpRequestFrom("192.0.2.77:1")) != "192.0.2.0/24" { |
| + t.Fatal("network buckets", nativeNetBucket(a), nativeNetBucket(b), nativeNetBucket(c)) |
| + } |
| + if startsPerNetDay.limit != 1000 || passkeyBeginsPerIP.limit != 60 { |
| + t.Fatal("limits moved") |
| + } |
| + app := newNativeApp(t) |
| + d := newDevice(t) |
| + for range 3 { |
| + if w := d.call(t, app, nativePrefix+"/passkey/begin", map[string]string{"device_key": d.public(), "platform": "ios"}, ""); w.Code != 200 { |
| + t.Fatal(w.Code) |
| + } |
| + } |
| + if n := count(t, app, "SELECT count(*) FROM home_id_ceremonies WHERE purpose='native'"); n != 1 { |
| + t.Fatal("one key holds several challenges", n) |
| + } |
| + if n := count(t, app, "SELECT count(*) FROM home_id_native_ceremonies"); n != 1 { |
| + t.Fatal("native ceremony rows", n) |
| + } |
| + // Native challenges may hold half the shared table, never the web's half. |
| + tx, err := app.db.Writer().Begin() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for i := range nativeCeremonyShare { |
| + if _, err := tx.Exec("INSERT INTO home_id_ceremonies VALUES(?,?,?,?,?)", fmt.Sprint("fill", i), "b", "", nativeCeremonyPurpose, time.Now().Unix()+300); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if err := tx.Commit(); err != nil { |
| + t.Fatal(err) |
| + } |
| + e := newDevice(t) |
| + if w := e.call(t, app, nativePrefix+"/passkey/begin", map[string]string{"device_key": e.public(), "platform": "ios"}, "", proofOpts{ip: "198.51.100.9:1"}); w.Code != 503 { |
| + t.Fatal("native took more than its share", w.Code) |
| + } |
| + if w := postJSON(t, app, "/passkey/register/begin", signInFully(t, app, "web-share@example.invalid"), nil); w.Code != 200 { |
| + t.Fatal("the web's passkey ceremonies were locked out", w.Code) |
| + } |
| +} |
diff --git a/internal/home/native_revoke_test.go b/internal/home/native_revoke_test.go| index 85f9d1a..fa994b0 100644 |
| --- a/internal/home/native_revoke_test.go |
| +++ b/internal/home/native_revoke_test.go |
| @@ -1,12 +1,16 @@ |
| package home |
| import ( |
| + "net/http" |
| + "net/http/httptest" |
| "net/url" |
| + "regexp" |
| "strings" |
| "testing" |
| "time" |
| "amadan.net/oficina/home/internal/home/sealtest" |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| "amadan.net/rastrillo/rastrillo/webauthn" |
| ) |
| @@ -37,15 +41,22 @@ func TestNativeFirstEnrolmentRevokesPasskeylessGrants(t *testing.T) { |
| } |
| } |
| -// §13 Revocation: "Sign out all devices" ends every grant, behind a fresh |
| -// session and request-forgery protection. |
| +// §13 Revocation, with Paul's 2026-11-14 ruling: "Sign out all devices" ends |
| +// every grant and every Home browser session of that person, on id.* in one |
| +// transaction with the grants, and on the directory in one transaction with |
| +// the signed receipt this browser carries across. Behind a fresh session and |
| +// request-forgery protection. |
| func TestNativeSignOutAllDevices(t *testing.T) { |
| - app := newNativeApp(t) |
| + f := newMountedChooser(t) |
| + app := f.p.credential |
| g1, _ := newDevice(t).signInByCode(t, app, sealtest.CanaryAddress) |
| app = app.restart(t) |
| g2, _ := newDevice(t).signInByCode(t, app, sealtest.CanaryAddress) |
| other, _ := newDevice(t).signInByCode(t, app, "other@example.invalid") |
| - session := signInFully(t, app, sealtest.CanaryAddress) |
| + otherBrowser := signInFully(t, app, "other@example.invalid") |
| + elsewhere := signInFully(t, app, sealtest.CanaryAddress) // another browser |
| + session := signInFully(t, app.restart(t), sealtest.CanaryAddress) |
| + person := subjectOf(t, app, session) |
| page := exchangeRequest(app.App, "GET", Origin+signoutAllPath, "", nil, session) |
| if page.Code != 200 || !strings.Contains(page.Body.String(), `action="/devices/sign-out-all"`) { |
| @@ -58,7 +69,8 @@ func TestNativeSignOutAllDevices(t *testing.T) { |
| t.Fatal("no session ended devices") |
| } |
| // A stale session must re-authenticate first. |
| - if _, err := app.db.Writer().Exec("UPDATE sessions SET auth_time=?, created_at=?", time.Now().Add(-time.Hour).UTC().Format(time.RFC3339), time.Now().Add(-time.Hour).UTC().Format(time.RFC3339)); err != nil { |
| + stamp := time.Now().Add(-time.Hour).UTC().Format(time.RFC3339) |
| + if _, err := app.db.Writer().Exec("UPDATE sessions SET auth_time=?, created_at=? WHERE token_hash=?", stamp, stamp, sessions.HashToken(session.Value)); err != nil { |
| t.Fatal(err) |
| } |
| if stale := exchangeRequest(app.App, "POST", Origin+signoutAllPath, Origin, url.Values{}, session); stale.Code == 200 { |
| @@ -68,21 +80,90 @@ func TestNativeSignOutAllDevices(t *testing.T) { |
| t.Fatal("grants ended without a fresh session", n) |
| } |
| session = signInFully(t, app.restart(t), sealtest.CanaryAddress) |
| + |
| + // The person's directory sessions, in two browsers and one native app, |
| + // and someone else's. |
| + dirA, dirB, dirOther := f.session(t, person), f.session(t, person), f.session(t, chooserOther) |
| + if _, err := f.p.directory.db.Writer().Exec("INSERT INTO sessions(token_hash,subject,method,auth_time,created_at,expires_at) VALUES('native-dir',?,?,?,?,?)", person, nativeSessionMethod, stamp, stamp, time.Now().Add(time.Hour).UTC().Format(time.RFC3339)); err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| done := exchangeRequest(app.App, "POST", Origin+signoutAllPath, Origin, url.Values{}, session) |
| - if done.Code != 200 || !strings.Contains(done.Body.String(), "All devices are signed out") { |
| + if done.Code != 200 || !strings.Contains(done.Body.String(), `action="`+directoryOrigin+signedOutAllPath+`"`) { |
| t.Fatal("sign out all", done.Code) |
| } |
| + if c := namedCookieOrNil(done, app.sessions.CookieName()); c == nil || c.MaxAge >= 0 { |
| + t.Fatal("this browser's id.* cookie was not cleared") |
| + } |
| + // id.*: every grant and every session of the person, at once. |
| for _, g := range []string{g1, g2} { |
| if ended, reason := grantState(t, app, g); !ended || reason != "all_devices" { |
| t.Fatal("grant survived", reason) |
| } |
| } |
| + if n := count(t, app, "SELECT count(*) FROM sessions WHERE subject=?", person); n != 0 { |
| + t.Fatal("id.* sessions survived", n) |
| + } |
| + if r := exchangeRequest(app.App, "GET", Origin+signoutAllPath, "", nil, elsewhere); r.Code == 200 { |
| + t.Fatal("the person's other id.* browser is still signed in") |
| + } |
| if ended, _ := grantState(t, app, other); ended { |
| t.Fatal("another person's grant ended") |
| } |
| - if subjectOf(t, app, session) == "" { |
| - t.Fatal("this browser was signed out") |
| + if subjectOf(t, app, otherBrowser) == "" { |
| + t.Fatal("another person's session ended") |
| + } |
| + |
| + // The directory: the receipt from the hop page ends every session of |
| + // the person there, once. |
| + token := regexp.MustCompile(`name="assertion" value="([^"]+)"`).FindStringSubmatch(done.Body.String())[1] |
| + if bad := exchangeRequest(f.p.directory, "POST", directoryOrigin+signedOutAllPath, directoryOrigin, url.Values{"assertion": {token}}, dirA); bad.Code == 303 { |
| + t.Fatal("receipt accepted from the wrong origin") |
| + } |
| + hop := exchangeRequest(f.p.directory, "POST", directoryOrigin+signedOutAllPath, Origin, url.Values{"assertion": {token}}, dirA) |
| + if hop.Code != 303 || hop.Header().Get("Location") != "/signed-out" { |
| + t.Fatal("directory hop", hop.Code, hop.Body.String()) |
| + } |
| + n := 0 |
| + f.p.directory.db.Writer().QueryRow("SELECT count(*) FROM sessions WHERE subject=?", person).Scan(&n) |
| + if n != 0 { |
| + t.Fatal("directory sessions survived", n) |
| + } |
| + for _, c := range []*http.Cookie{dirA, dirB} { |
| + if w := exchangeRequest(f.p.directory, "GET", directoryOrigin+"/", "", nil, c); strings.Contains(w.Body.String(), "Sign out all devices") { |
| + t.Fatal("a directory browser is still signed in") |
| + } |
| + } |
| + if w := exchangeRequest(f.p.directory, "GET", directoryOrigin+"/", "", nil, dirOther); !strings.Contains(w.Body.String(), "Sign out all devices") { |
| + t.Fatal("control: a signed-in directory page shows the menu item") |
| + } |
| + f.p.directory.db.Writer().QueryRow("SELECT count(*) FROM sessions WHERE subject=?", chooserOther).Scan(&n) |
| + if n != 1 { |
| + t.Fatal("another person's directory session ended") |
| + } |
| + landed := exchangeRequest(f.p.directory, "GET", directoryOrigin+"/signed-out", "", nil, namedCookie(t, hop, "__Host-oficina-signed-out-all")) |
| + if !strings.Contains(landed.Body.String(), "All devices are signed out") { |
| + t.Fatal("signed-out page", landed.Code) |
| + } |
| + if again := exchangeRequest(f.p.directory, "POST", directoryOrigin+signedOutAllPath, Origin, url.Values{"assertion": {token}}); again.Code == 303 { |
| + t.Fatal("receipt replayed") |
| + } |
| + // A sign-in assertion is not a sign-out receipt. |
| + fresh := signInFully(t, app.restart(t), "victim@example.invalid") |
| + _, intent := f.p.start(t) |
| + signin, _ := f.p.mint(t, intent, fresh) |
| + if w := exchangeRequest(f.p.directory, "POST", directoryOrigin+signedOutAllPath, Origin, url.Values{"assertion": {signin}}); w.Code == 303 { |
| + t.Fatal("a sign-in assertion signed someone out") |
| + } |
| +} |
| + |
| +func namedCookieOrNil(r *httptest.ResponseRecorder, name string) *http.Cookie { |
| + for _, c := range r.Result().Cookies() { |
| + if c.Name == name { |
| + return c |
| + } |
| } |
| + return nil |
| } |
| // §13 Revocation: recovery-based replacement ends every grant. |
diff --git a/internal/home/operator_confirm.go b/internal/home/operator_confirm.go| index e090a1f..31e2b8c 100644 |
| --- a/internal/home/operator_confirm.go |
| +++ b/internal/home/operator_confirm.go |
| @@ -53,7 +53,9 @@ func operatorTime(unix int64) string { |
| // passes here as it passes the Team page (the amendment's inherited gap); |
| // the credential page is where the method is visible and refused. |
| func directoryFresh(s sessions.Session, now time.Time) bool { |
| - return !s.AuthTime.IsZero() && !s.AuthTime.After(now) && now.Sub(s.AuthTime) <= operatorFreshness |
| + // A native app's directory session is never fresh: it reads teams and |
| + // nothing else (directory_native.go, nativeSessionsStayNative). |
| + return s.Method != nativeSessionMethod && !s.AuthTime.IsZero() && !s.AuthTime.After(now) && now.Sub(s.AuthTime) <= operatorFreshness |
| } |
| type directoryPlanView struct { |
diff --git a/internal/home/signout_all.go b/internal/home/signout_all.go| index ebe0e59..42c5527 100644 |
| --- a/internal/home/signout_all.go |
| +++ b/internal/home/signout_all.go |
| @@ -1,24 +1,57 @@ |
| package home |
| import ( |
| + "crypto/sha256" |
| + "crypto/subtle" |
| + "encoding/base64" |
| + "encoding/hex" |
| "net/http" |
| "time" |
| + |
| + "amadan.net/rastrillo/rastrillo/assertion" |
| ) |
| // signoutAllPath is "Sign out all devices" (§10): the slice-A stand-in for |
| -// A2's Devices page. It ends every native grant the person holds. Browser |
| -// sessions are not native grants and are left alone; each device's team |
| -// sessions run out within seven days (the disclosed residual). |
| +// A2's Devices page. Paul, 2026-11-14: it ends every native grant AND every |
| +// Home browser session the person has, on id.* and on the directory, |
| +// including the browser pressing the button. |
| +// |
| +// id.* holds the grants and its own sessions in one database, so those end |
| +// in one transaction. The directory's sessions live in the directory's own |
| +// database, which id.* cannot write; they end in one transaction there, when |
| +// this browser carries a signed receipt across (signedOutAllPath). What |
| +// cannot be made atomic is the hop between the two stores: if the browser |
| +// never makes it, the person's directory sessions run to their own expiry. |
| +// They grant identity only (never an app's content), and the native ones |
| +// cannot be renewed once the grants are gone. |
| const signoutAllPath = "/devices/sign-out-all" |
| +// signedOutAllPath is the directory's receiver for that receipt. |
| +const signedOutAllPath = "/auth/signed-out-all" |
| + |
| +// signoutAllNonceContext domain-separates the receipt's nonce. The receipt |
| +// is an ordinary v1 assertion for the directory audience whose nonce Home |
| +// derives from its own jti, so it can match no browser's pending sign-in |
| +// and no native verifier, and the receiver accepts no other nonce. |
| +const signoutAllNonceContext = "oficina-id/signout-all/v1" |
| + |
| +func signoutAllNonce(jti string) string { |
| + h := sha256.New() |
| + h.Write([]byte(signoutAllNonceContext)) |
| + h.Write([]byte{0}) |
| + h.Write([]byte(jti)) |
| + return base64.RawURLEncoding.EncodeToString(h.Sum(nil)[:16]) |
| +} |
| + |
| func (a *App) handleSignoutAllPage(w http.ResponseWriter, r *http.Request) { |
| - a.render(w, r, http.StatusOK, "id_signout_all.html", map[string]any{"Done": false}) |
| + a.render(w, r, http.StatusOK, "id_signout_all.html", nil) |
| } |
| // handleSignoutAll is behind RequireFresh and csrf.Protect, and re-reads the |
| // live session inside the writer transaction, as recovery-code generation |
| // does, so a session revoked a moment ago cannot end anybody's devices. |
| func (a *App) handleSignoutAll(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Cache-Control", "no-store") |
| tx, now, err := a.idTransaction(r.Context()) |
| if err != nil { |
| a.serverError(w, r) |
| @@ -30,9 +63,98 @@ func (a *App) handleSignoutAll(w http.ResponseWriter, r *http.Request) { |
| a.signinFailed(w, r) |
| return |
| } |
| - if err = endGrants(tx, live.Subject, "all_devices", now); err != nil || tx.Commit() != nil { |
| + authTime := live.AuthTime |
| + if authTime.IsZero() { |
| + authTime = live.At |
| + } |
| + if err = endGrants(tx, live.Subject, "all_devices", now); err != nil { |
| + a.serverError(w, r) |
| + return |
| + } |
| + // Every id.* session of this person, this browser's included, in the |
| + // same transaction as the grants, along with the half-finished sign-ins |
| + // that would otherwise mint a new one. |
| + for _, q := range []string{ |
| + "DELETE FROM sessions WHERE subject=?", |
| + "DELETE FROM passkey_pending WHERE subject=?", |
| + "DELETE FROM home_id_native_pending WHERE person_ref=?", |
| + } { |
| + if _, err = tx.Exec(q, live.Subject); err != nil { |
| + a.serverError(w, r) |
| + return |
| + } |
| + } |
| + id, err := assertion.RandomID() |
| + if err != nil { |
| + a.serverError(w, r) |
| + return |
| + } |
| + receipt, err := assertion.Sign(a.runtime.signer, assertion.Claims{ |
| + Version: 1, Issuer: a.origins.Credential, Audience: a.origins.Directory, Subject: live.Subject, |
| + KeyID: a.runtime.keyID, ID: id, Nonce: signoutAllNonce(id), |
| + IssuedAt: now, ExpiresAt: now + 120, AuthTime: min(authTime.Unix(), now), |
| + }) |
| + if err != nil { |
| + a.serverError(w, r) |
| + return |
| + } |
| + if tx.Commit() != nil { |
| a.serverError(w, r) |
| return |
| } |
| - a.render(w, r, http.StatusOK, "id_signout_all.html", map[string]any{"Done": true, "Directory": a.origins.Directory}) |
| + idCookie(w, a.sessions.CookieName(), "", -1) |
| + // The hop to the directory: the same self-submitting form, transport and |
| + // referrer policy as the assertion handoff. |
| + w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin") |
| + a.render(w, r, http.StatusOK, "assertion.html", map[string]any{"Action": a.origins.Directory + signedOutAllPath, "Token": receipt}) |
| +} |
| + |
| +// handleSignedOutAll is the directory's half: POST /auth/signed-out-all |
| +// {assertion}, from the credential origin only. It ends every directory |
| +// session the person holds, browser and native, in one transaction with |
| +// the receipt's jti, then lands this browser on the signed-out page. |
| +func (a *App) handleSignedOutAll(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Cache-Control", "no-store") |
| + if origins := r.Header.Values("Origin"); len(origins) != 1 || origins[0] != a.origins.Credential { |
| + a.failDirectoryHandoff(w, r, http.StatusForbidden) |
| + return |
| + } |
| + r.Body = http.MaxBytesReader(w, r.Body, 16<<10) |
| + if r.ParseForm() != nil || len(r.PostForm["assertion"]) != 1 || len(r.PostForm) != 1 { |
| + a.failDirectoryHandoff(w, r, http.StatusBadRequest) |
| + return |
| + } |
| + v, err := assertion.NewVerifier(a.origins.Credential, a.origins.Directory, a.runtime.keys) |
| + if err != nil { |
| + a.failDirectoryHandoff(w, r, http.StatusServiceUnavailable) |
| + return |
| + } |
| + claims, err := v.Verify(r.PostForm.Get("assertion"), time.Now()) |
| + if err != nil || subtle.ConstantTimeCompare([]byte(claims.Nonce), []byte(signoutAllNonce(claims.ID))) != 1 || !ValidPersonRef(claims.Subject) { |
| + a.failDirectoryHandoff(w, r, http.StatusForbidden) |
| + return |
| + } |
| + tx, err := a.db.Writer().BeginTx(r.Context(), nil) |
| + if err != nil { |
| + a.failDirectoryHandoff(w, r, http.StatusServiceUnavailable) |
| + return |
| + } |
| + defer tx.Rollback() |
| + jti := sha256.Sum256([]byte(claims.Issuer + "\x00" + claims.ID)) |
| + res, err := tx.Exec("INSERT INTO oficina_handoff_replay(jti_hash,expires_at) VALUES(?,?) ON CONFLICT DO NOTHING", hex.EncodeToString(jti[:]), claims.ExpiresAt) |
| + if err != nil { |
| + a.failDirectoryHandoff(w, r, http.StatusServiceUnavailable) |
| + return |
| + } |
| + if n, err := res.RowsAffected(); err != nil || n != 1 { |
| + a.failDirectoryHandoff(w, r, http.StatusForbidden) |
| + return |
| + } |
| + if _, err = tx.Exec("DELETE FROM sessions WHERE subject=?", claims.Subject); err != nil || tx.Commit() != nil { |
| + a.failDirectoryHandoff(w, r, http.StatusServiceUnavailable) |
| + return |
| + } |
| + idCookie(w, a.sessions.CookieName(), "", -1) |
| + idCookie(w, "__Host-oficina-signed-out-all", "1", 300) |
| + http.Redirect(w, r, "/signed-out", http.StatusSeeOther) |
| } |
diff --git a/internal/home/team_page.go b/internal/home/team_page.go| index 6d32c17..aa403a5 100644 |
| --- a/internal/home/team_page.go |
| +++ b/internal/home/team_page.go |
| @@ -65,7 +65,7 @@ var teamPaths = map[string]bool{teamPath: true, teamAddPath: true, teamRolePath: |
| // rule; it is restated here so that the two can never drift apart silently |
| // (TestTeamFreshnessIsTheOperatorRule). |
| func teamFresh(s sessions.Session, now time.Time) bool { |
| - return !s.AuthTime.IsZero() && !s.AuthTime.After(now) && now.Sub(s.AuthTime) <= teamFreshness |
| + return s.Method != nativeSessionMethod && !s.AuthTime.IsZero() && !s.AuthTime.After(now) && now.Sub(s.AuthTime) <= teamFreshness |
| } |
| func teamReturn(sqid string) string { |
diff --git a/internal/home/templates/directory_signed_out.html b/internal/home/templates/directory_signed_out.html| index dab7ccf..35cb536 100644 |
| --- a/internal/home/templates/directory_signed_out.html |
| +++ b/internal/home/templates/directory_signed_out.html |
| @@ -6,7 +6,11 @@ |
| <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}} |
| +{{else if .Data.AllDevices}}{{with signedOutDoor}} |
| +<h1>All devices are signed out</h1> |
| +<p estilo-signin-body>Your Oficina ID is signed out in this browser, in every other browser, and in the Oficina apps on every device. Each one asks you to sign in again.</p> |
| +<p><a href="{{.Link.Href}}" rst-btn="primary">{{.Link.Label}}</a></p> |
| +{{end}}{{else}}{{with signedOutDoor}} |
| <h1>{{.Heading}}</h1> |
| <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> |
diff --git a/internal/home/templates/id_signout_all.html b/internal/home/templates/id_signout_all.html| index ebbe279..55e8a6b 100644 |
| --- a/internal/home/templates/id_signout_all.html |
| +++ b/internal/home/templates/id_signout_all.html |
| @@ -1,18 +1,11 @@ |
| {{define "title"}}Sign out all devices · Oficina{{end}} |
| {{define "content"}} |
| -{{if .Data.Done}} |
| -<h1>All devices are signed out</h1> |
| -<p>Every Oficina app on every device is signed out of your Oficina ID. Each one asks you to sign in again the next time it opens.</p> |
| -<p>An app that is offline now finds out when it next connects. Until then it can keep using what it already has open for up to seven days.</p> |
| -<a href="{{.Data.Directory}}/" rst-btn="primary">Done</a> |
| -{{else}} |
| <h1>Sign out all devices</h1> |
| -<p>This signs your Oficina ID out of the Oficina apps on every Mac, iPhone and iPad, including this one's apps. You stay signed in to this browser.</p> |
| -<p>Use it if you have lost a device, or if you signed in somewhere you shouldn't have.</p> |
| +<p>This signs your Oficina ID out everywhere: the Oficina apps on every Mac, iPhone and iPad, and every browser, this one included.</p> |
| +<p>Use it if you have lost a device, or if you signed in somewhere you shouldn't have. An app that is offline finds out when it next connects; until then it can keep what it already has open for up to seven days.</p> |
| <form method="post" action="/devices/sign-out-all" rst-form> |
| <div rst-form-foot> |
| <button type="submit" rst-btn="danger">Sign out all devices</button> |
| </div> |
| </form> |
| {{end}} |
| -{{end}} |