Skip to content

Local-first 🧠 memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly 😴 dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.

TypeScript
8.7 KB
Raw Blame
/**
 * Secret exec path (t_0b134404, part 2): allowlist-gated subprocess
 * execution with env injection and redacted output. The capability
 * gate is the operator-declared glob allowlist; a non-matching
 * command is refused and audited, and a command that echoes the
 * secret back gets the value scrubbed before the caller sees it.
 */

import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";

import { loadOrCreateKey } from "../../../../src/core/brain/secrets/crypto.ts";
import {
  SecretStoreLockedError,
  wrapKeyfile,
} from "../../../../src/core/brain/secrets/envelope.ts";
import {
  matchesAllowlist,
  runWithSecret,
  SecretExecDeniedError,
} from "../../../../src/core/brain/secrets/exec.ts";
import { secretsDir, setSecret } from "../../../../src/core/brain/secrets/store.ts";
import { fakeCredential } from "../../../helpers/fake-credentials.ts";

const NOW = new Date("2026-06-05T10:00:00Z");
const CTX = { agent: "tester", now: NOW };

let vault: string;

beforeEach(() => {
  vault = mkdtempSync(join(tmpdir(), "o2b-secret-exec-"));
  mkdirSync(join(vault, "Brain"), { recursive: true });
});

afterEach(() => {
  rmSync(vault, { recursive: true, force: true });
});

describe("matchesAllowlist (pure)", () => {
  test("a trailing star means this binary with arguments; tokens align otherwise", () => {
    expect(matchesAllowlist(["curl *"], ["curl", "https://api.example.com"])).toBe(true);
    expect(matchesAllowlist(["curl *"], ["curl"])).toBe(false);
    expect(matchesAllowlist(["curl *"], ["bash", "-c", "curl"])).toBe(false);
    expect(matchesAllowlist(["echo secret-test"], ["echo", "secret-test"])).toBe(true);
    expect(matchesAllowlist(["echo secret-test"], ["echo", "other", "secret-test"])).toBe(false);
    expect(matchesAllowlist([], ["anything"])).toBe(false);
  });

  test("argv boundaries are visible: a space inside one argument cannot satisfy two tokens (t_sec_allowlist_segments)", () => {
    // The joined-string matcher read `curl * https://good` as a regular
    // expression over `argv.join(" ")`, so the single argument
    // `https://evil https://good` satisfied it - and the curl that
    // actually spawned fetched both URLs. Segment matching counts
    // elements instead.
    expect(matchesAllowlist(["curl * https://good"], ["curl", "https://evil https://good"])).toBe(
      false,
    );
    expect(matchesAllowlist(["curl * https://good"], ["curl", "--silent", "https://good"])).toBe(
      true,
    );
  });

  test("regex metacharacters in patterns stay literal; stars glob within one element", () => {
    expect(matchesAllowlist(["node script.js"], ["node", "scriptxjs"])).toBe(false);
    expect(matchesAllowlist(["node script*.js"], ["node", "scriptABC.js"])).toBe(true);
  });
});

