Secrets check catches keys in JavaScript, TypeScript and Go declarations and stops flagging names, run folders and base64 noise (GST-3500) (#4869)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
Review-Finding: p1/specialist-batched#1 reader=security
Review-Finding: p1/red-team#1 reader=red-team
Review-Finding: p2/outside-voice#1 reader=outside-voice
Review-Finding: p2/outside-voice#2 reader=outside-voice
Review-Finding: p2/outside-voice#3 reader=outside-voice
Review-Finding: p2/outside-voice#4 reader=outside-voice
Review-Finding: p2/outside-voice#5 reader=outside-voice
Review-Finding: p2/outside-voice#6 reader=outside-voice
Review-Finding: p2/adversarial-native#1 reader=adversarial-native
This commit is contained in:
Garry Tanandcapy-ai[bot] authored and GitHub committed 2026-11-28 09:48:28 +00:00
1 parent 36a8ae067c
commit f7beb0a71b
8 files changed
+602 -37

No files matched your search

@@ -0,0 +1,4 @@
---
important: security
---
**The secrets check now catches keys in JavaScript, TypeScript and Go declarations, and stops flagging JSON key paths, run folders and base64 noise.** A key written as `const token = "<key>";` (or `let`, `var`, a class field, or Go's `token := "<key>"`) is now flagged when the value looks like a real key: a provider prefix such as `sk-` or `ghp_`, or long random text. A name or word as the value (`const API_KEY = "AUTHENTICATION"`) stays clean. A JSON `"key": "sources/vector-index"` field and a `20261123-1711` run folder no longer raise false alarms. A key from your environment is now also found when it appears base64-encoded, and a short `AIza…` or `sk-…` match buried deep in a long base64 blob is no longer reported. (GST-3500)
+51
View File
@@ -2068,6 +2068,57 @@ those, each with its scope and its reason:
no path in the hook), so it never reports less than before. A name too long
to write once decoded is scanned as `added` plus its extension, and a name
holding a control character is printed quoted.
- JavaScript, TypeScript and Go declarations (GST-3500): a key bound by
`const`, `let` or `var` (with or without `export` or a type), or by a class
field (`private apiKey = "<key>";`), reports as `env.kv.js` in a `.js`,
`.jsx`, `.ts`, `.tsx`, `.mjs`, `.cjs`, `.mts` or `.cts` file, and Go's
`token := "<key>"`, `var token = "<key>"` and `const apiKey string = "<key>"`
report as `env.kv.go` in a `.go` file. Names like these are everywhere in
code, so the name never decides: the literal must look like a secret. It
either starts with a provider key prefix (`sk-`, `sk_live_`, `ghp_`, `AKIA`,
`xox…-`, …) and is not a word, or it is random text: at least 16
characters, at least 3.5 bits per character (3.0 for hex such as a UUID or
digest), with a run of 8 or more letters and digits that is not a word
followed by a number. A `+` chain of quoted pieces is joined first, and a
template's text beside its `${…}` slots is read piece by piece. So
`const API_KEY = "AUTHENTICATION"`, `"MY_SERVICE_API_KEY"`,
`'CorrectHorseBatteryStaple'`, `'terminalFontSize'` and paths give nothing,
and neither do types, destructuring, imports, calls and `process.env` reads.
Known limits, not read by these rules: a low-entropy human password
(`"hunter2hunter2"`); a random token of 16 to 20 characters falls under the
bar about one time in six; a fallback after an environment read
(`process.env.TOKEN ?? "<key>"`); a declaration that does not start its
line; a value on the line after its `=`; `.vue`, `.svelte` and other files.
- JSON key paths (GBRA-108): in a `.json`, `.json5`, `.jsonc` or `.jsonl`
file, a field named exactly `"key"` whose value is a short lowercase path of
words (`"key": "sources/vector-index"` in a
check's golden output) no longer reports as `env.kv`. A secret, a long mixed
run of letters and digits, an uppercase letter in the path or another field
name still reports. An environment-variable name as a value
(`API_KEY=OPENAI_API_KEY`) still reports too: a dotenv file stores it
literally, so it may be a password; allowlist it by value.
- Run-folder stamps (TRUT-39): `pii.phone.e164` no longer reads a
`YYYYMMDD-HHMM` date and minute with a real calendar date
(`runs/20261123-1711/`) as a phone number. An impossible date (February 31),
hour or minute, and every other grouping, still reports. Known limit: a
12-digit number written as 8 digits, a dash and 4 digits that also reads as
a real date and time is not reported.
- Base64 (HARN-108): a credential from the environment is also found by its
base64 and base64url text at each of the three byte alignments (of its
normalized form and of its bytes as given), so a key inside an encoded blob,
`data:` URI or config reports as `env.value` (HIGH). Two short provider
shapes can turn up by chance in long base64: Google's `AIza…` inside
standard base64 and OpenAI's bare `sk-…` inside base64url. Such a match that
starts at least 64 characters into a 200-character run of one alphabet, where
the text before it reads as encoded data (mixed case and digits, no `=`, few
separators, so never a path or a long name), no longer reports. Keys with a
longer fixed prefix (`sk-ant-`, `sk-or-v1-`, `sk-proj-`, `AQ.`) always
report, and an exact value is still found by value. Known limits: an `AIza…`
key glued after 64 or more random-looking characters of one alphabet reads as
chance; base64 wrapped across
lines (the `base64` command's and MIME's 76-column output, PEM's 64) is
matched line by line, so an encoded value that crosses a line break is not
found.
- Known limits, still reported, allowlist them by value: a JS/TS template key
built from `${…}` slots (#4287), an array of names in source code
(`"get_token": [load_auth, "authOperations"]`), and a generic type with
+2 -2
View File
@@ -14,7 +14,7 @@ import { gitDiffInParts, mergeParts } from '../../diff-parts';
import { spawnSync } from '../../spawn-sync';
import * as fs from 'node:fs';
import * as path from 'node:path';
import { credentialEnvValues, normalizeWithMap } from '../../redact-engine';
import { base64Forms, credentialEnvValues, normalizeWithMap } from '../../redact-engine';
import { runScriptSync } from '../../script-invocation';
import { allowlistDigest, applyAllowlist, describeAllowlisted, describeMissed, describeUntested, displayPath, type AllowlistFinding } from '../allowlist';
import { baseInputs, sha256 } from '../context';
@@ -294,7 +294,7 @@ function run(ctx: PregateContext): CheckResult {
let medium = false;
let parsedAll = true;
const unsplit = new Set<string>();
const overlapChars = Math.max(SCAN_OVERLAP_CHARS, ...credentialEnvValues(ctx.env ?? process.env).map(({ value }) => normalizeWithMap(value).normalized.length));
const overlapChars = Math.max(SCAN_OVERLAP_CHARS, ...credentialEnvValues(ctx.env ?? process.env).flatMap(({ value }) => { const normalized = normalizeWithMap(value).normalized; return [normalized, ...base64Forms(normalized), ...base64Forms(value)].map((form) => form.length); }));
for (const [i, part] of parts.entries()) for (const [j, reading] of part.texts.entries()) {
const pieces = scanParts(reading, SCAN_MAX_BYTES, SCAN_OVERLAP_LINES, overlapChars);
if (!Array.isArray(pieces)) { unsplit.add(`${part.file ? `${displayPath(part.file)}, ` : ''}${part.keep ? 'line' : 'added line'} ${pieces.line} (${pieces.why})`); continue; }
+57 -30
View File
@@ -476,41 +476,46 @@ function scanInternal(input: string, opts: ScanOptions, spans?: Map<Finding, Ori
clearStringSpanCache();
// Environment values, by exact value: a credential that is already in the
// process environment needs no shape to be recognized.
// process environment needs no shape to be recognized. HARN-108: so is its
// base64 or base64url encoding at any byte alignment (a key inside an
// encoded blob, data: URI or config), of its normalized form and of its
// bytes as given, found the same way and just as HIGH.
for (const { name, value: raw } of credentialEnvValues(opts.processEnv ?? process.env)) {
// The text was normalized before matching; the value takes the same form,
// and the allowlist and placeholder rules see both forms.
const value = normalizeOriginal(raw).normalized;
if (allow.has(raw) || allow.has(value) || value.length < MIN_ENV_VALUE_LENGTH || isPlaceholderSpan(value)) continue;
let from = 0;
let normOffset: number;
while ((normOffset = normalized.indexOf(value, from)) !== -1) {
from = normOffset + value.length;
const origOffset = map[Math.min(normOffset, map.length - 1)] ?? 0;
// Keyed on the span, not the offset alone: when one credential's value is
// a prefix of another's, both findings exist and their spans coalesce.
const key = `env.value:${origOffset}:${value.length}`;
if (seen.has(key)) continue;
seen.add(key);
starts ??= lineStarts(input);
const { line, col } = lineColAt(starts, input, origOffset);
const finding: Finding = {
id: "env.value",
tier: "HIGH",
severity: "HIGH",
category: "secret",
description: `Value of the ${name} environment variable`,
line,
col,
// A live credential: the name already says what leaked; show no bytes.
preview: "********",
autoRedactable: false,
repoVisibility,
};
findings.push(finding);
if (spans) {
const end = spanEnds?.[normOffset + value.length - 1];
if (end !== undefined && end > origOffset) spans.set(finding, { start: origOffset, end });
for (const form of new Set([value, ...base64Forms(value), ...base64Forms(raw)])) {
let from = 0;
let normOffset: number;
while ((normOffset = normalized.indexOf(form, from)) !== -1) {
from = normOffset + form.length;
const origOffset = map[Math.min(normOffset, map.length - 1)] ?? 0;
// Keyed on the span, not the offset alone: when one credential's value is
// a prefix of another's, both findings exist and their spans coalesce.
const key = `env.value:${origOffset}:${form.length}`;
if (seen.has(key)) continue;
seen.add(key);
starts ??= lineStarts(input);
const { line, col } = lineColAt(starts, input, origOffset);
const finding: Finding = {
id: "env.value",
tier: "HIGH",
severity: "HIGH",
category: "secret",
description: `Value of the ${name} environment variable${form === value ? "" : ", base64-encoded"}`,
line,
col,
// A live credential: the name already says what leaked; show no bytes.
preview: "********",
autoRedactable: false,
repoVisibility,
};
findings.push(finding);
if (spans) {
const end = spanEnds?.[normOffset + form.length - 1];
if (end !== undefined && end > origOffset) spans.set(finding, { start: origOffset, end });
}
}
}
}
@@ -547,6 +552,28 @@ const MIN_ENV_VALUE_LENGTH = 8;
* leaked form; it is matched against the normalized text in its own normalized
* form, so a value NFKC rewrites still finds its leaked bytes.
*/
/**
* HARN-108: the stable base64 and base64url text of `value` at each of the
* three byte alignments it can take inside a longer encoded stream (up to six
* distinct strings). Each alignment encodes the value after 0, 1 or 2 filler
* bytes and drops the characters that also carry bits of a neighbouring byte:
* 0, 2 or 3 at the front, and the last one when the value does not end on a
* 3-byte boundary. Forms shorter than the minimum value length are dropped.
*/
const BASE64_LEAD = [0, 2, 3];
export function base64Forms(value: string): string[] {
const bytes = Buffer.from(value, "utf8");
const forms = new Set<string>();
for (const [shift, lead] of BASE64_LEAD.entries()) {
const encoded = Buffer.concat([Buffer.alloc(shift), bytes]).toString("base64").replace(/=+$/, "");
const core = encoded.slice(lead, encoded.length - ((shift + bytes.length) % 3 === 0 ? 0 : 1));
if (core.length < MIN_ENV_VALUE_LENGTH) continue;
forms.add(core);
forms.add(core.replace(/\+/g, "-").replace(/\//g, "_"));
}
return [...forms];
}
export function credentialEnvValues(env: Record<string, string | undefined>): Array<{ name: string; value: string }> {
const out: Array<{ name: string; value: string }> = [];
for (const [name, raw] of Object.entries(env)) {
+185 -2
View File
@@ -227,6 +227,57 @@ function looksLikeCompactTimestamp(span: string): boolean {
);
}
/**
* TRUT-39 (truther#1231): a run folder named by date and minute
* (`20261123-1711`, YYYYMMDD-HHMM) reads as an 8-4 digit phone number.
* Only that exact shape with a real calendar date, hour and minute from the
* years 1900-2099 is exempt; a phone number written 8-4 is not a national
* format, and every other grouping, a `+` or any separator but one `-`
* still reports.
*/
const RUN_STAMP = /^(?:19|20)\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])-(?:[01]\d|2[0-3])[0-5]\d$/;
export function looksLikeRunStamp(span: string): boolean {
if (!RUN_STAMP.test(span)) return false;
const [year, month, day] = [span.slice(0, 4), span.slice(4, 6), span.slice(6, 8)].map(Number);
return new Date(Date.UTC(year!, month! - 1, day!)).getUTCDate() === day;
}
/**
* HARN-108: two provider shapes are short enough to turn up by chance inside
* long base64 text (a data: URI, an encoded blob or session): Google's
* `AIza` + 35 characters inside standard base64, and OpenAI's bare `sk-` + 32
* or more letters and digits inside base64url. Only those two call this; a
* longer fixed prefix (`sk-ant-api03-`, `sk-or-v1-`, `sk-proj-`, Google's
* `AQ.`) cannot occur by chance and always reports. A match is chance when it
* starts at least 64 characters into a run of 200 or more characters of one
* alphabet (standard `+` and `/` for `AIza`, url-safe `-` and `_` for
* `sk-`), the 64 or more characters before it hold an uppercase letter, a
* lowercase letter and a digit with no `=` (padding only ends a run), and at
* most one in 16 of them is a `+`, `/`, `-` or `_`, so a path or a long
* name (`MY_LONG_SERVICE_..._KEY_V2=`, `/v1/Projects/Abc123/...`) never
* qualifies. A known secret's exact value, base64 forms included, is found by
* value in redact-engine whatever surrounds it. The scan looks at most 200
* characters each way, so it stays linear.
*/
const BASE64_STANDARD = /[A-Za-z0-9+/]/;
const BASE64_URL = /[A-Za-z0-9_-]/;
const BASE64_RUN_MIN = 200;
const BASE64_DEPTH_MIN = 64;
function chanceMatchInBase64(match: RegExpExecArray): boolean {
const { start, end } = spanBounds(match);
const text = match.input;
const alphabet = text.startsWith("sk-", start) ? BASE64_URL : BASE64_STANDARD;
let before = 0;
while (before < BASE64_RUN_MIN && start - before > 0 && alphabet.test(text[start - before - 1]!)) before++;
if (before < BASE64_DEPTH_MIN) return false;
const lead = text.slice(start - before, start);
if (!/[A-Z]/.test(lead) || !/[a-z]/.test(lead) || !/\d/.test(lead)) return false;
if (lead.replace(/[A-Za-z0-9]/g, "").length * 16 > lead.length) return false;
let after = 0;
while (before + (end - start) + after < BASE64_RUN_MIN && end + after < text.length && alphabet.test(text[end + after]!)) after++;
return before + (end - start) + after >= BASE64_RUN_MIN;
}
/**
* Bare integers that programs print as constants: 2^30 through 2^49 and each
* one minus one (`4294967296`, `2147483647`), and the 32-bit multipliers,
@@ -1137,6 +1188,8 @@ function isSourceExpression(span: string, match: RegExpExecArray, sourcePath: st
* Another file, a scan without a path, a comment and a `/` start are unchanged.
*/
const RUST_SOURCE = /\.rs$/i;
const JS_SOURCE = /\.[cm]?[jt]sx?$/i;
const GO_SOURCE = /\.go$/i;
const RUST_TYPE_TOKEN = /[ \t]+|::|->|=>|'[A-Za-z_]\w*|[A-Za-z_]\w*|\d+|[&*<>()[\]{},;:+?!|]/y;
const RUST_LOWERCASE_TYPE = /^(?:[iu](?:8|16|32|64|128|size)|f32|f64|bool|char|str|dyn|impl|fn|mut|const|unsafe|extern|for|self|crate|super)$/;
function readsAsRustName(name: string): boolean {
@@ -1226,6 +1279,82 @@ function holdsSecretText(text: string): boolean {
return isSecretRun(text.replace(/\s+/g, ""));
}
/**
* GST-3500: a value shaped like a secret, judged on the value alone, for
* rules whose name match is too common to carry any weight (a JS/TS or Go
* declaration, a JSON `"key"` field). It either starts with a provider key
* prefix and is a secret run by isSecretRun (`sk-…`, `ghp_…`, `AKIA…`), or
* it is random text: at least 16 characters, at least 3.5 bits per
* character, holding a run of 8 or more letters and digits, with a digit and
* two letters, that is not a word followed or led by a number (`OAUTH2`,
* `v2024`).
* Hex text (a digest, a UUID with its dashes removed) is judged at 3.0 bits:
* its alphabet caps it at 4, and a random 32-digit hex string falls under 3.5
* about one time in five.
* A CONSTANT_CASE or camelCase name, a letters-only passphrase, a lowercase
* path and a placeholder never qualify; neither does a low-entropy human
* password, on purpose.
*/
const KNOWN_SECRET_PREFIX =
/^(?:sk-|sk_live_|rk_live_|pk_live_|sb_secret_|sbp_|gh[pousr]_|github_pat_|gl(?:pat|ptt|dt)-|gsk_|tvly-|ntn_|secret_|hf_|npm_|dop_v1_|AKIA|ASIA|xox[baprs]-|AIza|AQ\.|SG\.|GOCSPX-|eyJ)/;
const RANDOM_TEXT_MIN_LENGTH = 16;
const RANDOM_TEXT_MIN_BITS = 3.5;
const HEX_TEXT = /^[0-9a-f]+(?:-[0-9a-f]+)*$/i;
const HEX_TEXT_MIN_BITS = 3.0;
function isRandomRun(run: string): boolean {
const digits = run.replace(/\D/g, "").length;
return digits >= 1 && run.length - digits >= 2 && !/^(?:[A-Za-z]+\d+|\d+[A-Za-z]+)$/.test(run);
}
export function isSecretShapedValue(value: string): boolean {
if (isPlaceholderSpan(value)) return false;
if (KNOWN_SECRET_PREFIX.test(value) && isSecretRun(value)) return true;
if (value.length < RANDOM_TEXT_MIN_LENGTH || !(value.match(/[A-Za-z0-9]{8,}/g) ?? []).some(isRandomRun)) return false;
return HEX_TEXT.test(value) ? shannonEntropy(value.replace(/-/g, "")) >= HEX_TEXT_MIN_BITS : shannonEntropy(value) >= RANDOM_TEXT_MIN_BITS;
}
/**
* GST-3500: the literal a JS/TS or Go declaration assigns, read whole and
* judged by isSecretShapedValue: a `+` chain of quoted pieces is joined
* (concatenationHoldsSecret), a quoted literal is read to its closing quote
* on the line, and a template literal's static text beside its `${…}` slots
* is read piece by piece. Each candidate is split at whitespace first, since
* no key holds a space.
*/
const TEMPLATE_TEXT_BREAK = /[\s"'=:,;(){}[\]|@]+/;
function declaredLiteralIsSecret(span: string, match: RegExpExecArray): boolean {
if (concatenationHoldsSecret(match, isSecretShapedValue)) return true;
const { start } = spanBounds(match);
const line = match.input.slice(start - 1).split("\n", 1)[0]!;
if (line[0] === "\x60") {
const close = line.indexOf("\x60", 1);
const body = close < 0 ? line.slice(1) : line.slice(1, close);
return body.split(/\$\{[^}]*\}/).some((text) => text.split(TEMPLATE_TEXT_BREAK).some(isSecretShapedValue));
}
const literal = line[0] === '"' || line[0] === "'" ? (quotedAt(line, 0)?.text ?? span) : span;
return literal.split(/\s+/).some(isSecretShapedValue);
}
/**
* GBRA-108: in a .json, .json5, .jsonc or .jsonl file, a field named exactly `"key"` whose value is a short
* lowercase path of words (`"key": "sources/vector-index"`,
* `"key": "config/embedding_model"` in a check's golden output) names a
* setting, not a credential. Every `/`, `_`, `.` or `-` separated word is
* letters only or at most four characters (`v2`, `e2e`), the value holds a
* `/` and is at most 120 characters, and it is not secret-shaped. Any other
* name, quoting, an uppercase letter, a long mixed run of letters and digits
* (`sources/x7k2m9q4`), a key prefix (`"key": "sk-…"`), another file type or
* a scan without a path is checked as before.
*/
const JSON_KEY_FIELD = /"key"[ \t]*:[ \t]*"$/;
const JSON_SOURCE = /\.json[5cl]?$/i;
const LOWERCASE_KEY_PATH = /^[a-z][a-z0-9]*(?:[/_.-][a-z0-9]+)*$/;
function isJsonKeyPath(span: string, match: RegExpExecArray, sourcePath: string | undefined): boolean {
if (!sourcePath || !JSON_SOURCE.test(sourcePath) || span.length > 120 || !span.includes("/") || !LOWERCASE_KEY_PATH.test(span)) return false;
if (!span.split(/[/_.-]/).every((word) => /^[a-z]+$/.test(word) || word.length <= 4)) return false;
const { start, end } = spanBounds(match);
return JSON_KEY_FIELD.test(match.input.slice(match.index, start)) && match.input[end] === '"' && !isSecretShapedValue(span);
}
/** The text of the `"…"` or `'…'` literal whose quote is at `i` and the index after it, or null when it does not close on the line. */
function quotedAt(line: string, i: number): { text: string; end: number } | null {
for (let j = i + 1; j < line.length; j += line[j] === "\\" ? 2 : 1) if (line[j] === line[i]) return { text: line.slice(i + 1, j), end: j + 1 };
@@ -1242,7 +1371,7 @@ function quotedAt(line: string, i: number): { text: string; end: number } | null
*/
const CHAIN_NAME = /[A-Za-z_$][\w$]*(?:\??\.[A-Za-z_$][\w$]*)*/y;
const CHAIN_PLUS = /[ \t]*\+[ \t]*/y;
function concatenationHoldsSecret(match: RegExpExecArray): boolean {
function concatenationHoldsSecret(match: RegExpExecArray, holdsSecret: (text: string) => boolean = holdsSecretText): boolean {
const { start } = spanBounds(match);
const line = match.input.slice(/["']/.test(match.input[start - 1] ?? "") ? start - 1 : start).split("\n", 1)[0]!;
let joined = "";
@@ -1256,7 +1385,7 @@ function concatenationHoldsSecret(match: RegExpExecArray): boolean {
CHAIN_PLUS.lastIndex = literal ? literal.end : CHAIN_NAME.lastIndex;
if (!CHAIN_PLUS.exec(line)) break;
}
return pieces > 1 && holdsSecretText(joined);
return pieces > 1 && holdsSecret(joined);
}
/**
@@ -1603,6 +1732,7 @@ export const PATTERNS: RedactPattern[] = [
// bare: sk- + contiguous alphanumeric run (legacy), keeps {32,} floor
regex:
/\b(sk-(?:proj|svcacct|admin)-[A-Za-z0-9_-]{20,}|sk-[A-Za-z0-9]{32,})\b/,
validate: (span, match) => !(/^sk-[A-Za-z0-9]+$/.test(span) && chanceMatchInBase64(match)),
},
{
id: "openrouter.key",
@@ -1736,6 +1866,7 @@ export const PATTERNS: RedactPattern[] = [
category: "secret",
description: "Google API key (AIza… or AQ.…; sometimes a public client key)",
regex: /\b(AIza[0-9A-Za-z\-_]{35}|AQ\.[0-9A-Za-z\-_]{20,})\b/,
validate: (span, match) => !(span.startsWith("AIza") && chanceMatchInBase64(match)),
},
{
id: "jwt",
@@ -1799,6 +1930,7 @@ export const PATTERNS: RedactPattern[] = [
// GST-3474: so is a Rust type annotation or match-arm path (isRustTypeAnnotation).
// #3208: so is a schema field identifier (isSchemaFieldIdentifier).
// GST-1894: so is a self-named fixture label in a test file (isTestFixtureLabel).
// GBRA-108: so is a JSON "key" field's lowercase path (isJsonKeyPath).
// GST-3004: so is a dotted field path (isDottedFieldPath, #4289), and so
// is key-naming text in a comment
// (isCommentText). GST-3297: so is a regex literal's body after its
@@ -1820,6 +1952,7 @@ export const PATTERNS: RedactPattern[] = [
!isRegexLiteralBody(span, match) &&
!isSchemaFieldIdentifier(span, match) &&
!isTestFixtureLabel(span, opts?.sourcePath) &&
!isJsonKeyPath(span, match, opts?.sourcePath) &&
shannonEntropy(span) >= 3.0)),
},
{
@@ -1848,6 +1981,55 @@ export const PATTERNS: RedactPattern[] = [
return !!name && isCredentialShapedEnvName(`${name}=`) && !isPlaceholderSpan(span) && !/^\$\{?[A-Za-z_]/.test(span) && shannonEntropy(span) >= 3.0;
},
},
{
id: "env.kv.js",
tier: "MEDIUM",
category: "secret",
description: "Secret-named JS/TS const, let, var or class field holding a secret-shaped string literal",
// GST-3500: env.kv needs the name to start its line, so a key bound by a
// JavaScript or TypeScript declaration (`const token = "<key>";`,
// `export let API_KEY = '<key>'`) or a class field (`private apiKey =
// "<key>";`) gave no finding. This rule reads one to four of `declare`,
// `public`, `private`, `protected`, `static`, `readonly`, `override`,
// `accessor`, `const`, `let` and `var` (after an optional `export`),
// an optional `#` private name, a secret-named name with an optional
// `?`/`!` and type (which stops at `;`, so the value belongs to the same
// declaration), then `=` and a quoted or template literal (an empty
// first piece of a `+` chain and leading spaces are read past), at a line
// start (diff markers as env.kv) or after `//` or `/*`. A name with no
// keyword is left to env.kv, so no line reports twice. Names like these
// are everywhere in code, so the name never decides: the literal must be
// secret-shaped (declaredLiteralIsSecret), which leaves key names, paths,
// environment-variable names and words as values clean without a list of
// exemptions. It is its own pattern so env.kv's matches are unchanged,
// and validate keeps it to .js, .jsx, .ts, .tsx, .mjs, .cjs, .mts and .cts
// files; a scan without a path is env.kv.rust's.
regex: /(?:^(?:[ +-]?\+|[ +-]?-(?! [^ \t]))?|(?<=(?:^|[ \t])(?:\/{2,3}|\/\*{1,2})))[ \t]*(?:export[ \t]+)?(?:(?:declare|public|private|protected|static|readonly|override|accessor|const|let|var)[ \t]+){1,4}#?[$\w]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIALS?|DSN|AUTH|COOKIE|SESSION|PRIVATE)[?!]?(?:[ \t]*:[^=;\n]{1,120}?)?[ \t]*=[ \t]*["'\x60]((?:["'\x60][ \t]*\+[ \t]*["'\x60]|[ \t]+)?[^\s'"\x60\\]{8,}|[^\s'"\x60\\]{1,7}(?=["'\x60]?[ \t]*\+))/i,
validate: (span, match, opts) => {
if (!opts?.sourcePath || !JS_SOURCE.test(opts.sourcePath)) return false;
const name = /([$\w]+)[?!]?[ \t]*(?::[^=;\n]*)?=/.exec(match[0])?.[1]?.replace(/\$/g, "");
return !!name && isCredentialShapedEnvName(`${name}=`) && declaredLiteralIsSecret(span, match);
},
},
{
id: "env.kv.go",
tier: "MEDIUM",
category: "secret",
description: "Secret-named Go var, const or := binding holding a secret-shaped string literal",
// GST-3500 coverage matrix (gbrain #10028): env.kv reads `token = "<key>"`
// but not Go's `token := "<key>"`, `var token = "<key>"` or
// `const apiKey string = "<key>"`. This rule reads those three forms, with
// an optional type after a `var` or `const` name, and a quoted or raw
// string literal, at a line start (diff markers as env.kv) or after `//`
// or `/*`. As in env.kv.js, the literal must be secret-shaped
// (declaredLiteralIsSecret); validate keeps it to .go files.
regex: /(?:^(?:[ +-]?\+|[ +-]?-(?! [^ \t]))?|(?<=(?:^|[ \t])(?:\/{2,3}|\/\*{1,2})))[ \t]*(?:(?:var|const)[ \t]+\w*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIALS?|DSN|AUTH|COOKIE|SESSION|PRIVATE)(?:[ \t]+[\w.*[\]]{1,60})?[ \t]*=|\w*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIALS?|DSN|AUTH|COOKIE|SESSION|PRIVATE)[ \t]*:=)[ \t]*["\x60]((?:["\x60][ \t]*\+[ \t]*["\x60]|[ \t]+)?[^\s"\x60\\]{8,}|[^\s"\x60\\]{1,7}(?=["\x60]?[ \t]*\+))/i,
validate: (span, match, opts) => {
if (!opts?.sourcePath || !GO_SOURCE.test(opts.sourcePath)) return false;
const name = /(?:\b(?:var|const)[ \t]+)?(\w+)(?:[ \t]+[\w.*[\]]+)?[ \t]*:?=/i.exec(match[0])?.[1];
return !!name && isCredentialShapedEnvName(`${name}=`) && declaredLiteralIsSecret(span, match);
},
},
{
id: "auth.bearer",
tier: "MEDIUM",
@@ -1897,6 +2079,7 @@ export const PATTERNS: RedactPattern[] = [
!insideUuid(match) &&
span.replace(/\D/g, "").length >= 10 &&
!looksLikeCompactTimestamp(span) &&
!looksLikeRunStamp(span) &&
!isNumericConstant(span) &&
!looksLikeParcelId(span, match) &&
!looksLikeDecimalCoordinates(span) &&
@@ -109,6 +109,18 @@ describe('pregate secrets: source context and diff integrity', () => {
expect({ status: r.status, rows: r.lines.filter((l) => l.includes('env.kv.rust')).sort() }).toEqual({ status: 'fail', rows: [expect.stringContaining('(src/clé.rs, added line 2)'), expect.stringContaining('(src/my file.rs, added line 2)')] });
}, 60_000);
// Value: protects=pregate's secrets check fails a secret-shaped key bound by a TS const or class field and passes names, words and JSON key paths
// as values; fails_when=a JS/TS declaration of a key passes the push check, or a name-valued declaration, a JSON "key" path or a run-folder stamp blocks it;
// why_new=GST-3500, GBRA-108, TRUT-39; seam=fixture repo; no_claim=other languages, covered in redact-secret-shaped-values.test.ts
test('a secret-shaped key bound by a TS const or class field fails; names, words, JSON key paths and run stamps pass (GST-3500)', () => {
const secret = ['sk-live-', 'Qx9vL2mZ', 'p8Rt4Kw7', 'Yn3Bh2Jd'].join('');
const ts = 'import { API_KEY } from "./config";\nconst { token } = await auth();\nlet apiKey: string;\nconst API_TOKEN = "AUTHENTICATION"; process.env[API_TOKEN];\nexport const MODE_KEY = "transcript_ingest_mode";\n';
const clean = { 'src/client.ts': ts, 'test/fixtures/doctor.json': '[\n { "key": "sources/vector-index", "ok": true },\n { "key": "config/embedding_model", "ok": true }\n]\n', 'runs.md': 'See runs/20261123-1711/report.md\n' };
expect(repo(clean).secrets()).toMatchObject({ status: 'pass', lines: [] });
const r = repo({ 'src/client.ts': ts + 'export const API_SECRET = "' + secret + '";\nclass Client {\n private apiKey = "' + secret + '";\n}\n' }).secrets();
expect({ status: r.status, rows: r.lines.filter((l) => l.includes('env.kv')).sort() }).toEqual({ status: 'fail', rows: [expect.stringContaining('(src/client.ts, added line 6)'), expect.stringContaining('(src/client.ts, added line 8)')] });
}, 60_000);
test('a Python call that reads key.json is code; the same key name holding a literal key still fails (GST-1064)', () => {
expect(repo({ 'attach.py': 'import json\nkey = json.loads(files.get("key.json", ""))\n' }).secrets().status).toBe('pass');
const fake = 'Zx9Q' + 'w8Er7Ty6Ui5Op4As3Df2';
+7 -3
View File
@@ -52,6 +52,8 @@ const SAMPLES: Record<string, string> = {
"jwt": ["eyJhbGciOiJIUzI1NiJ9", "eyJzdWIiOiIxMjM0NTY3ODkwIn0", "dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U"].join("."),
"env.kv": j("API_TOKEN=", "8Fk2pQ9vXz4wL7mN3rT6yB1cD5eG0hJ"),
"env.kv.rust": j('let api_token = "', "8Fk2pQ9vXz4wL7mN3rT6yB1cD5eG0hJ", '";'),
"env.kv.js": j('const api_token = "', "8Fk2pQ9vXz4wL7mN3rT6yB1cD5eG0hJ", '";'),
"env.kv.go": j('api_token := "', "8Fk2pQ9vXz4wL7mN3rT6yB1cD5eG0hJ", '"'),
"auth.bearer": j("Authorization: Bearer ", "a1B2c3D4e5F6g7H8i9J0k1L2"),
"pii.email": j("dana.whitfield@", "acmecorp.io"),
"pii.phone.e164": j("+1415", "5552671"),
@@ -67,13 +69,15 @@ const SAMPLES: Record<string, string> = {
"hygiene.todo": j("TO", "DO(dana)"),
};
const ids = (text: string) => scan(text, { repoVisibility: "public", processEnv: {} }).findings.map((f) => f.id);
const ids = (text: string, sourcePath?: string) => scan(text, { repoVisibility: "public", processEnv: {}, ...(sourcePath ? { sourcePath } : {}) }).findings.map((f) => f.id);
/** A pattern that reads only one language's files gets its sample under that file type. */
const SAMPLE_PATHS: Record<string, string> = { "env.kv.js": "src/config.ts", "env.kv.go": "cmd/config.go" };
const hunk = (body: string) => ["diff --git a/x b/x", "--- a/x", "+++ b/x", "@@ -0,0 +1 @@", body, ""].join("\n");
describe("GST-543: a diff line prefix never hides a finding", () => {
test("every pattern has a sample that reports bare", () => {
expect(PATTERNS.map((p) => p.id).filter((id) => !SAMPLES[id])).toEqual([]);
expect(PATTERNS.filter((p) => !ids(SAMPLES[p.id]!).includes(p.id)).map((p) => p.id)).toEqual([]);
expect(PATTERNS.filter((p) => !ids(SAMPLES[p.id]!, SAMPLE_PATHS[p.id]).includes(p.id)).map((p) => p.id)).toEqual([]);
});
test("each sample still reports behind +, - and a space, and on an added line inside a hunk", () => {
@@ -81,7 +85,7 @@ describe("GST-543: a diff line prefix never hides a finding", () => {
for (const p of PATTERNS) {
const s = SAMPLES[p.id]!;
for (const [label, text] of [["+", "+" + s], ["-", "-" + s], ["space", " " + s], ["hunk", hunk("+" + s)], ["indented hunk", hunk("+ " + s)], ["indented removed", hunk("- " + s)], ["tab removed", hunk("-\t" + s)], ["combined ++", hunk("++" + s)], ["combined space+", hunk(" + " + s)], ["combined +-", hunk("+-" + s)]] as const)
if (!ids(text).includes(p.id)) missed.push(`${p.id} (${label})`);
if (!ids(text, SAMPLE_PATHS[p.id]).includes(p.id)) missed.push(`${p.id} (${label})`);
}
expect(missed).toEqual([]);
});
+284
View File
@@ -0,0 +1,284 @@
/**
* GST-3500 redesign of the secrets scan's declaration rules, plus three
* false-positive and miss reports gathered on the same issue:
*
* - JS/TS and Go declarations (`const token = "<key>"`, `token := "<key>"`)
* gave no finding. They now report as env.kv.js and env.kv.go, but only
* when the literal is secret-shaped (a provider key prefix, or random
* text: 16+ characters, 3.5+ bits, a mixed run of letters and digits).
* The name alone never reports, so key names, environment-variable names,
* paths and words as values stay clean.
* - GBRA-108: env.kv read a JSON `"key": "sources/vector-index"` field as a
* credential. (GEVA-561's environment-variable name as a value,
* `API_KEY=OPENAI_API_KEY`, still reports: a dotenv line stores it
* literally, so it could be a password.)
* - TRUT-39: the phone rule read a YYYYMMDD-HHMM run folder as a number.
* - HARN-108: a known secret's base64 form was never found by value, and
* `AIza…`/`sk-…` matched by chance deep inside long base64 blobs.
*/
// Value: protects=secret-shaped JS/TS and Go declarations report while names-as-values stay clean, JSON "key" paths and run-folder stamps stop reporting, and a known secret's base64 forms report HIGH; fails_when=a declaration miss returns, a word or name value reports, an exemption swallows a real secret, a base64-encoded key goes unfound, or a chance AIza/sk- match deep in a blob reports; why_new=GST-3500, GBRA-108, GEVA-561, TRUT-39 and HARN-108 had no cases; seam=none; no_claim=scanner-level only, the pregate case lives in pregate-secrets-source-context.test.ts
import { describe, expect, test } from "bun:test";
import { base64Forms, scan } from "../lib/redact-engine";
import { isSecretShapedValue, looksLikeRunStamp } from "../lib/redact-patterns";
const ids = (text: string, sourcePath?: string, processEnv: Record<string, string> = {}) =>
scan(text, { repoVisibility: "private", processEnv, ...(sourcePath ? { sourcePath } : {}) }).findings.map((f) => f.id);
const j = (...parts: string[]) => parts.join("");
const S = j("Qx9vL2mZ", "p8Rt4Kw7", "Yn3Bh2Jd");
const SK = j("sk-", "live-", "Qx9vL2mZp8", "Rt4Kw7Yn3B");
const UUID = j("ef41947a-643b-", "4494-aaee-", "149f288a9b29");
const HEX = j("9f8e7d6c5b4a3928", "1706f5e4d3c2b1a0");
const GHP = j("ghp_", "a1B2c3D4e5F6g7H8i9J0", "k1L2m3N4o5P6q7R8");
const BT = "\x60";
const has = (id: string, cases: ReadonlyArray<readonly [string, string | undefined]>, want: boolean) => {
for (const [code, file] of cases) expect({ code, file, hit: ids(code, file).includes(id) }).toEqual({ code, file, hit: want });
};
describe("isSecretShapedValue: the value decides, never the name (GST-3500)", () => {
test("provider prefixes, UUIDs, hex and mixed random runs are secret-shaped", () => {
for (const v of [S, SK, UUID, HEX, GHP, S.toUpperCase(), S.toLowerCase(), j("AKIA", "ZQ3XN7P2LM4RT8WV")])
expect({ v, shaped: isSecretShapedValue(v) }).toEqual({ v, shaped: true });
});
test("words, names, paths, placeholders and short or low-entropy text are not", () => {
for (const v of ["AUTHENTICATION", "PRODUCTION", "CORRECT_HORSE_BATTERY_STAPLE", "CorrectHorseBatteryStaple", "MY_SERVICE_API_KEY", "OAUTH2_SESSION_TOKEN", "agent_model", "terminalFontSize", "test/skill-e2e-plan.test.ts#plan-ceo-review", "e6-multiblock-sentinel", "sources/vector-index", "changeme", "your-api-key-here", "hunter2hunter2", "sk-abcdefgh", "v2024-release-notes", "123e4567-e89b-12d3-a456-426614174000"])
expect({ v, shaped: isSecretShapedValue(v) }).toEqual({ v, shaped: false });
});
});
describe("env.kv.js: a secret-shaped literal bound by a JS/TS declaration reports (GST-3500)", () => {
test("const, let, var, export, typed, template, class-field and + chain forms report", () => {
has("env.kv.js", [
['const token = "' + SK + '";', "src/client.ts"],
["const token = '" + UUID + "';", "src/client.js"],
['let apiKey = "' + HEX + '";', "src/client.tsx"],
['var secret = "' + S + '";', "lib/legacy.cjs"],
['export const API_KEY = "' + S + '";', "src/config.mjs"],
['export let clientSecret = "' + GHP + '";', "src/config.mts"],
['const apiKey: string = "' + S + '";', "src/config.ts"],
['const API_KEY = "' + S.toUpperCase() + '";', "src/config.ts"],
["const authToken = " + BT + S + BT + ";", "src/config.jsx"],
[' private apiKey = "' + S + '";', "src/client.ts"],
[' static readonly ACCESS_TOKEN: string = "' + S + '";', "src/client.ts"],
[' private #password = "' + S + '";', "src/client.js"],
["const token = " + BT + S + "${suffix}" + BT + ";", "src/client.ts"],
["const token = " + BT + "${prefix}-" + S + BT + ";", "src/client.ts"],
['const API_KEY = "' + S + '" as const;', "src/config.cts"],
['// const token = "' + S + '";', "src/client.ts"],
['const token = "sk_live_" + "' + S + '";', "src/client.ts"],
['const token = "ab" + "' + S + '";', "src/client.ts"],
['const token = "" + "' + S + '";', "src/client.ts"],
['const token = " ' + S + '";', "src/client.ts"],
['diff --git a/src/a.ts b/src/a.ts\n+++ b/src/a.ts\n@@ -0,0 +1 @@\n+const token = "' + S + '";\n', "src/a.ts"],
], true);
});
test("names, words and paths as values give no finding, however credential-shaped the name", () => {
has("env.kv.js", [
['const API_KEY = "AUTHENTICATION"; process.env[API_KEY];', "src/client.ts"],
['const token = "PRODUCTION";', "src/client.ts"],
['const password = "CORRECT_HORSE_BATTERY_STAPLE";', "src/client.ts"],
["const secret = 'CorrectHorseBatteryStaple';", "src/client.ts"],
['const API_KEY = "MY_SERVICE_API_KEY"; process.env[API_KEY];', "src/client.ts"],
['export const SESSION_KEY = "OAUTH2_SESSION_TOKEN";', "src/config.ts"],
["export const MODE_KEY = 'transcript_ingest_mode';", "lib/consent.ts"],
["export const VISIBILITY_OVERRIDE_KEY = 'sealed.visibility';", "lib/guard.ts"],
["const FONT_SIZE_KEY = 'terminalFontSize';", "extension/panel.js"],
["const key = 'test/skill-e2e-plan.test.ts#plan-ceo-review';", "test/shards.ts"],
["export const MULTIBLOCK_SENTINEL_KEY = 'e6-multiblock-sentinel';", "test/helpers/multiblock.ts"],
["const key = 'sekrit-ubi-key-4711';", "src/client.ts"],
['let session: string; const mode = "BILLING_DASHBOARD";', "src/client.ts"],
["const authToken = 'route-table-' + suffix;", "src/routes.ts"],
["const secret = " + BT + 'LINKEDIN_CLIENT_SECRET="${value}"' + BT + ";", "src/ingest.ts"],
], false);
});
test("type annotations, destructuring, imports, calls, environment reads and placeholders give no finding", () => {
has("env.kv.js", [
["let token: string;", "src/client.ts"],
["const token: string = getToken();", "src/client.ts"],
["const { token } = await auth();", "src/client.ts"],
["const { apiKey = defaultKey } = options;", "src/client.ts"],
['const [apiKey, setApiKey] = useState("");', "src/App.tsx"],
['import { API_KEY } from "./config";', "src/client.ts"],
['import token from "./token";', "src/client.ts"],
["const token = process.env.API_TOKEN;", "src/client.ts"],
['const token = "changeme";', "src/client.ts"],
['const token = "${API_TOKEN}";', "src/client.ts"],
["const token = " + BT + "Bearer ${jwt}" + BT + ";", "src/client.ts"],
['const monkey = "' + S + '";', "src/client.ts"],
['const tokenCount = "' + S + '";', "src/client.ts"],
["private apiKey: string;", "src/client.ts"],
], false);
});
test("gives up on purpose: a low-entropy human password in a declaration is not read", () => {
has("env.kv.js", [['const password = "hunter2hunter2";', "src/client.ts"]], false);
});
test("scoped to JS/TS: other files and scans without a path are not read by this rule", () => {
has("env.kv.js", [
['const token = "' + S + '";', "src/lib.rs"],
['const token = "' + S + '";', "app/client.py"],
['const token = "' + S + '";', "docs/setup.md"],
['const token = "' + S + '";', undefined],
], false);
});
test("hold: lines env.kv reports today still report", () => {
has("env.kv", [
[' apiKey: "' + S + '",', "src/client.ts"],
["API_KEY=" + S, ".env"],
['const a = 1; // apiKey: "' + S + '"', "src/client.ts"],
[' #password = "' + S + '";', "src/client.js"],
], true);
});
});
describe("coverage matrix for non-JS assignments (gbrain #10028)", () => {
test("Rust let, Go :=, var and const, Python and YAML assignments report", () => {
has("env.kv.rust", [['let token = "' + SK + '";', "src/main.rs"]], true);
has("env.kv.go", [
['token := "' + S + '"', "cmd/main.go"],
['\tapiToken := "' + SK + '"', "cmd/main.go"],
['var secret = "' + HEX + '"', "cmd/main.go"],
['const apiKey string = "' + S + '"', "cmd/main.go"],
['token := "" + "' + S + '"', "cmd/main.go"],
["\tpassword := " + BT + S + BT, "cmd/main.go"],
], true);
has("env.kv", [['token = "' + S + '"', "app/settings.py"], ["token: " + S, "config/app.yaml"]], true);
});
test("Go declarations without a secret-shaped literal, and other files, give no env.kv.go finding", () => {
has("env.kv.go", [
['token := os.Getenv("API_TOKEN")', "cmd/main.go"],
['token := "PRODUCTION"', "cmd/main.go"],
["var token string", "cmd/main.go"],
['token := ""', "cmd/main.go"],
['const tokenHeader = "X-Session-Token"', "cmd/main.go"],
['token := "' + S + '"', "src/client.ts"],
['token := "' + S + '"', undefined],
], false);
});
});
describe("env.kv: a JSON key path is a name; an environment-variable name as a value still reports (GBRA-108, GEVA-561)", () => {
test("a JSON \"key\" field holding a short lowercase path gives no finding", () => {
has("env.kv", [
['"key": "sources/vector-index",', "test/fixtures/doctor.json"],
[' "key": "config/embedding_model",', "test/goldens/doctor.json"],
[' "key": "sources/foo"', "data/sources.jsonl"],
[' { "key": "checks/e2e/doctor", "ok": true }', "golden.json"],
], false);
});
test("a secret under \"key\", a mixed run, an uppercase path or another name still reports", () => {
has("env.kv", [
['"key": "' + SK + '",', "test/fixtures/doctor.json"],
['"key": "' + S + '",', "test/fixtures/doctor.json"],
['"key": "sources/' + S.toLowerCase() + '",', "test/fixtures/doctor.json"],
['"key": "sources/x7k2m9q4",', "test/fixtures/doctor.json"],
['"key": "Sources/VectorIndex9",', "test/fixtures/doctor.json"],
['"api_key": "sources/vector-index",', "test/fixtures/doctor.json"],
['"key": "sources/vector-index",', "src/config.ts"],
['"key": "sources/vector-index",', undefined],
], true);
});
test("hold: an environment-variable name as a value, quoted or not, still reports, as does a secret", () => {
has("env.kv", [["API_KEY=OPENAI_API_KEY", ".env"], ["token: GITHUB_TOKEN", "config/ci.yaml"], [" token: DAEMON_TOKEN,", undefined], ["API_KEY=" + S.toUpperCase(), ".env"], ["API_KEY=QX9V_L2MZ_P8RT_API_KEY", ".env"], ["API_KEY=OPENAI_API_KEY_" + S, ".env"], ["OPENAI_API_KEY: 'ANOTHER_SECRET',", "test/codex.test.ts"], ['"apiKey": "ANTHROPIC_API_KEY",', "config.json"]], true);
});
});
describe("pii.phone.e164: a YYYYMMDD-HHMM run folder is a date, not a phone number (TRUT-39)", () => {
test("valid run stamps give no finding", () => {
for (const text of ["runs/20261123-1711/report.md", "20261123-1711", "out/20251231-2359-retry", "19990101-0000"])
expect({ text, phone: ids(text, "notes.md").includes("pii.phone.e164") }).toEqual({ text, phone: false });
expect(looksLikeRunStamp("20261123-1711")).toBe(true);
});
test("phone numbers and invalid stamps still report", () => {
for (const text of [j("call +1 415-", "555-0123"), j("415-555", "-0123"), j("+44 20 ", "7946 0958"), j("20261323", "-1711"), j("20261123", "-2471"), j("20261132", "-1711"), j("30261123", "-1711"), j("20260231", "-1711"), j("20250229", "-0900")])
expect({ text, phone: ids(text, "notes.md").includes("pii.phone.e164") }).toEqual({ text, phone: true });
expect(looksLikeRunStamp(j("20261123", "-171"))).toBe(false);
expect(looksLikeRunStamp(j("20240229", "-0900"))).toBe(true);
});
});
describe("HARN-108: base64 forms of a known secret and chance matches in base64 blobs", () => {
const SECRET = j("Zq8Lm2Xv", "7Nc4Rt9W", "y1Kp6Hd3");
const env = { SERVICE_API_KEY: SECRET };
const filler = (n: number, seed: number) => Buffer.from(Array.from({ length: n }, (_, i) => (i * 37 + seed * 11 + 5) % 256));
const embed = (shift: number, url: boolean) => {
const text = Buffer.concat([filler(30 + shift, shift), Buffer.from(SECRET), filler(31, 7)]).toString("base64");
return url ? text.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "") : text;
};
test("base64Forms gives one stable string per alignment and alphabet, each a substring of the encoded stream", () => {
const forms = base64Forms(SECRET);
expect(forms.length).toBeGreaterThanOrEqual(3);
expect(forms.length).toBeLessThanOrEqual(6);
for (const shift of [0, 1, 2]) for (const url of [false, true]) expect({ shift, url, found: forms.some((f) => embed(shift, url).includes(f)) }).toEqual({ shift, url, found: true });
});
test("the value's base64 or base64url form at each alignment reports env.value HIGH", () => {
for (const shift of [0, 1, 2]) for (const url of [false, true]) {
const found = scan("blob: " + embed(shift, url) + "\n", { processEnv: env }).findings.filter((f) => f.id === "env.value");
expect({ shift, url, hits: found.map((f) => [f.severity, f.description]) }).toEqual({ shift, url, hits: [["HIGH", "Value of the SERVICE_API_KEY environment variable, base64-encoded"]] });
}
});
test("a value that normalization changes is also found by its bytes as given", () => {
const wide = j("Zq8", "Lm2Xv7Nc4Rt9Wy1Kp6Hd3");
const text = Buffer.concat([filler(31, 2), Buffer.from(wide), filler(31, 7)]).toString("base64");
expect(ids("blob: " + text, undefined, { WIDE_API_KEY: wide })).toContain("env.value");
});
test("the plain value still reports, and a blob without the value does not", () => {
expect(ids("key " + SECRET, undefined, env)).toContain("env.value");
const other = Buffer.concat([filler(30, 1), Buffer.from(SECRET.split("").reverse().join("")), filler(31, 7)]).toString("base64");
expect(ids("blob: " + other, undefined, env)).not.toContain("env.value");
});
const AIZA = j("AIza", "SyA1b2C3d4E5f6G7h8I9j0K1l2M3n4O5p6Q");
const OPENAI = j("sk-proj-", "a1B2c3D4e5F6g7H8i9J0k1L2m3N4o5P6q7R8s9T0u1V2w3X4");
const BLOB = filler(240, 3).toString("base64");
const inside = (key: string, at: number, blob = BLOB) => "data:image/png;base64," + blob.slice(0, at) + "/" + key + "/" + blob.slice(at);
test("a pattern match deep inside a long base64 run is chance and gives no provider finding", () => {
expect(ids(inside(AIZA, 100))).not.toContain("google.api_key");
});
test("a key at the start of a run, in a short run or on its own still reports", () => {
expect(ids(inside(AIZA, 10))).toContain("google.api_key");
expect(ids(inside(AIZA, 100, BLOB.slice(0, 120)))).toContain("google.api_key");
expect(ids("GOOGLE_KEY: " + AIZA)).toContain("google.api_key");
expect(ids(inside(OPENAI, 20))).toContain("openai.key");
const ANTHROPIC = j("sk-ant-api03-", "Ab3dE5gH7jK9mN1pQ3sT5vX7zB9cD1fG3hJ5kL7nP9rS1tV3wY5aC7eF9iK1mO3qU5xZ7bD9fH1jL3nR5tW7yA9cE1gI3kM5oQ7-xyzAA");
expect(ids("MY_COMPANY_PRODUCTION_ANTHROPIC_API_KEY_FOR_THE_BACKGROUND_WORKER_FLEET_AND_BATCH_JOBS_V2=" + ANTHROPIC)).toContain("anthropic.key");
expect(ids("services/" + "background-worker-fleet-and-batch-jobs-for-the-production-cluster-v2/" + OPENAI + "/" + "x".repeat(60))).toContain("openai.key");
});
test("a long fixed prefix never reads as chance: Anthropic, OpenRouter, prefixed OpenAI and AQ. keys deep in a run still report", () => {
const ANTHROPIC = j("sk-ant-api03-", "Ab3dE5gH7jK9mN1pQ3sT5vX7zB9cD1fG3hJ5kL7nP9rS1tV3wY5aC7eF9iK1mO3qU5xZ7bD9fH1jL3nR5tW7yA9cE1gI3kM5oQ7-xyzAA");
const ROUTER = j("sk-or-v1-", "9f8e7d6c5b4a39281706f5e4d3c2b1a0", "9f8e7d6c5b4a39281706f5e4d3c2b1a0");
const AQ = j("AQ.", "Ab3dE5gH7jK9mN1pQ3sT5vX7z");
expect(ids(inside(ANTHROPIC, 100))).toContain("anthropic.key");
expect(ids(inside(ROUTER, 100))).toContain("openrouter.key");
expect(ids(inside(OPENAI, 120))).toContain("openai.key");
expect(ids(inside(AQ, 100))).toContain("google.api_key");
expect(ids("GET /v1/Projects/Abc123Def456/Workspaces/Team7Alpha/Keys/Region9West/Accounts/Prod42Main/" + ANTHROPIC + " HTTP/1.1", "notes.md")).toContain("anthropic.key");
});
test("a bare sk- key deep in a base64url run is chance; inside standard base64 or after a path it still reports", () => {
const BARE = j("sk-", "Ab3dE5gH7jK9mN1pQ3sT5vX7zB9cD1fG3hJ5");
const URL_BLOB = BLOB.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
expect(ids("token=" + URL_BLOB.slice(0, 100) + "-" + BARE + "-" + URL_BLOB.slice(100))).not.toContain("openai.key");
expect(ids("/v1/Projects/Abc123Def456/Workspaces/Team7Alpha/Keys/Region9West/Accounts/Prod42Main/" + BARE + "/" + "Ab3dE5gH7jK9".repeat(8))).toContain("openai.key");
});
test("the exact value stays HIGH deep inside a long base64 run", () => {
const found = scan(inside(AIZA, 100), { processEnv: { GOOGLE_API_KEY: AIZA } }).findings.filter((f) => f.id === "env.value");
expect(found.map((f) => f.severity)).toEqual(["HIGH"]);
});
});