/** Unit-only IO: signed payload serialization and source/fence version routing. * Catalog/role internals have separate actual PostgreSQL acceptance. */ import assert from "node:assert/strict" import { createHash, createHmac, randomUUID } from "node:crypto" import { mkdtemp, writeFile, rm } from "node:fs/promises" import os from "node:os" import path from "node:path" import { test, mock } from "node:test" import { BANDWIDTH_NODE_REGISTRY_DDL } from "./bandwidth-node-registry-schema.js" import { BANDWIDTH_EXTERNAL_NODE_REGISTRY_DDL } from "./bandwidth-external-node-registry-schema.js" import { bandwidthNodeBootstrapSchema, canonicalBandwidthNodeBootstrap, canonicalBandwidthNodeValue, bandwidthNodeRegistrySchemaSourceSha256, bandwidthPeerRegistrySchemaSourceSha256 } from "./bandwidth-node-bootstrap.js" const sha = (value: string | Buffer) => createHash("sha256").update(value).digest("hex") test("v1 canonical bytes/hash stay fixed while v2 explicitly binds the combined DDL", () => { const root = { installationId: randomUUID(), issuerKeySha256: "a".repeat(64), quiescenceProof: "b".repeat(64), registryCatalogSha256: "c".repeat(64), attestationRef: "unit-only explicit operator attestation reference" } const v1 = { format: "mmapp-bandwidth-node-bootstrap-v1", ...root, registrySchemaSourceSha256: bandwidthNodeRegistrySchemaSourceSha256() } assert.equal(bandwidthNodeRegistrySchemaSourceSha256(), sha(BANDWIDTH_NODE_REGISTRY_DDL)) assert.equal(canonicalBandwidthNodeBootstrap(v1), canonicalBandwidthNodeValue(v1)) const v2 = { ...v1, format: "mmapp-bandwidth-node-bootstrap-v2", registrySchemaSourceSha256: bandwidthPeerRegistrySchemaSourceSha256() } assert.equal(bandwidthPeerRegistrySchemaSourceSha256(), sha(BANDWIDTH_NODE_REGISTRY_DDL + "\0" + BANDWIDTH_EXTERNAL_NODE_REGISTRY_DDL)) assert.notEqual(v1.registrySchemaSourceSha256, v2.registrySchemaSourceSha256) assert.equal(canonicalBandwidthNodeBootstrap(v2), canonicalBandwidthNodeValue(v2)) assert.throws(() => bandwidthNodeBootstrapSchema.parse({ ...v2, format: "mmapp-bandwidth-node-bootstrap-v3" })) assert.throws(() => bandwidthNodeBootstrapSchema.parse({ ...v2, upgrade: true })) }) test("source dual-version catalog/role selection, external shapes and unchanged canonical MAC domains", async () => { // This fixture supplies a scalar fake core. Fused core/registry SQL has its // own genuine signed-file frame and owned PostgreSQL acceptance suites. mock.module("./bandwidth-control-registry-identity.js",{namedExports:{assertBandwidthControlRegistryIdentity:async()=>{throw Error("scalar core fixture must not invoke joint SQL")}}}) const counters = { managed: 0, combined: 0, role: 0, externalRole: 0, connections: 0, releases: 0 } let extension = false, externalRoleAllowed = true, drift: (() => void) | undefined const catalog = "c".repeat(64) mock.module("./bandwidth-node-registry-catalog.js", { namedExports: { observeBandwidthNodeRegistryCatalog: async (_sql: unknown, live: () => void) => { counters.managed++; live(); if (extension) throw Error("v1 rejects extension"); return catalog }, observeBandwidthPeerRegistryCatalog: async (_sql: unknown, live: () => void) => { counters.combined++; live(); if (!extension) throw Error("missing external component"); return catalog }, } }) mock.module("./bandwidth-node-registry-role.js", { namedExports: { assertBandwidthNodeRegistryRuntimeRole: async (_sql: unknown, _expected: unknown, live: () => void) => { counters.role++; live() } } }) mock.module("./bandwidth-external-node-registry-role.js", { namedExports: { assertBandwidthExternalNodeRegistryRuntimeRole: async (_sql: unknown, _expected: unknown, live: () => void) => { counters.externalRole++; live(); if (!externalRoleAllowed) throw Error("external role denied") } } }) // Preserve the original fake metadata boundary while production obtains its // same strict component observations in one SQL snapshot. mock.module("./bandwidth-peer-identity.js", { namedExports: { assertBandwidthPeerIdentity: async (sql: { query(text: string): Promise<{ rows: Record[] }> }, expected: Record, live: () => void) => { counters.role++; counters.externalRole++; counters.combined++; live() if (!extension || !externalRoleAllowed || expected.registryCatalogSha256 !== catalog) throw Error("identity refused") const rows = (await sql.query("SELECT installation_id::pg_catalog.text,issuer_key_sha256,quiescence_proof,status FROM mmapp_control.bandwidth_node_authority WHERE id=1")).rows live() if (rows.length !== 1 || rows[0].installation_id !== expected.installationId || rows[0].issuer_key_sha256 !== expected.issuerKeySha256 || rows[0].quiescence_proof !== expected.quiescenceProof || rows[0].status !== "active") throw Error("authority refused") } } }) mock.module("./bandwidth-node-identity.js", { namedExports: { assertBandwidthNodeIdentity: async (sql: {query(text:string):Promise<{rows:Record[]}>}, expected:Record, live:()=>void) => { counters.role++; counters.managed++; live() if(extension || expected.registryCatalogSha256!==catalog)throw Error("v1 identity refused") const rows=(await sql.query("SELECT installation_id::pg_catalog.text,issuer_key_sha256,quiescence_proof,status FROM mmapp_control.bandwidth_node_authority WHERE id=1")).rows live() if(rows.length!==1||rows[0].installation_id!==expected.installationId||rows[0].issuer_key_sha256!==expected.issuerKeySha256||rows[0].quiescence_proof!==expected.quiescenceProof||rows[0].status!=="active")throw Error("v1 authority refused") } } }) const { createConfiguredBandwidthNodeSource } = await import("./bandwidth-node-source.js") const directory = await mkdtemp(path.join(os.tmpdir(), "mm-bootstrap-v2-")), issuerKeyFile = path.join(directory, "issuer"), bootstrapFile = path.join(directory, "bootstrap") const key = Buffer.alloc(32, 71), issuerKeySha256 = sha(key) await writeFile(issuerKeyFile, key); await writeFile(bootstrapFile, JSON.stringify({ unitOnly: true })) const root = { installationId: randomUUID(), issuerKeySha256, quiescenceProof: "b".repeat(64) } let bootstrap = { ...root, format: "mmapp-bandwidth-node-bootstrap-v1" as "mmapp-bandwidth-node-bootstrap-v1" | "mmapp-bandwidth-node-bootstrap-v2", registrySchemaSourceSha256: bandwidthNodeRegistrySchemaSourceSha256(), registryCatalogSha256: catalog, attestationRef: "unit-only explicit bootstrap operator reference" } const sourceRecord = { installationId: root.installationId, controlGeneration: randomUUID(), sourceRecordSha256: "d".repeat(64), databaseName: "unit-control", runtimeRole: "unit-runtime", ownerRole: "unit-owner" } const fence = { verifyNodeBootstrap: async () => ({ bootstrap: structuredClone(bootstrap), source: sourceRecord }), query: async () => { drift?.(); return { rows: [{ installation_id: root.installationId, issuer_key_sha256: issuerKeySha256, quiescence_proof: root.quiescenceProof, status: "active" }] } } } const core = { async connect(_scope: unknown, dispatch: (value: unknown) => Promise) { counters.connections++ return { query: async () => { await dispatch(fence); return { rows: [] } }, release: () => { counters.releases++ } } } } const source = createConfiguredBandwidthNodeSource(core as never, { issuerKeyFile, issuerKeySha256, bootstrapFile }) const scope = () => ({ deadlineAt: Date.now() + 5000 }) const external = { ...root, enrollmentId: randomUUID(), incarnation: randomUUID(), nodeId: randomUUID(), status: "active" } const claim = [{ kind: "software-id", value: "UNIT-SOFTWARE-ID" }] const expected = (purpose: string, value: unknown) => createHmac("sha256", key).update("mmapp-bandwidth-node-" + purpose + "-v1:" + canonicalBandwidthNodeValue(value)).digest("hex") try { let session = await source.open(scope()) assert(counters.managed > 0); assert.equal(counters.combined, 0); assert.equal(counters.externalRole, 0) assert.equal(await session.keyedProof("claim", claim), expected("claim", claim)); session.close() session = await source.open(scope()); await assert.rejects(session.keyedProof("external-alias", external)); session.close() extension = true; await assert.rejects(source.open(scope()), "v1 pin must refuse after extension") bootstrap = { ...bootstrap, format: "mmapp-bandwidth-node-bootstrap-v2", registrySchemaSourceSha256: bandwidthPeerRegistrySchemaSourceSha256() } session = await source.open(scope()); assert(counters.combined > 0); assert(counters.externalRole > 0) const leaseCount = counters.connections assert.equal(await session.keyedProof("external-alias", external), expected("external-alias", external)) assert.equal(await session.keyedProof("claim", claim), expected("claim", claim)) const node = { ...root, nodeId: external.nodeId, claimProof: sha("unit claim") } assert.equal(await session.keyedProof("node", node), expected("node", node)) const event = { ...root, eventId: randomUUID(), enrollmentId: external.enrollmentId, incarnation: external.incarnation, nodeId: external.nodeId, kind: "enroll", oldStatus: null, newStatus: "active", authorityProof: "f".repeat(64) } assert.equal(await session.keyedProof("external-event", event), expected("external-event", event)) for (const invalid of [{ ...external, serverId: 12 }, { ...external, enrollmentId: 12 }]) await assert.rejects(session.keyedProof("external-alias", invalid)) await assert.rejects(session.keyedProof("external-event", { ...event, oldStatus: "active" })) assert.equal(counters.connections, leaseCount, "proof guards use the same lease") session.close() externalRoleAllowed = false; await assert.rejects(source.open(scope())); externalRoleAllowed = true session = await source.open(scope()); drift = () => { bootstrap.quiescenceProof = "e".repeat(64) } await assert.rejects(session.keyedProof("claim", claim), "signed bootstrap cannot change after pin"); drift = undefined; session.close() bootstrap.quiescenceProof = root.quiescenceProof session = await source.open(scope()); const binding = await session.binding(); session.close() const participants = [101, 102].map(serverId => ({ evidence: { version: 1 as const, serverId, sourceProof: "a".repeat(64), authorityGeneration: "unit-original", routingEndpointEpoch: randomUUID(), observedAt: Date.now(), expiresAt: Date.now() + 5000, claims: claim as { kind: "software-id"; value: string }[], physicalUniquenessVerified: false as const, cloneResistanceVerified: false as const }, receipt: { serverId, canonicalNodeId: randomUUID(), incarnation: randomUUID(), status: "active" as const, outcome: "existing" as const }, eventId: randomUUID(), })) const dispatchFence = { ...fence, async query(text: string, values?: unknown[]) { if (text.includes("pg_try_advisory")) return { rows: [{ locked: true }] } if (text.includes("FROM mmapp_control.bandwidth_node_authority")) return fence.query() const p = participants.find(p => p.receipt.serverId === values?.[0]); assert(p) const r = p.receipt, claimProof = expected("claim", p.evidence.claims) if (text.includes("FROM mmapp_control.bandwidth_node_aliases")) return { rows: [{ server_id: r.serverId, incarnation: r.incarnation, node_id: r.canonicalNodeId, status: "active", claim_proof: claimProof, record_mac: expected("alias", { ...root, serverId: r.serverId, incarnation: r.incarnation, nodeId: r.canonicalNodeId, status: "active" }), enrollment_mac: expected("node", { ...root, nodeId: r.canonicalNodeId, claimProof }) }] } assert(text.includes("FROM mmapp_control.bandwidth_node_events")) const event = { ...root, eventId: p.eventId, serverId: r.serverId, incarnation: r.incarnation, nodeId: r.canonicalNodeId, kind: "enroll", oldStatus: null, newStatus: "active", authorityProof: "f".repeat(64) } return { rows: [{ event_id: p.eventId, incarnation: r.incarnation, node_id: r.canonicalNodeId, kind: "enroll", old_status: null, new_status: "active", authority_proof: event.authorityProof, event_mac: expected("event", event) }] } } } const beforeFenceConnections = counters.connections, beforeFenceExternal = counters.externalRole const resolved = participants.map(({ evidence, receipt }) => ({ evidence, receipt })) await source.assertResolvedOnFence(dispatchFence as never, { binding, participants: resolved }, scope()) assert.equal(counters.connections, beforeFenceConnections, "dispatch fence never borrows another lease") assert(counters.externalRole > beforeFenceExternal, "v2 dispatch fence authenticates external runtime role") externalRoleAllowed = false await assert.rejects(source.assertResolvedOnFence(dispatchFence as never, { binding, participants: resolved }, scope())); externalRoleAllowed = true assert(counters.releases > 0) } finally { source.close(); mock.restoreAll(); await rm(directory, { recursive: true, force: true }) } })