216 lines
17 KiB
TypeScript
216 lines
17 KiB
TypeScript
/** Real AES-GCM/Ed25519/files and genuine PRIVATE branded operator-window
|
|
* guard. Only external Q + physical SQL are a labelled synthetic fixture.
|
|
* No PostgreSQL, RouterOS, daemon or production credentials. */
|
|
import assert from "node:assert/strict"
|
|
import { createCipheriv, createHash, generateKeyPairSync, randomBytes, randomUUID, sign } from "node:crypto"
|
|
import { basename, dirname, join } from "node:path"
|
|
import { tmpdir } from "node:os"
|
|
import { mock, test } from "node:test"
|
|
import { canonicalBandwidthNodeValue as canonical } from "./bandwidth-node-bootstrap.js"
|
|
|
|
const fs=await import("node:fs/promises"),actual=await import("./bandwidth-control-source.js")
|
|
const reads:string[]=[],gates=new Map<string,Promise<void>>(),keyPaths=new Set<string>(),keyBuffers:Buffer[]=[]
|
|
mock.module("./bandwidth-control-source.js",{namedExports:{...actual,async readBandwidthControlFile(path:string,max:number,live:()=>void){
|
|
reads.push(path);const bytes=await actual.readBandwidthControlFile(path,max,live)
|
|
if(keyPaths.has(path))keyBuffers.push(bytes)
|
|
await gates.get(path);return bytes
|
|
}}})
|
|
const {createConfiguredExternalBandwidthPeerSource,BandwidthExternalPeerSourceError}=await import("./bandwidth-external-peer-source.js")
|
|
const {createBandwidthOperatorOriginalAuthorityReader,createBandwidthOperatorExternalFencer,createBandwidthOperatorWriterWindows}=await import("./bandwidth-operator-writer-window.js")
|
|
const {bandwidthOperatorEnrollmentGrantSchema}=await import("./bandwidth-operator-enrollment.js")
|
|
const sha=(value:string|Buffer)=>createHash("sha256").update(value).digest("hex")
|
|
const scope=(ms=5000,signal?:AbortSignal)=>({deadlineAt:Date.now()+ms,signal})
|
|
const turn=()=>new Promise<void>(done=>setImmediate(done))
|
|
const deferred=()=>{let resolve!:()=>void;const promise=new Promise<void>(done=>{resolve=done});return {promise,resolve}}
|
|
const denied=(error:unknown)=>error instanceof BandwidthExternalPeerSourceError
|
|
|
|
async function fixture(options:{badAad?:boolean;badTag?:boolean;noncanonicalPlain?:boolean;profileInstallationId?:string}={}){
|
|
const directory=await fs.mkdtemp(join(await fs.realpath(tmpdir()),"mm-external-peer-")),profileDirectory=join(directory,"profile"),keyDirectory=join(directory,"keys")
|
|
await fs.mkdir(profileDirectory);await fs.mkdir(keyDirectory)
|
|
const key=randomBytes(32),operator=generateKeyPairSync("ed25519"),root={installationId:randomUUID(),issuerKeySha256:"a".repeat(64),quiescenceProof:"b".repeat(64)}
|
|
const config={profileFile:join(profileDirectory,"management.json"),keyFile:join(keyDirectory,"management.key"),installationId:options.profileInstallationId??root.installationId,enrollmentId:randomUUID(),keySha256:sha(key)}
|
|
const endpoint={host:"127.0.0.1",port:80,useSsl:false,verifySsl:true,username:"OWNED_EXTERNAL_USER",password:"OWNED_EXTERNAL_PRIVATE_PASSWORD"}
|
|
const header={format:"mmapp-bandwidth-external-management-v1" as const,installationId:config.installationId,enrollmentId:config.enrollmentId,generation:randomUUID(),enabled:true,routingEndpointEpoch:randomUUID(),keySha256:config.keySha256}
|
|
function encrypt(value=endpoint,aad:unknown=header){
|
|
const iv=randomBytes(12),cipher=createCipheriv("aes-256-gcm",key,iv);cipher.setAAD(Buffer.from(canonical(aad)))
|
|
const bytes=Buffer.concat([cipher.update((options.noncanonicalPlain?" ":"")+canonical(value)),cipher.final()])
|
|
return Buffer.concat([iv,cipher.getAuthTag(),bytes]).toString("base64url")
|
|
}
|
|
let profile={...header,ciphertext:encrypt(endpoint,options.badAad?{...header,generation:randomUUID()}:header)}
|
|
if(options.badTag){const bytes=Buffer.from(profile.ciphertext,"base64url");bytes[12]^=1;profile={...profile,ciphertext:bytes.toString("base64url")}}
|
|
const publish=()=>fs.writeFile(config.profileFile,canonical(profile))
|
|
await publish();await fs.writeFile(config.keyFile,key);keyPaths.add(config.keyFile)
|
|
const trustKeyFile=join(directory,"operator.pem"),grantFile=join(directory,"operator.json")
|
|
await fs.writeFile(trustKeyFile,operator.publicKey.export({type:"spki",format:"pem"}))
|
|
let grant=bandwidthOperatorEnrollmentGrantSchema.parse({format:"mmapp-bandwidth-operator-enrollment-v1",...root,grantId:randomUUID(),operatorId:"SYNTHETIC-EXTERNAL-STORAGE-OPERATOR",executorInventorySha256:"c".repeat(64),executorsStoppedAt:Date.now()-2000,issuedAt:Date.now()-1000,expiresAt:Date.now()+30000,
|
|
peerRef:{kind:"external",enrollmentId:config.enrollmentId},sourceProof:sha(canonical(profile)),authorityGeneration:profile.generation,routingEndpointEpoch:profile.routingEndpointEpoch,claims:[{kind:"system-id",value:"SYNTHETIC-EXTERNAL-IDENTITY"}]})
|
|
async function publishGrant(){const bytes=Buffer.from(canonical(grant));await fs.writeFile(grantFile,JSON.stringify({format:"mmapp-bandwidth-operator-enrollment-envelope-v1",payload:bytes.toString("base64url"),signature:sign(null,bytes,operator.privateKey).toString("base64url")}))}
|
|
await publishGrant()
|
|
const originals=createBandwidthOperatorOriginalAuthorityReader({...root,trustKeyFile,grantFile,trustKeySha256:sha(operator.publicKey.export({type:"spki",format:"der"}))})
|
|
let q=0,sql=0,held=false,destroyed=0,allowed=true
|
|
const controls:{onQ?:()=>Promise<void>}={}
|
|
const external=createBandwidthOperatorExternalFencer({async acquire(){return {async assertCurrent(){q++;await controls.onQ?.();if(!allowed)throw Error("synthetic Q revoked")},close(){}}}})
|
|
const windows=createBandwidthOperatorWriterWindows({originals,external,source:{async open(_scope,guard){await guard();const lifetime=new AbortController();let closed=false;return {
|
|
async binding(){await guard();return root},async keyedProof(){assert.fail("external storage cannot request MACs")},close(){if(closed)return;closed=true;lifetime.abort();destroyed++;held=false},connection:Object.freeze({lifetimeSignal:lifetime.signal,release(){assert.fail("physical release is window owner only")},async query(text:string){sql++;await guard();if(text.includes("pg_try_advisory_lock(")){held=true;return {rows:[{acquired:true}]}}if(text.includes("pg_locks"))return {rows:[{backend_pid:71,held}]};if(text.includes("pg_backend_pid()"))return {rows:[{backend_pid:71}]};throw Error("unexpected synthetic SQL")}}),
|
|
}}},registry:{async register(){assert.fail("no registration in source fixture")}}})
|
|
const lifetime=scope(),original=await originals.acquire(lifetime),window=await windows.open(original,lifetime),guard=windows.createPeerSourceGuard(window,original)
|
|
const before=reads.length,source=createConfiguredExternalBandwidthPeerSource({...config,installationId:root.installationId},guard)
|
|
assert.equal(reads.length,before,"source constructor must be inert")
|
|
return {source,config,endpoint,header,guard,windows,originals,grantFile,profileDirectory,controls,get profile(){return profile},set profile(value){profile=value},get grant(){return grant},set grant(value){grant=value},publish,publishGrant,encrypt,get q(){return q},get sql(){return sql},get destroyed(){return destroyed},revoke(){allowed=false},lose(){held=false},get peer(){return {kind:"external" as const,enrollmentId:config.enrollmentId}},async close(){
|
|
source.close();windows.close();originals.close();gates.delete(config.keyFile);keyPaths.delete(config.keyFile);key.fill(0)
|
|
await turn();await turn()
|
|
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-external-peer-[A-Za-z0-9]+$/)
|
|
await fs.rm(actual,{recursive:true,force:true})
|
|
}}
|
|
}
|
|
|
|
test("real AES-GCM private read under genuine guard; metadata fresh file checks with key missing perform zero Q/SQL/key reads",async()=>{
|
|
const f=await fixture(),firstKey=keyBuffers.length
|
|
try{
|
|
const perCall=new AbortController(),expected=await f.source.read(f.peer,scope(5000,perCall.signal));assert(expected)
|
|
assert.deepEqual(expected.endpoint,{...f.endpoint,routingEndpointEpoch:f.header.routingEndpointEpoch})
|
|
assert.equal(expected.sourceProof,sha(canonical(f.profile)));assert.equal(expected.authorityGeneration,f.profile.generation)
|
|
assert(Object.isFrozen(expected));assert(Object.isFrozen(expected.endpoint));assert.equal(keyBuffers.length-firstKey,1);assert(keyBuffers.at(-1)!.every(byte=>byte===0))
|
|
await fs.rename(f.config.keyFile,f.config.keyFile+".absent")
|
|
perCall.abort() // A reader disposes its temporary IO signal on success.
|
|
const q=f.q,sql=f.sql,keyReads=reads.filter(path=>path===f.config.keyFile).length
|
|
await f.source.assertMetadataCurrent!(structuredClone(expected),scope())
|
|
assert.equal(f.q,q);assert.equal(f.sql,sql);assert.equal(reads.filter(path=>path===f.config.keyFile).length,keyReads)
|
|
assert.equal(f.destroyed,0)
|
|
}finally{await f.close()}
|
|
})
|
|
|
|
test("anonymous/copied/structural guard and proxy/accessor configuration cannot construct a credential source",async()=>{
|
|
const f=await fixture();let called=0;const trap=()=>{called++;throw Error("caller getter")}
|
|
try{
|
|
for(const guard of [{verifyRead:async()=>{},verifyMetadata:async()=>{}},{...f.guard},new Proxy(f.guard,{get:trap}),{}])assert.throws(()=>createConfiguredExternalBandwidthPeerSource(f.config,guard as never),denied)
|
|
for(const config of [Object.defineProperty({...f.config},"profileFile",{get:trap}),new Proxy(f.config,{getPrototypeOf:trap}),{...f.config,toJSON:trap}])assert.throws(()=>createConfiguredExternalBandwidthPeerSource(config,f.guard),denied)
|
|
assert.equal(called,0)
|
|
}finally{await f.close()}
|
|
})
|
|
|
|
test("encrypted profile/config installation cannot cross genuine original guard installation, even with signed exact sourceProof",async()=>{
|
|
const f=await fixture({profileInstallationId:randomUUID()})
|
|
try{
|
|
assert.notEqual(f.config.installationId,f.guard.installationId)
|
|
assert.equal(f.profile.installationId,f.config.installationId)
|
|
assert.equal(f.grant.sourceProof,sha(canonical(f.profile)))
|
|
const before=reads.length,q=f.q,sql=f.sql
|
|
assert.throws(()=>createConfiguredExternalBandwidthPeerSource(f.config,f.guard),denied)
|
|
assert.equal(reads.length,before);assert.equal(f.q,q);assert.equal(f.sql,sql)
|
|
}finally{await f.close()}
|
|
})
|
|
|
|
test("Q/session/original revocation happens BEFORE key read; no failed read publishes a metadata binding",async()=>{
|
|
for(const mode of ["Q","session","grant"]){
|
|
const f=await fixture()
|
|
try{
|
|
const keyReads=reads.filter(path=>path===f.config.keyFile).length
|
|
if(mode==="Q")f.revoke();if(mode==="session")f.lose();if(mode==="grant")await fs.unlink(f.grantFile)
|
|
await assert.rejects(f.source.read(f.peer,scope()),denied)
|
|
assert.equal(reads.filter(path=>path===f.config.keyFile).length,keyReads)
|
|
await assert.rejects(f.source.assertMetadataCurrent!({} as never,scope()),denied)
|
|
assert.equal(f.destroyed,1)
|
|
}finally{await f.close()}
|
|
}
|
|
})
|
|
|
|
test("AAD/auth-tag/noncanonical plaintext and changed key pin reject; no key remains retained after failure",async()=>{
|
|
for(const mode of ["aad","tag","canonical","key"]){
|
|
const f=await fixture({badAad:mode==="aad",badTag:mode==="tag",noncanonicalPlain:mode==="canonical"}),before=keyBuffers.length
|
|
try{
|
|
if(mode==="key")await fs.writeFile(f.config.keyFile,randomBytes(32))
|
|
await assert.rejects(f.source.read(f.peer,scope()),denied)
|
|
for(const key of keyBuffers.slice(before))assert(key.every(byte=>byte===0))
|
|
}finally{await f.close()}
|
|
}
|
|
})
|
|
|
|
test("fresh encrypted profile/gen/ciphertext/enabled changes and same-byte directory clone permanently refuse original metadata",async()=>{
|
|
for(const mode of ["generation","ciphertext","disabled","directory"]){
|
|
const f=await fixture()
|
|
try{
|
|
const expected=await f.source.read(f.peer,scope());assert(expected)
|
|
const q=f.q,sql=f.sql,keys=reads.filter(path=>path===f.config.keyFile).length
|
|
if(mode==="directory"){
|
|
const bytes=await fs.readFile(f.config.profileFile),target=f.profileDirectory+"-old",stat=await fs.lstat(f.profileDirectory)
|
|
assert(stat.isDirectory()&&!stat.isSymbolicLink());assert.equal(await fs.realpath(f.profileDirectory),f.profileDirectory)
|
|
assert.equal(dirname(target),dirname(f.profileDirectory));assert.match(basename(dirname(target)),/^mm-external-peer-[A-Za-z0-9]+$/)
|
|
await fs.rename(f.profileDirectory,target);await fs.mkdir(f.profileDirectory);await fs.writeFile(f.config.profileFile,bytes)
|
|
}else{f.profile={...f.profile,...(mode==="generation"?{generation:randomUUID()}:mode==="disabled"?{enabled:false}:{ciphertext:f.encrypt()})};await f.publish()}
|
|
await assert.rejects(f.source.assertMetadataCurrent!(expected,scope()),denied)
|
|
assert.equal(f.q,q);assert.equal(f.sql,sql);assert.equal(reads.filter(path=>path===f.config.keyFile).length,keys)
|
|
await assert.rejects(f.source.read(f.peer,scope()),denied)
|
|
}finally{await f.close()}
|
|
}
|
|
})
|
|
|
|
test("metadata requires this instance's successful original private binding; mismatched credentials never read key",async()=>{
|
|
const f=await fixture()
|
|
try{
|
|
const noRead=createConfiguredExternalBandwidthPeerSource(f.config,f.guard),before=reads.length
|
|
await assert.rejects(noRead.assertMetadataCurrent!({} as never,scope()),denied);assert.equal(reads.length,before)
|
|
const expected=await f.source.read(f.peer,scope());assert(expected)
|
|
const changed={...expected,endpoint:{...expected.endpoint,password:"wrong"}},keys=reads.filter(path=>path===f.config.keyFile).length
|
|
await assert.rejects(f.source.assertMetadataCurrent!(changed,scope()),denied);assert.equal(reads.filter(path=>path===f.config.keyFile).length,keys)
|
|
}finally{await f.close()}
|
|
})
|
|
|
|
test("abort/close during delayed key result refuses promptly and late key buffer is wiped; lifetime cannot resume",async()=>{
|
|
for(const mode of ["abort","close","deadline"]){
|
|
const f=await fixture(),gate=deferred(),controller=new AbortController(),before=keyBuffers.length
|
|
try{
|
|
gates.set(f.config.keyFile,gate.promise)
|
|
const input=scope(mode==="deadline"?200:5000,controller.signal),pending=f.source.read(f.peer,input);void pending.catch(()=>{})
|
|
const end=Date.now()+2000;while(keyBuffers.length===before&&Date.now()<end)await turn();assert.equal(keyBuffers.length,before+1)
|
|
if(mode==="abort")controller.abort();if(mode==="close")f.source.close();input.deadlineAt=Date.now()+50000
|
|
await assert.rejects(pending,denied);gate.resolve();await turn();await turn();assert(keyBuffers.at(-1)!.every(byte=>byte===0))
|
|
await assert.rejects(f.source.read(f.peer,scope()),denied)
|
|
}finally{gate.resolve();await f.close()}
|
|
}
|
|
})
|
|
|
|
test("missing/malformed/disabled/foreign public profile and missing key refuse without bootstrap or fallback",async()=>{
|
|
for(const mode of ["missing-profile","json","disabled","foreign","missing-key"]){
|
|
const f=await fixture()
|
|
try{
|
|
if(mode==="missing-profile")await fs.unlink(f.config.profileFile)
|
|
if(mode==="json")await fs.writeFile(f.config.profileFile,"{")
|
|
if(mode==="disabled"){f.profile={...f.profile,enabled:false};await f.publish()}
|
|
if(mode==="foreign"){f.profile={...f.profile,installationId:randomUUID()};await f.publish()}
|
|
if(mode==="missing-key")await fs.unlink(f.config.keyFile)
|
|
const before=reads.filter(path=>path===f.config.keyFile).length
|
|
await assert.rejects(f.source.read(f.peer,scope()),denied)
|
|
assert.equal(reads.filter(path=>path===f.config.keyFile).length-before,mode==="missing-key"?1:0)
|
|
await assert.rejects(f.source.read(f.peer,scope()),denied)
|
|
}finally{await f.close()}
|
|
}
|
|
})
|
|
|
|
test("source first wall/monotonic horizon cannot be renewed or rolled back by later metadata scopes",async()=>{
|
|
for(const mode of ["expired","rollback"]){
|
|
const f=await fixture(),now=Date.now
|
|
try{
|
|
const wall=now(),expected=await f.source.read(f.peer,scope());assert(expected)
|
|
const q=f.q,sql=f.sql,keys=reads.filter(path=>path===f.config.keyFile).length
|
|
Date.now=()=>mode==="expired"?wall+6000:wall-1000
|
|
await assert.rejects(f.source.assertMetadataCurrent!(expected,scope()),denied)
|
|
assert.equal(f.q,q);assert.equal(f.sql,sql);assert.equal(reads.filter(path=>path===f.config.keyFile).length,keys)
|
|
}finally{Date.now=now;await f.close()}
|
|
}
|
|
})
|
|
|
|
test("metadata grant withdrawal rejects without Q/SQL/key; copies/getters cannot change private expected snapshot",async()=>{
|
|
const f=await fixture();let called=0
|
|
try{
|
|
const expected=await f.source.read(f.peer,scope());assert(expected)
|
|
const q=f.q,sql=f.sql,keys=reads.filter(path=>path===f.config.keyFile).length
|
|
await fs.unlink(f.grantFile)
|
|
await assert.rejects(f.source.assertMetadataCurrent!(structuredClone(expected),scope()),denied)
|
|
assert.equal(f.q,q);assert.equal(f.sql,sql);assert.equal(reads.filter(path=>path===f.config.keyFile).length,keys)
|
|
const hostile=Object.defineProperty({...expected},"endpoint",{get(){called++;return expected.endpoint}})
|
|
await assert.rejects(f.source.assertMetadataCurrent!(hostile,scope()),denied);assert.equal(called,0)
|
|
}finally{await f.close()}
|
|
})
|