oficina / home Public

Fix ID sign-out, anonymous challenges and recovery review findings

Paul Campbell pushed by paul@keymail.dev 04fa66ba25bfa29aee8175e728d7f99ff3a91b02 parent e19f9dd
14 files changed, +500 −76
  • implementation/oficina-id-slice1-copy.md +14 −0
  • implementation/oficina-id-slice1-validation.md +13 −0
  • internal/home/directory.go +5 −1
  • internal/home/exchange.go +2 −1
  • internal/home/id_direct.go +68 −0
  • internal/home/id_passkey.go +31 −20
  • internal/home/id_passkey_test.go +45 −13
  • internal/home/id_recovery.go +22 −7
  • internal/home/id_recovery_test.go +3 −0
  • internal/home/id_review_test.go +234 −0
  • internal/home/id_signout_test.go +17 −17
  • internal/home/identity/migrations/0003_direct.sql +5 −0
  • internal/home/signout_test.go +29 −13
  • internal/home/templates/directory_signed_out.html +12 −4

CI failed — run details

diff --git a/implementation/oficina-id-slice1-copy.md b/implementation/oficina-id-slice1-copy.md
index e15e076..a15b83e 100644
--- a/implementation/oficina-id-slice1-copy.md
+++ b/implementation/oficina-id-slice1-copy.md
@@ -32,3 +32,17 @@ Reviewed by GPT-6 Astra. Fixed labels only; no account-authored text.
- The confirmation email can no longer be sent from this page.
The delegated Astra follow-up accepted the Oficina ID scope clarification.
+
+## Fable review fixes
+
+COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13)
+
+Astra reviewed these exact additions and revisions before implementation:
+
+- Interim title: Sign out · Oficina
+- Interim heading: Finish signing out
+- Interim body: You are signed out of the directory. Finish signing out of Oficina ID before leaving this device.
+- Button: Sign out of Oficina ID
+- Returned-page body: You are signed out of the directory in this browser.
+- Recovery notice subject: A recovery code was used for your Oficina account
+- Recovery notice body: Someone signed in to your Oficina account using email and a recovery code. If this was not you, sign in with your passkey and generate new recovery codes. This invalidates the previous codes but does not sign out anyone already signed in.
diff --git a/implementation/oficina-id-slice1-validation.md b/implementation/oficina-id-slice1-validation.md
index a3cab05..fc56b9b 100644
--- a/implementation/oficina-id-slice1-validation.md
+++ b/implementation/oficina-id-slice1-validation.md
@@ -108,3 +108,16 @@ static assets retain their own cache policy. The regression passes and removing
the header is killed by mutation. The final record is 63 checks / 62 killed /
one independently guarded survivor. Targeted renderer and browser tests follow
this final three-line production change; final-tip CI reruns the full gate.
+
+## Fable review fixes: red tests
+
+After merging origin/main, the revised real-form signout regression and hanging
+issuer test both failed because the local page had no credential POST form.
+The anonymous-begin flood failed on request 10,001; its first 10,000 requests
+filled the ceremony table. Sealed-proof cases failed because no sealed proof
+existed. Recovery tests failed for full RAM blocking the email gate, missing/full
+RAM still consuming codes, no redemption notice, and recovery satisfying linking.
+The replacement regression failed because the new passkey login skipped codes.
+These failures were observed before their production changes. Existing recovery
+exclusion, replacement method/session binding, and attempt-budget guards already
+passed; their missing mutations are added in this review pass.
diff --git a/internal/home/directory.go b/internal/home/directory.go
index 03a7e43..8d68b98 100644
--- a/internal/home/directory.go
+++ b/internal/home/directory.go
@@ -165,12 +165,16 @@ func (a *App) directoryRouter() http.Handler {
r.Post(signoutPath, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
a.sessions.SignOut(w, r)
+ idCookie(w, "__Host-oficina-finish-signout", "1", 300)
http.Redirect(w, r, "/signed-out", http.StatusSeeOther)
})
r.Get("/signed-out", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
- a.render(w, r, 200, "directory_signed_out.html", map[string]any{})
+ finish := cookieValue(r, "__Host-oficina-finish-signout") == "1"
+ idCookie(w, "__Host-oficina-finish-signout", "", -1)
+ a.render(w, r, 200, "directory_signed_out.html", map[string]any{"Finish": finish, "Action": a.origins.Credential + signoutPath})
})
+ r.Get("/static/assertion.js", serveAsset(staticAsset("assertion.js"), "text/javascript; charset=utf-8"))
r.Get("/healthz", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) })
mountCSS(r, "/static/tokens.css", staticAsset("tokens.css"))
mountCSS(r, "/static/theme.css", theme.CSS())
diff --git a/internal/home/exchange.go b/internal/home/exchange.go
index 0c15119..c2c9a39 100644
--- a/internal/home/exchange.go
+++ b/internal/home/exchange.go
@@ -4,6 +4,7 @@ import (
"encoding/base64"
"net/http"
"net/url"
+ "strings"
"time"
"amadan.net/oficina/home/handoff"
@@ -111,7 +112,7 @@ func (a *App) handleAssertion(w http.ResponseWriter, r *http.Request) {
if c, err := r.Cookie(a.sessions.CookieName()); err == nil {
sameSession = intent.Previous != "" && sessions.HashToken(c.Value) == intent.Previous
}
- if intent.MaxAge != 0 && (sameSession || (intent.Started != 0 && authTime.Unix() < intent.Started) || !sessions.Fresh(session, time.Duration(intent.MaxAge)*time.Second, now) || authTime.After(now) || keymailWithoutGesture(session)) {
+ if intent.MaxAge != 0 && (sameSession || (intent.Started != 0 && authTime.Unix() < intent.Started) || !sessions.Fresh(session, time.Duration(intent.MaxAge)*time.Second, now) || authTime.After(now) || keymailWithoutGesture(session) || strings.Contains(session.Method, "recovery")) {
http.Redirect(w, r, "/signin?return_to=%2Fauthorize%2Fresume", http.StatusSeeOther)
return
}
diff --git a/internal/home/id_direct.go b/internal/home/id_direct.go
new file mode 100644
index 0000000..7fc7be5
--- /dev/null
+++ b/internal/home/id_direct.go
@@ -0,0 +1,68 @@
+package home
+
+import (
+ "database/sql"
+ "encoding/base64"
+ "encoding/hex"
+ "encoding/json"
+ "net/http"
+ "time"
+
+ "amadan.net/rastrillo/rastrillo/webauthn"
+)
+
+type directChallenge struct {
+ Challenge string `json:"challenge"`
+ Expires int64 `json:"expires"`
+}
+
+// Anonymous begins allocate only a sealed browser cookie. Replay receipts are
+// written after WebAuthn verification, in the same transaction as session mint.
+func (a *App) idDirectBegin(w http.ResponseWriter, r *http.Request) {
+ challenge, err := webauthn.NewChallenge()
+ if err != nil {
+ idRefuse(w)
+ return
+ }
+ plain, err := json.Marshal(directChallenge{hex.EncodeToString(challenge), time.Now().Unix() + 300})
+ if err != nil {
+ idRefuse(w)
+ return
+ }
+ sealed, err := a.secrets.Sealer.Seal("id.direct", plain)
+ if err != nil {
+ idRefuse(w)
+ return
+ }
+ idCookie(w, ceremonyCookie, base64.RawURLEncoding.EncodeToString(sealed), 300)
+ idJSONReply(w, 200, map[string]any{"challenge": base64.RawURLEncoding.EncodeToString(challenge)})
+}
+func (a *App) idDirectProof(r *http.Request, challenge []byte, now int64) (int64, error) {
+ value := cookieValue(r, ceremonyCookie)
+ sealed, err := base64.RawURLEncoding.Strict().DecodeString(value)
+ if err != nil {
+ return 0, errIDProof
+ }
+ plain, err := a.secrets.Sealer.Open("id.direct", sealed)
+ if err != nil {
+ return 0, errIDProof
+ }
+ var proof directChallenge
+ if json.Unmarshal(plain, &proof) != nil || proof.Challenge != hex.EncodeToString(challenge) || proof.Expires <= now || proof.Expires > now+300 {
+ return 0, errIDProof
+ }
+ return proof.Expires, nil
+}
+func consumeDirect(tx *sql.Tx, challenge []byte, expires, now int64) error {
+ if _, err := tx.Exec("DELETE FROM home_id_direct_used WHERE expires_at<=?", now); err != nil {
+ return errIDProof
+ }
+ var n int
+ if tx.QueryRow("SELECT count(*) FROM home_id_direct_used").Scan(&n) != nil || n >= 10000 {
+ return errIDProof
+ }
+ if _, err := tx.Exec("INSERT INTO home_id_direct_used VALUES(?,?)", hex.EncodeToString(challenge), expires); err != nil {
+ return errIDProof
+ }
+ return nil
+}
diff --git a/internal/home/id_passkey.go b/internal/home/id_passkey.go
index 7513bb9..634d06f 100644
--- a/internal/home/id_passkey.go
+++ b/internal/home/id_passkey.go
@@ -132,24 +132,16 @@ func (a *App) idBinding(tx *sql.Tx, r *http.Request, purpose string, now int64)
}
func (a *App) idBegin(purpose string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
+ if purpose == "direct" {
+ a.idDirectBegin(w, r)
+ return
+ }
tx, now, err := a.idTransaction(r.Context())
if err != nil {
idRefuse(w)
return
}
defer tx.Rollback()
- var direct string
- if purpose == "direct" {
- direct, _, err = sessions.NewToken()
- if err != nil {
- idRefuse(w)
- return
- }
- r = r.Clone(r.Context())
- r.Header = r.Header.Clone()
- r.Header.Del("Cookie")
- r.AddCookie(&http.Cookie{Name: ceremonyCookie, Value: direct})
- }
subject, binding, err := a.idBinding(tx, r, purpose, now)
if err != nil {
idRefuse(w)
@@ -210,9 +202,6 @@ func (a *App) idBegin(purpose string) http.HandlerFunc {
idRefuse(w)
return
}
- if direct != "" {
- idCookie(w, ceremonyCookie, direct, 300)
- }
idJSONReply(w, 200, map[string]any{"challenge": base64.RawURLEncoding.EncodeToString(challenge), "credentials": credentials})
}
}
@@ -289,11 +278,21 @@ func (a *App) idFinish(purpose string) http.HandlerFunc {
idRefuse(w)
return
}
- var consumed string
- err = tx.QueryRow("DELETE FROM home_id_ceremonies WHERE challenge=? AND browser_hash=? AND subject=? AND purpose=? AND expires_at>? RETURNING challenge", hex.EncodeToString(challenge), binding, subject, purpose, now).Scan(&consumed)
- if err != nil {
- idRefuse(w)
- return
+ var directExpires int64
+ if purpose == "direct" {
+ directExpires, err = a.idDirectProof(r, challenge, now)
+ if err != nil {
+ idRefuse(w)
+ return
+ }
+ } else {
+ var consumed string
+ err = tx.QueryRow("DELETE FROM home_id_ceremonies WHERE challenge=? AND browser_hash=? AND subject=? AND purpose=? AND expires_at>? RETURNING challenge", hex.EncodeToString(challenge), binding, subject, purpose, now).Scan(&consumed)
+ if err != nil {
+ idRefuse(w)
+ return
+ }
+
}
refuse := func() { _ = tx.Commit(); idRefuse(w) }
if purpose == "register" || purpose == "replace" {
@@ -375,6 +374,10 @@ func (a *App) idFinish(purpose string) http.HandlerFunc {
refuse()
return
}
+ if purpose == "direct" && consumeDirect(tx, challenge, directExpires, now) != nil {
+ idRefuse(w)
+ return
+ }
if _, e = tx.Exec("UPDATE passkey_credentials SET sign_count=? WHERE id=?", next, hex.EncodeToString(id)); e != nil {
idRefuse(w)
return
@@ -387,6 +390,14 @@ func (a *App) idFinish(purpose string) http.HandlerFunc {
}
method += "+passkey"
}
+ var codes int
+ if tx.QueryRow("SELECT count(*) FROM passkey_recovery_codes WHERE subject=?", owner).Scan(&codes) != nil {
+ idRefuse(w)
+ return
+ }
+ if codes == 0 {
+ to = "/passkey/codes"
+ }
token, e := a.idMint(tx, r, sessions.Session{Subject: owner, Method: method, AuthTime: time.Unix(now, 0)}, now)
if e != nil {
idRefuse(w)
diff --git a/internal/home/id_passkey_test.go b/internal/home/id_passkey_test.go
index 83b7840..1b74412 100644
--- a/internal/home/id_passkey_test.go
+++ b/internal/home/id_passkey_test.go
@@ -63,7 +63,7 @@ func TestIDDirectPasskey(t *testing.T) {
sealtest.AssertNoPlaintext(t, app.dbPath)
}
func TestIDPasskeyRejectsBadProofs(t *testing.T) {
- for _, kind := range []string{"origin", "rp", "uv", "signature", "unknown", "expired", "purpose"} {
+ for _, kind := range []string{"origin", "rp", "uv", "signature", "unknown"} {
t.Run(kind, func(t *testing.T) {
app := newTestApp(t)
s := signInFully(t, app, sealtest.CanaryAddress)
@@ -83,14 +83,7 @@ func TestIDPasskeyRejectsBadProofs(t *testing.T) {
opts.CorruptSig = true
case "unknown":
key, _ = authtest.New()
- case "expired":
- if _, err := app.db.Writer().Exec("UPDATE home_id_ceremonies SET expires_at=?", time.Now().Unix()-1); err != nil {
- t.Fatal(err)
- }
- case "purpose":
- if _, err := app.db.Writer().Exec("UPDATE home_id_ceremonies SET purpose='register'"); err != nil {
- t.Fatal(err)
- }
+
}
r := idJSON(t, app, "/passkey/direct/finish", assertionBody(key, challenge, opts), c)
if r.Code == 200 || sessionCookie(r) != nil {
@@ -233,9 +226,11 @@ func TestIDChallengeBrowserCookiesAndExpiry(t *testing.T) {
other := idJSON(t, a, "/passkey/direct/begin", nil)
cookies = []*http.Cookie{namedCookie(t, other, ceremonyCookie)}
case "ttl":
- var expiry int64
- if err := a.db.Writer().QueryRow("SELECT expires_at FROM home_id_ceremonies WHERE purpose='direct'").Scan(&expiry); err != nil || expiry > time.Now().Unix()+300 || expiry < time.Now().Unix()+295 {
- t.Fatal("challenge lifetime", expiry, err)
+ raw, _ := base64.RawURLEncoding.DecodeString(c.Value)
+ plain, err := a.secrets.Sealer.Open("id.direct", raw)
+ var proof directChallenge
+ if err != nil || json.Unmarshal(plain, &proof) != nil || proof.Expires > time.Now().Unix()+300 || proof.Expires < time.Now().Unix()+295 {
+ t.Fatal("challenge lifetime")
}
return
case "clock":
@@ -244,7 +239,7 @@ func TestIDChallengeBrowserCookiesAndExpiry(t *testing.T) {
if _, err := a.db.Writer().Exec("WITH RECURSIVE n(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM n WHERE x<10000) INSERT INTO home_id_ceremonies SELECT printf('%064x',x),'other','','direct',? FROM n", time.Now().Unix()+300); err != nil {
t.Fatal(err)
}
- if r := idJSON(t, a, "/passkey/direct/begin", nil); r.Code == 200 {
+ if r := idJSON(t, a, "/passkey/register/begin", nil, s); r.Code == 200 {
t.Fatal("challenge bound bypassed")
}
return
@@ -287,3 +282,40 @@ func TestIDLegacyCredentialCannotSignInDirectly(t *testing.T) {
t.Fatal("legacy credential bypassed mailbox gate")
}
}
+
+func TestIDGatedChallengeGuards(t *testing.T) {
+ for _, kind := range []string{"purpose", "expiry", "browser", "single-use", "ttl"} {
+ t.Run(kind, func(t *testing.T) {
+ a := newTestApp(t)
+ s := signInFully(t, a, sealtest.CanaryAddress)
+ k := enrol(t, a, s)
+ g := redeemAfterSignIn(t, a, sealtest.CanaryAddress)
+ cookies := g.Result().Cookies()
+ b := idJSON(t, a, "/passkey/signin/begin", nil, cookies...)
+ body := assertionBody(k, challengeFrom(t, b), authtest.Options{RPID: credentialHost, Origin: Origin})
+ switch kind {
+ case "purpose":
+ a.db.Writer().Exec("UPDATE home_id_ceremonies SET purpose='register'")
+ case "expiry":
+ a.db.Writer().Exec("UPDATE home_id_ceremonies SET expires_at=0")
+ case "browser":
+ a.db.Writer().Exec("UPDATE home_id_ceremonies SET browser_hash='other'")
+ case "ttl":
+ var expiry int64
+ a.db.Writer().QueryRow("SELECT expires_at FROM home_id_ceremonies").Scan(&expiry)
+ if expiry > time.Now().Unix()+300 || expiry < time.Now().Unix()+295 {
+ t.Fatal("gated challenge TTL")
+ }
+ return
+ case "single-use":
+ // A valid signed response with a bad origin consumes the gated proof too.
+ bad := assertionBody(k, challengeFrom(t, b), authtest.Options{RPID: credentialHost, Origin: "https://evil.invalid"})
+ idJSON(t, a, "/passkey/signin/finish", bad, cookies...)
+ }
+ r := idJSON(t, a, "/passkey/signin/finish", body, cookies...)
+ if r.Code == 200 {
+ t.Fatal("gated guard failed", kind)
+ }
+ })
+ }
+}
diff --git a/internal/home/id_recovery.go b/internal/home/id_recovery.go
index 1e890d3..1448e40 100644
--- a/internal/home/id_recovery.go
+++ b/internal/home/id_recovery.go
@@ -111,10 +111,10 @@ func (a *App) idGate(w http.ResponseWriter, r *http.Request, s sessions.Session,
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}) {
+ mailboxUnix = 0
+ }
+ if _, err = tx.Exec("INSERT INTO passkey_pending(token_hash,subject,method,return_to,expires_at,mailbox_at) VALUES(?,?,?,?,?,?)", hash, s.Subject, s.Method, sessions.SafeReturn(r, "/"), time.Unix(now+300, 0).UTC().Format(time.RFC3339), mailboxUnix); err != nil {
return false, errIDProof
}
if err = tx.Commit(); err != nil {
@@ -256,14 +256,18 @@ func (a *App) idRecovery(w http.ResponseWriter, r *http.Request) {
idRefuse(w)
return
}
- if tx.Commit() != nil {
+ p, ok := a.mailboxes.get(binding)
+ if !ok || p.subject != subject || !a.mailboxes.put(hash, p) {
idRefuse(w)
return
}
- if p, ok := a.mailboxes.get(binding); ok && p.subject == subject {
- a.mailboxes.remove(binding)
- a.mailboxes.put(hash, p)
+ if tx.Commit() != nil {
+ a.mailboxes.remove(hash)
+ idRefuse(w)
+ return
}
+ a.mailboxes.remove(binding)
+ a.sendRecoverySigninNotice(r.Context(), p.address)
idCookie(w, a.sessions.CookieName(), token, 30*24*3600)
idCookie(w, gateCookie, "", -1)
idCookie(w, recoveryCookie, proof, int(exp.Unix()-now))
@@ -399,3 +403,14 @@ func (a *App) handleNoticeRetry(w http.ResponseWriter, r *http.Request) {
}
http.Redirect(w, r, "/passkey/replaced", http.StatusSeeOther)
}
+
+const recoverySigninNoticeSubject = "A recovery code was used for your Oficina account"
+const recoverySigninNoticeBody = "Someone signed in to your Oficina account using email and a recovery code. If this was not you, sign in with your passkey and generate new recovery codes. This invalidates the previous codes but does not sign out anyone already signed in."
+
+func (a *App) sendRecoverySigninNotice(ctx context.Context, address string) {
+ ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
+ defer cancel()
+ if a.secrets.Mailer.Send(ctx, address, recoverySigninNoticeSubject, recoverySigninNoticeBody) != nil {
+ a.logger.Error("recovery signin notice failed")
+ }
+}
diff --git a/internal/home/id_recovery_test.go b/internal/home/id_recovery_test.go
index a194cc8..db9592f 100644
--- a/internal/home/id_recovery_test.go
+++ b/internal/home/id_recovery_test.go
@@ -148,6 +148,9 @@ func TestIDRecoveryReplacementRevokesEverything(t *testing.T) {
if r.Code != 200 {
t.Fatal("replacement cannot sign in", r.Code)
}
+ if !strings.Contains(r.Body.String(), `"to":"/passkey/codes"`) {
+ t.Fatal("replacement signin skipped new recovery codes")
+ }
idCodes(t, a, sessionCookie(r))
mail, ok := a.mailer.last()
if !ok || mail.To != sealtest.CanaryAddress || mail.Subject != "Your Oficina passkeys were replaced" {
diff --git a/internal/home/id_review_test.go b/internal/home/id_review_test.go
new file mode 100644
index 0000000..3a5b7ae
--- /dev/null
+++ b/internal/home/id_review_test.go
@@ -0,0 +1,234 @@
+package home
+
+import (
+ "encoding/base64"
+ "encoding/json"
+ "fmt"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/home/internal/home/sealtest"
+ "amadan.net/rastrillo/rastrillo/sessions"
+ "amadan.net/rastrillo/rastrillo/webauthn/authtest"
+)
+
+func fullMailbox(a *testApp) {
+ a.mailboxes.mu.Lock()
+ defer a.mailboxes.mu.Unlock()
+ if a.mailboxes.entries == nil {
+ a.mailboxes.entries = map[string]mailboxProof{}
+ }
+ for i := len(a.mailboxes.entries); i < 1000; i++ {
+ a.mailboxes.entries[fmt.Sprint("filler", i)] = mailboxProof{expires: time.Now().Unix() + 300}
+ }
+}
+func TestIDFullMailboxAllowsGatedSignin(t *testing.T) {
+ a := newTestApp(t)
+ s := signInFully(t, a, sealtest.CanaryAddress)
+ k := enrol(t, a, s)
+ fullMailbox(a)
+ g := redeemAfterSignIn(t, a, sealtest.CanaryAddress)
+ if g.Code != 303 || g.Header().Get("Location") != confirmPath {
+ t.Fatal("RAM capacity blocked email gate", g.Code)
+ }
+ var at int64
+ if err := a.db.Writer().QueryRow("SELECT mailbox_at FROM passkey_pending").Scan(&at); err != nil || at != 0 {
+ t.Fatal("gate advertised unavailable mailbox proof", at, err)
+ }
+ b := idJSON(t, a, "/passkey/signin/begin", nil, g.Result().Cookies()...)
+ r := idJSON(t, a, "/passkey/signin/finish", assertionBody(k, challengeFrom(t, b), authtest.Options{RPID: credentialHost, Origin: Origin}), g.Result().Cookies()...)
+ if r.Code != 200 || sessionCookie(r) == nil {
+ t.Fatal("gated passkey refused", r.Code)
+ }
+}
+func TestIDRecoveryMailboxFailurePreservesCode(t *testing.T) {
+ for _, kind := range []string{"missing", "full"} {
+ t.Run(kind, func(t *testing.T) {
+ a := newTestApp(t)
+ s := signInFully(t, a, sealtest.CanaryAddress)
+ enrol(t, a, s)
+ codes := idCodes(t, a, s)
+ g := redeemAfterSignIn(t, a, sealtest.CanaryAddress)
+ if kind == "missing" {
+ a.mailboxes.entries = map[string]mailboxProof{}
+ } else {
+ fullMailbox(a)
+ }
+ r := exchangeRequest(a.App, "POST", Origin+"/passkey/signin/recovery", Origin, url.Values{"code": {codes[0]}}, g.Result().Cookies()...)
+ if sessionCookie(r) != nil {
+ t.Fatal("recovered without reserving RAM proof")
+ }
+ var n int
+ a.db.Writer().QueryRow("SELECT count(*) FROM passkey_recovery_codes").Scan(&n)
+ if n != 10 {
+ t.Fatal("RAM failure consumed code", n)
+ }
+ a.db.Writer().QueryRow("SELECT count(*) FROM passkey_pending").Scan(&n)
+ if n != 1 {
+ t.Fatal("RAM failure consumed gate", n)
+ }
+ })
+ }
+}
+func TestIDRecoverySigninNotice(t *testing.T) {
+ a := newTestApp(t)
+ s := signInFully(t, a, sealtest.CanaryAddress)
+ enrol(t, a, s)
+ codes := idCodes(t, a, s)
+ g := redeemAfterSignIn(t, a, sealtest.CanaryAddress)
+ r := exchangeRequest(a.App, "POST", Origin+"/passkey/signin/recovery", Origin, url.Values{"code": {codes[0]}}, g.Result().Cookies()...)
+ if sessionCookie(r) == nil {
+ t.Fatal("recovery failed")
+ }
+ m, ok := a.mailer.last()
+ if !ok || m.Subject != "A recovery code was used for your Oficina account" || m.To != sealtest.CanaryAddress {
+ t.Fatal("redemption notice missing")
+ }
+ // Delivery must leave the RAM proof available for replacement.
+ if p := exchangeRequest(a.App, "GET", Origin+"/passkey/replace", "", nil, r.Result().Cookies()...); p.Code != 200 {
+ t.Fatal("notice consumed replacement proof")
+ }
+ sealtest.AssertNoPlaintext(t, a.dbPath)
+}
+func TestIDRecoveryCannotLink(t *testing.T) {
+ p := newExchangePair(t)
+ _, intent := p.startFresh(t, nil)
+ s := signInFully(t, p.credential, sealtest.CanaryAddress)
+ if _, err := p.credential.db.Writer().Exec("UPDATE sessions SET method='email+recovery'"); err != nil {
+ t.Fatal(err)
+ }
+ for _, method := range []string{"GET", "POST"} {
+ r := exchangeRequest(p.credential.App, method, Origin+"/authorize/resume", Origin, nil, intent, s)
+ if r.Code != 303 || !strings.HasPrefix(r.Header().Get("Location"), "/signin") {
+ t.Fatal("recovery satisfied linking", method, r.Code)
+ }
+ }
+}
+func TestIDDirectFloodLeavesGatedCapacity(t *testing.T) {
+ a := newTestApp(t)
+ s := signInFully(t, a, sealtest.CanaryAddress)
+ enrol(t, a, s)
+ g := redeemAfterSignIn(t, a, sealtest.CanaryAddress)
+ for i := 0; i < 10001; i++ {
+ r := idJSON(t, a, "/passkey/direct/begin", nil)
+ if r.Code != 200 {
+ t.Fatal("direct begin refused", i)
+ }
+ }
+ var n int
+ if err := a.db.Writer().QueryRow("SELECT count(*) FROM home_id_ceremonies").Scan(&n); err != nil || n != 0 {
+ t.Fatal("anonymous begins retained state", n, err)
+ }
+ if r := idJSON(t, a, "/passkey/signin/begin", nil, g.Result().Cookies()...); r.Code != 200 {
+ t.Fatal("flood blocked authenticated gate")
+ }
+}
+func TestIDDirectSealedChallenge(t *testing.T) {
+ for _, kind := range []string{"tampered", "expired", "future", "mismatch"} {
+ t.Run(kind, func(t *testing.T) {
+ a := newTestApp(t)
+ s := signInFully(t, a, sealtest.CanaryAddress)
+ k := enrol(t, a, s)
+ b := idJSON(t, a, "/passkey/direct/begin", nil)
+ c := namedCookie(t, b, ceremonyCookie)
+ raw, err := base64.RawURLEncoding.DecodeString(c.Value)
+ if err != nil {
+ t.Fatal(err)
+ }
+ plain, err := a.secrets.Sealer.Open("id.direct", raw)
+ if err != nil {
+ t.Fatal("direct challenge is not sealed")
+ }
+ var proof map[string]any
+ if json.Unmarshal(plain, &proof) != nil {
+ t.Fatal("invalid proof")
+ }
+ switch kind {
+ case "tampered":
+ raw[len(raw)-1] ^= 1
+ default:
+ switch kind {
+ case "expired":
+ proof["expires"] = time.Now().Unix() - 1
+ case "future":
+ proof["expires"] = time.Now().Unix() + 600
+ case "mismatch":
+ proof["challenge"] = strings.Repeat("0", 64)
+ }
+ plain, _ = json.Marshal(proof)
+ raw, err = a.secrets.Sealer.Seal("id.direct", plain)
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ c.Value = base64.RawURLEncoding.EncodeToString(raw)
+ r := idJSON(t, a, "/passkey/direct/finish", assertionBody(k, challengeFrom(t, b), authtest.Options{RPID: credentialHost, Origin: Origin}), c)
+ if r.Code == 200 {
+ t.Fatal("invalid sealed proof accepted", kind)
+ }
+ })
+ }
+}
+func TestIDRecoveryExclusions(t *testing.T) {
+ a, cookies, _ := replacementFixture(t)
+ if r := idJSON(t, a, "/passkey/register/begin", nil, cookies...); r.Code == 200 {
+ t.Fatal("recovery enrolled directly")
+ }
+ if r := exchangeRequest(a.App, "POST", Origin+"/passkey/codes", Origin, url.Values{}, cookies...); r.Code == 200 {
+ t.Fatal("recovery generated codes")
+ }
+}
+func TestIDReplacementRequiresRecoverySession(t *testing.T) {
+ for _, kind := range []string{"method", "session"} {
+ t.Run(kind, func(t *testing.T) {
+ a, cookies, body := replacementFixture(t)
+ if kind == "method" {
+ a.db.Writer().Exec("UPDATE sessions SET method='email'")
+ } else {
+ var token string
+ for _, c := range cookies {
+ if c.Name == a.sessions.CookieName() {
+ token = c.Value
+ }
+ }
+ // Change only the proof's session binding, keeping person and RAM proof valid.
+ a.db.Writer().Exec("UPDATE home_id_recovery_proofs SET session_hash=?", sessions.HashToken(token+"different"))
+ }
+ r := idJSON(t, a, "/passkey/replace/finish", body, cookies...)
+ if r.Code == 200 {
+ t.Fatal("replacement accepted wrong session authority", kind)
+ }
+ })
+ }
+}
+func TestIDLimitsBeforeValidCode(t *testing.T) {
+ for _, bucket := range []string{"account", "ip"} {
+ t.Run(bucket, func(t *testing.T) {
+ a := newTestApp(t)
+ s := signInFully(t, a, sealtest.CanaryAddress)
+ enrol(t, a, s)
+ codes := idCodes(t, a, s)
+ g := redeemAfterSignIn(t, a, sealtest.CanaryAddress)
+ key := "account:" + subjectOf(t, a, s)
+ limit := 5
+ if bucket == "ip" {
+ req := httptest.NewRequest("POST", Origin+"/", nil)
+ key = "ip:" + blindIndex(a.secrets.Pepper, clientIP(req))
+ limit = 20
+ }
+ a.db.Writer().Exec("INSERT INTO home_id_attempts VALUES(?,?,?)", key, limit, time.Now().Unix()+900)
+ r := exchangeRequest(a.App, "POST", Origin+"/passkey/signin/recovery", Origin, url.Values{"code": {codes[0]}}, g.Result().Cookies()...)
+ if sessionCookie(r) != nil {
+ t.Fatal("valid code bypassed exhausted budget")
+ }
+ var n int
+ a.db.Writer().QueryRow("SELECT count(*) FROM passkey_recovery_codes").Scan(&n)
+ if n != 10 {
+ t.Fatal("budget refusal consumed valid code", n)
+ }
+ })
+ }
+}
diff --git a/internal/home/id_signout_test.go b/internal/home/id_signout_test.go
index 41a6f5a..8d60eca 100644
--- a/internal/home/id_signout_test.go
+++ b/internal/home/id_signout_test.go
@@ -17,22 +17,6 @@ func TestIDLocalSignoutWithHangingIssuer(t *testing.T) {
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
@@ -47,10 +31,26 @@ func TestIDLocalSignoutWithHangingIssuer(t *testing.T) {
}()); ok || s.Subject != "" {
t.Fatal("local session not revoked")
}
- page := exchangeRequest(p.directory, "GET", directoryOrigin+"/signed-out", "", nil)
+ page := exchangeRequest(p.directory, "GET", directoryOrigin+"/signed-out", "", nil, r.Result().Cookies()...)
if page.Code != 200 {
t.Fatal("local landing failed")
}
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ req, _ := http.NewRequestWithContext(ctx, "POST", signoutFormAction(t, page.Body.String()), nil)
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ resp, _ := issuer.Client().Do(req)
+ if resp != nil {
+ resp.Body.Close()
+ }
+ }()
+ select {
+ case <-accepted:
+ case <-time.After(time.Second):
+ t.Fatal("issuer did not accept connection")
+ }
// 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" {
diff --git a/internal/home/identity/migrations/0003_direct.sql b/internal/home/identity/migrations/0003_direct.sql
new file mode 100644
index 0000000..38fcfd6
--- /dev/null
+++ b/internal/home/identity/migrations/0003_direct.sql
@@ -0,0 +1,5 @@
+CREATE TABLE home_id_direct_used (
+ challenge TEXT PRIMARY KEY,
+ expires_at INTEGER NOT NULL
+);
+CREATE INDEX home_id_direct_expiry ON home_id_direct_used(expires_at);
diff --git a/internal/home/signout_test.go b/internal/home/signout_test.go
index fbf95c3..144a858 100644
--- a/internal/home/signout_test.go
+++ b/internal/home/signout_test.go
@@ -4,6 +4,7 @@ import (
"net/http"
"net/http/httptest"
"net/url"
+ "regexp"
"strings"
"testing"
@@ -73,25 +74,23 @@ func TestSignOutEndsTheCredentialSession(t *testing.T) {
t.Fatal("precondition: a live credential session mints silently")
}
- // The directory ends its own session, then hands the same POST on to
- // the credential origin. 307, not 303: the method has to survive so
- // the credential origin receives a POST it can origin-check, rather
- // than a GET anyone could link to.
out := exchangeRequest(p.directory, "POST", directoryOrigin+"/signout", directoryOrigin, url.Values{}, directory)
if out.Code != http.StatusSeeOther || out.Header().Get("Location") != "/signed-out" {
- t.Fatalf("directory sign-out: %d %q", out.Code, out.Header().Get("Location"))
+ t.Fatal("local landing missing")
}
if !clearsCookie(out, directory.Name) {
- t.Fatal("directory sign-out left its cookie")
+ t.Fatal("directory cookie survived")
}
- if page := exchangeRequest(p.directory, "GET", directoryOrigin+"/", "", nil, directory); strings.Contains(page.Body.String(), "You are signed in.") {
- t.Fatal("directory session survived sign-out")
+ landing := exchangeRequest(p.directory, "GET", directoryOrigin+out.Header().Get("Location"), "", nil, out.Result().Cookies()...)
+ action := signoutFormAction(t, landing.Body.String())
+ if action != Origin+"/signout" {
+ t.Fatal("wrong issuer form action", action)
}
-
- // The browser re-sends the POST to id.*. These are the headers
- // Chromium really sends on that hop (captured live, polish-audit B2):
- // the 307 nulls Origin, so the directory is named by Referer alone.
- end := signoutHop(p, "null", "same-site", directoryOrigin+"/", credential)
+ if !strings.Contains(landing.Body.String(), "/static/assertion.js") {
+ t.Fatal("automatic second step missing")
+ }
+ // Follow the page's actual form, preserving its method and browser origin.
+ end := exchangeRequest(p.credential.App, "POST", action, directoryOrigin, url.Values{}, credential)
if end.Code != http.StatusSeeOther || end.Header().Get("Location") != directoryOrigin+"/signed-out" {
t.Fatalf("credential sign-out: %d %q", end.Code, end.Header().Get("Location"))
}
@@ -102,6 +101,14 @@ func TestSignOutEndsTheCredentialSession(t *testing.T) {
t.Fatal("sign-out response cacheable")
}
+ returned := exchangeRequest(p.directory, "GET", end.Header().Get("Location"), "", nil, landing.Result().Cookies()...)
+ if returned.Code != 200 || strings.Contains(returned.Body.String(), "data-assertion-handoff") {
+ t.Fatal("signout return loops")
+ }
+ if page := exchangeRequest(p.directory, "GET", directoryOrigin+"/", "", nil, directory); strings.Contains(page.Body.String(), "You are signed in.") {
+ t.Fatal("directory session survived")
+ }
+
// The cookie is gone from the browser, but a copy of it must not work
// either: the row is revoked, not merely forgotten.
if resumeMints(t, p, credential) {
@@ -420,3 +427,12 @@ func TestCredentialSignOutKeepsASuiteOriginsPort(t *testing.T) {
t.Fatal("ported suite origin admitted cross-site", rec.Code)
}
}
+
+func signoutFormAction(t *testing.T, body string) string {
+ t.Helper()
+ m := regexp.MustCompile(`<form method="post" action="([^"]+)"[^>]*data-assertion-handoff`).FindStringSubmatch(body)
+ if len(m) != 2 || !strings.Contains(body, "Sign out of Oficina ID</button>") {
+ t.Fatal("signed-out page has no issuer POST and fallback button")
+ }
+ return m[1]
+}
diff --git a/internal/home/templates/directory_signed_out.html b/internal/home/templates/directory_signed_out.html
index d427a1a..dab7ccf 100644
--- a/internal/home/templates/directory_signed_out.html
+++ b/internal/home/templates/directory_signed_out.html
@@ -1,6 +1,14 @@
-{{define "title"}}{{signedOutDoor.Title}}{{end}}
-{{define "content"}}{{with signedOutDoor}}
+{{define "title"}}{{if .Data.Finish}}Sign out · Oficina{{else}}{{signedOutDoor.Title}}{{end}}{{end}}
+{{define "content"}}
+{{if .Data.Finish}}
+<h1>Finish signing out</h1>
+<p estilo-signin-body>You are signed out of the directory. Finish signing out of Oficina ID before leaving this device.</p>
+<form method="post" action="{{.Data.Action}}" data-assertion-handoff rst-form>
+<button type="submit" rst-btn="primary">Sign out of Oficina ID</button>
+</form>
+{{else}}{{with signedOutDoor}}
<h1>{{.Heading}}</h1>
-<p estilo-signin-body>{{.Body}}</p>
+<p estilo-signin-body>You are signed out of the directory in this browser.</p>
<p><a href="{{.Link.Href}}" rst-btn="primary">{{.Link.Label}}</a></p>
-{{end}}{{end}}
+{{end}}{{end}}{{end}}
+{{define "scripts"}}{{if .Data.Finish}}<script src='{{v "/static/assertion.js"}}' async></script>{{end}}{{end}}