Files
MikrotikManager/backend/src/services/bandwidth-control-source.sql.test.ts
T

391 lines
34 KiB
TypeScript

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 { execFile } from "node:child_process"
import { createServer, type Socket } from "node:net"
import { open, readFile, stat, unlink, writeFile } from "node:fs/promises"
import { resolve } from "node:path"
import { promisify } from "node:util"
import type { Pool } from "pg"
import type { BandwidthBinding, BandwidthScope } from "./bandwidth-admission.js"
import type { BandwidthControlRecord } from "./bandwidth-control-source.js"
import { assertOwnedBandwidthSql, canonical, completionProof, fixtureBinding, fixtureMac, prepareOwnedBandwidthState, scope } from "./bandwidth-admission-process.sql-helper.js"
assertOwnedBandwidthSql()
await prepareOwnedBandwidthState()
const { Pool: PgPool } = await import("pg")
const { pool: admin, closePool } = await import("../db/index.js")
const { applySqlMigrations } = await import("../db/migrate.js")
const { BANDWIDTH_ADMISSION_PROPOSAL_DDL } = await import("./bandwidth-admission-schema.js")
const { BANDWIDTH_CONTROL_SOURCE_DDL, canonicalBandwidthControlRecord, bandwidthControlEndpointSha256, bandwidthControlSchemaSourceSha256, observeBandwidthControlCatalog, createConfiguredBandwidthControlSource } = await import("./bandwidth-control-source.js")
const { createBandwidthAdmissionSqlJournal } = await import("./bandwidth-admission-storage.js")
const { assertBandwidthControlRuntimeRole } = await import("./bandwidth-control-role.js")
const { sealEmptyBandwidthControlSource } = await import("./bandwidth-control-provision.js")
const cases: string[] = []
const suffix = randomUUID().replaceAll("-", "")
const ownerRole = "bw_owner_" + suffix, runtimeRole = "bw_runtime_" + suffix, restorerRole = "bw_restore_" + suffix
const databaseName = "bw_control_source_" + suffix
assert(/^[a-z_]+[a-f0-9]{32}$/.test(databaseName))
for (const name of [ownerRole, runtimeRole, restorerRole]) assert(/^bw_(?:owner|runtime|restore)_[a-f0-9]{32}$/.test(name))
const quote = (name: string) => { assert(/^[a-z_]+[a-f0-9]{32}$/.test(name)); return '"' + name + '"' }
const passwords = new Map([ownerRole, runtimeRole, restorerRole].map(role => [role, randomBytes(32).toString("hex")]))
const base = new URL(process.env.DATABASE_URL!)
const roleUrl = (role: string): string => {
const value = new URL(base); value.pathname = "/" + databaseName; value.username = role; value.password = passwords.get(role)!
return value.toString()
}
const connections: Pool[] = [], createdRoles: string[] = []
const sourceClosers: Array<() => Promise<void>> = []
let databaseCreated = false
let operatorIssuerAccepted=false
const connectRole = (role: string) => { const value = new PgPool({ connectionString: roleUrl(role), max: 4 }); connections.push(value); return value }
const expected = { databaseName, runtimeRole, ownerRole }
const live = () => { /* Only a fixed synchronous fixture lifetime fence; not a production issuer. */ }
async function metadata(connection: Pool) {
return (await connection.query(`SELECT t.tgname,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 IN ('bandwidth_attempts','bandwidth_node_occupancy','bandwidth_attempt_events','bandwidth_source_identity') AND NOT t.tgisinternal ORDER BY t.tgname`)).rows
}
async function rows(connection: Pool, includeSource = true) {
const result: Record<string, unknown> = {}
for (const name of ["bandwidth_attempts", "bandwidth_node_occupancy", "bandwidth_attempt_events", ...(includeSource ? ["bandwidth_source_identity"] : [])])
result[name] = (await connection.query(`SELECT to_jsonb(t) AS row FROM mmapp_control.${name} t ORDER BY to_jsonb(t)::text`)).rows
return canonical(result)
}
try {
for (const role of [ownerRole, runtimeRole, restorerRole]) {
const password = passwords.get(role)!; assert(/^[a-f0-9]{64}$/.test(password))
await admin.query(`CREATE ROLE ${quote(role)} LOGIN PASSWORD '${password}' NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS NOINHERIT`)
createdRoles.push(role)
}
await admin.query(`CREATE DATABASE ${quote(databaseName)} OWNER ${quote(ownerRole)} TEMPLATE template0`); databaseCreated = true
const app = connectRole(restorerRole), owner = connectRole(ownerRole), runtime = connectRole(runtimeRole)
const adminUrl = new URL(base); adminUrl.pathname = "/" + databaseName
const adminTarget = new PgPool({ connectionString: adminUrl.toString() }); connections.push(adminTarget)
await owner.query(`GRANT USAGE,CREATE ON SCHEMA public TO ${quote(restorerRole)}`)
await adminTarget.query(`ALTER SCHEMA public OWNER TO ${quote(restorerRole)}`)
await applySqlMigrations(app)
assert.equal(Number((await app.query("SELECT count(*) AS n FROM public.schema_migrations")).rows[0].n), MIGRATION_MANIFEST.length)
await owner.query(`CREATE SCHEMA mmapp_control AUTHORIZATION ${quote(ownerRole)}`)
await owner.query(BANDWIDTH_ADMISSION_PROPOSAL_DDL)
await owner.query(BANDWIDTH_CONTROL_SOURCE_DDL)
await owner.query("REVOKE ALL ON SCHEMA mmapp_control FROM PUBLIC")
await owner.query("REVOKE ALL ON ALL TABLES IN SCHEMA mmapp_control FROM PUBLIC")
await owner.query("REVOKE ALL ON ALL FUNCTIONS IN SCHEMA mmapp_control FROM PUBLIC")
await owner.query(`GRANT USAGE ON SCHEMA mmapp_control TO ${quote(runtimeRole)}`)
await owner.query(`GRANT SELECT,INSERT,UPDATE ON mmapp_control.bandwidth_attempts TO ${quote(runtimeRole)}`)
await owner.query(`GRANT SELECT,INSERT,DELETE ON mmapp_control.bandwidth_node_occupancy TO ${quote(runtimeRole)}`)
await owner.query(`GRANT SELECT,INSERT ON mmapp_control.bandwidth_attempt_events TO ${quote(runtimeRole)}`)
await owner.query(`GRANT SELECT ON mmapp_control.bandwidth_source_identity TO ${quote(runtimeRole)}`)
await owner.query(`GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA mmapp_control TO ${quote(runtimeRole)}`)
const roles = (await admin.query(`SELECT rolname,rolsuper,rolcreatedb,rolcreaterole,rolreplication,rolbypassrls,rolinherit FROM pg_catalog.pg_roles WHERE rolname=ANY($1::text[]) ORDER BY rolname`, [[ownerRole, runtimeRole, restorerRole]])).rows
assert.equal(roles.length, 3)
for (const role of roles) for (const field of ["rolsuper", "rolcreatedb", "rolcreaterole", "rolreplication", "rolbypassrls", "rolinherit"]) assert.equal(role[field], false)
assert.equal((await app.query("SELECT pg_catalog.has_database_privilege(current_user,current_database(),'CREATE') AS allowed")).rows[0].allowed, false)
const outsideUrl = new URL(base); outsideUrl.username = restorerRole; outsideUrl.password = passwords.get(restorerRole)!
const outside = new PgPool({ connectionString: outsideUrl.toString() }); connections.push(outside)
await assert.rejects(outside.query(`DROP DATABASE ${quote(databaseName)}`), (error: unknown) => (error as { code?: string }).code === "42501")
cases.push("three actual restricted LOGIN roles; control owner owns target DATABASE and schema, app-restorer receives only public USAGE/CREATE for normal39 objects; restorer lacks database CREATE and actual outside-session DROP DATABASE is denied by permission")
await assertBandwidthControlRuntimeRole(runtime, expected, live)
await assert.rejects(assertBandwidthControlRuntimeRole(owner, expected, live))
await assert.rejects(assertBandwidthControlRuntimeRole(adminTarget, expected, live))
await owner.query(`GRANT CREATE ON SCHEMA mmapp_control TO ${quote(runtimeRole)}`)
await assert.rejects(assertBandwidthControlRuntimeRole(runtime, expected, live))
await owner.query(`REVOKE CREATE ON SCHEMA mmapp_control FROM ${quote(runtimeRole)}`)
await owner.query(`GRANT DELETE ON mmapp_control.bandwidth_attempts TO ${quote(runtimeRole)}`)
await assert.rejects(assertBandwidthControlRuntimeRole(runtime, expected, live))
await owner.query(`REVOKE DELETE ON mmapp_control.bandwidth_attempts FROM ${quote(runtimeRole)}`)
await admin.query(`GRANT ${quote(ownerRole)} TO ${quote(runtimeRole)}`)
await assert.rejects(assertBandwidthControlRuntimeRole(runtime, expected, live))
await admin.query(`REVOKE ${quote(ownerRole)} FROM ${quote(runtimeRole)}`)
await assertBandwidthControlRuntimeRole(runtime, expected, live)
cases.push("actual runtime role verifier accepts precise DML role and refuses owner/admin sessions, extra schema CREATE, extra attempt DELETE and dangerous owner membership; restored least privilege accepted")
const sha = (value: Buffer | string) => createHash("sha256").update(value).digest("hex")
const { privateKey, publicKey } = generateKeyPairSync("ed25519"), eventKey = randomBytes(32)
const publicDer = publicKey.export({ type: "spki", format: "der" }), publicPem = publicKey.export({ type: "spki", format: "pem" })
const installationId = randomUUID()
let controlGeneration:string = randomUUID()
const databaseOid = Number((await runtime.query("SELECT oid::int AS id FROM pg_catalog.pg_database WHERE datname=current_database()")).rows[0].id)
let record:BandwidthControlRecord = { format: "mmapp-bandwidth-control-source-v1" as const, installationId, controlGeneration, databaseName, runtimeRole, ownerRole, databaseOid,
endpointSha256: bandwidthControlEndpointSha256(roleUrl(runtimeRole)), schemaSourceSha256: bandwidthControlSchemaSourceSha256(),
catalogSha256: await observeBandwidthControlCatalog(runtime, live), eventKeySha256: sha(eventKey),
attestationRef: "Owned synthetic provisioner fixture; real Ed25519 signature; not production enrollment" }
const recordBytes = Buffer.from(canonicalBandwidthControlRecord(record), "utf8")
let envelope = { format: "mmapp-bandwidth-control-envelope-v1", payload: recordBytes.toString("base64url"), signature: sign(null, recordBytes, privateKey).toString("base64url") }
const attestationFile = resolve(process.env.MCP_STATE_DIR!, "bandwidth-role-attestation.json")
const trustKeyFile = resolve(process.env.MCP_STATE_DIR!, "bandwidth-role-trust.pem"), eventKeyFile = resolve(process.env.MCP_STATE_DIR!, "bandwidth-role-event.key")
await writeFile(attestationFile, JSON.stringify(envelope), { flag: "wx", mode: 0o600 })
await writeFile(trustKeyFile, publicPem, { flag: "wx", mode: 0o600 }); await writeFile(eventKeyFile, eventKey, { flag: "wx", mode: 0o600 })
// The configured application connection is the restricted app-restorer in
// the original application database, never the disposable admin account or
// the separately owned control database.
const applicationUrl = new URL(base)
applicationUrl.username = restorerRole; applicationUrl.password = passwords.get(restorerRole)!
const config = { databaseUrl: roleUrl(runtimeRole), applicationDatabaseUrl: applicationUrl.toString(), attestationFile, trustKeyFile, trustKeySha256: sha(publicDer), eventKeyFile }
assert.throws(() => createConfiguredBandwidthControlSource({ ...config, applicationDatabaseUrl: roleUrl(restorerRole) }))
for(const parameter of ["user="+ownerRole,"host=other-host","dbname=other-db","options=-crole%3D"+ownerRole]){
assert.throws(()=>createConfiguredBandwidthControlSource({...config,applicationDatabaseUrl:config.applicationDatabaseUrl+"?"+parameter}))
assert.throws(()=>createConfiguredBandwidthControlSource({...config,databaseUrl:config.databaseUrl+"?"+parameter}))
}
const source = createConfiguredBandwidthControlSource(config); sourceClosers.push(async () => { await source.close() })
const unprovisioned = await rows(owner)
await assert.rejects(source.connect(scope()))
assert.deepEqual(await rows(owner), unprovisioned)
assert.equal((await owner.query("SELECT count(*)::int AS n FROM mmapp_control.bandwidth_source_identity")).rows[0].n, 0)
cases.push("configured control cannot reuse application database name; authentic signed files without externally installed source row refuse without automatic identity enrollment or ledger writes")
// Exercise the real explicit operator issuer, rather than inserting its row
// or signing its final record in the fixture. No startup enrollment is used.
await unlink(attestationFile)
const issuerPrivateKeyFile=resolve(process.env.MCP_STATE_DIR!,"bandwidth-role-issuer.pem")
await writeFile(issuerPrivateKeyFile,privateKey.export({type:"pkcs8",format:"pem"}),{flag:"wx",mode:0o600})
const provisionConfig={...config,ownerDatabaseUrl:roleUrl(ownerRole),issuerPrivateKeyFile,
attestationRef:"Explicit owned operator issuer acceptance; empty preinstalled store; not physical node enrollment"}
await assert.rejects(sealEmptyBandwidthControlSource({...provisionConfig,trustKeySha256:"0".repeat(64)}))
assert.deepEqual(await rows(owner),unprovisioned)
let directorySync=false
try{const directory=await open(process.env.MCP_STATE_DIR!,"r");try{await directory.sync();directorySync=true}finally{await directory.close()}}catch{/* Actual filesystem capability, not a simulated durability acknowledgement. */}
if(directorySync){
record={...await sealEmptyBandwidthControlSource(provisionConfig)}
controlGeneration=record.controlGeneration;operatorIssuerAccepted=true
envelope=JSON.parse(await readFile(attestationFile,"utf8"))
assert.equal(await readFile(attestationFile,"utf8"),await readFile(attestationFile+".pending","utf8"))
const sealed=await rows(owner)
await assert.rejects(sealEmptyBandwidthControlSource(provisionConfig))
assert.deepEqual(await rows(owner),sealed)
cases.push("actual durable-filesystem operator issuer seals empty preinstalled store using existing keys, verifies committed runtime identity before no-replace publication, preserves pending evidence and refuses rerun")
}else{
await assert.rejects(sealEmptyBandwidthControlSource(provisionConfig))
assert.deepEqual(await rows(owner),unprovisioned)
for(const path of [attestationFile,attestationFile+".pending"])await assert.rejects(stat(path),(error:unknown)=>(error as NodeJS.ErrnoException).code==="ENOENT")
// This is explicitly the source-reader fixture, not issuer acceptance.
await writeFile(attestationFile,JSON.stringify(envelope),{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(recordBytes),sha(eventKey)])
cases.push("actual filesystem cannot flush directories: explicit issuer refuses before SQL/pending publication with no ledger/file changes; reader tests continue with explicitly synthetic owner-installed identity, not an issuer durability claim")
}
const firstLease = await source.connect(scope())
try { assert.equal((await firstLease.query("SELECT CURRENT_USER AS name")).rows[0].name, runtimeRole) } finally { firstLease.release() }
{
const before=await rows(owner),pin=sha(recordBytes),value={nested:{field:"original"}},snapshot=canonical(value)
const pending=source.admissionProof("bandwidth-request-v1",value,pin,scope())
value.nested.field="mutated-after-call"
const proof=await pending
assert.equal(proof,createHmac("sha256",eventKey).update("mmapp-bandwidth-admission-v1:bandwidth-request-v1:"+snapshot).digest("hex"))
assert.notEqual(proof,await source.admissionProof("bandwidth-command-v1",JSON.parse(snapshot),pin,scope()))
await assert.rejects(source.admissionProof("arbitrary-unapproved-domain",{},pin,scope()))
await assert.rejects(source.admissionProof("bandwidth-request-v1",{},"a".repeat(64),scope()))
const large={raw:"x".repeat(8*1048576)}
assert.equal(await source.admissionProof("bandwidth-terminal-v1",large,pin,scope()),createHmac("sha256",eventKey).update("mmapp-bandwidth-admission-v1:bandwidth-terminal-v1:"+canonical(large)).digest("hex"))
await assert.rejects(source.admissionProof("bandwidth-terminal-v1","x".repeat(9*1048576),pin,scope()))
assert.deepEqual(await rows(owner),before)
cases.push("admission HMAC captures before await, separates fixed purpose domains, pins original signed source, accepts full eight-MiB native payload and refuses oversized/unknown-domain/replaced-source proofs without data changes")
}
{
const before=await rows(owner)
const foreignSource=createConfiguredBandwidthControlSource(config)
sourceClosers.push(async()=>{await foreignSource.close()})
const windows=Array.from({length:4},()=>scope())
const leases=await Promise.all(windows.map(window=>source.connect(window)))
try{
const pids=await Promise.all(leases.map(async lease=>(await lease.query("SELECT pg_backend_pid() AS pid")).rows[0].pid))
assert.equal(new Set(pids).size,4)
const events=leases.map((_lease,index)=>({fixture:"same-lease-event",index,nested:{value:"original"}}))
const snapshots=events.map(event=>canonical(event))
const proofs=leases.map((lease,index)=>source.eventProofOnConnection(events[index],lease,windows[index]))
for(const event of events)event.nested.value="mutated-after-call"
assert.deepEqual(await Promise.all(proofs),snapshots.map(snapshot=>createHmac("sha256",eventKey).update("bandwidth-control-event-v1:"+snapshot).digest("hex")))
assert.deepEqual(await Promise.all(leases.map(async lease=>(await lease.query("SELECT pg_backend_pid() AS pid")).rows[0].pid)),pids)
await assert.rejects(foreignSource.eventProofOnConnection({},leases[0],scope()))
await assert.rejects(source.eventProofOnConnection({},Object.freeze({...leases[0]}),scope()))
await assert.rejects(source.eventProofOnConnection({},firstLease,scope()))
await assert.rejects(source.eventProofOnConnection({payload:"x".repeat(65537)},leases[0],scope()))
const canceled=new AbortController();canceled.abort()
await assert.rejects(source.eventProofOnConnection({},leases[0],{...scope(),signal:canceled.signal}))
await assert.rejects(source.eventProofOnConnection({},leases[0],{deadlineAt:Date.now()-1}))
assert.deepEqual(await rows(owner),before)
}finally{for(const lease of leases)lease.release()}
await assert.rejects(source.eventProofOnConnection({},leases[0],scope()))
let allowed=true,guardCalls=0
const guarded=await source.connect(scope(),async()=>{guardCalls++;assert(allowed)})
allowed=false
try{await assert.rejects(source.eventProofOnConnection({},guarded,scope()));assert(guardCalls>0)}finally{guarded.release(true)}
assert.deepEqual(await rows(owner),before)
cases.push("four actual runtime leases saturate pool and sign captured events on the same four backend PIDs without fifth checkout; foreign/fake/released leases, oversized payload, abort, expiry and revoked original dispatch guard refuse with exact control data unchanged")
}
const makeJournal = (proofGate?:()=>Promise<void>) => {
let activeScope: BandwidthScope | undefined
let activeConnection: Awaited<ReturnType<typeof source.connect>> | undefined
const journal = createBandwidthAdmissionSqlJournal({ now: Date.now, connect: async window => { activeConnection=await source.connect(window); return activeConnection },
authorize: async (binding, window) => { assert.equal(binding.controlGeneration, controlGeneration); assert.equal(binding.authorityProof, fixtureMac("authority")); assert(Date.now() < window.deadlineAt); window.signal?.throwIfAborted() },
verifyEvidence: async (transition, binding, evidence) => {
if (transition === "complete") assert.deepEqual(evidence, { terminalProof: completionProof(binding) })
if (transition === "release-before-dispatch") assert.deepEqual(evidence, {from:"reserved",proof:"private-no-send"})
},
eventProof: async event => { assert(activeScope); assert(activeConnection); if(proofGate)await proofGate(); return source.eventProofOnConnection(event, activeConnection, activeScope) },
})
const run = async <T>(work: (window: BandwidthScope) => Promise<T>): Promise<T> => { activeScope = scope(); try { return await work(activeScope) } finally { activeScope = undefined; activeConnection=undefined } }
return { reserve: (binding: BandwidthBinding) => run(window => journal.reserve(binding, window)), arm: (binding: BandwidthBinding) => run(window => journal.arm(binding, window)), quarantine: (binding: BandwidthBinding) => run(window => journal.quarantine(binding, window)),
complete:(binding:BandwidthBinding)=>run(window=>journal.complete(binding,{terminalProof:completionProof(binding)},window)),
noSend:(binding:BandwidthBinding)=>run(window=>journal.releaseBeforeDispatch(binding,{from:"reserved",proof:"private-no-send"},window)) }
}
const fixture = makeJournal(), b = fixtureBinding("roles:A", "roles:B", { controlGeneration })
await fixture.reserve(b); await fixture.arm(b); await fixture.quarantine(b)
cases.push("genuine owned Ed25519 signed record, pinned SPKI key, private raw event key and immutable source row verified by configured runtime-role source; journal uses that source for every connection and event MAC")
const {acceptBandwidthJournalDurability}=await import("./bandwidth-journal-durability.sql-helper.js")
const journalDurabilityAcceptance=await acceptBandwidthJournalDurability(source,owner,controlGeneration)
cases.push("actual runtime session synchronous_commit=off cannot weaken journal durability: all eight real COMMIT observe on, persisted MACs/terminal occupancy verified and LOCAL setting does not leak")
const {acceptBandwidthNativePermits}=await import("./bandwidth-native-permit.sql-helper.js")
const nativeTransportAcceptance=await acceptBandwidthNativePermits(source,owner,controlGeneration)
cases.push(...nativeTransportAcceptance.checks)
{
let arrived=0,release!:()=>void
const gate=new Promise<void>(resolve=>{release=resolve})
const proofGate=async()=>{if(++arrived===4)release();await gate}
const bindings=Array.from({length:4},(_unused,index)=>fixtureBinding("pool:A:"+index,"pool:B:"+index,{controlGeneration}))
const journals=bindings.map(()=>makeJournal(proofGate))
await Promise.all(journals.map((journal,index)=>journal.reserve(bindings[index])))
assert.equal(arrived,4)
assert.equal(Number((await owner.query("SELECT count(*) AS n FROM mmapp_control.bandwidth_node_occupancy WHERE attempt_id=ANY($1::uuid[])",[bindings.map(binding=>binding.attemptId)])).rows[0].n),8)
await Promise.all(journals.map((journal,index)=>journal.noSend(bindings[index])))
assert.equal(Number((await owner.query("SELECT count(*) AS n FROM mmapp_control.bandwidth_node_occupancy WHERE attempt_id=ANY($1::uuid[])",[bindings.map(binding=>binding.attemptId)])).rows[0].n),0)
cases.push("four real journal transactions reach signing barrier together with all four pool leases held, commit reserves through same-lease MACs and release only proven-no-send occupancy without nested checkout")
}
{
const completed=fixtureBinding("roles:complete:A","roles:complete:B",{controlGeneration}),finished=makeJournal()
await finished.reserve(completed);await finished.arm(completed);await finished.complete(completed)
await assert.rejects(finished.complete(completed))
const notSent=fixtureBinding("roles:no-send:A","roles:no-send:B",{controlGeneration}),cancelled=makeJournal()
await cancelled.reserve(notSent);await cancelled.noSend(notSent)
for(const attempt of [completed,notSent]){
assert.equal((await owner.query("SELECT count(*)::int AS n FROM mmapp_control.bandwidth_node_occupancy WHERE attempt_id=$1",[attempt.attemptId])).rows[0].n,0)
assert.equal((await owner.query("SELECT state FROM mmapp_control.bandwidth_attempts WHERE attempt_id=$1",[attempt.attemptId])).rows[0].state,"released")
}
assert.equal((await owner.query("SELECT count(*)::int AS n FROM mmapp_control.bandwidth_node_occupancy WHERE attempt_id=$1",[b.attemptId])).rows[0].n,2)
cases.push("actual restricted runtime completes strict synthetic terminal attempt and releases reserved synthetic no-send attempt with exact DELETE rights; duplicate completion refused and unrelated quarantined pair stays occupied")
}
const original = await rows(owner), guards = await metadata(owner)
assert.equal(guards.length, 11); assert(guards.every(row => row.enabled === "A"))
cases.push("actual least-privilege runtime commits keyed reserve/arm/quarantine while preserving both unknown node owners")
const denied = [
"SELECT * FROM mmapp_control.bandwidth_attempts",
"SELECT * FROM mmapp_control.bandwidth_source_identity",
"UPDATE mmapp_control.bandwidth_attempts SET state='released'",
"DELETE FROM mmapp_control.bandwidth_node_occupancy",
"DROP TABLE mmapp_control.bandwidth_attempts CASCADE",
"ALTER TABLE mmapp_control.bandwidth_attempts ADD COLUMN hostile integer",
"DROP SCHEMA mmapp_control CASCADE",
]
for (const sql of denied) await assert.rejects(app.query(sql))
await assert.rejects(runtime.query("UPDATE mmapp_control.bandwidth_source_identity SET status='quarantined' WHERE id=1"))
await assert.rejects(runtime.query("DELETE FROM mmapp_control.bandwidth_source_identity"))
await assert.rejects(app.query("SET session_replication_role=replica"))
await assert.rejects(runtime.query("SET session_replication_role=replica"))
for (const role of [ownerRole, runtimeRole, base.username]) await assert.rejects(app.query(`SET ROLE "${role.replaceAll('"', '""')}"`))
await app.query(`CREATE FUNCTION public.bw_owned_crafted(command text) RETURNS text LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog AS $body$
BEGIN EXECUTE command; RETURN 'unexpectedly-allowed'; END $body$`)
for (const sql of denied) await assert.rejects(app.query("SELECT public.bw_owned_crafted($1)", [sql]))
assert.deepEqual(await rows(owner), original); assert.deepEqual(await metadata(owner), guards)
cases.push("actual app-restorer cannot read/write/drop/alter control, SET ROLE owner/runtime/admin, or use its own crafted PUBLIC SECURITY DEFINER function to reach control; rows and ALWAYS guards unchanged")
if (process.env.MMAPP_OWN_BANDWIDTH_RESTORE === "true") {
const { runPrivateDatabaseDump } = await import("./database-dump-connection.js")
const { restorePartitionedDatabase } = await import("./system-database-partition-restore.js")
const execute = promisify(execFile), file = resolve(process.env.MCP_STATE_DIR!, "bandwidth-role-public.dump")
const appUrl = new URL(roleUrl(restorerRole)), env = { ...process.env, PGHOST: appUrl.hostname, PGPORT: appUrl.port, PGUSER: restorerRole, PGPASSWORD: passwords.get(restorerRole)! }
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 restricted-role archive command failed: " + program) }
}
const marker = Number((await app.query("INSERT INTO public.servers(name,host,enabled) VALUES('role-archive-before','127.0.0.1',false) RETURNING id")).rows[0].id)
await writeFile(file, await runPrivateDatabaseDump(appUrl.toString(), { authorize: async () => {} }), { flag: "wx", mode: 0o600 })
const toc = (await command("pg_restore", ["--list", file])).toString("utf8"); assert(!toc.includes("mmapp_control"))
await app.query("UPDATE public.servers SET name='role-archive-after' WHERE id=$1", [marker])
await restorePartitionedDatabase(file, appUrl.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, "role-archive-before")
assert.deepEqual(await rows(owner), original); assert.deepEqual(await metadata(owner), guards)
await assertBandwidthControlRuntimeRole(runtime, expected, live)
const lease = await source.connect(scope()); lease.release()
const next = fixtureBinding("roles:B", "roles:C", { controlGeneration }), restarted = makeJournal()
await assert.rejects(restarted.reserve(next))
assert.deepEqual(await rows(owner), original)
cases.push("actual public-only dump and transactional restore AUTHENTICATED AS non-superuser app-restorer restore public marker, preserve unknown control rows/ALWAYS metadata, and leave overlapping runtime reserve blocked")
}
{
const sockets=new Set<Socket>(),blackhole=createServer(socket=>{sockets.add(socket);socket.on("error",()=>{});socket.on("close",()=>sockets.delete(socket))})
await new Promise<void>((done,reject)=>{blackhole.once("error",reject);blackhole.listen(0,"127.0.0.1",done)})
const address=blackhole.address();assert(address&&typeof address!=="string")
const stalledUrl=new URL(config.databaseUrl);stalledUrl.port=String(address.port)
const signed=Buffer.from(canonicalBandwidthControlRecord({...record,endpointSha256:bandwidthControlEndpointSha256(stalledUrl.toString())}))
const stalledFile=resolve(process.env.MCP_STATE_DIR!,"bandwidth-physical-connect-timeout.json")
await writeFile(stalledFile,JSON.stringify({format:"mmapp-bandwidth-control-envelope-v1",payload:signed.toString("base64url"),signature:sign(null,signed,privateKey).toString("base64url")}),{flag:"wx",mode:0o600})
const stalled=createConfiguredBandwidthControlSource({...config,databaseUrl:stalledUrl.toString(),attestationFile:stalledFile})
const began=Date.now(),before=await rows(owner)
try{
await assert.rejects(stalled.connect({deadlineAt:Date.now()+10000}))
await stalled.close()
assert(Date.now()-began<8000,"actual physical checkout and pool shutdown must finish before TCP/default timeout")
assert.deepEqual(await rows(owner),before)
}finally{
await stalled.close();for(const socket of sockets)socket.destroy()
await new Promise<void>((done,reject)=>blackhole.close(error=>error?reject(error):done()))
}
cases.push("actual loopback TCP peer accepts but never completes PostgreSQL handshake: physical checkout timeout and pool close finish within 8s, no SQL or ledger mutation and no abandoned healthy connection")
}
{
const before = await rows(owner), lease = await source.connect(scope())
try {
await writeFile(attestationFile, JSON.stringify({ ...envelope, payload: Buffer.from(canonicalBandwidthControlRecord({ ...record, controlGeneration: randomUUID() })).toString("base64url") }))
await assert.rejects(lease.query("SELECT 1")); await assert.rejects(source.connect(scope()))
} finally { lease.release(true); await writeFile(attestationFile, JSON.stringify(envelope), { mode: 0o600 }) }
const signingLease=await source.connect(scope())
await writeFile(eventKeyFile, randomBytes(32), { mode: 0o600 })
try {
await assert.rejects(source.eventProof({ fixture: "event-key-drift" }, scope()))
await assert.rejects(source.eventProofOnConnection({fixture:"same-lease-key-drift"},signingLease,scope()))
} finally { signingLease.release(true);await writeFile(eventKeyFile, eventKey, { mode: 0o600 }) }
const healthy = await source.connect(scope()); healthy.release()
assert.deepEqual(await rows(owner), before)
cases.push("live configured lease and new checkout refuse unsigned changed generation; event MAC refuses private key drift; restoring exact trusted files creates no ledger writes")
}
{
const before=await rows(owner)
const altered=[
{...envelope,signature:"A".repeat(86)},
{...envelope,payload:Buffer.from(JSON.stringify(record,null,2)).toString("base64url")},
{...envelope,unknownField:true},
]
for(const value of altered){
await writeFile(attestationFile,JSON.stringify(value))
try{await assert.rejects(source.connect(scope()))}finally{await writeFile(attestationFile,JSON.stringify(envelope))}
}
const wrongIssuer=generateKeyPairSync("ed25519").publicKey.export({type:"spki",format:"pem"})
await writeFile(trustKeyFile,wrongIssuer)
try{await assert.rejects(source.connect(scope()))}finally{await writeFile(trustKeyFile,publicPem)}
const lease=await source.connect(scope())
await owner.query("ALTER TABLE mmapp_control.bandwidth_source_identity DISABLE TRIGGER bandwidth_source_identity_guard")
try{await assert.rejects(lease.query("SELECT 1"));await assert.rejects(source.connect(scope()))}
finally{lease.release(true);await owner.query("ALTER TABLE mmapp_control.bandwidth_source_identity ENABLE ALWAYS TRIGGER bandwidth_source_identity_guard")}
const healthy=await source.connect(scope());healthy.release()
assert.deepEqual(await rows(owner),before)
cases.push("actual malformed signature, noncanonical payload, unknown envelope field, substituted issuer and disabled ALWAYS source guard refuse live/new source leases without changing ledger; restoring exact files/catalog recovers only the same identity")
}
{
const before = await rows(owner, false)
await owner.query("UPDATE mmapp_control.bandwidth_source_identity SET status='quarantined' WHERE id=1")
await assert.rejects(source.connect(scope())); await assert.rejects(source.eventProof({ fixture: "quarantined" }, scope()))
assert.deepEqual(await rows(owner, false), before)
cases.push("actual external owner source quarantine blocks new leases/event signing and never clears existing unknown occupancy")
}
console.log("Owned bandwidth control source/roles:", JSON.stringify({ cases, nativeTransportAcceptance, journalDurabilityAcceptance, normalMigrationCount: MIGRATION_MANIFEST.length, productionReady: false, productionIssuerAccepted: false, operatorIssuerAccepted,
nativeChrCalls: 0, actualRestrictedRoles: 3, sourceGenerationClaimed: false, runtimeDispatchIntegrated: false,
limits: ["Role isolation is proven only for the explicit exercised SQL/function/restore attempts", "Control-provider rollback/clone fencing, physical router identity and mandatory native dispatch integration remain unproven; explicit issuer does not supply native readiness"] }))
} finally {
for (const close of sourceClosers) await close()
for (const connection of connections) await connection.end()
if (databaseCreated) await admin.query(`DROP DATABASE ${quote(databaseName)}`)
for (const role of createdRoles.reverse()) await admin.query(`DROP ROLE ${quote(role)}`)
await closePool()
}