/** Genuine coordinator prerequisite, real Ed25519 grant and authenticated * localhost license GET. Metadata checker is explicit controlled source state, * not production SQL/Q or public snapshot admission authority. */ import assert from "node:assert/strict" import { createHash, generateKeyPairSync, randomUUID, sign } from "node:crypto" import { once } from "node:events" import { createServer } from "node:http" import { lstat, mkdir, mkdtemp, realpath, rm, unlink, 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 { createBandwidthOperatorEnrollmentPrerequisite, bandwidthOperatorEnrollmentGrantSchema, type BandwidthOperatorEnrollmentPublicMetadata } from "./bandwidth-operator-enrollment.js" import type { BandwidthPeerSourceSnapshot, BandwidthPeerTrustedSource } from "./bandwidth-peer-observation.js" import type { BandwidthNodeObservationScope } from "./bandwidth-node-observation.js" import { canonicalBandwidthNodeValue } from "./bandwidth-node-bootstrap.js" type Coordinator = ReturnType function typeSeparation(value: BandwidthOperatorEnrollmentPublicMetadata) { // @ts-expect-error PUBLIC outer wrapper is not a strong current-Q inspection. const strong: Awaited> = value return strong } void typeSeparation test("operator PUBLIC metadata authenticates current original grant without Q/credentials/native", async t => { let nativeGets = 0 const server = createServer((request, response) => { nativeGets++; assert.equal(request.method, "GET"); assert.equal(request.url, "/rest/system/license") assert.equal(request.headers.authorization, "Basic " + Buffer.from("metadata-user:metadata-private-password").toString("base64")) response.writeHead(200, { "content-type": "application/json" }); response.end(JSON.stringify({ "system-id": "SYNTHETIC-OPERATOR-METADATA" })) }) server.listen(0, "127.0.0.1"); await once(server, "listening") const address = server.address(); assert(address && typeof address !== "string") const port = address.port const root = await realpath(tmpdir()), folder = await mkdtemp(join(root, "bw-operator-metadata-")) const all: Coordinator[] = [] let ordinal = 0 const scope = (ms = 4000, signal?: AbortSignal) => ({ deadlineAt: Date.now() + ms, ...(signal ? { signal } : {}) }) async function fixture(checker = true) { const directory = join(folder, String(++ordinal)), keys = generateKeyPairSync("ed25519"), peerRef = { kind: "server" as const, serverId: 71 } await mkdir(directory) const trustKeyFile = join(directory, "operator.pub"), grantFile = join(directory, "grant.json") await writeFile(trustKeyFile, keys.publicKey.export({ type: "spki", format: "pem" })) const config = { trustKeyFile, grantFile, trustKeySha256: createHash("sha256").update(keys.publicKey.export({ type: "spki", format: "der" })).digest("hex"), installationId: randomUUID(), issuerKeySha256: "a".repeat(64), quiescenceProof: "b".repeat(64) } let currentSource: BandwidthPeerSourceSnapshot = { peerRef, enabled: true, sourceProof: "c".repeat(64), authorityGeneration: "original-source", endpoint: { host: "127.0.0.1", port, username: "metadata-user", password: "metadata-private-password", useSsl: false, verifySsl: true, routingEndpointEpoch: randomUUID() } } const expectedSource = structuredClone(currentSource) let reads = 0, q = 0, checks = 0, hook: (() => Promise) | undefined const trusted: BandwidthPeerTrustedSource = { async read() { reads++; return currentSource }, ...(checker ? { async assertMetadataCurrent(expected: Readonly, requested: Readonly) { checks++; assert.deepEqual(expected, expectedSource); assert(Object.isFrozen(expected) && Object.isFrozen(expected.endpoint)) await hook?.(); requested.signal?.throwIfAborted(); assert.deepEqual(currentSource, expected) } } : {}) } const coordinator = createBandwidthOperatorEnrollmentPrerequisite(config, trusted, { async verify() { q++ } }); all.push(coordinator) // Build only the exact signed descriptor (configuration paths are private). const grant = bandwidthOperatorEnrollmentGrantSchema.parse({ format: "mmapp-bandwidth-operator-enrollment-v1", grantId: randomUUID(), operatorId: "original-metadata-operator", installationId: config.installationId, issuerKeySha256: config.issuerKeySha256, quiescenceProof: config.quiescenceProof, executorInventorySha256: "d".repeat(64), executorsStoppedAt: Date.now() - 2000, issuedAt: Date.now() - 1000, expiresAt: Date.now() + 60000, peerRef, sourceProof: expectedSource.sourceProof, authorityGeneration: expectedSource.authorityGeneration, routingEndpointEpoch: expectedSource.endpoint.routingEndpointEpoch, claims: [{ kind: "system-id", value: "SYNTHETIC-OPERATOR-METADATA" }] }) 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() return { coordinator, trusted, grantFile, trustKeyFile, peerRef, grant, publish, reset() { reads = q = checks = nativeGets = 0 }, counts: () => ({ reads, q, checks, nativeGets }), hook(value: typeof hook) { hook = value }, drift() { currentSource = { ...currentSource, endpoint: { ...currentSource.endpoint, password: "changed" } } } } } try { await t.test("genuine acquire needs Q/license; PUBLIC metadata then uses only private checker and signed files", async () => { const f = await fixture(), token = await f.coordinator.acquire(f.peerRef, scope()) assert(f.counts().q > 0 && f.counts().reads > 0 && f.counts().nativeGets > 0); f.reset() const value = await f.coordinator.inspectMetadata(token, scope()) assert.equal(value.format, "mmapp-bandwidth-operator-enrollment-metadata-v1"); assert.equal(value.metadata.grantId, f.grant.grantId) assert(Object.isFrozen(value) && Object.isFrozen(value.metadata) && Object.isFrozen(value.metadata.authority)) assert(!("writerBarrierVerified" in value) && !("writerBarrierVerified" in value.metadata) && !("endpointMappingVerified" in value.metadata)) assert(!JSON.stringify(value).includes("metadata-private-password")); assert(!JSON.stringify(value).includes("metadata-user")) assert.deepEqual(f.counts(), { reads: 0, q: 0, checks: 1, nativeGets: 0 }) }) await t.test("constructor captures checker; absent checker refuses with no credential/native/Q fallback", async () => { const f = await fixture(), token = await f.coordinator.acquire(f.peerRef, scope()); f.reset() f.trusted.assertMetadataCurrent = async () => { throw Error("replacement") } await f.coordinator.inspectMetadata(token, scope()); assert.deepEqual(f.counts(), { reads: 0, q: 0, checks: 1, nativeGets: 0 }) const missing = await fixture(false), absentToken = await missing.coordinator.acquire(missing.peerRef, scope()); missing.reset() await assert.rejects(missing.coordinator.inspectMetadata(absentToken, scope())); assert.deepEqual(missing.counts(), { reads: 0, q: 0, checks: 0, nativeGets: 0 }) }) await t.test("foreign/copied prerequisites and revoked original grant refuse before checker", async () => { const f = await fixture(), token = await f.coordinator.acquire(f.peerRef, scope()), foreign = await fixture(); f.reset(); foreign.reset() for (const copied of [{ ...token }, JSON.parse(JSON.stringify(token))]) await assert.rejects(f.coordinator.inspectMetadata(copied, scope())) await assert.rejects(foreign.coordinator.inspectMetadata(token, scope())) await f.publish({ ...f.grant, grantId: randomUUID() }); await assert.rejects(f.coordinator.inspectMetadata(token, scope())) assert.deepEqual(f.counts(), { reads: 0, q: 0, checks: 0, nativeGets: 0 }) }) await t.test("grant rotation/deletion/key change during checker and endpoint drift reject without fallback", async () => { for (const fault of ["rotate", "delete", "key", "endpoint"] as const) { const f = await fixture(), token = await f.coordinator.acquire(f.peerRef, scope()); f.reset() f.hook(async () => { if (fault === "rotate") await f.publish({ ...f.grant, grantId: randomUUID() }); if (fault === "delete") await unlink(f.grantFile) if (fault === "key") await writeFile(f.trustKeyFile, generateKeyPairSync("ed25519").publicKey.export({ type: "spki", format: "pem" })); if (fault === "endpoint") f.drift() }) await assert.rejects(f.coordinator.inspectMetadata(token, scope())); assert.deepEqual(f.counts(), { reads: 0, q: 0, checks: 1, nativeGets: 0 }) } }) await t.test("original abort/expiry cannot renew with larger deadline/new signal; new shorter call remains supported", async () => { const f = await fixture(), caller = new AbortController(), token = await f.coordinator.acquire(f.peerRef, scope(4000, caller.signal)); f.reset() await f.coordinator.inspectMetadata(token, scope(1000)); caller.abort() await assert.rejects(f.coordinator.inspectMetadata(token, scope(60000, new AbortController().signal))); assert.equal(f.counts().checks, 1) const g = await fixture(), short = await g.coordinator.acquire(g.peerRef, scope(700)); g.reset(); await delay(750) await assert.rejects(g.coordinator.inspectMetadata(short, scope(60000))); assert.deepEqual(g.counts(), { reads: 0, q: 0, checks: 0, nativeGets: 0 }) }) await t.test("caller mutation/abort or coordinator.close during pending checker prevents late publication", async () => { for (const cancel of ["abort", "close"] as const) { const f = await fixture(), token = await f.coordinator.acquire(f.peerRef, scope()); f.reset() let entered!: () => void, release!: () => void const started = new Promise(resolve => { entered = resolve }), held = new Promise(resolve => { release = resolve }) f.hook(async () => { entered(); await held }) const caller = new AbortController(), input = scope(3000, caller.signal), pending = f.coordinator.inspectMetadata(token, input); void pending.catch(() => {}) await started; input.deadlineAt += 60000; input.signal = new AbortController().signal if (cancel === "abort") caller.abort(); else f.coordinator.close() await assert.rejects(pending); release(); await delay(0); assert.deepEqual(f.counts(), { reads: 0, q: 0, checks: 1, nativeGets: 0 }) } }) await t.test("scope proxy/getter rejected without user code; native signal overrides ignored", async () => { const f = await fixture(), token = await f.coordinator.acquire(f.peerRef, scope()); f.reset(); let traps = 0 const trap = () => { traps++; throw Error("No caller trap") } await assert.rejects(f.coordinator.inspectMetadata(token, new Proxy(scope(), { getPrototypeOf: trap, ownKeys: trap }))) await assert.rejects(f.coordinator.inspectMetadata(token, { get deadlineAt() { return trap() } })); assert.equal(traps, 0) const caller = new AbortController(); Object.defineProperties(caller.signal, { aborted: { get: trap }, addEventListener: { value: trap }, removeEventListener: { value: trap } }) await f.coordinator.inspectMetadata(token, scope(1000, caller.signal)); assert.equal(traps, 0) assert.deepEqual(f.counts(), { reads: 0, q: 0, checks: 1, nativeGets: 0 }) }) await t.test("short call's monotonic horizon survives caller mutation and wall rollback during checker", async () => { const f = await fixture(), token = await f.coordinator.acquire(f.peerRef, scope()); f.reset() let entered!: () => void, release!: () => void const started = new Promise(resolve => { entered = resolve }), held = new Promise(resolve => { release = resolve }) f.hook(async () => { entered(); await held }) const originalNow = Date.now, input = scope(200), pending = f.coordinator.inspectMetadata(token, input); void pending.catch(() => {}) try { await Promise.race([started, pending.then(() => assert.fail("checker was not reached"))]) input.deadlineAt = originalNow() + 60000; Date.now = () => originalNow() - 60000 await assert.rejects(pending) } finally { Date.now = originalNow; release(); await delay(0) } assert.deepEqual(f.counts(), { reads: 0, q: 0, checks: 1, nativeGets: 0 }) }) } finally { for (const coordinator of all) coordinator.close() server.closeAllConnections(); server.close(); await once(server, "close") const { closePool } = await import("../db/index.js"); await closePool() const actual = await realpath(folder); assert.equal(dirname(actual), root); assert.match(basename(actual), /^bw-operator-metadata-/); assert((await lstat(folder)).isDirectory()) await rm(actual, { recursive: true, force: true }) } })