diff --git a/scenarios/plex-node.yml b/scenarios/plex-node.yml new file mode 100644 index 0000000..67724b9 --- /dev/null +++ b/scenarios/plex-node.yml @@ -0,0 +1,31 @@ +# 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 substrate, 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] } + inbound: allow + memory: 3GiB + cpus: 2 + +images: + - postgres:17-alpine + - cloudamqp/lavinmq:latest + - mesh-control:development + # Plex's tool runtime, built by scripts/build-module-runtime.sh plex into the local daemon and + # stocked into the scenario's own registry, which is where the host pulls it from. + - mesh-runtime-plex:development + +place: + all: [host, runtime] diff --git a/scenarios/redis-node.yml b/scenarios/redis-node.yml new file mode 100644 index 0000000..9c44d97 --- /dev/null +++ b/scenarios/redis-node.yml @@ -0,0 +1,31 @@ +# 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 +# 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. +scenario: redis-node + +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: + - postgres:17-alpine + - cloudamqp/lavinmq:latest + - mesh-control:development + - redis:7-alpine + # Redis's tool+provisioner runtime, built by scripts/build-module-runtime.sh redis into the local + # daemon and stocked into the scenario's own registry, which is where the host pulls it from. + - mesh-runtime-redis:development + +place: + all: [host, runtime] diff --git a/scripts/build-module-runtime.sh b/scripts/build-module-runtime.sh new file mode 100755 index 0000000..eb10634 --- /dev/null +++ b/scripts/build-module-runtime.sh @@ -0,0 +1,50 @@ +#!/usr/bin/env bash +# Build a per-module runtime image (novox/hq ADR 0052): the tool runtime carrying ONE module's +# compiled code, which serves that module's tools and runs its events/provisioner under the module's +# own scoped broker account. Generalises build-runtime-image.sh from the audit-logger to any module. +# +# build-module-runtime.sh +# -> tags mesh-runtime-:development and saves it to +set -euo pipefail + +MODULE="${1:?usage: build-module-runtime.sh }" +OUT="${2:?usage: build-module-runtime.sh }" +HERE="$(cd "$(dirname "$0")/.." && pwd)"; ROOT="$(cd "$HERE/.." && pwd)" +MESH_TOOLS="${MESH_TOOLS:-$ROOT/mesh-tools}" +MESH_SDK="${MESH_SDK:-$ROOT/mesh-sdk}" +MESH_CATALOG="${MESH_CATALOG:-$ROOT/mesh-catalog}" +MOD="$MESH_CATALOG/modules/$MODULE" +TAG="${RUNTIME_TAG:-mesh-runtime-$MODULE:development}" +BASE="${RUNTIME_BASE:-node:22-bookworm-slim}" +[ -d "$MOD" ] || { echo "no module $MODULE at $MOD" >&2; exit 1; } + +( cd "$MESH_SDK" && npm run build >/dev/null ) +( cd "$MESH_TOOLS" && npm run build >/dev/null ) +# Compile whichever of the module's entrypoints exist. +SRCS=(); for f in client.ts index.ts tools/index.ts provisioner/index.ts; do [ -f "$MOD/$f" ] && SRCS+=("$f"); done +TSC="$MESH_SDK/node_modules/.bin/tsc"; ( cd "$MOD" && "$TSC" "${SRCS[@]}" --module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist >/dev/null ) + +STAGE="$(mktemp -d)"; trap 'rm -rf "$STAGE"' EXIT +cp -r "$MESH_TOOLS/dist" "$STAGE/dist" +cp -rL "$MESH_TOOLS/node_modules" "$STAGE/node_modules" +mkdir -p "$STAGE/modules/$MODULE"; cp -r "$MOD/dist" "$STAGE/modules/$MODULE/dist" +cp "$MESH_TOOLS/package.json" "$STAGE/package.json" + +# The entrypoints the runtime loads: tools, events and (a provider's) provisioner, whichever exist. +ENTRIES=""; for e in tools/index.js index.js provisioner/index.js; do + [ -f "$STAGE/modules/$MODULE/dist/$e" ] && ENTRIES="${ENTRIES:+$ENTRIES,}/app/modules/$MODULE/dist/$e" +done + +cat > "$STAGE/Dockerfile" < $OUT" diff --git a/test/integration/assigned-plex.test.ts b/test/integration/assigned-plex.test.ts new file mode 100644 index 0000000..de5b638 --- /dev/null +++ b/test/integration/assigned-plex.test.ts @@ -0,0 +1,237 @@ +/** + * 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 substrate bundle, and the runtime image stocked by the scenario: + * + * MESH_LAB_HOST_BINARY=.../mesh-host + * MESH_LAB_BUNDLE=.../examples/substrate-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 } 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 = "plex-node"; +const MACHINE = "anchor"; + +let instanceId = ""; +/** What the scenario's registry serves, by digest. */ +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 { + 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-control /mesh-control ${command}`, timeoutMs); +} + +/** The pinned reference for one of the scenario's images, by repository. */ +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; +} + +/** The substrate bundle, its image references pointed at this scenario's own registry. */ +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; +} + +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-control /mesh-control 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; + + // Raise the substrate — store, broker, control — from the bundle. + 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}`); + } + + // 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-control:/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-control'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 new file mode 100644 index 0000000..574f031 --- /dev/null +++ b/test/integration/assigned-redis.test.ts @@ -0,0 +1,279 @@ +/** + * 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 substrate bundle, and the runtime image stocked by the scenario: + * + * MESH_LAB_HOST_BINARY=.../mesh-host MESH_LAB_BUNDLE=.../examples/substrate-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 } 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 = "redis-node"; +const MACHINE = "anchor"; + +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 { + 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-control /mesh-control ${command}`, timeoutMs); +} + +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; +} + +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-control /mesh-control 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("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 substrate 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-control:/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}`); +});