Files
MikrotikManager/backend/src/modules/mcp/chr-recursive-restore.test.ts
T

120 lines
12 KiB
TypeScript

import assert from "node:assert/strict"
import { randomUUID } from "node:crypto"
import { writeFile } from "node:fs/promises"
import { setTimeout as delay } from "node:timers/promises"
import { pool, closePool } from "../../db/index.js"
import { applySqlMigrations } from "../../db/migrate.js"
import { mcpConnectionCreateSchema } from "@mmapp/contracts/mcp"
import { createMcpConnection, authenticateMcpToken, updateMcpSettings } from "./store.js"
import { invokeMcpTool, approvePlan, applyPlan } from "./runtime.js"
import { readRosSnapshot, routerClient } from "./resources.js"
import { parseRecursiveCatalog } from "../../services/recursive-route-catalog.js"
import { readRecursiveNativeRowsForServer, readRecursiveRoutesForServer } from "../../routes/recursive-routes.js"
import { fingerprintPayload } from "../../services/config-revisions.js"
import type { AuthUser } from "../../lib/permissions.js"
const hosts = (process.env.MMAPP_TEST_CHR_HOSTS ?? "").split(",").map(value => value.trim()).filter(Boolean)
assert.equal(hosts.length, 2); assert.equal(new Set(hosts).size, 2)
assert.ok(hosts.every(host => ["194.226.121.150", "104.165.244.7"].includes(host)))
const ports = process.env.MMAPP_TEST_CHR_TUNNEL_PORTS?.split(",").map(Number)
if (ports) assert.ok(ports.length === hosts.length && ports.every(port => Number.isInteger(port) && port >= 1024 && port <= 65535))
assert.ok(process.env.MMAPP_TEST_CHR_USER && process.env.MMAPP_TEST_CHR_PASSWORD)
const marker = "mcp-test-" + randomUUID().slice(0, 8), tableName = marker + "-rec"
const actor: AuthUser = { id: "chr-recursive-restore-owner", apps: ["mm"], permissions: ["mm:settings:admin", "mm:network:admin", "mm:servers:admin"], expiresAt: Date.now() + 3600000 }
const checks: Record<string, unknown>[] = []
const report = { startedAt: new Date().toISOString(), marker, complete: false, trafficValidation: false, checks, finishedAt: "" }
const save = () => writeFile(new URL("../../../../docs/mcp-chr-recursive-restore-acceptance.json", import.meta.url), JSON.stringify(report, null, 2) + "\n")
try {
await applySqlMigrations(pool)
assert.equal((await pool.query("SELECT count(*)::int AS n FROM servers")).rows[0].n, 0)
await updateMcpSettings({ enabled: true }, actor)
for (const [index, host] of hosts.entries()) await pool.query("INSERT INTO servers(id,name,host,port,use_ssl,username,password) VALUES($1,$2,$3,$4,false,$5,$6)", [index + 1, marker, ports ? "127.0.0.1" : host, ports?.[index] ?? 80, process.env.MMAPP_TEST_CHR_USER, process.env.MMAPP_TEST_CHR_PASSWORD])
const operationIds = ["routing.recursive.revision.restore", "routing.recursive.routes.replace", "routing.recursive.routes.read", "routing.recursive.gateways.read", "ros.routing_table.create", "ros.routing_table.delete", "ros.ipv4_route.create", "ros.ipv4_route.delete"]
const access = await createMcpConnection(mcpConnectionCreateSchema.parse({ name: marker, mode: "approval", expiresAt: new Date(Date.now() + 1800000).toISOString(), permissions: ["mm:network:write", "mm:network:read"], limits: { callsPerMinute: 120, concurrentReads: 4, mutationsPerHour: 100, serversPerPlan: 2, objectsPerPlan: 100 }, scope: { serverIds: [1, 2], operationIds, allowGlobal: false } }), actor)
const principal = await authenticateMcpToken(access.token)
const execute = async (tool: string, input: Record<string, unknown>) => {
const plan = await invokeMcpTool(principal, tool, input) as { planId: string; changes: { before: { observed: { routingTable: string; comment: string }[] }; steps: { input: { routes: { routingTable: string; comment: string; disabled: boolean }[] } }[] } }
if (["mm_recursive_revision_restore_plan", "mm_recursive_routes_replace_plan"].includes(tool)) {
assert.equal(plan.changes.before.observed.length, 1, "Never auto-approve replacement of an unexpected owned set")
assert.ok(plan.changes.before.observed.every(row => row.routingTable === tableName && row.comment === marker))
assert.ok(plan.changes.steps[0].input.routes.every(row => row.routingTable === tableName && row.comment === marker && row.disabled))
}
await approvePlan(plan.planId, actor, true)
const operation = await applyPlan(principal, plan.planId, randomUUID())
for (let attempt = 0; attempt < 100; attempt++) {
const row = (await pool.query("SELECT state,error_code FROM mcp_operations WHERE id=$1", [operation.id])).rows[0]
if (!["pending", "running"].includes(row.state)) {
assert.equal(row.state, "applied", `${tool}: ${row.state}/${row.error_code}`)
return operation.id
}
await delay(300)
}
throw Error("Operation pending; never automatically replay lab writes")
}
for (const [index, host] of hosts.entries()) {
const serverId = index + 1, { server, client } = await routerClient(serverId)
const baseline = await Promise.all(["ipv4_route", "routing_table"].map(resource => readRosSnapshot(serverId, resource)))
assert.equal(parseRecursiveCatalog(await readRecursiveNativeRowsForServer(server)).length, 0, "Lab restore refuses existing owned recursive routes")
assert.ok(!baseline[1].rows.some(row => row.name === tableName))
checks.push({ host, phase: "preflight", baselineFingerprints: baseline.map(({ resource, fingerprint }) => ({ resource, fingerprint })) }); await save()
try {
await execute("mm_routing_table_create_plan", { serverId, fields: { name: tableName, fib: false } })
const table = (await readRosSnapshot(serverId, "routing_table")).rows.find(row => row.name === tableName)
assert.equal(table?.fib, "false")
await execute("mm_ipv4_route_create_plan", { serverId, fields: { "dst-address": `198.18.250.${serverId}/32`, gateway: "192.0.2.1", "routing-table": tableName, distance: 10, scope: 30, "target-scope": 10, "check-gateway": "none", disabled: true, comment: "MikrotikManager:recursive " + marker } })
const owned = parseRecursiveCatalog(await readRecursiveNativeRowsForServer(server))
assert.equal(owned.length, 1); assert.equal(owned[0].routingTable, tableName); assert.equal(owned[0].comment, marker)
const cachedBeforeRestore = await readRecursiveRoutesForServer(server)
assert.equal(cachedBeforeRestore.live, true); assert.equal(cachedBeforeRestore.routes.length, 1)
const logicalId = cachedBeforeRestore.routes[0].id
const payload = [{ ...owned[0], distance: 25, country: "lab-metadata" }], revisionId = randomUUID()
await pool.query("INSERT INTO config_revisions(id,server_id,section,source,fingerprint,payload) VALUES($1,$2,'recursive-routes','apply',$3,$4::jsonb)", [revisionId, serverId, fingerprintPayload(payload), JSON.stringify(payload)])
const restored = await execute("mm_recursive_revision_restore_plan", { serverId, revisionId })
const after = parseRecursiveCatalog(await readRecursiveNativeRowsForServer(server))
assert.equal(after.length, 1); assert.equal(after[0].distance, 25); assert.equal(after[0].disabled, true); assert.notEqual(after[0].id, owned[0].id)
assert.equal((await pool.query("SELECT country FROM recursive_routes WHERE server_id=$1", [serverId])).rows[0].country, "lab-metadata")
checks.push({ host, phase: "restore", operationId: restored, nativeDistance: 25, disabled: true, nativeIdRecreated: true, metadataVerified: true }); await save()
const binding = (await pool.query("INSERT INTO filter_rules(server_id,community,gateway_tunnel_id) VALUES($1,'65000:997',$2) RETURNING id", [serverId, "rec:" + logicalId])).rows[0].id
try {
for (let attempt = 0; attempt < 2; attempt++) {
const live = await readRecursiveRoutesForServer(server)
assert.equal(live.live, true); assert.equal(live.routes[0].id, logicalId); assert.equal(live.routes[0].country, "lab-metadata")
}
const metadataBefore = (await pool.query("SELECT * FROM recursive_routes WHERE server_id=$1", [serverId])).rows
const revisionsBefore = (await pool.query("SELECT * FROM config_revisions WHERE server_id=$1 ORDER BY id", [serverId])).rows
const observed = await invokeMcpTool(principal, "mm_recursive_routes_get", { serverId }) as { routes: { id: string }[]; live: boolean; forwardingVerified: boolean }
assert.equal(observed.live, true); assert.equal(observed.routes[0].id, logicalId); assert.equal(observed.forwardingVerified, false)
await invokeMcpTool(principal, "mm_recursive_gateways_get", { serverId, limit: 1 })
assert.deepEqual((await pool.query("SELECT * FROM recursive_routes WHERE server_id=$1", [serverId])).rows, metadataBefore)
assert.deepEqual((await pool.query("SELECT * FROM config_revisions WHERE server_id=$1 ORDER BY id", [serverId])).rows, revisionsBefore)
assert.equal((await pool.query("SELECT gateway_tunnel_id FROM filter_rules WHERE id=$1", [binding])).rows[0].gateway_tunnel_id, "rec:" + logicalId)
checks.push({ host, phase: "stable-identity-readers", stableLogicalId: true, bindingPreserved: true, observerHasNoMetadataWrites: true, forwardingVerified: false }); await save()
const edited = await execute("mm_recursive_routes_replace_plan", { serverId, routes: [{ ...payload[0], id: logicalId, distance: 30 }] })
const afterEdit = await readRecursiveRoutesForServer(server)
assert.equal(afterEdit.live, true); assert.equal(afterEdit.routes[0].id, logicalId); assert.equal(afterEdit.routes[0].distance, 30); assert.equal(afterEdit.routes[0].disabled, true)
assert.equal((await pool.query("SELECT gateway_tunnel_id FROM filter_rules WHERE id=$1", [binding])).rows[0].gateway_tunnel_id, "rec:" + logicalId)
checks.push({ host, phase: "full-set-edit", operationId: edited, nativeDistance: 30, disabled: true, stableLogicalId: true, bindingPreserved: true, perCommandReadBack: true }); await save()
} finally { await pool.query("DELETE FROM filter_rules WHERE id=$1", [binding]) }
const directCleared = await execute("mm_recursive_routes_replace_plan", { serverId, routes: [], source: "copy" })
assert.equal(parseRecursiveCatalog(await readRecursiveNativeRowsForServer(server)).length, 0)
checks.push({ host, phase: "full-set-empty", operationId: directCleared, ownedSetEmpty: true }); await save()
await execute("mm_ipv4_route_create_plan", { serverId, fields: { "dst-address": `198.18.250.${serverId}/32`, gateway: "192.0.2.1", "routing-table": tableName, distance: 10, scope: 30, "target-scope": 10, "check-gateway": "none", disabled: true, comment: "MikrotikManager:recursive " + marker } })
const emptyRevision = randomUUID()
await pool.query("INSERT INTO config_revisions(id,server_id,section,source,fingerprint,payload) VALUES($1,$2,'recursive-routes','apply',$3,'[]'::jsonb)", [emptyRevision, serverId, fingerprintPayload([])])
const cleared = await execute("mm_recursive_revision_restore_plan", { serverId, revisionId: emptyRevision })
assert.equal(parseRecursiveCatalog(await readRecursiveNativeRowsForServer(server)).length, 0)
checks.push({ host, phase: "empty-revision", operationId: cleared, ownedSetEmpty: true }); await save()
} finally {
const own = (await readRosSnapshot(serverId, "ipv4_route")).rows.filter(row => row["routing-table"] === tableName && row.comment === "MikrotikManager:recursive " + marker)
for (const row of own) await execute("mm_ipv4_route_delete_plan", { serverId, id: row[".id"] })
assert.ok(!(await client.get<Record<string, unknown>[]>("/routing/rule")).some(row => row.table === tableName))
const tables = (await readRosSnapshot(serverId, "routing_table")).rows.filter(row => row.name === tableName)
for (const row of tables) { assert.equal(row.fib, "false"); await execute("mm_routing_table_delete_plan", { serverId, id: row[".id"] }) }
for (const snapshot of baseline) assert.equal((await readRosSnapshot(serverId, snapshot.resource)).fingerprint, snapshot.fingerprint, "Lab baseline changed")
checks.push({ host, phase: "cleanup", baselineRestored: true }); await save()
}
console.log(`✓ CHR ${serverId}: disabled non-FIB recursive restore, native/cache/revision read-back, empty restore and baseline cleanup`)
}
report.complete = true; report.finishedAt = new Date().toISOString(); await save()
} finally { await closePool() }