Files
MikrotikManager/backend/src/services/bandwidth-node-identity.test.ts
T

117 lines
16 KiB
TypeScript

import assert from "node:assert/strict"
import { test } from "node:test"
import { BANDWIDTH_ADMISSION_PROPOSAL_DDL } from "./bandwidth-admission-schema.js"
import { BANDWIDTH_NODE_REGISTRY_DDL } from "./bandwidth-node-registry-schema.js"
import { validateBandwidthNodeRegistryCatalogRows } from "./bandwidth-node-registry-catalog.js"
import { assertBandwidthNodeIdentity, validateBandwidthNodeIdentityRows, BANDWIDTH_NODE_IDENTITY_SQL, BandwidthNodeIdentityRefused, type BandwidthNodeIdentityExpected } from "./bandwidth-node-identity.js"
type Row=Record<string,unknown>
type Item={section:string;raw_json:string|null}
type Batch={kind:string;row_order:string;raw_json:string|null}
function catalogFixture():Item[]{
const found:Record<string,Row[]>={namespace:[{name:"mmapp_control",owner:"fixed_owner"}],tables:[],columns:[],functions:[],triggers:[],constraints:[],indexes:[],rules:[],policies:[]}
const tableBodies=new Map<string,string>()
const tables=["bandwidth_node_authority","bandwidth_nodes","bandwidth_node_aliases","bandwidth_node_events"]
const functions=["bandwidth_node_authority_guard","bandwidth_node_immutable_guard","bandwidth_node_alias_guard","bandwidth_node_event_guard","bandwidth_node_alias_consistency_guard","bandwidth_admission_reject_truncate"]
for(const ddl of [BANDWIDTH_ADMISSION_PROPOSAL_DDL,BANDWIDTH_NODE_REGISTRY_DDL]){
for(const match of ddl.matchAll(/CREATE TABLE mmapp_control\.([a-z_]+) \(([\s\S]*?)\n\);/g)){
const table=match[1];if(!tables.includes(table))continue;tableBodies.set(table,match[2])
found.tables.push({name:table,owner:"fixed_owner",kind:"r",persistence:"p",row_security:false,force_row_security:false,is_partition:false,replica_identity:"d",options:null,has_parent:false,has_children:false,typed_table:false,access_method:"heap"})
let position=0
for(const column of match[2].matchAll(/^\s+([a-z_][a-z_0-9]*) (uuid|text|integer|bigint|jsonb|timestamptz)\b([^\n]*)/gm)){
const type=column[2]==="integer"?"int4":column[2]==="bigint"?"int8":column[2],isText=type==="text"
found.columns.push({table_name:table,position:++position,name:column[1],type_namespace:"pg_catalog",type_name:type,not_null:/NOT NULL|PRIMARY KEY/.test(column[3]),identity:"",generated:"",collation_namespace:isText?"pg_catalog":null,collation_name:isText?(/COLLATE "C"/.test(column[3])?"C":"default"):null,default_expr:/DEFAULT clock_timestamp\(\)/.test(column[3])?"clock_timestamp()":/DEFAULT 'active'/.test(column[3])?"'active'::text":null})
}
}
for(const match of ddl.matchAll(/CREATE FUNCTION mmapp_control\.([a-z_]+)\([\s\S]*?\)\s+RETURNS\s+(?:boolean|trigger)[\s\S]*?\bAS\s+\$body\$([\s\S]*?)\$body\$;/g)){
if(!functions.includes(match[1]))continue
const validator=match[1]==="bandwidth_admission_binding_valid",args=validator?["jsonb","uuid","text","text","text","text","text","text"]:[]
found.functions.push({name:match[1],owner:"fixed_owner",language:"plpgsql",body:match[2],security_definer:false,strict:validator,volatility:validator?"i":"v",leakproof:false,kind:"f",parallel:"u",argument_defaults:0,variadic:false,returns_set:false,has_support:false,input_only:true,argument_names:validator?["b","attempt","caller","operation","source","destination","proof","generation"]:null,config:["search_path=pg_catalog, mmapp_control"],return_type:validator?"bool":"trigger",return_namespace:"pg_catalog",argument_types:args,argument_namespaces:args.map(()=>"pg_catalog")})
}
for(const match of ddl.matchAll(/CREATE (CONSTRAINT )?TRIGGER ([a-z_]+) (BEFORE|AFTER) ([\s\S]*?) ON mmapp_control\.([a-z_]+) ([\s\S]*?)EXECUTE FUNCTION mmapp_control\.([a-z_]+)\(\);/g)){
if(!tables.includes(match[5]))continue
const deferred=!!match[1],events=match[4],row=match[6].includes("FOR EACH ROW"),type=(row?1:0)+(match[3]==="BEFORE"?2:0)+(events.includes("INSERT")?4:0)+(events.includes("DELETE")?8:0)+(events.includes("UPDATE")?16:0)+(events.includes("TRUNCATE")?32:0)
found.triggers.push({table_name:match[5],name:match[2],internal:false,type,enabled:"A",deferrable:deferred,initially_deferred:deferred,is_constraint:deferred,constraint_name:deferred?match[2]:null,function_namespace:"mmapp_control",function_name:match[7],argument_count:0,arguments:"",columns:"",condition:null,old_table:null,new_table:null})
}
}
const addConstraint=(table:string,type:string,keys:string[],name:string,extra:Row={})=>found.constraints.push({table_name:table,name,type,validated:true,deferrable:type==="t",initially_deferred:type==="t",keys,foreign_namespace:null,foreign_table:null,foreign_keys:[],update_action:" ",delete_action:" ",match_type:" ",definition:type+":"+keys.join(","),...extra})
for(const [table,body]of tableBodies){
let index=0
for(const _ of body.matchAll(/\bCHECK\s*\(/g))addConstraint(table,"c",[],`${table}_check_${index++}`)
for(const column of found.columns.filter(row=>row.table_name===table&&row.not_null))addConstraint(table,"n",[String(column.name)],`${table}_${column.name}_not_null`)
}
for(const row of found.triggers.filter(row=>row.is_constraint))addConstraint(String(row.table_name),"t",[],String(row.name))
const specifications:Record<string,Array<[string,string[]]>>={bandwidth_node_authority:[["p",["id"]]],bandwidth_nodes:[["p",["node_id"]],["u",["claim_proof"]]],bandwidth_node_aliases:[["p",["server_id"]],["u",["incarnation"]],["i",["node_id"]]],bandwidth_node_events:[["p",["event_id"]],["u",["server_id","kind"]],["i",["node_id"]]]}
for(const[table,specs]of Object.entries(specifications))for(const[kind,keys]of specs){
if(kind!=="i")addConstraint(table,kind,keys,`${table}_${kind}`)
const fields=keys.map(name=>found.columns.find(row=>row.table_name===table&&row.name===name)!)
found.indexes.push({table_name:table,name:`${table}_${kind}`,unique:kind!=="i",primary:kind==="p",valid:true,ready:true,live:true,key_count:keys.length,attribute_count:keys.length,method:"btree",keys,collations:fields.map(row=>row.collation_name),collation_namespaces:fields.map(row=>row.collation_namespace),operator_classes:fields.map(row=>row.type_name==="uuid"?"uuid_ops":row.type_name==="int4"?"int4_ops":row.type_name==="int8"?"int8_ops":"text_ops"),operator_class_namespaces:fields.map(()=>"pg_catalog"),options:keys.map(()=>"0").join(" "),expressions:null,predicate:null,definition:`index ${table} (${keys.join(",")})`})
}
for(const[table,key,parent]of[["bandwidth_node_aliases","node_id","bandwidth_nodes"],["bandwidth_node_events","server_id","bandwidth_node_aliases"],["bandwidth_node_events","node_id","bandwidth_nodes"]]){
const name=`${table}_${key}_fkey`
addConstraint(table,"f",[key],name,{foreign_namespace:"mmapp_control",foreign_table:parent,foreign_keys:[key],update_action:"r",delete_action:"r",match_type:"s"})
for(const[relation,fn,type]of[[table,"RI_FKey_check_ins",5],[table,"RI_FKey_check_upd",17],[parent,"RI_FKey_restrict_del",9],[parent,"RI_FKey_restrict_upd",17]]as const)found.triggers.push({table_name:relation,name:null,internal:true,type,enabled:"O",deferrable:false,initially_deferred:false,is_constraint:true,constraint_name:name,function_namespace:"pg_catalog",function_name:fn,argument_count:0,arguments:"",columns:"",condition:null,old_table:null,new_table:null})
}
return Object.entries(found).flatMap(([section,rows])=>rows.map(row=>({section,raw_json:JSON.stringify(row)})))
}
function fixture(){
const catalog=catalogFixture(),expected:BandwidthNodeIdentityExpected={databaseName:"v1_control",runtimeRole:"v1_runtime",ownerRole:"fixed_owner",installationId:"11111111-1111-4111-8111-111111111111",issuerKeySha256:"a".repeat(64),quiescenceProof:"b".repeat(64),registryCatalogSha256:validateBandwidthNodeRegistryCatalogRows(catalog)}
const role={observation:{databaseName:expected.databaseName,sessionRole:expected.runtimeRole,currentRole:expected.runtimeRole,runtimeRoleExists:true,ownerRoleExists:true,runtimeFlagsSafe:true,ownerMembership:false,dangerousMembership:false,schemaExists:true,schemaOwner:expected.ownerRole,schemaUsage:true,schemaCreate:false,publicSchemaUsage:false,publicSchemaCreate:false,tables:["bandwidth_node_aliases","bandwidth_nodes","bandwidth_node_events","bandwidth_node_authority"].map(name=>({name,exists:true,ownerRole:expected.ownerRole,ownedByRuntime:false,privilegesExact:true}))}}
const authority={installation_id:expected.installationId,issuer_key_sha256:expected.issuerKeySha256,quiescence_proof:expected.quiescenceProof,status:"active"}
const groups:Record<string,unknown[]>={role:[role],catalog,authority:[authority]},rows:Batch[]=Object.entries(groups).flatMap(([kind,values])=>values.map(value=>({kind,row_order:"",raw_json:JSON.stringify(value)})))
ordinal(rows);return{rows,expected,catalog}
}
function ordinal(rows:Batch[]){rows.forEach((row,index)=>{row.row_order=String(index+1)});return rows}
const refused=(error:unknown)=>error instanceof BandwidthNodeIdentityRefused
const check=(f:ReturnType<typeof fixture>)=>validateBandwidthNodeIdentityRows(f.rows,f.expected)
function change(f:ReturnType<typeof fixture>,kind:string,mutate:(row:Row)=>void){const item=f.rows.find(row=>row.kind===kind)!;const value=JSON.parse(item.raw_json!) as Row;mutate(value);item.raw_json=JSON.stringify(value)}
function catalogChange(f:ReturnType<typeof fixture>,section:string,mutate:(row:Row)=>void){const item=f.rows.find(row=>row.kind==="catalog"&&(JSON.parse(row.raw_json!) as Item).section===section)!;const value=JSON.parse(item.raw_json!) as Item,row=JSON.parse(value.raw_json!) as Row;mutate(row);value.raw_json=JSON.stringify(row);item.raw_json=JSON.stringify(value)}
test("exact original role/catalog/authority share ONE fixed materialized SELECT and retain before/after/final live checks",async()=>{
const f=fixture(),events:string[]=[];let calls=0
await assertBandwidthNodeIdentity({async query(text,values){calls++;events.push("SQL");assert.equal(text,BANDWIDTH_NODE_IDENTITY_SQL);assert.deepEqual(values,[f.expected.databaseName,f.expected.runtimeRole,f.expected.ownerRole]);return{rows:f.rows}}},f.expected,()=>events.push("live"))
assert.equal(calls,1);assert.deepEqual(events,["live","SQL","live","live"])
for(const name of ["node_role","node_catalog","authority"])assert(BANDWIDTH_NODE_IDENTITY_SQL.includes(name+" AS MATERIALIZED"))
assert(BANDWIDTH_NODE_IDENTITY_SQL.includes("ORDER BY c.relname,t.tgname LIMIT 23"));assert(!BANDWIDTH_NODE_IDENTITY_SQL.includes("ORDER BY c.relname,t.tgname LIMIT 27"));assert(!BANDWIDTH_NODE_IDENTITY_SQL.includes("bandwidth_external_node"));assert(!/INSERT INTO|CREATE TABLE|CREATE FUNCTION/.test(BANDWIDTH_NODE_IDENTITY_SQL))
})
test("legacy signed digest is exactly unchanged; transport order/key order do not alter meaning",()=>{
const f=fixture();assert.equal(validateBandwidthNodeRegistryCatalogRows(f.catalog),f.expected.registryCatalogSha256);f.rows.reverse();for(const item of f.rows){const row=JSON.parse(item.raw_json!) as Row;item.raw_json=JSON.stringify(Object.fromEntries(Object.entries(row).reverse()))}check(f)
})
test("missing/duplicate role, catalog or authority cannot substitute a partial snapshot",()=>{
for(const kind of ["role","catalog","authority"]){const f=fixture();f.rows=ordinal(f.rows.filter(row=>row.kind!==kind));assert.throws(()=>check(f),refused);const duplicate=fixture();duplicate.rows.push({...duplicate.rows.find(row=>row.kind===kind)!});ordinal(duplicate.rows);assert.throws(()=>check(duplicate),refused)}
})
test("outer tags/shape/ordinals, NULL overflow and malformed nested JSON fail closed",()=>{
for(const mutate of [(rows:Batch[])=>{rows[0].kind="external-role"},(rows:Batch[])=>{rows[0].raw_json=null},(rows:Batch[])=>{rows[0].raw_json="{"},(rows:Batch[])=>{rows[0].raw_json="[]"},(rows:Batch[])=>{rows[0].row_order=rows[1].row_order},(rows:Batch[])=>{rows[0].row_order="0"},(rows:Batch[])=>{rows[0].row_order="01"},(rows:Batch[])=>{rows[0].row_order="999"}]){const f=fixture();mutate(f.rows);assert.throws(()=>check(f),refused)}
const f=fixture();catalogChange(f,"functions",row=>{delete row.body});assert.throws(()=>check(f),refused)
})
test("strict row/per-row/total/component byte bounds preserve the old tighter catalog budget",()=>{
const f=fixture(),row={kind:"catalog",row_order:"1",raw_json:JSON.stringify({padding:"x".repeat(131180)})}
assert.throws(()=>validateBandwidthNodeIdentityRows(ordinal(Array.from({length:233},()=>({...row}))),f.expected),refused)
assert.throws(()=>validateBandwidthNodeIdentityRows([{...row,raw_json:JSON.stringify({padding:"x".repeat(131201)})}],f.expected),refused)
assert.throws(()=>validateBandwidthNodeIdentityRows(ordinal(Array.from({length:33},()=>({...row}))),f.expected),refused)
assert.throws(()=>validateBandwidthNodeIdentityRows(ordinal(Array.from({length:231},()=>({...row,raw_json:"{}"}))),f.expected),refused)
})
test("v1 still requires EXACT22 triggers; an external incoming FK cannot be blessed by the new observer",()=>{
const f=fixture(),existing=f.rows.find(row=>row.kind==="catalog"&&(JSON.parse(row.raw_json!) as Item).section==="triggers")!,extra=structuredClone(existing),item=JSON.parse(extra.raw_json!) as Item,trigger=JSON.parse(item.raw_json!) as Row
trigger.table_name="bandwidth_nodes";trigger.constraint_name="bandwidth_external_node_aliases_node_id_fkey";trigger.name=null;trigger.internal=true;item.raw_json=JSON.stringify(trigger);extra.raw_json=JSON.stringify(item);f.rows.push(extra);ordinal(f.rows);assert.throws(()=>check(f),refused)
})
test("old role privileges/membership/schema ownership, literal guard and signed expression pin checks remain exact",()=>{
for(const mutate of [(row:Row)=>{(row.observation as Row).dangerousMembership=true},(row:Row)=>{(row.observation as Row).runtimeFlagsSafe=false},(row:Row)=>{(row.observation as Row).publicSchemaCreate=true},(row:Row)=>{((row.observation as Row).tables as Row[])[0].privilegesExact=false}]){const f=fixture();change(f,"role",mutate);assert.throws(()=>check(f),refused)}
for(const [section,mutate]of [["functions",(row:Row)=>{row.body="BEGIN RETURN NEW; END;"}],["triggers",(row:Row)=>{row.enabled="O"}],["constraints",(row:Row)=>{row.definition="CHECK(true)"}],["indexes",(row:Row)=>{row.predicate="false"}]] as const){const f=fixture();catalogChange(f,section,mutate);assert.throws(()=>check(f),refused)}
})
test("active authority exact installation/issuer/quiescence is required alongside matching legacy catalog",()=>{
for(const mutate of [(row:Row)=>{row.installation_id="22222222-2222-4222-8222-222222222222"},(row:Row)=>{row.issuer_key_sha256="f".repeat(64)},(row:Row)=>{row.quiescence_proof="f".repeat(64)},(row:Row)=>{row.status="quarantined"},(row:Row)=>{row.ready=true}]){const f=fixture();change(f,"authority",mutate);assert.throws(()=>check(f),refused)}
})
test("original expected scalar pins are copied beforeawait; input getters/symbols cannot provide a later authority",async()=>{
const f=fixture(),original={...f.expected}
await assertBandwidthNodeIdentity({async query(_text,values){assert.deepEqual(values,[original.databaseName,original.runtimeRole,original.ownerRole]);f.expected.registryCatalogSha256="f".repeat(64);f.expected.issuerKeySha256="f".repeat(64);return{rows:f.rows}}},f.expected,()=>{})
const g=fixture();let getters=0,calls=0;Object.defineProperty(g.expected,"issuerKeySha256",{enumerable:true,get(){getters++;return"a".repeat(64)}})
await assert.rejects(assertBandwidthNodeIdentity({async query(){calls++;return{rows:g.rows}}},g.expected,()=>{}),refused);assert.equal(getters,0);assert.equal(calls,0)
const h=fixture();Object.defineProperty(h.expected,Symbol("proof"),{value:true});assert.throws(()=>check(h),refused)
})
test("late scope/original grant revocation and SQL failure preserve final live boundary without endpoint/key disclosure",async()=>{
const f=fixture(),expired=Error("original grant stopped");let live=0
await assert.rejects(assertBandwidthNodeIdentity({async query(){return{rows:f.rows}}},f.expected,()=>{if(++live===2)throw expired}),error=>error===expired);assert.equal(live,2)
const events:string[]=[];await assert.rejects(assertBandwidthNodeIdentity({async query(){events.push("SQL");throw Error("private endpoint/password/key")}},f.expected,()=>events.push("live")),error=>refused(error)&&!String(error).includes("password"));assert.deepEqual(events,["live","SQL","live"])
let calls=0;await assert.rejects(assertBandwidthNodeIdentity({async query(){calls++;return{rows:f.rows}}},f.expected,()=>{throw expired}),error=>error===expired);assert.equal(calls,0)
})