Files
MikrotikManager/backend/src/modules/mcp/wireguard-revision-acceptance.ts
T
Denozordec d255694cda
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 10m41s
Docker images / frontend-image (push) Successful in 2m13s
Docker images / updater-image (push) Successful in 1m17s
Docker images / netflow-agent-image (push) Successful in 33s
Docker images / backend-image (push) Successful in 1m58s
Docker images / publish-release (push) Successful in 11s
Docker images / notify-webhook (push) Successful in 2s
fix(mcp): исправить проверку зависимостей туннеля на больших таблицах маршрутов
2026-11-22 17:51:05 +07:00

128 lines
13 KiB
TypeScript

import assert from "node:assert/strict"
import { installLoopbackFixtureAgent } from "../../test/loopback-http-agent.js"
import { randomUUID } from "node:crypto"
import { createServer } from "node:http"
import { setTimeout as delay } from "node:timers/promises"
import Fastify from "fastify"
import { serializerCompiler,validatorCompiler } from "@fastify/type-provider-zod"
import { mcpConnectionCreateSchema } from "@mmapp/contracts/mcp"
import { pool } from "../../db/index.js"
import type { AuthUser } from "../../lib/permissions.js"
import { wireguardInterfaceDependencyPaths } from "../../services/wireguard-interface-delete.js"
import { wireguardPublicKey } from "../../services/wireguard-interface-create.js"
import { canonicalWireguardSnapshot } from "../../services/entity-snapshots.js"
import { fingerprintPayload } from "../../services/config-revisions.js"
import wireguardRoutes from "../../routes/wireguard.js"
import { createMcpConnection,authenticateMcpToken,setConnectionStatus } from "./store.js"
import { invokeMcpTool,approvePlan,applyPlan } from "./runtime.js"
import { WIREGUARD_REVISION_RESTORE_SERVICE as service } from "./wireguard-revision-actions.js"
/** Run only from the explicitly authorized, serial, isolated PostgreSQL harness.
* Owns server 149, one connection, and a loopback RouterOS double. No live router. */
export async function acceptWireguardRevisionRestore(actor:AuthUser){
type Rows=Record<string,Record<string,string>[]>
const serverId=149,key=Buffer.alloc(32,91).toString("base64"),peerKey=Buffer.alloc(32,92).toString("base64")
const initial:Rows=Object.fromEntries([...wireguardInterfaceDependencyPaths,"/interface/wireguard","/interface/wireguard/peers","/ip/address","/ipv6/address"].map(path=>[path,[]]))
initial["/interface/wireguard"]=[{".id":"*a",name:"wg-revision",disabled:"false",mtu:"1420","listen-port":"13231","public-key":wireguardPublicKey(key),"private-key":key,opaque:"NEVER_RESTORE_INTERFACE_OPAQUE"}]
initial["/interface"]=[{".id":"*a",name:"wg-revision",type:"wg",disabled:"false"},{".id":"*e",name:"ether1",type:"ether",comment:"NEVER_RESTORE_FOREIGN"}]
initial["/interface/wireguard/peers"]=[{".id":"*b",interface:"wg-revision","public-key":peerKey,"allowed-address":"192.0.2.2/32",disabled:"false","persistent-keepalive":"25s","endpoint-address":"old.example","endpoint-port":"54321",comment:"old",name:"old","client-address":"old","client-dns":"old","client-endpoint":"old","preshared-key":"NEVER_RESTORE_PSK"}]
initial["/ip/address"]=[{".id":"*c",interface:"wg-revision",address:"192.0.2.1/24",disabled:"false",dynamic:"false",comment:"old"}]
const payload=()=>canonicalWireguardSnapshot({interfaces:[{name:"wg-revision",privateKey:"*****",listenPort:13232,mtu:1380,comment:"",disabled:false,address:"2001:db8:149::1/64",innerAddresses:[{address:"2001:db8:149::1/64",disabled:false,advertise:false,noDad:true,comment:""}],peers:[{publicKey:peerKey,allowedAddresses:["2001:db8:149::2/128"],endpointAddress:"",endpointPort:"",persistentKeepalive:null,comment:"",name:"",disabled:false,privateKey:"*****",clientAddress:"",clientDns:"",clientEndpoint:""}]}]})
let rows=structuredClone(initial),commands:string[]=[],mode="normal",nextId=100,reads=0,afterWrite:(()=>Promise<unknown>)|undefined
const reset=()=>{rows=structuredClone(initial);commands=[];mode="normal";afterWrite=undefined}
const router=createServer(async(req,res)=>{
res.setHeader("content-type","application/json")
const [pathname, query] = (req.url ?? "").slice(5).split("?")
const path = decodeURIComponent(pathname)
const selectedRows = () => rows[path].filter(row => !query || (row.dynamic === "true") === query.startsWith("dynamic=true"))
if(req.method==="GET"){reads++;if(!Object.hasOwn(rows,path)){res.statusCode=404;res.end("{}");return}res.end(JSON.stringify(selectedRows()));return}
let raw="";for await(const chunk of req)raw+=chunk
const body=raw?JSON.parse(raw)as Record<string,string>:{},base=["/interface/wireguard/peers","/interface/wireguard","/ip/address","/ipv6/address"].find(p=>path===p||path.startsWith(p+"/"))
if(!base||!["PUT","PATCH","DELETE"].includes(req.method??"")){res.statusCode=400;res.end("{}");return}
commands.push(req.method+" "+path)
const id=path.slice(base.length+1)
if(mode!=="ignored"){
if(req.method==="DELETE"){rows[base]=rows[base].filter(row=>row[".id"]!==id);if(base==="/interface/wireguard")rows["/interface"]=rows["/interface"].filter(row=>row[".id"]!==id)}
else if(req.method==="PATCH"){
const selected=rows[base].find(row=>row[".id"]===id)!;Object.assign(selected,body)
if(base==="/interface/wireguard"){if(body["private-key"])selected["public-key"]=wireguardPublicKey(body["private-key"]);const generic=rows["/interface"].find(row=>row[".id"]===id)!;for(const k of Object.keys(body))if(generic[k]!==undefined)generic[k]=selected[k]}
}else{
const row:Record<string,string>={".id":"*"+(++nextId).toString(16),dynamic:"false",...body}
rows[base].push(row)
if(base==="/interface/wireguard"){row["public-key"]=wireguardPublicKey(body["private-key"]);rows["/interface"].push({".id":row[".id"],name:row.name,type:"wg",disabled:row.disabled})}
}
}
if(mode==="collateral")rows["/interface/wireguard/peers"][0]["preshared-key"]="NEVER_RESTORE_CHANGED_PSK"
if(afterWrite){const hook=afterWrite;afterWrite=undefined;await hook()}
if(mode==="lost"){req.socket.destroy();return}
res.end("{}")
})
await new Promise<void>(resolve=>router.listen(0,"127.0.0.1",resolve))
const closeFixtureAgent=installLoopbackFixtureAgent(router)
const rest=Fastify();rest.setValidatorCompiler(validatorCompiler);rest.setSerializerCompiler(serializerCompiler)
let connectionId:string|undefined,inserted=false
const revisionIds:string[]=[]
const revision=async(value:unknown,section="wireguard",sid=serverId)=>{const id=randomUUID();revisionIds.push(id);await pool.query("INSERT INTO config_revisions(id,server_id,section,source,fingerprint,payload) VALUES($1,$2,$3,'manual',$4,$5::jsonb)",[id,sid,section,fingerprintPayload(value),JSON.stringify(value)]);return id}
const wait=async(id:string)=>{for(let attempt=0;attempt<3000;attempt++){const row=(await pool.query("SELECT state FROM mcp_operations WHERE id=$1",[id])).rows[0];if(row&&!['pending','running'].includes(row.state))return String(row.state);await delay(25)}throw Error("WireGuard revision remains live; never replay")}
try{
assert.equal((await pool.query("SELECT id FROM servers WHERE id=$1",[serverId])).rows.length,0,"WireGuard revision fixture ID must be unused")
await pool.query("INSERT INTO servers(id,name,host,port,use_ssl,password) VALUES($1,'wg-revision','127.0.0.1',$2,false,'NEVER_RESTORE_ENDPOINT')",[serverId,(router.address()as{port:number}).port]);inserted=true
await rest.register(wireguardRoutes,{prefix:"/api"})
const issued=await createMcpConnection(mcpConnectionCreateSchema.parse({name:"WireGuard revision",mode:"approval",expiresAt:new Date(Date.now()+1800000).toISOString(),permissions:["mm:network:write"],scope:{serverIds:[serverId],operationIds:[service,"operations.reconcile"],allowGlobal:false},limits:{callsPerMinute:240,mutationsPerHour:1000}}),actor)
connectionId=issued.connection.id;const principal=await authenticateMcpToken(issued.token)
const prepare=async(revisionId:string)=>{
const plan=await invokeMcpTool(principal,"mm_wireguard_revision_restore_plan",{serverId,revisionId})as{planId:string;state:string}
assert.equal(plan.state,"awaiting-approval");for(const hidden of [key,peerKey,"NEVER_RESTORE_"])assert.ok(!JSON.stringify(plan).includes(hidden));return plan
}
const run=async(planId:string)=>{await approvePlan(planId,actor,true);const idempotency=randomUUID(),op=await applyPlan(principal,planId,idempotency);return{op,idempotency,state:await wait(op.id)}}
for(const bad of [null,{},[],{interfaces:[{}]}]){
const id=await revision(bad),before=reads;await assert.rejects(prepare(id));assert.equal(reads,before)
assert.ok((await rest.inject({method:"POST",url:`/api/wireguard/revisions/${id}/restore`,payload:{serverId}})).statusCode>=400);assert.equal(commands.length,0)
}
const selected=await revision(payload())
for(const fault of ["normal","ignored","collateral","lost"]){
reset();const plan=await prepare(selected);mode=fault;const outcome=await run(plan.planId)
if(outcome.state!==(fault==="normal"?"applied":fault==="lost"?"unknown":"partial")){
const operation=(await pool.query("SELECT state,error_code,result FROM mcp_operations WHERE id=$1",[outcome.op.id])).rows[0]
console.log("WireGuard revision sanitized diagnostic",JSON.stringify({fault,operation,commands,interfaces:rows["/interface/wireguard"].map(row=>({id:row[".id"],name:row.name,disabled:row.disabled,mtu:row.mtu,listenPort:row["listen-port"]})),generic:rows["/interface"].map(row=>({id:row[".id"],name:row.name,disabled:row.disabled})),addresses:{v4:rows["/ip/address"].length,v6:rows["/ipv6/address"].length},peers:rows["/interface/wireguard/peers"].map(row=>({id:row[".id"],disabled:row.disabled,endpointConfigured:!!row["endpoint-address"],keepalive:row["persistent-keepalive"],opaquePskPreserved:row["preshared-key"]==="NEVER_RESTORE_PSK"}))}))
}
assert.equal(outcome.state,fault==="normal"?"applied":fault==="lost"?"unknown":"partial",fault)
assert.equal((await applyPlan(principal,plan.planId,outcome.idempotency)).id,outcome.op.id)
const count=commands.length,reconcile=await invokeMcpTool(principal,"mm_operation_reconcile",{operationId:outcome.op.id})as{automaticRetry:boolean;results:{matchesOriginalState:boolean;matchesDesiredState:boolean}[]}
assert.equal(reconcile.automaticRetry,false);assert.equal(reconcile.results[0].matchesDesiredState,fault==="normal");assert.equal(commands.length,count)
if(fault!=="normal"){
assert.equal(count,1)
const stored=(await pool.query("SELECT result FROM mcp_operations WHERE id=$1",[outcome.op.id])).rows[0].result
assert.equal(stored.confirmedWrites,0,"Top-level service step did not return")
assert.equal(stored.nativeProgress.acknowledgedWrites,fault==="lost"?0:1)
assert.equal(stored.nativeProgress.verifiedCommands,0)
assert.ok(Number.isSafeInteger(stored.nativeProgress.commandCount)&&stored.nativeProgress.commandCount>=1)
assert.equal(stored.nativeProgress.automaticReplay,false)
}
if(fault==="normal"){
assert.equal(rows["/interface/wireguard"][0]["private-key"],key);assert.equal(rows["/interface/wireguard/peers"][0]["preshared-key"],"NEVER_RESTORE_PSK");assert.equal(rows["/interface/wireguard/peers"][0]["endpoint-address"],"");assert.equal(rows["/ip/address"].length,0);assert.equal(rows["/ipv6/address"][0]["no-dad"],"true")
const step=(await pool.query("SELECT intended_state FROM mcp_operation_steps WHERE operation_id=$1 AND step_index=0",[outcome.op.id])).rows[0]
await pool.query("UPDATE mcp_operation_steps SET intended_state=jsonb_set(intended_state,'{input,receiptId}',to_jsonb($2::text)) WHERE operation_id=$1 AND step_index=0",[outcome.op.id,randomUUID()])
assert.equal((await invokeMcpTool(principal,"mm_operation_reconcile",{operationId:outcome.op.id})as{results:{matchesDesiredState:boolean}[]}).results[0].matchesDesiredState,false)
await pool.query("UPDATE mcp_operation_steps SET intended_state=$2::jsonb WHERE operation_id=$1 AND step_index=0",[outcome.op.id,JSON.stringify(step.intended_state)])
}
}
reset();rows["/interface/vlan"].push({".id":"*d",interface:"wg-revision"});await assert.rejects(prepare(selected));assert.equal(commands.length,0)
reset();const history=await prepare(selected)
await pool.query("DELETE FROM config_revisions WHERE server_id=$1 AND source='rollback'",[serverId])
await pool.query("CREATE FUNCTION mcp_wg_revision_history_fixture() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.server_id=149 AND NEW.source='rollback' THEN RAISE EXCEPTION 'fixture history unavailable'; END IF; RETURN NEW; END $$")
try{
await pool.query("CREATE TRIGGER mcp_wg_revision_history_fixture BEFORE INSERT ON config_revisions FOR EACH ROW EXECUTE FUNCTION mcp_wg_revision_history_fixture()")
assert.equal((await run(history.planId)).state,"partial");assert.ok(commands.length>1)
}finally{await pool.query("DROP TRIGGER IF EXISTS mcp_wg_revision_history_fixture ON config_revisions");await pool.query("DROP FUNCTION IF EXISTS mcp_wg_revision_history_fixture()")}
reset();const revoked=await prepare(selected);afterWrite=()=>setConnectionStatus(connectionId!,"revoked",actor);assert.equal((await run(revoked.planId)).state,"unknown");assert.equal(commands.length,1)
console.log("WireGuard revision SQL/loopback: strict REST/MCP revisions, clears/IPv6/private conservation, ignored/collateral/lost ACK, no replay/checkpoint tamper and post-ACK revocation passed")
}finally{
closeFixtureAgent()
await rest.close();await new Promise<void>((resolve,reject)=>router.close(error=>error?reject(error):resolve()))
if(connectionId)await setConnectionStatus(connectionId,"revoked",actor)
if(revisionIds.length)await pool.query("DELETE FROM config_revisions WHERE id=ANY($1::text[])",[revisionIds])
if(inserted){await pool.query("DELETE FROM config_revisions WHERE server_id=$1",[serverId]);await pool.query("DELETE FROM servers WHERE id=$1",[serverId])}
}
}