One name per thing, per the HQ glossary: the module/container/image/binary/repo becomes mesh-controller, the seat the-controller, and the store+broker pair the foundation (embedded base bundles, default template and example lock renamed with their go:embed directives). No behaviour change — a pure vocabulary rename. Claude-Session: https://claude.ai/code/session_01D6qtiYU3P9jk3pnAXyAFyx
242 lines
11 KiB
TypeScript
242 lines
11 KiB
TypeScript
/**
|
|
* 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<string> {
|
|
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<string> {
|
|
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<void> {
|
|
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}`);
|
|
});
|