describe("runWithSecret", () => {
  test("an allowlisted command sees the env var; output is redacted", async () => {
    setSecret(vault, {
      name: "api-key",
      value: "sk-redact-me-12345",
      envVar: "MY_API_KEY",
      allow: ["bun -e *"],
      agent: "tester",
      now: NOW,
    });
    const result = await runWithSecret(
      vault,
      "api-key",
      ["bun", "-e", "console.log('key=' + process.env.MY_API_KEY)"],
      CTX,
    );
    expect(result.exitCode).toBe(0);
    expect(result.stdout).not.toContain("sk-redact-me-12345");
    expect(result.stdout).toContain("***REDACTED***");
  });

  test("a non-matching command is refused and audited", async () => {
    setSecret(vault, {
      name: "api-key",
      value: "sk-redact-me-12345",
      allow: ["curl *"],
      agent: "tester",
      now: NOW,
    });
    await expect(runWithSecret(vault, "api-key", ["bash", "-c", "env"], CTX)).rejects.toThrow(
      SecretExecDeniedError,
    );
    const auditDir = join(vault, "Brain", "log", "secret-custody");
    const lines = readdirSync(auditDir)
      .flatMap((f) => readFileSync(join(auditDir, f), "utf8").split("\n"))
      .filter((l) => l.trim().length > 0)
      .map((l) => JSON.parse(l) as { action: string; ok: boolean });
    expect(lines.some((l) => l.action === "secret_exec_denied" && l.ok === false)).toBe(true);
  });

  test("an empty allowlist denies every exec", async () => {
    setSecret(vault, {
      name: "locked",
      value: "sealed-value",
      agent: "tester",
      now: NOW,
    });
    await expect(runWithSecret(vault, "locked", ["echo", "hi"], CTX)).rejects.toThrow(
      /empty allowlist/,
    );
  });

  test("the subprocess env is minimal - unrelated parent vars do not leak", async () => {
    process.env["UNRELATED_PARENT_TOKEN"] = "leak-me-not";
    try {
      setSecret(vault, {
        name: "api-key",
        value: "sk-redact-me-12345",
        envVar: "MY_API_KEY",
        allow: ["bun -e *"],
        agent: "tester",
        now: NOW,
      });
      const result = await runWithSecret(
        vault,
        "api-key",
        ["bun", "-e", "console.log('leak=' + process.env.UNRELATED_PARENT_TOKEN)"],
        CTX,
      );
      expect(result.exitCode).toBe(0);
      expect(result.stdout).toContain("leak=undefined");
    } finally {
      delete process.env["UNRELATED_PARENT_TOKEN"];
    }
  });

  test("a foreign bare secret in argv is redacted in the persisted audit trail", async () => {
    setSecret(vault, {
      name: "api-key",
      value: "own-custody-secret",
      envVar: "MY_API_KEY",
      allow: ["bun *"],
      agent: "tester",
      now: NOW,
    });
    // The agent passes some OTHER credential as a bare positional argument —
    // it never enters the custody store, so it is not a known literal, but it
    // must not land in the long-lived audit log in cleartext.
    const foreignToken = "sk-foreign-abc123def456";
    const result = await runWithSecret(
      vault,
      "api-key",
      ["bun", "-e", "process.exit(0)", foreignToken],
      CTX,
    );
    expect(result.exitCode).toBe(0);

    const auditDir = join(vault, "Brain", "log", "secret-custody");
    const raw = readdirSync(auditDir)
      .map((f) => readFileSync(join(auditDir, f), "utf8"))
      .join("");
    expect(raw).not.toContain(foreignToken);
    const started = raw
      .split("\n")
      .filter((l) => l.trim().length > 0)
      .map((l) => JSON.parse(l) as { action: string; details?: { command?: string } })
      .find((l) => l.action === "secret_exec_started");
    expect(started).toBeDefined();
    expect(started!.details!.command).toContain("***REDACTED***");
    expect(started!.details!.command).not.toContain(foreignToken);
  });

  test("a transformed echo of the secret is scrubbed too, not only the literal (audit L3)", async () => {
    const value = fakeCredential("sk-", "live-9f8e7d6c5b4a39281706f5e4d3c2b1a0");
    const encoded = Buffer.from(value).toString("base64");
    setSecret(vault, {
      name: "api-key",
      value,
      envVar: "MY_API_KEY",
      allow: ["bun -e *"],
      agent: "tester",
      now: NOW,
    });
    const result = await runWithSecret(
      vault,
      "api-key",
      [
        "bun",
        "-e",
        "console.log(Buffer.from(process.env.MY_API_KEY).toString('base64')); " +
          "console.error(Buffer.from(process.env.MY_API_KEY).toString('base64'))",
      ],
      CTX,
    );
    expect(result.exitCode).toBe(0);
    expect(result.stdout).not.toContain(encoded);
    expect(result.stderr).not.toContain(encoded);
    expect(result.stdout).toContain("***REDACTED***");
  });

  test("the subprocess exit code propagates", async () => {
    setSecret(vault, {
      name: "api-key",
      value: "sk-redact-me-12345",
      allow: ["bun -e *"],
      agent: "tester",
      now: NOW,
    });
    const result = await runWithSecret(vault, "api-key", ["bun", "-e", "process.exit(3)"], CTX);
    expect(result.exitCode).toBe(3);
  });

  test("exec under a locked store refuses by name before the allowlist is consulted", async () => {
    setSecret(vault, {
      name: "api-key",
      value: "sk-redact-me-12345",
      allow: ["bun -e *"],
      agent: "tester",
      now: NOW,
    });
    const keyPath = join(secretsDir(vault), "keyfile");
    wrapKeyfile(keyPath, fakeCredential("exec-wrap", "-phrase-", "42"), loadOrCreateKey(keyPath));
    await expect(runWithSecret(vault, "api-key", ["echo", "hi"], CTX)).rejects.toThrow(
      SecretStoreLockedError,
    );
    // No exec decision was reached, so no exec record lands: the refusal is
    // the custody lock's, not the allowlist's.
    const auditDir = join(vault, "Brain", "log", "secret-custody");
    const raw = readdirSync(auditDir)
      .map((f) => readFileSync(join(auditDir, f), "utf8"))
      .join("");
    expect(raw).not.toContain("secret_exec_started");
    expect(raw).not.toContain("secret_exec_denied");
  });
});