Skip to content

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

16.5 KB
Raw Blame
// The exact shapes the drivers write (ACP `env: [{name,value}]` and claude's mcpServers object), so a shape change breaks the test, not the secret.
import { describe, expect, it } from "vitest";

import { holdsCredential } from "../shared/redact.ts";
import { redactSecrets } from "./redact.ts";

const flat = (value: unknown) => JSON.stringify(value);

describe("redactSecrets", () => {
  it("omits private MCP descriptors even when a credential uses an ordinary header name", () => {
    const descriptor = JSON.stringify({ url: "https://example.test/mcp", headers: { "x-tenant": "private-synthetic-value" } });
    const record = `OMB_REMOTE_MCP_CONFIG_${"0".repeat(64)}`;
    const logged = redactSecrets({ params: { mcpServers: [{ env: [{ name: "OMB_GATE_UPSTREAM", value: descriptor }] }] }, env: { OMB_REMOTE_MCP_SERVER: descriptor, [record]: JSON.stringify({ OMB_REMOTE_MCP_SERVER: descriptor }) } });
    expect(flat(logged)).not.toContain("private-synthetic-value");
    expect(flat(logged)).toContain("OMB_GATE_UPSTREAM");
    expect(flat(logged)).toContain(record);
  });
  it("masks the tokens in an ACP session/new, keeping the shape", () => {
    const sessionNew = {
      jsonrpc: "2.0",
      id: 3,
      method: "session/new",
      params: {
        cwd: "/Users/someone",
        mcpServers: [
          {
            name: "agents",
            command: "/usr/bin/node",
            args: ["/app/agents-proxy.js"],
            env: [
              { name: "OMB_BOT_ID", value: "bot-123" },
              { name: "OMB_COMMS_TOKEN", value: "s3cret-comms-token-value" },
            ],
          },
          {
            name: "computer",
            command: "/usr/bin/node",
            args: ["/app/computer-proxy.js"],
            env: [
              { name: "OGB_BOX_ID", value: "boat-9" },
              { name: "OGB_BOX_TOKEN", value: "box_live_abcdefghijklmnop" },
            ],
          },
        ],
      },
    };

    const out = flat(redactSecrets(sessionNew));

    expect(out).not.toContain("s3cret-comms-token-value");
    expect(out).not.toContain("box_live_abcdefghijklmnop");
    expect(out).toContain("session/new");
    expect(out).toContain("OMB_COMMS_TOKEN");
    expect(out).toContain("OGB_BOX_TOKEN");
    expect(out).toContain("bot-123");
    expect(out).toContain("boat-9");
    expect(out).toContain("/app/agents-proxy.js");
    expect(out).toContain("«redacted 24 chars»");
  });

  it("masks a Composio key in an MCP header and an env object", () => {
    const config = {
      mcpServers: {
        composio: {
          type: "http",
          url: "https://app.composio.dev/tool_router/v3/trs_test/mcp",
          headers: { "x-api-key": "ak_live_supersecret" },
        },
        computer: { env: { ELECTRON_RUN_AS_NODE: "1", OGB_BOX_TOKEN: "box_live_zzz" } },
      },
    };

    const out = flat(redactSecrets(config));
    expect(out).not.toContain("ak_live_supersecret");
    expect(out).not.toContain("box_live_zzz");
    expect(out).toContain("app.composio.dev");
    expect(out).toContain("ELECTRON_RUN_AS_NODE");
    expect(out).toContain('"1"');
  });

  it("still content-redacts an ACP env entry whose name is not secret-shaped", () => {
    const alpha = "abcdefghijklmnopqrstuvwxyz0123456789";
    const leaked = `sk-ant-api03-${alpha}`;
    const sessionNew = {
      params: {
        mcpServers: [
          {
            name: "custom",
            env: [
              { name: "SESSION_CONFIG", value: leaked },
              { name: "FEATURE_FLAG", value: "enabled" },
            ],
          },
        ],
      },
    };

    const out = flat(redactSecrets(sessionNew));
    expect(out).not.toContain(leaked);
    expect(out).toContain("SESSION_CONFIG");
    expect(out).toContain("FEATURE_FLAG");
    expect(out).toContain("enabled");
    expect(out).toMatch(/«redacted \d+ chars»/);
  });

  it("leaves ordinary protocol traffic alone", () => {
    const update = {
      method: "session/update",
      params: { update: { sessionUpdate: "agent_message_chunk", content: { text: "the key to this bug" } } },
    };
    expect(redactSecrets(update)).toEqual(update);
  });

  it("does not mangle words that merely contain 'key'", () => {
    const msg = { keyboard: "cmd+k", monkey: "business", keys: "SECRET-LIST", hotkey: "ctrl" };
    const out = redactSecrets(msg) as Record<string, string>;
    expect(out.keyboard).toBe("cmd+k");
    expect(out.monkey).toBe("business");
    expect(out.hotkey).toBe("ctrl");
    expect(out.keys).toContain("redacted");
  });

  it("survives cycles-adjacent depth and non-objects", () => {
    expect(redactSecrets("plain")).toBe("plain");
    expect(redactSecrets(null)).toBe(null);
    expect(redactSecrets(42)).toBe(42);
    let deep: Record<string, unknown> = { token: "deep-secret" };
    for (let i = 0; i < 20; i++) deep = { nested: deep };
    expect(() => redactSecrets(deep)).not.toThrow();
  });
});

