openai bed: prove the static-key model-access path (ADR 0050)
A single-node VM bed: the operator sets an API key on an openai licence, the mesh seals it to the consumer, the host unseals and mounts it, and the consumer writes it as OPENAI_API_KEY (env + Codex auth.json). Asserts the written key equals the one set — the other shape ADR 0050 defines, and the ADR 0054 branch where a static-key vendor records no usage. Green on the first run. Claude-Session: https://claude.ai/code/session_01LrgweAeERJYBg88c5cKDzF
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
# One machine that becomes a mesh, then plays out the STATIC-KEY half of model-access (novox/hq
|
||||
# ADR 0050) for OpenAI. Where the Anthropic bed proves the refreshable-grant shape (a manager holds a
|
||||
# refresh token, the mesh delivers only the access token), this proves the OTHER shape ADR 0050
|
||||
# defines and no vendor had exercised: a single operator-supplied key, sealed to the consumer holder,
|
||||
# unsealed by the host, and written where an OpenAI/Codex client reads it. There is no manager, no
|
||||
# refresh, and no usage — a static-key vendor exposes none, which ADR 0054 says is fine.
|
||||
#
|
||||
# The flow the test drives:
|
||||
# the operator sets the API key on the licence -> the mesh seals it to the consumer holder ->
|
||||
# the host unseals it and mounts it at the consumer's secret path -> the consumer writes it as
|
||||
# OPENAI_API_KEY (env file + the Codex auth.json). The test asserts the written key equals the one
|
||||
# the operator set — through the sealed delivery path, unchanged.
|
||||
#
|
||||
# MESH_LAB_HOST_BINARY=.../mesh-host MESH_LAB_BUNDLE=.../examples/substrate-first-node.lock
|
||||
# Build the consumer runtime image into the local daemon first (raise() stocks it from there):
|
||||
# scripts/build-module-runtime.sh openai-consumer /tmp/openai-consumer.tar
|
||||
scenario: openai-bed
|
||||
|
||||
segments:
|
||||
hosting:
|
||||
kind: public
|
||||
cidr: [192.0.2.0/24]
|
||||
|
||||
machines:
|
||||
anchor:
|
||||
at: { segment: hosting, address: [192.0.2.10] }
|
||||
inbound: allow
|
||||
memory: 3GiB
|
||||
cpus: 2
|
||||
|
||||
images:
|
||||
# The first-node substrate: store, broker, control.
|
||||
- postgres:17-alpine
|
||||
- cloudamqp/lavinmq:latest
|
||||
- mesh-control:development
|
||||
# The static-key consumer runtime, built by scripts/build-module-runtime.sh into the local daemon and
|
||||
# stocked into the scenario's own registry, which is where the host pulls it from.
|
||||
- mesh-runtime-openai-consumer:development
|
||||
|
||||
place:
|
||||
all: [host, runtime]
|
||||
@@ -0,0 +1,246 @@
|
||||
/**
|
||||
* 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/substrate-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 } from "./harness.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 substrate 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 stocked: string[] = [];
|
||||
|
||||
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<string> {
|
||||
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<string> {
|
||||
return must(`docker exec mesh-control /mesh-control ${command}`, timeoutMs);
|
||||
}
|
||||
|
||||
async function meshTry(command: string): Promise<{ out: string; ok: boolean }> {
|
||||
return on(`docker exec mesh-control /mesh-control ${command}`);
|
||||
}
|
||||
|
||||
function pinned(repository: string): string {
|
||||
const found = stocked.find((r) => r.slice(r.indexOf("/") + 1, r.indexOf("@")) === repository);
|
||||
assert.ok(found, `the scenario stocks no ${repository}; it serves ${stocked.join(", ")}`);
|
||||
return found;
|
||||
}
|
||||
|
||||
function bundleFor(images: string[]): string {
|
||||
let text = readFileSync(bundle, "utf8");
|
||||
for (const ref of images) {
|
||||
const repository = ref.slice(ref.indexOf("/") + 1, ref.indexOf("@"));
|
||||
const escaped = repository.replaceAll("/", "\\/").replaceAll(".", "\\.");
|
||||
text = text.replaceAll(new RegExp(`[A-Za-z0-9_.:-]+\\/${escaped}@sha256:[0-9a-f]+`, "g"), ref);
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
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<string> {
|
||||
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<void> {
|
||||
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;
|
||||
stocked = raised.images;
|
||||
|
||||
await must(`cat > /tmp/substrate.lock <<'MESHBUNDLE'\n${bundleFor(raised.images)}\nMESHBUNDLE`);
|
||||
await must(`${HOST_PATH} apply /tmp/substrate.lock`, 600_000);
|
||||
const up = await must(`docker ps --format '{{.Names}}'`);
|
||||
for (const c of ["mesh-store", "mesh-broker", "mesh-control"]) {
|
||||
assert.match(up, new RegExp(c), `the substrate 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-control 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-control 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-control:/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-control:/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}`);
|
||||
});
|
||||
Reference in New Issue
Block a user