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

86 lines
8.7 KiB
TypeScript

import assert from "node:assert/strict"
import { test } from "node:test"
import { createHash, generateKeyPairSync, randomBytes, randomUUID, sign } from "node:crypto"
import { mkdtemp, mkdir, writeFile, rm, realpath } from "node:fs/promises"
import { resolve, join, dirname, basename } from "node:path"
import { tmpdir } from "node:os"
import { Pool } from "pg"
import { createConfiguredBandwidthControlSource, canonicalBandwidthControlRecord, bandwidthControlEndpointSha256, bandwidthControlSchemaSourceSha256, BandwidthControlSourceError, type BandwidthControlRegistryDispatchFence } from "./bandwidth-control-source.js"
import { canonicalBandwidthNodeBootstrap, bandwidthNodeRegistrySchemaSourceSha256, bandwidthPeerRegistrySchemaSourceSha256 } from "./bandwidth-node-bootstrap.js"
import { expected as coreExpected, rows as coreRows } from "../test/fixtures/bandwidth-control-identity.js"
import { fixture as v1Fixture } from "../test/fixtures/bandwidth-node-identity.js"
import { fixture as v2Fixture } from "../test/fixtures/bandwidth-peer-identity.js"
const sha=(value:Buffer|string)=>createHash("sha256").update(value).digest("hex")
test("configured core registry frames authenticate fresh files and complete metadata before/after driver SQL (fake PostgreSQL only)",async t=>{
const temporaryParent=await realpath(tmpdir()),ownedRoot=await mkdtemp(join(temporaryParent,"mm-bandwidth-registry-frame-"))
t.after(async()=>{assert.equal(dirname(ownedRoot),temporaryParent);assert(basename(ownedRoot).startsWith("mm-bandwidth-registry-frame-"));await rm(ownedRoot,{recursive:true,force:true})})
const oldConnect=Pool.prototype.connect
try{
for(const version of[1,2])for(const scenario of["positive","empty","foreign","cross-frame","skip-after","key-rotation","bootstrap-rotation","revoked-core","revoked-registry","actor-revoked","abort","overlap","malformed","source-pin-rotation","sql-after-files"]){
const directory=resolve(ownedRoot,randomUUID());await mkdir(directory,{recursive:true})
const {publicKey,privateKey}=generateKeyPairSync("ed25519"),eventKey=randomBytes(32),registry=version===1?v1Fixture():v2Fixture()
const databaseUrl="postgresql://bandwidth_runtime:[email protected]:65432/owned_database",applicationDatabaseUrl="postgresql://restricted_application:[email protected]:65432/application_database"
const record={format:"mmapp-bandwidth-control-source-v1" as const,installationId:registry.expected.installationId,controlGeneration:randomUUID(),databaseName:"owned_database",databaseOid:123,runtimeRole:"bandwidth_runtime",ownerRole:"fixed_owner",endpointSha256:bandwidthControlEndpointSha256(databaseUrl),schemaSourceSha256:bandwidthControlSchemaSourceSha256(),catalogSha256:coreExpected.catalogSha256,eventKeySha256:sha(eventKey),attestationRef:"Synthetic inert candidate control source only, not production authority"}
const bootstrap={format:version===1?"mmapp-bandwidth-node-bootstrap-v1" as const:"mmapp-bandwidth-node-bootstrap-v2" as const,installationId:registry.expected.installationId,issuerKeySha256:registry.expected.issuerKeySha256,quiescenceProof:registry.expected.quiescenceProof,registrySchemaSourceSha256:version===1?bandwidthNodeRegistrySchemaSourceSha256():bandwidthPeerRegistrySchemaSourceSha256(),registryCatalogSha256:registry.expected.registryCatalogSha256,attestationRef:"Synthetic inert candidate registry statement only, not production enrollment"}
const signed=(format:string,text:string)=>{const data=Buffer.from(text);return{format,payload:data.toString("base64url"),signature:sign(null,data,privateKey).toString("base64url")}}
const signedBootstrap=(value=bootstrap)=>signed("mmapp-bandwidth-node-bootstrap-envelope-v1",canonicalBandwidthNodeBootstrap(value))
const trustKeyFile=resolve(directory,"trust.pem"),eventKeyFile=resolve(directory,"event.key"),attestationFile=resolve(directory,"source.json")
await Promise.all([writeFile(trustKeyFile,publicKey.export({type:"spki",format:"pem"})),writeFile(eventKeyFile,eventKey),writeFile(attestationFile,JSON.stringify(signed("mmapp-bandwidth-control-envelope-v1",canonicalBandwidthControlRecord(record))))])
Object.assign(coreExpected,{installationId:record.installationId,controlGeneration:record.controlGeneration,sourceRecordSha256:sha(canonicalBandwidthControlRecord(record)),eventKeySha256:record.eventKeySha256})
let destroyed=0,checkouts=0,jointCalls=0,targetCalls=0,phases=0,latestEnvelope=signedBootstrap(),previousVerified:unknown
const order:string[]=[],controller=new AbortController(),window={deadlineAt:Date.now()+10000,signal:controller.signal}
Pool.prototype.connect=(async()=>{
checkouts++
return {async query(config:{text:string;values?:unknown[]}){
const text=config.text
if(text.startsWith("/* bandwidth-control:registry-identity */")){
jointCalls++;order.push("joint")
assert.deepEqual(config.values,[record.databaseName,record.runtimeRole,record.ownerRole,"restricted_application"])
assert(text.includes("core_identity AS MATERIALIZED"));assert(text.includes("registry_identity AS MATERIALIZED"))
const both=[...coreRows().map(row=>({family:"core",...row})),...registry.rows.map(row=>({family:"registry",...row}))]
if(scenario==="malformed")both[0]={...both[0],extra:"untrusted"} as never
if(scenario==="revoked-core"){const row=both.find(row=>row.family==="core"&&row.kind==="source")!;row.raw_json=JSON.stringify({...JSON.parse(row.raw_json!),status:"quarantined"})}
if(scenario==="revoked-registry"){const row=both.find(row=>row.family==="registry"&&row.kind==="authority")!;row.raw_json=JSON.stringify({...JSON.parse(row.raw_json!),status:"quarantined"})}
if(scenario==="abort")controller.abort()
return{rows:both,command:"SELECT"}
}
if(text.startsWith("/* bandwidth-control:identity */")){order.push("initial-core");return{rows:coreRows(),command:"SELECT"}}
if(text==="SELECT ownership_check"){order.push("ownership");return{rows:[],command:"SELECT"}}
assert.equal(text,"SELECT candidate_target");targetCalls++;order.push("target");return{rows:[{value:"original"}],command:"SELECT"}
},release(unsafe:boolean){assert.equal(unsafe,true);destroyed++}}
}) as never
const source=createConfiguredBandwidthControlSource({databaseUrl,applicationDatabaseUrl,trustKeyFile,eventKeyFile,attestationFile,trustKeySha256:sha(publicKey.export({type:"spki",format:"der"}))})
let lease:Awaited<ReturnType<typeof source.connectRegistry>>|undefined
const guard=async(fence:BandwidthControlRegistryDispatchFence)=>{
phases++;order.push("files-before")
if(scenario==="empty")return
const verified=await fence.verifyNodeBootstrap(latestEnvelope)
if(scenario==="foreign"){await fence.assertRegistryIdentity(structuredClone(verified));return}
if(scenario==="cross-frame"&&phases===2){await fence.assertRegistryIdentity(previousVerified as never);return}
previousVerified=verified
if(scenario==="overlap"){const first=fence.assertRegistryIdentity(verified);await Promise.all([first,fence.assertRegistryIdentity(verified)]);return}
await fence.assertRegistryIdentity(verified)
if(scenario==="skip-after")return
await fence.query("SELECT ownership_check")
if(scenario==="key-rotation")await writeFile(eventKeyFile,randomBytes(32))
if(scenario==="bootstrap-rotation")latestEnvelope=signedBootstrap({...bootstrap,quiescenceProof:"f".repeat(64)})
if(scenario==="source-pin-rotation")await writeFile(attestationFile,JSON.stringify(signed("mmapp-bandwidth-control-envelope-v1",canonicalBandwidthControlRecord({...record,controlGeneration:randomUUID()}))))
await fence.verifyNodeBootstrap(latestEnvelope);order.push("files-after")
if(scenario==="sql-after-files")await fence.query("SELECT ownership_check")
if(scenario==="actor-revoked")throw Error("Original actor revoked")
order.push("actor-last")
}
try{
lease=await source.connectRegistry(window,guard)
const work=lease.query("SELECT candidate_target")
if(scenario==="positive"){
assert.deepEqual((await work).rows,[{value:"original"}]);assert.equal(checkouts,1);assert.equal(jointCalls,2);assert.equal(targetCalls,1)
assert.deepEqual(order,["initial-core","files-before","joint","ownership","files-after","actor-last","target","files-before","joint","ownership","files-after","actor-last"])
}else await assert.rejects(work,(error:unknown)=>error instanceof BandwidthControlSourceError,`${version}:${scenario}`)
if(scenario!=="positive"&&scenario!=="cross-frame")assert.equal(targetCalls,0,`${version}:${scenario}`)
}finally{lease?.release(true);await source.close();assert.equal(destroyed,1);assert.equal(dirname(directory),ownedRoot);await rm(directory,{recursive:true,force:true})}
}
}finally{Pool.prototype.connect=oldConnect}
})