@strixgov/mcp-proxy 0.2.3 → 0.2.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +34 -0
- package/README.md +75 -25
- package/examples/controlled-launcher/README.md +33 -0
- package/examples/controlled-launcher/acceptance.mjs +337 -0
- package/examples/controlled-launcher/agent-client.mjs +18 -0
- package/examples/controlled-launcher/approval-relay.mjs +19 -0
- package/examples/controlled-launcher/approver.mjs +27 -0
- package/examples/controlled-launcher/authorizer.mjs +73 -0
- package/examples/controlled-launcher/bridge-client.mjs +8 -0
- package/examples/controlled-launcher/destination.mjs +18 -0
- package/examples/controlled-launcher/executor.mjs +74 -0
- package/examples/controlled-launcher/kernel-authority/acceptance.mjs +627 -0
- package/examples/controlled-launcher/kernel-authority/broker.mjs +83 -0
- package/examples/controlled-launcher/kernel-authority/derive.mjs +12 -0
- package/examples/controlled-launcher/kernel-authority/executor.mjs +105 -0
- package/examples/controlled-launcher/kernel-authority/reconcile.mjs +43 -0
- package/examples/controlled-launcher/kernel-authority/shim.mjs +38 -0
- package/examples/controlled-launcher/kernel-authority/signing-provider.mjs +137 -0
- package/examples/controlled-launcher/kernel-authority/strix-approver.mjs +73 -0
- package/examples/controlled-launcher/lib.mjs +63 -0
- package/examples/controlled-launcher/make-config.mjs +16 -0
- package/examples/controlled-launcher/proxy-host.mjs +19 -0
- package/examples/controlled-launcher/reconcile.mjs +30 -0
- package/examples/controlled-launcher/shim.mjs +32 -0
- package/examples/github-reference/README.md +34 -0
- package/examples/github-reference/acceptance.mjs +675 -0
- package/examples/github-reference/claims-matrix.md +34 -0
- package/examples/github-reference/demo-script.md +17 -0
- package/examples/github-reference/package-lock.json +1330 -0
- package/examples/github-reference/package.json +23 -0
- package/examples/github-reference/reuse-inventory.md +24 -0
- package/examples/synthetic-server/proxy-config.json +16 -0
- package/examples/synthetic-server/quickstart.mjs +98 -0
- package/examples/synthetic-server/server.mjs +54 -0
- package/package.json +6 -5
- package/test/package-contract.test.mjs +12 -0
- package/test/synthetic-quickstart.test.mjs +44 -0
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Controlled-launcher acceptance (root required; creates throwaway OS users; DUMMY credentials; localhost only).
|
|
3
|
+
// usage: node acceptance.mjs <tarball-dir> <results-dir>
|
|
4
|
+
// <tarball-dir> holds the published tarballs (npm pack). Nothing from the repository source is executed except
|
|
5
|
+
// the small reference scripts in this directory (shim/executor/authorizer/...), which are the code under review.
|
|
6
|
+
import { execFileSync, spawn, spawnSync } from "node:child_process";
|
|
7
|
+
import fs from "node:fs";
|
|
8
|
+
import path from "node:path";
|
|
9
|
+
import os from "node:os";
|
|
10
|
+
import crypto from "node:crypto";
|
|
11
|
+
import { fileURLToPath } from "node:url";
|
|
12
|
+
|
|
13
|
+
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
|
14
|
+
const [TARBALLS, RESULTS] = [path.resolve(process.argv[2]), path.resolve(process.argv[3])];
|
|
15
|
+
if (process.getuid() !== 0) { console.error("must run as root"); process.exit(2); }
|
|
16
|
+
fs.mkdirSync(RESULTS, { recursive: true });
|
|
17
|
+
const W = fs.mkdtempSync("/tmp/p2ctl."); fs.chmodSync(W, 0o755);
|
|
18
|
+
const NODE = process.execPath;
|
|
19
|
+
const USERS = ["p2agent", "p2proxy", "p2exec", "p2auth", "p2approver", "p2dest", "p2obs"];
|
|
20
|
+
const matrix = [];
|
|
21
|
+
const rec = (id, area, route, expected, actual, disposition) => {
|
|
22
|
+
matrix.push({ id, area, route, expected, actual: String(actual).replace(new RegExp(W, "g"), "<W>").slice(0, 400), disposition });
|
|
23
|
+
console.log(`${disposition.padEnd(7)} ${id} ${route}`); if (disposition === "FAIL" || disposition === "BLOCKED") console.log(" actual: " + matrix.at(-1).actual.slice(0, 300));
|
|
24
|
+
};
|
|
25
|
+
const sh = (cmd, args, o = {}) => spawnSync(cmd, args, { cwd: o.cwd, encoding: "utf8", timeout: o.timeout ?? 20000, env: o.env ?? { PATH: "/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" }, input: o.input });
|
|
26
|
+
const CLOSE = 'for i in $(seq 3 255); do eval "exec $i>&-"; done; exec "$@"';
|
|
27
|
+
const asArgs = (u, argv, { groups = true, env = {} } = {}) =>
|
|
28
|
+
["--reuid", u, "--regid", u, groups ? "--init-groups" : "--clear-groups", "--reset-env", "bash", "-c", CLOSE, "_", ...(Object.keys(env).length ? ["env", ...Object.entries(env).map(([k, v]) => `${k}=${v}`)] : []), ...argv];
|
|
29
|
+
const as = (u, argv, o = {}) => sh("setpriv", asArgs(u, argv, o), o);
|
|
30
|
+
const bg = (u, argv, logName, o = {}) => {
|
|
31
|
+
const out = fs.openSync(path.join(W, "logs", logName), "a");
|
|
32
|
+
const p = spawn("setpriv", asArgs(u, argv, o), { stdio: ["ignore", out, out], detached: true });
|
|
33
|
+
p.unref(); return p;
|
|
34
|
+
};
|
|
35
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
36
|
+
const pid = (u, pat) => sh("pgrep", ["-u", u, "-f", pat]).stdout.trim().split("\n").filter(Boolean)[0];
|
|
37
|
+
const j = (s) => { try { return JSON.parse(s); } catch { return null; } };
|
|
38
|
+
const mk = (d, owner, mode) => { fs.mkdirSync(path.join(W, d), { recursive: true }); if (owner) sh("chown", [owner, path.join(W, d)]); fs.chmodSync(path.join(W, d), mode); };
|
|
39
|
+
const P = (d) => path.join(W, d);
|
|
40
|
+
|
|
41
|
+
// ---------- setup: identities, groups, directories ----------
|
|
42
|
+
for (const g of ["p2appr-shared"]) if (sh("getent", ["group", g]).status !== 0) sh("groupadd", [g]);
|
|
43
|
+
for (const u of USERS) if (sh("id", [u]).status !== 0) { sh("groupdel", [u]); const r = sh("useradd", ["-M", "-s", "/usr/sbin/nologin", u]); if (r.status !== 0) { console.error("useradd failed", u, r.stderr); process.exit(6); } }
|
|
44
|
+
sh("usermod", ["-aG", "p2appr-shared", "p2approver"]); sh("usermod", ["-aG", "p2appr-shared", "p2proxy"]);
|
|
45
|
+
mk("logs", null, 0o755); mk("bin", null, 0o755);
|
|
46
|
+
mk("sock-agent", "p2proxy:p2agent", 0o2710); mk("sock-exec", "p2exec:p2proxy", 0o2750); mk("sock-claim", "p2auth:p2proxy", 0o2750); mk("sock-reg", "p2auth:p2approver", 0o2750);
|
|
47
|
+
mk("st-exec", "p2exec", 0o755); mk("st-auth", "p2auth", 0o755); mk("st-proxy", "p2proxy", 0o755); mk("proxy-approvals", "p2proxy", 0o700);
|
|
48
|
+
mk("cred-exec", "p2exec", 0o700); mk("cred-obs", "p2obs", 0o700); mk("approver-home", "p2approver:p2appr-shared", 0o710);
|
|
49
|
+
mk("approver-home/approvals", "p2approver:p2appr-shared", 0o2770); mk("work-agent", "p2agent", 0o755);
|
|
50
|
+
sh("chmod", ["777", P("logs")]);
|
|
51
|
+
const EXEC_TOKEN = "DUMMY-EXEC-" + crypto.randomBytes(8).toString("hex"), OBS_TOKEN = "DUMMY-OBS-" + crypto.randomBytes(8).toString("hex");
|
|
52
|
+
fs.writeFileSync(P("cred-exec/token"), EXEC_TOKEN, { mode: 0o400 }); sh("chown", ["p2exec", P("cred-exec/token")]);
|
|
53
|
+
fs.writeFileSync(P("cred-obs/token"), OBS_TOKEN, { mode: 0o400 }); sh("chown", ["p2obs", P("cred-obs/token")]);
|
|
54
|
+
fs.writeFileSync(P("approver-home/passphrase"), "synthetic-approver-passphrase-" + crypto.randomBytes(4).toString("hex"), { mode: 0o400 }); sh("chown", ["p2approver", P("approver-home/passphrase")]);
|
|
55
|
+
|
|
56
|
+
// ---------- install the PUBLISHED packages into a root-owned consumer ----------
|
|
57
|
+
const C = P("consumer"); fs.mkdirSync(C); fs.writeFileSync(path.join(C, "package.json"), '{"name":"consumer","private":true,"type":"module"}');
|
|
58
|
+
const tgz = fs.readdirSync(TARBALLS).filter((f) => f.endsWith(".tgz")).map((f) => path.join(TARBALLS, f));
|
|
59
|
+
const inst = sh("npm", ["install", "--ignore-scripts", "--no-audit", "--no-fund", ...tgz], { timeout: 180000, cwd: C, env: { ...process.env } });
|
|
60
|
+
if (inst.status !== 0) { console.error(inst.stderr); process.exit(3); }
|
|
61
|
+
const L = path.join(C, "launcher"); fs.mkdirSync(L);
|
|
62
|
+
for (const f of fs.readdirSync(HERE).filter((f) => f.endsWith(".mjs") && f !== "acceptance.mjs")) fs.copyFileSync(path.join(HERE, f), path.join(L, f));
|
|
63
|
+
sh("chmod", ["-R", "go-w,a+rX", C]);
|
|
64
|
+
const NM = path.join(C, "node_modules/@strixgov");
|
|
65
|
+
const versions = Object.fromEntries(fs.readdirSync(NM).map((n) => [n, JSON.parse(fs.readFileSync(path.join(NM, n, "package.json"), "utf8")).version]));
|
|
66
|
+
|
|
67
|
+
// ---------- start services ----------
|
|
68
|
+
const destPort = 20000 + Math.floor(Math.random() * 20000), connPort = destPort + 1;
|
|
69
|
+
const DEST = `http://127.0.0.1:${destPort}`;
|
|
70
|
+
const DESTLOG = P("logs/destination-requests.jsonl"); fs.writeFileSync(DESTLOG, ""); fs.chmodSync(DESTLOG, 0o666);
|
|
71
|
+
bg("p2dest", [NODE, path.join(L, "destination.mjs"), String(destPort), DESTLOG], "destination.log", { env: { DEST_EXEC: EXEC_TOKEN, DEST_OBS: OBS_TOKEN } });
|
|
72
|
+
// hosted-connector stand-in (an "undeclared route" the agent may try): logs every hit itself
|
|
73
|
+
const CONNLOG = P("logs/connector-standin-requests.jsonl"); fs.writeFileSync(CONNLOG, ""); fs.chmodSync(CONNLOG, 0o666);
|
|
74
|
+
bg("p2dest", [NODE, "-e", `require('http').createServer((q,s)=>{require('fs').appendFileSync('${CONNLOG}',JSON.stringify({t:Date.now(),m:q.method,u:q.url})+'\\n');s.end('connector-standin')}).listen(${connPort},'127.0.0.1')`], "connector.log");
|
|
75
|
+
{ const r = as("p2approver", [NODE, path.join(L, "approver.mjs"), "init", P("approver-home")], { timeout: 60000 }); if (r.status !== 0) { console.error("approver init failed:", r.stderr, r.stdout); process.exit(5); } }
|
|
76
|
+
fs.copyFileSync(P("approver-home/approver-public.json"), P("approver-public.json")); fs.chmodSync(P("approver-public.json"), 0o644); // public key only (pinned by proxy config and authorizer)
|
|
77
|
+
const approverPub = P("approver-public.json");
|
|
78
|
+
const mkcfg = sh(NODE, [path.join(L, "make-config.mjs"), P("proxy-config.json"), approverPub, P("proxy-approvals"), P("st-proxy"), path.join(L, "shim.mjs"), P("sock-exec/exec.sock"), P("sock-claim/claim.sock"), process.env.APPROVAL_TIMEOUT_MS ?? "9000"]);
|
|
79
|
+
if (mkcfg.status !== 0) { console.error(mkcfg.stderr); process.exit(4); }
|
|
80
|
+
fs.writeFileSync(P("config-summary.json"), mkcfg.stdout);
|
|
81
|
+
const startAuth = (ttl) => bg("p2auth", [NODE, path.join(L, "authorizer.mjs"), P("sock-reg/reg.sock"), P("sock-claim/claim.sock"), P("st-auth"), approverPub, "tenant-synthetic", "isolated-test"], "authorizer.log", { env: { AUTHZ_TTL_MS: String(ttl) } });
|
|
82
|
+
const startExec = (extra = {}) => bg("p2exec", [NODE, path.join(L, "executor.mjs"), P("sock-exec/exec.sock"), P("st-exec"), P("st-auth/jwks.json"), DEST, "tenant-synthetic", "isolated-test"], "executor.log", { env: { EXECUTOR_TOKEN: EXEC_TOKEN, ...extra } });
|
|
83
|
+
startAuth(60000); await sleep(800); startExec(); await sleep(800);
|
|
84
|
+
bg("p2proxy", [NODE, path.join(L, "proxy-host.mjs"), P("sock-agent/mcp.sock"), path.join(NM, "mcp-proxy/bin/strix-mcp-proxy.mjs"), P("proxy-config.json")], "proxy-host.log");
|
|
85
|
+
bg("p2proxy", [NODE, path.join(L, "approval-relay.mjs"), P("proxy-approvals"), P("approver-home/approvals")], "relay.log");
|
|
86
|
+
await sleep(1200);
|
|
87
|
+
for (const [u, pat] of [["p2auth", "authorizer.mjs"], ["p2exec", "executor.mjs"], ["p2proxy", "proxy-host.mjs"], ["p2dest", "destination.mjs"]]) if (!pid(u, pat)) { console.error(`HARNESS FAULT: ${pat} not running`); console.error(fs.readdirSync(P("logs")).map((n) => n + ":\n" + fs.readFileSync(P("logs/" + n), "utf8").slice(-600)).join("\n")); process.exit(70); }
|
|
88
|
+
fs.writeFileSync(P("services.txt"), sh("ps", ["-eo", "pid,user,args"]).stdout.split("\n").filter((l) => /p2(agent|proxy|exec|auth|approver|dest|obs)/.test(l)).join("\n").replace(/DUMMY-[a-z]+-[0-9a-f]+/g, "<redacted>"));
|
|
89
|
+
|
|
90
|
+
const agentSock = P("sock-agent/mcp.sock");
|
|
91
|
+
const agentCall = (tool, args, ms = 60000) => new Promise((resolve) => {
|
|
92
|
+
const out = fs.openSync(P("logs/agent-call.out"), "w");
|
|
93
|
+
const p = spawn("setpriv", asArgs("p2agent", [NODE, path.join(L, "agent-client.mjs"), agentSock, "call", tool, JSON.stringify(args)], { groups: false }), { stdio: ["ignore", "pipe", "pipe"] });
|
|
94
|
+
let buf = ""; p.stdout.on("data", (d) => (buf += d)); p.stderr.on("data", () => {});
|
|
95
|
+
const t = setTimeout(() => p.kill(), ms);
|
|
96
|
+
p.on("close", () => { clearTimeout(t); resolve(j(buf.trim().split("\n").pop()) ?? { ok: false, error: "no output: " + buf.slice(0, 120) }); });
|
|
97
|
+
});
|
|
98
|
+
const pendingIds = () => (fs.existsSync(P("approver-home/approvals")) ? fs.readdirSync(P("approver-home/approvals")).filter((n) => n.endsWith(".request.json")).map((n) => n.replace(".request.json", "")) : []);
|
|
99
|
+
const approve = (id) => { const r = as("p2approver", [NODE, path.join(L, "approver.mjs"), "approve", P("approver-home"), id, P("sock-reg/reg.sock")], { timeout: 30000 }); return j(r.stdout.trim().split("\n").pop()) ?? { err: r.stderr.slice(0, 200) }; };
|
|
100
|
+
const destLines = () => fs.readFileSync(DESTLOG, "utf8").trim().split("\n").filter(Boolean).map(JSON.parse);
|
|
101
|
+
const marks = () => destLines().length;
|
|
102
|
+
const since = (m) => destLines().slice(m).filter((x) => !(x.method === "GET" && x.role === "observer"));
|
|
103
|
+
const execRaw = (user, msg) => as(user, [NODE, "-e", `const net=require('net');const c=net.connect('${P("sock-exec/exec.sock")}');let b='';c.on('error',e=>console.log(JSON.stringify({sockErr:e.code})));c.on('connect',()=>c.write(${JSON.stringify(JSON.stringify(msg))}+'\\n'));c.on('data',d=>b+=d);c.on('end',()=>console.log(b.trim()))`], { groups: true });
|
|
104
|
+
const observe = (outName) => { as("p2obs", [NODE, path.join(L, "reconcile.mjs"), P("st-exec"), DEST, P("logs/" + outName)], { env: { OBSERVER_TOKEN: OBS_TOKEN } }); fs.chmodSync(P("logs/" + outName), 0o644); return j(fs.readFileSync(P("logs/" + outName), "utf8")); };
|
|
105
|
+
async function approvedCall(tool, args) { // full path: agent -> published proxy -> approver -> authorizer -> shim -> executor -> destination
|
|
106
|
+
const before = new Set(pendingIds());
|
|
107
|
+
const p = agentCall(tool, args);
|
|
108
|
+
let id; for (let i = 0; i < 80 && !id; i++) { await sleep(100); id = pendingIds().find((x) => !before.has(x)); }
|
|
109
|
+
if (!id) return { result: await p, id: null };
|
|
110
|
+
const ap = approve(id);
|
|
111
|
+
return { result: await p, id, ap };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// ================= Gate A: published-proxy topology reachable; MCP lists =================
|
|
115
|
+
const lst = as("p2agent", [NODE, path.join(L, "agent-client.mjs"), agentSock, "list"], { groups: false });
|
|
116
|
+
rec("TP-01", "topology", "agent lists tools through bridge -> trusted proxy service -> published proxy 0.2.4 -> credential-free shim", "tool list returned", lst.stdout.trim() || lst.stderr.slice(0, 150), j(lst.stdout) ? "PASS" : "FAIL");
|
|
117
|
+
|
|
118
|
+
// ================= Gate B: credential isolation against THIS topology =================
|
|
119
|
+
const XPID = pid("p2exec", "executor.mjs"), APID = pid("p2auth", "authorizer.mjs"), HPID = pid("p2proxy", "proxy-host.mjs");
|
|
120
|
+
const denied = (r) => /Permission denied|EACCES|EPERM/.test(r.stdout + r.stderr);
|
|
121
|
+
const A = (argv, o) => as("p2agent", argv, { groups: false, ...o });
|
|
122
|
+
const probe = (id, route, argv, expectDenied = true) => { const r = A(argv); const ok = expectDenied ? denied(r) : true; rec(id, "credential-isolation", route, "kernel permission denial", (r.stdout + r.stderr).trim().replace(/\n/g, " "), ok ? "PASS" : "FAIL"); return r; };
|
|
123
|
+
probe("CI-01", "read executor credential file", ["cat", P("cred-exec/token")]);
|
|
124
|
+
probe("CI-02", "read observer credential file", ["cat", P("cred-obs/token")]);
|
|
125
|
+
probe("CI-03", "read authorizer signing key", ["cat", P("st-auth/private.pem")]);
|
|
126
|
+
probe("CI-04", "read executor outcome-signing key", ["cat", P("st-exec/outcome-key.pem")]);
|
|
127
|
+
probe("CI-05", "read approver passphrase", ["cat", P("approver-home/passphrase")]);
|
|
128
|
+
probe("CI-06", "read approver private key", ["cat", P("approver-home/approver/key.enc.json")]);
|
|
129
|
+
probe("CI-07", "list proxy approvals dir (pending requests)", ["ls", P("proxy-approvals")]);
|
|
130
|
+
probe("CI-08", "read executor /proc environ", ["cat", `/proc/${XPID}/environ`]);
|
|
131
|
+
probe("CI-09", "enumerate executor fds", ["ls", `/proc/${XPID}/fd`]);
|
|
132
|
+
probe("CI-10", "read executor memory", [NODE, "-e", `require('fs').readFileSync('/proc/${XPID}/mem')`]);
|
|
133
|
+
probe("CI-11", "read authorizer /proc environ", ["cat", `/proc/${APID}/environ`]);
|
|
134
|
+
probe("CI-12", "read proxy-service /proc environ", ["cat", `/proc/${HPID}/environ`]);
|
|
135
|
+
const pk = sh("find", [P("st-proxy"), "-name", "*.json", "-o", "-name", "*.pem", "-o", "-name", "private*"]).stdout.split("\n").filter((f) => /key|private/i.test(f));
|
|
136
|
+
const pkr = pk.map((f) => ({ f, r: A(["cat", f]) }));
|
|
137
|
+
rec("CI-13", "credential-isolation", "read proxy signing private key(s) in proxy store", "private key unreadable by agent", pkr.map((x) => path.basename(x.f) + ":" + (denied(x.r) ? "denied" : "READABLE")).join(", ") || "no key files found", pkr.length && pkr.every((x) => denied(x.r) || /public/i.test(x.f)) ? "PASS" : (pkr.length ? "FAIL" : "BLOCKED"));
|
|
138
|
+
const ps = A(["ps", "-eo", "pid,user,args"]); const leak = /DUMMY-/.test(ps.stdout);
|
|
139
|
+
rec("CI-14", "credential-isolation", "credentials in process listing (argv)", "no credential on any command line", leak ? "LEAK" : "none", leak ? "FAIL" : "PASS");
|
|
140
|
+
const envp = A([NODE, "-e", "console.log(Object.keys(process.env).filter(k=>/TOKEN|SECRET|KEY|PASS/i.test(k)).join(',')||'none')"]);
|
|
141
|
+
rec("CI-15", "credential-isolation", "agent process environment", "no credential variables", envp.stdout.trim(), envp.stdout.trim() === "none" ? "PASS" : "FAIL");
|
|
142
|
+
const fds = A(["bash", "-c", 'for f in /proc/self/fd/*; do t=$(readlink $f 2>/dev/null); case "$t" in /*|pipe:*|socket:*) echo "${f##*/}=$t";; esac; done | grep -v "^[012]=" | grep -v "/proc/.*/fd$" | tr "\\n" " "']);
|
|
143
|
+
rec("CI-16", "credential-isolation", "agent inherited file descriptors", "none beyond stdio", fds.stdout.trim() || "none", fds.stdout.trim() === "" ? "PASS" : "FAIL");
|
|
144
|
+
const grep = A(["grep", "-rl", "-e", EXEC_TOKEN, "-e", OBS_TOKEN, W]); const files = grep.stdout.trim().split("\n").filter(Boolean);
|
|
145
|
+
rec("CI-17", "credential-isolation", "credentials in any file/log readable by agent (recursive over the whole work tree, incl. logs, receipts, relayed approvals)", "no readable file contains a credential", files.join(" ") || "none", files.length ? "FAIL" : "PASS");
|
|
146
|
+
const sudo = A(["sudo", "-n", "-u", "p2exec", "id"]);
|
|
147
|
+
rec("CI-18", "credential-isolation", "agent escalates to executor uid via sudo", "no rule", (sudo.stdout + sudo.stderr).trim().slice(0, 80), /uid=/.test(sudo.stdout) ? "FAIL" : "PASS");
|
|
148
|
+
for (const [id, name, sockp] of [["IPC-01", "executor socket", "sock-exec/exec.sock"], ["IPC-02", "authorizer claim socket", "sock-claim/claim.sock"], ["IPC-03", "authorizer register socket", "sock-reg/reg.sock"]]) {
|
|
149
|
+
const r = A([NODE, "-e", `const c=require('net').connect('${P(sockp)}');c.on('error',e=>console.log(e.code));c.on('connect',()=>{console.log('CONNECTED');process.exit()})`]);
|
|
150
|
+
rec(id, "credential-isolation", `agent connects to ${name} directly (IPC)`, "EACCES", r.stdout.trim(), /EACCES|EPERM/.test(r.stdout) ? "PASS" : "FAIL");
|
|
151
|
+
}
|
|
152
|
+
// trusted-config / executable integrity: agent cannot modify
|
|
153
|
+
for (const [id, what, target] of [["INT-01", "proxy config", P("proxy-config.json")], ["INT-02", "executor script", path.join(L, "executor.mjs")], ["INT-03", "shim script", path.join(L, "shim.mjs")], ["INT-04", "published proxy package", path.join(NM, "mcp-proxy/package.json")]]) {
|
|
154
|
+
const r = A(["bash", "-c", `echo tampered >> '${target}'`]);
|
|
155
|
+
rec(id, "trusted-config-integrity", `agent appends to ${what}`, "write denied", (r.stderr || r.stdout).trim(), denied(r) ? "PASS" : "FAIL");
|
|
156
|
+
}
|
|
157
|
+
const subst = A(["bash", "-c", `rm -f '${P("sock-exec/exec.sock")}'; ln -s /dev/null '${P("sock-exec/exec.sock")}'`]);
|
|
158
|
+
rec("INT-05", "trusted-config-integrity", "agent replaces executor socket (executor substitution)", "write denied in socket directory", (subst.stderr || subst.stdout).trim(), denied(subst) ? "PASS" : "FAIL");
|
|
159
|
+
const subst2 = A(["bash", "-c", `rm -f '${P("sock-agent/mcp.sock")}'`]);
|
|
160
|
+
rec("INT-06", "trusted-config-integrity", "agent removes proxy-service socket", "write denied (dir is search-only for agent)", (subst2.stderr || subst2.stdout).trim(), denied(subst2) ? "PASS" : "FAIL");
|
|
161
|
+
|
|
162
|
+
// ================= Gate C: authorization through the real path =================
|
|
163
|
+
let m = marks();
|
|
164
|
+
const okp = await approvedCall("create_branch", { owner: "synthetic", repo: "fixture", branch: "authorized-1", from_branch: "main" });
|
|
165
|
+
const d1 = since(m);
|
|
166
|
+
rec("AZ-01", "authorization", "agent -> published proxy -> approver-signed approval -> payload-bound token -> executor -> destination", "branch created exactly once; destination request role=executor 201", JSON.stringify({ call: okp.result, approval: okp.ap?.registered?.ok, dest: d1.map((x) => `${x.method} ${x.url} ${x.role} ${x.status}`) }), okp.result.ok && !okp.result.isError && d1.length === 1 && d1[0].status === 201 ? "PASS" : "FAIL");
|
|
167
|
+
m = marks();
|
|
168
|
+
const noap = await agentCall("create_branch", { owner: "synthetic", repo: "fixture", branch: "unapproved-1", from_branch: "main" });
|
|
169
|
+
rec("AZ-02", "authorization", "write with no approval (approval times out)", "denied by published proxy; destination sees nothing", JSON.stringify({ call: noap, dest: since(m).length }), since(m).length === 0 && (noap.isError || !noap.ok) ? "PASS" : "FAIL");
|
|
170
|
+
m = marks();
|
|
171
|
+
const r3 = j(execRaw("p2proxy", { tool: "create_branch", args: { owner: "synthetic", repo: "fixture", branch: "bypass-no-token" } }).stdout);
|
|
172
|
+
rec("AZ-03", "authorization", "trusted proxy uid calls executor directly with no token", "AUTHORIZATION_REQUIRED; destination sees nothing", JSON.stringify({ reply: r3, dest: since(m).length }), r3?.error === "AUTHORIZATION_REQUIRED" && since(m).length === 0 ? "PASS" : "FAIL");
|
|
173
|
+
const forgedPriv = crypto.generateKeyPairSync("ed25519").privateKey;
|
|
174
|
+
const fpay = { schemaVersion: 1, authorizationId: "authz_forged01", decisionId: "dec_forged", capabilityId: "mcp.github.create_branch", actorId: "agent:controlled-launcher-demo", actorClass: "agent", payloadHash: "sha256:" + "0".repeat(64), tenantId: "tenant-synthetic", environment: "isolated-test", nonce: crypto.randomBytes(16).toString("hex"), issuedAt: "2026-11-22T00:00:00Z", expiresAt: "2099-01-01T00:00:00Z" };
|
|
175
|
+
const { canonicalizeJSON } = await import(path.join(C, "node_modules/@strixgov/mcp-token-validator/src/index.mjs"));
|
|
176
|
+
const forged = { ...fpay, signingKeyId: "mode3-authz-test-1", signature: crypto.sign(null, Buffer.from(canonicalizeJSON(fpay)), forgedPriv).toString("base64url") };
|
|
177
|
+
m = marks();
|
|
178
|
+
const r4 = j(execRaw("p2proxy", { tool: "create_branch", args: { owner: "synthetic", repo: "fixture", branch: "bypass-forged" }, token: forged }).stdout);
|
|
179
|
+
rec("AZ-04", "authorization", "forged token (valid shape, wrong signing key)", "AUTHORIZATION_INVALID / SIGNATURE_INVALID", JSON.stringify({ reply: r4, dest: since(m).length }), r4?.detail === "SIGNATURE_INVALID" && since(m).length === 0 ? "PASS" : "FAIL");
|
|
180
|
+
|
|
181
|
+
// approve payload A; then try payload B with A's token (payload substitution), then replay A
|
|
182
|
+
const argsA = { owner: "synthetic", repo: "fixture", branch: "authorized-A", from_branch: "main" };
|
|
183
|
+
const argsB = { owner: "synthetic", repo: "fixture", branch: "substituted-B", from_branch: "main" };
|
|
184
|
+
const sockClaim = P("sock-claim/claim.sock");
|
|
185
|
+
const claim = (u, payload) => j(as(u, [NODE, "-e", `const c=require('net').connect('${sockClaim}');let b='';c.on('error',e=>console.log(JSON.stringify({sockErr:e.code})));c.on('connect',()=>c.write(JSON.stringify({op:'claim',payloadHash:'${payload}',capabilityId:'mcp.github.create_branch'})+'\\n'));c.on('data',d=>b+=d);c.on('end',()=>console.log(b.trim()))`], { groups: true }).stdout);
|
|
186
|
+
const { payloadHash: ph } = await import(path.join(L, "lib.mjs"));
|
|
187
|
+
// obtain an approval for A without letting the shim consume the token: ask the proxy path, but intercept by claiming first as proxy uid
|
|
188
|
+
const before = new Set(pendingIds());
|
|
189
|
+
const pA = agentCall("create_branch", argsA, 30000);
|
|
190
|
+
let idA; for (let i = 0; i < 80 && !idA; i++) { await sleep(100); idA = pendingIds().find((x) => !before.has(x)); }
|
|
191
|
+
const apA = approve(idA);
|
|
192
|
+
const tokenA = claim("p2proxy", ph(argsA)); // race the shim: whichever claims first holds the one token
|
|
193
|
+
await pA;
|
|
194
|
+
const tokA = tokenA?.token ?? null;
|
|
195
|
+
if (!tokA) rec("AZ-05", "authorization", "payload substitution (token for A presented with B)", "needs a claimed token", "shim claimed first; token held by the shim path (see AZ-01 for the legitimate claim). Re-run to exercise direct substitution", "BLOCKED");
|
|
196
|
+
else {
|
|
197
|
+
m = marks();
|
|
198
|
+
const rB = j(execRaw("p2proxy", { tool: "create_branch", args: argsB, token: tokA }).stdout);
|
|
199
|
+
rec("AZ-05", "authorization", "payload substitution: token approved for A presented with B", "AUTHORIZATION_PAYLOAD_MISMATCH; destination sees nothing", JSON.stringify({ reply: rB, dest: since(m).length }), rB?.error === "AUTHORIZATION_PAYLOAD_MISMATCH" && since(m).length === 0 ? "PASS" : "FAIL");
|
|
200
|
+
const rA2 = j(execRaw("p2proxy", { tool: "create_branch", args: argsA, token: tokA }).stdout);
|
|
201
|
+
rec("AZ-06", "authorization", "replay: same token again (it was consumed by the payload-mismatch presentation: single use is by nonce, not by outcome)", "NONCE_REUSED; destination sees nothing", JSON.stringify({ reply: rA2, dest: since(m).length }), rA2?.detail === "NONCE_REUSED" && since(m).length === 0 ? "PASS" : "FAIL");
|
|
202
|
+
}
|
|
203
|
+
const reg = j(as("p2approver", [NODE, "-e", `const c=require('net').connect('${P("sock-reg/reg.sock")}');c.on('connect',()=>c.write(JSON.stringify({op:'register',requestText:require('fs').readFileSync('${P("approver-home/approvals")}/${idA}.request.json','utf8'),response:JSON.parse(require('fs').readFileSync('${P("approver-home/approvals")}/${idA}.response.json','utf8'))})+'\\n'));let b='';c.on('data',d=>b+=d);c.on('end',()=>console.log(b.trim()))`]).stdout);
|
|
204
|
+
rec("AZ-07", "authorization", "replay of an approval: register the same signed approval a second time", "APPROVAL_ALREADY_USED", JSON.stringify(reg), reg?.error === "APPROVAL_ALREADY_USED" ? "PASS" : (reg ? "FAIL" : "BLOCKED"));
|
|
205
|
+
// tampered approval / wrong approver
|
|
206
|
+
const reqText = fs.existsSync(P(`approver-home/approvals/${idA}.request.json`)) ? fs.readFileSync(P(`approver-home/approvals/${idA}.request.json`), "utf8") : null;
|
|
207
|
+
const resp = fs.existsSync(P(`approver-home/approvals/${idA}.response.json`)) ? JSON.parse(fs.readFileSync(P(`approver-home/approvals/${idA}.response.json`), "utf8")) : null;
|
|
208
|
+
const regTry = (body) => j(sh(NODE, ["-e", `const c=require('net').connect('${P("sock-reg/reg.sock")}');c.on('error',e=>console.log(JSON.stringify({sockErr:e.code})));c.on('connect',()=>c.write(${JSON.stringify(JSON.stringify(body))}+'\\n'));let b='';c.on('data',d=>b+=d);c.on('end',()=>console.log(b.trim()))`]).stdout);
|
|
209
|
+
if (reqText && resp) {
|
|
210
|
+
const t1 = regTry({ op: "register", requestText: reqText.replace(argsA.branch, "tampered"), response: resp });
|
|
211
|
+
rec("AZ-08", "authorization", "approval presented with a request whose bytes were altered", "REQUEST_HASH_MISMATCH", JSON.stringify(t1), t1?.error === "REQUEST_HASH_MISMATCH" ? "PASS" : "FAIL");
|
|
212
|
+
const t2 = regTry({ op: "register", requestText: reqText, response: { ...resp, signature: Buffer.alloc(64, 1).toString("base64url") } });
|
|
213
|
+
rec("AZ-09", "authorization", "approval with corrupted signature", "BAD_SIGNATURE", JSON.stringify(t2), t2?.error === "BAD_SIGNATURE" ? "PASS" : "FAIL");
|
|
214
|
+
const t3 = regTry({ op: "register", requestText: reqText, response: { ...resp, kid: "0000000000000000" } });
|
|
215
|
+
rec("AZ-10", "authorization", "approval signed by an unpinned approver key", "UNKNOWN_APPROVER_KEY", JSON.stringify(t3), t3?.error === "UNKNOWN_APPROVER_KEY" ? "PASS" : "FAIL");
|
|
216
|
+
} else rec("AZ-08..10", "authorization", "tamper tests on approval", "needs approval files", "approval files already consumed/removed by the proxy before capture", "BLOCKED");
|
|
217
|
+
|
|
218
|
+
// concurrency: one approval, 8 parallel claims -> exactly one token
|
|
219
|
+
const argsC = { owner: "synthetic", repo: "fixture", branch: "authorized-C", from_branch: "main" };
|
|
220
|
+
const beforeC = new Set(pendingIds());
|
|
221
|
+
const reqPath = (id) => P(`approver-home/approvals/${id}.request.json`);
|
|
222
|
+
// create a pending request WITHOUT letting the shim claim: call the proxy, approve, but race 8 claimants plus the shim
|
|
223
|
+
const pC = agentCall("create_branch", argsC, 30000);
|
|
224
|
+
let idC; for (let i = 0; i < 80 && !idC; i++) { await sleep(100); idC = pendingIds().find((x) => !beforeC.has(x)); }
|
|
225
|
+
approve(idC);
|
|
226
|
+
const claimers = await Promise.all(Array.from({ length: 8 }, () => new Promise((res) => res(claim("p2proxy", ph(argsC))))));
|
|
227
|
+
const callC = await pC;
|
|
228
|
+
const winners = claimers.filter((x) => x?.ok).length;
|
|
229
|
+
const shimGot = callC.ok && !callC.isError ? 1 : 0;
|
|
230
|
+
rec("CC-01", "concurrency", "one approval, 8 parallel claimants + the shim", "total tokens delivered <= 1", `claimant winners=${winners}, shim-delivered=${shimGot}`, winners + shimGot <= 1 ? "PASS" : "FAIL");
|
|
231
|
+
// concurrent presentation of one token to the executor
|
|
232
|
+
const tokC = claimers.find((x) => x?.ok)?.token;
|
|
233
|
+
if (tokC) {
|
|
234
|
+
m = marks();
|
|
235
|
+
const rs = await Promise.all(Array.from({ length: 8 }, () => new Promise((res) => res(j(execRaw("p2proxy", { tool: "create_branch", args: argsC, token: tokC }).stdout)))));
|
|
236
|
+
const succ = rs.filter((x) => x?.ok && !x?.isError).length; const created = since(m).filter((x) => x.status === 201).length;
|
|
237
|
+
rec("CC-02", "concurrency", "one valid token presented 8x in parallel to the executor", "exactly one execution (atomic nonce burn)", `successes=${succ}, destination 201s=${created}`, succ === 1 && created === 1 ? "PASS" : "FAIL");
|
|
238
|
+
} else rec("CC-02", "concurrency", "one valid token presented 8x in parallel", "needs a claimed token", "the shim won the claim race in CC-01", "BLOCKED");
|
|
239
|
+
|
|
240
|
+
// expiry: restart authorizer with 1s TTL, mint, wait, present
|
|
241
|
+
sh("pkill", ["-u", "p2auth", "-f", "authorizer.mjs"]); await sleep(500); startAuth(1000); await sleep(800);
|
|
242
|
+
const argsE = { owner: "synthetic", repo: "fixture", branch: "expiring-E", from_branch: "main" };
|
|
243
|
+
const beforeE = new Set(pendingIds());
|
|
244
|
+
const pE = agentCall("create_branch", argsE, 30000);
|
|
245
|
+
let idE; for (let i = 0; i < 80 && !idE; i++) { await sleep(100); idE = pendingIds().find((x) => !beforeE.has(x)); }
|
|
246
|
+
approve(idE);
|
|
247
|
+
const tokE = claim("p2proxy", ph(argsE))?.token; await pE;
|
|
248
|
+
if (tokE) { await sleep(2200); m = marks(); const rE = j(execRaw("p2proxy", { tool: "create_branch", args: argsE, token: tokE }).stdout);
|
|
249
|
+
rec("AZ-11", "authorization", "expired token (1s TTL, presented after 2.2s)", "AUTHORIZATION_INVALID / EXPIRED", JSON.stringify({ reply: rE, dest: since(m).length }), rE?.detail === "EXPIRED" && since(m).length === 0 ? "PASS" : "FAIL"); }
|
|
250
|
+
else rec("AZ-11", "authorization", "expired token", "needs a claimed token", "shim won the claim", "BLOCKED");
|
|
251
|
+
sh("pkill", ["-u", "p2auth", "-f", "authorizer.mjs"]); await sleep(500); startAuth(60000); await sleep(800);
|
|
252
|
+
|
|
253
|
+
// crash recovery: executor exits after STARTED fsync; restart; no retry; observer resolves
|
|
254
|
+
sh("pkill", ["-u", "p2exec", "-f", "executor.mjs"]); await sleep(500); startExec({ EXECUTOR_TEST_CRASH_AFTER_STARTED: "1" }); await sleep(800);
|
|
255
|
+
const argsR = { owner: "synthetic", repo: "fixture", branch: "crash-R", from_branch: "main" };
|
|
256
|
+
m = marks();
|
|
257
|
+
const crashed = await approvedCall("create_branch", argsR);
|
|
258
|
+
await sleep(500);
|
|
259
|
+
const alive = !!pid("p2exec", "executor.mjs");
|
|
260
|
+
sh("pkill", ["-u", "p2exec", "-f", "executor.mjs"]); await sleep(300); startExec(); await sleep(1000);
|
|
261
|
+
const attempts = fs.readFileSync(P("st-exec/attempts.jsonl"), "utf8").trim().split("\n").map(JSON.parse);
|
|
262
|
+
const recovered = attempts.find((a) => a.state === "RECOVERED_UNKNOWN");
|
|
263
|
+
const obs1 = observe("reconcile-after-crash.json");
|
|
264
|
+
const row = obs1.attempts.find((a) => a.ref === "refs/heads/crash-R");
|
|
265
|
+
rec("CR-01", "crash-recovery", "executor crashes after durable STARTED, before destination call; restart", "no automatic retry; attempt recorded UNKNOWN; observer resolves NOT_EXECUTED; destination unchanged", JSON.stringify({ executorAliveAfterCall: alive, recovered: !!recovered, verdict: row?.verdict, destRequestsDuringCrash: since(m).length, callResult: crashed.result }), !alive && recovered && row?.verdict === "RESOLVED_BY_OBSERVATION_NOT_EXECUTED" && since(m).length === 0 ? "PASS" : "FAIL");
|
|
266
|
+
|
|
267
|
+
// ================= Alternate routes to the protected destination (before the network rule: credential control only) =================
|
|
268
|
+
{
|
|
269
|
+
const post = (hdr) => A(["curl", "-s", "-m", "4", "-o", "/dev/null", "-w", "%{http_code}", "-X", "POST", ...hdr, `${DEST}/repos/synthetic/fixture/git/refs`, "-d", '{"ref":"refs/heads/bypass-curl"}']);
|
|
270
|
+
let m0 = marks(); let r = post([]); let d = since(m0);
|
|
271
|
+
rec("BP-01", "alternate-route", "direct REST create-branch, no credential", "401 at destination; no write", `http=${r.stdout.trim()}; destination: ${d.map((x) => `${x.role} ${x.status}`)}`, r.stdout.trim() === "401" && d.every((x) => x.status === 401) ? "PASS" : "FAIL");
|
|
272
|
+
m0 = marks(); r = post(["-H", "Authorization: Bearer agent-held-dummy"]); d = since(m0);
|
|
273
|
+
rec("BP-02", "alternate-route", "direct REST create-branch with the only credential the agent holds", "401 at destination; no write", `http=${r.stdout.trim()}; destination: ${d.map((x) => `${x.role} ${x.status}`)}`, r.stdout.trim() === "401" && d.every((x) => x.status === 401) ? "PASS" : "FAIL");
|
|
274
|
+
m0 = marks(); r = A(["git", "-c", "http.extraHeader=Authorization: Bearer agent-held-dummy", "ls-remote", `${DEST}/synthetic/fixture.git`], { timeout: 15000 }); d = since(m0);
|
|
275
|
+
rec("BP-03", "alternate-route", "git over HTTP with the agent's credential", "no write accepted", `git exit=${r.status}; destination: ${d.map((x) => `${x.method} ${x.role} ${x.status}`)}`, d.every((x) => x.status !== 201 && x.status !== 200) ? "PASS" : "FAIL");
|
|
276
|
+
m0 = marks(); r = A(["env", `GH_HOST=127.0.0.1:${destPort}`, "GH_TOKEN=agent-held-dummy", "gh", "api", "/repos/synthetic/fixture/branches"], { timeout: 15000 }); d = since(m0);
|
|
277
|
+
rec("BP-04", "alternate-route", "gh CLI against the destination with the agent's credential", "no data returned", `gh exit=${r.status}; destination reads by non-observer: ${destLines().slice(m0).map((x) => x.role + " " + x.status)}`, !/branches/.test(r.stdout) ? "PASS" : "FAIL");
|
|
278
|
+
m0 = marks(); r = A([NODE, path.join(L, "executor.mjs"), P("work-agent/own.sock"), P("work-agent"), P("st-auth/jwks.json"), DEST, "tenant-synthetic", "isolated-test"], { timeout: 10000 });
|
|
279
|
+
rec("BP-05", "alternate-route", "agent runs its own copy of the executor", "no credential available: refuses to start; destination sees nothing", `exit=${r.status} ${r.stderr.trim().slice(0, 80)}; destination +${since(m0).length}`, r.status === 2 && since(m0).length === 0 ? "PASS" : "FAIL");
|
|
280
|
+
m0 = marks(); r = A([NODE, "-e", `fetch('${DEST}/repos/synthetic/fixture/git/refs',{method:'POST',headers:{authorization:'Bearer '+(process.env.EXECUTOR_TOKEN||'none')},body:JSON.stringify({ref:'refs/heads/bypass-own-mcp'})}).then(r=>console.log(r.status))`]); d = since(m0);
|
|
281
|
+
rec("BP-06", "alternate-route", "agent-launched second tool server calling the destination", "401 at destination; no write", `http=${r.stdout.trim()}; destination: ${d.map((x) => `${x.role} ${x.status}`)}`, r.stdout.trim() === "401" && d.every((x) => x.status === 401) ? "PASS" : "FAIL");
|
|
282
|
+
const obsNow = observe("reconcile-bypass-check.json");
|
|
283
|
+
rec("BP-07", "alternate-route", "independent observer after all bypass attempts", "destination holds no branch without a matching executor attempt record", JSON.stringify(obsNow.destinationBranchesWithNoAttemptRecord), obsNow.destinationBranchesWithNoAttemptRecord.length === 0 ? "PASS" : "FAIL");
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// ================= Gate D: network policy (declared default-deny for the agent identity) =================
|
|
287
|
+
const connUrl = `http://127.0.0.1:${connPort}/hosted-connector`;
|
|
288
|
+
const tryNet = (u) => A(["curl", "-s", "-m", "3", "-o", "/dev/null", "-w", "%{http_code}", u]);
|
|
289
|
+
const hits = () => fs.readFileSync(CONNLOG, "utf8").trim().split("\n").filter(Boolean).length;
|
|
290
|
+
let h0 = hits(); const ctl = tryNet(connUrl); await sleep(300);
|
|
291
|
+
rec("NP-01", "network", "POSITIVE CONTROL (no policy yet): agent reaches the hosted-connector stand-in", "route is reachable without the policy (proves the test can detect a bypass)", `http=${ctl.stdout.trim()}, stand-in hits +${hits() - h0}`, hits() > h0 ? "PASS" : "BLOCKED");
|
|
292
|
+
const ipt = sh("iptables", ["-I", "OUTPUT", "1", "-m", "owner", "--uid-owner", "p2agent", "-j", "REJECT"]);
|
|
293
|
+
const ipt6 = sh("ip6tables", ["-I", "OUTPUT", "1", "-m", "owner", "--uid-owner", "p2agent", "-j", "REJECT"]);
|
|
294
|
+
if (ipt.status !== 0) rec("NP-02", "network", "install default-deny egress rule for agent identity", "rule installed", (ipt.stderr || "").trim(), "BLOCKED");
|
|
295
|
+
else {
|
|
296
|
+
h0 = hits(); const m0 = marks(); const r1 = tryNet(connUrl); const r2 = tryNet(`${DEST}/repos/synthetic/fixture/git/refs`); const r3b = tryNet("https://example.com"); await sleep(300);
|
|
297
|
+
rec("NP-02", "network", "hosted-connector stand-in after default-deny rule", "connection refused; stand-in log unchanged", `http=${r1.stdout.trim() || "000"}, stand-in hits +${hits() - h0}`, hits() === h0 ? "PASS" : "FAIL");
|
|
298
|
+
rec("NP-03", "network", "agent direct to destination after rule", "refused; destination log unchanged", `http=${r2.stdout.trim() || "000"}, destination requests +${since(m0).length}`, since(m0).length === 0 ? "PASS" : "FAIL");
|
|
299
|
+
rec("NP-04", "network", "agent to external HTTPS host after rule", "refused", `http=${r3b.stdout.trim() || "000"}`, (r3b.stdout.trim() || "000") === "000" ? "PASS" : "FAIL");
|
|
300
|
+
const agentStill = as("p2agent", [NODE, path.join(L, "agent-client.mjs"), agentSock, "list"], { groups: false });
|
|
301
|
+
rec("NP-05", "network", "governed path still works for the agent (AF_UNIX is not covered by the network rule)", "tool list still returned", agentStill.stdout.trim().slice(0, 100), j(agentStill.stdout) ? "PASS" : "FAIL");
|
|
302
|
+
const counters = sh("iptables", ["-nvL", "OUTPUT", "--line-numbers"]).stdout; fs.writeFileSync(P("iptables-counters.txt"), counters);
|
|
303
|
+
rec("NP-06", "network", "enforcement scope declared", "rule applies to uid p2agent only (IPv4+IPv6 OUTPUT); other uids, hosts, and containers are NOT covered", `ip6tables rule status=${ipt6.status}`, "PASS");
|
|
304
|
+
}
|
|
305
|
+
sh("iptables", ["-D", "OUTPUT", "-m", "owner", "--uid-owner", "p2agent", "-j", "REJECT"]); sh("ip6tables", ["-D", "OUTPUT", "-m", "owner", "--uid-owner", "p2agent", "-j", "REJECT"]);
|
|
306
|
+
|
|
307
|
+
// ================= Evidence: independent verification =================
|
|
308
|
+
const obs2 = observe("reconcile-final.json");
|
|
309
|
+
const storeDir = P("st-proxy"); const find = (n) => sh("find", [storeDir, "-name", n]).stdout.trim().split("\n").filter(Boolean);
|
|
310
|
+
const receipts = find("receipts.jsonl")[0], jwk = find("public-jwk.json")[0];
|
|
311
|
+
const verBin = path.join(NM, "verifier/bin/verify.mjs");
|
|
312
|
+
let chain = { status: "BLOCKED" };
|
|
313
|
+
if (receipts && jwk) { const v = sh(NODE, [verBin, "chain", receipts, "--jwks", jwk], { timeout: 30000 }); chain = { exit: v.status, stdout: v.stdout.slice(0, 300), stderr: v.stderr.slice(0, 200) };
|
|
314
|
+
fs.writeFileSync(P("logs/verifier-chain.txt"), v.stdout + v.stderr);
|
|
315
|
+
const tampered = P("logs/receipts-tampered.jsonl"); const lines = fs.readFileSync(receipts, "utf8").trim().split("\n"); const r0 = JSON.parse(lines[0]); r0.decision = r0.decision === "ALLOW" ? "DENY" : "ALLOW"; lines[0] = JSON.stringify(r0); fs.writeFileSync(tampered, lines.join("\n") + "\n");
|
|
316
|
+
const vt = sh(NODE, [verBin, "chain", tampered, "--jwks", jwk], { timeout: 30000 }); chain.tamperedExit = vt.status; }
|
|
317
|
+
rec("EV-01", "evidence", "published verifier 1.25.0 verifies the proxy receipt chain from the real topology; tampered copy must fail", "chain valid (exit 0); tampered exit != 0", JSON.stringify(chain), chain.exit === 0 && chain.tamperedExit !== 0 ? "PASS" : (receipts ? "FAIL" : "BLOCKED"));
|
|
318
|
+
const bad = obs2.attempts.filter((a) => a.verdict.startsWith("INCONSISTENT") || a.outcomeSignatureValid === false);
|
|
319
|
+
rec("EV-02", "evidence", "executor-signed outcome records reconciled against independent observer", "every attempt consistent with destination; signatures valid; no destination branch without an attempt record", JSON.stringify({ attempts: obs2.attempts.map((a) => `${a.ref.split("/").pop()}:${a.executorReported}:${a.verdict}`), unattributed: obs2.destinationBranchesWithNoAttemptRecord }), bad.length === 0 && obs2.destinationBranchesWithNoAttemptRecord.length === 0 ? "PASS" : "FAIL");
|
|
320
|
+
const dl = destLines().filter((x) => x.method === "POST");
|
|
321
|
+
rec("EV-03", "evidence", "every destination write was made by the executor credential", "no POST by any other role", dl.map((x) => `${x.url} ${x.role} ${x.status}`).join("; "), dl.every((x) => x.role === "executor" || x.status === 401) && dl.filter((x) => x.status === 201).every((x) => x.role === "executor") ? "PASS" : "FAIL");
|
|
322
|
+
|
|
323
|
+
// ---------- write results ----------
|
|
324
|
+
for (const [src, dst] of [[P("logs/destination-requests.jsonl"), "destination-requests.jsonl"], [P("logs/connector-standin-requests.jsonl"), "connector-standin-requests.jsonl"], [P("st-auth/authorizer-log.jsonl"), "authorizer-log.jsonl"], [P("st-exec/attempts.jsonl"), "executor-attempts.jsonl"], [P("st-exec/outcomes.jsonl"), "executor-outcomes-signed.jsonl"], [P("st-exec/outcome-jwks.json"), "executor-outcome-jwks.json"], [P("st-auth/jwks.json"), "authorization-jwks.json"], [P("proxy-config.json"), "proxy-config.json"], [P("services.txt"), "services.txt"], [P("iptables-counters.txt"), "iptables-counters.txt"], [P("logs/reconcile-final.json"), "reconcile-final.json"], [P("logs/reconcile-after-crash.json"), "reconcile-after-crash.json"], [P("logs/verifier-chain.txt"), "verifier-chain.txt"], [receipts, "proxy-receipts.jsonl"], [jwk, "proxy-public-jwk.json"]]) if (src && fs.existsSync(src)) fs.writeFileSync(path.join(RESULTS, dst), fs.readFileSync(src, "utf8").replace(new RegExp(W, "g"), "<W>"));
|
|
325
|
+
for (const f of fs.readdirSync(P("st-exec/nonces"))) fs.appendFileSync(path.join(RESULTS, "burned-nonce-markers.txt"), f + "\n");
|
|
326
|
+
fs.writeFileSync(path.join(RESULTS, "versions.json"), JSON.stringify(versions, null, 1));
|
|
327
|
+
fs.writeFileSync(path.join(RESULTS, "matrix.json"), JSON.stringify(matrix, null, 1));
|
|
328
|
+
const leakFinal = sh("grep", ["-rl", "-e", EXEC_TOKEN, "-e", OBS_TOKEN, RESULTS]).stdout.trim();
|
|
329
|
+
if (leakFinal) console.log("WARNING: dummy credential found in results: " + leakFinal);
|
|
330
|
+
// ---------- teardown ----------
|
|
331
|
+
for (const u of USERS) sh("pkill", ["-9", "-u", u]);
|
|
332
|
+
await sleep(500);
|
|
333
|
+
for (const u of USERS) { sh("userdel", [u]); sh("groupdel", [u]); } sh("groupdel", ["p2appr-shared"]);
|
|
334
|
+
fs.rmSync(W, { recursive: true, force: true });
|
|
335
|
+
const c = (d) => matrix.filter((x) => x.disposition === d).length;
|
|
336
|
+
console.log(`\nPASS=${c("PASS")} FAIL=${c("FAIL")} BLOCKED=${c("BLOCKED")} OPEN=${c("OPEN")}`);
|
|
337
|
+
process.exit(c("FAIL") ? 1 : 0);
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The unprivileged MCP client (runs as the agent identity). Connects ONLY through the bridge to the trusted proxy service.
|
|
3
|
+
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
4
|
+
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
const [sock, cmd, tool, json] = process.argv.slice(2);
|
|
8
|
+
const bridge = path.join(path.dirname(fileURLToPath(import.meta.url)), "bridge-client.mjs");
|
|
9
|
+
const client = new Client({ name: "agent-under-test", version: "0.0.1" });
|
|
10
|
+
await client.connect(new StdioClientTransport({ command: process.execPath, args: [bridge, sock], env: { PATH: "/usr/bin:/bin" } }));
|
|
11
|
+
try {
|
|
12
|
+
if (cmd === "list") console.log(JSON.stringify((await client.listTools()).tools.map((t) => t.name)));
|
|
13
|
+
else {
|
|
14
|
+
const r = await client.callTool({ name: tool, arguments: JSON.parse(json ?? "{}") }, undefined, { timeout: 45000 });
|
|
15
|
+
console.log(JSON.stringify({ ok: true, isError: !!r.isError, text: r.content?.[0]?.text }));
|
|
16
|
+
}
|
|
17
|
+
} catch (e) { console.log(JSON.stringify({ ok: false, error: String(e?.message ?? e).slice(0, 300) })); }
|
|
18
|
+
await client.close(); process.exit(0);
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Copies bytes between the proxy's private approvals dir (0700, files 0600) and the approver's dir.
|
|
3
|
+
// It cannot approve anything: the proxy requires an approver-signed response over the request's exact bytes.
|
|
4
|
+
import fs from "node:fs";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
const [proxyDir, approverDir] = process.argv.slice(2);
|
|
7
|
+
const seen = new Set();
|
|
8
|
+
setInterval(() => {
|
|
9
|
+
for (const n of fs.readdirSync(proxyDir).filter((x) => x.endsWith(".request.json"))) {
|
|
10
|
+
const dst = path.join(approverDir, n);
|
|
11
|
+
if (!fs.existsSync(dst)) { try { fs.writeFileSync(dst, fs.readFileSync(path.join(proxyDir, n)), { mode: 0o640 }); } catch {} }
|
|
12
|
+
}
|
|
13
|
+
for (const n of fs.readdirSync(approverDir).filter((x) => x.endsWith(".response.json"))) {
|
|
14
|
+
const id = n.replace(/\.response\.json$/, "");
|
|
15
|
+
const src = path.join(approverDir, n);
|
|
16
|
+
if (seen.has(n) || !fs.existsSync(path.join(proxyDir, id + ".request.json"))) continue;
|
|
17
|
+
try { fs.writeFileSync(path.join(proxyDir, n), fs.readFileSync(src), { mode: 0o600 }); seen.add(n); } catch {}
|
|
18
|
+
}
|
|
19
|
+
}, 100);
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Human-approver stand-in (separate OS identity). Uses @strixgov/guard's own approveSigned (signs the exact
|
|
3
|
+
// request bytes), then submits request+signed response to the authorizer so a payload-bound token can be minted.
|
|
4
|
+
// In a real deployment a person types the passphrase at a TTY; here a 0400 file stands in. Test approver only.
|
|
5
|
+
import fs from "node:fs";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { approveSigned, createApproverKey, readApproverPublic } from "@strixgov/guard";
|
|
8
|
+
import { call } from "./lib.mjs";
|
|
9
|
+
const [cmd, home, ...rest] = process.argv.slice(2);
|
|
10
|
+
process.env.STRIX_GUARD_HOME = home;
|
|
11
|
+
const passFile = path.join(home, "passphrase");
|
|
12
|
+
if (cmd === "init") {
|
|
13
|
+
const pub = await createApproverKey({ passphrase: fs.readFileSync(passFile, "utf8").trim(), label: "synthetic-approver", force: true });
|
|
14
|
+
fs.writeFileSync(path.join(home, "approver-public.json"), JSON.stringify(pub), { mode: 0o644 });
|
|
15
|
+
} else if (cmd === "approve") {
|
|
16
|
+
const [requestId, registerSock] = rest;
|
|
17
|
+
const reqPath = path.join(home, "approvals", `${requestId}.request.json`);
|
|
18
|
+
const requestText = fs.readFileSync(reqPath, "utf8");
|
|
19
|
+
const r = await approveSigned(requestId, { io: { isTty: true, confirm: async () => true, secret: async () => fs.readFileSync(passFile, "utf8").trim(), print: () => {} } });
|
|
20
|
+
fs.chmodSync(r.responsePath, 0o640);
|
|
21
|
+
const response = JSON.parse(fs.readFileSync(r.responsePath, "utf8"));
|
|
22
|
+
const reg = await call(registerSock, { op: "register", requestText, response });
|
|
23
|
+
console.log(JSON.stringify({ requestId, signed: true, registered: reg }));
|
|
24
|
+
} else if (cmd === "pending") {
|
|
25
|
+
const dir = path.join(home, "approvals");
|
|
26
|
+
console.log(fs.readdirSync(dir).filter((n) => n.endsWith(".request.json")).map((n) => n.replace(".request.json", "")).join("\n"));
|
|
27
|
+
} else { console.error("usage: init|approve|pending"); process.exit(2); }
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// TEST-KEY authorization service (stands in for the Strix kernel; NOT a production minter).
|
|
3
|
+
// Mints an execution_authorization_v1 token only from an approver-signed approval of the EXACT request,
|
|
4
|
+
// pinned to the Guard approver public key. The token binds payloadHash = SHA-256(SCJ v1(args)).
|
|
5
|
+
// Tokens are claimed once (atomic rename); an approval request id can be registered once.
|
|
6
|
+
import fs from "node:fs";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import crypto from "node:crypto";
|
|
9
|
+
import { serve, payloadHash, sha256hex, signCanonical, jwkPublic, pubFromX, canonicalizeJSON } from "./lib.mjs";
|
|
10
|
+
|
|
11
|
+
const [registerSock, claimSock, stateDir, approverPubFile, tenantId, environment] = process.argv.slice(2);
|
|
12
|
+
const KID = "mode3-authz-test-1";
|
|
13
|
+
for (const d of ["unclaimed", "claimed", "registered"]) fs.mkdirSync(path.join(stateDir, d), { recursive: true, mode: 0o700 });
|
|
14
|
+
const keyFile = path.join(stateDir, "private.pem");
|
|
15
|
+
let priv;
|
|
16
|
+
if (fs.existsSync(keyFile)) priv = crypto.createPrivateKey(fs.readFileSync(keyFile));
|
|
17
|
+
else {
|
|
18
|
+
const kp = crypto.generateKeyPairSync("ed25519");
|
|
19
|
+
fs.writeFileSync(keyFile, kp.privateKey.export({ format: "pem", type: "pkcs8" }), { mode: 0o400 });
|
|
20
|
+
priv = kp.privateKey;
|
|
21
|
+
}
|
|
22
|
+
const pub = crypto.createPublicKey(priv);
|
|
23
|
+
fs.writeFileSync(path.join(stateDir, "jwks.json"), JSON.stringify({ keys: [jwkPublic(pub, KID)] }, null, 2), { mode: 0o644 });
|
|
24
|
+
const approver = JSON.parse(fs.readFileSync(approverPubFile, "utf8"));
|
|
25
|
+
const approverKey = pubFromX(approver.publicKey);
|
|
26
|
+
const log = (o) => fs.appendFileSync(path.join(stateDir, "authorizer-log.jsonl"), JSON.stringify({ t: new Date().toISOString(), ...o }) + "\n");
|
|
27
|
+
|
|
28
|
+
// Mirrors @strixgov/guard approvalPreimage (strix-guard-approval/v1).
|
|
29
|
+
const preimage = ({ requestId, requestSha256, approved, decidedAt, kid }) =>
|
|
30
|
+
["strix-guard-approval/v1", `request:${requestId}`, `requestSha256:${requestSha256}`, `approved:${approved === true ? "true" : "false"}`, `decidedAt:${decidedAt}`, `kid:${kid}`].join("\n");
|
|
31
|
+
|
|
32
|
+
serve(registerSock, async (m) => {
|
|
33
|
+
if (m.op !== "register") return { ok: false, error: "UNKNOWN_OP" };
|
|
34
|
+
const { requestText, response } = m;
|
|
35
|
+
let req;
|
|
36
|
+
try { req = JSON.parse(requestText); } catch { return { ok: false, error: "REQUEST_NOT_JSON" }; }
|
|
37
|
+
if (!response || response.approved !== true) return { ok: false, error: "NOT_APPROVED" };
|
|
38
|
+
if (response.kid !== approver.kid) return { ok: false, error: "UNKNOWN_APPROVER_KEY" };
|
|
39
|
+
if (response.requestSha256 !== sha256hex(requestText)) return { ok: false, error: "REQUEST_HASH_MISMATCH" };
|
|
40
|
+
const ok = crypto.verify(null, Buffer.from(preimage({ requestId: req.requestId, requestSha256: response.requestSha256, approved: true, decidedAt: response.decidedAt, kid: response.kid }), "utf8"), approverKey, Buffer.from(response.signature ?? "", "base64url"));
|
|
41
|
+
if (!ok) { log({ ev: "register-refused", reason: "BAD_SIGNATURE", requestId: req.requestId }); return { ok: false, error: "BAD_SIGNATURE" }; }
|
|
42
|
+
if (Date.now() - Date.parse(response.decidedAt) > 5 * 60_000) return { ok: false, error: "APPROVAL_STALE" };
|
|
43
|
+
try { fs.writeFileSync(path.join(stateDir, "registered", req.requestId), "", { flag: "wx" }); }
|
|
44
|
+
catch { log({ ev: "register-refused", reason: "APPROVAL_ALREADY_USED", requestId: req.requestId }); return { ok: false, error: "APPROVAL_ALREADY_USED" }; }
|
|
45
|
+
const args = req.invocation?.args ?? {};
|
|
46
|
+
const now = Date.now();
|
|
47
|
+
const payload = {
|
|
48
|
+
schemaVersion: 1, authorizationId: "authz_" + crypto.randomBytes(8).toString("hex"), decisionId: "dec_" + req.requestId,
|
|
49
|
+
capabilityId: req.capability.id, actorId: "agent:controlled-launcher-demo", actorClass: "agent",
|
|
50
|
+
payloadHash: payloadHash(args), tenantId, environment, nonce: crypto.randomBytes(16).toString("hex"),
|
|
51
|
+
issuedAt: new Date(now).toISOString().replace(/\.\d+Z$/, "Z"), expiresAt: new Date(now + Number(process.env.AUTHZ_TTL_MS ?? 60000)).toISOString().replace(/\.\d+Z$/, "Z"),
|
|
52
|
+
};
|
|
53
|
+
const token = { ...payload, signingKeyId: KID, signature: signCanonical(payload, priv) };
|
|
54
|
+
const file = path.join(stateDir, "unclaimed", `${payload.payloadHash.slice(7)}.${payload.authorizationId}.json`);
|
|
55
|
+
fs.writeFileSync(file, JSON.stringify(token), { mode: 0o600 });
|
|
56
|
+
log({ ev: "minted", requestId: req.requestId, authorizationId: payload.authorizationId, payloadHash: payload.payloadHash, capabilityId: payload.capabilityId });
|
|
57
|
+
return { ok: true, authorizationId: payload.authorizationId, payloadHash: payload.payloadHash };
|
|
58
|
+
}, 0o660);
|
|
59
|
+
|
|
60
|
+
serve(claimSock, async (m) => {
|
|
61
|
+
if (m.op !== "claim" || typeof m.payloadHash !== "string" || !/^sha256:[0-9a-f]{64}$/.test(m.payloadHash)) return { ok: false, error: "BAD_CLAIM" };
|
|
62
|
+
const prefix = m.payloadHash.slice(7) + ".";
|
|
63
|
+
for (const name of fs.readdirSync(path.join(stateDir, "unclaimed")).filter((n) => n.startsWith(prefix))) {
|
|
64
|
+
try { fs.renameSync(path.join(stateDir, "unclaimed", name), path.join(stateDir, "claimed", name)); }
|
|
65
|
+
catch { continue; } // lost the race: another claimant took it
|
|
66
|
+
const token = JSON.parse(fs.readFileSync(path.join(stateDir, "claimed", name), "utf8"));
|
|
67
|
+
if (m.capabilityId && token.capabilityId !== m.capabilityId) { log({ ev: "claim-capability-mismatch", name }); continue; }
|
|
68
|
+
log({ ev: "claimed", authorizationId: token.authorizationId, payloadHash: m.payloadHash });
|
|
69
|
+
return { ok: true, token };
|
|
70
|
+
}
|
|
71
|
+
log({ ev: "claim-none", payloadHash: m.payloadHash });
|
|
72
|
+
return { ok: false, error: "NO_AUTHORIZATION" };
|
|
73
|
+
}, 0o660);
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// What the unprivileged MCP client launches as its "server command". It is only a stdio<->socket pipe to the
|
|
3
|
+
// trusted proxy service. It carries no configuration and no credentials.
|
|
4
|
+
import net from "node:net";
|
|
5
|
+
const c = net.connect(process.argv[2]);
|
|
6
|
+
process.stdin.pipe(c); c.pipe(process.stdout);
|
|
7
|
+
c.on("error", (e) => { process.stderr.write("bridge: " + e.code + "\n"); process.exit(1); });
|
|
8
|
+
c.on("close", () => process.exit(0));
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// Synthetic GitHub-shaped destination. Logs EVERY request independently of any proxy.
|
|
2
|
+
import http from "node:http"; import fs from "node:fs";
|
|
3
|
+
const [port, log] = process.argv.slice(2); const execTok = process.env.DEST_EXEC, obsTok = process.env.DEST_OBS;
|
|
4
|
+
const branches = new Set(["main"]);
|
|
5
|
+
http.createServer((req, res) => {
|
|
6
|
+
let body = ""; req.on("data", d => body += d); req.on("end", () => {
|
|
7
|
+
const auth = (req.headers.authorization || "").replace(/^Bearer /, "");
|
|
8
|
+
const role = auth === execTok ? "executor" : auth === obsTok ? "observer" : auth ? "unknown-token" : "none";
|
|
9
|
+
let status = 401, out = { error: "unauthorized" };
|
|
10
|
+
if (req.method === "POST" && req.url === "/repos/synthetic/fixture/git/refs" && role === "executor") {
|
|
11
|
+
const ref = JSON.parse(body || "{}").ref; branches.add(ref); status = 201; out = { created: ref };
|
|
12
|
+
} else if (req.method === "GET" && req.url === "/repos/synthetic/fixture/branches" && (role === "observer" || role === "executor")) {
|
|
13
|
+
status = 200; out = { branches: [...branches] };
|
|
14
|
+
} else if (role !== "none" && role !== "unknown-token") { status = 403; out = { error: "role not permitted" }; }
|
|
15
|
+
fs.appendFileSync(log, JSON.stringify({ t: new Date().toISOString(), method: req.method, url: req.url, role, status, body: body.slice(0, 200) }) + "\n");
|
|
16
|
+
res.writeHead(status, { "content-type": "application/json" }); res.end(JSON.stringify(out));
|
|
17
|
+
});
|
|
18
|
+
}).listen(+port, "127.0.0.1");
|