import { redactSecretsInText } from "./redact.ts";

describe("redactSecretsInText", () => {
  it("masks known key prefixes wherever they appear", () => {
    // Assembled at runtime, so no token-shaped literal sits in the source for GitHub's push protection to flag.
    const alpha = "abcdefghijklmnopqrstuvwxyz0123456789";
    const cases: Array<[string, RegExp]> = [
      [`set ANTHROPIC_API_KEY=sk-ant-api03-${alpha}`, /sk-ant/],
      [`OpenAI: sk-proj-${alpha}ABCD`, /sk-proj/],
      [`gh token ${"gh" + "p_"}${alpha}`, /ghp_/],
      [`fine-grained ${"github_" + "pat_"}11ABCDEFG0${alpha}`, /github_pat_/],
      [`slack ${"xox" + "b-"}${"123456789012"}-${"1234567890123"}-${alpha.slice(0, 24)}`, /xoxb-/],
      [`slack app ${"xa" + "pp-"}1-A0123456789-${"1234567890123"}-${alpha.slice(0, 24)}`, /xapp-|A0123456789/],
      [`aws ${"AKIA" + "IOSFODNN7EXAMPLE"} and more`, /IOSFODNN7EXAMPLE/],
      [`aws temporary ${"ASIA" + "IOSFODNN7EXAMPLE"} and more`, /IOSFODNN7EXAMPLE/],
      [`google ${"AIza" + "SyA-"}${alpha.slice(0, 32)}`, /AIza/],
      [`npm ${"npm" + "_"}${alpha}`, /npm_[a-z]/],
      [`xai ${"xai-"}${alpha}`, /xai-/],
      [`groq ${"gsk_"}${alpha}ABCD`, /gsk_/],
      [`meta ${"LLM|"}607358788850350|${alpha}`, /LLM\|6073/],
      [`huggingface ${"hf_"}${alpha}`, /hf_/],
      [`pypi ${"py" + "pi-"}AgEIcHlwaS5vcmcCJDAwMDAwMDAwLTAwMDAtMDAwMC0wMDAwLTAwMDAwMDAwMDAwMAACKlszLCJhYmNkZWYiXQAABiBy${alpha}`, /pypi-|AgEIcHlwaS5vcmc/],
      [`gitlab ${"glp" + "at-"}${alpha.slice(0, 20)}`, /glpat-[a-z]/],
      [`gitlab routable ${"glp" + "at-"}${alpha.slice(0, 27)}.01.0r03gxo7a`, /glpat-[a-z]|r03gxo7a/],
      [`gitlab deploy ${"gld" + "t-"}${alpha.slice(0, 20)}`, /gldt-[a-z]/],
      [`gitlab runner ${"glr" + "t-"}${alpha.slice(0, 20)}`, /glrt-[a-z]/],
      [`gitlab registered runner ${"glr" + "tr-"}${alpha.slice(0, 20)}`, /glrtr-[a-z]/],
      [`stripe ${"sk_" + "live_"}${alpha}`, /sk_live_[a-z]/],
      [`stripe test ${"sk_" + "test_"}${alpha}`, /sk_test_[a-z]/],
      [`stripe restricted ${"rk_" + "live_"}${alpha}`, /rk_live_[a-z]/],
      [`webhook secret ${"whsec" + "_"}${alpha}`, /whsec_[a-z]/],
      [`automation address http://127.0.0.1:8800/hooks/wh_abc/${"whsec" + "_"}${alpha}-_x`, /whsec_[a-z]/],
    ];
    for (const [input, leak] of cases) {
      const out = redactSecretsInText(input);
      expect(out, input).not.toMatch(leak);
      expect(out).toMatch(/«redacted \d+ chars»/);
    }
  });

  it("masks SendGrid API keys", () => {
    // SG.<22-char key id>.<43-char secret>, assembled at runtime like the cases above.
    const key = `${"S" + "G."}${"abcdefghij0123456789_-"}.${"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghij0123456"}`;
    expect(redactSecretsInText(`sendgrid ${key} sent`)).toBe(`sendgrid «redacted ${key.length} chars» sent`);
    expect(holdsCredential(`mail via ${key}`)).toBe(true);
    for (const ordinary of ["SG.example.com", `${"S" + "G."}${"a".repeat(22)}.${"b".repeat(20)}`, `${"S" + "G."}${"a".repeat(22)}.${"b".repeat(44)}`, "Use the SG. prefix for the key"]) {
      expect(redactSecretsInText(ordinary)).toBe(ordinary);
      expect(holdsCredential(ordinary)).toBe(false);
    }
  });

  it("masks Notion integration tokens", () => {
    // ntn_ plus 46 letters and digits, assembled at runtime like the cases above.
    const token = `${"nt" + "n_"}${"0123456789A"}${"bcdefghijklmnopqrstuvwxyzABCDEFGHIJ"}`;
    expect(redactSecretsInText(`notion ${token} connected`)).toBe(`notion «redacted ${token.length} chars» connected`);
    expect(holdsCredential(`header Notion ${token}`)).toBe(true);
    for (const ordinary of ["ntn_example", `${"nt" + "n_"}${"a".repeat(39)}`, `example_${"nt" + "n_"}${"a".repeat(46)}`]) {
      expect(redactSecretsInText(ordinary)).toBe(ordinary);
      expect(holdsCredential(ordinary)).toBe(false);
    }
  });

  it("masks Perplexity API keys", () => {
    // pplx- plus 48 letters and digits, assembled at runtime like the cases above.
    const key = `${"pp" + "lx-"}${"0123456789ABCDEFGHIJKLMN"}${"opqrstuvwxyzabcdefghijkl"}`;
    expect(redactSecretsInText(`perplexity ${key} search`)).toBe(`perplexity «redacted ${key.length} chars» search`);
    expect(holdsCredential(`search via ${key}`)).toBe(true);
    for (const ordinary of ["perplexity/pplx-decider-v1.1-27b", `${"pp" + "lx-"}${"a".repeat(47)}`, `${"pp" + "lx-"}${"a".repeat(49)}`, `example_${"pp" + "lx-"}${"a".repeat(48)}`]) {
      expect(redactSecretsInText(ordinary)).toBe(ordinary);
      expect(holdsCredential(ordinary)).toBe(false);
    }
  });

  it.each([
    ["xai-", 20],
    ["gsk_", 40],
    ["hf_", 30],
  ] as const)("bounds %s masking without changing ordinary text", (prefix, minimum) => {
    const key = prefix + "a".repeat(minimum);
    const longer = key + "AB12";
    const text = `before "${key}", ${longer}; after ✓`;
    const expected = `before "«redacted ${key.length} chars»", «redacted ${longer.length} chars»; after ✓`;

    expect(redactSecretsInText(text)).toBe(expected);
    expect(redactSecretsInText(expected)).toBe(expected);
    expect(redactSecrets({ note: text })).toEqual({ note: expected });
    for (const ordinary of [prefix + "a".repeat(minimum - 1), `example_${key}`, `${prefix}example`]) {
      expect(redactSecretsInText(ordinary)).toBe(ordinary);
    }
  });

  it("masks JWTs, PEM private key blocks, and bearer tokens", () => {
    const jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c";
    expect(redactSecretsInText(`token ${jwt} ok`)).toBe(`token «redacted ${jwt.length} chars» ok`);
    const pem = "-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW\n-----END OPENSSH PRIVATE KEY-----";
    const out = redactSecretsInText(`here:\n${pem}\ndone`);
    expect(out).not.toContain("b3BlbnNzaC1r");
    expect(out).toMatch(/BEGIN OPENSSH PRIVATE KEY[\s\S]*«redacted \d+ chars»[\s\S]*END OPENSSH PRIVATE KEY/);
    expect(redactSecretsInText('curl -H "Authorization: Bearer abc.def-ghi_jkl123456789"')).toBe('curl -H "Authorization: Bearer «redacted 24 chars»"');
  });

  it("masks Basic credentials in an Authorization header", () => {
    // dXNlcjpodW50ZXIy is base64 for user:hunter2.
    expect(redactSecretsInText('curl -H "Authorization: Basic dXNlcjpodW50ZXIy" https://api.example.com')).toBe(
      'curl -H "Authorization: Basic «redacted 16 chars»" https://api.example.com',
    );
    expect(redactSecretsInText("Proxy-Authorization: basic YWxhZGRpbjpvcGVuc2VzYW1l")).toBe("Proxy-Authorization: basic «redacted 24 chars»");
    expect(redactSecretsInText('{"Authorization":"Basic YTpi"}')).toBe('{"Authorization":"Basic «redacted 4 chars»"}');
    for (const s of ["Basic configuration is covered below", "Authorization: Basic YOUR_CREDENTIALS", "Authorization: Basic <base64>"]) {
      expect(redactSecretsInText(s), s).toBe(s);
    }
  });

  it("is byte-for-byte idempotent for PEM blocks", () => {
    const privateKeyBody = "c3VwZXItc2VjcmV0LXByaXZhdGUta2V5LWJ5dGVz";
    const pem = [
      "-----BEGIN PRIVATE KEY-----",
      privateKeyBody,
      "-----END PRIVATE KEY-----",
    ].join("\n");
    const once = redactSecretsInText(`before\n${pem}\nafter`);

    expect(redactSecretsInText(once)).toBe(once);
    expect(once).toContain(`«redacted ${privateKeyBody.length} chars»`);
  });

  it("masks the value of a secret-shaped key=value or key: value, keeping the key", () => {
    expect(redactSecretsInText("export DATABASE_PASSWORD=hunter2hunter2")).toBe("export DATABASE_PASSWORD=«redacted 14 chars»");
    expect(redactSecretsInText('{"api_key": "abcd1234efgh5678"}')).toBe('{"api_key": "«redacted 16 chars»"}');
    expect(redactSecretsInText("client_secret: 'zzzz-yyyy-xxxx-1'")).toBe("client_secret: '«redacted 16 chars»'");
    expect(redactSecretsInText("--token=abc123def456")).toBe("--token=«redacted 12 chars»");
  });

  it("masks an assignment to any name ending in KEY, whatever the value looks like", () => {
    expect(redactSecretsInText(`OPENAI_API_KEY=sk-${"a".repeat(20)} pnpm test`)).toBe("OPENAI_API_KEY=«redacted 23 chars» pnpm test");
    expect(redactSecretsInText("X_KEY=value pnpm control:omb doctor")).toBe("X_KEY=«redacted 5 chars» pnpm control:omb doctor");
    expect(redactSecretsInText("export xai-key='abc.def'")).toBe("export xai-key='«redacted 7 chars»'");
  });

  it("masks the password in a URL's userinfo, keeping the user and the host", () => {
    expect(redactSecretsInText("psql postgres://maus:[email protected]:5432/app")).toBe("psql postgres://maus:«redacted 6 chars»@db.internal:5432/app");
    expect(redactSecretsInText("curl https://user:p%40ss@host/path")).toBe("curl https://user:«redacted 6 chars»@host/path");
  });

  it("masks the value of a secret-naming flag, in both spellings", () => {
    expect(redactSecretsInText("gh auth login --token abc123")).toBe("gh auth login --token «redacted 6 chars»");
    expect(redactSecretsInText("tool --password=hunter2 --api-key 'k1' --secret s")).toBe("tool --password=«redacted 7 chars» --api-key '«redacted 2 chars»' --secret «redacted 1 chars»");
    expect(redactSecretsInText("tool --token --verbose")).toBe("tool --token --verbose");
  });

  it("does not mask ordinary words near those rules", () => {
    for (const s of [
      "hotkey=cmd+k keyboard=qwerty monkey=business",
      "https://host:8080/path and user@host",
      "git log --tokens-are-not-a-flag --passwords",
      "the key: patience",
    ]) {
      expect(redactSecretsInText(s), s).toBe(s);
    }
  });

  it("leaves ordinary text, code, hashes and URLs alone", () => {
    for (const s of [
      "the keyboard shortcut is cmd-k",
      "git commit 3f2a9c1e7b4d5a6f8e9c0b1a2d3e4f5a6b7c8d9e",
      "https://example.com/path?page=2&sort=asc",
      "const token = await getToken(); // fetches later",
      "password: (leave blank to keep the current one)",
      "Bearer tokens are sent in the Authorization header",
      "sk-8",
    ]) {
      expect(redactSecretsInText(s), s).toBe(s);
    }
  });

  it("is applied to string values inside redactSecrets too", () => {
    const out = redactSecrets({ command: "curl -H 'Authorization: Bearer abcdefghijklmnop'", note: "fine" }) as Record<string, string>;
    expect(out.command).toContain("«redacted");
    expect(out.note).toBe("fine");
  });

  it("is idempotent for structurally identified credentials", () => {
    const input = {
      apiKey: "abcdefgh12345678",
      env: [{ name: "OMB_COMMS_TOKEN", value: "abcdefghijklmnop" }],
    };
    const once = redactSecrets(input);

    expect(redactSecrets(once)).toEqual(once);
  });
});

