/** * The mesh plays out the STATIC-KEY half of model-access for OpenAI, end to end (novox/hq ADR 0050). * Where the Anthropic bed proves the refreshable-grant shape, this proves the other shape ADR 0050 * defines — and the ADR 0054 branch where a static-key vendor exposes no usage and records nothing: * * the operator sets one API key on the licence (`licence key`, read from a file, never a CLI arg) -> * the mesh seals it to the consumer holder (the generic static-key adapter) -> the host unseals it * with the node's private key and mounts it at the module's secret path -> the consumer runtime * writes it where an OpenAI/Codex client reads it (OPENAI_API_KEY env + the Codex auth.json). * * The property proven: the key the consumer writes equals the key the operator set, carried through the * ordinary sealed-delivery path — with NO manager, NO refresh, NO access/refresh split, NO usage. The * whole of OpenAI's integration in the control plane is one registry line (vendor -> static-key). * * MESH_LAB_HOST_BINARY=.../mesh-host MESH_LAB_BUNDLE=.../examples/foundation-first-node.lock * Build the consumer runtime image into the local daemon first: * scripts/build-module-runtime.sh openai-consumer /tmp/openai-consumer.tar */ import { test, before, after } from "node:test"; import assert from "node:assert/strict"; import { existsSync, readFileSync } from "node:fs"; import { loadScenario } from "../../src/declaration/parse.ts"; import { raise } from "../../src/lifecycle/raise.ts"; import { destroy, exec } from "../../src/lifecycle/operate.ts"; import { hostBinaryPath, HOST_PATH } from "../../src/lifecycle/place.ts"; import { labIsUsable, destroyAll, foundationBundle, onTheMachine } from "./harness.ts"; import type { HeldImage } from "../../src/pinning.ts"; const capability = await labIsUsable(); const binary = hostBinaryPath(); const bundle = process.env["MESH_LAB_BUNDLE"] ?? ""; const skip = !capability.usable ? `lab not usable: ${capability.why}` : !binary || !existsSync(binary) ? "MESH_LAB_HOST_BINARY is not set to a built mesh-host" : !bundle || !existsSync(bundle) ? "MESH_LAB_BUNDLE is not set to a foundation bundle (mesh-host examples/)" : false; const SCENARIO = "openai-bed"; const MACHINE = "anchor"; // The API key the flow moves. The whole test is that the key the consumer writes equals this one, // carried through the sealed delivery path unchanged. A fake value shaped like a real key. const API_KEY = "sk-lab-openai-static-key-value-for-the-bed-only"; let instanceId = ""; let held: HeldImage[] = []; function quote(s: string): string { return `'${s.replaceAll("'", `'\\''`)}'`; } async function on(command: string, timeoutMs?: number): Promise<{ out: string; ok: boolean }> { const { stdout } = await exec(instanceId, MACHINE, [ "sh", "-c", `exec 2>&1\n${command}\necho "__exit=$?"`, ], timeoutMs); const marker = stdout.lastIndexOf("__exit="); if (marker < 0) return { out: stdout, ok: false }; return { out: stdout.slice(0, marker), ok: stdout.slice(marker + 7).trim() === "0" }; } async function must(command: string, timeoutMs?: number): Promise { const { out, ok } = await on(command, timeoutMs); if (!ok) throw new Error(`${MACHINE}: ${command}\n${out}`); return out; } async function mesh(command: string, timeoutMs?: number): Promise { return must(`docker exec mesh-controller /mesh-controller ${command}`, timeoutMs); } async function meshTry(command: string): Promise<{ out: string; ok: boolean }> { return on(`docker exec mesh-controller /mesh-controller ${command}`); } /** What a manifest's image reference becomes on the machine — ours by ID, everything else as written. */ function pinned(reference: string): string { return onTheMachine(reference, held); } function bundleFor(images: HeldImage[]): string { return foundationBundle(bundle, images); } function tokenFrom(said: string): string { const found = said.split("\n").map((l) => l.trim()).find((l) => l.length > 100 && !l.includes(" ")); assert.ok(found, `no token in:\n${said}`); return found; } /** The local image id the host pulled for a runtime, so the test can drive it deterministically. */ async function imageId(substr: string): Promise { const out = (await must(`docker images --no-trunc --format '{{.ID}} {{.Repository}}' | grep ${quote(substr)} | head -1`)).trim(); const id = out.split(/\s+/)[0] ?? ""; assert.ok(id.startsWith("sha256:") || id.length > 0, `no local image matched ${substr}:\n${out}`); return id; } async function settled(withinMs = 600_000): Promise { const until = Date.now() + withinMs; let last = ""; while (Date.now() < until) { const asked = await meshTry(`status --json`); if (asked.ok) { try { const state = JSON.parse(asked.out) as { wrong: { node: string; outcome: string }[]; waiting: { node: string }[]; reported: { node: string; outcome: string; current: boolean }[]; }; const bad = state.wrong.find((w) => w.node === MACHINE); if (bad) throw new Error(`${MACHINE} did not apply what it was sent: ${bad.outcome}\n${asked.out}`); const word = state.reported.find((r) => r.node === MACHINE); if (!state.waiting.some((w) => w.node === MACHINE) && word?.outcome === "applied" && word.current) return; last = asked.out; } catch (err) { if (err instanceof Error && err.message.includes("did not apply")) throw err; last = asked.out; } } await new Promise((r) => setTimeout(r, 5000)); } throw new Error(`${MACHINE} never caught up within ${Math.round(withinMs / 1000)}s. Last:\n${last}`); } before(async () => { if (skip) return; const raised = await raise(loadScenario(`scenarios/${SCENARIO}.yml`), { onProgress: (m) => console.log(`raise: ${m}`), }); instanceId = raised.instanceId; held = raised.images; await must(`cat > /tmp/foundation.lock <<'MESHBUNDLE'\n${bundleFor(raised.images)}\nMESHBUNDLE`); await must(`${HOST_PATH} apply /tmp/foundation.lock`, 600_000); const up = await must(`docker ps --format '{{.Names}}'`); for (const c of ["mesh-store", "mesh-broker", "mesh-controller"]) { assert.match(up, new RegExp(c), `the foundation did not raise ${c}:\n${up}`); } await mesh(`node add ${MACHINE}`); const token = tokenFrom(await mesh(`token issue --node ${MACHINE}`)); await must(`${HOST_PATH} enrol --token ${quote(token)}`); await must(`nohup ${HOST_PATH} run > /var/log/mesh-host.log 2>&1 & sleep 3`); }, { timeout: 1_800_000 }); after(async () => { if (instanceId) await destroy(instanceId); await destroyAll(`${SCENARIO}-`); }, { timeout: 600_000 }); test("a static-key model-access licence delivers the operator's API key to the consumer, unchanged", { skip, timeout: 1_500_000, }, async () => { const consumerImage = pinned("mesh-runtime-openai-consumer"); // --- the licence, a record with vendor openai (static-key) ------------------------------------- // No manager: a static-key licence has none (mesh-controller refuses `licence manager` on it). The // consumer is put on the licence BEFORE the key is set — the static-key adapter's Accept seals to the // CURRENT holders, so a holder must exist first, or the key would seal to nobody. await mesh(`licence add openai personal --serves '{"model":"gpt-model"}'`); await mesh(`licence use personal ${MACHINE} openai-consumer`); // The operator sets the static key. `licence key` reads it from a file (never a CLI arg) and seals it // to the holder; the plaintext is discarded by the control plane. Staged 0644 so distroless // mesh-controller can read the file (docker cp preserves the mode). await must(`printf %s ${quote(API_KEY)} > /tmp/openai-key && chmod 0644 /tmp/openai-key && docker cp /tmp/openai-key mesh-controller:/openai-key`); await mesh(`licence key personal --file /openai-key`); // --- deploy the consumer ----------------------------------------------------------------------- // Inline manifest mirroring the committed module.json: a model-access holder whose delivered key // arrives at its secret path. The scheduled apply container installs as present state (ADR 0053) and // its image is pulled at apply (schedule-pull); the test drives apply directly for a deterministic // flow rather than waiting on cron. const consumerManifest = JSON.stringify({ module: "openai-consumer", version: "1", requires: ["model-access"], binds: { "model-access": "/var/lib/openai-consumer/model.json" }, secrets: { "model-access": "/var/lib/openai-consumer/api-key" }, resources: [ { id: "state", type: "directory", path: "/var/lib/openai-consumer", mode: "0700" }, { id: "config", type: "directory", path: "/var/lib/openai-consumer/config", mode: "0700" }, { id: "apply", type: "container", name: "mesh-openai-consumer-apply", image: consumerImage, network: "host", schedule: "*/5 * * * *", args: ["run", "/app/modules/openai-consumer/dist/apply/index.js"], volumes: ["/var/lib/openai-consumer:/run/state"], env: { MESH_MODEL_ACCESS_SECRET_FILE: "/run/state/api-key", MESH_MODEL_ACCESS_BIND_FILE: "/run/state/model.json", MESH_OPENAI_ENV_FILE: "/run/state/config/openai.env", MESH_OPENAI_CREDENTIALS_FILE: "/run/state/config/auth.json", }, }, ], }); await must(`printf %s ${quote(consumerManifest)} > /tmp/openai-consumer.json && docker cp /tmp/openai-consumer.json mesh-controller:/openai-consumer.json`); await mesh(`module add /openai-consumer.json`); await mesh(`module issue openai-consumer --node ${MACHINE}`); await mesh(`assign ${MACHINE} openai-consumer`); await mesh(`push ${MACHINE}`); await settled(); // --- the host unsealed and mounted the key ----------------------------------------------------- let delivered = false; for (let i = 0; i < 20 && !delivered; i++) { delivered = (await on(`test -s /var/lib/openai-consumer/api-key`)).ok; if (!delivered) await new Promise((r) => setTimeout(r, 3000)); } assert.ok(delivered, "the sealed API key was never delivered to the consumer's secret path"); // The delivered key equals the operator's — sealed by the mesh, unsealed by the host, unchanged. The // control plane sealed it and never held it in the clear; here it is, in the clear, on the node the // licence was granted to. const mounted = (await must(`cat /var/lib/openai-consumer/api-key`)).trim(); assert.equal(mounted, API_KEY, "the host mounted a different key than the operator set"); // --- the consumer writes the credential -------------------------------------------------------- const consumerId = await imageId("openai-consumer"); await must( `docker run --rm --network host -v /var/lib/openai-consumer:/run/state ` + `-e MESH_MODEL_ACCESS_SECRET_FILE=/run/state/api-key ` + `-e MESH_MODEL_ACCESS_BIND_FILE=/run/state/model.json ` + `-e MESH_OPENAI_ENV_FILE=/run/state/config/openai.env ` + `-e MESH_OPENAI_CREDENTIALS_FILE=/run/state/config/auth.json ` + `${consumerId} run /app/modules/openai-consumer/dist/apply/index.js`, ); // Written where an OpenAI/Codex client reads it: the env file and the Codex auth.json, both the key. const env = await must(`cat /var/lib/openai-consumer/config/openai.env`); assert.match(env, new RegExp(`OPENAI_API_KEY=${API_KEY}`), `the env file does not carry the key:\n${env}`); const auth = await must(`cat /var/lib/openai-consumer/config/auth.json`); const parsed = JSON.parse(auth) as { OPENAI_API_KEY?: string }; assert.equal(parsed.OPENAI_API_KEY, API_KEY, `the Codex auth.json does not carry the key:\n${auth}`); });