Verify ID browser flows and close freshness and runtime regressions
17 files changed,
+583
−43
implementation/oficina-id-slice1-validation.md+16 −0internal/home/app.go+1 −1internal/home/exchange_test.go+22 −0internal/home/id_browser_test.go+142 −0internal/home/id_exchange_test.go+41 −0internal/home/id_limiter.go+24 −0internal/home/id_passkey.go+21 −5internal/home/id_passkey_test.go+159 −3internal/home/id_recovery_test.go+116 −1internal/home/operator_ceremony_test.go+1 −1internal/home/operator_http_test.go+4 −1internal/home/passkey.go+5 −2internal/home/passkey_test.go+12 −12internal/home/runtime.go+2 −0internal/home/signin_test.go+15 −15internal/home/team_page_test.go+1 −1internal/home/testapp_test.go+1 −1
CI failed — run details
diff --git a/implementation/oficina-id-slice1-validation.md b/implementation/oficina-id-slice1-validation.md| index 89c0aa6..5b2ef78 100644 |
| --- a/implementation/oficina-id-slice1-validation.md |
| +++ b/implementation/oficina-id-slice1-validation.md |
| @@ -41,3 +41,19 @@ Pending. |
| - 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. |
| + |
| +- Real Chromium: TestIDBrowserDirectPasskeyAndGeneratedNames, |
| + TestIDBrowserLegacyNonresidentGate and TestIDBrowserScriptlessCrossSiteReturn |
| + pass against two HTTPS sites routed to a loopback test server. No deploy. |
| +- Further red/green regressions: legacy runtime missing identity schema; |
| + duplicate/trailing ceremony JSON; enrollment exceeding the allowlist bound; |
| + future/passive enrollment authentication; readable address in Flow's limiter. |
| + The limiter now receives a blinded address key and still shares its IP budget |
| + with /resolve. Existing rate-limit tests remain in force. |
| +- Added code/person/replay races, live registration binding, clock rollback, |
| + challenge/cookie bounds, unrelated step-up refusal, backup-file privacy and |
| + notice retry tests. All targeted ID tests pass. |
| +- First hosted CI at df69548 failed three old fixtures (recent-session reuse |
| + and GET minting). Fixtures now reauthenticate the original identity and POST |
| + Continue; operator fixtures have explicit larger mail budgets for repeated |
| + independent test ceremonies. Production mail limits are unchanged. |
diff --git a/internal/home/app.go b/internal/home/app.go| index f774086..bdb3e3d 100644 |
| --- a/internal/home/app.go |
| +++ b/internal/home/app.go |
| @@ -144,7 +144,7 @@ func NewWithOrigins(secrets Secrets, d *db.DB, logger *slog.Logger, origins Orig |
| // The flow's default, made explicit so that /resolve shares its per-IP |
| // budget (resolve.go). |
| a.signinLimiter = signin.NewMemoryLimiter(15 * time.Minute) |
| - a.flow.Limiter = a.signinLimiter |
| + a.flow.Limiter = blindSigninLimiter{next: a.signinLimiter, pepper: secrets.Pepper} |
| a.resolveLimiter = signin.NewMemoryLimiter(time.Hour) |
| if a.passkeys, err = newPasskeys(a); err != nil { |
diff --git a/internal/home/exchange_test.go b/internal/home/exchange_test.go| index 2f76670..fe1baf0 100644 |
| --- a/internal/home/exchange_test.go |
| +++ b/internal/home/exchange_test.go |
| @@ -322,3 +322,25 @@ func TestDirectoryRoleUpgradePreservesExistingDatabase(t *testing.T) { |
| } |
| sealtest.AssertNoPlaintext(t, old.dbPath) |
| } |
| + |
| +func reauthenticateCredential(t *testing.T, a *testApp, c *http.Cookie) *http.Cookie { |
| + t.Helper() |
| + subject := subjectOf(t, a, c) |
| + var blind string |
| + if err := a.db.Writer().QueryRow("SELECT blind_index FROM people WHERE person_ref=?", subject).Scan(&blind); err != nil { |
| + t.Fatal(err) |
| + } |
| + address := "" |
| + a.mailer.mu.Lock() |
| + for _, m := range a.mailer.sent { |
| + if blindIndex(a.secrets.Pepper, m.To) == blind { |
| + address = m.To |
| + break |
| + } |
| + } |
| + a.mailer.mu.Unlock() |
| + if address == "" { |
| + t.Fatal("fixture lacks verified mailbox") |
| + } |
| + return signInFully(t, a, address) |
| +} |
diff --git a/internal/home/id_browser_test.go b/internal/home/id_browser_test.go| new file mode 100644 |
| index 0000000..b579052 |
| --- /dev/null |
| +++ b/internal/home/id_browser_test.go |
| @@ -0,0 +1,142 @@ |
| +//go:build browser |
| + |
| +package home |
| + |
| +import ( |
| + "context" |
| + "crypto/x509" |
| + "encoding/base64" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/home/internal/home/sealtest" |
| + "amadan.net/rastrillo/rastrillo/harness" |
| + "github.com/chromedp/cdproto/emulation" |
| + "github.com/chromedp/cdproto/network" |
| + "github.com/chromedp/cdproto/webauthn" |
| + "github.com/chromedp/chromedp" |
| +) |
| + |
| +const browserIssuer = "https://id.example.org" |
| +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) { |
| + t.Helper() |
| + p := newExchangePair(t) |
| + const consumer = "https://directory.example.test" |
| + origins := Origins{browserIssuer, consumer} |
| + old := p.credential.App |
| + app, err := NewWithOrigins(old.secrets, p.credential.db, quietLogger(), origins) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + app.flow.Classifier = old.flow.Classifier |
| + app.runtime = old.runtime |
| + p.credential.App = app |
| + p.credential.runtime.origins = origins |
| + p.credential.runtime.consumers["directory"] = consumer |
| + directory, err := NewRuntime(Runtime{role: "directory", origins: origins, secrets: p.directory.secrets, keys: p.credential.runtime.keys}, p.directory.db, quietLogger()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + p.directory = directory |
| + ch, dh := p.credential.Router(), p.directory.Router() |
| + 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" { |
| + dh.ServeHTTP(w, r) |
| + } else { |
| + http.NotFound(w, r) |
| + } |
| + })) |
| + 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())) |
| + alloc, stop := chromedp.NewExecAllocator(context.Background(), opts...) |
| + ctx, cancel := chromedp.NewContext(alloc) |
| + t.Cleanup(func() { _ = chromedp.Cancel(ctx); cancel(); stop() }) |
| + if err := chromedp.Run(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + var authenticator webauthn.AuthenticatorID |
| + idBrowserRun(t, ctx, webauthn.Enable(), chromedp.ActionFunc(func(ctx context.Context) error { |
| + var e error |
| + authenticator, e = webauthn.AddVirtualAuthenticator(&webauthn.VirtualAuthenticatorOptions{Protocol: webauthn.AuthenticatorProtocolCtap2, Transport: webauthn.AuthenticatorTransportInternal, HasResidentKey: true, HasUserVerification: true, IsUserVerified: true, AutomaticPresenceSimulation: true}).Do(ctx) |
| + return e |
| + })) |
| + return p, ctx, authenticator |
| +} |
| +func idBrowserRun(t *testing.T, ctx context.Context, actions ...chromedp.Action) { |
| + t.Helper() |
| + ctx, cancel := context.WithTimeout(ctx, 20*time.Second) |
| + defer cancel() |
| + if err := chromedp.Run(ctx, actions...); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| +func idBrowserCookie(c *http.Cookie) chromedp.Action { |
| + return network.SetCookie(c.Name, c.Value).WithURL(browserIssuer + "/").WithHTTPOnly(true).WithSecure(true).WithSameSite(network.CookieSameSiteLax) |
| +} |
| + |
| +func TestIDBrowserDirectPasskeyAndGeneratedNames(t *testing.T) { |
| + p, ctx, authenticator := idBrowser(t) |
| + s := signInFully(t, p.credential, sealtest.CanaryAddress) |
| + subject := subjectOf(t, p.credential, s) |
| + idBrowserRun(t, ctx, idBrowserCookie(s), chromedp.Navigate(browserIssuer+"/passkey/enrol"), chromedp.WaitVisible("#passkey-enrol"), chromedp.Click("#passkey-enrol"), chromedp.WaitVisible(`form[action="/passkey/codes"]`)) |
| + var credentials []*webauthn.Credential |
| + idBrowserRun(t, ctx, chromedp.ActionFunc(func(ctx context.Context) error { |
| + var e error |
| + credentials, e = webauthn.GetCredentials(authenticator).Do(ctx) |
| + return e |
| + })) |
| + if len(credentials) != 1 || !credentials[0].IsResidentCredential || credentials[0].UserName != subject || credentials[0].UserDisplayName != subject { |
| + t.Fatal("WebAuthn names were not generated opaque identifiers") |
| + } |
| + idBrowserRun(t, ctx, network.DeleteCookies(s.Name).WithURL(browserIssuer+"/"), chromedp.Navigate(browserIssuer+"/signin?return_to=%2Fpasskey%2Fcodes"), chromedp.WaitVisible("#passkey-direct"), chromedp.Click("#passkey-direct"), chromedp.WaitVisible(`form[action="/passkey/codes"]`)) |
| + sealtest.AssertNoPlaintext(t, p.credential.dbPath) |
| +} |
| +func TestIDBrowserLegacyNonresidentGate(t *testing.T) { |
| + p, ctx, authenticator := idBrowser(t) |
| + s := signInFully(t, p.credential, sealtest.CanaryAddress) |
| + key := enrol(t, p.credential, s) |
| + if _, err := p.credential.db.Writer().Exec("DELETE FROM home_id_discoverable"); err != nil { |
| + t.Fatal(err) |
| + } |
| + gated := redeemAfterSignIn(t, p.credential, sealtest.CanaryAddress) |
| + if _, err := p.credential.db.Writer().Exec("UPDATE passkey_pending SET return_to='/passkey/codes'"); err != nil { |
| + t.Fatal(err) |
| + } |
| + private, err := x509.MarshalPKCS8PrivateKey(key.Key) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + actions := []chromedp.Action{webauthn.AddCredential(authenticator, &webauthn.Credential{CredentialID: base64.StdEncoding.EncodeToString(key.CredID), RpID: browserRP, PrivateKey: base64.StdEncoding.EncodeToString(private), IsResidentCredential: false})} |
| + for _, c := range gated.Result().Cookies() { |
| + if c.Value != "" { |
| + actions = append(actions, idBrowserCookie(c)) |
| + } |
| + } |
| + actions = append(actions, chromedp.Navigate(browserIssuer+confirmPath), chromedp.WaitVisible("#passkey-confirm"), chromedp.Click("#passkey-confirm"), chromedp.WaitVisible(`form[action="/passkey/codes"]`)) |
| + idBrowserRun(t, ctx, actions...) |
| +} |
| +func TestIDBrowserScriptlessCrossSiteReturn(t *testing.T) { |
| + p, ctx, _ := idBrowser(t) |
| + idBrowserRun(t, ctx, emulation.SetScriptExecutionDisabled(true), chromedp.Navigate(p.directory.origins.Directory+"/auth/start"), chromedp.WaitVisible("#address"), chromedp.SendKeys("#address", sealtest.CanaryAddress), chromedp.Click(`form[action="/signin"] button`), chromedp.WaitVisible(`a[href*="/signin"]`)) |
| + token := capturedLink(t, p.credential) |
| + idBrowserRun(t, ctx, chromedp.Navigate(browserIssuer+linkPath+"?token="+url.QueryEscape(token)), chromedp.WaitVisible(`form[action="/signin/verify"] button`), chromedp.Click(`form[action="/signin/verify"] button`), chromedp.WaitVisible(`form[action="/authorize/resume"] button`), chromedp.Click(`form[action="/authorize/resume"] button`), chromedp.WaitVisible(`form[data-assertion-handoff] button`), chromedp.Click(`form[data-assertion-handoff] button`), chromedp.WaitVisible(`[estilo-account]`)) |
| + var location string |
| + idBrowserRun(t, ctx, chromedp.Location(&location)) |
| + if !strings.HasPrefix(location, p.directory.origins.Directory+"/") { |
| + t.Fatal("cross-site finish lost browser binding") |
| + } |
| + sealtest.AssertNoPlaintext(t, p.credential.dbPath) |
| + sealtest.AssertNoPlaintext(t, p.directoryPath) |
| +} |
diff --git a/internal/home/id_exchange_test.go b/internal/home/id_exchange_test.go| index 7c2ffb0..c1dfe88 100644 |
| --- a/internal/home/id_exchange_test.go |
| +++ b/internal/home/id_exchange_test.go |
| @@ -1,13 +1,16 @@ |
| package home |
| import ( |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| "net/http" |
| "net/http/httptest" |
| "net/url" |
| "strings" |
| "testing" |
| + "time" |
| "amadan.net/oficina/home/internal/home/sealtest" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| ) |
| func TestIDLinkAlwaysRequiresNewGesture(t *testing.T) { |
| @@ -58,3 +61,41 @@ func TestIDRevokedCachedSessionCannotMint(t *testing.T) { |
| t.Fatal("cached revoked session minted an assertion") |
| } |
| } |
| + |
| +func TestIDLegacyRuntimeAppliesIdentitySchema(t *testing.T) { |
| + d, err := migrate.Replay(t.Context(), (Runtime{}).ServingSchema().All()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer d.Close() |
| + if _, err = d.Exec("UPDATE home_id_clock SET high_water=1 WHERE id=1"); err != nil { |
| + t.Fatal("legacy runtime cannot serve identity handlers", err) |
| + } |
| + a := newTestApp(t) |
| + signInFully(t, a, sealtest.CanaryAddress) |
| +} |
| + |
| +func TestIDLinkRejectsProofBeforeTransactionStart(t *testing.T) { |
| + p := newExchangePair(t) |
| + old := signInFully(t, p.credential, sealtest.CanaryAddress) |
| + _, intent := p.startFresh(t, old) |
| + current := signInFully(t, p.credential, sealtest.CanaryAddress) |
| + if _, err := p.credential.db.Writer().Exec("UPDATE sessions SET auth_time=? WHERE token_hash=?", time.Now().Add(-30*time.Second).UTC().Format(time.RFC3339), sessions.HashToken(current.Value)); err != nil { |
| + t.Fatal(err) |
| + } |
| + r := exchangeRequest(p.credential.App, "POST", Origin+"/authorize/resume", Origin, nil, intent, current) |
| + if r.Code != 303 || !strings.HasPrefix(r.Header().Get("Location"), "/signin?") { |
| + t.Fatal("otherwise fresh proof predating link start was accepted") |
| + } |
| +} |
| + |
| +func TestIDLinkRejectsPassiveMintedSession(t *testing.T) { |
| + p := newExchangePair(t) |
| + _, intent := p.startFresh(t, nil) |
| + s := signInFully(t, p.credential, sealtest.CanaryAddress) |
| + p.credential.db.Writer().Exec("UPDATE sessions SET method='keymail',auth_time=''") |
| + r := exchangeRequest(p.credential.App, "POST", Origin+"/authorize/resume", Origin, nil, intent, s) |
| + if r.Code != 303 { |
| + t.Fatal("passive newly minted session satisfied linking") |
| + } |
| +} |
diff --git a/internal/home/id_limiter.go b/internal/home/id_limiter.go| new file mode 100644 |
| index 0000000..b424a29 |
| --- /dev/null |
| +++ b/internal/home/id_limiter.go |
| @@ -0,0 +1,24 @@ |
| +package home |
| + |
| +import ( |
| + "context" |
| + "strings" |
| + "time" |
| + |
| + "github.com/keymaildev/signin" |
| +) |
| + |
| +// Keep Flow's address budget without retaining its readable key. IP keys stay |
| +// shared with /resolve's budget. The upstream blind-auth-store adapter can use |
| +// this same Limiter seam without changing the stored person identity. |
| +type blindSigninLimiter struct { |
| + next signin.Limiter |
| + pepper []byte |
| +} |
| + |
| +func (l blindSigninLimiter) Allow(ctx context.Context, key string, now time.Time, budget int) (bool, error) { |
| + if address, ok := strings.CutPrefix(key, "addr:"); ok { |
| + key = "addr:" + blindIndex(l.pepper, address) |
| + } |
| + return l.next.Allow(ctx, key, now, budget) |
| +} |
diff --git a/internal/home/id_passkey.go b/internal/home/id_passkey.go| index 43beacd..7513bb9 100644 |
| --- a/internal/home/id_passkey.go |
| +++ b/internal/home/id_passkey.go |
| @@ -13,6 +13,7 @@ import ( |
| "amadan.net/rastrillo/rastrillo/sessions" |
| "amadan.net/rastrillo/rastrillo/webauthn" |
| + strictjson "github.com/go-json-experiment/json" |
| ) |
| const ceremonyCookie = "__Host-oficina-ceremony" |
| @@ -87,6 +88,14 @@ func (a *App) idSession(tx *sql.Tx, r *http.Request, now int64) (sessions.Sessio |
| s.At, _ = time.Parse(time.RFC3339, created) |
| return s, hash, nil |
| } |
| +func idFreshSession(s sessions.Session, age time.Duration, now time.Time) bool { |
| + at := s.AuthTime |
| + if at.IsZero() { |
| + at = s.At |
| + } |
| + return !keymailWithoutGesture(s) && !at.After(now) && sessions.Fresh(s, age, now) |
| +} |
| + |
| func (a *App) idBinding(tx *sql.Tx, r *http.Request, purpose string, now int64) (subject, binding string, err error) { |
| switch purpose { |
| case "replace": |
| @@ -115,7 +124,7 @@ func (a *App) idBinding(tx *sql.Tx, r *http.Request, purpose string, now int64) |
| if e != nil { |
| return "", "", e |
| } |
| - if purpose == "register" && (!sessions.Fresh(s, enrolFreshness, time.Unix(now, 0)) || strings.Contains(s.Method, "recovery")) { |
| + if purpose == "register" && (!idFreshSession(s, enrolFreshness, time.Unix(now, 0)) || strings.Contains(s.Method, "recovery")) { |
| return "", "", errIDProof |
| } |
| return s.Subject, hash, nil |
| @@ -166,7 +175,7 @@ func (a *App) idBegin(purpose string) http.HandlerFunc { |
| } |
| 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) |
| + rows, e := tx.Query("SELECT id FROM passkey_credentials WHERE subject=? ORDER BY id LIMIT 101", subject) |
| if e != nil { |
| idRefuse(w) |
| return |
| @@ -188,6 +197,10 @@ func (a *App) idBegin(purpose string) http.HandlerFunc { |
| } |
| e = rows.Err() |
| rows.Close() |
| + if len(credentials) > 100 { |
| + idRefuse(w) |
| + return |
| + } |
| if e != nil { |
| idRefuse(w) |
| return |
| @@ -214,9 +227,7 @@ type idCeremony struct { |
| func decodeIDCeremony(w http.ResponseWriter, r *http.Request) (idCeremony, []byte, []byte, error) { |
| var body idCeremony |
| - d := json.NewDecoder(http.MaxBytesReader(w, r.Body, 64<<10)) |
| - d.DisallowUnknownFields() |
| - if d.Decode(&body) != nil { |
| + if strictjson.UnmarshalRead(http.MaxBytesReader(w, r.Body, 64<<10), &body, strictjson.RejectUnknownMembers(true)) != nil { |
| return body, nil, nil, errIDProof |
| } |
| cd, err := base64.RawURLEncoding.Strict().DecodeString(body.ClientData) |
| @@ -312,6 +323,11 @@ func (a *App) idFinish(purpose string) http.HandlerFunc { |
| idJSONReply(w, 200, map[string]any{"ok": true, "to": "/passkey/replaced"}) |
| return |
| } |
| + var count int |
| + if tx.QueryRow("SELECT count(*) FROM passkey_credentials WHERE subject=?", subject).Scan(&count) != nil || count >= 100 { |
| + idRefuse(w) |
| + return |
| + } |
| id := hex.EncodeToString(cred.ID) |
| if _, e = tx.Exec("INSERT INTO passkey_credentials(id,subject,public_key,sign_count,created_at) VALUES(?,?,?,?,?)", id, subject, cred.PublicKey, cred.SignCount, time.Unix(now, 0).UTC().Format(time.RFC3339)); e != nil { |
| idRefuse(w) |
diff --git a/internal/home/id_passkey_test.go b/internal/home/id_passkey_test.go| index da5edb5..83b7840 100644 |
| --- a/internal/home/id_passkey_test.go |
| +++ b/internal/home/id_passkey_test.go |
| @@ -3,6 +3,7 @@ package home |
| import ( |
| "encoding/base64" |
| "encoding/json" |
| + "fmt" |
| "net/http" |
| "net/http/httptest" |
| "strings" |
| @@ -19,8 +20,8 @@ func idJSON(t *testing.T, app *testApp, path string, body any, cookies ...*http. |
| if err != nil { |
| t.Fatal(err) |
| } |
| - req := httptest.NewRequest("POST", Origin+path, strings.NewReader(string(b))) |
| - req.Header.Set("Origin", Origin) |
| + req := httptest.NewRequest("POST", app.origins.Credential+path, strings.NewReader(string(b))) |
| + req.Header.Set("Origin", app.origins.Credential) |
| req.Header.Set("Content-Type", "application/json") |
| for _, c := range cookies { |
| if c != nil { |
| @@ -42,7 +43,8 @@ func TestIDDirectPasskey(t *testing.T) { |
| begin := idJSON(t, app, "/passkey/direct/begin", nil) |
| challenge := challengeFrom(t, begin) |
| cookie := namedCookie(t, begin, "__Host-oficina-ceremony") |
| - body := assertionBody(key, challenge, authtest.Options{RPID: credentialHost, Origin: Origin}) |
| + zero := uint32(0) |
| + body := assertionBody(key, challenge, authtest.Options{RPID: credentialHost, Origin: Origin, Count: &zero}) |
| wrong := idJSON(t, app, "/passkey/direct/finish", body) |
| if sessionCookie(wrong) != nil || wrong.Code == 200 { |
| t.Fatal("unbound browser signed in") |
| @@ -131,3 +133,157 @@ func TestIDGateOffersBoundLegacyCredentials(t *testing.T) { |
| t.Fatal("legacy gated signin failed", r.Code) |
| } |
| } |
| + |
| +func TestIDCeremonyRejectsAmbiguousJSON(t *testing.T) { |
| + for _, kind := range []string{"trailing", "duplicate"} { |
| + t.Run(kind, func(t *testing.T) { |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + key := enrol(t, a, s) |
| + begin := idJSON(t, a, "/passkey/direct/begin", nil) |
| + cookie := namedCookie(t, begin, ceremonyCookie) |
| + body := assertionBody(key, challengeFrom(t, begin), authtest.Options{RPID: credentialHost, Origin: Origin}) |
| + b, _ := json.Marshal(body) |
| + if kind == "trailing" { |
| + b = append(b, []byte(` {}`)...) |
| + } else { |
| + b = append([]byte(`{"id":"ignored",`), b[1:]...) |
| + } |
| + req := httptest.NewRequest("POST", Origin+"/passkey/direct/finish", strings.NewReader(string(b))) |
| + req.Header.Set("Origin", Origin) |
| + req.AddCookie(cookie) |
| + w := httptest.NewRecorder() |
| + a.Router().ServeHTTP(w, req) |
| + if w.Code == 200 || sessionCookie(w) != nil { |
| + t.Fatal("ambiguous ceremony JSON accepted") |
| + } |
| + }) |
| + } |
| +} |
| +func TestIDEnrollmentBound(t *testing.T) { |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + key := enrol(t, a, s) |
| + subject := subjectOf(t, a, s) |
| + for i := 0; i < 99; i++ { |
| + if _, err := a.db.Writer().Exec("INSERT INTO passkey_credentials(id,subject,public_key,sign_count,created_at) VALUES(?,?,?,0,'2026-11-13')", fmt.Sprintf("%064x", i), subject, key.COSEKey()); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + begin := idJSON(t, a, "/passkey/register/begin", nil, s) |
| + next, _ := authtest.New() |
| + cd, att := next.Create(challengeFrom(t, begin), authtest.Options{RPID: credentialHost, Origin: Origin}) |
| + r := idJSON(t, a, "/passkey/register/finish", map[string]string{"clientDataJSON": base64.RawURLEncoding.EncodeToString(cd), "attestationObject": base64.RawURLEncoding.EncodeToString(att)}, s) |
| + if r.Code == 200 { |
| + t.Fatal("enrollment exceeded the gated allowlist bound") |
| + } |
| +} |
| + |
| +func TestIDEnrollmentRejectsFutureAndPassiveAuthentication(t *testing.T) { |
| + for _, kind := range []string{"future", "passive"} { |
| + t.Run(kind, func(t *testing.T) { |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + query := "UPDATE sessions SET auth_time=?" |
| + value := time.Now().Add(time.Hour).UTC().Format(time.RFC3339) |
| + if kind == "passive" { |
| + query = "UPDATE sessions SET auth_time=?,method='keymail'" |
| + value = "" |
| + } |
| + if _, err := a.db.Writer().Exec(query, value); err != nil { |
| + t.Fatal(err) |
| + } |
| + if r := idJSON(t, a, "/passkey/register/begin", nil, s); r.Code == 200 { |
| + t.Fatal("enrollment accepted non-fresh authentication", kind) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestIDGateBindsCredentialOwner(t *testing.T) { |
| + a := newTestApp(t) |
| + first := signInFully(t, a, sealtest.CanaryAddress) |
| + enrol(t, a, first) |
| + second := signInFully(t, a, "other@example.invalid") |
| + key := enrol(t, a, second) |
| + gated := redeemAfterSignIn(t, a, sealtest.CanaryAddress) |
| + begin := idJSON(t, a, "/passkey/signin/begin", nil, gated.Result().Cookies()...) |
| + 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 || sessionCookie(r) != nil { |
| + t.Fatal("another person's passkey completed gate") |
| + } |
| +} |
| +func TestIDChallengeBrowserCookiesAndExpiry(t *testing.T) { |
| + for _, kind := range []string{"duplicate", "other-browser", "ttl", "clock", "capacity"} { |
| + t.Run(kind, func(t *testing.T) { |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + key := enrol(t, a, s) |
| + b := idJSON(t, a, "/passkey/direct/begin", nil) |
| + c := namedCookie(t, b, ceremonyCookie) |
| + if c.MaxAge != 300 || !c.Secure || !c.HttpOnly || c.Domain != "" || c.Path != "/" || c.SameSite != http.SameSiteLaxMode { |
| + t.Fatal("challenge cookie isolation or TTL") |
| + } |
| + body := assertionBody(key, challengeFrom(t, b), authtest.Options{RPID: credentialHost, Origin: Origin}) |
| + cookies := []*http.Cookie{c} |
| + switch kind { |
| + case "duplicate": |
| + cookies = append(cookies, c) |
| + case "other-browser": |
| + 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) |
| + } |
| + return |
| + case "clock": |
| + a.db.Writer().Exec("UPDATE home_id_clock SET high_water=?", time.Now().Unix()+100) |
| + case "capacity": |
| + 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 { |
| + t.Fatal("challenge bound bypassed") |
| + } |
| + return |
| + } |
| + if r := idJSON(t, a, "/passkey/direct/finish", body, cookies...); r.Code == 200 || sessionCookie(r) != nil { |
| + t.Fatal("challenge accepted", kind) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestIDRegistrationChallengeSubjectAndLiveSession(t *testing.T) { |
| + for _, kind := range []string{"subject", "expired-session"} { |
| + t.Run(kind, func(t *testing.T) { |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + b := idJSON(t, a, "/passkey/register/begin", nil, s) |
| + k, _ := authtest.New() |
| + cd, att := k.Create(challengeFrom(t, b), authtest.Options{RPID: credentialHost, Origin: Origin}) |
| + if kind == "subject" { |
| + a.db.Writer().Exec("UPDATE home_id_ceremonies SET subject='other'") |
| + } else { |
| + a.db.Writer().Exec("UPDATE sessions SET expires_at='2000-01-01T00:00:00Z'") |
| + } |
| + r := idJSON(t, a, "/passkey/register/finish", map[string]string{"clientDataJSON": base64.RawURLEncoding.EncodeToString(cd), "attestationObject": base64.RawURLEncoding.EncodeToString(att)}, s) |
| + if r.Code == 200 { |
| + t.Fatal("registration lost live subject/session binding") |
| + } |
| + }) |
| + } |
| +} |
| +func TestIDLegacyCredentialCannotSignInDirectly(t *testing.T) { |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + k := enrol(t, a, s) |
| + a.db.Writer().Exec("DELETE FROM home_id_discoverable") |
| + b := idJSON(t, a, "/passkey/direct/begin", nil) |
| + r := idJSON(t, a, "/passkey/direct/finish", assertionBody(k, challengeFrom(t, b), authtest.Options{RPID: credentialHost, Origin: Origin}), namedCookie(t, b, ceremonyCookie)) |
| + if r.Code == 200 { |
| + t.Fatal("legacy credential bypassed mailbox gate") |
| + } |
| +} |
diff --git a/internal/home/id_recovery_test.go b/internal/home/id_recovery_test.go| index 5e84c82..bb87665 100644 |
| --- a/internal/home/id_recovery_test.go |
| +++ b/internal/home/id_recovery_test.go |
| @@ -1,19 +1,24 @@ |
| package home |
| import ( |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| "bytes" |
| "context" |
| + cryptorand "crypto/rand" |
| "encoding/base64" |
| "errors" |
| "fmt" |
| "github.com/keymaildev/signin" |
| + "io" |
| "log/slog" |
| "net/http" |
| "net/http/httptest" |
| "net/url" |
| + "path/filepath" |
| "regexp" |
| "strings" |
| "sync" |
| + "sync/atomic" |
| "testing" |
| "time" |
| @@ -45,6 +50,9 @@ func TestIDRecoveryEntropy(t *testing.T) { |
| s := signInFully(t, a, sealtest.CanaryAddress) |
| enrol(t, a, s) |
| seen := map[string]bool{} |
| + entropy := &entropyReader{Reader: cryptorand.Reader} |
| + cryptorand.Reader = entropy |
| + defer func() { cryptorand.Reader = entropy.Reader }() |
| for _, c := range idCodes(t, a, s) { |
| raw := strings.ReplaceAll(c, "-", "") |
| if len(raw) < 16 || seen[raw] { |
| @@ -52,8 +60,18 @@ func TestIDRecoveryEntropy(t *testing.T) { |
| } |
| seen[raw] = true |
| } |
| + if entropy.n < 100 { |
| + t.Fatal("recovery codes used less than 80 bits each", entropy.n) |
| + } |
| sealtest.AssertNoPlaintext(t, a.dbPath) |
| } |
| + |
| +type entropyReader struct { |
| + io.Reader |
| + n int |
| +} |
| + |
| +func (r *entropyReader) Read(b []byte) (int, error) { n, e := r.Reader.Read(b); r.n += n; return n, e } |
| func TestIDRecoveryAttemptLimitSurvivesReconstruction(t *testing.T) { |
| a := newTestApp(t) |
| s := signInFully(t, a, sealtest.CanaryAddress) |
| @@ -87,6 +105,10 @@ func TestIDRecoveryReplacementRevokesEverything(t *testing.T) { |
| t.Fatal("recovery signin", recovery.Code) |
| } |
| cookies := recovery.Result().Cookies() |
| + redeemAfterSignIn(t, a, sealtest.CanaryAddress) // another device still between factors |
| + subject := subjectOf(t, a, s) |
| + a.db.Writer().Exec("INSERT INTO passkey_challenges VALUES(?, ?, 'stepup', ?)", "old-challenge", subject, time.Now().Add(time.Minute).UTC().Format(time.RFC3339)) |
| + a.db.Writer().Exec("INSERT INTO home_id_ceremonies VALUES(?, ?, ?, 'stepup', ?)", "other-challenge", "other-browser", subject, time.Now().Unix()+60) |
| // 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") |
| @@ -103,7 +125,7 @@ func TestIDRecoveryReplacementRevokesEverything(t *testing.T) { |
| if done.Code != 200 { |
| t.Fatal("replace", done.Code) |
| } |
| - for _, table := range []string{"sessions", "passkey_recovery_codes", "passkey_pending", "home_id_recovery_proofs"} { |
| + for _, table := range []string{"sessions", "passkey_recovery_codes", "passkey_pending", "home_id_recovery_proofs", "passkey_challenges", "home_id_ceremonies"} { |
| 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) |
| @@ -303,3 +325,96 @@ func TestIDRecoveryIPLimitAcrossAccounts(t *testing.T) { |
| } |
| } |
| } |
| + |
| +func TestIDSigninLimiterUsesBlindedAddress(t *testing.T) { |
| + a := newTestApp(t) |
| + signIn(t, a, sealtest.CanaryAddress) |
| + if strings.Contains(fmt.Sprintf("%#v", a.signinLimiter), sealtest.CanaryAddress) { |
| + t.Fatal("sign-in limiter retains a readable address") |
| + } |
| +} |
| +func TestIDRecoveryPrivacyInBackup(t *testing.T) { |
| + a, cookies, body := replacementFixture(t) |
| + done := idJSON(t, a, "/passkey/replace/finish", body, cookies...) |
| + if done.Code != 200 { |
| + t.Fatal("replacement", done.Code) |
| + } |
| + backup := filepath.Join(t.TempDir(), "backup.sqlite") |
| + if _, err := a.db.Writer().Exec("VACUUM INTO ?", backup); err != nil { |
| + t.Fatal(err) |
| + } |
| + sealtest.AssertNoPlaintext(t, backup) |
| + sealtest.AssertNoPlaintext(t, a.dbPath) |
| +} |
| +func TestIDReplacementNoticeRetry(t *testing.T) { |
| + a, cookies, body := replacementFixture(t) |
| + a.secrets.Mailer = idFailMailer{} |
| + done := idJSON(t, a, "/passkey/replace/finish", body, cookies...) |
| + if done.Code != 200 { |
| + t.Fatal("replacement", done.Code) |
| + } |
| + a.secrets.Mailer = a.mailer |
| + retry := exchangeRequest(a.App, "POST", Origin+"/passkey/notice", Origin, url.Values{}, done.Result().Cookies()...) |
| + if retry.Code != 303 { |
| + t.Fatal("retry", retry.Code) |
| + } |
| + mail, ok := a.mailer.last() |
| + if !ok || mail.To != sealtest.CanaryAddress || mail.Subject != replacementNoticeSubject { |
| + t.Fatal("retry did not use proven mailbox") |
| + } |
| + key := sessions.HashToken(namedCookie(t, done, noticeCookie).Value) |
| + if _, ok := a.mailboxes.get(key); ok { |
| + t.Fatal("successful notice retained address") |
| + } |
| +} |
| + |
| +func TestIDRecoveryCodePersonBindingAndReplay(t *testing.T) { |
| + a := newTestApp(t) |
| + s := signInFully(t, a, sealtest.CanaryAddress) |
| + enrol(t, a, s) |
| + codes := idCodes(t, a, s) |
| + other := signInFully(t, a, "other@example.invalid") |
| + enrol(t, a, other) |
| + wrongGate := redeemAfterSignIn(t, a, "other@example.invalid") |
| + wrong := exchangeRequest(a.App, "POST", Origin+"/passkey/signin/recovery", Origin, url.Values{"code": {codes[0]}}, wrongGate.Result().Cookies()...) |
| + if sessionCookie(wrong) != nil { |
| + t.Fatal("code crossed accounts") |
| + } |
| + gate := redeemAfterSignIn(t, a, sealtest.CanaryAddress) |
| + var successes atomic.Int32 |
| + var wg sync.WaitGroup |
| + for i := 0; i < 12; i++ { |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + r := exchangeRequest(a.App, "POST", Origin+"/passkey/signin/recovery", Origin, url.Values{"code": {codes[0]}}, gate.Result().Cookies()...) |
| + if sessionCookie(r) != nil { |
| + successes.Add(1) |
| + } |
| + }() |
| + } |
| + wg.Wait() |
| + if successes.Load() != 1 { |
| + t.Fatal("recovery proof minted more than once", successes.Load()) |
| + } |
| + gate = redeemAfterSignIn(t, a, sealtest.CanaryAddress) |
| + replay := exchangeRequest(a.App, "POST", Origin+"/passkey/signin/recovery", Origin, url.Values{"code": {codes[0]}}, gate.Result().Cookies()...) |
| + if sessionCookie(replay) != nil { |
| + t.Fatal("used code replayed with new mailbox proof") |
| + } |
| +} |
| +func TestIDRecoveryCannotRegenerateCodesOrSatisfyPasskeyOnlyStepup(t *testing.T) { |
| + a, cookies, _ := replacementFixture(t) |
| + r := exchangeRequest(a.App, "POST", Origin+"/passkey/codes", Origin, url.Values{}, cookies...) |
| + if r.Code == 200 { |
| + t.Fatal("recovery session generated codes before new passkey proof") |
| + } |
| + req := httptest.NewRequest("GET", Origin+"/", nil) |
| + for _, c := range cookies { |
| + req.AddCookie(c) |
| + } |
| + s, ok := a.sessions.From(req) |
| + if !ok || credentialFresh(s, time.Now()) { |
| + t.Fatal("recovery satisfied passkey-only operator stepup") |
| + } |
| +} |
diff --git a/internal/home/operator_ceremony_test.go b/internal/home/operator_ceremony_test.go| index 1f25986..6e8b049 100644 |
| --- a/internal/home/operator_ceremony_test.go |
| +++ b/internal/home/operator_ceremony_test.go |
| @@ -270,7 +270,7 @@ func TestOperatorEndToEndProvisioningAndRegistry(t *testing.T) { |
| } |
| intent := namedCookie(t, authorize, assertionIntentCookie) |
| session := signInFully(t, f.credential, sealtest.CanaryAddress) |
| - handoff := exchangeRequest(f.credential.App, "GET", Origin+"/authorize/resume", "", nil, intent, session) |
| + handoff := exchangeRequest(f.credential.App, "POST", Origin+"/authorize/resume", Origin, nil, intent, session) |
| target := "https://" + operatorLabel + ".docs.oficina.works" |
| csp := handoff.Header().Get("Content-Security-Policy") |
| if handoff.Code != 200 || !strings.Contains(csp, "form-action 'self' "+target+" "+directoryOrigin+";") && !strings.HasSuffix(csp, "form-action 'self' "+target+" "+directoryOrigin) { |
diff --git a/internal/home/operator_http_test.go b/internal/home/operator_http_test.go| index c61caf7..c8fcfcd 100644 |
| --- a/internal/home/operator_http_test.go |
| +++ b/internal/home/operator_http_test.go |
| @@ -134,6 +134,9 @@ func newOperatorFixtureConsumers(t *testing.T, consumers map[string]string) *ope |
| capp.flow.Classifier.LookupTXT = func(context.Context, string) ([]string, error) { |
| return nil, errors.New("no resolver in tests") |
| } |
| + // This fixture performs many independent operator ceremonies in one window. |
| + capp.flow.IPBudget = 200 |
| + capp.flow.AddressBudget = 100 |
| f.credential = &testApp{App: capp, mailer: mailer, db: cd, dbPath: credPath} |
| // Directory role. |
| @@ -261,7 +264,7 @@ 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) |
| - credentialSession = signInFully(t, f.credential, f.paulAddress) |
| + credentialSession = reauthenticateCredential(t, f.credential, credentialSession) |
| 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 { |
diff --git a/internal/home/passkey.go b/internal/home/passkey.go| index c80da24..84d7958 100644 |
| --- a/internal/home/passkey.go |
| +++ b/internal/home/passkey.go |
| @@ -8,7 +8,6 @@ import ( |
| "time" |
| "amadan.net/rastrillo/rastrillo/passkey" |
| - "amadan.net/rastrillo/rastrillo/sessions" |
| "amadan.net/rastrillo/rastrillo/webauthn" |
| ) |
| @@ -150,6 +149,10 @@ func (a *App) handlePasskeyEnrol(w http.ResponseWriter, r *http.Request) { |
| http.Redirect(w, r, "/signin", http.StatusSeeOther) |
| return |
| } |
| + if !idFreshSession(sess, enrolFreshness, time.Now()) { |
| + http.Redirect(w, r, "/signin?force=1&return_to=%2Fpasskey%2Fenrol", http.StatusSeeOther) |
| + return |
| + } |
| if strings.Contains(sess.Method, "recovery") { |
| http.Redirect(w, r, "/passkey/replace", http.StatusSeeOther) |
| return |
| @@ -194,7 +197,7 @@ func (a *App) handleRegenerateRecoveryCodes(w http.ResponseWriter, r *http.Reque |
| } |
| 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)) { |
| + if err != nil || live.Subject != sess.Subject || strings.Contains(live.Method, "recovery") || !idFreshSession(live, codesFreshness, time.Unix(now, 0)) { |
| a.signinFailed(w, r) |
| return |
| } |
diff --git a/internal/home/passkey_test.go b/internal/home/passkey_test.go| index 30f8417..0a63eca 100644 |
| --- a/internal/home/passkey_test.go |
| +++ b/internal/home/passkey_test.go |
| @@ -40,9 +40,9 @@ func postJSON(t *testing.T, app *testApp, path string, cookie *http.Cookie, body |
| payload = "{}" |
| } |
| req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(payload)) |
| - req.Host = credentialHost |
| + req.Host = app.credentialHost |
| req.Header.Set("Content-Type", "application/json") |
| - req.Header.Set("Origin", Origin) |
| + req.Header.Set("Origin", app.origins.Credential) |
| if cookie != nil { |
| req.AddCookie(cookie) |
| } |
| @@ -78,7 +78,7 @@ func enrol(t *testing.T, app *testApp, cookie *http.Cookie) *authtest.Authentica |
| t.Fatal(err) |
| } |
| challenge := challengeFrom(t, postJSON(t, app, "/passkey/register/begin", cookie, nil)) |
| - clientData, attestation := a.Create(challenge, authtest.Options{RPID: app.credentialHost, Origin: Origin}) |
| + clientData, attestation := a.Create(challenge, authtest.Options{RPID: app.credentialHost, Origin: app.origins.Credential}) |
| rec := postJSON(t, app, "/passkey/register/finish", cookie, map[string]string{ |
| "clientDataJSON": base64.RawURLEncoding.EncodeToString(clientData), |
| "attestationObject": base64.RawURLEncoding.EncodeToString(attestation), |
| @@ -167,9 +167,9 @@ func TestRecoveryCodeCompletesSignInWithoutScript(t *testing.T) { |
| form := url.Values{"code": {codes[0]}} |
| req := httptest.NewRequest(http.MethodPost, "/passkey/signin/recovery", strings.NewReader(form.Encode())) |
| - req.Host = credentialHost |
| + req.Host = app.credentialHost |
| req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| - req.Header.Set("Origin", Origin) |
| + req.Header.Set("Origin", app.origins.Credential) |
| for _, c := range (&http.Response{Header: gated.Header()}).Cookies() { |
| req.AddCookie(c) |
| } |
| @@ -194,7 +194,7 @@ func TestRecoveryCodeCompletesSignInWithoutScript(t *testing.T) { |
| func subjectOf(t *testing.T, app *testApp, cookie *http.Cookie) string { |
| t.Helper() |
| req := httptest.NewRequest(http.MethodGet, "/", nil) |
| - req.Host = credentialHost |
| + req.Host = app.credentialHost |
| req.AddCookie(cookie) |
| sess, ok := app.sessions.From(req) |
| if !ok { |
| @@ -209,7 +209,7 @@ func TestScriptAssetsAreServedOnNamedPaths(t *testing.T) { |
| app := newTestApp(t) |
| for _, path := range []string{"/static/webauthn.mjs", "/static/passkey.js"} { |
| req := httptest.NewRequest(http.MethodGet, path, nil) |
| - req.Host = credentialHost |
| + req.Host = app.credentialHost |
| w := httptest.NewRecorder() |
| app.Router().ServeHTTP(w, req) |
| if w.Code != http.StatusOK { |
| @@ -233,7 +233,7 @@ func TestRecoveryCodesPageNeedsAFreshSession(t *testing.T) { |
| get := func() int { |
| req := httptest.NewRequest(http.MethodGet, "/passkey/codes", nil) |
| - req.Host = credentialHost |
| + req.Host = app.credentialHost |
| req.AddCookie(cookie) |
| w := httptest.NewRecorder() |
| app.Router().ServeHTTP(w, req) |
| @@ -285,9 +285,9 @@ func TestRecoveryCodeProducesAFreshSession(t *testing.T) { |
| form := url.Values{"code": {codes[0]}} |
| req := httptest.NewRequest(http.MethodPost, "/passkey/signin/recovery", strings.NewReader(form.Encode())) |
| - req.Host = credentialHost |
| + req.Host = app.credentialHost |
| req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| - req.Header.Set("Origin", Origin) |
| + req.Header.Set("Origin", app.origins.Credential) |
| for _, c := range (&http.Response{Header: gated.Header()}).Cookies() { |
| req.AddCookie(c) |
| } |
| @@ -344,7 +344,7 @@ func TestEnrolmentNeedsAFreshSession(t *testing.T) { |
| // The page itself redirects to re-authenticate rather than 404ing or |
| // 403ing: a detour, not a dead end. |
| req := httptest.NewRequest(http.MethodGet, "/passkey/enrol", nil) |
| - req.Host = credentialHost |
| + req.Host = app.credentialHost |
| req.AddCookie(cookie) |
| w := httptest.NewRecorder() |
| app.Router().ServeHTTP(w, req) |
| @@ -386,7 +386,7 @@ func TestEnrolThenReadCodesWithoutReauthenticating(t *testing.T) { |
| enrol(t, app, cookie) |
| req := httptest.NewRequest(http.MethodGet, "/passkey/codes", nil) |
| - req.Host = credentialHost |
| + req.Host = app.credentialHost |
| req.AddCookie(cookie) |
| w := httptest.NewRecorder() |
| app.Router().ServeHTTP(w, req) |
diff --git a/internal/home/runtime.go b/internal/home/runtime.go| index 02cb0d8..bed7dee 100644 |
| --- a/internal/home/runtime.go |
| +++ b/internal/home/runtime.go |
| @@ -215,6 +215,8 @@ func (cfg Runtime) ServingSchema() *migrate.Set { |
| return migrate.Merge(cfg.Schema(), operator.DirectoryHTTPSchema, directorydata.TeamSchema) |
| case "credential": |
| return migrate.Merge(cfg.Schema(), operator.CredentialHTTPSchema, identitySchema) |
| + case "": |
| + return migrate.Merge(cfg.Schema(), identitySchema) |
| } |
| return cfg.Schema() |
| } |
diff --git a/internal/home/signin_test.go b/internal/home/signin_test.go| index e308d8d..3402a14 100644 |
| --- a/internal/home/signin_test.go |
| +++ b/internal/home/signin_test.go |
| @@ -27,9 +27,9 @@ func signIn(t *testing.T, app *testApp, addr string) *httptest.ResponseRecorder |
| t.Helper() |
| form := url.Values{"address": {addr}} |
| req := httptest.NewRequest(http.MethodPost, "/signin", strings.NewReader(form.Encode())) |
| - req.Host = credentialHost |
| + req.Host = app.credentialHost |
| req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| - req.Header.Set("Origin", Origin) |
| + req.Header.Set("Origin", app.origins.Credential) |
| w := httptest.NewRecorder() |
| app.Router().ServeHTTP(w, req) |
| return w |
| @@ -42,7 +42,7 @@ func capturedLink(t *testing.T, app *testApp) string { |
| if !ok { |
| t.Fatal("no mail was sent") |
| } |
| - i := strings.Index(sent.Body, Origin+linkPath) |
| + i := strings.Index(sent.Body, app.origins.Credential+linkPath) |
| if i < 0 { |
| t.Fatalf("no sign-in link in the mail body: %q", sent.Body) |
| } |
| @@ -66,9 +66,9 @@ func redeem(t *testing.T, app *testApp, token string) *httptest.ResponseRecorder |
| t.Helper() |
| form := url.Values{"token": {token}} |
| req := httptest.NewRequest(http.MethodPost, linkPath, strings.NewReader(form.Encode())) |
| - req.Host = credentialHost |
| + req.Host = app.credentialHost |
| req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| - req.Header.Set("Origin", Origin) |
| + req.Header.Set("Origin", app.origins.Credential) |
| w := httptest.NewRecorder() |
| app.Router().ServeHTTP(w, req) |
| return w |
| @@ -167,7 +167,7 @@ func TestGetDoesNotRedeemTheLink(t *testing.T) { |
| token := capturedLink(t, app) |
| req := httptest.NewRequest(http.MethodGet, linkPath+"?token="+url.QueryEscape(token), nil) |
| - req.Host = credentialHost |
| + req.Host = app.credentialHost |
| w := httptest.NewRecorder() |
| app.Router().ServeHTTP(w, req) |
| @@ -201,7 +201,7 @@ func TestVerifyPageDoesNotDistinguishTokens(t *testing.T) { |
| get := func(token string) *httptest.ResponseRecorder { |
| req := httptest.NewRequest(http.MethodGet, linkPath+"?token="+url.QueryEscape(token), nil) |
| - req.Host = credentialHost |
| + req.Host = app.credentialHost |
| w := httptest.NewRecorder() |
| app.Router().ServeHTTP(w, req) |
| return w |
| @@ -336,7 +336,7 @@ func TestSigninPostRequiresOriginEvidence(t *testing.T) { |
| for _, path := range []string{"/signin", linkPath} { |
| form := url.Values{"address": {"person@example.invalid"}} |
| req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(form.Encode())) |
| - req.Host = credentialHost |
| + req.Host = app.credentialHost |
| req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| w := httptest.NewRecorder() |
| app.Router().ServeHTTP(w, req) |
| @@ -403,7 +403,7 @@ func TestCallbackWithNoPendingCookieMintsNothing(t *testing.T) { |
| "", |
| } { |
| req := httptest.NewRequest(http.MethodGet, callbackPath+q, nil) |
| - req.Host = credentialHost |
| + req.Host = app.credentialHost |
| w := httptest.NewRecorder() |
| app.Router().ServeHTTP(w, req) |
| @@ -439,7 +439,7 @@ func TestForgedPendingBlobIsRefused(t *testing.T) { |
| app := newTestApp(t) |
| req := httptest.NewRequest(http.MethodGet, callbackPath+"?code=x&state=s", nil) |
| - req.Host = credentialHost |
| + req.Host = app.credentialHost |
| req.AddCookie(&http.Cookie{ |
| Name: pendingCookie, |
| // Well-formed shape — payload.mac — with a MAC that is not one. |
| @@ -470,9 +470,9 @@ func TestSigninIsRateLimitedPerIPNotGlobally(t *testing.T) { |
| post := func(ip, addr string) int { |
| form := url.Values{"address": {addr}} |
| req := httptest.NewRequest(http.MethodPost, "/signin", strings.NewReader(form.Encode())) |
| - req.Host = credentialHost |
| + req.Host = app.credentialHost |
| req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| - req.Header.Set("Origin", Origin) |
| + req.Header.Set("Origin", app.origins.Credential) |
| req.Header.Set("X-Forwarded-For", ip) |
| w := httptest.NewRecorder() |
| app.Router().ServeHTTP(w, req) |
| @@ -509,9 +509,9 @@ func TestSigninIsRateLimitedPerAddress(t *testing.T) { |
| for i := range 12 { |
| form := url.Values{"address": {"target@example.invalid"}} |
| req := httptest.NewRequest(http.MethodPost, "/signin", strings.NewReader(form.Encode())) |
| - req.Host = credentialHost |
| + req.Host = app.credentialHost |
| req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| - req.Header.Set("Origin", Origin) |
| + req.Header.Set("Origin", app.origins.Credential) |
| req.Header.Set("X-Forwarded-For", fmt.Sprintf("198.51.100.%d", i+1)) |
| w := httptest.NewRecorder() |
| app.Router().ServeHTTP(w, req) |
| @@ -538,7 +538,7 @@ func TestVerifyPageWritesNothing(t *testing.T) { |
| before := dumpDatabase(t, app) |
| for _, tok := range []string{token, "not-a-real-token", ""} { |
| req := httptest.NewRequest(http.MethodGet, linkPath+"?token="+url.QueryEscape(tok), nil) |
| - req.Host = credentialHost |
| + req.Host = app.credentialHost |
| app.Router().ServeHTTP(httptest.NewRecorder(), req) |
| } |
| if after := dumpDatabase(t, app); after != before { |
diff --git a/internal/home/team_page_test.go b/internal/home/team_page_test.go| index a0ad046..a33565a 100644 |
| --- a/internal/home/team_page_test.go |
| +++ b/internal/home/team_page_test.go |
| @@ -75,7 +75,7 @@ func (f *teamFixture) exchange(t *testing.T, cred *http.Cookie, start, returnTo |
| authorize := exchangeRequest(f.credential.App, "GET", begin.Header().Get("Location"), "", nil, cred) |
| intent := namedCookie(t, authorize, assertionIntentCookie) |
| if strings.Contains(begin.Header().Get("Location"), "max_age=300") { |
| - cred = signInFully(t, f.credential, f.paulAddress) |
| + cred = reauthenticateCredential(t, f.credential, cred) |
| } |
| resume := exchangeRequest(f.credential.App, "POST", Origin+"/authorize/resume", Origin, nil, intent, cred) |
| m := regexp.MustCompile(`name="assertion" value="([^"]+)"`).FindStringSubmatch(resume.Body.String()) |
diff --git a/internal/home/testapp_test.go b/internal/home/testapp_test.go| index 8cee5d5..7398c80 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, migrate.Merge(BootSchema, identitySchema)); err != nil { |
| + if _, err := migrate.Apply(context.Background(), d, (Runtime{}).ServingSchema()); err != nil { |
| t.Fatalf("migrate.Apply: %v", err) |
| } |