/** * The mesh assigns the route-proxy provider and a hello-web consumer, and a request to the * consumer's name — sent to the proxy — is forwarded to the workload and returns the workload's own * answer. Then the consumer is unassigned and the same request stops working. This is the * route-forwarding half of exposure, mesh-driven end to end (novox/hq ADR 0007, 08-connectivity * §3), with nothing hand-written. * * **A route is a grant.** hello-web `requires: route` and contributes `{name, port}`; route-proxy * `provides: route`, and the *mesh* writes it the contributions file (`receives.route`) — the test * places nothing. The proxy reads that file as $ROUTES and forwards by the `Host` header to * `http://:`, where `at` is where the mesh says the consumer is (empty here — co-located — * so 127.0.0.1, the published backend port). The two claims this bed proves, straight from * 08-connectivity §3's "Checked in the lab": * * - a request to the consumer's name reaches the workload across the proxy and returns its answer; * - unassigning the module withdraws the route and the same request stops working — the proxy * replaces its table rather than merging, so a name whose module left is no longer served. * * route-proxy carries no broker account, no own-secrets and no provisioner: it neither mints a * credential nor emits an event, it only reads the file the mesh writes. So `module add` → `assign` * → ONE `push` is the whole sequence for each of the two modules, with no `module issue` (as * schedule-tick and the run-once bed established for a module that needs no scoped account). * * This bed proves ROUTE-FORWARDING over plain HTTP. The public-ACME/TLS half — ordering a * publicly-trusted certificate and answering an HTTP-01 challenge at the name — is proven separately * by certificates.test.ts, which drives the same proxy binary against a real ACME server (Pebble). * * MESH_LAB_HOST_BINARY=.../mesh-host MESH_LAB_BUNDLE=.../examples/foundation-first-node.lock * scripts/build-route-proxy-image.sh builds mesh-route-proxy:development into the local daemon; * scenarios/route-forwarding.yml stocks it and alpine:latest, and serves both by digest. */ 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, catalogueModule, catalogueIsPresent, deriveTheFilterOn } 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 = "route-forwarding"; const MACHINE = "anchor"; const NAME = "hello.example"; const PAGE = "hello from hello-web, routed by the mesh"; /** The node's public domain; hello-web's label composes under it (ADR 0066). */ const DOMAIN = "example"; 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; } /** 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. */ /** 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}`); } /** A request to the proxy carrying the consumer's public name. The proxy binds :80 on the machine's * own network (network: host), so it is reached at 127.0.0.1 from inside the machine. */ async function throughProxy(host: string): Promise<{ out: string; ok: boolean }> { return on(`curl -s --max-time 5 -H ${quote(`Host: ${host}`)} http://127.0.0.1/`); } 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 the host runs 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 routes a public name through the proxy to the consumer, and withdraws it on unassign", { skip, timeout: 1_500_000, }, async () => { // All three from the catalogue (novox/hq ADR 0093, issue 074): the authority the proxy requires, // the proxy, and the consumer. The proxy's manifest names the runtime image the scenario stocks; // the authority and the consumer's server are pulled upstream by digest. The name the consumer // is routed under is composed from its label and the node's public domain (ADR 0066), which // the bed sets first. await mesh(`node public-domain ${MACHINE} ${DOMAIN}`); // The authority certifies itself for the machine's private-network address, which is what a // consumer on any node dials (ADR 0098); a machine raised from the bundle has none until it is // placed on the overlay. Placed as a hub of one, the way a real first node is, and converged // BEFORE the modules arrive: the proxy fetches the authority's roots at that address at first // start, so the interface must exist by then — in one push the order between modules is not // promised. The derived filter admits the hub's port, as genesis does on a control-node (ADR 0088). await mesh(`overlay place ${MACHINE} --hub --endpoint 192.0.2.10:51820 --site lab`); await mesh(`assign ${MACHINE} networking`); await mesh(`push ${MACHINE}`); await settled(); await deriveTheFilterOn({ machine: MACHINE, node: MACHINE, hubPort: 51820, must: (_m, c, t) => must(c, t), mesh, on: (_m, c, t) => on(c, t) }); const overlay = await must(`ip -4 addr show dev mesh0 2>&1 || ip -4 addr 2>&1`); assert.match(overlay, /inet 10\./, `${MACHINE} has no private-network address after networking converged:\n${overlay}`); for (const name of ["step-ca", "route-proxy", "hello-web"]) { await must(`printf %s ${quote(catalogueModule(name, held))} > /tmp/${name}.json && docker cp /tmp/${name}.json mesh-controller:/${name}.json`); await mesh(`module add /${name}.json`); if (name === "step-ca") await mesh(`module issue ${name} --node ${MACHINE}`); await mesh(`assign ${MACHINE} ${name}`); } await mesh(`push ${MACHINE}`); await settled(); // The mesh matched the two and wrote route-proxy its contributions file — the test wrote nothing. const routes = await must(`cat /var/lib/route-proxy/routes/mesh.json`); assert.match(routes, new RegExp(NAME.replace(/\./g, "\\.")), `the mesh did not write route-proxy the route for ${NAME}:\n${routes}`); assert.match(routes, /"port": *8080/, `the route did not carry the consumer's port:\n${routes}`); // --- THE PROOF: a request to the name, sent to the proxy, returns the workload's own answer ------ // The proxy polls its routes file every couple of seconds and the backend takes a moment to bind, // so this is retried. It is the exact shape of 08-connectivity §3's lab check. let served = { out: "", ok: false }; const untilServed = Date.now() + 120_000; while (Date.now() < untilServed) { served = await throughProxy(NAME); if (served.ok && served.out.includes(PAGE)) break; await new Promise((r) => setTimeout(r, 3000)); } assert.ok(served.out.includes(PAGE), `the name ${NAME} was never routed to the workload:\n${served.out}\n` + `---routes---\n${routes}\n` + `---proxy log---\n${(await on(`docker logs route-proxy 2>&1 | tail -20`)).out}\n` + `---host log---\n${(await on(`tail -40 /var/log/mesh-host.log`)).out}`); // --- a name the proxy does not serve is refused by name, not with a bare 404 -------------------- const unknown = await throughProxy("nobody-asked-for-this.example"); assert.doesNotMatch(unknown.out, new RegExp(PAGE), `an unrouted name reached the workload:\n${unknown.out}`); assert.match(unknown.out, /no route for/, `the proxy did not name what it serves for an unknown host:\n${unknown.out}`); // --- WITHDRAWAL: unassigning the consumer removes the route, and the same request stops working -- // The file the proxy is given is the whole truth about who has a route, so the proxy replaces its // table rather than merging — a name whose module left is no longer served (08-connectivity §3). await mesh(`unassign ${MACHINE} hello-web`); await mesh(`push ${MACHINE}`); await settled(); let gone = { out: "", ok: false }; const untilGone = Date.now() + 60_000; while (Date.now() < untilGone) { gone = await throughProxy(NAME); if (!gone.out.includes(PAGE)) break; await new Promise((r) => setTimeout(r, 3000)); } assert.doesNotMatch(gone.out, new RegExp(PAGE), `the route outlived the module that asked for it — withdrawal did not take:\n${gone.out}\n` + `---routes---\n${(await on(`cat /var/lib/route-proxy/routes/mesh.json`)).out}`); assert.match(gone.out, /no route for/, `after withdrawal the proxy did not report ${NAME} as unserved:\n${gone.out}`); });