mirror of
https://github.com/garrytan/gstack.git
synced 2026-12-02 04:43:59 +01:00
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:
1 parent
36a8ae067c
commit
f7beb0a71b
8 files changed
+602
-37
No files matched your search
@@ -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
@@ -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
@@ -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) &&
|
||||
|
||||
Reference in new issue
Block a user