fix(test): обновить заглушки standalone-тестов IPsec и восстановления БД

Устаревшие тесты, не дефекты продукта (профили test:ipsec и
test:system-database):
- ipsec-nat и ipsec-group: аудит конфигурации теперь пишется через
  requestAccountingWrite (BEGIN, pg_catalog.pg_try_advisory_xact_lock_shared,
  COMMIT), а SQL-заглушка знала только прежние запросы и падала, превращая
  ожидаемый отказ preflight 409 в 502. Заглушка принимает новые запросы
  блокировки и границы транзакции.
- database-restore-audit: bootstrap.ts теперь импортирует модули карантина и
  контрольной точки восстановления и читает process.env; в карту заглушек
  добавлены значения обычного запуска (без карантина и checkpoint), в
  контекст передан пустой process.env. Проверка порядка (guard → миграции →
  импорт → аудит) не менялась.
Проверено: --all --regression-only для test:ipsec и test:system-database → exit 0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DenozordecandClaude Opus 5.5 committed 2026-11-15 23:38:32 +07:00
1 parent 1094acb5c5
commit 77e52f157a
3 files changed
+10 -6

No files matched your search

+1 -1
View File
@@ -21,7 +21,7 @@ assert.equal(templateBody?.group,IPSEC_POLICY_GROUP)
const original=MikrotikClient.fromServer;let writes=0;MikrotikClient.fromServer=()=>({get:async(p:string)=>p==="/ip/ipsec/policy/group"?groups:[],put:async()=>{writes++},patch:async()=>{writes++},delete:async()=>{writes++},post:async()=>{writes++}}) as unknown as MikrotikClient
const originalSelect=db.select,originalQuery=pool.query,originalConnect=pool.connect
const server={id:1,enabled:true,routingEndpointEpoch:"00000000-0000-4000-8000-000000000001"} as Parameters<typeof fetchIpsecState>[0]
const fixtureQuery=async(sql:string)=>{if(sql.startsWith("SELECT pg_try_advisory_lock"))return{rows:[{acquired:true}]};if(sql.startsWith("SELECT pg_advisory_unlock"))return{rows:[{pg_advisory_unlock:true}]};if(sql.startsWith("SELECT object_ref FROM mcp_protections")||sql.startsWith("INSERT INTO mcp_audit("))return{rows:[]};throw Error("Unexpected SQL in standalone init group fixture: "+sql)}
const fixtureQuery=async(sql:string)=>{if(/^SELECT (pg_catalog\.)?pg_try_advisory_(xact_)?lock/.test(sql))return{rows:[{acquired:true}]};if(/^SELECT (pg_catalog\.)?pg_advisory_unlock/.test(sql))return{rows:[{pg_advisory_unlock:true,released:true}]};if(["BEGIN","COMMIT","ROLLBACK"].includes(sql))return{rows:[]};if(sql.startsWith("SELECT object_ref FROM mcp_protections")||sql.startsWith("INSERT INTO mcp_audit("))return{rows:[]};throw Error("Unexpected SQL in standalone init group fixture: "+sql)}
pool.query=fixtureQuery as typeof pool.query;pool.connect=(async()=>({query:fixtureQuery,release:()=>{}}))as unknown as typeof pool.connect
db.select=(()=>({from:(table:unknown)=>{assert.equal(table,servers);return{where:()=>({limit:async()=>[server]})}}}))as unknown as typeof db.select
const app=Fastify();app.setValidatorCompiler(validatorCompiler);app.setSerializerCompiler(serializerCompiler)
+2 -2
View File
@@ -16,12 +16,12 @@ let writes=0
const original=MikrotikClient.fromServer
const originalSelect=db.select,originalQuery=pool.query,originalConnect=pool.connect
const server={id:1,enabled:true,host:"192.0.2.1",routingEndpointEpoch:"00000000-0000-4000-8000-000000000001"} as Parameters<typeof fetchIpsecState>[0]
const fixtureQuery=async(sql:string)=>{if(sql.startsWith("SELECT pg_try_advisory_lock"))return{rows:[{acquired:true}]};if(sql.startsWith("SELECT pg_advisory_unlock"))return{rows:[{pg_advisory_unlock:true}]};if(sql.startsWith("SELECT object_ref FROM mcp_protections")||sql.startsWith("INSERT INTO mcp_audit("))return{rows:[]};throw Error("Unexpected SQL in standalone init NAT fixture: "+sql)}
const fixtureQuery=async(sql:string)=>{if(/^SELECT (pg_catalog\.)?pg_try_advisory_(xact_)?lock/.test(sql))return{rows:[{acquired:true}]};if(/^SELECT (pg_catalog\.)?pg_advisory_unlock/.test(sql))return{rows:[{pg_advisory_unlock:true,released:true}]};if(["BEGIN","COMMIT","ROLLBACK"].includes(sql))return{rows:[]};if(sql.startsWith("SELECT object_ref FROM mcp_protections")||sql.startsWith("INSERT INTO mcp_audit("))return{rows:[]};throw Error("Unexpected SQL in standalone init NAT fixture: "+sql)}
pool.query=fixtureQuery as typeof pool.query;pool.connect=(async()=>({query:fixtureQuery,release:()=>{}}))as unknown as typeof pool.connect
db.select=(()=>({from:(table:unknown)=>{assert.equal(table,servers);return{where:()=>({limit:async()=>[server]})}}}))as unknown as typeof db.select
MikrotikClient.fromServer=()=>({get:async(p:string)=>p==="/interface"?interfaces:[],put:async()=>{writes++},patch:async()=>{writes++},post:async()=>{writes++},delete:async()=>{writes++}}) as unknown as MikrotikClient
const app=Fastify();app.setValidatorCompiler(validatorCompiler);app.setSerializerCompiler(serializerCompiler)
try {await app.register(createIpsecRoutes({findServer:async()=>server,recordRevision:async()=>{throw Error("must not record")}}),{prefix:"/api"});const r=await app.inject({method:"POST",url:"/api/ipsec/server/init",payload:{serverId:1,serverEndpoint:"192.0.2.1",poolCidr:"198.18.82.0/24",createNatRule:true}});assert.equal(r.statusCode,409);assert.equal(writes,0);assert.match(r.json().error,/Изменений не было/)}finally{await app.close();MikrotikClient.fromServer=original;db.select=originalSelect;pool.query=originalQuery;pool.connect=originalConnect}
try {await app.register(createIpsecRoutes({findServer:async()=>server,recordRevision:async()=>{throw Error("must not record")}}),{prefix:"/api"});const r=await app.inject({method:"POST",url:"/api/ipsec/server/init",payload:{serverId:1,serverEndpoint:"192.0.2.1",poolCidr:"198.18.82.0/24",createNatRule:true}});assert.equal(r.statusCode,409,r.body);assert.equal(writes,0);assert.match(r.json().error,/Изменений не было/)}finally{await app.close();MikrotikClient.fromServer=original;db.select=originalSelect;pool.query=originalQuery;pool.connect=originalConnect}
for(const existing of [false,true]){let body:Record<string,string>|undefined;let method="";await ensureNatRule({get:async()=>existing?[{".id":"*N",chain:"srcnat",comment:"owned","out-interface-list":"WAN"}]:[],put:async(_p:string,b:Record<string,string>)=>{method="put";body=b},patch:async(_p:string,b:Record<string,string>)=>{method="patch";body=b}} as unknown as MikrotikClient,"198.18.82.0/24","owned","ether1");assert.equal(method,existing?"patch":"put");assert.equal(body?.["out-interface"],"ether1");assert.equal(body?.["ipsec-policy"],"out,none");assert.equal(body?.["out-interface-list"],undefined)}
console.log("IPsec NAT: verified egress, PPP/duplicates, missing/ambiguous/VRF no-write preflight and scoped create/update")
@@ -85,15 +85,19 @@ for(const legacyImport of [false,true])test('actual bootstrap audit follows migr
const source=await readFile(path.join(backend,'src/db/bootstrap.ts'),'utf8'),events:string[]=[],exports:Record<string,unknown>={}
const query=async()=>{events.push('sql');return {rows:[{sqlite_imported_at:'done',released:true}]}},client={query}
const modules:Record<string,unknown>={
'./index.js':{pool:{query,connect:async()=>client}},'./migrate.js':{applySqlMigrations:async()=>events.push('migrations')},
'./index.js':{pool:{query,connect:async()=>client},assertRuntimeDatabaseActivationCurrent:()=>{},readRuntimeDatabaseWriterHead:async()=>undefined},
'./migrate.js':{applySqlMigrations:async()=>events.push('migrations'),assertSqlMigrationsApplied:async()=>events.push('migrations-checked')},
// Ordinary startup: no restore quarantine and no restore checkpoint.
'./database-restore-quarantine.js':{databaseRestoreQuarantineEnabled:()=>false,assertDatabaseRestoreQuarantineOpen:async()=>{}},
'../services/database-restore-checkpoint.js':{DatabaseRestoreCheckpointRefused:class extends Error{},readDatabaseRestoreCheckpoint:async()=>undefined,restoreJournalHeadsEqual:()=>true,restoreWriterHeadIsCurrent:()=>true},
'./operation-lock.js':{withSystemDatabaseOperationLock:async(_connect:unknown,run:(owner:typeof client,discard:()=>void)=>Promise<void>)=>run(client,()=>{})},
'./partitions.js':{dropExpiredPartitions:async()=>events.push('drop'),ensurePartitionsAround:async()=>events.push('partitions')},
'./sqlite-import.js':{shouldImportSqlite:async()=>legacyImport,sqliteFileLooksPresent:()=>false,importSqliteToPostgres:async()=>{events.push('import');return {durationMs:0,tables:{}}}},
'../config.js':{env:{DATABASE_PATH:'synthetic'}},'../modules/mcp/security.js':{mcpStateDirectory:()=>root},
'../services/database-maintenance-startup.js':{assertDatabaseMaintenanceStartup:async()=>events.push('guard')},
'../services/database-maintenance-startup.js':{assertDatabaseMaintenanceStartup:async()=>events.push('guard'),assertDatabaseRestoreJournalCurrent:async()=>undefined},
'../services/database-restore-audit.js':{reconcileDatabaseRestoreAudits:async()=>{events.push('audit');throw Error('Pending audit import')}},
}
runInNewContext(ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022}}).outputText,{exports,require:(name:string)=>{assert(name in modules);return modules[name]},console})
runInNewContext(ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022}}).outputText,{exports,require:(name:string)=>{assert(name in modules,name);return modules[name]},console,process:{env:{}}})
await assert.rejects((exports.initDatabase as ()=>Promise<void>)(),/Pending audit import/)
assert.equal(events[0],'guard');assert.equal(events.at(-1),'audit');assert(events.indexOf('migrations')<events.indexOf('audit'));if(legacyImport)assert(events.indexOf('import')<events.indexOf('audit'))
}))