/** Actual signed files and configured source; only catalog SQL and the core * transport are synthetic. This does not establish PostgreSQL acceptance. */ import assert from "node:assert/strict" import { createHash, createHmac, generateKeyPairSync, randomUUID, sign, verify } from "node:crypto" import { mkdtemp, rm, writeFile } from "node:fs/promises" import os from "node:os" import path from "node:path" import { mock, test } from "node:test" import { bandwidthNodeBootstrapSchema, canonicalBandwidthNodeBootstrap, canonicalBandwidthNodeValue, bandwidthNodeRegistrySchemaSourceSha256, bandwidthPeerRegistrySchemaSourceSha256 } from "./bandwidth-node-bootstrap.js" import type { BandwidthNodeProofInput } from "./bandwidth-node-source.js" const sha = (value: Buffer | string) => createHash("sha256").update(value).digest("hex") const deferred = () => { let resolve!: () => void; const promise = new Promise(done => { resolve = done }); return { promise, resolve } } test("configured source atomic MAC batch boundaries", async t => { mock.module("./bandwidth-control-registry-identity.js",{namedExports:{assertBandwidthControlRegistryIdentity:async()=>{throw Error("scalar core fixture must not invoke joint SQL")}}}) const identity = async (sql: { query(text: string): Promise }, _expected: unknown, live: () => void) => { live(); await sql.query("synthetic catalog boundary"); live() } mock.module("./bandwidth-node-identity.js", { namedExports: { assertBandwidthNodeIdentity: identity } }) mock.module("./bandwidth-peer-identity.js", { namedExports: { assertBandwidthPeerIdentity: identity } }) const { createConfiguredBandwidthNodeSource } = await import("./bandwidth-node-source.js") async function fixture(v2 = true) { const directory = await mkdtemp(path.join(os.tmpdir(), "mm-node-proof-batch-")) const issuerKeyFile = path.join(directory, "issuer"), bootstrapFile = path.join(directory, "bootstrap") const key = Buffer.alloc(32, 81), keys = generateKeyPairSync("ed25519") const root = { installationId: randomUUID(), issuerKeySha256: sha(key), quiescenceProof: "b".repeat(64) } const bootstrap = { ...root, format: v2 ? "mmapp-bandwidth-node-bootstrap-v2" : "mmapp-bandwidth-node-bootstrap-v1", registrySchemaSourceSha256: v2 ? bandwidthPeerRegistrySchemaSourceSha256() : bandwidthNodeRegistrySchemaSourceSha256(), registryCatalogSha256: "c".repeat(64), attestationRef: "explicit unit operator bootstrap attestation" } const publish = async () => { const payload = Buffer.from(canonicalBandwidthNodeBootstrap(bootstrap)); await writeFile(bootstrapFile, JSON.stringify({ payload: payload.toString("base64url"), signature: sign(null, payload, keys.privateKey).toString("base64url") })) } await writeFile(issuerKeyFile, key); await publish() let queries = 0, connections = 0, releases = 0, guards = 0, revoked = false let metadataHook: (() => Promise) | undefined const sourceRecord = { installationId: root.installationId, controlGeneration: randomUUID(), sourceRecordSha256: "d".repeat(64), databaseName: "mock-control", runtimeRole: "mock-runtime", ownerRole: "mock-owner" } const fence = { async verifyNodeBootstrap(raw: unknown) { const signed = raw as { payload: string; signature: string }, payload = Buffer.from(signed.payload, "base64url") assert(verify(null, payload, keys.publicKey, Buffer.from(signed.signature, "base64url"))) return { bootstrap: bandwidthNodeBootstrapSchema.parse(JSON.parse(payload.toString())), source: { ...sourceRecord } } }, async query() { await metadataHook?.(); return { rows: [] } }, } const core = { async connect(_scope: unknown, dispatch: (value: unknown) => Promise) { connections++ return { async query() { queries++; await dispatch(fence); await dispatch(fence); return { rows: [] } }, release() { releases++ } } } } const source = createConfiguredBandwidthNodeSource(core as never, { issuerKeyFile, bootstrapFile, issuerKeySha256: root.issuerKeySha256 }) const originalGuard=async()=>{guards++;if(revoked)throw Error("original authority revoked")} const open = (signal?: AbortSignal, lifetime = 5000) => source.open({ deadlineAt: Date.now() + lifetime, signal }, originalGuard) const openOwned=(ownership:Parameters[2])=>source.openWithOwnershipFence({deadlineAt:Date.now()+5000},originalGuard,ownership) const nodeId = randomUUID(), incarnation = randomUUID(), eventId = randomUUID() const subject = v2 ? { enrollmentId: randomUUID() } : { serverId: 71 } const batch = (): BandwidthNodeProofInput[] => [ { purpose: "node", value: { ...root, nodeId, claimProof: "e".repeat(64) } }, { purpose: v2 ? "external-alias" : "alias", value: { ...root, ...subject, nodeId, incarnation, status: "active" } }, { purpose: v2 ? "external-event" : "event", value: { ...root, ...subject, nodeId, incarnation, eventId, kind: "enroll", oldStatus: null, newStatus: "active", authorityProof: "f".repeat(64) } }, ] const expected = (items: readonly BandwidthNodeProofInput[]) => items.map(({ purpose, value }) => createHmac("sha256", key).update("mmapp-bandwidth-node-" + purpose + "-v1:" + canonicalBandwidthNodeValue(value)).digest("hex")) return { source, open, openOwned, batch, expected, root, bootstrap, sourceRecord, publish, issuerKeyFile, counts: () => ({ queries, connections, releases, guards }), hook: (value?: () => Promise) => { metadataHook = value }, revoke: () => { revoked = true }, async dispose() { source.close(); await rm(directory, { recursive: true, force: true }) } } } try { await t.test("raw ownership probes share the lease and files plus original authority remain checked afterward",async()=>{ for(const fault of ["none","key","grant"] as const){const f=await fixture();try{ let probes=0,armed=false const session=await f.openOwned(async fence=>{ probes++;await fence.query("fixed synthetic ownership probe") if(armed&&fault==="key")await writeFile(f.issuerKeyFile,Buffer.alloc(32,82)) if(armed&&fault==="grant")f.revoke() }) const before=f.counts().queries;armed=true if(fault==="none"){assert.deepEqual(await session.keyedProofs(f.batch()),f.expected(f.batch()));assert.equal(f.counts().queries-before,1);assert.equal(f.counts().connections,1);assert(probes>=4);session.close()} else{await assert.rejects(session.keyedProofs(f.batch()));assert.equal(f.counts().releases,1)} }finally{await f.dispose()}} }) await t.test("both versions preserve scalar domains, one fresh cycle and frozen output", async () => { for (const v2 of [false, true]) { const f = await fixture(v2); try { const session = await f.open(), before = f.counts(), items = f.batch() const result = await session.keyedProofs(items) assert.deepEqual(result, f.expected(items)); assert(Object.isFrozen(result)) assert.equal(f.counts().queries - before.queries, 1); assert.equal(f.counts().connections, 1) assert.equal(f.counts().guards - before.guards, 2, "original guard surrounds physical query") for (let index = 0; index < items.length; index++) assert.equal(await session.keyedProof(items[index].purpose, items[index].value), result[index]) session.close() } finally { await f.dispose() } } }) await t.test("capture precedes blocked metadata and caller mutation cannot change any MAC", async () => { const f = await fixture(); try { const session = await f.open(), entered = deferred(), unblock = deferred(), items = f.batch(), expected = f.expected(items) f.hook(async () => { entered.resolve(); await unblock.promise }) const pending = session.keyedProofs(items); await entered.promise ;(items[0].value as Record).claimProof = "a".repeat(64) items[1] = { purpose: "claim", value: [{ kind: "system-id", value: "replacement" }] }; items.length = 1 unblock.resolve(); assert.deepEqual(await pending, expected); session.close() } finally { await f.dispose() } }) await t.test("accessors, sparse/symbol/serializer inputs and bounds reject before IO without executing caller code", async () => { const f = await fixture(); try { const session = await f.open(), before = f.counts().queries; let calls = 0 const getter = { purpose: "node", get value() { calls++; return f.batch()[0].value } } const nested = { ...f.batch()[0], value: { get installationId() { calls++; return f.root.installationId } } } const sparse = new Array(3); sparse[0] = f.batch()[0] const symbol = Object.assign(f.batch()[0], { [Symbol("hidden")]: "hidden" }) const serializer = { purpose: "node", value: { toJSON() { calls++; return f.batch()[0].value } } } for (const invalid of [[], sparse, [getter], [nested], [symbol], [serializer], [...f.batch(), ...f.batch()], [{ purpose: "claim", value: [{ kind: "system-id", value: "x".repeat(65537) }] }]]) await assert.rejects(session.keyedProofs(invalid)) assert.equal(calls, 0); assert.equal(f.counts().queries, before); session.close() } finally { await f.dispose() } }) await t.test("one wrong root or external domain under v1 rejects the entire batch", async () => { for (const external of [false, true]) { const f = await fixture(false); try { const session = await f.open(), items = f.batch() items[2] = external ? { purpose: "external-alias", value: { ...f.root, enrollmentId: randomUUID(), nodeId: randomUUID(), incarnation: randomUUID(), status: "active" } } : { ...items[2], value: { ...(items[2].value as object), installationId: randomUUID() } } await assert.rejects(session.keyedProofs(items)); assert.equal(f.counts().releases, 1) } finally { await f.dispose() } } }) await t.test("key/bootstrap/source drift and last authority revocation after metadata refuse all MACs", async () => { for (const fault of ["key", "bootstrap", "source", "grant"] as const) { const f = await fixture(); try { const session = await f.open(); let applied = false f.hook(async () => { if (applied) return; applied = true if (fault === "key") await writeFile(f.issuerKeyFile, Buffer.alloc(32, 82)) if (fault === "bootstrap") { f.bootstrap.quiescenceProof = "a".repeat(64); await f.publish() } if (fault === "source") f.sourceRecord.sourceRecordSha256 = "a".repeat(64) if (fault === "grant") f.revoke() }) await assert.rejects(session.keyedProofs(f.batch())); assert.equal(f.counts().releases, 1) } finally { await f.dispose() } } }) await t.test("abort/expiry during blocked IO retires once and a late result cannot resume", async () => { for (const expire of [false, true]) { const f = await fixture(); const unblock = deferred(); try { const abort = new AbortController(), session = await f.open(abort.signal, expire ? 200 : 5000), entered = deferred() f.hook(async () => { entered.resolve(); await unblock.promise }) const pending = session.keyedProofs(f.batch()), rejected = assert.rejects(pending) await entered.promise; if (!expire) abort.abort(); await rejected assert.equal(f.counts().releases, 1); unblock.resolve() await assert.rejects(session.binding()); assert.equal(f.counts().releases, 1) } finally { unblock.resolve(); await f.dispose() } } }) await t.test("concurrent batch/scalar or binding destroys the lease instead of overlapping", async () => { for (const scalar of [false, true]) { const f = await fixture(); const unblock = deferred(); try { const session = await f.open(), entered = deferred() f.hook(async () => { entered.resolve(); await unblock.promise }) const first = assert.rejects(session.keyedProofs(f.batch())); await entered.promise await assert.rejects(scalar ? session.keyedProof("claim", [{ kind: "system-id", value: "second" }]) : session.binding()) await first; unblock.resolve(); assert.equal(f.counts().releases, 1) } finally { unblock.resolve(); await f.dispose() } } }) } finally { mock.restoreAll() } })