@strixgov/mcp-proxy 0.2.4 → 0.3.0

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.
Files changed (50) hide show
  1. package/CHANGELOG.md +92 -1
  2. package/README.md +277 -38
  3. package/bin/strix-mcp-proxy.mjs +100 -5
  4. package/examples/controlled-launcher/README.md +33 -0
  5. package/examples/controlled-launcher/acceptance.mjs +337 -0
  6. package/examples/controlled-launcher/agent-client.mjs +18 -0
  7. package/examples/controlled-launcher/approval-relay.mjs +19 -0
  8. package/examples/controlled-launcher/approver.mjs +27 -0
  9. package/examples/controlled-launcher/authorizer.mjs +73 -0
  10. package/examples/controlled-launcher/bridge-client.mjs +8 -0
  11. package/examples/controlled-launcher/destination.mjs +18 -0
  12. package/examples/controlled-launcher/executor.mjs +74 -0
  13. package/examples/controlled-launcher/kernel-authority/acceptance.mjs +627 -0
  14. package/examples/controlled-launcher/kernel-authority/broker.mjs +83 -0
  15. package/examples/controlled-launcher/kernel-authority/derive.mjs +12 -0
  16. package/examples/controlled-launcher/kernel-authority/executor.mjs +105 -0
  17. package/examples/controlled-launcher/kernel-authority/reconcile.mjs +43 -0
  18. package/examples/controlled-launcher/kernel-authority/shim.mjs +38 -0
  19. package/examples/controlled-launcher/kernel-authority/signing-provider.mjs +137 -0
  20. package/examples/controlled-launcher/kernel-authority/strix-approver.mjs +73 -0
  21. package/examples/controlled-launcher/lib.mjs +63 -0
  22. package/examples/controlled-launcher/make-config.mjs +16 -0
  23. package/examples/controlled-launcher/proxy-host.mjs +19 -0
  24. package/examples/controlled-launcher/reconcile.mjs +30 -0
  25. package/examples/controlled-launcher/shim.mjs +32 -0
  26. package/examples/github-reference/README.md +1 -1
  27. package/examples/github-reference/acceptance.mjs +10 -3
  28. package/examples/github-reference/claims-matrix.md +3 -3
  29. package/examples/github-reference/package-lock.json +48 -44
  30. package/examples/github-reference/package.json +4 -4
  31. package/examples/github-reference/reuse-inventory.md +4 -4
  32. package/examples/synthetic-server/proxy-config.json +16 -0
  33. package/examples/synthetic-server/quickstart.mjs +98 -0
  34. package/examples/synthetic-server/server.mjs +54 -0
  35. package/package.json +5 -4
  36. package/src/config.mjs +152 -2
  37. package/src/content-guard.mjs +432 -0
  38. package/src/http-upstream.mjs +431 -0
  39. package/src/index.mjs +11 -2
  40. package/src/proxy.mjs +241 -33
  41. package/src/tool-guard.mjs +183 -0
  42. package/src/types.d.ts +83 -1
  43. package/test/content-guard-hardening.test.mjs +159 -0
  44. package/test/content-guard.test.mjs +387 -0
  45. package/test/http-upstream-config.test.mjs +115 -0
  46. package/test/http-upstream-e2e.test.mjs +279 -0
  47. package/test/http-upstream.test.mjs +304 -0
  48. package/test/synthetic-quickstart.test.mjs +44 -0
  49. package/test/tool-guard.test.mjs +243 -0
  50. package/test/validate-cli.test.mjs +171 -0
@@ -17,7 +17,7 @@
17
17
  * Audit events print to stderr so the MCP stdio channel on stdout stays clean.
18
18
  */
19
19
 
20
- import { startProxy, loadConfig, resolveCapabilities } from "../src/index.mjs";
20
+ import { startProxy, loadConfig, resolveCapabilities, describeConfig, unknownConfigKeys } from "../src/index.mjs";
21
21
 
22
22
  const argv = process.argv.slice(2);
