Files
gstack/test/redact-engine.test.ts
T
caba78fefa v1.83.0.0 feat: Memorable recall bridge, opt-in and receipted (supersedes #2831) (#2836)
* feat: add optional Memorable workflow memory

(cherry picked from commit 6bd5d477b2)

* fix: refuse the second registration, and say what leaves the machine

Two things the first cut got wrong.

Memorable's own installer registers the same UserPromptSubmit hook, under its
own name and outside gstack's table. `memorable start`, `memorable setup` and
`memorable install-hooks` all do it, and that is the documented way to install
the CLI, so on most machines it is already there before gstack is asked.
Registering ours beside it ran the same command twice on every prompt: context
injected twice, and the session captured twice against the user's own
extraction allowance. `enable` now looks for it and refuses, naming the entry
and the file it lives in; `status` says who registered it rather than reporting
none. Matched on the command rather than on a tag, for the reason the hook
table already gives: Claude Code rewrites settings and private tags do not
survive it.

The removal instruction says to delete the entry by hand because Memorable has
no command that removes its own hook. `uninstall-hooks` is not a command in
0.5.18; it answers "unknown command".

The README said "Memorable, not gstack, owns the captured data and any network
access", which answers the question by pointing away from it. It now carries a
per-command table of exactly what leaves the machine, in the shape the adopted
gbrain section uses, and it is explicit that the hook makes no network call of
its own, that every row is the third-party CLI acting under its own consent,
and that `gstack-egress` will therefore not show any of it. Under it, the split
between what gstack pin-tests (the gating and the wiring) and what is
Memorable's claim (storage, sending, and what disable and forget erase).

The CHANGELOG entry is removed. This file has never carried an [Unreleased]
heading; every entry is a version and a date, written at release. The text is
in the pull request for whoever cuts the next one.

Three tests added: enable refuses and touches neither consent nor settings when
Memorable already holds the hook, status names that registration, and a foreign
UserPromptSubmit hook is not mistaken for Memorable's.

(cherry picked from commit e0899afa8c)

* docs: a guide for the Memorable bridge, in the gbrain-sync shape

README carries the section and the egress table; this is the page it links to
for anyone who wants the whole thing. Same shape as docs/gbrain-sync.md, which
is the closest thing in the repo: an optional integration whose interesting
questions are all about what leaves the machine and how to turn it off.

What it covers that the README cannot at that length: that the hook sees every
Claude Code prompt rather than only the ones a skill produced; that capture is
a separate consent from this bridge, so turning the bridge off does not turn
capture off; what to do when Memorable has already registered the hook itself,
which is the common case because its own installer does it; and why the hook
has no loud failure path.

The egress table is repeated here rather than linked, because the sentence it
is answering ("what does this send") is the one somebody arrives on this page
already asking.

Co-authored-by: Advaiyt Sane <advaiyt.sane@gmail.com>
Co-authored-by: Nikhil Krishnaswamy <krishnaswamynikhil@gmail.com>
(cherry picked from commit 5c108cc0f7)

* feat(settings-hook): identity-aware remove-source + read-only list-items

remove-source used to inspect only entries still carrying the
_gstack_source tag. Claude Code strips that tag when it rewrites
settings.json, so an off switch built on remove-source alone silently
no-oped on exactly the entries it was written for. Removal is now driven
by KNOWN_HOOKS identity for the requested source (tagged or not), keeps
the tagged-single-item legacy-stray rule, never touches another source's
items, and leaves entries with nothing of ours byte-identical.

list-items is the read-only view of the same identity table: one JSON
string literal per matching hook command, filters (--owned-by,
--command-regex as a JavaScript RegExp) applied inside the JS, empty
stdout for no match, and the mutating verbs' exit codes (1 usage, 3
unparseable settings, 4 unexpected shape) so callers can decide
mutations from its output without parsing raw command strings.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* feat(config): memorable_recall consent key (on|off, default off, reject-and-preserve)

The gstack-side gate for the Memorable UserPromptSubmit bridge. `on` lets
a Claude Code hook hand every prompt to a third-party binary, so the key
follows the codex_reviews rule: an invalid value is rejected and the
stored value kept, never coerced in either direction. Registered in all
four places gstack-config keeps in sync (annotated header, DEFAULTS
table, the set validator, and both enumeration loops). Memorable's own
capture consent (`memorable enable`) is a separate thing gstack never
sets.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* feat(hooks): memorable-user-prompt-hook.ts — consent gate, deny veto, HIGH-tier pre-scan, fail-closed receipt, trust envelope; runExternal in spawn-bin

The PR's hook exec'd the vendor binary with the full environment and
passed its stdout to Claude verbatim. It is now the house pattern: a
fail-open bash shim over a .ts twin that (1) gates on the memorable_recall
consent key, (2) skips repos whose trust policy is deny or read-only,
(3) scans the prompt (raw bytes and decoded string leaves) and refuses to
hand over a HIGH-tier credential shape, (4) writes a fail-closed egress
receipt naming the local executable it ran, (5) spawns the vendor in its
own process group with an allowlisted environment and group-kills it on
timeout, (6) accepts only a string additionalContext back, caps it at
8 KiB on a UTF-8 boundary and wraps it in the trust envelope, and (7)
records an `output-written` outcome after the stdout write completes.
One deadline clock (4.5 s) undercuts Claude Code's 5 s kill and bounds
both ledger writes through the new lockBudgetMs option on
writeReceipt/writeOutcome (default unchanged).

spawn-bin gains runExternal for external executables (detached group,
stderr drained, stdin EPIPE handled, stdout capped, win32 refused).
The wiring test pins the sink fail-closed and sweeps hosts/.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(gstack-memorable): canonical hook path, no vendor consent, --timeout 5, identity-based status, verified disable, lifecycle lock

enable used to bake the hook path from whatever tree the CLI ran in and
to run the vendor's own `memorable enable` (its consent for storing AND
uploading session traces) before registering anything. It now resolves
the canonical install like setup does and refuses when that install does
not carry this bridge (version and hook-twin check), registers through
the canonical hook manager with --timeout 5, records gstack's own consent
in memorable_recall, never executes the vendor, and restores the captured
prior state if consent cannot be recorded. disable flips the gate first,
removes the entry by identity (tag or no tag), verifies both states and
reports partial failure instead of a blended success. status reads only:
resolution path, gate, registration by identity (gstack / vendor-own /
both / unknown), mismatch lines, receipt count, recent hook errors. enable
and disable serialise under a lock with stale takeover. Windows is
refused (TODOS.md D21). Exit codes mirror the hook manager (3/4/5).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(setup): --no-team sweep keeps the opt-in gstack-memorable hook

`./setup --no-team` finishes its teardown with `prune-stale --all`, which
removes every KNOWN_HOOKS item. The Memorable bridge hook is a
user-registered opt-in unrelated to team mode, exactly like verify-gate,
so it joins the sweep exclusion list. The verify-gate pin now accepts the
comma-extended list; a schema-aware case proves the exclusion keeps both
opt-ins (tagged or tag-stripped) while the uninstall sweep still removes
them.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(uninstall): named gstack-memorable arm, vendor-consent notice, honest kept config

