Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 10m41s
Docker images / frontend-image (push) Successful in 2m13s
Docker images / updater-image (push) Successful in 1m17s
Docker images / netflow-agent-image (push) Successful in 33s
Docker images / backend-image (push) Successful in 1m58s
Docker images / publish-release (push) Successful in 11s
Docker images / notify-webhook (push) Successful in 2s
298 lines
28 KiB
TypeScript
298 lines
28 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 { wgImportPreviewSchema, wgImportResponseSchema } from "@mmapp/contracts/wireguard"
|
|
import { pool } from "../../db/index.js"
|
|
import type { AuthUser } from "../../lib/permissions.js"
|
|
import { wireguardInterfaceDependencyPaths } from "../../services/wireguard-interface-delete.js"
|
|
import { wireguardPublicKey } from "../../services/wireguard-interface-create.js"
|
|
import { WIREGUARD_IMPORT_MAX_BYTES } from "../../services/wireguard-import-plan.js"
|
|
import { createMcpConnection, authenticateMcpToken, setConnectionStatus } from "./store.js"
|
|
import { encryptSecret, fingerprint } from "./security.js"
|
|
import { WIREGUARD_IMPORT_CONTENT_PURPOSE } from "./wireguard-import-actions.js"
|
|
import { invokeMcpTool, approvePlan, applyPlan } from "./runtime.js"
|
|
import wireguardRoutes from "../../routes/wireguard.js"
|
|
import { afterConfigurationIntentCommit } from "../../test/fixtures/configuration-audit-commit.js"
|
|
|
|
type Rows = Record<string, Record<string, string>[]>
|
|
/** Explicitly invoked by the isolated SQL acceptance harness. Network traffic
|
|
* is restricted to this loopback RouterOS double; never run against a router. */
|
|
export async function acceptWireguardImport(actor: AuthUser) {
|
|
const key = (byte: number) => Buffer.alloc(32, byte).toString("base64")
|
|
const privateKey = key(71), peerOne = key(72), peerTwo = key(73), generated = key(74)
|
|
const content = `/interface wireguard add name=wg-import private-key="${privateKey}" listen-port=54321 mtu=1300 comment="imported\\nsecond\\tline"\n/ipv6 address add interface=wg-import address=2001:db8:141::1/64 advertise=no\n/interface wireguard peers add interface=wg-import public-key="${peerOne}" allowed-address=192.0.2.2/32 endpoint-address=vpn.example.org endpoint-port=54321 private-key=auto client-address=10.0.0.2 client-dns=1.1.1.1 client-endpoint=vpn.example.org name=first persistent-keepalive=25 comment="first\\r\\npeer"\n/interface wireguard peers add interface=wg-import public-key="${peerTwo}" allowed-address=2001:db8:141::2/128 private-key=none name=second disabled=yes`
|
|
const initial: Rows = Object.fromEntries([...wireguardInterfaceDependencyPaths, "/interface/wireguard", "/interface/wireguard/peers", "/ip/address", "/ipv6/address"].map(path => [path, []]))
|
|
initial["/interface/wireguard"] = [{ ".id": "*f", name: "wg-foreign", disabled: "false", "public-key": wireguardPublicKey(generated), "private-key": "NEVER_IMPORT_FOREIGN_KEY", opaque: "NEVER_IMPORT_FOREIGN_OPAQUE" }]
|
|
initial["/interface"] = [{ ".id": "*f", name: "wg-foreign", type: "wg" }]
|
|
let rows = structuredClone(initial), reads = 0, commands: string[] = [], commandBodies: Record<string, string>[] = [], mode = "normal", number = 0, insertedServers = false
|
|
const reset = () => { rows = structuredClone(initial); commands = []; commandBodies = []; mode = "normal"; number = 0 }
|
|
const assertPublic = (value: unknown) => {
|
|
const text = typeof value === "string" ? value : JSON.stringify(value)
|
|
for (const hidden of [privateKey, peerOne, peerTwo, generated, content, "NEVER_IMPORT_"]) assert.equal(text.includes(hidden), false, "Public response must omit raw imported/native keys and configuration")
|
|
}
|
|
const router = createServer((req, res) => {
|
|
const [pathname, query] = (req.url ?? "").slice(5).split("?")
|
|
const path = decodeURIComponent(pathname)
|
|
const selectedRows = () => rows[path].filter(row => !query || (row.dynamic === "true") === query.startsWith("dynamic=true"))
|
|
res.setHeader("content-type", "application/json")
|
|
if (req.method === "GET") { reads++; if (!Object.hasOwn(rows, path)) { res.statusCode = 404; res.end("{}"); return }; res.end(JSON.stringify(selectedRows())); return }
|
|
if (!["PUT", "PATCH"].includes(req.method ?? "")) { res.statusCode = 400; res.end("{}"); return }
|
|
let raw = ""
|
|
req.on("data", chunk => { raw += chunk }); req.on("end", () => {
|
|
const body = JSON.parse(raw) as Record<string, string>
|
|
commands.push(req.method + " " + path)
|
|
commandBodies.push(structuredClone(body))
|
|
if (mode === "reject" && commands.length === 4) { res.statusCode = 422; res.end('{"message":"fixture reject"}'); return }
|
|
let receipt: Record<string, string> = {}
|
|
if (req.method === "PUT") {
|
|
if (!Object.hasOwn(rows, path)) { res.statusCode = 400; res.end("{}"); return }
|
|
const row: Record<string, string> = { ".id": "*" + (++number).toString(16), ...body, dynamic: "false", opaque: "NEVER_IMPORT_NEW_DEFAULT" }
|
|
if (path === "/interface/wireguard") { Object.assign(row, { "public-key": wireguardPublicKey(privateKey) }); rows["/interface"].push({ ".id": row[".id"], name: row.name, type: "wg" }) }
|
|
if (row["private-key"] === "auto") row["private-key"] = generated
|
|
rows[path].push(row); receipt = { ".id": row[".id"] }
|
|
} else {
|
|
const id = path.split("/").at(-1)!, base = path.slice(0, path.lastIndexOf("/"))
|
|
const row = rows[base]?.find(row => row[".id"] === id)
|
|
if (!row) { res.statusCode = 404; res.end("{}"); return }; Object.assign(row, body)
|
|
if (base === "/interface/wireguard" && row.name === "wg-import" && body.disabled === "false") {
|
|
// Real RouterOS normalizes ignored X25519 bits when enabling the
|
|
// selected interface. Keep the observed public key corroboration.
|
|
const scalar = Buffer.from(row["private-key"], "base64")
|
|
scalar[0] &= 248; scalar[31] = (scalar[31] & 127) | 64
|
|
row["private-key"] = scalar.toString("base64")
|
|
row["public-key"] = wireguardPublicKey(row["private-key"])
|
|
}
|
|
}
|
|
if (mode === "collateral" && commands.length === 3) rows["/interface/wireguard"][0].opaque = "NEVER_IMPORT_CHANGED_FOREIGN"
|
|
if (mode === "lost" && commands.length === 4) { req.socket.destroy(); return }
|
|
res.end(JSON.stringify(receipt))
|
|
})
|
|
})
|
|
await new Promise<void>(resolve => router.listen(0, "127.0.0.1", resolve))
|
|
const rest = Fastify(); rest.setValidatorCompiler(validatorCompiler); rest.setSerializerCompiler(serializerCompiler)
|
|
const secretIds: string[] = [], connectionIds: string[] = []
|
|
const secret = async (purpose: string, serverId: number, owner = actor.id, text = content) => {
|
|
const id = randomUUID(); secretIds.push(id)
|
|
await pool.query("INSERT INTO mcp_secrets(id,purpose,server_id,ciphertext,created_by) VALUES($1,$2,$3,$4,$5)", [id, purpose, serverId, await encryptSecret(text), owner]); return id
|
|
}
|
|
const wait = async (id: string) => {
|
|
for (let i = 0; i < 3000; i++) { const row = (await pool.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("WireGuard import remains live; never replay")
|
|
}
|
|
try {
|
|
assert.equal((await pool.query("SELECT id FROM servers WHERE id IN (141,142)")).rows.length, 0, "Import fixture IDs must be unused")
|
|
await pool.query("INSERT INTO servers(id,name,host,port,use_ssl,password) VALUES(141,'wg-import-fixture','127.0.0.1',$1,false,'NEVER_IMPORT_ENDPOINT'),(142,'wg-import-outside','127.0.0.1',$1,false,'NEVER_IMPORT_OUTSIDE')", [(router.address() as { port: number }).port])
|
|
insertedServers = true
|
|
await rest.register(wireguardRoutes, { prefix: "/api" })
|
|
console.log("WireGuard import fixture: local REST/MCP router and owned SQL rows prepared")
|
|
const issued = await createMcpConnection(mcpConnectionCreateSchema.parse({ name: "WireGuard import", mode: "approval", expiresAt: new Date(Date.now() + 1800000).toISOString(), permissions: ["mm:network:write"], scope: { serverIds: [141], operationIds: ["network.wireguard.import.preview", "network.wireguard.import", "operations.reconcile"], allowGlobal: false }, limits: { callsPerMinute: 120, mutationsPerHour: 200 } }), actor)
|
|
connectionIds.push(issued.connection.id)
|
|
const principal = await authenticateMcpToken(issued.token), contentRef = await secret(WIREGUARD_IMPORT_CONTENT_PURPOSE, 141)
|
|
const full = { serverId: 141, contentRef, format: "auto" }
|
|
const prepare = (input: unknown = full) => invokeMcpTool(principal, "mm_wireguard_import_plan", input) as Promise<{ planId: string; state: string; changes: { mutationCost: number; objects: { kind: string; id: string; serverId?: number }[] } }>
|
|
const beforeInvalid = reads
|
|
for (const input of [{ ...full, content }, { ...full, serverId: 142 }, { ...full, format: "script" }]) await assert.rejects(prepare(input))
|
|
for (const ref of [await secret("wrong-purpose", 141), await secret(WIREGUARD_IMPORT_CONTENT_PURPOSE, 142), await secret(WIREGUARD_IMPORT_CONTENT_PURPOSE, 141, "wrong-owner"), await secret(WIREGUARD_IMPORT_CONTENT_PURPOSE, 141, actor.id, "x".repeat(WIREGUARD_IMPORT_MAX_BYTES + 1))]) await assert.rejects(prepare({ ...full, contentRef: ref }))
|
|
assert.equal(reads, beforeInvalid); assert.equal(commands.length, 0)
|
|
const preview = await invokeMcpTool(principal, "mm_wireguard_import_preview", full)
|
|
for (const secret of [privateKey, peerOne, peerTwo]) assert.equal(JSON.stringify(preview).includes(secret), false)
|
|
assert.equal(reads, beforeInvalid, "Parser preview does not read native state")
|
|
const restInput = { serverId: 141, content, format: "auto" }
|
|
const sql = pool.query.bind(pool)
|
|
let invalidSql = 0
|
|
pool.query = ((...args: unknown[]) => { invalidSql++; return (sql as (...args: unknown[]) => unknown)(...args) }) as typeof pool.query
|
|
const readsBeforeInvalidRest = reads
|
|
try {
|
|
for (const serverId of ["", "141x", "141.5", "0", "-1", "9007199254740992", 0, -1, 1.5, null, false]) {
|
|
for (const dryRun of [true, false]) {
|
|
const response = await rest.inject({ method: "POST", url: "/api/wireguard/import", payload: { ...restInput, serverId, dryRun } })
|
|
assert.equal(response.statusCode, 400); assertPublic(response.body)
|
|
}
|
|
}
|
|
assert.equal(invalidSql, 0, "Invalid REST server IDs must be rejected before any SQL")
|
|
} finally { pool.query = sql as typeof pool.query }
|
|
assert.equal(reads, readsBeforeInvalidRest); assert.equal(commands.length, 0)
|
|
const dry = await rest.inject({ method: "POST", url: "/api/wireguard/import", payload: { ...restInput, dryRun: true } })
|
|
assert.equal(dry.statusCode, 200); assertPublic(dry.body)
|
|
const dryBody = wgImportResponseSchema.parse(dry.json())
|
|
assert.equal(dryBody.dryRun, true); assert.equal(dryBody.applied, undefined)
|
|
assert.deepEqual(dryBody.preview.interface, { name: "wg-import", listenPort: 54321, mtu: 1300, comment: "imported\nsecond\tline", address: "2001:db8:141::1/64" })
|
|
assert.equal(dryBody.preview.peers.length, 2)
|
|
assert.deepEqual(dryBody.preview.peers[0], { publicKey: "[KEY]", allowedAddresses: ["192.0.2.2/32"], endpointAddress: "vpn.example.org", endpointPort: 54321, persistentKeepalive: 25, comment: "first\r\npeer", name: "first", clientAddress: "10.0.0.2", clientDns: "1.1.1.1", clientEndpoint: "vpn.example.org" })
|
|
assert.equal(dryBody.preview.peers[1].disabled, true)
|
|
const mcpPreview = (preview as { preview: { peers: Record<string, unknown>[] } }).preview
|
|
assert.deepEqual(dryBody.preview, wgImportPreviewSchema.parse({ ...mcpPreview, peers: mcpPreview.peers.map(peer => ({ ...peer, publicKey: "[KEY]" })) }), "REST retains UI preview shape while carrying the same complete safe metadata")
|
|
assert.equal(reads, readsBeforeInvalidRest); assert.equal(commands.length, 0)
|
|
const failedParse = await rest.inject({ method: "POST", url: "/api/wireguard/import", payload: { ...restInput, content: content + `\n/system script add source="${privateKey}"`, dryRun: false } })
|
|
assert.equal(failedParse.statusCode, 400); assertPublic(failedParse.body)
|
|
assert.equal(reads, readsBeforeInvalidRest)
|
|
reset()
|
|
const appliedRest = await rest.inject({ method: "POST", url: "/api/wireguard/import", payload: restInput })
|
|
assert.equal(appliedRest.statusCode, 200, appliedRest.body); assertPublic(appliedRest.body)
|
|
const appliedRestBody = appliedRest.json() as { dryRun: boolean; preview: unknown; applied: { interfaceName: string; peersCreated: number; verified: boolean; completedCommands: number; commandCount: number } }
|
|
assert.equal(wgImportResponseSchema.safeParse(appliedRestBody).success, true)
|
|
assert.equal(appliedRestBody.dryRun, false); assert.deepEqual(appliedRestBody.preview, dryBody.preview)
|
|
assert.deepEqual(appliedRestBody.applied, { interfaceName: "wg-import", peersCreated: 2, verified: true, completedCommands: 7, commandCount: 7 })
|
|
assert.equal(commands.length, 7)
|
|
assert.deepEqual(commandBodies.slice(0, 4).map(body => body.disabled), ["true", "true", "true", "true"])
|
|
assert.equal(rows["/interface/wireguard"][1].disabled, "false"); assert.equal(rows["/interface/wireguard"][1].comment, "imported\nsecond\tline")
|
|
assert.equal(rows["/interface/wireguard/peers"].length, 2); assert.equal(rows["/interface/wireguard/peers"][0].disabled, "false"); assert.equal(rows["/interface/wireguard/peers"][1].disabled, "true")
|
|
assert.equal(rows["/interface/wireguard/peers"][0].comment, "first\r\npeer")
|
|
assert.equal(rows["/ipv6/address"][0].address, "2001:db8:141::1/64"); assert.equal(rows["/ipv6/address"][0].disabled, "false"); assert.equal(rows["/ipv6/address"][0].advertise, "false")
|
|
assert.equal(fingerprint(rows["/interface/wireguard"][0]), fingerprint(initial["/interface/wireguard"][0]), "Foreign native/opaque properties must survive REST import")
|
|
const restNative = { commands: [...commands], bodyProof: fingerprint(commandBodies) }
|
|
const revisions = (await pool.query("SELECT source,payload FROM config_revisions WHERE server_id=141 AND section='wireguard' ORDER BY created_at DESC,id DESC")).rows
|
|
assert.ok(revisions.length > 0); assert.equal(revisions[0].source, "copy")
|
|
const saved = (revisions[0].payload as { interfaces: { name: string; peers: unknown[]; innerAddresses: { address: string }[] }[] }).interfaces.find(iface => iface.name === "wg-import")
|
|
assert.ok(saved); assert.equal(saved.peers.length, 2); assert.equal(saved.innerAddresses[0].address, "2001:db8:141::1/64")
|
|
for (const fault of ["reject", "lost"]) {
|
|
reset(); mode = fault
|
|
const beforeRevisions = (await pool.query("SELECT count(*)::int AS n FROM config_revisions WHERE server_id=141 AND section='wireguard'")).rows[0].n
|
|
const response = await rest.inject({ method: "POST", url: "/api/wireguard/import", payload: restInput })
|
|
assert.equal(response.statusCode, 502); assertPublic(response.body)
|
|
const failure = response.json() as { state: string; verifiedPrefixCommands: number; commandCount: number; automaticReplay: boolean; preview: unknown }
|
|
assert.equal(failure.state, fault === "reject" ? "partial" : "needs-review"); assert.equal(failure.verifiedPrefixCommands, 3); assert.equal(failure.commandCount, 7); assert.equal(failure.automaticReplay, false)
|
|
assert.deepEqual(failure.preview, dryBody.preview); assert.equal(commands.length, 4)
|
|
assert.equal(rows["/interface/wireguard/peers"].length, fault === "reject" ? 1 : 2)
|
|
assert.equal(rows["/interface/wireguard"][1].disabled, "true"); assert.equal(rows["/ipv6/address"][0].disabled, "true")
|
|
const repeat = await rest.inject({ method: "POST", url: "/api/wireguard/import", payload: restInput })
|
|
assert.notEqual(repeat.statusCode, 200); assertPublic(repeat.body); assert.equal(commands.length, 4, "REST does not automatically replay or clean up a partially created interface")
|
|
assert.equal((await pool.query("SELECT count(*)::int AS n FROM config_revisions WHERE server_id=141 AND section='wireguard'")).rows[0].n, beforeRevisions)
|
|
}
|
|
reset()
|
|
console.log("WireGuard import REST parity: strict IDs before SQL/HTTP, full redacted preview, seven shared stages/two peers/IPv6, copy revision, partial/unknown no replay")
|
|
const limited = await createMcpConnection(mcpConnectionCreateSchema.parse({ name: "WireGuard import object budget", mode: "approval", expiresAt: new Date(Date.now() + 1800000).toISOString(), permissions: ["mm:network:write"], scope: { serverIds: [141], operationIds: ["network.wireguard.import"], allowGlobal: false }, limits: { callsPerMinute: 120, mutationsPerHour: 200, objectsPerPlan: 2 } }), actor)
|
|
connectionIds.push(limited.connection.id)
|
|
await assert.rejects(invokeMcpTool(await authenticateMcpToken(limited.token), "mm_wireguard_import_plan", full), (error: { code?: string }) => error.code === "PLAN_LIMIT_EXCEEDED")
|
|
assert.equal(commands.length, 0)
|
|
let plan = await prepare(); assert.equal(plan.state, "awaiting-approval"); assert.equal(plan.changes.mutationCost, 8)
|
|
await assert.rejects(applyPlan(principal, plan.planId, randomUUID())); assert.equal(commands.length, 0)
|
|
for (const fault of ["normal", "lost", "reject", "collateral"]) {
|
|
reset(); plan = await prepare(); await approvePlan(plan.planId, actor, true); mode = fault
|
|
const idempotency = randomUUID(), operation = await applyPlan(principal, plan.planId, idempotency), completed = await wait(operation.id)
|
|
assert.equal(completed.state, fault === "normal" ? "applied" : fault === "reject" ? "partial" : "unknown", JSON.stringify({ fault, ...completed }))
|
|
const sent: number = commands.length
|
|
assert.equal(sent, fault === "normal" ? 7 : fault === "collateral" ? 3 : 4)
|
|
assert.equal((await applyPlan(principal, plan.planId, idempotency)).id, operation.id); assert.equal(commands.length, sent)
|
|
const reconciliation = await invokeMcpTool(principal, "mm_operation_reconcile", { operationId: operation.id }) as { automaticRetry: boolean; results: { matchesDesiredState: boolean; verifiedPrefixCommands: number | null }[] }
|
|
assert.equal(reconciliation.automaticRetry, false); assert.equal(reconciliation.results[0].matchesDesiredState, fault === "normal")
|
|
assert.equal(reconciliation.results[0].verifiedPrefixCommands, fault === "normal" ? 7 : fault === "reject" ? 3 : null)
|
|
assert.equal(commands.length, sent)
|
|
if (fault === "normal") {
|
|
assert.deepEqual(commands, restNative.commands); assert.equal(fingerprint(commandBodies), restNative.bodyProof, "REST and MCP dispatch exactly the same complete native payloads")
|
|
const step = (await pool.query("SELECT intended_state,result FROM mcp_operation_steps WHERE operation_id=$1", [operation.id])).rows[0]
|
|
for (const secret of [privateKey, peerOne, peerTwo, "NEVER_IMPORT_"]) assert.equal(JSON.stringify(step).includes(secret), false)
|
|
assert.equal(step.result.peersCreated, 2); assert.equal(step.result.completedCommands, 7)
|
|
assert.equal(rows["/interface/wireguard/peers"][0].disabled, "false"); assert.equal(rows["/interface/wireguard/peers"][1].disabled, "true")
|
|
const intended = step.intended_state, savedResult = step.result
|
|
for (const state of ["intent", "applied", "sent"]) {
|
|
await pool.query("UPDATE mcp_operation_steps SET state=$2 WHERE operation_id=$1", [operation.id, state])
|
|
const lostFinal = await invokeMcpTool(principal, "mm_operation_reconcile", { operationId: operation.id }) as { results: { matchesDesiredState: boolean; configurationMatchesDesiredState: boolean }[] }
|
|
assert.equal(lostFinal.results[0].matchesDesiredState, false)
|
|
assert.equal(lostFinal.results[0].configurationMatchesDesiredState, true, "Final audit prefix is native proof, not a successful operation acknowledgement")
|
|
}
|
|
await pool.query("UPDATE mcp_operation_steps SET state='verified',intended_state=$2::jsonb,result=$3::jsonb WHERE operation_id=$1", [operation.id, JSON.stringify({ ...intended, service: "other" }), JSON.stringify(savedResult)])
|
|
assert.equal((await invokeMcpTool(principal, "mm_operation_reconcile", { operationId: operation.id }) as { results: { matchesDesiredState: boolean }[] }).results[0].matchesDesiredState, false)
|
|
await pool.query("UPDATE mcp_operation_steps SET state='verified',intended_state=$2::jsonb,result=$3::jsonb WHERE operation_id=$1", [operation.id, JSON.stringify(intended), JSON.stringify(savedResult)])
|
|
}
|
|
}
|
|
reset(); plan = await prepare(); await approvePlan(plan.planId, actor, true)
|
|
// Persist the final native-prefix proof, then lose its acknowledgement to
|
|
// the service. Native configuration is complete, generic VERIFIED is absent.
|
|
const checkpointQuery = pool.query.bind(pool)
|
|
let finalCheckpointAckLost = false
|
|
pool.query = ((...args: unknown[]) => {
|
|
const sql = typeof args[0] === "string" ? args[0] : (args[0] as { text?: string })?.text
|
|
const params = args[1] as unknown[] | undefined
|
|
const pending = (checkpointQuery as (...args: unknown[]) => Promise<unknown>)(...args)
|
|
if (!finalCheckpointAckLost && sql?.startsWith("INSERT INTO mcp_audit") && params?.[1] === "wireguard.import.checkpoint" && String(params[3]).includes('"completedCommands":7')) {
|
|
finalCheckpointAckLost = true
|
|
return pending.then(() => { throw Error("Fixture final checkpoint acknowledgement lost") })
|
|
}
|
|
return pending
|
|
}) as typeof pool.query
|
|
try {
|
|
const replayKey = randomUUID(), unknown = await applyPlan(principal, plan.planId, replayKey)
|
|
assert.equal((await wait(unknown.id)).state, "unknown"); assert.equal(finalCheckpointAckLost, true); assert.equal(commands.length, 7)
|
|
const step = (await checkpointQuery("SELECT state,result FROM mcp_operation_steps WHERE operation_id=$1", [unknown.id])).rows[0]
|
|
assert.equal(step.state, "intent"); assert.equal(step.result, null)
|
|
const lost = await invokeMcpTool(principal, "mm_operation_reconcile", { operationId: unknown.id }) as { results: { matchesDesiredState: boolean; configurationMatchesDesiredState: boolean; verifiedFinalCheckpointAvailable: boolean; verifiedPrefixCommands: number | null }[] }
|
|
assert.equal(lost.results[0].configurationMatchesDesiredState, true); assert.equal(lost.results[0].verifiedPrefixCommands, 7)
|
|
assert.equal(lost.results[0].matchesDesiredState, false); assert.equal(lost.results[0].verifiedFinalCheckpointAvailable, false)
|
|
assert.equal((await applyPlan(principal, plan.planId, replayKey)).id, unknown.id); assert.equal(commands.length, 7)
|
|
} finally { pool.query = checkpointQuery as typeof pool.query }
|
|
reset(); plan = await prepare(); await approvePlan(plan.planId, actor, true)
|
|
console.log("WireGuard import MCP phases: human-only native outcomes and exact generic VERIFIED checkpoint variants checked")
|
|
const individual = plan.changes.objects.filter(object => object.kind === "wireguard_peer")[1]
|
|
assert.ok(individual)
|
|
const lateProtection = randomUUID()
|
|
// Audits commit on transaction clients, so the drift hook wraps pool.connect rather than pool.query.
|
|
// Omit serverId deliberately: the logical-object closure must catch
|
|
// this exact protected import peer after the durable native intent.
|
|
const late = afterConfigurationIntentCommit(payload => payload.path === "/interface/wireguard", () => pool.query("INSERT INTO mcp_protections(id,object_ref,created_by) VALUES($1,$2,$3)", [lateProtection, { kind: individual.kind, id: individual.id, protection: "deny" }, actor.id]))
|
|
try {
|
|
assert.equal((await wait((await applyPlan(principal, plan.planId, randomUUID())).id)).state, "unknown")
|
|
assert.equal(late.fired(), true); assert.equal(commands.length, 0)
|
|
} finally { late.restore(); await pool.query("DELETE FROM mcp_protections WHERE id=$1", [lateProtection]) }
|
|
// A native ID is device-local. A different server's *3 protection must not
|
|
// block this import; a new same-server protection after durable activation
|
|
// intent must stop before the first PATCH, with the disabled prefix intact.
|
|
for (const transport of ["rest", "mcp"]) {
|
|
reset()
|
|
const outsideProtection = randomUUID(), nativeProtection = randomUUID(), query = pool.query.bind(pool)
|
|
let late: ReturnType<typeof afterConfigurationIntentCommit> | undefined
|
|
await query("INSERT INTO mcp_protections(id,object_ref,created_by) VALUES($1,$2,$3)", [outsideProtection, { kind: "wireguard_peer", id: "*3", serverId: 142, protection: "deny" }, actor.id])
|
|
try {
|
|
const nativePlan = transport === "mcp" ? await prepare() : undefined
|
|
if (nativePlan) await approvePlan(nativePlan.planId, actor, true)
|
|
// Audits commit on transaction clients, so the drift hook wraps pool.connect rather than pool.query.
|
|
late = afterConfigurationIntentCommit(payload => payload.path === "/interface/wireguard/peers/*3", () => query("INSERT INTO mcp_protections(id,object_ref,created_by) VALUES($1,$2,$3)", [nativeProtection, { kind: "wireguard_peer", id: "*3", serverId: 141, protection: "deny" }, actor.id]))
|
|
if (nativePlan) {
|
|
const idempotency = randomUUID(), operation = await applyPlan(principal, nativePlan.planId, idempotency)
|
|
assert.equal((await wait(operation.id)).state, "unknown")
|
|
assert.equal((await applyPlan(principal, nativePlan.planId, idempotency)).id, operation.id)
|
|
} else {
|
|
const response = await rest.inject({ method: "POST", url: "/api/wireguard/import", payload: restInput })
|
|
assert.equal(response.statusCode, 502, response.body); assertPublic(response.body)
|
|
assert.equal(response.json().state, "needs-review"); assert.equal(response.json().verifiedPrefixCommands, 4)
|
|
assert.equal(response.json().automaticReplay, false)
|
|
assert.notEqual((await rest.inject({ method: "POST", url: "/api/wireguard/import", payload: restInput })).statusCode, 200)
|
|
}
|
|
assert.equal(late.fired(), true, transport)
|
|
assert.equal(commands.length, 4, "Four creations, no activation or replay after late native protection")
|
|
assert.ok(commands.every(command => command.startsWith("PUT ")))
|
|
assert.equal(rows["/interface/wireguard"][1].disabled, "true")
|
|
assert.ok(rows["/interface/wireguard/peers"].every(row => row.disabled === "true"))
|
|
assert.equal(rows["/ipv6/address"][0].disabled, "true")
|
|
} finally {
|
|
late?.restore()
|
|
await query("DELETE FROM mcp_protections WHERE id=ANY($1::uuid[])", [[outsideProtection, nativeProtection]])
|
|
}
|
|
}
|
|
console.log("WireGuard import native protection scope: other-server duplicate ID allowed; late same-server peer protection after durable intent stops REST/MCP before PATCH, prefix four disabled, no replay")
|
|
reset(); plan = await prepare(); await approvePlan(plan.planId, actor, true)
|
|
await pool.query("UPDATE mcp_secrets SET ciphertext=$2 WHERE id=$1", [contentRef, await encryptSecret(content + "\n# changed revision")])
|
|
assert.equal((await wait((await applyPlan(principal, plan.planId, randomUUID())).id)).state, "rejected"); assert.equal(commands.length, 0)
|
|
await pool.query("UPDATE mcp_secrets SET ciphertext=$2 WHERE id=$1", [contentRef, await encryptSecret(content)])
|
|
const protection = randomUUID()
|
|
await pool.query("INSERT INTO mcp_protections(id,object_ref,created_by) VALUES($1,$2,$3)", [protection, { kind: "wireguard-import", id: "wg-import", serverId: 141, protection: "deny" }, actor.id])
|
|
try { await assert.rejects(prepare()); assert.equal(commands.length, 0) } finally { await pool.query("DELETE FROM mcp_protections WHERE id=$1", [protection]) }
|
|
const audited = (await pool.query("SELECT payload FROM mcp_audit WHERE connection_id=$1", [issued.connection.id])).rows
|
|
for (const secret of [privateKey, peerOne, peerTwo, "NEVER_IMPORT_"]) assert.equal(JSON.stringify(audited).includes(secret), false)
|
|
console.log("WireGuard import SQL/loopback helper: contentRef owner/purpose/server/revision, strict preview, human approval, multi-peer disabled staging, checkpoints, partial/unknown no replay, reconciliation and privacy")
|
|
} finally {
|
|
await rest.close()
|
|
for (const id of connectionIds) await setConnectionStatus(id, "paused", actor)
|
|
await pool.query("DELETE FROM mcp_secrets WHERE id=ANY($1::uuid[])", [secretIds])
|
|
if (insertedServers) {
|
|
await pool.query("DELETE FROM config_revisions WHERE server_id IN (141,142)")
|
|
await pool.query("DELETE FROM servers WHERE id IN (141,142)")
|
|
}
|
|
router.closeAllConnections(); await new Promise<void>(resolve => router.close(() => resolve()))
|
|
}
|
|
}
|