Verify browser sign-out and preserve cross-site cookie revocation
13 files changed,
+315
−28
go.mod+1 −0go.sum+2 −0implementation/oficina-id-slice1-validation.md+17 −0internal/home/assertion_fresh_test.go+5 −2internal/home/door_copy_test.go+2 −2internal/home/id_browser_test.go+48 −3internal/home/id_recovery_test.go+4 −0internal/home/id_review_test.go+119 −1internal/home/id_signout_test.go+11 −0internal/home/security.go+1 −1internal/home/signout.go+17 −11internal/home/signout_test.go+30 −0scripts/check-id-mutations.py+58 −8
CI failed — run details
Intent
Human
Fable's code review of oficina-id-slice1 (c2eeb346): READY AFTER FIXES.
diff --git a/go.mod b/go.mod| index e4dc4c5..cc02403 100644 |
| --- a/go.mod |
| +++ b/go.mod |
| @@ -43,6 +43,7 @@ require ( |
| github.com/ncruces/go-strftime v1.0.0 // indirect |
| github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect |
| golang.org/x/crypto v0.55.0 // indirect |
| + golang.org/x/net v0.57.0 |
| golang.org/x/text v0.41.0 // indirect |
| gorm.io/gorm v1.31.2 // indirect |
| modernc.org/libc v1.74.1 // indirect |
diff --git a/go.sum b/go.sum| index 22001f4..e106f06 100644 |
| --- a/go.sum |
| +++ b/go.sum |
| @@ -70,6 +70,8 @@ golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M= |
| golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis= |
| golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk= |
| golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40= |
| +golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE= |
| +golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU= |
| golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= |
| golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= |
| golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= |
diff --git a/implementation/oficina-id-slice1-validation.md b/implementation/oficina-id-slice1-validation.md| index fc56b9b..f03a0ea 100644 |
| --- a/implementation/oficina-id-slice1-validation.md |
| +++ b/implementation/oficina-id-slice1-validation.md |
| @@ -121,3 +121,20 @@ 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. |
| + |
| +Astra's follow-up found cross-site directory classification used the directory |
| +hostname instead of ID's cookie site. TestCredentialSignoutUsesIssuerSite failed |
| +before the fix. Sign-out now compares the issuer's scheme and public-suffix |
| +registrable domain; the existing workspace x/net version is explicitly required |
| +by this module. Chromium sign-out passes for same-site and cross-site origins, |
| +with scripts on and off. Selectors distinguish the issuer confirmation button |
| +from the directory menu button to avoid clicking the page being navigated away |
| +from. The hanging test posts the actual local page's form and checks the local |
| +landing and revoked session again while that request is blocked. |
| + |
| +The full mutation pass exposed redundant refusal in an old restart fixture: |
| +missing RAM proof hid removed persistent attempt limits. The fixture now obtains |
| +a fresh mailbox proof after reconstruction. Persisted mailbox freshness is also |
| +checked with the independent RAM proof kept live, so neither defense masks the |
| +other in the mutation check. Legacy 50-bit codes have a compatibility regression; |
| +only newly generated sets receive the 128-bit entropy guarantee. |
diff --git a/internal/home/assertion_fresh_test.go b/internal/home/assertion_fresh_test.go| index 3799bc7..a999e3e 100644 |
| --- a/internal/home/assertion_fresh_test.go |
| +++ b/internal/home/assertion_fresh_test.go |
| @@ -137,7 +137,7 @@ func TestOrdinaryIntentKeepsKeymailAndInvalidIntentCannotRequestFreshness(t *tes |
| } |
| } |
| -func TestFreshAssertionAcceptsCompletedKeymailRecovery(t *testing.T) { |
| +func TestFreshAssertionRejectsCompletedKeymailRecovery(t *testing.T) { |
| p := newExchangePair(t) |
| const address = "person@keymail.invalid" |
| newKeymailStub(t, p.credential, address) |
| @@ -165,5 +165,8 @@ func TestFreshAssertionAcceptsCompletedKeymailRecovery(t *testing.T) { |
| if sessionCookie(recovery) == nil { |
| t.Fatal("recovery did not complete", recovery.Code) |
| } |
| - p.mint(t, intent, sessionCookie(recovery)) |
| + r := exchangeRequest(p.credential.App, "POST", Origin+"/authorize/resume", Origin, nil, intent, sessionCookie(recovery)) |
| + if r.Code != 303 || !strings.HasPrefix(r.Header().Get("Location"), "/signin") { |
| + t.Fatal("recovery satisfied linking reauthentication") |
| + } |
| } |
diff --git a/internal/home/door_copy_test.go b/internal/home/door_copy_test.go| index 7c5552a..141a765 100644 |
| --- a/internal/home/door_copy_test.go |
| +++ b/internal/home/door_copy_test.go |
| @@ -79,9 +79,9 @@ func TestDoorSpeaksTheSuiteCopy(t *testing.T) { |
| mustContain(t, "/signed-out", out.Body.String(), |
| "<title>Signed out · Oficina</title>", |
| "<h1>You’re signed out</h1>", |
| - "You’ve signed out of Oficina on this device.", |
| + "You are signed out of the directory in this browser.", |
| `rst-btn="primary">Sign in</a>`) |
| - mustNotContain(t, "/signed-out", out.Body.String(), "You are signed out", "Home") |
| + mustNotContain(t, "/signed-out", out.Body.String(), "You’ve signed out of Oficina on this device.", "Home") |
| } |
| // The hub builds its own signin.Flow, so it sets the email itself: the |
diff --git a/internal/home/id_browser_test.go b/internal/home/id_browser_test.go| index b579052..2e4839c 100644 |
| --- a/internal/home/id_browser_test.go |
| +++ b/internal/home/id_browser_test.go |
| @@ -6,6 +6,7 @@ import ( |
| "context" |
| "crypto/x509" |
| "encoding/base64" |
| + "fmt" |
| "net/http" |
| "net/http/httptest" |
| "net/url" |
| @@ -15,6 +16,7 @@ import ( |
| "amadan.net/oficina/home/internal/home/sealtest" |
| "amadan.net/rastrillo/rastrillo/harness" |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| "github.com/chromedp/cdproto/emulation" |
| "github.com/chromedp/cdproto/network" |
| "github.com/chromedp/cdproto/webauthn" |
| @@ -27,9 +29,12 @@ const browserRP = "id.example.org" |
| // Two different sites, real HTTPS and real browser cookies. DNS is redirected |
| // only inside this Chrome process; the test server listens on loopback. |
| func idBrowser(t *testing.T) (exchangePair, context.Context, webauthn.AuthenticatorID) { |
| + return idBrowserFor(t, "https://directory.example.test") |
| +} |
| +func idBrowserFor(t *testing.T, consumer string) (exchangePair, context.Context, webauthn.AuthenticatorID) { |
| t.Helper() |
| p := newExchangePair(t) |
| - const consumer = "https://directory.example.test" |
| + consumerURL, _ := url.Parse(consumer) |
| origins := Origins{browserIssuer, consumer} |
| old := p.credential.App |
| app, err := NewWithOrigins(old.secrets, p.credential.db, quietLogger(), origins) |
| @@ -50,7 +55,7 @@ func idBrowser(t *testing.T) (exchangePair, context.Context, webauthn.Authentica |
| server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| if r.Host == browserRP { |
| ch.ServeHTTP(w, r) |
| - } else if r.Host == "directory.example.test" { |
| + } else if r.Host == consumerURL.Hostname() { |
| dh.ServeHTTP(w, r) |
| } else { |
| http.NotFound(w, r) |
| @@ -59,7 +64,7 @@ func idBrowser(t *testing.T) (exchangePair, context.Context, webauthn.Authentica |
| t.Cleanup(server.Close) |
| u, _ := url.Parse(server.URL) |
| useChrome(t) |
| - opts := append(chromedp.DefaultExecAllocatorOptions[:], chromedp.ExecPath(harness.ChromePath(t)), chromedp.NoSandbox, chromedp.Flag("ignore-certificate-errors", true), chromedp.Flag("no-proxy-server", true), chromedp.Flag("host-resolver-rules", "MAP id.example.org "+u.Host+", MAP directory.example.test "+u.Host), chromedp.UserDataDir(t.TempDir())) |
| + opts := append(chromedp.DefaultExecAllocatorOptions[:], chromedp.ExecPath(harness.ChromePath(t)), chromedp.NoSandbox, chromedp.Flag("ignore-certificate-errors", true), chromedp.Flag("no-proxy-server", true), chromedp.Flag("host-resolver-rules", "MAP id.example.org "+u.Host+", MAP "+consumerURL.Hostname()+" "+u.Host), chromedp.UserDataDir(t.TempDir())) |
| alloc, stop := chromedp.NewExecAllocator(context.Background(), opts...) |
| ctx, cancel := chromedp.NewContext(alloc) |
| t.Cleanup(func() { _ = chromedp.Cancel(ctx); cancel(); stop() }) |
| @@ -140,3 +145,43 @@ func TestIDBrowserScriptlessCrossSiteReturn(t *testing.T) { |
| sealtest.AssertNoPlaintext(t, p.credential.dbPath) |
| sealtest.AssertNoPlaintext(t, p.directoryPath) |
| } |
| + |
| +func TestIDBrowserSignoutBothOrigins(t *testing.T) { |
| + for _, consumer := range []string{"https://example.org", "https://directory.example.test"} { |
| + for _, scripts := range []bool{true, false} { |
| + t.Run(fmt.Sprintf("%s/scripts=%v", consumer, scripts), func(t *testing.T) { |
| + p, ctx, _ := idBrowserFor(t, consumer) |
| + credential := signInFully(t, p.credential, sealtest.CanaryAddress) |
| + w := httptest.NewRecorder() |
| + req := httptest.NewRequest("POST", consumer+"/", nil) |
| + if err := p.directory.sessions.SignIn(w, req, sessions.Session{Subject: subjectOf(t, p.credential, credential), Method: "assertion", AuthTime: time.Now()}); err != nil { |
| + t.Fatal(err) |
| + } |
| + directory := sessionCookie(w) |
| + if directory == nil { |
| + t.Fatal("missing directory session") |
| + } |
| + idBrowserRun(t, ctx, emulation.SetScriptExecutionDisabled(!scripts), idBrowserCookie(credential), network.SetCookie(directory.Name, directory.Value).WithURL(consumer+"/").WithHTTPOnly(true).WithSecure(true).WithSameSite(network.CookieSameSiteLax), chromedp.Navigate(consumer+"/"), chromedp.WaitVisible(`[estilo-account] > summary`), chromedp.Click(`[estilo-account] > summary`), chromedp.Click(`form[action="/signout"] button`)) |
| + if !scripts { |
| + idBrowserRun(t, ctx, chromedp.WaitVisible(`form[data-assertion-handoff] button`), chromedp.Click(`form[data-assertion-handoff] button`)) |
| + } |
| + |
| + if consumer == "https://directory.example.test" { |
| + // Lax cookies do not ride a cross-site POST. The same-origin fallback |
| + // button on ID must complete that second hop with the credential cookie. |
| + idBrowserRun(t, ctx, chromedp.WaitVisible(`form[rst-form][action="/signout"] button`), chromedp.Click(`form[rst-form][action="/signout"] button`)) |
| + } |
| + idBrowserRun(t, ctx, chromedp.WaitVisible(`a[rst-btn="primary"]`)) |
| + var rows int |
| + p.credential.db.Writer().QueryRow("SELECT count(*) FROM sessions").Scan(&rows) |
| + if rows != 0 { |
| + t.Fatal("browser signout retained ID session", rows) |
| + } |
| + p.directory.db.Writer().QueryRow("SELECT count(*) FROM sessions").Scan(&rows) |
| + if rows != 0 { |
| + t.Fatal("browser signout retained directory session", rows) |
| + } |
| + }) |
| + } |
| + } |
| +} |
diff --git a/internal/home/id_recovery_test.go b/internal/home/id_recovery_test.go| index db9592f..a3c5d2a 100644 |
| --- a/internal/home/id_recovery_test.go |
| +++ b/internal/home/id_recovery_test.go |
| @@ -89,7 +89,11 @@ func TestIDRecoveryAttemptLimitSurvivesReconstruction(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| + app.flow.Classifier = a.flow.Classifier |
| a.App = app |
| + // RAM intentionally does not survive reconstruction. Re-prove the mailbox |
| + // so the persistent attempt limit, not missing RAM, must refuse this code. |
| + gated = redeemAfterSignIn(t, a, sealtest.CanaryAddress) |
| 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") |
diff --git a/internal/home/id_review_test.go b/internal/home/id_review_test.go| index 3a5b7ae..47170ed 100644 |
| --- a/internal/home/id_review_test.go |
| +++ b/internal/home/id_review_test.go |
| @@ -1,9 +1,11 @@ |
| package home |
| import ( |
| + "bytes" |
| "encoding/base64" |
| "encoding/json" |
| "fmt" |
| + "log/slog" |
| "net/http/httptest" |
| "net/url" |
| "strings" |
| @@ -117,9 +119,16 @@ func TestIDDirectFloodLeavesGatedCapacity(t *testing.T) { |
| if r.Code != 200 { |
| t.Fatal("direct begin refused", i) |
| } |
| + if i == 0 { |
| + var n int |
| + a.db.Writer().QueryRow("SELECT (SELECT count(*) FROM home_id_ceremonies)+(SELECT count(*) FROM home_id_direct_used)").Scan(&n) |
| + if n != 0 { |
| + t.Fatal("anonymous begin stored challenge") |
| + } |
| + } |
| } |
| var n int |
| - if err := a.db.Writer().QueryRow("SELECT count(*) FROM home_id_ceremonies").Scan(&n); err != nil || n != 0 { |
| + if err := a.db.Writer().QueryRow("SELECT (SELECT count(*) FROM home_id_ceremonies)+(SELECT count(*) FROM home_id_direct_used)").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 { |
| @@ -232,3 +241,112 @@ func TestIDLimitsBeforeValidCode(t *testing.T) { |
| }) |
| } |
| } |
| + |
| +func TestIDRecoverySigninNoticeFailurePrivacy(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) |
| + var logs bytes.Buffer |
| + a.logger = slog.New(slog.NewTextHandler(&logs, nil)) |
| + a.secrets.Mailer = idFailMailer{} |
| + r := exchangeRequest(a.App, "POST", Origin+"/passkey/signin/recovery", Origin, url.Values{"code": {codes[0]}}, g.Result().Cookies()...) |
| + if sessionCookie(r) == nil { |
| + t.Fatal("notice failure rolled back recovery") |
| + } |
| + if strings.Contains(logs.String(), sealtest.CanaryAddress) { |
| + t.Fatal("notice error leaked address") |
| + } |
| + sealtest.AssertNoPlaintext(t, a.dbPath) |
| +} |
| +func TestIDLegacyRecoveryCodesStillRedeem(t *testing.T) { |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + enrol(t, a, s) |
| + codes, err := a.passkeys.RegenerateRecoveryCodes(subjectOf(t, a, s)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(normalizeIDCode(codes[0])) != 10 { |
| + t.Fatal("fixture no longer exercises legacy 50-bit format") |
| + } |
| + 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("legacy code rejected") |
| + } |
| +} |
| +func TestIDDirectReceiptsBounded(t *testing.T) { |
| + for _, kind := range []string{"capacity", "expiry", "invalid-proof", "restart"} { |
| + 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) |
| + zero := uint32(0) |
| + opts := authtest.Options{RPID: credentialHost, Origin: Origin, Count: &zero} |
| + if kind == "capacity" || kind == "expiry" { |
| + exp := time.Now().Unix() + 300 |
| + if kind == "expiry" { |
| + exp = 0 |
| + } |
| + 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_direct_used SELECT printf('%064x',x),? FROM n", exp); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if kind == "invalid-proof" { |
| + opts.CorruptSig = true |
| + } |
| + body := assertionBody(k, challengeFrom(t, b), opts) |
| + r := idJSON(t, a, "/passkey/direct/finish", body, c) |
| + switch kind { |
| + case "capacity": |
| + if r.Code == 200 { |
| + t.Fatal("receipt cap bypassed") |
| + } |
| + case "expiry": |
| + if r.Code != 200 { |
| + t.Fatal("expired receipts not reclaimed") |
| + } |
| + case "invalid-proof": |
| + var n int |
| + a.db.Writer().QueryRow("SELECT count(*) FROM home_id_direct_used").Scan(&n) |
| + if n != 0 { |
| + t.Fatal("invalid proof retained receipt") |
| + } |
| + case "restart": |
| + if r.Code != 200 { |
| + t.Fatal("first signin failed") |
| + } |
| + app, err := New(a.secrets, a.db, a.logger) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + a.App = app |
| + if replay := idJSON(t, a, "/passkey/direct/finish", body, c); replay.Code == 200 { |
| + t.Fatal("restart allowed replay") |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestIDRecoveryMailboxTimeDefense(t *testing.T) { |
| + for _, at := range []int64{0, time.Now().Unix() - 600, time.Now().Unix() + 600} { |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + enrol(t, a, s) |
| + codes := idCodes(t, a, s) |
| + g := redeemAfterSignIn(t, a, sealtest.CanaryAddress) |
| + // Keep the independent RAM proof live while checking persisted freshness. |
| + if _, err := a.db.Writer().Exec("UPDATE passkey_pending SET mailbox_at=?", at); err != nil { |
| + t.Fatal(err) |
| + } |
| + r := exchangeRequest(a.App, "POST", Origin+"/passkey/signin/recovery", Origin, url.Values{"code": {codes[0]}}, g.Result().Cookies()...) |
| + if sessionCookie(r) != nil { |
| + t.Fatal("invalid persisted mailbox time accepted", at) |
| + } |
| + } |
| +} |
diff --git a/internal/home/id_signout_test.go b/internal/home/id_signout_test.go| index 8d60eca..3fc92c5 100644 |
| --- a/internal/home/id_signout_test.go |
| +++ b/internal/home/id_signout_test.go |
| @@ -51,6 +51,17 @@ func TestIDLocalSignoutWithHangingIssuer(t *testing.T) { |
| case <-time.After(time.Second): |
| t.Fatal("issuer did not accept connection") |
| } |
| + // The actual page form is now waiting on the issuer; local pages still |
| + // respond and the copied directory session remains revoked. |
| + again := exchangeRequest(p.directory, "GET", directoryOrigin+"/signed-out", "", nil) |
| + if again.Code != 200 { |
| + t.Fatal("hanging form blocked local landing") |
| + } |
| + local := httptest.NewRequest("GET", directoryOrigin+"/", nil) |
| + local.AddCookie(directory) |
| + if _, ok := p.directory.sessions.From(local); ok { |
| + t.Fatal("hanging issuer restored local session") |
| + } |
| // 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/security.go b/internal/home/security.go| index 20eec76..09386f0 100644 |
| --- a/internal/home/security.go |
| +++ b/internal/home/security.go |
| @@ -33,7 +33,7 @@ func (a *App) securityPolicy(consumer string) string { |
| origins[consumer] = true |
| } |
| // form-action governs a form's redirects too, so the directory's |
| - // sign-out, which 307s its POST on to the credential origin, is |
| + // signed-out page posts a second form to the credential origin and is |
| // blocked in the browser without this. See signoutPath. |
| if a.runtime != nil && a.runtime.role == "directory" { |
| origins[a.origins.Credential] = true |
diff --git a/internal/home/signout.go b/internal/home/signout.go| index 2c3644c..9b3eac3 100644 |
| --- a/internal/home/signout.go |
| +++ b/internal/home/signout.go |
| @@ -3,9 +3,9 @@ package home |
| import ( |
| "net/http" |
| "net/url" |
| - "strings" |
| "amadan.net/rastrillo/rastrillo/csrf" |
| + "golang.org/x/net/publicsuffix" |
| ) |
| // Each origin revokes and lands locally. A consumer may separately offer |
| @@ -159,18 +159,24 @@ func (a *App) consumerOrigin(origin string) (string, bool) { |
| return "", false |
| } |
| -// onSuiteSite reports whether origin's hostname is the directory's host |
| -// or under it. The directory is the suite's apex (oficina.works), and the |
| -// credential origin and every team instance sit under it, so this is the |
| -// site a browser's Sec-Fetch-Site compares against. A site has no port, |
| -// so the hostname is compared, never the host: a registered team on :8443 |
| -// is still same-site (the #74 review, finding 2). The caller keeps the |
| -// full origin, port included, for the redirect. |
| +// onSuiteSite compares schemeful sites with the credential origin. Configured |
| +// directory origins may be cross-site, and their Lax ID cookie is then absent. |
| func (a *App) onSuiteSite(origin string) bool { |
| - u, err := url.Parse(origin) |
| + consumer, err := url.Parse(origin) |
| if err != nil { |
| return false |
| } |
| - host := u.Hostname() |
| - return host == a.directoryHost || strings.HasSuffix(host, "."+a.directoryHost) |
| + issuer, err := url.Parse(a.origins.Credential) |
| + if err != nil || consumer.Scheme != issuer.Scheme { |
| + return false |
| + } |
| + if consumer.Hostname() == issuer.Hostname() { |
| + return true |
| + } |
| + site, err := publicsuffix.EffectiveTLDPlusOne(issuer.Hostname()) |
| + if err != nil { |
| + return false |
| + } |
| + other, err := publicsuffix.EffectiveTLDPlusOne(consumer.Hostname()) |
| + return err == nil && site == other |
| } |
diff --git a/internal/home/signout_test.go b/internal/home/signout_test.go| index 144a858..40228c7 100644 |
| --- a/internal/home/signout_test.go |
| +++ b/internal/home/signout_test.go |
| @@ -436,3 +436,33 @@ func signoutFormAction(t *testing.T, body string) string { |
| } |
| return m[1] |
| } |
| + |
| +func TestCredentialSignoutUsesIssuerSite(t *testing.T) { |
| + p := newExchangePair(t) |
| + a := p.credential.App |
| + a.origins = Origins{"https://id.example.org", "https://directory.example.test"} |
| + a.directoryHost = "directory.example.test" |
| + a.runtime.consumers["directory"] = a.origins.Directory |
| + for _, metadata := range []string{"", "cross-site"} { |
| + r := httptest.NewRequest("POST", a.origins.Credential+signoutPath, nil) |
| + r.Header.Set("Origin", a.origins.Directory) |
| + r.Header.Set("Sec-Fetch-Site", metadata) |
| + if _, verdict := a.signoutReturn(r); verdict != signoutConfirm { |
| + t.Fatal("cross-site registered directory must confirm with its ID cookie", metadata, verdict) |
| + } |
| + } |
| + for _, tc := range []struct { |
| + issuer, consumer string |
| + same bool |
| + }{ |
| + {"https://id.example.co.uk", "https://directory.example.co.uk", true}, |
| + {"https://id.example.co.uk", "https://other.co.uk", false}, |
| + {"https://id.oficina.works", "https://blue.docs.oficina.works:8443", true}, |
| + {"https://id.example.org", "http://id.example.org", false}, |
| + } { |
| + a.origins.Credential = tc.issuer |
| + if a.onSuiteSite(tc.consumer) != tc.same { |
| + t.Fatal("incorrect issuer-site classification", tc.issuer, tc.consumer) |
| + } |
| + } |
| +} |
diff --git a/scripts/check-id-mutations.py b/scripts/check-id-mutations.py| index 76a7138..19928a6 100755 |
| --- a/scripts/check-id-mutations.py |
| +++ b/scripts/check-id-mutations.py |
| @@ -24,12 +24,12 @@ CASES = [ |
| ("future enrollment time", "id_passkey.go", "&& !at.After(now)", "&& (!at.After(now) || true)", "TestIDEnrollmentRejectsFutureAndPassiveAuthentication/future"), |
| ("passive enrollment", "id_passkey.go", "!keymailWithoutGesture(s) &&", "(!keymailWithoutGesture(s) || true) &&", "TestIDEnrollmentRejectsFutureAndPassiveAuthentication/passive"), |
| ("challenge capacity", "id_passkey.go", "n >= 10000", "n >= 100000", "TestIDChallengeBrowserCookiesAndExpiry/capacity"), |
| - ("challenge lifetime", "id_passkey.go", "purpose, now+300", "purpose, now+600", "TestIDChallengeBrowserCookiesAndExpiry/ttl"), |
| - ("challenge browser", "id_passkey.go", "WHERE challenge=? AND browser_hash=? AND", "WHERE challenge=? AND (? IS NOT NULL) AND", "TestIDChallengeBrowserCookiesAndExpiry/other-browser"), |
| + ("challenge lifetime", "id_passkey.go", "purpose, now+300", "purpose, now+600", "TestIDGatedChallengeGuards/ttl"), |
| + ("challenge browser", "id_passkey.go", "WHERE challenge=? AND browser_hash=? AND", "WHERE challenge=? AND (? IS NOT NULL) AND", "TestIDGatedChallengeGuards/browser"), |
| ("challenge subject", "id_passkey.go", "AND subject=? AND purpose=?", "AND (? IS NOT NULL) AND purpose=?", "TestIDRegistrationChallengeSubjectAndLiveSession/subject"), |
| - ("challenge purpose", "id_passkey.go", "AND purpose=? AND expires_at>? RETURNING", "AND (? IS NOT NULL) AND expires_at>? RETURNING", "TestIDPasskeyRejectsBadProofs/purpose"), |
| - ("challenge expiry", "id_passkey.go", "AND expires_at>? RETURNING challenge", "AND (? IS NOT NULL) RETURNING challenge", "TestIDPasskeyRejectsBadProofs/expired"), |
| - ("challenge single use", "id_passkey.go", "DELETE FROM home_id_ceremonies WHERE challenge=? AND browser_hash=? AND subject=? AND purpose=? AND expires_at>? RETURNING challenge", "SELECT challenge FROM home_id_ceremonies WHERE challenge=? AND browser_hash=? AND subject=? AND purpose=? AND expires_at>?", "TestIDDirectPasskey"), |
| + ("challenge purpose", "id_passkey.go", "AND purpose=? AND expires_at>? RETURNING", "AND (? IS NOT NULL) AND expires_at>? RETURNING", "TestIDGatedChallengeGuards/purpose"), |
| + ("challenge expiry", "id_passkey.go", "AND expires_at>? RETURNING challenge", "AND (? IS NOT NULL) RETURNING challenge", "TestIDGatedChallengeGuards/expiry"), |
| + ("challenge single use", "id_passkey.go", "DELETE FROM home_id_ceremonies WHERE challenge=? AND browser_hash=? AND subject=? AND purpose=? AND expires_at>? RETURNING challenge", "SELECT challenge FROM home_id_ceremonies WHERE challenge=? AND browser_hash=? AND subject=? AND purpose=? AND expires_at>?", "TestIDGatedChallengeGuards/single-use"), |
| ("strict ceremony JSON", "id_passkey.go", "strictjson.UnmarshalRead(http.MaxBytesReader(w, r.Body, 64<<10), &body, strictjson.RejectUnknownMembers(true))", "decodeLooseIDJSON(r, &body)", "TestIDCeremonyRejectsAmbiguousJSON"), |
| ("credential collision", "id_passkey.go", "INSERT INTO passkey_credentials(id,subject,public_key,sign_count,created_at)", "INSERT OR REPLACE INTO passkey_credentials(id,subject,public_key,sign_count,created_at)", "TestIDEnrollmentCannotTransferCredential"), |
| ("credential enrollment bound", "id_passkey.go", "count >= 100", "count >= 1000", "TestIDEnrollmentBound"), |
| @@ -41,7 +41,7 @@ CASES = [ |
| ("IP attempt budget", "id_recovery.go", 'blindIndex(a.secrets.Pepper, clientIP(r)), 20}', 'blindIndex(a.secrets.Pepper, clientIP(r)), 200}', "TestIDRecoveryIPLimitAcrossAccounts"), |
| ("attempt increment", "id_recovery.go", "failures=failures+1", "failures=failures+0", "TestIDRecoveryAttemptLimitSurvivesReconstruction"), |
| ("attempt persistence", "app.go", "a.signinLimiter = signin.NewMemoryLimiter(15 * time.Minute)", '_, _ = d.Writer().Exec("DELETE FROM home_id_attempts")\n a.signinLimiter = signin.NewMemoryLimiter(15 * time.Minute)', "TestIDRecoveryAttemptLimitSurvivesReconstruction"), |
| - ("mailbox freshness", "id_recovery.go", "if mailboxAt <= 0 || mailboxAt > now || mailboxAt+300 <= now {", "if false && (mailboxAt <= 0 || mailboxAt > now || mailboxAt+300 <= now) {", "TestIDRecoveryRequiresFreshMailboxGesture"), |
| + ("mailbox freshness", "id_recovery.go", "if mailboxAt <= 0 || mailboxAt > now || mailboxAt+300 <= now {", "if false && (mailboxAt <= 0 || mailboxAt > now || mailboxAt+300 <= now) {", "TestIDRecoveryMailboxTimeDefense"), |
| ("recovery code person", "id_recovery.go", "WHERE subject=? AND code_hash=? RETURNING subject", "WHERE (? IS NOT NULL) AND code_hash=? RETURNING subject", "TestIDRecoveryCodePersonBindingAndReplay"), |
| ("recovery code single use", "id_recovery.go", "DELETE FROM passkey_recovery_codes WHERE subject=? AND code_hash=? RETURNING subject", "SELECT subject FROM passkey_recovery_codes WHERE subject=? AND code_hash=?", "TestIDRecoveryCodePersonBindingAndReplay"), |
| ("recovery proof expiry", "id_recovery.go", "AND subject=? AND expires_at>?", "AND subject=? AND (? IS NOT NULL)", "TestIDReplacementProofBinding/expired"), |
| @@ -74,6 +74,40 @@ CASES += [ |
| CASES += [ |
| ("credential page cache privacy","render.go", 'w.Header().Set("Cache-Control", "no-store")', 'w.Header().Set("Cache-Control", "")', "TestIDCredentialPagesAreNoStore"), |
| ] |
| +CASES += [ |
| + ("link recovery exclusion", "exchange.go", '|| strings.Contains(session.Method, "recovery")', '|| (false && strings.Contains(session.Method, "recovery"))', "TestIDRecoveryCannotLink"), |
| + ("enrollment recovery exclusion", "id_passkey.go", '|| strings.Contains(s.Method, "recovery")', '|| (false && strings.Contains(s.Method, "recovery"))', "TestIDRecoveryExclusions"), |
| + ("codes recovery exclusion", "passkey.go", '|| strings.Contains(live.Method, "recovery")', '|| (false && strings.Contains(live.Method, "recovery"))', "TestIDRecoveryExclusions"), |
| + ("replacement recovery suffix", "id_recovery.go", '!strings.HasSuffix(s.Method, "+recovery")', '(false && !strings.HasSuffix(s.Method, "+recovery"))', "TestIDReplacementRequiresRecoverySession/method"), |
| + ("replacement session binding", "id_recovery.go", 'AND session_hash=? AND subject=?', 'AND (? IS NOT NULL) AND subject=?', "TestIDReplacementRequiresRecoverySession/session"), |
| + ("limits before code consumption", "id_recovery.go", 'for _, b := range buckets {', 'for _, b := range buckets {', "TestIDLimitsBeforeValidCode"), |
| + ("recovery RAM reservation", "id_recovery.go", '|| !a.mailboxes.put(hash, p)', '|| (false && !a.mailboxes.put(hash, p))', "TestIDRecoveryMailboxFailurePreservesCode/full"), |
| + ("recovery RAM required", "id_recovery.go", '!ok || p.subject != subject ||', 'false ||', "TestIDRecoveryMailboxFailurePreservesCode/missing"), |
| + ("full mailbox permits gate", "id_recovery.go", 'mailboxUnix = 0', 'return false, errIDProof', "TestIDFullMailboxAllowsGatedSignin"), |
| + ("recovery signin notice", "id_recovery.go", 'a.sendRecoverySigninNotice(r.Context(), p.address)', '// notice omitted', "TestIDRecoverySigninNotice$"), |
| + ("new codes after replacement", "id_passkey.go", 'if codes == 0 {', 'if codes == 0 && false {', "TestIDRecoveryReplacementRevokesEverything"), |
| + ("stateless anonymous begin", "id_direct.go", 'idCookie(w, ceremonyCookie,', '_, _ = a.db.Writer().Exec("INSERT INTO home_id_ceremonies VALUES(?,?,?,?,?)", hex.EncodeToString(challenge), "browser", "", "direct", time.Now().Unix()+300)\n idCookie(w, ceremonyCookie,', "TestIDDirectFloodLeavesGatedCapacity"), |
| + ("direct seal authentication", "id_direct.go", 'plain, err := a.secrets.Sealer.Open("id.direct", sealed)', 'plain, err := a.secrets.Sealer.Open("id.direct", sealed)', "TestIDDirectSealedChallenge/tampered"), |
| + ("direct challenge binding", "id_direct.go", 'proof.Challenge != hex.EncodeToString(challenge)', '(proof.Challenge != hex.EncodeToString(challenge) && false)', "TestIDDirectSealedChallenge/mismatch"), |
| + ("direct expiry", "id_direct.go", 'proof.Expires <= now', '(proof.Expires <= now && false)', "TestIDDirectSealedChallenge/expired"), |
| + ("direct maximum lifetime", "id_direct.go", 'proof.Expires > now+300', '(proof.Expires > now+300 && false)', "TestIDDirectSealedChallenge/future"), |
| + ("direct receipt replay", "id_direct.go", 'INSERT INTO home_id_direct_used', 'INSERT OR REPLACE INTO home_id_direct_used', "TestIDDirectPasskey|TestIDDirectReceiptsBounded/restart"), |
| + ("direct receipt cap", "id_direct.go", 'n >= 10000', 'n >= 100000', "TestIDDirectReceiptsBounded/capacity"), |
| + ("direct receipt expiry", "id_direct.go", 'WHERE expires_at<=?', 'WHERE expires_at<? AND 0', "TestIDDirectReceiptsBounded/expiry"), |
| + ("issuer signout form", "directory.go", '"Action": a.origins.Credential + signoutPath', '"Action": a.origins.Directory + signoutPath', "TestSignOutEndsTheCredentialSession"), |
| + ("issuer signout auto step", "directory.go", 'finish := cookieValue(r, "__Host-oficina-finish-signout") == "1"', 'finish := false && cookieValue(r, "__Host-oficina-finish-signout") == "1"', "TestSignOutEndsTheCredentialSession"), |
| + ("issuer signout no loop", "directory.go", 'idCookie(w, "__Host-oficina-finish-signout", "", -1)', 'idCookie(w, "__Host-oficina-finish-signout", "1", 300)', "TestSignOutEndsTheCredentialSession"), |
| + ("issuer signout autosubmit", "static/assertion.js", 'form.requestSubmit()', 'form.checkValidity()', "TestIDBrowserSignoutBothOrigins"), |
| +] |
| +CASES += [ |
| + ("issuer site classification", "signout.go", 'site == other', 'site == other || true', "TestCredentialSignoutUsesIssuerSite"), |
| + ("issuer scheme classification", "signout.go", 'consumer.Scheme != issuer.Scheme', '(false && consumer.Scheme != issuer.Scheme)', "TestCredentialSignoutUsesIssuerSite"), |
| + ("recovery session marked", "id_recovery.go", 'Method: method + "+recovery"', 'Method: method', "TestIDRecoverySigninNotice$"), |
| +] |
| +CASES += [ |
| + ("anonymous begin stores no receipt", "id_direct.go", 'idCookie(w, ceremonyCookie,', '_, _ = a.db.Writer().Exec("INSERT INTO home_id_direct_used VALUES(?,?)", hex.EncodeToString(challenge), time.Now().Unix()+300)\n idCookie(w, ceremonyCookie,', "TestIDDirectFloodLeavesGatedCapacity"), |
| + ("recovery notice log privacy", "id_recovery.go", 'if a.secrets.Mailer.Send(ctx, address, recoverySigninNoticeSubject, recoverySigninNoticeBody) != nil {', 'if err:=a.secrets.Mailer.Send(ctx,address,recoverySigninNoticeSubject,recoverySigninNoticeBody);err!=nil {a.logger.Error("notice failed","err",err)', "TestIDRecoverySigninNoticeFailurePrivacy"), |
| +] |
| for table in ("sessions", "passkey_credentials", "passkey_recovery_codes", "passkey_pending", "passkey_challenges", "home_id_ceremonies", "home_id_recovery_proofs"): |
| CASES.append(("replacement revokes " + table,"id_recovery.go",f'\n\t\t"DELETE FROM {table} WHERE subject=?",',f'\n\t\t"DELETE FROM {table} WHERE subject=? AND 0",',"TestIDRecoveryReplacementRevokesEverything")) |
| @@ -86,9 +120,25 @@ for guard,file,old,new,test in CASES: |
| continue |
| path=HOME/file |
| original=path.read_text() |
| - if original.count(old)!=1: |
| + if original.count(old)!=1 and guard not in ("limits before code consumption", "replacement rollback"): |
| raise SystemExit(f"{guard}: expected one source match, got {original.count(old)}") |
| changed=original.replace(old,new) |
| + if guard=="replacement rollback": |
| + before,after=original.rsplit(old,1) |
| + changed=before+new+after |
| + if guard=="limits before code consumption": |
| + start=original.index("\tvar got string\n") |
| + end=original.index("\tif err == sql.ErrNoRows {",start) |
| + deletion=original[start:end] |
| + changed=original[:start]+original[end:] |
| + point=changed.index("\tfor _, b := range buckets {") |
| + changed=changed[:point]+deletion+changed[point:] |
| + if guard=="recovery RAM required": |
| + changed=changed.replace("p, ok := a.mailboxes.get(binding)", "p, _ := a.mailboxes.get(binding)") |
| + if guard=="direct seal authentication": |
| + # Model accepting a forged cookie by treating failed authentication as a |
| + # matching current challenge. A raw 'ignore err' still fails JSON parsing. |
| + changed=changed.replace('if err != nil {\n\t\treturn 0, errIDProof\n\t}\n\tvar proof', 'if err != nil {plain, _ = json.Marshal(directChallenge{hex.EncodeToString(challenge), now+300})}\n\tvar proof') |
| if guard=="recovery subject defenses together": |
| changed=changed.replace("!ok || p.subject != subject", "!ok || (p.subject != subject && false)") |
| if guard=="strict ceremony JSON": |
| @@ -97,7 +147,7 @@ for guard,file,old,new,test in CASES: |
| start=time.monotonic() |
| try: |
| path.write_text(changed) |
| - proc=subprocess.run(["go","test","./internal/home","-count=1","-timeout=30s","-run",test],cwd=ROOT,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True,timeout=75) |
| + proc=subprocess.run(["go","test","./internal/home","-count=1","-timeout=60s"]+(["-tags=browser"] if guard=="issuer signout autosubmit" else [])+["-run",test],cwd=ROOT,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True,timeout=75) |
| output=proc.stdout |
| if proc.returncode==0: |
| status="survived" |