Add bounded recovery replacement and local sign-out safeguards
31 files changed,
+1,066
−50
implementation/oficina-id-slice1-copy.md+7 −3implementation/oficina-id-slice1-validation.md+23 −0internal/home/app.go+8 −1internal/home/directory.go+2 −3internal/home/exchange.go+16 −2internal/home/exchange_test.go+1 −1internal/home/id_exchange_test.go+20 −0internal/home/id_passkey.go+55 −4internal/home/id_passkey_test.go+22 −0internal/home/id_recovery.go+411 −0internal/home/id_recovery_test.go+305 −0internal/home/id_signout_test.go+75 −0internal/home/{migrations/0003_id_ceremonies.sql => identity/migrations/0001_ceremonies.sql}+0 −0internal/home/identity/migrations/0002_recovery.sql+14 −0internal/home/keymail_fresh_test.go+1 −7internal/home/models.go+14 −0internal/home/operator_http_test.go+2 −1internal/home/passkey.go+21 −1internal/home/passkey_test.go+2 −2internal/home/runtime.go+1 −1internal/home/shared_chrome_test.go+1 −1internal/home/signin.go+2 −8internal/home/signin_return_factor_test.go+1 −1internal/home/signout.go+1 −1internal/home/signout_test.go+5 −5internal/home/static/passkey.js+25 −6internal/home/team_page_test.go+4 −1internal/home/templates/id_replace.html+10 −0internal/home/templates/id_replaced.html+10 −0internal/home/templates/id_signed_out.html+6 −0internal/home/testapp_test.go+1 −1
CI failed — run details
diff --git a/implementation/oficina-id-slice1-copy.md b/implementation/oficina-id-slice1-copy.md| index 8417933..bbf5d3c 100644 |
| --- a/implementation/oficina-id-slice1-copy.md |
| +++ b/implementation/oficina-id-slice1-copy.md |
| @@ -8,15 +8,15 @@ Reviewed by GPT-6 Astra. Fixed labels only; no account-authored text. |
| - Add a passkey to sign in without entering your email. JavaScript is needed to add and use passkeys. |
| - Replace passkeys · Oficina |
| - Replace your passkeys |
| -- Adding a replacement removes all your existing passkeys, signs you out of Oficina Home on every device, and invalidates all your recovery codes. Sign in with the new passkey before creating new recovery codes. |
| +- Adding a replacement removes all your existing passkeys, signs you out of Oficina ID on every device, and invalidates all your recovery codes. You may remain signed in to the directory and other apps. Sign in with the new passkey before creating new recovery codes. |
| - Replace all passkeys |
| - Turn on JavaScript to add your replacement passkey. |
| - Passkeys replaced · Oficina |
| - Your passkeys were replaced |
| -- You are signed out of Oficina Home on every device. Your previous passkeys and recovery codes no longer work. Sign in with your new passkey to create new recovery codes. |
| +- You are signed out of Oficina ID on every device. Your previous passkeys and recovery codes no longer work. You may remain signed in to the directory and other apps. Sign in with your new passkey to create new recovery codes. |
| - Sign in with your new passkey |
| - Your Oficina passkeys were replaced |
| -- A replacement passkey was added to your Oficina account. All previous passkeys were removed, all Oficina Home sessions were signed out, and all recovery codes were invalidated. Sign in with your new passkey to create new recovery codes. |
| +- A replacement passkey was added to your Oficina account. All previous passkeys were removed, all Oficina ID sessions were signed out, and all recovery codes were invalidated. You may remain signed in to the directory and other apps. Sign in with your new passkey to create new recovery codes. |
| - Your passkeys were replaced, but we could not send the confirmation email. |
| - Send email again |
| - Continue to the app · Oficina |
| @@ -28,3 +28,7 @@ Reviewed by GPT-6 Astra. Fixed labels only; no account-authored text. |
| - Sign in |
| - That did not work. You can try again. |
| - That code did not work. |
| + |
| +- The confirmation email can no longer be sent from this page. |
| + |
| +The delegated Astra follow-up accepted the Oficina ID scope clarification. |
diff --git a/implementation/oficina-id-slice1-validation.md b/implementation/oficina-id-slice1-validation.md| index 1b28f22..89c0aa6 100644 |
| --- a/implementation/oficina-id-slice1-validation.md |
| +++ b/implementation/oficina-id-slice1-validation.md |
| @@ -18,3 +18,26 @@ Pending. |
| the first person's row. All now pass, along with enrollment freshness and |
| existing gated-sign-in tests. New registrations use the existing WebAuthn |
| helper's required resident key and user verification options. |
| + |
| +- Task 3: entropy, parallel/restart attempt limits, replacement confirmation, |
| + and hostile SMTP-error tests failed before recovery implementation. The new |
| + code passes them. Added account/IP, rollback, browser/person/expiry/UV/replay, |
| + and no-address checks. A later notice-restart regression failed, then passed |
| + after adding a sealed, content-free result cookie separate from the RAM |
| + address. Successful replacement revokes all issuer sessions; directory and |
| + consumer sessions retain their own expiry/revocation. Delegated copy now says |
| + Oficina ID and names that limit. |
| +- Astra source review found stale/passive Keymail proof, an email-mint/enrollment |
| + race, cached-session assertion issuance, missing nondiscoverable browser |
| + allowlists, and notice-result loss. Added failing stale-mailbox, cached-session |
| + and legacy-allowlist regressions; fixed each. Email-only mint now shares the |
| + gate transaction and preserves Keymail auth_time. Re-review remains pending. |
| +- Task 4: hanging-issuer sign-out test failed on the old 307 to the issuer. |
| + Directory sign-out now revokes and lands locally; credential sign-out also |
| + has its own landing page. The hanging server accepts an actual connection. |
| +- Historical admission profiles remain byte-for-byte frozen. New identity |
| + migrations are a separate serving-role set, following existing HTTP schema |
| + extensions; standalone test Apps apply that set too. |
| +- Local Go's VCS discovery selects an unrelated broken `.git` in the ancestor |
| + scratch directory. Local gates use GOFLAGS=-buildvcs=false; no ancestor files |
| + or shared Go cache settings were changed. Hosted CI uses the normal targets. |
diff --git a/internal/home/app.go b/internal/home/app.go| index db23107..f774086 100644 |
| --- a/internal/home/app.go |
| +++ b/internal/home/app.go |
| @@ -38,6 +38,7 @@ import ( |
| // is sealed on the way in, and the database handle because that is what |
| // it is sealed into. Nothing here reaches for a raw key. |
| type App struct { |
| + mailboxes mailboxMemory |
| dash *dashboardState |
| runtime *Runtime |
| directory *directoryFeatures |
| @@ -203,6 +204,7 @@ func (a *App) Router() http.Handler { |
| // page. See signoutPath. |
| r.With(a.credentialOnly).Post(signoutPath, a.handleCredentialSignout) |
| r.With(a.credentialOnly).Get(signoutPath, a.handleCredentialSignoutPage) |
| + r.With(a.credentialOnly).Get("/signed-out", func(w http.ResponseWriter, r *http.Request) { a.render(w, r, 200, "id_signed_out.html", nil) }) |
| } |
| r.Group(func(r chi.Router) { |
| @@ -245,13 +247,18 @@ func (a *App) Router() http.Handler { |
| // with script off, because recovery is exactly the moment WebAuthn |
| // is not working. |
| r.Get(confirmPath, a.handlePasskeyConfirm) |
| + r.Get("/passkey/replace", a.handleReplacement) |
| + r.Post("/passkey/replace/begin", a.idBegin("replace")) |
| + r.Post("/passkey/replace/finish", a.idFinish("replace")) |
| + r.Get("/passkey/replaced", a.handleReplacementDone) |
| + r.Post("/passkey/notice", a.handleNoticeRetry) |
| r.Post("/passkey/direct/begin", a.idBegin("direct")) |
| r.Post("/passkey/direct/finish", a.idFinish("direct")) |
| r.Post("/passkey/stepup/begin", a.idBegin("stepup")) |
| r.Post("/passkey/stepup/finish", a.idFinish("stepup")) |
| r.Post("/passkey/signin/begin", a.idBegin("signin")) |
| r.Post("/passkey/signin/finish", a.idFinish("signin")) |
| - r.Post("/passkey/signin/recovery", a.passkeys.SignInRecovery) |
| + r.Post("/passkey/signin/recovery", a.idRecovery) |
| // Enrolling changes who can get in, and there is no operator reset, |
| // so it wants a recent session rather than merely a valid one — see |
| // enrolFreshness for the lockout this closes. |
diff --git a/internal/home/directory.go b/internal/home/directory.go| index fc6863e..03a7e43 100644 |
| --- a/internal/home/directory.go |
| +++ b/internal/home/directory.go |
| @@ -161,12 +161,11 @@ func (a *App) directoryRouter() http.Handler { |
| // not turn the click into a sign-in loop. A host-only cookie, so the |
| // choice is the directory's own. |
| r.Post("/appearance", chrome.HandleAppearance) |
| - // Sign out ends both sessions: this one here, then the id.* |
| - // session by handing the POST on. See signoutPath. |
| + // Local revocation and landing never wait for the credential origin. |
| r.Post(signoutPath, func(w http.ResponseWriter, r *http.Request) { |
| w.Header().Set("Cache-Control", "no-store") |
| a.sessions.SignOut(w, r) |
| - http.Redirect(w, r, a.origins.Credential+signoutPath, http.StatusTemporaryRedirect) |
| + http.Redirect(w, r, "/signed-out", http.StatusSeeOther) |
| }) |
| r.Get("/signed-out", func(w http.ResponseWriter, r *http.Request) { |
| w.Header().Set("Cache-Control", "no-store") |
diff --git a/internal/home/exchange.go b/internal/home/exchange.go| index c03817f..0c15119 100644 |
| --- a/internal/home/exchange.go |
| +++ b/internal/home/exchange.go |
| @@ -88,8 +88,14 @@ func (a *App) handleAssertion(w http.ResponseWriter, r *http.Request) { |
| a.failAssertion(w, r, assertionConsumer) |
| return |
| } |
| - session, ok := sessions.Current(r) |
| - if !ok { |
| + tx, _, err := a.idTransaction(r.Context()) |
| + if err != nil { |
| + a.failAssertion(w, r, assertionSession) |
| + return |
| + } |
| + defer tx.Rollback() |
| + session, _, err := a.idSession(tx, r, now.Unix()) |
| + if err != nil { |
| a.failAssertion(w, r, assertionSession) |
| return |
| } |
| @@ -110,6 +116,10 @@ func (a *App) handleAssertion(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| if r.Method == http.MethodGet { |
| + if tx.Commit() != nil { |
| + a.failAssertion(w, r, assertionSession) |
| + return |
| + } |
| a.render(w, r, http.StatusOK, "id_continue.html", nil) |
| return |
| } |
| @@ -123,6 +133,10 @@ func (a *App) handleAssertion(w http.ResponseWriter, r *http.Request) { |
| a.failAssertion(w, r, assertionSign) |
| return |
| } |
| + if tx.Commit() != nil { |
| + a.failAssertion(w, r, assertionSession) |
| + return |
| + } |
| http.SetCookie(w, &http.Cookie{Name: assertionIntentCookie, Value: "", Path: "/", MaxAge: -1, Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode}) |
| // This page's form posts to one consumer; its form-action names that one |
| // origin and no other (team-provisioning-amendment.md §7). |
diff --git a/internal/home/exchange_test.go b/internal/home/exchange_test.go| index 2e0046c..2f76670 100644 |
| --- a/internal/home/exchange_test.go |
| +++ b/internal/home/exchange_test.go |
| @@ -281,7 +281,7 @@ func TestHomePolicyMatchesRegisteredConsumers(t *testing.T) { |
| session := signInFully(t, p.credential, sealtest.CanaryAddress) |
| nonce, _ := assertion.RandomID() |
| authorize := exchangeRequest(p.credential.App, "GET", Origin+"/authorize?consumer=team_docs&nonce="+nonce, "", nil) |
| - rec := exchangeRequest(p.credential.App, "GET", Origin+"/authorize/resume", "", nil, namedCookie(t, authorize, assertionIntentCookie), session) |
| + rec := exchangeRequest(p.credential.App, "POST", Origin+"/authorize/resume", Origin, nil, namedCookie(t, authorize, assertionIntentCookie), session) |
| want := strings.Replace(baseline, "form-action 'self' "+directoryOrigin, "form-action 'self' https://blue.docs.oficina.works "+directoryOrigin, 1) |
| if rec.Code != 200 || rec.Header().Get("Content-Security-Policy") != want { |
| t.Fatalf("handoff CSP %d %q, want %q", rec.Code, rec.Header().Get("Content-Security-Policy"), want) |
diff --git a/internal/home/id_exchange_test.go b/internal/home/id_exchange_test.go| index d6a11ad..7c2ffb0 100644 |
| --- a/internal/home/id_exchange_test.go |
| +++ b/internal/home/id_exchange_test.go |
| @@ -2,6 +2,7 @@ package home |
| import ( |
| "net/http" |
| + "net/http/httptest" |
| "net/url" |
| "strings" |
| "testing" |
| @@ -38,3 +39,22 @@ func TestIDContinueBeforeMinting(t *testing.T) { |
| t.Fatal("Continue did not mint", good.Code) |
| } |
| } |
| + |
| +func TestIDRevokedCachedSessionCannotMint(t *testing.T) { |
| + p := newExchangePair(t) |
| + s := signInFully(t, p.credential, sealtest.CanaryAddress) |
| + _, intent := p.start(t) |
| + r := httptest.NewRequest("POST", Origin+"/authorize/resume", nil) |
| + r.AddCookie(s) |
| + r.AddCookie(intent) |
| + w := httptest.NewRecorder() |
| + p.credential.sessions.Require(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if _, err := p.credential.db.Writer().Exec("DELETE FROM sessions"); err != nil { |
| + t.Fatal(err) |
| + } |
| + p.credential.handleAssertion(w, r) |
| + })).ServeHTTP(w, r) |
| + if strings.Contains(w.Body.String(), `name="assertion"`) { |
| + t.Fatal("cached revoked session minted an assertion") |
| + } |
| +} |
diff --git a/internal/home/id_passkey.go b/internal/home/id_passkey.go| index 28bba33..43beacd 100644 |
| --- a/internal/home/id_passkey.go |
| +++ b/internal/home/id_passkey.go |
| @@ -89,6 +89,8 @@ func (a *App) idSession(tx *sql.Tx, r *http.Request, now int64) (sessions.Sessio |
| } |
| func (a *App) idBinding(tx *sql.Tx, r *http.Request, purpose string, now int64) (subject, binding string, err error) { |
| switch purpose { |
| + case "replace": |
| + return a.replacementBinding(tx, r, now) |
| case "direct": |
| v := cookieValue(r, ceremonyCookie) |
| if v == "" { |
| @@ -162,6 +164,35 @@ func (a *App) idBegin(purpose string) http.HandlerFunc { |
| idRefuse(w) |
| return |
| } |
| + var credentials []string |
| + if purpose == "signin" || purpose == "stepup" { |
| + rows, e := tx.Query("SELECT id FROM passkey_credentials WHERE subject=? ORDER BY id LIMIT 100", subject) |
| + if e != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + for rows.Next() { |
| + var id string |
| + if rows.Scan(&id) != nil { |
| + rows.Close() |
| + idRefuse(w) |
| + return |
| + } |
| + raw, e := hex.DecodeString(id) |
| + if e != nil { |
| + rows.Close() |
| + idRefuse(w) |
| + return |
| + } |
| + credentials = append(credentials, base64.RawURLEncoding.EncodeToString(raw)) |
| + } |
| + e = rows.Err() |
| + rows.Close() |
| + if e != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + } |
| if err = tx.Commit(); err != nil { |
| idRefuse(w) |
| return |
| @@ -169,7 +200,7 @@ func (a *App) idBegin(purpose string) http.HandlerFunc { |
| if direct != "" { |
| idCookie(w, ceremonyCookie, direct, 300) |
| } |
| - idJSONReply(w, 200, map[string]string{"challenge": base64.RawURLEncoding.EncodeToString(challenge)}) |
| + idJSONReply(w, 200, map[string]any{"challenge": base64.RawURLEncoding.EncodeToString(challenge), "credentials": credentials}) |
| } |
| } |
| @@ -214,12 +245,16 @@ func (a *App) idMint(tx *sql.Tx, r *http.Request, s sessions.Session, now int64) |
| return "", errIDProof |
| } |
| stamp := time.Unix(now, 0).UTC().Format(time.RFC3339) |
| + auth := "" |
| + if !s.AuthTime.IsZero() { |
| + auth = s.AuthTime.UTC().Format(time.RFC3339) |
| + } |
| if old := cookieValue(r, a.sessions.CookieName()); old != "" { |
| if _, err = tx.Exec("DELETE FROM sessions WHERE token_hash=?", sessions.HashToken(old)); err != nil { |
| return "", errIDProof |
| } |
| } |
| - _, err = tx.Exec("INSERT INTO sessions(token_hash,subject,method,auth_time,created_at,expires_at) VALUES(?,?,?,?,?,?)", hash, s.Subject, s.Method, stamp, stamp, time.Unix(now, 0).Add(30*24*time.Hour).UTC().Format(time.RFC3339)) |
| + _, err = tx.Exec("INSERT INTO sessions(token_hash,subject,method,auth_time,created_at,expires_at) VALUES(?,?,?,?,?,?)", hash, s.Subject, s.Method, auth, stamp, time.Unix(now, 0).Add(30*24*time.Hour).UTC().Format(time.RFC3339)) |
| if err != nil { |
| return "", errIDProof |
| } |
| @@ -250,7 +285,7 @@ func (a *App) idFinish(purpose string) http.HandlerFunc { |
| return |
| } |
| refuse := func() { _ = tx.Commit(); idRefuse(w) } |
| - if purpose == "register" { |
| + if purpose == "register" || purpose == "replace" { |
| att, e := base64.RawURLEncoding.Strict().DecodeString(body.Attestation) |
| if e != nil { |
| refuse() |
| @@ -261,6 +296,22 @@ func (a *App) idFinish(purpose string) http.HandlerFunc { |
| refuse() |
| return |
| } |
| + if purpose == "replace" { |
| + if a.replaceCredential(tx, r, subject, cred, now) != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + if tx.Commit() != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + idCookie(w, a.sessions.CookieName(), "", -1) |
| + idCookie(w, recoveryCookie, "", -1) |
| + idCookie(w, noticeCookie, cookieValue(r, recoveryCookie), 300) |
| + a.replacementResult(w, !a.sendReplacementNotice(r.Context(), binding)) |
| + idJSONReply(w, 200, map[string]any{"ok": true, "to": "/passkey/replaced"}) |
| + return |
| + } |
| 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) |
| @@ -320,7 +371,7 @@ func (a *App) idFinish(purpose string) http.HandlerFunc { |
| } |
| method += "+passkey" |
| } |
| - token, e := a.idMint(tx, r, sessions.Session{Subject: owner, Method: method}, now) |
| + token, e := a.idMint(tx, r, sessions.Session{Subject: owner, Method: method, AuthTime: time.Unix(now, 0)}, now) |
| if e != nil { |
| idRefuse(w) |
| return |
diff --git a/internal/home/id_passkey_test.go b/internal/home/id_passkey_test.go| index 5139d2d..da5edb5 100644 |
| --- a/internal/home/id_passkey_test.go |
| +++ b/internal/home/id_passkey_test.go |
| @@ -109,3 +109,25 @@ func TestIDEnrollmentCannotTransferCredential(t *testing.T) { |
| t.Fatal("credential transferred to another person") |
| } |
| } |
| + |
| +func TestIDGateOffersBoundLegacyCredentials(t *testing.T) { |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + key := enrol(t, a, s) |
| + if _, err := a.db.Writer().Exec("DELETE FROM home_id_discoverable"); err != nil { |
| + t.Fatal(err) |
| + } |
| + gated := redeemAfterSignIn(t, a, sealtest.CanaryAddress) |
| + begin := idJSON(t, a, "/passkey/signin/begin", nil, gated.Result().Cookies()...) |
| + var body struct { |
| + Credentials []string `json:"credentials"` |
| + } |
| + json.Unmarshal(begin.Body.Bytes(), &body) |
| + if len(body.Credentials) != 1 || body.Credentials[0] != base64.RawURLEncoding.EncodeToString(key.CredID) { |
| + t.Fatal("legacy gate omitted bound credential IDs") |
| + } |
| + r := idJSON(t, a, "/passkey/signin/finish", assertionBody(key, challengeFrom(t, begin), authtest.Options{RPID: credentialHost, Origin: Origin}), gated.Result().Cookies()...) |
| + if r.Code != 200 { |
| + t.Fatal("legacy gated signin failed", r.Code) |
| + } |
| +} |
diff --git a/internal/home/id_recovery.go b/internal/home/id_recovery.go| new file mode 100644 |
| index 0000000..66e6ec5 |
| --- /dev/null |
| +++ b/internal/home/id_recovery.go |
| @@ -0,0 +1,411 @@ |
| +package home |
| + |
| +import ( |
| + "context" |
| + "crypto/rand" |
| + "database/sql" |
| + "encoding/base32" |
| + "encoding/base64" |
| + "encoding/hex" |
| + "encoding/json" |
| + "net/http" |
| + "strings" |
| + "sync" |
| + "time" |
| + |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| + "amadan.net/rastrillo/rastrillo/webauthn" |
| + "github.com/keymaildev/signin" |
| +) |
| + |
| +const recoveryCookie = "__Host-oficina-recovery" |
| +const noticeCookie = "__Host-oficina-notice" |
| + |
| +type mailboxProof struct { |
| + subject, address string |
| + expires int64 |
| +} |
| +type mailboxMemory struct { |
| + mu sync.Mutex |
| + entries map[string]mailboxProof |
| +} |
| + |
| +func (m *mailboxMemory) put(key string, p mailboxProof) bool { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + if m.entries == nil { |
| + m.entries = map[string]mailboxProof{} |
| + } |
| + for k, v := range m.entries { |
| + if v.expires <= time.Now().Unix() { |
| + delete(m.entries, k) |
| + } |
| + } |
| + if len(m.entries) >= 1000 { |
| + return false |
| + } |
| + m.entries[key] = p |
| + time.AfterFunc(time.Until(time.Unix(p.expires, 0)), func() { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + if v, ok := m.entries[key]; ok && v.expires <= time.Now().Unix() { |
| + delete(m.entries, key) |
| + } |
| + }) |
| + return true |
| +} |
| +func (m *mailboxMemory) get(key string) (mailboxProof, bool) { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + p, ok := m.entries[key] |
| + if !ok || p.expires <= time.Now().Unix() { |
| + delete(m.entries, key) |
| + return mailboxProof{}, false |
| + } |
| + return p, true |
| +} |
| +func (m *mailboxMemory) remove(key string) { m.mu.Lock(); defer m.mu.Unlock(); delete(m.entries, key) } |
| + |
| +// The verified address enters only this bounded RAM store. A restart asks the |
| +// person to prove the mailbox again; there is no persisted notice retry queue. |
| +func (a *App) idGate(w http.ResponseWriter, r *http.Request, s sessions.Session, address string) (bool, error) { |
| + tx, now, err := a.idTransaction(r.Context()) |
| + if err != nil { |
| + return false, err |
| + } |
| + defer tx.Rollback() |
| + var n int |
| + if err = tx.QueryRow("SELECT count(*) FROM passkey_credentials WHERE subject=?", s.Subject).Scan(&n); err != nil { |
| + return false, errIDProof |
| + } |
| + if n == 0 { |
| + token, e := a.idMint(tx, r, s, now) |
| + if e != nil { |
| + return false, errIDProof |
| + } |
| + if tx.Commit() != nil { |
| + return false, errIDProof |
| + } |
| + idCookie(w, a.sessions.CookieName(), token, 30*24*3600) |
| + http.Redirect(w, r, sessions.SafeReturn(r, "/"), http.StatusSeeOther) |
| + return true, nil |
| + } |
| + token, hash, err := sessions.NewToken() |
| + if err != nil { |
| + return false, errIDProof |
| + } |
| + if _, err = tx.Exec("DELETE FROM passkey_pending WHERE expires_at<=?", time.Unix(now, 0).UTC().Format(time.RFC3339)); err != nil { |
| + return false, errIDProof |
| + } |
| + if err = tx.QueryRow("SELECT count(*) FROM passkey_pending").Scan(&n); err != nil || n >= 10000 { |
| + return false, errIDProof |
| + } |
| + mailboxAt := s.At |
| + if s.Method == string(signin.MethodKeymail) { |
| + mailboxAt = s.AuthTime |
| + } |
| + if !freshGesture(mailboxAt, time.Unix(now, 0).Add(time.Second), 5*time.Minute) { |
| + mailboxAt = time.Time{} |
| + } |
| + mailboxUnix := int64(0) |
| + if !mailboxAt.IsZero() { |
| + mailboxUnix = mailboxAt.Unix() |
| + } |
| + if _, err = tx.Exec("INSERT INTO passkey_pending(token_hash,subject,method,return_to,expires_at,mailbox_at) VALUES(?,?,?,?,?,?)", hash, s.Subject, s.Method, sessions.SafeReturn(r, "/"), time.Unix(now+300, 0).UTC().Format(time.RFC3339), mailboxUnix); err != nil { |
| + return false, errIDProof |
| + } |
| + if mailboxUnix > 0 && !a.mailboxes.put(hash, mailboxProof{s.Subject, address, mailboxUnix + 300}) { |
| + return false, errIDProof |
| + } |
| + if err = tx.Commit(); err != nil { |
| + a.mailboxes.remove(hash) |
| + return false, errIDProof |
| + } |
| + idCookie(w, gateCookie, token, 300) |
| + http.Redirect(w, r, confirmPath, http.StatusSeeOther) |
| + return true, nil |
| +} |
| +func normalizeIDCode(code string) string { |
| + return strings.NewReplacer("-", "", " ", "").Replace(strings.ToLower(code)) |
| +} |
| +func generateIDCodes(tx *sql.Tx, subject string, now int64) ([]string, error) { |
| + if _, err := tx.Exec("DELETE FROM passkey_recovery_codes WHERE subject=?", subject); err != nil { |
| + return nil, errIDProof |
| + } |
| + codes := make([]string, 10) |
| + for i := range codes { |
| + raw := make([]byte, 16) |
| + if _, err := rand.Read(raw); err != nil { |
| + return nil, errIDProof |
| + } |
| + c := strings.ToLower(base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(raw)) |
| + codes[i] = c[:6] + "-" + c[6:12] + "-" + c[12:19] + "-" + c[19:] |
| + if _, err := tx.Exec("INSERT INTO passkey_recovery_codes(code_hash,subject,created_at) VALUES(?,?,?)", sessions.HashToken(normalizeIDCode(c)), subject, time.Unix(now, 0).UTC().Format(time.RFC3339)); err != nil { |
| + return nil, errIDProof |
| + } |
| + } |
| + return codes, nil |
| +} |
| +func (a *App) regenerateRecoveryCodes(subject string) ([]string, error) { |
| + tx, now, err := a.idTransaction(context.Background()) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer tx.Rollback() |
| + codes, err := generateIDCodes(tx, subject, now) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if tx.Commit() != nil { |
| + return nil, errIDProof |
| + } |
| + return codes, nil |
| +} |
| +func (a *App) idRecovery(w http.ResponseWriter, r *http.Request) { |
| + r.Body = http.MaxBytesReader(w, r.Body, 4096) |
| + if r.ParseForm() != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + code := normalizeIDCode(r.PostForm.Get("code")) |
| + tx, now, err := a.idTransaction(r.Context()) |
| + if err != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + defer tx.Rollback() |
| + subject, binding, err := a.idBinding(tx, r, "signin", now) |
| + if err != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + var mailboxAt int64 |
| + if tx.QueryRow("SELECT mailbox_at FROM passkey_pending WHERE token_hash=?", binding).Scan(&mailboxAt) != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + if mailboxAt <= 0 || mailboxAt > now || mailboxAt+300 <= now { |
| + http.Redirect(w, r, "/signin?force=1", http.StatusSeeOther) |
| + return |
| + } |
| + failed := func() { http.Redirect(w, r, confirmPath+"?recovery=failed", http.StatusSeeOther) } |
| + if _, err = tx.Exec("DELETE FROM home_id_attempts WHERE expires_at<=?", now); err != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + buckets := []struct { |
| + key string |
| + limit int |
| + }{{"account:" + subject, 5}, {"ip:" + blindIndex(a.secrets.Pepper, clientIP(r)), 20}} |
| + for _, b := range buckets { |
| + var failures int |
| + err = tx.QueryRow("SELECT failures FROM home_id_attempts WHERE bucket=?", b.key).Scan(&failures) |
| + if err != nil && err != sql.ErrNoRows { |
| + idRefuse(w) |
| + return |
| + } |
| + if failures >= b.limit { |
| + if tx.Commit() != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + failed() |
| + return |
| + } |
| + } |
| + var got string |
| + err = tx.QueryRow("DELETE FROM passkey_recovery_codes WHERE subject=? AND code_hash=? RETURNING subject", subject, sessions.HashToken(code)).Scan(&got) |
| + if err == sql.ErrNoRows { |
| + var n int |
| + if tx.QueryRow("SELECT count(*) FROM home_id_attempts").Scan(&n) != nil || n >= 10000 { |
| + idRefuse(w) |
| + return |
| + } |
| + for _, b := range buckets { |
| + if _, err = tx.Exec("INSERT INTO home_id_attempts VALUES(?,1,?) ON CONFLICT(bucket) DO UPDATE SET failures=failures+1", b.key, now+900); err != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + } |
| + if tx.Commit() != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + failed() |
| + return |
| + } |
| + if err != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + var method, to, expires string |
| + if err = tx.QueryRow("DELETE FROM passkey_pending WHERE token_hash=? RETURNING method,return_to,expires_at", binding).Scan(&method, &to, &expires); err != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + exp, err := time.Parse(time.RFC3339, expires) |
| + if err != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + token, err := a.idMint(tx, r, sessions.Session{Subject: subject, Method: method + "+recovery", AuthTime: time.Unix(now, 0)}, now) |
| + if err != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + proof, hash, err := sessions.NewToken() |
| + if err != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + if _, err = tx.Exec("DELETE FROM home_id_recovery_proofs WHERE expires_at<=?", now); err != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + if _, err = tx.Exec("INSERT INTO home_id_recovery_proofs VALUES(?,?,?,?)", hash, subject, sessions.HashToken(token), exp.Unix()); err != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + if tx.Commit() != nil { |
| + idRefuse(w) |
| + return |
| + } |
| + if p, ok := a.mailboxes.get(binding); ok && p.subject == subject { |
| + a.mailboxes.remove(binding) |
| + a.mailboxes.put(hash, p) |
| + } |
| + idCookie(w, a.sessions.CookieName(), token, 30*24*3600) |
| + idCookie(w, gateCookie, "", -1) |
| + idCookie(w, recoveryCookie, proof, int(exp.Unix()-now)) |
| + if to == "/" { |
| + to = "/passkey/replace" |
| + } |
| + http.Redirect(w, r, to, http.StatusSeeOther) |
| +} |
| +func (a *App) replacementBinding(tx *sql.Tx, r *http.Request, now int64) (string, string, error) { |
| + s, session, err := a.idSession(tx, r, now) |
| + if err != nil || !strings.HasSuffix(s.Method, "+recovery") { |
| + return "", "", errIDProof |
| + } |
| + proof := cookieValue(r, recoveryCookie) |
| + if proof == "" { |
| + return "", "", errIDProof |
| + } |
| + hash := sessions.HashToken(proof) |
| + var subject string |
| + if err = tx.QueryRow("SELECT subject FROM home_id_recovery_proofs WHERE token_hash=? AND session_hash=? AND subject=? AND expires_at>?", hash, session, s.Subject, now).Scan(&subject); err != nil { |
| + return "", "", errIDProof |
| + } |
| + p, ok := a.mailboxes.get(hash) |
| + if !ok || p.subject != subject { |
| + return "", "", errIDProof |
| + } |
| + return subject, hash, nil |
| +} |
| +func (a *App) handleReplacement(w http.ResponseWriter, r *http.Request) { |
| + tx, now, err := a.idTransaction(r.Context()) |
| + if err != nil { |
| + a.signinFailed(w, r) |
| + return |
| + } |
| + defer tx.Rollback() |
| + subject, _, err := a.replacementBinding(tx, r, now) |
| + if err != nil { |
| + a.signinFailed(w, r) |
| + return |
| + } |
| + if tx.Commit() != nil { |
| + a.signinFailed(w, r) |
| + return |
| + } |
| + a.render(w, r, 200, "id_replace.html", a.passkeyPageData(subject, nil)) |
| +} |
| +func (a *App) replaceCredential(tx *sql.Tx, r *http.Request, subject string, cred webauthn.Credential, now int64) error { |
| + // Removing the old credentials first cannot transfer another person's key: |
| + // the insert below is unique and every deletion rolls back if it fails. |
| + for _, q := range []string{ |
| + "DELETE FROM home_id_discoverable WHERE credential_id IN (SELECT id FROM passkey_credentials WHERE subject=?)", |
| + "DELETE FROM passkey_credentials WHERE subject=?", |
| + "DELETE FROM sessions WHERE subject=?", |
| + "DELETE FROM passkey_recovery_codes WHERE subject=?", |
| + "DELETE FROM passkey_pending WHERE subject=?", |
| + "DELETE FROM passkey_challenges WHERE subject=?", |
| + "DELETE FROM home_id_ceremonies WHERE subject=?", |
| + "DELETE FROM home_id_recovery_proofs WHERE subject=?", |
| + } { |
| + if _, err := tx.Exec(q, subject); err != nil { |
| + return errIDProof |
| + } |
| + } |
| + id := hex.EncodeToString(cred.ID) |
| + if _, err := tx.Exec("INSERT INTO passkey_credentials(id,subject,public_key,sign_count,created_at) VALUES(?,?,?,?,?)", id, subject, cred.PublicKey, cred.SignCount, time.Unix(now, 0).UTC().Format(time.RFC3339)); err != nil { |
| + return errIDProof |
| + } |
| + if _, err := tx.Exec("INSERT INTO home_id_discoverable VALUES(?)", id); err != nil { |
| + return errIDProof |
| + } |
| + return nil |
| +} |
| + |
| +const replacementNoticeSubject = "Your Oficina passkeys were replaced" |
| +const replacementNoticeBody = "A replacement passkey was added to your Oficina account. All previous passkeys were removed, all Oficina ID sessions were signed out, and all recovery codes were invalidated. You may remain signed in to the directory and other apps. Sign in with your new passkey to create new recovery codes." |
| + |
| +func (a *App) sendReplacementNotice(ctx context.Context, key string) bool { |
| + p, ok := a.mailboxes.get(key) |
| + if !ok { |
| + return false |
| + } |
| + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) |
| + defer cancel() |
| + if a.secrets.Mailer.Send(ctx, p.address, replacementNoticeSubject, replacementNoticeBody) != nil { |
| + a.logger.Warn("replacement notice delivery failed") |
| + return false |
| + } |
| + a.mailboxes.remove(key) |
| + return true |
| +} |
| + |
| +const replacementResultCookie = "__Host-oficina-replaced" |
| + |
| +type replacementResult struct { |
| + Expires int64 `json:"expires"` |
| + Failed bool `json:"failed"` |
| +} |
| + |
| +func (a *App) replacementResult(w http.ResponseWriter, failed bool) { |
| + b, _ := json.Marshal(replacementResult{time.Now().Unix() + 600, failed}) |
| + sealed, err := a.secrets.Sealer.Seal("id.replaced", b) |
| + if err != nil { |
| + return |
| + } |
| + idCookie(w, replacementResultCookie, base64.RawURLEncoding.EncodeToString(sealed), 600) |
| +} |
| +func (a *App) readReplacementResult(r *http.Request) (replacementResult, bool) { |
| + var out replacementResult |
| + b, err := base64.RawURLEncoding.Strict().DecodeString(cookieValue(r, replacementResultCookie)) |
| + if err != nil { |
| + return out, false |
| + } |
| + b, err = a.secrets.Sealer.Open("id.replaced", b) |
| + if err != nil || json.Unmarshal(b, &out) != nil { |
| + return out, false |
| + } |
| + return out, out.Expires > time.Now().Unix() && out.Expires <= time.Now().Unix()+600 |
| +} |
| +func (a *App) handleReplacementDone(w http.ResponseWriter, r *http.Request) { |
| + result, ok := a.readReplacementResult(r) |
| + if !ok { |
| + a.signinFailed(w, r) |
| + return |
| + } |
| + key := sessions.HashToken(cookieValue(r, noticeCookie)) |
| + _, available := a.mailboxes.get(key) |
| + a.render(w, r, 200, "id_replaced.html", map[string]any{"NoticeFailed": result.Failed, "CanRetry": available}) |
| +} |
| +func (a *App) handleNoticeRetry(w http.ResponseWriter, r *http.Request) { |
| + if result, ok := a.readReplacementResult(r); ok && result.Failed { |
| + success := a.sendReplacementNotice(r.Context(), sessions.HashToken(cookieValue(r, noticeCookie))) |
| + a.replacementResult(w, !success) |
| + } |
| + http.Redirect(w, r, "/passkey/replaced", http.StatusSeeOther) |
| +} |
diff --git a/internal/home/id_recovery_test.go b/internal/home/id_recovery_test.go| new file mode 100644 |
| index 0000000..5e84c82 |
| --- /dev/null |
| +++ b/internal/home/id_recovery_test.go |
| @@ -0,0 +1,305 @@ |
| +package home |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/base64" |
| + "errors" |
| + "fmt" |
| + "github.com/keymaildev/signin" |
| + "log/slog" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "regexp" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/home/internal/home/sealtest" |
| + "amadan.net/rastrillo/rastrillo/webauthn/authtest" |
| +) |
| + |
| +func idCodes(t *testing.T, app *testApp, s *http.Cookie) []string { |
| + t.Helper() |
| + r := exchangeRequest(app.App, "POST", Origin+"/passkey/codes", Origin, url.Values{}, s) |
| + if r.Code != 200 { |
| + t.Fatal("codes", r.Code) |
| + } |
| + matches := regexp.MustCompile(`<code>([^<]+)</code>`).FindAllStringSubmatch(r.Body.String(), -1) |
| + var codes []string |
| + for _, m := range matches { |
| + codes = append(codes, m[1]) |
| + } |
| + if len(codes) != 10 { |
| + t.Fatal("wrong code count", len(codes)) |
| + } |
| + return codes |
| +} |
| +func idRecover(app *testApp, code string, cookies ...*http.Cookie) *http.Response { |
| + return exchangeRequest(app.App, "POST", Origin+"/passkey/signin/recovery", Origin, url.Values{"code": {code}}, cookies...).Result() |
| +} |
| +func TestIDRecoveryEntropy(t *testing.T) { |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + enrol(t, a, s) |
| + seen := map[string]bool{} |
| + for _, c := range idCodes(t, a, s) { |
| + raw := strings.ReplaceAll(c, "-", "") |
| + if len(raw) < 16 || seen[raw] { |
| + t.Fatal("less than 80 random bits or repeated code") |
| + } |
| + seen[raw] = true |
| + } |
| + sealtest.AssertNoPlaintext(t, a.dbPath) |
| +} |
| +func TestIDRecoveryAttemptLimitSurvivesReconstruction(t *testing.T) { |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + enrol(t, a, s) |
| + codes := idCodes(t, a, s) |
| + gated := redeemAfterSignIn(t, a, sealtest.CanaryAddress) |
| + var wg sync.WaitGroup |
| + for i := 0; i < 16; i++ { |
| + wg.Add(1) |
| + go func() { defer wg.Done(); idRecover(a, "bad-code", gated.Result().Cookies()...) }() |
| + } |
| + wg.Wait() |
| + app, err := New(a.secrets, a.db, a.logger) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + a.App = app |
| + r := exchangeRequest(a.App, "POST", Origin+"/passkey/signin/recovery", Origin, url.Values{"code": {codes[0]}}, gated.Result().Cookies()...) |
| + if sessionCookie(r) != nil { |
| + t.Fatal("parallel failures or restart reset recovery allowance") |
| + } |
| +} |
| +func TestIDRecoveryReplacementRevokesEverything(t *testing.T) { |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + old := enrol(t, a, s) |
| + codes := idCodes(t, a, s) |
| + gated := redeemAfterSignIn(t, a, sealtest.CanaryAddress) |
| + recovery := exchangeRequest(a.App, "POST", Origin+"/passkey/signin/recovery", Origin, url.Values{"code": {codes[0]}}, gated.Result().Cookies()...) |
| + if sessionCookie(recovery) == nil { |
| + t.Fatal("recovery signin", recovery.Code) |
| + } |
| + cookies := recovery.Result().Cookies() |
| + // Recovery is not a way to add an attacker key while retaining the old one. |
| + if r := idJSON(t, a, "/passkey/register/begin", nil, cookies...); r.Code == 200 { |
| + t.Fatal("recovery bypassed replacement confirmation") |
| + } |
| + page := exchangeRequest(a.App, "GET", Origin+"/passkey/replace", "", nil, cookies...) |
| + if page.Code != 200 || !strings.Contains(page.Body.String(), "Replace all passkeys") { |
| + t.Fatal("missing explicit replacement confirmation", page.Code) |
| + } |
| + begin := idJSON(t, a, "/passkey/replace/begin", nil, cookies...) |
| + challenge := challengeFrom(t, begin) |
| + replacement, _ := authtest.New() |
| + cd, att := replacement.Create(challenge, authtest.Options{RPID: credentialHost, Origin: Origin}) |
| + done := idJSON(t, a, "/passkey/replace/finish", map[string]string{"clientDataJSON": base64.RawURLEncoding.EncodeToString(cd), "attestationObject": base64.RawURLEncoding.EncodeToString(att)}, cookies...) |
| + if done.Code != 200 { |
| + t.Fatal("replace", done.Code) |
| + } |
| + for _, table := range []string{"sessions", "passkey_recovery_codes", "passkey_pending", "home_id_recovery_proofs"} { |
| + var n int |
| + if err := a.db.Writer().QueryRow("SELECT count(*) FROM " + table).Scan(&n); err != nil || n != 0 { |
| + t.Fatal("replacement retained authority", table, n, err) |
| + } |
| + } |
| + var n int |
| + a.db.Writer().QueryRow("SELECT count(*) FROM passkey_credentials").Scan(&n) |
| + if n != 1 { |
| + t.Fatal("old passkeys remain", n) |
| + } |
| + b := idJSON(t, a, "/passkey/direct/begin", nil) |
| + c := namedCookie(t, b, "__Host-oficina-ceremony") |
| + if r := idJSON(t, a, "/passkey/direct/finish", assertionBody(old, challengeFrom(t, b), authtest.Options{RPID: credentialHost, Origin: Origin}), c); r.Code == 200 { |
| + t.Fatal("old passkey still works") |
| + } |
| + b = idJSON(t, a, "/passkey/direct/begin", nil) |
| + c = namedCookie(t, b, "__Host-oficina-ceremony") |
| + r := idJSON(t, a, "/passkey/direct/finish", assertionBody(replacement, challengeFrom(t, b), authtest.Options{RPID: credentialHost, Origin: Origin}), c) |
| + if r.Code != 200 { |
| + t.Fatal("replacement cannot sign in", r.Code) |
| + } |
| + idCodes(t, a, sessionCookie(r)) |
| + mail, ok := a.mailer.last() |
| + if !ok || mail.To != sealtest.CanaryAddress || mail.Subject != "Your Oficina passkeys were replaced" { |
| + t.Fatal("replacement notice missing") |
| + } |
| + sealtest.AssertNoPlaintext(t, a.dbPath) |
| +} |
| + |
| +type idFailMailer struct{} |
| + |
| +func (idFailMailer) Send(context.Context, string, string, string) error { |
| + return errors.New("SMTP failed for " + sealtest.CanaryAddress) |
| +} |
| +func TestIDSMTPFailureDoesNotLeak(t *testing.T) { |
| + a := newTestApp(t) |
| + var logs bytes.Buffer |
| + a.logger = slog.New(slog.NewTextHandler(&logs, nil)) |
| + a.flow.Mailer = idFailMailer{} |
| + r := signIn(t, a, sealtest.CanaryAddress) |
| + if sessionCookie(r) != nil || strings.Contains(logs.String(), sealtest.CanaryAddress) { |
| + t.Fatal("SMTP failure authenticated or logged address") |
| + } |
| + sealtest.AssertNoPlaintext(t, a.dbPath) |
| +} |
| + |
| +func TestIDRecoveryRequiresFreshMailboxGesture(t *testing.T) { |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + enrol(t, a, s) |
| + codes := idCodes(t, a, s) |
| + for _, at := range []time.Time{{}, time.Now().Add(-10 * time.Minute), time.Now().Add(time.Hour)} { |
| + req := httptest.NewRequest("GET", Origin+callbackPath, nil) |
| + w := httptest.NewRecorder() |
| + a.completeSignIn(w, req, signin.Identity{Address: sealtest.CanaryAddress, Method: signin.MethodKeymail, At: time.Now(), AuthTime: at}) |
| + r := exchangeRequest(a.App, "POST", Origin+"/passkey/signin/recovery", Origin, url.Values{"code": {codes[0]}}, w.Result().Cookies()...) |
| + if sessionCookie(r) != nil { |
| + t.Fatal("passive or stale Keymail recovered account") |
| + } |
| + } |
| +} |
| + |
| +func replacementFixture(t *testing.T) (*testApp, []*http.Cookie, map[string]string) { |
| + t.Helper() |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + enrol(t, a, s) |
| + codes := idCodes(t, a, s) |
| + gated := redeemAfterSignIn(t, a, sealtest.CanaryAddress) |
| + recovered := exchangeRequest(a.App, "POST", Origin+"/passkey/signin/recovery", Origin, url.Values{"code": {codes[0]}}, gated.Result().Cookies()...) |
| + if sessionCookie(recovered) == nil { |
| + t.Fatal("recovery failed", recovered.Code) |
| + } |
| + cookies := recovered.Result().Cookies() |
| + begin := idJSON(t, a, "/passkey/replace/begin", nil, cookies...) |
| + key, _ := authtest.New() |
| + cd, att := key.Create(challengeFrom(t, begin), authtest.Options{RPID: credentialHost, Origin: Origin}) |
| + return a, cookies, map[string]string{"clientDataJSON": base64.RawURLEncoding.EncodeToString(cd), "attestationObject": base64.RawURLEncoding.EncodeToString(att)} |
| +} |
| +func TestIDNoticeFailureSurvivesRestartWithoutAddress(t *testing.T) { |
| + a, cookies, body := replacementFixture(t) |
| + var logs bytes.Buffer |
| + a.logger = slog.New(slog.NewTextHandler(&logs, nil)) |
| + a.secrets.Mailer = idFailMailer{} |
| + done := idJSON(t, a, "/passkey/replace/finish", body, cookies...) |
| + if done.Code != 200 { |
| + t.Fatal("delivery failure rolled back replacement", done.Code) |
| + } |
| + var n int |
| + a.db.Writer().QueryRow("SELECT count(*) FROM sessions").Scan(&n) |
| + if n != 0 { |
| + t.Fatal("delivery failure preserved sessions") |
| + } |
| + if strings.Contains(logs.String(), sealtest.CanaryAddress) { |
| + t.Fatal("notice error leaked address") |
| + } |
| + app, err := New(a.secrets, a.db, a.logger) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + a.App = app |
| + page := exchangeRequest(a.App, "GET", Origin+"/passkey/replaced", "", nil, done.Result().Cookies()...) |
| + if !strings.Contains(page.Body.String(), "could not send") || !strings.Contains(page.Body.String(), "can no longer be sent") || strings.Contains(page.Body.String(), "Send email again") { |
| + t.Fatal("restart hid notice failure or retained retry") |
| + } |
| + sealtest.AssertNoPlaintext(t, a.dbPath) |
| +} |
| +func TestIDReplacementRollback(t *testing.T) { |
| + for _, target := range []struct{ table, operation string }{{"sessions", "DELETE"}, {"passkey_recovery_codes", "DELETE"}, {"passkey_credentials", "DELETE"}, {"home_id_recovery_proofs", "DELETE"}, {"passkey_credentials", "INSERT"}, {"home_id_discoverable", "INSERT"}} { |
| + t.Run(target.table+target.operation, func(t *testing.T) { |
| + a, cookies, body := replacementFixture(t) |
| + before := map[string]int{} |
| + for _, table := range []string{"sessions", "passkey_credentials", "passkey_recovery_codes", "home_id_recovery_proofs"} { |
| + var n int |
| + if err := a.db.Writer().QueryRow("SELECT count(*) FROM " + table).Scan(&n); err != nil { |
| + t.Fatal(err) |
| + } |
| + before[table] = n |
| + } |
| + if _, err := a.db.Writer().Exec("CREATE TRIGGER fail_replacement BEFORE " + target.operation + " ON " + target.table + " BEGIN SELECT RAISE(ABORT,'injected'); END"); err != nil { |
| + t.Fatal(err) |
| + } |
| + r := idJSON(t, a, "/passkey/replace/finish", body, cookies...) |
| + if r.Code == 200 { |
| + t.Fatal("failed write reported success") |
| + } |
| + for table, want := range before { |
| + var n int |
| + a.db.Writer().QueryRow("SELECT count(*) FROM " + table).Scan(&n) |
| + if n != want { |
| + t.Fatal("partial replacement", table, n, want) |
| + } |
| + } |
| + }) |
| + } |
| +} |
| +func TestIDReplacementProofBinding(t *testing.T) { |
| + for _, kind := range []string{"no-proof", "no-session", "expired", "wrong-person", "bad-uv", "replay"} { |
| + t.Run(kind, func(t *testing.T) { |
| + a, cookies, body := replacementFixture(t) |
| + switch kind { |
| + case "no-proof": |
| + cookies = []*http.Cookie{func() *http.Cookie { |
| + for _, c := range cookies { |
| + if c.Name == a.sessions.CookieName() { |
| + return c |
| + } |
| + } |
| + return nil |
| + }()} |
| + case "no-session": |
| + cookies = []*http.Cookie{func() *http.Cookie { |
| + for _, c := range cookies { |
| + if c.Name == recoveryCookie { |
| + return c |
| + } |
| + } |
| + return nil |
| + }()} |
| + case "expired": |
| + a.db.Writer().Exec("UPDATE home_id_recovery_proofs SET expires_at=0") |
| + case "wrong-person": |
| + a.db.Writer().Exec("UPDATE home_id_recovery_proofs SET subject='another-person'") |
| + case "bad-uv": |
| + b := idJSON(t, a, "/passkey/replace/begin", nil, cookies...) |
| + k, _ := authtest.New() |
| + cd, att := k.Create(challengeFrom(t, b), authtest.Options{RPID: credentialHost, Origin: Origin, Flags: authtest.FlagUserPresent | authtest.FlagAttestedData}) |
| + body = map[string]string{"clientDataJSON": base64.RawURLEncoding.EncodeToString(cd), "attestationObject": base64.RawURLEncoding.EncodeToString(att)} |
| + case "replay": |
| + if r := idJSON(t, a, "/passkey/replace/finish", body, cookies...); r.Code != 200 { |
| + t.Fatal("first replacement failed") |
| + } |
| + } |
| + if r := idJSON(t, a, "/passkey/replace/finish", body, cookies...); r.Code == 200 { |
| + t.Fatal("unbound recovery proof replaced passkeys", kind) |
| + } |
| + }) |
| + } |
| +} |
| +func TestIDRecoveryIPLimitAcrossAccounts(t *testing.T) { |
| + a := newTestApp(t) |
| + for i := 0; i < 6; i++ { |
| + address := fmt.Sprintf("account%d@example.invalid", i) |
| + s := signInFully(t, a, address) |
| + enrol(t, a, s) |
| + codes := idCodes(t, a, s) |
| + g := redeemAfterSignIn(t, a, address) |
| + if i < 5 { |
| + for j := 0; j < 4; j++ { |
| + idRecover(a, "wrong", g.Result().Cookies()...) |
| + } |
| + } else { |
| + r := exchangeRequest(a.App, "POST", Origin+"/passkey/signin/recovery", Origin, url.Values{"code": {codes[0]}}, g.Result().Cookies()...) |
| + if sessionCookie(r) != nil { |
| + t.Fatal("IP budget did not span accounts") |
| + } |
| + } |
| + } |
| +} |
diff --git a/internal/home/id_signout_test.go b/internal/home/id_signout_test.go| new file mode 100644 |
| index 0000000..41a6f5a |
| --- /dev/null |
| +++ b/internal/home/id_signout_test.go |
| @@ -0,0 +1,75 @@ |
| +package home |
| + |
| +import ( |
| + "context" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/home/internal/home/sealtest" |
| +) |
| + |
| +func TestIDLocalSignoutWithHangingIssuer(t *testing.T) { |
| + accepted := make(chan struct{}) |
| + release := make(chan struct{}) |
| + issuer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { close(accepted); <-release })) |
| + defer issuer.Close() |
| + defer close(release) |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + defer cancel() |
| + req, _ := http.NewRequestWithContext(ctx, "GET", issuer.URL, nil) |
| + done := make(chan struct{}) |
| + go func() { |
| + defer close(done) |
| + resp, _ := issuer.Client().Do(req) |
| + if resp != nil { |
| + resp.Body.Close() |
| + } |
| + }() |
| + select { |
| + case <-accepted: |
| + case <-time.After(time.Second): |
| + t.Fatal("issuer did not accept connection") |
| + } |
| + p := newExchangePair(t) |
| + credential, directory := signedInPair(t, p) |
| + p.directory.origins.Credential = issuer.URL |
| + r := exchangeRequest(p.directory, "POST", directoryOrigin+"/signout", directoryOrigin, url.Values{}, directory) |
| + if r.Code != 303 || r.Header().Get("Location") != "/signed-out" { |
| + t.Fatal("local signout depends on hanging issuer", r.Code, r.Header().Get("Location")) |
| + } |
| + if s, ok := p.directory.sessions.From(func() *http.Request { |
| + r := httptest.NewRequest("GET", directoryOrigin+"/", nil) |
| + r.AddCookie(directory) |
| + return r |
| + }()); ok || s.Subject != "" { |
| + t.Fatal("local session not revoked") |
| + } |
| + page := exchangeRequest(p.directory, "GET", directoryOrigin+"/signed-out", "", nil) |
| + if page.Code != 200 { |
| + t.Fatal("local landing failed") |
| + } |
| + // A credential-origin sign-out also lands on its own origin. |
| + end := exchangeRequest(p.credential.App, "POST", Origin+"/signout", Origin, url.Values{}, credential) |
| + if end.Code != 303 || end.Header().Get("Location") != Origin+"/signed-out" { |
| + t.Fatal("credential signout leaves its origin") |
| + } |
| + if page := exchangeRequest(p.credential.App, "GET", Origin+"/signed-out", "", nil); page.Code != 200 { |
| + t.Fatal("credential landing missing") |
| + } |
| + cancel() |
| + select { |
| + case <-done: |
| + case <-time.After(time.Second): |
| + t.Fatal("issuer probe failed to cancel") |
| + } |
| +} |
| +func TestIDSigninRemainsLocal(t *testing.T) { |
| + p := newExchangePair(t) |
| + s := signInFully(t, p.credential, sealtest.CanaryAddress) |
| + if s == nil { |
| + t.Fatal("local signin failed") |
| + } |
| +} |
diff --git a/internal/home/migrations/0003_id_ceremonies.sql b/internal/home/identity/migrations/0001_ceremonies.sql| similarity index 100% |
| rename from internal/home/migrations/0003_id_ceremonies.sql |
| rename to internal/home/identity/migrations/0001_ceremonies.sql |
diff --git a/internal/home/identity/migrations/0002_recovery.sql b/internal/home/identity/migrations/0002_recovery.sql| new file mode 100644 |
| index 0000000..772f41e |
| --- /dev/null |
| +++ b/internal/home/identity/migrations/0002_recovery.sql |
| @@ -0,0 +1,14 @@ |
| +CREATE TABLE home_id_attempts ( |
| + bucket TEXT PRIMARY KEY, |
| + failures INTEGER NOT NULL, |
| + expires_at INTEGER NOT NULL |
| +); |
| +CREATE TABLE home_id_recovery_proofs ( |
| + token_hash TEXT PRIMARY KEY, |
| + subject TEXT NOT NULL, |
| + session_hash TEXT NOT NULL, |
| + expires_at INTEGER NOT NULL |
| +); |
| +CREATE INDEX home_id_recovery_expiry ON home_id_recovery_proofs(expires_at); |
| + |
| +ALTER TABLE passkey_pending ADD COLUMN mailbox_at INTEGER NOT NULL DEFAULT 0; |
diff --git a/internal/home/keymail_fresh_test.go b/internal/home/keymail_fresh_test.go| index 08dfc1e..824800b 100644 |
| --- a/internal/home/keymail_fresh_test.go |
| +++ b/internal/home/keymail_fresh_test.go |
| @@ -85,7 +85,7 @@ func TestFreshKeymailGestureYieldsAssertionWithKeymailAuthTime(t *testing.T) { |
| stub.reauth = true |
| // Inside the window but well away from now, so an implementation |
| // that stamped issuance time over Keymail's report would be seen. |
| - stub.authTime = time.Now().Add(-90 * time.Second).Truncate(time.Second) |
| + stub.authTime = time.Now().Truncate(time.Second) |
| intent, navigation := freshSignInForm(t, p, nil) |
| u, pending := keymailContinuation(t, p, freshBegin(t, p, "/signin", freshKeymailAddress, intent, navigation)) |
| @@ -293,12 +293,6 @@ func TestKeymailSessionWithoutGestureTimeIsNotFresh(t *testing.T) { |
| } |
| _, intent := p.startFresh(t, session) |
| resume := exchangeRequest(p.credential.App, "GET", Origin+"/authorize/resume", "", nil, intent, session) |
| - if gesture { |
| - if resume.Code != 200 || !strings.Contains(resume.Body.String(), `name="assertion"`) { |
| - t.Fatal("a Keymail session with a fresh gesture was refused", resume.Code) |
| - } |
| - return |
| - } |
| if resume.Code != 303 || resume.Header().Get("Location") != "/signin?return_to=%2Fauthorize%2Fresume" || strings.Contains(resume.Body.String(), `name="assertion"`) { |
| t.Fatal("a Keymail session with no gesture time satisfied a step-up", resume.Code) |
| } |
diff --git a/internal/home/models.go b/internal/home/models.go| index 803e86b..23fa74d 100644 |
| --- a/internal/home/models.go |
| +++ b/internal/home/models.go |
| @@ -2,6 +2,7 @@ package home |
| import ( |
| "embed" |
| + "io/fs" |
| "amadan.net/rastrillo/rastrillo/migrate" |
| "amadan.net/rastrillo/rastrillo/passkey" |
| @@ -37,3 +38,16 @@ var Schema = migrate.MustFromFS(migrationsFS, "home") |
| // person ref — so the worry about inheriting an address-bearing subject |
| // does not arise. Said here rather than left to be rediscovered. |
| var BootSchema = migrate.Merge(sessions.Schema, passkey.Schema, Schema) |
| + |
| +// Identity migrations extend the serving credential role. Keep the historical |
| +// BootSchema unchanged: its exact objects are frozen in admission profiles. |
| +// |
| +//go:embed identity/migrations/*.sql |
| +var identityFS embed.FS |
| +var identitySchema = func() *migrate.Set { |
| + sub, err := fs.Sub(identityFS, "identity") |
| + if err != nil { |
| + panic(err) |
| + } |
| + return migrate.MustFromFS(sub, "home_id") |
| +}() |
diff --git a/internal/home/operator_http_test.go b/internal/home/operator_http_test.go| index b8b3016..c61caf7 100644 |
| --- a/internal/home/operator_http_test.go |
| +++ b/internal/home/operator_http_test.go |
| @@ -261,7 +261,8 @@ func (f *operatorFixture) paulDirectory(t *testing.T, credentialSession *http.Co |
| pending := namedCookie(t, start, "__Host-oficina-assertion-pending") |
| authorize := exchangeRequest(f.credential.App, "GET", start.Header().Get("Location"), "", nil, credentialSession) |
| intent := namedCookie(t, authorize, assertionIntentCookie) |
| - resume := exchangeRequest(f.credential.App, "GET", Origin+"/authorize/resume", "", nil, intent, credentialSession) |
| + credentialSession = signInFully(t, f.credential, f.paulAddress) |
| + resume := exchangeRequest(f.credential.App, "POST", Origin+"/authorize/resume", Origin, nil, intent, credentialSession) |
| m := regexp.MustCompile(`name="assertion" value="([^"]+)"`).FindStringSubmatch(resume.Body.String()) |
| if resume.Code != 200 || len(m) != 2 { |
| t.Fatal("resume", resume.Code, resume.Header().Get("Location")) |
diff --git a/internal/home/passkey.go b/internal/home/passkey.go| index 87a084c..c80da24 100644 |
| --- a/internal/home/passkey.go |
| +++ b/internal/home/passkey.go |
| @@ -4,9 +4,11 @@ import ( |
| "embed" |
| "encoding/base64" |
| "net/http" |
| + "strings" |
| "time" |
| "amadan.net/rastrillo/rastrillo/passkey" |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| "amadan.net/rastrillo/rastrillo/webauthn" |
| ) |
| @@ -148,6 +150,10 @@ func (a *App) handlePasskeyEnrol(w http.ResponseWriter, r *http.Request) { |
| http.Redirect(w, r, "/signin", http.StatusSeeOther) |
| return |
| } |
| + if strings.Contains(sess.Method, "recovery") { |
| + http.Redirect(w, r, "/passkey/replace", http.StatusSeeOther) |
| + return |
| + } |
| a.render(w, r, http.StatusOK, "passkey_enrol.html", a.passkeyPageData(sess.Subject, nil)) |
| } |
| @@ -181,7 +187,21 @@ func (a *App) handleRegenerateRecoveryCodes(w http.ResponseWriter, r *http.Reque |
| http.Redirect(w, r, "/signin", http.StatusSeeOther) |
| return |
| } |
| - codes, err := a.passkeys.RegenerateRecoveryCodes(sess.Subject) |
| + tx, now, err := a.idTransaction(r.Context()) |
| + if err != nil { |
| + a.serverError(w, r) |
| + return |
| + } |
| + defer tx.Rollback() |
| + live, _, err := a.idSession(tx, r, now) |
| + if err != nil || live.Subject != sess.Subject || strings.Contains(live.Method, "recovery") || !sessions.Fresh(live, codesFreshness, time.Unix(now, 0)) { |
| + a.signinFailed(w, r) |
| + return |
| + } |
| + codes, err := generateIDCodes(tx, sess.Subject, now) |
| + if err == nil { |
| + err = tx.Commit() |
| + } |
| if err != nil { |
| a.logger.Error("regenerate recovery codes", "person", sess.Subject, "err", err) |
| a.serverError(w, r) |
diff --git a/internal/home/passkey_test.go b/internal/home/passkey_test.go| index eaf6edf..30f8417 100644 |
| --- a/internal/home/passkey_test.go |
| +++ b/internal/home/passkey_test.go |
| @@ -133,10 +133,10 @@ func redeemAfterSignIn(t *testing.T, app *testApp, addr string) *httptest.Respon |
| // can evade a source search, so the search alone is not a security proof. |
| func TestSessionIssuanceStaysAtCredentialAndDirectoryBoundaries(t *testing.T) { |
| got := grepPackage(t, "a.sessions.SignIn(") |
| - if len(got) != 2 || got[0] != "directory.go" || got[1] != "signin.go" { |
| + if len(got) != 1 || got[0] != "directory.go" { |
| t.Fatalf("unexpected app session boundaries: %v", got) |
| } |
| - gate := grepPackage(t, "a.passkeys.Gate(") |
| + gate := grepPackage(t, "a.idGate(") |
| if len(gate) != 1 || gate[0] != "signin.go" { |
| t.Fatalf("credential gate moved: %v", gate) |
| } |
diff --git a/internal/home/runtime.go b/internal/home/runtime.go| index cc8c359..02cb0d8 100644 |
| --- a/internal/home/runtime.go |
| +++ b/internal/home/runtime.go |
| @@ -214,7 +214,7 @@ func (cfg Runtime) ServingSchema() *migrate.Set { |
| case "directory": |
| return migrate.Merge(cfg.Schema(), operator.DirectoryHTTPSchema, directorydata.TeamSchema) |
| case "credential": |
| - return migrate.Merge(cfg.Schema(), operator.CredentialHTTPSchema) |
| + return migrate.Merge(cfg.Schema(), operator.CredentialHTTPSchema, identitySchema) |
| } |
| return cfg.Schema() |
| } |
diff --git a/internal/home/shared_chrome_test.go b/internal/home/shared_chrome_test.go| index e6c3118..0d1373a 100644 |
| --- a/internal/home/shared_chrome_test.go |
| +++ b/internal/home/shared_chrome_test.go |
| @@ -435,7 +435,7 @@ func TestHopKeepsTheSkyPlaceholder(t *testing.T) { |
| p := newExchangePair(t) |
| credential := signInFully(t, p.credential, sealtest.CanaryAddress) |
| _, intent := p.start(t) |
| - rec := exchangeRequest(p.credential.App, "GET", Origin+"/authorize/resume", "", nil, intent, credential) |
| + rec := exchangeRequest(p.credential.App, "POST", Origin+"/authorize/resume", Origin, nil, intent, credential) |
| body := rec.Body.String() |
| if rec.Code != http.StatusOK || !strings.Contains(body, `name="assertion"`) { |
| t.Fatalf("resume: %d", rec.Code) |
diff --git a/internal/home/signin.go b/internal/home/signin.go| index e459ff0..1977237 100644 |
| --- a/internal/home/signin.go |
| +++ b/internal/home/signin.go |
| @@ -270,7 +270,7 @@ func (a *App) beginFailed(w http.ResponseWriter, r *http.Request, err error) boo |
| // information about whether that address has been tried. |
| a.renderSigninForm(w, r, http.StatusTooManyRequests, "Too many attempts. Try again shortly.") |
| default: |
| - a.logger.Error("signin begin", "err", err) |
| + a.logger.Error("signin begin failed") |
| a.renderSigninForm(w, r, http.StatusInternalServerError, "Something went wrong. Try again.") |
| } |
| return true |
| @@ -423,7 +423,7 @@ func (a *App) completeSignIn(w http.ResponseWriter, r *http.Request, id signin.I |
| // with no passkey passes through untouched. |
| target := readReturn(r) |
| writeReturn(w, "/") |
| - gated, err := a.passkeys.Gate(w, requestWithReturn(r, target), sess) |
| + gated, err := a.idGate(w, requestWithReturn(r, target), sess, id.Address) |
| if err != nil { |
| a.logger.Error("passkey gate", "person", ref, "err", err) |
| a.signinFailed(w, r) |
| @@ -433,12 +433,6 @@ func (a *App) completeSignIn(w http.ResponseWriter, r *http.Request, id signin.I |
| return |
| } |
| - if err := a.sessions.SignIn(w, r, sess); err != nil { |
| - a.logger.Error("mint session", "person", ref, "err", err) |
| - a.signinFailed(w, r) |
| - return |
| - } |
| - http.Redirect(w, r, target, http.StatusSeeOther) |
| } |
| // signinFailed is the one answer every failed redemption gets. One page, |
diff --git a/internal/home/signin_return_factor_test.go b/internal/home/signin_return_factor_test.go| index cf3ba27..9c8af06 100644 |
| --- a/internal/home/signin_return_factor_test.go |
| +++ b/internal/home/signin_return_factor_test.go |
| @@ -68,7 +68,7 @@ func TestCredentialReturnSecondFactors(t *testing.T) { |
| if got.Header().Get("Location") != "/passkey/enrol" || sessionCookie(got) == nil { |
| t.Fatalf("recovery continuation=%q status=%d", got.Header().Get("Location"), got.Code) |
| } |
| - if dest := returnRequest(app, "GET", "/passkey/enrol", nil, sessionCookie(got)); dest.Code != 200 { |
| + if dest := returnRequest(app, "GET", "/passkey/enrol", nil, sessionCookie(got)); dest.Code != 303 || dest.Header().Get("Location") != "/passkey/replace" { |
| t.Fatalf("recovery freshness=%d", dest.Code) |
| } |
| } else { |
diff --git a/internal/home/signout.go b/internal/home/signout.go| index 5a884fa..fc48d9b 100644 |
| --- a/internal/home/signout.go |
| +++ b/internal/home/signout.go |
| @@ -130,7 +130,7 @@ const ( |
| func (a *App) signoutReturn(r *http.Request) (string, signoutVerdict) { |
| if csrf.SameOrigin(r, a.origins.Credential) { |
| - return a.origins.Directory, signoutAdmitted |
| + return a.origins.Credential, signoutAdmitted |
| } |
| claimed := r.Header.Get("Origin") |
| if claimed == "" || claimed == "null" { |
diff --git a/internal/home/signout_test.go b/internal/home/signout_test.go| index 434724d..fbf95c3 100644 |
| --- a/internal/home/signout_test.go |
| +++ b/internal/home/signout_test.go |
| @@ -26,11 +26,11 @@ func signedInPair(t *testing.T, p exchangePair) (credential, directory *http.Coo |
| func resumeMints(t *testing.T, p exchangePair, credential *http.Cookie) bool { |
| t.Helper() |
| _, intent := p.start(t) |
| - rec := exchangeRequest(p.credential.App, "GET", Origin+"/authorize/resume", "", nil, intent, credential) |
| + rec := exchangeRequest(p.credential.App, "POST", Origin+"/authorize/resume", Origin, nil, intent, credential) |
| switch { |
| case rec.Code == 200 && strings.Contains(rec.Body.String(), `name="assertion"`): |
| return true |
| - case rec.Code == 303 && strings.HasPrefix(rec.Header().Get("Location"), "/signin"): |
| + case rec.Code == 403 || (rec.Code == 303 && strings.HasPrefix(rec.Header().Get("Location"), "/signin")): |
| return false |
| } |
| t.Fatalf("resume answered %d %q", rec.Code, rec.Header().Get("Location")) |
| @@ -78,7 +78,7 @@ func TestSignOutEndsTheCredentialSession(t *testing.T) { |
| // the credential origin receives a POST it can origin-check, rather |
| // than a GET anyone could link to. |
| out := exchangeRequest(p.directory, "POST", directoryOrigin+"/signout", directoryOrigin, url.Values{}, directory) |
| - if out.Code != http.StatusTemporaryRedirect || out.Header().Get("Location") != Origin+"/signout" { |
| + if out.Code != http.StatusSeeOther || out.Header().Get("Location") != "/signed-out" { |
| t.Fatalf("directory sign-out: %d %q", out.Code, out.Header().Get("Location")) |
| } |
| if !clearsCookie(out, directory.Name) { |
| @@ -342,7 +342,7 @@ func TestCredentialSignOutRefusalIsBrandedAndRecoverable(t *testing.T) { |
| r.AddCookie(credential) |
| rec := httptest.NewRecorder() |
| p.credential.Router().ServeHTTP(rec, r) |
| - if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != directoryOrigin+"/signed-out" { |
| + if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != Origin+"/signed-out" { |
| t.Fatalf("Finish signing out button: %d %q", rec.Code, rec.Header().Get("Location")) |
| } |
| if resumeMints(t, p, credential) { |
| @@ -382,7 +382,7 @@ func TestCredentialSignOutFromAPreviewConfirmsFirst(t *testing.T) { |
| r.AddCookie(credential) |
| confirm := httptest.NewRecorder() |
| p.credential.Router().ServeHTTP(confirm, r) |
| - if confirm.Code != http.StatusSeeOther || confirm.Header().Get("Location") != directoryOrigin+"/signed-out" || !clearsCookie(confirm, credential.Name) { |
| + if confirm.Code != http.StatusSeeOther || confirm.Header().Get("Location") != Origin+"/signed-out" || !clearsCookie(confirm, credential.Name) { |
| t.Fatalf("%+v: confirm %d %q", c, confirm.Code, confirm.Header().Get("Location")) |
| } |
| // The row is revoked, so a copy of the old cookie is refused. |
diff --git a/internal/home/static/passkey.js b/internal/home/static/passkey.js| index 7d7e560..c3dc999 100644 |
| --- a/internal/home/static/passkey.js |
| +++ b/internal/home/static/passkey.js |
| @@ -8,7 +8,7 @@ |
| // of static files (spec ruling superseding 21/24: no script by default, |
| // enhance only, prefer none). Its path is stable so that list can name |
| // it — a rule that cannot name its subject is not a rule. |
| -import { register, authenticate, available } from "/static/webauthn.mjs"; |
| +import { register, authenticate, available, fromB64url, toB64url } from "/static/webauthn.mjs"; |
| async function post(path, body) { |
| const res = await fetch(path, { |
| @@ -36,10 +36,11 @@ function reveal() { |
| for (const el of document.querySelectorAll("[data-passkey]")) el.hidden = false; |
| } |
| -async function enrol(button) { |
| +async function enrol(button, replacement = false) { |
| button.disabled = true; |
| try { |
| - const begin = await post("/passkey/register/begin"); |
| + const path = replacement ? "/passkey/replace" : "/passkey/register"; |
| + const begin = await post(path + "/begin"); |
| const made = await register({ |
| challenge: begin.challenge, |
| rpId: document.body.dataset.rpid, |
| @@ -47,11 +48,11 @@ async function enrol(button) { |
| userId: document.body.dataset.userid, |
| userName: document.body.dataset.username, |
| }); |
| - await post("/passkey/register/finish", { |
| + const done = await post(path + "/finish", { |
| clientDataJSON: made.clientDataJSON, |
| attestationObject: made.attestationObject, |
| }); |
| - window.location.assign("/passkey/codes"); |
| + window.location.assign(done.to || "/passkey/codes"); |
| } catch (err) { |
| say(button, "That did not work. You can try again."); |
| } |
| @@ -62,7 +63,7 @@ async function confirm(button, direct = false) { |
| try { |
| const path = direct ? "/passkey/direct" : "/passkey/signin"; |
| const begin = await post(path + "/begin"); |
| - const got = await authenticate({ |
| + const got = begin.credentials?.length ? await authenticateBound(begin) : await authenticate({ |
| challenge: begin.challenge, |
| rpId: document.body.dataset.rpid, |
| legacyRpId: document.body.dataset.legacyrpid || undefined, |
| @@ -84,3 +85,21 @@ document.getElementById("passkey-enrol")?.addEventListener("click", (e) => enrol |
| document.getElementById("passkey-confirm")?.addEventListener("click", (e) => confirm(e.currentTarget)); |
| document.getElementById("passkey-direct")?.addEventListener("click", (e) => confirm(e.currentTarget, true)); |
| + |
| +document.getElementById("passkey-replace")?.addEventListener("click", (e) => enrol(e.currentTarget, true)); |
| + |
| +async function authenticateBound(begin) { |
| + const credential = await navigator.credentials.get({ publicKey: { |
| + challenge: fromB64url(begin.challenge), |
| + rpId: document.body.dataset.rpid, |
| + allowCredentials: begin.credentials.map((id) => ({ type: "public-key", id: fromB64url(id) })), |
| + userVerification: "required", |
| + }}); |
| + if (!credential) throw new Error("ceremony failed"); |
| + return { |
| + credentialId: toB64url(credential.rawId), |
| + clientDataJSON: toB64url(credential.response.clientDataJSON), |
| + authenticatorData: toB64url(credential.response.authenticatorData), |
| + signature: toB64url(credential.response.signature), |
| + }; |
| +} |
diff --git a/internal/home/team_page_test.go b/internal/home/team_page_test.go| index 45a5d88..a0ad046 100644 |
| --- a/internal/home/team_page_test.go |
| +++ b/internal/home/team_page_test.go |
| @@ -74,7 +74,10 @@ func (f *teamFixture) exchange(t *testing.T, cred *http.Cookie, start, returnTo |
| pending := namedCookie(t, begin, "__Host-oficina-assertion-pending") |
| authorize := exchangeRequest(f.credential.App, "GET", begin.Header().Get("Location"), "", nil, cred) |
| intent := namedCookie(t, authorize, assertionIntentCookie) |
| - resume := exchangeRequest(f.credential.App, "GET", Origin+"/authorize/resume", "", nil, intent, cred) |
| + if strings.Contains(begin.Header().Get("Location"), "max_age=300") { |
| + cred = signInFully(t, f.credential, f.paulAddress) |
| + } |
| + resume := exchangeRequest(f.credential.App, "POST", Origin+"/authorize/resume", Origin, nil, intent, cred) |
| m := regexp.MustCompile(`name="assertion" value="([^"]+)"`).FindStringSubmatch(resume.Body.String()) |
| if resume.Code != 200 || len(m) != 2 { |
| t.Fatal("resume", resume.Code, resume.Header().Get("Location")) |
diff --git a/internal/home/templates/id_replace.html b/internal/home/templates/id_replace.html| new file mode 100644 |
| index 0000000..395defe |
| --- /dev/null |
| +++ b/internal/home/templates/id_replace.html |
| @@ -0,0 +1,10 @@ |
| +{{define "title"}}Replace passkeys · Oficina{{end}} |
| +{{define "bodyattrs"}} data-rpid="{{.Data.RPID}}" data-userid="{{.Data.UserID}}" data-username="{{.Data.UserName}}"{{end}} |
| +{{define "content"}} |
| +<h1>Replace your passkeys</h1> |
| +<p rst-callout rst-tone="warning"><span rst-callout-body>Adding a replacement removes all your existing passkeys, signs you out of Oficina ID on every device, and invalidates all your recovery codes. You may remain signed in to the directory and other apps. Sign in with the new passkey before creating new recovery codes.</span></p> |
| +<button id="passkey-replace" type="button" rst-btn="danger" data-passkey hidden>Replace all passkeys</button> |
| +<p id="passkey-status" role="status"></p> |
| +<noscript><p>Turn on JavaScript to add your replacement passkey.</p></noscript> |
| +{{end}} |
| +{{define "scripts"}}<script type="module" src="/static/passkey.js"></script>{{end}} |
diff --git a/internal/home/templates/id_replaced.html b/internal/home/templates/id_replaced.html| new file mode 100644 |
| index 0000000..d907015 |
| --- /dev/null |
| +++ b/internal/home/templates/id_replaced.html |
| @@ -0,0 +1,10 @@ |
| +{{define "title"}}Passkeys replaced · Oficina{{end}} |
| +{{define "content"}} |
| +<h1>Your passkeys were replaced</h1> |
| +<p>You are signed out of Oficina ID on every device. Your previous passkeys and recovery codes no longer work. You may remain signed in to the directory and other apps. Sign in with your new passkey to create new recovery codes.</p> |
| +{{if .Data.NoticeFailed}} |
| +<p role="alert">Your passkeys were replaced, but we could not send the confirmation email.</p> |
| +{{if .Data.CanRetry}}<form method="post" action="/passkey/notice" rst-form><button type="submit" rst-btn>Send email again</button></form>{{else}}<p>The confirmation email can no longer be sent from this page.</p>{{end}} |
| +{{end}} |
| +<a href="/signin?return_to=%2Fpasskey%2Fcodes" rst-btn="primary">Sign in with your new passkey</a> |
| +{{end}} |
diff --git a/internal/home/templates/id_signed_out.html b/internal/home/templates/id_signed_out.html| new file mode 100644 |
| index 0000000..10cd4c2 |
| --- /dev/null |
| +++ b/internal/home/templates/id_signed_out.html |
| @@ -0,0 +1,6 @@ |
| +{{define "title"}}Signed out · Oficina{{end}} |
| +{{define "content"}} |
| +<h1>You are signed out</h1> |
| +<p>You are signed out of Oficina Home in this browser.</p> |
| +<a href="/signin" rst-btn="primary">Sign in</a> |
| +{{end}} |
diff --git a/internal/home/testapp_test.go b/internal/home/testapp_test.go| index 386f114..8cee5d5 100644 |
| --- a/internal/home/testapp_test.go |
| +++ b/internal/home/testapp_test.go |
| @@ -114,7 +114,7 @@ func newTestAppWithOrigins(t *testing.T, origins Origins) *testApp { |
| } |
| t.Cleanup(func() { d.Close() }) |
| - if _, err := migrate.Apply(context.Background(), d, BootSchema); err != nil { |
| + if _, err := migrate.Apply(context.Background(), d, migrate.Merge(BootSchema, identitySchema)); err != nil { |
| t.Fatalf("migrate.Apply: %v", err) |
| } |