Use Garry Tan's exact Claude Code setup: 23 opinionated tools that serve as CEO, Designer, Eng Manager, Release Manager, Doc Engineer, and QA
TypeScript
The pre-push credential guard says to fetch first, instead of failing or blaming old history, when the remote branch moved (#4790) (#4794)
Garry Tan4394a02363d6
diff --git a/bin/gstack-redact-prepush b/bin/gstack-redact-prepushindex c988d2807..bc75fe746 100755--- a/bin/gstack-redact-prepush+++ b/bin/gstack-redact-prepush@@ -19,6 +19,9 @@* pushed). Special cases:* - remote sha all-zeroes → new branch: diff against merge-base with the* remote's default branch (fallback: scan all commits unique to local ref).+ * - remote sha not in this repo → the remote moved since the last fetch:+ * diff against merge-base with that branch's tracking ref, else as a new+ * branch (#4790). Never the whole tree while a fetched ref anchors it.* - local sha all-zeroes → branch delete: nothing to scan, skip.* - force-push → remote..local still gives the net new content.*@@ -84,6 +87,9 @@ function gitStrict(args: string[]): string {// status !== 0 covers BOTH a non-zero exit AND null (process killed by a// signal or maxBuffer overflow — null !== 0 is true).if (r.status !== 0) {+ if ((r.error as NodeJS.ErrnoException | undefined)?.code === "ENOBUFS") {+ throw new Error(`git ${args[0]} failed (status=killed/overflow): it printed more than 64 MiB, more than the guard reads in one pass (ENOBUFS, SPAWN_OUTPUT_INCOMPLETE)`);+ }throw new Error(`git ${args[0]} failed (status=${r.status ?? "killed/overflow"}${r.error ? `, ${r.error.message}` : ""}): ${(r.stderr ?? "").slice(0, 300)}`,);@@ -190,6 +196,27 @@ function unknownRemoteTipBase(localSha: string): string | null {return null;}+/**+ * Base for a ref whose remote tip is not in this repository (#4790). The tip+ * cannot be an ancestor of localSha, so the remote moved since the last fetch+ * (or the branch was never fetched here). What this machine last fetched of+ * that branch from the push remote anchors the range; without it, the+ * new-branch chain does. Scanning from the empty tree instead re-reported+ * content already on the remote as this push's, and on a large repository+ * overflowed the diff buffer and blocked every such push.+ *+ * Scoped like remotesExclusionArgs: a URL push has no tracking namespace and+ * falls through, so a secret only another remote has seen is still scanned.+ */+function missingRemoteTipBase(localSha: string, remoteRef: string): string | null {+ const target = pushTarget();+ const remote = target.kind === "remote" ? target.name : target.kind === "unknown" ? "origin" : null;+ const branch = remoteRef.startsWith("refs/heads/") ? remoteRef.slice("refs/heads/".length) : "";+ const tracking = remote && branch ? git(["rev-parse", "--verify", "--quiet", `refs/remotes/${remote}/${branch}^{commit}`]).trim() : "";+ const base = tracking ? git(["merge-base", localSha, tracking]).trim() : "";+ return base || unknownRemoteTipBase(localSha);+}+/*** The commits this push actually adds — reachable from localSha and from NO* remote-tracking ref.@@ -276,17 +303,26 @@ function addedLinesFromNewCommits(localSha: string, remoteSha: string): AddedFil*/interface AddedFile { file: string; text: string; lines: number[]; commit?: string; binary?: boolean }-/** Return the added lines for a ref update being pushed. */-function addedLinesFor(localSha: string, remoteSha: string): AddedFile[] {+/**+ * Return the added lines for a ref update being pushed. `unfetchedBase` is+ * missingRemoteTipBase's anchor when the remote tip is not in this repository.+ */+function addedLinesFor(localSha: string, remoteSha: string, unfetchedBase: string | null): AddedFile[] {// Preferred ONLY when this push carries catch-up commits: scanning them again// is the bug. Every other shape falls through to the range logic below.const fromNew = addedLinesFromNewCommits(localSha, remoteSha);if (fromNew !== null) return fromNew;let range: string;- if (ZERO.test(remoteSha) || !objectExists(remoteSha)) {- const base = ZERO.test(remoteSha) ? unknownRemoteTipBase(localSha) : null;+ if (ZERO.test(remoteSha)) {+ const base = unknownRemoteTipBase(localSha);range = base ? `${base}..${localSha}` : `${emptyTreeOid()}..${localSha}`;+ } else if (!objectExists(remoteSha)) {+ // The base stands in for the remote tip, so catch-up commits narrow as they+ // do for a known tip. What it leaves out is checked separately (main).+ const fromBase = unfetchedBase ? addedLinesFromNewCommits(localSha, unfetchedBase) : null;+ if (fromBase !== null) return fromBase;+ range = unfetchedBase ? `${unfetchedBase}..${localSha}` : `${emptyTreeOid()}..${localSha}`;} else {// Existing branch (incl. force-push): net new content remote..local.range = `${remoteSha}..${localSha}`;@@ -308,11 +344,14 @@ function addedLinesFor(localSha: string, remoteSha: string): AddedFile[] {// --irreversible-delete: a deleted file's old lines are not printed. They// add nothing to scan, and with --text a deleted 70 MiB binary filled the// 64 MiB buffer and blocked the push. (GST-2261)- const diff = gitStrict([+ return addedLinesInRange(range);+}++function addedLinesInRange(range: string): AddedFile[] {+ return collectAddedLines(gitStrict(["diff", "--text", "--irreversible-delete", "--unified=0", "--no-color", "--no-ext-diff", "--no-textconv","--src-prefix=a/", "--dst-prefix=b/", range,- ]);- return collectAddedLines(diff);+ ]));}/**@@ -648,13 +687,18 @@ function main() {const historyRevs = new Set<string>();let trackingRemote: string | null = null;const pushedRefs: Array<{ localSha: string; remoteSha: string }> = [];+ // Pushes whose remote tip this repository has not fetched (#4790), and the+ // whole pushed tree of each, read for credentials the narrowed range left out.+ const unfetchedRefs: string[] = [];+ const olderParts: Array<{ part: AddedFile; allowlist: string[] }> = [];+ const olderUnread: string[] = [];for (const fields of refs) {// Fail CLOSED on a ref line we cannot parse (#2498): git hands pre-push// exactly "<local ref> <local sha> <remote ref> <remote sha>" — anything// else means we cannot tell WHAT is being pushed, and silently skipping// it would leave that ref unscanned.- const [, localSha, , remoteSha] = fields;+ const [, localSha, remoteRef, remoteSha] = fields;const shaShaped = (s: string | undefined) => !!s && /^[0-9a-f]{40,64}$/i.test(s);if (fields.length !== 4 || !shaShaped(localSha) || !shaShaped(remoteSha)) {process.stderr.write(@@ -667,17 +711,31 @@ function main() {}if (ZERO.test(localSha!)) continue; // branch delete → nothing pushedpushedRefs.push({ localSha: localSha!, remoteSha: remoteSha! });+ const tipMissing = !ZERO.test(remoteSha!) && !objectExists(remoteSha!);+ const unfetchedBase = tipMissing ? missingRemoteTipBase(localSha!, remoteRef!) : null;+ if (tipMissing) {+ process.stderr.write(+ `gstack-redact-prepush: ${remoteRef} on the remote is at ${remoteSha!.slice(0, 12)}, which this repository has not fetched; ` ++ `scanning ${unfetchedBase ? `the commits after ${unfetchedBase.slice(0, 12)} as this push's, and the rest of the pushed tree for credentials` : "all of its history"}. ` ++ "If git rejects the push, run `git fetch`, then rebase or merge and push again.\n",+ );+ }let added: AddedFile[];try {- added = addedLinesFor(localSha, remoteSha || "0");+ added = addedLinesFor(localSha, remoteSha || "0", unfetchedBase);} catch (err) {// Fail CLOSED (#1946): if we can't compute the pushed diff we can't// scan it, and unscanned-but-allowed is the failure mode this hook// exists to prevent.+ const reason = err instanceof Error ? err.message.split("\n")[0] : String(err);process.stderr.write("\n⛔ gstack-redact-prepush BLOCKED the push — could not compute the pushed diff, " +"so it cannot be scanned for credentials.\n" +- ` (${err instanceof Error ? err.message.split("\n")[0] : String(err)})\n` ++ ` (${reason})\n` ++ (tipMissing+ ? `The remote's ${remoteRef} is at a commit this repository has not fetched, so the guard could not tell what this push adds. ` ++ "Run `git fetch`, rebase or merge, then push again.\n"+ : /ENOBUFS/.test(reason) ? "The pushed range is too large to scan in one pass; push fewer commits at a time.\n" : "") +"Bypass if you're sure: GSTACK_REDACT_PREPUSH=skip git push (or git push --no-verify)\n",);process.exit(1);@@ -685,6 +743,20 @@ function main() {const allowlist = committedAllowlist(localSha);for (const entry of allowlist) allowEntries.add(entry);for (const part of added) if (part.text.trim()) parts.push({ part, allowlist });+ if (unfetchedBase) {+ // The narrowed range trusts this clone's fetched copy of the remote, which+ // can be stale: a remote rewritten to drop a commit that copy still holds+ // would get it back from a forced push. So the whole pushed tree is still+ // read, as before #4790, within the diff bound; a credential it holds, or+ // a tree too large to read, blocks with a fetch-first message rather than+ // as this push's own credential.+ unfetchedRefs.push(remoteRef!);+ try {+ for (const part of addedLinesInRange(`${emptyTreeOid()}..${localSha}`)) if (part.text.trim()) olderParts.push({ part, allowlist });+ } catch (err) {+ olderUnread.push(` ${remoteRef}: ${err instanceof Error ? err.message.split("\n")[0] : String(err)}\n`);+ }+ }historyRevs.add(localSha);if (!ZERO.test(remoteSha) && objectExists(remoteSha)) historyRevs.add(remoteSha);else {@@ -712,8 +784,12 @@ function main() {const reported = new Map<number[], Set<string>>();// A name git quotes or tab-ends was read as no file before GST-3528, so it is// also scanned without its path: the decoded name never reports less than that.- for (const { part, allowlist } of parts) for (const pathless of part.file && gitMangledPath(part.file) && !/\.(?:dart|pyi?)$/i.test(part.file) ? [false, true] : [false]) {- const opts = { repoVisibility: "private" as const, ...emails.options, ...(part.file && !pathless && !/\.(?:dart|pyi?)$/i.test(part.file) ? { sourcePath: part.file } : {}) };+ const pathlessModes = (part: AddedFile) => part.file && gitMangledPath(part.file) && !/\.(?:dart|pyi?)$/i.test(part.file) ? [false, true] : [false];+ const scanOpts = (part: AddedFile, pathless: boolean) => ({ repoVisibility: "private" as const, ...emails.options, ...(part.file && !pathless && !/\.(?:dart|pyi?)$/i.test(part.file) ? { sourcePath: part.file } : {}) });+ const highKey = (f: Finding, part: AddedFile, lineTexts: string[]) => `${f.id}\0${part.file}\0${lineTexts[f.line - 1]}`;+ const newHighKeys = new Set<string>();+ for (const { part, allowlist } of parts) for (const pathless of pathlessModes(part)) {+ const opts = scanOpts(part, pathless);const findings = scanAddedLines(part.text, opts);const kept = allowlist.length? new Set(scanAddedLines(part.text, { ...opts, allowlist }).map(findingKey))@@ -730,14 +806,34 @@ function main() {const key = `${findingKey(f)}:${lineTexts[f.line - 1]}`;if (seen.has(key)) continue;seen.add(key);- if (f.severity === "HIGH") allHigh.push(f);- else if (f.severity === "MEDIUM") {+ if (f.severity === "HIGH") {+ allHigh.push(f);+ newHighKeys.add(highKey(f, part, lineTexts));+ } else if (f.severity === "MEDIUM") {mediums.push(mediumLine(f, part));if (f.id === "pii.email") emailMedium = true;}}}+ // HIGH findings in the pushed tree of a ref whose remote tip is unfetched,+ // other than the ones already reported as this push's. Never the value.+ const olderHigh: string[] = [];+ const olderSeen = new Set<string>();+ for (const { part, allowlist } of olderParts) for (const pathless of pathlessModes(part)) {+ const opts = scanOpts(part, pathless);+ const kept = allowlist.length ? new Set(scanAddedLines(part.text, { ...opts, allowlist }).map(findingKey)) : null;+ const lineTexts = part.text.split("\n");+ for (const f of scanAddedLines(part.text, opts)) {+ if (f.severity !== "HIGH" || (part.binary && f.category !== "secret") || (kept && !kept.has(findingKey(f)))) continue;+ const key = highKey(f, part, lineTexts);+ if (newHighKeys.has(key) || olderSeen.has(key)) continue;+ olderSeen.add(key);+ olderHigh.push(` HIGH ${f.id} ${findingWhere(f, part)}\n`);+ }+ }+ const unfetchedBlocks = olderHigh.length > 0 || olderUnread.length > 0;+if (allowEntries.size > 0) {process.stderr.write(`gstack-redact-prepush: ${ALLOWLIST_PATH} (${allowEntries.size} entr${allowEntries.size === 1 ? "y" : "ies"}) ` +@@ -765,6 +861,22 @@ function main() {if (sealedText) process.stderr.write(sealedText);const sealedBlocks = !!sealed && (sealed.status === "refused" || sealed.status === "error");+ if (unfetchedBlocks) {+ process.stderr.write(+ `\n⛔ gstack-redact-prepush BLOCKED the push — the remote tip of ${unfetchedRefs.join(", ")} is not in this repository, ` ++ "so the guard can't tell whether the older history this push carries is already on the remote.\n\n",+ );+ for (const line of olderHigh) process.stderr.write(line);+ if (olderUnread.length) process.stderr.write(" The pushed tree could not be read within the guard's bound:\n");+ for (const line of olderUnread) process.stderr.write(line);+ process.stderr.write(+ "\nRun `git fetch`, then rebase or merge and push again. With the remote tip fetched, the guard scans only your new commits.\n",+ );+ if (allHigh.length === 0) {+ process.stderr.write("This is a guardrail: `git push --no-verify` or `GSTACK_REDACT_PREPUSH=skip git push` bypass it.\n");+ }+ }+if (allHigh.length > 0) {// A scan that could not RUN is not a scan that FOUND something. Reporting// "credential(s) in the pushed diff — rotate the credential" for an@@ -812,7 +924,7 @@ function main() {process.exit(1);}- process.exit(sealedBlocks ? 1 : 0);+ process.exit(sealedBlocks || unfetchedBlocks ? 1 : 0);}main();diff --git a/changelog.d/prepush-guard-scans-only-pushed-commits.md b/changelog.d/prepush-guard-scans-only-pushed-commits.mdnew file mode 100644index 000000000..c00fcdd88--- /dev/null+++ b/changelog.d/prepush-guard-scans-only-pushed-commits.md@@ -0,0 +1,4 @@+---+important: blocker+---+**When the branch you push moved on the remote since your last fetch, the pre-push credential guard now tells you to run `git fetch` instead of failing with ENOBUFS or telling you to rotate a credential that is already on the remote.** It scans the commits you are adding as your own, so a secret in them still blocks as before. The rest of what you push is still checked, because your clone's copy of the remote may be out of date; a credential there, or history too large to read, blocks with a message to fetch first, and after the fetch only your new commits are scanned. Reported by @ajrmooreuk in #4790.diff --git a/test/redact-prepush-missing-remote-tip.test.ts b/test/redact-prepush-missing-remote-tip.test.tsnew file mode 100644index 000000000..7ac4234d3--- /dev/null+++ b/test/redact-prepush-missing-remote-tip.test.ts@@ -0,0 +1,309 @@+/**+ * gstack-redact-prepush when the remote tip of the pushed branch is not in+ * this repository (#4790): the remote moved since the last fetch, or the+ * branch exists on the remote but was never fetched here.+ *+ * Before the fix the hook scanned the whole tree of the pushed commit from the+ * empty tree. On a large repository that overflowed the 64 MiB diff buffer and+ * blocked the push with ENOBUFS; on any repository it reported credentials+ * already on the remote as if this push added them.+ *+ * The hook works out what is being pushed from what this machine last fetched+ * of the push remote: the merge-base with that branch's tracking ref, else with+ * the remote's default branch, else the commits no tracking ref of the push+ * remote reaches. A credential there is this push's own. That fetched copy can+ * be stale (the remote may have dropped a commit it still holds), so the rest+ * of the pushed tree is still read as before: a credential in it, or a tree+ * too large to read, blocks with "run git fetch", never "rotate". After a+ * fetch the remote tip is known and only the new commits are scanned.+ *+ * Every test runs the real hook against real repositories on disk.+ */+import { afterEach, describe, expect, test } from "bun:test";+import { spawnSync } from "node:child_process";+import * as fs from "node:fs";+import * as os from "node:os";+import * as path from "node:path";+import { gitEnv } from "./helpers/git-env";++const PREPUSH = path.resolve(import.meta.dir, "..", "bin", "gstack-redact-prepush");+const KEY_ON_REMOTE = ["AKIA", "1234567890ABCDEF"].join("");+const KEY_PUSHED = ["AKIA", "FEDCBA0987654321"].join("");+const MISSING_TIP = "1".repeat(40);+const roots: string[] = [];++afterEach(() => {+ for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true });+});++function git(cwd: string, ...args: string[]): string {+ const r = spawnSync("git", args, { cwd, encoding: "utf8", timeout: 60_000, env: gitEnv(), maxBuffer: 16 * 1024 * 1024 });+ if (r.status !== 0) throw new Error(`git ${args.join(" ")} failed: ${r.stderr}`);+ return r.stdout.trim();+}++function tempRoot(): string {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "prepush-missing-tip-"));+ roots.push(root);+ return root;+}++function newRepo(dir: string): string {+ fs.mkdirSync(dir, { recursive: true });+ git(dir, "init", "-q", "-b", "main");+ git(dir, "config", "user.name", "Fixture");+ git(dir, "config", "user.email", "[email protected]");+ return dir;+}++function commit(repo: string, file: string, body: string | Buffer, message: string): string {+ fs.mkdirSync(path.dirname(path.join(repo, file)), { recursive: true });+ fs.writeFileSync(path.join(repo, file), body);+ git(repo, "add", file);+ git(repo, "commit", "-qm", message);+ return git(repo, "rev-parse", "HEAD");+}++/** Run the hook as git does: argv is the push remote's name and URL, stdin the ref lines. */+function hook(repo: string, remote: string, url: string, line: string): { code: number | null; stderr: string } {+ const r = spawnSync("bun", [PREPUSH, remote, url], {+ cwd: repo, input: line, encoding: "utf8", timeout: 120_000, env: gitEnv(),+ });+ return { code: r.status, stderr: r.stderr ?? "" };+}++/**+ * The issue's repro: clone a lands a token fixture on main, clone b lands an+ * unrelated commit, and clone a, which never fetched b's commit, pushes its+ * own change. The remote tip is b's commit, which a does not have.+ */+function staleClone(): { root: string; remote: string; a: string; remoteTip: string } {+ const root = tempRoot();+ const remote = path.join(root, "remote.git");+ git(root, "init", "--bare", "-q", "-b", "main", remote);+ const a = newRepo(path.join(root, "a"));+ git(a, "remote", "add", "origin", remote);+ commit(a, "README.md", "base\n", "root");+ commit(a, "fixture.env", `TOKEN=${KEY_ON_REMOTE}\n`, "fixture already on main");+ git(a, "push", "-q", "origin", "main");+ const b = path.join(root, "b");+ git(root, "clone", "-q", remote, b);+ git(b, "config", "user.name", "Other");+ git(b, "config", "user.email", "[email protected]");+ const remoteTip = commit(b, "other.txt", "other\n", "someone else lands on main");+ git(b, "push", "-q", "origin", "main");+ return { root, remote, a, remoteTip };+}++const FETCH_FIRST = "is not in this repository, so the guard can't tell whether the older history";+const OWN_CREDENTIAL = "credential(s) in the pushed diff";++describe("remote tip missing: the remote moved since the last fetch", () => {+ test("content already on the remote is not called this push's credential; the push is told to fetch first", () => {+ const { remote, a, remoteTip } = staleClone();+ const head = commit(a, "mine.txt", "mine\n", "my change");+ expect(spawnSync("git", ["cat-file", "-e", remoteTip], { cwd: a, env: gitEnv(), timeout: 30_000 }).status).not.toBe(0);+ const r = hook(a, "origin", remote, `refs/heads/main ${head} refs/heads/main ${remoteTip}\n`);+ expect(r.code).toBe(1);+ expect(r.stderr).toContain(FETCH_FIRST);+ expect(r.stderr).toContain("fixture.env:1");+ expect(r.stderr).toContain("run `git fetch`");+ expect(r.stderr).not.toContain(OWN_CREDENTIAL);+ expect(r.stderr).not.toContain("Rotate");+ });++ test("after git fetch and a rebase, only the new commits are scanned and the push passes", () => {+ const { remote, a, remoteTip } = staleClone();+ commit(a, "mine.txt", "mine\n", "my change");+ git(a, "fetch", "-q", "origin");+ git(a, "rebase", "-q", "origin/main");+ const head = git(a, "rev-parse", "HEAD");+ const r = hook(a, "origin", remote, `refs/heads/main ${head} refs/heads/main ${remoteTip}\n`);+ expect(r.code, r.stderr).toBe(0);+ expect(r.stderr).not.toContain("aws.access_key");+ });++ test("a secret in the pushed commit still blocks as this push's credential", () => {+ const { remote, a, remoteTip } = staleClone();+ const head = commit(a, "leak.txt", `key ${KEY_PUSHED}\n`, "my change with a key");+ const r = hook(a, "origin", remote, `refs/heads/main ${head} refs/heads/main ${remoteTip}\n`);+ expect(r.code).toBe(1);+ expect(r.stderr).toContain(OWN_CREDENTIAL);+ expect(r.stderr).toContain("aws.access_key");+ });++ test("a catch-up merge of the fetched default branch is not called this push's credential", () => {+ const { remote, a } = staleClone();+ git(a, "checkout", "-q", "-b", "feature", "HEAD~1");+ commit(a, "feature.txt", "feature v1\n", "feature work");+ git(a, "push", "-q", "origin", "feature");+ git(a, "fetch", "-q", "origin");+ git(a, "merge", "-q", "--no-edit", "origin/main");+ const head = commit(a, "feature.txt", "feature v2\n", "more feature work");+ const r = hook(a, "origin", remote, `refs/heads/feature ${head} refs/heads/feature ${MISSING_TIP}\n`);+ expect(r.stderr).not.toContain(OWN_CREDENTIAL);+ expect(r.stderr).toContain(FETCH_FIRST);+ expect(r.code).toBe(1);+ });++ test("a secret that only reached another remote is still scanned on its way to this one", () => {+ const { a } = staleClone();+ const publish = path.join(path.dirname(a), "publish.git");+ git(path.dirname(a), "init", "--bare", "-q", "-b", "main", publish);+ git(a, "remote", "add", "publish", publish);+ const head = commit(a, "mine.txt", "mine\n", "my change");+ const r = hook(a, "publish", publish, `refs/heads/main ${head} refs/heads/main ${MISSING_TIP}\n`);+ expect(r.code).toBe(1);+ expect(r.stderr).toContain("aws.access_key");+ });++ test("a push by URL has no fetched copy to anchor on, so everything is scanned", () => {+ const { remote, a, remoteTip } = staleClone();+ const head = commit(a, "mine.txt", "mine\n", "my change");+ const r = hook(a, remote, remote, `refs/heads/main ${head} refs/heads/main ${remoteTip}\n`);+ expect(r.code).toBe(1);+ expect(r.stderr).toContain("aws.access_key");+ });+});++/**+ * Clone a pushed feature commit S; clone b rewrote feature without S and+ * force-pushed. Clone a never fetched, so its tracking ref still holds S, and+ * a forced push of a's branch would put S back on the remote.+ */+function scrubbedRemote(sBody: string): { remote: string; a: string; remoteTip: string } {+ const root = tempRoot();+ const remote = path.join(root, "remote.git");+ git(root, "init", "--bare", "-q", "-b", "main", remote);+ const a = newRepo(path.join(root, "a"));+ git(a, "remote", "add", "origin", remote);+ commit(a, "README.md", "base\n", "root");+ git(a, "push", "-q", "origin", "main");+ git(a, "checkout", "-q", "-b", "feature");+ commit(a, "settings.txt", sBody, "commit S");+ git(a, "push", "-q", "origin", "feature");+ const b = path.join(root, "b");+ git(root, "clone", "-q", "-b", "feature", remote, b);+ git(b, "config", "user.name", "Other");+ git(b, "config", "user.email", "[email protected]");+ git(b, "reset", "-q", "--hard", "HEAD~1");+ const remoteTip = commit(b, "other.txt", "other\n", "commit C, without S");+ git(b, "push", "-q", "--force", "origin", "feature");+ return { remote, a, remoteTip };+}++describe("a stale tracking ref after the remote was rewritten", () => {+ test("a scrubbed commit restored by a forced push is still scanned and blocks", () => {+ const { remote, a, remoteTip } = scrubbedRemote(`key ${KEY_ON_REMOTE}\n`);+ const head = commit(a, "mine.txt", "mine\n", "commit H on top of S");+ expect(spawnSync("git", ["cat-file", "-e", remoteTip], { cwd: a, env: gitEnv(), timeout: 30_000 }).status).not.toBe(0);+ const r = hook(a, "origin", remote, `refs/heads/feature ${head} refs/heads/feature ${remoteTip}\n`);+ expect(r.code).toBe(1);+ expect(r.stderr).toContain(FETCH_FIRST);+ expect(r.stderr).toContain("settings.txt:1");+ expect(r.stderr).not.toContain("Rotate");+ });++ test("a clean forced update over the same rewrite still passes", () => {+ const { remote, a, remoteTip } = scrubbedRemote("clean setting\n");+ const head = commit(a, "mine.txt", "mine\n", "commit H on top of S");+ const r = hook(a, "origin", remote, `refs/heads/feature ${head} refs/heads/feature ${remoteTip}\n`);+ expect(r.code, r.stderr).toBe(0);+ expect(r.stderr).toContain("has not fetched");+ });+});++describe("a new branch", () => {+ test("a branch the remote lacks (zero tip) scans only its own commits", () => {+ const { remote, a } = staleClone();+ git(a, "checkout", "-q", "-b", "topic");+ const head = commit(a, "topic.txt", "topic\n", "topic work");+ const r = hook(a, "origin", remote, `refs/heads/topic ${head} refs/heads/topic ${"0".repeat(40)}\n`);+ expect(r.stderr).not.toContain("aws.access_key");+ expect(r.code, r.stderr).toBe(0);+ });++ test("a clean branch on the remote this clone never fetched passes", () => {+ const root = tempRoot();+ const repo = newRepo(path.join(root, "repo"));+ const url = path.join(root, "remote.git");+ git(repo, "remote", "add", "origin", url);+ commit(repo, "README.md", "base\n", "root");+ git(repo, "update-ref", "refs/remotes/origin/main", "HEAD");+ git(repo, "checkout", "-q", "-b", "topic");+ const head = commit(repo, "topic.txt", "topic\n", "topic work");+ const r = hook(repo, "origin", url, `refs/heads/topic ${head} refs/heads/topic ${MISSING_TIP}\n`);+ expect(r.code, r.stderr).toBe(0);+ expect(r.stderr).toContain("the commits after");+ });++ test("a new branch still blocks on its own secret", () => {+ const { remote, a } = staleClone();+ git(a, "checkout", "-q", "-b", "topic");+ const head = commit(a, "topic.txt", `key ${KEY_PUSHED}\n`, "topic with a key");+ const r = hook(a, "origin", remote, `refs/heads/topic ${head} refs/heads/topic ${MISSING_TIP}\n`);+ expect(r.code).toBe(1);+ expect(r.stderr).toContain(OWN_CREDENTIAL);+ expect(r.stderr).toContain("aws.access_key");+ });+});++/** About 70 MB of old history: more diff than the hook's 64 MiB buffer holds. */+function hugeHistory(repo: string): void {+ const line = "x".repeat(99) + "\n";+ commit(repo, "big/history.txt", Buffer.from(line.repeat(700_000)), "huge old history");+}++describe("a huge history", () => {+ test("one secret in the newest commit is reported as this push's credential; the unreadable tree says fetch first", () => {+ const root = tempRoot();+ const repo = newRepo(path.join(root, "repo"));+ const url = path.join(root, "remote.git");+ git(repo, "remote", "add", "origin", url);+ hugeHistory(repo);+ git(repo, "update-ref", "refs/remotes/origin/main", "HEAD");+ const fetched = git(repo, "rev-parse", "HEAD");+ const clean = commit(repo, "clean.txt", "clean\n", "clean change");+ const unfetched = hook(repo, "origin", url, `refs/heads/main ${clean} refs/heads/main ${MISSING_TIP}\n`);+ expect(unfetched.code).toBe(1);+ expect(unfetched.stderr).toContain("could not be read within the guard's bound");+ expect(unfetched.stderr).toContain("run `git fetch`");+ expect(unfetched.stderr).not.toContain("could not compute the pushed diff");+ const afterFetch = hook(repo, "origin", url, `refs/heads/main ${clean} refs/heads/main ${fetched}\n`);+ expect(afterFetch.code, afterFetch.stderr).toBe(0);+ const head = commit(repo, "leak.txt", `key ${KEY_PUSHED}\n`, "newest commit with a key");+ const r = hook(repo, "origin", url, `refs/heads/main ${head} refs/heads/main ${MISSING_TIP}\n`);+ expect(r.code).toBe(1);+ expect(r.stderr).not.toContain("could not compute the pushed diff");+ expect(r.stderr).toContain(OWN_CREDENTIAL);+ expect(r.stderr).toContain("aws.access_key");+ }, 180_000);+});++describe("a repository with no remote refs", () => {+ test("every commit is new as far as it can tell, so an old secret is still reported", () => {+ const root = tempRoot();+ const repo = newRepo(path.join(root, "repo"));+ const url = path.join(root, "remote.git");+ git(repo, "remote", "add", "origin", url);+ commit(repo, "config.txt", `key ${KEY_ON_REMOTE}\n`, "old");+ const head = commit(repo, "mine.txt", "mine\n", "new");+ const r = hook(repo, "origin", url, `refs/heads/main ${head} refs/heads/main ${MISSING_TIP}\n`);+ expect(r.code).toBe(1);+ expect(r.stderr).toContain("aws.access_key");+ });++ test("a range too large to read fails closed and says to fetch first", () => {+ const root = tempRoot();+ const repo = newRepo(path.join(root, "repo"));+ const url = path.join(root, "remote.git");+ git(repo, "remote", "add", "origin", url);+ hugeHistory(repo);+ const head = commit(repo, "mine.txt", "mine\n", "new");+ const r = hook(repo, "origin", url, `refs/heads/main ${head} refs/heads/main ${MISSING_TIP}\n`);+ expect(r.code).toBe(1);+ expect(r.stderr).toContain("BLOCKED");+ expect(r.stderr).toContain("more than 64 MiB");+ expect(r.stderr).toContain("git fetch");+ }, 180_000);+});