Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,7 @@ This is the part I most wanted to get right.
- A test fails the build if a credential can reach the repo. This isn't on the honor system.

- Arbella's own auto-push hook is never stored in the repo, so a pulled machine does not inherit it.
- A real local secret is only reused when nothing else in its server, provider or settings block changed; otherwise the local version is kept and reported. That guard stops a secret from quietly following a changed endpoint. It is not a sandbox: the repo stays trusted, because it can ship hooks and MCP commands that run code.

Putting secrets in the repo is opt-in, and the default is off. It's your private repo and your call — but I'd leave it there.

Expand Down
90 changes: 66 additions & 24 deletions src/core/placement/redacted.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,12 @@
* REDACTED marker where a secret used to be; placing it verbatim would break the
* local tool. These helpers merge the real local value back in, or report the
* key as missing. Never logs or returns anything but key paths for omissions.
*
* A real local secret is reused only when its scope (see {@link scopeOf}) is
* otherwise unchanged; no list of endpoint key names is involved. Threat model:
* the backup repo is trusted (it ships hooks and MCP commands that run code).
* This guard keeps a secret from silently following a changed endpoint or
* block; it is not a sandbox against a malicious repo.
*/
import { isDeepStrictEqual } from "node:util";
import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
Expand All @@ -22,65 +28,101 @@ export function hasMarker(v: unknown): boolean {
return false;
}

/** Parent keys whose children are whole server/provider definitions (entries). */
const ENTRY_PARENTS = new Set(["mcpServers", "mcp_servers", "servers", "mcp", "model_providers"]);
/**
* Maps of whole server/provider definitions, anchored at the document root. A
* name matched at any depth would let a nested "servers" key pose as an entry.
*/
const ENTRY_MAPS: readonly (readonly string[])[] = [
["mcpServers"], ["mcp_servers"], ["servers"], ["mcp"], ["mcp", "servers"],
["model_providers"], ["profiles"],
];

const startsWith = (path: readonly string[], prefix: readonly string[]): boolean =>
prefix.length <= path.length && prefix.every((k, i) => path[i] === k);

/**
* Is `repo` equal to `local` once every repo marker path is dropped from both?
* Key order does not matter; any repo-side addition or local-only key counts as
* a change. Only then may a real local value be reused inside that scope.
* The subtree that must be unchanged before the secret at `path` may be reused:
* the whole object when `rootIsEntry`; else the entry under the longest matching
* ENTRY_MAPS path; else the top-level subtree; else (a top-level leaf) the
* whole document.
*
* Safety never depends on ENTRY_MAPS being complete: a map we do not know falls
* back to its coarser top-level subtree, which contains every entry. The list
* only NARROWS the scope for usability, so an omission cannot open a hole.
*/
const blindEqual = (repo: Plain, local: unknown): boolean =>
isPlain(local) &&
isDeepStrictEqual(
markerPaths(repo).reduce(withoutPath, repo as unknown),
markerPaths(repo).reduce(withoutPath, local as unknown),
);
export function scopeOf(path: readonly string[], rootIsEntry = false): string[] {
if (rootIsEntry) return [];
const map = ENTRY_MAPS.filter((m) => path.length > m.length + 1 && startsWith(path, m)).reduce<
readonly string[] | undefined
>((best, m) => (best === undefined || m.length > best.length ? m : best), undefined);
if (map) return [...map, path[map.length]!];
return path.length > 1 ? [path[0]!] : [];
}

const getAt = (node: unknown, path: readonly string[]): unknown =>
path.reduce<unknown>((n, k) => (isPlain(n) ? n[k] : undefined), node);

/**
* Is the repo scope equal to the local scope once the repo's marker paths inside
* it are dropped from both? Key order does not matter; any repo-side addition or
* local-only key counts as a change. A missing local scope is never equal.
*/
function scopeUnchanged(repo: Plain, local: Plain, scope: string[], markers: string[][]): boolean {
const repoScope = getAt(repo, scope);
const localScope = getAt(local, scope);
if (!isPlain(repoScope) || !isPlain(localScope)) return false;
const inside = markers.filter((m) => startsWith(m, scope)).map((m) => m.slice(scope.length));
return isDeepStrictEqual(inside.reduce(withoutPath, repoScope as unknown), inside.reduce(withoutPath, localScope as unknown));
}

