185 lines
14 KiB
TypeScript
185 lines
14 KiB
TypeScript
/** Actual bounded files/Ed25519. Only IO scheduling and forbidden secret/PG
|
|
* traps are mocked; no authority, query result or signature is substituted. */
|
|
import assert from "node:assert/strict"
|
|
import { createHash, generateKeyPairSync, randomUUID, sign } from "node:crypto"
|
|
import { basename, dirname, join } from "node:path"
|
|
import { tmpdir } from "node:os"
|
|
import { mock, test } from "node:test"
|
|
import type { BandwidthPublicNodeBootstrapMetadata, BandwidthVerifiedNodeBootstrap } from "./bandwidth-control-source.js"
|
|
|
|
const fs=await import("node:fs/promises"),pg=await import("pg")
|
|
const forbidden=new Set<string>(),gates=new Map<string,Promise<void>>(),reads:string[]=[]
|
|
let secretAttempts=0,poolAttempts=0
|
|
const check=(path:unknown)=>{if(typeof path==="string"&&forbidden.has(path)){secretAttempts++;throw Error("secret IO forbidden")}}
|
|
mock.module("node:fs/promises",{namedExports:{...fs,
|
|
async lstat(...args:Parameters<typeof fs.lstat>){check(args[0]);reads.push(String(args[0]));await gates.get(String(args[0]));return Reflect.apply(fs.lstat,fs,args)},
|
|
async realpath(...args:Parameters<typeof fs.realpath>){check(args[0]);return Reflect.apply(fs.realpath,fs,args)},
|
|
async open(...args:Parameters<typeof fs.open>){check(args[0]);return Reflect.apply(fs.open,fs,args)},
|
|
}})
|
|
const {default:pgDefault,...pgNamed}=pg
|
|
class ForbiddenPool {constructor(){poolAttempts++;throw Error("public metadata attempted PG")}}
|
|
mock.module("pg",{defaultExport:{...pgDefault,Pool:ForbiddenPool},namedExports:{...pgNamed,Pool:ForbiddenPool}})
|
|
const core=await import("./bandwidth-control-source.js")
|
|
const node=await import("./bandwidth-node-bootstrap.js")
|
|
const sha=(value:string|Buffer)=>createHash("sha256").update(value).digest("hex")
|
|
const turn=()=>new Promise<void>(done=>setImmediate(done))
|
|
const scope=(signal?:AbortSignal)=>({deadlineAt:Date.now()+5000,signal})
|
|
|
|
function distinctPublicType(value:BandwidthPublicNodeBootstrapMetadata){
|
|
// @ts-expect-error PUBLIC projection cannot satisfy strong database source.
|
|
const strong:BandwidthVerifiedNodeBootstrap=value
|
|
void strong
|
|
return value
|
|
}
|
|
async function fixture(){
|
|
const directory=await fs.mkdtemp(join(tmpdir(),"mm-control-public-"))
|
|
const keys=generateKeyPairSync("ed25519"),eventKeyFile=join(directory,"event.secret"),trustKeyFile=join(directory,"trust.pem"),attestationFile=join(directory,"attestation.json")
|
|
const config={databaseUrl:"postgresql://control_runtime:[email protected]:1/control",applicationDatabaseUrl:"postgresql://application:[email protected]:1/application",eventKeyFile,trustKeyFile,attestationFile,trustKeySha256:sha(keys.publicKey.export({type:"spki",format:"der"}))}
|
|
let record={format:"mmapp-bandwidth-control-source-v1" as const,installationId:randomUUID(),controlGeneration:randomUUID(),databaseName:"control",databaseOid:123,runtimeRole:"control_runtime",ownerRole:"control_owner",endpointSha256:core.bandwidthControlEndpointSha256(config.databaseUrl),schemaSourceSha256:core.bandwidthControlSchemaSourceSha256(),catalogSha256:"a".repeat(64),eventKeySha256:"e".repeat(64),attestationRef:"explicit public-only control fixture attestation reference"}
|
|
const bootstrap={format:"mmapp-bandwidth-node-bootstrap-v1" as "mmapp-bandwidth-node-bootstrap-v1"|"mmapp-bandwidth-node-bootstrap-v2",installationId:record.installationId,issuerKeySha256:"b".repeat(64),quiescenceProof:"c".repeat(64),registrySchemaSourceSha256:node.bandwidthNodeRegistrySchemaSourceSha256(),registryCatalogSha256:"d".repeat(64),attestationRef:"explicit public-only node fixture attestation reference"}
|
|
const envelope=(text:string,format:string)=>{const payload=Buffer.from(text);return {format,payload:payload.toString("base64url"),signature:sign(null,payload,keys.privateKey).toString("base64url")}}
|
|
const signedNode=(text=node.canonicalBandwidthNodeBootstrap(bootstrap))=>envelope(text,"mmapp-bandwidth-node-bootstrap-envelope-v1")
|
|
const publish=async(text=core.canonicalBandwidthControlRecord(record))=>fs.writeFile(attestationFile,JSON.stringify(envelope(text,"mmapp-bandwidth-control-envelope-v1")))
|
|
await fs.writeFile(trustKeyFile,keys.publicKey.export({type:"spki",format:"pem"}));await publish()
|
|
forbidden.add(eventKeyFile)
|
|
const reader=core.createConfiguredBandwidthControlSource(config)
|
|
return {reader,config,bootstrap,signedNode,publish,get record(){return record},set record(value){record=value},async close(){
|
|
gates.delete(trustKeyFile);gates.delete(attestationFile);await reader.close();await turn();await turn()
|
|
forbidden.delete(eventKeyFile)
|
|
const actual=await fs.realpath(directory),parent=await fs.realpath(tmpdir()),stat=await fs.lstat(directory)
|
|
assert(stat.isDirectory()&&!stat.isSymbolicLink());assert.equal(dirname(actual),parent);assert.match(basename(actual),/^mm-control-public-[A-Za-z0-9]+$/)
|
|
await fs.rm(actual,{recursive:true,force:true})
|
|
assert.equal(secretAttempts,0);assert.equal(poolAttempts,0)
|
|
}}
|
|
}
|
|
|
|
test("inert construction; actual signed public v1/v2 with missing/permission-marked secret, secret read trap and zero PG",async()=>{
|
|
const before=reads.length,f=await fixture()
|
|
try{
|
|
assert.equal(reads.length,before)
|
|
for(const secret of ["missing","permission-denied"]){
|
|
if(secret==="permission-denied"){await fs.writeFile(f.config.eventKeyFile,Buffer.alloc(32));await fs.chmod(f.config.eventKeyFile,0)}
|
|
for(const format of ["mmapp-bandwidth-node-bootstrap-v1","mmapp-bandwidth-node-bootstrap-v2"] as const){
|
|
f.bootstrap.format=format;f.bootstrap.registrySchemaSourceSha256=format.endsWith("v2")?node.bandwidthPeerRegistrySchemaSourceSha256():node.bandwidthNodeRegistrySchemaSourceSha256()
|
|
const value=distinctPublicType(await f.reader.inspectPublicNodeBootstrap(f.signedNode(),scope()))
|
|
assert.equal(value.format,"mmapp-bandwidth-public-node-metadata-v1");assert.deepEqual(value.bootstrap,f.bootstrap)
|
|
assert.equal(value.source.sourceRecordSha256,sha(core.canonicalBandwidthControlRecord(f.record)))
|
|
assert.deepEqual(value.publicDatabase,{databaseName:"control",runtimeRole:"control_runtime",ownerRole:"control_owner",databaseOid:123,catalogSha256:"a".repeat(64)})
|
|
for(const part of [value,value.bootstrap,value.source,value.publicDatabase])assert(Object.isFrozen(part))
|
|
assert.equal("runtimeRole"in value.source,false);assert.equal("keyCurrent"in value,false);assert.equal("credentialsVerified"in value,false)
|
|
}
|
|
}
|
|
}finally{await fs.chmod(f.config.eventKeyFile,0o600).catch(()=>{});await f.close()}
|
|
})
|
|
|
|
test("fresh control generation/hash and pinned public trust; no prior public result grants strong access",async()=>{
|
|
const f=await fixture()
|
|
try{
|
|
const first=await f.reader.inspectPublicNodeBootstrap(f.signedNode(),scope())
|
|
f.record={...f.record,controlGeneration:randomUUID()};await f.publish()
|
|
const current=await f.reader.inspectPublicNodeBootstrap(f.signedNode(),scope());assert.notDeepEqual(current.source,first.source)
|
|
// Public/copied objects never create a genuine configured connection.
|
|
await assert.rejects(f.reader.verifyNodeBootstrap(f.signedNode(),first as never,scope()))
|
|
await assert.rejects(f.reader.verifyNodeBootstrap(f.signedNode(),structuredClone(current) as never,scope()))
|
|
await fs.writeFile(f.config.trustKeyFile,generateKeyPairSync("ed25519").publicKey.export({type:"spki",format:"pem"}))
|
|
await assert.rejects(f.reader.inspectPublicNodeBootstrap(f.signedNode(),scope()))
|
|
}finally{await f.close()}
|
|
})
|
|
|
|
test("genuine configured CORE -> NODE public composition rereads signed files with no issuer/event key or SQL",async()=>{
|
|
const {createConfiguredBandwidthNodeSource}=await import("./bandwidth-node-source.js")
|
|
const f=await fixture(),bootstrapFile=join(dirname(f.config.attestationFile),"node-bootstrap.json"),issuerKeyFile=join(dirname(f.config.attestationFile),"issuer.secret")
|
|
forbidden.add(issuerKeyFile)
|
|
const reader=createConfiguredBandwidthNodeSource(f.reader,{bootstrapFile,issuerKeyFile,issuerKeySha256:f.bootstrap.issuerKeySha256})
|
|
try{
|
|
for(const format of ["mmapp-bandwidth-node-bootstrap-v1","mmapp-bandwidth-node-bootstrap-v2"] as const){
|
|
f.bootstrap.format=format;f.bootstrap.registrySchemaSourceSha256=format.endsWith("v2")?node.bandwidthPeerRegistrySchemaSourceSha256():node.bandwidthNodeRegistrySchemaSourceSha256()
|
|
await fs.writeFile(bootstrapFile,JSON.stringify(f.signedNode()))
|
|
const before=reads.length,first=await reader.inspectPublicBootstrap(scope())
|
|
assert.equal(first.format,"mmapp-bandwidth-public-node-metadata-v1")
|
|
assert.equal(first.bootstrapSha256,sha(node.canonicalBandwidthNodeBootstrap(f.bootstrap)))
|
|
assert.equal(first.source.sourceRecordSha256,sha(core.canonicalBandwidthControlRecord(f.record)))
|
|
assert.equal(first.source.controlGeneration,f.record.controlGeneration)
|
|
assert.equal(first.publicDatabase.databaseOid,123)
|
|
assert.deepEqual(reads.slice(before).sort(),[bootstrapFile,bootstrapFile,f.config.trustKeyFile,f.config.trustKeyFile,f.config.attestationFile,f.config.attestationFile].sort())
|
|
for(const part of [first,first.bootstrap,first.source,first.publicDatabase])assert(Object.isFrozen(part))
|
|
f.record={...f.record,controlGeneration:randomUUID()};await f.publish()
|
|
const current=await reader.inspectPublicBootstrap(scope())
|
|
assert.equal(current.source.controlGeneration,f.record.controlGeneration)
|
|
assert.notDeepEqual(current.source,first.source)
|
|
assert.equal(current.bootstrapSha256,first.bootstrapSha256)
|
|
assert.equal(secretAttempts,0);assert.equal(poolAttempts,0)
|
|
}
|
|
}finally{reader.close();forbidden.delete(issuerKeyFile);await f.close()}
|
|
})
|
|
|
|
test("control signature/canonical/schema/endpoint/database/roles and node signature/install/schema remain mandatory",async()=>{
|
|
const f=await fixture(),original={...f.record},bootstrap={...f.bootstrap}
|
|
try{
|
|
for(const change of [{databaseName:"elsewhere"},{runtimeRole:"other_runtime"},{ownerRole:"control_runtime"},{endpointSha256:"0".repeat(64)},{schemaSourceSha256:"0".repeat(64)}]){
|
|
f.record={...original,...change};await f.publish();await assert.rejects(f.reader.inspectPublicNodeBootstrap(f.signedNode(),scope()))
|
|
}
|
|
f.record=original;await f.publish(" "+core.canonicalBandwidthControlRecord(original));await assert.rejects(f.reader.inspectPublicNodeBootstrap(f.signedNode(),scope()))
|
|
await f.publish();const corrupt=JSON.parse(await fs.readFile(f.config.attestationFile,"utf8"));corrupt.signature="A".repeat(86);await fs.writeFile(f.config.attestationFile,JSON.stringify(corrupt));await assert.rejects(f.reader.inspectPublicNodeBootstrap(f.signedNode(),scope()))
|
|
await f.publish()
|
|
for(const change of [{installationId:randomUUID()},{registrySchemaSourceSha256:"0".repeat(64)},{issuerKeySha256:original.eventKeySha256}]){
|
|
Object.assign(f.bootstrap,bootstrap,change);await assert.rejects(f.reader.inspectPublicNodeBootstrap(f.signedNode(),scope()))
|
|
}
|
|
Object.assign(f.bootstrap,bootstrap)
|
|
await assert.rejects(f.reader.inspectPublicNodeBootstrap({...f.signedNode(),signature:"A".repeat(86)},scope()))
|
|
await assert.rejects(f.reader.inspectPublicNodeBootstrap(f.signedNode(" "+node.canonicalBandwidthNodeBootstrap(bootstrap)),scope()))
|
|
}finally{await f.close()}
|
|
})
|
|
|
|
test("accessors/proxies/toJSON are refused without executing caller code or public IO",async()=>{
|
|
const f=await fixture();let called=0
|
|
const trap=()=>{called++;throw Error("caller code")}
|
|
try{
|
|
const before=reads.length
|
|
for(const envelope of [Object.defineProperty({...f.signedNode()},"payload",{get:trap}),{...f.signedNode(),toJSON:trap},new Proxy(f.signedNode(),{getPrototypeOf:trap})])await assert.rejects(f.reader.inspectPublicNodeBootstrap(envelope,scope()))
|
|
for(const input of [Object.defineProperty(scope(),"deadlineAt",{get:trap}),{...scope(),toJSON:trap},new Proxy(scope(),{ownKeys:trap})])await assert.rejects(f.reader.inspectPublicNodeBootstrap(f.signedNode(),input))
|
|
const aborted=new AbortController();aborted.abort()
|
|
for(const input of [{deadlineAt:Date.now()-1},scope(aborted.signal),{deadlineAt:NaN}])await assert.rejects(f.reader.inspectPublicNodeBootstrap(f.signedNode(),input))
|
|
assert.equal(called,0);assert.equal(reads.length,before)
|
|
const hostileSignal=new AbortController().signal
|
|
for(const property of ["aborted","addEventListener","removeEventListener"])Object.defineProperty(hostileSignal,property,{get:trap})
|
|
assert.deepEqual((await f.reader.inspectPublicNodeBootstrap(f.signedNode(),scope(hostileSignal))).bootstrap,f.bootstrap)
|
|
assert.equal(called,0)
|
|
}finally{await f.close()}
|
|
})
|
|
|
|
test("envelope and original scope captured before blocked IO; caller mutation cannot switch verified input",async()=>{
|
|
const f=await fixture();let release!:()=>void
|
|
try{
|
|
gates.set(f.config.trustKeyFile,new Promise<void>(done=>{release=done}))
|
|
const signed=f.signedNode(),input=scope(),pending=f.reader.inspectPublicNodeBootstrap(signed,input)
|
|
await turn();signed.signature="A".repeat(86);input.deadlineAt=0;release()
|
|
assert.deepEqual((await pending).bootstrap,f.bootstrap)
|
|
}finally{release?.();await f.close()}
|
|
})
|
|
|
|
test("abort/deadline/close reject blocked reads before release and late IO cannot publish evidence",async()=>{
|
|
for(const mode of ["abort","deadline","close"]){
|
|
const f=await fixture();let release!:()=>void
|
|
try{
|
|
gates.set(f.config.trustKeyFile,new Promise<void>(done=>{release=done}))
|
|
const controller=new AbortController(),input=scope(controller.signal)
|
|
if(mode==="deadline")input.deadlineAt=Date.now()+30
|
|
const pending=f.reader.inspectPublicNodeBootstrap(f.signedNode(),input);void pending.catch(()=>{})
|
|
await turn();if(mode==="abort")controller.abort();if(mode==="close")await f.reader.close()
|
|
await assert.rejects(pending,{code:"BANDWIDTH_CONTROL_SOURCE_UNAVAILABLE"})
|
|
release();await turn();await turn()
|
|
if(mode==="close")await assert.rejects(f.reader.inspectPublicNodeBootstrap(f.signedNode(),scope()))
|
|
}finally{release?.();await f.close()}
|
|
}
|
|
})
|
|
|
|
test("wall rollback is refused after awaited IO, without renewing the original monotonic horizon",async()=>{
|
|
const f=await fixture(),now=Date.now;let release!:()=>void
|
|
try{
|
|
const initial=now();gates.set(f.config.trustKeyFile,new Promise<void>(done=>{release=done}))
|
|
const pending=f.reader.inspectPublicNodeBootstrap(f.signedNode(),scope());void pending.catch(()=>{})
|
|
await turn();Date.now=()=>initial-1000;release();await assert.rejects(pending)
|
|
}finally{Date.now=now;release?.();await f.close()}
|
|
})
|