Skip to content

Commit 58b1df0

Browse files
garrytantianxchen
andcommitted
fix(redact): decide TS/JSX source syntax by file context, not by value shape
Review follow-up to the #3048 fix. The word-shape heuristic also exempted real secrets made of words (API_KEY=VelvetRiverOrbitSunset; in a .env). The scanner now takes the file path (ScanOptions.sourcePath): the pre-push hook scans the pushed diff per file with its +++ b/ path, and gstack-redact --from-file passes its path. Only in a TypeScript/JSX file is an unquoted value after ':' or a JSX brace of names treated as source; the same line in .env/YAML, or with no path, is scanned as a literal, and the jwt pattern still fires in .ts files. Co-authored-by: tianxchen <[email protected]>
1 parent 7c882bd commit 58b1df0

6 files changed

Lines changed: 112 additions & 48 deletions

File tree

‎bin/gstack-redact‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,8 @@ function buildOpts(): ScanOptions {
217217
selfEmail: arg("--self-email"),
218218
repoPublicEmails: readLines(arg("--repo-public-emails")),
219219
...(maxBytesOpt !== undefined ? { maxBytes: maxBytesOpt } : {}),
220+
// The scanned file's path lets patterns tell TS/JSX source syntax from a literal (#3048).
221+
...(arg("--from-file") ? { sourcePath: arg("--from-file") } : {}),
220222
};
221223
}
222224

‎bin/gstack-redact-prepush‎

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -248,7 +248,10 @@ function addedLinesFromNewCommits(localSha: string, remoteSha: string): string |
248248
}
249249