The identity sweep already removed the Memorable bridge hook as an
unnamed stray. It now has a named arm like every other source, so the
summary says what went, and says plainly that Memorable's own consent
(if the user granted it) is theirs to revoke. Under --keep-state the kept
config is set memorable_recall=off so it never claims a hook that is
gone. The canonical-paths pins cover the sixth KNOWN_HOOKS row and the
new uninstall source.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* feat(egress): memorable-recall row in gstack-egress grants

`gstack-egress grants` promises every standing consent in force with the
command that revokes it. The Memorable bridge's memorable_recall key is
one, so it gets a row: off by default, granted only when
`gstack-memorable enable` set it, revoked by `gstack-memorable disable`.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* docs(memorable): accurate bridge guide; README row, Docs table, privacy pointer; PROJECT_STRUCTURE

The README section becomes one row in the Standalone binaries table (the
shape every other binary uses) plus a Docs-table row and one Privacy
bullet saying that optional third-party bridges are off by default and
receipted. The guide now separates the two consents, says what gstack
hands to the vendor binary and what the receipt can and cannot attest,
attributes every statement about the vendor's network activity to the
vendor, describes the hook manager accurately (identity via KNOWN_HOOKS,
list-items vs list-sources, rollback is whole-file), states the Claude
Code hot-reload behaviour, adds a troubleshooting runbook, and keeps the
contributors' credit in the CHANGELOG idiom.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* chore(todos): Memorable bridge follow-ups

Filed from the CEO and eng reviews of the bridge fix-up: the generic
third-party hook seam, Windows support (deferred whole), the envelope
kind parameter, a vendor payload-minimization contract, a latency and
timeout revisit, resolver and canonical-root consolidation, a
non-interactive MEDIUM-tier redaction policy for hooks, and adopting
list-items at setup's plan-tune check.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(settings-hook): list-items --owned-by with --command-regex intersects

When both filters are given, an item must satisfy both: owned by the
requested source AND matching the pattern. Before, the regex branch
skipped every owned row, so the combination could never match.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(gstack-memorable): compat_check reads list-items output before grepping

Under pipefail, piping the probe straight into grep -q let a non-zero
probe exit mask the match, so a hook manager without list-items was
sometimes reported as compatible. Capture the output, then grep.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* test: coverage for the memorable bridge (remove-source regression for every KNOWN_HOOKS source)

- settings-hook: identity removal pinned for each source in KNOWN_HOOKS;
  list-items unknown flag and combined --owned-by/--command-regex
- gstack-memorable: enable/disable failure paths (lock give-up exit 5
  with the test-only lock timeout override, consent-write failures
  guarded by canRevokeWrites, canonical-version mismatch, no-bun status)
- hook: non-object JSON, missing cwd, non-ASCII bytes, held-open stdin,
  shim without bun, stripControl, resolveVendor, runExternal ENOENT
- egress-receipt: lockBudgetMs 0 and writeOutcome on garbage input
- uninstall: no memorable entry present reports nothing removed

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* docs(memorable): gbrain backend note and the settings-rewrite race

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* perf(redact-engine): line/col by binary search over a per-scan line index

lineColAt walked the input from offset 0 for every finding, so a match-dense
input (a pasted log full of emails and IPs) cost O(findings x bytes): 128 KiB
took ~400 ms and 900 KiB tens of seconds. The line starts are now indexed once
per scan, on the first finding, and each finding is a binary search.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* feat(gbrain-repo-policy-client): repoPolicyTier accepts a spawn timeout

The policy script spawn was fixed at 10 s, more than twice the memorable
hook's whole budget. Callers on their own deadline pass what they can afford;
a timeout reads as unreadable and polarity stays the caller's.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(spawn-bin): runExternal resolves on the child's exit, keeps stdin errors advisory

- A vendor that exits 0 but leaves a background child holding its pipes was
  held to the deadline, group-killed and reported as a timeout with its
  answer dropped. 'exit' now starts a short stdout drain, then resolves with
  the real exit code and kills whatever still holds the group.
- EPIPE on the child's stdin (it answered before reading a large input) is
  reported as stdinError, separate from error, so a delivered answer is not
  classified as a spawn failure.
- Stdio streams are destroyed and the child unref'd on resolve so a straggler
  cannot pin the hook process; tail/grace/drain sizes are named constants.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(hooks): memorable hook closes the review army's gaps

- Vendor failures are logged even with empty stderr (a silently hanging
  vendor taxed every prompt invisibly); the stderr tail is withheld when the
  redaction engine finds a credential or PII shape in it; hook-errors.log is
  created 0600.
- Trust-policy veto fails closed when git cannot run or answer in time (it
  read as 'no remote' before); the policy script spawn is bounded by the
  hook's clock; a payload cwd that is not a directory falls back.
- Each secret scan is admitted by the deadline clock (the engine's cost grows
  with match density); stdin is decoded once.
- The pre-spawn gate re-check logs a config failure instead of swallowing it;
  an incomplete stdin read is named as such, not as 'not JSON'.
- Carriage returns are stripped with the other controls.
- The vendor env allowlist adds the standard proxy, TLS and XDG variables so
  a vendor behind a corporate proxy or private CA still reaches its service.
- A stdin EPIPE on a delivered answer is recorded in the outcome, not treated
  as a spawn error.
- Stage caps and the truncation marker are named constants; a test-only
  GSTACK_MEMORABLE_TEST_BUDGET_MS can shorten (never widen) the budget.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(gstack-memorable): lock staleness from the directory mtime; honest messages

- A contender that looked between the holder's mkdir and its ts write read a
  missing ts as 0, called the lock stale and reclaimed it; staleness now comes
  from the lock directory's own mtime (the settings-hook idiom).
- The ensure-event failure is no longer labelled 'warning'; the consent-write
  rollback message says what was actually kept; a removal that left no entry
  is reported on stdout, not as an error; receipts are counted from the
  filtered JSON array, not a formatting artefact; the resolution order and
  lock tuning are named once.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(uninstall): memorable_recall goes off whether or not state is kept

gstack-config resolves its root through GSTACK_STATE_ROOT/GSTACK_HOME, which
can differ from the STATE_DIR uninstall removes; a full uninstall could leave
memorable_recall=on in a config that survived. Flipped only when currently on.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* test: pin the review-army fixes for the memorable bridge

Nonce-scoped orphan checks (the system-wide ps grep could see another
shard's sleeper); exit-with-lingering-grandchild; advisory stdin EPIPE;
withheld stderr; vendor timeout logged with empty stderr; CR stripping;
budget seam; rate-limit expiry and 0600 log; unreadable policy store fails
closed; file-as-cwd fallback; mtime-based lock staleness and the mkdir gap.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* docs(memorable): vendor environment allowlist and stderr policy; two follow-ups

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(hooks): memorable hook second-pass review fixes

- Trust-policy lookup fails closed on any git failure that is not 'no such
  remote' or 'not a git repository' (a corrupt or unreadable .git/config and
  dubious ownership exit 128 and used to read as 'no remote').