/**
* Merge a repo value (may contain markers) with the local one. A marker leaf (a
* string, or an array containing a marker) takes the local value at the same key
* path when that is real; otherwise only that key is omitted and its path
* reported. A local marker counts as no value. A real local value is reused only
* when everything else in the leaf's scope is unchanged (see {@link blindEqual}):
* the scope is the nearest enclosing server/provider entry (an object under
* mcpServers, mcp_servers, servers, mcp or model_providers), else the leaf's own
* parent object. Otherwise the leaf is omitted and its path listed in `unsafe`,
* so a changed command, url, env or any other key can never redirect a secret.
* `rootIsEntry` marks `repo` itself as such an entry (a bare server definition).
* when the leaf's {@link scopeOf scope} (its server/provider entry, else its
* top-level subtree, else the whole document) is otherwise unchanged
* ({@link scopeUnchanged}). Otherwise the leaf is omitted and its path listed in
* `unsafe`, so a changed command, url, host, env or any other key in the block
* can never redirect a secret, whatever it is called. `rootIsEntry` marks `repo`
* itself as one entry (a bare server definition).
*/
export function mergeRedacted(
repo: unknown,
local: unknown,
opts: { rootIsEntry?: boolean } = {},
): { value: unknown; missing: string[][]; unsafe: string[][] } {
if (!isPlain(repo)) return { value: repo, missing: [], unsafe: [] };
return mergeObject(repo, isPlain(local) ? local : undefined, [], undefined, opts.rootIsEntry === true);
const localObj = isPlain(local) ? local : undefined;
const markers = markerPaths(repo);
const reusable = new Set(
markers
.filter((m) => localObj !== undefined && scopeUnchanged(repo, localObj, scopeOf(m, opts.rootIsEntry === true), markers))
.map((m) => JSON.stringify(m)),
);
return mergeObject(repo, localObj, [], reusable);
}

