Проверено пробами на стенде RouterOS 7.24.5: /certificate не принимает comment, sign и export-certificate адресуются только по .id и не принимают name и days-valid, подпись меняет authority и digest-algorithm, peer с address 0.0.0.0/0 возвращается без address, id файлов имеют вид **<base62>. Сертификаты продукта опознаются по имени и цепочке подписи, версии операций повышены (init 5, user_create 3, экспорт 2). Стабы приёмки отказывают как RouterOS 7.24. Генеральная репетиция на CHR: init 13 и PSK-клиент 2 команды сошлись с проекцией продукта, туннель, ping 10/10, рост SA, сверка 66/66. Co-Authored-By: Claude Opus 5.5 <[email protected]>
154 lines
17 KiB
TypeScript
154 lines
17 KiB
TypeScript
import assert from "node:assert/strict"
|
|
import { installLoopbackFixtureAgent } from "../../test/loopback-http-agent.js"
|
|
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 { createIpsecRoutes } from "../../routes/ipsec.js"
|
|
import { ipsecPeerDeletePaths } from "../../services/ipsec-peer-delete.js"
|
|
import { IPSEC_CA_CERT, IPSEC_COMMON_NAME, IPSEC_POLICY_GROUP, IPSEC_SERVER_CERT, ipsecManagedComment } from "../../services/ipsec-config.js"
|
|
import { ipsecExternalPoolDependencyPaths } from "../../services/ipsec-pool-dependencies.js"
|
|
import { MikrotikClient } from "../../services/mikrotik.js"
|
|
import { createMcpConnection, authenticateMcpToken, setConnectionStatus } from "./store.js"
|
|
import { invokeMcpTool, approvePlan, applyPlan } from "./runtime.js"
|
|
|
|
/** Opt-in serial disposable SQL + loopback RouterOS acceptance; no live router. */
|
|
export async function acceptIpsecServerInit(actor: AuthUser) {
|
|
type Row = Record<string, string>
|
|
const serverId = 208, query = pool.query.bind(pool)
|
|
const base: Record<string, Row[]> = { ...Object.fromEntries([...ipsecPeerDeletePaths, ...ipsecExternalPoolDependencyPaths].map(path => [path, []])),
|
|
"/ip/ipsec/profile": [{ ".id": "*foreign", name: "foreign-profile", opaque: "NEVER_FOREIGN_PROFILE" }],
|
|
"/ip/route": [{ ".id": "*route", "dst-address": "0.0.0.0/0", "immediate-gw": "192.0.2.1%ether1", active: "true", opaque: "NEVER_ROUTE" }],
|
|
"/interface": [{ ".id": "*interface", name: "ether1", disabled: "false", opaque: "NEVER_INTERFACE" }],
|
|
}
|
|
let catalogs = structuredClone(base), serial = 0, mode = "normal", connectionId: string | undefined, afterAck: (() => Promise<unknown>) | undefined
|
|
const commands: Array<{ method: string; path: string; fields: Row }> = []
|
|
const originalGet = MikrotikClient.prototype.get, originalPut = MikrotikClient.prototype.put
|
|
const transportFailures: Array<{ method: string; path: string; code: string; causeCode: string; name: string; status?: number; timeout: boolean }> = []
|
|
const requestCounts: Record<string, number> = {}
|
|
const knownCodes = new Set(["EADDRNOTAVAIL", "ENOBUFS", "EACCES", "ECONNRESET", "ECONNABORTED", "ECONNREFUSED", "ETIMEDOUT", "EHOSTUNREACH", "ENETUNREACH", "EPIPE", "EMFILE", "ENFILE", "EADDRINUSE", "EAI_AGAIN", "ENOTFOUND", "ABORT_ERR"])
|
|
const knownPaths = new Set([...ipsecPeerDeletePaths, ...ipsecExternalPoolDependencyPaths, "/ip/route", "/interface"])
|
|
const observeFailure = (method: string, path: string, error: unknown) => {
|
|
const value = error as { code?: unknown; name?: unknown; statusCode?: unknown; message?: unknown; cause?: { code?: unknown } } | null
|
|
transportFailures.push({ method, path: knownPaths.has(path) ? path : "unknown-catalog", code: typeof value?.code === "string" && knownCodes.has(value.code) ? value.code : "UNCLASSIFIED", causeCode: typeof value?.cause?.code === "string" && knownCodes.has(value.cause.code) ? value.cause.code : "UNCLASSIFIED", name: typeof value?.name === "string" && ["Error", "AbortError", "TimeoutError", "MikrotikError", "SyntaxError", "RangeError"].includes(value.name) ? value.name : "unknown-error", ...(typeof value?.statusCode === "number" && Number.isInteger(value.statusCode) && value.statusCode >= 0 && value.statusCode <= 599 ? { status: value.statusCode } : {}), timeout: typeof value?.message === "string" && /timed out after|timeout|aborted due to timeout/i.test(value.message) })
|
|
}
|
|
// Diagnostic wrappers retain the actual production transport and rethrow the
|
|
// exact error. Never serialize provider message/body, credentials or fields.
|
|
MikrotikClient.prototype.get = async function<T>(path: string, timeoutMs?: number, signal?: AbortSignal, maxResponseBytes?: number): Promise<T> {
|
|
requestCounts[`GET ${knownPaths.has(path) ? path : "unknown-catalog"}`] = (requestCounts[`GET ${knownPaths.has(path) ? path : "unknown-catalog"}`] ?? 0) + 1
|
|
try { return await originalGet.call(this, path, timeoutMs, signal, maxResponseBytes) as T } catch (error) { observeFailure("GET", path, error); throw error }
|
|
}
|
|
MikrotikClient.prototype.put = async function<T>(path: string, fields: Row, timeoutMs?: number, beforeDispatch?: () => Promise<unknown>): Promise<T> {
|
|
try { return await originalPut.call(this, path, fields, timeoutMs, beforeDispatch) as T } catch (error) { observeFailure("PUT", path, error); throw error }
|
|
}
|
|
const router = createServer(async (req, res) => {
|
|
const path = decodeURIComponent((req.url ?? "").replace(/^\/rest/, "")); res.setHeader("content-type", "application/json")
|
|
try {
|
|
if (req.method === "GET") { res.end(JSON.stringify(catalogs[path] ?? [])); return }
|
|
let raw = ""; for await (const chunk of req) raw += chunk
|
|
const fields = raw ? JSON.parse(raw) as Row : {}
|
|
commands.push({ method: req.method!, path, fields })
|
|
// RouterOS 7.24 (stand probe 2026-11-21): no `comment` on /certificate; sign and export by `.id` only, no `name`/`days-valid`.
|
|
const refusal = req.method === "PUT" && path === "/certificate" && "comment" in fields ? "unknown parameter comment"
|
|
: path === "/certificate/sign" && ("days-valid" in fields || "name" in fields) ? ("days-valid" in fields ? "unknown parameter days-valid" : "missing =.id=")
|
|
: path === "/certificate/export-certificate" && "name" in fields ? "unknown parameter name" : undefined
|
|
if (refusal) { res.statusCode = 400; res.end(JSON.stringify({ error: 400, message: "Bad Request", detail: refusal })); return }
|
|
let result: Row = {}
|
|
if (mode !== "ignored") {
|
|
if (path === "/certificate/sign") {
|
|
const row = catalogs["/certificate"].find(row => row[".id"] === fields[".id"]); assert(row)
|
|
Object.assign(row, { ...(fields.ca ? { ca: fields.ca } : { authority: "true" }), "digest-algorithm": "sha256", fingerprint: "synthetic-fingerprint", "invalid-before": "2026-01-01", "invalid-after": "2030-01-01", "private-key": "true", "serial-number": "synthetic" })
|
|
} else {
|
|
const catalog = Object.hasOwn(catalogs, path) ? path : Object.keys(catalogs).sort((a, b) => b.length - a.length).find(value => path.startsWith(value + "/")); assert(catalog)
|
|
if (req.method === "PUT") { result = { ".id": `*new${++serial}`, ...fields, "native-default": "NEVER_NATIVE_DEFAULT" }; if (catalog === "/ip/ipsec/peer" && result.address === "0.0.0.0/0") delete result.address; catalogs[catalog].push(result) }
|
|
else if (req.method === "PATCH") { const row = catalogs[catalog].find(row => row[".id"] === path.slice(catalog.length + 1)); assert(row); Object.assign(row, fields); if (catalog === "/ip/ipsec/peer" && row.address === "0.0.0.0/0") delete row.address }
|
|
else throw Error("unexpected mutation")
|
|
}
|
|
}
|
|
if (mode === "collateral") catalogs["/ip/ipsec/profile"][0].opaque = "NEVER_COLLATERAL"
|
|
if (afterAck) { const run = afterAck; afterAck = undefined; await run() }
|
|
if (mode === "lost") { req.socket.destroy(); return }
|
|
if (mode === "missingAck" && req.method === "PUT") result = {}
|
|
res.end(JSON.stringify(result))
|
|
} catch { res.statusCode = 500; res.end('{"error":"NEVER_PROVIDER"}') }
|
|
})
|
|
await new Promise<void>(resolve => router.listen(0, "127.0.0.1", resolve))
|
|
const closeFixtureAgent = installLoopbackFixtureAgent(router)
|
|
const rest = Fastify(); rest.setValidatorCompiler(validatorCompiler); rest.setSerializerCompiler(serializerCompiler)
|
|
const reset = () => { catalogs = structuredClone(base); serial = 0; mode = "normal"; afterAck = undefined; transportFailures.length = 0 }
|
|
const hidden = (value: unknown) => assert(!JSON.stringify(value).includes("NEVER_"), "private fixture data leaked")
|
|
const wait = async (id: string) => { for (const deadline = Date.now() + 140000; Date.now() < deadline;) { const row = (await query("SELECT state,error_code FROM mcp_operations WHERE id=$1", [id])).rows[0]; if (!["pending", "running"].includes(row.state)) return row; await delay(25) }; throw Error("Init remains active; never replay") }
|
|
try {
|
|
assert.equal(Number((await query("SELECT count(*)::text AS n FROM servers WHERE id=$1", [serverId])).rows[0].n), 0)
|
|
await query("INSERT INTO servers(id,name,host,port,use_ssl,password) VALUES($1,'ipsec-init','127.0.0.1',$2,false,'NEVER_ENDPOINT')", [serverId, (router.address() as { port: number }).port])
|
|
await rest.register(createIpsecRoutes(), { prefix: "/api" })
|
|
const access = await createMcpConnection(mcpConnectionCreateSchema.parse({ name: "IPsec init", mode: "autonomous", expiresAt: new Date(Date.now() + 1800000).toISOString(), permissions: ["mm:network:write", "mm:network:read"], scope: { serverIds: [serverId], operationIds: ["network.ipsec.server.init", "operations.reconcile"], allowGlobal: false }, limits: { callsPerMinute: 120, mutationsPerHour: 1000 } }), actor)
|
|
connectionId = access.connection.id
|
|
const principal = await authenticateMcpToken(access.token)
|
|
const request = { serverEndpoint: "vpn.example.test", poolCidr: "10.77.0.0/24", dns: "192.0.2.53", caDaysValid: 3650, serverDaysValid: 900, clientDaysValid: 180, createNatRule: true }
|
|
const prepare = (body: Record<string, unknown> = request) => invokeMcpTool(principal, "mm_ipsec_server_init_plan", { serverId, request: body }) as Promise<{ planId: string; state: string }>
|
|
const apply = async (body: Record<string, unknown> = request) => { const plan = await prepare(body); hidden(plan); assert.equal(plan.state, "awaiting-approval"); await approvePlan(plan.planId, actor, true); const key = randomUUID(), operation = await applyPlan(principal, plan.planId, key); return { plan, key, operation, ...await wait(operation.id) } }
|
|
const receipt = async (id: string) => (await query("SELECT result FROM mcp_operation_steps WHERE operation_id=$1", [id])).rows[0].result
|
|
const normalize = (entries: typeof commands) => entries.map(row => ({ ...row, path: row.path.replace(/\*new\d+/g, "*created") }))
|
|
for (const nat of [false, true]) {
|
|
reset(); const start = commands.length, body = { ...request, createNatRule: nat, serverEndpoint: nat ? request.serverEndpoint : "2001:0DB8:0:0:0:0:0:10" }, result = await apply(body)
|
|
assert.equal(result.state, "applied", JSON.stringify({ result, nativeDispatches: commands.slice(start).map(command => ({ method: command.method, path: command.path, fieldNames: Object.keys(command.fields) })), rowCounts: Object.fromEntries(Object.entries(catalogs).map(([path, rows]) => [path, rows.length])), storedReceipt: await receipt(result.operation.id) })); hidden(result)
|
|
const accepted = normalize(commands.slice(start)), saved = await receipt(result.operation.id); hidden(saved); assert.equal(saved.historyRecorded, true)
|
|
assert.equal(saved.commandCount, nat ? 14 : 13)
|
|
assert.equal(commands.slice(start).find(row => row.method === "PUT" && row.path === "/certificate" && row.fields.name === IPSEC_SERVER_CERT)?.fields["subject-alt-name"], nat ? "DNS:vpn.example.test" : "IP:2001:db8::10")
|
|
assert.equal(commands.slice(start).filter(row => row.path === "/certificate/sign").length, 2)
|
|
assert(!commands.slice(start).some(row => /export|^\/file/.test(row.path)))
|
|
for (const [path, rows] of Object.entries(base)) for (const row of rows) assert.deepEqual(catalogs[path].find(current => current[".id"] === row[".id"]), row)
|
|
const rerunStart = commands.length, rerun = await apply(body); assert.equal(rerun.state, "applied", JSON.stringify(rerun)); assert(!commands.slice(rerunStart).some(row => row.path === "/certificate/sign" || row.method === "PUT"))
|
|
reset(); const restStart = commands.length
|
|
const response = await rest.inject({ method: "POST", url: "/api/ipsec/server/init", payload: { ...body, serverId } }); assert.equal(response.statusCode, 201, JSON.stringify({ response: response.json(), transportFailures, requestCounts, nativeDispatches: commands.slice(restStart).map(row => ({ method: row.method, path: row.path, fieldNames: Object.keys(row.fields) })) }))
|
|
assert.deepEqual(normalize(commands.slice(restStart)), accepted)
|
|
}
|
|
reset(); let start = commands.length
|
|
for (const body of [{ ...request, psk: "NEVER_RAW" }, { ...request, passphrase: "NEVER_RAW" }, { ...request, poolCidr: "invalid" }]) await assert.rejects(prepare(body))
|
|
const invalidEndpoint = { ...request, serverEndpoint: "192.0.2.999" }
|
|
await assert.rejects(prepare(invalidEndpoint), { code: "INVALID_INPUT" })
|
|
assert.equal((await rest.inject({ method: "POST", url: "/api/ipsec/server/init", payload: { ...invalidEndpoint, serverId } })).statusCode, 400)
|
|
const unapproved = await prepare(); await assert.rejects(applyPlan(principal, unapproved.planId, randomUUID())); assert.equal(commands.length, start)
|
|
for (const path of [...ipsecPeerDeletePaths.filter(path => path !== "/ip/ipsec/active-peers"), "/interface", "/ip/route", ...ipsecExternalPoolDependencyPaths]) {
|
|
reset(); const stale = await prepare(); await approvePlan(stale.planId, actor, true)
|
|
catalogs[path].push({ ".id": "*late", name: "late", opaque: "NEVER_LATE" })
|
|
assert.notEqual((await wait((await applyPlan(principal, stale.planId, randomUUID())).id)).state, "applied"); assert.equal(commands.length, start)
|
|
}
|
|
for (const modify of [
|
|
() => catalogs["/certificate"].push({ ".id": "*ca", name: IPSEC_CA_CERT, comment: "foreign" }),
|
|
() => catalogs["/certificate"].push({ ".id": "*ca", name: IPSEC_CA_CERT, comment: ipsecManagedComment("CA") }),
|
|
() => catalogs["/ip/ipsec/profile"].push({ ".id": "*owned", name: IPSEC_COMMON_NAME, dynamic: "true", comment: ipsecManagedComment() }),
|
|
() => catalogs["/ip/ipsec/policy/group"].push({ ".id": "*group", name: IPSEC_POLICY_GROUP }),
|
|
]) { reset(); modify(); await assert.rejects(prepare()); assert.equal(commands.length, start) }
|
|
reset(); const seeded = await apply(); assert.equal(seeded.state, "applied"); const managed = structuredClone(catalogs)
|
|
for (const path of ipsecExternalPoolDependencyPaths) {
|
|
catalogs = structuredClone(managed)
|
|
catalogs[path].push({ ".id": "*allocator", name: "foreign-allocator", [path.startsWith("/ppp/") ? "remote-address" : "address-pool"]: IPSEC_COMMON_NAME })
|
|
const before = commands.length; await assert.rejects(prepare()); assert.equal(commands.length, before)
|
|
}
|
|
for (const fault of ["lost", "ignored", "collateral", "missingAck"]) {
|
|
reset(); mode = fault; start = commands.length; const result = await apply()
|
|
const diagnostic = async () => ({ fault, operation: (await query("SELECT state,error_code,result FROM mcp_operations WHERE id=$1", [result.operation.id])).rows[0], steps: (await query("SELECT step_index,state,result FROM mcp_operation_steps WHERE operation_id=$1 ORDER BY step_index", [result.operation.id])).rows, transportFailures, requestCounts, nativeDispatches: commands.slice(start).map(row => ({ method: row.method, path: row.path, fieldNames: Object.keys(row.fields) })) })
|
|
if (!["partial", "unknown"].includes(result.state) || commands.length !== start + 1) assert.fail(JSON.stringify(await diagnostic()))
|
|
assert.equal(result.error_code, fault === "lost" ? "MUTATION_OUTCOME_UNKNOWN" : "VERIFICATION_FAILED", JSON.stringify(await diagnostic()))
|
|
assert.equal(commands.length, start + 1)
|
|
await applyPlan(principal, result.plan.planId, result.key); assert.equal(commands.length, start + 1)
|
|
const reconciliation = await invokeMcpTool(principal, "mm_operation_reconcile", { operationId: result.operation.id }) as { automaticRetry: boolean; results: { matchesDesiredState: boolean }[] }; assert.equal(reconciliation.automaticRetry, false); assert.equal(reconciliation.results[0].matchesDesiredState, false); assert.equal(commands.length, start + 1)
|
|
}
|
|
reset(); start = commands.length; afterAck = () => setConnectionStatus(connectionId!, "paused", actor)
|
|
const revoked = await apply(); assert(["partial", "unknown"].includes(revoked.state)); assert.equal(commands.length, start + 1)
|
|
for (const table of ["mcp_audit", "mcp_plans", "mcp_operation_steps"]) hidden((await query(table === "mcp_operation_steps" ? "SELECT s.* FROM mcp_operation_steps s JOIN mcp_operations o ON o.id=s.operation_id WHERE o.connection_id=$1" : `SELECT * FROM ${table} WHERE connection_id=$1`, [connectionId])).rows)
|
|
console.log("✓ IPsec init SQL/loopback: full REST parity, NAT on/off, CA/server sign, owned reuse, all-config-catalog stale proofs, foreign/system conflict, lost/ignored/collateral/missing ACK, no replay, grant revocation, private audit")
|
|
} finally {
|
|
closeFixtureAgent()
|
|
MikrotikClient.prototype.get = originalGet; MikrotikClient.prototype.put = originalPut
|
|
if (connectionId) await setConnectionStatus(connectionId, "paused", actor)
|
|
await rest.close(); await query("DELETE FROM servers WHERE id=$1", [serverId]); router.closeAllConnections(); await new Promise<void>(resolve => router.close(() => resolve()))
|
|
}
|
|
}
|