| 1 | #!/usr/bin/env python3 |
| 2 | """Remove one ID guard at a time, run its regression, and restore the source.""" |
| 3 | import json |
| 4 | import os |
| 5 | from pathlib import Path |
| 6 | import subprocess |
| 7 | import sys |
| 8 | import time |
| 9 | |
| 10 | ROOT = Path(__file__).resolve().parent.parent |
| 11 | HOME = ROOT / "internal/home" |
| 12 | # Guard, file, exact source, replacement, test expression. |
| 13 | CASES = [ |
| 14 | ("continue gesture", "exchange.go", "if r.Method == http.MethodGet {", "if false && r.Method == http.MethodGet {", "TestIDContinueBeforeMinting"), |
| 15 | ("link new session", "exchange.go", "sameSession ||", "(sameSession && false) ||", "TestIDLinkAlwaysRequiresNewGesture"), |
| 16 | ("link transaction start", "exchange.go", "authTime.Unix() < intent.Started", "authTime.Unix() < 0", "TestIDLinkRejectsProofBeforeTransactionStart"), |
| 17 | ("passive Keymail issuance", "exchange.go", "|| keymailWithoutGesture(session)", "|| (false && keymailWithoutGesture(session))", "TestIDLinkRejectsPassiveMintedSession"), |
| 18 | ("live issuance session", "exchange.go", "session, _, err := a.idSession(tx, r, now.Unix())", "session, _ := sessions.Current(r)", "TestIDRevokedCachedSessionCannotMint"), |
| 19 | ("audience", "exchange.go", "Audience: target", "Audience: a.origins.Credential", "TestHomeDirectoryExchangeAndPrivacy"), |
| 20 | ("nonce", "exchange.go", "Nonce: intent.Nonce", "Nonce: id", "TestHomeDirectoryExchangeAndPrivacy"), |
| 21 | ("assertion lifetime", "exchange.go", "ExpiresAt: now.Unix() + 120", "ExpiresAt: now.Unix() + 121", "TestHomeDirectoryExchangeAndPrivacy"), |
| 22 | ("cookie ambiguity", "id_passkey.go", "count != 1 || len(value) > 4096", "count < 1 || len(value) > 4096", "TestIDChallengeBrowserCookiesAndExpiry/duplicate"), |
| 23 | ("clock rollback", "id_passkey.go", "err != nil || now < high", "err != nil || (now < high && false)", "TestIDChallengeBrowserCookiesAndExpiry/clock"), |
| 24 | ("future enrollment time", "id_passkey.go", "&& !at.After(now)", "&& (!at.After(now) || true)", "TestIDEnrollmentRejectsFutureAndPassiveAuthentication/future"), |
| 25 | ("passive enrollment", "id_passkey.go", "!keymailWithoutGesture(s) &&", "(!keymailWithoutGesture(s) || true) &&", "TestIDEnrollmentRejectsFutureAndPassiveAuthentication/passive"), |
| 26 | ("challenge capacity", "id_passkey.go", "n >= 10000", "n >= 100000", "TestIDChallengeBrowserCookiesAndExpiry/capacity"), |
| 27 | ("challenge lifetime", "id_passkey.go", "purpose, now+300", "purpose, now+600", "TestIDGatedChallengeGuards/ttl"), |
| 28 | ("challenge browser", "id_passkey.go", "WHERE challenge=? AND browser_hash=? AND", "WHERE challenge=? AND (? IS NOT NULL) AND", "TestIDGatedChallengeGuards/browser"), |
| 29 | ("challenge subject", "id_passkey.go", "AND subject=? AND purpose=?", "AND (? IS NOT NULL) AND purpose=?", "TestIDRegistrationChallengeSubjectAndLiveSession/subject"), |
| 30 | ("challenge purpose", "id_passkey.go", "AND purpose=? AND expires_at>? RETURNING", "AND (? IS NOT NULL) AND expires_at>? RETURNING", "TestIDGatedChallengeGuards/purpose"), |
| 31 | ("challenge expiry", "id_passkey.go", "AND expires_at>? RETURNING challenge", "AND (? IS NOT NULL) RETURNING challenge", "TestIDGatedChallengeGuards/expiry"), |
| 32 | ("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"), |
| 33 | ("strict ceremony JSON", "id_passkey.go", "strictjson.UnmarshalRead(http.MaxBytesReader(w, r.Body, 64<<10), &body, strictjson.RejectUnknownMembers(true))", "decodeLooseIDJSON(r, &body)", "TestIDCeremonyRejectsAmbiguousJSON"), |
| 34 | ("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"), |
| 35 | ("credential enrollment bound", "id_passkey.go", "count >= 100", "count >= 1000", "TestIDEnrollmentBound"), |
| 36 | ("credential owner", "id_passkey.go", '(subject != "" && owner != subject)', '(subject != "" && owner != subject && false)', "TestIDGateBindsCredentialOwner"), |
| 37 | ("discoverable admission", "id_passkey.go", " AND id IN (SELECT credential_id FROM home_id_discoverable)", " AND 1=1", "TestIDLegacyCredentialCannotSignInDirectly"), |
| 38 | ("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)"), |
| 39 | ("recovery entropy", "id_recovery.go", "rand.Read(raw)", "rand.Read(raw[:6])", "TestIDRecoveryEntropy"), |
| 40 | ("account attempt budget", "id_recovery.go", '{"account:" + subject, 5}', '{"account:" + subject, 500}', "TestIDRecoveryAttemptLimitSurvivesReconstruction"), |
| 41 | ("IP attempt budget", "id_recovery.go", 'blindIndex(a.secrets.Pepper, clientIP(r)), 20}', 'blindIndex(a.secrets.Pepper, clientIP(r)), 200}', "TestIDRecoveryIPLimitAcrossAccounts"), |
| 42 | ("attempt increment", "id_recovery.go", "failures=failures+1", "failures=failures+0", "TestIDRecoveryAttemptLimitSurvivesReconstruction"), |
| 43 | ("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"), |
| 44 | ("mailbox freshness", "id_recovery.go", "if mailboxAt <= 0 || mailboxAt > now || mailboxAt+300 <= now {", "if false && (mailboxAt <= 0 || mailboxAt > now || mailboxAt+300 <= now) {", "TestIDRecoveryMailboxTimeDefense"), |
| 45 | ("recovery code person", "id_recovery.go", "WHERE subject=? AND code_hash=? RETURNING subject", "WHERE (? IS NOT NULL) AND code_hash=? RETURNING subject", "TestIDRecoveryCodePersonBindingAndReplay"), |
| 46 | ("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"), |
| 47 | ("recovery proof expiry", "id_recovery.go", "AND subject=? AND expires_at>?", "AND subject=? AND (? IS NOT NULL)", "TestIDReplacementProofBinding/expired"), |
| 48 | ("recovery proof subject", "id_recovery.go", "AND subject=? AND expires_at>?", "AND (? IS NOT NULL) AND expires_at>?", "TestIDReplacementProofBinding/wrong-person"), |
| 49 | ("recovery proof capacity", "id_recovery.go", "proofCount >= 10000", "proofCount >= 100000", "TestIDRecoveryProofCapacity"), |
| 50 | ("mailbox memory capacity", "id_recovery.go", "len(m.entries) >= 1000", "len(m.entries) >= 1001", "TestIDMailboxMemoryBoundAndExpiry"), |
| 51 | ("mailbox memory expiry", "id_recovery.go", "!ok || p.expires <= time.Now().Unix()", "!ok || (false && p.expires <= time.Now().Unix())", "TestIDMailboxMemoryBoundAndExpiry"), |
| 52 | ("notice outcome", "id_passkey.go", "a.replacementResult(w, !a.sendReplacementNotice(r.Context(), binding))", "a.sendReplacementNotice(r.Context(), binding); a.replacementResult(w, false)", "TestIDNoticeFailureSurvivesRestartWithoutAddress"), |
| 53 | ("SMTP log privacy", "signin.go", 'a.logger.Error("signin begin failed")', 'a.logger.Error("signin begin failed", "err", err)', "TestIDSMTPFailureDoesNotLeak"), |
| 54 | ("limiter address blinding", "id_limiter.go", 'key = "addr:" + blindIndex(l.pepper, address)', 'key = "addr:" + address', "TestIDSigninLimiterUsesBlindedAddress"), |
| 55 | ("local signout", "directory.go", 'http.Redirect(w, r, "/signed-out", http.StatusSeeOther)', 'http.Redirect(w, r, a.origins.Credential+signoutPath, http.StatusTemporaryRedirect)', "TestIDLocalSignoutWithHangingIssuer"), |
| 56 | ("sealed link storage", "links.go", "hash, sealed, purpose, expires.UTC()", "hash, append(sealed[:0], []byte(address)...), purpose, expires.UTC()", "TestFullSigninLeavesNoReadableAddress"), |
| 57 | ] |
| 58 | CASES += [ |
| 59 | ("closed authorize fields","exchange.go","len(q) != wantFields", "(len(q) != wantFields && false)", "TestIDClosedAuthorize"), |
| 60 | ("authorize consumer uniqueness","exchange.go", 'len(q["consumer"]) != 1', '(len(q["consumer"]) != 1 && false)', "TestIDClosedAuthorize"), |
| 61 | ("authorize nonce uniqueness","exchange.go", 'len(q["nonce"]) != 1', '(len(q["nonce"]) != 1 && false)', "TestIDClosedAuthorize"), |
| 62 | ("CSRF for sensitive posts","app.go", "csrf.Protect(a.origins.Credential)", 'csrf.Protect("https://evil.invalid")', "TestIDAllSensitivePostsRequireOrigin"), |
| 63 | ("recovery subject defenses together", "id_recovery.go", "AND subject=? AND expires_at>?", "AND (? IS NOT NULL) AND expires_at>?", "TestIDReplacementProofBinding/wrong-person"), |
| 64 | ] |
| 65 | CASES += [ |
| 66 | ("registered authorize consumer","exchange.go", 'a.consumers()[q.Get("consumer")] == ""', '(a.consumers()[q.Get("consumer")] == "" && false)', "TestIDClosedAuthorize"), |
| 67 | ("authorize nonce format","exchange.go", '!handoff.ValidNonce(q.Get("nonce"))', '(!handoff.ValidNonce(q.Get("nonce")) && false)', "TestIDClosedAuthorize"), |
| 68 | ("authorize max age","exchange.go", 'len(values) != 1 || values[0] != "300"', '(len(values) != 1 || values[0] != "300") && false', "TestIDClosedAuthorize"), |
| 69 | ("replacement rollback","id_passkey.go", 'defer tx.Rollback()\n\t\tsubject, binding, err :=', 'defer tx.Commit()\n\t\tsubject, binding, err :=', "TestIDReplacementRollback"), |
| 70 | ("email authentication time","signin.go", 'sess.AuthTime = id.At', 'sess.AuthTime = time.Time{}', "TestIDEmailMintPreservesVerificationTime"), |
| 71 | ("codes after enrollment","passkey.go", 'if enrolled == 0 {', 'if enrolled == 0 && false {', "TestIDCodesRequireEnrolledPasskey"), |
| 72 | ("fresh intent start provenance","assertion_intent.go", 'intent.Started <= 0 || intent.Started > now.Unix()', '(intent.Started <= 0 && false) || intent.Started > now.Unix()', "TestIDFreshIntentRequiresStartTime"), |
| 73 | ] |
| 74 | CASES += [ |
| 75 | ("credential page cache privacy","render.go", 'w.Header().Set("Cache-Control", "no-store")', 'w.Header().Set("Cache-Control", "")', "TestIDCredentialPagesAreNoStore"), |
| 76 | ] |
| 77 | CASES += [ |
| 78 | ("link recovery exclusion", "exchange.go", '|| strings.Contains(session.Method, "recovery")', '|| (false && strings.Contains(session.Method, "recovery"))', "TestIDRecoveryCannotLink"), |
| 79 | ("enrollment recovery exclusion", "id_passkey.go", '|| strings.Contains(s.Method, "recovery")', '|| (false && strings.Contains(s.Method, "recovery"))', "TestIDRecoveryExclusions"), |
| 80 | ("codes recovery exclusion", "passkey.go", '|| strings.Contains(live.Method, "recovery")', '|| (false && strings.Contains(live.Method, "recovery"))', "TestIDRecoveryExclusions"), |
| 81 | ("replacement recovery suffix", "id_recovery.go", '!strings.HasSuffix(s.Method, "+recovery")', '(false && !strings.HasSuffix(s.Method, "+recovery"))', "TestIDReplacementRequiresRecoverySession/method"), |
| 82 | ("replacement session binding", "id_recovery.go", 'AND session_hash=? AND subject=?', 'AND (? IS NOT NULL) AND subject=?', "TestIDReplacementRequiresRecoverySession/session"), |
| 83 | ("limits before code consumption", "id_recovery.go", 'for _, b := range buckets {', 'for _, b := range buckets {', "TestIDLimitsBeforeValidCode"), |
| 84 | ("recovery RAM reservation", "id_recovery.go", '|| !a.mailboxes.put(hash, p)', '|| (false && !a.mailboxes.put(hash, p))', "TestIDRecoveryMailboxFailurePreservesCode/full"), |
| 85 | ("recovery RAM required", "id_recovery.go", '!ok || p.subject != subject ||', 'false ||', "TestIDRecoveryMailboxFailurePreservesCode/missing"), |
| 86 | ("full mailbox permits gate", "id_recovery.go", 'mailboxUnix = 0', 'return false, errIDProof', "TestIDFullMailboxAllowsGatedSignin"), |
| 87 | ("recovery signin notice", "id_recovery.go", 'a.sendRecoverySigninNotice(r.Context(), p.address)', '// notice omitted', "TestIDRecoverySigninNotice$"), |
| 88 | ("new codes after replacement", "id_passkey.go", 'if codes == 0 {', 'if codes == 0 && false {', "TestIDRecoveryReplacementRevokesEverything"), |
| 89 | ("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"), |
| 90 | ("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"), |
| 91 | ("direct challenge binding", "id_direct.go", 'proof.Challenge != hex.EncodeToString(challenge)', '(proof.Challenge != hex.EncodeToString(challenge) && false)', "TestIDDirectSealedChallenge/mismatch"), |
| 92 | ("direct expiry", "id_direct.go", 'proof.Expires <= now', '(proof.Expires <= now && false)', "TestIDDirectSealedChallenge/expired"), |
| 93 | ("direct maximum lifetime", "id_direct.go", 'proof.Expires > now+300', '(proof.Expires > now+300 && false)', "TestIDDirectSealedChallenge/future"), |
| 94 | ("direct receipt replay", "id_direct.go", 'INSERT INTO home_id_direct_used', 'INSERT OR REPLACE INTO home_id_direct_used', "TestIDDirectPasskey|TestIDDirectReceiptsBounded/restart"), |
| 95 | ("direct receipt cap", "id_direct.go", 'n >= 10000', 'n >= 100000', "TestIDDirectReceiptsBounded/capacity"), |
| 96 | ("direct receipt expiry", "id_direct.go", 'WHERE expires_at<=?', 'WHERE expires_at<? AND 0', "TestIDDirectReceiptsBounded/expiry"), |
| 97 | ("issuer signout form", "directory.go", '"Action": a.origins.Credential + signoutPath', '"Action": a.origins.Directory + signoutPath', "TestSignOutEndsTheCredentialSession"), |
| 98 | ("issuer signout auto step", "directory.go", 'finish := cookieValue(r, "__Host-oficina-finish-signout") == "1"', 'finish := false && cookieValue(r, "__Host-oficina-finish-signout") == "1"', "TestSignOutEndsTheCredentialSession"), |
| 99 | ("issuer signout no loop", "directory.go", 'idCookie(w, "__Host-oficina-finish-signout", "", -1)', 'idCookie(w, "__Host-oficina-finish-signout", "1", 300)', "TestSignOutEndsTheCredentialSession"), |
| 100 | ("issuer signout autosubmit", "static/assertion.js", 'form.requestSubmit()', 'form.checkValidity()', "TestIDBrowserSignoutBothOrigins"), |
| 101 | ] |
| 102 | CASES += [ |
| 103 | ("issuer site classification", "signout.go", 'site == other', 'site == other || true', "TestCredentialSignoutUsesIssuerSite"), |
| 104 | ("issuer scheme classification", "signout.go", 'consumer.Scheme != issuer.Scheme', '(false && consumer.Scheme != issuer.Scheme)', "TestCredentialSignoutUsesIssuerSite"), |
| 105 | ("recovery session marked", "id_recovery.go", 'Method: method + "+recovery"', 'Method: method', "TestIDRecoverySigninNotice$"), |
| 106 | ] |
| 107 | CASES += [ |
| 108 | ("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"), |
| 109 | ("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"), |
| 110 | ] |
| 111 | for table in ("sessions", "passkey_credentials", "passkey_recovery_codes", "passkey_pending", "passkey_challenges", "home_id_ceremonies", "home_id_recovery_proofs"): |
| 112 | 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")) |
| 113 | |
| 114 | results=[] |
| 115 | selected=set(sys.argv[1:]) |
| 116 | out=ROOT/"implementation/oficina-id-slice1-mutations.json" |
| 117 | previous=json.loads(out.read_text()) if selected and out.exists() else [] |
| 118 | for guard,file,old,new,test in CASES: |
| 119 | if selected and guard not in selected: |
| 120 | continue |
| 121 | path=HOME/file |
| 122 | original=path.read_text() |
| 123 | if original.count(old)!=1 and guard not in ("limits before code consumption", "replacement rollback"): |
| 124 | raise SystemExit(f"{guard}: expected one source match, got {original.count(old)}") |
| 125 | changed=original.replace(old,new) |
| 126 | if guard=="replacement rollback": |
| 127 | before,after=original.rsplit(old,1) |
| 128 | changed=before+new+after |
| 129 | if guard=="limits before code consumption": |
| 130 | start=original.index("\tvar got string\n") |
| 131 | end=original.index("\tif err == sql.ErrNoRows {",start) |
| 132 | deletion=original[start:end] |
| 133 | changed=original[:start]+original[end:] |
| 134 | point=changed.index("\tfor _, b := range buckets {") |
| 135 | changed=changed[:point]+deletion+changed[point:] |
| 136 | if guard=="recovery RAM required": |
| 137 | changed=changed.replace("p, ok := a.mailboxes.get(binding)", "p, _ := a.mailboxes.get(binding)") |
| 138 | if guard=="direct seal authentication": |
| 139 | # Model accepting a forged cookie by treating failed authentication as a |
| 140 | # matching current challenge. A raw 'ignore err' still fails JSON parsing. |
| 141 | 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') |
| 142 | if guard=="recovery subject defenses together": |
| 143 | changed=changed.replace("!ok || p.subject != subject", "!ok || (p.subject != subject && false)") |
| 144 | if guard=="strict ceremony JSON": |
| 145 | # Keep the strict import used while replacing its behavior for this mutant. |
| 146 | changed+='\nfunc decodeLooseIDJSON(r *http.Request, dst any) error { _ = strictjson.RejectUnknownMembers; return json.NewDecoder(r.Body).Decode(dst) }\n' |
| 147 | start=time.monotonic() |
| 148 | try: |
| 149 | path.write_text(changed) |
| 150 | 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) |
| 151 | output=proc.stdout |
| 152 | if proc.returncode==0: |
| 153 | status="survived" |
| 154 | elif "[build failed]" in output: |
| 155 | status="invalid" |
| 156 | elif "--- FAIL:" in output: |
| 157 | status="killed" |
| 158 | else: |
| 159 | status="error" |
| 160 | failures=[line.strip() for line in output.splitlines() if "--- FAIL:" in line] |
| 161 | except subprocess.TimeoutExpired: |
| 162 | status="timeout";failures=[] |
| 163 | finally: |
| 164 | path.write_text(original) |
| 165 | row={"guard":guard,"file":"internal/home/"+file,"test":test,"result":status,"failures":failures,"seconds":round(time.monotonic()-start,2)} |
| 166 | if status=="survived" and guard=="recovery proof subject": |
| 167 | row["explanation"]="Independent in-memory mailbox subject check still refuses. The paired mutation removes both checks and must fail the same regression." |
| 168 | results.append(row) |
| 169 | snapshot=[r for r in previous if r["guard"] not in {v["guard"] for v in results}]+results |
| 170 | (ROOT/"implementation/oficina-id-slice1-mutations.json").write_text(json.dumps(snapshot,indent=2)+"\n") |
| 171 | print(f"{status}: {guard}",flush=True) |
| 172 | if status in ("invalid","error"): |
| 173 | print(output[-1200:],flush=True) |
| 174 | out=ROOT/"implementation/oficina-id-slice1-mutations.json" |
| 175 | if selected and out.exists(): |
| 176 | results=[r for r in previous if r["guard"] not in selected]+results |
| 177 | out.write_text(json.dumps(results,indent=2)+"\n") |
| 178 | sys.exit(0 if all(r["result"]=="killed" or (r["guard"]=="recovery proof subject" and r["result"]=="survived") for r in results) else 1) |
| 179 | |