Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Redaction in time proportional to the text: bound the name, scheme and JWT parts (#6852)

Milind Soni60ba1c0df9e8
diff --git a/shared/redact-linear.test.ts b/shared/redact-linear.test.ts
new file mode 100644
index 0000000000..4e61af8cf0
--- /dev/null
+++ b/shared/redact-linear.test.ts
@@ -0,0 +1,81 @@
+// Redaction runs on the server's only thread for every engine event, protocol line and tool result, so its work must grow
+// with the text, never with its square: a quadratic pattern held a Cloud home's thread for minutes on one tool output of a
+// few MB (a base64url blob), and the home stopped answering its health checks.
+import { randomBytes } from "node:crypto";
+import { describe, expect, it } from "vitest";
+
+import { redactSecretsInText } from "./redact.ts";
+
+const MB = 1_048_576;
+const timed = (text: string) => { const at = performance.now(); const out = redactSecretsInText(text); return { out, ms: performance.now() - at }; };
+
+describe("redactSecretsInText on large text", () => {
+ // Each took seconds to minutes before (2 MB of base64url: about 4 minutes, measured; 2 MB of BEGIN lines with no END:
+ // about 50 s); now well under a second each. The bound here is wide, so a slow machine never fails it.
+ const shapes: Array<[string, () => string]> = [
+ ["base64url", () => randomBytes(Math.ceil((2 * MB * 3) / 4)).toString("base64url").slice(0, 2 * MB)],
+ ["hyphenated words", () => "ab-".repeat(MB / 3)],
+ ["names ending in -key", () => "a-key".repeat(MB / 5)],
+ ["JWT-like starts", () => `-eyJ${"a".repeat(30)}`.repeat(MB / 34)],
+ ["private key BEGIN lines with no END", () => "fixtures/key.pem:-----BEGIN RSA PRIVATE KEY-----\n".repeat((2 * MB) / 50)],
+ ["a long scheme-like run", () => `${"a".repeat(MB)}://`],
+ ];
+ for (const [name, make] of shapes) {
+ it(`takes time in proportion to the text: ${name}`, () => {
+ const text = make();
+ const { out, ms } = timed(text);
+ expect(ms).toBeLessThan(10_000);
+ expect(out.length).toBeGreaterThan(0);
+ });
+ }
+
+ it("still masks what it masked before, the blob around it unchanged", () => {
+ const blob = randomBytes(300_000).toString("base64url");
+ const text = `${blob} MY_SERVICE_API_KEY=abcd1234efgh ${blob}`;
+ const out = redactSecretsInText(text);
+ expect(out).not.toContain("abcd1234efgh");
+ expect(out.startsWith(blob)).toBe(true);
+ expect(out.endsWith(blob)).toBe(true);
+ });
+});
+
+describe("redactSecretsInText: names, schemes, JWTs and key blocks of any length", () => {
+ it("masks a secret whose name has a long prefix, the name kept as it was", () => {
+ const name = `${"A".repeat(140)}_API_KEY`;
+ expect(redactSecretsInText(`${name}=abcd1234efgh`)).toBe(`${name}=«redacted 12 chars»`);
+ expect(redactSecretsInText(`${"SEG_".repeat(35)}TOKEN=abcd1234efgh`)).not.toContain("abcd1234efgh");
+ expect(redactSecretsInText(`${"b".repeat(140)}-key=v4lue`)).toBe(`${"b".repeat(140)}-key=«redacted 5 chars»`);
+ const hyphens = Array.from({ length: 60 }, () => "seg").join("-");
+ expect(redactSecretsInText(`${hyphens}-key=v4lue`)).not.toContain("v4lue");
+ expect(redactSecretsInText(`${hyphens}_token=abcd1234efgh`)).not.toContain("abcd1234efgh");
+ });
+
+ it("masks a URL password after a scheme of 40 characters", () => {
+ const scheme = "a".repeat(40);
+ expect(redactSecretsInText(`${scheme}://user:hunter2pass@host`)).toBe(`${scheme}://user:«redacted 11 chars»@host`);
+ expect(redactSecretsInText("postgres://admin:[email protected]/app")).not.toContain("hunter2pass");
+ });
+
+ it("masks a JWT whatever its size, and only from a word boundary to one", () => {
+ for (const payload of [40, 12_000, 40_000]) {
+ const jwt = `eyJ${"h".repeat(40)}.${"p".repeat(payload)}.${"s".repeat(342)}`;
+ expect(redactSecretsInText(`token was ${jwt} here`)).toBe(`token was «redacted ${jwt.length} chars» here`);
+ }
+ const jwt = `eyJ${"h".repeat(20)}.${"p".repeat(40)}.${"s".repeat(40)}`;
+ // Trailing dashes are not part of it; one glued to a word is not one; a short part makes none.
+ expect(redactSecretsInText(`(${jwt}--)`)).toBe(`(«redacted ${jwt.length} chars»--)`);
+ expect(redactSecretsInText(`x${jwt}`)).toBe(`x${jwt}`);
+ expect(redactSecretsInText(`a eyJhhhhhhhh.pppp.ssssssssss b`)).toBe("a eyJhhhhhhhh.pppp.ssssssssss b");
+ // In a long run of base64url, after a dash.
+ const blob = randomBytes(50_000).toString("base64url");
+ expect(redactSecretsInText(`${blob}-${jwt} z`)).toBe(`${blob}-«redacted ${jwt.length} chars» z`);
+ });
+
+ it("masks each private key block up to its first END, and leaves a BEGIN with no END as it was", () => {
+ const block = (body: string) => `-----BEGIN RSA PRIVATE KEY-----\n${body}\n-----END RSA PRIVATE KEY-----`;
+ expect(redactSecretsInText(`a ${block("MIIEsecret1")} b ${block("MIIEsecret22")} c`))
+ .toBe(`a -----BEGIN RSA PRIVATE KEY-----\n«redacted 11 chars»\n-----END RSA PRIVATE KEY----- b -----BEGIN RSA PRIVATE KEY-----\n«redacted 12 chars»\n-----END RSA PRIVATE KEY----- c`);
+ const open = "-----BEGIN PRIVATE KEY-----\nMIIEnoend";
+ expect(redactSecretsInText(open)).toBe(open);
+ });
+});
diff --git a/shared/redact.ts b/shared/redact.ts
index 3183f116f0..275bce2e43 100644
--- a/shared/redact.ts
+++ b/shared/redact.ts
@@ -36,35 +36,91 @@ const KEY_PREFIXES: RegExp[] = [
/\bwhsec_[A-Za-z0-9_-]{20,}/g, // webhook secrets, alone or in an automation's address
/\bSG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}(?![A-Za-z0-9_-])/g, // sendgrid api keys
/\bbak_[A-Za-z0-9_-]{20,}/g, // Bot API keys
- /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g, // jwt
];
const KEY_PREFIX_TESTS = KEY_PREFIXES.map((re) => new RegExp(re.source));
const PRIVATE_KEY_BLOCK = /-----BEGIN [A-Z ]*PRIVATE KEY-----/;
+// A JWT: `eyJ` at a word boundary, then three runs of base64url of 8 or more, joined by dots, ending at a word boundary
+// (`/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/`). Found by a scan, not that pattern: the pattern
+// read from every `eyJ` in a long run of base64url to the run's end, so its work grew with the square of the text. Every
+// `eyJ` in one run reaches the same dot, so a run that fails for one fails for all after it, and the scan moves past it.
+const JWT_RUN = /[A-Za-z0-9_-]*/y;
+const WORD = /[A-Za-z0-9_]/;
+const runEnd = (text: string, from: number) => { JWT_RUN.lastIndex = from; JWT_RUN.test(text); return JWT_RUN.lastIndex; };
+/** Each JWT in the text as [start, end), in order. */
+function* jwtSpans(text: string): Generator<[number, number]> {
+ for (let from = 0; ;) {
+ const at = text.indexOf("eyJ", from);
+ if (at < 0) return;
+ if (at > 0 && WORD.test(text[at - 1]!)) { from = at + 1; continue; }
+ const first = runEnd(text, at);
+ if (first - at - 3 < 8 || text[first] !== ".") { from = Math.max(first, at + 1); continue; }
+ const second = runEnd(text, first + 1);
+ if (second - first - 1 < 8 || text[second] !== ".") { from = first; continue; }
+ let third = runEnd(text, second + 1);
+ // The last part ends at a word boundary: trailing dashes are not part of it.
+ while (third > second + 1 && text[third - 1] === "-") third -= 1;
+ if (third - second - 1 < 8) { from = first; continue; }
+ yield [at, third];
+ from = third;
+ }
+}
+function maskJwts(text: string): string {
+ let out = "", last = 0;
+ for (const [start, end] of jwtSpans(text)) { out += text.slice(last, start) + mask(text.slice(start, end)); last = end; }
+ return last === 0 ? text : out + text.slice(last);
+}
+
+// A private key block: its BEGIN line, the body up to the first END line after it, and that END line. Found by a scan for
+// the same reason as a JWT: a lazy pattern read from every BEGIN with no END to the end of the text. With no END after one
+// BEGIN there is none after any later one, so the scan stops.
+const PEM_BEGIN = /-----BEGIN [A-Z ]*PRIVATE KEY-----/g;
+const PEM_END = /-----END [A-Z ]*PRIVATE KEY-----/g;
+function maskPemBlocks(text: string): string {
+ let out = "", last = 0;
+ for (PEM_BEGIN.lastIndex = 0; ;) {
+ const begin = PEM_BEGIN.exec(text);
+ if (!begin) break;
+ PEM_END.lastIndex = PEM_BEGIN.lastIndex;
+ const end = PEM_END.exec(text);
+ if (!end) break;
+ out += `${text.slice(last, begin.index)}${begin[0]}\n${mask(text.slice(PEM_BEGIN.lastIndex, end.index).trim())}\n${end[0]}`;
+ last = PEM_END.lastIndex;
+ PEM_BEGIN.lastIndex = last;
+ }
+ return last === 0 ? text : out + text.slice(last);
+}
+
/** Only shapes that are unmistakably a credential (a provider's key prefix, a private key block), never a name or a
* placeholder: text holding one is a credential store, not instructions. */
export function holdsCredential(text: string): boolean {
- return PRIVATE_KEY_BLOCK.test(text) || KEY_PREFIX_TESTS.some((re) => re.test(text));
+ return PRIVATE_KEY_BLOCK.test(text) || KEY_PREFIX_TESTS.some((re) => re.test(text)) || !jwtSpans(text).next().done;
}
const BEARER = /(\bBearer\s+)([A-Za-z0-9._~+/=-]{12,})/g;
/** `Authorization: Basic dXNlcjpwYXNz`: the base64 is `user:password` in the clear. Only after an
* Authorization header, so prose like "Basic configuration" stays. */
const BASIC_AUTH = /(\bAuthorization["']?\s*[:=]\s*["']?Basic\s+)([A-Za-z0-9+/]{4,}={0,2})(?![A-Za-z0-9._~+/=-])/gi;
-const PEM_BLOCK = /(-----BEGIN [A-Z ]*PRIVATE KEY-----)([\s\S]*?)(-----END [A-Z ]*PRIVATE KEY-----)/g;
/** key=value / key: value / key="value" where the key is secret-shaped.
* The value must be a single token of some length; prose after a colon
- * ("password: leave blank…") has spaces and does not match. */
+ * ("password: leave blank…") has spaces and does not match.
+ *
+ * The name before the secret word is not part of the match, only that no letter or digit comes right before the word
+ * (`MY_SERVICE_API_KEY`, `x-token`): a match that began at the name read every word boundary in a long run of name
+ * characters (a base64url blob, `a-b-c-…`) to the run's end and back, and one 400 KB tool output held the server's only
+ * thread about ten seconds, a few MB for minutes. The output is the same: the name is left as it was. */
const KEY_VALUE =
- /\b((?:[A-Za-z0-9_-]*_)?(?:api[_-]?key|apikey|secret|token|password|passwd|authorization|auth[_-]?token|access[_-]?key|private[_-]?key)s?)(["']?\s*[=:]\s*)(["']?)([A-Za-z0-9._~+/=-]{8,})\3/gi;
+ /(?<![A-Za-z0-9])((?:api[_-]?key|apikey|secret|token|password|passwd|authorization|auth[_-]?token|access[_-]?key|private[_-]?key)s?)(["']?\s*[=:]\s*)(["']?)([A-Za-z0-9._~+/=-]{8,})\3/gi;
/** `X_KEY=value`, `xai-key=value`: an assignment to a name that ENDS in key
* is a credential whatever the value looks like, so no length floor. The
- * separator before `key` is what keeps `hotkey=` and `keyboard=` out. */
-const KEY_SUFFIX_ASSIGNMENT = /\b([A-Za-z][A-Za-z0-9_-]*[_-]key)s?(=)(["']?)([A-Za-z0-9._~+/=-]+)\3/gi;
+ * separator before `key` is what keeps `hotkey=` and `keyboard=` out. Only the `_key`/`-key` end is matched, after any
+ * name character, for the reason KEY_VALUE's name is not. */
+const KEY_SUFFIX_ASSIGNMENT = /(?<=[A-Za-z0-9_-])([_-]key)s?(=)(["']?)([A-Za-z0-9._~+/=-]+)\3/gi;
/** `--token abc`, `--password=abc`: the flag names a secret; the value is
* whatever single token follows, never another flag. */
const SECRET_FLAG = /(--(?:token|password|passwd|api-key|apikey|secret|access-key|auth-token)(?:=|\s+))(["']?)(?!-)([A-Za-z0-9._~+/=-]+)\2/gi;
-/** `scheme://user:secret@host` — the password in a URL's userinfo. */
-const URL_USERINFO = /(\b[a-z][a-z0-9+.-]*:\/\/[^\s/:@'"]+:)([^\s/@'"«»]+)(@)/gi;
+/** `scheme://user:secret@host` — the password in a URL's userinfo. At most the scheme's last 32 characters are matched
+ * (a longer one keeps the rest as it was), with no word boundary before it, for the reason KEY_VALUE's name is not. */
+const URL_USERINFO = /([a-z][a-z0-9+.-]{0,31}:\/\/[^\s/:@'"]+:)([^\s/@'"«»]+)(@)/gi;
// A saved website password has no shape: it is known by value. The server
// registers a scrubber for the values it holds, and every redaction below
@@ -94,8 +150,9 @@ export function redactSecretsInText(text: string): string {
const held = scrubHeldSecrets(text);
if (held.length < 8) return held;
let out = held;
- out = out.replace(PEM_BLOCK, (_m, open: string, body: string, close: string) => `${open}\n${mask(body.trim())}\n${close}`);
+ out = maskPemBlocks(out);
for (const re of KEY_PREFIXES) out = out.replace(re, (m) => mask(m));
+ out = maskJwts(out);
out = out.replace(BEARER, (_m, lead: string, tok: string) => `${lead}${mask(tok)}`);
out = out.replace(BASIC_AUTH, (_m, lead: string, creds: string) => `${lead}${mask(creds)}`);
out = out.replace(KEY_VALUE, (_m, key: string, sep: string, quote: string, value: string) => `${key}${sep}${quote}${mask(value)}${quote}`);