Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gstack/pregate.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
"LICENSE": [],
"licenses/**": [],
"contrib/**": [],
"supabase/**": []
"supabase/**": [],
"qm/sandbox/skills/gstack-review/scripts/diff-base.sh": ["test/qm-edition.test.ts"]
},
"selection": {
"free-tests.yml/free-suite": "bun run scripts/test-free-shards.ts --list"
Expand Down
8 changes: 7 additions & 1 deletion bin/gstack-artifacts-init
Original file line number Diff line number Diff line change
Expand Up @@ -431,7 +431,13 @@ if [ ! -f "$SCAN" ]; then
echo "gstack-artifacts pre-commit: refusing commit — the secret scanner $SCAN is missing; rerun gstack-artifacts-init to reinstall this hook." >&2
exit 1
fi
hits=$(git diff --cached --no-renames --no-color --no-ext-diff | python3 "$SCAN" gate -)
TEXT=$(mktemp) || { echo "gstack-artifacts pre-commit: refusing commit — could not create a temporary file for the secret scan." >&2; exit 1; }
trap 'rm -f "$TEXT"' EXIT
if ! git diff --cached --no-renames --no-color --no-ext-diff --text --no-textconv -U3 > "$TEXT"; then
echo "gstack-artifacts pre-commit: refusing commit — git could not read the staged diff for the secret scan." >&2
exit 1
fi
hits=$(git diff --cached --no-renames --no-color --no-ext-diff | python3 "$SCAN" gate - "$TEXT")
rc=$?
[ "$rc" -eq 0 ] && exit 0
if [ "$rc" -eq 3 ]; then
Expand Down
8 changes: 7 additions & 1 deletion bin/gstack-brain-restore
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,13 @@ if [ ! -f "$SCAN" ]; then
echo "gstack-brain pre-commit: refusing commit — the secret scanner $SCAN is missing; rerun gstack-brain-restore to reinstall this hook." >&2
exit 1
fi
hits=$(git diff --cached --no-renames --no-color --no-ext-diff | python3 "$SCAN" gate -)
TEXT=$(mktemp) || { echo "gstack-brain pre-commit: refusing commit — could not create a temporary file for the secret scan." >&2; exit 1; }
trap 'rm -f "$TEXT"' EXIT
if ! git diff --cached --no-renames --no-color --no-ext-diff --text --no-textconv -U3 > "$TEXT"; then
echo "gstack-brain pre-commit: refusing commit — git could not read the staged diff for the secret scan." >&2
exit 1
fi
hits=$(git diff --cached --no-renames --no-color --no-ext-diff | python3 "$SCAN" gate - "$TEXT")
rc=$?
[ "$rc" -eq 0 ] && exit 0
if [ "$rc" -eq 3 ]; then
Expand Down
111 changes: 95 additions & 16 deletions bin/gstack-brain-secret-scan.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,20 @@
a secret in a file name or one that lines up across an unchanged line is
held. Each added line is also scanned with its JSON string literals decoded,
so a secret hidden behind \u escapes or backslash-escaped quotes is caught.
Each hunk's new text (its unchanged and added lines without their diff
markers) is scanned as one block too, so a key on an unchanged line joins a
value added under it.

Callers pass two readings of the same staged diff and every check runs on
both, so neither can lose what the other holds. The first is the plain
`git diff` the hook has always scanned, with the user's diff.context and
textconv drivers. The second is the same diff with --text, --no-textconv and
-U3, so a file git calls binary arrives as its bytes and a diff.context below
3 cannot drop the unchanged lines around an edit. A line or hunk holding a
NUL byte is also read as UTF-16 in both byte orders and alignments, and with
its NULs removed. A section of the second reading that still says "Binary
files ... differ" or carries a "GIT binary patch" was not diffed as text; it
is flagged as binary-not-scanned (fail closed).