describe("holdsCredential", () => {
  it("knows a provider key or a private key block, never a name, a placeholder or code that reads one", () => {
    for (const text of [
      `TWINE_PASSWORD: ${"py" + "pi-"}AgENdGVzdC5weXBpLm9yZwIkMDAwMDAwMDAtMDAwMC0wMDAwLTAwMDAtMDAwMDAwMDAwMDAwAAIqWzMsImFiY2RlZiJdAAAGIA`,
      '{"apiKey": "sk-ant-api03-0123456789abcdefABCD"}', "GITHUB_TOKEN=ghp_0123456789abcdefghij0123", "-----BEGIN OPENSSH PRIVATE KEY-----\nabc\n",
      "aws_access_key_id = AKIAABCDEFGHIJKLMNOP", `temporary aws key ${"ASIA" + "ABCDEFGHIJKLMNOP"}`, `git clone https://oauth2:${"glp" + "at-"}[email protected]/x.git`, `runner token ${"glr" + "tr-"}0123456789abcdefABCD`, `SLACK_APP_TOKEN: ${"xa" + "pp-"}1-A0123456789-1234567890123-abcdef0123456789`, `stripe.secret = "${"sk_" + "live_"}0123456789abcdefABCD"`,
    ]) expect(holdsCredential(text), text).toBe(true);
    for (const text of [
      "token = os.environ['GITHUB_TOKEN']", "API_KEY=your-key-here", "Authorization: Bearer YOUR_TOKEN_HERE", "Keep credentials out of the repo.",
      "-----BEGIN PUBLIC KEY-----", "GITLAB_TOKEN=glpat-your-token-here", `release notes mention ${"py" + "pi-"}AgE${"x".repeat(60)}`,
    ]) expect(holdsCredential(text), text).toBe(false);
  });
});