mirror of
https://github.com/garrytan/gstack.git
synced 2026-11-24 00:51:31 +01:00
Redactor hides key=value secrets that follow a slash, so /cso history stops printing them (GST-3297) (#4571)
gstack's redactor now hides `password=…`, `api_key=…` and `token=…` values that come after a `/`, such as a symlink target `../password=…`, `cfg/api_key=…` or a Markdown link to such a path. Why: `/cso`'s retained Git history went through this redactor and kept those values, so `gstack-cso history` printed them; review packets, telemetry and ship logs use the same redactor. Nothing to do. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1/red-team#1 reader=red-team
This commit is contained in:
1 parent
6a64c49213
commit
64795163af
3 files changed
+225
-4
No files matched your search
@@ -0,0 +1,4 @@
|
||||
---
|
||||
important: security
|
||||
---
|
||||
- **Secret values written as `name=value` at the end of a path are now hidden.** gstack's redactor only recognized `password=…`, `api_key=…` or `token=…` at the start of a line, so the same thing after a slash (`../password=…`, `cfg/api_key=…`, `https://host/cb/token=…`) came back unredacted. `/cso` was the visible case: its retained Git history kept such a value from a symlink target, a link that only exists in history, or ordinary file content, and `gstack-cso history` printed it. The same redactor covers review packets, telemetry and ship logs, so they now hide these values too. Paths and code that only mention these words, values that are placeholders or `${VAR}` references, and regex literals in code are left as they were.
|
||||
+36
-4
@@ -1205,11 +1205,36 @@ function concatenationHoldsSecret(match: RegExpExecArray): boolean {
|
||||
* match that starts after other text on its line is a comment's, and its value,
|
||||
* less trailing punctuation, reports only when it is a secret run by
|
||||
* isSecretRun. Code before the comment is matched from the line start and
|
||||
* checked as before.
|
||||
* checked as before. GST-3297: a match that starts after a path's `/` is not
|
||||
* a comment's (`a/token=…`), so it is checked like a line-start match; one
|
||||
* after a comment marker that opens a quoted string or bracket (`"// key: …"`)
|
||||
* is still a comment's.
|
||||
*/
|
||||
const COMMENT_MARKER_BEFORE = /(?:^|[ \t"'`([])(?:#{1,6}|\/{2,3}|\/\*{1,2}|<!--)$/;
|
||||
|
||||
/**
|
||||
* GST-3297: a name that starts after a `/` can be the start of a regex
|
||||
* literal (`content.match(/authtoken:\s*(.+)/)`), whose "value" is pattern
|
||||
* text. It is one only when the `/` follows an operator or opening bracket
|
||||
* (never a path segment) and the body before the closing `/` holds regex
|
||||
* syntax (an escape, a character class, a group or a {n,m} quantifier), so a
|
||||
* Markdown link or a YAML value whose path holds a key=value secret still
|
||||
* reports.
|
||||
* Matches from the line start or a comment marker never qualify.
|
||||
*/
|
||||
const REGEX_LITERAL_OPENER = /(?:[(,=:[!&|?{};]|\breturn)[ \t]*\/$/;
|
||||
const REGEX_LITERAL_SYNTAX = /\\|\[[^\]]*\]|\([^)]*\)|\{\d+(?:,\d*)?\}/;
|
||||
function isRegexLiteralBody(span: string, match: RegExpExecArray): boolean {
|
||||
const close = span.indexOf("/");
|
||||
if (close < 0 || !REGEX_LITERAL_SYNTAX.test(span.slice(0, close))) return false;
|
||||
const lineStart = match.input.lastIndexOf("\n", match.index - 1) + 1;
|
||||
return REGEX_LITERAL_OPENER.test(match.input.slice(lineStart, match.index));
|
||||
}
|
||||
function isCommentText(span: string, match: RegExpExecArray): boolean {
|
||||
const lineStart = match.input.lastIndexOf("\n", match.index - 1) + 1;
|
||||
if (/^(?:[ +-]?\+|[ +-]?-(?! [^ \t]))?[ \t]*$/.test(match.input.slice(lineStart, match.index))) return false;
|
||||
const before = match.input.slice(lineStart, match.index);
|
||||
if (/^(?:[ +-]?\+|[ +-]?-(?! [^ \t]))?[ \t]*$/.test(before)) return false;
|
||||
if (!COMMENT_MARKER_BEFORE.test(before)) return false;
|
||||
return !isSecretRun(span.replace(/[,;.)]+$/, ""));
|
||||
}
|
||||
|
||||
@@ -1695,7 +1720,12 @@ export const PATTERNS: RedactPattern[] = [
|
||||
// matched on its own from the line start. A short first piece followed by
|
||||
// `+` is captured so concatenationHoldsSecret can read the rest of the
|
||||
// chain.
|
||||
regex: /(?:^(?:[ +-]?\+|[ +-]?-(?! [^ \t]))?|(?<=(?:^|[ \t])(?:#{1,6}|\/{2,3}|\/\*{1,2}|<!--)))[ \t]*(?:export[ \t]+)?["']?[A-Za-z0-9_.-]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIALS?|DSN|AUTH|COOKIE|SESSION|PRIVATE)["']?[ \t]*[:=][ \t]*["']?([^\s'"]{8,}|[^\s'"]{1,7}(?=["']?[ \t]*\+))["']?/i,
|
||||
// GST-3297: a name may also start right after a `/`, so a key=value
|
||||
// secret at the end of a path (`../password=…`, `cfg/api_key=…`) reports
|
||||
// wherever it sits: a symlink target in `git log -p`, a diff header, a
|
||||
// quoted string, mid-line. The name class excludes `/`, so each attempt
|
||||
// ends at the next separator and the scan stays linear.
|
||||
regex: /(?:^(?:[ +-]?\+|[ +-]?-(?! [^ \t]))?|(?<=(?:^|[ \t])(?:#{1,6}|\/{2,3}|\/\*{1,2}|<!--))|(?<=\/))[ \t]*(?:export[ \t]+)?["']?[A-Za-z0-9_.-]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIALS?|DSN|AUTH|COOKIE|SESSION|PRIVATE)["']?[ \t]*[:=][ \t]*["']?([^\s'"]{8,}|[^\s'"]{1,7}(?=["']?[ \t]*\+))["']?/i,
|
||||
// Only fire on credential-shaped names with high-entropy values — kills
|
||||
// `FOO_KEY=changeme` and `cacheKey: <entropic-id>` FPs. #2912: a value
|
||||
// that is exactly an environment read (`os.environ["X"]`,
|
||||
@@ -1710,7 +1740,8 @@ export const PATTERNS: RedactPattern[] = [
|
||||
// GST-1894: so is a self-named fixture label in a test file (isTestFixtureLabel).
|
||||
// GST-3004: so is a dotted field path (isDottedFieldPath, #4289), and so
|
||||
// is key-naming text in a comment
|
||||
// (isCommentText). A secret literal in a `+` chain reports first,
|
||||
// (isCommentText). GST-3297: so is a regex literal's body after its
|
||||
// opening `/` (isRegexLiteralBody). A secret literal in a `+` chain reports first,
|
||||
// whatever the exemptions say about the chain's first piece
|
||||
// (concatenationHoldsSecret).
|
||||
validate: (span, match, opts) =>
|
||||
@@ -1724,6 +1755,7 @@ export const PATTERNS: RedactPattern[] = [
|
||||
!isAttributeReference(span, match, opts?.sourcePath) &&
|
||||
!isDottedFieldPath(span, match, opts?.sourcePath) &&
|
||||
!isCommentText(span, match) &&
|
||||
!isRegexLiteralBody(span, match) &&
|
||||
!isSchemaFieldIdentifier(span, match) &&
|
||||
!isTestFixtureLabel(span, opts?.sourcePath) &&
|
||||
shannonEntropy(span) >= 3.0)),
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
/**
|
||||
* GST-3297: a key=value secret that follows a path separator is still a
|
||||
* secret. env.kv anchored its name at the line start (or after a diff marker
|
||||
* or comment marker), so `../password=<v>`, `path/api_key=<v>` and
|
||||
* `a/token=<v>` came back raw from the shared redactor. /cso's history.txt is
|
||||
* `git log -p` text redacted by it, so a tracked symlink target, a link that
|
||||
* exists only in history, and ordinary file content all leaked through
|
||||
* `gstack-cso history`. The name may now also start right after a `/`.
|
||||
*/
|
||||
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import * as fs from "node:fs";
|
||||
import * as os from "node:os";
|
||||
import * as path from "node:path";
|
||||
import { redact } from "../lib/cso/process";
|
||||
import { redactFindingSpans, scan } from "../lib/redact-engine";
|
||||
|
||||
const j = (...p: string[]) => p.join("");
|
||||
const VALUE = j("Xk9", "qPz7Lm2Rt8Vw4Ny6");
|
||||
const PASSWORD = j("pass", "word");
|
||||
const API_KEY = j("api", "_key");
|
||||
const TOKEN = j("to", "ken");
|
||||
const kv = (key: string, value = VALUE) => `${key}=${value}`;
|
||||
|
||||
const envKv = (text: string) => scan(text).findings.filter((f) => f.id === "env.kv");
|
||||
|
||||
describe("env.kv after a path separator (GST-3297)", () => {
|
||||
const leaks: [string, string][] = [
|
||||
["link target, parent dir", `../${kv(PASSWORD)}`],
|
||||
["link target, nested", `cfg/a/../../${kv(TOKEN)}`],
|
||||
["link target, absolute", `/etc/app/${kv(API_KEY)}`],
|
||||
["link line in a manifest", `cfg/up -> ../${kv(PASSWORD)}`],
|
||||
["file content, path prefix", `path/${kv(API_KEY)}`],
|
||||
["file content, short prefix", `a/${kv(TOKEN)}`],
|
||||
["file content, colon form", `settings/${API_KEY}: ${VALUE}`],
|
||||
["file content, double quotes", `target: "../${kv(PASSWORD)}"`],
|
||||
["file content, single quotes", `ln -s 'a/${kv(TOKEN)}' cfg/up`],
|
||||
["file content, mid-line", `url = https://example.test/cb/${kv(TOKEN)}`],
|
||||
["hunk, added line", `+../${kv(PASSWORD)}`],
|
||||
["hunk, removed line", `-../${kv(PASSWORD)}`],
|
||||
["hunk, combined diff", `+-a/${kv(TOKEN)}`],
|
||||
["hunk, context line", ` path/${kv(API_KEY)}`],
|
||||
["hunk, diff header path", `diff --git a/${kv(TOKEN)} b/${kv(TOKEN)}`],
|
||||
["hunk, dashed name", `+a/x-${kv(PASSWORD)}`],
|
||||
["comment with a path", `# rotate cfg/${kv(TOKEN)}`],
|
||||
["call argument, absolute path", `open("/${kv(TOKEN)}")`],
|
||||
["bracketed path, no closing slash", `(/${kv(TOKEN)})`],
|
||||
["doubled slash in a path", `+..//${kv(PASSWORD)}`],
|
||||
["quoted comment marker with a secret run", `x = "//${kv(TOKEN)}"`],
|
||||
["YAML value with a later slash", `link: /${kv(API_KEY)}/rest`],
|
||||
["assignment value with a later slash", `cfg=/db_${kv(PASSWORD)}/x`],
|
||||
["Markdown link with a later slash", `[cb](/${kv(API_KEY)}/rest)`],
|
||||
["single-slash URL with a later slash", `file:/${kv(TOKEN)}/x`],
|
||||
];
|
||||
|
||||
for (const [name, text] of leaks) {
|
||||
test(`redacts: ${name}`, () => {
|
||||
expect(envKv(text).length).toBeGreaterThan(0);
|
||||
const out = redact(text);
|
||||
expect(out).not.toContain(VALUE);
|
||||
expect(out).toContain("<REDACTED-env.kv>");
|
||||
});
|
||||
}
|
||||
|
||||
test("a git log -p hunk keeps its shape and loses only the values", () => {
|
||||
const hunk = [
|
||||
"commit 0123456789abcdef0123456789abcdef01234567",
|
||||
"Subject: links",
|
||||
"diff --git a/cfg/up b/cfg/up",
|
||||
"new file mode 120000",
|
||||
"--- /dev/null",
|
||||
"+++ b/cfg/up",
|
||||
"@@ -0,0 +1 @@",
|
||||
`+../${kv(PASSWORD)}`,
|
||||
"\\ No newline at end of file",
|
||||
"diff --git a/app.env b/app.env",
|
||||
"--- a/app.env",
|
||||
"+++ b/app.env",
|
||||
"@@ -1,2 +1,2 @@",
|
||||
`-path/${kv(API_KEY)}`,
|
||||
`+path/${API_KEY}=\${API_KEY}`,
|
||||
` a/${kv(TOKEN)}`,
|
||||
"",
|
||||
].join("\n");
|
||||
const out = redactFindingSpans(hunk) ?? "";
|
||||
expect(out).not.toContain(VALUE);
|
||||
expect(out.split("\n")).toHaveLength(hunk.split("\n").length);
|
||||
expect(out).toContain("+../password=<REDACTED-env.kv>");
|
||||
expect(out).toContain("-path/api_key=<REDACTED-env.kv>");
|
||||
expect(out).toContain(" a/token=<REDACTED-env.kv>");
|
||||
expect(out).toContain("+path/api_key=${API_KEY}");
|
||||
expect(out).toContain("diff --git a/cfg/up b/cfg/up");
|
||||
});
|
||||
|
||||
const clean = [
|
||||
"src/auth/token.ts",
|
||||
"lib/password-reset/index.ts",
|
||||
"docs/api_key.md",
|
||||
"routes/token/:id",
|
||||
"test/fixtures/session-cookie.json",
|
||||
"import { getToken } from '../auth/token';",
|
||||
"const token = await getToken(req);",
|
||||
"if (!password) throw new Error('password required');",
|
||||
"fetch('/oauth/token?grant_type=refresh_token')",
|
||||
"app.post('/api/session', login);",
|
||||
"see docs/auth/token for how rotation works",
|
||||
`cfg/${PASSWORD}=changeme`,
|
||||
`docs/${TOKEN}=<your-token-here>`,
|
||||
`url/${TOKEN}=\${TOKEN}`,
|
||||
`deploy/${API_KEY}=\$API_KEY`,
|
||||
`a/cacheKey=${VALUE}`,
|
||||
`a/sortKey=${VALUE}`,
|
||||
`+src/${TOKEN}=getToken(request)`,
|
||||
`// see a/${TOKEN}: rotated weekly by the ops team`,
|
||||
"const match = content.match(/authtoken:\\s*(.+)/);",
|
||||
"const re = /token=([A-Za-z0-9]+)/g;",
|
||||
`["// signal_key: 'test-discipline',", "hooks/preference.ts"],`,
|
||||
"if (!/api_key=[A-Za-z0-9]{20,}/.test(line)) return;",
|
||||
"return /token=([A-Za-z0-9]{8,})/;",
|
||||
];
|
||||
|
||||
for (const text of clean) {
|
||||
test(`negative control stays unredacted: ${text}`, () => {
|
||||
expect(envKv(text)).toEqual([]);
|
||||
expect(redact(text)).toBe(text);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const ROOT = path.resolve(import.meta.dir, "..");
|
||||
const launcher = path.join(ROOT, "bin", "gstack-cso-launcher");
|
||||
const MIB = 1024 * 1024;
|
||||
|
||||
describe.skipIf(process.platform === "win32")("/cso history never prints a key=value secret after a slash (GST-3297)", () => {
|
||||
let root = "";
|
||||
let state = "";
|
||||
beforeAll(() => {
|
||||
root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "cso-kv-slash-")));
|
||||
state = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "cso-kv-slash-state-")));
|
||||
});
|
||||
afterAll(() => {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
fs.rmSync(state, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
const git = (repo: string, ...args: string[]) => {
|
||||
const result = spawnSync("/usr/bin/git", ["-C", repo, ...args], { encoding: "utf8", env: { HOME: root, PATH: "/usr/bin:/bin" }, timeout: 60_000 });
|
||||
if (result.status) throw new Error(result.stderr);
|
||||
return result.stdout;
|
||||
};
|
||||
const cso = (repo: string, args: string[]) =>
|
||||
spawnSync(launcher, args, { cwd: repo, encoding: "utf8", env: { HOME: root, GSTACK_HOME: state, PATH: "/usr/bin:/bin" }, timeout: 120_000, maxBuffer: 64 * MIB });
|
||||
|
||||
test("link target, history-only link and file content are all redacted in history.txt and the history command", () => {
|
||||
const repo = path.join(root, "repo"),
|
||||
secrets = [j(VALUE, "1"), j(VALUE, "2"), j(VALUE, "3")];
|
||||
fs.mkdirSync(path.join(repo, "cfg"), { recursive: true });
|
||||
git(repo, "init", "-q");
|
||||
git(repo, "config", "user.email", "fixture@example.test");
|
||||
git(repo, "config", "user.name", "Fixture");
|
||||
fs.writeFileSync(path.join(repo, "README.md"), "readme\n");
|
||||
fs.symlinkSync(`../${kv(PASSWORD, secrets[0])}`, path.join(repo, "cfg", "up"));
|
||||
fs.symlinkSync(`a/${kv(TOKEN, secrets[1])}`, path.join(repo, "cfg", "gone"));
|
||||
fs.writeFileSync(path.join(repo, "cfg", "notes.txt"), `see path/${kv(API_KEY, secrets[2])}\nsrc/auth/token.ts\n`);
|
||||
git(repo, "add", "-A");
|
||||
git(repo, "commit", "-qm", "links");
|
||||
fs.unlinkSync(path.join(repo, "cfg", "gone"));
|
||||
git(repo, "add", "-A");
|
||||
git(repo, "commit", "-qm", "drop link");
|
||||
|
||||
const started = cso(repo, ["start", "--repo", repo, "--scope", "auth", "--offline"]);
|
||||
expect(started.stderr).toBe("");
|
||||
expect(started.status).toBe(0);
|
||||
const run = JSON.parse(started.stdout),
|
||||
dir = path.join(state, "security", "cso", run.repoId, run.runId),
|
||||
history = fs.readFileSync(path.join(dir, "history.txt"), "utf8"),
|
||||
printed = cso(repo, ["history", run.runId]);
|
||||
expect(printed.status).toBe(0);
|
||||
for (const text of [history, printed.stdout]) {
|
||||
expect(text).toContain("Subject: drop link");
|
||||
expect(text).toContain("src/auth/token.ts");
|
||||
for (const secret of secrets) expect(text).not.toContain(secret);
|
||||
}
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user