Files
MikrotikManager/backend/src/modules/mcp/chr-wireguard-interface-update.ts
T

89 lines
9.1 KiB
TypeScript

import assert from "node:assert/strict"
import { pool } from "../../db/index.js"
import { readWireguardInterfaceUpdateState, planWireguardInterfaceUpdate, projectWireguardInterfaceUpdate } from "../../services/wireguard-interface-update.js"
import { wireguardInterfaceDeleteValue } from "../../services/wireguard-interface-delete.js"
import { wireguardConfigurationRows } from "../../services/wireguard-peer-delete.js"
import { greStableRows } from "../../services/gre-mutation-state.js"
import { fingerprint } from "./security.js"
import { wireguardCreateKey, wireguardPublicKey } from "../../services/wireguard-interface-create.js"
import { readRosSnapshot, routerClient } from "./resources.js"
import { invokeMcpTool } from "./runtime.js"
import type { McpPrincipal } from "./store.js"
/** Owned disabled fixtures: native identity and basic PATCH, never forwarding. */
export async function acceptChrWireguardInterfaceUpdate(marker: string, principal: McpPrincipal, serverIds: number[], execute: (tool: string, args: Record<string, unknown>) => Promise<string>, checks: Record<string, unknown>[], checkpoint: () => Promise<void>) {
assert.match(marker, /^mcp-test-[a-f0-9]{8}$/)
for (const serverId of serverIds) {
const name = `${marker}-wg-patch-${serverId}`, renamed = name + "-renamed"
const { server, client } = await routerClient(serverId)
const baseline = await readWireguardInterfaceUpdateState(server, "*0")
const resources = ["wireguard", "wireguard_peer", "ipv4_address", "ipv6_address"]
const snapshots = await Promise.all(resources.map(resource => readRosSnapshot(serverId, resource)))
assert.ok(snapshots.every(snapshot => !snapshot.rows.some(row => row.name === name || row.name === renamed || row.comment === marker)))
checks.push({ phase: "wg-interface-update-preflight", serverId, privateBaseline: baseline.proof, baselines: snapshots.map(({ resource, fingerprint }) => ({ resource, fingerprint })) }); await checkpoint()
let id: string | undefined
try {
await execute("mm_wireguard_create_plan", { serverId, fields: { name, disabled: true, comment: marker, mtu: 1420 } })
const own = (await readRosSnapshot(serverId, "wireguard")).rows.filter(row => row.name === name && row.comment === marker)
assert.equal(own.length, 1); assert.equal(own[0].disabled, "true"); id = String(own[0][".id"])
const generic = await client.get<Record<string, unknown>[]>("/interface?.proplist=.id,name,type,disabled", 10000, undefined, 1048576)
const match = generic.filter(row => row[".id"] === id || row.name === name)
assert.equal(match.length, 1); assert.equal(match[0][".id"], id); assert.equal(match[0].name, name); assert.equal(match[0].type, "wg")
checks.push({ phase: "wg-interface-nonempty-identity", serverId, nativeId: id, genericId: match[0][".id"], type: match[0].type, disabled: true }); await checkpoint()
const patch = { name: renamed, listenPort: 51901, mtu: 1400, comment: marker + "-updated", disabled: true }
const before = await readWireguardInterfaceUpdateState(server, id)
const commands = planWireguardInterfaceUpdate(before, id, patch)
assert.equal(commands.length, 1)
const expected = projectWireguardInterfaceUpdate(before, commands[0])
let operationId: string
try { operationId = await execute("mm_wireguard_interface_edit_plan", { serverId, interfaceId: id, patch }) }
catch (error) {
const after = await readWireguardInterfaceUpdateState(server, id)
const left = wireguardInterfaceDeleteValue(expected), right = wireguardInterfaceDeleteValue(after)
const sections = Object.keys(left).filter(key => fingerprint(left[key as keyof typeof left]) !== fingerprint(right[key as keyof typeof right]))
const differences: { collection: string; nativeId: string; fields: string[] }[] = []
const permittedFields = new Set(["name", "mtu", "listen-port", "disabled", "comment", "public-key", "private-key", "mac-address", "arp", "arp-timeout", "default-name", "type", "dynamic"])
const compare = (collection: string, a: Record<string, string>[], b: Record<string, string>[]) => {
const old = greStableRows(wireguardConfigurationRows(a)), fresh = greStableRows(wireguardConfigurationRows(b))
for (const nativeId of new Set([...old, ...fresh].map(row => row[".id"]))) {
if (typeof nativeId !== "string" || !/^\*[a-z0-9]+$/i.test(nativeId)) throw new Error("Invalid diagnostic native ID")
const first = old.find(row => row[".id"] === nativeId), second = fresh.find(row => row[".id"] === nativeId)
if (fingerprint(first ?? null) === fingerprint(second ?? null)) continue
const keys = [...new Set([...Object.keys(first ?? {}), ...Object.keys(second ?? {})])].filter(key => first?.[key] !== second?.[key])
differences.push({ collection, nativeId, fields: [...new Set(keys.map(key => permittedFields.has(key) ? key : "opaque-field"))] })
}
}
compare("wireguard", expected.base.interfaces, after.base.interfaces)
for (const path of Object.keys(expected.dependencies)) compare(path, expected.dependencies[path], after.dependencies[path])
const first = expected.base.interfaces.find(row => row[".id"] === id)!, second = after.base.interfaces.find(row => row[".id"] === id)!
const originalKey = wireguardCreateKey.safeParse(first?.["private-key"]), observedKey = wireguardCreateKey.safeParse(second?.["private-key"])
const clamp = (value: string) => { const bytes = Buffer.from(value, "base64"); bytes[0] &= 248; bytes[31] = (bytes[31] & 127) | 64; return bytes }
const keyFacts = { originalPresent: first?.["private-key"] !== undefined, observedPresent: second?.["private-key"] !== undefined, originalValid: originalKey.success, observedValid: observedKey.success, publicIdentityUnchanged: first?.["public-key"] === second?.["public-key"], originalDerivesPublic: originalKey.success && wireguardPublicKey(originalKey.data) === first?.["public-key"], observedDerivesPublic: observedKey.success && wireguardPublicKey(observedKey.data) === second?.["public-key"], clampedScalarsEqual: originalKey.success && observedKey.success && clamp(originalKey.data).equals(clamp(observedKey.data)) }
checks.push({ phase: "wg-interface-update-projection-diagnostic", serverId, sections, differences: differences.slice(0, 100), keyFacts, sourceProofUnchanged: expected.base.serverProof === after.base.serverProof, rawValuesDisclosed: false }); await checkpoint()
throw error
}
let current = (await readRosSnapshot(serverId, "wireguard")).rows.find(row => row[".id"] === id)
assert.ok(current); assert.equal(current.name, renamed); assert.equal(current.comment, marker + "-updated"); assert.equal(Number(current["listen-port"]), 51901); assert.equal(Number(current.mtu), 1400); assert.equal(current.disabled, "true")
const result = (await pool.query("SELECT result FROM mcp_operation_steps WHERE operation_id=$1 AND step_index=0 AND state='verified'", [operationId])).rows[0]?.result
assert.equal(result?.verified, true); assert.equal(result.commandCount, 1); assert.equal(result.completedCommands, 1)
const reconciled = await invokeMcpTool(principal, "mm_operation_reconcile", { operationId }) as { automaticRetry: boolean; results: { matchesDesiredState: boolean }[] }
assert.equal(reconciled.automaticRetry, false); assert.equal(reconciled.results[0]?.matchesDesiredState, true)
await execute("mm_wireguard_update_plan", { serverId, id, fields: { comment: marker, mtu: 1420, disabled: true } })
current = (await readRosSnapshot(serverId, "wireguard")).rows.find(row => row[".id"] === id)
assert.equal(current?.comment, marker); assert.equal(Number(current?.mtu), 1420); assert.equal(current?.name, renamed); assert.equal(current?.disabled, "true")
checks.push({ phase: "wg-interface-update-verified", serverId, operationId, nativeId: id, businessAndNativeAlias: true, fields: ["name", "listenPort", "mtu", "comment", "disabled"], exactVerifiedReconcile: true, fixtureRemainedDisabled: true, forwardingVerified: false, keyRotationVerified: false, addressAndPeerRenameVerified: false }); await checkpoint()
} finally {
// A distinct approved cleanup plan observes current state; never resend an unknown PATCH.
const rows = (await readRosSnapshot(serverId, "wireguard")).rows.filter(row => [name, renamed].includes(String(row.name)) && [marker, marker + "-updated"].includes(String(row.comment)))
assert.ok(rows.length <= 1)
for (const row of rows) {
assert.equal(row.disabled, "true"); if (id !== undefined) assert.equal(row[".id"], id)
await execute("mm_wireguard_delete_plan", { serverId, id: row[".id"] })
}
for (const snapshot of snapshots) assert.equal((await readRosSnapshot(serverId, snapshot.resource)).fingerprint, snapshot.fingerprint)
assert.equal((await readWireguardInterfaceUpdateState(server, "*0")).proof, baseline.proof)
checks.push({ phase: "wg-interface-update-baseline-restored", serverId, fingerprints: snapshots.length, privateProofRestored: true, unknownForwardNotReplayed: true, forwardingVerified: false }); await checkpoint()
}
}
}