diff --git a/changelog.d/secrets-check-reads-rust.md b/changelog.d/secrets-check-reads-rust.md new file mode 100644 index 000000000..da7084988 --- /dev/null +++ b/changelog.d/secrets-check-reads-rust.md @@ -0,0 +1 @@ +**The secrets check now reads Rust.** A key written as `let token = "";` (or `let mut`, `const` or `static`, with or without a type) in a `.rs` file was never flagged; it now is, as `env.kv.rust`. Rust type annotations such as `token: Option<&str>,`, `key: &RelationshipKey,` and match arms such as `Token::Char(c) =>` in a `.rs` file no longer read as secrets, so Rust projects can drop their allowlist entries for them. Other languages' files are checked exactly as before; a scan with no file path also reports the new binding form. (GST-3474) diff --git a/docs/pregate.md b/docs/pregate.md index 4b044e8be..30c3b8029 100644 --- a/docs/pregate.md +++ b/docs/pregate.md @@ -1958,6 +1958,23 @@ those, each with its scope and its reason: read from the value, never from the key's name or the file's path, and a secret in the same position, a literal after it on the line, or the same text in a config file still reports. +- Rust (GST-3474): in a `.rs` file, a type annotation at the start of a line + (`token: Option<&str>,`, `key: &RelationshipKey,`, + `by_key: Mutex>,`) and a match arm's path + (`Token::Char(c) => {`) are code, not credentials. A literal, an `=`, a + second field on the line, or a name that reads as random still reports. + So does a value with no closing comma or one that is not type-shaped (a + lowercase name that is not a primitive like `u32` or `str`, or an all-caps + word), because pregate reads a `.rs` file's added lines alone and cannot see + a string or block comment around them. Known limit: a line inside a Rust + string or block comment that reads exactly like a field annotation + (`token: Option,`) passes. + A key bound with `let`, `let mut`, `const` or `static` + (`let token = "";`, `const API_KEY: &str = "";`) reports as + `env.kv.rust`; with a file path it reports only in a `.rs` file. A scan + without a path reports it too, and the pre-push hook scans Dart and Python + files without one, so a Dart `const token = "";` gets an `env.kv.rust` + warning there. - 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 diff --git a/lib/redact-patterns.ts b/lib/redact-patterns.ts index 0f97cb836..71167845d 100644 --- a/lib/redact-patterns.ts +++ b/lib/redact-patterns.ts @@ -1116,6 +1116,66 @@ function isSourceExpression(span: string, match: RegExpExecArray, sourcePath: st return !insideString(match.input, start, sourcePath); } +/** + * GST-3474: in Rust source, `name: Type` at the start of a line is a struct + * field or parameter type (`token: Option<&str>,`, `key: &RelationshipKey,`) + * and `Name::Variant(..) =>` is a match arm's path pattern; neither holds a + * value. Only a line-start match with an unquoted name and a `:` passes, and + * only when its code up to a trailing `//` comment is made of Rust type and + * pattern tokens: names, paths, lifetimes, `&`, `*`, brackets, `+`, `?`, + * `!`, `|`, `->`, `=>`, an array length after `;`, and one closing `,` + * with nothing after it, which a field or parameter line has and a line of + * text does not (a match arm needs no comma). A lowercase name is a primitive + * or keyword (`u32`, `str`, `dyn`), a path segment before `::` or a match + * arm's binding; an all-caps name over four letters is a path segment or an + * array length. pregate reads a .rs file's added lines alone, so a + * `token: ` line inside a string or block comment arrives looking like + * code: a lowercase, all-caps or comma-less value there still reports. A + * string or char literal, an `=` assignment, a `.`, a `;`, a second field, or + * a name that reads as random (three digit runs, a word over 20 letters, or + * case changes about every two letters in a name of 12 or more) still reports. + * Another file, a scan without a path, a comment and a `/` start are unchanged. + */ +const RUST_SOURCE = /\.rs$/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 { + if ((name.match(/\d+/g) ?? []).length > 2) return false; + const words = name.match(/[A-Z]+(?![a-z])|[A-Z]?[a-z]+/g) ?? []; + if (words.some((word) => word.length > 20)) return false; + return name.length < 12 || words.join("").length >= 3 * words.length; +} +function isRustTypeAnnotation(span: string, match: RegExpExecArray, sourcePath: string | undefined): boolean { + if (!sourcePath || !RUST_SOURCE.test(sourcePath)) return false; + if (match.index > 0 && match.input[match.index - 1] !== "\n") return false; + const { start } = spanBounds(match); + if (!/^[ +-]{0,2}[ \t]*[A-Za-z_]\w*[ \t]*:[ \t]*$/.test(match.input.slice(match.index, start))) return false; + const code = match.input.slice(start).split("\n", 1)[0]!.replace(/\r$/, "").replace(/[ \t]*\/\/.*$/, ""); + const arm = code.startsWith(":") && code.includes("=>"); + let depth = 0; + let closed = false; + let previous = ""; + for (let i = 0; i < code.length; ) { + RUST_TYPE_TOKEN.lastIndex = i; + const token = RUST_TYPE_TOKEN.exec(code)?.[0]; + if (!token) return false; + i += token.length; + if (/^[ \t]/.test(token)) continue; + if (closed) return false; + if (/^\d/.test(token) ? previous !== ";" : /^[A-Za-z_]/.test(token) && !readsAsRustName(token)) return false; + if (/^[A-Za-z_]/.test(token) && !code.startsWith("::", i)) { + if (/^[a-z_]/.test(token) && !RUST_LOWERCASE_TYPE.test(token) && !(arm && depth > 0)) return false; + if (!/[a-z]/.test(token) && token.length > 4 && previous !== ";") return false; + } + if (/^[<([{]$/.test(token)) depth += 1; + else if (/^[>)\]}]$/.test(token)) depth = Math.max(0, depth - 1); + else if (depth === 0 && token === ";") return false; + else if (depth === 0 && token === ",") closed = true; + previous = token; + } + return closed || arm; +} + /** * #4209: in Python and Dart source, an unquoted dotted name chain that is the * whole right-hand side of an `=` assignment (`session = self.client.session`, @@ -1736,6 +1796,7 @@ export const PATTERNS: RedactPattern[] = [ // #2899: a function call assigned to the name is code, not a value (see // isCallExpression). #3048, #3630: so is a TS/JSX/Dart/Python type or expression (isSourceExpression). // #4209: so is a dotted attribute read assigned with = in Python or Dart (isAttributeReference). + // 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). // GST-3004: so is a dotted field path (isDottedFieldPath, #4289), and so @@ -1752,6 +1813,7 @@ export const PATTERNS: RedactPattern[] = [ !isBareEnvRead(span, match) && !isCallExpression(span, match) && !isSourceExpression(span, match, opts?.sourcePath) && + !isRustTypeAnnotation(span, match, opts?.sourcePath) && !isAttributeReference(span, match, opts?.sourcePath) && !isDottedFieldPath(span, match, opts?.sourcePath) && !isCommentText(span, match) && @@ -1760,6 +1822,32 @@ export const PATTERNS: RedactPattern[] = [ !isTestFixtureLabel(span, opts?.sourcePath) && shannonEntropy(span) >= 3.0)), }, + { + id: "env.kv.rust", + tier: "MEDIUM", + category: "secret", + description: "Secret-named Rust let, const or static binding with a high-entropy string literal", + // GST-3474 (gbrain #10028): env.kv needs the name to start its line (or + // follow a comment marker or `/`), so `let token = "";` and + // `const API_KEY: &str = "";` in a .rs file gave no finding while + // `token: ""` did. This rule reads a `let`, `let mut`, `const`, + // `static` or `static mut` binding, with an optional `pub` or `pub(..)`, + // an optional type, and a string, raw or byte literal that is the value + // itself or the first argument of `Some`, `String::from`, `Box::new` or + // `Cow::Borrowed`/`Cow::Owned`, at a line start (diff markers as env.kv) + // or after `//`, `///`, `//!`, `/*` or `/**`. It is its own pattern so + // env.kv's matches, and the spans they consume, are unchanged in every + // file. validate keeps it to Rust: a scan with a path reports it only in a + // .rs file, so a JS or TS `let` or `const` reads exactly as before; a scan + // without a path reports it. The name and value get env.kv's checks: a + // credential-shaped name, no placeholder or `${` read, and 3.0 bits. + regex: /(?:^(?:[ +-]?\+|[ +-]?-(?! [^ \t]))?|(?<=(?:^|[ \t])(?:\/{2,3}!?|\/\*{1,2})))[ \t]*(?:pub(?:\([a-z:_ \t]{0,40}\))?[ \t]+)?(?:let|const|static)[ \t]+(?:mut[ \t]+)?[A-Za-z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIALS?|DSN|AUTH|COOKIE|SESSION|PRIVATE)(?:[ \t]*:[^=\n]{1,120}?)?[ \t]*=[ \t]*&?[ \t]*(?:(?:Some|String::from|Box::new|Cow::Borrowed|Cow::Owned)\([ \t]*&?)?(?:b?r#{0,3}|b)?"([^\s"\\]{8,})/i, + validate: (span, match, opts) => { + if (opts?.sourcePath && !RUST_SOURCE.test(opts.sourcePath)) return false; + const name = /\b(?:let|const|static)[ \t]+(?:mut[ \t]+)?(\w+)/i.exec(match[0])?.[1]; + return !!name && isCredentialShapedEnvName(`${name}=`) && !isPlaceholderSpan(span) && !/^\$\{?[A-Za-z_]/.test(span) && shannonEntropy(span) >= 3.0; + }, + }, { id: "auth.bearer", tier: "MEDIUM", diff --git a/test/pregate-secrets-source-context.test.ts b/test/pregate-secrets-source-context.test.ts index 1686b5ee0..ecbd49bf3 100644 --- a/test/pregate-secrets-source-context.test.ts +++ b/test/pregate-secrets-source-context.test.ts @@ -129,6 +129,16 @@ describe('pregate secrets: source context and diff integrity', () => { expect({ status: r.status, rows: r.lines.filter((l) => l.includes('env.kv')).sort() }).toEqual({ status: 'fail', rows: [expect.stringContaining('(app/storage.py, line 5)'), expect.stringContaining('(src/launch.ts, added line 6)')] }); }); + // Value: protects=pregate's secrets check passes a Rust file of type annotations and fails a key bound with let or const in a .rs file; fails_when=Rust + // type annotations block a push again, or a let or const binding of a key passes it; why_new=GST-3474 came from gbrain #10028's pregate runs; seam=fixture repo; no_claim=other languages + test('Rust type annotations pass; a key bound with let or const in a .rs file still fails (GST-3474)', () => { + const secret = ['sk-live-FAKE-', 'Qx9vL2mZ', 'p8Rt4Kw7', 'Yn3Bh2Jd'].join(''); + const rs = "pub struct Index<'a> {\n token: Option<&'a str>,\n key: &'a RelationshipKey,\n by_key: Mutex>,\n}\n"; + expect(repo({ 'src/index.rs': rs }).secrets()).toMatchObject({ status: 'pass', lines: [] }); + const r = repo({ 'src/index.rs': rs + 'fn connect() {\n let token = "' + secret + '";\n}\nconst API_KEY: &str = "' + secret + '";\n' }).secrets(); + expect({ status: r.status, rows: r.lines.filter((l) => l.includes('env.kv')).sort() }).toEqual({ status: 'fail', rows: [expect.stringContaining('(src/index.rs, added line 7)'), expect.stringContaining('(src/index.rs, added line 9)')] }); + }); + test('parseAddedLineNumbers numbers each added line from its hunk header', () => { const diff = ['diff --git a/a.py b/a.py', '--- a/a.py', '+++ b/a.py', '@@ -3,0 +4,2 @@', '+one', '+two', '@@ -9 +11 @@', '-old', '+new'].join('\n'); expect([...parseAddedLineNumbers(diff)]).toEqual([['a.py', [4, 5, 11]]]); diff --git a/test/redact-diff-prefix.test.ts b/test/redact-diff-prefix.test.ts index b7a2bdacd..98a4e6a35 100644 --- a/test/redact-diff-prefix.test.ts +++ b/test/redact-diff-prefix.test.ts @@ -51,6 +51,7 @@ const SAMPLES: Record = { "google.api_key": j("AIza", "SyA1b2C3d4E5f6G7h8I9j0K1l2M3n4O5p6Q"), "jwt": ["eyJhbGciOiJIUzI1NiJ9", "eyJzdWIiOiIxMjM0NTY3ODkwIn0", "dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U"].join("."), "env.kv": j("API_TOKEN=", "8Fk2pQ9vXz4wL7mN3rT6yB1cD5eG0hJ"), + "env.kv.rust": j('let api_token = "', "8Fk2pQ9vXz4wL7mN3rT6yB1cD5eG0hJ", '";'), "auth.bearer": j("Authorization: Bearer ", "a1B2c3D4e5F6g7H8i9J0k1L2"), "pii.email": j("dana.whitfield@", "acmecorp.io"), "pii.phone.e164": j("+1415", "5552671"), diff --git a/test/redact-env-kv-rust.test.ts b/test/redact-env-kv-rust.test.ts new file mode 100644 index 000000000..d95ccaf5f --- /dev/null +++ b/test/redact-env-kv-rust.test.ts @@ -0,0 +1,106 @@ +/** + * GST-3474 (gbrain #10028): env.kv did not read Rust. A secret bound with + * `let`, `let mut`, `const` or `static` (`let token = "";`) gave no + * finding, because the name had to start the line. And a Rust type annotation + * (`token: Option<&str>,`, `key: &RelationshipKey,`) or a match arm's path + * (`Token::Char(c) => {`) read as a secret-named value, so every Rust landing + * needed allowlist entries. The binding now reports as env.kv.rust in a .rs + * file or a scan without a path, and a type annotation in a .rs file passes; + * every hold case below puts a secret in the same position and still reports. + */ +// Value: protects=a secret in a Rust let, const or static binding reports and a Rust type annotation passes; fails_when=the binding miss returns, a type annotation reports again, the binding rule fires in another language's file, or the annotation exemption lets a literal, a random name or a second field through; why_new=GST-3474 had no Rust case; 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 { scan } from "../lib/redact-engine"; + +const ids = (text: string, sourcePath?: string) => + scan(text, { repoVisibility: "private", processEnv: {}, ...(sourcePath ? { sourcePath } : {}) }).findings.map((f) => f.id); +const S = "Qx9vL2mZp8Rt4Kw7Yn3Bh2Jd"; +const FAKE = ["sk", "live", "FAKE", S].join("-"); +const LETTERS = "QxvLmZpRtKwYnBhJdTqWsV"; +const has = (id: string, cases: ReadonlyArray, want: boolean) => { + for (const [code, file] of cases) expect({ code, file, hit: ids(code, file).includes(id) }).toEqual({ code, file, hit: want }); +}; + +describe("env.kv.rust: a secret in a Rust binding reports (GST-3474)", () => { + test("let, let mut, const, static and their visibility, type and literal forms report", () => { + has("env.kv.rust", [ + ['let token = "' + FAKE + '";', "src/lib.rs"], + [' let token = "' + S + '";', "src/lib.rs"], + ['let mut api_key = "' + S + '";', "src/lib.rs"], + ['const API_KEY: &str = "' + S + '";', "src/lib.rs"], + ["pub const API_KEY: &'static str = \"" + S + '";', "src/lib.rs"], + ['pub(crate) static SESSION_SECRET: &str = "' + S + '";', "src/lib.rs"], + ['static mut AUTH_TOKEN: &str = "' + S + '";', "src/lib.rs"], + [' let token: &str = "' + S + '";', "src/lib.rs"], + [' let client_secret = String::from("' + S + '");', "src/lib.rs"], + [' let token = "' + S + '".to_string();', "src/lib.rs"], + [' let token = r#"' + S + '"#;', "src/lib.rs"], + [' let password = b"' + S + '";', "src/lib.rs"], + [' // let token = "' + S + '";', "src/lib.rs"], + ['let token = "' + S + '";', undefined], + ['diff --git a/src/lib.rs b/src/lib.rs\n+++ b/src/lib.rs\n@@ -0,0 +1 @@\n+ let token = "' + S + '";\n', undefined], + ], true); + }); + + test("benign: a placeholder, an environment read, a short or low-entropy value and a non-credential name give no finding", () => { + has("env.kv.rust", [ + ['let token = "changeme";', "src/lib.rs"], + ['let token = "${API_TOKEN}";', "src/lib.rs"], + ['let token = env::var("API_TOKEN")?;', "src/lib.rs"], + ['let token = std::env::var("GITHUB_TOKEN").unwrap_or_default();', "src/lib.rs"], + ['let token = "short";', "src/lib.rs"], + ["let token = None;", "src/lib.rs"], + ['let monkey = "' + S + '";', "src/lib.rs"], + ['let token_count = "' + S + '";', "src/lib.rs"], + ], false); + }); + + test("scoped to Rust: the same binding in another language's file is not read by the Rust rule", () => { + has("env.kv.rust", [ + ['let token = "' + S + '";', "src/client.ts"], + ['const token = "' + S + '";', "src/client.js"], + ['static token = "' + S + '"', "app/client.py"], + ], false); + }); +}); + +describe("env.kv: a Rust type annotation is code, not a secret (GST-3474)", () => { + test("struct fields, parameters and match-arm paths in a .rs file pass", () => { + has("env.kv", [ + [" token: Option<&str>,", "src/lib.rs"], + [" key: &RelationshipKey,", "src/lib.rs"], + [" by_key: Mutex>,", "src/lib.rs"], + [" Token::Char(c) => {", "src/lib.rs"], + [" session: Arc>,", "src/lib.rs"], + [" auth: Box bool + Send + Sync>,", "src/lib.rs"], + [" private_key: &'a [u8; 32],", "src/lib.rs"], + [" session_token: Option, // refreshed on login", "src/lib.rs"], + [" private_key: [u8; KEY_LEN],", "src/lib.rs"], + ], false); + }); + + test("hold: a literal, a random name, a second field, a quoted name, a comment and other files still report", () => { + has("env.kv", [ + [' token: "' + S + '",', "src/lib.rs"], + [" key: &" + S + ",", "src/lib.rs"], + [" token: " + LETTERS + ",", "src/lib.rs"], + [' token: Option<&str> = "' + S + '",', "src/lib.rs"], + [" token: Option<&str>, other: " + S + ",", "src/lib.rs"], + [' "token": Option<&str>,', "src/lib.rs"], + [" token: Option<&str>, // token: " + S, "src/lib.rs"], + ["// token: " + S, "src/lib.rs"], + [" token: Option<&str>,", "deploy/values.yaml"], + [" key: &RelationshipKey,", undefined], + [" Token::Char(c) => {", "src/lexer.ts"], + ], true); + }); + + test("hold: a credential line inside a string, a struct literal's value and a comma-less line still report", () => { + has("env.kv", [ + ['const CFG: &str = r#"\nstripe:\n token: qxvlmzprtkwynbhjdtwa\n"#;\n', "src/cfg.rs"], + ['const CFG: &str = "\nauth:\n token: QXVLMZPRTKWYNBHJ\n";\n', "src/cfg.rs"], + [" password: Hunter2password", "src/cfg.rs"], + [" token: auth_token_value,", "src/lib.rs"], + ], true); + }); +});