diff --git a/scripts/build-module-runtime.sh b/scripts/build-module-runtime.sh index eb10634..dd6b340 100755 --- a/scripts/build-module-runtime.sh +++ b/scripts/build-module-runtime.sh @@ -35,9 +35,18 @@ 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 +# A module whose code drives a CLI needs that CLI in the image — postgres shells out to `psql`, minio +# to `mc`. Everything else speaks a wire protocol or HTTP and needs nothing added. +EXTRA="" +case "$MODULE" in + postgres) EXTRA='RUN apt-get update && apt-get install -y --no-install-recommends postgresql-client && rm -rf /var/lib/apt/lists/*' ;; + minio) EXTRA='COPY --from=minio/mc:latest /usr/bin/mc /usr/bin/mc' ;; +esac + cat > "$STAGE/Dockerfile" < { + 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("redis's runtime, on the backend's private network, binds the broker and provisions with the mesh's credential", { + skip, timeout: 900_000, +}, async () => { + // Exactly the committed redis shape: a private `redis` network, the server on it with a published + // port, and the runtime on it too — reaching redis by name and the broker by NAT. + const manifest = JSON.stringify({ + module: "redis", + version: "1", + provides: [{ name: "redis-cache", scope: "mesh" }], + serves: { "redis-cache": {} }, + emits: ["module.redis.cache.provisioned", "module.redis.cache.deprovisioned"], + consumes: ["module.redis.cache.provisioned", "module.redis.cache.deprovisioned"], + receives: { "redis-cache": "/var/lib/redis-module/grants/mesh.json" }, + grants: { "redis-cache": "/var/lib/redis-module/grants" }, + "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: "net", type: "network", name: "redis" }, + { + id: "server", type: "container", name: "redis", image: pinned("redis"), network: "redis", + ports: ["6379"], + 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: "redis", + volumes: [ + "/var/lib/mesh/redis/broker:/run/secrets/broker:ro", + "/var/lib/redis-module/grants:/var/lib/redis-module/grants:ro", + "/var/lib/redis-module/default.secret:/run/secrets/default:ro", + ], + env: { + MESH_BROKER_FILE: "/run/secrets/broker", + MESH_RECEIVES: "/var/lib/redis-module/grants/mesh.json", + MESH_PROVISION_REDIS: "redis:6379", + MESH_PROVISION_PASSWORD_FILE: "/run/secrets/default", + }, + }, + ], + }); + await must(`printf %s ${quote(manifest)} > /tmp/redis.json && docker cp /tmp/redis.json mesh-control:/redis.json`); + await mesh("module add /redis.json"); + await mesh(`module issue redis --node ${MACHINE}`); + await mesh(`assign ${MACHINE} redis`); + await mesh(`push ${MACHINE}`); + await settled(); + + const running = await must(`docker ps --format '{{.Names}}'`); + assert.match(running, /mesh-redis/, `redis's runtime is not running:\n${(await on(`docker logs mesh-redis 2>&1 | tail -30`)).out}`); + + // It bound the broker from the private network: its scoped account is on the broker. If NAT to the + // broker had failed, the runtime would have crashed and never authenticated. + const users = await must(`docker exec mesh-broker lavinmqctl list_users 2>&1`); + assert.match(users, /anchor-redis/, + `the runtime's scoped account is not on the broker — it did not reach the broker from the bridge:\n` + + `${(await on(`docker logs mesh-redis 2>&1 | tail -30`)).out}`); + + // The mesh delivers the contribution and the unsealed password; the provisioner creates the login. + const password = "mesh-minted-bridge-7c1"; + await must(`printf %s ${quote(password)} > /var/lib/redis-module/grants/app.secret`); + const contributions = JSON.stringify({ + contributions: 1, requirement: "redis-cache", generated: "by the mesh", + given: [{ from: "app", node: "app-node", at: "192.0.2.20:6379", as: "app-one", secret: "/var/lib/redis-module/grants/app.secret", values: {} }], + }); + await must(`printf %s ${quote(contributions)} > /var/lib/redis-module/grants/mesh.json`); + + const adminPw = await must(`cat /var/lib/redis-module/default.secret`); + let acl = ""; + const until = Date.now() + 60_000; + while (Date.now() < until) { + acl = (await on(`docker exec redis redis-cli -a ${quote(adminPw)} --no-auth-warning ACL LIST 2>/dev/null`)).out; + if (/app-one/.test(acl)) break; + await new Promise((r) => setTimeout(r, 3000)); + } + assert.match(acl, /app-one/, `the provisioner never created the login:\n${(await on(`docker logs mesh-redis 2>&1 | tail -30`)).out}\n---\n${acl}`); + + const authed = await on(`docker exec redis redis-cli --user app-one --pass ${quote(password)} --no-auth-warning PING 2>&1`); + assert.doesNotMatch(authed.out, /WRONGPASS/, `the consumer could not authenticate with the mesh's password:\n${authed.out}`); + assert.match(authed.out, /PONG/, `expected PONG:\n${authed.out}`); +});