250250
/** Return the added-line text for a ref update being pushed. */
251-
function addedLinesFor(localSha: string, remoteSha: string): string {
251+
/** Added lines grouped by the file they were added to (`+++ b/` path; empty when unknown). */
252+
interface AddedFile { file: string; text: string }
253+
254+
function addedLinesFor(localSha: string, remoteSha: string): AddedFile[] {
252255
// Preferred ONLY when this push carries catch-up commits: scanning them again
253256
// is the bug. Every other shape falls through to the range logic below.
254257
const fromNew = addedLinesFromNewCommits(localSha, remoteSha);
@@ -284,8 +287,8 @@ function addedLinesFor(localSha: string, remoteSha: string): string {
284287
* Added-line text from a unified diff. Shared by both range strategies so the
285288
* hunk-aware header handling below cannot drift between them.
286289
*/
287-
function collectAddedLines(diff: string): string {
288-
const added: string[] = [];
290+
function collectAddedLines(diff: string): AddedFile[] {
291+
const added: AddedFile[] = [];
289292
// Hunk-aware header skip (#2498): `+++ ` is only a FILE HEADER outside a
290293
// hunk. Inside a hunk, an added content line whose text begins with "++"
291294
// renders as "+++<content>" — the old blanket startsWith("+++") skip
@@ -294,7 +297,8 @@ function collectAddedLines(diff: string): string {
294297
let file = "";
295298
let fileLines: string[] = [];
296299
const flush = () => {
297-
added.push(...releaseVersionExempt(file, fileLines));
300+
const lines = releaseVersionExempt(file, fileLines);
301+
if (lines.length) added.push({ file, text: lines.join("\n") });
298302
fileLines = [];
299303
};
300304
for (const line of diff.split("\n")) {
@@ -309,7 +313,7 @@ function collectAddedLines(diff: string): string {
309313
if (line.startsWith("+")) fileLines.push(line.slice(1));
310314
}
311315
flush();
312-
return added.join("\n");
316+
return added;
313317
}
314318

315319
const VERSION_FILE_CONTENT = /^\d+(?:\.\d+)+$/;
@@ -492,7 +496,7 @@ function main() {
492496
process.exit(1);
493497
}
494498
if (ZERO.test(localSha!)) continue; // branch delete → nothing pushed
495-
let added: string;
499+
let added: AddedFile[];
496500
try {
497501
added = addedLinesFor(localSha, remoteSha || "0");
498502
} catch (err) {
@@ -507,14 +511,17 @@ function main() {
507511
);
508512
process.exit(1);
509513
}
510-
if (!added.trim()) continue;
514+
if (!added.some((part) => part.text.trim())) continue;
511515
// Visibility doesn't change HIGH behavior; pass private so nothing is treated
512516
// as public-strict (HIGH blocks regardless either way).
513517
// Sliced (see scanAddedLines) so a large-but-legitimate diff is actually
514518
// scanned rather than blocked unscanned on the engine's size cap.
515-
for (const f of scanAddedLines(added, { repoVisibility: "private" })) {
516-
if (f.severity === "HIGH") allHigh.push(f);
517-
else if (f.severity === "MEDIUM") mediumCount++;
519+
// Scanned per file so a pattern can use the file's type (#3048).
520+
for (const part of added) {
521+
for (const f of scanAddedLines(part.text, { repoVisibility: "private", ...(part.file ? { sourcePath: part.file } : {}) })) {
522+
if (f.severity === "HIGH") allHigh.push(f);
523+
else if (f.severity === "MEDIUM") mediumCount++;
524+
}
518525
}
519526
}
520527

‎lib/redact-engine.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,12 @@ export interface ScanOptions {
6969
repoPublicEmails?: string[];
7070
/** Hard byte cap. Oversize input fails CLOSED. Default 1 MiB. */
7171
maxBytes?: number;
72+
/**
73+
* Path of the file the input came from, when known (the pre-push hook's
74+
* `+++ b/` path, `--from-file`). Lets a pattern tell source syntax from a
75+
* literal: in a TypeScript/JSX file `session: SessionState,` is a type.
76+
*/
77+
sourcePath?: string;
7278
}
7379

7480
export interface ScanResult {
@@ -399,7 +405,7 @@ function scanInternal(input: string, opts: ScanOptions, spans?: Map<Finding, Ori
399405
if (allow.has(span)) continue;
400406

401407
// Pattern-specific validators (Luhn, entropy, RFC1918, etc).
402-
if (pat.validate && !pat.validate(span, m)) continue;
408+
if (pat.validate && !pat.validate(span, m, opts)) continue;
403409

404410
// Proximity requirement.
405411
if (

‎lib/redact-patterns.ts‎

Lines changed: 20 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ export interface RedactPattern {
6565
* (crypto wallets), RFC1918-exclusion (public IPs), etc. Receives the
6666
* matched secret span (group 1 or match[0]) and the full match array.
6767
*/
68-
validate?: (span: string, match: RegExpExecArray) => boolean;
68+
validate?: (span: string, match: RegExpExecArray, opts?: { sourcePath?: string }) => boolean;
6969
/**
7070
* Proximity requirement: the pattern only counts if `nearRegex` also matches
7171
* within `nearWindow` chars of the match. Used for AWS secret keys (need
@@ -590,33 +590,30 @@ function isCallExpression(span: string, match: RegExpExecArray): boolean {
590590
}
591591

592592
/**
593-
* #3048: an unquoted value that names code is source syntax, not a literal:
594-
* a TypeScript parameter or property type (`session: SessionState,`) or a JSX
595-
* expression (`key={turn.requestId + turn.role}`, `apiKey={settings.apiKey}`).
596-
* A code name has no digits and reads as words: every camelCase/dotted part
597-
* is 2+ letters, they average 3+ letters, and each 3+ letter part has a vowel.
598-
* Random tokens fail that (mixed case gives 1-letter parts; most hold digits).
599-
* The bare form needs a code terminator (`,` `;` `)`) and no quote before it;
600-
* the JSX form needs its closing brace on the line and no quoted literal.
593+
* #3048: in a TypeScript/JSX file, an unquoted value after `:` is a type or an
594+
* expression, never a string literal (`session: SessionState,`), and a JSX
595+
* brace holding only names and property reads (`key={turn.requestId + turn.role}`)
596+
* is an expression. Decided by file context, not by how the value looks:
597+
* `API_KEY=VelvetRiverOrbitSunset;` in a .env or YAML file is still a literal.
598+
* Without a known TS/JSX path nothing is exempt.
601599
*/
602-
function readsAsCodeName(text: string): boolean {
603-
if (!/^[A-Za-z_$][A-Za-z_$]*(?:\.[A-Za-z_$][A-Za-z_$]*)*$/.test(text)) return false;
604-
const parts = text.split(/[._$]+|(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/).filter(Boolean);
605-
return parts.length > 0 && parts.every(p => p.length >= 2 && (p.length < 3 || /[aeiouy]/i.test(p))) &&
606-
parts.reduce((n, p) => n + p.length, 0) / parts.length >= 3;
607-
}
600+
const TS_SOURCE = /\.(?:[cm]?tsx?|jsx)$/i;
601+
const CODE_NAME_CHAIN = /^[A-Za-z_$][\w$]*(?:\??\.[A-Za-z_$][\w$]*)*(?:<[\w$.,\s<>[\]|]*>)?(?:\[\])*$/;
608602

609-
function isCodeReference(span: string, match: RegExpExecArray): boolean {
603+
function isSourceExpression(span: string, match: RegExpExecArray, sourcePath: string | undefined): boolean {
604+
if (!sourcePath || !TS_SOURCE.test(sourcePath)) return false;
610605
const { start } = spanBounds(match);
611-
if (match.input[start - 1] === '"' || match.input[start - 1] === "'") return false;
606+
const before = match.input[start - 1];
607+
if (before === '"' || before === "'" || before === "`") return false;
612608
if (span.startsWith("{")) {
613609
const line = match.input.slice(start + 1).split("\n", 1)[0];
614610
const close = line.indexOf("}");
615611
if (close < 0 || /["'`]/.test(line.slice(0, close))) return false;
616-
return line.slice(0, close).split("+").every(term => readsAsCodeName(term.trim()));
612+
return line.slice(0, close).split("+").every(term => CODE_NAME_CHAIN.test(term.trim()));
617613
}
618-
const m = span.match(/^(.+?)[,;)]+$/);
619-
return m !== null && readsAsCodeName(m[1]!);
614+
const separator = match[0].slice(0, match[0].length - span.length).trimEnd().slice(-1);
615+
if (separator !== ":") return false;
616+
return CODE_NAME_CHAIN.test(span.replace(/[,;)=|]+$/, ""));
620617
}
621618

622619
export const PATTERNS: RedactPattern[] = [
@@ -893,14 +890,14 @@ export const PATTERNS: RedactPattern[] = [
893890
// literal (`os.getenv("X", "<secret>")`). A literal appended to the read
894891
// itself (`process.env.X||"…"`) is not an exact read and still fires.
895892
// #2899: a function call assigned to the name is code, not a value (see
896-
// isCallExpression). #3048: so is a type or JSX expression (isCodeReference).
897-
validate: (span, match) =>
893+
// isCallExpression). #3048: so is a TS/JSX type or expression (isSourceExpression).
894+
validate: (span, match, opts) =>
898895
isCredentialShapedEnvName(match[0]) &&
899896
!isPlaceholderSpan(span) &&
900897
!/^\$\{?[A-Za-z_]/.test(span) &&
901898
!isBareEnvRead(span, match) &&
902899
!isCallExpression(span, match) &&
903-
!isCodeReference(span, match) &&
900+
!isSourceExpression(span, match, opts?.sourcePath) &&
904901
shannonEntropy(span) >= 3.0,
905902
},
906903
{

‎test/redact-engine.test.ts‎

Lines changed: 42 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -234,21 +234,30 @@ describe("MEDIUM demoted credential-shaped patterns (TENSION-1)", () => {
234234
expect(ids(`authToken: ${v}`)).toContain("env.kv"); // (iv) credential camel
235235
expect(ids(`clientSecret: ${v}`)).toContain("env.kv"); // (iv) credential camel
236236
});
237-
// #3048 — a TypeScript type or JSX expression names code, not a literal;
238-
// credential literals in the same shapes must still fire.
239-
test("env.kv skips TypeScript types and JSX expressions, keeps literals in those shapes (#3048)", () => {
237+
// #3048 — in a TS/JSX file an unquoted value after `:` is a type or an
238+
// expression, and a JSX brace of names is an expression. Decided by file
239+
// context: the same shapes in .env/YAML (or with no path) are literals.
240+
test("env.kv skips TS/JSX source syntax by file context, never by value shape (#3048)", () => {
241+
const kv = (text: string, sourcePath?: string) =>
242+
scan(text, { repoVisibility: "private", ...(sourcePath ? { sourcePath } : {}) }).findings.some((f) => f.id === "env.kv");
240243
const v = "8Fk2pQ9vXz4wL7mN3rT6yB1cD5eG0hJ";
241-
for (const code of [
242-
"export async function issueServerCoachItem(\n db: Pool,\n session: SessionState,\n item: IssuedCoachItem,\n): Promise<void> {}",
243-
"interface Props {\n session: SessionState;\n}",
244-
"key={turn.requestId + turn.role + index}",
245-
"apiKey={settings.apiKey}",
246-
]) expect({ code, ids: ids(code) }).toEqual({ code, ids: ids(code).filter(id => id !== "env.kv") });
247-
for (const literal of [
248-
`session: ${v},`, `session: "${v}",`, `key={${v}}`, `API_KEY={${v}}`,
249-
`key={settings.apiKey + "${v}"}`, `key="${v}"`, `api_key: ${v}`,
250-
"token: QxZpLmNvTrKbWdHgJcFs,", "token: QxZpLmNvTrKbWdHgJcFs",
251-
]) expect({ literal, kv: ids(literal).includes("env.kv") }).toEqual({ literal, kv: true });
244+
const signature = "export async function issueServerCoachItem(\n db: Pool,\n session: SessionState,\n item: IssuedCoachItem,\n): Promise<void> {}";
245+
for (const [code, file] of [
246+
[signature, "src/coach.ts"],
247+
["interface Props {\n session: SessionState;\n}", "src/props.ts"],
248+
["key={turn.requestId + turn.role + index}", "src/Turn.tsx"],
249+
["apiKey={settings.apiKey}", "src/Settings.jsx"],
250+
] as const) expect({ code, kv: kv(code, file) }).toEqual({ code, kv: false });
251+
for (const [literal, file] of [
252+
["API_KEY=VelvetRiverOrbitSunset;", ".env"],
253+
["password: {RiverStoneAmberCedar}", "config/app.yml"],
254+
[signature, undefined],
255+
[" session: SessionState,", "deploy/values.yaml"],
256+
[`session: "${v}",`, "src/a.ts"], [`key={${v}}`, "src/A.tsx"], [`API_KEY={${v}}`, "src/A.tsx"],
257+
[`key={settings.apiKey + "${v}"}`, "src/A.tsx"], [`key="${v}"`, "src/A.tsx"], [`api_key: ${v}`, ".env"],
258+
] as const) expect({ literal, file, kv: kv(literal, file) }).toEqual({ literal, file, kv: true });
259+
const jwt = ["eyJhbGciOiJIUzI1NiJ9", "eyJzdWIiOiIxMjM0NTY3ODkwIn0", "dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U"].join(".");
260+
expect(scan(`token: ${jwt},`, { repoVisibility: "private", sourcePath: "src/auth.ts" }).findings.map((f) => f.id)).toContain("jwt");
252261
});
253262
// #2912 — a line that READS a secret from the environment holds no secret;
254263
// it must not fire (and so must not be masked or withhold a /cso source file).
@@ -683,3 +692,22 @@ describe("taxonomy integrity", () => {
683692
}
684693
});
685694
});
695+
696+
describe("#3048: gstack-redact --from-file passes the file's path as scan context", () => {
697+
test("the same line is source syntax in a .ts file and a literal in YAML", () => {
698+
const fs = require("node:fs") as typeof import("node:fs");
699+
const os = require("node:os") as typeof import("node:os");
700+
const path = require("node:path") as typeof import("node:path");
701+
const { spawnSync } = require("node:child_process") as typeof import("node:child_process");
702+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "redact-from-file-"));
703+
try {
704+
const kv = (name: string) => {
705+
fs.writeFileSync(path.join(dir, name), " session: SessionState,\n");
706+
const r = spawnSync("bun", [path.join(import.meta.dir, "..", "bin", "gstack-redact"), "--from-file", path.join(dir, name), "--json"], { encoding: "utf8", timeout: 30_000 });
707+
return (JSON.parse(r.stdout).findings as Array<{ id: string }>).some((f) => f.id === "env.kv");
708+
};
709+
expect(kv("coach.ts")).toBe(false);
710+
expect(kv("values.yaml")).toBe(true);
711+
} finally { fs.rmSync(dir, { recursive: true, force: true }); }
712+
});
713+
});

‎test/redact-prepush-hook.test.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -638,3 +638,27 @@ describe("diff-extraction bypasses (#2498, minimal reimplementation)", () => {
638638
expect(stderr).toContain("could not parse");
639639
});
640640
});
641+
642+
describe("#3048: the pushed diff is scanned per file, so TS/JSX source syntax is not a secret", () => {
643+
const mediums = (stderr: string): number => Number(/(\d+) MEDIUM finding/.exec(stderr)?.[1] ?? 0);
644+
test("a TS parameter type and a JSX expression raise nothing; the same shape in YAML still does", () => {
645+
const base = git(["rev-parse", "HEAD"]);
646+
for (const [file, content] of [
647+
["src/coach.ts", "export function issue(\n session: SessionState,\n): void {}\n"],
648+
["src/Turn.tsx", "<Row key={turn.requestId + turn.role} />\n"],
649+
] as const) {
650+
fs.mkdirSync(path.dirname(path.join(repo, file)), { recursive: true });
651+
fs.writeFileSync(path.join(repo, file), content);
652+
git(["add", file]);
653+
}
654+
git(["commit", "-q", "-m", "ts"]);
655+
const tsHead = git(["rev-parse", "HEAD"]);
656+
expect(mediums(runHook(`refs/heads/main ${tsHead} refs/heads/main ${base}\n`).stderr)).toBe(0);
657+
fs.mkdirSync(path.join(repo, "deploy"), { recursive: true });
658+
fs.writeFileSync(path.join(repo, "deploy", "values.yaml"), " session: SessionState,\n");
659+
git(["add", "deploy/values.yaml"]);
660+
git(["commit", "-q", "-m", "yaml"]);
661+
const yamlHead = git(["rev-parse", "HEAD"]);
662+
expect(mediums(runHook(`refs/heads/main ${yamlHead} refs/heads/main ${tsHead}\n`).stderr)).toBe(1);
663+
});
664+
});

0 commit comments

Comments
 (0)