Files
MikrotikManager/backend/src/services/bandwidth-managed-peer-source.test.ts
T

135 lines
9.0 KiB
TypeScript

/** Guard and application transport controlled; no PG/Q authority claim here.
* Genuine guard + real SQL compositions are covered by the owned PG profile. */
import assert from "node:assert/strict"
import { EventEmitter } from "node:events"
import { randomUUID } from "node:crypto"
import { performance } from "node:perf_hooks"
import { mock, test } from "node:test"
let reads = 0, metas = 0, checkouts = 0, projections = 0, predicates = 0, revoked = false
let beforeRead: (() => void) | undefined, queryGate: Promise<void> | undefined
let current = { host: "127.0.0.1", port: 8443, useSsl: true, verifySsl: true, username: "private-user", password: "private-original-password", routingEndpointEpoch: randomUUID() }
let enabled = true
const clients: Array<EventEmitter & { destroyed: boolean; releases: number }> = []
const guard = Object.freeze({ async verifyRead() { reads++; beforeRead?.(); if (revoked) throw Error("revoked") },
async verifyMetadata() { metas++; if (revoked) throw Error("revoked") } })
const owner = guard
mock.module("./bandwidth-operator-writer-window.js", { namedExports: {
assertBandwidthOperatorPeerSourceGuard(value: unknown) { assert.equal(value, owner) },
} })
mock.module("../db/index.js", { namedExports: { pool: { async connect() {
checkouts++
const client = Object.assign(new EventEmitter(), { destroyed: false, releases: 0,
async query(input: { text: string; values: unknown[] }) {
await queryGate
const { text, values } = input
if (text.startsWith("/* bandwidth-managed:guarded-credentials */")) {
projections++; assert(text.includes("enabled IS TRUE AND routing_endpoint_epoch=$2::uuid"))
assert.deepEqual(values, [17, initialEpoch])
return { command: "SELECT", rowCount: enabled && current.routingEndpointEpoch === values[1] ? 1 : 0,
rows: enabled && current.routingEndpointEpoch === values[1] ? [{ endpoint: { ...current } }] : [] }
}
assert(text.startsWith("/* bandwidth-managed:metadata-current */")); predicates++
const match = enabled && values[0] === 17 && [current.host, current.port, current.useSsl, current.verifySsl,
current.username, current.password, current.routingEndpointEpoch].every((value, i) => value === values[i + 1])
return { command: "SELECT", rowCount: 1, rows: [{ metadata_current: match }] }
},
release(destroy: boolean) { this.releases++; assert.equal(this.releases, 1); this.destroyed = destroy },
})
clients.push(client); return client
} } } })
const { createConfiguredManagedBandwidthPeerSource } = await import("./bandwidth-managed-peer-source.js")
const initialEpoch = current.routingEndpointEpoch
const config = { serverId: 17, sourceProof: "c".repeat(64), authorityGeneration: "controlled-unit-generation", routingEndpointEpoch: initialEpoch }
const peer = { kind: "server" as const, serverId: 17 }
const scope = (signal?: AbortSignal, duration = 1000) => ({ deadlineAt: Date.now() + duration, signal })
const make = () => createConfiguredManagedBandwidthPeerSource(config, guard as never)
const reset = () => { reads = metas = checkouts = projections = predicates = 0; revoked = false; beforeRead = undefined; queryGate = undefined;
enabled = true; current = { host: "127.0.0.1", port: 8443, useSsl: true, verifySsl: true, username: "private-user", password: "private-original-password", routingEndpointEpoch: initialEpoch }; clients.length = 0 }
const turn = () => new Promise<void>(done => setImmediate(done))
test("managed operator source fixed transport and private binding", async t => {
await t.test("inert constructor, guard before projection, metadata uses no read guard or credential result", async () => {
reset(); const source = make(); assert.equal(checkouts + reads + metas, 0)
try {
const snapshot = await source.read(peer, scope())
assert(Object.isFrozen(snapshot) && Object.isFrozen(snapshot.endpoint)); assert.equal(snapshot.endpoint.password, current.password)
assert.equal(reads, 2); assert.equal(projections, 1); assert.equal(predicates, 1)
const baseline = { reads, projections }
await source.assertMetadataCurrent(snapshot, scope()); await source.assertMetadataCurrent(structuredClone(snapshot), scope())
assert.equal(reads, baseline.reads); assert.equal(projections, baseline.projections); assert.equal(predicates, 3)
assert.equal(clients.filter(client => client.destroyed).length, 1)
} finally { source.close() }
})
await t.test("metadata requires previous read; no structural guard or foreign peer fallback", async () => {
reset(); assert.throws(() => createConfiguredManagedBandwidthPeerSource(config, { ...guard } as never))
const source = make()
await assert.rejects(source.assertMetadataCurrent({} as never, scope())); assert.equal(checkouts, 0)
await assert.rejects(source.read({ kind: "external", enrollmentId: randomUUID() } as never, scope())); assert.equal(checkouts, 0)
source.close()
})
await t.test("current grant failure precedes pool/secret dispatch; changed epoch gates SQL payload", async () => {
for (const fault of ["original", "epoch", "disabled"] as const) {
reset(); const source = make()
if (fault === "original") revoked = true
else beforeRead = () => { if (fault === "epoch") current.routingEndpointEpoch = randomUUID(); else enabled = false }
await assert.rejects(source.read(peer, scope()))
if (fault === "original") assert.equal(checkouts, 0)
assert.equal(predicates, 0); await assert.rejects(source.read(peer, scope())); source.close()
}
})
await t.test("all private snapshot fields/current endpoint changes refuse metadata without another projection", async () => {
for (const fault of ["password", "epoch", "enabled", "expected"] as const) {
reset(); const source = make(), original = await source.read(peer, scope()), before = { reads, projections }
if (fault === "password") current.password = "changed"
if (fault === "epoch") current.routingEndpointEpoch = randomUUID()
if (fault === "enabled") enabled = false
const expected = fault === "expected" ? { ...original, endpoint: { ...original.endpoint, username: "forged" } } : original
await assert.rejects(source.assertMetadataCurrent(expected, scope())); assert.equal(reads, before.reads); assert.equal(projections, before.projections)
await assert.rejects(source.read(peer, scope())); source.close()
}
})
await t.test("scope/expected getters and proxies have zero callbacks", async () => {
reset(); let touched = 0
const source = make(), original = await source.read(peer, scope())
const hostile = { ...original, get endpoint() { touched++; return original.endpoint } }
await assert.rejects(source.assertMetadataCurrent(hostile, scope())); assert.equal(touched, 0); source.close()
const second = make()
await assert.rejects(second.read(peer, new Proxy(scope(), { getPrototypeOf() { touched++; return Object.prototype } })))
assert.equal(touched, 0); second.close()
})
await t.test("abort/close/busy pending driver retire source and suppress late results", async () => {
for (const fault of ["abort", "close", "busy"] as const) {
reset(); const source = make(), controller = new AbortController()
let finish!: () => void; queryGate = new Promise<void>(done => { finish = done })
const pending = source.read(peer, scope(controller.signal)); void pending.catch(() => {})
while (!clients.length) await turn()
if (fault === "abort") controller.abort()
if (fault === "close") source.close()
if (fault === "busy") await assert.rejects(source.read(peer, scope()))
await assert.rejects(pending); assert(clients[0].destroyed)
finish(); await turn(); await turn()
assert.equal(predicates, 0); await assert.rejects(source.read(peer, scope())); source.close()
}
})
await t.test("source close revokes retained metadata and pre-abort cannot borrow", async () => {
reset(); const source = make(), original = await source.read(peer, scope())
source.close(); await assert.rejects(source.assertMetadataCurrent(original, scope())); await assert.rejects(source.read(peer, scope()))
const second = make(), expired = new AbortController(); expired.abort()
await assert.rejects(second.read(peer, scope(expired.signal))); assert.equal(reads, 2); second.close()
})
await t.test("later scope cannot renew the first wall or monotonic horizon", async () => {
for (const clock of ["wall", "mono"] as const) {
reset(); const source = make(), original = await source.read(peer, scope(undefined, 1000))
const before = { reads, projections, predicates }
const realWall = Date.now.bind(Date), realMono = performance.now.bind(performance)
const spy = clock === "wall" ? mock.method(Date, "now", () => realWall() + 2000)
: mock.method(performance, "now", () => realMono() + 2000)
try {
await assert.rejects(source.assertMetadataCurrent(original, scope(undefined, 5000)))
assert.deepEqual({ reads, projections, predicates }, before)
} finally { spy.mock.restore(); source.close() }
}
})
})