package home import ( "bytes" "encoding/base64" "encoding/json" "fmt" "log/slog" "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) } 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 (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 { 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) } }) } } 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.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("another credential can exhaust direct sign-in") } 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) } } }