23
23
  if (argv.includes("--help") || argv.includes("-h")) {
@@ -30,6 +30,30 @@ if (argv.includes("--version") || argv.includes("-v")) {
30
30
  process.exit(0);
31
31
  }
32
32
 
33
+ if (argv.includes("--validate")) {
34
+ // Dry run: read and check the config, resolve the capability pack, print what
35
+ // it would do, and exit. Connects to nothing, spawns nothing, prints no
36
+ // credential. Exit 0 = valid, 1 = invalid.
37
+ const configPath = argv[argv.indexOf("--config") + 1];
38
+ if (!argv.includes("--config") || !configPath || configPath.startsWith("--")) {
39
+ console.error("strix-mcp-proxy --validate needs --config <path>");
40
+ process.exit(1);
41
+ }
42
+ try {
43
+ const cfg = await loadConfig(configPath);
44
+ const capabilities = await resolveCapabilities(cfg.capabilities);
45
+ const report = describeConfig(cfg, capabilities);
46
+ process.stdout.write(JSON.stringify({ valid: true, ...report }, null, 2) + "\n");
47
+ process.exitCode = 0;
48
+ } catch (err) {
49
+ process.stdout.write(JSON.stringify({ valid: false, error: err.message }, null, 2) + "\n");
50
+ process.exitCode = 1;
51
+ }
52
+ // Let the stream drain before the process ends: process.exit() can cut piped output short.
53
+ await new Promise((resolve) => process.stdout.write("", resolve));
54
+ process.exit(process.exitCode ?? 0);
55
+ }
56
+
33
57
  try {
34
58
  const opts = await parseArgs(argv);
35
59
  const handle = await startProxy({
@@ -79,6 +103,9 @@ async function parseArgs(argv) {
79
103
  const configPath = flag("--config");
80
104
  if (configPath) {
81
105
  const cfg = await loadConfig(configPath);
106
+ for (const key of unknownConfigKeys(cfg)) {
107
+ console.error(`[strix-proxy] warning: unknown config key '${key}' is ignored (typo?)`);
108
+ }
82
109
  return {
83
110
  serverId: cfg.serverId,
84
111
  upstream: cfg.upstream,
@@ -88,14 +115,44 @@ async function parseArgs(argv) {
88
115
  approval: cfg.approval,
89
116
  storagePath: cfg.storagePath,
90
117
  keyPath: cfg.keyPath,
118
+ toolPinning: cfg.toolPinning,
119
+ hideDeniedTools: cfg.hideDeniedTools,
120
+ rateLimits: cfg.rateLimits,
121
+ // Command-line scanning flags override the file, the same way --repin-tools does.
122
+ secretScanning: flag("--secret-scanning-args") || flag("--secret-scanning-results")
123
+ ? { ...(cfg.secretScanning || {}), ...(flag("--secret-scanning-args") ? { arguments: flag("--secret-scanning-args") } : {}), ...(flag("--secret-scanning-results") ? { results: flag("--secret-scanning-results") } : {}) }
124
+ : cfg.secretScanning,
125
+ argumentRules: cfg.argumentRules,
126
+ auditLog: cfg.auditLog,
127
+ // --repin-tools on the command line wins, so an operator can accept a
128
+ // changed tool without editing the config file.
129
+ repinTools: argv.includes("--repin-tools") || cfg.repinTools === true,
91
130
  };
92
131
  }
93
132
 
94
133
  const upstreamCommand = flag("--upstream-command");
95
- if (!upstreamCommand) {
96
- throw new Error("missing --config or --upstream-command (run with --help)");
134
+ const upstreamUrl = flag("--upstream-url");
135
+ if (!upstreamCommand && !upstreamUrl) {
136
+ throw new Error("missing --config or --upstream-command (or --upstream-url) (run with --help)");
137
+ }
138
+ if (upstreamCommand && upstreamUrl) {
139
+ throw new Error("--upstream-command and --upstream-url are mutually exclusive");
97
140
  }
98
141
  const upstreamArgs = flagAll("--upstream-arg");
142
+ // --upstream-header-env "Authorization=NOTION_TOKEN" reads the header's
143
+ // value from the environment variable; the value never appears in argv.
144
+ const upstreamHeaders = {};
145
+ for (const spec of flagAll("--upstream-header-env")) {
146
+ const eq = spec.indexOf("=");
147
+ if (eq <= 0 || eq === spec.length - 1) {
148
+ throw new Error(`--upstream-header-env expects NAME=ENV_VAR, got '${spec}'`);
149
+ }
150
+ const name = spec.slice(0, eq);
151
+ const envVar = spec.slice(eq + 1);
152
+ upstreamHeaders[name] = /^authorization$/i.test(name)
153
+ ? { fromEnv: envVar, prefix: "Bearer " }
154
+ : { fromEnv: envVar };
155
+ }
99
156
  const serverId = flag("--server-id") ?? "proxy";
100
157
  const capabilitiesPath = flag("--capabilities");
101
158
  const policyDefault = flag("--policy-default") ?? "DENY";
@@ -109,7 +166,9 @@ async function parseArgs(argv) {
109
166
 
110
167
  return {
111
168
  serverId,
112
- upstream: { command: upstreamCommand, args: upstreamArgs },
169
+ upstream: upstreamUrl
170
+ ? { url: upstreamUrl, headers: upstreamHeaders }
171
+ : { command: upstreamCommand, args: upstreamArgs },
113
172
  capabilities: capabilitiesPath ? await resolveCapabilities(capabilitiesPath) : undefined,
114
173
  policy: {
115
174
  riskOverrides: Object.keys(riskOverrides).length > 0 ? riskOverrides : undefined,
@@ -117,6 +176,12 @@ async function parseArgs(argv) {
117
176
  },
118
177
  approval: { enabled: approvalEnabled },
119
178
  storagePath,
179
+ toolPinning: flag("--tool-pinning") ?? undefined,
180
+ hideDeniedTools: argv.includes("--hide-denied-tools"),
181
+ repinTools: argv.includes("--repin-tools"),
182
+ secretScanning: flag("--secret-scanning-args") || flag("--secret-scanning-results")
183
+ ? { arguments: flag("--secret-scanning-args"), results: flag("--secret-scanning-results") }
184
+ : undefined,
120
185
  };
121
186
  }
122
187
 
@@ -126,6 +191,7 @@ function printHelp() {
126
191
  USAGE
127
192
  strix-mcp-proxy --config <path>
128
193
  strix-mcp-proxy --upstream-command <cmd> [--upstream-arg <a> ...] [other flags]
194
+ strix-mcp-proxy --upstream-url <https-url> [--upstream-header-env H=VAR ...] [other flags]
129
195
 
130
196
  CONFIG-FILE MODE
131
197
  --config <path> Path to a JSON config file (see README for shape)
@@ -133,6 +199,13 @@ CONFIG-FILE MODE
133
199
  FLAG MODE
134
200
  --upstream-command <cmd> Command to spawn the upstream MCP server (e.g. "npx")
135
201
  --upstream-arg <arg> One arg for the upstream command (repeatable)
202
+ --upstream-url <url> Remote MCP server reached over Streamable HTTP
203
+ (https only; plain http only for a loopback host)
204
+ --upstream-header-env H=VAR
205
+ Send header H with the value of environment
206
+ variable VAR (repeatable). For Authorization the
207
+ value is sent as "Bearer <VAR>". Values never
208
+ appear in argv, receipts, logs or errors.
136
209
  --server-id <id> Namespace prefix for capability ids (default: "proxy")
137
210
  --capabilities <pkg> Companion-pack import path
138
211
  (e.g. @strixgov/capabilities-mcp-common/notion)
@@ -145,6 +218,27 @@ FLAG MODE
145
218
  --approval-enabled Enable the approval gate (requires custom prompt)
146
219
  --storage-path <dir> Persist authorization receipts and execution outcomes
147
220
  (default: ~/.strix-mcp-proxy/<serverId>)
221
+ --tool-pinning <mode> block (default) | warn | off. Pins each tool's
222
+ definition on first sight; a later change is
223
+ refused (block) or reported (warn)
224
+ --repin-tools Accept the upstream's current tool definitions
225
+ as the new pins (works with --config too)
226
+ --hide-denied-tools Leave tools that policy always denies out of
227
+ tools/list
228
+ --secret-scanning-args <m>
229
+ block (default) | warn | off. Refuse (block) or
230
+ report a call whose arguments contain a
231
+ credential-shaped string
232
+ --secret-scanning-results <m>
233
+ warn (default) | redact | off. Report, or replace
234
+ with [REDACTED:<kind>], credential-shaped strings
235
+ in a tool's result before the client sees it
236
+
237
+ CHECK A CONFIG
238
+ --validate --config <path>
239
+ Read and check the config, resolve the capability
240
+ pack, print what it would do (no credentials) and
241
+ exit 0 (valid) or 1 (invalid). Connects to nothing.
148
242
 
149
243
  TRUSTED WORKLOAD IDENTITY
150
244
  STRIX_TRUSTED_ACTOR_ID Fixed authenticated workload identity
@@ -157,7 +251,8 @@ GENERAL
157
251
  --help, -h Show this help
158
252
  --version, -v Show proxy version
159
253
 
160
- The proxy speaks MCP over stdio toward its consumer. NVIDIA OO Agents,
254
+ The proxy speaks MCP over stdio toward its consumer. Its upstream can be a
255
+ child process (stdio) or a remote server (Streamable HTTP). NVIDIA OO Agents,
161
256
  Claude Desktop, mcp-cli, and other .mcp.json clients can spawn this binary
162
257
  in place of the upstream MCP server.
163
258
  `);
@@ -0,0 +1,33 @@
1
+ # Controlled launcher: separate-identity reference topology for the published MCP proxy
2
+
3
+ Reference code under review. Not a product, not published, not Mode 3 complete. Synthetic destination, dummy credentials, localhost only. Run: `sudo node acceptance.mjs <dir-of-npm-pack-tarballs> <results-dir>` (root is required to create throwaway OS users; they are removed at the end).
4
+
5
+ ## Architecture and trust boundaries
6
+
7
+ ```
8
+ AGENT identity (p2agent) TRUSTED PROXY SERVICE (p2proxy) CREDENTIAL HOLDER (p2exec) DESTINATION (p2dest)
9
+ MCP client proxy-host.mjs executor.mjs synthetic GitHub-shaped API
10
+ | stdio per connection spawns the PUBLISHED holds the ONLY executor credential logs EVERY request itself
11
+ v @strixgov/mcp-proxy 0.2.4 with a validates execution_authorization_v1
12
+ bridge-client.mjs --unix socket--> root-owned config (client controls (published validator 0.1.0): ^
13
+ (bytes only) bytes only, not exe/config/env) signature, expiry, tenant/env/actor, | Bearer = executor credential
14
+ | Guard-signed approval gate EXACT payloadHash, atomic nonce burn |
15
+ v (approver key pinned) write-ahead attempt log (fsync) |
16
+ shim.mjs (credential-free upstream) signs outcome records (test key) ------+
17
+ | claim token for exact payload
18
+ v OBSERVER (p2obs): read-only credential,
19
+ APPROVER stand-in (p2approver) --signs exact request bytes--> AUTHORIZER (p2auth) reconciles executor-reported outcomes
20
+ (Guard approveSigned) registers approval; mints payload-bound token against destination state
21
+ with a TEST key; claim = atomic rename (once)
22
+ ```
23
+ Identities: p2agent (untrusted), p2proxy (trusted service, holds no destination credential and no signing key for tokens), p2exec (sole holder of the destination credential), p2auth (holds the TEST token-signing key), p2approver (holds the approver key), p2dest, p2obs. Sockets and directories are permissioned so each arrow above is the only path; the agent has write/search access to nothing but its own bridge socket.
24
+
25
+ Trust rules: the executor trusts neither the shim nor the proxy (the token is checked at the executor). The authorizer trusts only the pinned approver public key. The approval relay copies bytes only; it cannot approve (signature over exact request bytes is required). Credentials are never passed to the proxy or the agent.
26
+
27
+ ## What is the "narrow adapter"
28
+
29
+ The published proxy has no token interface. Instead of modifying it or substituting a proxy, three small reviewable pieces sit around it: `shim.mjs` (its upstream), `authorizer.mjs` (token mint from a signed approval of the exact request) and `executor.mjs` (validates). The authorizer is a TEST-KEY stand-in for the Strix kernel: it is not production custody and not a production minter.
30
+
31
+ ## Results
32
+
33
+ See `docs/evidence/mcp-phase2-reference-2026-11-22/controlled-launcher/` (matrix.json, receipts, outcomes, observer reconciliations, counters, versions) and the readiness report there.
@@ -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);