/** * The whole grant, mesh-driven end to end — novox/hq ADR 0053 with nothing hand-written. * * The earlier provider tests put the contributions file and the password on disk by hand, standing * in for the control plane. This one does not: a provider (redis) and a consumer (a module that * `requires` redis-cache) are both assigned, and the *mesh* mints the password, seals a copy to each * end, writes redis its contributions file and the consumer its bound file, and the host unseals * each side's secret. redis's provisioner — reading only what the mesh wrote — creates the ACL user * under the login the mesh derived, with the password the mesh minted. The proof is the consumer's * end: the credential the mesh delivered *it* authenticates against the login redis created for it. * Mint on one side and create on the other agreeing, with no shared key and nothing placed by the * test, is the entire provider/consumer contract working as one thing. * * 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, which * scenarios/redis-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, catalogueModule, catalogueIsPresent } 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/)" : catalogueIsPresent(); 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 grants a consumer redis's cache, and the credential it delivers authenticates", { skip, timeout: 900_000, }, async () => { // The PROVIDER: the catalogue's redis (novox/hq 04-ISSUES/074) — server and a broker-bound // runtime on the private redis network, the runtime running the provisioner. It requires a // `secret` for its own password, so the vault that provides one is installed beside it, exactly // as the vault bed does. const vaultManifest = catalogueModule("mesh-vault", held); const redisManifest = catalogueModule("redis", held); // The CONSUMER: a module that requires redis-cache and no more. It runs no code here — the mesh // delivers it a bound file (where redis is, and the login to present) and its sealed password, // which the host unseals onto the machine. That delivery is exactly what a real consumer reads. const consumerManifest = JSON.stringify({ module: "cacheuser", version: "1", // `mesh_anchor_cacheuser` is 21 characters, over the 20 a backend keeps (ADR 0049); the slug // makes the consumer identity `mesh_anchor_cache`. slug: "cache", requires: ["redis-cache"], // `contributes` (not just `requires`) is what makes a consumer *ask* — the grant forms from a // contribution. It must be non-empty; redis's provisioner ignores the value (it uses the login // the mesh derives), so the name is only what marks this module as wanting a cache. contributes: { "redis-cache": { name: "cacheuser" } }, binds: { "redis-cache": "/var/lib/cacheuser/redis.json" }, secrets: { "redis-cache": "/var/lib/cacheuser/redis.secret" }, resources: [{ id: "state", type: "directory", path: "/var/lib/cacheuser", mode: "0700" }], }); await must(`printf %s ${quote(vaultManifest)} > /tmp/mesh-vault.json && docker cp /tmp/mesh-vault.json mesh-controller:/mesh-vault.json`); await mesh("module add /mesh-vault.json"); await mesh(`module issue mesh-vault --node ${MACHINE}`); await mesh(`assign ${MACHINE} mesh-vault`); await must(`printf %s ${quote(redisManifest)} > /tmp/redis.json && docker cp /tmp/redis.json mesh-controller:/redis.json`); await mesh("module add /redis.json"); await mesh(`module issue redis --node ${MACHINE}`); await mesh(`assign ${MACHINE} redis`); await must(`printf %s ${quote(consumerManifest)} > /tmp/cacheuser.json && docker cp /tmp/cacheuser.json mesh-controller:/cacheuser.json`); await mesh("module add /cacheuser.json"); await mesh(`assign ${MACHINE} cacheuser`); await mesh(`push ${MACHINE}`); await settled(); // The mesh matched the two and wrote redis its contributions file — the test wrote nothing here. const contributions = await must(`cat /var/lib/redis-module/grants/mesh.json`); assert.match(contributions, /"as"/, `the mesh did not write redis a contributions file:\n${contributions}`); // 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/cacheuser/redis.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 cache:\n${boundRaw}`); const bound = JSON.parse(boundRaw) as { as: string; from: string; provision: string }; assert.equal(bound.provision, "redis-cache"); assert.ok(bound.from, `the consumer was not told which node serves its cache:\n${boundRaw}`); const as = bound.as; const password = (await must(`cat /var/lib/cacheuser/redis.secret`)).trim(); assert.ok(as && password, `the consumer's login or password was empty (as=${as})`); // redis's provisioner, reading only the mesh's contributions, created the ACL user. Wait for it. const adminPw = await must(`cat /var/lib/redis-module/default.secret`); let acl = ""; const untilAcl = Date.now() + 60_000; while (Date.now() < untilAcl) { acl = (await on(`docker exec redis redis-cli -a ${quote(adminPw)} --no-auth-warning ACL LIST 2>/dev/null`)).out; if (acl.includes(as)) break; await new Promise((r) => setTimeout(r, 3000)); } assert.match(acl, new RegExp(as.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")), `redis never created the login the mesh granted (${as}):\n${(await on(`docker logs mesh-redis 2>&1 | tail -30`)).out}\n---\n${acl}`); // THE PROOF, from the consumer's side: the credential the mesh delivered *it* — the login from its // bound file, the password from its secret — authenticates against the login redis created. Mint // and create agreeing across the two ends, with no shared key and nothing the test placed. const authed = await on(`docker exec redis redis-cli --user ${quote(as)} --pass ${quote(password)} --no-auth-warning PING 2>&1`); assert.doesNotMatch(authed.out, /WRONGPASS|NOPERM|no password/i, `the consumer's mesh-delivered credential did not authenticate — the two ends do not agree:\n${authed.out}`); assert.match(authed.out, /PONG/, `expected PONG authenticating as the granted consumer:\n${authed.out}`); // And the provider needed no seal key to do it: the password reached it as a file the host left // after unsealing, so MESH_SEAL_KEY is set nowhere (novox/hq ADR 0048). Carried over from the // retired provider-uses-mesh-credential bed, whose other proofs this bed makes with the mesh // writing the contributions rather than the bed. const runtimeEnv = await must(`docker inspect mesh-redis --format '{{json .Config.Env}}'`); assert.doesNotMatch(runtimeEnv, /MESH_SEAL_KEY/, `a seal key was set after all — ADR 0048 is not what ran:\n${runtimeEnv}`); // A grant means exactly the consumer's own keys: under its name it reads and writes, outside it // and on the server as a whole it is refused. Carried over from the large mesh bed's retired // cache-grant test — without this a provisioner that granted everything would keep every bed green. const asConsumer = (command: string) => on(`docker exec redis redis-cli --user ${quote(as)} --pass ${quote(password)} --no-auth-warning ${command} 2>&1`); assert.match((await asConsumer("SET cacheuser:proof yes")).out, /OK/, "the consumer cannot write under its own name"); assert.match((await asConsumer("GET cacheuser:proof")).out, /yes/, "the consumer cannot read back what it wrote"); assert.match((await asConsumer("SET other:proof no")).out, /NOPERM|no permissions/i, "the consumer wrote outside its own keys, so the grant means more than it says"); assert.match((await asConsumer("FLUSHALL")).out, /NOPERM|no permissions/i, "the consumer flushed the whole server, so the grant means more than it says"); });