Files
MikrotikManager/backend/src/modules/mcp/ipsec-user-create-acceptance.ts
T

135 lines
17 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 jwt from "@fastify/jwt"
import { serializerCompiler, validatorCompiler } from "@fastify/type-provider-zod"
import { mcpConnectionCreateSchema } from "@mmapp/contracts/mcp"
import { env } from "../../config.js"
import { pool } from "../../db/index.js"
import type { AuthUser } from "../../lib/permissions.js"
import { createIpsecRoutes } from "../../routes/ipsec.js"
import { createMcpRoutes } from "../../routes/mcp.js"
import { getEnabledIpsecServerById } from "../../services/ipsec-live.js"
import { ipsecPeerDeletePaths } from "../../services/ipsec-peer-delete.js"
import { createMcpConnection, authenticateMcpToken, setConnectionStatus } from "./store.js"
import { encryptSecret } from "./security.js"
import { ipsecUserCreateSecretPurpose } from "./ipsec-user-create-actions.js"
import { invokeMcpTool, approvePlan, applyPlan } from "./runtime.js"
/** Opt-in serial disposable SQL/loopback acceptance. All certificate bytes are inert synthetic ASCII. */
export async function acceptIpsecUserCreate(actor: AuthUser) {
type Row = Record<string, string>
const serverId = 206, secretIds: string[] = [], query = pool.query.bind(pool), fakeP12 = "NEVER_SYNTHETIC_PKCS12_BYTES"
const base: Record<string, Row[]> = { ...Object.fromEntries([...ipsecPeerDeletePaths, "/file"].map(path => [path, []])),
"/ip/ipsec/peer": [{ ".id": "*p", name: "ike", "exchange-mode": "ike2", passive: "yes", profile: "profile", comment: "MikrotikManager:ipsec", opaque: "NEVER_PEER" }],
"/ip/ipsec/identity": [{ ".id": "*listener", peer: "ike", "auth-method": "digital-signature", certificate: "ipsec-server", "mode-config": "ipsec-vpn", "policy-template-group": "group", opaque: "NEVER_LISTENER" }],
"/ip/ipsec/mode-config": [{ ".id": "*m", name: "ipsec-vpn", "address-pool": "pool", "static-dns": "192.0.2.53", opaque: "NEVER_MC" }],
"/ip/pool": [{ ".id": "*o", name: "pool", ranges: "192.0.2.1-192.0.2.50" }],
"/ip/ipsec/profile": [{ ".id": "*r", name: "profile", opaque: "NEVER_PROFILE" }],
"/ip/ipsec/policy/group": [{ ".id": "*g", name: "group" }],
"/ip/ipsec/policy": [{ ".id": "*y", group: "group", proposal: "proposal", opaque: "NEVER_POLICY" }],
"/ip/ipsec/proposal": [{ ".id": "*q", name: "proposal" }],
"/certificate": [{ ".id": "*a", name: "ca", "key-usage": "key-cert-sign,crl-sign", authority: "true", "private-key": "true" }, { ".id": "*s", name: "ipsec-server", "common-name": "vpn.example.test", "key-usage": "tls-server", ca: "ca", opaque: "NEVER_SERVER_CERT" }],
"/file": [{ ".id": "*f", name: "foreign.p12", size: "10", opaque: "NEVER_FOREIGN_FILE" }],
}
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 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 : {}
if (path === "/file/get" || path === "/file/print") { res.end(JSON.stringify({ ret: fakeP12 })); return }
commands.push({ method: req.method!, path, fields })
let result: Row = {}
if (mode !== "ignored") {
if (path === "/certificate/sign") {
const row = catalogs["/certificate"].find(row => row.name === fields.name); assert(row)
Object.assign(row, { ca: fields.ca, fingerprint: "synthetic-fingerprint", "invalid-before": "2026-01-01", "invalid-after": "2030-01-01", "private-key": "true", "serial-number": "synthetic" })
} else if (path === "/certificate/export-certificate") catalogs["/file"].push({ ".id": `*new${++serial}`, name: `${fields["file-name"]}.p12`, size: String(Buffer.byteLength(fakeP12)), type: "file" })
else {
const catalog = Object.keys(catalogs).find(value => path === value || path.startsWith(value + "/")); assert(catalog)
if (req.method === "PUT") { result = { ".id": `*new${++serial}`, ...fields, "native-default": "NEVER_NATIVE_DEFAULT" }; 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) }
else if (req.method === "DELETE") catalogs[catalog] = catalogs[catalog].filter(row => row[".id"] !== path.slice(catalog.length + 1))
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 }
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 rest = Fastify(); rest.setValidatorCompiler(validatorCompiler); rest.setSerializerCompiler(serializerCompiler)
const portal = Fastify(); await portal.register(jwt, { secret: env.jwtSecret }); await portal.register(createMcpRoutes(async () => {}), { prefix: "/api" })
const reset = () => { catalogs = structuredClone(base); serial = 0; mode = "normal"; afterAck = undefined }
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("Creation remains active; never replay") }
const secret = async (kind: "psk" | "passphrase", purpose?: string, owner = actor.id) => { const id = randomUUID(); secretIds.push(id); await query("INSERT INTO mcp_secrets(id,purpose,server_id,ciphertext,created_by) VALUES($1,$2,$3,$4,$5)", [id, purpose ?? ipsecUserCreateSecretPurpose(serverId, "Alice", kind), serverId, await encryptSecret(kind === "psk" ? "NEVER_PSK_SECRET" : "NEVER_EXPORT_PASSPHRASE"), owner]); return id }
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-create','127.0.0.1',$2,false,'NEVER_ENDPOINT')", [serverId, (router.address() as { port: number }).port])
await query("INSERT INTO app_users(id,login,name) VALUES('ipsec-create-other-owner','ipsec-create-other-owner','IPsec fixture')")
await rest.register(createIpsecRoutes({ findServer: getEnabledIpsecServerById, recordRevision: async input => { await input.capture(); return { id: "fixture-history" } as never } }), { prefix: "/api" })
const access = await createMcpConnection(mcpConnectionCreateSchema.parse({ name: "IPsec create", mode: "autonomous", expiresAt: new Date(Date.now() + 1800000).toISOString(), permissions: ["mm:network:write", "mm:network:read"], scope: { serverIds: [serverId], operationIds: ["network.ipsec.users.create", "operations.reconcile"], allowGlobal: false }, limits: { callsPerMinute: 120, mutationsPerHour: 1000 } }), actor)
connectionId = access.connection.id
const principal = await authenticateMcpToken(access.token), psk = await secret("psk"), passphrase = await secret("passphrase")
const prepare = (request: Record<string, unknown>) => invokeMcpTool(principal, "mm_ipsec_user_create_plan", { serverId, request }) as Promise<{ planId: string; state: string }>
const apply = async (request: Record<string, unknown>) => { const plan = await prepare(request); 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 token = (id = actor.id, permissions = actor.permissions) => portal.jwt.sign({ sub: id, apps: ["mm"], permissions }, { expiresIn: "1h" })
const headers = { authorization: `Bearer ${token()}` }
const normalize = (entries: typeof commands) => entries.map(row => ({ ...row, path: row.path.replace(/\*new\d+/g, "*created"), fields: Object.fromEntries(Object.entries(row.fields).map(([key, value]) => [key, key === "file-name" ? "export-prefix" : value])) }))
for (const [authMethod, staticIp] of [["pre-shared-key", undefined], ["pre-shared-key", "192.0.2.7"], ["certificate", undefined], ["certificate", "192.0.2.7"]] as const) {
reset(); const start = commands.length, request = { name: "Alice", authMethod, ...(staticIp ? { staticIp } : {}), ...(authMethod === "certificate" ? { daysValid: 365, passphraseSecretRef: passphrase, privateKeyExport: true } : { pskSecretRef: psk, remoteId: "alice.example.test" }) }
const result = await apply(request); assert.equal(result.state, "applied", JSON.stringify(result)); hidden(result)
const accepted = normalize(commands.slice(start)), saved = await receipt(result.operation.id); hidden(saved); assert.equal(saved.historyRecorded, true)
assert.deepEqual(catalogs["/file"], base["/file"]); assert.deepEqual(catalogs["/ip/ipsec/profile"], base["/ip/ipsec/profile"])
for (const [path, rows] of Object.entries(base)) for (const row of rows) assert.deepEqual(catalogs[path].find(current => current[".id"] === row[".id"]), row, `existing raw object changed: ${path}/${row[".id"]}`)
if (authMethod === "certificate") {
assert.equal(saved.humanDownloadOnly, true); assert.equal(saved.ipsecContentReturned, false)
const stored = (await query("SELECT * FROM mcp_artifacts WHERE id=$1", [saved.artifactId])).rows[0]; hidden(stored); assert.equal(stored.access_scope.kind, "ipsec-user-bundle"); assert(stored.expires_at.getTime() <= Date.now() + 900000)
const download = await portal.inject({ url: saved.downloadPath, headers }); assert.equal(download.statusCode, 200, download.body); assert.equal(download.headers["cache-control"], "private, no-store")
const bundle = download.json(); assert.equal(Buffer.from(bundle.contentB64, "base64").toString(), fakeP12); assert.equal(bundle.passphrase, "NEVER_EXPORT_PASSPHRASE")
assert.equal((await portal.inject({ url: saved.downloadPath, headers: { authorization: `Bearer ${token("other-owner")}` } })).statusCode, 403)
assert.equal((await portal.inject({ url: saved.downloadPath, headers: { authorization: `Bearer ${token(actor.id, ["mm:network:read"])}` } })).statusCode, 403)
const listing: { statusCode: number; body: string; json: () => { items: Array<{ id: string; artifactReceipts: Array<{ artifactId: string }> }> } } = await portal.inject({ url: `/api/mcp/operations?connectionId=${connectionId}`, headers }); assert.equal(listing.statusCode, 200, listing.body); hidden(listing.json()); assert(listing.json().items.find((row: { id: string }) => row.id === result.operation.id)!.artifactReceipts.some((row: { artifactId: string }) => row.artifactId === saved.artifactId))
await query("UPDATE mcp_artifacts SET expires_at=now()-interval '1 second' WHERE id=$1", [saved.artifactId]); assert.equal((await portal.inject({ url: saved.downloadPath, headers })).statusCode, 404)
}
reset(); const restStart = commands.length
const response = await rest.inject({ method: "POST", url: "/api/ipsec/users", payload: { serverId, name: "Alice", authMethod, ...(staticIp ? { staticIp } : {}), ...(authMethod === "certificate" ? { daysValid: 365, passphrase: "NEVER_EXPORT_PASSPHRASE" } : { psk: "NEVER_PSK_SECRET", remoteId: "alice.example.test" }) } }); assert.equal(response.statusCode, 201, response.body)
assert.deepEqual(normalize(commands.slice(restStart)), accepted)
}
reset(); const rawStart = commands.length
for (const request of [{ name: "Alice" }, { name: "Alice", authMethod: "pre-shared-key", psk: "NEVER_RAW" }, { name: "Alice", privateKeyExport: true, staticIp: "bad" }]) await assert.rejects(prepare(request))
assert.equal(commands.length, rawStart)
for (const reference of [await secret("psk", "wrong-purpose"), await secret("psk", undefined, "ipsec-create-other-owner"), await secret("psk", ipsecUserCreateSecretPurpose(serverId, "other-client", "psk"))]) await assert.rejects(prepare({ name: "Alice", authMethod: "pre-shared-key", pskSecretRef: reference }))
const wrongServer = await secret("psk"); await query("UPDATE mcp_secrets SET server_id=NULL WHERE id=$1", [wrongServer]); await assert.rejects(prepare({ name: "Alice", authMethod: "pre-shared-key", pskSecretRef: wrongServer }))
reset(); catalogs["/ip/ipsec/mode-config"].push({ ".id": "*foreign", name: "mc-ipsec-alice", address: "192.0.2.8", opaque: "NEVER_FOREIGN_MC" }); catalogs["/ip/ipsec/identity"].push({ ".id": "*consumer", peer: "ike", "auth-method": "pre-shared-key", "mode-config": "*FOREIGN", comment: "other client" })
await assert.rejects(prepare({ name: "Alice", authMethod: "pre-shared-key", pskSecretRef: psk, staticIp: "192.0.2.7" })); assert.equal(commands.length, rawStart)
reset()
const unapproved = await prepare({ name: "Alice", authMethod: "pre-shared-key", pskSecretRef: psk }); await assert.rejects(applyPlan(principal, unapproved.planId, randomUUID())); assert.equal(commands.length, rawStart)
reset(); const stale = await prepare({ name: "Alice", authMethod: "pre-shared-key", pskSecretRef: psk }); await approvePlan(stale.planId, actor, true); catalogs["/ip/ipsec/profile"][0].opaque = "NEVER_LATE"; assert.notEqual((await wait((await applyPlan(principal, stale.planId, randomUUID())).id)).state, "applied"); assert.equal(commands.length, rawStart)
for (const fault of ["lost", "ignored", "collateral"]) {
reset(); mode = fault; const start = commands.length, result = await apply({ name: "Alice", authMethod: "pre-shared-key", pskSecretRef: psk, staticIp: "192.0.2.7" }); assert(["partial", "unknown"].includes(result.state)); 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(); const revoked = await secret("psk"), start = commands.length; afterAck = () => query("DELETE FROM mcp_secrets WHERE id=$1", [revoked])
const result = await apply({ name: "Alice", authMethod: "pre-shared-key", pskSecretRef: revoked, staticIp: "192.0.2.7" }); assert(["partial", "unknown"].includes(result.state)); assert.equal(commands.length, start + 1)
reset(); const cert = await apply({ name: "Alice", privateKeyExport: true, passphraseSecretRef: passphrase }), saved = await receipt(cert.operation.id)
await setConnectionStatus(connectionId, "paused", actor)
assert.notEqual((await portal.inject({ url: saved.downloadPath, headers })).statusCode, 200)
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 create SQL/loopback: all REST modes, cert sign/export/cleanup, full raw conservation, purpose/owner/revocation, no replay, encrypted owner portal artifact and TTL")
} finally {
if (connectionId) { await setConnectionStatus(connectionId, "paused", actor); await query("DELETE FROM mcp_artifacts WHERE connection_id=$1", [connectionId]) }
await rest.close(); await portal.close(); await query("DELETE FROM mcp_secrets WHERE id=ANY($1::uuid[])", [secretIds]); await query("DELETE FROM app_users WHERE id='ipsec-create-other-owner'"); await query("DELETE FROM servers WHERE id=$1", [serverId]); router.closeAllConnections(); await new Promise<void>(resolve => router.close(() => resolve()))
}
}