import assert from "node:assert/strict" import { greMutationSchema } from "./gre-mutation-input.js" import { planGreMutation, verifyGreMutationOp, executeGreMutationOps } from "./gre-mutation.js" import { assertGreDeleteDependencies, greDependencyPaths, greMutationProof, readGreMutationState, readGrePskValue, type GreMutationState } from "./gre-mutation-state.js" import { pool } from "../db/index.js" import { MikrotikClient } from "./mikrotik.js" import type { ServerRow } from "../modules/servers/repository/servers-repository.js" import type { RosWriteOp } from "./entity-snapshots.js" const server = {id:1,enabled:true} as ServerRow const empty = ():GreMutationState => ({serverConfiguration:"source",gre:[],ipv4:[],ipv6:[],dependencies:Object.fromEntries(greDependencyPaths.map(path=>[path,[]])),bindings:[],filters:[]}) const native = {".id":"*G",name:"own-gre","local-address":"0.0.0.0","remote-address":"192.0.2.2",mtu:"1476",keepalive:"1m,3",dscp:"inherit",disabled:"true",running:"false","clamp-tcp-mss":"true","allow-fast-path":"true","ipsec-secret":"",comment:"opaque network=10.0.0.2/32","dont-fragment":"no"} const hiddenSecretRow={".id":"*G",name:"own-gre"} assert.equal(await readGrePskValue(hiddenSecretRow,async body=>{assert.deepEqual(body,{"show-sensitive":"",".proplist":".id,ipsec-secret",".query":[".id=*G"]});return[{".id":"*G","ipsec-secret":""}]}),"") for(const raw of [[],{},[{".id":"*OTHER","ipsec-secret":"key"}],[{".id":"*G"}],[{".id":"*G","ipsec-secret":"***"}]])await assert.rejects(readGrePskValue(hiddenSecretRow,async()=>raw),/чувствительное/) let capabilityReads=0 assert.equal(await readGrePskValue(hiddenSecretRow,async()=>[],{get:async()=>[],capability:async()=>{capabilityReads++;return"sensitive-role"}}),"");assert.equal(capabilityReads,2) await assert.rejects(readGrePskValue(hiddenSecretRow,async()=>[],{get:async()=>[],capability:async()=>undefined}),/чувствительное/) let changedRole=0 await assert.rejects(readGrePskValue(hiddenSecretRow,async()=>[],{get:async()=>[],capability:async()=>"role-"+(changedRole++)}),/чувствительное/) function apply(state:GreMutationState,op:RosWriteOp) { const next = structuredClone(state), path = ["/interface/gre","/ip/address","/ipv6/address"].find(path=>op.path===path||op.path.startsWith(path+"/"))! const key = path==="/interface/gre"?"gre":path==="/ip/address"?"ipv4":"ipv6", id = op.path.slice(path.length+1) const body = "body" in op ? Object.fromEntries(Object.entries(op.body).map(([key,value])=>[key,value==="yes"?"true":value==="no"?"false":value])) : {} if (op.op === "put") { const row = key==="gre"?{...native,...body,".id":"*C",comment:body.comment??""}:{".id":key==="ipv4"?"*A":"*B",dynamic:"false",invalid:"false","no-dad":"false","eui-64":"false","from-pool":"",...body} next[key].push(row) if (key==="gre") next.dependencies["/interface"].push({".id":"*C",name:row.name,type:"gre"}) } else if (op.op === "patch") Object.assign(next[key].find(row=>row[".id"]===id)!,body) else if (op.op === "post" && op.path === "/interface/gre/unset") next.gre.find(row=>row[".id"]===body[".id"])!["ipsec-secret"] = "" else if (op.op === "delete") { next[key]=next[key].filter(row=>row[".id"]!==id) if (key==="gre") next.dependencies["/interface"]=next.dependencies["/interface"].filter(row=>row[".id"]!==id) } return next } for (const fields of [{name:"x",remoteAddress:"bad"},{name:"x",remoteAddress:"192.0.2.2",mtu:1},{name:"x",remoteAddress:"192.0.2.2",dscp:64},{name:"x",remoteAddress:"192.0.2.2",ipsecSecret:"secret",allowFastPath:true}]) assert.equal(greMutationSchema.safeParse({operation:"create",fields}).success,false) assert.equal(greMutationSchema.safeParse({operation:"update",fields:{}}).success,false) const create = greMutationSchema.parse({operation:"create",fields:{name:"own-gre",remoteAddress:"192.0.2.2",localInnerIp:"198.18.1.1/30",enabled:true}}) let state = empty(), commands = 0 const ops = planGreMutation(server,create,state) assert.equal(ops.length,3); assert.equal(ops[0].op,"put"); assert.equal("body" in ops[0]&&ops[0].body.disabled,"yes"); assert.equal(ops[2].path,"/interface/gre/@created") assert.equal("body" in ops[0] && ops[0].body.mtu, "1476") assert.ok("body" in ops[0] && !("ipsec-secret" in ops[0].body)) const createWithClear = greMutationSchema.parse({operation:"create",fields:{name:"clear-gre",remoteAddress:"192.0.2.2",ipsecSecret:""}}) const createWithClearOp = planGreMutation(server,createWithClear,state)[0] assert.ok("body" in createWithClearOp && !("ipsec-secret" in createWithClearOp.body)) const autoCreate = greMutationSchema.parse({operation:"create",fields:{name:"own-gre",remoteAddress:"192.0.2.2",mtu:"auto"}}) const autoPut = planGreMutation(server,autoCreate,state)[0] assert.equal("body" in autoPut && autoPut.body.mtu, "auto") const receipt = await executeGreMutationOps(create,state,ops,{read:async()=>structuredClone(state),command:async op=>{commands++;state=apply(state,op)}}) assert.equal(receipt.verified,true); assert.equal(receipt.completedCommands,3); assert.equal(state.gre[0].disabled,"false"); assert.equal(state.ipv4[0].interface,"own-gre") const update = greMutationSchema.parse({operation:"update",rosId:"*C",fields:{mtu:1400,localInnerIp:"fd00::1/64"}}) const oldComment = state.gre[0].comment const updateOps = planGreMutation(server,update,state) const updated = await executeGreMutationOps(update,state,updateOps,{read:async()=>structuredClone(state),command:async op=>{commands++;state=apply(state,op)}}) assert.equal(updated.verified,true); assert.equal(state.ipv4.length,0); assert.equal(state.ipv6.length,1); assert.equal(state.gre[0].mtu,"1400"); assert.equal(state.gre[0].comment,oldComment); assert.equal(state.gre[0].disabled,"false") const preserve = empty(); preserve.gre=[{...native}] const autoState = structuredClone(preserve); autoState.gre[0].mtu = "auto" const autoComment = greMutationSchema.parse({operation:"update",rosId:"*G",fields:{comment:"new comment"}}) const autoPatch = planGreMutation(server, autoComment, autoState)[0] assert.equal("body" in autoPatch && autoPatch.body.mtu, "auto") const autoAfter = apply(autoState, autoPatch) assert.ok(verifyGreMutationOp(autoState, autoAfter, autoPatch)) autoAfter.gre[0].mtu = "1476" assert.equal(verifyGreMutationOp(autoState, autoAfter, autoPatch), false) const commentPlan = planGreMutation(server,greMutationSchema.parse({operation:"update",rosId:"*G",fields:{mtu:1400}}),preserve) assert.equal(commentPlan[0].op,"patch"); assert.equal("body" in commentPlan[0]&&commentPlan[0].body.keepalive,"1m,3"); assert.equal("body" in commentPlan[0]&&commentPlan[0].body.comment,native.comment); assert.ok(!("body" in commentPlan[0]&&"ipsec-secret" in commentPlan[0].body)) const clear = planGreMutation(server,greMutationSchema.parse({operation:"update",rosId:"*G",fields:{comment:"",remoteInnerIp:"",localAddress:"",ipsecSecret:""}}),preserve) assert.deepEqual(clear[0],{op:"post",path:"/interface/gre/unset",body:{".id":"*G","value-name":"ipsec-secret"}}) assert.equal(clear[1].op,"patch"); assert.equal("body" in clear[1]&&clear[1].body.comment,""); assert.ok("body" in clear[1]&&!("ipsec-secret" in clear[1].body)) const runningWithKey = structuredClone(preserve) Object.assign(runningWithKey.gre[0], {disabled:"false","ipsec-secret":"fixture-key","allow-fast-path":"false"}) const clearRunning = greMutationSchema.parse({operation:"update",rosId:"*G",fields:{ipsecSecret:"",allowFastPath:true}}) const clearRunningOps = planGreMutation(server,clearRunning,runningWithKey) assert.deepEqual(clearRunningOps.map(op=>op.op),["patch","post","patch","patch"]) assert.equal(verifyGreMutationOp(runningWithKey,runningWithKey,clearRunningOps[1]),false) let afterClear = runningWithKey const cleared = await executeGreMutationOps(clearRunning,runningWithKey,clearRunningOps,{read:async()=>afterClear,command:async op=>{afterClear=apply(afterClear,op)}}) assert.equal(cleared.verified,true) assert.equal(afterClear.gre[0]["ipsec-secret"],"") assert.equal(afterClear.gre[0].disabled,"false") const collision = empty(); collision.dependencies["/interface"]=[{".id":"*E",name:"own-gre",type:"ether"}] assert.throws(()=>planGreMutation(server,create,collision),/используется/) assert.throws(()=>planGreMutation(server,greMutationSchema.parse({operation:"delete",rosId:"*G",name:"different"}),preserve),/разные/) for(const dependency of ["/interface/vlan","/routing/ospf/interface-template","/routing/bfd/configuration","/routing/bgp/connection","/ip/vrf","/routing/filter/rule","/ip/route"]) { const referenced = structuredClone(preserve); referenced.dependencies[dependency]=[{".id":"*D",interface:"own-gre"}] assert.throws(()=>assertGreDeleteDependencies(referenced,native),/используется/) } const bound = structuredClone(preserve); bound.bindings=[{id:"user-binding",interfaceName:"own-gre"}]; assert.throws(()=>assertGreDeleteDependencies(bound,native),/привязкой/) const opaque = structuredClone(preserve); opaque.gre[0]["dont-fragment"]="yes"; assert.notDeepEqual(greMutationProof(opaque),greMutationProof(preserve)) const hiddenPsk=structuredClone(preserve);delete hiddenPsk.gre[0]["ipsec-secret"] assert.ok(planGreMutation(server,greMutationSchema.parse({operation:"update",rosId:"*G",fields:{mtu:1400}}),hiddenPsk).length>0) assert.throws(()=>planGreMutation(server,greMutationSchema.parse({operation:"update",rosId:"*G",fields:{allowFastPath:true}}),hiddenPsk),/PSK/) const unknownTimer=structuredClone(preserve);unknownTimer.gre[0].keepalive="unverified" assert.throws(()=>planGreMutation(server,greMutationSchema.parse({operation:"update",rosId:"*G",fields:{keepaliveRetries:5}}),unknownTimer),/таймер/) const dynamicAddress=structuredClone(preserve);dynamicAddress.ipv4=[{".id":"*DHCP",address:"192.0.2.1/24",interface:"own-gre",dynamic:"true",disabled:"false"}] assert.throws(()=>planGreMutation(server,greMutationSchema.parse({operation:"delete",rosId:"*G"}),dynamicAddress),/динамический/) const stagedAddress=empty();stagedAddress.gre=[{...native}] const putAddress:RosWriteOp={op:"put",path:"/ip/address",body:{interface:"own-gre",address:"198.18.1.1/30",disabled:"no"}} const invalidOnDisabled=apply(stagedAddress,putAddress);invalidOnDisabled.ipv4[0].invalid="true" assert.equal(verifyGreMutationOp(stagedAddress,invalidOnDisabled,putAddress),true) invalidOnDisabled.ipv4[0].dynamic="true";assert.equal(verifyGreMutationOp(stagedAddress,invalidOnDisabled,putAddress),false) const changed = apply(preserve,{op:"patch",path:"/interface/gre/*G",body:{mtu:"1400"}}) assert.equal(verifyGreMutationOp(preserve,changed,{op:"patch",path:"/interface/gre/*G",body:{mtu:"1400"}}),true) changed.gre[0]["dont-fragment"]="yes"; assert.equal(verifyGreMutationOp(preserve,changed,{op:"patch",path:"/interface/gre/*G",body:{mtu:"1400"}}),false) const dynamic = structuredClone(preserve); dynamic.ipv6=[{".id":"*LL",address:"fe80::1/64",interface:"own-gre",dynamic:"true"}]; assert.deepEqual(greMutationProof(dynamic),greMutationProof(preserve)) state=empty();commands=0 const ignored = await executeGreMutationOps(create,state,ops,{read:async()=>structuredClone(state),command:async op=>{commands++;if(commands===1)state=apply(state,op)}}) assert.equal(ignored.verified,false); assert.equal(ignored.completedCommands,1); assert.equal(commands,2); assert.equal(state.gre[0].disabled,"true") state=empty();commands=0 await assert.rejects(executeGreMutationOps(create,state,ops,{read:async()=>structuredClone(state),command:async op=>{commands++;state=apply(state,op);throw new Error("lost reply")}}),/lost reply/) assert.equal(commands,1); assert.equal(state.gre[0].disabled,"true") const deletion = greMutationSchema.parse({operation:"delete",name:"own-gre"}) const deleteOps = planGreMutation(server,deletion,state) assert.equal(deleteOps.at(-1)?.path,"/interface/gre/*C") const originalClient = MikrotikClient.fromServer, originalQuery = pool.query const routeRequests: string[] = [] const configured = { ".id": "*S", static: "true", dynamic: "false" } const learned = Array.from({ length: 25_626 }, (_, i) => ({ ".id": `*${(i + 100).toString(16)}`, dynamic: "true", bgp: "true" })) let ignoresFilter = false MikrotikClient.fromServer = (() => ({ async get(path: string) { if (!/^\/(?:ip|ipv6)\/route(?:\?|$)/.test(path)) return [] routeRequests.push(path) if (path.endsWith("?static=true")) return ignoresFilter ? [configured, learned[0]] : [configured] return [configured, ...learned] }, async post() { throw new Error("Unexpected native read in route catalogue test") }, })) as unknown as typeof MikrotikClient.fromServer pool.query = (async () => ({ rows: [] })) as unknown as typeof pool.query try { const configuredPaths = ["/ip/route?static=true", "/ipv6/route?static=true"] for (const input of [create, greMutationSchema.parse({ operation: "update", name: "test-gre", fields: { enabled: true } })]) { routeRequests.length = 0 const snapshot = await readGreMutationState(server, input) assert.deepEqual(routeRequests.sort(), configuredPaths.sort()) assert.deepEqual(snapshot.dependencies["/ip/route"], [configured]) } ignoresFilter = true await assert.rejects(readGreMutationState(server, create), /вне запрошенного фильтра GRE/) routeRequests.length = 0 await assert.rejects(readGreMutationState(server, deletion), /каталог зависимостей GRE/) assert.deepEqual(routeRequests.sort(), ["/ip/route", "/ipv6/route"].sort()) } finally { MikrotikClient.fromServer = originalClient pool.query = originalQuery } console.log("GRE mutations: disabled staging, v4→v6 primary replacement, opaque/timer/secret preservation, native identity, parent/application dependencies, link-local exclusion, per-command proof and ignored/lost stop")