Устаревшие тесты, не дефекты продукта (профили 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 <[email protected]>
28 lines
3.8 KiB
TypeScript
28 lines
3.8 KiB
TypeScript
import assert from "node:assert/strict"
|
|
import Fastify from "fastify"
|
|
import { validatorCompiler, serializerCompiler } from "@fastify/type-provider-zod"
|
|
import { createIpsecRoutes } from "./ipsec.js"
|
|
import { MikrotikClient } from "../services/mikrotik.js"
|
|
import { fetchIpsecState } from "../services/ipsec-live.js"
|
|
import { ensureNatRule, selectIpsecNatInterface } from "../services/ipsec-ros.js"
|
|
import { db, pool } from "../db/index.js"
|
|
import { servers } from "../db/schema.js"
|
|
const interfaces=[{".id":"*E",name:"ether1"},{".id":"*E2",name:"ether2"},{".id":"*PPP",name:"pppoe-out1"}]
|
|
const route={".id":"*R","dst-address":"0.0.0.0/0",active:"true","routing-table":"main","immediate-gw":"192.0.2.1%ether1"}
|
|
assert.equal(selectIpsecNatInterface([route,{...route,".id":"*R2"}],interfaces),"ether1")
|
|
assert.equal(selectIpsecNatInterface([{...route,"immediate-gw":"pppoe-out1"}],interfaces),"pppoe-out1")
|
|
for(const routes of [[],[{...route,active:"false"}],[{...route,"routing-table":"other"}],[route,{...route,"immediate-gw":"192.0.2.2%ether2"}]])assert.throws(()=>selectIpsecNatInterface(routes,interfaces),/однозначно/)
|
|
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(/^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,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")
|
|
|