- pickAdditionalContext takes the first complete top-level JSON object, so a
  vendor whose background helper appends a line to stdout (or prints a banner
  first) does not lose its answer.
- The hook-errors.log rate limiter keys on a stable string (a vendor's
  timestamped stderr no longer defeats it); the log is chmod 0600 on every
  append because sibling hooks create the same file without a mode.
- Scan admission is sized by payload bytes (scan() is uninterruptible).
- The receipt payload class is a stable token; the prose moved to the docs.
- Header, constants and comments match the behaviour (silent skips vs logged
  refusals; HIGH/MEDIUM withholding; STAGE_CAP_MS scope; runExternal in the
  spawn-bin header; the ledger lock budget doc).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(gstack-memorable): stale-lock takeover by atomic rename; comments match behaviour

Two contenders that both saw a stale lock could both reclaim it with rm -rf;
the settings-hook idiom (mv to a private name, exactly one winner) is used
instead. The hook-manager fallback comment now says every verb falls back.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* test: second-pass coverage for the memorable bridge

Policy lookup outcomes (plain dir, repo without policy, corrupt .git/config
fails closed); repoPolicyTier timeoutMs; line/col at line starts, after blank
lines, CRLF and first char; tolerant first-JSON-object parsing; keyed rate
limit; uninstall never creates a config just to say off and flips consent in
a GSTACK_STATE_ROOT outside the removed state dir.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* docs(memorable): silent skips vs logged refusals; payload class token; D21/D24 anchors

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(hooks): memorable hook survives host termination and brace-bearing banners

- The bash shim runs bun as a job and forwards SIGTERM/SIGINT/SIGHUP (bash
  holds a signal until a foreground child exits); the .ts kills the in-flight
  vendor's process group on the way out (runExternal exposes the group kill
  through onSpawn), so a hook the host terminates cannot leave the vendor
  running with the prompt on its stdin.
- The tolerant stdout parser tries every complete top-level object (bounded)
  and takes the first carrying a string additionalContext, so a banner with
  braces or quotes, or a progress object, no longer costs the answer.
- git runs with LC_ALL=C and the not-a-repository check is anchored to the
  start of its message: a localized git or a repository path containing the
  phrase can no longer flip the lookup.
- The rate limiter remembers up to 32 live keys, so alternating failures cost
  two lines, not one per prompt.
- Unicode format characters (bidi overrides, zero-width spaces) are stripped
  from vendor text at egress; the zero-width joiner stays for emoji.
- A killed child (timeout, ENOBUFS) resolves on exit without the stdout drain,
  and the post-kill grace is 100 ms, so the timeout outcome fits the reserve.
- The ledger size warning, which the host discards from an exit-0 hook's
  stderr, is logged where status looks.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(gstack-memorable): failed stale-lock takeover reaches the give-up; disable runs without gstack-config; status shows ledger size

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* test: host termination kills the vendor group; brace banners, decoys and format characters; non-reclaimable stale lock gives up; ledger line in status

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* docs(memorable): the vendor dies with a terminated hook

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* test: deterministic stdin EPIPE case for runExternal (child closes stdin, stays alive)

Under parallel shard load a child that merely exits fast raced the write and
the EPIPE was not always observed; closing the read end first makes it so.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(hooks): outside-model review fixes for the memorable hook and runExternal

- Nothing in the vendor's process group outlives the call: the group is
  killed on every resolve, the clean 'close' path included (a helper the
  vendor forked with redirected stdio ran on unsupervised before).
- A child that already exited when the deadline fires keeps its result; the
  deadline only ends the drain instead of rewriting a completed exit as a
  timeout.
- The decoded-leaf scan reports when its node/depth bound cut the walk short
  and the hook refuses the hand-off as unscanned; object keys are scanned too.
- git for the trust-policy lookup runs without inherited GIT_* selectors
  (GIT_DIR, GIT_WORK_TREE, GIT_CONFIG_*), so it inspects the session's
  repository and no other; a host cancellation kills that git as well.
- An unmatched brace in a vendor banner no longer hides the answer after it.
- The stderr tail is scanned whole before it is cropped for the log, so a
  credential's prefix cannot be cropped away from its secret half.
- The vendor override reads an empty GSTACK_MEMORABLE_BIN as unset, exactly
  as bin/gstack-memorable does, so enable checks the binary the hook runs.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(gstack-memorable): stale-lock reclaim checks the inode it judged and the owner's liveness; status reports a failed receipt query as unknown

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(uninstall): revoke memorable_recall independently of the hook manager and name a failed revocation

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* test: group kill on clean close, walk exhaustion refused, GIT_DIR cannot bypass the deny, unmatched-brace banner, whole-tail scan, empty-override parity, uninstall revocation without the hook manager

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* docs(memorable): the process-group guarantee and its setsid boundary

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* chore(release): v1.83.0.0 — Memorable recall bridge, identity-aware hook removal, faster redaction line/col

