Files
MikrotikManager/backend/src/services/bandwidth-registry-combined.test.ts
T

106 lines
8.4 KiB
TypeScript

/** Actual registry guards; explicit inert SQL/issuer/provenance fixture only.
* No PG, Docker, external Q, native transport or operating acceptance claim. */
import assert from "node:assert/strict"
import { randomUUID } from "node:crypto"
import { test } from "node:test"
import { setTimeout as delay } from "node:timers/promises"
import { createBandwidthNodeRegistry, type BandwidthNodeRegistryDependencies } from "./bandwidth-node-registry.js"
import { createBandwidthExternalNodeRegistry, type BandwidthExternalNodeRegistryDependencies } from "./bandwidth-external-node-registry.js"
import type { BandwidthScope } from "./bandwidth-admission.js"
import type { BandwidthNodeObservationEvidence } from "./bandwidth-node-observation.js"
import type { BandwidthPeerObservationEvidence } from "./bandwidth-peer-observation.js"
type Kind = "managed" | "external"
type Fault = "action" | "peer" | "copy-token" | "scope" | "accessor" | "nested-accessor" | "reuse" | "root-drift" | "late"
function fixture(kind: Kind, useCombined = true) {
const token = Object.freeze(Object.create(null)), subject = kind === "managed" ? 71 : randomUUID(), expiry = Date.now() + 10000
const root = { installationId: randomUUID(), issuerKeySha256: "a".repeat(64), quiescenceProof: "b".repeat(64) }
const authority = { ...root, authorityProof: "c".repeat(64), authorityGeneration: "synthetic-original", expiresAt: expiry }
const evidence = { version: kind === "managed" ? 1 : 2, ...(kind === "managed" ? { serverId: subject } : { peerRef: { kind: "external", enrollmentId: subject } }),
sourceProof: "d".repeat(64), authorityGeneration: "synthetic-source", routingEndpointEpoch: randomUUID(), observedAt: Date.now(), expiresAt: expiry,
claims: [{ kind: "system-id", value: "synthetic-node" }], physicalUniquenessVerified: false, cloneResistanceVerified: false }
const queries: string[] = [], releases: boolean[] = []
let frames = 0, inspections = 0, authorizations = 0, getters = 0, revoked = false, saved: unknown, fault: Fault | undefined
let queryHook: ((sql: string) => void) | undefined
const inspect = async (value: unknown) => { inspections++; assert.equal(value, token); return structuredClone(evidence) }
const authorize = async () => { authorizations++; if (revoked) throw Error("synthetic original revoked"); return { ...authority } }
const fresh = async (action: string, observation: unknown, requestedId: number | string | undefined, scope: BandwidthScope): Promise<never> => {
frames++; assert.equal(observation, token); if (revoked) throw Error("synthetic original revoked")
assert(requestedId === undefined || requestedId === subject)
if (fault === "reuse" && saved) return saved as never
const frame: Record<string, unknown> = { action, observation, scope, [kind === "managed" ? "serverId" : "enrollmentId"]: subject,
evidence: structuredClone(evidence), authority: { ...authority } }
if (fault === "action") frame.action = "quarantine"
if (fault === "peer") frame[kind === "managed" ? "serverId" : "enrollmentId"] = kind === "managed" ? 72 : randomUUID()
if (fault === "copy-token") frame.observation = { ...token }
if (fault === "scope") frame.scope = { ...scope }
if (fault === "accessor") Object.defineProperty(frame, "authority", { enumerable: true, get() { getters++; return authority } })
if (fault === "nested-accessor") Object.defineProperty(frame.authority, "authorityProof", { enumerable: true, get() { getters++; return authority.authorityProof } })
if (fault === "root-drift" && frames > 1) (frame.authority as typeof authority).installationId = randomUUID()
if (fault === "late") { (frame.evidence as typeof evidence).expiresAt = Date.now() + 5; await delay(15) }
saved = Object.freeze(frame); return saved as never
}
const common = { now: Date.now, authorize, async connect() { return {
release(unsafe?: boolean) { releases.push(unsafe === true) },
async query(sql: string) {
queries.push(sql); queryHook?.(sql)
if (sql === "BEGIN" || sql === "COMMIT" || sql === "ROLLBACK") return { command: sql, rows: [] }
if (sql.startsWith("DO $mmapp_bandwidth_register$")) return { command: "DO", rows: [] }
if (sql.startsWith("WITH aliases AS MATERIALIZED")) return { command: "SELECT", rows: [{ aliases: [], nodes: [], events: [], claim_nodes: [] }] }
if (sql.includes("FROM mmapp_control.bandwidth_node_authority")) return { command: "SELECT", rows: [{ installation_id: root.installationId,
issuer_key_sha256: root.issuerKeySha256, quiescence_proof: root.quiescenceProof, status: "active" }] }
if (sql.includes("set_config") || sql.includes("pg_advisory_xact_lock")) return { command: "SELECT", rows: [] }
throw Error("Unexpected fixed fixture SQL")
},
} }, async keyedProof() { return "e".repeat(64) } }
const dependencies = kind === "managed"
? { ...common, inspect: inspect as (value: unknown) => Promise<BandwidthNodeObservationEvidence>, inspectAndAuthorize: useCombined ? fresh : undefined } satisfies BandwidthNodeRegistryDependencies
: { ...common, inspect: inspect as (value: unknown) => Promise<BandwidthPeerObservationEvidence>, inspectAndAuthorize: useCombined ? fresh : undefined } satisfies BandwidthExternalNodeRegistryDependencies
const registry = kind === "managed" ? createBandwidthNodeRegistry(dependencies as BandwidthNodeRegistryDependencies) : createBandwidthExternalNodeRegistry(dependencies as BandwidthExternalNodeRegistryDependencies)
return { registry, token, queries, releases, dependencies, setFault(value: Fault) { fault = value }, revoke() { revoked = true },
hook(value: typeof queryHook) { queryHook = value }, counts: () => ({ frames, inspections, authorizations, getters }) }
}
const scope = () => ({ deadlineAt: Date.now() + 5000 })
for (const kind of ["managed", "external"] as const) {
test(kind + ": fresh combined frames replace only paired inspect/authorize, generic fallback remains", async () => {
for (const combined of [true, false]) {
const f = fixture(kind, combined)
const receipt = await f.registry.register(f.token, scope())
assert.equal(receipt.outcome, "new"); assert.equal(f.queries.filter(sql => sql === "COMMIT").length, 1); assert.deepEqual(f.releases, [true])
if (combined) { assert(f.counts().frames > f.queries.length); assert.equal(f.counts().inspections + f.counts().authorizations, 0) }
else { assert.equal(f.counts().frames, 0); assert(f.counts().inspections > f.queries.length); assert.equal(f.counts().inspections, f.counts().authorizations) }
}
})
test(kind + ": captured constructor callback cannot be replaced", async () => {
const f = fixture(kind)
f.dependencies.inspectAndAuthorize = async () => { throw Error("replacement") }
assert.equal((await f.registry.register(f.token, scope())).status, "active")
})
test(kind + ": action/peer/copy/scope/accessor/late frames refuse before SQL", async () => {
for (const fault of ["action", "peer", "copy-token", "scope", "accessor", "nested-accessor", "late"] as const) {
const f = fixture(kind); f.setFault(fault)
await assert.rejects(f.registry.register(f.token, scope()))
assert.equal(f.queries.length, 0); assert.equal(f.counts().getters, 0)
}
})
test(kind + ": stale reused frame/root drift and copied caller token refuse before BEGIN", async () => {
for (const fault of ["reuse", "root-drift"] as const) {
const f = fixture(kind); f.setFault(fault)
await assert.rejects(f.registry.register(f.token, scope())); assert.equal(f.queries.length, 0); assert.deepEqual(f.releases, [true])
}
const f = fixture(kind); await assert.rejects(f.registry.register({ ...f.token }, scope())); assert.equal(f.queries.length, 0)
})
test(kind + ": every post-IO frame rechecks revocation before subsequent SQL or COMMIT", async () => {
for (const boundary of ["BEGIN", "DO"] as const) {
const f = fixture(kind)
f.hook(sql => { if (boundary === "BEGIN" ? sql === "BEGIN" : sql.startsWith("DO $mmapp_bandwidth_register$")) f.revoke() })
await assert.rejects(f.registry.register(f.token, scope()))
assert(!f.queries.includes("COMMIT")); assert.deepEqual(f.releases, [true])
// BEGIN's post-ACK guard can fail before transactionStarted is assigned;
// existing fallback destroys that lease, so PG rolls it back on close.
if (boundary === "BEGIN") assert.deepEqual(f.queries, ["BEGIN"])
else assert.equal(f.queries.at(-1), "ROLLBACK")
}
})
}