Oficina ID native slice A, Home half: grants, codes, native passkeys, assert, sign-out-all, directory
Per the approved native spec (979dac4) and Paul's rulings of 2026-11-14: - device-bound grants + device-key proofs (identity migration 0004), persistent replay table, per-grant/per-person rate limits, Date/now for clock skew; - email code start/resend/verify with every spec limit, per-(address, device key) and daily caps (429 daily_limit), returning-device exemption by end reason, shared web/native email budget, sealed addresses swept at boot/verify; - native passkey begin/finish against RP id.oficina.works; static /.well-known/apple-app-site-association (webcredentials, five App IDs); - assert via handoff.NativeChallenge/NativeNonce and shared mintPolicy; 401 grant_ended vs proof_rejected; - "Sign out all devices" ends every grant AND every Home browser session (Paul), via a one-shot signed receipt to oficina.works; per-person signed-out-at marks refuse assertions minted before the press, checked atomically with session creation; honest copy (open team-app tabs keep their sessions); - directory: native exchange (always admits; native sessions confined to the teams API and never fresh), /api/native/teams, zero-teams help, sign-out; - .amadan/timeout 15m -> 20m (main alone used ~14 min of the race budget). Reviewed by Fable four times (cdad4ed, 6365328, 5281e03 APPROVE AFTER FIXES; 29be2e7's N1 fix checked by the lander). make test green; hub CI passed at 29be2e7. Follow-ups: connect instances don't read the signed-out-all mark yet (slice C); internal/provisioner race time. Squashed from feat/oficina-id-native-a into main.
37 files changed,
+4,551
−26
.amadan/timeout+1 −1go.mod+1 −1go.sum+2 −0internal/home/app.go+13 −0internal/home/calma.go+17 −15internal/home/chrome.go+1 −0internal/home/directory.go+40 −4internal/home/directory_id/migrations/0001_signed_out_all.sql+11 −0internal/home/directory_native.go+276 −0internal/home/directory_native_test.go+160 −0internal/home/exchange.go+5 −0internal/home/exchange_test.go+1 −1internal/home/handoff_failure.go+7 −0internal/home/id_passkey.go+7 −0internal/home/id_recovery.go+5 −0internal/home/identity/migrations/0004_native.sql+101 −0internal/home/models.go+14 −0internal/home/native.go+540 −0internal/home/native_assert.go+87 −0internal/home/native_code.go+651 −0internal/home/native_code_test.go+537 −0internal/home/native_grant_test.go+355 −0internal/home/native_helpers_test.go+241 −0internal/home/native_logs_test.go+66 −0internal/home/native_passkey.go+308 −0internal/home/native_passkey_test.go+223 −0internal/home/native_review_test.go+348 −0internal/home/native_revoke_test.go+200 −0internal/home/operator_confirm.go+3 −1internal/home/runtime.go+1 −1internal/home/signout_all.go+278 −0internal/home/team_page.go+1 −1internal/home/templates/directory_no_teams.html+7 −0internal/home/templates/directory_signed_out.html+5 −1internal/home/templates/directory_signout_all_failed.html+7 −0internal/home/templates/id_signout_all.html+12 −0internal/home/templates/id_signout_all_hop.html+19 −0
CI passed — run details
landed from feat/oficina-id-native-a
diff --git a/.amadan/timeout b/.amadan/timeout| index 960e1d6..982b6c9 100644 |
| --- a/.amadan/timeout |
| +++ b/.amadan/timeout |
| @@ -1 +1 @@ |
| -15m |
| +20m |
diff --git a/go.mod b/go.mod| index cc02403..a680404 100644 |
| --- a/go.mod |
| +++ b/go.mod |
| @@ -7,7 +7,7 @@ toolchain go1.26.5 |
| require ( |
| amadan.net/oficina/estilo.git v0.0.0-20261025200559-260f98c42e2d |
| amadan.net/oficina/home/dashboard v0.0.0-20261024234842-3774eb68f816 |
| - amadan.net/oficina/home/handoff v0.0.0-20261027235000-69ea999ccbf7 |
| + amadan.net/oficina/home/handoff v0.0.0-20261114110939-e03a01a1881c |
| amadan.net/oficina/home/roster v0.0.0-20261028165624-d942439ac4e4 |
| amadan.net/rastrillo/rastrillo v0.26.1-0.20260908075707-29e4491631bd |
| filippo.io/age v1.3.2 |
diff --git a/go.sum b/go.sum| index e106f06..e9041b2 100644 |
| --- a/go.sum |
| +++ b/go.sum |
| @@ -6,6 +6,8 @@ amadan.net/oficina/home/dashboard v0.0.0-20261024234842-3774eb68f816 h1:AFDuOio0 |
| amadan.net/oficina/home/dashboard v0.0.0-20261024234842-3774eb68f816/go.mod h1:+7xsX+QyVFrKy5gDAGh+FZ5+75z4CibWTL0wl9DWAw0= |
| amadan.net/oficina/home/handoff v0.0.0-20261027235000-69ea999ccbf7 h1:F0wJpR9hBz5CBfCdw80TuBu0Ufioh+tmpODB9Y7ifH0= |
| amadan.net/oficina/home/handoff v0.0.0-20261027235000-69ea999ccbf7/go.mod h1:YISpzFJ+iMgrM0rUL032OSzsAQbP4/nozvXLCCOcn1k= |
| +amadan.net/oficina/home/handoff v0.0.0-20261114110939-e03a01a1881c h1:KxjjyIlEu3hY1G6l26IrI2PRcogOscpTeydRgNzimbA= |
| +amadan.net/oficina/home/handoff v0.0.0-20261114110939-e03a01a1881c/go.mod h1:YISpzFJ+iMgrM0rUL032OSzsAQbP4/nozvXLCCOcn1k= |
| amadan.net/oficina/home/roster v0.0.0-20261028165624-d942439ac4e4 h1:jg3sS7hy8Qaewrv/7CZ4kjIYE62FaIG4KMlfNs918dY= |
| amadan.net/oficina/home/roster v0.0.0-20261028165624-d942439ac4e4/go.mod h1:gqshuXyDtFZUCYbhuZyV3Epc51pUcsLbpqAqiA5UiXg= |
| amadan.net/rastrillo/rastrillo v0.26.1-0.20260908075707-29e4491631bd h1:jlFSt95M1ontOg+VePU+kIJpChtWqDQAbnmlxqCnbgc= |
diff --git a/internal/home/app.go b/internal/home/app.go| index bdb3e3d..609c733 100644 |
| --- a/internal/home/app.go |
| +++ b/internal/home/app.go |
| @@ -43,6 +43,7 @@ type App struct { |
| runtime *Runtime |
| directory *directoryFeatures |
| consumer *handoff.Consumer |
| + handoffStore *handoff.Store // the directory's: native exchange and sign-out-all |
| fresh *handoff.Consumer |
| op *operatorEndpoint |
| origins Origins |
| @@ -159,6 +160,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 |
| } |
| @@ -205,6 +209,9 @@ func (a *App) Router() http.Handler { |
| r.With(a.credentialOnly).Post(signoutPath, a.handleCredentialSignout) |
| r.With(a.credentialOnly).Get(signoutPath, a.handleCredentialSignoutPage) |
| r.With(a.credentialOnly).Get("/signed-out", func(w http.ResponseWriter, r *http.Request) { a.render(w, r, 200, "id_signed_out.html", nil) }) |
| + // Oficina ID for the native apps (native.go): JSON only, outside |
| + // csrf.Protect because each refuses any browser evidence header. |
| + a.mountNative(r) |
| } |
| r.Group(func(r chi.Router) { |
| @@ -264,6 +271,12 @@ func (a *App) Router() http.Handler { |
| // enrolFreshness for the lockout this closes. |
| r.Group(func(r chi.Router) { |
| r.Use(a.sessions.RequireFresh(enrolFreshness)) |
| + // Ending every device's grant changes who can get in, so it |
| + // wants a recent session too (§10). |
| + if a.runtime != nil && a.runtime.role == "credential" { |
| + r.Get(signoutAllPath, a.handleSignoutAllPage) |
| + r.Post(signoutAllPath, a.handleSignoutAll) |
| + } |
| r.Get("/passkey/enrol", a.handlePasskeyEnrol) |
| r.Post("/passkey/register/begin", a.idBegin("register")) |
| r.Post("/passkey/register/finish", a.idFinish("register")) |
diff --git a/internal/home/calma.go b/internal/home/calma.go| index 647b04a..36f2e48 100644 |
| --- a/internal/home/calma.go |
| +++ b/internal/home/calma.go |
| @@ -73,18 +73,19 @@ const suiteName = "Oficina" |
| // error pages are plain pages under the bar. |
| // Not assertion.html or docs_continue.html: they are hops (hopPages). |
| var doorPages = map[string]bool{ |
| - "signin.html": true, |
| - "check_your_mail.html": true, |
| - "signin_confirm.html": true, |
| - "signin_failed.html": true, |
| - "passkey_confirm.html": true, |
| - "passkey_enrol.html": true, |
| - "recovery_codes.html": true, |
| - "handoff_failed.html": true, |
| - "signout_confirm.html": true, |
| - "directory_signed_out.html": true, |
| - "operator_confirm_id.html": true, |
| - "resolve.html": true, |
| + "signin.html": true, |
| + "check_your_mail.html": true, |
| + "signin_confirm.html": true, |
| + "signin_failed.html": true, |
| + "passkey_confirm.html": true, |
| + "passkey_enrol.html": true, |
| + "recovery_codes.html": true, |
| + "handoff_failed.html": true, |
| + "signout_confirm.html": true, |
| + "directory_signed_out.html": true, |
| + "operator_confirm_id.html": true, |
| + "resolve.html": true, |
| + "directory_signout_all_failed.html": true, |
| } |
| // hopPages move on by themselves (an auto-submit, a 0 s refresh). They |
| @@ -92,9 +93,10 @@ var doorPages = map[string]bool{ |
| // door and the directory is not a blank page (r3 C2), but load no script, |
| // no sky layer and no card: the card shows only if the hop stalls. |
| var hopPages = map[string]bool{ |
| - "assertion.html": true, |
| - "docs_continue.html": true, |
| - "resolve_handoff.html": true, |
| + "assertion.html": true, |
| + "docs_continue.html": true, |
| + "resolve_handoff.html": true, |
| + "id_signout_all_hop.html": true, |
| } |
| // mountCalma serves the Calma pieces Home's pages link: the sky's layers |
diff --git a/internal/home/chrome.go b/internal/home/chrome.go| index bfbdba3..08de0fa 100644 |
| --- a/internal/home/chrome.go |
| +++ b/internal/home/chrome.go |
| @@ -95,6 +95,7 @@ func (a *App) account(r *http.Request, status int) *chrome.Account { |
| items = append(items, |
| menu.Item{Href: a.origins.Credential + "/passkey/enrol", Label: "Passkeys"}, |
| menu.Item{Href: a.origins.Credential + "/passkey/codes", Label: "Recovery codes"}, |
| + menu.Item{Href: a.origins.Credential + signoutAllPath, Label: "Sign out all devices"}, |
| ) |
| return &chrome.Account{ |
| TriggerLabel: "Account", |
diff --git a/internal/home/directory.go b/internal/home/directory.go| index 8d68b98..5626d0b 100644 |
| --- a/internal/home/directory.go |
| +++ b/internal/home/directory.go |
| @@ -44,10 +44,27 @@ func newDirectory(cfg Runtime, d *db.DB, logger *slog.Logger) (*App, error) { |
| if err = store.Sweep(context.Background(), time.Now()); err != nil { |
| return nil, err |
| } |
| - a := &App{runtime: &cfg, origins: cfg.origins, credentialHost: strings.TrimPrefix(cfg.origins.Credential, "https://"), directoryHost: strings.TrimPrefix(cfg.origins.Directory, "https://"), secrets: cfg.secrets, db: d, logger: logger, renderer: renderer, sessions: sess} |
| + a := &App{handoffStore: store, runtime: &cfg, origins: cfg.origins, credentialHost: strings.TrimPrefix(cfg.origins.Credential, "https://"), directoryHost: strings.TrimPrefix(cfg.origins.Directory, "https://"), secrets: cfg.secrets, db: d, logger: logger, renderer: renderer, sessions: sess} |
| // One completion for both consumers: the directory's one session boundary. |
| complete := func(w http.ResponseWriter, r *http.Request, c assertion.Claims) error { |
| - return a.sessions.SignIn(w, r, sessions.Session{Subject: c.Subject, Method: "assertion", AuthTime: time.Unix(c.AuthTime, 0)}) |
| + // An assertion issued before "Sign out all devices" buys nothing. |
| + if err := a.directorySigninAllowed(r.Context(), c); err != nil { |
| + markSignedOutAllFinish(w) |
| + return err |
| + } |
| + afterMarkCheck() |
| + if err := a.sessions.SignIn(w, r, sessions.Session{Subject: c.Subject, Method: "assertion", AuthTime: time.Unix(c.AuthTime, 0)}); err != nil { |
| + return err |
| + } |
| + // SignIn writes on its own, so a receipt may have committed between |
| + // the check above and it. Check again now the session exists; if the |
| + // press came in between, the new session goes too. |
| + if err := a.directorySigninAllowed(r.Context(), c); err != nil { |
| + a.undoSignIn(w, r) |
| + markSignedOutAllFinish(w) |
| + return err |
| + } |
| + return nil |
| } |
| a.consumer, err = handoff.NewConsumer(handoff.ConsumerConfig{Store: store, ConsumerID: "directory", CurrentSubject: func(r *http.Request) string { |
| s, ok := sessions.Current(r) |
| @@ -94,6 +111,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). |
| @@ -107,6 +127,13 @@ func (a *App) directoryRouter() http.Handler { |
| // The credential origin's member-resolution receipt arrives here as a |
| // cross-origin POST, with its own exact Origin check (team_page.go). |
| r.Post(teamResolvedPath, a.handleTeamResolved) |
| + // The native exchange and sign-out (directory_native.go) refuse every |
| + // 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 { |
| @@ -115,7 +142,14 @@ func (a *App) directoryRouter() http.Handler { |
| } |
| r.Get(handoff.StartPath, a.consumer.Start) |
| r.Get(a.fresh.StartPath(), a.fresh.Start) |
| - r.Get(handoff.FinishPath, a.consumer.Finish) |
| + r.Get(handoff.FinishPath, func(w http.ResponseWriter, r *http.Request) { |
| + // The writer lets Complete tell Fail that the refusal was "Sign |
| + // out all devices", so the person sees that rather than a |
| + // generic failure. |
| + a.consumer.Finish(&finishWriter{ResponseWriter: w}, r) |
| + }) |
| + r.Get(nativeTeamsPath, a.directoryNativeTeams) |
| + r.Get(noTeamsHelpPath, a.handleNoTeamsHelp) |
| r.Get("/signin", func(w http.ResponseWriter, r *http.Request) { |
| http.Redirect(w, r, handoff.StartPath, http.StatusSeeOther) |
| }) |
| @@ -171,8 +205,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_id/migrations/0001_signed_out_all.sql b/internal/home/directory_id/migrations/0001_signed_out_all.sql| new file mode 100644 |
| index 0000000..a933160 |
| --- /dev/null |
| +++ b/internal/home/directory_id/migrations/0001_signed_out_all.sql |
| @@ -0,0 +1,11 @@ |
| +-- "Sign out all devices" (Oficina ID native spec §10, Paul's ruling of |
| +-- 2026-11-14). The directory records when a person last pressed it, as the |
| +-- receipt's iat, and refuses any assertion for that person issued at or |
| +-- before it: one minted in the 120 seconds before the press could otherwise |
| +-- still buy a fresh directory session. A mark matters only while such an |
| +-- assertion could be live, so rows older than five minutes are pruned. |
| +CREATE TABLE home_directory_signed_out_all ( |
| + person_ref TEXT PRIMARY KEY, |
| + at INTEGER NOT NULL |
| +); |
| +CREATE INDEX home_directory_signed_out_all_at ON home_directory_signed_out_all(at); |
diff --git a/internal/home/directory_native.go b/internal/home/directory_native.go| new file mode 100644 |
| index 0000000..efa8fbd |
| --- /dev/null |
| +++ b/internal/home/directory_native.go |
| @@ -0,0 +1,276 @@ |
| +package home |
| + |
| +import ( |
| + "crypto/subtle" |
| + "database/sql" |
| + "errors" |
| + "io" |
| + "mime" |
| + "net/http" |
| + "time" |
| + |
| + "amadan.net/oficina/home/handoff" |
| + "amadan.net/oficina/home/internal/home/directorydata" |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| +) |
| + |
| +// The directory's half of native sign-in (§9). The directory is a consumer |
| +// like any team instance: the app asks the credential origin for an |
| +// assertion with aud = the directory, redeems it here for a directory |
| +// session, and reads its teams with that session. Nothing here renders, sets |
| +// a cookie, or answers a browser. |
| +const ( |
| + nativeExchangePath = "/native/oficina-id" |
| + nativeTeamsPath = "/api/native/teams" |
| + nativeDirectorySignout = "/native/signout" |
| + noTeamsHelpPath = "/help/teams" |
| + |
| + // nativeSessionMethod marks a session minted for a native app. It lives |
| + // seven days, absolute (§7); the app re-mints after a day and on a 401. |
| + nativeSessionMethod = "home-assertion-native" |
| + nativeSessionLife = 7 * day |
| +) |
| + |
| +// nativeTeamApps are the native apps; the list is filtered to them (§9). |
| +var nativeTeamApps = map[string]bool{"calls": true, "docs": true, "sheets": true, "calendar": true, "memoria": true} |
| + |
| +// directoryNativeExchange is POST /native/oficina-id {assertion, verifier, |
| +// target?, choice?}. It verifies the assertion against the pinned keys with |
| +// the exact issuer and the directory as audience, recomputes the native |
| +// nonce from the verifier, reserves the jti, and mints a seven-day directory |
| +// session whose token goes back in the body, never in a cookie. |
| +// |
| +// The request and every answer are connect.Bridge.NativeExchange's, so one |
| +// client speaks to the directory and to every team instance alike: JSON |
| +// {"state": …}, ok / invalid / failed / unavailable. choice is accepted and |
| +// ignored and target is echoed: the directory links nobody and allocates |
| +// nothing, so a person ref is the whole answer, and the unknown and choose |
| +// states never arise here. |
| +func (a *App) directoryNativeExchange(w http.ResponseWriter, r *http.Request) { |
| + answer := func(status int, state string) { nativeReply(w, status, map[string]string{"state": state}) } |
| + if _, ok := r.Header["Origin"]; ok { |
| + answer(http.StatusBadRequest, "invalid") |
| + return |
| + } |
| + if _, ok := r.Header["Sec-Fetch-Site"]; ok { |
| + answer(http.StatusBadRequest, "invalid") |
| + return |
| + } |
| + media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) |
| + if err != nil || media != "application/json" || r.URL.RawQuery != "" { |
| + answer(http.StatusBadRequest, "invalid") |
| + return |
| + } |
| + body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 12*1024)) |
| + if err != nil { |
| + answer(http.StatusBadRequest, "invalid") |
| + return |
| + } |
| + var in struct { |
| + Assertion string `json:"assertion"` |
| + Verifier string `json:"verifier"` |
| + Target string `json:"target,omitzero"` |
| + Choice string `json:"choice,omitzero"` |
| + } |
| + if !decodeNative(body, &in) || in.Assertion == "" || (in.Choice != "" && in.Choice != "new") || (in.Target != "" && !handoff.SafePath(in.Target)) { |
| + answer(http.StatusBadRequest, "invalid") |
| + return |
| + } |
| + challenge, ok := handoff.NativeChallenge(in.Verifier) |
| + if !ok { |
| + answer(http.StatusBadRequest, "invalid") |
| + return |
| + } |
| + nonce, _ := handoff.NativeNonce(challenge) |
| + now := time.Now() |
| + claims, err := a.handoffStore.Verify(in.Assertion, now) |
| + if err != nil || subtle.ConstantTimeCompare([]byte(claims.Nonce), []byte(nonce)) != 1 || !ValidPersonRef(claims.Subject) { |
| + answer(http.StatusUnauthorized, "failed") |
| + return |
| + } |
| + if a.directorySigninAllowed(r.Context(), claims) != nil { |
| + answer(http.StatusUnauthorized, "failed") |
| + return |
| + } |
| + afterMarkCheck() |
| + // The jti is reserved in handoff's own committed transaction, as |
| + // connect's NativeExchange does; a reserved jti that then mints nothing |
| + // costs the app one fresh assertion (spec §7, accepted non-atomicity). |
| + if _, err = a.handoffStore.Reserve(r.Context(), in.Assertion, now); err != nil { |
| + if errors.Is(err, handoff.ErrRefused) { |
| + answer(http.StatusUnauthorized, "failed") |
| + } else { |
| + answer(http.StatusServiceUnavailable, "unavailable") |
| + } |
| + return |
| + } |
| + tx, err := a.db.Writer().BeginTx(r.Context(), nil) |
| + if err != nil { |
| + answer(http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + defer tx.Rollback() |
| + // The mark again, inside the transaction that inserts the session: the |
| + // directory's writer is one connection, so a receipt cannot commit |
| + // between this check and the insert. The check above only saves a jti. |
| + if before, err := signedOutBefore(r.Context(), tx, "home_directory_signed_out_all", claims.Subject, claims.IssuedAt); err != nil || before { |
| + if err != nil { |
| + answer(http.StatusServiceUnavailable, "unavailable") |
| + } else { |
| + answer(http.StatusUnauthorized, "failed") |
| + } |
| + return |
| + } |
| + token, hash, err := sessions.NewToken() |
| + if err != nil { |
| + answer(http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + expires := now.Unix() + nativeSessionLife |
| + if _, err = tx.Exec("INSERT INTO sessions(token_hash,subject,method,auth_time,created_at,expires_at) VALUES(?,?,?,?,?,?)", |
| + hash, claims.Subject, nativeSessionMethod, time.Unix(claims.AuthTime, 0).UTC().Format(time.RFC3339), now.UTC().Format(time.RFC3339), time.Unix(expires, 0).UTC().Format(time.RFC3339)); err != nil { |
| + answer(http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + if tx.Commit() != nil { |
| + answer(http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + reply := map[string]any{"state": "ok", "name": a.sessions.CookieName(), "value": token, "expires_at": expires} |
| + if in.Target != "" { |
| + reply["target"] = in.Target |
| + } |
| + nativeReply(w, http.StatusOK, reply) |
| +} |
| + |
| +type nativeTeamApp struct { |
| + App string `json:"app"` |
| + Origin string `json:"origin"` |
| + ConsumerID string `json:"consumer_id"` |
| +} |
| +type nativeTeam struct { |
| + SQID string `json:"sqid"` |
| + Label string `json:"label"` |
| + Name string `json:"name"` |
| + Role string `json:"role"` |
| + Apps []nativeTeamApp `json:"apps"` |
| +} |
| + |
| +// directoryNativeTeams is GET /api/native/teams: the person's teams with |
| +// live instances of the five native apps, from Store.AgentChoices. Zero |
| +// teams is an empty list, never an error; the app then shows its help and |
| +// may link noTeamsHelpPath. |
| +func (a *App) directoryNativeTeams(w http.ResponseWriter, r *http.Request) { |
| + if _, ok := r.Header["Origin"]; ok { |
| + nativeFail(w, http.StatusForbidden, "browser") |
| + return |
| + } |
| + if _, ok := r.Header["Sec-Fetch-Site"]; ok { |
| + nativeFail(w, http.StatusForbidden, "browser") |
| + return |
| + } |
| + s, ok := sessions.Current(r) |
| + if !ok || s.Method != nativeSessionMethod { |
| + nativeUnauthorized(w, "session") |
| + return |
| + } |
| + choices, err := a.directory.store.AgentChoices(r.Context(), s.Subject) |
| + if errors.Is(err, directorydata.ErrInvalid) { |
| + nativeUnauthorized(w, "session") |
| + return |
| + } |
| + if err != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + teams := []nativeTeam{} |
| + for _, c := range choices { |
| + if !nativeTeamApps[c.App] { |
| + continue |
| + } |
| + if len(teams) == 0 || teams[len(teams)-1].SQID != c.SQID { |
| + teams = append(teams, nativeTeam{SQID: c.SQID, Label: c.Label, Name: c.Name, Role: c.Role, Apps: []nativeTeamApp{}}) |
| + } |
| + last := &teams[len(teams)-1] |
| + last.Apps = append(last.Apps, nativeTeamApp{App: c.App, Origin: c.Origin, ConsumerID: c.ConsumerID}) |
| + } |
| + nativeReply(w, http.StatusOK, teams) |
| +} |
| + |
| +// directoryNativeSignout is POST /native/signout {}: the app's directory |
| +// session ends (§10 step 3). Outside csrf.Protect, because a native call |
| +// carries no origin evidence; it refuses any that a browser would send, and |
| +// it can end only a native session. |
| +func (a *App) directoryNativeSignout(w http.ResponseWriter, r *http.Request) { |
| + body, ok := nativeIntake(w, r) |
| + if !ok { |
| + return |
| + } |
| + var in struct{} |
| + if !decodeNative(body, &in) { |
| + nativeFail(w, http.StatusBadRequest, "request") |
| + return |
| + } |
| + if token := cookieValue(r, a.sessions.CookieName()); token != "" { |
| + if _, err := a.db.Writer().ExecContext(r.Context(), "DELETE FROM sessions WHERE token_hash=? AND method=?", sessions.HashToken(token), nativeSessionMethod); err != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + } |
| + nativeReply(w, http.StatusOK, map[string]string{}) |
| +} |
| + |
| +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() |
| + var tokens []string |
| + for _, c := range r.Cookies() { |
| + if c.Name == name { |
| + tokens = append(tokens, c.Value) |
| + } |
| + } |
| + if len(tokens) == 0 || r.URL.Path == nativeTeamsPath || r.URL.Path == nativeDirectorySignout { |
| + next.ServeHTTP(w, r) |
| + return |
| + } |
| + // Every cookie of the session name is looked up, not just a lone |
| + // one: the session middleware takes the first of several, so a |
| + // native token hidden among duplicates must not get through. If any |
| + // is native, all of that name go; otherwise the request is untouched |
| + // and the existing ambiguous-session refusals still see it. |
| + native := len(tokens) > 8 // more than that is not a browser; strip without looking |
| + for _, token := range tokens[:min(len(tokens), 8)] { |
| + 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 |
| + } |
| + native = native || method == nativeSessionMethod |
| + } |
| + if !native { |
| + 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/directory_native_test.go b/internal/home/directory_native_test.go| new file mode 100644 |
| index 0000000..f66600f |
| --- /dev/null |
| +++ b/internal/home/directory_native_test.go |
| @@ -0,0 +1,160 @@ |
| +package home |
| + |
| +import ( |
| + "encoding/json" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// directoryCall is a native app's request to the directory. |
| +func directoryCall(t *testing.T, f chooserFixture, method, path, body string, cookie *http.Cookie, headers map[string]string) *httptest.ResponseRecorder { |
| + t.Helper() |
| + r := httptest.NewRequest(method, directoryOrigin+path, strings.NewReader(body)) |
| + if body != "" { |
| + r.Header.Set("Content-Type", "application/json") |
| + } |
| + if cookie != nil { |
| + r.AddCookie(cookie) |
| + } |
| + for k, v := range headers { |
| + r.Header.Set(k, v) |
| + } |
| + w := httptest.NewRecorder() |
| + f.p.directory.Router().ServeHTTP(w, r) |
| + return w |
| +} |
| + |
| +func exchangeBody(assertion, verifier string, extra ...string) string { |
| + m := map[string]string{"assertion": assertion, "verifier": verifier} |
| + for i := 0; i+1 < len(extra); i += 2 { |
| + m[extra[i]] = extra[i+1] |
| + } |
| + b, _ := json.Marshal(m) |
| + return string(b) |
| +} |
| + |
| +// §9: assert for the directory, exchange it with the verifier, read the |
| +// teams. Zero teams is an empty list. |
| +func TestNativeDirectoryTeams(t *testing.T) { |
| + t.Parallel() |
| + f := newMountedChooser(t) |
| + cred := f.p.credential |
| + d := newDevice(t) |
| + grant, _ := d.signInByCode(t, cred, "teams@example.invalid") |
| + var person string |
| + cred.db.Writer().QueryRow("SELECT person_ref FROM home_id_grants").Scan(&person) |
| + |
| + mint := func(seed byte) (string, string) { |
| + verifier, challenge := verifierFor(seed) |
| + w := d.assert(t, cred, grant, directoryOrigin, challenge) |
| + if w.Code != 200 { |
| + t.Fatal("assert", w.Code, w.Body.String()) |
| + } |
| + return decodeReply(t, w)["assertion"].(string), verifier |
| + } |
| + token, verifier := mint(10) |
| + // A wrong verifier, a browser and a non-JSON body are refused. |
| + wrongVerifier, _ := verifierFor(11) |
| + if w := directoryCall(t, f, "POST", nativeExchangePath, exchangeBody(token, wrongVerifier), nil, nil); w.Code != 401 || decodeReply(t, w)["state"] != "failed" { |
| + t.Fatal("wrong verifier", w.Code) |
| + } |
| + if w := directoryCall(t, f, "POST", nativeExchangePath, exchangeBody(token, verifier), nil, map[string]string{"Origin": directoryOrigin}); w.Code != 400 || decodeReply(t, w)["state"] != "invalid" { |
| + t.Fatal("a browser exchanged", w.Code) |
| + } |
| + w := directoryCall(t, f, "POST", nativeExchangePath, exchangeBody(token, verifier), nil, nil) |
| + if w.Code != 200 || len(w.Result().Cookies()) != 0 { |
| + t.Fatal("exchange", w.Code, w.Body.String(), w.Header()) |
| + } |
| + out := decodeReply(t, w) |
| + if out["state"] != "ok" { |
| + t.Fatal("state", out) |
| + } |
| + cookie := &http.Cookie{Name: out["name"].(string), Value: out["value"].(string)} |
| + if exp := int64(out["expires_at"].(float64)); exp > time.Now().Unix()+7*day || exp < time.Now().Unix()+7*day-60 { |
| + t.Fatal("native directory session is not seven days", exp) |
| + } |
| + // target is echoed, choice ignored, as connect's exchange does. |
| + t2, v2 := mint(12) |
| + w2 := directoryCall(t, f, "POST", nativeExchangePath, exchangeBody(t2, v2, "target", "/teams", "choice", "new"), nil, nil) |
| + if w2.Code != 200 || decodeReply(t, w2)["target"] != "/teams" { |
| + t.Fatal("target", w2.Code, w2.Body.String()) |
| + } |
| + if w := directoryCall(t, f, "POST", nativeExchangePath, exchangeBody(t2, v2, "choice", "old"), nil, nil); w.Code != 400 { |
| + t.Fatal("unknown choice", w.Code) |
| + } |
| + // The same assertion twice is a replay. |
| + if w := directoryCall(t, f, "POST", nativeExchangePath, exchangeBody(token, verifier), nil, nil); w.Code != 401 { |
| + t.Fatal("replayed exchange", w.Code) |
| + } |
| + |
| + w = directoryCall(t, f, "GET", nativeTeamsPath, "", cookie, nil) |
| + if w.Code != 200 || strings.TrimSpace(w.Body.String()) != "[]" || w.Header().Get("Cache-Control") != "no-store" { |
| + t.Fatal("zero teams", w.Code, w.Body.String()) |
| + } |
| + f.team(t, "AAA111", "blue", "Blue team", person) |
| + f.team(t, "BBB222", "green", "Not yours", chooserOther) |
| + w = directoryCall(t, f, "GET", nativeTeamsPath, "", cookie, nil) |
| + var teams []nativeTeam |
| + if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &teams) != nil || len(teams) != 1 { |
| + t.Fatal("teams", w.Code, w.Body.String()) |
| + } |
| + tm := teams[0] |
| + if tm.SQID != "AAA111" || tm.Label != "blue" || tm.Name != "Blue team" || tm.Role != "member" || len(tm.Apps) != 1 || tm.Apps[0] != (nativeTeamApp{"docs", "https://blue.docs.oficina.works", "blue-docs"}) { |
| + t.Fatalf("team %+v", tm) |
| + } |
| + // A browser cannot read it, nor a browser session. |
| + if w := directoryCall(t, f, "GET", nativeTeamsPath, "", cookie, map[string]string{"Sec-Fetch-Site": "same-origin"}); w.Code != 403 { |
| + t.Fatal("a browser read teams", w.Code) |
| + } |
| + if w := directoryCall(t, f, "GET", nativeTeamsPath, "", f.session(t, person), nil); w.Code != 401 { |
| + t.Fatal("a browser session read the native list", w.Code) |
| + } |
| + if w := directoryCall(t, f, "GET", nativeTeamsPath, "", nil, nil); w.Code != 401 { |
| + t.Fatal("anonymous teams", w.Code) |
| + } |
| + // Sign-out ends the native directory session, and only that. |
| + if w := directoryCall(t, f, "POST", nativeDirectorySignout, "{}", cookie, nil); w.Code != 200 { |
| + t.Fatal("directory signout", w.Code) |
| + } |
| + if w := directoryCall(t, f, "GET", nativeTeamsPath, "", cookie, nil); w.Code != 401 { |
| + t.Fatal("a signed-out session read teams", w.Code) |
| + } |
| +} |
| + |
| +// §12: the exchange accepts only native nonces. An assertion minted through |
| +// /authorize, with a browser's nonce, does not redeem here. |
| +func TestNativeDirectoryRefusesBrowserNonce(t *testing.T) { |
| + t.Parallel() |
| + f := newMountedChooser(t) |
| + session := signInFully(t, f.p.credential, "web@example.invalid") |
| + _, intent := f.p.start(t) |
| + token, _ := f.p.mint(t, intent, session) |
| + for seed := byte(0); seed < 4; seed++ { |
| + verifier, _ := verifierFor(seed) |
| + if w := directoryCall(t, f, "POST", nativeExchangePath, exchangeBody(token, verifier), nil, nil); w.Code == 200 { |
| + t.Fatal("a browser assertion redeemed natively") |
| + } |
| + } |
| + // An assertion for another audience fails too. |
| + d := newDevice(t) |
| + grant, _ := d.signInByCode(t, f.p.credential, "aud@example.invalid") |
| + verifier, challenge := verifierFor(20) |
| + w := d.assert(t, f.p.credential, grant, "https://blue.docs.oficina.works", challenge) |
| + if w := directoryCall(t, f, "POST", nativeExchangePath, exchangeBody(decodeReply(t, w)["assertion"].(string), verifier), nil, nil); w.Code != 401 { |
| + t.Fatal("swapped audience redeemed", w.Code) |
| + } |
| +} |
| + |
| +// The zero-teams help (§9, Paul's ruling H): help text only while Alta is |
| +// blocked. |
| +func TestNativeDirectoryNoTeamsHelp(t *testing.T) { |
| + t.Parallel() |
| + f := newMountedChooser(t) |
| + w := directoryCall(t, f, "GET", noTeamsHelpPath, "", nil, nil) |
| + if w.Code != 200 || !strings.Contains(w.Body.String(), "not on a team yet") || strings.Contains(w.Body.String(), "Create a team") { |
| + t.Fatal("help", w.Code) |
| + } |
| +} |
diff --git a/internal/home/exchange.go b/internal/home/exchange.go| index c2c9a39..e9023bd 100644 |
| --- a/internal/home/exchange.go |
| +++ b/internal/home/exchange.go |
| @@ -116,6 +116,11 @@ func (a *App) handleAssertion(w http.ResponseWriter, r *http.Request) { |
| http.Redirect(w, r, "/signin?return_to=%2Fauthorize%2Fresume", http.StatusSeeOther) |
| return |
| } |
| + // The one mint rule, shared with the native assert (native_assert.go). |
| + if mintPolicy(intent.Consumer, session.Method) != nil { |
| + a.failAssertion(w, r, assertionConsumer) |
| + return |
| + } |
| if r.Method == http.MethodGet { |
| if tx.Commit() != nil { |
| a.failAssertion(w, r, assertionSession) |
diff --git a/internal/home/exchange_test.go b/internal/home/exchange_test.go| index fe1baf0..9dbbadd 100644 |
| --- a/internal/home/exchange_test.go |
| +++ b/internal/home/exchange_test.go |
| @@ -50,7 +50,7 @@ func newExchangePair(t *testing.T) exchangePair { |
| t.Fatal(err) |
| } |
| t.Cleanup(func() { d.Close() }) |
| - if _, err = migrate.Apply(context.Background(), d, (Runtime{role: "directory"}).Schema()); err != nil { |
| + if _, err = migrate.Apply(context.Background(), d, migrate.Merge((Runtime{role: "directory"}).Schema(), directoryIDSchema)); err != nil { |
| t.Fatal(err) |
| } |
| dek := make([]byte, 32) |
diff --git a/internal/home/handoff_failure.go b/internal/home/handoff_failure.go| index cb12d38..85a4fc6 100644 |
| --- a/internal/home/handoff_failure.go |
| +++ b/internal/home/handoff_failure.go |
| @@ -54,6 +54,13 @@ func (a *App) failAssertion(w http.ResponseWriter, r *http.Request, code handoff |
| } |
| func (a *App) failDirectoryHandoff(w http.ResponseWriter, r *http.Request, status int) { |
| + if signedOutAllFinish(w) { |
| + // The assertion predates "Sign out all devices": say that, not |
| + // "something went wrong". |
| + w.Header().Set("Cache-Control", "no-store") |
| + a.render(w, r, http.StatusForbidden, "directory_signed_out.html", map[string]any{"AllDevices": true, "Action": a.origins.Credential + signoutPath}) |
| + return |
| + } |
| stage := "directory_unknown" |
| switch r.URL.Path { |
| case handoff.StartPath: |
diff --git a/internal/home/id_passkey.go b/internal/home/id_passkey.go| index 9c3c9f3..234fede 100644 |
| --- a/internal/home/id_passkey.go |
| +++ b/internal/home/id_passkey.go |
| @@ -328,6 +328,13 @@ func (a *App) idFinish(purpose string) http.HandlerFunc { |
| idRefuse(w) |
| return |
| } |
| + // A first passkey ends every grant that has none (§3). A web |
| + // enrolment has no enrolling grant, so every code-only device |
| + // signs in again, now with the passkey. |
| + if count == 0 && endPasskeylessGrants(tx, subject, "", now) != nil { |
| + idRefuse(w) |
| + return |
| + } |
| id := hex.EncodeToString(cred.ID) |
| if _, e = tx.Exec("INSERT INTO passkey_credentials(id,subject,public_key,sign_count,created_at) VALUES(?,?,?,?,?)", id, subject, cred.PublicKey, cred.SignCount, time.Unix(now, 0).UTC().Format(time.RFC3339)); e != nil { |
| idRefuse(w) |
diff --git a/internal/home/id_recovery.go b/internal/home/id_recovery.go| index 1448e40..8327b40 100644 |
| --- a/internal/home/id_recovery.go |
| +++ b/internal/home/id_recovery.go |
| @@ -331,6 +331,11 @@ func (a *App) replaceCredential(tx *sql.Tx, r *http.Request, subject string, cre |
| return errIDProof |
| } |
| } |
| + // Replacement by recovery code is full account control, and it is also |
| + // how a lost device is cut off: every native grant ends (§3). |
| + if err := endGrants(tx, subject, "replacement", now); err != nil { |
| + return err |
| + } |
| id := hex.EncodeToString(cred.ID) |
| if _, err := tx.Exec("INSERT INTO passkey_credentials(id,subject,public_key,sign_count,created_at) VALUES(?,?,?,?,?)", id, subject, cred.PublicKey, cred.SignCount, time.Unix(now, 0).UTC().Format(time.RFC3339)); err != nil { |
| return errIDProof |
diff --git a/internal/home/identity/migrations/0004_native.sql b/internal/home/identity/migrations/0004_native.sql| new file mode 100644 |
| index 0000000..b6b266e |
| --- /dev/null |
| +++ b/internal/home/identity/migrations/0004_native.sql |
| @@ -0,0 +1,101 @@ |
| +-- Oficina ID, the native slice (docs/superpowers/specs/2026-11-14-oficina-id-native.md). |
| +-- |
| +-- A grant is a device's long-lived Oficina ID credential (§3). Only the |
| +-- SHA-256 of its token is stored. identity_id is an HMAC of the person ref |
| +-- under a Home-only key, so a device can tell identities apart without |
| +-- holding the ref. Ended rows keep device_key for 365 days so that §4 can |
| +-- recognise a returning device; end_reason says how it ended. |
| +CREATE TABLE home_id_grants ( |
| + grant_hash TEXT PRIMARY KEY, |
| + person_ref TEXT NOT NULL, |
| + identity_id TEXT NOT NULL, |
| + device_key TEXT NOT NULL, |
| + platform TEXT NOT NULL, |
| + method TEXT NOT NULL, |
| + auth_time INTEGER NOT NULL, |
| + created_at INTEGER NOT NULL, |
| + last_used_day TEXT NOT NULL, |
| + expires_at INTEGER NOT NULL, |
| + ended_at INTEGER, |
| + end_reason TEXT CHECK (end_reason IN ('expiry','lru','enrolment','signout','all_devices','revoke','replacement')) |
| +); |
| +CREATE INDEX home_id_grants_person ON home_id_grants(person_ref, ended_at); |
| +CREATE INDEX home_id_grants_device ON home_id_grants(device_key, person_ref); |
| +CREATE INDEX home_id_grants_ended ON home_id_grants(ended_at); |
| + |
| +-- The proof replay table (§3): one row per accepted jti, written only after |
| +-- the grant and the signature verify, kept 60 seconds. It is also the |
| +-- per-grant rate limit's counter. |
| +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 |
| +-- row is deleted at verify or expiry, under secure_delete. |
| +-- blind_index is a Home-keyed HMAC used only to keep one live code per (address, device key); |
| +-- ip_bucket is blinded the same way. code_mac is an HMAC of the code, never |
| +-- the code. |
| +CREATE TABLE home_id_native_starts ( |
| + start_hash TEXT PRIMARY KEY, |
| + sealed_address BLOB NOT NULL, |
| + blind_index TEXT NOT NULL, |
| + device_key TEXT NOT NULL, |
| + platform TEXT NOT NULL, |
| + ip_bucket TEXT NOT NULL, |
| + code_mac TEXT NOT NULL, |
| + sends INTEGER NOT NULL, |
| + last_send INTEGER NOT NULL, |
| + attempts INTEGER NOT NULL, |
| + expires_at INTEGER NOT NULL, |
| + UNIQUE (blind_index, device_key) |
| +); |
| +CREATE INDEX home_id_native_starts_ip ON home_id_native_starts(ip_bucket, expires_at); |
| +CREATE INDEX home_id_native_starts_expiry ON home_id_native_starts(expires_at); |
| + |
| +-- A code verified for an account that has a passkey (§4): the person must |
| +-- still assert one. Valid five minutes and bound to the start and its key. |
| +CREATE TABLE home_id_native_pending ( |
| + pending_hash TEXT PRIMARY KEY, |
| + person_ref TEXT NOT NULL, |
| + start_hash TEXT NOT NULL, |
| + device_key TEXT NOT NULL, |
| + platform TEXT NOT NULL, |
| + method TEXT NOT NULL, |
| + expires_at INTEGER NOT NULL |
| +); |
| +CREATE INDEX home_id_native_pending_expiry ON home_id_native_pending(expires_at); |
| + |
| +-- Persistent fixed-window counters for §4's limits. Keys are blinded; none |
| +-- shares a key with home_id_attempts, which recovery uses. |
| +CREATE TABLE home_id_native_buckets ( |
| + bucket TEXT PRIMARY KEY, |
| + count INTEGER NOT NULL, |
| + expires_at INTEGER NOT NULL |
| +); |
| +CREATE INDEX home_id_native_buckets_expiry ON home_id_native_buckets(expires_at); |
| + |
| +-- Native passkey challenges count within home_id_ceremonies; this records |
| +-- the device key and platform a native challenge is bound to (§5), keyed by |
| +-- the same challenge and deleted with it. |
| +CREATE TABLE home_id_native_ceremonies ( |
| + challenge TEXT PRIMARY KEY, |
| + device_key TEXT NOT NULL, |
| + platform TEXT NOT NULL, |
| + pending TEXT NOT NULL, |
| + expires_at INTEGER NOT NULL |
| +); |
| + |
| +-- The credential origin's copy of the "Sign out all devices" mark (§10): the |
| +-- press time, per person. No grant created at or before it authenticates, |
| +-- and rows older than five minutes are pruned. |
| +CREATE TABLE home_id_signed_out_all ( |
| + person_ref TEXT PRIMARY KEY, |
| + at INTEGER NOT NULL |
| +); |
| +CREATE INDEX home_id_signed_out_all_at ON home_id_signed_out_all(at); |
diff --git a/internal/home/models.go b/internal/home/models.go| index 23fa74d..4bf9f7b 100644 |
| --- a/internal/home/models.go |
| +++ b/internal/home/models.go |
| @@ -51,3 +51,17 @@ var identitySchema = func() *migrate.Set { |
| } |
| return migrate.MustFromFS(sub, "home_id") |
| }() |
| + |
| +// directoryIDSchema is the directory's Oficina ID additions: today only the |
| +// "Sign out all devices" mark. Applied by the directory's ServingSchema, so |
| +// the frozen role schema is unchanged. |
| +// |
| +//go:embed directory_id/migrations/*.sql |
| +var directoryIDFS embed.FS |
| +var directoryIDSchema = func() *migrate.Set { |
| + sub, err := fs.Sub(directoryIDFS, "directory_id") |
| + if err != nil { |
| + panic(err) |
| + } |
| + return migrate.MustFromFS(sub, "home_directory_id") |
| +}() |
diff --git a/internal/home/native.go b/internal/home/native.go| new file mode 100644 |
| index 0000000..9f6ae9a |
| --- /dev/null |
| +++ b/internal/home/native.go |
| @@ -0,0 +1,540 @@ |
| +package home |
| + |
| +import ( |
| + "crypto/elliptic" |
| + "crypto/hmac" |
| + "crypto/rand" |
| + "crypto/sha256" |
| + "database/sql" |
| + "encoding/base64" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "mime" |
| + "net/http" |
| + "strings" |
| + "time" |
| + |
| + assertioncrypto "amadan.net/rastrillo/rastrillo/crypto" |
| + "github.com/go-chi/chi/v5" |
| + strictjson "github.com/go-json-experiment/json" |
| +) |
| + |
| +// The native half of Oficina ID (docs/superpowers/specs/2026-11-14-oficina-id-native.md). |
| +// |
| +// Every endpoint here lives under nativePrefix on the credential origin. They |
| +// take JSON only, answer no-store, send no CORS headers, render nothing and |
| +// refuse any request carrying Origin or Sec-Fetch-Site: a browser has no |
| +// business here, and refusing its evidence headers keeps every one of these |
| +// endpoints out of reach of a page (§4). |
| +const nativePrefix = "/native/v1" |
| + |
| +const ( |
| + // nativeProofContext domain-separates the device-key proof (§3). |
| + nativeProofContext = "oficina-id/native-proof/v1" |
| + |
| + 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 |
| + nativeGrantsPerID = 20 // live grants per person; a 21st ends the LRU |
| + nativeBodyLimit = 64 << 10 |
| + day = 24 * 3600 |
| +) |
| + |
| +// nativeReplayCap is how many replay rows the table holds before it fails |
| +// 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. |
| +var nativePlatforms = map[string]bool{"macos": true, "ios": true, "ipados": true} |
| + |
| +// mountNative mounts the native endpoints on the credential role. They sit |
| +// outside csrf.Protect: they refuse every browser evidence header instead. |
| +func (a *App) mountNative(r chi.Router) { |
| + r.Group(func(r chi.Router) { |
| + r.Use(a.credentialOnly) |
| + r.Post(nativePrefix+"/code/start", a.nativeCodeStart) |
| + r.Post(nativePrefix+"/code/resend", a.nativeCodeResend) |
| + r.Post(nativePrefix+"/code/verify", a.nativeCodeVerify) |
| + r.Post(nativePrefix+"/passkey/begin", a.nativePasskeyBegin) |
| + r.Post(nativePrefix+"/passkey/finish", a.nativePasskeyFinish) |
| + r.Post(nativePrefix+"/assert", a.nativeAuthed(a.nativeAssert)) |
| + r.Post(nativePrefix+"/signout", a.nativeAuthed(a.nativeSignout)) |
| + r.Get(aasaPath, a.serveAASA) |
| + }) |
| +} |
| + |
| +// nativeReply is every native answer. Date is set explicitly because the |
| +// client corrects its clock from it (§3); net/http would add one, but a |
| +// header the protocol depends on should not rest on a server default. |
| +func nativeReply(w http.ResponseWriter, status int, v any) { |
| + h := w.Header() |
| + h.Set("Cache-Control", "no-store") |
| + h.Set("Content-Type", "application/json") |
| + h.Set("X-Content-Type-Options", "nosniff") |
| + h.Set("Date", time.Now().UTC().Format(http.TimeFormat)) |
| + w.WriteHeader(status) |
| + _ = json.NewEncoder(w).Encode(v) |
| +} |
| + |
| +func nativeFail(w http.ResponseWriter, status int, code string) { |
| + nativeReply(w, status, map[string]string{"error": code}) |
| +} |
| + |
| +// The two 401 answers. The client wipes the device's identity only on |
| +// nativeGrantEnded: the grant is gone (never existed, revoked, signed out, |
| +// expired, replaced or swept by an enrolment). Every other refusal — a bad |
| +// signature, a skewed iat, a wrong htu or body, a replayed jti, a malformed |
| +// header — is nativeProofRejected, which the client may retry once after |
| +// correcting its clock from "now". |
| +const ( |
| + nativeGrantEnded = "grant_ended" |
| + nativeProofRejected = "proof_rejected" |
| +) |
| + |
| +// nativeUnauthorized carries the server's clock, so a client whose proof |
| +// failed on iat can correct its offset and retry once (§3). |
| +func nativeUnauthorized(w http.ResponseWriter, code string) { |
| + nativeReply(w, http.StatusUnauthorized, map[string]any{"error": code, "now": time.Now().Unix()}) |
| +} |
| + |
| +// nativeIntake applies the transport rules every native endpoint shares and |
| +// returns the raw body, which the proof's bh covers byte for byte. |
| +func nativeIntake(w http.ResponseWriter, r *http.Request) ([]byte, bool) { |
| + if _, ok := r.Header["Origin"]; ok { |
| + nativeFail(w, http.StatusForbidden, "browser") |
| + return nil, false |
| + } |
| + if _, ok := r.Header["Sec-Fetch-Site"]; ok { |
| + nativeFail(w, http.StatusForbidden, "browser") |
| + return nil, false |
| + } |
| + if r.URL.RawQuery != "" { |
| + nativeFail(w, http.StatusBadRequest, "request") |
| + return nil, false |
| + } |
| + media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) |
| + if err != nil || media != "application/json" { |
| + nativeFail(w, http.StatusUnsupportedMediaType, "json") |
| + return nil, false |
| + } |
| + body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, nativeBodyLimit)) |
| + if err != nil { |
| + nativeFail(w, http.StatusRequestEntityTooLarge, "request") |
| + return nil, false |
| + } |
| + return body, true |
| +} |
| + |
| +// decodeNative is strict: unknown members, duplicates and trailing data are |
| +// all refusals, so two parsers can never read one body two ways. |
| +func decodeNative(body []byte, v any) bool { |
| + return strictjson.Unmarshal(body, v, strictjson.RejectUnknownMembers(true)) == nil |
| +} |
| + |
| +// b64 is the one encoding on the native wire: base64url without padding. |
| +var nb64 = base64.RawURLEncoding |
| + |
| +func decodeB64(s string, n int) ([]byte, bool) { |
| + b, err := nb64.Strict().DecodeString(s) |
| + if err != nil || (n > 0 && len(b) != n) || nb64.EncodeToString(b) != s { |
| + return nil, false |
| + } |
| + return b, true |
| +} |
| + |
| +// decodeDeviceKey accepts a 65-byte uncompressed P-256 point, base64url, and |
| +// nothing else — the shape rastrillo/crypto.Verify takes. |
| +func decodeDeviceKey(s string) ([]byte, bool) { |
| + if len(s) != 87 { |
| + return nil, false |
| + } |
| + b, ok := decodeB64(s, 65) |
| + if !ok { |
| + return nil, false |
| + } |
| + if x, _ := elliptic.Unmarshal(elliptic.P256(), b); x == nil { |
| + return nil, false |
| + } |
| + return b, true |
| +} |
| + |
| +// nativeProof is the Oficina-Proof payload (§3). No JWT, no algorithm field. |
| +type nativeProof struct { |
| + V int `json:"v"` |
| + HTM string `json:"htm"` |
| + HTU string `json:"htu"` |
| + IAT int64 `json:"iat"` |
| + JTI string `json:"jti"` |
| + BH string `json:"bh"` |
| +} |
| + |
| +var errNativeProof = errors.New("home: native proof refused") |
| + |
| +// parseNativeProof reads the header without trusting any of it yet. |
| +func parseNativeProof(r *http.Request) (nativeProof, []byte, []byte, error) { |
| + var p nativeProof |
| + values := r.Header.Values("Oficina-Proof") |
| + if len(values) != 1 || len(values[0]) > 2048 { |
| + return p, nil, nil, errNativeProof |
| + } |
| + enc, sigEnc, ok := strings.Cut(values[0], ".") |
| + if !ok || strings.Contains(sigEnc, ".") { |
| + return p, nil, nil, errNativeProof |
| + } |
| + payload, ok := decodeB64(enc, 0) |
| + if !ok { |
| + return p, nil, nil, errNativeProof |
| + } |
| + sig, ok := decodeB64(sigEnc, 64) |
| + if !ok { |
| + return p, nil, nil, errNativeProof |
| + } |
| + if !decodeNative(payload, &p) { |
| + return p, nil, nil, errNativeProof |
| + } |
| + if p.V != 1 || p.HTM == "" || p.HTU == "" || p.IAT <= 0 || !nativeJTI(p.JTI) || len(p.BH) != 43 { |
| + return p, nil, nil, errNativeProof |
| + } |
| + return p, payload, sig, nil |
| +} |
| + |
| +func nativeJTI(s string) bool { |
| + if len(s) < 16 || len(s) > 64 { |
| + return false |
| + } |
| + for i := 0; i < len(s); i++ { |
| + if !alphaNumeric(s[i]) && s[i] != '-' && s[i] != '_' { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| +func alphaNumeric(b byte) bool { |
| + return b >= 'a' && b <= 'z' || b >= 'A' && b <= 'Z' || b >= '0' && b <= '9' |
| +} |
| + |
| +// verifyNativeProof is the whole check except the jti, which the caller |
| +// records only after this passes (§3: no jti row before the grant and the |
| +// signature verify). |
| +func (a *App) verifyNativeProof(r *http.Request, body, key []byte, p nativeProof, payload, sig []byte, now int64) bool { |
| + if !assertioncrypto.Verify(key, nativeProofContext, payload, sig) { |
| + return false |
| + } |
| + bh := sha256.Sum256(body) |
| + skew := p.IAT - now |
| + return p.HTM == r.Method && |
| + p.HTU == a.origins.Credential+r.URL.Path && |
| + skew <= nativeProofSkew && skew >= -nativeProofSkew && |
| + hmac.Equal([]byte(p.BH), []byte(nb64.EncodeToString(bh[:]))) |
| +} |
| + |
| +// 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") |
| +} |
| + |
| +func (a *App) nativeMAC(purpose string, parts ...string) string { |
| + m := hmac.New(sha256.New, a.nativeKey(purpose)) |
| + for _, p := range parts { |
| + m.Write([]byte(p)) |
| + m.Write([]byte{0}) |
| + } |
| + return hex.EncodeToString(m.Sum(nil)) |
| +} |
| + |
| +// identityID is what a device keys an identity by; it never holds the ref. |
| +func (a *App) identityID(person string) string { |
| + m := hmac.New(sha256.New, a.nativeKey("identity-id")) |
| + m.Write([]byte(person)) |
| + return nb64.EncodeToString(m.Sum(nil)) |
| +} |
| + |
| +func nativeHash(s string) string { h := sha256.Sum256([]byte(s)); return hex.EncodeToString(h[:]) } |
| + |
| +func nativeToken() (string, error) { |
| + b := make([]byte, 32) |
| + if _, err := rand.Read(b); err != nil { |
| + return "", err |
| + } |
| + return nb64.EncodeToString(b), nil |
| +} |
| + |
| +// nativeGrant is a live grant as loaded for one authenticated call. |
| +type nativeGrant struct { |
| + hash, person, identityID, deviceKey, platform, method string |
| + authTime int64 |
| +} |
| + |
| +func dayOf(unix int64) string { return time.Unix(unix, 0).UTC().Format(dayFormat) } |
| + |
| +// idleCutoff is the newest last_used_day that has already expired: a grant |
| +// last used on day D lapses at the start of D+91, whatever hour it was used. |
| +func idleCutoff(now int64) string { return dayOf(now - (nativeGrantIdleDays+1)*day) } |
| + |
| +// nativeAuthed authenticates a grant-holding call (§3) and hands the handler |
| +// an open writer transaction. The handler's answer is committed together |
| +// with the jti, so a refused handler still spends its jti. |
| +func (a *App) nativeAuthed(handle func(tx *sql.Tx, g nativeGrant, body []byte, now int64) (int, any)) http.HandlerFunc { |
| + return func(w http.ResponseWriter, r *http.Request) { |
| + body, ok := nativeIntake(w, r) |
| + if !ok { |
| + return |
| + } |
| + auth := r.Header.Values("Authorization") |
| + token, found := "", false |
| + if len(auth) == 1 { |
| + token, found = strings.CutPrefix(auth[0], "OficinaID ") |
| + } |
| + if !found || len(token) != 43 { |
| + nativeUnauthorized(w, nativeProofRejected) |
| + return |
| + } |
| + if _, ok := decodeB64(token, 32); !ok { |
| + nativeUnauthorized(w, nativeProofRejected) |
| + return |
| + } |
| + p, payload, sig, err := parseNativeProof(r) |
| + if err != nil { |
| + nativeUnauthorized(w, nativeProofRejected) |
| + return |
| + } |
| + tx, now, err := a.idTransaction(r.Context()) |
| + if err != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + defer tx.Rollback() |
| + var g nativeGrant |
| + var expires int64 |
| + var lastUsed string |
| + var ended sql.NullInt64 |
| + g.hash = nativeHash(token) |
| + var created int64 |
| + err = tx.QueryRow("SELECT person_ref,identity_id,device_key,platform,method,auth_time,expires_at,last_used_day,ended_at,created_at FROM home_id_grants WHERE grant_hash=?", g.hash). |
| + Scan(&g.person, &g.identityID, &g.deviceKey, &g.platform, &g.method, &g.authTime, &expires, &lastUsed, &ended, &created) |
| + if errors.Is(err, sql.ErrNoRows) || (err == nil && ended.Valid) { |
| + nativeUnauthorized(w, nativeGrantEnded) |
| + return |
| + } |
| + if err != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + // Belt and braces: "Sign out all devices" ends every grant in the |
| + // same transaction as its mark, so none created at or before the |
| + // mark should be live; if one is, it is not honoured. |
| + if before, err := signedOutBefore(r.Context(), tx, "home_id_signed_out_all", g.person, created); err != nil || before { |
| + if err != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + } else { |
| + nativeUnauthorized(w, nativeGrantEnded) |
| + } |
| + return |
| + } |
| + if expires <= now || lastUsed <= idleCutoff(now) { |
| + if _, err = tx.Exec("UPDATE home_id_grants SET ended_at=?,end_reason='expiry' WHERE grant_hash=? AND ended_at IS NULL", now, g.hash); err != nil || tx.Commit() != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + nativeUnauthorized(w, nativeGrantEnded) |
| + return |
| + } |
| + key, ok := decodeDeviceKey(g.deviceKey) |
| + if !ok || !a.verifyNativeProof(r, body, key, p, payload, sig, now) { |
| + nativeUnauthorized(w, nativeProofRejected) |
| + return |
| + } |
| + // Only now, with the grant live and the signature good, does the jti |
| + // touch the table. A row lives 61 seconds, not 60: iat may be 30 |
| + // seconds ahead of now and is accepted until 30 seconds behind, so |
| + // the last second a replay could pass is now+60, and the row must |
| + // still be there then. |
| + if _, err = tx.Exec("DELETE FROM home_id_native_replay WHERE expires_at<=?", now); err != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + var total, mine int |
| + if tx.QueryRow("SELECT count(*) FROM home_id_native_replay").Scan(&total) != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + if total >= nativeReplayCap { |
| + // Fails closed: a full table refuses every proof rather than |
| + // forgetting the oldest ones and readmitting their replays. |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + if tx.QueryRow("SELECT count(*) FROM home_id_native_replay WHERE grant_hash=?", g.hash).Scan(&mine) != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + if mine >= nativeReplayPerMin { |
| + nativeFail(w, http.StatusTooManyRequests, "rate_limited") |
| + return |
| + } |
| + // 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 |
| + } |
| + if n, err := res.RowsAffected(); err != nil || n != 1 { |
| + nativeUnauthorized(w, nativeProofRejected) |
| + return |
| + } |
| + if today := dayOf(now); lastUsed != today { |
| + if _, err = tx.Exec("UPDATE home_id_grants SET last_used_day=? WHERE grant_hash=?", today, g.hash); err != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + } |
| + status, reply := handle(tx, g, body, now) |
| + if status == 0 || tx.Commit() != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + nativeReply(w, status, reply) |
| + } |
| +} |
| + |
| +// nativePreGrant verifies a proof-only call (§3): one made before a grant |
| +// exists, signed by the key the call is bound to. These never touch the jti |
| +// table; their single-use start or challenge is their replay protection. |
| +func (a *App) nativePreGrant(r *http.Request, body []byte, deviceKey string, now int64) bool { |
| + key, ok := decodeDeviceKey(deviceKey) |
| + if !ok { |
| + return false |
| + } |
| + p, payload, sig, err := parseNativeProof(r) |
| + return err == nil && a.verifyNativeProof(r, body, key, p, payload, sig, now) |
| +} |
| + |
| +// mintGrant issues a grant to one device. It is called inside the writer |
| +// transaction that consumed the sign-in's proof, so a grant exists only if |
| +// that proof is gone. |
| +func (a *App) mintGrant(tx *sql.Tx, person, deviceKey, platform, method string, authTime, now int64) (map[string]any, error) { |
| + if err := sweepGrants(tx, now); err != nil { |
| + return nil, err |
| + } |
| + // A 21st live grant ends the least recently used one. |
| + for { |
| + var live int |
| + if err := tx.QueryRow("SELECT count(*) FROM home_id_grants WHERE person_ref=? AND ended_at IS NULL", person).Scan(&live); err != nil { |
| + return nil, errIDProof |
| + } |
| + if live < nativeGrantsPerID { |
| + break |
| + } |
| + if _, err := tx.Exec("UPDATE home_id_grants SET ended_at=?,end_reason='lru' WHERE grant_hash=(SELECT grant_hash FROM home_id_grants WHERE person_ref=? AND ended_at IS NULL ORDER BY last_used_day,created_at LIMIT 1)", now, person); err != nil { |
| + return nil, errIDProof |
| + } |
| + } |
| + token, err := nativeToken() |
| + if err != nil { |
| + return nil, errIDProof |
| + } |
| + id := a.identityID(person) |
| + if _, err = tx.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(?,?,?,?,?,?,?,?,?,?)", |
| + nativeHash(token), person, id, deviceKey, platform, method, authTime, now, dayOf(now), now+nativeGrantLife); err != nil { |
| + return nil, errIDProof |
| + } |
| + return map[string]any{"grant": token, "identity_id": id, "auth_time": authTime}, nil |
| +} |
| + |
| +// sweepGrants marks lapsed grants as expired and forgets ended ones once |
| +// their device key is no longer needed to recognise a returning device. |
| +func sweepGrants(tx *sql.Tx, now int64) error { |
| + if _, err := tx.Exec("UPDATE home_id_grants SET ended_at=?,end_reason='expiry' WHERE ended_at IS NULL AND (expires_at<=? OR last_used_day<=?)", now, now, idleCutoff(now)); err != nil { |
| + return errIDProof |
| + } |
| + if _, err := tx.Exec("DELETE FROM home_id_grants WHERE ended_at IS NOT NULL AND ended_at<=?", now-nativeGrantKeep); err != nil { |
| + return errIDProof |
| + } |
| + return nil |
| +} |
| + |
| +// endGrants ends every live grant a person holds, for one reason: "all_devices" |
| +// and "replacement" (§3, §10). |
| +func endGrants(tx *sql.Tx, person, reason string, now int64) error { |
| + _, err := tx.Exec("UPDATE home_id_grants SET ended_at=?,end_reason=? WHERE person_ref=? AND ended_at IS NULL", now, reason, person) |
| + if err != nil { |
| + return errIDProof |
| + } |
| + return nil |
| +} |
| + |
| +// endPasskeylessGrants is a first passkey enrolment's revocation (§3): every |
| +// live grant whose method has no passkey ends, except the enrolling grant. A |
| +// web enrolment has none, so it passes "". |
| +func endPasskeylessGrants(tx *sql.Tx, person, except string, now int64) error { |
| + _, err := tx.Exec("UPDATE home_id_grants SET ended_at=?,end_reason='enrolment' WHERE person_ref=? AND ended_at IS NULL AND instr(method,'passkey')=0 AND grant_hash<>?", now, person, except) |
| + if err != nil { |
| + return errIDProof |
| + } |
| + return nil |
| +} |
| + |
| +// 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 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 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 |
| + } |
| + switch reason.String { |
| + case "expiry", "lru", "enrolment": |
| + return true, nil |
| + } |
| + return false, nil |
| +} |
diff --git a/internal/home/native_assert.go b/internal/home/native_assert.go| new file mode 100644 |
| index 0000000..5521024 |
| --- /dev/null |
| +++ b/internal/home/native_assert.go |
| @@ -0,0 +1,87 @@ |
| +package home |
| + |
| +import ( |
| + "database/sql" |
| + "errors" |
| + "net/http" |
| + |
| + "amadan.net/oficina/home/handoff" |
| + "amadan.net/rastrillo/rastrillo/assertion" |
| +) |
| + |
| +var errMintPolicy = errors.New("home: mint refused by policy") |
| + |
| +// mintPolicy is the one rule for whether Home mints an assertion for a |
| +// consumer from a sign-in method. /authorize (handleAssertion) and the |
| +// native assert both call it, so a rule added here holds on both doors. |
| +// It is empty in slice A; Contra's passkey-only rule lands here later (§7). |
| +// |
| +// A variable rather than a function so a test can install a refusing |
| +// policy and watch both doors refuse. |
| +var mintPolicy = func(consumer, method string) error { return nil } |
| + |
| +// nativeAssert is POST assert {aud, challenge} → {assertion} (§7 step 1). |
| +// aud is an origin, matched exactly against the registered consumers. The |
| +// nonce is derived here from the caller's challenge, never taken from it. |
| +func (a *App) nativeAssert(tx *sql.Tx, g nativeGrant, body []byte, now int64) (int, any) { |
| + var in struct { |
| + Aud string `json:"aud"` |
| + Challenge string `json:"challenge"` |
| + } |
| + if !decodeNative(body, &in) { |
| + return http.StatusBadRequest, map[string]string{"error": "request"} |
| + } |
| + // The nonce is handoff's native derivation, the one every |
| + // NativeExchange recomputes; the caller supplies only the challenge. |
| + nonce, ok := handoff.NativeNonce(in.Challenge) |
| + if !ok { |
| + return http.StatusBadRequest, map[string]string{"error": "request"} |
| + } |
| + consumer := "" |
| + for id, origin := range a.consumers() { |
| + if origin == in.Aud { |
| + consumer = id |
| + break |
| + } |
| + } |
| + if consumer == "" || consumer == operatorConfirmConsumer || a.runtime == nil || a.runtime.signer == nil { |
| + return http.StatusBadRequest, map[string]string{"error": "audience"} |
| + } |
| + if mintPolicy(consumer, g.method) != nil { |
| + return http.StatusForbidden, map[string]string{"error": "policy"} |
| + } |
| + id, err := assertion.RandomID() |
| + if err != nil { |
| + return 0, nil |
| + } |
| + token, err := assertion.Sign(a.runtime.signer, assertion.Claims{ |
| + Version: 1, |
| + Issuer: a.origins.Credential, |
| + Audience: in.Aud, |
| + Subject: g.person, |
| + KeyID: a.runtime.keyID, |
| + ID: id, |
| + Nonce: nonce, |
| + IssuedAt: now, |
| + ExpiresAt: now + 120, |
| + AuthTime: g.authTime, |
| + }) |
| + if err != nil { |
| + return 0, nil |
| + } |
| + return http.StatusOK, map[string]string{"assertion": token} |
| +} |
| + |
| +// nativeSignout is POST signout: the device's own grant ends (§10). The app |
| +// signed this request before deleting its key, so it arrives after the key |
| +// is gone; the proof's 30-second window bounds how late. |
| +func (a *App) nativeSignout(tx *sql.Tx, g nativeGrant, body []byte, now int64) (int, any) { |
| + var in struct{} |
| + if !decodeNative(body, &in) { |
| + return http.StatusBadRequest, map[string]string{"error": "request"} |
| + } |
| + if _, err := tx.Exec("UPDATE home_id_grants SET ended_at=?,end_reason='signout' WHERE grant_hash=? AND ended_at IS NULL", now, g.hash); err != nil { |
| + return 0, nil |
| + } |
| + return http.StatusOK, map[string]string{} |
| +} |
diff --git a/internal/home/native_code.go b/internal/home/native_code.go| new file mode 100644 |
| index 0000000..bc1d4c7 |
| --- /dev/null |
| +++ b/internal/home/native_code.go |
| @@ -0,0 +1,651 @@ |
| +package home |
| + |
| +import ( |
| + "context" |
| + "crypto/hmac" |
| + "crypto/rand" |
| + "database/sql" |
| + "errors" |
| + "fmt" |
| + "math/big" |
| + "net" |
| + "net/http" |
| + "strings" |
| + "time" |
| + |
| + "github.com/keymaildev/signin" |
| +) |
| + |
| +// The email code (§4), for a person with no passkey yet. |
| +const ( |
| + nativeCodeLife = 600 // a code lives ten minutes |
| + nativeCodeTries = 5 // and dies after five wrong tries |
| + nativeCodeSends = 3 // a start gets at most three sends |
| + nativeResendAfter = 30 // thirty seconds apart |
| + nativePendingLife = 300 // a passkey-required pending lives five minutes |
| + nativeLivePerIP = 20 |
| + nativeBucketCap = 500000 |
| + nativeWindow = 900 |
| + nativeCodeSealScope = "native.code" |
| +) |
| + |
| +// nativeLiveStarts is the live-start table's size (§4). A variable only so a |
| +// test can fill it without 10,000 inserts. |
| +var nativeLiveStarts = 10000 |
| + |
| +// The §4 limits, each its own persistent fixed-window counter. The prefix |
| +// names the bucket; the rest of the key is blinded. |
| +type nativeLimit struct { |
| + prefix string |
| + limit int |
| + window int64 |
| +} |
| + |
| +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} |
| + // 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" |
| + |
| +// codeMailBody has no link: a link would sign in a browser (§4). |
| +func codeMailBody(code string) string { |
| + return "Your Oficina ID code is " + code + "\n\n" + |
| + "It expires in 10 minutes and works once.\n\n" + |
| + "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...)...)[:32] |
| +} |
| + |
| +// bucketFull reports whether a bucket has reached its limit in its window. |
| +func bucketFull(tx *sql.Tx, key string, l nativeLimit, now int64) (bool, error) { |
| + var n int |
| + err := tx.QueryRow("SELECT count FROM home_id_native_buckets WHERE bucket=? AND expires_at>?", key, now).Scan(&n) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return false, nil |
| + } |
| + if err != nil { |
| + return false, errIDProof |
| + } |
| + return n >= l.limit, nil |
| +} |
| + |
| +// bucketSpend counts one against a bucket, opening a new window when the |
| +// last one has closed. |
| +func bucketSpend(tx *sql.Tx, key string, l nativeLimit, now int64) error { |
| + _, err := tx.Exec(`INSERT INTO home_id_native_buckets(bucket,count,expires_at) VALUES(?,1,?) |
| + ON CONFLICT(bucket) DO UPDATE SET |
| + count = CASE WHEN expires_at<=? THEN 1 ELSE count+1 END, |
| + expires_at = CASE WHEN expires_at<=? THEN ? ELSE expires_at END`, key, now+l.window, now, now, now+l.window) |
| + if err != nil { |
| + return errIDProof |
| + } |
| + return nil |
| +} |
| + |
| +type nativeBucket struct { |
| + key string |
| + limit nativeLimit |
| + err error |
| +} |
| + |
| +// checkThenSpend refuses if any bucket is full, and otherwise spends one |
| +// from each, in the caller's transaction: parallel requests serialise on the |
| +// writer, so none can see a count another has not yet written. |
| +func checkThenSpend(tx *sql.Tx, buckets []nativeBucket, now int64) error { |
| + for _, b := range buckets { |
| + full, err := bucketFull(tx, b.key, b.limit, now) |
| + if err != nil { |
| + return err |
| + } |
| + if full { |
| + return b.err |
| + } |
| + } |
| + var n int |
| + if tx.QueryRow("SELECT count(*) FROM home_id_native_buckets").Scan(&n) != nil { |
| + return errIDProof |
| + } |
| + if n+len(buckets) > nativeBucketCap { |
| + return errIDProof |
| + } |
| + for _, b := range buckets { |
| + if err := bucketSpend(tx, b.key, b.limit, now); err != nil { |
| + return err |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// nativeIPBucket is §4's ip_bucket: the IPv4 /32 or the IPv6 /64, from the |
| +// same edge-written address signin's limiter uses. "" when no IP is known, |
| +// which skips the per-IP limits rather than pooling everyone into one. |
| +func nativeIPBucket(r *http.Request) string { |
| + ip := net.ParseIP(clientIP(r)) |
| + if ip == nil { |
| + return "" |
| + } |
| + if v4 := ip.To4(); v4 != nil { |
| + return v4.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 { |
| + return "", err |
| + } |
| + return fmt.Sprintf("%06d", n.Int64()), nil |
| +} |
| + |
| +// codeMAC binds a code to its start, so a code is worth nothing elsewhere. |
| +func (a *App) codeMAC(startHash, code string) string { |
| + return a.nativeMAC("native-code", startHash, code) |
| +} |
| + |
| +func validCode(s string) bool { |
| + if len(s) != 6 { |
| + return false |
| + } |
| + for i := 0; i < 6; i++ { |
| + if s[i] < '0' || s[i] > '9' { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +// nativeAddress is the address as /signin normalises it, and its native |
| +// blind: a Home-keyed HMAC distinct from the people table's index. |
| +func (a *App) nativeAddress(raw string) (address, blind string, err error) { |
| + local, domain, err := signin.SplitAddress(raw) |
| + if err != nil || len(raw) > 320 { |
| + return "", "", signin.ErrBadAddress |
| + } |
| + address = local + "@" + domain |
| + return address, a.nativeMAC("native-address", strings.ToLower(address)), nil |
| +} |
| + |
| +// personFor finds, never mints, the person behind an address. |
| +func (a *App) personFor(tx *sql.Tx, address string) (string, error) { |
| + var person string |
| + err := tx.QueryRow("SELECT person_ref FROM people WHERE blind_index=?", blindIndex(a.secrets.Pepper, address)).Scan(&person) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return "", nil |
| + } |
| + if err != nil { |
| + return "", errIDProof |
| + } |
| + return person, nil |
| +} |
| + |
| +// spendWebBudget spends the address's share of the web door's email budget, |
| +// so an address has one allowance across both doors (§4). |
| +func (a *App) spendWebBudget(ctx context.Context, address string) bool { |
| + budget := a.flow.AddressBudget |
| + if budget == 0 { |
| + budget = 5 |
| + } |
| + ok, err := a.flow.Limiter.Allow(ctx, "addr:"+strings.ToLower(address), time.Now(), budget) |
| + 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<=?", |
| + "DELETE FROM home_id_native_pending WHERE expires_at<=?", |
| + "DELETE FROM home_id_native_buckets WHERE expires_at<=?", |
| + } { |
| + if _, err := tx.Exec(q, now); err != nil { |
| + return errIDProof |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +func nativeLimitFail(w http.ResponseWriter, err error) { |
| + switch { |
| + case errors.Is(err, errNativeDailyLimit): |
| + nativeFail(w, http.StatusTooManyRequests, "daily_limit") |
| + case errors.Is(err, errNativeLimited): |
| + nativeFail(w, http.StatusTooManyRequests, "rate_limited") |
| + default: |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + } |
| +} |
| + |
| +// nativeCodeStart is POST code/start {email, device_key, platform}. The |
| +// answer is the same for an address Home knows and one it has never seen. |
| +func (a *App) nativeCodeStart(w http.ResponseWriter, r *http.Request) { |
| + body, ok := nativeIntake(w, r) |
| + if !ok { |
| + return |
| + } |
| + var in struct { |
| + Email string `json:"email"` |
| + DeviceKey string `json:"device_key"` |
| + Platform string `json:"platform"` |
| + } |
| + if !decodeNative(body, &in) || !nativePlatforms[in.Platform] { |
| + nativeFail(w, http.StatusBadRequest, "request") |
| + return |
| + } |
| + if !a.nativePreGrant(r, body, in.DeviceKey, time.Now().Unix()) { |
| + nativeUnauthorized(w, nativeProofRejected) |
| + return |
| + } |
| + address, blind, err := a.nativeAddress(in.Email) |
| + if err != nil { |
| + nativeFail(w, http.StatusBadRequest, "email") |
| + return |
| + } |
| + ip := nativeIPBucket(r) |
| + ipBlind := "" |
| + if ip != "" { |
| + ipBlind = a.nativeMAC("native-ip", ip) |
| + } |
| + |
| + tx, now, err := a.idTransaction(r.Context()) |
| + if err != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + defer tx.Rollback() |
| + if sweepCodes(tx, now) != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + // A second start for the same (address, key) replaces the first: one |
| + // code is live per pair, and the old one stops counting as live. |
| + if _, err = tx.Exec("DELETE FROM home_id_native_starts WHERE blind_index=? AND device_key=?", blind, in.DeviceKey); err != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + var live, liveIP int |
| + if tx.QueryRow("SELECT count(*) FROM home_id_native_starts").Scan(&live) != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + if live >= nativeLiveStarts { |
| + // Full: new starts wait, existing ones still verify, and the web's |
| + // link sign-in is untouched (§4). |
| + nativeFail(w, http.StatusServiceUnavailable, "full") |
| + return |
| + } |
| + if ipBlind != "" { |
| + if tx.QueryRow("SELECT count(*) FROM home_id_native_starts WHERE ip_bucket=?", ipBlind).Scan(&liveIP) != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + if liveIP >= nativeLivePerIP { |
| + nativeFail(w, http.StatusTooManyRequests, "rate_limited") |
| + return |
| + } |
| + } |
| + person, err := a.personFor(tx, address) |
| + if err != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + returning, err := returningKey(tx, person, in.DeviceKey) |
| + if err != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + buckets := []nativeBucket{{a.bucketKey(startsPerAddressKey, blind, in.DeviceKey), startsPerAddressKey, errNativeLimited}} |
| + if ipBlind != "" { |
| + buckets = append(buckets, |
| + nativeBucket{a.bucketKey(startsPerIP, ipBlind), startsPerIP, 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 |
| + // guesses are spent for the day, so it is refused before any mail. |
| + full, err := bucketFull(tx, a.bucketKey(wrongNewKeysPerDay, blind), wrongNewKeysPerDay, now) |
| + if err != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + if full { |
| + nativeLimitFail(w, errNativeDailyLimit) |
| + return |
| + } |
| + buckets = append(buckets, |
| + nativeBucket{a.bucketKey(startsPerAddress, blind), startsPerAddress, errNativeLimited}, |
| + nativeBucket{a.bucketKey(startsPerAddressDay, blind), startsPerAddressDay, errNativeLimited}) |
| + } |
| + if err = checkThenSpend(tx, buckets, now); err != nil { |
| + nativeLimitFail(w, err) |
| + return |
| + } |
| + start, err := nativeToken() |
| + if err != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + code, err := newNativeCode() |
| + if err != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + startHash := nativeHash(start) |
| + sealed, err := a.secrets.Sealer.Seal(nativeCodeSealScope, []byte(address)) |
| + if err != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + if _, err = tx.Exec("INSERT INTO home_id_native_starts(start_hash,sealed_address,blind_index,device_key,platform,ip_bucket,code_mac,sends,last_send,attempts,expires_at) VALUES(?,?,?,?,?,?,?,1,?,0,?)", |
| + startHash, sealed, blind, in.DeviceKey, in.Platform, ipBlind, a.codeMAC(startHash, code), now, now+nativeCodeLife); err != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + // Last before commit: the in-memory web budget cannot roll back, so it is |
| + // spent only once every persistent check has passed. |
| + if !a.spendWebBudget(r.Context(), address) { |
| + nativeLimitFail(w, errNativeLimited) |
| + return |
| + } |
| + if tx.Commit() != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + if !a.sendCode(r.Context(), address, code) { |
| + a.dropStart(r.Context(), startHash) |
| + nativeFail(w, http.StatusServiceUnavailable, "mail") |
| + return |
| + } |
| + nativeReply(w, http.StatusAccepted, map[string]any{"start": start, "resend_after": nativeResendAfter}) |
| +} |
| + |
| +// sendCode mails the code. Neither the code nor the address reaches a log. |
| +func (a *App) sendCode(ctx context.Context, address, code string) bool { |
| + ctx, cancel := context.WithTimeout(ctx, 10*time.Second) |
| + defer cancel() |
| + if a.secrets.Mailer.Send(ctx, address, codeMailSubject, codeMailBody(code)) != nil { |
| + a.logger.Warn("native code delivery failed") |
| + return false |
| + } |
| + return true |
| +} |
| + |
| +// dropStart removes a start whose mail failed. Best effort: the row is |
| +// sealed and expires in ten minutes regardless. |
| +func (a *App) dropStart(ctx context.Context, startHash string) { |
| + if _, err := a.db.Writer().ExecContext(ctx, "DELETE FROM home_id_native_starts WHERE start_hash=?", startHash); err != nil { |
| + a.logger.Warn("dropping an undelivered native start failed") |
| + } |
| +} |
| + |
| +type nativeStart struct { |
| + hash, deviceKey, platform, blind, codeMAC string |
| + sealed []byte |
| + sends, attempts int |
| + lastSend int64 |
| +} |
| + |
| +func loadStart(tx *sql.Tx, start string, now int64) (nativeStart, bool) { |
| + s := nativeStart{hash: nativeHash(start)} |
| + if _, ok := decodeB64(start, 32); !ok { |
| + return s, false |
| + } |
| + err := tx.QueryRow("SELECT device_key,platform,blind_index,code_mac,sealed_address,sends,attempts,last_send FROM home_id_native_starts WHERE start_hash=? AND expires_at>?", s.hash, now). |
| + Scan(&s.deviceKey, &s.platform, &s.blind, &s.codeMAC, &s.sealed, &s.sends, &s.attempts, &s.lastSend) |
| + return s, err == nil |
| +} |
| + |
| +// nativeCodeResend is POST code/resend {start}: a new code for the same |
| +// start, at most three sends, thirty seconds apart. |
| +func (a *App) nativeCodeResend(w http.ResponseWriter, r *http.Request) { |
| + body, ok := nativeIntake(w, r) |
| + if !ok { |
| + return |
| + } |
| + var in struct { |
| + Start string `json:"start"` |
| + } |
| + if !decodeNative(body, &in) { |
| + nativeFail(w, http.StatusBadRequest, "request") |
| + return |
| + } |
| + tx, now, err := a.idTransaction(r.Context()) |
| + if err != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + 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, |
| + // and the app starts again. |
| + nativeFail(w, http.StatusGone, "expired") |
| + return |
| + } |
| + if !a.nativePreGrant(r, body, s.deviceKey, now) { |
| + nativeUnauthorized(w, nativeProofRejected) |
| + return |
| + } |
| + if s.sends >= nativeCodeSends { |
| + nativeFail(w, http.StatusTooManyRequests, "rate_limited") |
| + return |
| + } |
| + if wait := s.lastSend + nativeResendAfter - now; wait > 0 { |
| + nativeReply(w, http.StatusTooManyRequests, map[string]any{"error": "rate_limited", "resend_after": wait}) |
| + return |
| + } |
| + plain, err := a.secrets.Sealer.Open(nativeCodeSealScope, s.sealed) |
| + if err != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + address := string(plain) |
| + code, err := newNativeCode() |
| + if err != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + // A new code replaces the old one, with its own five tries; the |
| + // persistent wrong-code buckets still bound guessing across codes. |
| + if _, err = tx.Exec("UPDATE home_id_native_starts SET code_mac=?,sends=sends+1,last_send=?,attempts=0,expires_at=? WHERE start_hash=?", a.codeMAC(s.hash, code), now, now+nativeCodeLife, s.hash); err != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + if !a.spendWebBudget(r.Context(), address) { |
| + nativeLimitFail(w, errNativeLimited) |
| + return |
| + } |
| + if tx.Commit() != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + if !a.sendCode(r.Context(), address, code) { |
| + nativeFail(w, http.StatusServiceUnavailable, "mail") |
| + return |
| + } |
| + nativeReply(w, http.StatusAccepted, map[string]any{"start": in.Start, "resend_after": nativeResendAfter}) |
| +} |
| + |
| +// nativeCodeVerify is POST code/verify {start, code}. A right code finds or |
| +// mints the person and runs idGate's check: no passkey mints a grant; a |
| +// passkey returns a pending that must be finished with one. |
| +func (a *App) nativeCodeVerify(w http.ResponseWriter, r *http.Request) { |
| + body, ok := nativeIntake(w, r) |
| + if !ok { |
| + return |
| + } |
| + var in struct { |
| + Start string `json:"start"` |
| + Code string `json:"code"` |
| + } |
| + if !decodeNative(body, &in) || !validCode(in.Code) { |
| + nativeFail(w, http.StatusBadRequest, "request") |
| + return |
| + } |
| + tx, now, err := a.idTransaction(r.Context()) |
| + if err != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + 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") |
| + return |
| + } |
| + if !a.nativePreGrant(r, body, s.deviceKey, now) { |
| + nativeUnauthorized(w, nativeProofRejected) |
| + return |
| + } |
| + plain, err := a.secrets.Sealer.Open(nativeCodeSealScope, s.sealed) |
| + if err != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + address := string(plain) |
| + person, err := a.personFor(tx, address) |
| + if err != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + returning, err := returningKey(tx, person, s.deviceKey) |
| + if err != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + wrongKey := nativeBucket{a.bucketKey(wrongPerAddressKey, s.blind, s.deviceKey), wrongPerAddressKey, errNativeLimited} |
| + wrongNew := nativeBucket{a.bucketKey(wrongNewKeysPerDay, s.blind), wrongNewKeysPerDay, errNativeDailyLimit} |
| + guard := []nativeBucket{wrongKey} |
| + if !returning { |
| + guard = append(guard, wrongNew) |
| + } |
| + for _, b := range guard { |
| + full, err := bucketFull(tx, b.key, b.limit, now) |
| + if err != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + if full { |
| + nativeLimitFail(w, b.err) |
| + return |
| + } |
| + } |
| + if !hmac.Equal([]byte(a.codeMAC(s.hash, in.Code)), []byte(s.codeMAC)) { |
| + for _, b := range guard { |
| + if bucketSpend(tx, b.key, b.limit, now) != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + } |
| + q := "UPDATE home_id_native_starts SET attempts=attempts+1 WHERE start_hash=?" |
| + if s.attempts+1 >= nativeCodeTries { |
| + q = "DELETE FROM home_id_native_starts WHERE start_hash=?" |
| + } |
| + if _, err = tx.Exec(q, s.hash); err != nil || tx.Commit() != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + nativeFail(w, http.StatusBadRequest, "code") |
| + return |
| + } |
| + // Right: the start is used once, and its sealed address goes with it. |
| + if _, err = tx.Exec("DELETE FROM home_id_native_starts WHERE start_hash=?", s.hash); err != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + if person == "" { |
| + if person, err = findOrMintPersonOn(r.Context(), tx, a.secrets.Pepper, address, time.Unix(now, 0)); err != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + } |
| + var passkeys int |
| + if tx.QueryRow("SELECT count(*) FROM passkey_credentials WHERE subject=?", person).Scan(&passkeys) != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + var reply map[string]any |
| + if passkeys == 0 { |
| + reply, err = a.mintGrant(tx, person, s.deviceKey, s.platform, "email", now, now) |
| + } else { |
| + reply, err = a.nativePending(tx, person, s, now) |
| + } |
| + if err != nil || tx.Commit() != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + nativeReply(w, http.StatusOK, reply) |
| +} |
| + |
| +// nativePending is a code verified for an enrolled account: no grant, only a |
| +// five-minute handle bound to the start and its key, finished by a passkey. |
| +func (a *App) nativePending(tx *sql.Tx, person string, s nativeStart, now int64) (map[string]any, error) { |
| + var n int |
| + if tx.QueryRow("SELECT count(*) FROM home_id_native_pending").Scan(&n) != nil || n >= nativeLiveStarts { |
| + return nil, errIDProof |
| + } |
| + pending, err := nativeToken() |
| + if err != nil { |
| + return nil, errIDProof |
| + } |
| + if _, err = tx.Exec("INSERT INTO home_id_native_pending VALUES(?,?,?,?,?,?,?)", nativeHash(pending), person, s.hash, s.deviceKey, s.platform, "email", now+nativePendingLife); err != nil { |
| + return nil, errIDProof |
| + } |
| + return map[string]any{"factor": []string{"passkey"}, "pending": pending}, nil |
| +} |
diff --git a/internal/home/native_code_test.go b/internal/home/native_code_test.go| new file mode 100644 |
| index 0000000..8435943 |
| --- /dev/null |
| +++ b/internal/home/native_code_test.go |
| @@ -0,0 +1,537 @@ |
| +package home |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "errors" |
| + "fmt" |
| + "log/slog" |
| + "net/http" |
| + "net/url" |
| + "sort" |
| + "strings" |
| + "sync" |
| + "testing" |
| + |
| + "amadan.net/oficina/home/internal/home/sealtest" |
| +) |
| + |
| +// §13 Codes: a full code sign-in, and the mail that carries the code. |
| +func TestNativeCodeSignIn(t *testing.T) { |
| + t.Parallel() |
| + app := newNativeApp(t) |
| + d := newDevice(t) |
| + start := d.start(t, app, sealtest.CanaryAddress) |
| + mail, _ := app.mailer.last() |
| + if mail.To != sealtest.CanaryAddress || mail.Subject != "Your Oficina ID code" || !strings.HasPrefix(mail.Body, "Your Oficina ID code is ") { |
| + t.Fatalf("mail: %+v", mail) |
| + } |
| + if strings.Contains(mail.Body, "http") || strings.Contains(mail.Body, "oficina.works") { |
| + t.Fatal("the code mail carries a link") |
| + } |
| + // No address at rest while the code is live: sealed, never readable. |
| + sealtest.AssertNoPlaintext(t, app.dbPath) |
| + w := d.verify(t, app, start, lastCode(t, app)) |
| + out := decodeReply(t, w) |
| + if w.Code != 200 || len(out["grant"].(string)) != 43 || out["identity_id"] == "" || out["auth_time"] == nil { |
| + t.Fatal("verify", w.Code, w.Body.String()) |
| + } |
| + if n := count(t, app, "SELECT count(*) FROM home_id_native_starts"); n != 0 { |
| + t.Fatal("a used start survived verify", n) |
| + } |
| + var method, platform string |
| + if err := app.db.Writer().QueryRow("SELECT method,platform FROM home_id_grants").Scan(&method, &platform); err != nil || method != "email" || platform != "macos" { |
| + t.Fatal("grant row", method, platform, err) |
| + } |
| + // The same person as the web door finds for that address. |
| + session := signInFully(t, app, sealtest.CanaryAddress) |
| + if out["identity_id"] != app.identityID(subjectOf(t, app, session)) { |
| + t.Fatal("native code found a different person than /signin") |
| + } |
| + sealtest.AssertNoPlaintext(t, app.dbPath) |
| +} |
| + |
| +// §13 Codes: identical answers for known and unknown addresses. |
| +func TestNativeCodeStartIdenticalForKnownAndUnknown(t *testing.T) { |
| + t.Parallel() |
| + app := newNativeApp(t) |
| + signInFully(t, app, "known@example.invalid") |
| + shape := func(email string) (int, []string, []string) { |
| + d := newDevice(t) |
| + w := d.call(t, app, nativePrefix+"/code/start", map[string]string{"email": email, "device_key": d.public(), "platform": "ios"}, "") |
| + var keys, headers []string |
| + for k := range decodeReply(t, w) { |
| + keys = append(keys, k) |
| + } |
| + for k := range w.Header() { |
| + headers = append(headers, k) |
| + } |
| + sort.Strings(keys) |
| + sort.Strings(headers) |
| + return w.Code, keys, headers |
| + } |
| + c1, k1, h1 := shape("known@example.invalid") |
| + c2, k2, h2 := shape("never-seen@example.invalid") |
| + if c1 != 202 || c1 != c2 || fmt.Sprint(k1) != fmt.Sprint(k2) || fmt.Sprint(h1) != fmt.Sprint(h2) { |
| + t.Fatal("known and unknown addresses differ", c1, c2, k1, k2, h1, h2) |
| + } |
| +} |
| + |
| +// §13 Codes: entropy, expiry and single use. |
| +func TestNativeCodeEntropyExpiryAndSingleUse(t *testing.T) { |
| + t.Parallel() |
| + seen := map[string]bool{} |
| + for range 200 { |
| + c, err := newNativeCode() |
| + if err != nil || !validCode(c) { |
| + t.Fatal("bad code", c, err) |
| + } |
| + seen[c] = true |
| + } |
| + if len(seen) < 190 { |
| + t.Fatal("codes repeat far too often", len(seen)) |
| + } |
| + app := newNativeApp(t) |
| + d := newDevice(t) |
| + start := d.start(t, app, "a@example.invalid") |
| + code := lastCode(t, app) |
| + var mac string |
| + app.db.Writer().QueryRow("SELECT code_mac FROM home_id_native_starts").Scan(&mac) |
| + if strings.Contains(mac, code) { |
| + t.Fatal("the code is at rest") |
| + } |
| + if w := d.verify(t, app, start, code); w.Code != 200 { |
| + t.Fatal("first use", w.Code) |
| + } |
| + if w := d.verify(t, app, start, code); w.Code == 200 { |
| + t.Fatal("a code worked twice") |
| + } |
| + // Expiry. |
| + start = d.start(t, app, "a@example.invalid") |
| + code = lastCode(t, app) |
| + if _, err := app.db.Writer().Exec("UPDATE home_id_native_starts SET expires_at=1"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if w := d.verify(t, app, start, code); w.Code == 200 { |
| + t.Fatal("an expired code worked") |
| + } |
| + // A code is bound to its start. |
| + other := newDevice(t) |
| + d.start(t, app, "b@example.invalid") |
| + c1 := lastCode(t, app) |
| + s2 := other.start(t, app, "b@example.invalid") |
| + if c2 := lastCode(t, app); c1 != c2 { |
| + if w := other.verify(t, app, s2, c1); w.Code == 200 { |
| + t.Fatal("one start's code opened another") |
| + } |
| + } |
| +} |
| + |
| +// §13 Codes: a code dies after five wrong tries. |
| +func TestNativeCodeDiesAfterFiveWrong(t *testing.T) { |
| + t.Parallel() |
| + app := newNativeApp(t) |
| + d := newDevice(t) |
| + start := d.start(t, app, "a@example.invalid") |
| + code := lastCode(t, app) |
| + wrong := "000000" |
| + if code == wrong { |
| + wrong = "111111" |
| + } |
| + for i := range 5 { |
| + if w := d.verify(t, app, start, wrong); w.Code != 400 || decodeReply(t, w)["error"] != "code" { |
| + t.Fatal("wrong try", i, w.Code, w.Body.String()) |
| + } |
| + } |
| + if w := d.verify(t, app, start, code); w.Code == 200 { |
| + t.Fatal("the right code worked after five wrong tries") |
| + } |
| +} |
| + |
| +// §13 Codes: persistent buckets survive a restart, and the per-(address, |
| +// key) wrong-code cap holds. |
| +func TestNativeCodeBucketsSurviveRestart(t *testing.T) { |
| + t.Parallel() |
| + app := newNativeApp(t) |
| + for range 5 { |
| + newDevice(t).start(t, app, "a@example.invalid") |
| + } |
| + // A restart forgets the web's in-memory budget; the native start cap |
| + // is on disk and still refuses. |
| + app = app.restart(t) |
| + d := newDevice(t) |
| + w := d.call(t, app, nativePrefix+"/code/start", map[string]string{"email": "a@example.invalid", "device_key": d.public(), "platform": "macos"}, "") |
| + if w.Code != 429 { |
| + t.Fatal("per-address start cap forgot itself across a restart", w.Code) |
| + } |
| + |
| + // Wrong codes per (address, key): five per fifteen minutes, counted |
| + // across codes (a resend gives a code fresh tries, never the address) |
| + // and across a restart. |
| + app = newNativeApp(t) |
| + d = newDevice(t) |
| + start := d.start(t, app, "b@example.invalid") |
| + wrong := func() { |
| + t.Helper() |
| + if w := d.verify(t, app, start, "999999"); w.Code != 400 && lastCode(t, app) != "999999" { |
| + t.Fatal("wrong code", w.Code) |
| + } |
| + } |
| + for range 4 { |
| + wrong() |
| + } |
| + if _, err := app.db.Writer().Exec("UPDATE home_id_native_starts SET last_send=last_send-31"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if w := d.call(t, app, nativePrefix+"/code/resend", map[string]string{"start": start}, ""); w.Code != 202 { |
| + t.Fatal("resend", w.Code) |
| + } |
| + app = app.restart(t) |
| + wrong() |
| + if w := d.verify(t, app, start, lastCode(t, app)); w.Code != 429 { |
| + t.Fatal("a sixth guess in the window was judged", w.Code) |
| + } |
| +} |
| + |
| +// §13 Codes: parallel starts cannot overspend a bucket. |
| +func TestNativeCodeParallelStartsHoldTheCap(t *testing.T) { |
| + t.Parallel() |
| + app := newNativeApp(t) |
| + var wg sync.WaitGroup |
| + var mu sync.Mutex |
| + codes := map[int]int{} |
| + devices := make([]*device, 12) |
| + for i := range devices { |
| + devices[i] = newDevice(t) |
| + } |
| + for _, d := range devices { |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + w := d.call(t, app, nativePrefix+"/code/start", map[string]string{"email": "p@example.invalid", "device_key": d.public(), "platform": "macos"}, "") |
| + mu.Lock() |
| + codes[w.Code]++ |
| + mu.Unlock() |
| + }() |
| + } |
| + wg.Wait() |
| + if codes[202] != 5 || codes[429] != 7 { |
| + t.Fatal("parallel starts overspent the address", codes) |
| + } |
| +} |
| + |
| +// §13 Codes: the daily cap, the returning-key exemption, and its exclusions. |
| +func TestNativeCodeDailyCapAndReturningKeys(t *testing.T) { |
| + t.Parallel() |
| + for _, tc := range []struct { |
| + reason string |
| + returning bool |
| + }{ |
| + // End to end for one of each kind; TestNativeReturningKeyRule and |
| + // the end_reason CHECK cover the rest without a sign-in apiece. |
| + {"", true}, {"expiry", true}, {"all_devices", false}, |
| + } { |
| + t.Run("ended="+tc.reason, func(t *testing.T) { |
| + app := newNativeApp(t) |
| + const email = "victim@example.invalid" |
| + mine := newDevice(t) |
| + grant, _ := mine.signInByCode(t, app, email) |
| + if tc.reason != "" { |
| + if _, err := app.db.Writer().Exec("UPDATE home_id_grants SET ended_at=1,end_reason=? WHERE grant_hash=?", tc.reason, nativeHash(grant)); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + // An attacker spends the address's new-device guesses: four |
| + // starts, five wrong codes each. |
| + for range 4 { |
| + a := newDevice(t) |
| + start := a.start(t, app, email) |
| + code := lastCode(t, app) |
| + wrong := "000000" |
| + if code == wrong { |
| + wrong = "000001" |
| + } |
| + for range 5 { |
| + a.verify(t, app, start, wrong) |
| + } |
| + } |
| + 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"] != "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 |
| + w = mine.call(t, app, nativePrefix+"/code/start", map[string]string{"email": email, "device_key": mine.public(), "platform": "macos"}, "") |
| + if tc.returning { |
| + if w.Code != 202 { |
| + t.Fatal("a returning device was blocked", w.Code, w.Body.String()) |
| + } |
| + start := decodeReply(t, w)["start"].(string) |
| + 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 || 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) { |
| + t.Parallel() |
| + 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) { |
| + t.Parallel() |
| + app := newNativeApp(t) |
| + d := newDevice(t) |
| + d.signInByCode(t, app, "e@example.invalid") |
| + for range 4 { |
| + d.start(t, app, "e@example.invalid") |
| + } |
| + app = app.restart(t) |
| + w := d.call(t, app, nativePrefix+"/code/start", map[string]string{"email": "e@example.invalid", "device_key": d.public(), "platform": "macos"}, "") |
| + if w.Code != 429 { |
| + t.Fatal("a returning key started six times in fifteen minutes", w.Code) |
| + } |
| +} |
| + |
| +// §13 Codes: one email allowance shared with the web, both ways. |
| +func TestNativeCodeSharesTheWebEmailBudget(t *testing.T) { |
| + t.Parallel() |
| + app := newNativeApp(t) |
| + for range 5 { |
| + signIn(t, app, "shared@example.invalid") |
| + } |
| + d := newDevice(t) |
| + w := d.call(t, app, nativePrefix+"/code/start", map[string]string{"email": "shared@example.invalid", "device_key": d.public(), "platform": "macos"}, "") |
| + if w.Code != 429 { |
| + t.Fatal("native start ignored the web's spent budget", w.Code) |
| + } |
| + app = newNativeApp(t) |
| + for range 5 { |
| + newDevice(t).start(t, app, "shared@example.invalid") |
| + } |
| + if rec := signIn(t, app, "shared@example.invalid"); rec.Code != http.StatusTooManyRequests { |
| + t.Fatal("the web ignored native starts", rec.Code) |
| + } |
| +} |
| + |
| +// §13 Codes: per-IP-bucket live starts, IPv6 by /64, and 503 when full. |
| +func TestNativeCodeLiveStartLimits(t *testing.T) { |
| + app := newNativeApp(t) |
| + for i := range 20 { |
| + newDevice(t).start(t, app, fmt.Sprintf("ip%d@example.invalid", i)) |
| + } |
| + if _, err := app.db.Writer().Exec("DELETE FROM home_id_native_buckets"); err != nil { |
| + t.Fatal(err) |
| + } |
| + d := newDevice(t) |
| + w := d.call(t, app, nativePrefix+"/code/start", map[string]string{"email": "ip-last@example.invalid", "device_key": d.public(), "platform": "macos"}, "") |
| + if w.Code != 429 { |
| + t.Fatal("a 21st live start from one IP bucket", w.Code) |
| + } |
| + if w := d.call(t, app, nativePrefix+"/code/start", map[string]string{"email": "ip-last@example.invalid", "device_key": d.public(), "platform": "macos"}, "", proofOpts{ip: "198.51.100.7:1"}); w.Code != 202 { |
| + t.Fatal("another IP was refused", w.Code) |
| + } |
| + a := httpRequestFrom("[2001:db8:1:2:aaaa::1]:1") |
| + b := httpRequestFrom("[2001:db8:1:2:bbbb::9]:1") |
| + c := httpRequestFrom("[2001:db8:1:3::1]:1") |
| + if nativeIPBucket(a) != nativeIPBucket(b) || nativeIPBucket(a) == nativeIPBucket(c) || nativeIPBucket(httpRequestFrom("192.0.2.1:1")) != "192.0.2.1" { |
| + t.Fatal("IP buckets", nativeIPBucket(a), nativeIPBucket(b), nativeIPBucket(c)) |
| + } |
| + |
| + // Full: new starts get 503, an existing start still verifies. |
| + app = newNativeApp(t) |
| + keep := newDevice(t) |
| + start := keep.start(t, app, "keep@example.invalid") |
| + code := lastCode(t, app) |
| + if nativeLiveStarts != 10000 { |
| + t.Fatal("the live-start table's size moved", nativeLiveStarts) |
| + } |
| + prev := nativeLiveStarts |
| + nativeLiveStarts = 100 |
| + t.Cleanup(func() { nativeLiveStarts = prev }) |
| + tx, err := app.db.Writer().Begin() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for i := range nativeLiveStarts - 1 { |
| + if _, err := tx.Exec("INSERT INTO home_id_native_starts VALUES(?,x'00',?,?,?,'',?,1,0,0,?)", fmt.Sprint("fill", i), fmt.Sprint("b", i), "k", "macos", "m", int64(1<<40)); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if err := tx.Commit(); err != nil { |
| + t.Fatal(err) |
| + } |
| + d = newDevice(t) |
| + w = d.call(t, app, nativePrefix+"/code/start", map[string]string{"email": "late@example.invalid", "device_key": d.public(), "platform": "macos"}, "") |
| + if w.Code != 503 || decodeReply(t, w)["error"] != "full" { |
| + t.Fatal("a full table took a start", w.Code, w.Body.String()) |
| + } |
| + if v := keep.verify(t, app, start, code); v.Code != 200 { |
| + t.Fatal("a full table refused an existing start", v.Code) |
| + } |
| + // The web's link sign-in is unaffected. |
| + if rec := signIn(t, app, "web@example.invalid"); rec.Code != http.StatusSeeOther { |
| + t.Fatal("a full native table blocked the web", rec.Code) |
| + } |
| +} |
| + |
| +func httpRequestFrom(addr string) *http.Request { |
| + r, _ := http.NewRequest("POST", Origin, nil) |
| + r.RemoteAddr = addr |
| + return r |
| +} |
| + |
| +// §13 Codes: no grant from a code alone on an enrolled account. |
| +func TestNativeCodeOnEnrolledAccountNeedsPasskey(t *testing.T) { |
| + t.Parallel() |
| + app := newNativeApp(t) |
| + session := signInFully(t, app, sealtest.CanaryAddress) |
| + enrol(t, app, session) |
| + d := newDevice(t) |
| + start := d.start(t, app, sealtest.CanaryAddress) |
| + w := d.verify(t, app, start, lastCode(t, app)) |
| + out := decodeReply(t, w) |
| + if w.Code != 200 || out["grant"] != nil || out["pending"] == nil || fmt.Sprint(out["factor"]) != "[passkey]" { |
| + t.Fatal("a code alone opened an enrolled account", w.Code, w.Body.String()) |
| + } |
| + if n := count(t, app, "SELECT count(*) FROM home_id_grants"); n != 0 { |
| + t.Fatal("a grant row exists", n) |
| + } |
| +} |
| + |
| +// §13 Codes: no address and no code in any log line, the failure paths |
| +// included. |
| +func TestNativeCodeNothingInLogs(t *testing.T) { |
| + t.Parallel() |
| + app := newNativeApp(t) |
| + var buf bytes.Buffer |
| + app.logger = slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelDebug})) |
| + d := newDevice(t) |
| + start := d.start(t, app, sealtest.CanaryAddress) |
| + code := lastCode(t, app) |
| + d.verify(t, app, start, "123456") |
| + d.call(t, app, nativePrefix+"/code/resend", map[string]string{"start": start}, "") |
| + d.verify(t, app, start, code) |
| + app.secrets.Mailer = failingMailer{} |
| + app.flow.Mailer = failingMailer{} |
| + e := newDevice(t) |
| + w := e.call(t, app, nativePrefix+"/code/start", map[string]string{"email": "other-" + sealtest.CanaryAddress, "device_key": e.public(), "platform": "macos"}, "") |
| + if w.Code != 503 { |
| + t.Fatal("failed mail answered", w.Code) |
| + } |
| + for _, needle := range []string{sealtest.CanaryAddress, url.QueryEscape(sealtest.CanaryAddress), code, start} { |
| + if strings.Contains(buf.String(), needle) || strings.Contains(w.Body.String(), needle) { |
| + t.Fatalf("%q reached a log line or an error", needle) |
| + } |
| + } |
| + if !strings.Contains(buf.String(), "native code delivery failed") { |
| + t.Fatal("the failure path did not run") |
| + } |
| + sealtest.AssertNoPlaintext(t, app.dbPath) |
| +} |
| + |
| +type failingMailer struct{} |
| + |
| +func (failingMailer) Send(context.Context, string, string, string) error { |
| + return errors.New("smtp down") |
| +} |
| + |
| +// Resend replaces the code, three sends at most, thirty seconds apart. |
| +func TestNativeCodeResend(t *testing.T) { |
| + t.Parallel() |
| + app := newNativeApp(t) |
| + d := newDevice(t) |
| + start := d.start(t, app, "r@example.invalid") |
| + first := lastCode(t, app) |
| + if w := d.call(t, app, nativePrefix+"/code/resend", map[string]string{"start": start}, ""); w.Code != 429 { |
| + t.Fatal("resend inside thirty seconds", w.Code) |
| + } |
| + for i := range 2 { |
| + if _, err := app.db.Writer().Exec("UPDATE home_id_native_starts SET last_send=last_send-31"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if w := d.call(t, app, nativePrefix+"/code/resend", map[string]string{"start": start}, ""); w.Code != 202 { |
| + t.Fatal("resend", i, w.Code, w.Body.String()) |
| + } |
| + } |
| + if _, err := app.db.Writer().Exec("UPDATE home_id_native_starts SET last_send=last_send-31"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if w := d.call(t, app, nativePrefix+"/code/resend", map[string]string{"start": start}, ""); w.Code != 429 { |
| + t.Fatal("a fourth send", w.Code) |
| + } |
| + latest := lastCode(t, app) |
| + if latest != first { |
| + if w := d.verify(t, app, start, first); w.Code == 200 { |
| + t.Fatal("a replaced code still worked") |
| + } |
| + } |
| + if w := d.verify(t, app, start, latest); w.Code != 200 { |
| + t.Fatal("the latest code failed", w.Code) |
| + } |
| + // A resend must be signed by the start's own key. |
| + start = d.start(t, app, "s@example.invalid") |
| + if _, err := app.db.Writer().Exec("UPDATE home_id_native_starts SET last_send=last_send-31"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if w := newDevice(t).call(t, app, nativePrefix+"/code/resend", map[string]string{"start": start}, ""); w.Code != 401 { |
| + t.Fatal("another key resent", w.Code) |
| + } |
| + if w := newDevice(t).verify(t, app, start, lastCode(t, app)); w.Code != 401 { |
| + t.Fatal("another key verified", w.Code) |
| + } |
| +} |
diff --git a/internal/home/native_grant_test.go b/internal/home/native_grant_test.go| new file mode 100644 |
| index 0000000..0378732 |
| --- /dev/null |
| +++ b/internal/home/native_grant_test.go |
| @@ -0,0 +1,355 @@ |
| +package home |
| + |
| +import ( |
| + "crypto/sha256" |
| + "encoding/base64" |
| + "errors" |
| + "fmt" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/home/handoff" |
| + "amadan.net/oficina/home/internal/home/sealtest" |
| +) |
| + |
| +const teamDocs = "https://blue.docs.oficina.works" |
| + |
| +// §13 Proof: every way a proof can be wrong is refused, and no jti is |
| +// recorded before the grant and the signature verify. |
| +func TestNativeProofRefusals(t *testing.T) { |
| + t.Parallel() |
| + app := newNativeApp(t) |
| + d := newDevice(t) |
| + grant, _ := d.signInByCode(t, app, "p@example.invalid") |
| + _, challenge := verifierFor(1) |
| + for name, o := range map[string]proofOpts{ |
| + "wrong key": {signer: newDevice(t)}, |
| + "skewed iat": {iat: time.Now().Unix() - 31}, |
| + "future iat": {iat: time.Now().Unix() + 31}, |
| + "wrong htu": {htu: Origin + nativePrefix + "/signout"}, |
| + "other host": {htu: "https://oficina.works" + nativePrefix + "/assert"}, |
| + "swapped body": {signedBody: []byte(`{"aud":"https://directory.example","challenge":"x"}`)}, |
| + "origin header": {headers: map[string]string{"Origin": Origin}}, |
| + "sec-fetch-site": {headers: map[string]string{"Sec-Fetch-Site": "none"}}, |
| + "malformed proof": {headers: map[string]string{"Oficina-Proof": "e30.AAAA"}}, |
| + } { |
| + w := d.assert(t, app, grant, teamDocs, challenge, o) |
| + if w.Code == 200 { |
| + t.Fatalf("%s: accepted", name) |
| + } |
| + if n := count(t, app, "SELECT count(*) FROM home_id_native_replay"); n != 0 { |
| + t.Fatalf("%s: a jti row before the proof verified", name) |
| + } |
| + } |
| + // An unknown or ended grant writes no jti either. |
| + if w := d.assert(t, app, strings.Repeat("A", 43), teamDocs, challenge); w.Code != 401 { |
| + t.Fatal("unknown grant", w.Code) |
| + } |
| + if n := count(t, app, "SELECT count(*) FROM home_id_native_replay"); n != 0 { |
| + t.Fatal("a jti row for an unknown grant") |
| + } |
| + // A 401 carries the server clock, and every answer a Date. |
| + w := d.assert(t, app, grant, teamDocs, challenge, proofOpts{iat: time.Now().Unix() - 100}) |
| + if w.Code != 401 || decodeReply(t, w)["now"] == nil || w.Header().Get("Date") == "" || w.Header().Get("Cache-Control") != "no-store" { |
| + t.Fatal("401 without now/Date", w.Code, w.Header()) |
| + } |
| + if w.Header().Get("Access-Control-Allow-Origin") != "" { |
| + t.Fatal("CORS on a native endpoint") |
| + } |
| +} |
| + |
| +// §13 Proof: a replayed jti is refused, also across a restart. |
| +func TestNativeProofReplay(t *testing.T) { |
| + t.Parallel() |
| + app := newNativeApp(t) |
| + d := newDevice(t) |
| + grant, _ := d.signInByCode(t, app, "r@example.invalid") |
| + _, challenge := verifierFor(2) |
| + o := proofOpts{jti: "replay-me-0123456789", iat: time.Now().Unix()} |
| + if w := d.assert(t, app, grant, teamDocs, challenge, o); w.Code != 200 { |
| + t.Fatal("first", w.Code, w.Body.String()) |
| + } |
| + if w := d.assert(t, app, grant, teamDocs, challenge, o); w.Code != 401 || decodeReply(t, w)["error"] != nativeProofRejected { |
| + t.Fatal("replay accepted", w.Code) |
| + } |
| + app = app.restart(t) |
| + if w := d.assert(t, app, grant, teamDocs, challenge, o); w.Code != 401 { |
| + t.Fatal("replay accepted after a restart", w.Code) |
| + } |
| +} |
| + |
| +// §13 Proof: the table fails closed when full, and each grant is limited to |
| +// 120 calls a minute. |
| +func TestNativeProofTableLimits(t *testing.T) { |
| + app := newNativeApp(t) |
| + d := newDevice(t) |
| + grant, _ := d.signInByCode(t, app, "l@example.invalid") |
| + _, challenge := verifierFor(3) |
| + for i := range nativeReplayPerMin { |
| + if w := d.assert(t, app, grant, teamDocs, challenge); w.Code != 200 { |
| + t.Fatal("call", i, w.Code) |
| + } |
| + } |
| + if w := d.assert(t, app, grant, teamDocs, challenge); w.Code != 429 { |
| + t.Fatal("call 121 in a minute", w.Code) |
| + } |
| + other := newDevice(t) |
| + grant2, _ := other.signInByCode(t, app, "m@example.invalid") |
| + if nativeReplayCap != 250000 { |
| + t.Fatal("the replay table's size moved", nativeReplayCap) |
| + } |
| + prev := nativeReplayCap |
| + nativeReplayCap = 200 |
| + t.Cleanup(func() { nativeReplayCap = prev }) |
| + tx, err := app.db.Writer().Begin() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for i := range nativeReplayCap { |
| + 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) |
| + } |
| + } |
| + if err := tx.Commit(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if w := other.assert(t, app, grant2, teamDocs, challenge); w.Code != 503 { |
| + t.Fatal("a full replay table admitted a proof", w.Code) |
| + } |
| +} |
| + |
| +// §13 Assert: the assertion is slice 1's v1 for the registered audience, |
| +// with the grant's auth_time and a nonce Home derived from the challenge. |
| +func TestNativeAssert(t *testing.T) { |
| + t.Parallel() |
| + app := newNativeApp(t) |
| + d := newDevice(t) |
| + grant, _ := d.signInByCode(t, app, sealtest.CanaryAddress) |
| + var authTime int64 |
| + app.db.Writer().QueryRow("SELECT auth_time FROM home_id_grants").Scan(&authTime) |
| + _, challenge := verifierFor(4) |
| + w := d.assert(t, app, grant, teamDocs, challenge) |
| + if w.Code != 200 { |
| + t.Fatal(w.Code, w.Body.String()) |
| + } |
| + token := decodeReply(t, w)["assertion"].(string) |
| + c := verifyAssertion(t, app, token, teamDocs) |
| + session := signInFully(t, app, sealtest.CanaryAddress) |
| + if c.Subject != subjectOf(t, app, session) || c.AuthTime != authTime || c.ExpiresAt-c.IssuedAt != 120 || c.Nonce != mustNativeNonce(t, challenge) { |
| + t.Fatalf("claims %+v", c) |
| + } |
| + // The nonce is derived, never the caller's: no challenge yields a nonce |
| + // equal to its own encoding, so a web nonce cannot be requested. |
| + if c.Nonce == base64.RawURLEncoding.EncodeToString(challenge[:16]) { |
| + t.Fatal("nonce is the challenge") |
| + } |
| + sum := sha256.Sum256(append([]byte("oficina-id/native/v1\x00"), challenge...)) |
| + if c.Nonce != base64.RawURLEncoding.EncodeToString(sum[:16]) { |
| + t.Fatal("nonce derivation drifted from the wire notes") |
| + } |
| + // Unregistered, near-miss and operator audiences are refused. |
| + for _, aud := range []string{"https://evil.example", teamDocs + "/", "https://BLUE.docs.oficina.works", "https://green.docs.oficina.works", operatorConfirmConsumer} { |
| + if w := d.assert(t, app, grant, aud, challenge); w.Code != 400 { |
| + t.Fatal("unregistered audience", aud, w.Code) |
| + } |
| + } |
| + if w := d.call(t, app, nativePrefix+"/assert", map[string]string{"aud": teamDocs, "challenge": "short"}, grant); w.Code != 400 { |
| + t.Fatal("short challenge", w.Code) |
| + } |
| + if w := d.call(t, app, nativePrefix+"/assert", map[string]string{"aud": teamDocs, "challenge": base64.RawURLEncoding.EncodeToString(challenge), "nonce": "chosen"}, grant); w.Code != 400 { |
| + t.Fatal("a caller-chosen nonce field was accepted", w.Code) |
| + } |
| + sealtest.AssertNoPlaintext(t, app.dbPath) |
| +} |
| + |
| +// §13 Assert: mintPolicy is one function shared with /authorize. |
| +func TestNativeMintPolicyShared(t *testing.T) { |
| + refused := errors.New("refused") |
| + prev := mintPolicy |
| + var seen []string |
| + mintPolicy = func(consumer, method string) error { seen = append(seen, consumer+"/"+method); return refused } |
| + t.Cleanup(func() { mintPolicy = prev }) |
| + |
| + p := newExchangePair(t) |
| + d := newDevice(t) |
| + grant, _ := d.signInByCode(t, p.credential, "policy@example.invalid") |
| + _, challenge := verifierFor(5) |
| + if w := d.assert(t, p.credential, grant, directoryOrigin, challenge); w.Code != 403 { |
| + t.Fatal("native assert ignored mintPolicy", w.Code) |
| + } |
| + session := signInFully(t, p.credential, "policy@example.invalid") |
| + _, intent := p.start(t) |
| + r := exchangeRequest(p.credential.App, "POST", Origin+"/authorize/resume", Origin, nil, intent, session) |
| + if strings.Contains(r.Body.String(), `name="assertion"`) { |
| + t.Fatal("/authorize ignored mintPolicy") |
| + } |
| + if fmt.Sprint(seen) != "[directory/email directory/magiclink]" { |
| + t.Fatal("policy inputs", seen) |
| + } |
| + // And both call sites name it: a second rule cannot appear beside it. |
| + for _, f := range []string{"exchange.go", "native_assert.go"} { |
| + found := false |
| + for _, g := range grepPackage(t, "mintPolicy(") { |
| + found = found || g == f |
| + } |
| + if !found { |
| + t.Fatal("mintPolicy not called from", f) |
| + } |
| + } |
| +} |
| + |
| +// §3: a 21st grant ends the least recently used; lapsed grants expire. |
| +func TestNativeGrantLimitsAndExpiry(t *testing.T) { |
| + t.Parallel() |
| + app := newNativeApp(t) |
| + 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) |
| + } |
| + } |
| + 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 { |
| + t.Fatal("live grants", n) |
| + } |
| + // Absolute and idle expiry. |
| + app2 := newNativeApp(t) |
| + for i, q := range []string{"UPDATE home_id_grants SET expires_at=1", "UPDATE home_id_grants SET last_used_day=?"} { |
| + e := newDevice(t) |
| + g, _ := e.signInByCode(t, app2, fmt.Sprintf("exp-%d@example.invalid", i)) |
| + args := []any{} |
| + if strings.Contains(q, "last_used_day") { |
| + args = append(args, idleCutoff(time.Now().Unix())) |
| + } |
| + if _, err := app2.db.Writer().Exec(q+" WHERE grant_hash='"+nativeHash(g)+"'", args...); err != nil { |
| + t.Fatal(err) |
| + } |
| + _, challenge := verifierFor(6) |
| + if w := e.assert(t, app2, g, teamDocs, challenge); w.Code != 401 { |
| + t.Fatal("expired grant used", q, w.Code) |
| + } |
| + if ended, reason := grantState(t, app2, g); !ended || reason != "expiry" { |
| + t.Fatal("expired grant not ended", reason) |
| + } |
| + } |
| + // A grant used yesterday is still live. |
| + e := newDevice(t) |
| + g, _ := e.signInByCode(t, app2, "fresh@example.invalid") |
| + if _, err := app2.db.Writer().Exec("UPDATE home_id_grants SET last_used_day=? WHERE grant_hash=?", dayOf(time.Now().Unix()-nativeGrantIdleDays*day), nativeHash(g)); err != nil { |
| + t.Fatal(err) |
| + } |
| + _, challenge := verifierFor(7) |
| + if w := e.assert(t, app2, g, teamDocs, challenge); w.Code != 200 { |
| + t.Fatal("a grant inside its idle window was refused", w.Code) |
| + } |
| +} |
| + |
| +// §10: the device's own sign-out ends its grant; a late, pre-signed one is |
| +// refused by the 30-second window. |
| +func TestNativeSignout(t *testing.T) { |
| + t.Parallel() |
| + app := newNativeApp(t) |
| + d := newDevice(t) |
| + grant, _ := d.signInByCode(t, app, "s@example.invalid") |
| + late := d.call(t, app, nativePrefix+"/signout", map[string]string{}, grant, proofOpts{iat: time.Now().Unix() - 40}) |
| + if late.Code != 401 { |
| + t.Fatal("late sign-out accepted", late.Code) |
| + } |
| + if w := d.call(t, app, nativePrefix+"/signout", map[string]string{}, grant); w.Code != 200 { |
| + t.Fatal("signout", w.Code, w.Body.String()) |
| + } |
| + if ended, reason := grantState(t, app, grant); !ended || reason != "signout" { |
| + t.Fatal("grant", reason) |
| + } |
| + _, challenge := verifierFor(8) |
| + if w := d.assert(t, app, grant, teamDocs, challenge); w.Code != 401 { |
| + t.Fatal("a signed-out grant asserted", w.Code) |
| + } |
| +} |
| + |
| +// The derivation's shared vector (verifier = base64url of 0x00..0x1f). The |
| +// challenge is SHA-256 of the verifier's base64url STRING, the convention the |
| +// coordinator fixed for all three halves (Home, connect, the Swift client). |
| +func TestNativeNonceVector(t *testing.T) { |
| + t.Parallel() |
| + raw := make([]byte, 32) |
| + for i := range raw { |
| + raw[i] = byte(i) |
| + } |
| + verifier := base64.RawURLEncoding.EncodeToString(raw) |
| + if verifier != "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8" { |
| + t.Fatal(verifier) |
| + } |
| + challenge := sha256.Sum256([]byte(verifier)) |
| + if c := base64.RawURLEncoding.EncodeToString(challenge[:]); c != "6oZqdX5MOLq_qBJ8vppAnT4fk6AP8UiP9zX8-Rev_9A" { |
| + t.Fatal("challenge", c) |
| + } |
| + if n := mustNativeNonce(t, challenge[:]); n != "ZVVVj2zbBfhkAIwAOKNylg" { |
| + t.Fatal("nonce", n) |
| + } |
| + // And handoff's, which assert and every exchange use, agrees. |
| + c, ok := handoff.NativeChallenge(verifier) |
| + if n, _ := handoff.NativeNonce(c); !ok || n != "ZVVVj2zbBfhkAIwAOKNylg" { |
| + t.Fatal("handoff derivation", c, n) |
| + } |
| +} |
| + |
| +// The two 401 markers: the client wipes the identity only on grant_ended. |
| +func TestNativeUnauthorizedMarkers(t *testing.T) { |
| + t.Parallel() |
| + app := newNativeApp(t) |
| + d := newDevice(t) |
| + grant, _ := d.signInByCode(t, app, "markers@example.invalid") |
| + _, challenge := verifierFor(40) |
| + for name, o := range map[string]proofOpts{"skew": {iat: time.Now().Unix() - 60}, "key": {signer: newDevice(t)}} { |
| + w := d.assert(t, app, grant, teamDocs, challenge, o) |
| + if out := decodeReply(t, w); w.Code != 401 || out["error"] != nativeProofRejected || out["now"] == nil { |
| + t.Fatal(name, w.Code, out) |
| + } |
| + } |
| + if w := d.assert(t, app, strings.Repeat("A", 43), teamDocs, challenge); decodeReply(t, w)["error"] != nativeGrantEnded { |
| + t.Fatal("unknown grant", w.Body.String()) |
| + } |
| + if w := d.call(t, app, nativePrefix+"/signout", map[string]string{}, grant); w.Code != 200 { |
| + t.Fatal(w.Code) |
| + } |
| + w := d.assert(t, app, grant, teamDocs, challenge) |
| + if out := decodeReply(t, w); w.Code != 401 || out["error"] != nativeGrantEnded || out["now"] == nil { |
| + t.Fatal("ended grant", w.Code, out) |
| + } |
| + // A gone start is 410 expired, on verify and resend alike. |
| + start := d.start(t, app, "gone@example.invalid") |
| + if _, err := app.db.Writer().Exec("UPDATE home_id_native_starts SET expires_at=1"); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, path := range []string{"/code/verify", "/code/resend"} { |
| + body := map[string]string{"start": start} |
| + if path == "/code/verify" { |
| + body["code"] = "123456" |
| + } |
| + if w := d.call(t, app, nativePrefix+path, body, ""); w.Code != 410 || decodeReply(t, w)["error"] != "expired" { |
| + t.Fatal(path, w.Code, w.Body.String()) |
| + } |
| + } |
| +} |
| + |
| +func mustNativeNonce(t *testing.T, challenge []byte) string { |
| + t.Helper() |
| + n, ok := handoff.NativeNonce(base64.RawURLEncoding.EncodeToString(challenge)) |
| + if !ok { |
| + t.Fatal("challenge") |
| + } |
| + return n |
| +} |
diff --git a/internal/home/native_helpers_test.go b/internal/home/native_helpers_test.go| new file mode 100644 |
| index 0000000..acfb89a |
| --- /dev/null |
| +++ b/internal/home/native_helpers_test.go |
| @@ -0,0 +1,241 @@ |
| +package home |
| + |
| +import ( |
| + "crypto/rand" |
| + "crypto/sha256" |
| + "encoding/base64" |
| + "encoding/hex" |
| + "encoding/json" |
| + "net/http" |
| + "net/http/httptest" |
| + "regexp" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/rastrillo/rastrillo/assertion" |
| + assertioncrypto "amadan.net/rastrillo/rastrillo/crypto" |
| +) |
| + |
| +// newNativeApp is a credential-role app: the native endpoints mount only |
| +// there. Its consumers are the directory and one team's Docs. |
| +func newNativeApp(t *testing.T) *testApp { |
| + t.Helper() |
| + app := newTestApp(t) |
| + key, err := assertioncrypto.Generate() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + sum := sha256.Sum256(key.SignPub()) |
| + kid := hex.EncodeToString(sum[:]) |
| + app.runtime = &Runtime{role: "credential", origins: app.origins, secrets: app.secrets, signer: key, keyID: kid, keys: map[string][]byte{kid: key.SignPub()}, consumers: map[string]string{"directory": directoryOrigin, "team_docs": "https://blue.docs.oficina.works"}} |
| + return app |
| +} |
| + |
| +// restart builds a fresh App on the same database and keys: every in-memory |
| +// budget is new, everything persistent is not. |
| +func (app *testApp) restart(t *testing.T) *testApp { |
| + t.Helper() |
| + next, err := NewWithOrigins(app.secrets, app.db, quietLogger(), app.origins) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + next.flow.Classifier.LookupTXT = app.flow.Classifier.LookupTXT |
| + next.runtime = app.runtime |
| + return &testApp{App: next, mailer: app.mailer, db: app.db, dbPath: app.dbPath} |
| +} |
| + |
| +// device is a native app's device key. |
| +type device struct { |
| + key *assertioncrypto.Keypair |
| + platform string |
| +} |
| + |
| +func newDevice(t *testing.T) *device { |
| + t.Helper() |
| + k, err := assertioncrypto.Generate() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return &device{key: k, platform: "macos"} |
| +} |
| +func (d *device) public() string { return base64.RawURLEncoding.EncodeToString(d.key.SignPub()) } |
| + |
| +// proofOpts tampers with one part of a proof. |
| +type proofOpts struct { |
| + iat int64 |
| + htu, jti string |
| + signedBody []byte // sign over this body instead of the one sent |
| + signer *device |
| + headers map[string]string |
| + ip string |
| +} |
| + |
| +func (d *device) proof(t *testing.T, path string, body []byte, o proofOpts) string { |
| + t.Helper() |
| + signed := body |
| + if o.signedBody != nil { |
| + signed = o.signedBody |
| + } |
| + bh := sha256.Sum256(signed) |
| + iat := time.Now().Unix() |
| + if o.iat != 0 { |
| + iat = o.iat |
| + } |
| + htu := Origin + path |
| + if o.htu != "" { |
| + htu = o.htu |
| + } |
| + jti := o.jti |
| + if jti == "" { |
| + r := make([]byte, 16) |
| + if _, err := rand.Read(r); err != nil { |
| + t.Fatal(err) |
| + } |
| + jti = base64.RawURLEncoding.EncodeToString(r) |
| + } |
| + payload, err := json.Marshal(map[string]any{"v": 1, "htm": "POST", "htu": htu, "iat": iat, "jti": jti, "bh": base64.RawURLEncoding.EncodeToString(bh[:])}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + signer := d |
| + if o.signer != nil { |
| + signer = o.signer |
| + } |
| + sig, err := assertioncrypto.Sign(signer.key, nativeProofContext, payload) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return base64.RawURLEncoding.EncodeToString(payload) + "." + base64.RawURLEncoding.EncodeToString(sig) |
| +} |
| + |
| +// call drives one native endpoint as the app would. |
| +func (d *device) call(t *testing.T, app *testApp, path string, body any, grant string, o ...proofOpts) *httptest.ResponseRecorder { |
| + t.Helper() |
| + var opts proofOpts |
| + if len(o) > 0 { |
| + opts = o[0] |
| + } |
| + b, err := json.Marshal(body) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + req := httptest.NewRequest("POST", Origin+path, strings.NewReader(string(b))) |
| + req.Header.Set("Content-Type", "application/json") |
| + req.Header.Set("Oficina-Proof", d.proof(t, path, b, opts)) |
| + if grant != "" { |
| + req.Header.Set("Authorization", "OficinaID "+grant) |
| + } |
| + req.RemoteAddr = "192.0.2.10:4444" |
| + if opts.ip != "" { |
| + req.RemoteAddr = opts.ip |
| + } |
| + for k, v := range opts.headers { |
| + req.Header.Set(k, v) |
| + } |
| + w := httptest.NewRecorder() |
| + app.Router().ServeHTTP(w, req) |
| + return w |
| +} |
| + |
| +func decodeReply(t *testing.T, w *httptest.ResponseRecorder) map[string]any { |
| + t.Helper() |
| + var out map[string]any |
| + if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil { |
| + t.Fatalf("not JSON (%d): %s", w.Code, w.Body.String()) |
| + } |
| + return out |
| +} |
| + |
| +func (d *device) start(t *testing.T, app *testApp, email string) string { |
| + t.Helper() |
| + w := d.call(t, app, nativePrefix+"/code/start", map[string]string{"email": email, "device_key": d.public(), "platform": d.platform}, "") |
| + if w.Code != http.StatusAccepted { |
| + t.Fatalf("start: %d %s", w.Code, w.Body.String()) |
| + } |
| + return decodeReply(t, w)["start"].(string) |
| +} |
| + |
| +var codeLine = regexp.MustCompile(`Your Oficina ID code is (\d{6})`) |
| + |
| +func lastCode(t *testing.T, app *testApp) string { |
| + t.Helper() |
| + m, ok := app.mailer.last() |
| + if !ok { |
| + t.Fatal("no mail") |
| + } |
| + got := codeLine.FindStringSubmatch(m.Body) |
| + if got == nil { |
| + t.Fatal("no code in mail") |
| + } |
| + return got[1] |
| +} |
| + |
| +func (d *device) verify(t *testing.T, app *testApp, start, code string) *httptest.ResponseRecorder { |
| + t.Helper() |
| + return d.call(t, app, nativePrefix+"/code/verify", map[string]string{"start": start, "code": code}, "") |
| +} |
| + |
| +// signInByCode runs the whole code sign-in and returns the grant token. |
| +func (d *device) signInByCode(t *testing.T, app *testApp, email string) (grant, identityID string) { |
| + t.Helper() |
| + start := d.start(t, app, email) |
| + w := d.verify(t, app, start, lastCode(t, app)) |
| + out := decodeReply(t, w) |
| + if w.Code != 200 || out["grant"] == nil { |
| + t.Fatalf("verify: %d %s", w.Code, w.Body.String()) |
| + } |
| + return out["grant"].(string), out["identity_id"].(string) |
| +} |
| + |
| +func (d *device) assert(t *testing.T, app *testApp, grant, aud string, challenge []byte, o ...proofOpts) *httptest.ResponseRecorder { |
| + t.Helper() |
| + return d.call(t, app, nativePrefix+"/assert", map[string]string{"aud": aud, "challenge": base64.RawURLEncoding.EncodeToString(challenge)}, grant, o...) |
| +} |
| + |
| +func grantState(t *testing.T, app *testApp, grant string) (ended bool, reason string) { |
| + t.Helper() |
| + var e *int64 |
| + var why *string |
| + if err := app.db.Writer().QueryRow("SELECT ended_at,end_reason FROM home_id_grants WHERE grant_hash=?", nativeHash(grant)).Scan(&e, &why); err != nil { |
| + t.Fatal(err) |
| + } |
| + if why != nil { |
| + reason = *why |
| + } |
| + return e != nil, reason |
| +} |
| + |
| +func count(t *testing.T, app *testApp, query string, args ...any) int { |
| + t.Helper() |
| + var n int |
| + if err := app.db.Writer().QueryRow(query, args...).Scan(&n); err != nil { |
| + t.Fatal(err) |
| + } |
| + return n |
| +} |
| + |
| +// verifierFor is a native client's verifier and challenge: SHA-256 of the |
| +// verifier's base64url string. |
| +func verifierFor(seed byte) (verifier string, challenge []byte) { |
| + raw := make([]byte, 32) |
| + for i := range raw { |
| + raw[i] = seed + byte(i) |
| + } |
| + verifier = base64.RawURLEncoding.EncodeToString(raw) |
| + sum := sha256.Sum256([]byte(verifier)) |
| + return verifier, sum[:] |
| +} |
| + |
| +func verifyAssertion(t *testing.T, app *testApp, token, aud string) assertion.Claims { |
| + t.Helper() |
| + v, err := assertion.NewVerifier(Origin, aud, app.runtime.keys) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + c, err := v.Verify(token, time.Now()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return c |
| +} |
diff --git a/internal/home/native_logs_test.go b/internal/home/native_logs_test.go| new file mode 100644 |
| index 0000000..0509ebc |
| --- /dev/null |
| +++ b/internal/home/native_logs_test.go |
| @@ -0,0 +1,66 @@ |
| +package home |
| + |
| +import ( |
| + "log" |
| + "log/slog" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/home/internal/home/logtest" |
| +) |
| + |
| +// TestNoContentInLogsNative is gate 9 extended to the native endpoints (§4: |
| +// "Gates 1, 2 and 9 extend to this table"). TestNoContentInLogs walks the |
| +// legacy role's router, where none of these mount, and its app logs to a |
| +// discarded logger; this one captures both the app's logger and the |
| +// default, drives a full code sign-in and assert with a canary address, |
| +// then sends canary-laden garbage to every native route on both origins. |
| +func TestNoContentInLogsNative(t *testing.T) { |
| + rec := logtest.NewRecorder() |
| + prevLogger, prevWriter, prevFlags := slog.Default(), log.Writer(), log.Flags() |
| + slog.SetDefault(slog.New(rec.Handler())) |
| + t.Cleanup(func() { |
| + slog.SetDefault(prevLogger) |
| + log.SetOutput(prevWriter) |
| + log.SetFlags(prevFlags) |
| + }) |
| + |
| + f := newMountedChooser(t) |
| + app := f.p.credential |
| + app.logger = slog.New(rec.Handler()) |
| + f.p.directory.logger = slog.New(rec.Handler()) |
| + address := strings.ToLower(logtest.Canaries[0]) |
| + |
| + d := newDevice(t) |
| + grant, _ := d.signInByCode(t, app, address) |
| + verifier, challenge := verifierFor(30) |
| + w := d.assert(t, app, grant, directoryOrigin, challenge) |
| + directoryCall(t, f, "POST", nativeExchangePath, exchangeBody(decodeReply(t, w)["assertion"].(string), verifier), nil, nil) |
| + start := d.start(t, app, address) |
| + d.verify(t, app, start, "000000") |
| + app.secrets.Mailer = failingMailer{} |
| + e := newDevice(t) |
| + if w := e.call(t, app, nativePrefix+"/code/start", map[string]string{"email": address, "device_key": e.public(), "platform": "ios"}, ""); w.Code != 503 { |
| + t.Fatal("undeliverable start", w.Code) |
| + } |
| + |
| + body := `{"email":"` + address + `","device_key":"` + logtest.Canaries[1] + `","platform":"` + logtest.Canaries[2] + `","start":"` + logtest.Canaries[1] + `","code":"` + logtest.Canaries[2] + `","pending":"` + logtest.Canaries[1] + `","aud":"https://` + logtest.Canaries[1] + `.example","challenge":"` + logtest.Canaries[2] + `"}` |
| + for _, path := range []string{"/code/start", "/code/resend", "/code/verify", "/passkey/begin", "/passkey/finish", "/assert", "/signout"} { |
| + r := httptest.NewRequest("POST", Origin+nativePrefix+path, strings.NewReader(body)) |
| + r.Header.Set("Content-Type", "application/json") |
| + r.Header.Set("Oficina-Proof", logtest.Canaries[0]+"."+logtest.Canaries[1]) |
| + r.Header.Set("Authorization", "OficinaID "+logtest.Canaries[2]) |
| + r.Header.Set("X-Forwarded-For", logtest.Canaries[0]) |
| + app.Router().ServeHTTP(httptest.NewRecorder(), r) |
| + } |
| + for _, path := range []string{nativeExchangePath, nativeDirectorySignout, nativeTeamsPath} { |
| + method := "POST" |
| + if path == nativeTeamsPath { |
| + method = "GET" |
| + } |
| + directoryCall(t, f, method, path, body, &http.Cookie{Name: f.p.directory.sessions.CookieName(), Value: logtest.Canaries[1]}, map[string]string{"X-Forwarded-For": logtest.Canaries[0]}) |
| + } |
| + rec.AssertNoContent(t) |
| +} |
diff --git a/internal/home/native_passkey.go b/internal/home/native_passkey.go| new file mode 100644 |
| index 0000000..f0af7ea |
| --- /dev/null |
| +++ b/internal/home/native_passkey.go |
| @@ -0,0 +1,308 @@ |
| +package home |
| + |
| +import ( |
| + "database/sql" |
| + "encoding/base64" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "net/http" |
| + |
| + "amadan.net/rastrillo/rastrillo/webauthn" |
| +) |
| + |
| +// Native passkey sign-in (§5). The app runs the platform ceremony against |
| +// RP id.oficina.works; Home verifies it exactly as the web door does — the |
| +// same RP, origin, user-verification and person-binding checks — and mints a |
| +// 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 |
| +// the key that start was made with. The challenge is single-use, lives five |
| +// minutes, is bound to the device key and counts within home_id_ceremonies. |
| +func (a *App) nativePasskeyBegin(w http.ResponseWriter, r *http.Request) { |
| + body, ok := nativeIntake(w, r) |
| + if !ok { |
| + return |
| + } |
| + var in struct { |
| + DeviceKey string `json:"device_key,omitzero"` |
| + Platform string `json:"platform,omitzero"` |
| + Pending string `json:"pending,omitzero"` |
| + } |
| + if !decodeNative(body, &in) || in.DeviceKey == "" || !nativePlatforms[in.Platform] { |
| + nativeFail(w, http.StatusBadRequest, "request") |
| + return |
| + } |
| + tx, now, err := a.idTransaction(r.Context()) |
| + if err != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + defer tx.Rollback() |
| + if sweepCodes(tx, now) != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + subject, key, platform, pendingHash := "", in.DeviceKey, in.Platform, "" |
| + if in.Pending != "" { |
| + if _, ok := decodeB64(in.Pending, 32); !ok { |
| + nativeFail(w, http.StatusBadRequest, "pending") |
| + return |
| + } |
| + pendingHash = nativeHash(in.Pending) |
| + if tx.QueryRow("SELECT person_ref,device_key,platform FROM home_id_native_pending WHERE pending_hash=? AND expires_at>?", pendingHash, now).Scan(&subject, &key, &platform) != nil { |
| + nativeFail(w, http.StatusGone, "expired") |
| + return |
| + } |
| + // The pending is bound to its start's key; the proof below is |
| + // checked against that key, never the one in the body. |
| + if key != in.DeviceKey { |
| + nativeUnauthorized(w, nativeProofRejected) |
| + return |
| + } |
| + } |
| + if !a.nativePreGrant(r, body, key, now) { |
| + nativeUnauthorized(w, nativeProofRejected) |
| + return |
| + } |
| + if ip := nativeIPBucket(r); ip != "" { |
| + 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 |
| + } |
| + } |
| + // 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 |
| + } |
| + } |
| + // 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 |
| + } |
| + challenge, err := webauthn.NewChallenge() |
| + if err != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + id := hex.EncodeToString(challenge) |
| + if _, err = tx.Exec("INSERT INTO home_id_ceremonies VALUES (?,?,?,?,?)", id, binding, subject, nativeCeremonyPurpose, now+300); err != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + if _, err = tx.Exec("INSERT INTO home_id_native_ceremonies VALUES (?,?,?,?,?)", id, key, platform, pendingHash, now+300); err != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + credentials := []string{} |
| + if subject != "" { |
| + rows, err := tx.Query("SELECT id FROM passkey_credentials WHERE subject=? ORDER BY id LIMIT 100", subject) |
| + if err != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + for rows.Next() { |
| + var hexID string |
| + if rows.Scan(&hexID) != nil { |
| + rows.Close() |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + raw, err := hex.DecodeString(hexID) |
| + if err != nil { |
| + rows.Close() |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + credentials = append(credentials, base64.RawURLEncoding.EncodeToString(raw)) |
| + } |
| + err = rows.Err() |
| + rows.Close() |
| + if err != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + } |
| + if tx.Commit() != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + nativeReply(w, http.StatusOK, map[string]any{"challenge": base64.RawURLEncoding.EncodeToString(challenge), "rp_id": a.credentialHost, "credentials": credentials}) |
| +} |
| + |
| +// nativePasskeyFinish is POST passkey/finish {id, clientDataJSON, |
| +// authenticatorData, signature, device_key, platform?, userHandle?}: the web |
| +// door's finish fields plus the device key. device_key must be the key the |
| +// challenge was bound to at begin, and the proof is checked against that |
| +// bound key. platform was fixed at begin and userHandle decides nothing |
| +// (the credential id names the owner, as on the web); both are accepted |
| +// and ignored. It returns {grant, identity_id, auth_time}. |
| +func (a *App) nativePasskeyFinish(w http.ResponseWriter, r *http.Request) { |
| + body, ok := nativeIntake(w, r) |
| + if !ok { |
| + return |
| + } |
| + var in struct { |
| + idCeremony |
| + DeviceKey string `json:"device_key"` |
| + Platform string `json:"platform,omitzero"` |
| + UserHandle string `json:"userHandle,omitzero"` |
| + } |
| + if !decodeNative(body, &in) || in.Attestation != "" || in.DeviceKey == "" || len(in.UserHandle) > 128 || (in.Platform != "" && !nativePlatforms[in.Platform]) { |
| + nativeFail(w, http.StatusBadRequest, "request") |
| + return |
| + } |
| + cd, err := base64.RawURLEncoding.Strict().DecodeString(in.ClientData) |
| + if err != nil { |
| + nativeFail(w, http.StatusBadRequest, "request") |
| + return |
| + } |
| + var c struct { |
| + Challenge string `json:"challenge"` |
| + } |
| + if json.Unmarshal(cd, &c) != nil { |
| + nativeFail(w, http.StatusBadRequest, "request") |
| + return |
| + } |
| + challenge, err := base64.RawURLEncoding.Strict().DecodeString(c.Challenge) |
| + if err != nil || len(challenge) != 32 { |
| + nativeFail(w, http.StatusBadRequest, "request") |
| + return |
| + } |
| + id := hex.EncodeToString(challenge) |
| + tx, now, err := a.idTransaction(r.Context()) |
| + if err != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + defer tx.Rollback() |
| + var key, platform, pendingHash string |
| + if tx.QueryRow("SELECT device_key,platform,pending FROM home_id_native_ceremonies WHERE challenge=? AND expires_at>?", id, now).Scan(&key, &platform, &pendingHash) != nil { |
| + nativeFail(w, http.StatusBadRequest, "passkey") |
| + return |
| + } |
| + if key != in.DeviceKey || !a.nativePreGrant(r, body, key, now) { |
| + nativeUnauthorized(w, nativeProofRejected) |
| + return |
| + } |
| + // Consume the challenge first and keep it consumed whatever follows: a |
| + // challenge that survived a failed verification could be tried again. |
| + var subject string |
| + if tx.QueryRow("DELETE FROM home_id_ceremonies WHERE challenge=? AND browser_hash=? AND purpose=? AND expires_at>? RETURNING subject", id, nativeHash("native\x00"+key), nativeCeremonyPurpose, now).Scan(&subject) != nil { |
| + nativeFail(w, http.StatusBadRequest, "passkey") |
| + return |
| + } |
| + if _, err = tx.Exec("DELETE FROM home_id_native_ceremonies WHERE challenge=?", id); err != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + refuse := func() { |
| + if tx.Commit() != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + nativeFail(w, http.StatusBadRequest, "passkey") |
| + } |
| + credID, e1 := base64.RawURLEncoding.Strict().DecodeString(in.ID) |
| + ad, e2 := base64.RawURLEncoding.Strict().DecodeString(in.AuthData) |
| + sig, e3 := base64.RawURLEncoding.Strict().DecodeString(in.Signature) |
| + if e1 != nil || e2 != nil || e3 != nil { |
| + refuse() |
| + return |
| + } |
| + // A discoverable sign-in accepts only discoverable credentials, as the |
| + // web's direct sign-in does; a pending one accepts only that person's. |
| + query := "SELECT subject,public_key,sign_count FROM passkey_credentials WHERE id=?" |
| + if subject == "" { |
| + query += " AND id IN (SELECT credential_id FROM home_id_discoverable)" |
| + } |
| + var owner string |
| + cred := webauthn.Credential{ID: credID} |
| + if err = tx.QueryRow(query, hex.EncodeToString(credID)).Scan(&owner, &cred.PublicKey, &cred.SignCount); err != nil || (subject != "" && owner != subject) { |
| + refuse() |
| + return |
| + } |
| + next, err := a.idWebAuthn().Verify(cred, challenge, cd, ad, sig) |
| + if err != nil { |
| + refuse() |
| + return |
| + } |
| + if _, err = tx.Exec("UPDATE passkey_credentials SET sign_count=? WHERE id=?", next, hex.EncodeToString(credID)); err != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + method := "passkey" |
| + if pendingHash != "" { |
| + var person, first string |
| + err = tx.QueryRow("DELETE FROM home_id_native_pending WHERE pending_hash=? AND device_key=? AND expires_at>? RETURNING person_ref,method", pendingHash, key, now).Scan(&person, &first) |
| + if errors.Is(err, sql.ErrNoRows) || (err == nil && person != owner) { |
| + refuse() |
| + return |
| + } |
| + if err != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + method = first + "+passkey" |
| + } |
| + reply, err := a.mintGrant(tx, owner, key, platform, method, now, now) |
| + if err != nil || tx.Commit() != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + return |
| + } |
| + nativeReply(w, http.StatusOK, reply) |
| +} |
| + |
| +// The association file (§5). Static, application/json, no redirect, no |
| +// applinks and no account-authored text: it lists each App ID allowed to use |
| +// passkeys for id.oficina.works. Mac and iPhone share bundle IDs, so there |
| +// are five. |
| +const aasaPath = "/.well-known/apple-app-site-association" |
| + |
| +var nativeAppIDs = []string{ |
| + "9U4A84C4WK.works.oficina.calls", |
| + "9U4A84C4WK.works.oficina.docs", |
| + "9U4A84C4WK.works.oficina.sheets", |
| + "9U4A84C4WK.works.oficina.calendar", |
| + "9U4A84C4WK.works.oficina.memoria", |
| +} |
| + |
| +var aasaBody = func() []byte { |
| + b, err := json.Marshal(map[string]any{"webcredentials": map[string]any{"apps": nativeAppIDs}}) |
| + if err != nil { |
| + panic(err) |
| + } |
| + return b |
| +}() |
| + |
| +func (a *App) serveAASA(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Content-Type", "application/json") |
| + w.Header().Set("Cache-Control", "public, max-age=3600") |
| + w.Header().Set("X-Content-Type-Options", "nosniff") |
| + _, _ = w.Write(aasaBody) |
| +} |
diff --git a/internal/home/native_passkey_test.go b/internal/home/native_passkey_test.go| new file mode 100644 |
| index 0000000..f90db2d |
| --- /dev/null |
| +++ b/internal/home/native_passkey_test.go |
| @@ -0,0 +1,223 @@ |
| +package home |
| + |
| +import ( |
| + "encoding/base64" |
| + "encoding/json" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/home/internal/home/sealtest" |
| + "amadan.net/rastrillo/rastrillo/webauthn/authtest" |
| +) |
| + |
| +// finishBody is the web finish fields plus what the app adds. |
| +func finishBody(d *device, body map[string]string) map[string]string { |
| + body["device_key"] = d.public() |
| + body["platform"] = d.platform |
| + body["userHandle"] = "ignored-handle" |
| + return body |
| +} |
| + |
| +func nativeChallenge(t *testing.T, w *httptest.ResponseRecorder) ([]byte, []string) { |
| + t.Helper() |
| + if w.Code != 200 { |
| + t.Fatalf("begin: %d %s", w.Code, w.Body.String()) |
| + } |
| + var out struct { |
| + Challenge string `json:"challenge"` |
| + RPID string `json:"rp_id"` |
| + Credentials []string `json:"credentials"` |
| + } |
| + if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil || out.RPID != credentialHost { |
| + t.Fatal("begin reply", w.Body.String()) |
| + } |
| + raw, err := base64.RawURLEncoding.DecodeString(out.Challenge) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return raw, out.Credentials |
| +} |
| + |
| +// §5: "Sign in with a passkey" needs no email; Home verifies the platform |
| +// ceremony exactly as the web does and mints a passkey grant. |
| +func TestNativePasskeySignIn(t *testing.T) { |
| + t.Parallel() |
| + app := newNativeApp(t) |
| + session := signInFully(t, app, sealtest.CanaryAddress) |
| + key := enrol(t, app, session) |
| + d := newDevice(t) |
| + challenge, creds := nativeChallenge(t, d.call(t, app, nativePrefix+"/passkey/begin", map[string]string{"device_key": d.public(), "platform": "ios"}, "")) |
| + if len(creds) != 0 { |
| + t.Fatal("a discoverable begin named credentials") |
| + } |
| + zero := uint32(0) |
| + body := finishBody(d, assertionBody(key, challenge, authtest.Options{RPID: credentialHost, Origin: Origin, Count: &zero})) |
| + // Bound to the device key: another key cannot finish it. |
| + if w := newDevice(t).call(t, app, nativePrefix+"/passkey/finish", body, ""); w.Code != 401 { |
| + t.Fatal("another device finished the ceremony", w.Code) |
| + } |
| + // The body's device_key must be the bound key. |
| + swapped := map[string]string{} |
| + for k, v := range body { |
| + swapped[k] = v |
| + } |
| + swapped["device_key"] = newDevice(t).public() |
| + if w := d.call(t, app, nativePrefix+"/passkey/finish", swapped, ""); w.Code != 401 { |
| + t.Fatal("a body naming another key finished", w.Code) |
| + } |
| + w := d.call(t, app, nativePrefix+"/passkey/finish", body, "") |
| + out := decodeReply(t, w) |
| + if w.Code != 200 || out["grant"] == nil || out["identity_id"] != app.identityID(subjectOf(t, app, session)) { |
| + t.Fatal("finish", w.Code, w.Body.String()) |
| + } |
| + var method, platform string |
| + app.db.Writer().QueryRow("SELECT method,platform FROM home_id_grants").Scan(&method, &platform) |
| + if method != "passkey" || platform != "ios" { |
| + t.Fatal("grant", method, platform) |
| + } |
| + // Single use. |
| + if w := d.call(t, app, nativePrefix+"/passkey/finish", body, ""); w.Code == 200 { |
| + t.Fatal("a challenge was used twice") |
| + } |
| + sealtest.AssertNoPlaintext(t, app.dbPath) |
| +} |
| + |
| +// §5: the exact RP, origin and user-verification checks, and a failed |
| +// ceremony still spends its challenge. |
| +func TestNativePasskeyRejectsBadCeremonies(t *testing.T) { |
| + t.Parallel() |
| + for _, kind := range []string{"origin", "rp", "uv", "signature", "unknown"} { |
| + t.Run(kind, func(t *testing.T) { |
| + app := newNativeApp(t) |
| + session := signInFully(t, app, sealtest.CanaryAddress) |
| + key := enrol(t, app, session) |
| + d := newDevice(t) |
| + challenge, _ := nativeChallenge(t, d.call(t, app, nativePrefix+"/passkey/begin", map[string]string{"device_key": d.public(), "platform": "macos"}, "")) |
| + zero := uint32(0) |
| + opts := authtest.Options{RPID: credentialHost, Origin: Origin, Count: &zero} |
| + switch kind { |
| + case "origin": |
| + opts.Origin = "https://oficina.works" |
| + case "rp": |
| + opts.RPID = "oficina.works" |
| + case "uv": |
| + opts.Flags = authtest.FlagUserPresent |
| + case "signature": |
| + opts.CorruptSig = true |
| + case "unknown": |
| + key, _ = authtest.New() |
| + } |
| + w := d.call(t, app, nativePrefix+"/passkey/finish", finishBody(d, assertionBody(key, challenge, opts)), "") |
| + if w.Code == 200 { |
| + t.Fatal("bad ceremony minted a grant") |
| + } |
| + good := finishBody(d, assertionBody(key, challenge, authtest.Options{RPID: credentialHost, Origin: Origin, Count: &zero})) |
| + if w := d.call(t, app, nativePrefix+"/passkey/finish", good, ""); w.Code == 200 { |
| + t.Fatal("a refused challenge was reusable") |
| + } |
| + if n := count(t, app, "SELECT count(*) FROM home_id_grants"); n != 0 { |
| + t.Fatal("grant row after a refusal") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// §4 + §5: a code on an enrolled account, finished with that person's |
| +// passkey, mints an email+passkey grant; another person's passkey cannot. |
| +func TestNativePendingFinishedByPasskey(t *testing.T) { |
| + t.Parallel() |
| + app := newNativeApp(t) |
| + session := signInFully(t, app, sealtest.CanaryAddress) |
| + key := enrol(t, app, session) |
| + otherSession := signInFully(t, app, "other@example.invalid") |
| + otherKey := enrol(t, app, otherSession) |
| + d := newDevice(t) |
| + start := d.start(t, app, sealtest.CanaryAddress) |
| + pending := decodeReply(t, d.verify(t, app, start, lastCode(t, app)))["pending"].(string) |
| + e := newDevice(t) |
| + if w := e.call(t, app, nativePrefix+"/passkey/begin", map[string]string{"pending": pending, "device_key": e.public(), "platform": "macos"}, ""); w.Code != 401 { |
| + t.Fatal("another key began a pending", w.Code) |
| + } |
| + challenge, creds := nativeChallenge(t, d.call(t, app, nativePrefix+"/passkey/begin", map[string]string{"pending": pending, "device_key": d.public(), "platform": "macos"}, "")) |
| + if len(creds) != 1 || creds[0] != base64.RawURLEncoding.EncodeToString(key.CredID) { |
| + t.Fatal("pending begin is not restricted to the person", creds) |
| + } |
| + zero := uint32(0) |
| + if w := d.call(t, app, nativePrefix+"/passkey/finish", finishBody(d, assertionBody(otherKey, challenge, authtest.Options{RPID: credentialHost, Origin: Origin, Count: &zero})), ""); w.Code == 200 { |
| + t.Fatal("another person's passkey finished the pending") |
| + } |
| + challenge, _ = nativeChallenge(t, d.call(t, app, nativePrefix+"/passkey/begin", map[string]string{"pending": pending, "device_key": d.public(), "platform": "macos"}, "")) |
| + w := d.call(t, app, nativePrefix+"/passkey/finish", finishBody(d, assertionBody(key, challenge, authtest.Options{RPID: credentialHost, Origin: Origin, Count: &zero})), "") |
| + if w.Code != 200 || decodeReply(t, w)["grant"] == nil { |
| + t.Fatal("pending finish", w.Code, w.Body.String()) |
| + } |
| + var method string |
| + app.db.Writer().QueryRow("SELECT method FROM home_id_grants").Scan(&method) |
| + if method != "email+passkey" { |
| + t.Fatal("method", method) |
| + } |
| + if n := count(t, app, "SELECT count(*) FROM home_id_native_pending"); n != 0 { |
| + t.Fatal("pending survived") |
| + } |
| +} |
| + |
| +// §13 Domains: the association file's content, and nothing else in it. |
| +func TestNativeAssociationFile(t *testing.T) { |
| + t.Parallel() |
| + app := newNativeApp(t) |
| + r := httptest.NewRequest("GET", Origin+aasaPath, nil) |
| + w := httptest.NewRecorder() |
| + app.Router().ServeHTTP(w, r) |
| + if w.Code != 200 || w.Header().Get("Content-Type") != "application/json" || w.Header().Get("Location") != "" { |
| + t.Fatal("aasa", w.Code, w.Header()) |
| + } |
| + var got map[string]map[string][]string |
| + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { |
| + t.Fatal(err) |
| + } |
| + want := []string{"9U4A84C4WK.works.oficina.calls", "9U4A84C4WK.works.oficina.docs", "9U4A84C4WK.works.oficina.sheets", "9U4A84C4WK.works.oficina.calendar", "9U4A84C4WK.works.oficina.memoria"} |
| + if len(got) != 1 || len(got["webcredentials"]) != 1 || strings.Join(got["webcredentials"]["apps"], ",") != strings.Join(want, ",") { |
| + t.Fatal("aasa content", w.Body.String()) |
| + } |
| + if strings.Contains(w.Body.String(), "applinks") { |
| + t.Fatal("applinks in slice A") |
| + } |
| + // Only the credential origin serves it. |
| + r = httptest.NewRequest("GET", directoryOrigin+aasaPath, nil) |
| + w = httptest.NewRecorder() |
| + app.Router().ServeHTTP(w, r) |
| + if w.Code == 200 { |
| + t.Fatal("served on the directory host") |
| + } |
| +} |
| + |
| +// §4: every native endpoint refuses browser evidence and non-JSON, and |
| +// renders nothing. |
| +func TestNativeEndpointsRefuseBrowsers(t *testing.T) { |
| + t.Parallel() |
| + app := newNativeApp(t) |
| + for _, path := range []string{"/code/start", "/code/resend", "/code/verify", "/passkey/begin", "/passkey/finish", "/assert", "/signout"} { |
| + for _, h := range []map[string]string{{"Origin": Origin}, {"Sec-Fetch-Site": "same-origin"}, {"Content-Type": "application/x-www-form-urlencoded"}} { |
| + r := httptest.NewRequest("POST", Origin+nativePrefix+path, strings.NewReader("{}")) |
| + r.Header.Set("Content-Type", "application/json") |
| + for k, v := range h { |
| + r.Header.Set(k, v) |
| + } |
| + w := httptest.NewRecorder() |
| + app.Router().ServeHTTP(w, r) |
| + if w.Code < 400 || w.Header().Get("Content-Type") != "application/json" || w.Header().Get("Cache-Control") != "no-store" || strings.Contains(w.Body.String(), "<") { |
| + t.Fatal(path, h, w.Code, w.Header()) |
| + } |
| + } |
| + } |
| + // The legacy role mounts none of it. |
| + legacy := newTestApp(t) |
| + r := httptest.NewRequest("POST", Origin+nativePrefix+"/code/start", strings.NewReader("{}")) |
| + r.Header.Set("Content-Type", "application/json") |
| + w := httptest.NewRecorder() |
| + legacy.Router().ServeHTTP(w, r) |
| + if w.Code != 404 && w.Code != 405 { |
| + t.Fatal("legacy role served native", w.Code) |
| + } |
| +} |
diff --git a/internal/home/native_review_test.go b/internal/home/native_review_test.go| new file mode 100644 |
| index 0000000..81218f2 |
| --- /dev/null |
| +++ b/internal/home/native_review_test.go |
| @@ -0,0 +1,348 @@ |
| +package home |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "net/http" |
| + "regexp" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/home/handoff" |
| + "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) { |
| + t.Parallel() |
| + 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") |
| + } |
| + // Fable's re-review F1: a duplicate cookie name hides nothing. The |
| + // session middleware takes the first of two; both are stripped. |
| + junk := &http.Cookie{Name: native.Name, Value: "junk"} |
| + dup := exchangeRequest(f.p.directory, "GET", directoryOrigin+"/", "", nil, native, junk) |
| + if strings.Contains(dup.Body.String(), "Sign out all devices") || dup.Body.String() == browser.Body.String() { |
| + t.Fatal("a duplicated native cookie opened the directory") |
| + } |
| + if w := exchangeRequest(f.p.directory, "POST", directoryOrigin+signoutPath, directoryOrigin, map[string][]string{}, native, junk); w.Code == 303 { |
| + var n int |
| + f.p.directory.db.Writer().QueryRow("SELECT count(*) FROM sessions WHERE method=?", nativeSessionMethod).Scan(&n) |
| + if n == 0 { |
| + t.Fatal("a duplicated native cookie used the browser sign-out") |
| + } |
| + } |
| + // 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) { |
| + t.Parallel() |
| + 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) |
| + // Each end_reason on its own. |
| + for reason, want := range map[string]bool{"expiry": true, "lru": true, "enrolment": true, "signout": false, "all_devices": false, "revoke": false, "replacement": false} { |
| + if _, err := app.db.Writer().Exec("DELETE FROM home_id_grants"); err != nil { |
| + t.Fatal(err) |
| + } |
| + insert("g", 100, 300, reason) |
| + check(want) |
| + } |
| +} |
| + |
| +// 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) { |
| + t.Parallel() |
| + 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) { |
| + t.Parallel() |
| + 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) |
| + } |
| +} |
| + |
| +// Fable's re-review F2: an assertion minted before "Sign out all devices" |
| +// (up to 120 s earlier, by /authorize or native assert) buys no directory |
| +// session afterwards; one minted after does. |
| +func TestNativeSignOutAllRefusesEarlierAssertions(t *testing.T) { |
| + t.Parallel() |
| + f := newMountedChooser(t) |
| + cred := f.p.credential |
| + session := signInFully(t, cred, "early@example.invalid") |
| + person := subjectOf(t, cred, session) |
| + // Minted before the press: a browser handoff and a native assertion. |
| + pending, intent := f.p.start(t) |
| + browserToken, _ := f.p.mint(t, intent, session) |
| + d := newDevice(t) |
| + grant, _ := d.signInByCode(t, cred.restart(t), "early@example.invalid") |
| + verifier, challenge := verifierFor(60) |
| + nativeToken := decodeReply(t, d.assert(t, cred, grant, directoryOrigin, challenge))["assertion"].(string) |
| + |
| + // The press, one second later so the marks are strictly after. |
| + time.Sleep(1100 * time.Millisecond) |
| + press := exchangeRequest(cred.App, "POST", Origin+signoutAllPath, Origin, map[string][]string{}, session) |
| + hop := regexp.MustCompile(`name="assertion" value="([^"]+)"`).FindStringSubmatch(press.Body.String()) |
| + if press.Code != 200 || hop == nil || !strings.Contains(press.Body.String(), "Finishing signing out of oficina.works") { |
| + t.Fatal("press", press.Code) |
| + } |
| + if w := exchangeRequest(f.p.directory, "POST", directoryOrigin+signedOutAllPath, Origin, map[string][]string{"assertion": {hop[1]}}); w.Code != 303 { |
| + t.Fatal("hop", w.Code) |
| + } |
| + var n int |
| + cred.db.Writer().QueryRow("SELECT count(*) FROM home_id_signed_out_all WHERE person_ref=?", person).Scan(&n) |
| + if n != 1 { |
| + t.Fatal("no mark on id.*") |
| + } |
| + // The earlier browser assertion cannot finish a sign-in. |
| + callback := exchangeRequest(f.p.directory, "POST", directoryOrigin+handoff.CallbackPath, Origin, map[string][]string{"assertion": {browserToken}}) |
| + if inbox := namedCookieOrNil(callback, "__Host-oficina-assertion-inbox"); inbox != nil { |
| + if fin := exchangeRequest(f.p.directory, "GET", directoryOrigin+handoff.FinishPath, "", nil, pending, inbox); sessionCookie(fin) != nil { |
| + t.Fatal("an assertion from before the press signed the directory in") |
| + } |
| + } |
| + // Nor the earlier native one. |
| + if w := directoryCall(t, f, "POST", nativeExchangePath, exchangeBody(nativeToken, verifier), nil, nil); w.Code != 401 { |
| + t.Fatal("a native assertion from before the press exchanged", w.Code) |
| + } |
| + // After the press, signing in works again. |
| + time.Sleep(1100 * time.Millisecond) |
| + again := signInFully(t, cred.restart(t), "early@example.invalid") |
| + pending, intent = f.p.start(t) |
| + token, _ := f.p.mint(t, intent, again) |
| + f.p.finish(t, token, pending) |
| +} |
| + |
| +// F4 and F5: a refused receipt lands on the failure page, which says what |
| +// did and did not sign out; and a browser holding someone else's directory |
| +// session keeps it. |
| +func TestNativeSignOutAllHopFailureAndOtherCookie(t *testing.T) { |
| + t.Parallel() |
| + f := newMountedChooser(t) |
| + w := exchangeRequest(f.p.directory, "POST", directoryOrigin+signedOutAllPath, Origin, map[string][]string{"assertion": {"nonsense"}}) |
| + if w.Code != 403 || !strings.Contains(w.Body.String(), "id.oficina.works is signed out") || !strings.Contains(w.Body.String(), Origin+signoutAllPath) { |
| + t.Fatal("failure page", w.Code) |
| + } |
| + cred := f.p.credential |
| + session := signInFully(t, cred, "owner@example.invalid") |
| + press := exchangeRequest(cred.App, "POST", Origin+signoutAllPath, Origin, map[string][]string{}, session) |
| + hop := regexp.MustCompile(`name="assertion" value="([^"]+)"`).FindStringSubmatch(press.Body.String()) |
| + someoneElse := f.session(t, chooserOther) |
| + done := exchangeRequest(f.p.directory, "POST", directoryOrigin+signedOutAllPath, Origin, map[string][]string{"assertion": {hop[1]}}, someoneElse) |
| + if done.Code != 303 { |
| + t.Fatal("hop", done.Code) |
| + } |
| + if c := namedCookieOrNil(done, f.p.directory.sessions.CookieName()); c != nil { |
| + t.Fatal("cleared another person's directory cookie") |
| + } |
| + var n int |
| + 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") |
| + } |
| +} |
| + |
| +// Fable's final check N1: a receipt that commits between a sign-in's first |
| +// mark check and its session write still wins, on both directory doors. |
| +// Serial: it swaps the afterMarkCheck seam. |
| +func TestNativeSignOutAllRaceOrderings(t *testing.T) { |
| + prev := afterMarkCheck |
| + t.Cleanup(func() { afterMarkCheck = prev }) |
| + f := newMountedChooser(t) |
| + cred := f.p.credential |
| + dirSessions := func(person string) int { |
| + var n int |
| + f.p.directory.db.Writer().QueryRow("SELECT count(*) FROM sessions WHERE subject=?", person).Scan(&n) |
| + return n |
| + } |
| + pressNow := func(person string) func() { |
| + return func() { |
| + if _, err := f.p.directory.db.Writer().Exec("INSERT INTO home_directory_signed_out_all(person_ref,at) VALUES(?,?) ON CONFLICT(person_ref) DO UPDATE SET at=excluded.at", person, time.Now().Unix()+5); err != nil { |
| + t.Error(err) |
| + } |
| + } |
| + } |
| + |
| + // (a) The native exchange: the in-transaction check refuses. |
| + d := newDevice(t) |
| + grant, _ := d.signInByCode(t, cred, "race-native@example.invalid") |
| + var person string |
| + cred.db.Writer().QueryRow("SELECT person_ref FROM home_id_grants").Scan(&person) |
| + verifier, challenge := verifierFor(70) |
| + token := decodeReply(t, d.assert(t, cred, grant, directoryOrigin, challenge))["assertion"].(string) |
| + afterMarkCheck = pressNow(person) |
| + if w := directoryCall(t, f, "POST", nativeExchangePath, exchangeBody(token, verifier), nil, nil); w.Code != 401 { |
| + t.Fatal("native exchange minted across a press", w.Code, w.Body.String()) |
| + } |
| + if n := dirSessions(person); n != 0 { |
| + t.Fatal("native session survived the press", n) |
| + } |
| + |
| + // (b) The browser finish: the re-check after SignIn undoes the session. |
| + afterMarkCheck = func() {} |
| + session := signInFully(t, cred, "race-web@example.invalid") |
| + webPerson := subjectOf(t, cred, session) |
| + pending, intent := f.p.start(t) |
| + browserToken, _ := f.p.mint(t, intent, session) |
| + callback := exchangeRequest(f.p.directory, "POST", directoryOrigin+handoff.CallbackPath, Origin, map[string][]string{"assertion": {browserToken}}) |
| + inbox := namedCookie(t, callback, "__Host-oficina-assertion-inbox") |
| + afterMarkCheck = pressNow(webPerson) |
| + fin := exchangeRequest(f.p.directory, "GET", directoryOrigin+handoff.FinishPath, "", nil, pending, inbox) |
| + if sessionCookie(fin) != nil || fin.Code != 403 || !strings.Contains(fin.Body.String(), "All devices are signed out") { |
| + t.Fatal("browser finish across a press", fin.Code, sessionCookie(fin) != nil) |
| + } |
| + if n := dirSessions(webPerson); n != 0 { |
| + t.Fatal("browser session survived the press", n) |
| + } |
| +} |
diff --git a/internal/home/native_revoke_test.go b/internal/home/native_revoke_test.go| new file mode 100644 |
| index 0000000..eb2a09f |
| --- /dev/null |
| +++ b/internal/home/native_revoke_test.go |
| @@ -0,0 +1,200 @@ |
| +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" |
| +) |
| + |
| +// §13 Revocation: a first passkey enrolment on the web ends every |
| +// passkey-less grant; later enrolments end nothing. |
| +func TestNativeFirstEnrolmentRevokesPasskeylessGrants(t *testing.T) { |
| + t.Parallel() |
| + app := newNativeApp(t) |
| + d := newDevice(t) |
| + g1, _ := d.signInByCode(t, app, sealtest.CanaryAddress) |
| + session := signInFully(t, app, sealtest.CanaryAddress) |
| + enrol(t, app, session) |
| + if ended, reason := grantState(t, app, g1); !ended || reason != "enrolment" { |
| + t.Fatal("code grant survived first enrolment", reason) |
| + } |
| + // It may sign in again, now with a passkey; a second enrolment leaves |
| + // that grant alone. |
| + app = app.restart(t) |
| + start := d.start(t, app, sealtest.CanaryAddress) |
| + if out := decodeReply(t, d.verify(t, app, start, lastCode(t, app))); out["pending"] == nil { |
| + t.Fatal("no pending", out) |
| + } |
| + 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('pk',?,'i','k','macos','passkey',1,1,?,?)", subjectOf(t, app, session), dayOf(time.Now().Unix()), time.Now().Unix()+day); err != nil { |
| + t.Fatal(err) |
| + } |
| + enrol(t, app, session) |
| + if n := count(t, app, "SELECT count(*) FROM home_id_grants WHERE grant_hash='pk' AND ended_at IS NULL"); n != 1 { |
| + t.Fatal("a second enrolment ended a passkey grant") |
| + } |
| +} |
| + |
| +// §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) { |
| + t.Parallel() |
| + 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") |
| + 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"`) { |
| + t.Fatal("page", page.Code) |
| + } |
| + if forged := exchangeRequest(app.App, "POST", Origin+signoutAllPath, "https://evil.example", url.Values{}, session); forged.Code != 403 { |
| + t.Fatal("cross-origin sign-out-all", forged.Code) |
| + } |
| + if anon := exchangeRequest(app.App, "POST", Origin+signoutAllPath, Origin, url.Values{}); anon.Code == 200 { |
| + t.Fatal("no session ended devices") |
| + } |
| + // A stale session must re-authenticate first. |
| + 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 { |
| + t.Fatal("a stale session ended devices") |
| + } |
| + if n := count(t, app, "SELECT count(*) FROM home_id_grants WHERE ended_at IS NOT NULL"); n != 0 { |
| + 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(), `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, 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. |
| +func TestNativeReplacementRevokesEveryGrant(t *testing.T) { |
| + t.Parallel() |
| + app := newNativeApp(t) |
| + d := newDevice(t) |
| + g, _ := d.signInByCode(t, app, sealtest.CanaryAddress) |
| + session := signInFully(t, app, sealtest.CanaryAddress) |
| + subject := subjectOf(t, app, session) |
| + // A passkey grant, as native passkey sign-in would leave. |
| + 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('pk',?,'i','k','macos','passkey',1,1,?,?)", subject, dayOf(time.Now().Unix()), time.Now().Unix()+day); err != nil { |
| + t.Fatal(err) |
| + } |
| + tx, now, err := app.idTransaction(t.Context()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cred := webauthn.Credential{ID: []byte("replacement-credential"), PublicKey: []byte{1}} |
| + if err := app.replaceCredential(tx, nil, subject, cred, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := tx.Commit(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if n := count(t, app, "SELECT count(*) FROM home_id_grants WHERE ended_at IS NULL"); n != 0 { |
| + t.Fatal("grants survived replacement", n) |
| + } |
| + if _, reason := grantState(t, app, g); reason != "replacement" { |
| + t.Fatal(reason) |
| + } |
| +} |
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/runtime.go b/internal/home/runtime.go| index bed7dee..b8737d8 100644 |
| --- a/internal/home/runtime.go |
| +++ b/internal/home/runtime.go |
| @@ -212,7 +212,7 @@ func (cfg Runtime) Schema() *migrate.Set { |
| func (cfg Runtime) ServingSchema() *migrate.Set { |
| switch cfg.role { |
| case "directory": |
| - return migrate.Merge(cfg.Schema(), operator.DirectoryHTTPSchema, directorydata.TeamSchema) |
| + return migrate.Merge(cfg.Schema(), operator.DirectoryHTTPSchema, directorydata.TeamSchema, directoryIDSchema) |
| case "credential": |
| return migrate.Merge(cfg.Schema(), operator.CredentialHTTPSchema, identitySchema) |
| case "": |
diff --git a/internal/home/signout_all.go b/internal/home/signout_all.go| new file mode 100644 |
| index 0000000..2b25a71 |
| --- /dev/null |
| +++ b/internal/home/signout_all.go |
| @@ -0,0 +1,278 @@ |
| +package home |
| + |
| +import ( |
| + "context" |
| + "crypto/sha256" |
| + "crypto/subtle" |
| + "database/sql" |
| + "encoding/base64" |
| + "encoding/hex" |
| + "errors" |
| + "net/http" |
| + "time" |
| + |
| + "amadan.net/rastrillo/rastrillo/assertion" |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| +) |
| + |
| +// signoutAllPath is "Sign out all devices" (§10): the slice-A stand-in for |
| +// 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.* ends its half in one |
| +// transaction; the directory ends its half in one transaction when this |
| +// browser carries the signed receipt across (signedOutAllPath). Both record |
| +// a per-person mark, and assertions issued at or before it are refused. The |
| +// residual (the hop between the two stores, and team instances that do not |
| +// read the mark yet) is in the branch description. |
| +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", 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) |
| + return |
| + } |
| + defer tx.Rollback() |
| + live, _, err := a.idSession(tx, r, now) |
| + if err != nil || !idFreshSession(live, enrolFreshness, time.Unix(now, 0)) { |
| + a.signinFailed(w, r) |
| + return |
| + } |
| + 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 |
| + } |
| + } |
| + if err = markSignedOutAll(tx, "home_id_signed_out_all", live.Subject, now); 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 |
| + } |
| + 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, "id_signout_all_hop.html", map[string]any{"Action": a.origins.Directory + signedOutAllPath, "Token": receipt}) |
| +} |
| + |
| +// markSignedOutAll records the press, keeping the later of two, and prunes |
| +// marks too old to matter: no assertion lives longer than 120 seconds. |
| +func markSignedOutAll(tx *sql.Tx, table, person string, at int64) error { |
| + if _, err := tx.Exec("DELETE FROM "+table+" WHERE at<?", at-signedOutAllKeep); err != nil { |
| + return errIDProof |
| + } |
| + if _, err := tx.Exec("INSERT INTO "+table+"(person_ref,at) VALUES(?,?) ON CONFLICT(person_ref) DO UPDATE SET at=MAX(at,excluded.at)", person, at); err != nil { |
| + return errIDProof |
| + } |
| + return nil |
| +} |
| + |
| +const signedOutAllKeep = 300 |
| + |
| +type rowQueryer interface { |
| + QueryRowContext(context.Context, string, ...any) *sql.Row |
| +} |
| + |
| +// signedOutBefore reports whether something issued at iat predates the |
| +// person's latest "Sign out all devices" (iat at or before the mark). |
| +func signedOutBefore(ctx context.Context, q rowQueryer, table, person string, iat int64) (bool, error) { |
| + var at int64 |
| + err := q.QueryRowContext(ctx, "SELECT at FROM "+table+" WHERE person_ref=?", person).Scan(&at) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return false, nil |
| + } |
| + if err != nil { |
| + return false, err |
| + } |
| + return iat <= at, nil |
| +} |
| + |
| +// errSignedOutAll refuses a directory sign-in from an assertion issued |
| +// before the person pressed "Sign out all devices". |
| +var errSignedOutAll = errors.New("home: assertion predates sign out all devices") |
| + |
| +// directorySigninAllowed is the directory's browser-finish check. |
| +func (a *App) directorySigninAllowed(ctx context.Context, c assertion.Claims) error { |
| + before, err := signedOutBefore(ctx, a.db.Writer(), "home_directory_signed_out_all", c.Subject, c.IssuedAt) |
| + if err != nil { |
| + return err |
| + } |
| + if before { |
| + return errSignedOutAll |
| + } |
| + return nil |
| +} |
| + |
| +// 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") |
| + failed := func(status int) { |
| + a.render(w, r, status, "directory_signout_all_failed.html", map[string]any{"Again": a.origins.Credential + signoutAllPath}) |
| + } |
| + if origins := r.Header.Values("Origin"); len(origins) != 1 || origins[0] != a.origins.Credential { |
| + failed(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 { |
| + failed(http.StatusBadRequest) |
| + return |
| + } |
| + claims, err := a.handoffStore.Verify(r.PostForm.Get("assertion"), time.Now()) |
| + if err != nil || subtle.ConstantTimeCompare([]byte(claims.Nonce), []byte(signoutAllNonce(claims.ID))) != 1 || !ValidPersonRef(claims.Subject) { |
| + failed(http.StatusForbidden) |
| + return |
| + } |
| + tx, err := a.db.Writer().BeginTx(r.Context(), nil) |
| + if err != nil { |
| + failed(http.StatusServiceUnavailable) |
| + return |
| + } |
| + defer tx.Rollback() |
| + // Reserved here rather than through handoff.Store.Reserve, on purpose: |
| + // the receipt is one-shot, so its jti, the sessions it ends and the mark |
| + // commit together. The key is handoff's jtiHash, SHA-256(iss ‖ 0 ‖ jti), |
| + // so the one ledger still refuses it at every other door. |
| + 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 { |
| + failed(http.StatusServiceUnavailable) |
| + return |
| + } |
| + if n, err := res.RowsAffected(); err != nil || n != 1 { |
| + failed(http.StatusForbidden) |
| + return |
| + } |
| + // Whose session does this browser hold? Its cookie is cleared only if it |
| + // is the receipt's person's, which the delete below ends anyway. |
| + mine := false |
| + if token := cookieValue(r, a.sessions.CookieName()); token != "" { |
| + var subject string |
| + if tx.QueryRow("SELECT subject FROM sessions WHERE token_hash=?", sessions.HashToken(token)).Scan(&subject) == nil { |
| + mine = subject == claims.Subject |
| + } |
| + } |
| + if _, err = tx.Exec("DELETE FROM sessions WHERE subject=?", claims.Subject); err != nil { |
| + failed(http.StatusServiceUnavailable) |
| + return |
| + } |
| + if markSignedOutAll(tx, "home_directory_signed_out_all", claims.Subject, claims.IssuedAt) != nil || tx.Commit() != nil { |
| + failed(http.StatusServiceUnavailable) |
| + return |
| + } |
| + if mine { |
| + idCookie(w, a.sessions.CookieName(), "", -1) |
| + } |
| + idCookie(w, "__Host-oficina-signed-out-all", "1", 300) |
| + http.Redirect(w, r, "/signed-out", http.StatusSeeOther) |
| +} |
| + |
| +// afterMarkCheck is a test seam: it runs between a sign-in's first mark |
| +// check and the write that follows, so a test can commit a receipt in that |
| +// gap. It does nothing in production. |
| +var afterMarkCheck = func() {} |
| + |
| +// finishWriter carries one fact from the directory's Complete to its Fail |
| +// hook through handoff.Consumer.Finish: the sign-in was refused because the |
| +// person pressed "Sign out all devices". |
| +type finishWriter struct { |
| + http.ResponseWriter |
| + signedOutAll bool |
| +} |
| + |
| +func markSignedOutAllFinish(w http.ResponseWriter) { |
| + if fw, ok := w.(*finishWriter); ok { |
| + fw.signedOutAll = true |
| + } |
| +} |
| + |
| +func signedOutAllFinish(w http.ResponseWriter) bool { |
| + fw, ok := w.(*finishWriter) |
| + return ok && fw.signedOutAll |
| +} |
| + |
| +// undoSignIn deletes the session sessions.SignIn just minted, found by the |
| +// cookie it set on this response, and replaces that cookie with a clearing |
| +// one. Nothing has been sent yet: handoff's Finish writes only after |
| +// Complete returns. |
| +func (a *App) undoSignIn(w http.ResponseWriter, r *http.Request) { |
| + name := a.sessions.CookieName() |
| + h := w.Header() |
| + kept := h.Values("Set-Cookie")[:0:0] |
| + for _, line := range h.Values("Set-Cookie") { |
| + c, err := http.ParseSetCookie(line) |
| + if err == nil && c.Name == name && c.Value != "" { |
| + if _, err := a.db.Writer().ExecContext(r.Context(), "DELETE FROM sessions WHERE token_hash=?", sessions.HashToken(c.Value)); err != nil { |
| + a.logger.Warn("undoing a refused directory sign-in failed") |
| + } |
| + continue |
| + } |
| + kept = append(kept, line) |
| + } |
| + h.Del("Set-Cookie") |
| + for _, line := range kept { |
| + h.Add("Set-Cookie", line) |
| + } |
| + idCookie(w, name, "", -1) |
| +} |
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_no_teams.html b/internal/home/templates/directory_no_teams.html| new file mode 100644 |
| index 0000000..7c0a420 |
| --- /dev/null |
| +++ b/internal/home/templates/directory_no_teams.html |
| @@ -0,0 +1,7 @@ |
| +{{define "title"}}Not on a team yet · Oficina{{end}} |
| +{{define "content"}} |
| +<h1>You're not on a team yet</h1> |
| +<p>The Oficina apps open a team's documents, sheets, calendars and calls. Your Oficina ID isn't on a team yet, so there is nothing for them to open.</p> |
| +<p>Ask the owner of your team to add the email address you signed in with. Then open the app again, and your team appears.</p> |
| +<p><a href="/">Back to Oficina</a></p> |
| +{{end}} |
diff --git a/internal/home/templates/directory_signed_out.html b/internal/home/templates/directory_signed_out.html| index dab7ccf..0f62138 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 on id.oficina.works and oficina.works in every browser. The Oficina apps sign out as each device next checks in. A team's app already open in a browser stays signed in until its own session ends.</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/directory_signout_all_failed.html b/internal/home/templates/directory_signout_all_failed.html| new file mode 100644 |
| index 0000000..5987651 |
| --- /dev/null |
| +++ b/internal/home/templates/directory_signout_all_failed.html |
| @@ -0,0 +1,7 @@ |
| +{{define "title"}}Not finished signing out · Oficina{{end}} |
| +{{define "content"}} |
| +<h1>oficina.works may still be signed in</h1> |
| +<p estilo-signin-body>id.oficina.works is signed out, and so are your Oficina apps as each device next checks in. Signing out of oficina.works didn’t finish, so it may still be signed in, in this browser and others.</p> |
| +<p estilo-signin-body>Sign in again and press Sign out all devices once more to finish.</p> |
| +<p><a href="{{.Data.Again}}" rst-btn="primary">Sign in and try again</a></p> |
| +{{end}} |
diff --git a/internal/home/templates/id_signout_all.html b/internal/home/templates/id_signout_all.html| new file mode 100644 |
| index 0000000..b95d0a5 |
| --- /dev/null |
| +++ b/internal/home/templates/id_signout_all.html |
| @@ -0,0 +1,12 @@ |
| +{{define "title"}}Sign out all devices · Oficina{{end}} |
| +{{define "content"}} |
| +<h1>Sign out all devices</h1> |
| +<p>This ends your Oficina ID sign-ins on id.oficina.works and oficina.works in every browser, this one included. The Oficina apps on every Mac, iPhone and iPad sign out as each device next checks in.</p> |
| +<p>A team's app already open in a browser, such as a Docs tab, stays signed in until its own session ends. An app on a device that stays offline can keep what it already has for up to seven days.</p> |
| +<p>If you have lost a device, this stops it signing in again with your Oficina ID. What it already has open can keep working 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}} |
diff --git a/internal/home/templates/id_signout_all_hop.html b/internal/home/templates/id_signout_all_hop.html| new file mode 100644 |
| index 0000000..aa35980 |
| --- /dev/null |
| +++ b/internal/home/templates/id_signout_all_hop.html |
| @@ -0,0 +1,19 @@ |
| +{{define "title"}}Finishing signing out · Oficina{{end}} |
| +{{define "head"}} |
| +{{/* Like assertion.html: the form submits itself (static/assertion.js) and |
| + the card shows only if that stalls, or at once with scripts off. */}} |
| +<style> |
| +[estilo-handoff] { animation: estilo-reveal 0s 1.5s both; } |
| +@keyframes estilo-reveal { from { visibility: hidden } to { visibility: visible } } |
| +</style> |
| +<noscript><style>[estilo-handoff] { animation: none; }</style></noscript> |
| +{{end}} |
| +{{define "content"}} |
| +<h1>Finishing signing out of oficina.works…</h1> |
| +<p estilo-signin-body>id.oficina.works and your Oficina apps are signed out. Select Continue to sign out of oficina.works too, if this page doesn’t move on.</p> |
| +<form method="post" action="{{.Data.Action}}" rst-form data-assertion-handoff> |
| +<input type="hidden" name="assertion" value="{{.Data.Token}}"> |
| +<button type="submit" rst-btn="primary">Continue</button> |
| +</form> |
| +{{end}} |
| +{{define "scripts"}}<script src='{{v "/static/assertion.js"}}' async></script>{{end}} |