import assert from "node:assert/strict" import { createPrivateKey, createPublicKey, randomBytes, randomUUID } from "node:crypto" import { mkdtemp, writeFile } from "node:fs/promises" import { createServer, type RequestListener } from "node:http" import { tmpdir } from "node:os" import { join } from "node:path" import { setTimeout as delay } from "node:timers/promises" import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client" import EmbeddedPostgres from "embedded-postgres" const dir = await mkdtemp(join(tmpdir(), "mm-ix-web-")) const socket = createServer() await new Promise(resolve => socket.listen(0, "127.0.0.1", resolve)) const pgPort = (socket.address() as { port: number }).port await new Promise(resolve => socket.close(() => resolve())) const password = randomBytes(24).toString("hex") const pg = new EmbeddedPostgres({ databaseDir: join(dir, "pg"), user: "ixlab", password, port: pgPort, persistent: false, initdbFlags: ["--encoding=UTF8", "--no-locale"], onLog() {} }) Object.assign(process.env, { NODE_ENV: "test", DATABASE_URL: `postgres://ixlab:${password}@127.0.0.1:${pgPort}/postgres`, MCP_STATE_DIR: join(dir, "state"), AUTH_REQUIRED: "true", AUTH_JWT_SECRET: randomBytes(32).toString("hex"), DATABASE_PATH: join(dir, "no-legacy.sqlite"), }) await pg.initialise() await pg.start() type RouterRows = Record[]> const rows: RouterRows = { "/ip/vrf": [{ ".id": "*1", name: "main", interfaces: "all", builtin: "true" }], "/interface": [{ ".id": "*A0", name: "gre-client", type: "gre", comment: "IX:ix-web-fixture" }], "/interface/gre": [{ ".id": "*A0", name: "gre-client", "local-address": "192.0.2.20", "remote-address": "192.0.2.21", "allow-fast-path": "false" }], "/ip/ipsec/policy": [{ ".id": "*A1", "src-address": "192.0.2.20/32", "dst-address": "192.0.2.21/32", protocol: "gre", action: "encrypt", level: "require", tunnel: "false", disabled: "false" }], } let writes = 0 let deletes = 0 let failPutAt = -1 let failDeleteAt = -1 const fixtureHubPublicKey = Buffer.alloc(32, 11).toString("base64") const serveRouter = (rows: RouterRows): RequestListener => async (request, response) => { try { const path = new URL(request.url!, "http://127.0.0.1").pathname.replace(/^\/rest/, "") let result: unknown if (request.method === "GET") result = rows[path] ?? [] else if (request.method === "PUT") { if (writes === failPutAt) throw Error("Synthetic RouterOS apply failure") let raw = "" for await (const chunk of request) raw += chunk const { "place-before": place, ...fields } = JSON.parse(raw) const row = { ...fields, ...(path === "/interface/wireguard" && { "public-key": fixtureHubPublicKey }), ".id": "*" + (++writes + 1).toString(16).toUpperCase() } const list = rows[path] ??= [] const index = list.findIndex(entry => entry[".id"] === place) list.splice(index < 0 ? list.length : index, 0, row) if (["/ip/vrf", "/interface/wireguard", "/interface/bridge", "/interface/gre"].includes(path)) { rows["/interface"].push({ ".id": row[".id"], name: row.name, type: path === "/interface/wireguard" ? "wg" : path.split("/").at(-1)!, comment: row.comment }) } result = row } else if (request.method === "PATCH") { const parent = path.slice(0, path.lastIndexOf("/")) const id = decodeURIComponent(path.slice(path.lastIndexOf("/") + 1)) const row = rows[parent]?.find(entry => entry[".id"] === id) assert(row) let raw = "" for await (const chunk of request) raw += chunk Object.assign(row, JSON.parse(raw)) writes++ result = row } else if (request.method === "DELETE") { if (deletes === failDeleteAt) throw Error("Synthetic RouterOS deletion failure") const parent = path.slice(0, path.lastIndexOf("/")) const id = decodeURIComponent(path.slice(path.lastIndexOf("/") + 1)) const index = (rows[parent] ?? []).findIndex(row => row[".id"] === id) assert(index >= 0) const [deleted] = rows[parent].splice(index, 1) rows["/interface"] = rows["/interface"].filter(row => row.name !== deleted.name || row[".id"] !== id) deletes++ response.statusCode = 204 response.end() return } else throw Error("Unexpected native verb: " + request.method) response.setHeader("content-type", "application/json") response.end(JSON.stringify(result)) } catch (error) { response.statusCode = 500 response.end(JSON.stringify({ error: String(error) })) } } const router = createServer(serveRouter(rows)) const backupRouter = createServer(serveRouter({ "/ip/vrf": [{ ".id": "*1", name: "main", interfaces: "all", builtin: "true" }], "/interface": [{ ".id": "*2", name: "ether1", type: "ether", running: "true" }], "/ip/address": [{ ".id": "*3", interface: "ether1", address: "198.51.100.20/24" }], "/ip/route": [{ ".id": "*4", "routing-table": "main", "dst-address": "0.0.0.0/0", gateway: "198.51.100.1%ether1", "immediate-gw": "198.51.100.1%ether1", active: "true" }], })) const { initDatabase } = await import("../../src/db/bootstrap.js") const { pool } = await import("../../src/db/index.js") let app: Awaited> | undefined let mcp: Client | undefined try { await initDatabase() assert.equal((await pool.query("SELECT enabled FROM mcp_settings WHERE id=1")).rows[0].enabled, false) await new Promise(resolve => router.listen(0, "127.0.0.1", resolve)) const port = (router.address() as { port: number }).port const { rows: [server] } = await pool.query(`INSERT INTO servers (name,host,port,enabled,type,username,password,use_ssl,verify_ssl) VALUES('owned-ix','127.0.0.1',$1,true,'ix-node','synthetic','synthetic',false,true) RETURNING id`, [port]) const { buildApp } = await import("../../src/index.js") const { env } = await import("../../src/config.js") app = await buildApp({ logger: false, startScheduler: false }) const origin = await app.listen({ host: "127.0.0.1", port: 0 }) const token = (owner: string, permission: string) => app!.jwt.sign({ iss: env.authIssuer, sub: owner, apps: ["mm"], permissions: [permission], iat: Math.floor(Date.now() / 1000) - 1, exp: Math.floor(Date.now() / 1000) + 600 }) const writer = token("ix-web-owner", "mm:network:write") const reader = token("ix-web-reader", "mm:network:read") const otherWriter = token("ix-web-other-owner", "mm:network:write") async function post(path: string, payload: object, status: number, jwt = writer, method = "POST") { const reply = await fetch(origin + "/api/ix/segments" + path, { method, headers: { "content-type": "application/json", ...(jwt ? { authorization: "Bearer " + jwt } : {}) }, body: JSON.stringify(payload), signal: AbortSignal.timeout(30_000) }) const data = reply.status === 204 ? undefined : await reply.json() assert.equal(reply.status, status, JSON.stringify(data)) return data } const configuration = { name: "ix-web-fixture", sites: [{ serverId: Number(server.id), autonomousSystem: 64512, routerId: "192.0.2.5", interfaces: [{ name: "wg-ix-web", kind: "wireguard", prefixes: ["2001:db8:12::/48"], provisionWireguard: { peerPublicKey: "A".repeat(43) + "=", listenPort: 51820, localAddress: "10.20.30.1/30", peerAddress: "10.20.30.2", hubEndpoint: "192.0.2.20" } }, { name: "gre-client", kind: "gre-ipsec", localEndpoint: "192.0.2.20", endpoint: "192.0.2.21" }] }] } const { segment } = await post("", { revision: 0, configuration }, 200) assert.equal(segment.revision, 1) assert.equal(segment.appliedRevision, null) const path = "/" + segment.id const linux = async (name?: string, status = 200) => { const query = name ? "?" + new URLSearchParams({ serverId: String(server.id), interfaceName: name }) : "" const response = await fetch(origin + "/api/ix/segments" + path + "/linux" + query, { headers: { authorization: "Bearer " + reader } }) const body = await response.json() assert.equal(response.status, status, JSON.stringify(body)) return body } assert.deepEqual(await linux(), { revision: null, items: [] }) const { digest, changes } = await post(path + "/plan", { revision: 1 }, 200) assert(changes.some((step: { path: string }) => step.path === "/interface/wireguard/peers")) await post(path + "/apply", { revision: 1, digest }, 401, "") await post(path + "/apply", { revision: 1, digest }, 403, reader) await post(path + "/apply", { revision: 1, digest }, 409, otherWriter) await post(path + "/apply", { revision: 1, digest: "0".repeat(64) }, 409) rows["/interface"].push({ ".id": "*F0", name: "test-drift", type: "ether" }) await post(path + "/apply", { revision: 1, digest }, 409) assert.equal(writes, 0) const fresh = await post(path + "/plan", { revision: 1 }, 200) await post(path + "/plan", { revision: 1, resume: true }, 409) const protectionId = randomUUID() await pool.query("INSERT INTO mcp_protections(id,object_ref,created_by) VALUES ($1,$2,'ix-web-owner')", [protectionId, { kind: "server", id: String(server.id), protection: "deny" }]) await post(path + "/apply", { revision: 1, digest: fresh.digest }, 409) assert.equal(writes, 0) await pool.query("DELETE FROM mcp_protections WHERE id=$1", [protectionId]) failPutAt = 1 await post(path + "/apply", { revision: 1, digest: fresh.digest }, 503) assert.equal(writes, 1) await post(path + "/plan", { revision: 1 }, 409) failPutAt = -1 const resume = await post(path + "/plan", { revision: 1, resume: true }, 200) assert.equal(resume.changes.length, changes.length - 1) const applied = await post(path + "/apply", { revision: 1, digest: resume.digest, resume: true }, 200) assert.equal(applied.segment.appliedRevision, 2) assert.equal(applied.result.configurationVerified, true) assert.equal(applied.result.forwardingVerified, false) const resultWrites = writes assert.equal(resultWrites, changes.length) const clients = await linux() assert.equal(clients.revision, 2) assert.deepEqual(clients.items.map((item: { kind: string }) => item.kind), ["wireguard", "gre-ipsec"]) const wg = await linux("wg-ix-web") assert.match(wg.template, /Endpoint = 192\.0\.2\.20:51820/) assert.match(wg.template, /Table = off/) assert(!wg.template.includes("A".repeat(43))) await post(path + "/linux/credential", { serverId: Number(server.id), interfaceName: "wg-ix-web" }, 404) const gre = await linux("gre-client") assert.match(gre.template, /local_ts = 192\.0\.2\.21\/32\[47\]/) assert.match(gre.template, /remote_ts = 192\.0\.2\.20\/32\[47\]/) assert.match(gre.template, /mode = transport/) assert.match(gre.setup, /mode gre local 192\.0\.2\.21 remote 192\.0\.2\.20/) rows["/ip/ipsec/policy"][0].disabled = "true" await linux("gre-client", 409) rows["/ip/ipsec/policy"][0].disabled = "false" rows["/interface/wireguard/peers"][0].disabled = "true" await linux("wg-ix-web", 409) delete rows["/interface/wireguard/peers"][0].disabled await post(path + "/apply", { revision: 1, digest: fresh.digest }, 409) assert.equal(writes, resultWrites) const next = await post("", { id: segment.id, revision: 2, configuration: { ...configuration, sites: [{ ...configuration.sites[0], discardNetworks: ["2001:db8:ff::/48"] }] } }, 200) assert.equal(next.segment.appliedRevision, 2) assert.equal((await linux("wg-ix-web")).revision, 2) const members = rows["/interface/list/member"] members.push({ ".id": "*FE", list: rows["/interface/list"][0].name, interface: "test-drift" }) const foreign = await post(path + "/plan", { revision: 3 }, 409) assert.match(foreign.error, /посторонний интерфейс/) members.pop() const nextPlan = await post(path + "/plan", { revision: 3 }, 200) await post(path + "/apply", { revision: 3, digest: nextPlan.digest }, 200) assert(rows["/ipv6/route"].some(row => row["dst-address"] === "2001:db8:ff::/48")) const { rows: [audit] } = await pool.query(`SELECT count(*)::int AS n FROM mcp_audit WHERE actor_id='ix-web-owner' AND action='configuration.acknowledged' AND connection_id IS NULL`) assert.equal(audit.n, writes) const { rows: [connections] } = await pool.query("SELECT count(*)::int AS n FROM mcp_connections") assert.equal(connections.n, 0) const draftConfig = { ...configuration, name: "ix-web-draft" } const draft = (await post("", { revision: 0, configuration: draftConfig }, 200)).segment const draftPath = "/" + draft.id const draftRemoval = await post(draftPath + "/removal-plan", { revision: 1 }, 200) assert.deepEqual(draftRemoval.changes, []) const deleteDraft = { revision: 1, digest: draftRemoval.digest } await post(draftPath, deleteDraft, 403, reader, "DELETE") await post(draftPath, deleteDraft, 409, otherWriter, "DELETE") await post(draftPath, deleteDraft, 204, writer, "DELETE") assert.equal(deletes, 0) await post(draftPath, deleteDraft, 404, writer, "DELETE") const recreated = (await post("", { revision: 0, configuration: draftConfig }, 200)).segment const removalInput = { revision: 4 } const blocked = await post(path + "/removal-plan", removalInput, 409) assert.match(blocked.error, /Отключите интерфейс.*gre-client/) rows["/interface"].find(row => row.name === "gre-client")!.disabled = "true" rows["/ip/address"].push({ ".id": "*FE", interface: "wg-ix-web", address: "192.0.2.1/32" }) assert.match((await post(path + "/removal-plan", removalInput, 409)).error, /нет в применённой ревизии/) rows["/ip/address"].pop() const removal = await post(path + "/removal-plan", removalInput, 200) assert.equal(removal.changes.length, writes) assert(removal.changes.every((change: { action: string }) => change.action === "delete")) failDeleteAt = 1 await post(path, { ...removalInput, digest: removal.digest }, 503, writer, "DELETE") assert.equal(deletes, 1) assert.equal((await pool.query("SELECT configuration->>'deleted' AS deleted FROM ix_segments WHERE id=$1", [segment.id])).rows[0].deleted, null) await post(path, { ...removalInput, digest: removal.digest }, 409, writer, "DELETE") failDeleteAt = -1 const remaining = await post(path + "/removal-plan", removalInput, 200) assert.equal(remaining.changes.length, removal.changes.length - 1) await post(path, { ...removalInput, digest: remaining.digest }, 204, writer, "DELETE") assert.equal(deletes, writes) assert.equal(rows["/ip/ipsec/policy"].length, 1) assert.deepEqual(rows["/interface"].map(row => row.name), ["gre-client", "test-drift"]) const { rows: [archive] } = await pool.query(`SELECT s.configuration->>'deleted' AS deleted, (SELECT count(*)::int FROM ix_segment_revisions WHERE segment_id=s.id) AS revisions, (SELECT count(*)::int FROM ix_segment_devices WHERE segment_id=s.id) AS devices FROM ix_segments s WHERE id=$1`, [segment.id]) assert.deepEqual(archive, { deleted: "true", revisions: 4, devices: 0 }) const listReply = await fetch(origin + "/api/ix/segments", { headers: { authorization: "Bearer " + reader } }) assert.equal(listReply.status, 200) assert.deepEqual((await listReply.json()).items.map((item: { configuration: { name: string } }) => item.configuration.name), [draftConfig.name]) process.env.MCP_PUBLIC_URL = origin + "/mcp" const ownerPermissions = ["mm:network:write", "mm:network:read", "mm:mcp:admin", "mm:mcp:approve"] const issuedAt = Math.floor(Date.now() / 1000) - 1 const ownerId = "ix-mcp-owner" const mcpJwt = app.jwt.sign({ iss: env.authIssuer, sub: ownerId, apps: ["mm"], permissions: ownerPermissions, iat: issuedAt, exp: issuedAt + 600 }) const { updateMcpSettings } = await import("../../src/modules/mcp/store.js") await updateMcpSettings({ enabled: true }, { id: ownerId, email: "ix@example.invalid", name: "IX acceptance", apps: ["mm"], permissions: ownerPermissions, issuedAt: issuedAt * 1000, expiresAt: (issuedAt + 600) * 1000 }) async function mcpPost(path: string, body: object) { const reply = await fetch(origin + "/api/mcp/" + path, { method: "POST", headers: { authorization: "Bearer " + mcpJwt, "content-type": "application/json" }, body: JSON.stringify(body) }) const data = await reply.json() assert(reply.ok, JSON.stringify(data)) return data } const { token: mcpToken } = await mcpPost("connections", { name: "IX removal acceptance", mode: "approval", permissions: ["mm:network:write", "mm:network:read"], expiresAt: new Date(Date.now() + 300_000).toISOString(), scope: { allowGlobal: false, serverIds: [Number(server.id)], operationIds: ["network.ix.delete", "network.wireguard.export", "changes.apply", "operations.read"] } }) mcp = new Client({ name: "ix-removal-acceptance", version: "1.0.0" }) await mcp.connect(new StreamableHTTPClientTransport(new URL(origin + "/mcp"), { requestInit: { headers: { authorization: "Bearer " + mcpToken } } })) async function call(name: string, args: object, error = false) { const reply = await mcp!.callTool({ name, arguments: args }) assert.equal(Boolean(reply.isError), error, JSON.stringify(reply.structuredContent ?? reply.content)) return (reply.structuredContent as { result: T } | undefined)?.result as T } const mcpPlan = await call<{ planId: string; state: string }>( "mm_ix_delete_plan", { id: recreated.id, revision: 1 }) assert.equal(mcpPlan.state, "awaiting-approval") const mcpApply = { planId: mcpPlan.planId, idempotencyKey: randomUUID() } await call("mm_change_apply", mcpApply, true) await mcpPost("plans/" + mcpPlan.planId + "/decision", { approve: true }) type Operation = { id: string; state: string; verification: string } const operation = await call("mm_change_apply", mcpApply) let terminal = operation for (let attempts = 0; attempts < 30 && ["pending", "running"].includes(terminal.state); attempts++) { await delay(200) terminal = await call("mm_operation_get", { operationId: operation.id }) } assert.equal(terminal.state, "applied", JSON.stringify(terminal)) assert.equal(terminal.verification, "passed") assert.equal(deletes, writes) const managed = (await post("", { revision: 0, configuration: { name: "ix-web-managed", sites: [ { serverId: Number(server.id), autonomousSystem: 64512, routerId: "192.0.2.6" }, ] } }, 200)).segment const managedPath = "/" + managed.id rows["/interface"].push({ ".id": "*FA", name: "ether1", type: "ether", running: "true" }) ;(rows["/ip/address"] ??= []).push( { ".id": "*FB", interface: "ether1", address: "192.0.2.20/24" }, { ".id": "*FC", interface: "ether1", address: "192.0.2.30/24" }, ) ;(rows["/ip/route"] ??= []).push({ ".id": "*FD", "routing-table": "main", "dst-address": "0.0.0.0/0", gateway: "192.0.2.1%ether1", "immediate-gw": "192.0.2.1%ether1", active: "true" }) const clientInput = { serverId: Number(server.id), name: "linux-auto", kind: "wireguard", hubEndpoint: "192.0.2.20", peerEndpoint: "192.0.2.40", exit: "local-wan", prefixes: [], destinations: ["203.0.113.0/24"], enabled: true } const staged = await post(managedPath + "/linux", { ...clientInput, revision: managed.revision }, 200) const clientKey = { serverId: clientInput.serverId, interfaceName: staged.interfaceName } await post(managedPath + "/linux/credential", clientKey, 409) await post(managedPath + "/linux/credential", clientKey, 403, reader) const edited = await post(managedPath + "/linux", { ...clientInput, ...clientKey, revision: staged.segment.revision, name: "linux-renamed" }, 200) const provision = edited.segment.configuration.sites[0].interfaces[0].provisionWireguard assert.deepEqual(provision, staged.segment.configuration.sites[0].interfaces[0].provisionWireguard) const plan = await post(managedPath + "/plan", { revision: edited.segment.revision }, 200) await post(managedPath + "/apply", { revision: edited.segment.revision, digest: plan.digest }, 200) const credential = await post(managedPath + "/linux/credential", clientKey, 200) const privateKey = credential.template.match(/^PrivateKey = ([A-Za-z0-9+/]{43}=)$/m)?.[1] assert.ok(privateKey) const scalar = Buffer.from(privateKey, "base64") const key = createPrivateKey({ key: Buffer.concat([Buffer.from("302e020100300506032b656e04220420", "hex"), scalar]), format: "der", type: "pkcs8" }) const publicKey = createPublicKey(key).export({ format: "der", type: "spki" }).subarray(-32).toString("base64") assert.equal(publicKey, provision.peerPublicKey) assert.equal(rows["/interface/wireguard/peers"].find(row => row.interface === clientKey.interfaceName)?.["public-key"], publicKey) assert(!JSON.stringify([edited, plan, rows]).includes(privateKey)) const templateResponse = await fetch(origin + "/api/ix/segments" + managedPath + "/linux?" + new URLSearchParams({ serverId: String(clientKey.serverId), interfaceName: clientKey.interfaceName, }), { headers: { authorization: "Bearer " + reader } }) assert.equal(templateResponse.status, 200) assert.match((await templateResponse.json()).template, /PrivateKey = <локальный_приватный_ключ>/) const exportPlan = await call<{ planId: string; state: string }>("mm_wireguard_export_plan", { ...clientKey, ixSegmentId: managed.id, format: "peer-conf" }) assert.equal(exportPlan.state, "awaiting-approval") assert(!JSON.stringify(exportPlan).includes(privateKey)) await mcpPost("plans/" + exportPlan.planId + "/decision", { approve: true }) const exportOperation = await call("mm_change_apply", { planId: exportPlan.planId, idempotencyKey: randomUUID() }) let exported = exportOperation for (let attempts = 0; attempts < 50 && ["pending", "running"].includes(exported.state); attempts++) { await delay(200) exported = await call("mm_operation_get", { operationId: exportOperation.id }) } assert.equal(exported.state, "applied", JSON.stringify(exported)) assert(!JSON.stringify(exported).includes(privateKey)) const { rows: [{ result: receipt }] } = await pool.query("SELECT result FROM mcp_operation_steps WHERE operation_id=$1", [exported.id]) assert.equal(receipt.humanDownloadOnly, true) const secretRecords = await pool.query(`SELECT to_jsonb(s) AS record FROM mcp_operation_steps s WHERE operation_id=$1 UNION ALL SELECT to_jsonb(p) FROM mcp_plans p WHERE id=$2 UNION ALL SELECT to_jsonb(a) FROM mcp_artifacts a WHERE id=$3 UNION ALL SELECT to_jsonb(a) FROM mcp_audit a WHERE actor_id IN ('ix-web-owner','ix-mcp-owner')`, [exported.id, exportPlan.planId, receipt.artifactId]) assert(!JSON.stringify(secretRecords.rows).includes(privateKey)) const download = await fetch(origin + receipt.downloadPath, { headers: { authorization: "Bearer " + mcpJwt } }) assert.equal(download.status, 200) assert.equal(await download.text(), credential.template) assert.equal(download.headers.get("cache-control"), "private, no-store") const denied = await fetch(origin + receipt.downloadPath, { headers: { authorization: "Bearer " + otherWriter } }) assert.equal(denied.status, 403) const appliedPeer = rows["/interface/wireguard/peers"].find(row => row.interface === clientKey.interfaceName)! appliedPeer.disabled = "true" const inactive = await fetch(origin + receipt.downloadPath, { headers: { authorization: "Bearer " + mcpJwt } }) assert.equal(inactive.status, 409) delete appliedPeer.disabled const companionInput = { ...clientInput, kind: "gre-ipsec", companionOf: clientKey.interfaceName } const canceled = await post(managedPath + "/linux", { ...companionInput, revision: credential.revision }, 200) const canceledKey = { serverId: clientKey.serverId, interfaceName: canceled.interfaceName } const reverted = await post(managedPath + "/linux/revoke", { ...canceledKey, revision: canceled.segment.revision }, 200) const noChanges = await post(managedPath + "/plan", { revision: reverted.segment.revision }, 200) assert.deepEqual(noChanges.changes, []) const resumed = await post(managedPath + "/apply", { revision: reverted.segment.revision, digest: noChanges.digest }, 200) const paired = await post(managedPath + "/linux", { ...companionInput, revision: resumed.segment.revision }, 200) const bindings = paired.segment.configuration.sites[0].interfaces const [wireguard, greBinding] = bindings assert.ok(wireguard.linux.clientId) const original = resumed.segment.configuration.sites[0].interfaces[0] assert.deepEqual(wireguard, { ...original, linux: { ...original.linux, clientId: wireguard.linux.clientId } }) assert.equal(wireguard.linux.clientId, greBinding.linux.clientId) assert.notEqual(wireguard.provisionWireguard.peerAddress, greBinding.provisionGre.peerAddress) const foreignRoute = { ".id": "*FE", "routing-table": "main", "dst-address": "198.51.100.0/24", gateway: "10.254.0.2%" + clientKey.interfaceName } rows["/ip/route"].push(foreignRoute) const blockedForeign = await post(managedPath + "/plan", { revision: paired.segment.revision }, 409) assert.match(blockedForeign.error, /другой маршрутизацией/) assert.equal(rows["/ip/route"].pop(), foreignRoute) const pairPlan = await post(managedPath + "/plan", { revision: paired.segment.revision }, 200) assert(!pairPlan.changes.some(change => change.path.startsWith("/interface/wireguard"))) const pairedApplied = await post(managedPath + "/apply", { revision: paired.segment.revision, digest: pairPlan.digest }, 200) const pairVrf = rows["/ip/vrf"].find(row => row.interfaces?.includes(wireguard.name))! assert(pairVrf.interfaces.split(",").includes(greBinding.name)) const greCredential = await post(managedPath + "/linux/credential", { serverId: clientKey.serverId, interfaceName: paired.interfaceName }, 200) assert.match(greCredential.template, /secret = "[a-f0-9]{64}"/) assert.match(greCredential.setup, /install -m 0600 "\$conf" \/etc\/swanctl\/conf\.d\//) assert.match(greCredential.setup, /ip -4 rule add pref \d+ from 192\.0\.2\.40\/32 lookup main/) assert.match(greCredential.setup, /ip -4 route replace default dev ixg\w+ src \S+ table \d+/) assert(greCredential.setup.indexOf(" lookup main\n") < greCredential.setup.indexOf("swanctl --initiate")) assert.equal((await post(managedPath + "/linux/credential", clientKey, 200)).template, credential.template) const bondPath = managedPath + "/linux-bonds" const bondInput = { revision: 0, name: "mixed", mode: "weighted", directCidrs: ["192.0.2.0/24"], members: [wireguard, greBinding].map((binding, i) => ({ segmentId: managed.id, serverId: clientKey.serverId, interfaceName: binding.name, weight: i ? 1 : 3, appliedRevision: pairedApplied.segment.revision })) } await post(bondPath, bondInput, 403, reader) const bond = await post(bondPath, bondInput, 200) assert.equal(bond.clientId, wireguard.linux.clientId) await post(bondPath, bondInput, 409) const bundlePath = bondPath + "/" + bond.id + "/export" const bundle = await post(bundlePath, { revision: 1 }, 200) assert.deepEqual(bundle.members.map(member => [member.kind, member.weight]), [["wireguard", 3], ["gre-ipsec", 1]]) assert.equal(bundle.members[0].peerPublicKey, fixtureHubPublicKey) assert.deepEqual(bundle.destinations, ["0.0.0.0/0"]) assert(!JSON.stringify(bundle).includes(privateKey)) if (process.env.IX_BOND_TEST_EXPORT) { await writeFile(process.env.IX_BOND_TEST_EXPORT, JSON.stringify(bundle, null, 2) + "\n", { flag: "wx" }) } await post(bundlePath, { revision: 1 }, 403, reader) await post(managedPath + "/removal-plan", { revision: pairedApplied.segment.revision }, 409) const { rows: [exit] } = await pool.query(`INSERT INTO servers (name,host,port,enabled,type,username,password,use_ssl,verify_ssl) VALUES('owned-exit','127.0.0.1',$1,true,'exit-node','synthetic','synthetic',false,true) RETURNING id`, [port]) const transit = { targetServerId: Number(exit.id), localEndpoint: "192.0.2.20", remoteEndpoint: "192.0.2.30", family: 4, name: "remote-exit" } const appliedRevision = pairedApplied.segment.revision const remoteClient = { ...clientInput, name: "linux-remote", revision: appliedRevision, exit: undefined, transit } const beforeStage = writes await post(managedPath + "/linux", { ...remoteClient, localAddress: "10.254.21.1/30" }, 400) const stagedRemote = await post(managedPath + "/linux", remoteClient, 200) assert(!Object.hasOwn(stagedRemote.segment.configuration, "linuxBonds")) assert.deepEqual(await post(bundlePath, { revision: 1 }, 200), bundle) const racing = await Promise.all(["equal", "failover"].map(mode => fetch(origin + "/api/ix/segments" + bondPath, { method: "POST", headers: { authorization: "Bearer " + writer, "content-type": "application/json" }, body: JSON.stringify({ ...bondInput, id: bond.id, revision: 1, mode }), }))) assert.deepEqual(racing.map(r => r.status).sort(), [200, 409]) const revised = await racing.find(r => r.ok)!.json() assert.equal(revised.revision, 2) await post(bundlePath, { revision: 1 }, 409) await post(bondPath + "/" + bond.id, { revision: 2 }, 204, writer, "DELETE") await post(bundlePath, { revision: 2 }, 409) assert.equal(writes, beforeStage) assert.equal(stagedRemote.segment.revision, appliedRevision + 1) assert.equal(stagedRemote.segment.appliedRevision, appliedRevision) const remoteSite = stagedRemote.segment.configuration.sites[0] assert.equal(remoteSite.interfaces.find(row => row.name === stagedRemote.interfaceName).linux.exit, transit.name) const transitBinding = remoteSite.interfaces.find(row => row.name === remoteSite.groups.find(group => group.id === transit.name).primary.interface) assert.equal(transitBinding.peerServerId, Number(exit.id)) const { ixReservedTunnelBindings } = await import("../../src/services/internet-exchange-store.js") assert((await ixReservedTunnelBindings(Number(exit.id))).some(binding => binding.name === transitBinding.name)) const remotePlan = await post(managedPath + "/plan", { revision: stagedRemote.segment.revision }, 200) assert(remotePlan.changes.some(change => change.serverId === Number(exit.id) && change.path === "/ip/firewall/nat" && change.fields["out-interface"] === "ether1")) assert(remotePlan.changes.some(change => change.serverId === Number(server.id) && change.path === "/interface/wireguard")) assert.equal(writes, beforeStage) const both = await post(managedPath + "/linux", { ...clientInput, name: "both", peerEndpoint: "192.0.2.41", revision: stagedRemote.segment.revision, additionalGre: true }, 200) const added = both.segment.configuration.sites[0].interfaces.filter(binding => binding.linux?.name === "both") assert.deepEqual(added.map(binding => binding.kind), ["wireguard", "gre-ipsec"]) assert.ok(added[0].linux.clientId) assert.equal(added[0].linux.clientId, added[1].linux.clientId) await new Promise(resolve => backupRouter.listen(0, "127.0.0.1", resolve)) const { rows: [secondIx] } = await pool.query(`INSERT INTO servers (name,host,port,enabled,type,username,password,use_ssl,verify_ssl) VALUES('owned-bond-peer','127.0.0.1',$1,true,'ix-node','synthetic','synthetic',false,true) RETURNING id`, [(backupRouter.address() as { port: number }).port]) const secondSegment = (await post("", { revision: 0, configuration: { name: "ix-web-bond-peer", sites: [ { serverId: Number(secondIx.id), autonomousSystem: 64513, routerId: "192.0.2.8" }, ] } }, 200)).segment const secondPath = "/" + secondSegment.id const secondInput = { ...clientInput, hubEndpoint: "198.51.100.20", serverId: Number(secondIx.id), revision: secondSegment.revision } await post(secondPath + "/linux", { ...secondInput, vpsClientId: randomUUID() }, 409) const secondWg = await post(secondPath + "/linux", { ...secondInput, vpsClientId: bond.clientId }, 200) const newTunnel = secondWg.segment.configuration.sites[0].interfaces[0] assert.equal(newTunnel.linux.clientId, bond.clientId) assert.notEqual(newTunnel.provisionWireguard.peerAddress, wireguard.provisionWireguard.peerAddress) const secondaryPlan = await post(secondPath + "/plan", { revision: secondWg.segment.revision }, 200) const secondaryApplied = (await post(secondPath + "/apply", { revision: secondWg.segment.revision, digest: secondaryPlan.digest }, 200)).segment const cross = await post(bondPath, { ...bondInput, members: [bondInput.members[0], { segmentId: secondSegment.id, appliedRevision: secondaryApplied.revision, serverId: secondInput.serverId, interfaceName: secondWg.interfaceName, weight: 1, }] }, 200) await post(secondPath + "/removal-plan", { revision: secondaryApplied.revision }, 409) const crossBundle = await post(bondPath + "/" + cross.id + "/export", { revision: 1 }, 200) assert.equal(crossBundle.members[1].address, newTunnel.provisionWireguard.peerAddress) await post(bondPath + "/" + cross.id, { revision: 1 }, 204, writer, "DELETE") await post(secondPath + "/removal-plan", { revision: secondaryApplied.revision }, 200) console.log(JSON.stringify({ appliedRevisions: [2, 4], writes, audit: audit.n, mcpConnections: connections.n, unauthenticated: 401, readOnly: 403, ownerMismatch: 409, drift: 409, replay: 409, protected: 409, linuxClients: clients.items.length, deletedDraft: true, removedNativeObjects: deletes, revisionsRetained: archive.revisions, mcpRemovalVerified: true, managedWireguardVerified: true, clientWithTransitStagedAtomically: true, bothProtocolsInOneVrf: true, mixedBondExport: true, crossSegmentBond: true, concurrentBondEdits: true })) } finally { await mcp?.close() await app?.close() await new Promise(resolve => router.close(() => resolve())) if (backupRouter.listening) await new Promise(resolve => backupRouter.close(() => resolve())) await pool.end() await pg.stop() } // As in the MCP integration suite, close the standalone runner after teardown and log flushing. process.stderr.write("", () => process.stdout.write("", () => process.exit()))