diff --git a/scenarios/postgres-node.yml b/scenarios/postgres-node.yml new file mode 100644 index 0000000..36d7ad0 --- /dev/null +++ b/scenarios/postgres-node.yml @@ -0,0 +1,30 @@ +# 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] } + inbound: allow + memory: 3GiB + cpus: 2 + +images: + - postgres:17-alpine + - cloudamqp/lavinmq:latest + - mesh-control:development + # postgres's runtime, built by scripts/build-module-runtime.sh postgres (it carries psql), stocked + # into the scenario's own registry. + - mesh-runtime-postgres:development + +place: + all: [host, runtime] diff --git a/test/integration/postgres-grant-end-to-end.test.ts b/test/integration/postgres-grant-end-to-end.test.ts new file mode 100644 index 0000000..240bfdb --- /dev/null +++ b/test/integration/postgres-grant-end-to-end.test.ts @@ -0,0 +1,247 @@ +/** + * 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/substrate-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 } 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 = "postgres-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 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 substrate'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-control:/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-control:/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}`); +});