events: an e2e test — an emitted event reaches the audit trail over the mesh's broker #2

Merged
jschoubben merged 78 commits from events/audit-e2e into initialization 2026-09-05 01:07:06 +00:00
3 changed files with 252 additions and 1 deletions
Showing only changes of commit 37b16cd0e9 - Show all commits
+30
View File
@@ -0,0 +1,30 @@
# One machine that becomes a mesh and then assigns itself the audit logger.
#
# The substrate is first-node's — a store, a broker, the control plane — and one module image on
# top: the tool runtime carrying the audit-logger (mesh-catalog). The node enrols itself and the
# mesh assigns it the audit logger, so its events account is one the mesh delivered, not the
# broker's own (novox/hq ADR 0048).
scenario: audit-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
# The tool runtime with the audit-logger, built by scripts/build-runtime-image.sh into the local
# daemon and stocked into the scenario's own registry, which is where the host pulls it from.
- mesh-runtime-audit:development
place:
all: [host, runtime]
+1 -1
View File
@@ -19,7 +19,7 @@ MESH_TOOLS="${MESH_TOOLS:-$ROOT/mesh-tools}"
MESH_SDK="${MESH_SDK:-$ROOT/mesh-sdk}"
MESH_CATALOG="${MESH_CATALOG:-$ROOT/mesh-catalog}"
AUDIT="$MESH_CATALOG/modules/audit-logger"
TAG="${RUNTIME_TAG:-mesh-runtime-audit:lab}"
TAG="${RUNTIME_TAG:-mesh-runtime-audit:development}"
BASE="${RUNTIME_BASE:-node:22-bookworm-slim}"
echo "building $TAG from:"
+221
View File
@@ -0,0 +1,221 @@
/**
* The mesh assigns the audit logger, and it consumes over an account the mesh delivered.
*
* events.test.ts proves the events path with the audit logger started by hand. This proves the
* whole of novox/hq ADR 0048: the module is assigned through the control plane, the mesh issues it
* a broker account scoped to what it consumes, seals it to the machine, and the host runs it as a
* container that connects over amqps with that account — never the broker's own. The trail filling
* is the proof the delivered, scoped credential authenticated and the subscription bound.
*
* It needs the host binary, the substrate bundle, and the runtime image stocked by the scenario:
*
* MESH_LAB_HOST_BINARY=.../mesh-host
* MESH_LAB_BUNDLE=.../examples/substrate-first-node.lock
* scripts/build-runtime-image.sh builds mesh-runtime-audit:development into the local daemon,
* which scenarios/audit-node.yml stocks — so no MESH_LAB_RUNTIME here; the host pulls it.
*/
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 = "audit-node";
const MACHINE = "anchor";
let instanceId = "";
/** What the scenario's registry serves, by digest. */
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<string> {
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<string> {
return must(`docker exec mesh-control /mesh-control ${command}`, timeoutMs);
}
/** The pinned reference for one of the scenario's images, by repository. */
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;
}
/** The substrate bundle, its image references pointed at this scenario's own registry. */
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<void> {
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;
// Raise the substrate — store, broker, control — from the bundle.
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}`);
}
// The node joins its own mesh, so it is a node the mesh can assign to, and start the host 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 assigns the audit logger, and it consumes over the account the mesh delivered", {
skip, timeout: 900_000,
}, async () => {
// The assigned-module manifest (mesh-catalog), its runtime image the digest this registry serves.
const manifest = JSON.stringify({
module: "audit-logger",
version: "1",
consumes: ["#"],
"own-secrets": { broker: "/var/lib/audit-logger/broker" },
resources: [
{ id: "state", type: "directory", path: "/var/lib/audit-logger", mode: "0700" },
{ id: "trail", type: "directory", path: "/var/lib/audit-logger/trail", mode: "0700" },
{
id: "run", type: "container", name: "mesh-audit-logger", image: pinned("mesh-runtime-audit"),
network: "host",
volumes: [
"/var/lib/audit-logger/broker:/run/secrets/broker:ro",
"/var/lib/audit-logger/trail:/trail",
],
env: { MESH_BROKER_FILE: "/run/secrets/broker", AUDIT_LOG: "/trail/audit.log" },
},
],
});
await must(`printf %s ${quote(manifest)} > /tmp/audit.json && docker cp /tmp/audit.json mesh-control:/audit.json`);
await mesh("module add /audit.json");
// The mesh issues its scoped account and seals it to this machine, then assigns and pushes it.
const issued = await mesh(`module issue audit-logger --node ${MACHINE}`);
assert.match(issued, /scoped to what it emits and consumes/, issued);
await mesh(`assign ${MACHINE} audit-logger`);
await mesh(`push ${MACHINE}`);
await settled();
// The container the mesh started is running.
const running = await must(`docker ps --format '{{.Names}}'`);
assert.match(running, /mesh-audit-logger/,
`the audit logger was assigned and is not running:\n${(await on(`tail -30 /var/log/mesh-host.log`)).out}`);
// The credential on disk is the scoped account over amqps, sealed — not the broker's own.
const credential = await must(`cat /var/lib/audit-logger/broker`);
assert.match(credential, /"url":"amqps:\/\/anchor-audit-logger:/, `not the scoped account:\n${credential}`);
assert.doesNotMatch(credential, /guest:guest/, "the audit logger holds the broker's own account");
assert.match(credential, /"fingerprint":"(sha256:)?[0-9a-f]{64}"/, "no fingerprint to pin the broker");
// An event, emitted by a probe over the bootstrap account (the audit logger's own may not emit).
await must(
`docker run --rm --network host -e MESH_BROKER_URL=amqp://guest:guest@127.0.0.1:5672/ ` +
`-e MESH_MODULE=probe -e MESH_NODE=${MACHINE} ${pinned("mesh-runtime-audit")} ` +
`emit module.probe.site.created '{"domain":"my-app"}'`,
);
// It reaches the trail the assigned container writes — proof its delivered account authenticated.
let line: Record<string, unknown> | undefined;
const until = Date.now() + 60_000;
while (Date.now() < until) {
const raw = await must(`cat /var/lib/audit-logger/trail/audit.log 2>/dev/null || true`);
line = raw.split("\n").map((l) => l.trim()).filter(Boolean).map((l) => JSON.parse(l) as Record<string, unknown>)
.find((e) => e.type === "module.probe.site.created");
if (line) break;
await new Promise((r) => setTimeout(r, 3000));
}
assert.ok(line, `the event never reached the trail:\n${(await on(`docker logs mesh-audit-logger 2>&1 | tail -20`)).out}`);
assert.equal(line.source, "probe");
assert.deepEqual(line.body, { domain: "my-app" });
// And the account the mesh made for it is a real one on the broker — the trail above already
// proved it authenticated and read its queue. That it reaches no further than its own queue is
// the scope CreateModuleAccount applies, checked as patterns in mesh-control's own tests.
const users = await must(`docker exec mesh-broker lavinmqctl list_users 2>&1`);
assert.match(users, /anchor-audit-logger/, `the scoped account is not on the broker:\n${users}`);
});