Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(transcripts): redact CLI-flag, suffixed-env, next-line and Markdown-table passwords (W4.1)

time-attack4b70d65aa3e9
diff --git a/docs/architecture/key-files/security.md b/docs/architecture/key-files/security.md
index c65836e8cf..67a1a8a7b9 100644
--- a/docs/architecture/key-files/security.md
+++ b/docs/architecture/key-files/security.md
@@ -24,6 +24,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/scope.ts` — OAuth scope hierarchy + allowlist (the 6 scope strings, `hasScope`, `assertAllowedScopes`, `filterAllowedScopes`, `parseScopeString`, `normalizeScopesInput`) AND the anonymous-registration policy: `DCR_REGISTRABLE_SCOPES` (`read`, `write`) and `dcrScopeViolation(requested, grantTypes)` — returns `null` when the requested scopes fit the Dynamic Client Registration ceiling, otherwise the `invalid_client_metadata` message naming the offending scopes and the operator remedy (`gbrain auth register-client` / admin API / `gbrain auth rescope-client <client_id> --scopes ...`). `agent` keeps its own "operator-approved grant with explicit delegation bindings" wording; when `grantTypes` includes `client_credentials` (only reachable under `--enable-dcr-insecure`) the ceiling is `read` alone; unknown scope strings are ignored here (the unknown-filter drops them). `scopesSupportedForDiscovery({ enableDcr })` is the `scopes_supported` list for OAuth discovery (consumed by `serve-http.ts`'s `authRouterOptions`): the DCR-registrable subset (`read write`, canonical order) while DCR is enabled — so a client that copies discovery into its registration passes `dcrScopeViolation` — and every scope except `agent` otherwise; it never narrows an operator-registered client, because a client that omits `scope` at `/authorize` receives its full registered set via `grantScopes` (`oauth-grants.ts`) and an explicit request is intersected with the registration. The DCR constants and the helper sit BELOW `ALLOWED_SCOPES_LIST`, and no comment line pairs that identifier with `[`, because `scripts/check-admin-scope-drift.sh` extracts the allowlist block with an awk match on exactly that pair. Pinned by `test/scope.test.ts` + `test/oauth-dcr-scope-ceiling.test.ts` + the discovery test in `test/e2e/serve-http-consent.test.ts`.
-- `src/core/secret-scan-labeled.ts` — the transcript-lane `labeled_credential` detector (#6147 idea, widened), compiled by `secret-scan.ts` only under `ScanOpts.labeledCredentials` (transcript pages, the recent-transcripts read and `transcripts audit-secrets`), after every other rule so a vendor or entropy claim keeps attribution. SINGLE labels (`password|passwd|passcode|passphrase|pwd`, optional identifier prefix, JSON-key quote, markdown bold) before `:`/`=`/`:`, and PAIR labels (`login|log-in|credentials|creds|user/pass|username/password|…`) before `:`/`=`/`:`/` - `/nothing then `user / pass` or `user:pass`, each in a bare and a quoted/backticked form; only the password half is claimed. `labeledValueIsCredential(value, form, head)` (the scanner passes the match head to `validate`) rejects placeholders, masks, templating, URLs, paths, calls, dotted references, digitless code identifiers, a backtick that closes a code span holding the label, a meeting link's `?pwd=`, and `LABELED_STOPLIST` words; a pair's password also needs 4+ chars with a letter and a digit or symbol, and its user half must not be a stopword. `endsWithDanglingPair` gates the next-line continuation pattern (such a line is scanned even when shorter than 8 chars). Claimed values join the echo dictionary at `ECHO_MIN_CHARS_LABELED` = 8 when `labeledEchoEligible`. Every quantifier is bounded (perf-pinned in `test/secret-scan-perf.test.ts`); acceptance table in `test/transcript-labeled-credential.test.ts`; user doc `docs/guides/data-ingestion.md#credential-redaction`.
+- `src/core/secret-scan-labeled.ts` — the transcript-lane `labeled_credential` detector (#6147 idea, widened), compiled by `secret-scan.ts` only under `ScanOpts.labeledCredentials` (transcript pages, the recent-transcripts read and `transcripts audit-secrets`), after every other rule so a vendor or entropy claim keeps attribution. SINGLE labels (`password|passwd|passcode|passphrase|pwd`, optional identifier prefix, JSON-key quote, markdown bold) before `:`/`=`/`:`, and PAIR labels (`login|log-in|credentials|creds|user/pass|username/password|…`) before `:`/`=`/`:`/` - `/nothing then `user / pass` or `user:pass`, each in a bare and a quoted/backticked form; only the password half is claimed. `labeledValueIsCredential(value, form, head)` (the scanner passes the match head to `validate`) rejects placeholders, masks, templating, URLs, paths, calls, dotted references, digitless code identifiers, a backtick that closes a code span holding the label, a meeting link's `?pwd=`, and `LABELED_STOPLIST` words; a pair's password also needs 4+ chars with a letter and a digit or symbol, and its user half must not be a stopword. W4.1 widens it: CLI flags with a separate value (`--password X`, `--pass "a b"`; suffixed flags such as `--password-file` are not labels), an env-name suffix after the label (`PASSWORD_DB=`; a setting suffix such as `_FILE`/`_MIN_LENGTH`/`_HINT` rejects via `settingSuffix`), values starting with `-` rejected, and Markdown tables (`tableCredentialCells` with per-scan `TableScanState`: cells under a password-label header column and the value cell of a non-header `| password | X |` row; escaped pipes, no outer pipes, several columns). `danglingLabel` gates the next-line continuation patterns per form: `pair` after a dangling pair, `single` (the whole next line is the value, validated as a single label) after a line ending in a single label and delimiter; such a line, and a table row with a claimed cell, is scanned even when shorter than 8 chars. Claimed values join the echo dictionary at `ECHO_MIN_CHARS_LABELED` = 8 when `labeledEchoEligible`. Every quantifier is bounded (perf-pinned in `test/secret-scan-perf.test.ts`); acceptance table in `test/transcript-labeled-credential.test.ts`; user doc `docs/guides/data-ingestion.md#credential-redaction`.
- `src/core/ssrf-validate.ts` — DNS-rebinding-defended URL validation. `validateAndResolveUrl(url)` resolves the hostname via `dns.lookup({all: true, family: 0})`, checks EVERY A and AAAA record against the internal-IP deny list, and returns the resolved IP so callers fetch by IP (validation IP === fetch IP defeats DNS rebinding). `fetchWithSSRFGuard(url, opts)` does redirect-aware fetching with per-hop re-validation (max 3 hops by default). Reusable across all URL-fetching features. Test seam `__setDnsLookupForTests` for hermetic tests.
diff --git a/docs/guides/data-ingestion.md b/docs/guides/data-ingestion.md
index aaf2fd214d..bec5b5c475 100644
--- a/docs/guides/data-ingestion.md
+++ b/docs/guides/data-ingestion.md
@@ -109,7 +109,19 @@ forms are recognized, with bare, quoted or backticked values:
`username/password`, followed by `:`, `=`, `:`, ` - ` or nothing, then
`user / pass` or `user:pass` — `login alice / hunter2`,
`creds: alice:hunter2`. Only the password half is redacted. A pair whose
- password starts the next line is redacted too.
+ password starts the next line is redacted too;
+- a command-line flag with its value after a space, `--password hunter2`,
+ `--pass "two words"` (`--password-file` and other suffixed flags are not
+ labels);
+- an environment name with more after the label, `PASSWORD_DB=…`,
+ `FOO_PASSWORD_BAR=…`, unless the suffix names a setting (`_FILE`, `_PATH`,
+ `_MIN_LENGTH`, `_HINT`, `_POLICY` and similar);
+- a single label that ends its line, with the value alone on the next line
+ (`password:` then `hunter2`);
+- Markdown table cells: every cell under a column headed `Password`, `pwd`,
+ `DB password` and the like, and the value in a `| password | … |` row,
+ including rows without outer pipes, escaped `\|` pipes and tables with
+ several credential columns.
To keep prose and code intact, a value is never redacted when it is a
placeholder (`<…>`, `${…}`, `$VAR`), a mask (`****`), a URL, a path, a
@@ -120,12 +132,13 @@ list is `LABELED_STOPLIST` in `src/core/secret-scan-labeled.ts`). A pair's
password must also be 4+ characters with a letter and a digit or symbol, so
`login: Google/GitHub SSO` and `credentials: docs/auth.md` stay. Known
misses: an unquoted multi-word passphrase, a label with no delimiter
-(`the password is …`), and a meeting link's `?pwd=` passcode. A redacted
+(`the password is …`), a short flag joined to its value (`mysql -phunter2`),
+and a meeting link's `?pwd=` passcode. A redacted
value of 8+ characters that is not a stoplisted word is also scrubbed where
the session repeats it bare.
-Pages imported before this detector shipped are not rewritten
-automatically. `gbrain transcripts audit-secrets --json` (read-only; all
+Pages imported before this detector (or a later widening of it) shipped are
+not rewritten automatically, so run the audit again after upgrading. `gbrain transcripts audit-secrets --json` (read-only; all
sources, or one with `--source-id`) lists the conversation pages that still
carry a credential: slug, source, hit count per pattern and line numbers,
never the text. The doctor check `transcript_secret_exposure` reads the
diff --git a/src/core/secret-scan-labeled.ts b/src/core/secret-scan-labeled.ts
index 86c0d13111..2586bb81b0 100644
--- a/src/core/secret-scan-labeled.ts
+++ b/src/core/secret-scan-labeled.ts
@@ -27,10 +27,22 @@
* documented stoplist of prose and code words never redact. A pair's password
* must also carry a letter plus a digit or a symbol, so prose such as
* `login: Google/GitHub SSO` or `credentials: docs/auth.md` stays intact.
+ * Wave 12 W4.1 adds: a CLI flag value (`--password X`, `--pass "a b"`;
+ * `--password-file` and other suffixed flags are not labels), an env name
+ * with a suffix after the label (`PASSWORD_DB=`, `FOO_PASSWORD_BAR=`; a
+ * stoplisted suffix such as `_FILE`, `_MIN_LENGTH` or `_HINT` is not a
+ * credential), a SINGLE label that ends its line with the value alone on the
+ * next line (`password:` then `hunter2`, validated as a single label), and
+ * Markdown table cells (`tableCredentialCells`): every cell of a column whose
+ * header is a password label, and the value cell of a `| password | X |`
+ * key/value row, with escaped pipes, rows without outer pipes and several
+ * credential columns.
+ *
* Accepted misses: an unquoted multi-word passphrase (`login: alice / pass
* word`), a delimiter-free single label (`the password is hunter2`), a pair
- * split by anything but one line break, and a meeting link's `?pwd=`
- * passcode (part of a shareable invite URL).
+ * split by anything but one line break, a concatenated short flag
+ * (`mysql -phunter2`: `-p` is a port flag elsewhere) and a meeting link's
+ * `?pwd=` passcode (part of a shareable invite URL).
*
* Every quantifier is bounded so each candidate start does constant work
* (pinned in test/secret-scan-perf.test.ts).
@@ -50,13 +62,15 @@ const BOLD = '(?:\\*{1,2}|_{2})?';
const PAIR_HEAD = `${LEFT}${PAIR_LABEL}${LABEL_END}${BOLD}${QUOTE}?\\s{0,4}(?:${DELIM}|-(?=\\s))?${BOLD}\\s{0,4}`;
const PAIR_USER = `(?:${QUOTE}[^"'\`\\n/]{1,128}${QUOTE}|[^\\s/:"'\`]{1,128})`;
const PAIR_SEP = '(?:\\s{0,4}/\\s{0,4}|:(?![/\\s]))';
-const SINGLE_HEAD = `${LEFT}[A-Za-z0-9_]{0,32}${SINGLE_LABEL}${LABEL_END}${BOLD}${QUOTE}?\\s{0,4}${DELIM}${BOLD}\\s{0,4}`;
+const LABEL_SUFFIX = '(?:_[A-Za-z0-9]{1,16}){0,2}';
+const SINGLE_HEAD = `${LEFT}[A-Za-z0-9_]{0,32}${SINGLE_LABEL}${LABEL_SUFFIX}${LABEL_END}${BOLD}${QUOTE}?\\s{0,4}${DELIM}${BOLD}\\s{0,4}`;
+const CLI_HEAD = '(?:^|\\s)--?(?:pass(?:word|wd|phrase)?|pwd)(?![A-Za-z0-9_=-])\\s{1,4}';
export interface LabeledPattern {
source: string;
form: 'single' | 'pair';
- /** Runs only on the line after one that ends in a dangling pair. */
- continuation?: true;
+ /** Runs only on the line after one that ends in a dangling label of this form. */
+ continuation?: 'single' | 'pair';
}
/** Group 1 = everything before the value, group 2 = the value (the scanner's shape). */
@@ -65,7 +79,12 @@ export const LABELED_CREDENTIAL_PATTERNS: readonly LabeledPattern[] = [
{ form: 'single', source: `(${SINGLE_HEAD})(${BARE_VALUE})${BARE_END}` },
{ form: 'pair', source: `(${PAIR_HEAD}${PAIR_USER}${PAIR_SEP}${QUOTE})(${QUOTED_VALUE})(?=${QUOTE})` },
{ form: 'pair', source: `(${PAIR_HEAD}${PAIR_USER}${PAIR_SEP})(${BARE_PASS})${BARE_END}` },
- { form: 'pair', continuation: true, source: `(^\\s{0,8}${QUOTE}?)(${BARE_PASS})${BARE_END}` },
+ { form: 'pair', continuation: 'pair', source: `(^\\s{0,8}${QUOTE}?)(${BARE_PASS})${BARE_END}` },
+ { form: 'single', source: `(${CLI_HEAD}${QUOTE})(${QUOTED_VALUE})(?=${QUOTE})` },
+ { form: 'single', source: `(${CLI_HEAD})(${BARE_VALUE})${BARE_END}` },
+ // The whole next line is the value (optionally quoted), so prose under a `Password:` heading is never claimed.
+ { form: 'single', continuation: 'single', source: `(^\\s{0,8}${QUOTE})(${QUOTED_VALUE})(?=${QUOTE}[,;]?\\s*$)` },
+ { form: 'single', continuation: 'single', source: `(^\\s{0,8})(${BARE_VALUE})(?=[.,;]?\\s*$)` },
];
/** Cheap gate before the label regexes run on a line. */
@@ -73,12 +92,26 @@ export const LABELED_PRECHECK_RE = /pass|pwd|log-?in|cred/i;
// nosemgrep: javascript.lang.security.audit.detect-non-literal-regexp.detect-non-literal-regexp -- compile-time literal; bounded quantifiers
const PAIR_DANGLING_RE = new RegExp(`${PAIR_HEAD}${PAIR_USER}\\s{0,4}/\\s{0,4}$`, 'i');
+// nosemgrep: javascript.lang.security.audit.detect-non-literal-regexp.detect-non-literal-regexp -- compile-time literal; bounded quantifiers
+const SINGLE_DANGLING_RE = new RegExp(`${SINGLE_HEAD}$`, 'i');
/** True when `line` ends in a pair label and user name with the password on the next line. */
export function endsWithDanglingPair(line: string): boolean {
return line.includes('/') && LABELED_PRECHECK_RE.test(line) && PAIR_DANGLING_RE.test(line);
}
+/**
+ * The label form `line` leaves dangling for the next line: `pair` (`login:
+ * alice /`), `single` (`password:` with nothing after it), or null. Only the
+ * last 128 characters are tested, so a long line costs constant work.
+ */
+export function danglingLabel(line: string): 'single' | 'pair' | null {
+ if (!LABELED_PRECHECK_RE.test(line)) return null;
+ if (endsWithDanglingPair(line)) return 'pair';
+ const tail = line.length > 128 ? line.slice(-128) : line;
+ return SINGLE_DANGLING_RE.test(tail) ? 'single' : null;
+}
+
/**
* Words that follow a credential label in prose or code without being the
* credential. Documented in docs/guides/data-ingestion.md ("Credential
@@ -119,6 +152,20 @@ const VERSION_RE = /^v?\d+(?:\.\d+)+$/;
const PAIR_SYMBOL_RE = /[0-9!@#$%^&*+=?~]/;
const LETTER_RE = /[A-Za-z]/;
+/** Env-name suffixes after a password label that name a setting, not the credential (`PASSWORD_FILE`, `PASSWORD_MIN_LENGTH`). */
+const SETTING_SUFFIX_RE = /(?:pass(?:word|wd|code|phrase)?|pwd)((?:_[A-Za-z0-9]{1,16}){1,2})(?![A-Za-z0-9_-])[^A-Za-z0-9]*$/i;
+const SETTING_SUFFIXES: ReadonlySet<string> = new Set([
+ 'file', 'path', 'dir', 'hint', 'length', 'len', 'min', 'max', 'policy', 'prompt', 'reset', 'required', 'enabled', 'disabled',
+ 'cmd', 'command', 'env', 'var', 'name', 'field', 'label', 'url', 'rule', 'rules', 'regex', 'pattern', 'expiry', 'expires',
+ 'ttl', 'age', 'rounds', 'cost', 'algo', 'algorithm', 'hash', 'salt', 'chars', 'strength', 'history', 'attempts', 'retries', 'auth', 'mode',
+]);
+
+/** True when the label in `head` carries a setting suffix (`PASSWORD_MIN_LENGTH=`), so its value is not a credential. */
+function settingSuffix(head: string): boolean {
+ const m = SETTING_SUFFIX_RE.exec(head);
+ return !!m && m[1]!.split('_').some((part) => SETTING_SUFFIXES.has(part.toLowerCase()));
+}
+
/** Minimum length before a labeled value joins the session-wide echo list. */
export const ECHO_MIN_CHARS_LABELED = 8;
@@ -150,7 +197,8 @@ const PAIR_USER_TAIL_RE = /([^\s/:"'`*]+)["'`]?\s*[/:]\s*["'`]?$/;
* (`login page / step2`).
*/
export function labeledValueIsCredential(value: string, form: 'single' | 'pair', head = ''): boolean {
- if (value.length < 3 || isStopword(value)) return false;
+ if (value.length < 3 || isStopword(value) || value.startsWith('-')) return false;
+ if (settingSuffix(head)) return false;
if (head.endsWith('`') && closesCodeSpan(head)) return false;
if (QUERY_PWD_RE.test(head)) return false;
if (PLACEHOLDER_PREFIX_RE.test(value) || MASK_RE.test(value) || URL_RE.test(value) || PATH_RE.test(value)) return false;
@@ -167,3 +215,89 @@ export function labeledValueIsCredential(value: string, form: 'single' | 'pair',
export function labeledEchoEligible(value: string): boolean {
return value.length >= ECHO_MIN_CHARS_LABELED && !isStopword(value) && !/\s/.test(value);
}
+
+/** A password-label column header or key cell (`Password`, `DB password`, `pwd`), after stripping Markdown emphasis and a colon. */
+const TABLE_LABEL_RE = /^(?:[a-z0-9]{1,32}[ _-])?(?:pass(?:word|wd|code|phrase)|pwd)$/;
+const TABLE_SEPARATOR_CELL_RE = /^:?-{3,}:?$/;
+
+interface TableCell { start: number; text: string }
+
+/** Cells of a pipe-table row (escaped `\|` is not a separator); null when the line has no unescaped pipe. */
+function tableCells(line: string): TableCell[] | null {
+ const cells: TableCell[] = [];
+ let from = 0;
+ let pipes = 0;
+ for (let k = 0; k <= line.length; k++) {
+ if (k < line.length && (line[k] !== '|' || (k > 0 && line[k - 1] === '\\'))) continue;
+ if (k < line.length) pipes++;
+ cells.push({ start: from, text: line.slice(from, k) });
+ from = k + 1;
+ }
+ if (pipes === 0) return null;
+ // Outer pipes leave an empty first/last cell.
+ if (cells.length > 1 && cells[0]!.text.trim() === '') cells.shift();
+ if (cells.length > 1 && cells[cells.length - 1]!.text.trim() === '') cells.pop();
+ return cells;
+}
+
+function isSeparatorRow(cells: TableCell[] | null): boolean {
+ return !!cells && cells.length > 0 && cells.every((c) => TABLE_SEPARATOR_CELL_RE.test(c.text.trim()));
+}
+
+function isLabelCell(text: string): boolean {
+ return TABLE_LABEL_RE.test(text.replace(/[*_`]/g, ' ').trim().replace(/:$/, '').replace(/\s+/g, ' ').toLowerCase());
+}
+
+/** The value inside a cell: trimmed, without one pair of surrounding backticks or quotes. */
+function cellValue(cell: TableCell): { start: number; value: string } | null {
+ const lead = cell.text.length - cell.text.trimStart().length;
+ let value = cell.text.trim();
+ let start = cell.start + lead;
+ const q = value[0];
+ if (value.length >= 2 && (q === '`' || q === '"' || q === "'") && value[value.length - 1] === q) {
+ value = value.slice(1, -1);
+ start += 1;
+ }
+ return value ? { start, value } : null;
+}
+
+/** Per-scan table state for `tableCredentialCells`: the credential column indexes of the table the scan is in. */
+export interface TableScanState { columns: number[] | null; previous: TableCell[] | null }
+
+export function newTableScanState(): TableScanState {
+ return { columns: null, previous: null };
+}
+
+/**
+ * Credential values in Markdown table row `line` (W4.1): cells under a
+ * password-label header column, and the value cell right after a password
+ * key cell in a row that is not itself a header. `next` is the following
+ * line (a header row is the one above a separator). Linear in the line.
+ */
+export function tableCredentialCells(line: string, next: string | undefined, state: TableScanState): Array<{ start: number; value: string }> {
+ const cells = tableCells(line);
+ const out: Array<{ start: number; value: string }> = [];
+ if (!cells) {
+ state.columns = null;
+ state.previous = null;
+ return out;
+ }
+ if (isSeparatorRow(cells)) {
+ const header = state.previous;
+ state.columns = header ? header.flatMap((c, k) => (isLabelCell(c.text) ? [k] : [])) : null;
+ state.previous = null;
+ return out;
+ }
+ state.previous = cells;
+ const claim = (cell: TableCell | undefined): void => {
+ const v = cell ? cellValue(cell) : null;
+ if (v && !isLabelCell(v.value) && labeledValueIsCredential(v.value, 'single')) out.push(v);
+ };
+ if (state.columns) for (const k of state.columns) claim(cells[k]);
+ if (next === undefined || !isSeparatorRow(tableCells(next))) {
+ for (let k = 0; k + 1 < cells.length; k++) {
+ if (isLabelCell(cells[k]!.text) && !state.columns?.includes(k + 1)) claim(cells[k + 1]);
+ }
+ }
+ return out;
+}
diff --git a/src/core/secret-scan.ts b/src/core/secret-scan.ts
index e6bf00c2e8..9ed03e257c 100644
--- a/src/core/secret-scan.ts
+++ b/src/core/secret-scan.ts
@@ -35,9 +35,11 @@ import {
LABELED_CREDENTIAL_PATTERNS,
ECHO_MIN_CHARS_LABELED,
LABELED_PRECHECK_RE,
- endsWithDanglingPair,
+ danglingLabel,
labeledEchoEligible,
labeledValueIsCredential,
+ newTableScanState,
+ tableCredentialCells,
} from './secret-scan-labeled.ts';
// ── Types ───────────────────────────────────────────────────────────────────
@@ -120,8 +122,8 @@ interface CompiledPattern {
precheck?: (line: string) => boolean;
/** See CorePattern.validate; `head` is the match text before the value. */
validate?: (value: string, head: string) => boolean;
- /** Runs only on the line after one that ends in a dangling credential pair. */
- continuation?: boolean;
+ /** Runs only on the line after one that ends in a dangling credential label of this form. */
+ continuation?: 'single' | 'pair';
}
interface CorePattern {
@@ -719,7 +721,7 @@ function compilePatterns(opts: ScanOpts): CompiledPattern[] {
name: 'labeled_credential',
// nosemgrep: javascript.lang.security.audit.detect-non-literal-regexp.detect-non-literal-regexp -- compile-time literal; bounded quantifiers, pinned by test/secret-scan-perf.test.ts
re: new RegExp(p.source, 'gi'),
- ...(p.continuation ? { continuation: true } : { precheck: (line: string) => LABELED_PRECHECK_RE.test(line) }),
+ ...(p.continuation ? { continuation: p.continuation } : { precheck: (line: string) => LABELED_PRECHECK_RE.test(line) }),
validate: (value: string, head: string) => labeledValueIsCredential(value, p.form, head),
});
}
@@ -973,12 +975,16 @@ function scanInternal(text: string, opts: ScanOpts): RawHit[] {
// redactFindings can splice the text once instead of searching it per
// value.
let offset = 0;
+ // W4.1: Markdown table state for the labeled lane (credential columns of the table being scanned).
+ const table = opts.labeledCredentials === true ? newTableScanState() : null;
for (let i = 0; i < lines.length; i++) {
const line = lines[i] ?? '';
const lineStart = offset;
offset += line.length + 1;
- const dangling = opts.labeledCredentials === true && i > 0 && endsWithDanglingPair(lines[i - 1] ?? '');
- if (line.length < 8 && !dangling) continue;
+ const dangling = opts.labeledCredentials === true && i > 0 ? danglingLabel(lines[i - 1] ?? '') : null;
+ const cells = table && line.includes('|') ? tableCredentialCells(line, lines[i + 1], table) : [];
+ if (table && !line.includes('|')) { table.columns = null; table.previous = null; }
+ if (line.length < 8 && !dangling && cells.length === 0) continue;
// ENG-12: a line wholly inside a private-key claim is already redacted by
// it; hits on it would only double-report (one key, one finding).
if (pem.length > 0 && insideClaim(pem, lineStart, lineStart + line.length)) continue;
@@ -997,7 +1003,7 @@ function scanInternal(text: string, opts: ScanOpts): RawHit[] {
hits.push({ pattern, value, start, abs: lineStart + start, line: i + 1, lineText: line, spans });
};
for (const p of patterns) {
- if (p.continuation && !dangling) continue;
+ if (p.continuation && p.continuation !== dangling) continue;
if (p.precheck && !p.precheck(line)) continue;
p.re.lastIndex = 0;
let m: RegExpExecArray | null;
@@ -1034,6 +1040,11 @@ function scanInternal(text: string, opts: ScanOpts): RawHit[] {
claim(p.name, value, start);
}
}
+ for (const cell of cells) {
+ if (taken && anyTaken(taken, cell.start, cell.start + cell.value.length)) continue;
+ taken ??= new Uint8Array(line.length);
+ claim('labeled_credential', cell.value, cell.start);
+ }
}
return hits;
}
diff --git a/test/secret-scan-perf.test.ts b/test/secret-scan-perf.test.ts
index c910d09958..e0e3ac554d 100644
--- a/test/secret-scan-perf.test.ts
+++ b/test/secret-scan-perf.test.ts
@@ -505,6 +505,10 @@ describe('labeled_credential (transcript lane): every candidate start does const
['a label, 200k spaces, then a value', 'password:' + ' '.repeat(200_000) + 'x'],
['200 KB of `a/` after a login label', 'login: ' + 'a/'.repeat(100_000)],
['20000 dangling pair lines', Array.from({ length: 20_000 }, () => 'login: alice-example /').join('\n')],
+ ['20000 dangling single labels', Array.from({ length: 20_000 }, () => 'password:').join('\n')],
+ ['a 10k-row table with two credential columns', ['| user | password | pwd |', '|---|---|---|', ...Array.from({ length: 10_000 }, (_, k) => `| u${k} | s3cret${k} | p${k}x\\|y |`)].join('\n')],
+ ['a 200 KB row of escaped pipes', '| password | ' + '\\|'.repeat(100_000) + ' |'],
+ ['200 KB of `--password `', '--password '.repeat(20_000)],
];
for (const [name, text] of adversaries) {
test(`${name}: redact < 400ms`, () => {
diff --git a/test/transcript-labeled-credential.test.ts b/test/transcript-labeled-credential.test.ts
index 713bd4c868..af47a56a10 100644
--- a/test/transcript-labeled-credential.test.ts
+++ b/test/transcript-labeled-credential.test.ts
@@ -52,6 +52,22 @@ const MUST_REDACT: Array<[string, string]> = [
['pwd label', `pwd=${PW}`],
['passcode label', `passcode: ${PW}`],
['trailing sentence punctuation', `The password: ${PW}.`],
+ // W4.1
+ ['CLI flag with a separate value', `mysql -u root --password ${PW} -h db.example`],
+ ['short CLI flag word', `psql --pass ${PW}`],
+ ['quoted CLI value with a space', `tool --password "a b ${PW}"`],
+ ['value alone on the next line', `password:\n${PW}`],
+ ['digitless value on the next line', `password:\n${['hunter', 'abc'].join('')}${PW}`],
+ ['next-line value with CRLF and indentation', `Password:\r\n ${PW}\r\n`],
+ ['quoted next-line value (pretty JSON)', `"password":\n "${PW}",`],
+ ['suffix after the label', `PASSWORD_DB=${PW}`],
+ ['label inside an env name', `FOO_PASSWORD_BAR=${PW}`],
+ ['table column', `| user | password |\n|---|---|\n| alice-example | ${PW} |`],
+ ['table without outer pipes', `user | password\n--- | ---\nalice-example | ${PW}`],
+ ['table cell with an escaped pipe', `| user | password |\n|---|---|\n| alice-example | a\\|${PW} |`],
+ ['table with two credential columns', `| password | user | pwd |\n|---|---|---|\n| ${PW} | alice-example | x${PW}y |`],
+ ['key/value table row', `| password | ${PW} |`],
+ ['table with CRLF', `| user | password |\r\n|---|---|\r\n| alice-example | ${PW} |\r\n`],
];
const MUST_KEEP: Array<[string, string]> = [
@@ -82,6 +98,16 @@ const MUST_KEEP: Array<[string, string]> = [
['await', 'const passphrase = await passphraseFrom(args);'],
['code span label', 'the libpq form (`password=`, `sslpassword=`) is scrubbed'],
['already redacted', 'password: <REDACTED:high_entropy_assignment>'],
+ // W4.1
+ ['setting suffix', 'PASSWORD_MIN_LENGTH=12345'],
+ ['file flag', '--password-file /run/secrets/db'],
+ ['file env', 'POSTGRES_PASSWORD_FILE=/run/secrets/db'],
+ ['n/a table cell', '| password | n/a |'],
+ ['policy header table', '| Password policy | Notes |\n|---|---|\n| strong | yes please |'],
+ ['password header row is not a key/value row', '| Password | Notes |\n|---|---|\n| x | y |'],
+ ['pass the test', 'make sure we pass the test suite'],
+ ['prose under a password heading', 'Password:\nYou can change it in the settings page'],
+ ['pass/fail column', '| test | pass |\n|---|---|\n| auth | ok2 |'],
];
describe('labeled_credential on the transcript page lane', () => {