import { MIGRATION_MANIFEST } from "../db/migration-manifest.js" import assert from "node:assert/strict" import { createHash, createHmac, generateKeyPairSync, randomBytes, randomUUID, sign } from "node:crypto" import { createServer } from "node:http" import { once } from "node:events" import { writeFile } from "node:fs/promises" import { execFile } from "node:child_process" import { promisify } from "node:util" import { resolve } from "node:path" import type { BandwidthNodeObservationEvidence, BandwidthNodeSourceSnapshot } from "./bandwidth-node-observation.js" import type { BandwidthNodeRegistryAction } from "./bandwidth-node-registry.js" import type { BandwidthControlDispatchFence } from "./bandwidth-control-source.js" import { assertOwnedBandwidthSql, prepareOwnedBandwidthState, scope } from "./bandwidth-admission-process.sql-helper.js" assertOwnedBandwidthSql(); await prepareOwnedBandwidthState() const { pool: admin, closePool } = await import("../db/index.js"), { Pool, Client } = 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 } = await import("./bandwidth-node-registry-schema.js") const { BANDWIDTH_CONTROL_SOURCE_DDL, canonicalBandwidthControlRecord, bandwidthControlEndpointSha256, bandwidthControlSchemaSourceSha256, observeBandwidthControlCatalog, createConfiguredBandwidthControlSource } = await import("./bandwidth-control-source.js") const { canonicalBandwidthNodeValue, canonicalBandwidthNodeBootstrap, bandwidthNodeRegistrySchemaSourceSha256 } = await import("./bandwidth-node-bootstrap.js") const { observeBandwidthNodeRegistryCatalog } = await import("./bandwidth-node-registry-catalog.js") const { createConfiguredBandwidthNodeSource } = await import("./bandwidth-node-source.js") const { createBandwidthNodeObservationReader } = await import("./bandwidth-node-observation.js") const { createBandwidthNodeRegistry } = await import("./bandwidth-node-registry.js") // Real application startup loads the native client before these short phases. // Do the same in this owned TS fixture; never renew an observed token's TTL. await import("./mikrotik.js") const sha = (value: Buffer | string) => createHash("sha256").update(value).digest("hex") const suffix = randomUUID().replaceAll("-", ""), ownerRole = "bns_owner_" + suffix, runtimeRole = "bns_runtime_" + suffix, appRole = "bns_app_" + suffix, databaseName = "bns_control_" + suffix const ident = (value: string) => { assert(/^[a-z_]+[a-f0-9]{32}$/.test(value)); return '"' + value + '"' } const passwords = new Map([ownerRole, runtimeRole, appRole].map(role => [role, randomBytes(32).toString("hex")])) const base = new URL(process.env.DATABASE_URL!), pools: InstanceType[] = [], roles: string[] = [] const connectionUrl = (role: string, name = databaseName) => { const value = new URL(base); value.pathname = "/" + name; value.username = role; value.password = passwords.get(role)!; return value.toString() } const rolePool = (role: string) => { const pool = new Pool({ connectionString: connectionUrl(role), max: 4 }); pools.push(pool); return pool } const cases: string[] = [], limitations: string[] = [] const allTables = ["bandwidth_attempts", "bandwidth_node_occupancy", "bandwidth_attempt_events", "bandwidth_source_identity", "bandwidth_node_authority", "bandwidth_nodes", "bandwidth_node_aliases", "bandwidth_node_events"] let databaseCreated = false, nativeGets = 0 const endpoints = new Map(), licenses = new Map>() const server = createServer((req, res) => { assert.equal(req.method, "GET"); assert.equal(req.url, "/rest/system/license"); nativeGets++ const credentials = Buffer.from((req.headers.authorization ?? "").slice(6), "base64").toString(), id = Number(/^node-(\d+):/.exec(credentials)?.[1]) res.setHeader("content-type", "application/json"); res.end(JSON.stringify(licenses.get(id) ?? {})) }) server.listen(0, "127.0.0.1"); await once(server, "listening") const address = server.address(); assert(address && typeof address !== "string"); const port = address.port const reader = createBandwidthNodeObservationReader({ async read(id) { return endpoints.get(id) } }) let core: ReturnType | undefined, nodeSource: ReturnType | undefined const extraSources: Array> = [] let routerGuardCompatibilityCleanup: (() => Promise) | undefined const eventKey = randomBytes(32), issuerKey = randomBytes(32), actorKey = randomBytes(32) const originalDriverQuery = Client.prototype.query type Actor = { id: number; action: BandwidthNodeRegistryAction; allowed: boolean; expiresAt: number; approvedClaims: unknown; sourceProof: string } let intercept: { actor: Actor; armed: boolean; fired: boolean; writesAfter: number; commits: number } | undefined let catalogMutation: { fired: boolean; run: () => Promise } | undefined let physicalRuntimeQueries = 0 let closedCoreMainDispatches = 0 // Instrument the real driver only in this disposable test. No response/result // is synthesized and no production source callback is replaced. Client.prototype.query = function (this: InstanceType, ...args: unknown[]) { const text = typeof args[0] === "string" ? args[0] : (args[0] as { text?: string })?.text ?? "" const target = this as unknown as { connectionParameters: { user: string; database: string } } const isRuntime = target.connectionParameters.user === runtimeRole && target.connectionParameters.database === databaseName if (isRuntime) physicalRuntimeQueries++ if (isRuntime && text.includes("CORE-CLOSED-GUARD-NO-DISPATCH")) closedCoreMainDispatches++ const watch = isRuntime ? intercept : undefined, mutation = isRuntime ? catalogMutation : undefined if (watch?.fired && /^(?:DO|INSERT|UPDATE|DELETE|COMMIT)\b/i.test(text.trim())) watch.writesAfter++ if (watch && /^COMMIT\b/i.test(text.trim())) watch.commits++ const result = Reflect.apply(originalDriverQuery, this, args) as unknown if (!result || typeof (result as Promise).then !== "function") return result return (result as Promise).then(async value => { const nodeCatalog = text.includes("'bandwidth_node_authority','bandwidth_nodes','bandwidth_node_aliases','bandwidth_node_events'") && text.includes("p.prosrc AS body") if (watch?.armed && !watch.fired && nodeCatalog) { watch.actor.allowed = false; watch.fired = true } if (mutation && !mutation.fired && nodeCatalog) { mutation.fired = true; await mutation.run() } return value }) } as typeof Client.prototype.query try { for (const role of [ownerRole, runtimeRole, appRole]) { const password = passwords.get(role)!; assert(/^[a-f0-9]{64}$/.test(password)) await admin.query(`CREATE ROLE ${ident(role)} LOGIN PASSWORD '${password}' NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS NOINHERIT`); roles.push(role) } await admin.query(`CREATE DATABASE ${ident(databaseName)} OWNER ${ident(ownerRole)} TEMPLATE template0`); databaseCreated = true const owner = rolePool(ownerRole), runtime = rolePool(runtimeRole), app = rolePool(appRole) const adminUrl = new URL(base); adminUrl.pathname = "/" + databaseName const targetAdmin = new Pool({ connectionString: adminUrl.toString() }); pools.push(targetAdmin) await targetAdmin.query(`ALTER SCHEMA public OWNER TO ${ident(appRole)}`) await applySqlMigrations(app) await owner.query("CREATE SCHEMA mmapp_control"); await owner.query(BANDWIDTH_ADMISSION_PROPOSAL_DDL); await owner.query(BANDWIDTH_CONTROL_SOURCE_DDL); await owner.query(BANDWIDTH_NODE_REGISTRY_DDL) await owner.query("REVOKE ALL ON SCHEMA mmapp_control FROM PUBLIC; REVOKE ALL ON ALL TABLES IN SCHEMA mmapp_control FROM PUBLIC; REVOKE ALL ON ALL FUNCTIONS IN SCHEMA mmapp_control FROM PUBLIC") await owner.query(`GRANT USAGE ON SCHEMA mmapp_control TO ${ident(runtimeRole)}`) await owner.query(`GRANT SELECT,INSERT,UPDATE ON mmapp_control.bandwidth_attempts,mmapp_control.bandwidth_node_aliases TO ${ident(runtimeRole)}`) await owner.query(`GRANT SELECT,INSERT,DELETE ON mmapp_control.bandwidth_node_occupancy TO ${ident(runtimeRole)}`) await owner.query(`GRANT SELECT,INSERT ON mmapp_control.bandwidth_attempt_events,mmapp_control.bandwidth_nodes,mmapp_control.bandwidth_node_events TO ${ident(runtimeRole)}`) await owner.query(`GRANT SELECT ON mmapp_control.bandwidth_source_identity,mmapp_control.bandwidth_node_authority TO ${ident(runtimeRole)}`) await owner.query(`GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA mmapp_control TO ${ident(runtimeRole)}`) const functions = (await owner.query("SELECT count(*)::int AS n FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid=p.pronamespace WHERE n.nspname='mmapp_control'")).rows[0].n assert.equal(functions, 12) assert.equal(Number((await app.query("SELECT count(*) AS n FROM public.schema_migrations")).rows[0].n), MIGRATION_MANIFEST.length) await assert.rejects(app.query("SELECT * FROM mmapp_control.bandwidth_node_authority")) await assert.rejects(runtime.query("UPDATE mmapp_control.bandwidth_node_authority SET status='quarantined'")) cases.push("actual separate owner/combined least-privilege runtime/restricted application roles, explicit external core+registry DDL with 12 functions, normal39 unchanged, no bootstrap rows auto-created") const live = () => {}, { publicKey, privateKey } = generateKeyPairSync("ed25519") const installationId = randomUUID(), controlGeneration = randomUUID(), issuerKeySha256 = sha(issuerKey) const quiescenceProof = sha("SYNTHETIC owned operator/quiescence statement; not legitimate production enrollment") const coreRecord = { format: "mmapp-bandwidth-control-source-v1" as const, installationId, controlGeneration, databaseName, runtimeRole, ownerRole, databaseOid: Number((await runtime.query("SELECT oid::text AS id FROM pg_catalog.pg_database WHERE datname=current_database()")).rows[0].id), endpointSha256: bandwidthControlEndpointSha256(connectionUrl(runtimeRole)), schemaSourceSha256: bandwidthControlSchemaSourceSha256(), catalogSha256: await observeBandwidthControlCatalog(runtime, live), eventKeySha256: sha(eventKey), attestationRef: "Owned synthetic external control record with genuine Ed25519 signature; not native readiness" } const bootstrap = { format: "mmapp-bandwidth-node-bootstrap-v1" as const, installationId, issuerKeySha256, quiescenceProof, registrySchemaSourceSha256: bandwidthNodeRegistrySchemaSourceSha256(), registryCatalogSha256: await observeBandwidthNodeRegistryCatalog(runtime, live), attestationRef: "Owned synthetic operator registry bootstrap with genuine signature; no production enrollment" } const signedCore = (value: unknown) => { const bytes = Buffer.from(canonicalBandwidthControlRecord(value)); return { format: "mmapp-bandwidth-control-envelope-v1", payload: bytes.toString("base64url"), signature: sign(null, bytes, privateKey).toString("base64url") } } const signedBootstrap = (value: unknown) => { const bytes = Buffer.from(canonicalBandwidthNodeBootstrap(value)); return { format: "mmapp-bandwidth-node-bootstrap-envelope-v1", payload: bytes.toString("base64url"), signature: sign(null, bytes, privateKey).toString("base64url") } } const attestationFile = resolve(process.env.MCP_STATE_DIR!, "node-source-core.json"), trustKeyFile = resolve(process.env.MCP_STATE_DIR!, "node-source-trust.pem"), eventKeyFile = resolve(process.env.MCP_STATE_DIR!, "node-source-core.key") const bootstrapFile = resolve(process.env.MCP_STATE_DIR!, "node-source-bootstrap.json"), issuerKeyFile = resolve(process.env.MCP_STATE_DIR!, "node-source-issuer.key") const originalBootstrap = signedBootstrap(bootstrap) for (const [file, bytes] of [[attestationFile, JSON.stringify(signedCore(coreRecord))], [trustKeyFile, publicKey.export({ type: "spki", format: "pem" })], [eventKeyFile, eventKey], [bootstrapFile, JSON.stringify(originalBootstrap)], [issuerKeyFile, issuerKey]] as const) await writeFile(file, bytes, { flag: "wx", mode: 0o600 }) await owner.query("INSERT INTO mmapp_control.bandwidth_source_identity(id,installation_id,control_generation,attestation_sha256,event_key_sha256) VALUES(1,$1,$2,$3,$4)", [installationId, controlGeneration, sha(canonicalBandwidthControlRecord(coreRecord)), sha(eventKey)]) await owner.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]) const config = { databaseUrl: connectionUrl(runtimeRole), applicationDatabaseUrl: connectionUrl(appRole, "postgres"), attestationFile, trustKeyFile, trustKeySha256: sha(publicKey.export({ type: "spki", format: "der" })), eventKeyFile } core = createConfiguredBandwidthControlSource(config) const nodeConfig = { issuerKeyFile, issuerKeySha256, bootstrapFile } nodeSource = createConfiguredBandwidthNodeSource(core, nodeConfig) const source = nodeSource, coreSource = core if (process.env.MMAPP_TEST_ROUTER_GUARD_COMPATIBILITY === "true") { const { acceptOwnedRouterGuardControlCompatibility } = await import("./router-configuration-guard-compatibility.sql-helper.js") const accepted = await acceptOwnedRouterGuardControlCompatibility({ admin: targetAdmin, databaseName, runtimeRole, ownerRole, v2: false, core: coreSource, node: source }) routerGuardCompatibilityCleanup = accepted.cleanup cases.push("router guard same-control compatibility: " + JSON.stringify(accepted.report)) } async function snapshot(tables = allTables) { const result: Record = {} for (const table of tables) { assert(/^bandwidth_[a-z_]+$/.test(table)); result[table] = sha(canonicalBandwidthNodeValue((await owner.query(`SELECT to_jsonb(t) AS row FROM mmapp_control.${table} t ORDER BY to_jsonb(t)::text`)).rows)) } return result } async function endpoint(claims: Record) { const id = Number((await app.query("INSERT INTO public.servers(name,host,enabled) VALUES('node-source-fixture','127.0.0.1',false) RETURNING id")).rows[0].id) endpoints.set(id, { serverId: id, enabled: true, sourceProof: sha("owned-source:" + id), authorityGeneration: "owned-source-v1", endpoint: { host: "127.0.0.1", port, useSsl: false, verifySsl: true, username: "node-" + id, password: "LOCALHOST-NATIVE-PRIVATE", routingEndpointEpoch: randomUUID() } }) licenses.set(id, claims); return id } const actorFor = (id: number, action: BandwidthNodeRegistryAction): Actor => ({ id, action, allowed: true, expiresAt: Date.now() + 120000, approvedClaims: ["system-id", "software-id"].filter(kind => Object.hasOwn(licenses.get(id)!, kind)).map(kind => ({ kind, value: licenses.get(id)![kind] })), sourceProof: endpoints.get(id)!.sourceProof }) const actorGuard = (actor: Actor) => { if (!actor.allowed || Date.now() >= actor.expiresAt) throw Error("Original actor grant revoked/expired") } async function operation(id: number, action: "register" | "resolve", actor = actorFor(id, action), armPhase?: "INSERT" | "COMMIT") { const diagnosticBegan=Date.now() const diagnosticQueries=physicalRuntimeQueries let diagnosticBindings=0,diagnosticProofs=0,diagnosticCommands=0,diagnosticLast="open" const parentScope = scope(10000), token = await reader.observe(id, parentScope), observed = await reader.inspect(token, parentScope) const diagnosticObserved=Date.now() // This fixed composition supplies original native/actor lifetimes. NodeSource // cannot infer authority or observation TTL from an opaque connection scope. const phaseScope = Object.freeze({ deadlineAt: Math.min(parentScope.deadlineAt, observed.expiresAt, actor.expiresAt), signal: parentScope.signal }) const originalIntentGuard = async (evidence?: Readonly) => { // Reader freshness uses the trusted application provider, never this core // lease. Actor revocation is checked LAST after asynchronous observation. const genuine = await reader.inspect(token, phaseScope) assert.equal(genuine.sourceProof, actor.sourceProof); assert.deepEqual(genuine.claims, actor.approvedClaims) if (evidence) { assert.equal(evidence.sourceProof, genuine.sourceProof); assert.deepEqual(evidence.claims, genuine.claims) } actorGuard(actor) } const session = await source.open(phaseScope, () => originalIntentGuard()) const diagnosticOpened=Date.now() try { const host = createBandwidthNodeRegistry({ now: Date.now, connect: async () => ({ release: () => session.close(), async query(text, values, options) { diagnosticCommands++;diagnosticLast=text.startsWith("DO ")?"register-batch":text.startsWith("WITH aliases")?"snapshot":text.startsWith("SELECT installation_id")?"authority":text.startsWith("SELECT pg_catalog.set_config")?"config":text.includes("pg_advisory_xact_lock")?"registry-lock":["BEGIN","COMMIT","ROLLBACK"].includes(text)?text:"other" if (intercept && (armPhase === "INSERT" && (text.startsWith("DO $mmapp_bandwidth_register$") || text.startsWith("INSERT INTO mmapp_control.bandwidth_nodes")) || armPhase === "COMMIT" && text === "COMMIT")) intercept.armed = true return session.connection.query(text, values, options) } }), inspect: (value, current) => reader.inspect(value, current), keyedProof: (purpose, value) => {diagnosticProofs++;return session.keyedProof(purpose, value)}, keyedProofs: inputs => {diagnosticProofs++;return session.keyedProofs(inputs)}, authorize: async (wanted, serverId, _current, evidence) => { assert.equal(wanted, actor.action); assert.equal(serverId, actor.id) const genuine = evidence as Readonly | undefined assert(genuine) diagnosticBindings++;const binding = await session.binding(); await originalIntentGuard(genuine) return { installationId: binding.installationId, issuerKeySha256: binding.issuerKeySha256, quiescenceProof: binding.quiescenceProof, authorityProof: createHmac("sha256", actorKey).update(canonicalBandwidthNodeValue({ wanted, serverId, intent: actor.approvedClaims })).digest("hex"), authorityGeneration: "owned-original-actor-v1", expiresAt: actor.expiresAt } } }) return action === "register" ? await host.register(token, phaseScope) : await host.resolve(token, phaseScope) } catch(error){ console.error("Owned node registry phase timing:",JSON.stringify({action,observeMs:diagnosticObserved-diagnosticBegan,openMs:diagnosticOpened-diagnosticObserved,registryMs:Date.now()-diagnosticOpened,observationRemainingMs:observed.expiresAt-Date.now(),physicalSql:physicalRuntimeQueries-diagnosticQueries,bindings:diagnosticBindings,proofs:diagnosticProofs,commands:diagnosticCommands,last:diagnosticLast})) throw error } finally { session.close() } } const a = await endpoint({ "system-id": "OP-SYS", "software-id": "OP-SOFT" }), b = await endpoint({ "system-id": "OP-SYS", "software-id": "OP-SOFT" }) const first = await operation(a, "register"), second = await operation(b, "register") assert.equal(first.canonicalNodeId, second.canonicalNodeId); assert.notEqual(first.incarnation, second.incarnation) assert.equal((await operation(a, "resolve")).canonicalNodeId, first.canonicalNodeId) cases.push("actual configured core+node source, genuine native reader and registry host compose register/resolve through one session with actor sealed intent; same claims preserve canonical UUID across aliases") const {acceptBandwidthExecutionHost}=await import("./bandwidth-execution-host.sql-helper.js") const executionHostAcceptance=await acceptBandwidthExecutionHost(coreSource,source,owner) cases.push(...executionHostAcceptance.checks) { const tokens=await Promise.all([reader.observe(a,scope()),reader.observe(b,scope())]) const evidences=await Promise.all(tokens.map(token=>reader.inspect(token,scope()))) const window=scope(4500),session=await source.open(window) const binding=await session.binding();session.close() const expected={binding,participants:[{evidence:evidences[0],receipt:first},{evidence:evidences[1],receipt:second}]} const before=await snapshot() const leases=await Promise.all(Array.from({length:4},()=>coreSource.connect(window,async fence=>source.assertResolvedOnFence(fence,expected,window)))) try{ await Promise.all(leases.map(lease=>lease.query("BEGIN"))) const pids=await Promise.all(leases.map(async lease=>(await lease.query("SELECT pg_catalog.pg_backend_pid() AS pid")).rows[0].pid)) assert.equal(new Set(pids).size,4) assert.equal((await owner.query("SELECT pg_catalog.pg_try_advisory_xact_lock(8723116) AS locked")).rows[0].locked,false) await Promise.all(leases.map(lease=>lease.query("COMMIT"))) }finally{leases.forEach(lease=>lease.release(true))} assert.equal((await owner.query("SELECT pg_catalog.pg_try_advisory_xact_lock(8723116) AS locked")).rows[0].locked,true) assert.deepEqual(await snapshot(),before) cases.push("four actual occupied core leases authenticate signed node role/catalog/claim/node/alias/event MACs through the SAME ephemeral fence with no fifth checkout; shared registry writer lock persists through real BEGIN/COMMIT and data remains exact") for(const change of ["claim","incarnation","source-record"] as const){ const freshTokens=await Promise.all([reader.observe(a,scope()),reader.observe(b,scope())]) const freshEvidence=await Promise.all(freshTokens.map(token=>reader.inspect(token,scope()))) const altered={binding:{...binding},participants:[{evidence:freshEvidence[0],receipt:{...first}},{evidence:freshEvidence[1],receipt:{...second}}]} if(change==="claim")altered.participants[0].evidence={...altered.participants[0].evidence,claims:[{kind:"system-id",value:"FORGED-LICENSE"}]} if(change==="incarnation")altered.participants[0].receipt={...altered.participants[0].receipt,incarnation:randomUUID()} if(change==="source-record")altered.binding.sourceRecordSha256="a".repeat(64) const freshWindow=scope(4000),lease=await coreSource.connect(freshWindow,async fence=>source.assertResolvedOnFence(fence,altered,freshWindow)) try{await assert.rejects(lease.query("SELECT 1 AS forbidden_fence_marker"))}finally{lease.release(true)} assert.deepEqual(await snapshot(),before) } cases.push("same-physical node fence refuses forged claims, replaced alias incarnation and original signed source hash without changing any of eight control tables") } { const window = scope(10000), session = await source.open(window) try { const binding = await session.binding(); assert.equal(binding.installationId, installationId); assert.equal(binding.controlGeneration, controlGeneration) assert.equal(Object.hasOwn(binding, "approved"), false); assert.equal(Object.hasOwn(binding, "ready"), false) await assert.rejects(session.keyedProof("unknown", {})); await assert.rejects(session.keyedProof("node", { ...binding, nodeId: randomUUID(), claimProof: "a".repeat(64) })) const value = { installationId, issuerKeySha256, quiescenceProof, nodeId: randomUUID(), claimProof: "a".repeat(64) }, original = canonicalBandwidthNodeValue(value) const pending = session.keyedProof("node", value); value.claimProof = "b".repeat(64) assert.equal(await pending, createHmac("sha256", issuerKey).update("mmapp-bandwidth-node-node-v1:" + original).digest("hex")) await assert.rejects(session.keyedProof("node", { installationId: randomUUID(), issuerKeySha256, quiescenceProof, nodeId: randomUUID(), claimProof: "a".repeat(64) })) } finally { session.close(); session.close() } await assert.rejects(session.binding()) const actor = actorFor(a, "register"); actor.allowed = false const before = await snapshot(); await assert.rejects(operation(a, "register", actor)); assert.deepEqual(await snapshot(), before) cases.push("binding/HMAC never grant actor permission; unknown/malformed/root-mismatched signing inputs refuse, proof input captured before await, closed session unusable and actor denial changes no row") } { const coreLease = await coreSource.connect(scope(10000)), foreign = await coreSource.connect(scope(10000)) const other = createConfiguredBandwidthControlSource(config) try { await assert.rejects(other.verifyNodeBootstrap(originalBootstrap, coreLease, scope())) await assert.rejects(coreSource.verifyNodeBootstrap(originalBootstrap, { query: async () => ({ rows: [] }), release() {} }, scope())) foreign.release(); await assert.rejects(coreSource.verifyNodeBootstrap(originalBootstrap, foreign, scope())) assert.equal((await coreSource.verifyNodeBootstrap(originalBootstrap, coreLease, scope())).bootstrap.installationId, installationId) } finally { coreLease.release(); foreign.release(); await other.close() } cases.push("bootstrap verifier requires its own active genuine core lease: different factory, fake facade and released lease cannot establish provenance") } { // Four sessions deliberately saturate the fixed core pool. Every binding, // HMAC and query must stay on its already-owned connection, not borrow #5. const sessions = await Promise.all(Array.from({ length: 4 }, () => source.open(scope(10000)))) try { const result = await Promise.all(sessions.map(async session => { const firstPid = Number((await session.connection.query("SELECT pg_catalog.pg_backend_pid() AS pid")).rows[0].pid) await session.binding(); await session.keyedProof("claim", [{ kind: "system-id", value: "FOUR-LEASES" }]) const after = Number((await session.connection.query("SELECT pg_catalog.pg_backend_pid() AS pid")).rows[0].pid) assert.equal(firstPid, after); return firstPid })) assert.equal(new Set(result).size, 4) } finally { sessions.forEach(session => session.close()) } cases.push("four concurrent sessions saturate actual core pool: binding/proof/query retain four distinct original backend PIDs with no nested fifth checkout/deadlock") } { const before = await snapshot(), session = await source.open(scope(10000)) try { const changed = signedBootstrap({ ...bootstrap, attestationRef: "A DIFFERENT genuinely signed operator statement must not replace a leased original binding" }) await writeFile(bootstrapFile, JSON.stringify(changed)); await assert.rejects(session.binding()) } finally { session.close(); await writeFile(bootstrapFile, JSON.stringify(originalBootstrap)) } const malformed = [ { ...originalBootstrap, signature: "A".repeat(86) }, signedBootstrap({ ...bootstrap, installationId: randomUUID() }), signedBootstrap({ ...bootstrap, registrySchemaSourceSha256: "f".repeat(64) }), signedBootstrap({ ...bootstrap, issuerKeySha256: sha(eventKey) }), { ...originalBootstrap, unexpected: true }, ] for (const envelope of malformed) { await writeFile(bootstrapFile, JSON.stringify(envelope)); await assert.rejects(source.open(scope(10000))) } await writeFile(bootstrapFile, JSON.stringify(originalBootstrap)) await writeFile(issuerKeyFile, randomBytes(32)); await assert.rejects(source.open(scope(10000))); await writeFile(issuerKeyFile, issuerKey) const wrongPin = createConfiguredBandwidthNodeSource(coreSource, { ...nodeConfig, issuerKeySha256: "f".repeat(64) }); extraSources.push(wrongPin) await assert.rejects(wrongPin.open(scope(10000))) const missing = createConfiguredBandwidthNodeSource(coreSource, { ...nodeConfig, bootstrapFile: resolve(process.env.MCP_STATE_DIR!, "MISSING-OPERATOR-BOOTSTRAP.json") }); extraSources.push(missing) await assert.rejects(missing.open(scope(10000))) assert.deepEqual(await snapshot(), before) cases.push("wrong issuer key/pin, same-key-as-core bootstrap, cross-install/schema/signature/unknown-field records and missing bootstrap refuse; valid different signed bootstrap cannot replace original live session; no auto rows or data mutation") } { const before = await snapshot() await owner.query(`GRANT CREATE ON SCHEMA mmapp_control TO ${ident(runtimeRole)}`) await assert.rejects(source.open(scope(10000))); await owner.query(`REVOKE CREATE ON SCHEMA mmapp_control FROM ${ident(runtimeRole)}`) await owner.query("ALTER TABLE mmapp_control.bandwidth_nodes DISABLE TRIGGER bandwidth_node_immutable_guard") try { await assert.rejects(source.open(scope(10000))) } finally { await owner.query("ALTER TABLE mmapp_control.bandwidth_nodes ENABLE ALWAYS TRIGGER bandwidth_node_immutable_guard") } assert.deepEqual(await snapshot(), before) cases.push("actual excess runtime ACL and disabled registry guard refuse via fixed source/role/catalog verification; guard disabling is metadata-only negative fixture with zero data writes") } for (const phase of ["INSERT", "COMMIT"] as const) { const id = await endpoint({ "system-id": "REVOKED-IN-METADATA-" + phase }), actor = actorFor(id, "register"), before = await snapshot() intercept = { actor, armed: false, fired: false, writesAfter: 0, commits: 0 } try { await assert.rejects(operation(id, "register", actor, phase)) assert.equal(intercept.fired, true); assert.equal(intercept.writesAfter, 0); assert.equal(intercept.commits, 0) assert.deepEqual(await snapshot(), before) } finally { intercept = undefined } cases.push("real original actor revoke DURING global catalog observation before " + phase + ": final core dispatch guard forbids physical write/COMMIT and preserves exact data") } for (const kind of ["issuer-key", "bootstrap"] as const) { const before = await snapshot(), session = await source.open(scope(10000)) const replacement = signedBootstrap({ ...bootstrap, attestationRef: "Different genuinely signed operator bootstrap changed DURING actual PostgreSQL catalog observation" }) catalogMutation = { fired: false, run: () => kind === "issuer-key" ? writeFile(issuerKeyFile, randomBytes(32)) : writeFile(bootstrapFile, JSON.stringify(replacement)) } try { await assert.rejects(session.keyedProof("claim", [{ kind: "system-id", value: "NO-STALE-HMAC" }])) assert.equal(catalogMutation.fired, true) assert.deepEqual(await snapshot(), before) } finally { catalogMutation = undefined; session.close() await writeFile(issuerKeyFile, issuerKey); await writeFile(bootstrapFile, JSON.stringify(originalBootstrap)) } cases.push("actual " + kind + " file changes AFTER PostgreSQL node-catalog result and before HMAC: operation refuses without returning stale proof or changing any control row") } { let stalled = false, entered!: () => void, release!: () => void const started = new Promise(resolve => { entered = resolve }), gate = new Promise(resolve => { release = resolve }) const before = await snapshot(), session = await source.open(scope(10000), async () => { if (stalled) { entered(); await gate } }) stalled = true const pending = session.connection.query("SELECT 'CLOSED-SESSION-MUST-NOT-DISPATCH'::text") const rejected = assert.rejects(pending) let timer: ReturnType | undefined, startTimer: ReturnType | undefined try { await Promise.race([started, new Promise((_resolve, reject) => { startTimer = setTimeout(() => reject(Error("Actual query did not reach original actor guard")), 3000) })]) clearTimeout(startTimer); session.close() await Promise.race([rejected, new Promise((_resolve, reject) => { timer = setTimeout(() => reject(Error("Closed session did not promptly reject stalled actor guard")), 750) })]) const countAfterClose = physicalRuntimeQueries release(); await new Promise(resolve => setTimeout(resolve, 75)) assert.equal(physicalRuntimeQueries, countAfterClose) assert.deepEqual(await snapshot(), before) } finally { clearTimeout(timer); clearTimeout(startTimer); release(); session.close() } cases.push("closing an actual session while original actor guard is stalled rejects before gate/deadline; releasing late guard dispatches no further physical SQL and changes no row") } { let entered!: () => void, release!: () => void const started = new Promise(resolve => { entered = resolve }), gate = new Promise(resolve => { release = resolve }) const before = await snapshot(), lease = await coreSource.connect(scope(10000), async () => { entered(); await gate }) const dispatchesBefore = closedCoreMainDispatches const pending = lease.query("SELECT 'CORE-CLOSED-GUARD-NO-DISPATCH'::text"), rejected = assert.rejects(pending) let timer: ReturnType | undefined, startTimer: ReturnType | undefined try { await Promise.race([started, new Promise((_resolve, reject) => { startTimer = setTimeout(() => reject(Error("Core query did not reach actual guard")), 3000) })]) clearTimeout(startTimer); lease.release(true) await Promise.race([rejected, new Promise((_resolve, reject) => { timer = setTimeout(() => reject(Error("Released core lease did not reject stalled guard")), 750) })]) const queriesAfterRelease = physicalRuntimeQueries release(); await new Promise(resolve => setTimeout(resolve, 75)) assert.equal(physicalRuntimeQueries, queriesAfterRelease); assert.equal(closedCoreMainDispatches, dispatchesBefore) assert.deepEqual(await snapshot(), before) } finally { clearTimeout(timer); clearTimeout(startTimer); release(); lease.release(true) } cases.push("direct actual core lease release rejects query stalled AFTER checkout within750ms while guard gate is closed; late guard continuation sends zero main/late SQL and preserves all eight tables") } { let saved: BandwidthControlDispatchFence | undefined const before = await snapshot(), lease = await coreSource.connect(scope(10000), async fence => { saved = fence }) try { assert.equal((await lease.query("SELECT 1::integer AS marker")).rows[0].marker, 1) assert(saved) const count = physicalRuntimeQueries await assert.rejects(saved.query("SELECT 1")); await assert.rejects(saved.verifyNodeBootstrap(originalBootstrap));await assert.rejects(saved.sourceIdentity()) assert.equal(physicalRuntimeQueries, count); assert.deepEqual(await snapshot(), before) } finally { lease.release(true) } cases.push("captured genuine raw dispatch fence expires when actual query finishes: retained query and valid signed bootstrap verification reject without any new physical driver query") } 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), url = new URL(connectionUrl(appRole)), file = resolve(process.env.MCP_STATE_DIR!, "operational-node-source-public.dump") const env = { ...process.env, PGHOST: url.hostname, PGPORT: url.port, PGUSER: appRole, PGPASSWORD: passwords.get(appRole)! } const command = async (program: string, args: string[]): Promise => { try { return (await execute(program, args, { env, encoding: "buffer", timeout: 30000, maxBuffer: 32 * 1048576, windowsHide: true })).stdout } catch { throw Error("Owned operational source archive command failed: " + program) } } const before = await snapshot(), marker = Number((await app.query("INSERT INTO public.servers(name,host,enabled) VALUES('operational-before','127.0.0.1',false) RETURNING id")).rows[0].id) await writeFile(file, await runPrivateDatabaseDump(url.toString(), { authorize: async () => {} }), { flag: "wx", mode: 0o600 }) await app.query("UPDATE public.servers SET name='operational-after' WHERE id=$1", [marker]) await restorePartitionedDatabase(file, url.toString(), { command, prepareSql: path => writeFile(path, "", { flag: "wx", mode: 0o600 }) }) assert.equal((await app.query("SELECT name FROM public.servers WHERE id=$1", [marker])).rows[0].name, "operational-before") assert.deepEqual(await snapshot(), before); assert.equal((await operation(a, "resolve")).canonicalNodeId, first.canonicalNodeId) cases.push("real restricted-application-role public-only dump/shared restore changes public marker while all eight external control tables and canonical UUID survive; fresh operational resolve succeeds") } else limitations.push("Public-only restore not requested") { const coreLease = await coreSource.connect(scope(10000)), nodeLease = await source.open(scope(10000)) const before = await snapshot(allTables.filter(name => name !== "bandwidth_source_identity")) try { // Explicit external-owner replacement fixture, not a runtime migration or // automatic enrollment. No guard is disabled to alter ledger data. await owner.query("DROP TABLE mmapp_control.bandwidth_source_identity") await owner.query("DROP FUNCTION mmapp_control.bandwidth_source_identity_guard()") await owner.query(BANDWIDTH_CONTROL_SOURCE_DDL) await owner.query(`REVOKE ALL ON mmapp_control.bandwidth_source_identity FROM PUBLIC; GRANT SELECT ON mmapp_control.bandwidth_source_identity TO ${ident(runtimeRole)}; REVOKE ALL ON FUNCTION mmapp_control.bandwidth_source_identity_guard() FROM PUBLIC; GRANT EXECUTE ON FUNCTION mmapp_control.bandwidth_source_identity_guard() TO ${ident(runtimeRole)}`) const renewed = { ...coreRecord, controlGeneration: randomUUID(), catalogSha256: await observeBandwidthControlCatalog(runtime, live), attestationRef: "Owned external valid source renewal fixture; persistent registry bootstrap identity deliberately unchanged" } await owner.query("INSERT INTO mmapp_control.bandwidth_source_identity(id,installation_id,control_generation,attestation_sha256,event_key_sha256) VALUES(1,$1,$2,$3,$4)", [installationId, renewed.controlGeneration, sha(canonicalBandwidthControlRecord(renewed)), sha(eventKey)]) await writeFile(attestationFile, JSON.stringify(signedCore(renewed))) await assert.rejects(coreLease.query("SELECT 1")); await assert.rejects(nodeLease.binding()) assert.equal((await operation(a, "resolve")).canonicalNodeId, first.canonicalNodeId) assert.deepEqual(await snapshot(allTables.filter(name => name !== "bandwidth_source_identity")), before) } finally { coreLease.release(true); nodeLease.close() } cases.push("valid externally signed core-generation renewal rejects original leased core/node sessions; fresh session resolves SAME persistent canonical UUID with unchanged seven non-identity tables and unchanged issuer/bootstrap") } { const before = await snapshot(allTables.filter(name => !["bandwidth_source_identity", "bandwidth_node_authority"].includes(name))) await owner.query("UPDATE mmapp_control.bandwidth_node_authority SET status='quarantined' WHERE id=1") await assert.rejects(source.open(scope(10000))) await owner.query("UPDATE mmapp_control.bandwidth_source_identity SET status='quarantined' WHERE id=1") await assert.rejects(coreSource.connect(scope(10000))); await assert.rejects(source.open(scope(10000))) assert.deepEqual(await snapshot(allTables.filter(name => !["bandwidth_source_identity", "bandwidth_node_authority"].includes(name))), before) cases.push("terminal registry authority and core source quarantine reject new operational sessions while every node/alias/event/core-occupancy row stays unchanged") } limitations.push("Genuine signatures/native localhost observations but synthetic operator/quiescence and actor grants; no production enrollment/physical uniqueness/clone fencing/native dispatch readiness") limitations.push("No automatic schema/bootstrap/key creation, external-provider rollback guarantee or production source catalog promotion is inferred from this fixture") console.log("Owned operational bandwidth node source:", JSON.stringify({ cases: cases.length, checks: cases, executionHostAcceptance, nativeLocalhostGets: nativeGets, realChrCalls: 0, normalMigrationCount: MIGRATION_MANIFEST.length, explicitOwnedExternalInstallation: true, productionReady: false, runtimeDispatchIntegrated: false, limitations })) } finally { intercept = undefined; catalogMutation = undefined; Client.prototype.query = originalDriverQuery extraSources.forEach(source => source.close()); nodeSource?.close(); await core?.close() reader.close(); server.closeAllConnections(); await new Promise(resolve => server.close(() => resolve())) await routerGuardCompatibilityCleanup?.() for (const pool of pools) await pool.end() if (databaseCreated) await admin.query(`DROP DATABASE ${ident(databaseName)}`) for (const role of roles.reverse()) await admin.query(`DROP ROLE ${ident(role)}`) eventKey.fill(0); issuerKey.fill(0); actorKey.fill(0); await closePool() }