Compare commits

...
2 Commits
Author SHA1 Message Date
Denozordec 3c06a72349 fix(mcp): снимать свойство встроенного ключа туннеля вместо пустого значения
Docker images / prepare-release (push) Successful in 12s
Docker images / backend-test (push) Successful in 11m44s
Docker images / frontend-image (push) Successful in 5m2s
Docker images / updater-image (push) Successful in 4m40s
Docker images / netflow-agent-image (push) Successful in 34s
Docker images / backend-image (push) Successful in 3m30s
Docker images / publish-release (push) Successful in 13s
Docker images / notify-webhook (push) Successful in 2s
2026-11-30 21:32:41 +07:00
Denozordec ea13365f37 fix(mcp): принимать перечень команд при выполнении плана туннеля
Docker images / prepare-release (push) Successful in 13s
Docker images / backend-test (push) Successful in 11m46s
Docker images / frontend-image (push) Successful in 2m21s
Docker images / updater-image (push) Successful in 41s
Docker images / netflow-agent-image (push) Successful in 38s
Docker images / backend-image (push) Successful in 2m25s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
2026-11-30 20:00:42 +07:00
10 changed files with 116 additions and 46 deletions

No files matched your search

@@ -1,7 +1,7 @@
import assert from "node:assert/strict"
import test from "node:test"
import { greIpsecPaths } from "../../services/gre-ipsec-transport.js"
import { greIke2DefaultProposal, greIke2SideCommands, greIke2StableCatalogues, planGreIke2Side, validateGreIke2Defaults, verifyGreIke2Create, verifyGreIke2Update } from "./gre-ikev2-pair-actions.js"
import { greIke2DefaultProposal, greIke2SideCommands, greIke2StableCatalogues, greIke2StepInput, greIke2StepSchema, planGreIke2Side, validateGreIke2Defaults, verifyGreIke2Create, verifyGreIke2Update } from "./gre-ikev2-pair-actions.js"
import { redact } from "./security.js"
const pair = { endpoints: [
@@ -74,6 +74,19 @@ test("resumes a partial side and changes only the verified old test policy's pro
assert.equal(verifyGreIke2Update(catalogs, after, patch), false)
})
test("the runner can parse the prepared plan after its JSON round trip", () => {
const planned = greIke2StepInput(pair, 0, secret, "source-proof", [
{ path: greIpsecPaths.peer, fields: {} },
{ path: greIpsecPaths.policy, id: "*4", fields: { proposal: "default" } },
])
assert.deepEqual(greIke2StepSchema.parse(JSON.parse(JSON.stringify(planned))), planned)
assert.deepEqual(planned.writes, [
{ path: greIpsecPaths.peer, action: "create" },
{ path: greIpsecPaths.policy, id: "*4", action: "update" },
])
assert.throws(() => greIke2StepSchema.parse({ ...planned, writes: [{ path: greIpsecPaths.proposal, id: "*4", action: "update" }] }))
})
test("requires the new plaintext drop to precede existing rules and preserve every prior object", () => {
const [command] = greIke2SideCommands(pair, 0, secret), before = empty()
before[greIpsecPaths.filter] = [{ ".id": "*A", chain: "input", action: "accept", packets: "19" }]
@@ -22,12 +22,25 @@ const endpoint = z.object({
outerAddress: z.string().refine(value => isIP(value) === 4 && value !== "0.0.0.0", "Требуется фиксированный внешний IPv4"),
}).strict()
const schema = z.object({ endpoints: z.array(endpoint).length(2) }).strict()
const stepSchema = schema.extend({ side: z.union([z.literal(0), z.literal(1)]), ipsecSecret: z.string().regex(/^[a-f0-9]{64}$/), beforeFingerprint: z.string() })
const writePath = z.enum([greIpsecPaths.filter, greIpsecPaths.profile, greIpsecPaths.peer, greIpsecPaths.identity, greIpsecPaths.policy])
export const greIke2StepSchema = schema.extend({
side: z.union([z.literal(0), z.literal(1)]),
ipsecSecret: z.string().regex(/^[a-f0-9]{64}$/),
beforeFingerprint: z.string(),
writes: z.array(z.discriminatedUnion("action", [
z.object({ path: writePath, action: z.literal("create") }).strict(),
z.object({ path: z.literal(greIpsecPaths.policy), action: z.literal("update"), id: z.string().regex(/^\*[a-z0-9]+$/i) }).strict(),
])).max(6),
})
type Pair = z.infer<typeof schema>
type Side = 0 | 1
type Fields = Record<string, string>
type Catalogue = Record<string, Fields[]>
type RouterWrite = { path: string; fields: Fields; id?: string }
export function greIke2StepInput(input: Pair, side: Side, ipsecSecret: string, beforeFingerprint: string, commands: RouterWrite[]) {
const writes = commands.map(({ path, id }) => id ? { path, id, action: "update" } : { path, action: "create" })
return greIke2StepSchema.parse({ endpoints: input.endpoints, side, ipsecSecret, beforeFingerprint, writes })
}
const sides = [0, 1] as const
const paths = Object.values(greIpsecPaths)
const runtimeFields: Readonly<Record<string, ReadonlySet<string>>> = {
@@ -193,14 +206,16 @@ async function readSide(input: Pair, side: Side) {
export function registerGreIke2PairActions(register: typeof add) {
registerMcpService(operation, {
current: async raw => {
const input = stepSchema.parse(raw)
const input = greIke2StepSchema.parse(raw)
return await Promise.all(sides.map(async side => (await readSide(input, side)).proof))
},
execute: async raw => {
const input = stepSchema.parse(raw), side = input.side, state = await readSide(input, side)
const input = greIke2StepSchema.parse(raw), side = input.side, state = await readSide(input, side)
if (state.proof !== input.beforeFingerprint) throw new McpError("STATE_CONFLICT", "GRE или IPsec изменился после подготовки", 409)
const desired = greIke2SideCommands(input, side, input.ipsecSecret)
const commands = planGreIke2Side(input, side, state.catalogs, desired)
const reviewed = greIke2StepInput(input, side, input.ipsecSecret, state.proof, commands).writes
if (fingerprint(reviewed) !== fingerprint(input.writes)) throw new McpError("STATE_CONFLICT", "Подготовленные команды IKEv2 отличаются от плана", 409)
let before = greIke2StableCatalogues(state.catalogs), confirmed = 0, verified = 0
for (const command of commands) {
let dispatched = false
@@ -234,14 +249,14 @@ export function registerGreIke2PairActions(register: typeof add) {
return { verified: true, commandCount: commands.length, afterFingerprint, greEnabled: false, forwardingVerified: false }
},
verify: async (raw, result) => {
const input = stepSchema.parse(raw)
const input = greIke2StepSchema.parse(raw)
const receipt = result as { verified?: boolean; afterFingerprint?: string } | null
return receipt?.verified === true && receipt.afterFingerprint === completedPairProof(input, input.side,
(await readSide(input, input.side)).catalogs, greIke2SideCommands(input, input.side, input.ipsecSecret))
},
})
register(operation, "mm_gre_ikev2_pair_configure_plan", "План настройки отдельного IKEv2 для двух существующих GRE", "network", "mm:network:write", "write", "servers", schema, {
version: 2,
version: 3,
target: raw => target(schema.parse(raw)),
prepare: async raw => {
const input = schema.parse(raw), scope = target(input)
@@ -250,10 +265,9 @@ export function registerGreIke2PairActions(register: typeof add) {
validateGreIke2Defaults(greIke2DefaultProposal(catalogs[0]), greIke2DefaultProposal(catalogs[1]))
const ipsecSecret = pairSecret(input, catalogs)
const changes = sides.map(side => planGreIke2Side(input, side, catalogs[side], greIke2SideCommands(input, side, ipsecSecret)))
const steps = sides.map(side => {
const writes = changes[side].map(command => ({ path: command.path, id: command.id, action: command.id ? "update" : "create" }))
return { kind: "service" as const, service: operation, input: { ...input, side, ipsecSecret, beforeFingerprint: before[side].proof, writes } }
})
const steps = sides.map(side => ({ kind: "service" as const, service: operation,
input: greIke2StepInput(input, side, ipsecSecret, before[side].proof, changes[side]),
}))
const objects = (await Promise.all(before.map(state => greMutationProtectionObjects(Number(state.server.id), state.gre)))).flat()
return { target: scope, objects, snapshots: [], before: before.map(state => state.proof), steps, mutationCost: Math.max(1, changes.flat().length), requiresHuman: true,
warnings: [
@@ -36,11 +36,15 @@ export function registerGreMutationActions(register: typeof add) {
return receipt?.verified===true && fingerprint(await current(input))===receipt.afterFingerprint
}})
register(service,"mm_gre_tunnel_"+operation+"_plan","План "+["создания","изменения","удаления"][index]+" GRE и его внутренних адресов", "network","mm:network:write","write","servers",schemas[index],{
version: operation === "delete" ? 1 : 2,
prepare:async(input,context)=>{
const serverId = Number(input.serverId), {server} = await routerClient(serverId)
let mutation = greMutationSchema.parse({operation,...(operation==="create"?{fields:input.fields}:{...("rosId" in input?{rosId:input.rosId}:{}),...("name" in input?{name:input.name}:{}),...(operation==="update"?{fields:input.fields}:{})})})
const state = await readGreMutationState(server,mutation), target = greTarget(mutation,state)
if (input.ipsecSecretRef && input.clearIpsecSecret) throw new McpError("INVALID_INPUT","Выберите новый PSK или явное удаление",400)
let mutation = greMutationSchema.parse({operation,...(operation==="create"?{fields:input.fields}:{...("rosId" in input?{rosId:input.rosId}:{}),...("name" in input?{name:input.name}:{}),...(operation==="update"?{fields:input.fields}:{})})})
if (mutation.operation === "update" && (input.ipsecSecretRef || input.clearIpsecSecret)) {
mutation = { ...mutation, fields: { ...mutation.fields, ipsecSecret: "" } }
}
const state = await readGreMutationState(server,mutation), target = greTarget(mutation,state)
if (mutation.operation!=="delete" && (input.ipsecSecretRef || input.clearIpsecSecret)) {
const name = mutation.operation==="create"?mutation.fields.name:target?.name
let value = ""
@@ -69,6 +69,7 @@ export function registerGreRevisionActions(register:typeof add){
},
})
register(service,"mm_gre_revision_restore_plan","Восстановить GRE и все статические адреса из ревизии после подтверждения","network","mm:network:write","write","servers",z.object({serverId:z.number().int().positive().safe(),revisionId:z.string().uuid()}).strict(),{
version:2,
prepare:async(input,context)=>{
const req=request(input,context),source=await read(req,context.signal)
const desired=materializeGreRestore(source.revision.desired,source.state),steps=planGreRevisionRestore(desired,source.state)
@@ -34,14 +34,19 @@ const native=createServer(async(req,res)=>{
}
assert.ok(base,"Only typed GRE/address writes allowed")
writes++
if(base==="/interface/gre"&&data["ipsec-secret"]===""&&["yes","true"].includes(data["allow-fast-path"])){
res.statusCode=400;res.end(JSON.stringify({error:400,detail:"failure: cannot enable fastpath together with ipsec yet"}));return
if(base==="/interface/gre"&&data["ipsec-secret"]===""){
res.statusCode=400;res.end(JSON.stringify({error:400,detail:"unexpected empty IPsec secret assignment"}));return
}
const fields=Object.fromEntries(Object.entries(data).map(([k,v])=>[k,v==="yes"?"true":v==="no"?"false":String(v)]))
if(!ignored){
if(req.method==="PUT"){
const row=base==="/interface/gre"?{".id":"*G"+(++nextId),"local-address":"0.0.0.0",mtu:"1476",keepalive:"10s,10",dscp:"inherit",disabled:"false",dynamic:"false",running:"false","clamp-tcp-mss":"true","allow-fast-path":"true","ipsec-secret":"",comment:"",...fields}:{".id":"*A"+(++nextId),disabled:"false",dynamic:"false",invalid:"false",advertise:"false","no-dad":"false","eui-64":"false","from-pool":"",comment:"",...fields}
;(collections[base]??=[]).push(row)
}else if(req.method==="POST"&&path==="/interface/gre/unset"){
assert.equal(data["value-name"],"ipsec-secret")
const row=collections[base].find(r=>r[".id"]===data[".id"])
assert.ok(row)
row["ipsec-secret"]=""
}else if(req.method==="PATCH")Object.assign(collections[base].find(r=>r[".id"]===path.slice(base.length+1))!,fields)
else if(req.method==="DELETE")collections[base]=collections[base].filter(r=>r[".id"]!==path.slice(base.length+1))
else assert.fail("Unsupported native write")
+1 -1
View File
@@ -907,7 +907,7 @@ export function greInterfaceBody(t: GreSnapshotTunnel): Record<string, string> {
"allow-fast-path": t.allowFastPath ? "yes" : "no",
comment: writeGreComment(t.comment, peer),
disabled: rosYesNo(t.disabled),
"ipsec-secret": isHiddenSecret(t.ipsecSecret) ? undefined : t.ipsecSecret,
"ipsec-secret": !t.ipsecSecret || isHiddenSecret(t.ipsecSecret) ? undefined : t.ipsecSecret,
})
}
+18 -1
View File
@@ -27,6 +27,7 @@ function apply(state:GreMutationState,op:RosWriteOp) {
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)
@@ -40,6 +41,10 @@ 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")
@@ -62,7 +67,19 @@ 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.equal(clear[0].op,"patch"); assert.equal("body" in clear[0]&&clear[0].body.comment,""); assert.equal("body" in clear[0]&&clear[0].body["ipsec-secret"],"")
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),/разные/)
+25 -4
View File
@@ -12,6 +12,11 @@ import { greMutationSchema, greTunnelFromBody, type GreMutation } from "./gre-mu
import { assertGreDeleteDependencies, greMutationProblem, greMutationProof, greNativeValue, greStableRows, greTarget, readGreMutationState, type GreMutationState } from "./gre-mutation-state.js"
const same = (a: unknown,b: unknown) => fingerprint(a) === fingerprint(b)
export function greSecretUnsetOp(id: string): RosWriteOp {
return { op: "post", path: "/interface/gre/unset", body: { ".id": id, "value-name": "ipsec-secret" } }
}
export async function recordGreMutationRevision(server:ServerRow){
try{
const revisionRecorded=(await captureAndAppendRevision({serverId:server.id,section:"gre",source:"apply",capture:async()=>{
@@ -61,17 +66,29 @@ export function planGreMutation(server: ServerRow, input: GreMutation, before: G
const ops = planGreRestore({tunnels:[desired]},selected)
if (ops[0]?.op !== "patch") throw greMutationProblem("Не подготовлено изменение GRE")
const body = ops[0].body
if (fields.ipsecSecret === undefined) delete body["ipsec-secret"]
const clearSecret = fields.ipsecSecret === ""
if (!fields.ipsecSecret) delete body["ipsec-secret"]
else body["ipsec-secret"] = fields.ipsecSecret
if (fields.localAddress !== undefined) body["local-address"] = fields.localAddress || "0.0.0.0"
body.comment = fields.comment !== undefined || fields.remoteInnerIp !== undefined ? desired.comment : target.comment ?? ""
if (ops.length === 1 && Object.entries(body).every(([key,value])=>same(greNativeValue(key,target[key]),greNativeValue(key,value)))) throw greMutationProblem("GRE уже имеет запрошенную конфигурацию")
if (!clearSecret && ops.length === 1 && Object.entries(body).every(([key,value])=>same(greNativeValue(key,target[key]),greNativeValue(key,value)))) throw greMutationProblem("GRE уже имеет запрошенную конфигурацию")
body.disabled = "yes"
if (clearSecret) {
// Clear even a configured empty value. RouterOS can create dynamic IKEv1 objects for it.
const path = ops[0].path
ops.unshift(greSecretUnsetOp(live.rosId))
if (!live.disabled) ops.unshift({ op: "patch", path, body: { disabled: "yes" } })
}
if (!desired.disabled) ops.push({op:"patch",path:"/interface/gre/"+live.rosId,body:{disabled:"no"}})
return ops
}
export function verifyGreMutationOp(before: GreMutationState, after: GreMutationState, op: RosWriteOp) {
if (op.op === "post" && op.path === "/interface/gre/unset" && op.body["value-name"] === "ipsec-secret") {
const id = op.body[".id"]
if (after.gre.find(row => row[".id"] === id)?.["ipsec-secret"] !== "") return false
return verifyGreMutationOp(before, after, { op: "patch", path: "/interface/gre/" + id, body: { "ipsec-secret": "" } })
}
const paths = {"/interface/gre":"gre","/ip/address":"ipv4","/ipv6/address":"ipv6"} as const
const path = Object.keys(paths).find(path=>op.path===path||op.path.startsWith(path+"/")) as keyof typeof paths|undefined
if (!path || !["put","patch","delete"].includes(op.op)) return false
@@ -79,8 +96,11 @@ export function verifyGreMutationOp(before: GreMutationState, after: GreMutation
const id = op.path === path ? undefined : decodeURIComponent(op.path.slice(path.length+1))
if (op.op === "put") {
const added = next[key].filter(row=>!prior[key].some(previous=>previous[".id"]===row[".id"]))
if (added.length !== 1 || !same(next[key].filter(row=>row!==added[0]),prior[key]) || !Object.entries(op.body).every(([field,value])=>same(greNativeValue(field,after[key].find(row=>row[".id"]===added[0][".id"])?.[field]),greNativeValue(field,value)))) return false
if (key!=="gre"&&observedBoolean(after[key].find(row=>row[".id"]===added[0][".id"])?.dynamic)!==false) return false
if (added.length !== 1 || !same(next[key].filter(row=>row!==added[0]),prior[key])) return false
const created = after[key].find(row => row[".id"] === added[0][".id"])
const expected = key === "gre" ? { "ipsec-secret": "", ...op.body } : op.body
if (!created || !Object.entries(expected).every(([field,value])=>same(greNativeValue(field,created[field]),greNativeValue(field,value)))) return false
if (key!=="gre"&&observedBoolean(created.dynamic)!==false) return false
// An address on our deliberately disabled GRE can legitimately be invalid.
// This proof confirms configuration, not link/DAD/forwarding readiness.
} else {
@@ -124,6 +144,7 @@ export async function mutateGreTunnel(server: ServerRow, raw: GreMutation, expec
const client = MikrotikClient.fromServer(fresh)
const receipt = await executeGreMutationOps(input,before,ops,{read:()=>readGreMutationState(fresh,input),...(input.operation==="delete"?{validate:(state:GreMutationState)=>{planGreMutation(fresh,input,state)}}:{}),command:op=>{
if (op.op === "put") return client.put(op.path,op.body)
if (op.op === "post") return client.post(op.path,op.body)
const slash = op.path.lastIndexOf("/"), path = op.path.slice(0,slash+1)+encodeURIComponent(op.path.slice(slash+1))
if (op.op === "delete") return client.delete(path)
if (op.op === "patch") return client.patch(path,op.body)
@@ -1,5 +1,5 @@
import assert from "node:assert/strict"
import {validateGreRestoreSnapshot,materializeGreRestore,planGreRevisionRestore,executeGreRevisionSteps,readGreRestoreState,greRestoreWireOp} from "./gre-revision-restore.js"
import {validateGreRestoreSnapshot,materializeGreRestore,planGreRevisionRestore,executeGreRevisionSteps,readGreRestoreState} from "./gre-revision-restore.js"
import {canonicalGreSnapshot,type GreSnapshot,type RosWriteOp} from "./entity-snapshots.js"
import {greDependencyPaths,type GreMutationState} from "./gre-mutation-state.js"
import {mapGreLive} from "./gre-live.js"
@@ -12,13 +12,6 @@ assert.equal(expiredAccess,0)
const empty=():GreMutationState=>({serverConfiguration:"source",restoreProtectionProof:"protections",gre:[],ipv4:[],ipv6:[],dependencies:Object.fromEntries(greDependencyPaths.map(p=>[p,[]])),bindings:[],filters:[]})
const native={".id":"*G",name:"old","local-address":"192.0.2.1","remote-address":"192.0.2.2",mtu:"1476",keepalive:"1m,3",dscp:"inherit",disabled:"false",dynamic:"false",running:"true","clamp-tcp-mss":"true","allow-fast-path":"false","ipsec-secret":" key ",comment:"old-comment","dont-fragment":"yes"}
const wanted=(name:string)=>({name,localAddress:"",remoteAddress:"192.0.2.2",localInnerIp:"",remoteInnerIp:"",innerAddresses:[],comment:"",disabled:false,mtu:1400,keepalive:"0",dscp:"inherit",clampTcpMss:true,allowFastPath:false,ipsecSecret:""})
const defaultCreate:RosWriteOp={op:"put",path:"/interface/gre",body:{name:"gre","ipsec-secret":"","allow-fast-path":"yes"}}
const defaultWire=greRestoreWireOp(defaultCreate,empty())
assert.ok("body"in defaultWire&&!("ipsec-secret"in defaultWire.body));assert.equal(defaultCreate.body["ipsec-secret"],"")
const keyState=empty();keyState.gre=[{...native}]
const clearKey:RosWriteOp={op:"patch",path:"/interface/gre/*G",body:{"ipsec-secret":"","allow-fast-path":"no"}}
assert.equal(greRestoreWireOp(clearKey,keyState),clearKey,"A real key removal must not be silently omitted")
keyState.gre[0]["ipsec-secret"]="";assert.ok("body"in greRestoreWireOp(clearKey,keyState)&&!("ipsec-secret"in(greRestoreWireOp(clearKey,keyState)as{body:Record<string,string>}).body))
const snapshot=(...names:string[])=>canonicalGreSnapshot({tunnels:names.map(wanted)})
let sequence=0
function apply(state:GreMutationState,op:RosWriteOp){
@@ -26,10 +19,11 @@ function apply(state:GreMutationState,op:RosWriteOp){
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(([k,v])=>[k,v==="yes"?"true":v==="no"?"false":v])):{}
if(op.op==="put"){
const added={...(key==="gre"?native:{dynamic:"false",invalid:"false","no-dad":"false","eui-64":"false","from-pool":""}),...body,".id":"*N"+(++sequence)}
const added={...(key==="gre"?{...native,"ipsec-secret":""}:{dynamic:"false",invalid:"false","no-dad":"false","eui-64":"false","from-pool":""}),...body,".id":"*N"+(++sequence)}
next[key].push(added)
if(key==="gre")next.dependencies["/interface"].push({".id":added[".id"],name:added.name,type:"gre"})
}else if(op.op==="patch")Object.assign(next[key].find(r=>r[".id"]===id)!,body)
else if(op.op==="post"&&op.path==="/interface/gre/unset")next.gre.find(r=>r[".id"]===body[".id"])!["ipsec-secret"]=""
else if(op.op==="delete"){
next[key]=next[key].filter(r=>r[".id"]!==id)
if(key==="gre")next.dependencies["/interface"]=next.dependencies["/interface"].filter(r=>r[".id"]!==id)
@@ -74,6 +68,13 @@ assert.deepEqual(state.ipv6.find(r=>r.interface==="ether1"),original.ipv6[0]);as
const firstAddress=commands.findIndex(op=>!op.path.startsWith("/interface/gre")),oldDisable=commands.findIndex(op=>op.path==="/interface/gre/*G"&&"body"in op&&op.body.disabled==="yes")
assert.ok(oldDisable>=0&&oldDisable<firstAddress);assert.ok(commands.slice(-2).every(op=>"body"in op&&op.body.disabled==="no"))
assert.deepEqual(planGreRevisionRestore(fixed,state),[])
assert.ok(commands.every(op=>!("body" in op)||op.body["ipsec-secret"]!==""))
const clearRevision=structuredClone(fixed)
clearRevision.tunnels.find(row=>row.name==="old")!.ipsecSecret=""
commands=[]
assert.equal((await execute(clearRevision)).verified,true)
assert.deepEqual(commands.find(op=>op.op==="post"),{op:"post",path:"/interface/gre/unset",body:{".id":"*G","value-name":"ipsec-secret"}})
assert.ok(commands.every(op=>!("body" in op)||!("ipsec-secret" in op.body)))
const deletion=planGreRevisionRestore({tunnels:[]},original)
assert.deepEqual(deletion[0],{kind:"native",op:{op:"patch",path:"/interface/gre/*G",body:{disabled:"yes"}}})
assert.equal(deletion.at(-1)?.kind,"native");state=structuredClone(original);commands=[]
+11 -17
View File
@@ -9,7 +9,7 @@ import { canonicalGreSnapshot,greAddressKey,greAddressPath,greInterfaceBody,isHi
import { mapGreLive } from "./gre-live.js"
import { greMtuSchema } from "./gre-mutation-input.js"
import { assertGreDeleteDependencies,greMutationProblem,greMutationProof,greNativeValue,readGreMutationState,type GreMutationState } from "./gre-mutation-state.js"
import { verifyGreMutationOp } from "./gre-mutation.js"
import { greSecretUnsetOp, verifyGreMutationOp } from "./gre-mutation.js"
import { observedBoolean } from "./ospf-observed-values.js"
import { MikrotikClient } from "./mikrotik.js"
import { withApplicationMutationLock,withConfigMutationLock } from "./config-mutation-lock.js"
@@ -69,17 +69,6 @@ export function materializeGreRestore(desired:GreSnapshot,before:GreMutationStat
})})
}
export type GreRestoreStep={kind:"native";op:RosWriteOp}|{kind:"enable";name:string}
/** RouterOS treats presence of an empty ipsec-secret as an IPsec write and
* rejects it together with FastPath. Omit a redundant empty assignment on the
* wire only; per-command verification still uses the original expected body. */
export function greRestoreWireOp(op:RosWriteOp,before:GreMutationState):RosWriteOp{
if((op.op!=="put"&&op.op!=="patch")||op.body["ipsec-secret"]!=="")return op
const creating=op.op==="put"&&op.path==="/interface/gre"
const live=op.op==="patch"&&op.path.startsWith("/interface/gre/")?before.gre.find(row=>row[".id"]===decodeURIComponent(op.path.slice("/interface/gre/".length))):undefined
if(!creating&&live?.["ipsec-secret"]!=="")return op
const body={...op.body};delete body["ipsec-secret"]
return{...op,body}
}
export function planGreRevisionRestore(desired:GreSnapshot,before:GreMutationState):GreRestoreStep[]{
const wanted=new Set(desired.tunnels.map(row=>row.name))
for(const live of before.gre){
@@ -95,10 +84,15 @@ export function planGreRevisionRestore(desired:GreSnapshot,before:GreMutationSta
let op=item
if((op.op==="put"&&op.path==="/interface/gre")||(op.op==="patch"&&op.path.startsWith("/interface/gre/"))){
const want=desired.tunnels.find(row=>row.name===("body"in op?op.body.name:undefined))!
const body:Record<string,string>={...op.body,"local-address":want.localAddress||"0.0.0.0",comment:greInterfaceBody(want).comment??"","ipsec-secret":want.ipsecSecret}
const body:Record<string,string>={...op.body,"local-address":want.localAddress||"0.0.0.0",comment:greInterfaceBody(want).comment??""}
const live=before.gre.find(row=>row.name===want.name)
const clearSecret=live&&Boolean(live["ipsec-secret"])&&!want.ipsecSecret
const addressChanges=legacy.some(row=>!row.path.startsWith("/interface/gre")&&("body"in row?row.body.interface===want.name:mapped.addrs.some(a=>a.interfaceName===want.name&&row.path===greAddressPath(a.address)+"/"+a.rosId)))
if(live&&Object.entries(body).every(([key,value])=>same(greNativeValue(key,live[key]),greNativeValue(key,value)))&&!addressChanges)continue
if(live&&!clearSecret&&Object.entries(body).every(([key,value])=>same(greNativeValue(key,live[key]),greNativeValue(key,value)))&&!addressChanges)continue
if(live&&clearSecret){
if(observedBoolean(live.disabled)===false)staging.push({kind:"native",op:{op:"patch",path:op.path,body:{disabled:"yes"}}})
staging.push({kind:"native",op:greSecretUnsetOp(live[".id"])})
}
body.disabled="yes";op={...op,body};if(!want.disabled)enable.add(want.name)
staging.push({kind:"native",op});continue
}
@@ -132,12 +126,12 @@ export async function restoreGreRevision(server:ServerRow,id:string,options:{bef
const desired=options.desired?validateGreRestoreSnapshot(options.desired):materializeGreRestore(revision.desired,before),steps=planGreRevisionRestore(desired,before),client=MikrotikClient.fromServer(server)
const checkRevision=async()=>{if((await readGreRestoreRevision(server.id,id,authorize)).revisionProof!==revision.revisionProof)throw problem("Ревизия изменилась во время GRE restore")}
const receipt=await executeGreRevisionSteps(before,steps,{read:()=>readGreRestoreState(server,authorize,undefined,deadlineAt),authorizeRevision:checkRevision,validate:state=>{planGreRevisionRestore(desired,state)},command:(op,gate)=>{
const wire=greRestoreWireOp(op,before)
const slash=op.path.lastIndexOf("/"),path=op.path.slice(0,slash+1)+encodeURIComponent(op.path.slice(slash+1))
const timeout=Math.max(1,Math.min(op.op==="delete"?10000:15000,deadlineAt-Date.now()))
if(wire.op==="put")return client.put(wire.path,wire.body,timeout,gate)
if(op.op==="put")return client.put(op.path,op.body,timeout,gate)
if(op.op==="post")return client.post(op.path,op.body,timeout,undefined,gate)
if(op.op==="delete")return client.delete(path,timeout,gate)
if(wire.op==="patch")return client.patch(path,wire.body,timeout,gate)
if(op.op==="patch")return client.patch(path,op.body,timeout,gate)
throw problem("Недопустимая команда GRE restore")
}})
const verified=receipt.verified&&planGreRevisionRestore(desired,receipt.after).length===0