/** Genuine signed original reader/window/guard. SQL session ownership and Q * are explicit inert fixture models, NOT actual PostgreSQL/Docker enforcement. */ import assert from "node:assert/strict" import { createHash, generateKeyPairSync, randomUUID, sign } from "node:crypto" import { lstat, mkdir, mkdtemp, realpath, rm, writeFile } from "node:fs/promises" import { tmpdir } from "node:os" import { basename, dirname, join } from "node:path" import { test } from "node:test" import { setTimeout as delay } from "node:timers/promises" import { bandwidthOperatorEnrollmentGrantSchema } from "./bandwidth-operator-enrollment.js" import { canonicalBandwidthNodeValue } from "./bandwidth-node-bootstrap.js" import { assertBandwidthOperatorPeerSourceGuard, createBandwidthOperatorExternalFencer, createBandwidthOperatorOriginalAuthorityReader, createBandwidthOperatorWriterWindows, type BandwidthOperatorPeerSourceBinding, type BandwidthOperatorPeerSourceGuard, type BandwidthOperatorRegistryBorrow, type BandwidthOperatorScope } from "./bandwidth-operator-writer-window.js" const scope = (ms = 4000, signal?: AbortSignal) => ({ deadlineAt: Date.now() + ms, ...(signal ? { signal } : {}) }) test("genuine operator peer source guard binds original held window", async t => { const root = await realpath(tmpdir()), folder = await mkdtemp(join(root, "bw-peer-source-guard-")), cleanup: Array<() => void> = [] let ordinal = 0, lifetimeGetters = 0 async function fixture(ttl = 4000, lifetimeMode: "normal" | "missing" | "hostile" | "accessor" | "proxy" | "aborted" = "normal") { const directory = join(folder, String(++ordinal)); await mkdir(directory) const keys = generateKeyPairSync("ed25519"), trustKeyFile = join(directory, "operator.pub"), grantFile = join(directory, "grant.json") await writeFile(trustKeyFile, keys.publicKey.export({ type: "spki", format: "pem" })) const rootFields = { installationId: randomUUID(), issuerKeySha256: "a".repeat(64), quiescenceProof: "b".repeat(64) } const grant = bandwidthOperatorEnrollmentGrantSchema.parse({ format: "mmapp-bandwidth-operator-enrollment-v1", ...rootFields, grantId: randomUUID(), operatorId: "synthetic-peer-guard", executorInventorySha256: "c".repeat(64), executorsStoppedAt: Date.now() - 2000, issuedAt: Date.now() - 1000, expiresAt: Date.now() + 60000, peerRef: { kind: "external", enrollmentId: randomUUID() }, sourceProof: "d".repeat(64), authorityGeneration: "synthetic-original-source", routingEndpointEpoch: randomUUID(), claims: [{ kind: "system-id", value: "SYNTHETIC-PEER-GUARD" }] }) const publish = async (value = grant) => { const payload = Buffer.from(canonicalBandwidthNodeValue(value)); await writeFile(grantFile, JSON.stringify({ format: "mmapp-bandwidth-operator-enrollment-envelope-v1", payload: payload.toString("base64url"), signature: sign(null, payload, keys.privateKey).toString("base64url") })) } await publish() const originals = createBandwidthOperatorOriginalAuthorityReader({ ...rootFields, trustKeyFile, grantFile, trustKeySha256: createHash("sha256").update(keys.publicKey.export({ type: "spki", format: "der" })).digest("hex") }) let q = 0, queries = 0, heldQueries = 0, opens = 0, destroys = 0, externalCloses = 0, secrets = 0, held = false, pid = 777, qAllowed = true, physicalClosed = false, closing = false const leaseLifetime = new AbortController() if (lifetimeMode === "hostile") Object.defineProperties(leaseLifetime.signal, { aborted: { get() { lifetimeGetters++; throw Error("No own getter") } }, addEventListener: { value() { lifetimeGetters++; throw Error("No own method") } }, removeEventListener: { value() { lifetimeGetters++; throw Error("No own method") } }, }) if (lifetimeMode === "aborted") leaseLifetime.abort() let heldHook: (() => Promise) | undefined, qHook: (() => Promise) | undefined let registerHook: ((borrowed: BandwidthOperatorRegistryBorrow, requested: BandwidthOperatorScope) => Promise) | undefined const caller = new AbortController(), originalScope = scope(ttl, caller.signal), authority = await originals.acquire(originalScope) const external = createBandwidthOperatorExternalFencer({ async acquire() { return { async assertCurrent() { q++; await qHook?.(); if (!qAllowed) throw Error("synthetic Q revoked") }, close() { externalCloses++ }, } } }) const windows = createBandwidthOperatorWriterWindows({ originals, external, source: { async open(_requested, guard) { opens++; await guard() const connection = { release() { throw Error("Owner-only physical close") }, async query(text: string) { assert(!physicalClosed); await guard(); queries++ if (text.includes("pg_try_advisory_lock")) { held = true; return { rows: [{ acquired: true }] } } if (text.includes("pg_locks")) { heldQueries++; await heldHook?.(); return { rows: [{ held, backend_pid: pid }] } } if (text.includes("pg_backend_pid()")) return { rows: [{ backend_pid: pid }] } if (["BEGIN", "COMMIT"].includes(text)) return { rows: [], command: text } throw Error("Unexpected fixed fixture SQL") }, } if (lifetimeMode !== "missing") Object.defineProperty(connection, "lifetimeSignal", lifetimeMode === "accessor" ? { enumerable: true, get() { lifetimeGetters++; return leaseLifetime.signal } } : { enumerable: true, value: lifetimeMode === "proxy" ? new Proxy(leaseLifetime.signal, { getPrototypeOf() { lifetimeGetters++; throw Error("No proxy trap") } }) : leaseLifetime.signal }) return { async binding() { await guard(); return rootFields }, async keyedProof() { secrets++; throw Error("No secret MAC permitted") }, close() { if (!closing) { closing = true; leaseLifetime.abort(); physicalClosed = true; held = false; destroys++ } }, connection } }, }, registry: { async register(_original, borrowed, requested) { await registerHook?.(borrowed, requested); await borrowed.connection.query("BEGIN"); await borrowed.connection.query("COMMIT"); borrowed.connection.release(true); return "synthetic-registry-complete" } } }) cleanup.push(() => { windows.close(); originals.close() }) const window = await windows.open(authority, originalScope) const binding: BandwidthOperatorPeerSourceBinding = { peerRef: grant.peerRef, sourceProof: grant.sourceProof, authorityGeneration: grant.authorityGeneration, routingEndpointEpoch: grant.routingEndpointEpoch } return { windows, originals, authority, window, binding, grant, publish, caller, guard: () => windows.createPeerSourceGuard(window, authority), reset() { q = queries = heldQueries = 0 }, counts: () => ({ q, queries, heldQueries, opens, destroys, externalCloses, secrets }), loseLock() { held = false }, loseOwner() { leaseLifetime.abort() }, changePid() { pid++ }, revokeQ() { qAllowed = false }, heldHook(value: typeof heldHook) { heldHook = value }, qHook(value: typeof qHook) { qHook = value }, registerHook(value: typeof registerHook) { registerHook = value } } } try { await t.test("brand rejects flags/JSON/copies; genuine read checks actual same fixture lease/PID with Q", async () => { const f = await fixture(), guard = f.guard(); f.reset() assertBandwidthOperatorPeerSourceGuard(guard) assert.equal(guard.installationId, f.grant.installationId) assert.deepEqual(Object.keys(guard).sort(), ["installationId", "verifyMetadata", "verifyRead"]) const installation = Object.getOwnPropertyDescriptor(guard, "installationId")! assert.equal(installation.value, f.grant.installationId); assert.equal(installation.writable, false); assert.equal(installation.configurable, false); assert(!installation.get) for (const fake of [{ verifyRead: async () => {}, verifyMetadata: async () => {} }, { ...guard }, JSON.parse(JSON.stringify(guard)), { ready: true }]) assert.throws(() => assertBandwidthOperatorPeerSourceGuard(fake)) await guard.verifyRead(f.binding, scope()); assert.equal(f.counts().heldQueries, 1); assert(f.counts().q > 0) assert.equal(f.counts().opens, 1); assert.equal(f.counts().secrets, 0) }) await t.test("metadata checks signed original only: zero Q/SQL/secret, never a held/Q proof", async () => { const f = await fixture(), guard = f.guard(); f.reset(); f.revokeQ(); f.loseLock() await guard.verifyMetadata(f.binding, scope()); assert.equal(f.counts().q + f.counts().queries + f.counts().secrets, 0) await assert.rejects(guard.verifyRead(f.binding, scope())); assert.equal(f.counts().destroys, 1) }) await t.test("missing/copied window or foreign original cannot mint a genuine guard", async () => { const f = await fixture(); f.reset() assert.throws(() => f.windows.createPeerSourceGuard({}, f.authority)); assert.throws(() => f.windows.createPeerSourceGuard({ ...f.window }, f.authority)) const foreign = await f.originals.acquire(scope()) assert.throws(() => f.windows.createPeerSourceGuard(f.window, foreign)); assert.equal(f.counts().destroys, 1); assert.equal(f.counts().queries, 0) }) await t.test("tuple drift/proxies/accessors fail before any secret or held SQL and revoke all window guards", async () => { for (const fault of ["peer", "proof", "generation", "epoch", "accessor", "proxy"] as const) { const f = await fixture(), guard = f.guard(), other = f.guard(); f.reset(); let getters = 0 let binding = structuredClone(f.binding) if (fault === "peer") binding = { ...binding, peerRef: { kind: "external", enrollmentId: randomUUID() } } if (fault === "proof") binding = { ...binding, sourceProof: "9".repeat(64) } if (fault === "generation") binding = { ...binding, authorityGeneration: "different" } if (fault === "epoch") binding = { ...binding, routingEndpointEpoch: randomUUID() } if (fault === "accessor") Object.defineProperty(binding, "sourceProof", { enumerable: true, get() { getters++; return f.binding.sourceProof } }) if (fault === "proxy") binding = new Proxy(binding, { getPrototypeOf() { getters++; throw Error("No proxy trap") } }) await assert.rejects(guard.verifyRead(binding, scope())); assert.equal(getters, 0) assert.equal(f.counts().q + f.counts().queries + f.counts().secrets, 0); assert.equal(f.counts().destroys, 1) assert.throws(() => assertBandwidthOperatorPeerSourceGuard(other)) } }) await t.test("held lock/PID drift and original grant rotation during Q deny the read", async () => { for (const fault of ["lock", "pid", "grant"] as const) { const f = await fixture(), guard = f.guard(); f.reset() if (fault === "lock") f.loseLock() if (fault === "pid") f.changePid() if (fault === "grant") { let done = false; f.qHook(async () => { if (!done) { done = true; await f.publish({ ...f.grant, grantId: randomUUID() }) } }) } await assert.rejects(guard.verifyRead(f.binding, scope())); assert.equal(f.counts().destroys, 1); assert.equal(f.counts().secrets, 0) if (fault !== "grant") assert.equal(f.counts().heldQueries, 1) } }) await t.test("physical owner abort DURING post-HELD Q revokes guard before consumer key callback", async () => { const f = await fixture(), guard = f.guard(); f.reset(); let keyCallbacks = 0, killed = false f.qHook(async () => { if (!killed && f.counts().heldQueries > 0) { killed = true; f.loseOwner() } }) const consumer = async () => { await guard.verifyRead(f.binding, scope()); keyCallbacks++ } await assert.rejects(consumer()); assert(killed); assert.equal(keyCallbacks, 0); assert.equal(f.counts().heldQueries, 1) assert.throws(() => assertBandwidthOperatorPeerSourceGuard(guard)); assert.equal(f.counts().destroys, 1) await assert.rejects(guard.verifyMetadata(f.binding, scope())) }) await t.test("guard requires native lifetime; legacy window without signal still registers; hostile getters never execute", async () => { const missing = await fixture(4000, "missing"); missing.reset() assert.throws(() => missing.guard()); assert.equal(missing.counts().destroys, 1); assert.equal(missing.counts().queries, 0) const legacy = await fixture(4000, "missing") assert.equal(await legacy.windows.register(legacy.window), "synthetic-registry-complete"); assert.equal(legacy.counts().destroys, 1) for (const mode of ["accessor", "proxy", "aborted"] as const) await assert.rejects(fixture(4000, mode)) const hostile = await fixture(4000, "hostile"), guard = hostile.guard(); hostile.reset() await guard.verifyRead(hostile.binding, scope()); hostile.loseOwner() assert.equal(hostile.counts().destroys, 1); assert.throws(() => assertBandwidthOperatorPeerSourceGuard(guard)); assert.equal(lifetimeGetters, 0) }) await t.test("idle physical lifetime loss revokes metadata guard without a new SQL/Q check", async () => { const f = await fixture(), guard = f.guard(); f.reset(); f.loseOwner() assert.equal(f.counts().destroys, 1); assert.throws(() => assertBandwidthOperatorPeerSourceGuard(guard)) await assert.rejects(guard.verifyMetadata(f.binding, scope())); assert.equal(f.counts().q + f.counts().queries, 0) }) await t.test("metadata original revocation/close/abort/expiry cannot revive under larger fresh scope", async () => { for (const fault of ["grant", "close", "abort", "expiry"] as const) { const f = await fixture(fault === "expiry" ? 700 : 4000), guard = f.guard(); f.reset() if (fault === "grant") await f.publish({ ...f.grant, grantId: randomUUID() }) if (fault === "close") f.windows.close() if (fault === "abort") f.caller.abort() if (fault === "expiry") await delay(750) await assert.rejects(guard.verifyMetadata(f.binding, scope(60000, new AbortController().signal))) assert.equal(f.counts().q + f.counts().queries, 0); assert.equal(f.counts().destroys, 1) } }) await t.test("guard is usable during registry phase and revoked after logical/final release", async () => { const f = await fixture(); let retained!: BandwidthOperatorPeerSourceGuard f.registerHook(async (_borrowed, requested) => { retained = f.guard(); await retained.verifyMetadata(f.binding, requested); await retained.verifyRead(f.binding, requested) }) await f.windows.register(f.window); assert.equal(f.counts().destroys, 1) assert.throws(() => assertBandwidthOperatorPeerSourceGuard(retained)); await assert.rejects(retained.verifyMetadata(f.binding, scope())) }) await t.test("requested signal mutation/cancel/short expiry or concurrent guard use destroys blocked lease; late held result cannot publish", async () => { for (const fault of ["abort", "expiry", "busy"] as const) { const f = await fixture(), guard = f.guard(); f.reset() let entered!: () => void, release!: () => void const started = new Promise(resolve => { entered = resolve }), held = new Promise(resolve => { release = resolve }) f.heldHook(async () => { entered(); await held }) const caller = new AbortController(), input = scope(fault === "expiry" ? 200 : 3000, caller.signal), pending = guard.verifyRead(f.binding, input); void pending.catch(() => {}) await Promise.race([started, pending.then(() => assert.fail("held probe was not reached"))]); input.deadlineAt += 60000; input.signal = new AbortController().signal if (fault === "abort") caller.abort() if (fault === "busy") await assert.rejects(guard.verifyMetadata(f.binding, scope())) await assert.rejects(pending); release(); await delay(0); assert.equal(f.counts().destroys, 1); assert.equal(f.counts().heldQueries, 1); assert.equal(f.counts().secrets, 0) } }) } finally { for (const close of cleanup) close() const actual = await realpath(folder); assert.equal(dirname(actual), root); assert.match(basename(actual), /^bw-peer-source-guard-/); assert((await lstat(folder)).isDirectory()) await rm(actual, { recursive: true, force: true }) } })