#!/usr/bin/env python3 """Remove one ID guard at a time, run its regression, and restore the source.""" import json import os from pathlib import Path import subprocess import sys import time ROOT = Path(__file__).resolve().parent.parent HOME = ROOT / "internal/home" # Guard, file, exact source, replacement, test expression. CASES = [ ("continue gesture", "exchange.go", "if r.Method == http.MethodGet {", "if false && r.Method == http.MethodGet {", "TestIDContinueBeforeMinting"), ("link new session", "exchange.go", "sameSession ||", "(sameSession && false) ||", "TestIDLinkAlwaysRequiresNewGesture"), ("link transaction start", "exchange.go", "authTime.Unix() < intent.Started", "authTime.Unix() < 0", "TestIDLinkRejectsProofBeforeTransactionStart"), ("passive Keymail issuance", "exchange.go", "|| keymailWithoutGesture(session)", "|| (false && keymailWithoutGesture(session))", "TestIDLinkRejectsPassiveMintedSession"), ("live issuance session", "exchange.go", "session, _, err := a.idSession(tx, r, now.Unix())", "session, _ := sessions.Current(r)", "TestIDRevokedCachedSessionCannotMint"), ("audience", "exchange.go", "Audience: target", "Audience: a.origins.Credential", "TestHomeDirectoryExchangeAndPrivacy"), ("nonce", "exchange.go", "Nonce: intent.Nonce", "Nonce: id", "TestHomeDirectoryExchangeAndPrivacy"), ("assertion lifetime", "exchange.go", "ExpiresAt: now.Unix() + 120", "ExpiresAt: now.Unix() + 121", "TestHomeDirectoryExchangeAndPrivacy"), ("cookie ambiguity", "id_passkey.go", "count != 1 || len(value) > 4096", "count < 1 || len(value) > 4096", "TestIDChallengeBrowserCookiesAndExpiry/duplicate"), ("clock rollback", "id_passkey.go", "err != nil || now < high", "err != nil || (now < high && false)", "TestIDChallengeBrowserCookiesAndExpiry/clock"), ("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", "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", "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"), ("credential owner", "id_passkey.go", '(subject != "" && owner != subject)', '(subject != "" && owner != subject && false)', "TestIDGateBindsCredentialOwner"), ("discoverable admission", "id_passkey.go", " AND id IN (SELECT credential_id FROM home_id_discoverable)", " AND 1=1", "TestIDLegacyCredentialCannotSignInDirectly"), ("WebAuthn verification", "id_passkey.go", "next, e := a.idWebAuthn().Verify(cred, challenge, cd, ad, sig)\n\t\tif e != nil {", "next, e := a.idWebAuthn().Verify(cred, challenge, cd, ad, sig)\n\t\te = nil\n\t\tif e != nil {", "TestIDPasskeyRejectsBadProofs/(origin|rp|uv|signature)"), ("recovery entropy", "id_recovery.go", "rand.Read(raw)", "rand.Read(raw[:6])", "TestIDRecoveryEntropy"), ("account attempt budget", "id_recovery.go", '{"account:" + subject, 5}', '{"account:" + subject, 500}', "TestIDRecoveryAttemptLimitSurvivesReconstruction"), ("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) {", "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"), ("recovery proof subject", "id_recovery.go", "AND subject=? AND expires_at>?", "AND (? IS NOT NULL) AND expires_at>?", "TestIDReplacementProofBinding/wrong-person"), ("recovery proof capacity", "id_recovery.go", "proofCount >= 10000", "proofCount >= 100000", "TestIDRecoveryProofCapacity"), ("mailbox memory capacity", "id_recovery.go", "len(m.entries) >= 1000", "len(m.entries) >= 1001", "TestIDMailboxMemoryBoundAndExpiry"), ("mailbox memory expiry", "id_recovery.go", "!ok || p.expires <= time.Now().Unix()", "!ok || (false && p.expires <= time.Now().Unix())", "TestIDMailboxMemoryBoundAndExpiry"), ("notice outcome", "id_passkey.go", "a.replacementResult(w, !a.sendReplacementNotice(r.Context(), binding))", "a.sendReplacementNotice(r.Context(), binding); a.replacementResult(w, false)", "TestIDNoticeFailureSurvivesRestartWithoutAddress"), ("SMTP log privacy", "signin.go", 'a.logger.Error("signin begin failed")', 'a.logger.Error("signin begin failed", "err", err)', "TestIDSMTPFailureDoesNotLeak"), ("limiter address blinding", "id_limiter.go", 'key = "addr:" + blindIndex(l.pepper, address)', 'key = "addr:" + address', "TestIDSigninLimiterUsesBlindedAddress"), ("local signout", "directory.go", 'http.Redirect(w, r, "/signed-out", http.StatusSeeOther)', 'http.Redirect(w, r, a.origins.Credential+signoutPath, http.StatusTemporaryRedirect)', "TestIDLocalSignoutWithHangingIssuer"), ("sealed link storage", "links.go", "hash, sealed, purpose, expires.UTC()", "hash, append(sealed[:0], []byte(address)...), purpose, expires.UTC()", "TestFullSigninLeavesNoReadableAddress"), ] CASES += [ ("closed authorize fields","exchange.go","len(q) != wantFields", "(len(q) != wantFields && false)", "TestIDClosedAuthorize"), ("authorize consumer uniqueness","exchange.go", 'len(q["consumer"]) != 1', '(len(q["consumer"]) != 1 && false)', "TestIDClosedAuthorize"), ("authorize nonce uniqueness","exchange.go", 'len(q["nonce"]) != 1', '(len(q["nonce"]) != 1 && false)', "TestIDClosedAuthorize"), ("CSRF for sensitive posts","app.go", "csrf.Protect(a.origins.Credential)", 'csrf.Protect("https://evil.invalid")', "TestIDAllSensitivePostsRequireOrigin"), ("recovery subject defenses together", "id_recovery.go", "AND subject=? AND expires_at>?", "AND (? IS NOT NULL) AND expires_at>?", "TestIDReplacementProofBinding/wrong-person"), ] CASES += [ ("registered authorize consumer","exchange.go", 'a.consumers()[q.Get("consumer")] == ""', '(a.consumers()[q.Get("consumer")] == "" && false)', "TestIDClosedAuthorize"), ("authorize nonce format","exchange.go", '!handoff.ValidNonce(q.Get("nonce"))', '(!handoff.ValidNonce(q.Get("nonce")) && false)', "TestIDClosedAuthorize"), ("authorize max age","exchange.go", 'len(values) != 1 || values[0] != "300"', '(len(values) != 1 || values[0] != "300") && false', "TestIDClosedAuthorize"), ("replacement rollback","id_passkey.go", 'defer tx.Rollback()\n\t\tsubject, binding, err :=', 'defer tx.Commit()\n\t\tsubject, binding, err :=', "TestIDReplacementRollback"), ("email authentication time","signin.go", 'sess.AuthTime = id.At', 'sess.AuthTime = time.Time{}', "TestIDEmailMintPreservesVerificationTime"), ("codes after enrollment","passkey.go", 'if enrolled == 0 {', 'if enrolled == 0 && false {', "TestIDCodesRequireEnrolledPasskey"), ("fresh intent start provenance","assertion_intent.go", 'intent.Started <= 0 || intent.Started > now.Unix()', '(intent.Started <= 0 && false) || intent.Started > now.Unix()', "TestIDFreshIntentRequiresStartTime"), ] 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