diff --git a/scenarios/minio-node.yml b/scenarios/minio-node.yml deleted file mode 100644 index 7163cf1..0000000 --- a/scenarios/minio-node.yml +++ /dev/null @@ -1,30 +0,0 @@ -# One machine that becomes a mesh and grants a consumer an S3 bucket from an assigned minio provider. -# -# The postgres bed proves the provider/consumer contract for a database; this proves it for object -# storage (novox/hq ADR 0052/0053), on a provider whose code drives the `mc` CLI (so the runtime image -# carries it): minio is assigned, a consumer that requires s3-bucket is assigned, and the mesh mints -# one secret key; minio's provisioner creates a bucket and a service account under the access key the -# mesh derived with the secret it minted, and the consumer reaches its bucket with only that. -scenario: minio-node - -segments: - hosting: - kind: public - cidr: [192.0.2.0/24] - -machines: - anchor: - at: { segment: hosting, address: [192.0.2.10] } - egress: true - inbound: allow - memory: 3GiB - cpus: 2 - -images: - - mesh-controller:development - # minio's runtime, built by scripts/build-module-runtime.sh minio (it carries mc), loaded onto - # the machine. - - mesh-runtime-minio:development - -place: - all: [host, runtime] diff --git a/scenarios/plex-node.yml b/scenarios/plex-node.yml deleted file mode 100644 index e2ffee2..0000000 --- a/scenarios/plex-node.yml +++ /dev/null @@ -1,30 +0,0 @@ -# One machine that becomes a mesh and then assigns itself plex's tool runtime. -# -# The audit-node bed proved an assigned *consumer* (novox/hq ADR 0048). This proves an assigned -# module that *serves tools* (ADR 0052): the same first-node foundation, plus plex's tool runtime on -# top. The node enrols itself, the mesh issues plex a broker account scoped to serve.plex.* and -# assigns it, the host runs the runtime container, and a caller invokes plex.plex_reachable over the -# mesh — proof the module runs its own code as its own process under its own scoped account. -scenario: plex-node - -segments: - hosting: - kind: public - cidr: [192.0.2.0/24] - -machines: - anchor: - at: { segment: hosting, address: [192.0.2.10] } - egress: true - inbound: allow - memory: 3GiB - cpus: 2 - -images: - - mesh-controller:development - # Plex's tool runtime, built by scripts/build-module-runtime.sh plex into the local daemon and - # loaded onto the machine, which holds it by its own image ID. - - mesh-runtime-plex:development - -place: - all: [host, runtime] diff --git a/scenarios/postgres-node.yml b/scenarios/postgres-node.yml deleted file mode 100644 index 3429b3e..0000000 --- a/scenarios/postgres-node.yml +++ /dev/null @@ -1,29 +0,0 @@ -# One machine that becomes a mesh and grants a consumer a database from an assigned postgres provider. -# -# The redis mesh-grant bed proves the whole provider/consumer contract for a cache; this proves it for -# a database (novox/hq ADR 0052/0053): postgres's runtime carries psql, its provisioner creates a role -# and database under the login the mesh derived with the password the mesh minted, and a consumer -# connects to its own database with only what the mesh delivered. -scenario: postgres-node - -segments: - hosting: - kind: public - cidr: [192.0.2.0/24] - -machines: - anchor: - at: { segment: hosting, address: [192.0.2.10] } - egress: true - inbound: allow - memory: 3GiB - cpus: 2 - -images: - - mesh-controller:development - # postgres's runtime, built by scripts/build-module-runtime.sh postgres (it carries psql), loaded - # onto the machine. - - mesh-runtime-postgres:development - -place: - all: [host, runtime] diff --git a/scenarios/redis-node.yml b/scenarios/redis-node.yml index 36df1c2..f18f1f8 100644 --- a/scenarios/redis-node.yml +++ b/scenarios/redis-node.yml @@ -1,6 +1,6 @@ # One machine that becomes a mesh and then assigns itself redis — a *provider* module. # -# plex-node proves an assigned module that serves tools (novox/hq ADR 0052). This proves the same +# A bed proving an assigned module that serves tools (novox/hq ADR 0052) once lived beside this; this proves the same # for a provider: redis's runtime runs its provisioner AND its tools as one process under one scoped # broker account. The provisioner emitting a lifecycle event is the thing 0052 fixes — before it, # the provisioner ran in a container with no broker and its emit could not fire. diff --git a/scenarios/sonarr-node.yml b/scenarios/sonarr-node.yml deleted file mode 100644 index 70dcbeb..0000000 --- a/scenarios/sonarr-node.yml +++ /dev/null @@ -1,27 +0,0 @@ -# One machine that becomes a mesh and assigns itself sonarr's tool runtime. -# -# plex-node proved a tools+events module that self-detects its token from a mounted config dir; this -# proves the same self-configuring pattern generalises to the Servarr family (novox/hq ADR 0052): -# sonarr's runtime detects its API key from the server's config.xml and serves sonarr's tools over a -# mesh-issued scoped account, with no live Sonarr to reach. -scenario: sonarr-node - -segments: - hosting: - kind: public - cidr: [192.0.2.0/24] - -machines: - anchor: - at: { segment: hosting, address: [192.0.2.10] } - egress: true - inbound: allow - memory: 3GiB - cpus: 2 - -images: - - mesh-controller:development - - mesh-runtime-sonarr:development - -place: - all: [host, runtime] diff --git a/test/beds-read-the-catalogue.test.ts b/test/beds-read-the-catalogue.test.ts index c6e0bad..932326b 100644 --- a/test/beds-read-the-catalogue.test.ts +++ b/test/beds-read-the-catalogue.test.ts @@ -54,12 +54,6 @@ const STILL_CARRIED: Record = { why: "DIFFERS: redis mints its own secret, baserow drops its route requirement, letta drops its ports" }, "lavinmq-bed.test.ts": { modules: ["lavinmq", "amqp-ping"], why: "BESIDE (lavinmq, with a bootstrap step and a data directory the catalogue has not got); DIFFERS (amqp-ping names its entrypoint)" }, - "assigned-grafana.test.ts": { modules: ["grafana"], why: "WEARING: the sidecar alone, no Grafana, no route" }, - "assigned-plex.test.ts": { modules: ["plex"], why: "WEARING: the sidecar alone, no Plex, the token in the environment" }, - "assigned-redis.test.ts": { modules: ["redis"], why: "WEARING: its own secret, a lab seal key in the environment" }, - "assigned-sonarr.test.ts": { modules: ["sonarr"], why: "WEARING: the sidecar alone against a forged config.xml" }, - "minio-grant-end-to-end.test.ts": { modules: ["minio"], why: "WEARING: a grant mechanism test, the root password by env-file" }, - "postgres-grant-end-to-end.test.ts": { modules: ["postgres"], why: "WEARING: a grant mechanism test, the superuser by env-file" }, "provider-uses-mesh-credential.test.ts": { modules: ["redis"], why: "WEARING: a credential mechanism test" }, "runtime-restart-on-config.test.ts": { modules: ["grafana"], why: "WEARING: a restart mechanism test" }, "route-forwarding.test.ts": { modules: ["route-proxy", "hello-web"], diff --git a/test/integration/assigned-grafana.test.ts b/test/integration/assigned-grafana.test.ts deleted file mode 100644 index 1d92897..0000000 --- a/test/integration/assigned-grafana.test.ts +++ /dev/null @@ -1,210 +0,0 @@ -/** - * The mesh assigns grafana's tool runtime, configured entirely by the assignment's settings — the - * ADR 0051 + 0052 case: config is the assignment's, delivered as a settings-merged file the runtime - * reads, not a credential baked into the manifest. - * - * plex/sonarr prove a runtime that self-detects its key from the app's own config. This proves the - * other half: the operator states grafana's URL and an API token as settings for this node, the - * control plane merges them into the module's mergeable config file, and the runtime reads that file - * at start, registers grafana's tools, and serves them under its scoped account. There is no live - * Grafana — that the serve queue is bound is the proof the settings reached the runtime and its - * tools loaded from them. - * - * MESH_LAB_HOST_BINARY=.../mesh-host MESH_LAB_BUNDLE=.../examples/foundation-first-node.lock - * scripts/build-module-runtime.sh grafana builds mesh-runtime-grafana:development into the local - * daemon, which scenarios/grafana-node.yml stocks — so no MESH_LAB_RUNTIME here; the host pulls it. - */ - -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 = "grafana-node"; -const MACHINE = "anchor"; - -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); -} - -/** 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; -} - -async function settled(withinMs = 480_000): Promise { - const until = Date.now() + withinMs; - let last = ""; - while (Date.now() < until) { - const asked = await on(`docker exec mesh-controller /mesh-controller 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("the mesh assigns grafana's runtime, configured by settings, and it serves its tools", { - skip, timeout: 900_000, -}, async () => { - // A grafana manifest with no credential in it: its runtime, and a mergeable config file the - // settings will fill. This is the whole point of ADR 0051 — the manifest carries defaults and - // structure, the assignment carries the URL and token. - const manifest = JSON.stringify({ - module: "grafana", - version: "1", - emits: ["module.grafana.alert.firing"], - "own-secrets": { broker: "/var/lib/mesh/grafana/broker" }, - resources: [ - { id: "mesh-state", type: "directory", path: "/var/lib/mesh/grafana", mode: "0700" }, - { id: "config", type: "file", path: "/var/lib/mesh/grafana/config.json", mode: "0600", content: "{}\n", merge: "json" }, - { - id: "runtime", type: "container", name: "mesh-grafana", image: pinned("mesh-runtime-grafana"), - network: "host", - volumes: [ - "/var/lib/mesh/grafana/broker:/run/secrets/broker:ro", - "/var/lib/mesh/grafana/config.json:/run/config/config.json:ro", - ], - env: { - MESH_BROKER_FILE: "/run/secrets/broker", - MESH_GRAFANA_CONFIG_FILE: "/run/config/config.json", - }, - }, - ], - }); - await must(`printf %s ${quote(manifest)} > /tmp/grafana.json && docker cp /tmp/grafana.json mesh-controller:/grafana.json`); - await mesh("module add /grafana.json"); - - // The operator states grafana's URL and API token as settings for this node — the config the - // runtime will read. Nothing about them is in the manifest. - const settings = JSON.stringify({ url: "http://127.0.0.1:3000", token: "lab-grafana-token" }); - await must(`printf %s ${quote(settings)} > /tmp/grafana-settings.json && docker cp /tmp/grafana-settings.json mesh-controller:/grafana-settings.json`); - await mesh(`settings set grafana /grafana-settings.json --node ${MACHINE}`); - - const issued = await mesh(`module issue grafana --node ${MACHINE}`); - assert.match(issued, /scoped to what it emits and consumes/, issued); - await mesh(`assign ${MACHINE} grafana`); - await mesh(`push ${MACHINE}`); - await settled(); - - const running = await must(`docker ps --format '{{.Names}}'`); - assert.match(running, /mesh-grafana/, - `grafana's runtime was assigned and is not running:\n${(await on(`tail -30 /var/log/mesh-host.log`)).out}`); - - // The settings reached the node: the rendered config file carries what was set, not the manifest's - // empty default. - const config = await must(`cat /var/lib/mesh/grafana/config.json`); - assert.match(config, /lab-grafana-token/, `the settings did not merge into the config file:\n${config}`); - - const credential = await must(`cat /var/lib/mesh/grafana/broker`); - assert.match(credential, /"url":"amqps:\/\/anchor-grafana:/, `not the scoped account:\n${credential}`); - assert.doesNotMatch(credential, /guest:guest/, "grafana's runtime holds the broker's own account"); - - // The runtime read that config, built its client from the settings-provided token, registered its - // tools, and bound their serve queues — the queue on the broker is the proof the settings-config - // path reached serving, with no credential in the manifest and no live Grafana. - let served = ""; - const untilServing = Date.now() + 60_000; - while (Date.now() < untilServing) { - served = await must(`docker exec mesh-broker lavinmqctl list_queues name 2>&1 || true`); - if (/serve\.grafana\.grafana_status/.test(served)) break; - await new Promise((r) => setTimeout(r, 3000)); - } - assert.match(served, /serve\.grafana\.grafana_status/, - `grafana's runtime never bound its serve queue (settings not read?):\n` + - `${(await on(`docker logs mesh-grafana 2>&1 | tail -20`)).out}\n---\n${served}`); - - const users = await must(`docker exec mesh-broker lavinmqctl list_users 2>&1`); - assert.match(users, /anchor-grafana/, `the scoped account is not on the broker:\n${users}`); -}); diff --git a/test/integration/assigned-plex.test.ts b/test/integration/assigned-plex.test.ts deleted file mode 100644 index 14e6877..0000000 --- a/test/integration/assigned-plex.test.ts +++ /dev/null @@ -1,231 +0,0 @@ -/** - * The mesh assigns plex's tool runtime, and it serves plex's tools over an account the mesh - * delivered — the whole of novox/hq ADR 0052. - * - * assigned-audit proves an assigned *consumer* (ADR 0048). This proves an assigned module that runs - * its OWN code as its OWN process under its OWN scoped account and *serves tools*: the module is - * assigned through the control plane, the mesh issues it an account scoped to serve.plex.* (and its - * events), seals it to the machine, and the host runs it as a container that binds amqps with that - * account. A caller then invokes plex.plex_reachable over the mesh and gets the tool's own answer — - * proof the invocation routed to the assigned runtime, ran plex's real code, and replied, all under - * the scoped account and never the broker's own. - * - * It needs the host binary, the foundation bundle, and the runtime image the scenario loads: - * - * MESH_LAB_HOST_BINARY=.../mesh-host - * MESH_LAB_BUNDLE=.../examples/foundation-first-node.lock - * scripts/build-module-runtime.sh plex builds mesh-runtime-plex:development into the local daemon, - * which scenarios/plex-node.yml stocks — so no MESH_LAB_RUNTIME here; the host pulls it. - */ - -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 = "plex-node"; -const MACHINE = "anchor"; - -let instanceId = ""; -/** The mesh's own images, as the machines hold them. */ -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; -} - -/** The control plane, a container on the node. */ -async function mesh(command: string, timeoutMs?: number): Promise { - return must(`docker exec mesh-controller /mesh-controller ${command}`, timeoutMs); -} - -/** The reference a manifest should carry, once this scenario has been raised. */ -/** 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); -} - -/** The foundation bundle: ours by the ID the machine holds, everything else upstream. */ -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; -} - -async function settled(withinMs = 480_000): Promise { - const until = Date.now() + withinMs; - let last = ""; - while (Date.now() < until) { - const asked = await on(`docker exec mesh-controller /mesh-controller 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; - - // Raise the foundation — store, broker, control — from the bundle. - 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}`); - } - - // The node joins its own mesh, so it is a node the mesh can assign to, and start the host so it - // applies what it is pushed. - 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("the mesh assigns plex's runtime, and it serves plex's tools over the account the mesh delivered", { - skip, timeout: 900_000, -}, async () => { - // A minimal plex manifest: its tools/events runtime (no Plex server or media mounts in the lab), - // its emits and consumes so the account is scoped to those too, and a token in the environment so - // the tools register without a running Plex to detect one from. The runtime image is the digest - // this scenario's registry serves. - const manifest = JSON.stringify({ - module: "plex", - version: "1", - emits: [ - "module.plex.playback.started", - "module.plex.playback.stopped", - "module.plex.item.added", - ], - consumes: ["module.*.download.completed"], - "own-secrets": { broker: "/var/lib/mesh/plex/broker" }, - resources: [ - { id: "mesh-state", type: "directory", path: "/var/lib/mesh/plex", mode: "0700" }, - { - id: "runtime", type: "container", name: "mesh-plex", image: pinned("mesh-runtime-plex"), - network: "host", - volumes: ["/var/lib/mesh/plex/broker:/run/secrets/broker:ro"], - env: { - MESH_BROKER_FILE: "/run/secrets/broker", - MESH_PLEX_URL: "http://127.0.0.1:32400", - MESH_PLEX_TOKEN: "lab-token", - }, - }, - ], - }); - await must(`printf %s ${quote(manifest)} > /tmp/plex.json && docker cp /tmp/plex.json mesh-controller:/plex.json`); - await mesh("module add /plex.json"); - - // The mesh issues plex's scoped account and seals it to this machine, then assigns and pushes it. - const issued = await mesh(`module issue plex --node ${MACHINE}`); - assert.match(issued, /scoped to what it emits and consumes/, issued); - await mesh(`assign ${MACHINE} plex`); - await mesh(`push ${MACHINE}`); - await settled(); - - // The runtime container the mesh started is running. - const running = await must(`docker ps --format '{{.Names}}'`); - assert.match(running, /mesh-plex/, - `plex's runtime was assigned and is not running:\n${(await on(`tail -30 /var/log/mesh-host.log`)).out}`); - - // The credential on disk is the scoped account over amqps, sealed — not the broker's own. - const credential = await must(`cat /var/lib/mesh/plex/broker`); - assert.match(credential, /"url":"amqps:\/\/anchor-plex:/, `not the scoped account:\n${credential}`); - assert.doesNotMatch(credential, /guest:guest/, "plex's runtime holds the broker's own account"); - assert.match(credential, /"fingerprint":"(sha256:)?[0-9a-f]{64}"/, "no fingerprint to pin the broker"); - - // The runtime registered and is serving its tools — the queue it declared is on the broker, - // named for the scope its account is granted (serve.plex.*). - let served = ""; - const untilServing = Date.now() + 60_000; - while (Date.now() < untilServing) { - served = await must(`docker exec mesh-broker lavinmqctl list_queues name 2>&1 || true`); - if (/serve\.plex\.plex_reachable/.test(served)) break; - await new Promise((r) => setTimeout(r, 3000)); - } - assert.match(served, /serve\.plex\.plex_reachable/, - `plex's runtime never bound its serve queue:\n${(await on(`docker logs mesh-plex 2>&1 | tail -20`)).out}\n---\n${served}`); - - // A caller invokes plex.plex_reachable over the mesh, from the bootstrap account (a caller, like - // mesh-controller's command API — plex's own account serves, it does not call). The reply is the - // tool's own answer: it ran in the assigned runtime and reported the Plex server is unreachable - // (there is none in the lab). A reply at all — not a timeout — is the proof the invocation routed - // to the assigned runtime and ran plex's real code under its scoped account. - const invoked = await must( - `docker run --rm --network host -e MESH_BROKER_URL=amqp://guest:guest@127.0.0.1:5672/ ` + - `${pinned("mesh-runtime-plex")} invoke plex plex_reachable`, - 120_000, - ); - const line = invoked.split("\n").map((l) => l.trim()).filter(Boolean).pop() ?? ""; - const result = JSON.parse(line) as { reachable: boolean; url: string; error?: string }; - assert.equal(result.reachable, false, `expected the lab's Plex to be unreachable:\n${invoked}`); - assert.match(result.url, /127\.0\.0\.1:32400/, `the tool ran but not against the configured server:\n${invoked}`); - - // And the account the mesh made for it is a real one on the broker, scoped — proven above by the - // serve queue authenticating and the invocation round-tripping under it. - const users = await must(`docker exec mesh-broker lavinmqctl list_users 2>&1`); - assert.match(users, /anchor-plex/, `the scoped account is not on the broker:\n${users}`); -}); diff --git a/test/integration/assigned-redis.test.ts b/test/integration/assigned-redis.test.ts deleted file mode 100644 index 2e8cea0..0000000 --- a/test/integration/assigned-redis.test.ts +++ /dev/null @@ -1,273 +0,0 @@ -/** - * The mesh assigns redis — a *provider* — and its runtime runs the provisioner AND the tools as one - * process under one account the mesh delivered (novox/hq ADR 0052). - * - * assigned-plex proves an assigned module that serves tools. This proves the provider half: redis's - * runtime binds its scoped account, serves redis's tools against the real server (redis_ping → - * PONG), and — the thing 0052 fixes — runs its provisioner in that same broker-bound process, so a - * grant is provisioned and its lifecycle event is emitted onto the mesh. Before 0052 the provisioner - * ran in a container with no broker and its emit could not fire at all. - * - * A caveat this test makes explicit: runProvisioner needs a seal key ($MESH_SEAL_KEY) and the mesh - * has no way yet to deliver one to a provider's runtime (04-ISSUES). The manifest here sets a - * lab-local key so the mechanism can be proven; the delivery is a separate, open design question. - * - * It needs the host binary, the foundation bundle, and the runtime image the scenario loads: - * - * MESH_LAB_HOST_BINARY=.../mesh-host MESH_LAB_BUNDLE=.../examples/foundation-first-node.lock - * scripts/build-module-runtime.sh redis builds mesh-runtime-redis:development into the local - * daemon, which scenarios/redis-node.yml stocks — so no MESH_LAB_RUNTIME here; the host pulls it. - */ - -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 = "redis-node"; -const MACHINE = "anchor"; - -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); -} - -/** 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; -} - -async function settled(withinMs = 480_000): Promise { - const until = Date.now() + withinMs; - let last = ""; - while (Date.now() < until) { - const asked = await on(`docker exec mesh-controller /mesh-controller 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("the mesh assigns redis, and its runtime serves tools and provisions grants over the account the mesh delivered", { - skip, timeout: 900_000, -}, async () => { - // A redis manifest with both halves it needs on this node: the redis server, and one broker-bound - // runtime that serves redis's tools AND runs its provisioner. Both reach the server over the host - // (127.0.0.1:6379) with the same admin password the mesh generated. MESH_SEAL_KEY is lab-local — - // the mesh cannot yet deliver one to a provider's runtime (see the file header / 04-ISSUES). - const manifest = JSON.stringify({ - module: "redis", - version: "1", - emits: ["module.redis.cache.provisioned", "module.redis.cache.deprovisioned"], - // redis's events entrypoint subscribes to its own lifecycle events (an audit-trail log), so it - // consumes them too — declared, or the foundation never makes the queue the runtime binds and it - // crashes on start with a 404 (novox/hq ADR 0046: a consume is declared). - consumes: ["module.redis.cache.provisioned", "module.redis.cache.deprovisioned"], - "own-secrets": { default: "/var/lib/redis-module/default.secret", broker: "/var/lib/mesh/redis/broker" }, - resources: [ - { id: "mesh-state", type: "directory", path: "/var/lib/mesh/redis", mode: "0700" }, - { id: "state", type: "directory", path: "/var/lib/redis-module", mode: "0700" }, - { id: "grants-dir", type: "directory", path: "/var/lib/redis-module/grants", mode: "0700" }, - { id: "data", type: "directory", path: "/services/redis/data", mode: "0700", owner: "999:999" }, - { - id: "server-conf", type: "file", path: "/var/lib/redis-module/redis.conf", mode: "0644", - content: "requirepass ${secret:default}\nappendonly no\ndir /data\n", - }, - { - id: "server", type: "container", name: "redis", image: pinned("redis"), network: "host", - volumes: [ - "/services/redis/data:/data", - "/var/lib/redis-module/redis.conf:/etc/redis/redis.conf:ro", - ], - args: ["/etc/redis/redis.conf"], - }, - { - id: "runtime", type: "container", name: "mesh-redis", image: pinned("mesh-runtime-redis"), - network: "host", - volumes: [ - "/var/lib/mesh/redis/broker:/run/secrets/broker:ro", - "/var/lib/redis-module/grants:/var/lib/redis-module/grants", - "/var/lib/redis-module/default.secret:/run/secrets/default:ro", - ], - env: { - MESH_BROKER_FILE: "/run/secrets/broker", - GRANTS: "/var/lib/redis-module/grants", - MESH_PROVISION_REDIS: "127.0.0.1:6379", - MESH_PROVISION_PASSWORD_FILE: "/run/secrets/default", - MESH_SEAL_KEY: "lab-only-seal-key", - }, - }, - ], - }); - await must(`printf %s ${quote(manifest)} > /tmp/redis.json && docker cp /tmp/redis.json mesh-controller:/redis.json`); - await mesh("module add /redis.json"); - - const issued = await mesh(`module issue redis --node ${MACHINE}`); - assert.match(issued, /scoped to what it emits and consumes/, issued); - await mesh(`assign ${MACHINE} redis`); - await mesh(`push ${MACHINE}`); - await settled(); - - // The server and the runtime the mesh started are both running. - const running = await must(`docker ps --format '{{.Names}}'`); - assert.match(running, /\bredis\b/, `redis's server is not running:\n${(await on(`tail -30 /var/log/mesh-host.log`)).out}`); - assert.match(running, /mesh-redis/, `redis's runtime is not running:\n${(await on(`docker logs mesh-redis 2>&1 | tail -20`)).out}`); - - // The credential on disk is the scoped account over amqps, sealed — not the broker's own. - const credential = await must(`cat /var/lib/mesh/redis/broker`); - assert.match(credential, /"url":"amqps:\/\/anchor-redis:/, `not the scoped account:\n${credential}`); - assert.doesNotMatch(credential, /guest:guest/, "redis's runtime holds the broker's own account"); - assert.match(credential, /"fingerprint":"(sha256:)?[0-9a-f]{64}"/, "no fingerprint to pin the broker"); - - // The runtime registered and is serving its tools — the serve queue is on the broker. - let served = ""; - const untilServing = Date.now() + 60_000; - while (Date.now() < untilServing) { - served = await must(`docker exec mesh-broker lavinmqctl list_queues name 2>&1 || true`); - if (/serve\.redis\.redis_ping/.test(served)) break; - await new Promise((r) => setTimeout(r, 3000)); - } - assert.match(served, /serve\.redis\.redis_ping/, - `redis's runtime never bound its serve queue:\n${(await on(`docker logs mesh-redis 2>&1 | tail -30`)).out}\n---\n${served}`); - - // A caller invokes redis.redis_ping over the mesh: the tool runs in the assigned runtime, reaches - // the real redis, and answers PONG. A positive round-trip against a real backend. - const pinged = await must( - `docker run --rm --network host -e MESH_BROKER_URL=amqp://guest:guest@127.0.0.1:5672/ ` + - `${pinned("mesh-runtime-redis")} invoke redis redis_ping`, - 120_000, - ); - const pingLine = pinged.split("\n").map((l) => l.trim()).filter(Boolean).pop() ?? ""; - const ping = JSON.parse(pingLine) as { ok: unknown }; - assert.ok(String(ping.ok).toUpperCase().includes("PONG") || ping.ok === true, - `redis_ping did not answer PONG through the mesh:\n${pinged}`); - - // The provider path: a grant appears (as the control plane would write it), and the provisioner — - // running inside the same broker-bound runtime — creates the ACL user and emits the lifecycle - // event. The sealed credential the harness writes only after adapter.create() returns is the - // proof create() ran to completion; and because emit() awaits the broker's publish confirm - // (ADR 0047), a completed create() means the provisioned event was accepted onto the mesh. - const grant = JSON.stringify({ resource: "redis-cache", consumer: "app-one", node: MACHINE, values: {} }); - await must(`printf %s ${quote(grant)} > /var/lib/redis-module/grants/app-one.grant.json`); - - let credentialWritten = false; - const untilProvisioned = Date.now() + 60_000; - while (Date.now() < untilProvisioned) { - const ls = await on(`ls /var/lib/redis-module/grants/`); - if (ls.ok && /app-one\.redis-cache\.credential/.test(ls.out)) { credentialWritten = true; break; } - await new Promise((r) => setTimeout(r, 3000)); - } - assert.ok(credentialWritten, - `the provisioner never provisioned the grant (no emit under a bound broker?):\n` + - `${(await on(`docker logs mesh-redis 2>&1 | tail -30`)).out}`); - - // No emit failed: the provisioner's announce() logs "emit ... failed" only when the broker refused - // the publish. Its absence, with the credential written, is the provisioner emitting on the mesh. - const runtimeLog = (await on(`docker logs mesh-redis 2>&1`)).out; - assert.doesNotMatch(runtimeLog, /emit .*failed/, - `the provisioner's emit was refused — the account cannot publish its lifecycle event:\n${runtimeLog}`); - - // And the ACL user the provisioner created is really on the redis server — the provisioning did - // its own half, not only the mesh bookkeeping. Asked through the same served tool surface. - const acl = await must( - `docker run --rm --network host -e MESH_BROKER_URL=amqp://guest:guest@127.0.0.1:5672/ ` + - `${pinned("mesh-runtime-redis")} invoke redis redis_command '{"command":"ACL LIST"}'`, - 120_000, - ); - assert.match(acl, /app-one/, `the provisioner did not create the consumer's ACL user on redis:\n${acl}`); - - // The scoped account the mesh made for it is a real one on the broker. - const users = await must(`docker exec mesh-broker lavinmqctl list_users 2>&1`); - assert.match(users, /anchor-redis/, `the scoped account is not on the broker:\n${users}`); -}); diff --git a/test/integration/assigned-sonarr.test.ts b/test/integration/assigned-sonarr.test.ts deleted file mode 100644 index dc63f19..0000000 --- a/test/integration/assigned-sonarr.test.ts +++ /dev/null @@ -1,214 +0,0 @@ -/** - * The mesh assigns sonarr's tool runtime, and it serves sonarr's tools over an account the mesh - * delivered — the Servarr case of novox/hq ADR 0052. - * - * assigned-plex proved a tools+events module that self-detects its token from a mounted config dir. - * This proves that self-configuring pattern generalises to the Servarr family: sonarr's runtime - * detects its API key from the server's own config.xml (a file resource stands in for the running - * Sonarr here), registers its tools, and serves them under a scoped account. There is no live Sonarr - * to reach — that the serve queue is bound is the proof the key was detected and the tools loaded. - * - * MESH_LAB_HOST_BINARY=.../mesh-host MESH_LAB_BUNDLE=.../examples/foundation-first-node.lock - * scripts/build-module-runtime.sh sonarr builds mesh-runtime-sonarr:development into the local - * daemon, which scenarios/sonarr-node.yml stocks — so no MESH_LAB_RUNTIME here; the host pulls it. - */ - -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 = "sonarr-node"; -const MACHINE = "anchor"; - -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); -} - -/** 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; -} - -async function settled(withinMs = 480_000): Promise { - const until = Date.now() + withinMs; - let last = ""; - while (Date.now() < until) { - const asked = await on(`docker exec mesh-controller /mesh-controller 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("the mesh assigns sonarr's runtime, and it detects its key and serves its tools", { - skip, timeout: 900_000, -}, async () => { - // A minimal sonarr manifest: its tool runtime, and a config.xml the runtime detects its API key - // from — the file resource stands in for the running Sonarr that would write it. No Sonarr server - // or media mounts; the tools simply have nothing live to reach. - const manifest = JSON.stringify({ - module: "sonarr", - version: "1", - emits: ["module.sonarr.episode.grabbed", "module.sonarr.download.completed"], - consumes: [], - "own-secrets": { broker: "/var/lib/mesh/sonarr/broker" }, - resources: [ - { id: "mesh-state", type: "directory", path: "/var/lib/mesh/sonarr", mode: "0700" }, - { id: "config", type: "directory", path: "/services/sonarr/config", mode: "0700" }, - { - id: "config-xml", type: "file", path: "/services/sonarr/config/config.xml", mode: "0644", - content: "\n 8989\n labdetectedapikey0000000000000000\n\n", - }, - { - id: "runtime", type: "container", name: "mesh-sonarr", image: pinned("mesh-runtime-sonarr"), - network: "host", - volumes: [ - "/var/lib/mesh/sonarr/broker:/run/secrets/broker:ro", - "/services/sonarr/config:/var/lib/sonarr/config:ro", - ], - env: { - MESH_BROKER_FILE: "/run/secrets/broker", - MESH_SONARR_URL: "http://127.0.0.1:8989", - MESH_SONARR_CONFIG_DIR: "/var/lib/sonarr/config", - }, - }, - ], - }); - await must(`printf %s ${quote(manifest)} > /tmp/sonarr.json && docker cp /tmp/sonarr.json mesh-controller:/sonarr.json`); - await mesh("module add /sonarr.json"); - - const issued = await mesh(`module issue sonarr --node ${MACHINE}`); - assert.match(issued, /scoped to what it emits and consumes/, issued); - await mesh(`assign ${MACHINE} sonarr`); - await mesh(`push ${MACHINE}`); - await settled(); - - const running = await must(`docker ps --format '{{.Names}}'`); - assert.match(running, /mesh-sonarr/, - `sonarr's runtime was assigned and is not running:\n${(await on(`tail -30 /var/log/mesh-host.log`)).out}`); - - const credential = await must(`cat /var/lib/mesh/sonarr/broker`); - assert.match(credential, /"url":"amqps:\/\/anchor-sonarr:/, `not the scoped account:\n${credential}`); - assert.doesNotMatch(credential, /guest:guest/, "sonarr's runtime holds the broker's own account"); - assert.match(credential, /"fingerprint":"(sha256:)?[0-9a-f]{64}"/, "no fingerprint to pin the broker"); - - // The runtime detected its API key from config.xml, registered its tools, and bound their serve - // queues — the queue on the broker is the proof the whole chain worked with no live Sonarr. - let served = ""; - const untilServing = Date.now() + 60_000; - while (Date.now() < untilServing) { - served = await must(`docker exec mesh-broker lavinmqctl list_queues name 2>&1 || true`); - if (/serve\.sonarr\.sonarr_status/.test(served)) break; - await new Promise((r) => setTimeout(r, 3000)); - } - assert.match(served, /serve\.sonarr\.sonarr_status/, - `sonarr's runtime never bound its serve queue (key not detected?):\n` + - `${(await on(`docker logs mesh-sonarr 2>&1 | tail -20`)).out}\n---\n${served}`); - - // A caller invokes sonarr_status over the mesh: it routes to the assigned runtime, which runs - // sonarr's real code and reports Sonarr unreachable (there is none). A reply — not a timeout — is - // the proof the invocation reached the runtime under its scoped account. - const invoked = await on( - `docker run --rm --network host -e MESH_BROKER_URL=amqp://guest:guest@127.0.0.1:5672/ ` + - `${pinned("mesh-runtime-sonarr")} invoke sonarr sonarr_status`, - 120_000, - ); - assert.doesNotMatch(invoked.out, /timed out/, - `sonarr_status timed out — nothing served the invocation:\n${invoked.out}`); - - const users = await must(`docker exec mesh-broker lavinmqctl list_users 2>&1`); - assert.match(users, /anchor-sonarr/, `the scoped account is not on the broker:\n${users}`); -}); diff --git a/test/integration/minio-grant-end-to-end.test.ts b/test/integration/minio-grant-end-to-end.test.ts deleted file mode 100644 index 34fd53e..0000000 --- a/test/integration/minio-grant-end-to-end.test.ts +++ /dev/null @@ -1,252 +0,0 @@ -/** - * The whole grant for an S3 bucket, mesh-driven — novox/hq ADR 0052/0053, the minio case. - * - * The postgres bed proves the provider/consumer contract for a database. This proves it for object - * storage, on a provider whose code drives the `mc` CLI (so the runtime image carries it): minio is - * assigned, a consumer that requires s3-bucket is assigned, and the mesh mints one secret key, sealing - * a copy to each end. minio's provisioner — reading only the mesh's contributions — creates a bucket - * and a service account under the access key the mesh derived, with the secret it minted. The proof is - * the consumer reaching its bucket with the access key and secret the mesh delivered it. Nothing is - * placed by the test. - * - * MESH_LAB_HOST_BINARY=.../mesh-host MESH_LAB_BUNDLE=.../examples/foundation-first-node.lock - * scripts/build-module-runtime.sh minio builds mesh-runtime-minio:development (with mc), which - * scenarios/minio-node.yml stocks. minio/minio:latest must be in the local daemon. - */ - -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"] ?? ""; - -// 04-ISSUES/010 is fixed by ADR 0054: an S3 access key is capped at 20, and the mesh derives -// `mesh__`, so `bucketuser` on `anchor` (22) would overflow — but a consumer declares a -// short `slug` and its identity fits. This bed's consumer does exactly that. -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 = "minio-node"; -const MACHINE = "anchor"; - -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); -} - -/** 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; -} - -/** Same rule minio's client uses to name a bucket for a consumer — recomputed so the test knows it. */ -function bucketFor(as: string): string { - const name = as.toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 63); - return name.length >= 3 ? name : `mesh-${name}`; -} - -async function settled(withinMs = 480_000): Promise { - const until = Date.now() + withinMs; - let last = ""; - while (Date.now() < until) { - const asked = await on(`docker exec mesh-controller /mesh-controller 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("the mesh grants a consumer an S3 bucket, and the credential it delivers reaches it", { - skip, timeout: 900_000, -}, async () => { - // The PROVIDER: minio in its committed shape — server and a broker-bound runtime (carrying mc) on - // the private minio network, the runtime running the provisioner. No published port on this - // single-node bed; the consumer reaches minio over the private network by name. - const minioManifest = JSON.stringify({ - module: "minio", - version: "1", - provides: [{ name: "s3-bucket", scope: "mesh" }], - serves: { "s3-bucket": { scheme: "http", region: "us-east-1" } }, - emits: ["module.minio.bucket.created", "module.minio.bucket.removed"], - receives: { "s3-bucket": "/var/lib/minio/grants/mesh.json" }, - grants: { "s3-bucket": "/var/lib/minio/grants" }, - "own-secrets": { root: "/var/lib/minio/root.secret", broker: "/var/lib/mesh/minio/broker" }, - resources: [ - { id: "mesh-state", type: "directory", path: "/var/lib/mesh/minio", mode: "0700" }, - { id: "state", type: "directory", path: "/var/lib/minio", mode: "0700" }, - { id: "grants", type: "directory", path: "/var/lib/minio/grants", mode: "0700" }, - { id: "root-env", type: "file", path: "/var/lib/minio/root.env", mode: "0600", content: "MINIO_ROOT_USER=meshroot\nMINIO_ROOT_PASSWORD=${secret:root}\n" }, - { id: "data", type: "directory", path: "/services/minio/data/data1-1", mode: "0700" }, - { id: "net", type: "network", name: "minio" }, - { - id: "server", type: "container", name: "minio", image: pinned("minio/minio"), network: "minio", - args: ["server", "/data", "--console-address", ":9001"], - "env-file": ["/var/lib/minio/root.env"], - volumes: ["/services/minio/data/data1-1:/data"], - }, - { - id: "runtime", type: "container", name: "mesh-minio", image: pinned("mesh-runtime-minio"), - network: "minio", - volumes: [ - "/var/lib/mesh/minio/broker:/run/secrets/broker:ro", - "/var/lib/minio/grants:/var/lib/minio/grants:ro", - "/var/lib/minio/root.secret:/run/secrets/root:ro", - ], - env: { - MESH_MINIO_ENDPOINT: "http://minio:9000", - MESH_MINIO_ROOT_USER: "meshroot", - MESH_MINIO_ROOT_PASSWORD_FILE: "/run/secrets/root", - MESH_BROKER_FILE: "/run/secrets/broker", - MESH_RECEIVES: "/var/lib/minio/grants/mesh.json", - }, - }, - ], - }); - - const consumerManifest = JSON.stringify({ - module: "bucketuser", - version: "1", - // A short slug, so the derived identity `mesh_anchor_bkt` fits an S3 access key's 20 chars where - // `mesh_anchor_bucketuser` (22) would not (novox/hq ADR 0054, 04-ISSUES/010). - slug: "bkt", - requires: ["s3-bucket"], - contributes: { "s3-bucket": { name: "bucketuser" } }, - binds: { "s3-bucket": "/var/lib/bucketuser/s3.json" }, - secrets: { "s3-bucket": "/var/lib/bucketuser/s3.secret" }, - resources: [{ id: "state", type: "directory", path: "/var/lib/bucketuser", mode: "0700" }], - }); - - await must(`printf %s ${quote(minioManifest)} > /tmp/minio.json && docker cp /tmp/minio.json mesh-controller:/minio.json`); - await mesh("module add /minio.json"); - await mesh(`module issue minio --node ${MACHINE}`); - await mesh(`assign ${MACHINE} minio`); - - await must(`printf %s ${quote(consumerManifest)} > /tmp/bucketuser.json && docker cp /tmp/bucketuser.json mesh-controller:/bucketuser.json`); - await mesh("module add /bucketuser.json"); - await mesh(`assign ${MACHINE} bucketuser`); - - await mesh(`push ${MACHINE}`); - await settled(); - - // The mesh delivered the consumer its bound file and its unsealed secret. - let boundRaw = ""; - const untilBound = Date.now() + 60_000; - while (Date.now() < untilBound) { - const got = await on(`cat /var/lib/bucketuser/s3.json 2>/dev/null`); - if (got.ok && /"as"/.test(got.out)) { boundRaw = got.out; break; } - await new Promise((r) => setTimeout(r, 3000)); - } - assert.match(boundRaw, /"as"/, `the consumer was never told about its bucket:\n${boundRaw}`); - const bound = JSON.parse(boundRaw) as { as: string; provision: string }; - assert.equal(bound.provision, "s3-bucket"); - const accessKey = bound.as; - const secretKey = (await must(`cat /var/lib/bucketuser/s3.secret`)).trim(); - assert.ok(accessKey && secretKey, `the consumer's access key or secret was empty (as=${accessKey})`); - const bucket = bucketFor(accessKey); - - // THE PROOF: reach the bucket as the consumer, with the access key and secret the mesh delivered - // it. mc listing the consumer's own bucket means the service account, the bucket, and the secret all - // line up across the two ends. A provisioner that set a different secret answers "Access Denied". - const probe = - `mc alias set probe http://minio:9000 ${quote(accessKey)} ${quote(secretKey)} >/dev/null 2>&1 && ` + - `mc ls probe/${quote(bucket)}/`; - let out = { out: "", ok: false }; - const untilReach = Date.now() + 90_000; - while (Date.now() < untilReach) { - out = await on(`docker exec mesh-minio sh -c ${quote(probe)} 2>&1`); - if (out.ok) break; - if (/denied/i.test(out.out)) break; // fast-fail: the credential is wrong - await new Promise((r) => setTimeout(r, 3000)); - } - assert.doesNotMatch(out.out, /denied/i, - `the consumer could not reach its bucket with the mesh's secret — the two ends do not agree:\n${out.out}`); - assert.ok(out.ok, - `the consumer could not list its granted bucket ${bucket} as ${accessKey}:\n${out.out}\n---\n${(await on(`docker logs mesh-minio 2>&1 | tail -30`)).out}`); -}); diff --git a/test/integration/postgres-grant-end-to-end.test.ts b/test/integration/postgres-grant-end-to-end.test.ts deleted file mode 100644 index 1859f98..0000000 --- a/test/integration/postgres-grant-end-to-end.test.ts +++ /dev/null @@ -1,241 +0,0 @@ -/** - * The whole grant for a database, mesh-driven — novox/hq ADR 0052/0053, the postgres case. - * - * The redis bed proves the provider/consumer contract for a cache. This proves it for a database, on - * a provider whose code shells out to `psql` (so the runtime image carries it): postgres is assigned, - * a consumer that requires postgres-database is assigned, and the mesh mints one password, seals a - * copy to each end, and writes each its file. postgres's provisioner — reading only the mesh's - * contributions — creates a role and a database under the login the mesh derived, with the password - * the mesh minted. The proof is the consumer connecting to its database with the credential the mesh - * delivered it. Nothing is placed by the test. - * - * MESH_LAB_HOST_BINARY=.../mesh-host MESH_LAB_BUNDLE=.../examples/foundation-first-node.lock - * scripts/build-module-runtime.sh postgres builds mesh-runtime-postgres:development (with psql), - * which scenarios/postgres-node.yml stocks. - */ - -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 = "postgres-node"; -const MACHINE = "anchor"; - -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); -} - -/** 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; -} - -async function settled(withinMs = 480_000): Promise { - const until = Date.now() + withinMs; - let last = ""; - while (Date.now() < until) { - const asked = await on(`docker exec mesh-controller /mesh-controller 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("the mesh grants a consumer a postgres database, and the credential it delivers connects", { - skip, timeout: 900_000, -}, async () => { - // The PROVIDER: postgres in its committed shape — server and a broker-bound runtime (carrying psql) - // on the private postgres network, the runtime running the provisioner. - const postgresManifest = JSON.stringify({ - module: "postgres", - version: "1", - provides: [{ name: "postgres-database", scope: "mesh" }], - serves: { "postgres-database": {} }, - emits: ["module.postgres.database.provisioned", "module.postgres.database.deprovisioned"], - consumes: ["module.postgres.database.provisioned", "module.postgres.database.deprovisioned"], - receives: { "postgres-database": "/var/lib/postgres/grants/mesh.json" }, - grants: { "postgres-database": "/var/lib/postgres/grants" }, - "own-secrets": { superuser: "/var/lib/postgres/superuser.secret", broker: "/var/lib/mesh/postgres/broker" }, - resources: [ - { id: "mesh-state", type: "directory", path: "/var/lib/mesh/postgres", mode: "0700" }, - { id: "state", type: "directory", path: "/var/lib/postgres", mode: "0700" }, - { id: "grants", type: "directory", path: "/var/lib/postgres/grants", mode: "0700" }, - { id: "superuser-env", type: "file", path: "/var/lib/postgres/superuser.env", mode: "0600", content: "POSTGRES_PASSWORD=${secret:superuser}\n" }, - { id: "data", type: "directory", path: "/services/postgres/db-data", mode: "0700" }, - { id: "net", type: "network", name: "postgres" }, - { - // No published port here: the foundation's own store already holds host :5432 on this - // single-node bed, and the consumer reaches postgres over the private network by name. The - // committed manifest publishes it for cross-node consumers, which is a different node. - id: "server", type: "container", name: "postgres", image: pinned("postgres"), network: "postgres", - env: { POSTGRES_USER: "postgres", POSTGRES_DB: "postgres" }, - "env-file": ["/var/lib/postgres/superuser.env"], - volumes: ["/services/postgres/db-data:/var/lib/postgresql/data"], - }, - { - id: "runtime", type: "container", name: "mesh-postgres", image: pinned("mesh-runtime-postgres"), - network: "postgres", - volumes: [ - "/var/lib/mesh/postgres/broker:/run/secrets/broker:ro", - "/var/lib/postgres/grants:/var/lib/postgres/grants:ro", - "/var/lib/postgres/superuser.secret:/run/secrets/superuser:ro", - ], - env: { - MESH_BROKER_FILE: "/run/secrets/broker", - MESH_RECEIVES: "/var/lib/postgres/grants/mesh.json", - MESH_PROVISION_POSTGRES: "postgres://postgres@postgres:5432/postgres?sslmode=disable", - MESH_PROVISION_PASSWORD_FILE: "/run/secrets/superuser", - }, - }, - ], - }); - - // The CONSUMER: a module that requires postgres-database and contributes a name so it asks. - const consumerManifest = JSON.stringify({ - module: "dbuser", - version: "1", - requires: ["postgres-database"], - contributes: { "postgres-database": { name: "dbuser" } }, - binds: { "postgres-database": "/var/lib/dbuser/db.json" }, - secrets: { "postgres-database": "/var/lib/dbuser/db.secret" }, - resources: [{ id: "state", type: "directory", path: "/var/lib/dbuser", mode: "0700" }], - }); - - await must(`printf %s ${quote(postgresManifest)} > /tmp/postgres.json && docker cp /tmp/postgres.json mesh-controller:/postgres.json`); - await mesh("module add /postgres.json"); - await mesh(`module issue postgres --node ${MACHINE}`); - await mesh(`assign ${MACHINE} postgres`); - - await must(`printf %s ${quote(consumerManifest)} > /tmp/dbuser.json && docker cp /tmp/dbuser.json mesh-controller:/dbuser.json`); - await mesh("module add /dbuser.json"); - await mesh(`assign ${MACHINE} dbuser`); - - await mesh(`push ${MACHINE}`); - await settled(); - - // The mesh delivered the consumer its bound file and its unsealed password. - let boundRaw = ""; - const untilBound = Date.now() + 60_000; - while (Date.now() < untilBound) { - const got = await on(`cat /var/lib/dbuser/db.json 2>/dev/null`); - if (got.ok && /"as"/.test(got.out)) { boundRaw = got.out; break; } - await new Promise((r) => setTimeout(r, 3000)); - } - assert.match(boundRaw, /"as"/, `the consumer was never told about its database:\n${boundRaw}`); - const bound = JSON.parse(boundRaw) as { as: string; provision: string }; - assert.equal(bound.provision, "postgres-database"); - const as = bound.as; - const password = (await must(`cat /var/lib/dbuser/db.secret`)).trim(); - assert.ok(as && password, `the consumer's login or password was empty (as=${as})`); - - // THE PROOF: connect to postgres as the consumer, with the login and password the mesh delivered - // it, to the database postgres's provisioner created — a real password-checked TCP connection (the - // runtime carries psql). A `1` back means the role, the database, and the password all line up - // across the two ends. A provisioner that set a different password answers "authentication failed". - const conn = `postgresql://${as}:${encodeURIComponent(password)}@postgres:5432/${as}?sslmode=disable`; - let out = { out: "", ok: false }; - const untilConn = Date.now() + 90_000; - while (Date.now() < untilConn) { - out = await on(`docker exec mesh-postgres psql ${quote(conn)} -tAc 'select 1' 2>&1`); - if (out.ok && /^1$/m.test(out.out)) break; - if (/authentication failed/i.test(out.out)) break; // fast-fail: the credential is wrong - await new Promise((r) => setTimeout(r, 3000)); - } - assert.doesNotMatch(out.out, /authentication failed/i, - `the consumer could not authenticate with the mesh's password — the two ends do not agree:\n${out.out}`); - assert.match(out.out, /^1$/m, - `the consumer could not connect to its granted database as ${as}:\n${out.out}\n---\n${(await on(`docker logs mesh-postgres 2>&1 | tail -30`)).out}`); -});