CHANGELOG entry for the Memorable workflow-memory bridge (opt-in, off by
default, Claude Code only), the identity-aware remove-source and read-only
list-items in the hook manager, the memorable-recall egress sink, runExternal,
lockBudgetMs, and the binary-search line/col index in the redaction engine.
No migration. Contributed by @AdvaiytSane and @NIkhil-cmd-cmd (#2831).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* test: stdin EPIPE observation is scheduling-dependent under shard load; pin the invariant instead

A delivered answer is never reclassified as a spawn error; when the EPIPE is
observed it is reported as stdinError. Whether it is observed before the
child's exit resolves the call is not something the test can force.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* docs: list the memorable-recall sink among the fail-closed egress sinks

CLAUDE.md and ARCHITECTURE.md enumerate the receipt sinks that refuse to
send when the ledger cannot be written; the Memorable bridge's per-prompt
hand-off is pinned fail-closed in test/egress-receipt-wiring.test.ts but
was missing from both lists.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* test: memorable bridge tests pass on a runner that enforces file modes; scanner-proof key fixture

- The consent-write-failure tests make the state dir read-only, which also
  blocked the bridge lock directory (exit 5 before the path under test);
  the locks dir is pre-created so only the consent write fails.
- The unreadable-store test leaves a 0600 directory behind (the policy
  script chmods the store path); cleanup restores the search bit and the
  suite's afterEach reopens directories before removing.
- The AWS-key-shaped fixture is built by concatenation, as every sibling
  test does, so the CI credential gate does not read it as a live key.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(gstack-memorable): name an unwritable state directory when the lock cannot be created

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: AdvaiytSane <advaiyt.sane@gmail.com>
Co-authored-by: Nikhil Krishnaswamy <krishnaswamynikhil@gmail.com>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-08 22:05:41 -07:00

656 lines
32 KiB
TypeScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Unit tests for lib/redact-engine.ts + lib/redact-patterns.ts.
*
* One positive test per pattern, plus FP-filters, validators (Luhn/entropy/
* RFC1918), email allowlist, no-promotion visibility semantics, tool-fence
* degrade, normalization (zero-width / homoglyph / entity), oversize fail-closed,
* and pure-function purity.
*/
import { describe, test, expect } from "bun:test";
import {
scan,
exitCodeFor,
maskPreview,
normalizeWithMap,
redactFindingSpans,
type RepoVisibility,
} from "../lib/redact-engine";
import {
PATTERNS,
luhnValid,
shannonEntropy,
isPublicIPv4,
isPlaceholderSpan,
URL_PASSWORD_PLACEHOLDER_WORDS,
} from "../lib/redact-patterns";
function ids(text: string, vis: RepoVisibility = "private"): string[] {
return scan(text, { repoVisibility: vis }).findings.map((f) => f.id);
}
describe("HIGH credential patterns", () => {
const cases: Array<[string, string]> = [
["aws.access_key", "key = AKIA1234567890ABCDEF"],
["aws.secret_key", "aws_secret_access_key = AbCdEfGhIjKlMnOpQrStUvWxYz0123456789AbCd"],
["github.pat", "token ghp_" + "1234567890abcdefghijklmnopqrstuvwxyz"],
["github.oauth", "gho_" + "1234567890abcdefghijklmnopqrstuvwxyz"],
["github.server", "ghs_1234567890abcdefghijklmnopqrstuvwxyz"],
["github.fine_grained", "github_pat_" + "A".repeat(82)],
["anthropic.key", "sk-ant-" + "api03-abcdefghij1234567890XYZ"],
["openai.key", "sk-proj-" + "a".repeat(40)],
["sendgrid.key", "SG." + "a".repeat(22) + "." + "b".repeat(43)],
["stripe.secret", "sk_live_" + "a".repeat(30)],
["slack.token", "xox" + "b-1234567890-abcdefghijklmnop"],
["slack.webhook", "https://hooks.slack.com/services/T00000000/B11111111/" + "a".repeat(24)],
["discord.webhook", "https://discord.com/api/webhooks/123456789012345678/" + "a".repeat(60)],
["pem.private_key", "-----BEGIN RSA PRIVATE KEY-----"],
// #1946 coverage-gap additions
["gitlab.token", "remote: glpat-" + "Ab12Cd34Ef56Gh78Ij90"],
["gitlab.token", "trigger glptt-" + "a1b2c3d4e5f6a7b8c9d0e1f2"],
["gitlab.token", "deploy gldt-" + "Zy98Xw76Vu54Ts32Rq10"],
["groq.key", "gsk_" + "AbCdEfGhIjKlMnOpQrStUvWxYz0123456789AbCdEfGhIjKlMn"],
["tavily.key", "tvly-" + "AbCdEfGhIjKlMnOpQrStUvWx"],
["tavily.key", "tvly-dev-" + "AbCdEfGhIjKlMnOpQrStUvWx"],
["notion.token", "ntn_" + "AbCdEfGhIjKlMnOpQrStUvWxYz0123456789AbCdEfGh"],
["notion.token", "secret_" + "AbCdEfGhIjKlMnOpQrStUvWxYz0123456789AbCdEfGh"],
["huggingface.token", "hf_" + "AbCdEfGhIjKlMnOpQrStUvWxYz012345"],
["npm.token", "npm_" + "a1B2c3D4e5F6g7H8i9J0k1L2m3N4o5P6q7R8"],
["digitalocean.token", "dop_v1_" + "0123456789abcdef".repeat(4)],
[
"gcp.service_account",
'{"private_key_id": "abc123", "private_key": "-----BEGIN PRIVATE KEY-----\\nMIIE..."}',
],
["google.oauth_client_secret", 'client_secret: "GOCSPX-' + "Ab3xQ9zLmNp2RtVw7YkD1sHf" + '"'],
["telegram.bot_token", "TELEGRAM_TOKEN=8326208591:AA" + "HdqRy9Lm2ZpXvKb4NcQw8TuEr6YoP1sVg"],
];
for (const [id, text] of cases) {
test(`flags ${id}`, () => {
expect(ids(text)).toContain(id);
});
}
// #1868 — modern OpenAI keys use base64url bodies (with - and _). The old
// [A-Za-z0-9]{32,} regex stopped at the first separator and missed them all,
// failing a HIGH credential OPEN through the redaction gate.
test("openai.key flags modern sk-proj-/sk-svcacct-/sk-admin- shapes (#1868)", () => {
const missed = [
"sk-proj-Ab12_Cd34-Ef56Gh78Ij90Kl12Mn34Op56Qr78St90Uv",
"sk-svcacct-abc_def-ghijklmnopqrstuvwxyz0123456789ABCDEF",
"sk-admin-AAAA_BBBB-CCCC_DDDD-EEEE_FFFF-GGGG_HHHH1234",
];
for (const key of missed) {
expect(ids(`OPENAI_API_KEY=${key}`)).toContain("openai.key");
}
// legacy contiguous shape still flags
expect(ids("sk-proj-" + "a".repeat(40))).toContain("openai.key");
});
test("openai.key does not over-match prose / malformed sk- strings (#1868 calibration)", () => {
// HIGH tier BLOCKS, so false positives on prose are costly. None of these
// should flag as openai.key.
const benign = [
"the sk-learning-rate-schedule-was-tuned-carefully", // hyphenated prose
"sk--double-dash-typo-not-a-real-key",
"use sk-proj for the project prefix in docs", // no body
"sk-short", // too short, no prefix
];
for (const text of benign) {
expect(ids(text)).not.toContain("openai.key");
}
});
test("twilio.auth_token needs an SID nearby", () => {
const sid = "AC" + "a".repeat(32);
const tok = "b".repeat(32);
expect(ids(`account ${sid} token ${tok}`)).toContain("twilio.auth_token");
// bare 32-hex with no SID nearby should NOT flag as twilio
expect(ids(`random ${tok} here`)).not.toContain("twilio.auth_token");
});
test("db.url_with_password flags real password, skips placeholder/env-var", () => {
expect(ids("postgres://user:s3cretP@ss@db.example.com/app")).toContain("db.url_with_password");
expect(ids("postgres://user:${DB_PASSWORD}@host/app")).not.toContain("db.url_with_password");
// Literal PASSWORD placeholder (URL-format doc comments).
expect(ids("postgresql://USER:PASSWORD@host/db")).not.toContain("db.url_with_password");
// JS template interpolations are code, not credentials — the
// uppercase-only placeholder form blocked a push over
// `postgresql://${dbUser}:${dbPass}@...` in a bash->TS port.
// eslint-disable-next-line no-template-curly-in-string
expect(ids("postgresql://${dbUser}:${dbPass}@${dbHost}:5432/db")).not.toContain("db.url_with_password");
// Assembled at runtime so this file's own diff never contains a
// credential-shaped literal (the prepush guard scans exact pushed bytes).
expect(ids("postgres://admin:" + "hun" + "ter2@db.internal/app")).toContain("db.url_with_password");
// Bare $UPPER_SNAKE is shell convention → suppressed; bare $lowercase is
// NOT an interpolation form — a real password starting with `$` must
// still block (both-braces-optional would have let it through).
expect(ids("postgres://user:$DB_PASSWORD@host/app")).not.toContain("db.url_with_password");
expect(ids("postgres://admin:$" + "hun" + "ter2@db.internal/app")).toContain("db.url_with_password");
// Mismatched brace is not an interpolation either (assembled at runtime
// so this file's own pushed bytes carry no blockable URL shape).
expect(ids("postgres://admin:${" + "dbPass@db.internal/app")).toContain("db.url_with_password");
// A fully-braced interpolation is code whatever it contains — the DSN
// builder's `${encodeURIComponent(dbPass)}` call site must not scan as a
// pushed secret.
expect(ids("postgresql://user:${encodeURIComponent(dbPass)}@host:5432/db")).not.toContain("db.url_with_password");
// A LOWERCASE literal 'password'/'pass' at the URL-password position is a
// real (terrible) credential, not a doc placeholder — only the ALL-CAPS
// doc convention (USER:PASSWORD) is suppressed. Assembled at runtime so
// this file's own bytes never carry a live credential shape.
expect(ids("postgres://admin:" + "pass" + "word@10.0.0.5/app")).toContain("db.url_with_password");
expect(ids("https://root:" + "pa" + "ss@127.0.0.1/")).toContain("creds.basic_auth_url");
// Structural placeholders still suppress at the URL position.
expect(ids("postgres://user:<your-password>@host/db")).not.toContain("db.url_with_password");
// An ALL-CAPS password that is NOT an exact placeholder token is a real
// secret and must block — the pre-fix shape rule (/^[A-Z][A-Z0-9_]*$/) waved
// every all-caps password through. Substring of a placeholder word (SECRET)
// must not rescue it. Assembled at runtime so this file's own pushed bytes
// carry no live DSN shape.
expect(ids("postgres://admin:" + "PROD2026" + "SECRET@db-prod.internal/app")).toContain("db.url_with_password");
expect(ids("postgres://admin:" + "ADMIN" + "123@host/db")).toContain("db.url_with_password");
});
// Every curated placeholder word must suppress at the URL-password position.
// The fix replaced a shape rule with a hand-curated EXACT set, so a typo or a
// dropped entry (CHANGEME -> CHANGME) would silently start blocking a legit
// doc placeholder with zero failure elsewhere. Loop the real exported set so
// the test can't drift from the source list.
test("db.url_with_password suppresses every curated placeholder word", () => {
for (const word of URL_PASSWORD_PLACEHOLDER_WORDS) {
expect(ids(`postgres://user:${word}@host/db`)).not.toContain("db.url_with_password");
}
// Guard the set stays a non-trivial curated list (catches an accidental clear).
expect(URL_PASSWORD_PLACEHOLDER_WORDS.size).toBeGreaterThanOrEqual(8);
// And a real secret that merely CONTAINS a placeholder word still blocks.
expect(ids("postgres://user:" + "MY" + "SECRETPASS@host/db")).toContain("db.url_with_password");
});
test("all HIGH patterns block (exit 3)", () => {
const r = scan("AKIA1234567890ABCDEF", { repoVisibility: "private" });
expect(exitCodeFor(r)).toBe(3);
});
});
describe("MEDIUM demoted credential-shaped patterns (TENSION-1)", () => {
test("stripe.publishable is MEDIUM not HIGH", () => {
const f = scan("pk_live_" + "a".repeat(30), { repoVisibility: "private" }).findings.find(
(x) => x.id === "stripe.publishable",
);
expect(f?.tier).toBe("MEDIUM");
});
test("google.api_key is MEDIUM", () => {
const f = scan("AIza" + "a".repeat(35), { repoVisibility: "private" }).findings.find(
(x) => x.id === "google.api_key",
);
expect(f?.tier).toBe("MEDIUM");
});
test("jwt is MEDIUM", () => {
const jwt = "eyJhbGciOiJ.eyJzdWIiOiI." + "x".repeat(20);
const f = scan(jwt, { repoVisibility: "private" }).findings.find((x) => x.id === "jwt");
expect(f?.tier).toBe("MEDIUM");
});
test("env.kv fires on high-entropy, skips placeholder", () => {
expect(ids("API_TOKEN=8Fk2pQ9vXz4wL7mN3rT6yB1cD5eG0hJ")).toContain("env.kv");
expect(ids("API_KEY=changeme")).not.toContain("env.kv");
expect(ids("API_KEY=${MY_VAR}")).not.toContain("env.kv");
});
// #1946 gap 3: the uppercase-`=`-only shape made lowercase and YAML/JSON
// colon assignments invisible — the exact config shapes people actually
// push. Each closed detection fail-open gets a pinned case.
test("env.kv fires on lowercase = assignment (#1946)", () => {
expect(ids("api_key=8Fk2pQ9vXz4wL7mN3rT6yB1cD5eG0hJ")).toContain("env.kv");
});
test("env.kv fires on YAML colon assignment (#1946)", () => {
expect(ids("password: 8Fk2pQ9vXz4wL7mN3rT6yB1cD5eG0hJ")).toContain("env.kv");
});
test("env.kv fires on quoted JSON key colon assignment (#1946)", () => {
expect(ids('"apiKey": "8Fk2pQ9vXz4wL7mN3rT6yB1cD5eG0hJ"')).toContain("env.kv");
});
test("env.kv colon/lowercase forms stay entropy-gated and placeholder-safe", () => {
expect(ids("password: changeme")).not.toContain("env.kv");
expect(ids("apiKey: YOUR_API_KEY_HERE")).not.toContain("env.kv");
expect(ids("api_key=${MY_VAR}")).not.toContain("env.kv");
});
// T1 calibration: the zero-or-more-prefix net matched ANY identifier ending
// in a suffix, so ordinary code (`cacheKey: <entropic id>`) hit a MEDIUM
// confirm prompt. Name shape must be credential-semantic to count.
test("env.kv ignores non-credential names ending in a suffix (entropic values)", () => {
const v = "8Fk2pQ9vXz4wL7mN3rT6yB1cD5eG0hJ";
expect(ids(`cacheKey: ${v}`)).not.toContain("env.kv");
expect(ids(`sortKey: ${v}`)).not.toContain("env.kv");
expect(ids(`partitionKey: ${v}`)).not.toContain("env.kv");
expect(ids(`hotkey: ${v}`)).not.toContain("env.kv");
expect(ids(`monkey: ${v}`)).not.toContain("env.kv");
expect(ids(`idempotencyKey: ${v}`)).not.toContain("env.kv");
});
test("env.kv still fires on every credential-shaped name form", () => {
const v = "8Fk2pQ9vXz4wL7mN3rT6yB1cD5eG0hJ";
expect(ids(`api_key=${v}`)).toContain("env.kv"); // (i) separator
expect(ids(`API_KEY=${v}`)).toContain("env.kv"); // (i) + ALL-CAPS
expect(ids(`x-access-key: ${v}`)).toContain("env.kv"); // (i) dash separator
expect(ids(`key: ${v}`)).toContain("env.kv"); // (ii) bare suffix
expect(ids(`APIKEY=${v}`)).toContain("env.kv"); // (iii) ALL-CAPS compound
expect(ids(`apiKey: ${v}`)).toContain("env.kv"); // (iv) credential camel
expect(ids(`authToken: ${v}`)).toContain("env.kv"); // (iv) credential camel
expect(ids(`clientSecret: ${v}`)).toContain("env.kv"); // (iv) credential camel
});
test("env.kv stays MEDIUM (calibration: generic net, not a blocker)", () => {
const f = scan("api_key=8Fk2pQ9vXz4wL7mN3rT6yB1cD5eG0hJ", { repoVisibility: "private" })
.findings.find((x) => x.id === "env.kv");
expect(f?.tier).toBe("MEDIUM");
});
// #1946 — Bearer is the most FP-prone shape in the wave: docs and examples
// are full of "Authorization: Bearer <token>". MEDIUM + header proximity +
// the env.kv entropy recipe keep it calibrated.
test("auth.bearer fires on a high-entropy token in header context", () => {
const text = "curl -H 'Authorization: Bearer 8Fk2pQ9vXz4wL7mN3rT6yB1cD5eG0hJq'";
const f = scan(text, { repoVisibility: "private" }).findings.find(
(x) => x.id === "auth.bearer",
);
expect(f).toBeDefined();
expect(f?.tier).toBe("MEDIUM");
});
test("auth.bearer skips placeholders and env interpolations", () => {
expect(ids("Authorization: Bearer YOUR_TOKEN_HERE_PLACEHOLDER")).not.toContain("auth.bearer");
expect(ids("Authorization: Bearer ${ACCESS_TOKEN_FROM_ENV}")).not.toContain("auth.bearer");
});
test("auth.bearer requires header context (bare 'Bearer x' prose doesn't fire)", () => {
expect(ids("the Bearer 8Fk2pQ9vXz4wL7mN3rT6yB1cD5eG0hJq walked in")).not.toContain(
"auth.bearer",
);
});
});
describe("#1946 pattern negatives (placeholders never fire)", () => {
test("short or placeholder shapes don't trip the new HIGH patterns", () => {
expect(ids("glpat-xxxx")).not.toContain("gitlab.token");
expect(ids("hf_token")).not.toContain("huggingface.token");
expect(ids("gsk_key")).not.toContain("groq.key");
expect(ids("tvly-key")).not.toContain("tavily.key");
expect(ids("ntn_token")).not.toContain("notion.token");
// `secret_` is an ordinary word; only the length makes it a credential.
expect(ids("secret_value")).not.toContain("notion.token");
expect(ids("npm_install")).not.toContain("npm.token");
expect(ids("dop_v1_short")).not.toContain("digitalocean.token");
// pem header WITHOUT the GCP JSON shape stays pem.private_key only.
expect(ids("-----BEGIN PRIVATE KEY-----")).not.toContain("gcp.service_account");
});
});
describe("google.oauth_client_secret / telegram.bot_token negatives", () => {
test("undersized and placeholder shapes never fire", () => {
// Length floor keeps short repo fixtures quiet (e.g. the 19-char body in
// openclaw's extensions/google/oauth.test.ts).
expect(ids("GOCSPX-FakeSecretValue123")).not.toContain("google.oauth_client_secret");
expect(ids("GOCSPX-short")).not.toContain("google.oauth_client_secret");
// Placeholder suppression on an otherwise correctly-sized body.
expect(ids("GOCSPX-example" + "a".repeat(17))).not.toContain("google.oauth_client_secret");
expect(ids("1234567890:AAexample" + "a".repeat(26))).not.toContain("telegram.bot_token");
// A plain number pair must not read as a bot token.
expect(ids("1234567890:1234567890")).not.toContain("telegram.bot_token");
// The AIza key stays MEDIUM (google.api_key); it is not promoted here.
expect(ids("AIza" + "a".repeat(35))).not.toContain("google.oauth_client_secret");
});
});
describe("PII patterns", () => {
test("email flags + is autoRedactable", () => {
const f = scan("ping alice@corp.io please", { repoVisibility: "private" }).findings.find(
(x) => x.id === "pii.email",
);
expect(f).toBeTruthy();
expect(f?.autoRedactable).toBe(true);
});
test("email allowlist: example.com, noreply, self, repo-public", () => {
expect(ids("see user@example.com")).not.toContain("pii.email");
expect(ids("from noreply@github.com")).not.toContain("pii.email");
expect(
scan("me@garry.dev", { repoVisibility: "private", selfEmail: "me@garry.dev" }).findings,
).toHaveLength(0);
expect(
scan("bob@acme.co", { repoVisibility: "private", repoPublicEmails: ["bob@acme.co"] }).findings,
).toHaveLength(0);
});
// A git SSH remote's `git@host` is a transport user@host, not a person's
// address. Suppressed by URL SHAPE rather than by allowlisting the `git`
// local part: a bare `git@` entry would also silently hide a real address
// at a domain that merely starts with "git".
test("ssh git remotes are not flagged as emails", () => {
expect(ids("set :repo_url, 'git@github.com:acme/widgets.git'")).not.toContain(
"pii.email",
);
expect(ids("git clone git@gitlab.com:acme/widgets.git")).not.toContain("pii.email");
expect(ids("git@bitbucket.org:acme/widgets.git")).not.toContain("pii.email");
expect(ids("git@ssh.dev.azure.com:v3/acme/widgets/widgets")).not.toContain("pii.email");
expect(ids("ssh -T git@github.com")).not.toContain("pii.email");
// General case: any host in <user>@<host>:<path>.git position.
expect(ids("git@git.acme-internal.net:infra/tools.git")).not.toContain("pii.email");
expect(ids("ssh://git@scm.acme-internal.net/infra/tools.git")).not.toContain("pii.email");
});
test("a real address is still flagged, including at a git host", () => {
expect(ids("ping alex@github.com about the issue")).toContain("pii.email");
// A domain that merely STARTS WITH "git" is not a git host — this is the
// case a bare `git@` local-part allowlist would have wrongly suppressed.
expect(ids("contact git@gitmail.com for access")).toContain("pii.email");
});
test("phone E.164 flags, skips compact timestamps", () => {
expect(ids("call +14155550123 now")).toContain("pii.phone.e164");
expect(ids("backup stamp 20260727202423 ran late")).not.toContain("pii.phone.e164");
});
test("ssn flags valid, skips 000 octet", () => {
expect(ids("ssn 123-45-6789")).toContain("pii.ssn");
expect(ids("000-12-3456")).not.toContain("pii.ssn");
});
test("credit card needs Luhn", () => {
expect(ids("card 4111111111111111")).toContain("pii.cc");
expect(ids("num 4111111111111112")).not.toContain("pii.cc");
});
test("public IP flagged, RFC1918 skipped", () => {
expect(ids("connect 8.8.8.8")).toContain("pii.ip_public");
expect(ids("local 192.168.1.5")).not.toContain("pii.ip_public");
expect(ids("local 10.0.0.1")).not.toContain("pii.ip_public");
});
// Digit-only UUIDs are the standard test-fixture shape, and their digit runs
// collide with both the card pattern (a 13-19 digit slice passes Luhn often
// enough to matter) and the phone pattern (hyphen groups read as national
// formatting). Observed live: 14 of 21 MEDIUM findings on one ordinary branch
// were exactly this, all from test files — the volume that makes people stop
// reading MEDIUM output at all.
test("digit-only UUID fixtures are not cards or phones", () => {
expect(ids("owner_user_id: '00000000-0000-0000-0000-000000000000'")).not.toContain("pii.cc");
expect(ids("const OWNER = '11111111-1111-1111-1111-111111111111'")).not.toContain(
"pii.phone.e164",
);
expect(ids("const TEAM = '22222222-2222-2222-2222-222222222222'")).not.toContain(
"pii.phone.e164",
);
// Hex UUIDs never matched these digit patterns; pinned so the suppression
// is not silently widened to something that swallows real numbers.
expect(ids("id 'a1b2c3d4-1111-2222-3333-444455556666'")).not.toContain("pii.cc");
});
test("UUID suppression requires TOTAL containment", () => {
// Real card sitting next to a UUID still reports — suppression is the
// exception and may only fire when the whole match is UUID interior.
expect(ids("00000000-0000-0000-0000-000000000000 4111111111111111")).toContain("pii.cc");
// And the plain cases are untouched.
expect(ids("card 4111-1111-1111-1111")).toContain("pii.cc");
expect(ids("reach me on +1 415 555 2671")).toContain("pii.phone.e164");
});
});
describe("internal + legal patterns", () => {
test("internal hostname", () => {
expect(ids("db1.corp internal host")).toContain("internal.hostname");
});
test("localhost url with path", () => {
expect(ids("hit http://localhost:8080/admin/secrets")).toContain("internal.url_private");
});
test("NDA marker", () => {
expect(ids("This is CONFIDENTIAL material")).toContain("legal.nda_marker");
});
test("named criticism needs a capitalized full name nearby", () => {
expect(ids("John Smith is incompetent at this")).toContain("legal.named_criticism");
expect(ids("the build is incompet019ently configured".replace("019", ""))).not.toContain(
"legal.named_criticism",
);
});
});
describe("LOW patterns surface only", () => {
test("user path is LOW", () => {
const f = scan("/Users/bob/secret/config", { repoVisibility: "private" }).findings.find(
(x) => x.id === "internal.user_path",
);
expect(f?.tier).toBe("LOW");
});
test("TODO marker is LOW", () => {
const f = scan("TODO(alice) fix later", { repoVisibility: "private" }).findings.find(
(x) => x.id === "hygiene.todo",
);
expect(f?.tier).toBe("LOW");
});
test("gstack-shortcut(dec-*) debt marker survives redaction untouched", () => {
// The shortcut ledger convention (AskUserQuestion Format / /retro Step 11.5)
// ships in commits and PR bodies BY DESIGN — the ledger is the point. It
// must not be caught by hygiene.todo's TODO(owner) shape or anything else.
const marker =
"// gstack-shortcut(dec-a1b2c3): global lock, upgrade when throughput matters";
const result = scan(marker, { repoVisibility: "public" });
expect(result.findings).toHaveLength(0);
});
});
describe("placeholder suppression (per-span)", () => {
test("AWS docs EXAMPLE key not flagged", () => {
expect(ids("AKIAIOSFODNN7EXAMPLE")).not.toContain("aws.access_key");
});
test("your_ prefix not flagged", () => {
expect(isPlaceholderSpan("your_api_key")).toBe(true);
});
test("a real secret on a line that ALSO contains EXAMPLE still flags", () => {
// line-based suppression would wrongly skip this; per-span must catch it.
expect(ids("# EXAMPLE usage\nkey AKIA1234567890ABCDEF")).toContain("aws.access_key");
});
});
describe("no visibility-based tier promotion (TENSION-2-followup)", () => {
test("email stays MEDIUM on both private and public", () => {
const priv = scan("x@corp.io", { repoVisibility: "private" }).findings[0];
const pub = scan("x@corp.io", { repoVisibility: "public" }).findings[0];
expect(priv.tier).toBe("MEDIUM");
expect(pub.tier).toBe("MEDIUM");
expect(pub.severity).toBe("MEDIUM"); // NOT promoted to HIGH
expect(pub.repoVisibility).toBe("public"); // recorded for sterner wording
});
test("demoted credential patterns stay MEDIUM on public", () => {
const pub = scan("pk_live_" + "a".repeat(30), { repoVisibility: "public" }).findings[0];
expect(pub.severity).toBe("MEDIUM");
});
test("unknown visibility treated as public for wording, still no promotion", () => {
const r = scan("x@corp.io", { repoVisibility: "unknown" });
expect(r.findings[0].severity).toBe("MEDIUM");
});
});
describe("tool-attributed fence WARN-degrade (TENSION-3)", () => {
test("placeholder-shaped credential in tool fence → WARN", () => {
const text = "```codex-review\nfound your_aws_key AKIAIOSFODNN7EXAMPLE in code\n```";
const r = scan(text, { repoVisibility: "private" });
// the EXAMPLE key is suppressed as placeholder; verify a non-credential note doesn't block
expect(r.counts.HIGH).toBe(0);
});
test("live-format credential in tool fence STILL blocks", () => {
const text = "```codex-review\nleaked AKIA1234567890ABCDEF here\n```";
const r = scan(text, { repoVisibility: "private" });
expect(r.counts.HIGH).toBe(1); // not degraded — live format
});
test("AKIA outside any fence blocks", () => {
expect(exitCodeFor(scan("AKIA1234567890ABCDEF", {}))).toBe(3);
});
});
describe("normalization", () => {
test("zero-width chars inside a key are stripped before matching", () => {
const zwsp = "";
const broken = "AKIA1234567890" + zwsp + "ABCDEF";
expect(ids(broken)).toContain("aws.access_key");
});
test("HTML entity decode", () => {
const { normalized } = normalizeWithMap("a &amp; b");
expect(normalized).toBe("a & b");
});
test("offset map points back into original", () => {
const input = "xyz";
const { normalized, map } = normalizeWithMap(input);
expect(normalized).toBe("xyz");
// 'z' is at normalized index 2, original index 3
expect(map[2]).toBe(3);
});
});
describe("oversize fails CLOSED", () => {
test("input over the byte cap returns a single blocking HIGH finding", () => {
const big = "a".repeat(2000);
const r = scan(big, { maxBytes: 1000 });
expect(r.oversize).toBe(true);
expect(r.counts.HIGH).toBe(1);
expect(r.findings[0].id).toBe("engine.input_too_large");
expect(exitCodeFor(r)).toBe(3);
});
// #1824: a malformed --max-bytes used to reach the engine as NaN. `byteLen >
// NaN` is always false, silently disabling the fail-closed guard. The engine
// guardrail must fall back to the default cap for any non-finite / <= 0 value.
test("NaN maxBytes falls back to the default cap (does NOT disable the guard)", () => {
const big = "a".repeat(2 * 1024 * 1024); // > 1 MiB default cap
const r = scan(big, { maxBytes: NaN });
expect(r.oversize).toBe(true);
expect(r.findings[0].id).toBe("engine.input_too_large");
expect(exitCodeFor(r)).toBe(3);
});
test("negative / zero maxBytes falls back to the default cap", () => {
// negative would make `byteLen > -5` always true (block everything);
// the guardrail normalizes it to the default instead.
const small = "ok";
expect(scan(small, { maxBytes: -5 }).oversize).toBeFalsy();
expect(scan(small, { maxBytes: 0 }).oversize).toBeFalsy();
const big = "a".repeat(2 * 1024 * 1024);
expect(scan(big, { maxBytes: -5 }).oversize).toBe(true);
});
});
describe("validators", () => {
test("luhn", () => {
expect(luhnValid("4111111111111111")).toBe(true);
expect(luhnValid("4111111111111112")).toBe(false);
});
test("entropy", () => {
expect(shannonEntropy("aaaaaaaa")).toBeLessThan(1);
expect(shannonEntropy("8Fk2pQ9vXz4wL7mN")).toBeGreaterThan(3);
});
test("isPublicIPv4", () => {
expect(isPublicIPv4("8.8.8.8")).toBe(true);
expect(isPublicIPv4("10.1.2.3")).toBe(false);
expect(isPublicIPv4("172.16.5.5")).toBe(false);
expect(isPublicIPv4("999.1.1.1")).toBe(false);
});
});
describe("masking + purity", () => {
test("preview never leaks more than 4 leading chars", () => {
expect(maskPreview("AKIA1234567890ABCDEF")).toBe("AKIA********…");
expect(maskPreview("abc")).toBe("abc");
});
test("scan is pure — same input twice yields identical findings", () => {
const a = scan("AKIA1234567890ABCDEF x@corp.io", { repoVisibility: "public" });
const b = scan("AKIA1234567890ABCDEF x@corp.io", { repoVisibility: "public" });
expect(a).toEqual(b);
});
});
describe("redactFindingSpans — machine-egress masking (#1947)", () => {
test("clean input passes through unchanged", () => {
const text = "push failed: remote rejected the branch";
expect(redactFindingSpans(text, { repoVisibility: "private" })).toBe(text);
});
test("a single finding's span becomes <REDACTED-{id}>, context survives", () => {
const token = "ghp_" + "1234567890abcdefghijklmnopqrstuvwxyz";
const out = redactFindingSpans(`auth ${token} rejected`, { repoVisibility: "private" });
expect(out).toBe("auth <REDACTED-github.pat> rejected");
});
test("multiple findings are all replaced (right-to-left splice keeps offsets valid)", () => {
const pat = "ghp_" + "1234567890abcdefghijklmnopqrstuvwxyz";
const aws = "AKIA1234567890ABCDEF";
const out = redactFindingSpans(`first ${aws} then ${pat} end`, {
repoVisibility: "private",
});
expect(out).toBe("first <REDACTED-aws.access_key> then <REDACTED-github.pat> end");
});
test("fails closed (null) when a span cannot be relocated — never raw passthrough", () => {
// env.kv's span (the value) starts well past the regex match start (the
// var name), so locateSpan's rewind-2 re-exec misses it. The contract is
// null → caller drops the whole payload. The one thing that must never
// happen is the secret surviving in the output.
const secret = "8Fk2pQ9vXz4wL7mN3rT6yB1cD5eG0hJq";
const out = redactFindingSpans(`API_KEY=${secret}`, { repoVisibility: "private" });
if (out !== null) {
// If locateSpan ever learns to find context-prefixed spans, masking
// must actually mask.
expect(out).not.toContain(secret);
} else {
expect(out).toBeNull();
}
});
test("line/col at boundaries: line start, after blank lines, first char, last unterminated line", () => {
const token = "ghp_" + "1234567890abcdefghijklmnopqrstuvwxyz";
const at = (text: string) => {
const f = scan(text, { repoVisibility: "private" }).findings.find((x) => x.id === "github.pat");
expect(f).toBeDefined();
return [f!.line, f!.col];
};
expect(at(`a\nb\n${token} x`)).toEqual([3, 1]);
expect(at(`a\n\n\n ${token}`)).toEqual([4, 3]);
expect(at(token)).toEqual([1, 1]);
expect(at(`one\r\ntwo ${token}`)).toEqual([2, 5]);
expect(redactFindingSpans(`a\nb\n${token} x`, { repoVisibility: "private" })).toBe("a\nb\n<REDACTED-github.pat> x");
});
test("multiline input redacts a finding past the first line (locateSpan line/col path)", () => {
const token = "ghp_" + "1234567890abcdefghijklmnopqrstuvwxyz";
const out = redactFindingSpans(`line one\nline two has ${token}\nline three`, {
repoVisibility: "private",
});
expect(out).toBe("line one\nline two has <REDACTED-github.pat>\nline three");
});
// Pre-landing review CRITICAL: pem.private_key and gcp.service_account
// capture only the HEADER, not the key material — a span splice would
// redact the marker and forward the key body. Marker-only patterns must
// drop the whole payload.
test("PEM private key → null (header-only span must not forward the key body)", () => {
const msg =
"deploy failed: -----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASC\n-----END PRIVATE KEY-----";
expect(redactFindingSpans(msg, { repoVisibility: "private" })).toBeNull();
});
test("GCP service-account JSON → null (key body follows the captured marker)", () => {
const msg =
'config dump: {"private_key_id": "abc123", "private_key": "-----BEGIN PRIVATE KEY-----\\nMIIEvQIBADANBg..."}';
expect(redactFindingSpans(msg, { repoVisibility: "private" })).toBeNull();
});
// Pre-landing review: overlapping spans (a Bearer token that is also a
// JWT) must coalesce — independent splices apply stale offsets and can
// leave trailing secret bytes or mangled markers.
test("overlapping spans (Bearer JWT fires auth.bearer + jwt) never leak and produce clean markers", () => {
const jwt = "eyJ" + "a".repeat(20) + ".eyJ" + "b".repeat(20) + "." + "c".repeat(20);
const out = redactFindingSpans(`Authorization: Bearer ${jwt}`, { repoVisibility: "private" });
expect(out).not.toBeNull();
expect(out!).not.toContain("eyJ");
expect(out!).not.toContain("aaaa");
expect(out!).not.toContain("cccc");
// One coalesced, well-formed marker — no truncated fragments.
expect(out!).toMatch(/^Authorization: Bearer <REDACTED-[a-z._+]+>$/);
});
});
describe("taxonomy integrity", () => {
test("every pattern has a unique id", () => {
const set = new Set(PATTERNS.map((p) => p.id));
expect(set.size).toBe(PATTERNS.length);
});
test("autoRedactable patterns have a redactToken", () => {
for (const p of PATTERNS) {
if (p.autoRedactable) expect(p.redactToken).toBeTruthy();
}
});
});