/** * The mesh assigns a SECOND wave of modules to one node in a single push — the ones converted this * session — and they resolve and come up together. catalogue-small's sibling, a heavier group. * * The four exercise the three converted shapes (novox/hq ADR 0039/0048/0052): * - mongodb — a database PROVIDER shaped like postgres: a server and a broker-bound runtime * (carrying `mongosh`) on the private mongodb network, the runtime running the provisioner over * the ADR-0048 MESH_RECEIVES contract. Its consumer proves the provisioner ran by connecting * with the mesh-minted credential. * - unifi — a tooled APP shaped like plex: a server and a broker-bound runtime that serves the * module's tools under a scoped account. No provisioner. (Lab credentials are set on the runtime * so unifi's client constructs and its tools register — as plex is given a lab token.) * - marrytts — a manifest-only PLAIN container: no runtime, no tools, no broker account. The proof * is simply that its container comes up under the co-resident push. * - postgres — the known-good provider control, verbatim from catalogue-small, so a mongodb-only * provisioning failure is unmistakable against a provider that is already proven. * * All are assigned to the one anchor, pushed ONCE, and the node converges ONCE with every one up. * * MESH_LAB_HOST_BINARY=.../mesh-host MESH_LAB_BUNDLE=.../examples/foundation-first-node.lock * scripts/build-module-runtime.sh {mongodb,unifi,postgres} build the runtime images into the local * daemon; scenarios/catalogue-apps.yml stocks them. mongo:7, lscr.io/linuxserver/unifi-controller * and synesthesiam/marytts must be in the local daemon to be stocked. */ 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 = "catalogue-apps"; 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 = 600_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 mongodb, unifi, marrytts and postgres to one node in one push, and all come up", { skip, timeout: 1_500_000, }, async () => { // --- postgres: the known-good provider control (verbatim from catalogue-small) ------------------ 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" }, { 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", }, }, ], }); const dbuserManifest = 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" }], }); // --- mongodb: a database provider shaped like postgres — server + broker-bound runtime (carrying // mongosh) on the private mongodb network, the runtime running the provisioner. ------------------- const mongodbManifest = JSON.stringify({ module: "mongodb", version: "1", provides: [{ name: "mongodb-database", scope: "mesh" }], serves: { "mongodb-database": {} }, emits: ["module.mongodb.database.provisioned", "module.mongodb.database.deprovisioned"], consumes: ["module.mongodb.database.provisioned", "module.mongodb.database.deprovisioned"], receives: { "mongodb-database": "/var/lib/mongodb/grants/mesh.json" }, grants: { "mongodb-database": "/var/lib/mongodb/grants" }, "own-secrets": { root: "/var/lib/mongodb/root.secret", broker: "/var/lib/mesh/mongodb/broker" }, resources: [ { id: "mesh-state", type: "directory", path: "/var/lib/mesh/mongodb", mode: "0700" }, { id: "state", type: "directory", path: "/var/lib/mongodb", mode: "0700" }, { id: "grants", type: "directory", path: "/var/lib/mongodb/grants", mode: "0700" }, { id: "root-env", type: "file", path: "/var/lib/mongodb/root.env", mode: "0600", content: "MONGO_INITDB_ROOT_PASSWORD=${secret:root}\n" }, { id: "data", type: "directory", path: "/services/mongodb/db-data", mode: "0700" }, { id: "net", type: "network", name: "mongodb" }, { id: "server", type: "container", name: "mongo", image: pinned("mongo"), network: "mongodb", env: { MONGO_INITDB_ROOT_USERNAME: "root" }, "env-file": ["/var/lib/mongodb/root.env"], volumes: ["/services/mongodb/db-data:/data/db"], }, { id: "runtime", type: "container", name: "mesh-mongodb", image: pinned("mesh-runtime-mongodb"), network: "mongodb", volumes: [ "/var/lib/mesh/mongodb/broker:/run/secrets/broker:ro", "/var/lib/mongodb/grants:/var/lib/mongodb/grants:ro", "/var/lib/mongodb/root.secret:/run/secrets/root:ro", ], env: { MESH_PROVISION_MONGODB: "mongodb://root@mongo:27017/admin?authSource=admin", MESH_PROVISION_PASSWORD_FILE: "/run/secrets/root", MESH_BROKER_FILE: "/run/secrets/broker", MESH_RECEIVES: "/var/lib/mongodb/grants/mesh.json", }, }, ], }); const mongouserManifest = JSON.stringify({ module: "mongouser", version: "1", // The mesh derives a consumer identity `mesh__` that must fit the tightest backend's // key length (20 chars — an S3 access key; ADR 0054). "mesh_anchor_mongouser" is 21, so this // consumer names itself with a short slug, exactly as bucketuser does in catalogue-small. slug: "mongo", requires: ["mongodb-database"], contributes: { "mongodb-database": { name: "mongouser" } }, binds: { "mongodb-database": "/var/lib/mongouser/db.json" }, secrets: { "mongodb-database": "/var/lib/mongouser/db.secret" }, resources: [{ id: "state", type: "directory", path: "/var/lib/mongouser", mode: "0700" }], }); // --- unifi: a tooled app. Server + broker-bound runtime that serves unifi's tools. Lab credentials // are set on the runtime so unifi's client constructs and its tools register (as plex gets a lab // token); the controller need not be reachable for `unifi_reachable` to be a bound serve queue. --- const unifiManifest = JSON.stringify({ module: "unifi", version: "1", "own-secrets": { broker: "/var/lib/mesh/unifi/broker" }, resources: [ { id: "mesh-state", type: "directory", path: "/var/lib/mesh/unifi", mode: "0700" }, { id: "data", type: "directory", path: "/services/unifi/data", mode: "0700", owner: "1000:1000" }, { id: "server", type: "container", name: "unifi-controller", image: pinned("lscr.io/linuxserver/unifi-controller"), ports: [ "8443:8443", "8080:8080", "3478:3478/udp", "10001:10001/udp", "1902:1900/udp", "8843:8843", "8880:8880", "6789:6789", "5514:5514/udp", ], env: { PUID: "1000", PGID: "1000", TZ: "Etc/UTC", MEM_LIMIT: "1024", MEM_STARTUP: "1024" }, volumes: ["/services/unifi/data:/config"], }, { id: "runtime", type: "container", name: "mesh-unifi", image: pinned("mesh-runtime-unifi"), network: "host", volumes: ["/var/lib/mesh/unifi/broker:/run/secrets/broker:ro"], env: { MESH_BROKER_FILE: "/run/secrets/broker", MESH_UNIFI_URL: "https://127.0.0.1:8443", MESH_UNIFI_USERNAME: "lab-admin", MESH_UNIFI_PASSWORD: "lab-password", }, }, ], }); // --- marrytts: a manifest-only plain container. No runtime, no tools, no broker account. --------- const marryttsManifest = JSON.stringify({ module: "marrytts", version: "1", resources: [ { id: "mesh-state", type: "directory", path: "/var/lib/mesh/marrytts", mode: "0700" }, { id: "server", type: "container", name: "marrytts", image: pinned("synesthesiam/marytts"), env: { TZ: "Europe/Brussels" }, ports: ["59125"], }, ], }); // --- add, issue (those that serve/emit), assign, then ONE push ---------------------------------- async function add(name: string, manifest: string): Promise { await must(`printf %s ${quote(manifest)} > /tmp/${name}.json && docker cp /tmp/${name}.json mesh-controller:/${name}.json`); await mesh(`module add /${name}.json`); } await add("postgres", postgresManifest); await mesh(`module issue postgres --node ${MACHINE}`); await mesh(`assign ${MACHINE} postgres`); await add("mongodb", mongodbManifest); const mongoIssued = await mesh(`module issue mongodb --node ${MACHINE}`); assert.match(mongoIssued, /scoped to what it emits and consumes/, mongoIssued); await mesh(`assign ${MACHINE} mongodb`); await add("unifi", unifiManifest); const unifiIssued = await mesh(`module issue unifi --node ${MACHINE}`); assert.match(unifiIssued, /scoped to what it emits and consumes/, unifiIssued); await mesh(`assign ${MACHINE} unifi`); // marrytts serves nothing and emits nothing — added and assigned, never issued. await add("marrytts", marryttsManifest); await mesh(`assign ${MACHINE} marrytts`); // The consumers: added and assigned, not issued (they serve nothing). await add("dbuser", dbuserManifest); await mesh(`assign ${MACHINE} dbuser`); await add("mongouser", mongouserManifest); await mesh(`assign ${MACHINE} mongouser`); // ONE push, ONE convergence — six modules resolved and applied together. await mesh(`push ${MACHINE}`); await settled(1_200_000); // unifi-controller + marrytts are heavy (Java/model init) — give convergence room // --- THE co-residence proof: every module's containers are up on the one node -------------------- const running = await must(`docker ps --format '{{.Names}}'`); for (const name of ["mesh-postgres", "postgres", "mesh-mongodb", "mongo", "unifi-controller", "mesh-unifi", "marrytts"]) { assert.match(running, new RegExp(`(^|\\n)${name}(\\n|$)`), `${name} is not running after a co-resident push:\n${running}\n---host log---\n${(await on(`tail -40 /var/log/mesh-host.log`)).out}`); } // Each provider/tooled module got its own scoped broker account; marrytts (no runtime) gets none. const users = await must(`docker exec mesh-broker lavinmqctl list_users 2>&1`); for (const acct of ["anchor-postgres", "anchor-mongodb", "anchor-unifi"]) { assert.match(users, new RegExp(acct), `the scoped account ${acct} is not on the broker:\n${users}`); } // --- postgres provisioned: the consumer got a credential that connects (the known-good control) -- let dbBoundRaw = ""; const untilDbBound = Date.now() + 90_000; while (Date.now() < untilDbBound) { const got = await on(`cat /var/lib/dbuser/db.json 2>/dev/null`); if (got.ok && /"as"/.test(got.out)) { dbBoundRaw = got.out; break; } await new Promise((r) => setTimeout(r, 3000)); } assert.match(dbBoundRaw, /"as"/, `postgres never granted the consumer its database:\n${dbBoundRaw}`); const dbBound = JSON.parse(dbBoundRaw) as { as: string; provision: string }; assert.equal(dbBound.provision, "postgres-database"); const dbAs = dbBound.as; const dbPassword = (await must(`cat /var/lib/dbuser/db.secret`)).trim(); assert.ok(dbAs && dbPassword, `the consumer's login or password was empty (as=${dbAs})`); const conn = `postgresql://${dbAs}:${encodeURIComponent(dbPassword)}@postgres:5432/${dbAs}?sslmode=disable`; let pg = { out: "", ok: false }; const untilConn = Date.now() + 90_000; while (Date.now() < untilConn) { pg = await on(`docker exec mesh-postgres psql ${quote(conn)} -tAc 'select 1' 2>&1`); if (pg.ok && /^1$/m.test(pg.out)) break; if (/authentication failed/i.test(pg.out)) break; await new Promise((r) => setTimeout(r, 3000)); } assert.doesNotMatch(pg.out, /authentication failed/i, `postgres delivered a password that does not authenticate:\n${pg.out}`); assert.match(pg.out, /^1$/m, `the consumer could not connect to its granted database as ${dbAs}:\n${pg.out}`); // --- mongodb provisioned: the consumer authenticates to its database with the mesh-minted key ---- // mongodb's provisioner reconciles the contributions the mesh writes at MESH_RECEIVES (ADR 0048) // and creates a database + owning user under exactly the login the mesh derived and the password it // minted. The proof is that mongouser authenticates as that login with that password — a // provisioner that invented its own would fail authentication. let mongoBoundRaw = ""; const untilMongoBound = Date.now() + 90_000; while (Date.now() < untilMongoBound) { const got = await on(`cat /var/lib/mongouser/db.json 2>/dev/null`); if (got.ok && /"as"/.test(got.out)) { mongoBoundRaw = got.out; break; } await new Promise((r) => setTimeout(r, 3000)); } assert.match(mongoBoundRaw, /"as"/, `mongodb never granted the consumer its database:\n${mongoBoundRaw}`); const mongoBound = JSON.parse(mongoBoundRaw) as { as: string; provision: string }; assert.equal(mongoBound.provision, "mongodb-database"); const mongoAs = mongoBound.as; const mongoPassword = (await must(`cat /var/lib/mongouser/db.secret`)).trim(); assert.ok(mongoAs && mongoPassword, `the consumer's login or password was empty (as=${mongoAs})`); const mongoUri = `mongodb://${encodeURIComponent(mongoAs)}:${encodeURIComponent(mongoPassword)}` + `@mongo:27017/${encodeURIComponent(mongoAs)}?authSource=${encodeURIComponent(mongoAs)}`; const mongoProbe = `mongosh ${quote(mongoUri)} --quiet --eval ${quote(`db.probe.insertOne({ ok: 1 }); print("MONGO_OK")`)}`; let mongoRes = { out: "", ok: false }; const untilMongoConn = Date.now() + 120_000; while (Date.now() < untilMongoConn) { mongoRes = await on(`docker exec mesh-mongodb sh -c ${quote(mongoProbe)} 2>&1`); if (mongoRes.ok && /MONGO_OK/.test(mongoRes.out)) break; if (/authentication failed/i.test(mongoRes.out)) break; await new Promise((r) => setTimeout(r, 3000)); } assert.doesNotMatch(mongoRes.out, /authentication failed/i, `mongodb delivered a credential that does not authenticate:\n${mongoRes.out}\n---runtime log---\n${(await on(`docker logs mesh-mongodb 2>&1 | tail -30`)).out}`); assert.match(mongoRes.out, /MONGO_OK/, `the consumer could not use its granted database as ${mongoAs}:\n${mongoRes.out}`); // --- mongodb and unifi serve their tools over their scoped accounts ------------------------------- let served = ""; const untilServing = Date.now() + 90_000; while (Date.now() < untilServing) { served = await must(`docker exec mesh-broker lavinmqctl list_queues name 2>&1 || true`); if (/serve\.mongodb\.mongodb_list_databases/.test(served) && /serve\.unifi\.unifi_reachable/.test(served)) break; await new Promise((r) => setTimeout(r, 3000)); } assert.match(served, /serve\.mongodb\.mongodb_list_databases/, `mongodb's runtime never bound its serve queue:\n${(await on(`docker logs mesh-mongodb 2>&1 | tail -20`)).out}\n---\n${served}`); assert.match(served, /serve\.unifi\.unifi_reachable/, `unifi's runtime never bound its serve queue:\n${(await on(`docker logs mesh-unifi 2>&1 | tail -20`)).out}\n---\n${served}`); });