Files
MikrotikManager/backend/src/services/vrf-execution-diagnostic.test.mjs
T
Denozordec c20b6b33c3
Docker images / prepare-release (push) Successful in 12s
Docker images / backend-test (push) Successful in 12m23s
Docker images / backend-image (push) Successful in 2m4s
Docker images / frontend-image (push) Successful in 2m16s
Docker images / updater-image (push) Successful in 40s
Docker images / netflow-agent-image (push) Successful in 33s
Docker images / notify-webhook (push) Successful in 2s
Docker images / publish-release (push) Successful in 10s
fix(ci): обновить тестовые фикстуры автономных планов
2026-11-22 13:09:15 +07:00

194 lines
19 KiB
JavaScript

import assert from 'node:assert/strict'
import {readFile} from 'node:fs/promises'
import ts from 'typescript'
// Execute the real emitted executor body with only its imported I/O dependencies
// substituted. No SQL, HTTP, config files or live authority can be contacted.
const compile=async name=>ts.transpileModule(await readFile(new URL(name,import.meta.url),'utf8'),{compilerOptions:{target:ts.ScriptTarget.ES2022,module:ts.ModuleKind.ES2022}}).outputText
const uri=source=>'data:text/javascript;base64,'+Buffer.from(source).toString('base64')
// Preserve offline I/O substitution while linking pure relative leaf modules.
const pureModules=new Map()
async function pureModuleUri(name){
if(pureModules.has(name))return pureModules.get(name)
const loading=(async()=>{
let code=await compile(name)
const ast=ts.createSourceFile(name,code,ts.ScriptTarget.ES2022,true,ts.ScriptKind.JS)
const imports=ast.statements.filter(ts.isImportDeclaration).filter(node=>node.moduleSpecifier.text.startsWith('./'))
const edits=await Promise.all(imports.map(async node=>({start:node.moduleSpecifier.getStart(ast),end:node.moduleSpecifier.end,value:await pureModuleUri(node.moduleSpecifier.text.replace(/\.js$/,'.ts'))})))
for(const edit of edits.reverse())code=code.slice(0,edit.start)+JSON.stringify(edit.value)+code.slice(edit.end)
return uri(code)
})()
pureModules.set(name,loading);return loading
}
const diagnosticUri=await pureModuleUri('./vrf-execution-diagnostic.ts')
const diagnostic=await import(diagnosticUri)
const refusalUri=await pureModuleUri('./vrf-transition-refusal.ts'),refusal=await import(refusalUri)
const id='12345678-1234-4123-8123-123456789abc'
let cases=0
for(const [error,expected]of [[Error('SECRET'),'Error'],[new TypeError('SECRET'),'TypeError'],[new RangeError('SECRET'),'RangeError'],[new SyntaxError('SECRET'),'SyntaxError'],[new ReferenceError('SECRET'),'ReferenceError'],[new URIError('SECRET'),'URIError'],[new EvalError('SECRET'),'EvalError'],[{message:'SECRET'},'NonError'],[new Proxy(Error('SECRET'),{get(){throw Error('getter')}}),'NonError']]){
const value=diagnostic.vrfExecutionDiagnostic(id,'create','raw-before',error,false,{serverId:1,catalog:'vrf',boundary:'native-get'})
assert.equal(value.errorClass,expected);assert.equal(JSON.stringify(value).includes('SECRET'),false);cases++
}
const trap=Error('SECRET')
for(const key of ['message','stack','code','cause'])Object.defineProperty(trap,key,{get(){throw Error('SECRET getter')}})
assert.equal(diagnostic.vrfExecutionDiagnostic(id,'create','raw-before',trap,false).category,'other');cases++
for(const code of ['ECONNRESET','ETIMEDOUT','40P01','SECRET']){
const value=diagnostic.vrfExecutionDiagnostic(id,'delete','ack-journal',Object.assign(Error('SECRET'),{code}),true)
assert.equal(value.category,({ECONNRESET:'reset',ETIMEDOUT:'timeout','40P01':'pg-deadlock'})[code]??'other')
assert.equal(JSON.stringify(value).includes('SECRET'),false);cases++
}
assert.equal(diagnostic.vrfExecutionDiagnostic('SECRET','create','raw-before',Error(),false),undefined)
assert.equal(diagnostic.vrfExecutionDiagnostic(id,'SECRET','raw-before',Error(),false),undefined)
assert.equal(diagnostic.vrfExecutionDiagnostic(id,'create','SECRET',Error(),false),undefined)
assert.equal(diagnostic.vrfExecutionDiagnostic(id,'create','raw-before',Error(),false,{serverId:1,catalog:'SECRET',boundary:'native-get'}).read,undefined);cases++
diagnostic.notifyVrfDiagnostic(()=>{throw Error('observer')},{})
diagnostic.notifyVrfDiagnostic(async()=>{throw Error('observer')},{})
await new Promise(resolve=>setImmediate(resolve));cases++
const key='__vrfDiagnosticOfflineFixture'
class McpError extends Error{constructor(code,message){super(message);this.code=code}}
globalThis[key]={McpError}
const functions=['readVrfProductionSnapshot','claimStoredVrfProductionTicket','inspectVrfProductionAdmission','assertVrfProductionHistoryProvenance','assertVrfProductionTransitionCheckpoint','classifyVrfProductionTransition','openVrfProductionTransitionCheckpoint','sealVrfProductionTransitionCheckpoint','vrfProductionCheckpointCatalogs','assertVerifiedConfigurationAccess','withVrfClaimQuarantine','assertVrfActionContext','vrfNativeActionFor','vrfActionContractsCurrent','findMcpOperation','decryptSecretExisting','encryptSecret','fingerprint','withVrfProductionSealingKey','configurationRows','resourceById','routerClient','rosSnapshotSourceProof']
const stubUri=uri(`export const McpError=globalThis.${key}.McpError;export const pool={query:(...args)=>globalThis.${key}.query(...args)};`+functions.map(name=>`export const ${name}=(...args)=>globalThis.${key}.${name}(...args);`).join('\n'))
let emitted=await compile('./vrf-production-execution.ts')
const ast=ts.createSourceFile('executor.js',emitted,ts.ScriptTarget.ES2022,true,ts.ScriptKind.JS)
const edits=ast.statements.filter(ts.isImportDeclaration).map(node=>({start:node.moduleSpecifier.getStart(ast),end:node.moduleSpecifier.end,value:node.moduleSpecifier.text.endsWith('/vrf-execution-diagnostic.js')?diagnosticUri:node.moduleSpecifier.text.endsWith('/vrf-transition-refusal.js')?refusalUri:stubUri}))
for(const edit of edits.reverse())emitted=emitted.slice(0,edit.start)+JSON.stringify(edit.value)+emitted.slice(edit.end)
const api=await import(uri(emitted))
function fixture(options={}){
const failure=Object.assign(Error('PRIVATE_PASSWORD native-body SQL /private/path'),{code:options.errno??'ETIMEDOUT'})
const events=[],calls=[];let settles=0,reads=0,deps=0,access=0,inspect=0,routers=0,guard,clientCalls=0
const proof='a'.repeat(64),snapshot={projection:'raw-native-v1',serverId:1,sourceProof:proof,catalogs:{vrf:[{'.id':'*0',name:'main',interfaces:'all',disabled:'false'}],interface_inventory:[]}}
const fail=name=>{calls.push(name);if(options.fail===name)throw failure}
const f={McpError,
async query(sql){
if(sql.includes('SELECT cp.after_sealed')){fail('history-load');return{rows:[]}}
if(sql.includes('SELECT ticket_id')){fail('ticket-lookup');return{rows:[{ticket_id:'ticket'}]}}
if(sql.includes('SET before_sealed'))fail('checkpoint-before')
if(sql.includes("SET state='applied'"))fail('ack-journal')
if(sql.includes('SET after_sealed'))fail('checkpoint-after')
return{rows:[{id,operation_id:id}]}
},
async assertVerifiedConfigurationAccess(){fail('access-'+(++access))},
async routerClient(){fail('router-'+(++routers));return{server:{},client:{
async put(){clientCalls++;fail('client-before-guard');await guard();fail('client-after-guard');return options.badAck?{}:{'.id':'*1'}},
async patch(){clientCalls++;await guard();return{'.id':'*1'}},
async delete(_path,_timeout,_before,onBody){clientCalls++;await guard();onBody(options.badDeleteBody?'PRIVATE_INVALID_JSON':'{}')},
}}},
async rosSnapshotSourceProof(){return proof},
vrfNativeActionFor(){return'ros.vrf.create'},assertVrfActionContext(){},vrfActionContractsCurrent(){return true},findMcpOperation(){return{version:1}},
async withVrfProductionSealingKey(work){fail('sealing-key');return work(Buffer.alloc(32))},
async readVrfProductionSnapshot(input){reads++;input.observeRead?.({serverId:1,catalog:'gre',boundary:'native-get'});fail('read-'+reads);return structuredClone(snapshot)},
configurationRows(_spec,rows){return rows},resourceById(){return{}},fingerprint(){return'current-fingerprint'},
async withVrfClaimQuarantine(input){return input.claim()},async claimStoredVrfProductionTicket(){fail('ticket-claim');return{privateSealed:'PRIVATE_SEALED'}},
async encryptSecret(){return'PRIVATE_CIPHERTEXT'},async decryptSecretExisting(){throw Error('not used')},
inspectVrfProductionAdmission(){fail('inspect-'+(++inspect));return{admission:{}}},
assertVrfProductionHistoryProvenance(){},assertVrfProductionTransitionCheckpoint(){},openVrfProductionTransitionCheckpoint(){},vrfProductionCheckpointCatalogs(){return[]},
classifyVrfProductionTransition(){
if(settles<(options.settling??0)){settles++;const error=Error('PRIVATE mid-flap');refusal.noteVrfTransitionRefusal(error,'address/route absence outside exact acquisition');refusal.noteVrfTransitionSettling(error);throw error}
fail('classification');return{checkpoint:{}}},sealVrfProductionTransitionCheckpoint(){return'PRIVATE_HISTORY'},
}
globalThis[key]=f
const input={operationId:id,planId:'plan',connectionId:'connection',ownerId:'owner',operationName:options.action==='delete'?'ros.vrf.delete':'ros.vrf.create',operationVersion:1,stepIndex:0,
step:{serverId:1,resource:'vrf',action:options.action??'create',...(options.action==='delete'?{id:'*1'}:{}),fields:options.action==='delete'?{}:{name:'customers',interfaces:'none'},placeBeforeId:options.action==='delete'?undefined:'*0'},sourceProof:proof,
originalSnapshots:options.originalDrift?[{serverId:1,resource:'vrf',sourceProof:proof,fingerprint:'old-fingerprint'}]:[],
async authorize(){},async assertDependencies(){fail('dependencies-'+(++deps))},installBeforeDispatch(value){fail('install');guard=value},
onDiagnostic(value){events.push(value);if(options.observerThrows)throw Error('logging failed');if(options.observerRejects)return Promise.reject(Error('async logging failed'))},
}
return{failure,events,calls,input,clientCalls:()=>clientCalls,reads:()=>reads,run:()=>api.executeVrfProductionStep(input)}
}
for(const [fail,stage,ack]of [
['access-1','initial-authorization',false],['sealing-key','sealing-key',false],['read-1','raw-before',false],
['ticket-lookup','ticket-lookup',false],['ticket-claim','ticket-claim',false],['checkpoint-before','checkpoint-before',false],['install','install-predispatch',false],
['access-2','explicit-predispatch-authorization',false],['dependencies-1','explicit-predispatch-dependencies',false],['read-2','explicit-predispatch-read',false],['inspect-1','explicit-predispatch-admission',false],['access-3','explicit-predispatch-final-authorization',false],
['router-4','dispatch-source',false],['client-before-guard','client-call',false],['access-4','installed-predispatch-authorization',false],['dependencies-2','installed-predispatch-dependencies',false],['read-3','installed-predispatch-read',false],['inspect-2','installed-predispatch-admission',false],['access-5','installed-predispatch-final-authorization',false],['client-after-guard','client-call',false],
['ack-journal','ack-journal',true],['access-6','post-ack-authorization',true],['read-4','raw-after',true],['classification','transition-classification',true],['dependencies-3','post-ack-dependencies',true],['access-7','post-ack-final-authorization',true],['checkpoint-after','checkpoint-after',true],
]){
const f=fixture({fail});let thrown;try{await f.run()}catch(error){thrown=error}
assert.ok(thrown,fail);assert.equal(f.events.length,1,fail);assert.equal(f.events[0].stage,stage,fail);assert.equal(f.events[0].executorAckObserved,ack,fail)
assert.equal(f.events[0].category,'timeout',fail)
if(fail.startsWith('read-'))assert.deepEqual(f.events[0].read,{serverId:1,catalog:'gre',boundary:'native-get'},fail)
else assert.equal(f.events[0].read,undefined,fail)
if(!ack)assert.equal(thrown,f.failure,fail)
else assert.ok(thrown instanceof api.VrfProductionAcknowledgedFailure,fail)
if(fail==='ack-journal')assert.equal(thrown.code,'VRF_ACK_JOURNAL_UNCONFIRMED')
if(fail==='checkpoint-after')assert.equal(thrown.code,'VRF_VERIFIED_CHECKPOINT_UNCONFIRMED')
assert.equal(JSON.stringify(f.events).includes('PRIVATE'),false);cases++
}
for(const observer of ['observerThrows','observerRejects']){
const f=fixture({fail:'read-1',[observer]:true});await assert.rejects(f.run(),error=>error===f.failure)
await new Promise(resolve=>setImmediate(resolve));assert.equal(f.events.length,1);cases++
}
const original=fixture({originalDrift:true});await assert.rejects(original.run(),error=>error.code==='STATE_CONFLICT');assert.equal(original.events[0].stage,'original-dependencies');cases++
const history=fixture({action:'delete',fail:'history-load'});await assert.rejects(history.run(),error=>error===history.failure);assert.equal(history.events[0].stage,'history-load');cases++
const malformed=fixture({badAck:true});await assert.rejects(malformed.run(),error=>error.code==='STATE_CONFLICT'&&!(error instanceof api.VrfProductionAcknowledgedFailure));assert.equal(malformed.events[0].stage,'ack-identity');assert.equal(malformed.events[0].executorAckObserved,true);cases++
const malformedDelete=fixture({action:'delete',badDeleteBody:true});await assert.rejects(malformedDelete.run(),error=>error instanceof api.VrfProductionAcknowledgedFailure&&error.code==='VERIFICATION_FAILED');assert.equal(malformedDelete.events[0].executorAckObserved,true);assert.equal(malformedDelete.events[0].stage,'ack-identity');cases++
const happy=fixture();const receipt=await happy.run();assert.equal(receipt.configurationVerified,true);assert.equal(happy.events.length,0);assert.equal(happy.clientCalls(),1);cases++
// Bounded post-ACK settling: real executor pauses, re-reads the full raw-after and never re-dispatches.
const settledOnce=fixture({settling:1});assert.equal((await settledOnce.run()).configurationVerified,true);assert.equal(settledOnce.reads(),5);assert.equal(settledOnce.clientCalls(),1);assert.equal(settledOnce.events.length,0);cases++
const neverSettled=fixture({settling:99});await assert.rejects(neverSettled.run(),error=>error instanceof api.VrfProductionAcknowledgedFailure&&error.code==='VERIFICATION_FAILED')
assert.equal(neverSettled.reads(),3+1+refusal.VRF_SETTLING_REREADS);assert.equal(neverSettled.clientCalls(),1);assert.equal(neverSettled.events.length,1)
assert.equal(neverSettled.events[0].stage,'transition-classification');assert.equal(neverSettled.events[0].attempts,1+refusal.VRF_SETTLING_REREADS);assert.deepEqual(neverSettled.events[0].transition,{guard:'ADDRESS_ROUTE_ABSENCE_OUTSIDE_EXACT_ACQUISITION'});cases++
const silent=fixture({fail:'read-1'});delete silent.input.onDiagnostic;await assert.rejects(silent.run(),error=>error===silent.failure);cases++
// Exercise the exact emitted runtime policy call/callback/fallback/clear wiring.
// Only its surrounding policy and executor I/O are synthetic. Extracting the
// live AST statements means this test fails if the runtime stops wiring them.
const runtimeSource=await compile('../modules/mcp/runtime.ts')
const runtimeAst=ts.createSourceFile('runtime.js',runtimeSource,ts.ScriptTarget.ES2022,true,ts.ScriptKind.JS)
const setup=[],clear=[],policyCalls=[],fallback=[]
function visit(node){
if(ts.isExpressionStatement(node)){
const text=node.getText(runtimeAst)
if(text.startsWith('vrfDiagnosticFallback = productionVrf'))setup.push(text)
if(text==='vrfDiagnosticFallback = undefined;')clear.push(text)
if(text==='vrfDiagnosticFallback?.failure(error);')fallback.push(text)
}
if(ts.isVariableStatement(node)&&node.declarationList.declarations.length===1){
const value=node.declarationList.declarations[0]
if(value.name.getText(runtimeAst)==='result'&&value.initializer&&ts.isAwaitExpression(value.initializer)&&ts.isCallExpression(value.initializer.expression)&&value.initializer.expression.expression.getText(runtimeAst)==='withVerifiedConfigurationChange'&&node.getText(runtimeAst).includes('executeVrfProductionStep'))policyCalls.push(node.getText(runtimeAst))
}
ts.forEachChild(node,visit)
}
visit(runtimeAst)
for(const statements of [setup,clear,policyCalls,fallback])assert.equal(statements.length,1)
const runtimeBoundary=new Function(`return async function(env){
const {productionVrf,step,plan,operationId,connection,serverIds,evidence,serviceExecution,reservedStep,authorizeCatalog,authorize,prefix,McpError,executeVrfProductionStep,executeRosStep,withVerifiedConfigurationChange,createVrfRuntimeDiagnosticBoundary,console}=env;
const index=0;let vrfDiagnosticFallback,vrfBeforeDispatch;
const beforeDispatch=env.beforeDispatch;
try{${setup[0]}\n${policyCalls[0]}\n${clear[0]}\nif(env.failAfterWrapper)throw env.failure;return result}
catch(error){${fallback[0]}\nthrow error}
}`)()
for(const mode of ['runtime-policy-entry','policy-authorize','executor-entry','executor-clone','executor-binding','executor-reported','runtime-policy-exit','after-wrapper','non-production','success']){
for(const loggerThrows of [false,true]){
const error=Object.assign(Error('PRIVATE_RUNTIME_POLICY_FAILURE'),{code:'ECONNRESET'}),events=[]
const env={failure:error,failAfterWrapper:mode==='after-wrapper',productionVrf:mode!=='non-production',
operationId:id,connection:{owner_id:'owner',id:'connection'},serverIds:[1],evidence:{objects:[],snapshots:[{resource:'vrf',serverId:1,sourceProof:'a'.repeat(64)}]},serviceExecution:undefined,reservedStep:{},
plan:{id:'plan',operation_id:'ros.vrf.create',operation_version:1,approved_by:'owner',evidence:{sealed:'fixture-ciphertext'}},step:{kind:'ros',step:{serverId:1,resource:'vrf',action:'create',fields:{name:'customers',interfaces:'none'}}},
prefix:{async check(){}},async authorize(){},async authorizeCatalog(){if(mode==='policy-authorize')throw error},McpError,createVrfRuntimeDiagnosticBoundary:diagnostic.createVrfRuntimeDiagnosticBoundary,
console:{error(raw){events.push(JSON.parse(raw));if(loggerThrows)throw Error('PRIVATE_LOGGER_FAILURE')}},
async executeRosStep(){throw error},
async executeVrfProductionStep(input){
if(mode==='executor-entry')throw error
if(mode==='executor-clone'){input.step.fields.uncloneable=()=>{};return api.executeVrfProductionStep(input)}
if(mode==='executor-binding'){fixture();globalThis[key].assertVrfActionContext=()=>{throw error};return api.executeVrfProductionStep(input)}
if(mode==='executor-reported'){input.onDiagnostic(diagnostic.vrfExecutionDiagnostic(id,'create','raw-before',error,false,{serverId:1,catalog:'vrf',boundary:'native-get'}));throw error}
return{kind:'vrf-production-execution-v1',configurationVerified:true,nativeId:'*1'}
},
async withVerifiedConfigurationChange(context,work){
if(mode==='runtime-policy-entry')throw error
if(mode==='policy-authorize')await context.authorize()
const receipt=await work();if(mode==='runtime-policy-exit')throw error;return receipt
},
}
if(mode==='success'){assert.equal((await runtimeBoundary(env)).configurationVerified,true);assert.equal(events.length,0)}
else{
await assert.rejects(runtimeBoundary(env),value=>mode==='executor-clone'?value.name==='DataCloneError':value===error)
if(['after-wrapper','non-production'].includes(mode))assert.equal(events.length,0)
else{assert.equal(events.length,1);assert.equal(events[0].stage,mode==='executor-reported'?'raw-before':['executor-clone','executor-binding'].includes(mode)?'executor-entry':mode==='policy-authorize'?'runtime-policy-entry':mode);assert.equal(events[0].executorAckObserved,mode==='runtime-policy-exit');assert.equal(events[0].category,mode==='executor-clone'?'other':'reset')}
}
assert.equal(JSON.stringify(events).includes('PRIVATE'),false);cases++
}
}
delete globalThis[key]
console.log('VRF private execution diagnostics, actual executor body with offline imported I/O, closed projection cases:',cases)