122 lines
13 KiB
TypeScript
122 lines
13 KiB
TypeScript
import assert from "node:assert/strict"
|
|
import { createHash, createHmac, randomUUID } from "node:crypto"
|
|
import { mkdtemp, writeFile, rm } from "node:fs/promises"
|
|
import path from "node:path"
|
|
import os from "node:os"
|
|
import { mock, test } from "node:test"
|
|
import { canonicalBandwidthNodeValue, bandwidthPeerRegistrySchemaSourceSha256 } from "./bandwidth-node-bootstrap.js"
|
|
import type { BandwidthResolvedPeerFence } from "./bandwidth-peer-fence.js"
|
|
import type { BandwidthPeerRef } from "./bandwidth-peer-reference.js"
|
|
|
|
test("v2 peer participant fence: exact native claims/alias history on one existing lease", async t => {
|
|
mock.module("./bandwidth-control-registry-identity.js",{namedExports:{assertBandwidthControlRegistryIdentity:async()=>{throw Error("isolated peer fence must not invoke joint SQL")}}})
|
|
let managedRoles = 0, externalRoles = 0, catalogs = 0, catalogAllowed = true, roleAllowed = true
|
|
mock.module("./bandwidth-node-registry-catalog.js", { namedExports: {
|
|
observeBandwidthNodeRegistryCatalog: async () => { throw Error("v2 must never fall back") },
|
|
observeBandwidthPeerRegistryCatalog: async (_sql: unknown, live: () => void) => { catalogs++; live(); if (!catalogAllowed) throw Error("catalog refused"); return "c".repeat(64) },
|
|
} })
|
|
mock.module("./bandwidth-node-registry-role.js", { namedExports: { assertBandwidthNodeRegistryRuntimeRole: async (_sql: unknown, _role: unknown, live: () => void) => { managedRoles++; live() } } })
|
|
mock.module("./bandwidth-external-node-registry-role.js", { namedExports: { assertBandwidthExternalNodeRegistryRuntimeRole: async (_sql: unknown, _role: unknown, live: () => void) => { externalRoles++; live(); if (!roleAllowed) throw Error("role refused") } } })
|
|
// This suite fakes metadata IO only; the batch's exact SQL/validators have
|
|
// their own unit and real PostgreSQL profiles.
|
|
mock.module("./bandwidth-peer-identity.js", { namedExports: { assertBandwidthPeerIdentity: async (sql: { query(text: string): Promise<{ rows: Record<string, unknown>[] }> }, expected: Record<string, string>, live: () => void) => {
|
|
managedRoles++; externalRoles++; catalogs++; live()
|
|
if (!catalogAllowed || !roleAllowed || expected.registryCatalogSha256 !== "c".repeat(64)) 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")
|
|
} } })
|
|
const { assertResolvedBandwidthPeersOnFence, BandwidthPeerFenceError } = await import("./bandwidth-peer-fence.js")
|
|
const directory = await mkdtemp(path.join(os.tmpdir(), "mm-peer-fence-")), issuerKeyFile = path.join(directory, "issuer"), bootstrapFile = path.join(directory, "bootstrap")
|
|
const key = Buffer.alloc(32, 83), sha = (value: string | Buffer) => createHash("sha256").update(value).digest("hex")
|
|
await writeFile(issuerKeyFile, key); await writeFile(bootstrapFile, JSON.stringify({ unitOnly: true }))
|
|
const root = { installationId: randomUUID(), issuerKeySha256: sha(key), quiescenceProof: "b".repeat(64) }, source = { controlGeneration: randomUUID(), sourceRecordSha256: "d".repeat(64), databaseName: "unit-db", ownerRole: "unit-owner", runtimeRole: "unit-runtime" }
|
|
const config = { issuerKeyFile, issuerKeySha256: root.issuerKeySha256, bootstrapFile }, sessions = new Set<() => void>()
|
|
let bootstrap = { ...root, format: "mmapp-bandwidth-node-bootstrap-v2", registrySchemaSourceSha256: bandwidthPeerRegistrySchemaSourceSha256(), registryCatalogSha256: "c".repeat(64), attestationRef: "unit-only explicit operator attestation" }
|
|
const proof = (purpose: string, value: unknown) => createHmac("sha256", key).update("mmapp-bandwidth-node-" + purpose + "-v1:" + canonicalBandwidthNodeValue(value)).digest("hex")
|
|
let input: BandwidthResolvedPeerFence, calls: { text: string; values?: unknown[] }[] = [], aliasFault: ((row: Record<string, unknown>) => void) | undefined,
|
|
eventFault: ((row: Record<string, unknown>) => void) | undefined, sqlHook: (() => Promise<void> | void) | undefined, locked = true
|
|
const eventIds = new Map<string, string>()
|
|
function reset(managedRemote = false) {
|
|
bootstrap = { ...bootstrap, ...root, format: "mmapp-bandwidth-node-bootstrap-v2" }; catalogAllowed = true; roleAllowed = true; locked = true
|
|
calls = []; aliasFault = undefined; eventFault = undefined; sqlHook = undefined
|
|
const refs: BandwidthPeerRef[] = [{ kind: "server", serverId: 101 }, managedRemote ? { kind: "server", serverId: 102 } : { kind: "external", enrollmentId: randomUUID() }]
|
|
input = { binding: { ...root, controlGeneration: source.controlGeneration, sourceRecordSha256: source.sourceRecordSha256, bootstrapSha256: sha(canonicalBandwidthNodeValue(bootstrap)) },
|
|
participants: refs.map((peerRef, index) => ({ evidence: { version: 2, peerRef, sourceProof: "a".repeat(64), authorityGeneration: "unit-grant", routingEndpointEpoch: randomUUID(), observedAt: Date.now(), expiresAt: Date.now() + 5000,
|
|
claims: [{ kind: "software-id", value: "UNIT-LICENSE-" + index }], physicalUniquenessVerified: false, cloneResistanceVerified: false },
|
|
receipt: { peerRef, canonicalNodeId: randomUUID(), incarnation: randomUUID(), status: "active", outcome: "existing" } })) }
|
|
}
|
|
const fence = { verifyNodeBootstrap: async () => ({ bootstrap: structuredClone(bootstrap), source: { ...root, ...source } }), async query(text: string, values?: unknown[]) {
|
|
calls.push({ text, values }); await sqlHook?.()
|
|
if (text.includes("pg_try_advisory")) return { rows: [{ locked }] }
|
|
if (text.includes("FROM mmapp_control.bandwidth_node_authority")) return { rows: [{ installation_id: root.installationId, issuer_key_sha256: root.issuerKeySha256, quiescence_proof: root.quiescenceProof, status: "active" }] }
|
|
const external = text.includes("bandwidth_external_node_"), participant = input.participants.find(item => item.receipt.peerRef.kind === (external ? "external" : "server") && (item.receipt.peerRef.kind === "server" ? item.receipt.peerRef.serverId : item.receipt.peerRef.enrollmentId) === values?.[0]); assert(participant)
|
|
const r = participant.receipt, ref = r.peerRef, subject = ref.kind === "server" ? { serverId: ref.serverId } : { enrollmentId: ref.enrollmentId }, claimProof = proof("claim", participant.evidence.claims)
|
|
if (text.includes("aliases a JOIN")) {
|
|
const row: Record<string, unknown> = { ...(ref.kind === "server" ? { server_id: ref.serverId } : { enrollment_id: ref.enrollmentId }), incarnation: r.incarnation, node_id: r.canonicalNodeId, status: "active", claim_proof: claimProof,
|
|
enrollment_mac: proof("node", { ...root, nodeId: r.canonicalNodeId, claimProof }), record_mac: proof(external ? "external-alias" : "alias", { ...root, ...subject, incarnation: r.incarnation, nodeId: r.canonicalNodeId, status: "active" }) }
|
|
aliasFault?.(row); return { rows: [row] }
|
|
}
|
|
assert(text.includes("events WHERE")); const id = String(values?.[0]); if (!eventIds.has(id)) eventIds.set(id, randomUUID()); const eventId = eventIds.get(id)!
|
|
const row: Record<string, unknown> = { event_id: eventId, incarnation: r.incarnation, node_id: r.canonicalNodeId, kind: "enroll", old_status: null, new_status: "active", authority_proof: "f".repeat(64),
|
|
event_mac: proof(external ? "external-event" : "event", { ...root, ...subject, eventId, incarnation: r.incarnation, nodeId: r.canonicalNodeId, kind: "enroll", oldStatus: null, newStatus: "active", authorityProof: "f".repeat(64) }) }
|
|
eventFault?.(row); return { rows: [row] }
|
|
} }
|
|
const scope = () => ({ deadlineAt: Date.now() + 5000 })
|
|
const check = (current = scope()) => assertResolvedBandwidthPeersOnFence(config, sessions, () => false, fence as never, input, current)
|
|
try {
|
|
await t.test("mixed managed/external and managed/managed verify all MAC domains with static parameterized SQL", async () => {
|
|
for (const managed of [false, true]) {
|
|
reset(managed); await check(); assert.equal(sessions.size, 0)
|
|
assert.equal(calls.length, 6); assert(calls.every(call => !/\b(?:INSERT|UPDATE|DELETE|BEGIN|COMMIT|ROLLBACK)\b/.test(call.text)))
|
|
assert(calls[0].text.includes("pg_try_advisory_xact_lock_shared(8723116)"))
|
|
assert.equal(calls.filter(call => call.text.includes("bandwidth_external_node_")).length, managed ? 0 : 2)
|
|
}
|
|
assert.equal(managedRoles, 2); assert.equal(externalRoles, 2); assert.equal(catalogs, 2)
|
|
})
|
|
await t.test("unknown/changed participant references, duplicate canonical identity and hostile descriptors fail before SQL", async () => {
|
|
for (const fault of ["ref", "canonical", "source", "terminal", "getter"] as const) {
|
|
reset(); const mutable = input as unknown as { participants: { receipt: { peerRef: BandwidthPeerRef; canonicalNodeId: string; status: string }; evidence: object }[] }
|
|
if (fault === "ref") mutable.participants[1].receipt.peerRef = { kind: "external", enrollmentId: randomUUID() }
|
|
if (fault === "canonical") mutable.participants[1].receipt.canonicalNodeId = mutable.participants[0].receipt.canonicalNodeId
|
|
if (fault === "source") mutable.participants.reverse()
|
|
if (fault === "terminal") mutable.participants[1].receipt.status = "tombstoned"
|
|
let reads = 0; if (fault === "getter") Object.defineProperty(mutable.participants[1].evidence, "claims", { enumerable: true, get() { reads++; return [] } })
|
|
await assert.rejects(check(), BandwidthPeerFenceError); assert.equal(calls.length, 0); assert.equal(reads, 0)
|
|
}
|
|
})
|
|
await t.test("alias/node/claim/event corruption and terminal alias status refuse", async () => {
|
|
for (const field of ["record_mac", "enrollment_mac", "claim_proof", "status", "incarnation", "node_id"]) {
|
|
reset(); aliasFault = row => { row[field] = field === "status" ? "tombstoned" : "0".repeat(64) }; await assert.rejects(check(), BandwidthPeerFenceError)
|
|
}
|
|
for (const field of ["event_mac", "authority_proof", "old_status", "new_status", "kind", "incarnation"]) {
|
|
reset(); eventFault = row => { row[field] = "changed" }; await assert.rejects(check(), BandwidthPeerFenceError)
|
|
}
|
|
})
|
|
await t.test("signed v1/root drift/catalog/role rejection and lost shared lock never fall back", async () => {
|
|
for (const fault of ["v1", "root", "catalog", "role", "lock"] as const) {
|
|
reset(); if (fault === "v1") bootstrap.format = "mmapp-bandwidth-node-bootstrap-v1"
|
|
if (fault === "root") bootstrap.quiescenceProof = "e".repeat(64)
|
|
if (fault === "catalog") catalogAllowed = false
|
|
if (fault === "role") roleAllowed = false
|
|
if (fault === "lock") locked = false
|
|
await assert.rejects(check(), BandwidthPeerFenceError)
|
|
}
|
|
})
|
|
await t.test("key/source pin changes during awaited rows cannot yield a stale last verification", async () => {
|
|
reset(); sqlHook = async () => { if (calls.length === 6) await writeFile(issuerKeyFile, Buffer.alloc(32, 99)) }
|
|
await assert.rejects(check(), BandwidthPeerFenceError); await writeFile(issuerKeyFile, key)
|
|
reset(); sqlHook = () => { if (calls.length === 6) bootstrap.quiescenceProof = "e".repeat(64) }; await assert.rejects(check(), BandwidthPeerFenceError)
|
|
})
|
|
await t.test("abort/deadline stop late SQL continuation and clear tracked windows", async () => {
|
|
reset(); let resume!: () => void, started!: () => void; const pending = new Promise<void>(resolve => { resume = resolve }), dispatched = new Promise<void>(resolve => { started = resolve })
|
|
sqlHook = () => { started(); return pending }
|
|
const controller = new AbortController(), work = check({ ...scope(), signal: controller.signal } as never); await dispatched; controller.abort()
|
|
await assert.rejects(work, BandwidthPeerFenceError); resume(); await new Promise(resolve => setTimeout(resolve, 10)); assert.equal(calls.length, 1); assert.equal(sessions.size, 0)
|
|
reset(); let resumeDeadline!: () => void; const deadlinePending = new Promise<void>(resolve => { resumeDeadline = resolve }); sqlHook = () => deadlinePending; const now = Date.now
|
|
try { const work = check({ deadlineAt: now() + 30 }); Date.now = () => now() - 10000; await assert.rejects(work, BandwidthPeerFenceError) } finally { Date.now = now }
|
|
resumeDeadline(); await new Promise(resolve => setTimeout(resolve, 10)); assert.equal(sessions.size, 0); assert.equal(calls.length, 1)
|
|
})
|
|
} finally { mock.restoreAll(); await rm(directory, { recursive: true, force: true }) }
|
|
})
|