Files
MikrotikManager/backend/src/test/mcp-users-bindings.ts
T

275 lines
20 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 { mcpConnectionCreateSchema } from "@mmapp/contracts/mcp"
import { interfaceCatalogStateSchema, userBindingCreateSchema } from "@mmapp/contracts/users"
import type { AuthUser } from "../lib/permissions.js"
import { pool } from "../db/index.js"
import { ensurePartitionFor } from "../db/partitions.js"
import { createMcpConnection, authenticateMcpToken, setConnectionStatus } from "../modules/mcp/store.js"
import { invokeMcpTool, approvePlan } from "../modules/mcp/runtime.js"
import { MAX_MCP_PUBLIC_ARRAY_ITEMS } from "../modules/mcp/security.js"
import { addBinding, getInterfaceCatalogState, listInterfaceCatalog } from "../modules/users/service/users-service.js"
/** Owned PostgreSQL and loopback RouterOS fixture; never writes to a real router. */
export async function verifyMcpUserBindings(actor: AuthUser) {
const serverId = 91731, login = "mcp-binding-" + randomUUID(), connections: string[] = []
let userId: string | undefined, otherUserId: string | undefined, nativeReads = 0, nativeWrites = 0
const otherLogin = login + "-other", wgKey = Buffer.alloc(32, 7).toString("base64")
const fixtures = [
{ name: "ether-owned-user", type: "ether", raw: "ether" },
{ name: "bridge-owned-user", type: "bridge", raw: "bridge" },
{ name: "vlan-owned-user", type: "vlan", raw: "vlan" },
{ name: "vxlan-owned-user", type: "vxlan", raw: "vxlan" },
{ name: "gre-owned-user", type: "gre", raw: "gre-tunnel" },
{ name: "other-owned-user", type: "other", raw: "dummy" },
{ name: "wg-owned-user", type: "wg", raw: "wg", peerPublicKey: wgKey },
{ name: "ipsec-vpn", type: "ipsec", raw: "ipsec", peerPublicKey: "owned-client-cn" },
{ name: "ipsec-vpn", type: "ipsec", raw: "ipsec", peerPublicKey: "owned-psk" },
]
const pendingOperations = new Set<string>()
const providerCanary = "internal RouterOS diagnostic " + randomUUID()
const wgPeer = { ".id": "*A", interface: "wg-owned-user", "public-key": wgKey, name: "Owned WG peer", "allowed-address": "192.0.2.7/32", disabled: "false" }
let catalogMode: "normal" | "upstream-error" | "duplicate" | "many-peers" = "normal"
const router = createServer((req, res) => {
res.setHeader("content-type", "application/json")
if (req.method !== "GET") { nativeWrites++; res.statusCode = 405; res.end("{}"); return }
nativeReads++
const path = new URL(req.url ?? "/", "http://127.0.0.1").pathname.replace(/^\/rest/, "")
if (catalogMode === "upstream-error" && (path === "/interface/wireguard/peers" || path === "/certificate")) {
res.statusCode = 500
res.end(JSON.stringify({ detail: providerCanary }))
return
}
const wgRows = catalogMode === "duplicate" ? [wgPeer, { ...wgPeer, ".id": "*D" }]
: catalogMode === "many-peers" ? Array.from({ length: MAX_MCP_PUBLIC_ARRAY_ITEMS + 1 }, (_, i) => {
const key = Buffer.alloc(32)
key.writeUInt16BE(i)
return { ...wgPeer, ".id": "*" + (i + 10).toString(16), "public-key": key.toString("base64") }
}) : [wgPeer]
const rows = path === "/interface" ? fixtures.filter(iface => iface.type !== "ipsec").map((iface, index) => ({ ".id": "*" + (index + 1).toString(16), name: iface.name, type: iface.raw, running: "true", disabled: "false" }))
: path === "/interface/wireguard/peers" ? wgRows
: path === "/certificate" ? [{ ".id": "*B", name: "ipsec-user-owned-client", "common-name": "owned-client-cn", ca: "owned-ca", "key-usage": "tls-client" }]
: path === "/ip/ipsec/identity" ? [{ ".id": "*C", peer: "ike-owned", "auth-method": "pre-shared-key", comment: "MikrotikManager:ipsec user=owned-psk" }] : []
res.end(JSON.stringify(rows))
})
await new Promise<void>(resolve => router.listen(0, "127.0.0.1", resolve))
const operations = ["users.create", "users.get", "users.interfaces.read", "users.interfaces.state", "users.binding_add", "users.binding_remove", "users.delete", "changes.apply", "operations.read"]
const issue = async (name: string, serverIds: number[], permissions = ["mm:users:write"]) => {
const access = await createMcpConnection(mcpConnectionCreateSchema.parse({ name, mode: "approval", expiresAt: new Date(Date.now() + 1800000).toISOString(), permissions,
scope: { allowGlobal: true, serverIds, operationIds: operations }, limits: { callsPerMinute: 2000, mutationsPerHour: 100 } }), actor)
connections.push(access.connection.id)
return authenticateMcpToken(access.token)
}
const state = async () => ({
users: (await pool.query("SELECT * FROM app_users WHERE login=ANY($1::text[]) ORDER BY login", [[login, otherLogin]])).rows,
bindings: (await pool.query("SELECT * FROM user_interface_bindings WHERE server_id=$1 ORDER BY id", [serverId])).rows,
})
const matches = (code: string) => (error: unknown) => (error as { code?: string }).code === code
try {
await pool.query("INSERT INTO servers(id,name,host,port,use_ssl,enabled) VALUES($1,'owned-user-binding','127.0.0.1',$2,false,true)", [serverId, (router.address() as { port: number }).port])
const sampledAt = new Date()
await ensurePartitionFor(pool, "server_snapshots", "week", sampledAt)
const snapshot = fixtures.filter(iface => iface.type !== "ipsec").map(iface => ({ name: iface.name, type: iface.raw, running: true, disabled: false }))
await pool.query("INSERT INTO server_snapshots(server_id,polled_at,status,raw_interfaces) VALUES($1,$2,'online',$3::jsonb)", [serverId, sampledAt.toISOString(), JSON.stringify(snapshot)])
const replaceSnapshot = (rows: typeof snapshot) => pool.query("UPDATE server_snapshots SET raw_interfaces=$3::jsonb WHERE server_id=$1 AND polled_at=$2", [serverId, sampledAt.toISOString(), JSON.stringify(rows)])
const principal = await issue("User binding journey", [serverId])
const narrow = await issue("User binding excluded server", [])
const readOnly = await issue("User binding read only", [serverId], ["mm:users:read"])
const getUser = async () => (await invokeMcpTool(principal, "mm_users_get", { id: userId }) as { user: { id: string; login: string; bindings: { id: string; serverId: number; interfaceName: string; interfaceType: string; peerPublicKey: string }[] } }).user
const apply = async (tool: string, input: unknown, expected: "applied" | "stale" | "race" = "applied", prepared?: { planId: string; state: string }) => {
const before = await state()
const plan = prepared ?? await invokeMcpTool(principal, tool, input) as { planId: string; state: string }
assert.equal(plan.state, "awaiting-approval")
assert.deepEqual(await state(), before, tool + " preparation changes no users or bindings")
const key = randomUUID()
await assert.rejects(invokeMcpTool(principal, "mm_change_apply", { planId: plan.planId, idempotencyKey: key }), matches("APPROVAL_REQUIRED"))
assert.deepEqual(await state(), before, tool + " unapproved apply changes no users or bindings")
await approvePlan(plan.planId, actor, true)
const operation = await invokeMcpTool(principal, "mm_change_apply", { planId: plan.planId, idempotencyKey: key }) as { id: string }
pendingOperations.add(operation.id)
for (let attempt = 0; attempt < 600; attempt++) {
const result = await invokeMcpTool(principal, "mm_operation_get", { operationId: operation.id }) as { state: string; verification: string; steps: { state: string }[] }
if (!["pending", "running"].includes(result.state)) {
pendingOperations.delete(operation.id)
if (expected === "applied") {
assert.equal(result.state, "applied", JSON.stringify(result))
assert.equal(result.verification, "passed")
assert.equal(result.steps.length, 1)
assert.ok(result.steps.every(step => step.state === "verified"))
} else {
assert.equal(result.state, expected === "stale" ? "rejected" : "unknown", JSON.stringify(result))
assert.deepEqual(await state(), before, "Refused race/stale plan leaves SQL ownership unchanged")
const stopped = (await pool.query("SELECT error_code,result FROM mcp_operations WHERE id=$1", [operation.id])).rows[0]
assert.equal(stopped.result.confirmedWrites, 0)
assert.equal(stopped.error_code, expected === "stale" ? "STATE_CONFLICT" : "DEVICE_UNAVAILABLE")
}
assert.equal((await invokeMcpTool(principal, "mm_change_apply", { planId: plan.planId, idempotencyKey: key }) as { id: string }).id, operation.id)
return
}
await delay(25)
}
throw Error("User binding operation remains live; never replay")
}
await apply("mm_users_create_plan", { user: { login, name: "Owned user binding", email: "[email protected]" } })
userId = (await state()).users[0]?.id
assert.ok(userId)
assert.equal((await getUser()).login, login)
assert.deepEqual((await getUser()).bindings, [])
await apply("mm_users_create_plan", { user: { login: otherLogin, name: "Other owned user", email: "[email protected]" } })
otherUserId = (await state()).users.find(row => row.login === otherLogin)?.id
assert.ok(otherUserId)
const invalidSelectors = [
{ interfaceName: "missing-native-interface" },
{ interfaceName: "wg-owned-user", interfaceType: "ether" },
{ interfaceName: "wg-owned-user", peerPublicKey: Buffer.alloc(32, 9).toString("base64") },
{ interfaceName: "ipsec-vpn", interfaceType: "ipsec", peerPublicKey: "missing-native-cn" },
]
for (const [index, binding] of invalidSelectors.entries()) {
const before = await state(), plansBefore = (await pool.query("SELECT count(*)::int AS n FROM mcp_plans")).rows[0].n
await assert.rejects(invokeMcpTool(principal, "mm_users_binding_add_plan", { id: userId, binding: { serverId, ...binding } }), matches(index === 1 ? "STATE_CONFLICT" : "NOT_FOUND"))
assert.deepEqual(await state(), before)
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_plans")).rows[0].n, plansBefore)
}
type CatalogEntry = { name: string; type: string; boundUserId: string | null; boundUserLogin: string | null; peers?: { publicKey: string; boundUserId: string | null; boundUserLogin: string | null }[] }
const catalog = async () => (await invokeMcpTool(principal, "mm_user_interfaces_list", { serverId }) as { interfaces: CatalogEntry[] }).interfaces
const owner = async (fixture: typeof fixtures[number]) => {
const iface = (await catalog()).find(entry => entry.name === fixture.name)
assert.ok(iface, fixture.name + " appears in catalog")
assert.equal(iface.type, fixture.type)
const entry = fixture.peerPublicKey ? iface.peers?.find(peer => peer.publicKey === fixture.peerPublicKey) : iface
assert.ok(entry, fixture.name + " peer appears in catalog")
return { id: entry.boundUserId, login: entry.boundUserLogin }
}
const catalogState = await invokeMcpTool(principal, "mm_user_interfaces_state_get", { serverId }) as { source: string; inventoryComplete: boolean; failures: unknown[] }
assert.equal(catalogState.source, "snapshot")
assert.equal(catalogState.inventoryComplete, true)
assert.deepEqual(catalogState.failures, [])
const catalogTools = ["mm_user_interfaces_list", "mm_user_interfaces_state_get"]
for (const tool of catalogTools) {
await assert.rejects(invokeMcpTool(narrow, tool, { serverId }), matches("SERVER_DENIED"))
}
try {
catalogMode = "upstream-error"
const publicState = interfaceCatalogStateSchema.parse(await getInterfaceCatalogState(serverId))
assert.deepEqual(publicState.failures.map(failure => failure.resource), ["wireguard", "ipsec"])
assert.equal(publicState.inventoryComplete, true)
assert.ok(publicState.interfaces.find(iface => iface.name === "wg-owned-user")?.peersError)
assert.ok(publicState.interfaces.find(iface => iface.name === "ipsec-vpn")?.peersError)
assert.ok(!JSON.stringify(publicState).includes(providerCanary))
const legacy = await listInterfaceCatalog(serverId)
assert.ok(legacy.find(iface => iface.name === "wg-owned-user")?.peersError)
assert.ok(!JSON.stringify(legacy).includes(providerCanary))
for (const tool of catalogTools) {
const result = await invokeMcpTool(readOnly, tool, { serverId })
assert.ok(!JSON.stringify(result).includes(providerCanary))
}
catalogMode = "duplicate"
assert.equal(interfaceCatalogStateSchema.safeParse(await getInterfaceCatalogState(serverId)).success, false)
for (const tool of catalogTools) {
await assert.rejects(invokeMcpTool(readOnly, tool, { serverId }), matches("STATE_UNAVAILABLE"))
}
catalogMode = "many-peers"
assert.equal((await listInterfaceCatalog(serverId)).find(iface => iface.name === "wg-owned-user")?.peers?.length, MAX_MCP_PUBLIC_ARRAY_ITEMS + 1)
for (const tool of catalogTools) {
await assert.rejects(invokeMcpTool(readOnly, tool, { serverId }), matches("BUDGET_EXCEEDED"))
}
catalogMode = "normal"
await replaceSnapshot(Array.from({ length: MAX_MCP_PUBLIC_ARRAY_ITEMS + 1 }, (_, i) => ({ ...snapshot[0], name: `ether-owned-catalog-${i}` })))
assert.equal(interfaceCatalogStateSchema.parse(await getInterfaceCatalogState(serverId)).inventoryComplete, true)
for (const tool of catalogTools) {
await assert.rejects(invokeMcpTool(readOnly, tool, { serverId }), matches("BUDGET_EXCEEDED"))
}
} finally {
catalogMode = "normal"
await replaceSnapshot(snapshot)
}
for (const fixture of fixtures) {
// Infer ordinary/WG types from native rows; verify the service's canonical
// name/key, including ordinary-interface peer clearing, after real INSERT.
const binding = { serverId, interfaceName: ` ${fixture.name} `, peerPublicKey: fixture.peerPublicKey ? ` ${fixture.peerPublicKey} ` : " ignored-non-peer ", ...(fixture.type === "ipsec" ? { interfaceType: "ipsec" } : {}) }
assert.deepEqual(await owner(fixture), { id: null, login: null })
const beforeDenied = await state()
const plansBefore = (await pool.query("SELECT count(*)::int AS n FROM mcp_plans")).rows[0].n
await assert.rejects(invokeMcpTool(narrow, "mm_users_binding_add_plan", { id: userId, binding }), matches("SERVER_DENIED"))
await assert.rejects(invokeMcpTool(readOnly, "mm_users_binding_add_plan", { id: userId, binding }), matches("CONNECTION_PERMISSION_MISSING"))
assert.deepEqual(await state(), beforeDenied)
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_plans")).rows[0].n, plansBefore, "Denied requests create no plans")
// Preparation cannot reserve the tuple: another owner can bind it before apply.
const racedInput = { id: otherUserId, binding }
const racedPlan = await invokeMcpTool(principal, "mm_users_binding_add_plan", racedInput) as { planId: string; state: string }
await apply("mm_users_binding_add_plan", { id: userId, binding })
const bound = (await getUser()).bindings
assert.equal(bound.length, 1)
assert.equal(bound[0].serverId, serverId)
assert.equal(bound[0].interfaceName, fixture.name)
assert.equal(bound[0].interfaceType, fixture.type)
assert.equal(bound[0].peerPublicKey, fixture.peerPublicKey ?? "")
assert.deepEqual(await owner(fixture), { id: userId, login })
const hidden: { incomplete: boolean; bindings: unknown[] } = (await invokeMcpTool(narrow, "mm_users_get", { id: userId }) as { user: { incomplete: boolean; bindings: unknown[] } }).user
assert.equal(hidden.incomplete, true)
assert.deepEqual(hidden.bindings, [])
const beforeConflict = await state()
const counts = async () => (await pool.query("SELECT (SELECT count(*)::int FROM mcp_plans) AS plans,(SELECT count(*)::int FROM mcp_operations) AS operations")).rows[0]
const beforeCounts = await counts()
if (fixture === fixtures[0]) {
const readsBefore = nativeReads
await assert.rejects(invokeMcpTool(principal, "mm_users_binding_remove_plan", { id: userId, bindingId: randomUUID() }), matches("NOT_FOUND"))
await assert.rejects(invokeMcpTool(principal, "mm_users_binding_remove_plan", { id: otherUserId, bindingId: bound[0].id }), matches("NOT_FOUND"))
assert.equal(nativeReads, readsBefore, "Invalid removal is refused from the current user snapshot")
assert.deepEqual(await counts(), beforeCounts, "Invalid removal creates no plan or operation")
assert.deepEqual(await state(), beforeConflict)
}
for (const id of [userId, otherUserId]) {
await assert.rejects(invokeMcpTool(principal, "mm_users_binding_add_plan", { id, binding }), matches("STATE_CONFLICT"))
}
await assert.rejects(invokeMcpTool(narrow, "mm_users_binding_add_plan", { id: userId, binding }), matches("SERVER_DENIED"))
await assert.rejects(invokeMcpTool(readOnly, "mm_users_binding_add_plan", { id: userId, binding }), matches("CONNECTION_PERMISSION_MISSING"))
if (fixture.peerPublicKey) {
await assert.rejects(invokeMcpTool(principal, "mm_users_binding_add_plan", { id: userId, binding: { ...binding, peerPublicKey: "" } }), matches("INVALID_INPUT"))
}
assert.deepEqual(await counts(), beforeCounts, "Deterministic duplicate/takeover creates no plan or operation")
assert.deepEqual(await state(), beforeConflict)
// REST's shared SQL service retains its 409 contract.
for (const id of [userId, otherUserId]) {
await assert.rejects(addBinding(id, userBindingCreateSchema.parse(binding)), (error: unknown) => (error as { status?: number }).status === 409)
}
assert.deepEqual(await state(), beforeConflict)
await apply("mm_users_binding_add_plan", racedInput, "race", racedPlan)
assert.deepEqual(await owner(fixture), { id: userId, login })
const beforeRemoveDenied = await state()
for (const tool of ["mm_users_binding_remove_plan", "mm_users_delete_plan"]) {
await assert.rejects(invokeMcpTool(narrow, tool, tool.includes("binding") ? { id: userId, bindingId: bound[0].id } : { id: userId }), matches("SERVER_DENIED"))
}
assert.deepEqual(await state(), beforeRemoveDenied)
const removeInput = { id: userId, bindingId: bound[0].id }
const staleRemoval = await invokeMcpTool(principal, "mm_users_binding_remove_plan", removeInput) as { planId: string; state: string }
await apply("mm_users_binding_remove_plan", removeInput)
assert.deepEqual((await getUser()).bindings, [])
assert.deepEqual(await owner(fixture), { id: null, login: null })
await apply("mm_users_binding_remove_plan", removeInput, "stale", staleRemoval)
assert.deepEqual(await owner(fixture), { id: null, login: null })
}
await apply("mm_users_delete_plan", { id: otherUserId })
await apply("mm_users_delete_plan", { id: userId })
await assert.rejects(invokeMcpTool(principal, "mm_users_get", { id: userId }), matches("NOT_FOUND"))
assert.deepEqual(await state(), { users: [], bindings: [] })
assert.ok(nativeReads > 0, "Catalog consulted loopback RouterOS fixture")
assert.equal(nativeWrites, 0, "User binding workflow never mutates RouterOS")
console.log("✓ MCP users: eight native binding types plus IPsec PSK, missing/type-spoof/peer/CN refusal, add/read/remove, catalog owner, duplicate/takeover refusal, approval/replay and scope; owned PostgreSQL/RouterOS stub")
} finally {
// Never race cleanup against an unresolved operation. This helper runs only
// inside the disposable owned profile, whose runner tears down its database.
if (pendingOperations.size === 0) {
for (const id of connections) await setConnectionStatus(id, "paused", actor)
await pool.query("DELETE FROM app_users WHERE login=ANY($1::text[])", [[login, otherLogin]])
await pool.query("DELETE FROM servers WHERE id=$1", [serverId])
}
await new Promise<void>((resolve, reject) => router.close(error => error ? reject(error) : resolve()))
}
}