function mergeObject(
repo: Plain,
local: Plain | undefined,
path: string[],
inherited: boolean | undefined,
rootIsEntry: boolean,
reusable: ReadonlySet<string>,
): { value: Plain; missing: string[][]; unsafe: string[][] } {
const value: Plain = {};
const missing: string[][] = [];
const unsafe: string[][] = [];
const isEntry = path.length === 0 ? rootIsEntry : ENTRY_PARENTS.has(path[path.length - 2]!);
const scopeOk = isEntry ? blindEqual(repo, local) : inherited;
for (const [key, rv] of Object.entries(repo)) {
const lv = local?.[key];
const here = [...path, key];
if (isPlain(rv)) {
const sub = mergeObject(rv, isPlain(lv) ? lv : undefined, here, scopeOk, false);
const sub = mergeObject(rv, isPlain(lv) ? lv : undefined, here, reusable);
value[key] = sub.value;
missing.push(...sub.missing);
unsafe.push(...sub.unsafe);
} else if (hasMarker(rv)) {
if (lv === undefined || hasMarker(lv)) missing.push(here);
else if (scopeOk ?? blindEqual(repo, local)) value[key] = lv;
else if (reusable.has(JSON.stringify(here))) value[key] = lv;
else unsafe.push(here);
} else {
value[key] = rv;
Expand Down
114 changes: 114 additions & 0 deletions test/unit/redacted-values.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
mergeRedacted,
mergeRedactedText,
parseStructured,
scopeOf,
repairRedacted,
repairRedactedText,
structuredKind,
Expand Down Expand Up @@ -444,11 +445,124 @@ describe("mergeRedacted: scope must be unchanged", () => {
expect(mergeRedacted(repo, local).unsafe).toEqual([]);
});

it("a server under an unrecognised map with a changed command is unsafe", () => {
const local = { context_servers: { x: { command: "good", env: { TOKEN: "real" } } } };
const repo = { context_servers: { x: { command: "evil", env: { TOKEN: R } } } };
expect(unsafeOf(repo, local)).toEqual([["context_servers", "x", "env", "TOKEN"]]);
});

it("a changed base_url outside any known entry next to a redacted api_key is unsafe", () => {
const local = { provider: { base_url: "https://good.example", api_key: "real" } };
const repo = { provider: { base_url: "https://evil.example", api_key: R } };
expect(unsafeOf(repo, local)).toEqual([["provider", "api_key"]]);
});

it("an unchanged server under an unrecognised map still reuses the value", () => {
const local = { context_servers: { x: { command: "c", env: { TOKEN: "real" } } } };
const repo = { context_servers: { x: { command: "c", env: { TOKEN: R } } } };
const r = mergeRedacted(repo, local);
expect(r.unsafe).toEqual([]);
expect(r.value).toEqual(local);
});

it("a settings-style top-level env with only the marker differing reuses the value while other keys change", () => {
const r = mergeRedacted(
{ model: "b", theme: "t2", env: { A: "1", K: R } },
{ model: "a", theme: "t1", env: { A: "1", K: "real" } },
);
expect(r.unsafe).toEqual([]);
expect(r.value).toEqual({ model: "b", theme: "t2", env: { A: "1", K: "real" } });
});

it("a missing local object at a required level means no reuse", () => {
const repo = { context_servers: { x: { command: "c", env: { TOKEN: R } } } };
expect(mergeRedacted(repo, { other: 1 }).missing).toEqual([["context_servers", "x", "env", "TOKEN"]]);
});

it("rootIsEntry makes a bare server definition the scope", () => {
const local = { command: "c", cwd: "/good", env: { T: "real" } };
const repo = { command: "c", cwd: "/evil", env: { T: R } };
expect(mergeRedacted(repo, local, { rootIsEntry: true }).unsafe).toEqual([["env", "T"]]);
// Without rootIsEntry the root is a document: only the [env] scope applies.
expect(mergeRedacted(repo, local).unsafe).toEqual([]);
const plain = { mode: "a", env: { T: R } };
expect(mergeRedacted(plain, { mode: "b", env: { T: "real" } }).unsafe).toEqual([]);
expect(mergeRedacted(plain, { mode: "b", env: { T: "real" } }, { rootIsEntry: true }).unsafe).toEqual([["env", "T"]]);
});

it("a nested config.servers.y.token inside mcpServers.x is scoped to x, not y", () => {
const local = { mcpServers: { x: { command: "good", config: { servers: { y: { token: "real" } } } } } };
const repo = { mcpServers: { x: { command: "evil", config: { servers: { y: { token: R } } } } } };
expect(unsafeOf(repo, local)).toEqual([["mcpServers", "x", "config", "servers", "y", "token"]]);
});

it("an unknown endpoint key (host) changed in an unrecognised map is unsafe", () => {
const local = { context_servers: { x: { host: "good.example", env: { TOKEN: "real" } } } };
const repo = { context_servers: { x: { host: "evil.example", env: { TOKEN: R } } } };
expect(unsafeOf(repo, local)).toEqual([["context_servers", "x", "env", "TOKEN"]]);
});

it("an unchanged context_servers.x with a changed sibling z is unsafe (coarse top-level fallback)", () => {
const local = { context_servers: { x: { command: "c", env: { TOKEN: "real" } }, z: { command: "old" } } };
const repo = { context_servers: { x: { command: "c", env: { TOKEN: R } }, z: { command: "new" } } };
expect(unsafeOf(repo, local)).toEqual([["context_servers", "x", "env", "TOKEN"]]);
});

it("mcp.servers.x (VS Code shape) reuses when only the marker differs, and is unsafe when x.uri changes", () => {
const local = { mcp: { servers: { x: { uri: "https://good.example", headers: { A: "real" } }, z: { uri: "old" } } } };
const same = { mcp: { servers: { x: { uri: "https://good.example", headers: { A: R } }, z: { uri: "new" } } } };
const r = mergeRedacted(same, local);
expect(r.unsafe).toEqual([]);
expect(r.value).toEqual({ mcp: { servers: { x: { uri: "https://good.example", headers: { A: "real" } }, z: { uri: "new" } } } });
const moved = { mcp: { servers: { x: { uri: "https://evil.example", headers: { A: R } } } } };
expect(unsafeOf(moved, local)).toEqual([["mcp", "servers", "x", "headers", "A"]]);
});

it("profiles.p.api_key with a changed profiles.p.base_url is unsafe", () => {
const local = { profiles: { p: { base_url: "https://good.example", api_key: "real" } } };
const repo = { profiles: { p: { base_url: "https://evil.example", api_key: R } } };
expect(unsafeOf(repo, local)).toEqual([["profiles", "p", "api_key"]]);
});

it("a top-level apiKey is scoped to the whole document", () => {
const local = { apiKey: "real", theme: "a" };
expect(unsafeOf({ apiKey: R, theme: "b" }, local)).toEqual([["apiKey"]]);
const r = mergeRedacted({ apiKey: R, theme: "a" }, local);
expect(r.unsafe).toEqual([]);
expect(r.value).toEqual(local);
});
});

describe("scopeOf", () => {
it("rootIsEntry makes the whole object the scope", () => {
expect(scopeOf(["env", "T"], true)).toEqual([]);
expect(scopeOf(["mcpServers", "x", "env", "T"], true)).toEqual([]);
});

it("a leaf under an anchored entry map is scoped to its entry", () => {
expect(scopeOf(["mcpServers", "x", "env", "T"])).toEqual(["mcpServers", "x"]);
expect(scopeOf(["model_providers", "p", "api_key"])).toEqual(["model_providers", "p"]);
expect(scopeOf(["profiles", "p", "api_key"])).toEqual(["profiles", "p"]);
});

it("the longest matching map wins", () => {
expect(scopeOf(["mcp", "servers", "x", "uri", "k"])).toEqual(["mcp", "servers", "x"]);
expect(scopeOf(["mcp", "other", "k"])).toEqual(["mcp", "other"]);
});

it("an entry map not anchored at the root is ignored", () => {
expect(scopeOf(["mcpServers", "x", "config", "servers", "y", "t"])).toEqual(["mcpServers", "x"]);
expect(scopeOf(["a", "servers", "x", "t"])).toEqual(["a"]);
});

it("an unknown map, or a leaf directly in a map, falls back to the top-level subtree", () => {
expect(scopeOf(["context_servers", "x", "env", "T"])).toEqual(["context_servers"]);
expect(scopeOf(["env", "K"])).toEqual(["env"]);
expect(scopeOf(["mcpServers", "x"])).toEqual(["mcpServers"]);
});

it("a top-level leaf is scoped to the whole document", () => {
expect(scopeOf(["apiKey"])).toEqual([]);
});
});

Expand Down
Loading