The first six pattern families are the original hook's; the four after them
mirror lib/redact-patterns.ts HIGH rules (stripe.secret/restricted,
Expand All @@ -15,10 +29,11 @@
The diff is read as bytes and decoded with replacement, so undecodable bytes
cannot crash the scan into a false "clean".

gate <diff|-> exit 0 clean, 3 hit (prints the family
gate <diff|-> [<text-diff>] exit 0 clean, 3 hit (prints the family
names); anything else is a scanner
failure (fail closed). "-" reads stdin.
attribute <diff> <names> <out> one pass: splits the diff on its
attribute <diff> <names> <out> [<text-diff>]
one pass: splits each diff on its
"diff --git" headers, pairs each section
with the NUL-separated names from
"git diff --name-only -z" (same order),
Expand Down Expand Up @@ -113,6 +128,50 @@ def added_lines(lines):
return out


def post_images(lines):
"""Each hunk's new text as bytes: its unchanged and added lines, markers
removed, joined on the newline byte git split them at."""
out, cur, in_hunk = [], [], False
for line in lines:
if line.startswith(b"diff --git ") or line.startswith(b"@@"):
if cur:
out.append(b"\n".join(cur))
cur, in_hunk = [], line.startswith(b"@@")
elif in_hunk and line[:1] in (b" ", b"+"):
cur.append(line[1:])
if cur:
out.append(b"\n".join(cur))
return out


def nul_readings(bodies):
"""Each byte string holding a NUL byte, read with its NULs removed and as
UTF-16LE and UTF-16BE from both byte alignments."""
out = []
for body in bodies:
if b"\0" not in body:
continue
out.append(body.replace(b"\0", b"").decode("utf-8", "replace"))
for chunk in (body, body[1:]):
chunk = chunk[:len(chunk) // 2 * 2]
out.append(chunk.decode("utf-16-le", "replace"))
out.append(chunk.decode("utf-16-be", "replace"))
return out


def unscanned_binary(lines):
"""True when a section's header says git did not diff a file as text."""
in_hunk = False
for line in lines:
if line.startswith(b"diff --git "):
in_hunk = False
elif line.startswith(b"@@"):
in_hunk = True
elif not in_hunk and (line.startswith(b"Binary files ") or line == b"GIT binary patch"):
return True
return False


def decoded_in_place(text):
"""text with every escaped JSON string literal replaced by its decoded
value in quotes, so a key and its value are matched together even when
Expand All @@ -127,13 +186,19 @@ def decode(m):
return json_string.sub(decode, text)


def families(lines):
def families(lines, text_reading=False):
added = added_lines(lines)
raw = b"\n".join(lines).decode("utf-8", "replace")
texts = [raw] + [decoded_in_place(line) for line in added] + [s for line in added for s in decoded_strings(line)]
posts = post_images(lines)
post_texts = [post.decode("utf-8", "replace") for post in posts]
texts = ([raw] + [decoded_in_place(line) for line in added] + [s for line in added for s in decoded_strings(line)]
+ post_texts + [decoded_in_place(text) for text in post_texts]
+ [t for nul in nul_readings([line[1:] for line in lines] + posts)
for t in [nul, decoded_in_place(nul)] + decoded_strings(nul)])
text = "\n".join(texts)
return [name for name, rx, real in patterns
if any(real is None or real(m) for m in rx.finditer(text))]
found = ['binary-not-scanned'] if text_reading and unscanned_binary(lines) else []
return found + [name for name, rx, real in patterns
if any(real is None or real(m) for m in rx.finditer(text))]


def read(path):
Expand All @@ -143,9 +208,27 @@ def read(path):
return f.read()


def union(plain, text):
hits = families(plain)
if text is not None:
hits += [h for h in families(text, text_reading=True) if h not in hits]
return hits


def sections(path):
out = []
for line in read(path).split(b"\n"):
if line.startswith(b"diff --git "):
out.append([line])
elif out:
out[-1].append(line)
return out


mode = sys.argv[1]
if mode == "gate":
hits = families(read(sys.argv[2]).split(b"\n"))
text = read(sys.argv[3]).split(b"\n") if len(sys.argv) > 3 else None
hits = union(read(sys.argv[2]).split(b"\n"), text)
if hits:
print(",".join(hits))
sys.exit(3)
Expand All @@ -155,18 +238,14 @@ def read(path):

diff_path, names_path, out_path = sys.argv[2:5]
names = [n.decode("utf-8", "surrogateescape") for n in read(names_path).split(b"\0") if n]
sections = []
for line in read(diff_path).split(b"\n"):
if line.startswith(b"diff --git "):
sections.append([line])
elif sections:
sections[-1].append(line)
if len(sections) != len(names):
plain = sections(diff_path)
text = sections(sys.argv[5]) if len(sys.argv) > 5 else [None] * len(plain)
if len(plain) != len(names) or len(text) != len(names):
sys.exit(4)
with open(out_path, "w", encoding="utf-8", errors="surrogateescape", newline="\n") as out:
for name, body in zip(names, sections):
for name, body, text_body in zip(names, plain, text):
if "\n" in name or "\t" in name:
sys.exit(4)
hits = families(body)
hits = union(body, text_body)
if hits:
out.write(hits[0] + "\t" + name + "\n")
22 changes: 15 additions & 7 deletions bin/gstack-brain-sync
Original file line number Diff line number Diff line change
Expand Up @@ -206,12 +206,17 @@ sync_active() {

# Secret scan over a staged diff file: bin/gstack-brain-secret-scan.py, the
# same scanner the artifacts repo's pre-commit hook runs. It scans the whole
# diff as written and each added line with its JSON string literals decoded,
# and prints only family names, never the matched text.
# secret_scan gate <diff> exit 0 clean, 3 hit (prints the
# diff as written, each added line with its JSON string literals decoded and
# each hunk's new text, and prints only family names, never the matched text.
# It reads two diffs of the same index: the plain diff (the user's
# diff.context and textconv drivers apply) and one with --text --no-textconv
# -U3, so binary files arrive as bytes and a small diff.context cannot hide
# the unchanged lines. Every finding from either reading counts.
# secret_scan gate <diff> [<text-diff>] exit 0 clean, 3 hit (prints the
# family names); anything else is
# a scanner failure (fail closed)
# secret_scan attribute <diff> <names> <out> writes "<family>\t<path>" per
# secret_scan attribute <diff> <names> <out> [<text-diff>]
# writes "<family>\t<path>" per
# flagged path; exit 0, or 4 when
# the diff's sections and the
# `git diff --name-only -z` names
Expand Down Expand Up @@ -1038,9 +1043,11 @@ hold_flagged_paths() {
WAITING=0
: > "$scan.hits"
: > "$scan.blobs"
(umask 077 && : > "$scan.diff" && : > "$scan.text") || rc=1
git -C "$GSTACK_HOME" diff --cached --no-renames --no-color --no-ext-diff > "$scan.diff" 2>/dev/null || rc=1
git -C "$GSTACK_HOME" diff --cached --no-renames --no-color --no-ext-diff --text --no-textconv -U3 > "$scan.text" 2>/dev/null || rc=1
git -C "$GSTACK_HOME" diff --cached --no-renames -z --name-only > "$scan.names" 2>/dev/null || rc=1
[ "$rc" -eq 0 ] && { secret_scan attribute "$scan.diff" "$scan.names" "$scan.hits" || rc=1; }
[ "$rc" -eq 0 ] && { secret_scan attribute "$scan.diff" "$scan.names" "$scan.hits" "$scan.text" || rc=1; }
[ "$rc" -eq 0 ] && { append_invalid_json_hits "$scan.names" "$scan.hits" || rc=1; }
# A successful add need not stage the requested spelling or current bytes
# (case-insensitive indexes and assume-unchanged can both report success).
Expand Down Expand Up @@ -1076,11 +1083,12 @@ hold_flagged_paths() {
{ grep -vxF -f "$scan.unstage" "$paths_file" || true; } > "$paths_file.kept"
mv -f "$paths_file.kept" "$paths_file"
fi
if ! git -C "$GSTACK_HOME" diff --cached --no-renames --no-color --no-ext-diff > "$scan.diff" 2>/dev/null; then
if ! git -C "$GSTACK_HOME" diff --cached --no-renames --no-color --no-ext-diff > "$scan.diff" 2>/dev/null \
|| ! git -C "$GSTACK_HOME" diff --cached --no-renames --no-color --no-ext-diff --text --no-textconv -U3 > "$scan.text" 2>/dev/null; then
block_drain "git could not read the staged diff for the re-scan"
return 1
fi
gate_out=$(secret_scan gate "$scan.diff") || gate_rc=$?
gate_out=$(secret_scan gate "$scan.diff" "$scan.text") || gate_rc=$?
[ "$gate_rc" -eq 0 ] && return 0
if [ "$gate_rc" -eq 3 ]; then
block_drain "a re-scan after holding back the flagged files still matched ($gate_out)"
Expand Down
4 changes: 3 additions & 1 deletion bin/gstack-ship-queue
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ import { EXIT, exitTableHelp, formatResult } from '../lib/headless-artifacts';
import { versionAtRef } from '../lib/restamp';
import { RESULT_CODES } from '../lib/result-codes';
import { resolveBaseBranch } from '../lib/ship-policy';
import { loadBasePolicy, ready, stamp, verify, type QueueContext, type StepOutput } from '../lib/ship-queue';
import { loadBasePolicy, ready, refreshBase, stamp, verify, type QueueContext, type StepOutput } from '../lib/ship-queue';
import { attemptFile, listAttempts, prepareGateAhead, recordGateAhead, type QueueFailure } from '../crew/lib/ship-queue-gate';
import { logShipCall } from '../lib/ship-call-log';

Expand Down Expand Up @@ -197,8 +197,10 @@ async function main(argv: string[]): Promise<number> {
if (gateExit !== undefined && !/^-?\d+$/.test(gateExit)) return usage('--gate-exit needs an exit code');
const gate = { gateExit: gateExit === undefined ? undefined : Number(gateExit), gateLog: flag(args, '--gate-log') };
if (cmd === 'ready') {
const unfetched = refreshBase(ctx);
const loaded = loadBasePolicy(ctx);
if (!('message' in loaded) && loaded.policy.train) return (await import('../crew/lib/ship-queue-train-cli')).readyMain(ctx, args, { pr, pregate: flag(args, '--pregate'), ...gate });
if (unfetched) return finish('ready', { ok: false, lines: [], run: 'none', failure: unfetched });
if (['--screen', '--no-screen', '--broad'].some(f => args.includes(f))) process.stderr.write('gstack-ship-queue ready: --screen/--no-screen/--broad ignored: the base policy declares no train block\n');
return finish('ready', ready(ctx, { pr, pregate: flag(args, '--pregate'), ...gate }));
}
Expand Down
Loading
Loading