373 lines
34 KiB
TypeScript
373 lines
34 KiB
TypeScript
import { MIGRATION_MANIFEST } from "../db/migration-manifest.js"
|
|
import assert from "node:assert/strict"
|
|
import { createHash, createHmac, randomBytes, randomUUID } from "node:crypto"
|
|
import { createServer } from "node:http"
|
|
import { once } from "node:events"
|
|
import { execFile } from "node:child_process"
|
|
import { writeFile } from "node:fs/promises"
|
|
import { resolve } from "node:path"
|
|
import { promisify } from "node:util"
|
|
import type { BandwidthNodeRegistryAction } from "./bandwidth-node-registry.js"
|
|
import type { BandwidthNodeObservationEvidence, BandwidthNodeSourceSnapshot } from "./bandwidth-node-observation.js"
|
|
import type { BandwidthScope } from "./bandwidth-admission.js"
|
|
import { assertOwnedBandwidthSql, canonical, createOwnedBandwidthHarness, fixtureBinding, prepareOwnedBandwidthState, scope } from "./bandwidth-admission-process.sql-helper.js"
|
|
|
|
assertOwnedBandwidthSql()
|
|
await prepareOwnedBandwidthState()
|
|
const { pool, closePool } = await import("../db/index.js")
|
|
const { Pool } = await import("pg")
|
|
const { applySqlMigrations } = await import("../db/migrate.js")
|
|
const { BANDWIDTH_ADMISSION_PROPOSAL_DDL } = await import("./bandwidth-admission-schema.js")
|
|
const { BANDWIDTH_NODE_REGISTRY_DDL, BANDWIDTH_NODE_REGISTRY_TABLES } = await import("./bandwidth-node-registry-schema.js")
|
|
const { createBandwidthNodeRegistry } = await import("./bandwidth-node-registry.js")
|
|
const { createBandwidthNodeObservationReader } = await import("./bandwidth-node-observation.js")
|
|
const { createProbeStorageConnectionConnector } = await import("./server-probe-storage-connection.js")
|
|
const cases: string[] = [], limitations: string[] = []
|
|
const key = randomBytes(32), installationId = randomUUID(), issuerKeySha256 = createHash("sha256").update(key).digest("hex")
|
|
const mac = (purpose: string, value: unknown) => createHmac("sha256", key).update("owned-bandwidth-node-registry:" + purpose + ":").update(canonical(value)).digest("hex")
|
|
const quiescenceProof = mac("synthetic-operator-quiescence", "Owned local fixture only; not actual production enrollment readiness")
|
|
const root = { installationId, issuerKeySha256, quiescenceProof }
|
|
const role = "bw_registry_" + randomUUID().replaceAll("-", ""), password = randomBytes(32).toString("hex")
|
|
assert(/^bw_registry_[a-f0-9]{32}$/.test(role)); assert(/^[a-f0-9]{64}$/.test(password))
|
|
const roleUrl = new URL(process.env.DATABASE_URL!); roleUrl.username = role; roleUrl.password = password
|
|
let runtime: InstanceType<typeof Pool> | undefined, roleCreated = false, nativeGets = 0, realCommitLosses = 0, droppedCommitCommands = 0
|
|
const sources = new Map<number, BandwidthNodeSourceSnapshot>(), license = new Map<number, Record<string, string>>()
|
|
const server = createServer((req, res) => {
|
|
const auth = Buffer.from((req.headers.authorization ?? "").replace(/^Basic /, ""), "base64").toString("utf8")
|
|
const match = /^reg-(\d+)(?:-v2)?:/.exec(auth), id = match ? Number(match[1]) : -1
|
|
assert.equal(req.method, "GET"); assert.equal(req.url, "/rest/system/license"); nativeGets++
|
|
if (!license.has(id)) { res.writeHead(404); res.end("{}"); return }
|
|
res.setHeader("content-type", "application/json"); res.end(JSON.stringify(license.get(id)))
|
|
})
|
|
server.listen(0, "127.0.0.1"); await once(server, "listening")
|
|
const address = server.address(); assert(address && typeof address !== "string")
|
|
const nativePort = address.port
|
|
const reader = createBandwidthNodeObservationReader({ async read(id) { return sources.get(id) } })
|
|
const observation = (id: number) => reader.observe(id, scope())
|
|
const coreTables = ["bandwidth_attempts", "bandwidth_node_occupancy", "bandwidth_attempt_events"]
|
|
async function digestTables(tables: readonly string[]) {
|
|
const result: Record<string, { rows: number; sha256: string }> = {}
|
|
for (const table of tables) {
|
|
assert(/^bandwidth_[a-z_]+$/.test(table))
|
|
const rows = (await pool.query(`SELECT to_jsonb(t) AS row FROM mmapp_control.${table} t ORDER BY to_jsonb(t)::text`)).rows
|
|
result[table] = { rows: rows.length, sha256: createHash("sha256").update(canonical(rows)).digest("hex") }
|
|
}
|
|
return result
|
|
}
|
|
async function endpoint(claims: Record<string, string>) {
|
|
const id = Number((await pool.query("INSERT INTO public.servers(name,host,enabled) VALUES('owned-registry','127.0.0.1',false) RETURNING id")).rows[0].id)
|
|
sources.set(id, { serverId: id, enabled: true, sourceProof: mac("source", id), authorityGeneration: "owned-source-v1",
|
|
endpoint: { host: "127.0.0.1", port: nativePort, useSsl: false, verifySsl: true, username: "reg-" + id, password: "owned-native-private", routingEndpointEpoch: randomUUID() } })
|
|
license.set(id, claims); return id
|
|
}
|
|
const expiry = Date.now() + 300000, deniedWrites = new Set<number>(), expired = new Map<number, number>(), epochs = new Map<number, number>()
|
|
let authorizeHook: ((action: BandwidthNodeRegistryAction, id: number, evidence: Readonly<BandwidthNodeObservationEvidence> | undefined) => Promise<void>) | undefined
|
|
let proofHook: ((purpose: string) => Promise<void>) | undefined
|
|
const authorize = async (action: BandwidthNodeRegistryAction, id: number, _window: BandwidthScope, evidence: Readonly<BandwidthNodeObservationEvidence> | undefined) => {
|
|
await authorizeHook?.(action, id, evidence)
|
|
assert(sources.has(id))
|
|
if (action !== "resolve" && deniedWrites.has(id)) throw Error("Owned original grant does not authorize registry write")
|
|
return { ...root, authorityProof: mac("original-grant", { action, id, epoch: epochs.get(id) ?? 1 }), authorityGeneration: "owned-grant-" + (epochs.get(id) ?? 1), expiresAt: expired.get(id) ?? expiry }
|
|
}
|
|
const deferred = () => { let resolve!: () => void; const promise = new Promise<void>(done => { resolve = done }); return { promise, resolve } }
|
|
function makeHost(options: { loseCommit?: boolean; dropCommitCommand?: boolean; beginBarrier?: { enter(): Promise<void> }; revokeBeforeCommit?: number; now?: () => number } = {}) {
|
|
let lose = options.loseCommit ?? false, lastPid = 0, checkouts = 0, commits = 0, queriesAfterRevocation = 0, physicalQueries = 0
|
|
let dropCommand = options.dropCommitCommand ?? false
|
|
let enrolled = false, finalAuthorityReturned = false, inspections = 0, revokedInsideInspect = false
|
|
const connector = createProbeStorageConnectionConnector(async () => {
|
|
assert(runtime); const raw = await runtime.connect(); checkouts++
|
|
lastPid = Number((await raw.query("SELECT pg_backend_pid() AS pid")).rows[0].pid); return raw
|
|
})
|
|
const host = createBandwidthNodeRegistry({ now: options.now ?? Date.now, authorize,
|
|
inspect: async (token, window) => {
|
|
const value = await reader.inspect(token, window)
|
|
// The first two inspections follow the final authority SELECT and the
|
|
// explicit final guard. The third is the real COMMIT dispatch guard.
|
|
if (value.serverId === options.revokeBeforeCommit && finalAuthorityReturned && ++inspections === 3) {
|
|
deniedWrites.add(value.serverId); revokedInsideInspect = true
|
|
}
|
|
return value
|
|
},
|
|
keyedProof: async (purpose, value) => { await proofHook?.(purpose); return mac(purpose, value) },
|
|
connect: async window => {
|
|
const client = await connector(window)
|
|
return { release: destroy => client.release(destroy), async query(sql, values, queryOptions) {
|
|
physicalQueries++
|
|
if (revokedInsideInspect) queriesAfterRevocation++
|
|
const result = await client.query(sql, values, queryOptions)
|
|
if (sql.startsWith("DO $mmapp_bandwidth_register$") || sql.startsWith("INSERT INTO mmapp_control.bandwidth_node_events")) enrolled = true
|
|
if (enrolled && sql.includes("SELECT installation_id::pg_catalog.text")) finalAuthorityReturned = true
|
|
if (sql === "BEGIN") await options.beginBarrier?.enter()
|
|
if (sql === "COMMIT") {
|
|
commits++
|
|
if (lose) { lose = false; realCommitLosses++; throw Error("Owned lost ACK AFTER actual registry COMMIT") }
|
|
if (dropCommand) { dropCommand = false; droppedCommitCommands++; return { rows: result.rows } }
|
|
}
|
|
return result
|
|
} }
|
|
},
|
|
})
|
|
return { host, pid: () => lastPid, checkouts: () => checkouts, commits: () => commits, physicalQueries: () => physicalQueries, queriesAfterRevocation: () => queriesAfterRevocation, revokedInsideInspect: () => revokedInsideInspect }
|
|
}
|
|
try {
|
|
await applySqlMigrations(pool)
|
|
assert.equal(Number((await pool.query("SELECT count(*) AS n FROM public.schema_migrations")).rows[0].n), MIGRATION_MANIFEST.length)
|
|
await pool.query("CREATE SCHEMA mmapp_control"); await pool.query(BANDWIDTH_ADMISSION_PROPOSAL_DDL); await pool.query(BANDWIDTH_NODE_REGISTRY_DDL)
|
|
await pool.query(`CREATE ROLE "${role}" LOGIN PASSWORD '${password}' NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS NOINHERIT`); roleCreated = true
|
|
await pool.query("REVOKE ALL ON SCHEMA mmapp_control FROM PUBLIC"); await pool.query(`GRANT USAGE ON SCHEMA mmapp_control TO "${role}"`)
|
|
await pool.query("REVOKE ALL ON ALL FUNCTIONS IN SCHEMA mmapp_control FROM PUBLIC")
|
|
await pool.query(`GRANT SELECT ON mmapp_control.bandwidth_node_authority TO "${role}"`)
|
|
await pool.query(`GRANT SELECT,INSERT ON mmapp_control.bandwidth_nodes,mmapp_control.bandwidth_node_events TO "${role}"`)
|
|
await pool.query(`GRANT SELECT,INSERT,UPDATE ON mmapp_control.bandwidth_node_aliases TO "${role}"`)
|
|
for (const fn of ["bandwidth_node_authority_guard", "bandwidth_node_immutable_guard", "bandwidth_node_alias_guard", "bandwidth_node_event_guard", "bandwidth_node_alias_consistency_guard", "bandwidth_admission_reject_truncate"])
|
|
await pool.query(`GRANT EXECUTE ON FUNCTION mmapp_control.${fn}() TO "${role}"`)
|
|
runtime = new Pool({ connectionString: roleUrl.toString(), max: 6 })
|
|
const flags = (await runtime.query("SELECT rolname,rolsuper,rolcreatedb,rolcreaterole,rolreplication,rolbypassrls,rolinherit FROM pg_catalog.pg_roles WHERE rolname=current_user")).rows[0]
|
|
assert.equal(flags.rolname, role)
|
|
for (const field of ["rolsuper", "rolcreatedb", "rolcreaterole", "rolreplication", "rolbypassrls", "rolinherit"]) assert.equal(flags[field], false)
|
|
await assert.rejects(runtime.query("UPDATE mmapp_control.bandwidth_nodes SET claim_proof=claim_proof"))
|
|
await assert.rejects(runtime.query("UPDATE mmapp_control.bandwidth_node_authority SET status='quarantined'"))
|
|
await assert.rejects(runtime.query("DELETE FROM mmapp_control.bandwidth_node_aliases"))
|
|
await assert.rejects(runtime.query("SELECT * FROM mmapp_control.bandwidth_attempts"))
|
|
cases.push("actual restricted LOGIN registry role: precise registry DML, no node/authority UPDATE, no DELETE, no core access or elevated flags")
|
|
const primary = makeHost(), sameClaims = { "system-id": "SYS-SHARED", "software-id": "SOFT-SHARED" }
|
|
const a = await endpoint(sameClaims), b = await endpoint(sameClaims)
|
|
const unseeded = await digestTables(BANDWIDTH_NODE_REGISTRY_TABLES)
|
|
await assert.rejects(primary.host.register(await observation(a), scope()))
|
|
assert.deepEqual(await digestTables(BANDWIDTH_NODE_REGISTRY_TABLES), unseeded)
|
|
await pool.query("INSERT INTO mmapp_control.bandwidth_node_authority(id,installation_id,issuer_key_sha256,quiescence_proof,status) VALUES(1,$1,$2,$3,'active')", [installationId, issuerKeySha256, quiescenceProof])
|
|
cases.push("missing external authority refuses without bootstrap/seed; owner explicitly installs synthetic quiescence/installation/separate issuer key record")
|
|
|
|
const first = await primary.host.register(await observation(a), scope()), second = await primary.host.register(await observation(b), scope())
|
|
assert.match(first.canonicalNodeId, /^[a-f0-9-]{36}$/); assert.equal(first.canonicalNodeId, second.canonicalNodeId); assert.notEqual(first.incarnation, second.incarnation)
|
|
assert.equal((await primary.host.register(await observation(a), scope())).outcome, "existing")
|
|
const missing = await endpoint({ "system-id": "MISSING" }), beforeResolve = await digestTables(BANDWIDTH_NODE_REGISTRY_TABLES)
|
|
await assert.rejects(primary.host.resolve(await observation(missing), scope())); assert.deepEqual(await digestTables(BANDWIDTH_NODE_REGISTRY_TABLES), beforeResolve)
|
|
await assert.rejects(primary.host.register(JSON.parse(JSON.stringify(await observation(missing))), scope()))
|
|
cases.push("two genuine native aliases share one random canonical UUID with distinct incarnations; existing registration is a receipt; resolve/serialized observation never auto-enroll")
|
|
{
|
|
const id = await endpoint({ "system-id": "ACTUAL-OBSERVED-UNAPPROVED-CLAIM" }), token = await observation(id), fixture = makeHost()
|
|
const before = await digestTables(BANDWIDTH_NODE_REGISTRY_TABLES)
|
|
const approvedClaims = [{ kind: "system-id", value: "DIFFERENT-ORIGINAL-APPROVED-CLAIM" }]
|
|
let received: Readonly<BandwidthNodeObservationEvidence> | undefined
|
|
authorizeHook = async (action, serverId, evidence) => {
|
|
if (action === "register" && serverId === id) {
|
|
received = evidence
|
|
assert(evidence); assert.equal(evidence.sourceProof, sources.get(id)!.sourceProof)
|
|
// The fixed original-grant fixture approves another claim. Genuine
|
|
// network evidence is necessary but cannot substitute for that intent.
|
|
assert.deepEqual(evidence.claims, approvedClaims)
|
|
}
|
|
}
|
|
try {
|
|
await assert.rejects(fixture.host.register(token, scope()))
|
|
assert(received); assert.equal(received.serverId, id); assert.equal(received.sourceProof, sources.get(id)!.sourceProof)
|
|
assert.deepEqual(received.claims, [{ kind: "system-id", value: "ACTUAL-OBSERVED-UNAPPROVED-CLAIM" }])
|
|
assert(Object.isFrozen(received)); assert(Object.isFrozen(received.claims)); assert(received.claims.every(Object.isFrozen))
|
|
assert(!Object.hasOwn(received, "endpoint")); assert(!JSON.stringify(received).includes("owned-native-private")); assert(!JSON.stringify(received).includes("reg-" + id))
|
|
assert.equal(fixture.checkouts(), 0); assert.deepEqual(await digestTables(BANDWIDTH_NODE_REGISTRY_TABLES), before)
|
|
} finally { authorizeHook = undefined }
|
|
cases.push("fixed original grant receives deeply frozen genuine inspected claims/source as fourth argument and denies different approved intent before any PG checkout; credentials/endpoint remain private")
|
|
}
|
|
const typedIds: string[] = []
|
|
for (const claims of [{ "system-id": "LEFT", "software-id": "RIGHT" }, { "system-id": "RIGHT", "software-id": "LEFT" }, { "system-id": "ONE" }, { "software-id": "ONE" }] as Array<Record<string, string>>) {
|
|
const id = await endpoint(claims); typedIds.push((await primary.host.register(await observation(id), scope())).canonicalNodeId)
|
|
}
|
|
assert.equal(new Set(typedIds).size, 4)
|
|
license.set(a, { "system-id": "FOREIGN", "software-id": "SOFT-SHARED" })
|
|
const driftBefore = await digestTables(BANDWIDTH_NODE_REGISTRY_TABLES)
|
|
await assert.rejects(primary.host.resolve(await observation(a), scope())); await assert.rejects(primary.host.register(await observation(a), scope()))
|
|
assert.deepEqual(await digestTables(BANDWIDTH_NODE_REGISTRY_TABLES), driftBefore); license.set(a, sameClaims)
|
|
const source = sources.get(a)!; source.endpoint.username = "reg-" + a + "-v2"; source.endpoint.password = "changed-private"; source.endpoint.routingEndpointEpoch = randomUUID(); source.sourceProof = mac("new-source-epoch", a)
|
|
assert.equal((await primary.host.resolve(await observation(a), scope())).canonicalNodeId, first.canonicalNodeId)
|
|
cases.push("typed claim kinds/full vectors never collapse; native claim drift cannot mint a replacement key; credentials/endpoint epoch drift with same observed claims preserves the canonical UUID")
|
|
|
|
const otherId = await endpoint({ "system-id": "OTHER-NODE" }), other = await primary.host.register(await observation(otherId), scope())
|
|
const core = await createOwnedBandwidthHarness(), coreBinding = fixtureBinding(first.canonicalNodeId, other.canonicalNodeId)
|
|
core.register(coreBinding); await core.journal.reserve(coreBinding, scope()); await core.journal.arm(coreBinding, scope()); await core.journal.quarantine(coreBinding, scope())
|
|
const coreBefore = await digestTables(coreTables)
|
|
assert.equal((await primary.host.retire(a, "tombstone", scope())).status, "tombstoned")
|
|
await assert.rejects(primary.host.register(await observation(a), scope())); await assert.rejects(primary.host.resolve(await observation(a), scope()))
|
|
await assert.rejects(primary.host.retire(a, "quarantine", scope()))
|
|
assert.equal((await primary.host.retire(a, "tombstone", scope())).outcome, "existing")
|
|
const replacementId = await endpoint(sameClaims), replacement = await primary.host.register(await observation(replacementId), scope())
|
|
assert.equal(replacement.canonicalNodeId, first.canonicalNodeId); assert.notEqual(replacement.incarnation, first.incarnation)
|
|
await primary.host.retire(b, "quarantine", scope()); await assert.rejects(primary.host.register(await observation(b), scope()))
|
|
await pool.query("DELETE FROM public.servers WHERE id=ANY($1::int[])", [[a, b]])
|
|
assert.deepEqual(await digestTables(coreTables), coreBefore)
|
|
const overlapping = fixtureBinding(replacement.canonicalNodeId, randomUUID()); core.register(overlapping)
|
|
await assert.rejects(core.journal.reserve(overlapping, scope())); assert.deepEqual(await digestTables(coreTables), coreBefore)
|
|
cases.push("actual core reserve/arm/unknown quarantine survives alias tombstone/quarantine/new alias and SQL app-server DELETE byte-for-byte; replacement alias cannot evade unknown occupancy")
|
|
|
|
{
|
|
const c1 = await endpoint({ "system-id": "CONCURRENT" }), c2 = await endpoint({ "system-id": "CONCURRENT" }), gate = deferred(); let joined = 0
|
|
const beginBarrier = { async enter() { if (++joined === 2) gate.resolve(); await gate.promise } }
|
|
const left = makeHost({ beginBarrier }), right = makeHost({ beginBarrier }), o1 = await observation(c1), o2 = await observation(c2)
|
|
const [r1, r2] = await Promise.all([left.host.register(o1, scope()), right.host.register(o2, scope())])
|
|
assert.notEqual(left.pid(), right.pid()); assert.equal(r1.canonicalNodeId, r2.canonicalNodeId); assert.notEqual(r1.incarnation, r2.incarnation)
|
|
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mmapp_control.bandwidth_nodes WHERE node_id=$1", [r1.canonicalNodeId])).rows[0].n, 1)
|
|
cases.push("two independent bounded PG clients/host instances start behind a real BEGIN barrier and concurrently enroll same native claim as exactly one node/two incarnations")
|
|
}
|
|
{
|
|
const id = await endpoint({ "system-id": "LOST-COMMIT" }), lost = makeHost({ loseCommit: true })
|
|
await assert.rejects(lost.host.register(await observation(id), scope()))
|
|
const persisted = (await pool.query("SELECT node_id::text FROM mmapp_control.bandwidth_node_aliases WHERE server_id=$1", [id])).rows[0]; assert(persisted)
|
|
const receipt = await makeHost().host.register(await observation(id), scope())
|
|
assert.equal(receipt.outcome, "existing"); assert.equal(receipt.canonicalNodeId, persisted.node_id)
|
|
const lostRetire = makeHost({ loseCommit: true }); await assert.rejects(lostRetire.host.retire(id, "tombstone", scope()))
|
|
assert.equal((await makeHost().host.retire(id, "tombstone", scope())).outcome, "existing")
|
|
await assert.rejects(primary.host.register(await observation(id), scope()))
|
|
cases.push("real register and retirement COMMITs lose ACK only AFTER server completion: durable rows persist, calls refuse, fresh host returns existing receipt without reactivation/native capability")
|
|
}
|
|
{
|
|
const id = await endpoint({ "system-id": "MISSING-COMMIT-COMMAND" }), badAck = makeHost({ dropCommitCommand: true })
|
|
await assert.rejects(badAck.host.register(await observation(id), scope()))
|
|
const stored = (await pool.query("SELECT node_id::text FROM mmapp_control.bandwidth_node_aliases WHERE server_id=$1", [id])).rows[0]; assert(stored)
|
|
const before = await digestTables(BANDWIDTH_NODE_REGISTRY_TABLES)
|
|
const existing = await makeHost().host.register(await observation(id), scope())
|
|
assert.equal(existing.outcome, "existing"); assert.equal(existing.canonicalNodeId, stored.node_id)
|
|
assert.deepEqual(await digestTables(BANDWIDTH_NODE_REGISTRY_TABLES), before)
|
|
cases.push("actual COMMIT succeeds but wrapper drops command and returns rows-only: host refuses the ACK; durable enrollment survives and fresh registration only reads existing receipt with no second node/event")
|
|
}
|
|
for (const bad of ["node", "alias", "event"] as const) {
|
|
const id = await endpoint({ "system-id": "MAC-TAMPER-" + bad }), token = await observation(id), evidence = await reader.inspect(token, scope())
|
|
const claimProof = mac("claim", evidence.claims), nodeId = randomUUID(), incarnation = randomUUID(), eventId = randomUUID(), authority = await authorize("register", id, scope(), evidence)
|
|
const nodeMac = mac("node", { ...root, nodeId, claimProof }), aliasMac = mac("alias", { ...root, serverId: id, incarnation, nodeId, status: "active" })
|
|
const eventMac = mac("event", { ...root, eventId, serverId: id, incarnation, nodeId, kind: "enroll", oldStatus: null, newStatus: "active", authorityProof: authority.authorityProof })
|
|
const owner = await pool.connect()
|
|
try {
|
|
await owner.query("BEGIN")
|
|
await owner.query("INSERT INTO mmapp_control.bandwidth_nodes(node_id,claim_proof,enrollment_mac) VALUES($1,$2,$3)", [nodeId, claimProof, bad === "node" ? "f".repeat(64) : nodeMac])
|
|
await owner.query("INSERT INTO mmapp_control.bandwidth_node_aliases(server_id,incarnation,node_id,status,record_mac) VALUES($1,$2,$3,'active',$4)", [id, incarnation, nodeId, bad === "alias" ? "f".repeat(64) : aliasMac])
|
|
await owner.query("INSERT INTO mmapp_control.bandwidth_node_events(event_id,server_id,incarnation,node_id,kind,old_status,new_status,authority_proof,event_mac) VALUES($1,$2,$3,$4,'enroll',NULL,'active',$5,$6)", [eventId, id, incarnation, nodeId, authority.authorityProof, bad === "event" ? "f".repeat(64) : eventMac])
|
|
await owner.query("COMMIT")
|
|
} finally { owner.release() }
|
|
const before = await digestTables(BANDWIDTH_NODE_REGISTRY_TABLES)
|
|
await assert.rejects(primary.host.resolve(token, scope())); await assert.rejects(primary.host.register(token, scope()))
|
|
assert.deepEqual(await digestTables(BANDWIDTH_NODE_REGISTRY_TABLES), before)
|
|
}
|
|
cases.push("owned structurally valid INSERT fixtures with individually forged prior node/alias/event MACs refuse genuine-observation resolve/register with exact data unchanged; no trigger disabling or immutable UPDATE")
|
|
|
|
{
|
|
const id = await endpoint({ "system-id": "REVOKED-IN-COMMIT-INSPECT" }), token = await observation(id)
|
|
const before = await digestTables(BANDWIDTH_NODE_REGISTRY_TABLES), fixture = makeHost({ revokeBeforeCommit: id })
|
|
try {
|
|
await assert.rejects(fixture.host.register(token, scope()))
|
|
assert.equal(fixture.revokedInsideInspect(), true); assert.equal(fixture.commits(), 0); assert.equal(fixture.queriesAfterRevocation(), 0)
|
|
assert.deepEqual(await digestTables(BANDWIDTH_NODE_REGISTRY_TABLES), before)
|
|
} finally { deniedWrites.delete(id) }
|
|
cases.push("real pre-COMMIT genuine-inspect wrapper revokes original write grant: final authorize runs after inspection, no subsequent physical SQL/COMMIT and no committed node/alias/event")
|
|
}
|
|
|
|
{
|
|
const before = await digestTables(BANDWIDTH_NODE_REGISTRY_TABLES), owner = await pool.connect()
|
|
try {
|
|
for (const sql of ["UPDATE mmapp_control.bandwidth_nodes SET claim_proof='" + "f".repeat(64) + "'", "DELETE FROM mmapp_control.bandwidth_node_aliases", "UPDATE mmapp_control.bandwidth_node_events SET event_mac='" + "f".repeat(64) + "'", "TRUNCATE mmapp_control.bandwidth_nodes,mmapp_control.bandwidth_node_aliases,mmapp_control.bandwidth_node_events"]) {
|
|
await owner.query("BEGIN"); try { await owner.query("SET LOCAL session_replication_role=replica"); await assert.rejects(owner.query(sql)) } finally { await owner.query("ROLLBACK") }
|
|
}
|
|
} finally { owner.release() }
|
|
await assert.rejects(runtime.query("UPDATE mmapp_control.bandwidth_node_aliases SET status='active',record_mac=$2 WHERE server_id=$1", [a, "f".repeat(64)]))
|
|
await assert.rejects(runtime.query("UPDATE mmapp_control.bandwidth_node_aliases SET status='active',record_mac=$2 WHERE server_id=$1", [b, "f".repeat(64)]))
|
|
await assert.rejects(runtime.query("UPDATE mmapp_control.bandwidth_node_aliases SET node_id=$2,record_mac=$3 WHERE server_id=$1", [replacementId, other.canonicalNodeId, "f".repeat(64)]))
|
|
await assert.rejects(runtime.query("UPDATE mmapp_control.bandwidth_node_aliases SET status='tombstoned',record_mac=$2 WHERE server_id=$1", [replacementId, "f".repeat(64)]))
|
|
assert.deepEqual(await digestTables(BANDWIDTH_NODE_REGISTRY_TABLES), before)
|
|
const triggers = (await pool.query("SELECT t.tgenabled::text AS enabled FROM pg_catalog.pg_trigger t JOIN pg_catalog.pg_class c ON c.oid=t.tgrelid JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname='mmapp_control' AND c.relname=ANY($1::text[]) AND NOT t.tgisinternal", [[...BANDWIDTH_NODE_REGISTRY_TABLES]])).rows
|
|
assert.equal(triggers.length, 10); assert(triggers.every(row => row.enabled === "A"))
|
|
cases.push("normal-role terminal reactivation and missing terminal event fail; actual owner replica-mode node/alias/event/TRUNCATE mutations refuse, ten ALWAYS guards and exact data preserved")
|
|
}
|
|
{
|
|
const id = await endpoint({ "system-id": "WRITES-DENIED" }), token = await observation(id), before = await digestTables(BANDWIDTH_NODE_REGISTRY_TABLES)
|
|
deniedWrites.add(id); await assert.rejects(primary.host.register(token, scope())); deniedWrites.delete(id)
|
|
let calls = 0
|
|
authorizeHook = async (_action, serverId) => { if (serverId === id && ++calls === 2) epochs.set(id, 2) }
|
|
await assert.rejects(primary.host.register(token, scope())); authorizeHook = undefined
|
|
sources.get(id)!.endpoint.routingEndpointEpoch = randomUUID()
|
|
await assert.rejects(primary.host.register(token, scope())); assert.deepEqual(await digestTables(BANDWIDTH_NODE_REGISTRY_TABLES), before)
|
|
cases.push("fixed original grant write denial, authority epoch drift between guards and stale genuine source endpoint epoch all refuse without registry mutation")
|
|
}
|
|
{
|
|
const id = await endpoint({ "system-id": "LATE-AUTH" }), token = await observation(id), gate = deferred(), began = deferred(), before = await digestTables(BANDWIDTH_NODE_REGISTRY_TABLES), late = makeHost()
|
|
authorizeHook = async (_action, serverId) => { if (serverId === id) { began.resolve(); await gate.promise } }
|
|
const pending = late.host.register(token, scope(120)); await began.promise; await assert.rejects(pending)
|
|
authorizeHook = undefined; gate.resolve(); await new Promise<void>(resolve => setImmediate(resolve))
|
|
assert.equal(late.checkouts(), 0); assert.deepEqual(await digestTables(BANDWIDTH_NODE_REGISTRY_TABLES), before)
|
|
cases.push("stalled original authorizer is bounded; late success after deadline never checks out PG or commits a registry row")
|
|
}
|
|
{
|
|
const id = await endpoint({ "system-id": "EXPIRED-ORIGINAL" }), token = await observation(id), gate = deferred(), began = deferred(), before = await digestTables(BANDWIDTH_NODE_REGISTRY_TABLES)
|
|
expired.set(id, Date.now() + 150); proofHook = async purpose => { if (purpose === "claim") { began.resolve(); await gate.promise } }
|
|
const pending = makeHost().host.register(token, scope()); await began.promise; await assert.rejects(pending)
|
|
expired.set(id, Date.now() + 30000); proofHook = undefined; gate.resolve(); await new Promise<void>(resolve => setImmediate(resolve))
|
|
assert.deepEqual(await digestTables(BANDWIDTH_NODE_REGISTRY_TABLES), before)
|
|
cases.push("original authority expires during private claim proof; replacing grant expiry and resolving late proof cannot resume old SQL/COMMIT")
|
|
}
|
|
{
|
|
const id = await endpoint({ "system-id": "RELATION-LOCK" }), token = await observation(id), blocker = await pool.connect(), fixture = makeHost()
|
|
const before = await digestTables(BANDWIDTH_NODE_REGISTRY_TABLES)
|
|
try {
|
|
await blocker.query("BEGIN"); await blocker.query("LOCK mmapp_control.bandwidth_nodes IN ACCESS EXCLUSIVE MODE")
|
|
await assert.rejects(fixture.host.register(token, scope(200))); const pid = fixture.pid()
|
|
await blocker.query("ROLLBACK")
|
|
let present = 1; const until = Date.now() + 2000
|
|
while (present && Date.now() < until) { present = Number((await blocker.query("SELECT count(*) AS n FROM pg_catalog.pg_stat_activity WHERE pid=$1", [pid])).rows[0].n); if (present) await new Promise<void>(resolve => setTimeout(resolve, 20)) }
|
|
assert.equal(present, 0); assert.deepEqual(await digestTables(BANDWIDTH_NODE_REGISTRY_TABLES), before)
|
|
} finally { await blocker.query("ROLLBACK").catch(() => {}); blocker.release() }
|
|
cases.push("actual relation-lock/deadline destroys bounded runtime backend; unlock cannot produce late node/alias/event COMMIT")
|
|
}
|
|
{
|
|
const id = await endpoint({ "system-id": "MONOTONIC-ROLLBACK" }), token = await observation(id), began = deferred(), gate = deferred()
|
|
const before = await digestTables(BANDWIDTH_NODE_REGISTRY_TABLES)
|
|
let offset = 0
|
|
const fixture = makeHost({ now: () => Date.now() + offset })
|
|
expired.set(id, Date.now() + 150)
|
|
proofHook = async purpose => { if (purpose === "claim") { began.resolve(); await gate.promise } }
|
|
const pending = fixture.host.register(token, scope(500))
|
|
let safetyTimer: ReturnType<typeof setTimeout> | undefined
|
|
try {
|
|
await began.promise; offset = -60000
|
|
const safety = new Promise<never>((_resolve, reject) => { safetyTimer = setTimeout(() => reject(Error("Monotonic deadline did not stop the original registry operation")), 1500) })
|
|
await assert.rejects(Promise.race([pending, safety]), (error: unknown) => (error as { code?: string }).code === "BANDWIDTH_NODE_REGISTRY_REFUSED")
|
|
const queriesAtReject = fixture.physicalQueries(), pid = fixture.pid(); assert(pid > 0)
|
|
proofHook = undefined; gate.resolve(); await new Promise<void>(resolve => setImmediate(resolve))
|
|
assert.equal(fixture.physicalQueries(), queriesAtReject); assert.equal(fixture.commits(), 0)
|
|
let present = 1; const goneBy = Date.now() + 2000
|
|
while (present && Date.now() < goneBy) { present = Number((await pool.query("SELECT count(*) AS n FROM pg_catalog.pg_stat_activity WHERE pid=$1", [pid])).rows[0].n); if (present) await new Promise<void>(resolve => setTimeout(resolve, 20)) }
|
|
assert.equal(present, 0); assert.deepEqual(await digestTables(BANDWIDTH_NODE_REGISTRY_TABLES), before)
|
|
} finally { if (safetyTimer) clearTimeout(safetyTimer); proofHook = undefined; gate.resolve(); expired.delete(id) }
|
|
cases.push("actual original grant expires while host-only wall clock rewinds 60 seconds during deferred private proof: real monotonic timer rejects, backend disappears, late proof sends no SQL/COMMIT and exact registry data stays unchanged")
|
|
}
|
|
|
|
if (process.env.MMAPP_OWN_BANDWIDTH_RESTORE === "true") {
|
|
const { runPrivateDatabaseDump } = await import("./database-dump-connection.js"), { restorePartitionedDatabase } = await import("./system-database-partition-restore.js")
|
|
const execute = promisify(execFile), file = resolve(process.env.MCP_STATE_DIR!, "node-registry-public.dump"), url = new URL(process.env.DATABASE_URL!)
|
|
const env = { ...process.env, PGHOST: url.hostname, PGPORT: url.port, PGUSER: url.username, PGPASSWORD: decodeURIComponent(url.password) }
|
|
const command = async (program: string, args: string[]): Promise<Buffer> => { try { return (await execute(program, args, { env, encoding: "buffer", timeout: 30000, maxBuffer: 32 * 1048576, windowsHide: true })).stdout } catch { throw Error("Owned registry archive command failed: " + program) } }
|
|
const marker = Number((await pool.query("INSERT INTO public.servers(name,host,enabled) VALUES('registry-before-restore','127.0.0.1',false) RETURNING id")).rows[0].id)
|
|
const before = await digestTables([...coreTables, ...BANDWIDTH_NODE_REGISTRY_TABLES])
|
|
await writeFile(file, await runPrivateDatabaseDump(url.toString(), { authorize: async () => {} }), { flag: "wx", mode: 0o600 })
|
|
assert(!(await command("pg_restore", ["--list", file])).toString("utf8").includes("mmapp_control"))
|
|
await pool.query("UPDATE public.servers SET name='registry-after-restore' WHERE id=$1", [marker])
|
|
await restorePartitionedDatabase(file, url.toString(), { command, prepareSql: path => writeFile(path, "", { flag: "wx", mode: 0o600 }) })
|
|
assert.equal((await pool.query("SELECT name FROM public.servers WHERE id=$1", [marker])).rows[0].name, "registry-before-restore")
|
|
assert.deepEqual(await digestTables([...coreTables, ...BANDWIDTH_NODE_REGISTRY_TABLES]), before)
|
|
assert.equal((await primary.host.resolve(await observation(replacementId), scope())).canonicalNodeId, first.canonicalNodeId)
|
|
cases.push("actual public-only dump/shared transactional restore replaces observable application row while exact seven control tables, canonical aliases and unknown core occupancy survive")
|
|
} else limitations.push("Public-only restore not requested")
|
|
const authorityBefore = await digestTables(BANDWIDTH_NODE_REGISTRY_TABLES)
|
|
await assert.rejects(pool.query("UPDATE mmapp_control.bandwidth_node_authority SET issuer_key_sha256=$1 WHERE id=1", ["f".repeat(64)]))
|
|
assert.deepEqual(await digestTables(BANDWIDTH_NODE_REGISTRY_TABLES), authorityBefore)
|
|
await pool.query("UPDATE mmapp_control.bandwidth_node_authority SET status='quarantined' WHERE id=1")
|
|
await assert.rejects(primary.host.resolve(await observation(replacementId), scope()))
|
|
assert.deepEqual(await digestTables(coreTables), coreBefore)
|
|
limitations.push("Synthetic explicit operator/quiescence authority and localhost license identities only; no genuine production enrollment readiness, physical uniqueness, clone resistance or dispatch wiring")
|
|
limitations.push("No cross-process registry test; concurrency uses two real backend sessions/host instances")
|
|
console.log("Owned canonical bandwidth registry:", JSON.stringify({ cases: cases.length, checks: cases, actualLocalhostLicenseGets: nativeGets, realCommitAckLosses: realCommitLosses, droppedCommitCommands,
|
|
normalMigrationCount: MIGRATION_MANIFEST.length, externalIssuerFixtureOnly: true, restrictedRegistryRole: true, coreUnknownPairPreserved: true, realChrCalls: 0, productionWired: false, limitations }))
|
|
} finally {
|
|
authorizeHook = undefined; proofHook = undefined; reader.close()
|
|
server.closeAllConnections(); await new Promise<void>(resolve => server.close(() => resolve()))
|
|
await runtime?.end()
|
|
if (roleCreated) { await pool.query(`DROP OWNED BY "${role}"`); await pool.query(`DROP ROLE "${role}"`) }
|
|
key.fill(0); await closePool()
|
|
}
|