@strixgov/mcp-proxy 0.2.4 → 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.
Files changed (35) hide show
  1. package/CHANGELOG.md +24 -1
  2. package/README.md +75 -25
  3. package/examples/controlled-launcher/README.md +33 -0
  4. package/examples/controlled-launcher/acceptance.mjs +337 -0
  5. package/examples/controlled-launcher/agent-client.mjs +18 -0
  6. package/examples/controlled-launcher/approval-relay.mjs +19 -0
  7. package/examples/controlled-launcher/approver.mjs +27 -0
  8. package/examples/controlled-launcher/authorizer.mjs +73 -0
  9. package/examples/controlled-launcher/bridge-client.mjs +8 -0
  10. package/examples/controlled-launcher/destination.mjs +18 -0
  11. package/examples/controlled-launcher/executor.mjs +74 -0
  12. package/examples/controlled-launcher/kernel-authority/acceptance.mjs +627 -0
  13. package/examples/controlled-launcher/kernel-authority/broker.mjs +83 -0
  14. package/examples/controlled-launcher/kernel-authority/derive.mjs +12 -0
  15. package/examples/controlled-launcher/kernel-authority/executor.mjs +105 -0
  16. package/examples/controlled-launcher/kernel-authority/reconcile.mjs +43 -0
  17. package/examples/controlled-launcher/kernel-authority/shim.mjs +38 -0
  18. package/examples/controlled-launcher/kernel-authority/signing-provider.mjs +137 -0
  19. package/examples/controlled-launcher/kernel-authority/strix-approver.mjs +73 -0
  20. package/examples/controlled-launcher/lib.mjs +63 -0
  21. package/examples/controlled-launcher/make-config.mjs +16 -0
  22. package/examples/controlled-launcher/proxy-host.mjs +19 -0
  23. package/examples/controlled-launcher/reconcile.mjs +30 -0
  24. package/examples/controlled-launcher/shim.mjs +32 -0
  25. package/examples/github-reference/README.md +1 -1
  26. package/examples/github-reference/acceptance.mjs +10 -3
  27. package/examples/github-reference/claims-matrix.md +3 -3
  28. package/examples/github-reference/package-lock.json +48 -44
  29. package/examples/github-reference/package.json +4 -4
  30. package/examples/github-reference/reuse-inventory.md +4 -4
  31. package/examples/synthetic-server/proxy-config.json +16 -0
  32. package/examples/synthetic-server/quickstart.mjs +98 -0
  33. package/examples/synthetic-server/server.mjs +54 -0
  34. package/package.json +5 -4
  35. package/test/synthetic-quickstart.test.mjs +44 -0
