151 lines
12 KiB
TypeScript
151 lines
12 KiB
TypeScript
/** Real signed bootstrap files + explicitly controlled public core verifier.
|
|
* No pool/SQL/issuer-secret/event-key/Q/native or strong-source acceptance. */
|
|
import assert from "node:assert/strict"
|
|
import { createHash, generateKeyPairSync, randomUUID, sign, verify } from "node:crypto"
|
|
import { lstat, mkdtemp, readFile, 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 { createConfiguredBandwidthNodeSource } from "./bandwidth-node-source.js"
|
|
import type { createConfiguredBandwidthControlSource, BandwidthPublicNodeBootstrapMetadata } from "./bandwidth-control-source.js"
|
|
import { bandwidthNodeBootstrapEnvelopeSchema, bandwidthNodeBootstrapSchema, canonicalBandwidthNodeValue } from "./bandwidth-node-bootstrap.js"
|
|
import type { BandwidthScope } from "./bandwidth-admission.js"
|
|
|
|
test("node public bootstrap is secret-free fresh metadata, never strong authority", async t => {
|
|
const root = await realpath(tmpdir()), folder = await mkdtemp(join(root, "bw-node-public-")), keys = generateKeyPairSync("ed25519")
|
|
const bootstrapFile = join(folder, "bootstrap.json"), issuerKeyFile = join(folder, "missing-issuer-secret"), eventKeyFile = join(folder, "missing-event-secret")
|
|
const issuerKeySha256 = "b".repeat(64), installationId = randomUUID()
|
|
const initialBootstrap = bandwidthNodeBootstrapSchema.parse({ format: "mmapp-bandwidth-node-bootstrap-v2", installationId, issuerKeySha256,
|
|
quiescenceProof: "c".repeat(64), registrySchemaSourceSha256: "d".repeat(64), registryCatalogSha256: "e".repeat(64), attestationRef: "controlled public fixture; no current Q or SQL proof" })
|
|
const initialSource = { installationId, controlGeneration: randomUUID(), sourceRecordSha256: "f".repeat(64) }
|
|
let source = { ...initialSource }, calls = 0, connects = 0, strongVerifications = 0
|
|
let hook: ((call: number, scope: BandwidthScope) => Promise<void>) | undefined
|
|
let after: ((call: number) => Promise<void>) | undefined
|
|
const all: Array<ReturnType<typeof createConfiguredBandwidthNodeSource>> = []
|
|
const scope = (ms = 2000, signal?: AbortSignal) => ({ deadlineAt: Date.now() + ms, ...(signal ? { signal } : {}) })
|
|
const core = {
|
|
async connect() { connects++; throw Error("No pool borrow permitted") },
|
|
async verifyNodeBootstrap() { strongVerifications++; throw Error("No strong verification permitted") },
|
|
async inspectPublicNodeBootstrap(raw: unknown, requested: BandwidthScope): Promise<BandwidthPublicNodeBootstrapMetadata> {
|
|
const call = ++calls; await hook?.(call, requested)
|
|
const envelope = bandwidthNodeBootstrapEnvelopeSchema.parse(raw), bytes = Buffer.from(envelope.payload, "base64url")
|
|
assert(verify(null, bytes, keys.publicKey, Buffer.from(envelope.signature, "base64url")))
|
|
const bootstrap = bandwidthNodeBootstrapSchema.parse(JSON.parse(bytes.toString("utf8")))
|
|
assert.equal(canonicalBandwidthNodeValue(bootstrap), bytes.toString("utf8"))
|
|
const result = Object.freeze({ format: "mmapp-bandwidth-public-node-metadata-v1" as const, bootstrap: Object.freeze(bootstrap), source: Object.freeze({ ...source }),
|
|
publicDatabase: Object.freeze({ databaseName: "public_fixture", runtimeRole: "public_reader", ownerRole: "public_owner", databaseOid: 1234, catalogSha256: "a".repeat(64) }) })
|
|
await after?.(call); return result
|
|
},
|
|
}
|
|
const make = (expected = issuerKeySha256) => {
|
|
const value = createConfiguredBandwidthNodeSource(core as unknown as ReturnType<typeof createConfiguredBandwidthControlSource>, { bootstrapFile, issuerKeyFile, issuerKeySha256: expected })
|
|
all.push(value); return value
|
|
}
|
|
const publish = async (value = initialBootstrap) => {
|
|
const payload = Buffer.from(canonicalBandwidthNodeValue(value))
|
|
await writeFile(bootstrapFile, JSON.stringify({ format: "mmapp-bandwidth-node-bootstrap-envelope-v1", payload: payload.toString("base64url"), signature: sign(null, payload, keys.privateKey).toString("base64url") }))
|
|
}
|
|
const reset = async () => { calls = 0; hook = undefined; after = undefined; source = { ...initialSource }; await publish() }
|
|
try {
|
|
await t.test("constructor performs no IO; missing secrets still allow immutable public projection without lease", async () => {
|
|
const node = make(); assert.equal(calls + connects + strongVerifications, 0)
|
|
await assert.rejects(readFile(bootstrapFile), { code: "ENOENT" }); await reset()
|
|
const result = await node.inspectPublicBootstrap(scope())
|
|
assert.equal(calls, 2); assert.equal(connects + strongVerifications, 0)
|
|
assert.equal(result.bootstrapSha256, createHash("sha256").update(canonicalBandwidthNodeValue(initialBootstrap)).digest("hex"))
|
|
assert(Object.isFrozen(result) && Object.isFrozen(result.bootstrap) && Object.isFrozen(result.source) && Object.isFrozen(result.publicDatabase))
|
|
assert.deepEqual(Object.keys(result.source).sort(), ["controlGeneration", "installationId", "sourceRecordSha256"])
|
|
assert(!("keyCurrent" in result) && !("quiescenceVerified" in result) && !("catalogVerified" in result))
|
|
await assert.rejects(readFile(issuerKeyFile), { code: "ENOENT" }); await assert.rejects(readFile(eventKeyFile), { code: "ENOENT" })
|
|
})
|
|
await t.test("every call rereads public bootstrap/source and captures its fixed verifier", async () => {
|
|
await reset(); const node = make(), first = await node.inspectPublicBootstrap(scope())
|
|
source.controlGeneration = randomUUID(); source.sourceRecordSha256 = "1".repeat(64)
|
|
await publish({ ...initialBootstrap, attestationRef: "new signed PUBLIC statement; no execution grant" })
|
|
const original = core.inspectPublicNodeBootstrap
|
|
try {
|
|
core.inspectPublicNodeBootstrap = async () => { throw Error("Replacement core method") }
|
|
const second = await node.inspectPublicBootstrap(scope())
|
|
assert.notEqual(second.bootstrapSha256, first.bootstrapSha256); assert.notEqual(second.source.controlGeneration, first.source.controlGeneration); assert.equal(calls, 4)
|
|
} finally { core.inspectPublicNodeBootstrap = original }
|
|
})
|
|
await t.test("bootstrap/source drift during public span and issuer mismatch cannot publish", async () => {
|
|
for (const fault of ["bootstrap", "source", "issuer"] as const) {
|
|
await reset(); const node = make(fault === "issuer" ? "9".repeat(64) : issuerKeySha256)
|
|
after = async call => { if (call === 1) { if (fault === "bootstrap") await publish({ ...initialBootstrap, quiescenceProof: "2".repeat(64) }); if (fault === "source") source.sourceRecordSha256 = "3".repeat(64) } }
|
|
await assert.rejects(node.inspectPublicBootstrap(scope())); assert.equal(connects + strongVerifications, 0)
|
|
}
|
|
})
|
|
await t.test("missing/tampered bootstrap and accessor/foreign/expired scopes fail before trusted core", async () => {
|
|
await reset(); const node = make(); await unlink(bootstrapFile)
|
|
await assert.rejects(node.inspectPublicBootstrap(scope())); assert.equal(calls, 0)
|
|
await writeFile(bootstrapFile, "{"); await assert.rejects(node.inspectPublicBootstrap(scope())); assert.equal(calls, 0)
|
|
await publish(); const raw = JSON.parse(await readFile(bootstrapFile, "utf8")); raw.signature = "a".repeat(86); await writeFile(bootstrapFile, JSON.stringify(raw))
|
|
await assert.rejects(node.inspectPublicBootstrap(scope())); assert.equal(calls, 1)
|
|
await reset(); let getters = 0
|
|
const getter = { get deadlineAt() { getters++; return Date.now() + 2000 } }
|
|
for (const input of [getter, { ...scope(), extra: true }, Object.assign(Object.create(null), scope()), { deadlineAt: Date.now() - 1 }]) await assert.rejects(node.inspectPublicBootstrap(input))
|
|
assert.equal(getters, 0); assert.equal(calls, 0)
|
|
const caller = new AbortController(); caller.abort(); await assert.rejects(node.inspectPublicBootstrap(scope(2000, caller.signal))); assert.equal(calls, 0)
|
|
})
|
|
await t.test("original cancellation/close rejects pending core and consumes late results", async () => {
|
|
for (const cancel of ["abort", "close"] as const) {
|
|
await reset(); const node = make(), caller = new AbortController()
|
|
let entered!: () => void, release!: () => void
|
|
const started = new Promise<void>(resolve => { entered = resolve }), held = new Promise<void>(resolve => { release = resolve })
|
|
let observed: AbortSignal | undefined
|
|
hook = async (_call, requested) => { observed = requested.signal; entered(); await held }
|
|
const input = scope(2000, caller.signal), pending = node.inspectPublicBootstrap(input); void pending.catch(() => {})
|
|
await started; input.deadlineAt += 60000; input.signal = new AbortController().signal
|
|
if (cancel === "abort") caller.abort(); else node.close()
|
|
await assert.rejects(pending); assert(observed?.aborted); release(); await delay(0)
|
|
assert.equal(calls, 1)
|
|
if (cancel === "close") await assert.rejects(node.inspectPublicBootstrap(scope()))
|
|
}
|
|
})
|
|
await t.test("scope/signal proxies run no traps; native signal operations ignore own hostile overrides", async () => {
|
|
await reset(); const node = make(); let traps = 0, overrides = 0
|
|
const trap = () => { traps++; throw Error("No proxy trap permitted") }
|
|
const proxy = new Proxy(scope(), { getPrototypeOf: trap, ownKeys: trap, getOwnPropertyDescriptor: trap, get: trap })
|
|
await assert.rejects(node.inspectPublicBootstrap(proxy)); assert.equal(traps, 0); assert.equal(calls, 0)
|
|
const proxySignal = new Proxy(new AbortController().signal, { get: trap, getPrototypeOf: trap })
|
|
await assert.rejects(node.inspectPublicBootstrap(scope(2000, proxySignal))); assert.equal(traps, 0); assert.equal(calls, 0)
|
|
const caller = new AbortController()
|
|
Object.defineProperties(caller.signal, {
|
|
aborted: { get() { overrides++; throw Error("No caller getter") } },
|
|
addEventListener: { value() { overrides++; throw Error("No caller add") } },
|
|
removeEventListener: { value() { overrides++; throw Error("No caller remove") } },
|
|
})
|
|
let entered!: () => void, release!: () => void
|
|
const started = new Promise<void>(resolve => { entered = resolve }), held = new Promise<void>(resolve => { release = resolve })
|
|
hook = async () => { entered(); await held }
|
|
const pending = node.inspectPublicBootstrap(scope(2000, caller.signal)); void pending.catch(() => {})
|
|
await started; caller.abort(); await assert.rejects(pending); release(); await delay(0)
|
|
assert.equal(overrides, 0); assert.equal(calls, 1)
|
|
})
|
|
await t.test("two rounds share the first source cap of at most10000ms", async () => {
|
|
await reset(); const node = make(), input = scope(60000), began = Date.now(), seen: BandwidthScope[] = []
|
|
hook = async (_call, requested) => { seen.push(requested) }
|
|
await node.inspectPublicBootstrap(input)
|
|
assert.equal(seen.length, 2); assert.equal(seen[0], seen[1]); assert(seen[0].deadlineAt <= began + 10000); assert(seen[0].deadlineAt < input.deadlineAt)
|
|
})
|
|
await t.test("original monotonic deadline cannot renew through mutation or backward wall jump", async () => {
|
|
await reset(); const node = make(), originalNow = Date.now
|
|
let entered!: () => void, release!: () => void
|
|
const started = new Promise<void>(resolve => { entered = resolve }), held = new Promise<void>(resolve => { release = resolve })
|
|
hook = async () => { entered(); await held }
|
|
const input = scope(30), pending = node.inspectPublicBootstrap(input); void pending.catch(() => {})
|
|
try {
|
|
await started; input.deadlineAt = originalNow() + 60000; Date.now = () => originalNow() - 60000
|
|
await assert.rejects(pending); assert.equal(calls, 1)
|
|
} finally { Date.now = originalNow; release(); await delay(0) }
|
|
})
|
|
assert.equal(connects + strongVerifications, 0)
|
|
} finally {
|
|
for (const node of all) node.close()
|
|
const actual = await realpath(folder); assert.equal(dirname(actual), root); assert.match(basename(actual), /^bw-node-public-/); assert((await lstat(folder)).isDirectory())
|
|
await rm(actual, { recursive: true, force: true })
|
|
}
|
|
})
|