126 lines
12 KiB
TypeScript
126 lines
12 KiB
TypeScript
import assert from "node:assert/strict"
|
|
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 ipsecRoutes, { createIpsecRoutes } from "../../routes/ipsec.js"
|
|
import { getEnabledIpsecServerById } from "../../services/ipsec-live.js"
|
|
import { ipsecPeerDeletePaths } from "../../services/ipsec-peer-delete.js"
|
|
import { createMcpConnection, authenticateMcpToken, setConnectionStatus } from "./store.js"
|
|
import { invokeMcpTool, approvePlan, applyPlan } from "./runtime.js"
|
|
|
|
/** Opt-in SQL + loopback HTTP acceptance. Never invokes a real RouterOS or external endpoint. */
|
|
export async function acceptIpsecPeerDeletion(actor: AuthUser) {
|
|
const serverId = 193, baseline: Record<string, Record<string, string>[]> = Object.fromEntries(ipsecPeerDeletePaths.map(path => [path, []]))
|
|
baseline["/ip/ipsec/peer"] = [{ ".id": "*a1", name: "ipsec-proof", disabled: "true", comment: "MikrotikManager:ipsec", opaque: "NEVER_IPSEC_OPAQUE" }, { ".id": "*a2", name: "ipsec-preserved", disabled: "true" }]
|
|
baseline["/ip/ipsec/identity"] = [{ ".id": "*b1", peer: "ipsec-proof", disabled: "true", secret: "NEVER_IPSEC_PSK", "auth-method": "pre-shared-key" }]
|
|
let catalogs = structuredClone(baseline), mode = "normal", deletes = 0, reads = 0, connectionId: string | undefined
|
|
let duringRead: (() => Promise<unknown>) | undefined
|
|
const router = createServer((req, res) => {
|
|
res.setHeader("content-type", "application/json")
|
|
const path = (req.url ?? "").replace(/^\/rest/, "")
|
|
if (req.method === "GET") { reads++; if (duringRead) { const hook = duringRead; duringRead = undefined; void hook().then(() => res.end(JSON.stringify(catalogs[path] ?? [])), () => { res.statusCode = 503; res.end("{}") }); return }; if (mode === "provider-error") { res.statusCode = 400; res.end('{"message":"NEVER_IPSEC_PROVIDER"}'); return }; res.end(JSON.stringify(catalogs[path] ?? [])); return }
|
|
if (req.method === "DELETE" && path === "/ip/ipsec/peer/*a1") {
|
|
deletes++
|
|
if (mode !== "ignored") catalogs["/ip/ipsec/peer"] = catalogs["/ip/ipsec/peer"].filter(row => row[".id"] !== "*a1")
|
|
if (mode === "collateral") catalogs["/ip/ipsec/identity"][0].secret = "changed"
|
|
if (mode === "lost") { req.socket.destroy(); return }
|
|
res.end("{}"); return
|
|
}
|
|
res.statusCode = 400; res.end("{}")
|
|
})
|
|
await new Promise<void>(resolve => router.listen(0, "127.0.0.1", resolve))
|
|
const rest = Fastify(); rest.setValidatorCompiler(validatorCompiler); rest.setSerializerCompiler(serializerCompiler)
|
|
const reset = () => { mode = "normal"; catalogs = structuredClone(baseline) }
|
|
const wait = async (id: string) => { for (const deadline = Date.now() + 140000; Date.now() < deadline;) { const state = (await pool.query("SELECT state FROM mcp_operations WHERE id=$1", [id])).rows[0].state; if (!["pending", "running"].includes(state)) return state; await delay(25) }; throw Error("IPsec operation remains live; never replay") }
|
|
try {
|
|
await pool.query("INSERT INTO servers(id,name,host,port,use_ssl,password) VALUES($1,'ipsec-peer-proof','127.0.0.1',$2,false,'NEVER_IPSEC_ENDPOINT_PASSWORD')", [serverId, (router.address() as { port: number }).port])
|
|
await rest.register(ipsecRoutes, { prefix: "/api" })
|
|
const access = await createMcpConnection(mcpConnectionCreateSchema.parse({ name: "IPsec peer deletion", mode: "approval", expiresAt: new Date(Date.now() + 1800000).toISOString(), permissions: ["mm:network:write", "mm:network:read"], scope: { serverIds: [serverId], operationIds: ["network.ipsec.peers.delete", "ros.ipsec_peer.delete", "operations.reconcile"], allowGlobal: false }, limits: { callsPerMinute: 120, mutationsPerHour: 100 } }), actor)
|
|
connectionId = access.connection.id
|
|
const principal = await authenticateMcpToken(access.token)
|
|
const prepare = async (force = true) => {
|
|
const plan = await invokeMcpTool(principal, "mm_ipsec_peer_remove_plan", { serverId, peerId: "*a1", force }) as { planId: string; state: string }
|
|
assert.equal(plan.state, "awaiting-approval"); assert.ok(!JSON.stringify(plan).includes("NEVER_")); return plan
|
|
}
|
|
const count = reads
|
|
await assert.rejects(invokeMcpTool(principal, "mm_ipsec_peer_remove_plan", { serverId: 1, peerId: "*a1" }))
|
|
await assert.rejects(invokeMcpTool(principal, "mm_ipsec_peer_remove_plan", { serverId, peerId: "ipsec-proof" }))
|
|
assert.equal(reads, count)
|
|
await assert.rejects(prepare(false), /identity/)
|
|
const aliasOnly = await createMcpConnection(mcpConnectionCreateSchema.parse({ name: "Native peer alias without business grant", mode: "approval", expiresAt: new Date(Date.now()+1800000).toISOString(), permissions: ["mm:network:write"], scope: { serverIds: [serverId], operationIds: ["ros.ipsec_peer.delete"], allowGlobal: false } }),actor)
|
|
try {
|
|
const beforeDenied=reads
|
|
await assert.rejects(invokeMcpTool(await authenticateMcpToken(aliasOnly.token),"mm_ipsec_peer_delete_plan",{serverId,id:"*a1"}))
|
|
assert.equal(reads,beforeDenied)
|
|
} finally { await setConnectionStatus(aliasOnly.connection.id,"paused",actor) }
|
|
await assert.rejects(invokeMcpTool(principal,"mm_ipsec_peer_delete_plan",{serverId,id:"*a1"}),/identity/)
|
|
catalogs["/ip/ipsec/identity"]=[]
|
|
const native = await invokeMcpTool(principal,"mm_ipsec_peer_delete_plan",{serverId,id:"*a1"}) as {planId:string}
|
|
await approvePlan(native.planId,actor,true)
|
|
const nativeBefore=deletes
|
|
assert.equal(await wait((await applyPlan(principal,native.planId,randomUUID())).id),"applied")
|
|
assert.equal(deletes,nativeBefore+1)
|
|
reset()
|
|
const blockedBefore=deletes
|
|
const blocked = await rest.inject({ method: "DELETE", url: `/api/ipsec/peers/${serverId}/*a1` }); assert.equal(blocked.statusCode, 409); assert.equal(deletes, blockedBefore)
|
|
for (const fault of ["normal", "ignored", "collateral", "lost"]) {
|
|
reset(); const plan = await prepare(); await approvePlan(plan.planId, actor, true); mode = fault
|
|
const before: number = deletes, key = randomUUID(), operation = await applyPlan(principal, plan.planId, key)
|
|
assert.equal(await wait(operation.id), fault === "normal" ? "applied" : fault === "lost" ? "unknown" : "partial")
|
|
assert.equal(deletes, before + 1)
|
|
assert.equal((await applyPlan(principal, plan.planId, key)).id, operation.id)
|
|
const reconciled = await invokeMcpTool(principal, "mm_operation_reconcile", { operationId: operation.id }) as { automaticRetry: boolean; results: { matchesDesiredState: boolean; configurationMatchesDesiredState: boolean; matchesOriginalState: boolean }[] }
|
|
assert.equal(reconciled.automaticRetry, false); assert.equal(reconciled.results[0].matchesDesiredState, fault === "normal"); assert.equal(reconciled.results[0].configurationMatchesDesiredState, ["normal", "lost"].includes(fault)); assert.equal(reconciled.results[0].matchesOriginalState, fault === "ignored"); assert.equal(deletes, before + 1)
|
|
if (fault === "normal") {
|
|
assert.deepEqual(catalogs["/ip/ipsec/identity"], baseline["/ip/ipsec/identity"])
|
|
const saved = (await pool.query("SELECT step_index,intended_state,result FROM mcp_operation_steps WHERE operation_id=$1", [operation.id])).rows[0]
|
|
for (const tamper of ["history", "intended", "native", "command-count"]) {
|
|
const wrongInput = structuredClone(saved.intended_state), wrongResult = structuredClone(saved.result)
|
|
if (tamper === "history") wrongResult.historyRecorded = false
|
|
if (tamper === "intended") wrongInput.input.force = false
|
|
if (tamper === "native") wrongResult.peerId = "*a2"
|
|
if (tamper === "command-count") wrongResult.completedCommands = 0
|
|
await pool.query("UPDATE mcp_operation_steps SET intended_state=$2::jsonb,result=$3::jsonb WHERE operation_id=$1 AND step_index=$4", [operation.id, JSON.stringify(wrongInput), JSON.stringify(wrongResult), saved.step_index])
|
|
const checked = await invokeMcpTool(principal, "mm_operation_reconcile", { operationId: operation.id }) as typeof reconciled
|
|
assert.equal(checked.results[0].configurationMatchesDesiredState, true); assert.equal(checked.results[0].matchesDesiredState, false); assert.equal(deletes, before + 1)
|
|
await pool.query("UPDATE mcp_operation_steps SET intended_state=$2::jsonb,result=$3::jsonb WHERE operation_id=$1 AND step_index=$4", [operation.id, JSON.stringify(saved.intended_state), JSON.stringify(saved.result), saved.step_index])
|
|
}
|
|
}
|
|
if (fault === "lost") {
|
|
const priorReads: number = reads, priorDeletes: number = deletes
|
|
duringRead = () => setConnectionStatus(access.connection.id, "paused", actor)
|
|
await assert.rejects(invokeMcpTool(principal, "mm_operation_reconcile", { operationId: operation.id }))
|
|
assert.equal(reads, priorReads + 1); assert.equal(deletes, priorDeletes)
|
|
await setConnectionStatus(access.connection.id, "active", actor)
|
|
}
|
|
}
|
|
reset(); const stale = await prepare(); await approvePlan(stale.planId, actor, true); catalogs["/ip/ipsec/identity"][0].secret = "NEVER_IPSEC_DRIFT"
|
|
const beforeStale = deletes; assert.equal(await wait((await applyPlan(principal, stale.planId, randomUUID())).id), "rejected"); assert.equal(deletes, beforeStale)
|
|
reset(); const protection = randomUUID()
|
|
await pool.query("INSERT INTO mcp_protections(id,object_ref,created_by) VALUES($1,$2::jsonb,'integration')", [protection, JSON.stringify({ kind: "ipsec_peer", id: "*a1", serverId, protection: "deny" })])
|
|
await assert.rejects(prepare()); assert.equal((await rest.inject({ method: "DELETE", url: `/api/ipsec/peers/${serverId}/*a1?force=true` })).statusCode, 409)
|
|
await pool.query("DELETE FROM mcp_protections WHERE id=$1", [protection])
|
|
reset(); mode = "provider-error"; await assert.rejects(prepare(), (error: Error) => !error.message.includes("NEVER_"))
|
|
reset(); const success = await rest.inject({ method: "DELETE", url: `/api/ipsec/peers/${serverId}/*a1?force=true` }); assert.equal(success.statusCode, 200); assert.equal(success.json().historyRecorded, true); assert.deepEqual(catalogs["/ip/ipsec/identity"], baseline["/ip/ipsec/identity"])
|
|
reset()
|
|
const historyFailure = Fastify(); historyFailure.setValidatorCompiler(validatorCompiler); historyFailure.setSerializerCompiler(serializerCompiler)
|
|
try {
|
|
await historyFailure.register(createIpsecRoutes({ findServer: getEnabledIpsecServerById, recordRevision: async () => { throw Error("NEVER_HISTORY_PROVIDER") } }), { prefix: "/api" })
|
|
const beforeHistory = deletes, failedHistory = await historyFailure.inject({ method: "DELETE", url: `/api/ipsec/peers/${serverId}/*a1?force=true` })
|
|
assert.equal(failedHistory.statusCode, 502); assert.equal(failedHistory.json().state, "applied"); assert.equal(failedHistory.json().historyRecorded, false); assert.equal(deletes, beforeHistory + 1); assert.ok(!failedHistory.body.includes("NEVER_"))
|
|
} finally { await historyFailure.close() }
|
|
const recorded = JSON.stringify((await pool.query("SELECT result FROM mcp_requests WHERE connection_id=$1", [connectionId])).rows); assert.ok(!recorded.includes("NEVER_"))
|
|
console.log("✓ IPsec peer deletion shared REST/MCP: exact native ID, force noncascade, source/opaque drift, protections, one DELETE, partial/unknown, private proof and no replay")
|
|
} finally {
|
|
if (connectionId) await setConnectionStatus(connectionId, "paused", actor)
|
|
await pool.query("DELETE FROM mcp_protections WHERE object_ref->>'serverId'=$1", [String(serverId)])
|
|
await pool.query("DELETE FROM servers WHERE id=$1", [serverId])
|
|
await rest.close(); router.closeAllConnections(); await new Promise<void>((resolve, reject) => router.close(error => error ? reject(error) : resolve()))
|
|
}
|
|
}
|