@@ -0,0 +1,627 @@
1
+ #!/usr/bin/env node
2
+ // Controlled-launcher acceptance, KERNEL-AUTHORITY edition (root required; throwaway OS users; DUMMY credentials; localhost).
3
+ // Authority is issued, bound and consumed by the REAL Strix authority route handlers (dev key, real Postgres),
4
+ // reached through the PUBLISHED @strixgov/execution-authority SDK. No stand-in authorizer.
5
+ // usage: KERNEL_CWD=<apps/strix-console> KERNEL_DATABASE_URL=<strix_app url> node acceptance.mjs <tarball-dir> <results-dir>
6
+ // <tarball-dir> holds the published tarballs (npm pack). Nothing from the repository source is executed except
7
+ // the small reference scripts in this directory (shim/executor/authorizer/...), which are the code under review.
8
+ import { execFileSync, spawn, spawnSync } from "node:child_process";
9
+ import fs from "node:fs";
10
+ import path from "node:path";
11
+ import os from "node:os";
12
+ import crypto from "node:crypto";
13
+ import { fileURLToPath, pathToFileURL } from "node:url";
14
+
15
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
16
+ const PARENT = path.resolve(HERE, "..");
17
+ const KERNEL_CWD = process.env.KERNEL_CWD, KERNEL_DB = process.env.KERNEL_DATABASE_URL;
18
+ if (!KERNEL_CWD || !KERNEL_DB) { console.error("KERNEL_CWD and KERNEL_DATABASE_URL are required"); process.exit(2); }
19
+ const [TARBALLS, RESULTS] = [path.resolve(process.argv[2]), path.resolve(process.argv[3])];
20
+ if (process.getuid() !== 0) { console.error("must run as root"); process.exit(2); }
21
+ fs.mkdirSync(RESULTS, { recursive: true });
22
+ const W = fs.mkdtempSync("/tmp/p2ctl."); fs.chmodSync(W, 0o755);
23
+ const NODE = process.execPath;
24
+ const USERS = ["p2agent", "p2proxy", "p2exec", "p2auth", "p2approver", "p2dest", "p2obs", "p2sign", "p2kernel", "p2apr1", "p2apr2", "p2apr3"];
25
+ const APRS = [{ name: "alice", user: "p2apr1" }, { name: "bob", user: "p2apr2" }, { name: "carol", user: "p2apr3" }]; // Strix approvers: three separate OS identities, each with its OWN key
26
+ const matrix = [];
27
+ const rec = (id, area, route, expected, actual, disposition) => {
28
+ matrix.push({ id, area, route, expected, actual: String(actual).replace(new RegExp(W, "g"), "<W>").slice(0, 400), disposition });
29
+ console.log(`${disposition.padEnd(7)} ${id} ${route}`); if (disposition === "FAIL" || disposition === "BLOCKED") console.log(" actual: " + matrix.at(-1).actual.slice(0, 300));
30
+ };
31
+ 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 });
32
+ const CLOSE = 'for i in $(seq 3 255); do eval "exec $i>&-"; done; exec "$@"';
33
+ const asArgs = (u, argv, { groups = true, env = {} } = {}) =>
34
+ ["--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];
35
+ const as = (u, argv, o = {}) => sh("setpriv", asArgs(u, argv, o), o);
36
+ const bg = (u, argv, logName, o = {}) => {
37
+ const out = fs.openSync(path.join(W, "logs", logName), "a");
38
+ const p = spawn("setpriv", asArgs(u, argv, o), { stdio: ["ignore", out, out], detached: true });
39
+ p.unref(); return p;
40
+ };
41
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
42
+ const pid = (u, pat) => sh("pgrep", ["-u", u, "-f", pat]).stdout.trim().split("\n").filter(Boolean)[0];
43
+ const j = (s) => { try { return JSON.parse(s); } catch { return null; } };
44
+ 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); };
45
+ const P = (d) => path.join(W, d);
46
+
47
+ // ---------- setup: identities, groups, directories ----------
48
+ for (const g of ["p2appr-shared", "p2signc"]) if (sh("getent", ["group", g]).status !== 0) sh("groupadd", [g]);
49
+ 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); } }
50
+ sh("usermod", ["-aG", "p2signc", "p2kernel"]); sh("usermod", ["-aG", "p2signc", "p2sign"]); // signing-socket clients: exactly the kernel (and the provider itself)
51
+ sh("usermod", ["-aG", "p2appr-shared", "p2approver"]); sh("usermod", ["-aG", "p2appr-shared", "p2proxy"]);
52
+ mk("logs", null, 0o755); mk("bin", null, 0o755);
53
+ mk("sock-agent", "p2proxy:p2agent", 0o2710); mk("sock-exec", "p2exec:p2proxy", 0o2750); mk("sock-claim", "p2auth:p2proxy", 0o2750); mk("sock-reg", "p2auth:p2approver", 0o2750);
54
+ mk("st-exec", "p2exec", 0o755); mk("st-auth", "p2auth", 0o755); mk("st-proxy", "p2proxy", 0o755); mk("proxy-approvals", "p2proxy", 0o700);
55
+ mk("kernel-home", "p2kernel", 0o700); mk("sign-keys", "p2sign", 0o700); mk("sign-keys2", "p2sign", 0o700); mk("sock-sign", "p2sign", 0o711);
56
+ mk("cred-exec", "p2exec", 0o700); mk("cred-obs", "p2obs", 0o700); mk("approver-home", "p2approver:p2appr-shared", 0o710);
57
+ mk("approver-home/approvals", "p2approver:p2appr-shared", 0o2770); mk("work-agent", "p2agent", 0o755);
58
+ sh("chmod", ["777", P("logs")]);
59
+ const SVC_TOKEN = "DUMMY-SVC-" + crypto.randomBytes(16).toString("hex"), REQ_TOKEN = "DUMMY-REQ-" + crypto.randomBytes(16).toString("hex"), RED_TOKEN = "DUMMY-RED-" + crypto.randomBytes(16).toString("hex"), APPR_SECRET = "DUMMY-APPR-" + crypto.randomBytes(8).toString("hex");
60
+ const EXEC_TOKEN = "DUMMY-EXEC-" + crypto.randomBytes(8).toString("hex"), OBS_TOKEN = "DUMMY-OBS-" + crypto.randomBytes(8).toString("hex");
61
+ fs.writeFileSync(P("cred-exec/token"), EXEC_TOKEN, { mode: 0o400 }); sh("chown", ["p2exec", P("cred-exec/token")]);
62
+ fs.writeFileSync(P("cred-obs/token"), OBS_TOKEN, { mode: 0o400 }); sh("chown", ["p2obs", P("cred-obs/token")]);
63
+ fs.writeFileSync(P("approver-home/passphrase"), "synthetic-approver-passphrase-" + crypto.randomBytes(4).toString("hex"), { mode: 0o400 }); sh("chown", ["p2approver", P("approver-home/passphrase")]);
64
+
65
+ // ---------- install the PUBLISHED packages into a root-owned consumer ----------
66
+ const C = P("consumer"); fs.mkdirSync(C); fs.writeFileSync(path.join(C, "package.json"), '{"name":"consumer","private":true,"type":"module"}');
67
+ const tgz = fs.readdirSync(TARBALLS).filter((f) => f.endsWith(".tgz")).map((f) => path.join(TARBALLS, f));
68
+ const inst = sh("npm", ["install", "--ignore-scripts", "--no-audit", "--no-fund", ...tgz], { timeout: 180000, cwd: C, env: { ...process.env } });
69
+ if (inst.status !== 0) { console.error(inst.stderr); process.exit(3); }
70
+ const L = path.join(C, "launcher"); fs.mkdirSync(L);
71
+ for (const f of fs.readdirSync(PARENT).filter((f) => f.endsWith(".mjs") && f !== "acceptance.mjs")) fs.copyFileSync(path.join(PARENT, f), path.join(L, f));
72
+ const KA = path.join(L, "kernel-authority"); fs.mkdirSync(KA);
73
+ for (const f of fs.readdirSync(HERE).filter((f) => f.endsWith(".mjs") && f !== "acceptance.mjs")) fs.copyFileSync(path.join(HERE, f), path.join(KA, f));
74
+ sh("chmod", ["-R", "go-w,a+rX", C]);
75
+ const NM = path.join(C, "node_modules/@strixgov");
76
+ const versions = Object.fromEntries(fs.readdirSync(NM).map((n) => [n, JSON.parse(fs.readFileSync(path.join(NM, n, "package.json"), "utf8")).version]));
77
+
78
+ // ---------- start services ----------
79
+ const destPort = 20000 + Math.floor(Math.random() * 20000), connPort = destPort + 1;
80
+ const DEST = `http://127.0.0.1:${destPort}`;
81
+ const DESTLOG = P("logs/destination-requests.jsonl"); fs.writeFileSync(DESTLOG, ""); fs.chmodSync(DESTLOG, 0o666);
82
+ bg("p2dest", [NODE, path.join(L, "destination.mjs"), String(destPort), DESTLOG], "destination.log", { env: { DEST_EXEC: EXEC_TOKEN, DEST_OBS: OBS_TOKEN } });
83
+ // hosted-connector stand-in (an "undeclared route" the agent may try): logs every hit itself
84
+ const CONNLOG = P("logs/connector-standin-requests.jsonl"); fs.writeFileSync(CONNLOG, ""); fs.chmodSync(CONNLOG, 0o666);
85
+ 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");
86
+ { 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); } }
87
+ 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)
88
+ const approverPub = P("approver-public.json");
89
+ const mkcfg = sh(NODE, [path.join(L, "make-config.mjs"), P("proxy-config.json"), approverPub, P("proxy-approvals"), P("st-proxy"), path.join(KA, "shim.mjs"), P("sock-exec/exec.sock"), P("sock-claim/claim.sock"), process.env.APPROVAL_TIMEOUT_MS ?? "9000"]);
90
+ if (mkcfg.status !== 0) { console.error(mkcfg.stderr); process.exit(4); }
91
+ fs.writeFileSync(P("config-summary.json"), mkcfg.stdout);
92
+ // ---- Strix approvers (Phase 4B-1): each generates its OWN key as its own OS user; only PUBLIC JWKs are published ----
93
+ const aprSecret = Object.fromEntries(APRS.map((a) => [a.name, "DUMMY-APR-" + a.name + "-" + crypto.randomBytes(16).toString("hex")]));
94
+ for (const a of APRS) mk("apr-" + a.name, a.user, 0o700);
95
+ const aprFile = [];
96
+ for (const a of APRS) { const r = as(a.user, [NODE, path.join(KA, "strix-approver.mjs"), "keygen", P("apr-" + a.name), "--principal", a.name]); if (r.status !== 0) { console.error("approver keygen failed", a.name, r.stderr, r.stdout); process.exit(5); }
97
+ const pub = JSON.parse(fs.readFileSync(P("apr-" + a.name + "/public.jwk.json"), "utf8")); aprFile.push({ principal: a.name, jwk: pub.jwk, secretSha256: crypto.createHash("sha256").update(aprSecret[a.name]).digest("hex") }); }
98
+ fs.writeFileSync(P("approvers.json"), JSON.stringify(aprFile, null, 1), { mode: 0o644 });
99
+ // ---- Phase 4B-2: the ISOLATED signing provider(s). Own OS user, 0700 keystore, unix socket 0660 owned by that user.
100
+ // The kernel (below) is configured with the provider's PUBLIC key only and holds no authority private key. ----
101
+ const SP = path.join(KA, "signing-provider.mjs"), ISSUER = "https://authority.strix.staging.test";
102
+ const spInit = (dir, kid) => { const r = as("p2sign", [NODE, SP, "init", "--dir", P(dir), "--issuer", ISSUER, "--kid", kid]); if (r.status !== 0) { console.error("signing provider init failed", r.stderr, r.stdout); process.exit(8); } return j(r.stdout); };
103
+ const KID1 = "strix-authority-dev-2026-11", KID2 = "strix-authority-dev-2026-12";
104
+ const spKey1 = spInit("sign-keys", KID1), spKey2 = spInit("sign-keys2", KID2);
105
+ const SIGNC_GID = sh("getent", ["group", "p2signc"]).stdout.split(":")[2];
106
+ const startProvider = (dir, sock, extra = []) => bg("p2sign", [NODE, SP, "serve", "--dir", P(dir), "--socket", P(sock), "--group", SIGNC_GID, ...extra], "signing-provider-" + dir + ".log");
107
+ startProvider("sign-keys", "sock-sign/sp1.sock"); startProvider("sign-keys2", "sock-sign/sp2.sock"); await sleep(900);
108
+ const signEnv = (n) => (n === "two" ? { STRIX_DEV_KERNEL_SIGNING_PROVIDER_SOCKET: P("sock-sign/sp2.sock"), STRIX_DEV_KERNEL_SIGNING_PUBLIC_X: spKey2.x, STRIX_DEV_KERNEL_KID: KID2 } : { STRIX_DEV_KERNEL_SIGNING_PROVIDER_SOCKET: P("sock-sign/sp1.sock"), STRIX_DEV_KERNEL_SIGNING_PUBLIC_X: spKey1.x, STRIX_DEV_KERNEL_KID: KID1 });
109
+ // ---- the REAL kernel (signing delegated to the provider), then a SECOND kernel that publishes the first key as REVOKED ----, then a SECOND kernel that publishes the first key as REVOKED ----
110
+ const startKernel = (name, env) => {
111
+ const dir = P("kernel-" + name); fs.mkdirSync(dir, { mode: 0o755 }); sh("chown", ["p2kernel", dir]); fs.rmSync(path.join(dir, "stop"), { force: true });
112
+ const out = fs.openSync(P("logs/kernel-" + name + ".log"), "a");
113
+ const kenv = { DATABASE_URL: KERNEL_DB, STRIX_DEV_KERNEL_DIR: dir, STRIX_DEV_KERNEL_TENANT: "tenant-mcp-staging", STRIX_DEV_KERNEL_CONSUMER: "consumer-mcp-synth", STRIX_DEV_KERNEL_SERVICE_TOKEN: SVC_TOKEN, STRIX_DEV_KERNEL_REQUEST_TOKEN: REQ_TOKEN, STRIX_DEV_KERNEL_REDEEM_TOKEN: RED_TOKEN, STRIX_DEV_KERNEL_OPERATOR_SECRET: APPR_SECRET, STRIX_DEV_KERNEL_APPROVERS: P("approvers.json"), STRIX_AUTHORITY_GRANT_TTL_SECONDS: "60", ...signEnv(name), ...env } ;
114
+ const p = spawn("setpriv", ["--reuid", "p2kernel", "--regid", "p2kernel", "--init-groups", "--reset-env", "env", "HOME=" + P("kernel-home"), "TMPDIR=" + P("kernel-home"), "PATH=" + process.env.PATH, ...Object.entries(kenv).map(([k, v]) => `${k}=${v}`), "npx", "vitest", "run", "--config", "vitest.backend.config.ts", "--testTimeout=0", "tests/authority/dev-kernel-serve.test.ts"], { cwd: KERNEL_CWD, stdio: ["ignore", out, out], detached: true });
115
+ p.unref(); return { dir, p };
116
+ };
117
+ const waitReady = async (k) => { for (let i = 0; i < 240; i++) { if (fs.existsSync(path.join(k.dir, "ready.json"))) return JSON.parse(fs.readFileSync(path.join(k.dir, "ready.json"), "utf8")); await sleep(500); } console.error("kernel did not start:\n" + fs.readFileSync(P("logs/kernel-" + path.basename(k.dir).slice(7) + ".log"), "utf8").slice(-1500)); process.exit(71); };
118
+ const K1 = startKernel("one", {}); const ready1 = await waitReady(K1);
119
+ const pin = (r, file, over = {}) => { fs.writeFileSync(P(file), JSON.stringify({ baseUrl: r.baseUrl, issuer: r.issuer, strixTenantId: r.strixTenantId, consumerTenantId: r.consumerTenantId, pinnedAuthorityKey: r.pinnedAuthorityKey, ...over }, null, 1), { mode: 0o644 }); return P(file); };
120
+ const PIN1 = pin(ready1, "pinned-trust-1.json"); // the provisioning record the executor and broker are given (root-owned)
121
+ const startBroker = () => bg("p2auth", [NODE, path.join(KA, "broker.mjs"), P("sock-reg/reg.sock"), P("sock-claim/claim.sock"), P("st-auth"), approverPub, PIN1], "broker.log", { env: { STRIX_SERVICE_TOKEN: REQ_TOKEN } });
122
+ const startExec = (extra = {}, o = {}) => bg("p2exec", [NODE, path.join(KA, "executor.mjs"), o.sock ?? P("sock-exec/exec.sock"), o.state ?? P("st-exec"), o.pin ?? PIN1, DEST], o.log ?? "executor.log", { env: { EXECUTOR_TOKEN: EXEC_TOKEN, STRIX_SERVICE_TOKEN: RED_TOKEN, ...extra } });
123
+ startBroker(); await sleep(800); startExec(); await sleep(1200);
124
+ 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");
125
+ bg("p2proxy", [NODE, path.join(L, "approval-relay.mjs"), P("proxy-approvals"), P("approver-home/approvals")], "relay.log");
126
+ await sleep(1200);
127
+ for (const [u, pat] of [["p2auth", "broker.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); }
128
+ 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>"));
129
+
130
+ const agentSock = P("sock-agent/mcp.sock");
131
+ const agentCall = (tool, args, ms = 60000) => new Promise((resolve) => {
132
+ const out = fs.openSync(P("logs/agent-call.out"), "w");
133
+ 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"] });
134
+ let buf = ""; p.stdout.on("data", (d) => (buf += d)); p.stderr.on("data", () => {});
135
+ const t = setTimeout(() => p.kill(), ms);
136
+ p.on("close", () => { clearTimeout(t); resolve(j(buf.trim().split("\n").pop()) ?? { ok: false, error: "no output: " + buf.slice(0, 120) }); });
137
+ });
138
+ 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", "")) : []);
139
+ 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) }; };
140
+ const destLines = () => fs.readFileSync(DESTLOG, "utf8").trim().split("\n").filter(Boolean).map(JSON.parse);
141
+ const marks = () => destLines().length;
142
+ const since = (m) => destLines().slice(m).filter((x) => !(x.method === "GET" && x.role === "observer"));
143
+ 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 });
144
+ const observe = (outName) => { as("p2obs", [NODE, path.join(KA, "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")); };
145
+ // ---- Strix approver actions (each runs as that approver's OWN OS user, with its own key; ASYNC so the harness stays live) ----
146
+ const aprRun = (name, cmd, args = [], extraEnv = {}) => new Promise((resolve) => {
147
+ const a = APRS.find((x) => x.name === name);
148
+ const p = spawn("setpriv", asArgs(a.user, [NODE, path.join(KA, "strix-approver.mjs"), cmd, P("apr-" + name), "--base", ready1.baseUrl, "--tenant", ready1.strixTenantId, ...args], { env: { STRIX_APPROVER_SECRET: aprSecret[name], STRIX_INGEST_HMAC_KEY: SVC_TOKEN, ...extraEnv } }), { stdio: ["ignore", "pipe", "pipe"] });
149
+ let b = ""; p.stdout.on("data", (d) => (b += d)); p.stderr.on("data", () => {});
150
+ const t = setTimeout(() => p.kill(), 30000);
151
+ p.on("close", () => { clearTimeout(t); resolve(j(b.trim().split("\n").pop()) ?? { ok: false, error: "no output" }); });
152
+ });
153
+ const aprInfo = (name, id) => aprRun(name, "info", ["--decision", id]);
154
+ const consoleApproveAll = async (id, who, expect) => { for (const n of who) { const i = await aprInfo("alice", id); if (i.state === "APPROVED") break; await aprRun(n, "approve", ["--decision", id, ...(expect ? ["--expect-payload", expect] : [])]); } };
155
+ const signEvent = (name, id, expect, extra = []) => aprRun(name, "sign", ["--decision", id, ...(expect ? ["--expect-payload", expect] : []), ...extra]);
156
+ const operatorRevokeKey = async (kid) => (await fetch(`${ready1.baseUrl}/dev/operator/revoke-approver-key/${encodeURIComponent(kid)}`, { method: "POST", headers: { "x-dev-operator-secret": APPR_SECRET } })).json();
157
+ const aprKid = (name) => JSON.parse(fs.readFileSync(P("apr-" + name + "/identity.json"), "utf8")).kid;
158
+ // plans: what the Strix approvers DO about one pending decision. Returns the per-event ingest outcomes.
159
+ async function runPlan(id, expect, plan = "full", ctx = {}) {
160
+ const ev = [];
161
+ if (plan === "none") return ev;
162
+ if (plan === "stale") { await consoleApproveAll(id, ["alice"], expect); ev.push(await signEvent("alice", id, expect)); ev.push(await signEvent("bob", id, expect)); await consoleApproveAll(id, ["bob", "carol"], expect); return ev; }
163
+ if (plan === "revoked-key") { await operatorRevokeKey(aprKid("carol")); await consoleApproveAll(id, ["alice", "carol"], expect); ev.push(await signEvent("alice", id, expect)); ev.push(await signEvent("carol", id, expect)); return ev; }
164
+ await consoleApproveAll(id, ["alice", "bob", "carol"], expect);
165
+ if (plan === "console-only") return ev;
166
+ if (plan === "one-signer") { ev.push(await signEvent("alice", id, expect)); return ev; }
167
+ if (plan === "same-twice") { ev.push(await signEvent("alice", id, expect)); ev.push(await signEvent("alice", id, expect)); return ev; }
168
+ if (plan === "forged") { ev.push(await signEvent("alice", id, expect)); ev.push(await signEvent("bob", id, expect, ["--use-kid", aprKid("alice"), "--as-principal", "alice"])); return ev; }
169
+ if (plan === "wrong-decision") { for (const n of ["alice", "bob"]) ev.push(await signEvent(n, id, expect, ["--evidence-hash", ctx.otherHash])); return ev; }
170
+ ev.push(await signEvent("alice", id, expect)); ev.push(await signEvent("bob", id, expect)); // full
171
+ return ev;
172
+ }
173
+ const approveAsync = (id) => new Promise((resolve) => { const p = spawn("setpriv", asArgs("p2approver", [NODE, path.join(L, "approver.mjs"), "approve", P("approver-home"), id, P("sock-reg/reg.sock")]), { stdio: ["ignore", "pipe", "pipe"] }); let b = ""; p.stdout.on("data", (d) => (b += d)); p.stderr.on("data", () => {}); const t = setTimeout(() => p.kill(), 60000); p.on("close", () => { clearTimeout(t); resolve(j(b.trim().split("\n").pop()) ?? { err: "no output" }); }); });
174
+ const brokerEvents = () => (fs.existsSync(P("st-auth/broker-log.jsonl")) ? fs.readFileSync(P("st-auth/broker-log.jsonl"), "utf8").trim().split("\n").filter(Boolean).map(JSON.parse) : []);
175
+ async function approvedCall(tool, args, plan = "full") { // full path: agent -> published proxy -> person's approval -> broker -> Strix approvers (own keys) -> kernel grant -> shim -> executor -> destination
176
+ const before = new Set(pendingIds());
177
+ const p = agentCall(tool, args);
178
+ let id; for (let i = 0; i < 80 && !id; i++) { await sleep(100); id = pendingIds().find((x) => !before.has(x)); }
179
+ if (!id) return { result: await p, id: null };
180
+ const apP = approveAsync(id);
181
+ let strix = null;
182
+ for (let i = 0; i < 120 && !strix; i++) { await sleep(150); const e = brokerEvents().find((x) => x.ev === "approval-required" && x.requestId === id); if (e) strix = e; }
183
+ const events = strix ? await runPlan(strix.strixDecisionId, sdk.canonicalSha256(args), plan, {}) : [];
184
+ const ap = await apP;
185
+ return { result: await p, id, ap, strixDecisionId: strix?.strixDecisionId, events };
186
+ }
187
+
188
+ // ================= Gate A: published-proxy topology reachable; MCP lists =================
189
+ const lst = as("p2agent", [NODE, path.join(L, "agent-client.mjs"), agentSock, "list"], { groups: false });
190
+ 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");
191
+
192
+ // ================= Gate B: credential isolation against THIS topology =================
193
+ const XPID = pid("p2exec", "executor.mjs"), APID = pid("p2auth", "broker.mjs"), HPID = pid("p2proxy", "proxy-host.mjs");
194
+ const denied = (r) => /Permission denied|EACCES|EPERM/.test(r.stdout + r.stderr);
195
+ const A = (argv, o) => as("p2agent", argv, { groups: false, ...o });
196
+ 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; };
197
+ probe("CI-01", "read executor credential file", ["cat", P("cred-exec/token")]);
198
+ probe("CI-02", "read observer credential file", ["cat", P("cred-obs/token")]);
199
+ probe("CI-03", "read broker-held kernel grants", ["bash", "-c", `cat ${P("st-auth")}/unclaimed/* ${P("st-auth")}/claimed/* 2>&1 | head -c 200; ls ${P("st-auth")}/unclaimed >/dev/null`], true);
200
+ probe("CI-04", "read executor outcome-signing key", ["cat", P("st-exec/outcome-key.pem")]);
201
+ probe("CI-05", "read approver passphrase", ["cat", P("approver-home/passphrase")]);
202
+ probe("CI-06", "read approver private key", ["cat", P("approver-home/approver/key.enc.json")]);
203
+ probe("CI-07", "list proxy approvals dir (pending requests)", ["ls", P("proxy-approvals")]);
204
+ probe("CI-08", "read executor /proc environ", ["cat", `/proc/${XPID}/environ`]);
205
+ probe("CI-09", "enumerate executor fds", ["ls", `/proc/${XPID}/fd`]);
206
+ probe("CI-10", "read executor memory", [NODE, "-e", `require('fs').readFileSync('/proc/${XPID}/mem')`]);
207
+ probe("CI-11", "read broker /proc environ", ["cat", `/proc/${APID}/environ`]);
208
+ probe("CI-12", "read proxy-service /proc environ", ["cat", `/proc/${HPID}/environ`]);
209
+ 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));
210
+ const pkr = pk.map((f) => ({ f, r: A(["cat", f]) }));
211
+ 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"));
212
+ const ps = A(["ps", "-eo", "pid,user,args"]); const leak = /DUMMY-/.test(ps.stdout);
213
+ rec("CI-14", "credential-isolation", "credentials in process listing (argv)", "no credential on any command line", leak ? "LEAK" : "none", leak ? "FAIL" : "PASS");
214
+ const envp = A([NODE, "-e", "console.log(Object.keys(process.env).filter(k=>/TOKEN|SECRET|KEY|PASS/i.test(k)).join(',')||'none')"]);
215
+ rec("CI-15", "credential-isolation", "agent process environment", "no credential variables", envp.stdout.trim(), envp.stdout.trim() === "none" ? "PASS" : "FAIL");
216
+ 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" " "']);
217
+ rec("CI-16", "credential-isolation", "agent inherited file descriptors", "none beyond stdio", fds.stdout.trim() || "none", fds.stdout.trim() === "" ? "PASS" : "FAIL");
218
+ const grep = A(["grep", "-rl", "-e", EXEC_TOKEN, "-e", OBS_TOKEN, "-e", SVC_TOKEN, "-e", REQ_TOKEN, "-e", RED_TOKEN, "-e", APPR_SECRET, W]); const files = grep.stdout.trim().split("\n").filter(Boolean);
219
+ 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");
220
+ const sudo = A(["sudo", "-n", "-u", "p2exec", "id"]);
221
+ 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");
222
+ for (const [id, name, sockp] of [["IPC-01", "executor socket", "sock-exec/exec.sock"], ["IPC-02", "broker claim socket", "sock-claim/claim.sock"], ["IPC-03", "broker register socket", "sock-reg/reg.sock"]]) {
223
+ 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()})`]);
224
+ rec(id, "credential-isolation", `agent connects to ${name} directly (IPC)`, "EACCES", r.stdout.trim(), /EACCES|EPERM/.test(r.stdout) ? "PASS" : "FAIL");
225
+ }
226
+ // trusted-config / executable integrity: agent cannot modify
227
+ for (const [id, what, target] of [["INT-01", "proxy config", P("proxy-config.json")], ["INT-02", "executor script", path.join(KA, "executor.mjs")], ["INT-03", "shim script", path.join(KA, "shim.mjs")], ["INT-04", "published proxy package", path.join(NM, "mcp-proxy/package.json")]]) {
228
+ const r = A(["bash", "-c", `echo tampered >> '${target}'`]);
229
+ rec(id, "trusted-config-integrity", `agent appends to ${what}`, "write denied", (r.stderr || r.stdout).trim(), denied(r) ? "PASS" : "FAIL");
230
+ }
231
+ const subst = A(["bash", "-c", `rm -f '${P("sock-exec/exec.sock")}'; ln -s /dev/null '${P("sock-exec/exec.sock")}'`]);
232
+ 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");
233
+ const subst2 = A(["bash", "-c", `rm -f '${P("sock-agent/mcp.sock")}'`]);
234
+ 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");
235
+
236
+ // ================= Gate C: authority issued, bound and consumed by the REAL Strix kernel =================
237
+ const sdkUrl = pathToFileURL(path.join(C, "node_modules/@strixgov/execution-authority/dist/index.js")).href;
238
+ const sdk = await import(sdkUrl);
239
+ const D = await import(pathToFileURL(path.join(KA, "derive.mjs")).href);
240
+ const RUN = crypto.randomBytes(3).toString("hex");
241
+ const mkClient = (r, token = SVC_TOKEN) => new sdk.StrixExecutionAuthorityClient({ baseUrl: r.baseUrl, token, strixTenantId: r.strixTenantId, issuer: r.issuer });
242
+ const clientReq = mkClient(ready1, REQ_TOKEN), client1 = mkClient(ready1, RED_TOKEN);
243
+ const proposalOf = (args, tag) => sdk.buildProposal({ proposalId: `xp:acc-${tag}-${RUN}`, tenantId: ready1.consumerTenantId, principalId: "agent:controlled-launcher-demo", action: D.CAPABILITY, consequenceId: D.consequenceIdFor(args), executionRoute: D.ROUTE, payloadCommitment: sdk.canonicalSha256(args), currentStateCommitment: sdk.canonicalSha256(D.STANDING) });
244
+ // TEST HARNESS PRIVILEGE (labelled): obtaining a grant directly stands in for the broker so a test can hold the grant itself.
245
+ const obtain = async (args, tag) => {
246
+ const p = proposalOf(args, tag);
247
+ let ev = await clientReq.evaluate(p, { minimumApprovals: 1 });
248
+ if (ev.status === "APPROVAL_REQUIRED") { await runPlan(ev.strixDecisionId, sdk.canonicalSha256(args), "full"); ev = await clientReq.evaluate(p, { minimumApprovals: 1 }); }
249
+ if (ev.status !== "GRANTED") throw new Error("no grant: " + JSON.stringify(ev));
250
+ return ev.grant;
251
+ };
252
+ const exec = (user, args, grant, sock = P("sock-exec/exec.sock")) => j(as(user, [NODE, "-e", `const net=require('net');const c=net.connect('${sock}');let b='';c.on('error',e=>console.log(JSON.stringify({sockErr:e.code})));c.on('connect',()=>c.write(${JSON.stringify(JSON.stringify({ tool: "create_branch", args, grant }))}+'\\n'));c.on('data',d=>b+=d);c.on('end',()=>console.log(b.trim()))`], { groups: true }).stdout);
253
+ const kernelStatus = (gid) => client1.reconcileRedemption(gid);
254
+ const brokerLog = () => (fs.existsSync(P("st-auth/broker-log.jsonl")) ? fs.readFileSync(P("st-auth/broker-log.jsonl"), "utf8").trim().split("\n").map(JSON.parse) : []);
255
+ const A_ = (b) => ({ owner: "synthetic", repo: "fixture", branch: b, from_branch: "main" });
256
+
257
+ // expiry grant is obtained FIRST; the kernel clamps TTL to >= 60s, so it is presented at the end of this gate
258
+ const expArgs = A_("expiring-E"); const expGrant = await obtain(expArgs, "exp"); const expAt = Date.now();
259
+
260
+ // AZ-01 the full governed path with a real kernel grant
261
+ let m = marks();
262
+ const okp = await approvedCall("create_branch", A_("authorized-1"));
263
+ const d1 = since(m);
264
+ const granted1 = brokerLog().filter((e) => e.ev === "granted").at(-1);
265
+ const ks1 = granted1 ? await kernelStatus(granted1.grantId) : null;
266
+ const allAttempts = () => fs.readFileSync(P("st-exec/attempts.jsonl"), "utf8").trim().split("\n").map(JSON.parse);
267
+ const statesForGrant = (gid) => { const rows = allAttempts(); const ids = new Set(rows.filter((a) => a.grantId === gid).map((a) => a.attemptId)); return rows.filter((a) => ids.has(a.attemptId)).map((a) => a.state); }; // follow-on records carry attemptId only
268
+ const att1 = statesForGrant(granted1?.grantId);
269
+ rec("AZ-01", "authorization", "agent -> published proxy -> person's signed approval -> broker -> REAL kernel grant -> shim -> executor (redeems at kernel) -> destination", "one destination write by the executor credential; kernel records the consumption; executor accounting INTENT->CONSUMED->STARTED->COMPLETED", JSON.stringify({ call: okp.result?.ok, dest: d1.map((x) => `${x.method} ${x.url} ${x.role} ${x.status}`), kernel: ks1?.status, executorStates: att1 }), okp.result?.ok && !okp.result.isError && d1.length === 1 && d1[0].status === 201 && ks1?.status === "CONSUMED" && att1.includes("INTENT") && att1.includes("CONSUMED") && att1.includes("STARTED") && att1.some((s) => s === "COMPLETED_SUCCEEDED") ? "PASS" : "FAIL");
270
+ m = marks();
271
+ const noap = await agentCall("create_branch", A_("unapproved-1"));
272
+ 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");
273
+ m = marks();
274
+ const r3 = exec("p2proxy", A_("bypass-no-grant"), undefined);
275
+ rec("AZ-03", "authorization", "trusted proxy uid calls the executor directly with no grant", "AUTHORIZATION_REQUIRED; destination sees nothing", JSON.stringify({ reply: r3, dest: since(m).length }), r3?.error === "AUTHORIZATION_REQUIRED" && since(m).length === 0 ? "PASS" : "FAIL");
276
+
277
+ // forged / untrusted grants: a real grant's payload re-signed by an attacker key, an unknown key id, an untrusted issuer
278
+ const argsF = A_("forged-F"); const realF = await obtain(argsF, "forge");
279
+ const atk = crypto.generateKeyPairSync("ed25519").privateKey;
280
+ const sign = (payload) => ({ payload, signature: crypto.sign(null, Buffer.from(sdk.canonicalJson(payload)), atk).toString("base64url"), algorithm: "Ed25519", canonicalization: realF.canonicalization });
281
+ const forgeries = [
282
+ ["real kid, attacker signature", sign({ ...realF.payload })],
283
+ ["unknown attacker kid", sign({ ...realF.payload, signingKeyId: "strix-authority-attacker-1" })],
284
+ ["untrusted issuer (https://evil.example)", sign({ ...realF.payload, issuer: "https://evil.example" })],
285
+ ];
286
+ m = marks(); const forgedOut = forgeries.map(([n, g]) => [n, exec("p2proxy", argsF, g)]);
287
+ const stF = await kernelStatus(realF.payload.grantId);
288
+ rec("AZ-04", "authorization", "forged key / unknown key / untrusted issuer", "each REFUSED before execution; destination sees nothing; the real grant stays unspent", JSON.stringify({ outcomes: forgedOut.map(([n, r]) => `${n}: ${r?.error} ${r?.detail ?? ""}`), dest: since(m).length, kernel: stF.status }), forgedOut.every(([, r]) => r?.ok === false && /AUTHORIZATION_REFUSED|TRUST_PIN_REFUSED/.test(r.error)) && since(m).length === 0 && stF.status === "NOT_CONSUMED" ? "PASS" : "FAIL");
289
+
290
+ // different work-order digest / modified target or payload
291
+ const argsA = A_("authorized-A"); const gA = await obtain(argsA, "A");
292
+ const argsB = A_("substituted-B");
293
+ m = marks();
294
+ const variants = [["different digest (other branch)", argsB], ["modified payload (from_branch changed)", { ...argsA, from_branch: "develop" }], ["extra field smuggled in", { ...argsA, force: true }], ["different repository (outside estate)", { ...argsA, repo: "other" }]];
295
+ const vOut = variants.map(([n, a]) => [n, exec("p2proxy", a, gA)]);
296
+ const stA = await kernelStatus(gA.payload.grantId);
297
+ rec("AZ-05", "authorization", "work order A's valid, unspent grant presented for a different digest / modified target or payload", "every variant REFUSED before execution; destination sees nothing; A's grant remains unspent", JSON.stringify({ outcomes: vOut.map(([n, r]) => `${n}: ${r?.error} ${r?.detail ?? ""}`), dest: since(m).length, kernel: stA.status }), vOut.every(([, r]) => r?.ok === false) && since(m).length === 0 && stA.status === "NOT_CONSUMED" ? "PASS" : "FAIL");
298
+ // the KERNEL's own check, not the SDK's: present B's consequence for A's grant straight to the consume endpoint
299
+ const consReq = await fetch(`${ready1.baseUrl}/api/v1/authority/grants/${encodeURIComponent(gA.payload.grantId)}/consume`, { method: "POST", headers: { authorization: "Bearer " + RED_TOKEN, "x-tenant-id": ready1.strixTenantId, "content-type": "application/json" }, body: JSON.stringify({ grant: gA, consequence: sdk.currentExecutionOf({ ...gA.payload, payloadCommitment: sdk.canonicalSha256(argsB), consequenceId: D.consequenceIdFor(argsB) }), consumedBy: "harness:swap" }) });
300
+ const consJ = await consReq.json().catch(() => ({}));
301
+ const stA2 = await kernelStatus(gA.payload.grantId);
302
+ rec("AZ-06", "authorization", "KERNEL-side: A's grant presented straight to the consume endpoint with B's digest (SDK bypassed)", "kernel refuses CONSEQUENCE_MISMATCH with signed refusal evidence; grant not spent", JSON.stringify({ http: consReq.status, reason: consJ.reasonCode ?? consJ.error, refusalEvidenceId: consJ.refusalEvidenceId, kernel: stA2.status }), consReq.status === 409 && /CONSEQUENCE_MISMATCH/.test(JSON.stringify(consJ)) && stA2.status === "NOT_CONSUMED" ? "PASS" : "FAIL");
303
+ // ROLE SEPARATION against the real kernel (enforced mode): the credential that may REQUEST authority may not REDEEM it, and the reverse.
304
+ {
305
+ const T = ready1.strixTenantId, g = encodeURIComponent(gA.payload.grantId), H = (tok) => ({ authorization: "Bearer " + tok, "x-tenant-id": T, "content-type": "application/json" });
306
+ const hit = async (m, url, tok) => { const r = await fetch(ready1.baseUrl + url, { method: m, headers: H(tok), body: m === "POST" ? JSON.stringify({ grant: gA, consequence: {}, consumedBy: "xr", outcome: "EXECUTED", handlerEntered: true, reportedBy: "xr" }) : undefined }); const b = await r.json().catch(() => ({})); return { s: r.status, c: b.code }; };
307
+ const reqTokOnRedeem = [await hit("POST", `/api/v1/authority/grants/${g}/consume`, REQ_TOKEN), await hit("POST", `/api/v1/authority/grants/${g}/outcome`, REQ_TOKEN), await hit("GET", `/api/v1/authority/grants/${g}`, REQ_TOKEN)];
308
+ const redTokOnRequest = [await hit("POST", `/api/v1/authority/requests/xr-${RUN}`, RED_TOKEN)];
309
+ const legacyTok = [await hit("POST", `/api/v1/authority/requests/xr-${RUN}`, SVC_TOKEN), await hit("POST", `/api/v1/authority/grants/${g}/consume`, SVC_TOKEN), await hit("POST", `/api/v1/authority/grants/${g}/outcome`, SVC_TOKEN), await hit("GET", `/api/v1/authority/grants/${g}`, SVC_TOKEN)];
310
+ const stX = await kernelStatus(gA.payload.grantId);
311
+ rec("XR-01", "role-separation", "the REQUEST credential (broker's) calls consume / outcome / status", "403 AUTHORITY_ROLE_MISMATCH each; grant not spent", JSON.stringify({ reqTokOnRedeem, kernel: stX.status }), reqTokOnRedeem.every((x) => x.s === 403 && x.c === "AUTHORITY_ROLE_MISMATCH") && stX.status !== "CONSUMED" ? "PASS" : "FAIL");
312
+ rec("XR-02", "role-separation", "the REDEEM credential (executor's) asks the kernel for authority", "403 AUTHORITY_ROLE_MISMATCH; no decision created", JSON.stringify({ redTokOnRequest }), redTokOnRequest.every((x) => x.s === 403 && x.c === "AUTHORITY_ROLE_MISMATCH") ? "PASS" : "FAIL");
313
+ rec("XR-03", "role-separation", "the legacy shared service credential (STRIX_INTERNAL_TOKEN) on every authority route", "401 each in enforced mode", JSON.stringify({ legacyTok }), legacyTok.every((x) => x.s === 401) ? "PASS" : "FAIL");
314
+ }
315
+ // ---- REAL APPROVALS (Phase 4B-1): separate approver identities, own keys, SE v2 events ----
316
+ {
317
+ const apAttempt = async (tag, plan, ctx = {}) => {
318
+ const args = A_("ap-" + tag + "-" + RUN), pr = proposalOf(args, "ap-" + tag);
319
+ const first = await clientReq.evaluate(pr, { minimumApprovals: 1 });
320
+ const events = await runPlan(first.strixDecisionId, sdk.canonicalSha256(args), plan, ctx);
321
+ let after; try { after = await clientReq.evaluate(pr, { minimumApprovals: 1 }); } catch (e) { after = { status: "ERR:" + (e.code ?? e.message) }; }
322
+ return { id: first.strixDecisionId, events, status: after.status + (after.reasonCode ? ":" + after.reasonCode : ""), granted: after.status === "GRANTED" };
323
+ };
324
+ const outs = (r) => r.events.map((e) => `${e.principal}:${e.outcome ?? e.error}`).join(",");
325
+ const landed = (e) => e.ok === true;
326
+ const r1 = await apAttempt("full", "full");
327
+ rec("AP-01", "approvals", "two distinct approvers, each signing an SE v2 event with their OWN key (separate OS users), ingested at the real route", "both events accepted from distinct principals; kernel GRANTS", JSON.stringify({ events: outs(r1), status: r1.status }), r1.granted && r1.events.length === 2 && r1.events.every(landed) && new Set(r1.events.map((e) => e.principal)).size === 2 ? "PASS" : "FAIL");
328
+ const r2 = await apAttempt("none", "none");
329
+ rec("AP-02", "approvals", "no approver acts", "APPROVAL_REQUIRED; no grant", r2.status, r2.status === "APPROVAL_REQUIRED" ? "PASS" : "FAIL");
330
+ const r3 = await apAttempt("console", "console-only");
331
+ rec("AP-03", "approvals", "console approvals reach quorum but NO signed SE v2 events exist", "no grant", r3.status, !r3.granted ? "PASS" : "FAIL");
332
+ const r4 = await apAttempt("one", "one-signer");
333
+ rec("AP-04", "approvals", "only ONE signed approval event (quorum of signed events not met)", "no grant", JSON.stringify({ events: outs(r4), status: r4.status }), !r4.granted ? "PASS" : "FAIL");
334
+ const r5 = await apAttempt("twice", "same-twice");
335
+ rec("AP-05", "approvals", "the SAME approver supplies both events (distinct approvers required)", "second event refused; no grant", JSON.stringify({ events: outs(r5), status: r5.status }), !r5.granted && landed(r5.events[0]) && !landed(r5.events[1]) ? "PASS" : "FAIL");
336
+ const r6 = await apAttempt("forged", "forged");
337
+ rec("AP-06", "approvals", "forged event: bob signs claiming to be alice's key", "signature_invalid at ingest; no grant", JSON.stringify({ events: outs(r6), status: r6.status }), !r6.granted && r6.events[1]?.outcome === "signature_invalid" ? "PASS" : "FAIL");
338
+ const other = await clientReq.evaluate(proposalOf(A_("ap-other-" + RUN), "ap-other"), { minimumApprovals: 1 });
339
+ const otherHash = (await aprInfo("alice", other.strixDecisionId)).evidenceHash;
340
+ const r7 = await apAttempt("wrong", "wrong-decision", { otherHash });
341
+ rec("AP-07", "approvals", "authentic approvals signed over a DIFFERENT decision's evidence hash presented for this decision", "no grant (exact-decision binding)", JSON.stringify({ events: outs(r7), status: r7.status }), !r7.granted ? "PASS" : "FAIL");
342
+ const r8 = await apAttempt("stale", "stale");
343
+ rec("AP-08", "approvals", "events signed before the decision changed (a later console approval altered the row)", "stale events refused; no grant", JSON.stringify({ events: outs(r8), status: r8.status }), !r8.granted ? "PASS" : "FAIL");
344
+ const r9 = await apAttempt("revoked", "revoked-key");
345
+ rec("AP-09", "approvals", "an approver's key is REVOKED by the operator before they sign", "revoked_key at ingest; no grant", JSON.stringify({ events: outs(r9), status: r9.status }), !r9.granted && r9.events[1]?.outcome === "revoked_key" ? "PASS" : "FAIL");
346
+ const refuse = await aprRun("bob", "approve", ["--decision", other.strixDecisionId, "--expect-payload", "sha256:" + "0".repeat(64)]);
347
+ rec("AP-10", "approvals", "an approver is asked to approve a payload that is not what the decision contains", "approver tool refuses; nothing approved", JSON.stringify(refuse), refuse.error === "REFUSED_NOT_WHAT_I_WAS_ASKED_TO_APPROVE" ? "PASS" : "FAIL");
348
+ const kpriv = APRS.flatMap((a) => ["agent", "p2auth", "p2exec", "p2proxy"].map((who) => [a.name, who, (who === "agent" ? A : (argv) => as(who, argv))(["cat", P("apr-" + a.name + "/private.key")])]));
349
+ const cross = (as("p2apr1", ["cat", P("apr-bob/private.key")]).stdout + as("p2apr2", ["cat", P("apr-carol/private.key")]).stdout).trim();
350
+ rec("AP-11", "approvals", "agent / broker / executor / proxy / another approver read an approver's PRIVATE key", "permission denied for all", kpriv.filter(([, , r]) => !denied(r)).map(([n, w]) => `${w} read ${n}`).join(",") || `denied x${kpriv.length}; cross-approver read ${cross ? "SUCCEEDED" : "denied"}`, kpriv.every(([, , r]) => denied(r)) && cross === "" ? "PASS" : "FAIL");
351
+ const noEnd = await fetch(ready1.baseUrl + "/dev/approve/anything", { method: "POST" }).then((r) => r.status);
352
+ rec("AP-12", "approvals", "the old all-in-one /dev/approve stand-in no longer exists on the kernel", "404", noEnd, noEnd === 404 ? "PASS" : "FAIL");
353
+ }
354
+ global.__refusalEvidence = consJ.refusalEvidenceId;
355
+ m = marks(); const exactA = exec("p2proxy", argsA, gA);
356
+ rec("AZ-07", "authorization", "exact action still redeems after the refusals (refusals spend nothing)", "one authorized execution (201)", JSON.stringify({ reply: exactA?.ok, dest: since(m).map((x) => `${x.role} ${x.status}`) }), exactA?.ok && !exactA.isError && since(m).length === 1 && since(m)[0].status === 201 ? "PASS" : "FAIL");
357
+ m = marks(); const reuse = exec("p2proxy", argsA, gA); const stA3 = await kernelStatus(gA.payload.grantId);
358
+ rec("AZ-08", "authorization", "reuse of the same grant after successful consumption", "refused (GRANT_ALREADY_CONSUMED) by the kernel; destination sees nothing", JSON.stringify({ reply: reuse, dest: since(m).length, kernel: stA3.status }), reuse?.ok === false && /ALREADY_CONSUMED/.test(JSON.stringify(reuse)) && since(m).length === 0 && stA3.status === "CONSUMED" ? "PASS" : "FAIL");
359
+
360
+ // eight simultaneous presentations of one fresh grant
361
+ const argsC = A_("authorized-C"); const gC = await obtain(argsC, "C");
362
+ m = marks();
363
+ const rs = await Promise.all(Array.from({ length: 8 }, () => new Promise((res) => res(exec("p2proxy", argsC, gC)))));
364
+ const succ = rs.filter((x) => x?.ok && !x?.isError).length, created = since(m).filter((x) => x.status === 201).length;
365
+ const attC = allAttempts().filter((a) => a.grantId === gC.payload.grantId);
366
+ const consumedRecs = attC.filter((a) => a.state === "CONSUMED").length;
367
+ rec("CC-02", "concurrency", "one real kernel grant presented 8x in parallel to the executor", "at most one consumption at the kernel; exactly one execution; no INDETERMINATE", `successes=${succ}, destination 201s=${created}, executor CONSUMED records=${consumedRecs}, replies=${[...new Set(rs.map((x) => x?.detail ?? x?.error ?? "ok"))].join("|")}`, succ === 1 && created === 1 && consumedRecs === 1 && !rs.some((x) => x?.error === "REDEMPTION_INDETERMINATE") ? "PASS" : "FAIL");
368
+
369
+ // key lifecycle: a kernel that publishes the pinned key as REVOKED; and no key-status information at all
370
+ const K2 = startKernel("two", { STRIX_DEV_KERNEL_KEYS_EXTRA: JSON.stringify([{ kid: ready1.pinnedAuthorityKey.kid, x: ready1.pinnedAuthorityKey.x, status: "revoked", notBefore: ready1.pinnedAuthorityKey.notBefore, notAfter: ready1.pinnedAuthorityKey.notAfter, revokedAt: "2026-11-23T00:00:00Z" }]) });
371
+ const ready2 = await waitReady(K2);
372
+ const PIN2 = pin(ready2, "pinned-trust-2.json", { pinnedAuthorityKey: ready1.pinnedAuthorityKey }); // told to trust K1; K2's published set revokes it
373
+ const PIN3 = pin(ready1, "pinned-trust-3.json", { baseUrl: "http://127.0.0.1:9" }); // key-status source unreachable
374
+ mk("st-exec2", "p2exec", 0o755); mk("st-exec3", "p2exec", 0o755);
375
+ startExec({}, { sock: P("sock-exec/exec2.sock"), state: P("st-exec2"), pin: PIN2, log: "executor2.log" }); startExec({}, { sock: P("sock-exec/exec3.sock"), state: P("st-exec3"), pin: PIN3, log: "executor3.log" }); await sleep(1500);
376
+ const gRev = await obtain(A_("revoked-key-R"), "rev"); m = marks();
377
+ const rRev = exec("p2proxy", A_("revoked-key-R"), gRev, P("sock-exec/exec2.sock"));
378
+ rec("AZ-09", "authorization", "grant signed by a key the kernel's published set now marks REVOKED", "refused under the declared revocation policy; destination sees nothing", JSON.stringify({ reply: rRev, dest: since(m).length }), rRev?.ok === false && /revoked/i.test(JSON.stringify(rRev)) && since(m).length === 0 ? "PASS" : "FAIL");
379
+ const gNk = await obtain(A_("no-keystatus-N"), "nok"); m = marks();
380
+ const rNk = exec("p2proxy", A_("no-keystatus-N"), gNk, P("sock-exec/exec3.sock"));
381
+ rec("AZ-10", "authorization", "required key-status / revocation information cannot be obtained", "fail closed: TRUST_NOT_ESTABLISHED; destination sees nothing; grant unspent", JSON.stringify({ reply: rNk, dest: since(m).length, kernel: (await kernelStatus(gNk.payload.grantId)).status }), rNk?.error === "TRUST_NOT_ESTABLISHED" && since(m).length === 0 ? "PASS" : "FAIL");
382
+
383
+ // crash recovery against the kernel's own store
384
+ sh("pkill", ["-u", "p2exec", "-f", "kernel-authority/executor.mjs"]); await sleep(600);
385
+ const crashRun = async (id, env, args) => {
386
+ sh("pkill", ["-u", "p2exec", "-f", "kernel-authority/executor.mjs"]); await sleep(600); // exactly one executor on the socket
387
+ startExec(env); await sleep(1200);
388
+ const g = await obtain(args, id); const mm = marks();
389
+ const r = exec("p2proxy", args, g); await sleep(600);
390
+ const alive = !!pid("p2exec", "kernel-authority/executor.mjs");
391
+ sh("pkill", ["-u", "p2exec", "-f", "kernel-authority/executor.mjs"]); await sleep(500);
392
+ startExec(); await sleep(1500); // recovery runs at startup
393
+ return { g, r, alive, destDuring: since(mm).length };
394
+ };
395
+ const argsR1 = A_("crash-after-started-R1"), argsR2 = A_("crash-after-consume-R2");
396
+ const cr1 = await crashRun("r1", { EXECUTOR_TEST_CRASH_AFTER_STARTED: "1" }, argsR1);
397
+ const cr2 = await crashRun("r2", { EXECUTOR_TEST_CRASH_AFTER_CONSUME: "1" }, argsR2);
398
+ const statesOf = (gid) => statesForGrant(gid);
399
+ const ksR1 = await kernelStatus(cr1.g.payload.grantId), ksR2 = await kernelStatus(cr2.g.payload.grantId);
400
+ const obsCrash = observe("reconcile-after-crash.json");
401
+ const rowR1 = obsCrash.attempts.find((a) => a.ref === "refs/heads/crash-after-started-R1"), rowR2 = obsCrash.attempts.find((a) => a.ref === "refs/heads/crash-after-consume-R2");
402
+ rec("CR-01", "crash-recovery", "executor crashes after durable STARTED, before the destination call; restart", "no retry; kernel consumption recorded; attempt UNKNOWN; kernel decision stays unresolved; observer resolves NOT_EXECUTED", JSON.stringify({ aliveAfter: cr1.alive, states: statesOf(cr1.g.payload.grantId), kernel: ksR1.status, unresolved: !!ksR1.unresolvedAttempt, verdict: rowR1?.verdict, destDuringCrash: cr1.destDuring }), !cr1.alive && statesOf(cr1.g.payload.grantId).includes("RECOVERED_UNKNOWN") && ksR1.status === "CONSUMED" && ksR1.unresolvedAttempt && rowR1?.verdict === "RESOLVED_BY_OBSERVATION_NOT_EXECUTED" && cr1.destDuring === 0 ? "PASS" : "FAIL");
403
+ m = marks(); const re2 = exec("p2proxy", argsR2, cr2.g);
404
+ rec("CR-02", "crash-recovery", "executor crashes AFTER the kernel consumed the grant but before STARTED; restart; the same grant is presented again", "no duplicate execution (GRANT_ALREADY_CONSUMED); recoverable accounting (RECOVERED_UNKNOWN + kernel unresolved); observer resolves NOT_EXECUTED", JSON.stringify({ aliveAfter: cr2.alive, states: statesOf(cr2.g.payload.grantId), kernel: ksR2.status, replay: re2?.detail ?? re2?.error, verdict: rowR2?.verdict, destAfterReplay: since(m).length }), !cr2.alive && statesOf(cr2.g.payload.grantId).includes("RECOVERED_UNKNOWN") && ksR2.status === "CONSUMED" && /ALREADY_CONSUMED/.test(JSON.stringify(re2)) && rowR2?.verdict === "RESOLVED_BY_OBSERVATION_NOT_EXECUTED" && since(m).length === 0 ? "PASS" : "FAIL");
405
+ // missing destination observation: the observer cannot reach the destination
406
+ as("p2obs", [NODE, path.join(KA, "reconcile.mjs"), P("st-exec"), "http://127.0.0.1:9", P("logs/reconcile-no-observation.json")], { env: { OBSERVER_TOKEN: OBS_TOKEN } }); fs.chmodSync(P("logs/reconcile-no-observation.json"), 0o644);
407
+ const noObs = j(fs.readFileSync(P("logs/reconcile-no-observation.json"), "utf8"));
408
+ const unresolved = noObs.attempts.filter((a) => a.executorReported === "UNKNOWN");
409
+ rec("OBS-01", "evidence", "destination cannot be observed", "UNKNOWN outcomes remain unknown (never promoted to executed or not-executed)", JSON.stringify({ observationError: noObs.observationError, unknownRows: unresolved.map((a) => a.verdict) }), unresolved.length >= 2 && unresolved.every((a) => a.verdict === "OUTCOME_REMAINS_UNKNOWN_NO_OBSERVATION") ? "PASS" : "FAIL");
410
+
411
+ // expiry, last (>= 60s elapsed since the grant was issued)
412
+ const wait = Math.max(0, 63000 - (Date.now() - expAt)); if (wait) await sleep(wait);
413
+ m = marks(); const rExp = exec("p2proxy", expArgs, expGrant);
414
+ rec("AZ-11", "authorization", "expired grant (kernel TTL floor 60s, presented after 63s)", "refused; destination sees nothing", JSON.stringify({ reply: rExp, dest: since(m).length, afterSeconds: Math.round((Date.now() - expAt) / 1000) }), rExp?.ok === false && since(m).length === 0 ? "PASS" : "FAIL");
415
+
416
+ // the agent against the KERNEL itself (before the network rule)
417
+ const kurl = ready1.baseUrl;
418
+ const curlStatus = (args) => A(["curl", "-s", "-m", "4", "-o", "/dev/null", "-w", "%{http_code}", ...args]).stdout.trim();
419
+ const k1 = curlStatus(["-X", "POST", `${kurl}/api/v1/authority/requests/xp:agent-self`, "-H", "content-type: application/json", "-d", "{}"]);
420
+ const k2 = curlStatus(["-X", "POST", `${kurl}/dev/console-approve/anything`, "-H", "x-dev-approver-id: alice", "-H", "x-dev-approver-secret: guess"]);
421
+ const k3 = curlStatus(["-X", "POST", `${kurl}/api/v1/authority/grants/sg:x/consume`, "-H", "content-type: application/json", "-d", "{}"]);
422
+ rec("KI-01", "kernel-access", "agent requests authority from the kernel / calls the console-approve stand-in with a guessed approver secret / calls consume, none holding a credential", "401/403 for every call (no service credential, no approver secret)", `request=${k1} approve=${k2} consume=${k3}`, [k1, k2, k3].every((c) => c === "401" || c === "403") ? "PASS" : "FAIL");
423
+ const kpid = sh("pgrep", ["-f", "dev-kernel-serve"]).stdout.trim().split("\n")[0];
424
+ const kenv = A(["cat", `/proc/${kpid}/environ`]);
425
+ rec("KI-02", "kernel-access", "agent reads the kernel process environment (service token, approver secret)", "permission denied", (kenv.stdout + kenv.stderr).trim().slice(0, 80), denied(kenv) ? "PASS" : "FAIL");
426
+
427
+ // ================= Alternate routes to the protected destination (before the network rule: credential control only) =================
428
+ {
429
+ 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"}']);
430
+ let m0 = marks(); let r = post([]); let d = since(m0);
431
+ 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");
432
+ m0 = marks(); r = post(["-H", "Authorization: Bearer agent-held-dummy"]); d = since(m0);
433
+ 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");
434
+ m0 = marks(); r = A(["git", "-c", "http.extraHeader=Authorization: Bearer agent-held-dummy", "ls-remote", `${DEST}/synthetic/fixture.git`], { timeout: 15000 }); d = since(m0);
435
+ 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");
436
+ 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);
437
+ 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");
438
+ m0 = marks(); r = A([NODE, path.join(KA, "executor.mjs"), P("work-agent/own.sock"), P("work-agent"), PIN1, DEST], { timeout: 10000 });
439
+ 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");
440
+ 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);
441
+ 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");
442
+ const obsNow = observe("reconcile-bypass-check.json");
443
+ rec("BP-07", "alternate-route", "independent observer after all bypass attempts", "destination holds no branch without a matching executor attempt record", JSON.stringify(obsNow.destinationBranchesWithNoConsumedAttempt), obsNow.destinationBranchesWithNoConsumedAttempt.length === 0 ? "PASS" : "FAIL");
444
+ }
445
+
446
+ // ================= Gate D: network policy (declared default-deny for the agent identity) =================
447
+ const connUrl = `http://127.0.0.1:${connPort}/hosted-connector`;
448
+ const tryNet = (u) => A(["curl", "-s", "-m", "3", "-o", "/dev/null", "-w", "%{http_code}", u]);
449
+ const hits = () => fs.readFileSync(CONNLOG, "utf8").trim().split("\n").filter(Boolean).length;
450
+ let h0 = hits(); const ctl = tryNet(connUrl); await sleep(300);
451
+ 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");
452
+ const kCtl = tryNet(ready1.baseUrl + "/.well-known/strix-authority-keys.json");
453
+ rec("NP-00", "network", "POSITIVE CONTROL (no policy yet): agent reaches the kernel's public key endpoint", "reachable without the policy", `http=${kCtl.stdout.trim()}`, kCtl.stdout.trim() === "200" ? "PASS" : "BLOCKED");
454
+ const ipt = sh("iptables", ["-I", "OUTPUT", "1", "-m", "owner", "--uid-owner", "p2agent", "-j", "REJECT"]);
455
+ const ipt6 = sh("ip6tables", ["-I", "OUTPUT", "1", "-m", "owner", "--uid-owner", "p2agent", "-j", "REJECT"]);
456
+ if (ipt.status !== 0) rec("NP-02", "network", "install default-deny egress rule for agent identity", "rule installed", (ipt.stderr || "").trim(), "BLOCKED");
457
+ else {
458
+ 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);
459
+ 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");
460
+ 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");
461
+ rec("NP-04", "network", "agent to external HTTPS host after rule", "refused", `http=${r3b.stdout.trim() || "000"}`, (r3b.stdout.trim() || "000") === "000" ? "PASS" : "FAIL");
462
+ const rk = tryNet(ready1.baseUrl + "/.well-known/strix-authority-keys.json");
463
+ rec("NP-07", "network", "agent to the kernel after the rule", "refused", `http=${rk.stdout.trim() || "000"}`, (rk.stdout.trim() || "000") === "000" ? "PASS" : "FAIL");
464
+ const agentStill = as("p2agent", [NODE, path.join(L, "agent-client.mjs"), agentSock, "list"], { groups: false });
465
+ 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");
466
+ const counters = sh("iptables", ["-nvL", "OUTPUT", "--line-numbers"]).stdout; fs.writeFileSync(P("iptables-counters.txt"), counters);
467
+ 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");
468
+ }
469
+ sh("iptables", ["-D", "OUTPUT", "-m", "owner", "--uid-owner", "p2agent", "-j", "REJECT"]); sh("ip6tables", ["-D", "OUTPUT", "-m", "owner", "--uid-owner", "p2agent", "-j", "REJECT"]);
470
+
471
+
472
+ // ================= Phase 4B-2: isolated signing provider =================
473
+ const procEnvOf = (pat) => fs.readdirSync("/proc").filter((d) => /^\d+$/.test(d)).filter((d) => { try { return fs.readFileSync(`/proc/${d}/environ`, "utf8").includes(pat); } catch { return false; } });
474
+ const sp_kernelPids = procEnvOf("STRIX_DEV_KERNEL_DIR=" + K1.dir);
475
+ const sp_keyB64 = j(fs.readFileSync(P("sign-keys/keys/" + KID1 + ".json"), "utf8")).pkcs8;
476
+ const sp_spPid = pid("p2sign", "signing-provider.mjs.*sign-keys .*sp1.sock") ?? pid("p2sign", "sp1.sock");
477
+ // SP-01 the kernel holds no authority private key
478
+ const sp4Env = sp_kernelPids.map((d) => fs.readFileSync(`/proc/${d}/environ`, "utf8"));
479
+ const leakInTree = sh("grep", ["-rlF", "-e", sp_keyB64, W, "--exclude-dir=sign-keys", "--exclude-dir=sign-keys2"]).stdout.trim();
480
+ rec("SP-01", "signing-provider", "kernel process environment / argv / work tree contain the provider's private key; kernel is launched in isolated-provider mode (SP-04/SP-06 prove the provider is actually the signer)", "kernel env has no authority private key and declares isolated-provider mode; the key bytes appear nowhere outside the provider keystore", JSON.stringify({ sp_kernelPids: sp_kernelPids.length, privateKeyEnv: sp4Env.some((e) => /STRIX_AUTHORITY_SIGNING_PRIVATE_KEY=/.test(e)), mode: sp4Env.some((e) => e.includes("STRIX_DEV_KERNEL_SIGNING_PROVIDER_SOCKET=")), keyInEnv: sp4Env.some((e) => e.includes(sp_keyB64)), keyOutsideKeystore: leakInTree || null, pinned: ready1.pinnedAuthorityKey.custody }), sp_kernelPids.length > 0 && !sp4Env.some((e) => /STRIX_AUTHORITY_SIGNING_PRIVATE_KEY=/.test(e) || e.includes(sp_keyB64)) && sp4Env.some((e) => e.includes("STRIX_DEV_KERNEL_SIGNING_PROVIDER_SOCKET=")) && !leakInTree ? "PASS" : "FAIL");
481
+ // SP-02 no other identity can reach the key or the signing socket
482
+ const sockClient = `const n=require('net');const c=n.connect(process.argv[1]);c.on('error',e=>console.log('ERR:'+e.code));c.on('connect',()=>c.write(JSON.stringify({op:'public-keys'})+'\\n'));c.on('data',d=>{console.log('REPLY:'+d.toString().slice(0,40));c.destroy()})`;
483
+ const sp_denials = [];
484
+ for (const u of ["p2agent", "p2proxy", "p2exec", "p2auth", "p2approver", "p2dest", "p2obs", "p2apr1", "p2apr2", "p2apr3"]) {
485
+ const readKey = as(u, ["cat", P("sign-keys/keys/" + KID1 + ".json")]);
486
+ const list = as(u, ["ls", P("sign-keys")]);
487
+ const conn = as(u, [NODE, "-e", sockClient, P("sock-sign/sp1.sock")]);
488
+ const penv = sp_spPid ? as(u, ["cat", `/proc/${sp_spPid}/environ`]) : { status: 1 };
489
+ const pmem = sp_spPid ? as(u, ["head", "-c", "16", `/proc/${sp_spPid}/mem`]) : { status: 1 };
490
+ const ok = readKey.status !== 0 && list.status !== 0 && /^ERR:/.test(conn.stdout.trim()) && penv.status !== 0 && pmem.status !== 0;
491
+ sp_denials.push({ u, ok, conn: conn.stdout.trim().slice(0, 30) });
492
+ }
493
+ rec("SP-02", "signing-provider", "every non-provider identity (agent, proxy, executor, broker, approvers x4, destination, observer) tries: read keystore, list keystore dir, connect to the signing socket, read provider /proc environ and memory", "all refused by the OS for every identity", JSON.stringify(sp_denials.map((d) => `${d.u}:${d.ok ? "denied" : "REACHED"}`)), sp_spPid && sp_denials.every((d) => d.ok) ? "PASS" : "FAIL");
494
+ // SP-03 the provider interface has no key-export path and is not a generic signing oracle
495
+ const spCall = (sockFile, req) => j(sh(NODE, ["-e", `const n=require('net');const c=n.connect(process.argv[1]);let b='';c.on('connect',()=>c.write(${JSON.stringify(JSON.stringify(req))}+'\\n'));c.on('data',d=>b+=d);c.on('end',()=>console.log(b.trim()));c.on('error',e=>console.log(JSON.stringify({sockErr:e.code})))`, P(sockFile)]).stdout);
496
+ const sp_probes = [["export", { op: "export", kid: KID1 }], ["get-key", { op: "get-private-key", kid: KID1 }], ["generate", { op: "generate", kid: "evil" }], ["arbitrary-bytes", { op: "sign", kid: KID1, message: Buffer.from("not an authority artifact").toString("base64") }], ["wrong-issuer", { op: "sign", kid: KID1, message: Buffer.from(JSON.stringify({ schemaVersion: "strix-execution-authority-v1", issuer: "https://evil.test", signingKeyId: KID1 })).toString("base64") }], ["unknown-kid", { op: "sign", kid: "nope", message: Buffer.from("{}").toString("base64") }]];
497
+ const sp_probeRes = sp_probes.map(([n, r]) => [n, spCall("sock-sign/sp1.sock", r)]);
498
+ const sp_pk = spCall("sock-sign/sp1.sock", { op: "public-keys" });
499
+ const spRefused = sp_probeRes.every(([, r]) => r && r.ok === false);
500
+ const noPrivate = !JSON.stringify([sp_probeRes, sp_pk]).includes(sp_keyB64) && !JSON.stringify(sp_pk).includes("pkcs8");
501
+ rec("SP-03", "signing-provider", "root client asks the provider to export / get the private key / generate a key / sign arbitrary bytes / sign for another issuer / sign for an unknown kid; public-keys output inspected", "every non-sign operation refused; no response contains private material; sign is purpose-gated", JSON.stringify({ sp_probes: sp_probeRes.map(([n, r]) => `${n}:${r?.error ?? "OK?!"}`), publicKeys: (sp_pk?.keys ?? []).map((k) => k.kid + ":" + k.status), noPrivateMaterial: noPrivate }), spRefused && noPrivate && sp_pk?.keys?.[0]?.x === spKey1.x ? "PASS" : "FAIL");
502
+ // SP-04 a real kernel grant is signed by the provider's key and verifies under the DECLARED public key
503
+ const gSp = await obtain(A_("signing-provider-grant"), "spg");
504
+ const spPub = crypto.createPublicKey({ key: { kty: "OKP", crv: "Ed25519", x: ready1.pinnedAuthorityKey.x }, format: "jwk" });
505
+ const gVerified = crypto.verify(null, Buffer.from(sdk.canonicalJson(gSp.payload), "utf8"), spPub, Buffer.from(gSp.signature, "base64url"));
506
+ rec("SP-04", "signing-provider", "real kernel grant (APPROVAL_REQUIRED -> 3 real approvers -> GRANTED) inspected", "payload.signingKeyId is the provider key; signature verifies under the kernel's DECLARED public key, which equals the provider's published key", JSON.stringify({ kid: gSp.payload.signingKeyId, declaredEqualsProvider: ready1.pinnedAuthorityKey.x === spKey1.x, signatureVerifies: gVerified }), gSp.payload.signingKeyId === KID1 && gVerified && ready1.pinnedAuthorityKey.x === spKey1.x ? "PASS" : "FAIL");
507
+ // SP-05 concurrent signing: 6 different proposals at once
508
+ const sp_cc = await Promise.allSettled(Array.from({ length: 6 }, (_, i) => obtain(A_("spc-" + i), "spc" + i)));
509
+ const sp_okc = sp_cc.filter((r) => r.status === "fulfilled" && crypto.verify(null, Buffer.from(sdk.canonicalJson(r.value.payload), "utf8"), spPub, Buffer.from(r.value.signature, "base64url"))).length;
510
+ rec("SP-05", "signing-provider", "6 grants requested and approved concurrently, each signed through the provider", "all 6 signed and verified under the declared key", `verified=${sp_okc}/6` + sp_cc.filter((r) => r.status === "rejected").map((r) => " " + String(r.reason).slice(0, 80)).join(""), sp_okc === 6 ? "PASS" : "FAIL");
511
+ // SP-06 provider unavailable -> kernel fails closed (503), nothing is signed, no fallback key exists; then recovers
512
+ sh("pkill", ["-u", "p2sign", "-f", "sp1.sock"]); await sleep(500);
513
+ const pSt = proposalOf(A_("provider-down"), "spd");
514
+ const evDown = await clientReq.evaluate(pSt, { minimumApprovals: 1 }).then((r) => ({ status: r.status }), (e) => ({ err: String(e.code ?? e.message).slice(0, 80) }));
515
+ const downFails = evDown.err !== undefined || evDown.status === "APPROVAL_REQUIRED";
516
+ let grantedDown = false;
517
+ if (evDown.status === "APPROVAL_REQUIRED") { try { const ev0 = await clientReq.evaluate(pSt, { minimumApprovals: 1 }); grantedDown = ev0.status === "GRANTED"; } catch { /* expected: signing unavailable once approved */ } }
518
+ startProvider("sign-keys", "sock-sign/sp1.sock"); await sleep(900);
519
+ const evUp = await clientReq.evaluate(proposalOf(A_("provider-up"), "spu"), { minimumApprovals: 1 }).then((r) => r.status, (e) => "ERR:" + e.message);
520
+ rec("SP-06", "signing-provider", "signing provider killed; kernel asked for authority; provider restarted", "no grant issued while the provider is down (fail closed, no environment-key fallback); service resumes after restart", JSON.stringify({ whileDown: evDown, grantedWhileDown: grantedDown, afterRestart: evUp }), !grantedDown && downFails && (evUp === "APPROVAL_REQUIRED" || evUp === "GRANTED") ? "PASS" : "FAIL");
521
+ // SP-07 provider key revoked at the provider -> no further grants; a pinned verifier still trusts earlier grants (they verify)
522
+ const gOld = await obtain(A_("pre-revocation"), "spr");
523
+ as("p2sign", [NODE, SP, "revoke", "--dir", P("sign-keys"), "--kid", KID1]);
524
+ const sp_revoked = await (async () => { try { const pr = proposalOf(A_("post-revocation"), "spo"); const e1 = await clientReq.evaluate(pr, { minimumApprovals: 1 }); if (e1.status === "APPROVAL_REQUIRED") { await runPlan(e1.strixDecisionId, sdk.canonicalSha256(A_("post-revocation")), "full"); const e2 = await clientReq.evaluate(pr, { minimumApprovals: 1 }); return { status: e2.status }; } return { status: e1.status }; } catch (e) { return { err: String(e.code ?? e.message).slice(0, 100) }; } })();
525
+ const earlierStillVerifies = crypto.verify(null, Buffer.from(sdk.canonicalJson(gOld.payload), "utf8"), spPub, Buffer.from(gOld.signature, "base64url"));
526
+ rec("SP-07", "signing-provider", "provider key revoked at the provider (operator CLI); kernel asked for a new grant", "no new grant is issued under the sp_revoked key; a grant signed before revocation still verifies under its key (revocation of a key is a kernel/verifier policy, not retroactive forgery)", JSON.stringify({ afterRevocation: sp_revoked, earlierGrantVerifies: earlierStillVerifies }), sp_revoked.status !== "GRANTED" && earlierStillVerifies ? "PASS" : "FAIL");
527
+ // SP-08 declared evidence limits
528
+ rec("SP-08", "signing-provider", "evidence scope declared", "dev provider: file-held key, same host, no HSM/KMS, no attestation, harness runs the kernel as root; does NOT prove production key custody, non-root kernel isolation (4B-3) or kernel memory secrecy", "declared in 4B2-COMPATIBILITY-AND-LIMITATIONS.md", "PASS");
529
+
530
+
531
+ // ================= Phase 4B-3: non-root service identities, least privilege =================
532
+ const uidOf = (d) => { try { return Number(/^Uid:\s+(\d+)/m.exec(fs.readFileSync(`/proc/${d}/status`, "utf8"))[1]); } catch { return null; } };
533
+ const svcUsers = { kernel: "p2kernel", "signing-provider": "p2sign", broker: "p2auth", executor: "p2exec", "proxy-service": "p2proxy", destination: "p2dest" };
534
+ const uidReport = {};
535
+ for (const [name, u] of Object.entries(svcUsers)) { const uidNum = Number(sh("id", ["-u", u]).stdout.trim()); const pids = sh("pgrep", ["-u", u]).stdout.trim().split("\n").filter(Boolean); uidReport[name] = { expectedUid: uidNum, processes: pids.length, allNonRoot: pids.length > 0 && pids.every((d) => { const x = uidOf(d); return x === uidNum && x !== 0; }) }; }
536
+ const k1uids = sp_kernelPids.map(uidOf);
537
+ rec("LP-01", "least-privilege", "every service of the real-kernel topology (kernel, signing provider, broker, executor, proxy service, destination) inspected in /proc", "each runs under its own dedicated non-root uid; the kernel is no longer root", JSON.stringify({ ...uidReport, kernelProcessUids: [...new Set(k1uids)] }), Object.values(uidReport).every((r) => r.allNonRoot) && k1uids.length > 0 && k1uids.every((x) => x !== 0 && x === uidReport.kernel.expectedUid) ? "PASS" : "FAIL");
538
+ // LP-02 socket + filesystem permissions of the signing path
539
+ const st = (f) => { const r = sh("stat", ["-c", "%a %U:%G", f]).stdout.trim(); return r; };
540
+ const grpMembers = sh("getent", ["group", "p2signc"]).stdout.trim().split(":")[3]?.split(",").filter(Boolean).sort() ?? [];
541
+ const permReport = { socket: st(P("sock-sign/sp1.sock")), keystore: st(P("sign-keys")), keyfile: st(P("sign-keys/keys/" + KID1 + ".json")), signGroupMembers: grpMembers };
542
+ rec("LP-02", "least-privilege", "signing socket, keystore directory and key file permissions; membership of the signing-client group", "socket 660 owned by the provider with group p2signc; keystore 700 and key file 600 owned by the provider; group contains exactly the kernel and the provider", JSON.stringify(permReport), /^660 p2sign:p2signc$/.test(permReport.socket) && /^700 p2sign:/.test(permReport.keystore) && /^600 p2sign:/.test(permReport.keyfile) && JSON.stringify(grpMembers) === JSON.stringify(["p2kernel", "p2sign"]) ? "PASS" : "FAIL");
543
+ // LP-03 the kernel identity: may USE the signing socket, may not reach the key, the provider process, or anyone else's secrets
544
+ const kern = (argv, o = {}) => as("p2kernel", argv, o);
545
+ const kernProbe = {
546
+ connectsToSocket: /^REPLY:/.test(kern([NODE, "-e", sockClient, P("sock-sign/sp1.sock")]).stdout.trim()),
547
+ readsKeyfile: kern(["cat", P("sign-keys/keys/" + KID1 + ".json")]).status === 0,
548
+ listsKeystore: kern(["ls", P("sign-keys")]).status === 0,
549
+ readsProviderEnviron: sp_spPid ? kern(["cat", `/proc/${sp_spPid}/environ`]).status === 0 : null,
550
+ readsProviderMem: sp_spPid ? kern(["head", "-c", "16", `/proc/${sp_spPid}/mem`]).status === 0 : null,
551
+ readsProviderFds: sp_spPid ? kern(["ls", `/proc/${sp_spPid}/fd`]).status === 0 : null,
552
+ writesKeystore: kern(["sh", "-c", `echo x > ${P("sign-keys/keys/evil.json")}`]).status === 0,
553
+ readsExecutorCred: kern(["cat", P("cred-exec/token")]).status === 0,
554
+ readsObserverCred: kern(["cat", P("cred-obs/token")]).status === 0,
555
+ readsBrokerState: kern(["cat", P("st-auth/broker-log.jsonl")]).status === 0 && kern(["ls", P("st-auth")]).stdout.includes("grants"),
556
+ readsApproverKeys: APRS.some((a) => kern(["cat", P("apr-" + a.name + "/private.key")]).status === 0),
557
+ readsProxyStore: kern(["ls", P("st-proxy")]).status === 0 && kern(["find", P("st-proxy"), "-name", "private*"]).stdout.trim() !== "",
558
+ readsExecutorProcEnv: XPID ? kern(["cat", `/proc/${XPID}/environ`]).status === 0 : null,
559
+ };
560
+ rec("LP-03", "least-privilege", "kernel identity (p2kernel, non-root) attempts: use the signing socket (needed), read key file, list keystore, read provider environ/mem/fds, write the keystore, read executor/observer credentials, broker state, approver private keys, proxy store, executor environ", "socket use allowed; EVERYTHING else refused", JSON.stringify(kernProbe), kernProbe.connectsToSocket && Object.entries(kernProbe).filter(([k]) => k !== "connectsToSocket").every(([, v]) => v === false || v === null) ? "PASS" : "FAIL");
561
+ // LP-04 unauthorized privilege escalation: every unprivileged identity
562
+ const escUsers = ["p2agent", "p2proxy", "p2exec", "p2auth", "p2approver", "p2dest", "p2obs", "p2kernel", "p2apr1", "p2apr2", "p2apr3"];
563
+ const esc = [];
564
+ for (const u of escUsers) {
565
+ const capEff = (as(u, ["sh", "-c", "grep -E '^CapEff' /proc/self/status"]).stdout.match(/CapEff:\s+(\w+)/) ?? [])[1];
566
+ const sudoR = as(u, ["sudo", "-n", "true"]);
567
+ const suR = as(u, ["sh", "-c", "su -s /bin/sh p2sign -c id </dev/null"]);
568
+ const setuidR = as(u, ["setpriv", "--reuid", "p2sign", "--regid", "p2sign", "--clear-groups", "id"]);
569
+ const killProv = sp_spPid ? as(u, ["kill", "-0", sp_spPid]) : { status: 1 };
570
+ const chmodKs = as(u, ["chmod", "755", P("sign-keys")]);
571
+ const chownKs = as(u, ["chown", u, P("sign-keys")]);
572
+ const squat = as(u, ["sh", "-c", `rm -f ${P("sock-sign/sp1.sock")} 2>/dev/null; echo squat > ${P("sock-sign/sp9.sock")}`]);
573
+ const ok = /^0+$/.test(capEff ?? "x") && sudoR.status !== 0 && suR.status !== 0 && setuidR.status !== 0 && killProv.status !== 0 && chmodKs.status !== 0 && chownKs.status !== 0 && squat.status !== 0;
574
+ esc.push({ u, ok, capEff, sudo: sudoR.status, su: suR.status, setuid: setuidR.status, killProvider: killProv.status, chmod: chmodKs.status, chown: chownKs.status, squat: squat.status });
575
+ }
576
+ rec("LP-04", "least-privilege", "every unprivileged identity tries: effective capabilities, sudo, su to the provider uid, setuid-switch to the provider uid, signal the provider process, chmod/chown the keystore, delete/replace the signing socket path", "no capabilities; every escalation and tampering attempt refused (the provider may of course signal itself)", JSON.stringify(esc.map((e) => `${e.u}:${e.ok ? "denied" : "REACHED " + JSON.stringify(e)}`)), esc.every((e) => e.ok) ? "PASS" : "FAIL");
577
+ const suid = sh("sh", ["-c", "find / -xdev -perm -4000 -type f 2>/dev/null | head -30"]).stdout.trim().split("\n").filter(Boolean);
578
+ fs.writeFileSync(P("logs/setuid-binaries.txt"), suid.join("\n"));
579
+ // LP-05 service restart: the provider is restarted as its own user; permissions and kernel signing survive; socket path cannot be taken over
580
+ sh("pkill", ["-u", "p2sign", "-f", "sp1.sock"]); await sleep(500);
581
+ const squatWhileDown = as("p2agent", [NODE, "-e", `const n=require('net');n.createServer().listen('${P("sock-sign/sp1.sock")}',()=>console.log('BOUND'));setTimeout(()=>process.exit(),800)`], { groups: false });
582
+ startProvider("sign-keys", "sock-sign/sp1.sock"); await sleep(1000);
583
+ const spPidAfter = pid("p2sign", "sp1.sock");
584
+ const afterReport = { squatByAgentWhileDown: /BOUND/.test(squatWhileDown.stdout), providerUidAfter: spPidAfter ? uidOf(spPidAfter) : null, socket: st(P("sock-sign/sp1.sock")), keystore: st(P("sign-keys")) };
585
+ const evR = await clientReq.evaluate(proposalOf(A_("after-restart"), "lpr"), { minimumApprovals: 1 }).then((r) => r.status, (e) => "ERR:" + String(e.code ?? e.message).slice(0, 60));
586
+ const lpKeyRevoked = j(fs.readFileSync(P("sign-keys/keys/" + KID1 + ".json"), "utf8")).status; // SP-07 revoked it earlier; restart must not resurrect it
587
+ rec("LP-05", "least-privilege", "signing provider killed and restarted; an unprivileged identity tries to bind the signing socket path while it is down; permissions and key status re-checked", "path not takeable by another identity; provider returns under its own non-root uid with the same 660/700 permissions; a revoked key is NOT resurrected by restart (no new grant while only revoked key remains)", JSON.stringify({ ...afterReport, keyStatus: lpKeyRevoked, evaluateAfterRestart: evR }), !afterReport.squatByAgentWhileDown && afterReport.providerUidAfter === Number(sh("id", ["-u", "p2sign"]).stdout.trim()) && /^660 p2sign:p2signc$/.test(afterReport.socket) && /^700 p2sign:/.test(afterReport.keystore) && lpKeyRevoked === "revoked" && evR !== "GRANTED" ? "PASS" : "FAIL");
588
+ // LP-06 the injection seam, observed on the running kernel: its keyring is in provider mode and a REQUIRE flag is honoured by the real process
589
+ const kreq = sp_kernelPids.length ? fs.readFileSync(`/proc/${sp_kernelPids[0]}/environ`, "utf8").includes("STRIX_DEV_KERNEL_SIGNING_PROVIDER_SOCKET=") : false;
590
+ rec("LP-06", "least-privilege", "kernel launched with a provider socket and no private key; unit suite proves deps.signer injection is refused in provider mode and REQUIRE_ISOLATED_SIGNING refuses env-key keyrings", "running kernel is provider-mode; bypass-by-injection is covered by apps/strix-console/tests/authority/signing-provider.test.ts (5 seam tests, red-proven)", JSON.stringify({ kernelProviderMode: kreq }), kreq ? "PASS" : "FAIL");
591
+ rec("LP-07", "least-privilege", "residual privileges and evidence scope declared", "root (the harness/operator) can still read every secret, start/stop services and install firewall rules; the kernel runs non-root but shares a host, kernel (OS) and Postgres role with the harness; a compromised OS kernel, root, or the DB role is out of scope", "declared in 4B3-SECURITY-BOUNDARY.md; setuid inventory in results/setuid-binaries.txt (" + suid.length + " entries)", "PASS");
592
+
593
+ // ================= Evidence: independent verification =================
594
+ const obs2 = observe("reconcile-final.json");
595
+ const storeDir = P("st-proxy"); const find = (n) => sh("find", [storeDir, "-name", n]).stdout.trim().split("\n").filter(Boolean);
596
+ const receipts = find("receipts.jsonl")[0], jwk = find("public-jwk.json")[0];
597
+ const verBin = path.join(NM, "verifier/bin/verify.mjs");
598
+ let chain = { status: "BLOCKED" };
599
+ 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) };
600
+ fs.writeFileSync(P("logs/verifier-chain.txt"), v.stdout + v.stderr);
601
+ 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");
602
+ const vt = sh(NODE, [verBin, "chain", tampered, "--jwks", jwk], { timeout: 30000 }); chain.tamperedExit = vt.status; }
603
+ 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"));
604
+ const bad = obs2.attempts.filter((a) => a.verdict.startsWith("INCONSISTENT") || a.outcomeSignatureValid === false);
605
+ 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.destinationBranchesWithNoConsumedAttempt }), bad.length === 0 && obs2.destinationBranchesWithNoConsumedAttempt.length === 0 ? "PASS" : "FAIL");
606
+ const evIds = [granted1 && ks1?.strixDecisionId, global.__refusalEvidence].filter(Boolean);
607
+ const evRes = []; for (const id of evIds) evRes.push([id, (await client1.verify(id).catch((e) => ({ verificationStatus: "ERR:" + e.message }))).verificationStatus]);
608
+ rec("EV-04", "evidence", "kernel-signed evidence (the consumed grant's outcome record and a signed refusal) verified by the PUBLISHED verifier via the SDK", "VERIFIED for each", JSON.stringify(evRes), evRes.length === 2 && evRes.every(([, v]) => v === "VERIFIED") ? "PASS" : "FAIL");
609
+ const dl = destLines().filter((x) => x.method === "POST");
610
+ 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");
611
+
612
+ // ---------- write results ----------
613
+ for (const [src, dst] of [[P("logs/setuid-binaries.txt"), "setuid-binaries.txt"], [P("logs/destination-requests.jsonl"), "destination-requests.jsonl"], [P("logs/connector-standin-requests.jsonl"), "connector-standin-requests.jsonl"], [P("st-auth/broker-log.jsonl"), "broker-log.jsonl"], [P("kernel-one/ready.json"), "kernel-ready.json"], [P("kernel-one/wire.jsonl"), "kernel-wire.jsonl"], [P("kernel-two/ready.json"), "kernel-two-ready.json"], [P("pinned-trust-1.json"), "pinned-trust-1.json"], [P("st-exec2/attempts.jsonl"), "executor2-attempts.jsonl"], [P("st-exec3/attempts.jsonl"), "executor3-attempts.jsonl"], [P("logs/reconcile-no-observation.json"), "reconcile-no-observation.json"], [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("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>"));
614
+ fs.writeFileSync(path.join(RESULTS, "versions.json"), JSON.stringify(versions, null, 1));
615
+ fs.writeFileSync(path.join(RESULTS, "matrix.json"), JSON.stringify(matrix, null, 1));
616
+ const leakFinal = sh("grep", ["-rl", "-e", EXEC_TOKEN, "-e", OBS_TOKEN, RESULTS]).stdout.trim();
617
+ if (leakFinal) console.log("WARNING: dummy credential found in results: " + leakFinal);
618
+ // ---------- teardown ----------
619
+ for (const k of [K1, K2]) fs.writeFileSync(path.join(k.dir, "stop"), "");
620
+ await sleep(1500); for (const k of [K1, K2]) { try { process.kill(-k.p.pid, "SIGKILL"); } catch {} }
621
+ for (const u of USERS) sh("pkill", ["-9", "-u", u]);
622
+ await sleep(500);
623
+ for (const u of USERS) { sh("userdel", [u]); sh("groupdel", [u]); } sh("groupdel", ["p2appr-shared"]); sh("groupdel", ["p2signc"]);
624
+ fs.rmSync(W, { recursive: true, force: true });
625
+ const c = (d) => matrix.filter((x) => x.disposition === d).length;
626
+ console.log(`\nPASS=${c("PASS")} FAIL=${c("FAIL")} BLOCKED=${c("BLOCKED")} OPEN=${c("OPEN")}`);
627
+ process.exit(c("FAIL") ? 1 : 0);