From d255694cda654400e702ad8d36126d9768510d84 Mon Sep 17 00:00:00 2001 From: Denozordec Date: Sun, 22 Nov 2026 17:51:05 +0700 Subject: [PATCH] =?UTF-8?q?fix(mcp):=20=D0=B8=D1=81=D0=BF=D1=80=D0=B0?= =?UTF-8?q?=D0=B2=D0=B8=D1=82=D1=8C=20=D0=BF=D1=80=D0=BE=D0=B2=D0=B5=D1=80?= =?UTF-8?q?=D0=BA=D1=83=20=D0=B7=D0=B0=D0=B2=D0=B8=D1=81=D0=B8=D0=BC=D0=BE?= =?UTF-8?q?=D1=81=D1=82=D0=B5=D0=B9=20=D1=82=D1=83=D0=BD=D0=BD=D0=B5=D0=BB?= =?UTF-8?q?=D1=8F=20=D0=BD=D0=B0=20=D0=B1=D0=BE=D0=BB=D1=8C=D1=88=D0=B8?= =?UTF-8?q?=D1=85=20=D1=82=D0=B0=D0=B1=D0=BB=D0=B8=D1=86=D0=B0=D1=85=20?= =?UTF-8?q?=D0=BC=D0=B0=D1=80=D1=88=D1=80=D1=83=D1=82=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mcp/ospf-route-proof-acceptance.ts | 8 +++- .../modules/mcp/ospf-route-proof-actions.ts | 2 +- .../mcp/wireguard-import-acceptance.ts | 6 ++- .../wireguard-interface-create-acceptance.ts | 9 +++- .../wireguard-interface-delete-acceptance.ts | 9 ++-- .../wireguard-interface-update-acceptance.ts | 6 ++- .../mcp/wireguard-peer-create-acceptance.ts | 6 ++- .../mcp/wireguard-revision-acceptance.ts | 6 ++- backend/src/services/ospf-route-proof.test.ts | 23 +++++++++- backend/src/services/ospf-route-proof.ts | 16 +++++-- .../wireguard-dependency-read.test.ts | 29 +++++++++++- .../services/wireguard-interface-delete.ts | 44 +++++++++++++++---- .../services/wireguard-revision-restore.ts | 4 +- 13 files changed, 137 insertions(+), 31 deletions(-) diff --git a/backend/src/modules/mcp/ospf-route-proof-acceptance.ts b/backend/src/modules/mcp/ospf-route-proof-acceptance.ts index 433c61f1..1e8e5205 100644 --- a/backend/src/modules/mcp/ospf-route-proof-acceptance.ts +++ b/backend/src/modules/mcp/ospf-route-proof-acceptance.ts @@ -17,11 +17,15 @@ export async function acceptOspfRouteProofMcp(actor: AuthUser) { const router = createServer(async (req, res) => { res.setHeader("content-type", "application/json") if (req.method === "GET" && req.url === tablePath) { reads++; res.end(JSON.stringify(tables)); return } - if (!["/rest/routing/route", "/rest/routing/route/get"].includes(req.url ?? "")) { res.statusCode = 404; res.end("{}"); return } + const url = new URL(req.url ?? "/", "http://fixture.invalid") + if (!["/rest/routing/route", "/rest/routing/route/get"].includes(url.pathname)) { res.statusCode = 404; res.end("{}"); return } reads++ if (beforeReply) { const hook = beforeReply; beforeReply = undefined; await hook() } if (nativeError) { res.statusCode = 400; res.end('{"message":"NEVER_ROUTE_PROVIDER_TOKEN"}'); return } - if (req.method === "GET") { res.end(JSON.stringify(rows)); return } + if (req.method === "GET") { + if (url.searchParams.get("dst-address") !== selection.prefix || url.searchParams.get("routing-table") !== selection.table) { res.statusCode = 400; res.end("{}"); return } + res.end(JSON.stringify(rows)); return + } let body = ""; for await (const chunk of req) body += chunk const key = JSON.parse(body)["value-name"] if (key === "ospf.metric" && afterMetric) { const hook = afterMetric; afterMetric = undefined; await hook() } diff --git a/backend/src/modules/mcp/ospf-route-proof-actions.ts b/backend/src/modules/mcp/ospf-route-proof-actions.ts index c4586431..8ae51446 100644 --- a/backend/src/modules/mcp/ospf-route-proof-actions.ts +++ b/backend/src/modules/mcp/ospf-route-proof-actions.ts @@ -36,7 +36,7 @@ export function registerOspfRouteProofActions(register: typeof add) { if (error instanceof McpError) throw error throw new McpError("STATE_UNAVAILABLE", input.expectAbsent === true ? "Отсутствие точного префикса во всей выбранной таблице не подтверждено" - : "Активный OSPF-маршрут, его метрика или выбранный выход не подтверждены; предел источника 10000 строк и 1 МиБ", 409) + : "Активный OSPF-маршрут, его метрика или выход через указанный интерфейс не подтверждены", 409) } }, }) diff --git a/backend/src/modules/mcp/wireguard-import-acceptance.ts b/backend/src/modules/mcp/wireguard-import-acceptance.ts index 55865132..f20e1da1 100644 --- a/backend/src/modules/mcp/wireguard-import-acceptance.ts +++ b/backend/src/modules/mcp/wireguard-import-acceptance.ts @@ -35,9 +35,11 @@ export async function acceptWireguardImport(actor: AuthUser) { 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 path = decodeURIComponent((req.url ?? "").replace(/^\/rest/, "")) + 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(rows[path])); return } + 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", () => { diff --git a/backend/src/modules/mcp/wireguard-interface-create-acceptance.ts b/backend/src/modules/mcp/wireguard-interface-create-acceptance.ts index 1c8b45fa..202b8024 100644 --- a/backend/src/modules/mcp/wireguard-interface-create-acceptance.ts +++ b/backend/src/modules/mcp/wireguard-interface-create-acceptance.ts @@ -24,18 +24,23 @@ export async function acceptWireguardInterfaceCreation(actor: AuthUser) { initial["/interface"] = [{ ".id": "*af", name: "wg-foreign", type: "wg" }] initial["/ip/address"] = [{ ".id": "*vf", address: "203.0.113.2/24", interface: "ether1", dynamic: "false", disabled: "false" }] initial["/ipv6/address"] = [] + initial["/ip/route"] = Array.from({ length: 12_608 }, (_, index) => ({ + ".id": `*r${index.toString(16)}`, dynamic: "true", bgp: "true", gateway: "192.0.2.1", "immediate-gw": "192.0.2.1%ether1", + })) let rows = structuredClone(initial), mode = "normal", reads = 0, commands: string[] = [], counter = 0 let afterWrite: (() => Promise) | undefined const reset = () => { rows = structuredClone(initial); mode = "normal"; commands = []; counter = 0; afterWrite = undefined } const router = createServer((req, res) => { res.setHeader("content-type", "application/json") - const path = decodeURIComponent((req.url ?? "").slice(5)) + 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")) if (req.method === "GET") { reads++ if (mode === "provider-error") { res.statusCode = 400; res.end('{"message":"NEVER_PROVIDER_SECRET"}'); return } if (!Object.hasOwn(rows, path)) { res.statusCode = 404; res.end("{}"); return } rows["/interface/wireguard/peers"][0].rx = String(reads) - res.end(JSON.stringify(rows[path])); return + res.end(JSON.stringify(selectedRows())); return } const base = ["/interface/wireguard/peers", "/interface/wireguard", "/ip/address", "/ipv6/address"].find(base => path === base || path.startsWith(base + "/")) if (!base || !["PUT", "PATCH"].includes(req.method ?? "")) { res.statusCode = 400; res.end("{}"); return } diff --git a/backend/src/modules/mcp/wireguard-interface-delete-acceptance.ts b/backend/src/modules/mcp/wireguard-interface-delete-acceptance.ts index 39b3c8aa..714a347e 100644 --- a/backend/src/modules/mcp/wireguard-interface-delete-acceptance.ts +++ b/backend/src/modules/mcp/wireguard-interface-delete-acceptance.ts @@ -26,7 +26,9 @@ export async function acceptWireguardInterfaceDeletion(actor: AuthUser) { let duringRead: (() => Promise) | undefined const router = createServer((req, res) => { res.setHeader("content-type", "application/json") - const path = decodeURIComponent((req.url ?? "").slice(5)) + 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")) if (req.method === "GET") { gets++ const respond = () => { @@ -34,7 +36,7 @@ export async function acceptWireguardInterfaceDeletion(actor: AuthUser) { if (!Object.hasOwn(rows, path)) { res.statusCode = 404; res.end("{}"); return } // Runtime traffic and DHCP lease clocks must not become configuration drift. rows["/interface/wireguard/peers"].find(row => row[".id"] === "*pf")!.rx = String(gets) - res.end(JSON.stringify(rows[path])) + res.end(JSON.stringify(selectedRows())) } if (duringRead) { const hook = duringRead; duringRead = undefined; void hook().then(respond, () => { res.statusCode = 503; res.end("{}"); }); return } respond(); return @@ -89,7 +91,8 @@ export async function acceptWireguardInterfaceDeletion(actor: AuthUser) { await assert.rejects(prepare(true), (error: { code?: string }) => error.code === "DEPENDENCY_CONFLICT") assert.equal(commands.length, 0, "Native alias must not acquire cascade permission") for (const [path, row] of [ - ["/interface/list/member", { interface: "wg-cascade", list: "LAN" }], ["/interface/vxlan", { interface: "wg-cascade" }], ["/ip/route", { gateway: "198.19.244.2%wg-cascade" }], + ["/interface/list/member", { interface: "wg-cascade", list: "LAN" }], ["/interface/vxlan", { interface: "wg-cascade" }], + ["/ip/route", { gateway: "wg-cascade" }], ["/ip/route", { dynamic: "true", "immediate-gw": "198.19.244.2%wg-cascade" }], ["/routing/filter/rule", { rule: 'set gw "wg-cascade";' }], ["/ip/firewall/filter", { "in-interface": "wg-cascade" }], ["/ip/dhcp-server", { interface: "wg-cascade" }], ["/routing/filter/rule", { rule: 'set gw "wg\\2dcascade";' }], ["/ip/ipsec/peer", { "local-address": "198.19.244.1" }], ["/routing/bgp/session", { dynamic: "true", "local.address": "2001:0db8:0244:0:0:0:0:1" }], diff --git a/backend/src/modules/mcp/wireguard-interface-update-acceptance.ts b/backend/src/modules/mcp/wireguard-interface-update-acceptance.ts index 6cb1ca70..735b7842 100644 --- a/backend/src/modules/mcp/wireguard-interface-update-acceptance.ts +++ b/backend/src/modules/mcp/wireguard-interface-update-acceptance.ts @@ -31,13 +31,15 @@ export async function acceptWireguardInterfaceUpdate(actor: AuthUser) { const reset = () => { rows = structuredClone(initial); commands = []; mode = "normal"; afterWrite = undefined } const router = createServer((req, res) => { res.setHeader("content-type", "application/json") - const path = decodeURIComponent((req.url ?? "").slice(5)) + 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")) if (req.method === "GET") { reads++ if (mode === "provider-error") { res.statusCode = 500; res.end('{"message":"NEVER_PROVIDER_SECRET"}'); return } if (!Object.hasOwn(rows, path)) { res.statusCode = 404; res.end("{}"); return } rows["/interface/wireguard/peers"][0].rx = String(reads) - res.end(JSON.stringify(rows[path])); return + res.end(JSON.stringify(selectedRows())); return } const base = ["/interface/wireguard", "/ip/address", "/ipv6/address"].find(base => path === base || path.startsWith(base + "/")) if (!base || !["PUT", "PATCH", "DELETE"].includes(req.method ?? "")) { res.statusCode = 400; res.end("{}"); return } diff --git a/backend/src/modules/mcp/wireguard-peer-create-acceptance.ts b/backend/src/modules/mcp/wireguard-peer-create-acceptance.ts index 5bf3046a..7aa7aaa2 100644 --- a/backend/src/modules/mcp/wireguard-peer-create-acceptance.ts +++ b/backend/src/modules/mcp/wireguard-peer-create-acceptance.ts @@ -33,13 +33,15 @@ export async function acceptWireguardPeerCreation(actor: AuthUser) { const reset = () => { rows = structuredClone(initial); mode = "normal"; commands = []; afterWrite = undefined } const router = createServer((req, res) => { res.setHeader("content-type", "application/json") - const path = decodeURIComponent((req.url ?? "").slice(5)), base = "/interface/wireguard/peers" + const [pathname, query] = (req.url ?? "").slice(5).split("?") + const path = decodeURIComponent(pathname), base = "/interface/wireguard/peers" + const selectedRows = () => rows[path].filter(row => !query || (row.dynamic === "true") === query.startsWith("dynamic=true")) if (req.method === "GET") { reads++ if (mode === "provider-error" || mode === "dependency-error" && path === "/ip/address") { res.statusCode = 400; res.end('{"message":"NEVER_PROVIDER_SECRET"}'); return } if (!Object.hasOwn(rows, path)) { res.statusCode = 404; res.end("{}"); return } rows[base][0].rx = String(reads) - res.end(JSON.stringify(rows[path])); return + res.end(JSON.stringify(selectedRows())); return } if (!["PUT", "PATCH"].includes(req.method ?? "") || !(path === base || path === base + "/*c")) { res.statusCode = 400; res.end("{}"); return } let raw = "" diff --git a/backend/src/modules/mcp/wireguard-revision-acceptance.ts b/backend/src/modules/mcp/wireguard-revision-acceptance.ts index 832d3610..e6b4fb06 100644 --- a/backend/src/modules/mcp/wireguard-revision-acceptance.ts +++ b/backend/src/modules/mcp/wireguard-revision-acceptance.ts @@ -32,8 +32,10 @@ export async function acceptWireguardRevisionRestore(actor:AuthUser){ const reset=()=>{rows=structuredClone(initial);commands=[];mode="normal";afterWrite=undefined} const router=createServer(async(req,res)=>{ res.setHeader("content-type","application/json") - const path=decodeURIComponent((req.url??"").slice(5)) - if(req.method==="GET"){reads++;if(!Object.hasOwn(rows,path)){res.statusCode=404;res.end("{}");return}res.end(JSON.stringify(rows[path]));return} + 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")) + if(req.method==="GET"){reads++;if(!Object.hasOwn(rows,path)){res.statusCode=404;res.end("{}");return}res.end(JSON.stringify(selectedRows()));return} let raw="";for await(const chunk of req)raw+=chunk const body=raw?JSON.parse(raw)as Record:{},base=["/interface/wireguard/peers","/interface/wireguard","/ip/address","/ipv6/address"].find(p=>path===p||path.startsWith(p+"/")) if(!base||!["PUT","PATCH","DELETE"].includes(req.method??"")){res.statusCode=400;res.end("{}");return} diff --git a/backend/src/services/ospf-route-proof.test.ts b/backend/src/services/ospf-route-proof.test.ts index 57e1bba4..786fc24c 100644 --- a/backend/src/services/ospf-route-proof.test.ts +++ b/backend/src/services/ospf-route-proof.test.ts @@ -1,5 +1,5 @@ import assert from "node:assert/strict" -import { readOspfRouteProof } from "./ospf-route-proof.js" +import { readOspfRouteAbsence, readOspfRouteProof } from "./ospf-route-proof.js" import { chrFixtureVrf } from "../modules/mcp/chr-fixture-context.js" const selection = { prefix: "198.19.1.2/32", table: "local-vrf", interface: "owned-gre" } @@ -10,6 +10,27 @@ const client = { get: async () => rows, post: async (_path: string, body: Record const proof = await readOspfRouteProof(client, selection) assert.equal(proof.metric, 60); assert.equal(JSON.stringify(proof).includes("NEVER_"), false) const original = structuredClone(rows) +const largeRib = Array.from({ length: 12_608 }, (_, index) => ({ + ".id": `*r${index.toString(16)}`, "dst-address": `10.${index >> 8}.${index & 255}.0/24`, "routing-table": selection.table, +})) +const exactSelection = { ...selection, table: "test & vrf", interface: "wg test" } +const largeTableClient = { + get: async (path: string) => { + const url = new URL(path, "http://fixture.invalid") + if (url.pathname === "/routing/table") return [{ ".id": "*t", name: exactSelection.table }] + assert.equal(url.pathname, "/routing/route") + assert.equal(url.searchParams.get("routing-table"), exactSelection.table) + const prefix = url.searchParams.get("dst-address") + assert(prefix) + return [...largeRib, { ...original[0], "routing-table": exactSelection.table, "immediate-gw": exactSelection.interface }] + .filter(row => row["routing-table"] === exactSelection.table && row["dst-address"] === prefix) + }, + post: async () => { throw new Error("unexpected getter") }, +} as unknown as Parameters[0] +assert.equal((await readOspfRouteProof(largeTableClient, exactSelection)).interface, "wg test") +await assert.rejects(readOspfRouteProof(largeTableClient, { ...exactSelection, interface: "wg" }), /selected interface/) +await assert.rejects(readOspfRouteAbsence(largeTableClient, exactSelection, async () => {}), /matching route/) +assert.equal((await readOspfRouteAbsence(largeTableClient, { ...exactSelection, prefix: "198.19.1.3/32" }, async () => {})).absenceVerified, true) rows = [{ ...original[0], ospf: "", active: "", "ospf.metric": "" }] getters = []; assert.equal((await readOspfRouteProof(client, selection)).metric, 40); assert.deepEqual(getters, ["ospf", "active", "ospf.metric"]) for (const patch of [{ ospf: "false" }, { active: "false" }, { contribution: "unreachable" }, { "ospf.metric": "unknown" }, { "ospf.metric": "16777216" }, { "immediate-gw": "198.18.1.2%owned-gre-other" }, { "immediate-gw": "198.18.1.2%owned-gre@foreign-vrf" }]) { diff --git a/backend/src/services/ospf-route-proof.ts b/backend/src/services/ospf-route-proof.ts index 23067c10..01471343 100644 --- a/backend/src/services/ospf-route-proof.ts +++ b/backend/src/services/ospf-route-proof.ts @@ -25,10 +25,18 @@ async function readBoundedRows(client: Pick, path: string return rows } +function routeLookupPath(prefix: string, table: string, includeScopedDestinations = false) { + const properties = ".id,dst-address,routing-table,afi,ospf,active,ospf.metric,immediate-gw,contribution" + const destination = includeScopedDestinations ? "" : `&dst-address=${encodeURIComponent(prefix)}` + return `/routing/route?.proplist=${properties}&routing-table=${encodeURIComponent(table)}${destination}` +} + export async function readOspfRouteAbsence(client: Pick, selection: { prefix: string; table: string }, beforeRead: () => Promise) { const prefix = canonicalOspfRouteProofPrefix(selection.prefix) if (!prefix || !selection.table || selection.table.length > 200) throw new OspfRouteProofError("Invalid OSPF route absence context") - const routes = await readBoundedRows(client, "/routing/route", beforeRead) + // RouterOS can render link-local destinations as fe80::%interface/64. + const linkLocal = /^fe[89ab][0-9a-f]:/i.test(prefix) + const routes = await readBoundedRows(client, routeLookupPath(prefix, selection.table, linkLocal), beforeRead) for (const row of routes) { const observed = row["dst-address"] const scoped = typeof observed === "string" ? /^([0-9a-f:]+)%[^/%]+(\/\d+)$/i.exec(observed) : null @@ -52,7 +60,7 @@ export async function readOspfRouteProof(client: Pick 200 || selection.interface.length > 200) throw new OspfRouteProofError("Invalid OSPF route proof context") const family = isIP(prefix.split("/")[0]) - const rows = await readBoundedRows(client, "/routing/route", beforeRead) + const rows = await readBoundedRows(client, routeLookupPath(prefix, selection.table), beforeRead) const matches = rows.filter(row => { if (row["routing-table"] !== selection.table || canonicalOspfRouteProofPrefix(row["dst-address"]) !== prefix) return false const active = flag(row.active) @@ -74,7 +82,9 @@ export async function readOspfRouteProof(client: Pick Object.assign(new Error("fixture reset"), { code: "ECONNRESET" }) +test("large routing tables do not enter a new WireGuard snapshot and still protect existing interfaces", async () => { + const target = { ".id": "*a", name: "wg-new" } + const configured = { ".id": "*b", static: "true", gateway: "wg-new-backup" } + const learned = Array.from({ length: 12_608 }, (_, index) => ({ + ".id": `*r${index.toString(16)}`, dynamic: "true", "immediate-gw": "192.0.2.1%ether1", + })) + const requests: string[] = [] + const read: ReturnType = async (path, query) => { + requests.push(path + query) + return query === "?static=true" ? [configured] : learned + } + const path = "/ip/route" + assert.deepEqual(await readWireguardRouteDependencies(read, path, false), [configured]) + assert.deepEqual(requests, ["/ip/route?static=true"]) + const assertSafe = (routes: Record[]) => assertGreDeleteDependencies({ dependencies: { [path]: routes }, bindings: [], filters: [] }, target) + assertSafe(await readWireguardRouteDependencies(read, path, true)) + assert.match(requests.at(-1)!, /^\/ip\/route\?dynamic=true&\.proplist=.*immediate-gw/) + configured.gateway = target.name + assert.throws(() => assertSafe([configured]), /используется/) + configured.gateway = "ether1" + learned[12_607]["immediate-gw"] = "192.0.2.1%wg-new" + const routes = await readWireguardRouteDependencies(read, path, true) + assert.throws(() => assertSafe(routes), /используется/) + await assert.rejects(readWireguardRouteDependencies(async () => learned, path, false), { code: "STATE_UNAVAILABLE" }) +}) + function fixture(t: TestContext, outcomes: Outcome[]) { const paths: string[] = [], timeouts: number[] = [] t.mock.method(http, "request", (options: http.RequestOptions, receive: (res: unknown) => void) => { diff --git a/backend/src/services/wireguard-interface-delete.ts b/backend/src/services/wireguard-interface-delete.ts index 34bf9fab..3bfa0aad 100644 --- a/backend/src/services/wireguard-interface-delete.ts +++ b/backend/src/services/wireguard-interface-delete.ts @@ -41,22 +41,22 @@ async function source(server: ServerRow, authorize: () => Promise) { const fresh = await getServerRowById(server.id) if (!fresh || !sameWireguardEndpoint(fresh, server)) throw fail("STATE_CONFLICT", "Источник WireGuard изменился") } -function nativeRows(raw: unknown, required: string[] = []): Row[] { - if (!Array.isArray(raw) || raw.length > 2000 || raw.some(row => !row || typeof row !== "object" || Array.isArray(row) || Object.values(row).some(value => typeof value !== "string") || typeof row[".id"] !== "string" || !/^\*[a-z0-9]+$/i.test(row[".id"]) || required.some(key => !row[key]?.trim()))) throw fail("STATE_UNAVAILABLE", "Недостоверный каталог зависимостей WireGuard") +function nativeRows(raw: unknown, required: string[] = [], rowLimit = 2000): Row[] { + if (!Array.isArray(raw) || raw.length > rowLimit || raw.some(row => !row || typeof row !== "object" || Array.isArray(row) || Object.values(row).some(value => typeof value !== "string") || typeof row[".id"] !== "string" || !/^\*[a-z0-9]+$/i.test(row[".id"]) || required.some(key => !row[key]?.trim()))) throw fail("STATE_UNAVAILABLE", "Недостоверный каталог зависимостей WireGuard") if (new Set(raw.map(row => row[".id"])).size !== raw.length) throw fail("STATE_UNAVAILABLE", "Повторяющиеся ID в каталоге WireGuard") return raw as Row[] } /** Retry at most two distinct catalogue GETs per capture, with fresh source authority. */ export function createWireguardDependencyReader(client: Pick, authorizeSource: () => Promise, now = () => performance.now()) { - const timeoutMs = 10_000, maxBytes = 1_048_576 + const timeoutMs = 10_000 const unavailable = () => fail("STATE_UNAVAILABLE", "Не прочитан обязательный источник зависимостей WireGuard") const retriedPaths = new Set() - return async (path: string): Promise => { + return async (path: string, query = "", maxBytes = 1_048_576): Promise => { await authorizeSource() const deadline = now() + timeoutMs try { - return await client.get(path, timeoutMs, undefined, maxBytes) + return await client.get(path + query, timeoutMs, undefined, maxBytes) } catch (error) { const retryableCatalogue = path === "/ip/address" || path === "/ipv6/address" || wireguardInterfaceDependencyPaths.includes(path) if (retriedPaths.size >= 2 || retriedPaths.has(path) || !retryableCatalogue @@ -67,14 +67,40 @@ export function createWireguardDependencyReader(client: Pick Promise = async () => {}): Promise { +const routePaths = new Set(["/ip/route", "/ipv6/route"]) +const routeRowLimit = 50_000 +const routeByteLimit = 8 * 1024 * 1024 + +export async function readWireguardRouteDependencies(read: ReturnType, path: string, existingInterface: boolean) { + const catalogue = async (query: string, dynamic: boolean) => { + const raw = await read(path, query, routeByteLimit) + if (Array.isArray(raw) && raw.length > routeRowLimit) throw markWireguardReadFailure(fail("STATE_UNAVAILABLE", "Превышен предел отфильтрованного каталога маршрутов WireGuard"), path, undefined, "catalogue-limit") + try { + const rows = nativeRows(raw, [], routeRowLimit) + if (rows.some(row => dynamic ? observedBoolean(row.dynamic) !== true : observedBoolean(row.dynamic) === true || observedBoolean(row.static) === false)) throw fail("STATE_UNAVAILABLE", "RouterOS вернул маршруты вне запрошенного фильтра") + return rows + } catch (error) { + if (!(error instanceof McpError)) throw error + throw markWireguardReadFailure(error, path, undefined, "invalid-catalogue") + } + } + const configured = await catalogue("?static=true", false) + if (!existingInterface) return configured + // Preserve checks on learned next hops before editing or removing an existing interface. + const learned = await catalogue("?dynamic=true&.proplist=.id,dynamic,connect,belongs-to,gateway,immediate-gw,vrf-interface,interface,local-address,routing-table", true) + const configuredIds = new Set(configured.map(row => row[".id"])) + if (learned.some(row => configuredIds.has(row[".id"]))) throw markWireguardReadFailure(fail("STATE_UNAVAILABLE", "Маршрут изменился во время сверки зависимостей WireGuard"), path, undefined, "invalid-catalogue") + return [...configured, ...learned] +} + +export async function readWireguardInterfaceDeleteState(server: ServerRow, id: string, authorize: () => Promise = async () => {}, includeLearnedRoutes?: boolean): Promise { const base = await readWireguardPeerDeletionState(server, authorize), client = MikrotikClient.fromServer(server) const readDependency = createWireguardDependencyReader(client, () => source(server, authorize)) let totalRows = base.interfaces.length + base.peers.length, bytes = Buffer.byteLength(JSON.stringify([base.interfaces, base.peers])) @@ -93,8 +119,10 @@ export async function readWireguardInterfaceDeleteState(server: ServerRow, id: s } const ipv4 = await read("/ip/address", ["address", "interface"]), ipv6 = await read("/ipv6/address", ["address", "interface"]) const dependencies: Record = {} - for (const path of wireguardInterfaceDependencyPaths) dependencies[path] = await read(path, path === "/interface" ? ["name"] : []) const parent = base.interfaces.find(row => row[".id"] === id) + for (const path of wireguardInterfaceDependencyPaths) dependencies[path] = routePaths.has(path) + ? await readWireguardRouteDependencies(readDependency, path, includeLearnedRoutes ?? (parent !== undefined)) + : await read(path, path === "/interface" ? ["name"] : []) if (parent && [...ipv4, ...ipv6].filter(row => [parent.name, id].includes(row.interface) && !automaticLinkLocal(row)).length + base.peers.filter(row => [parent.name, id].includes(row.interface)).length > 49) throw fail("STATE_UNAVAILABLE", "Каскад WireGuard превышает предел зависимых объектов") if (parent) for (const [path, rows] of [["/ip/address", ipv4], ["/ipv6/address", ipv6]] as const) for (const row of rows.filter(row => [parent.name, id].includes(row.interface))) { try { diff --git a/backend/src/services/wireguard-revision-restore.ts b/backend/src/services/wireguard-revision-restore.ts index 29e36324..ed7544d5 100644 --- a/backend/src/services/wireguard-revision-restore.ts +++ b/backend/src/services/wireguard-revision-restore.ts @@ -69,11 +69,11 @@ export const wireguardRestoreStateProof=(state:WireguardRestoreState)=>wireguard export async function readWireguardRestoreState(server:ServerRow,beforeRead:()=>Promise=async()=>{}) { const deadline=Date.now()+45000 const authorize=async()=>{if(Date.now()>=deadline)throw fail("Истёк бюджет чтения WireGuard restore","STATE_UNAVAILABLE");await beforeRead();if(Date.now()>=deadline)throw fail("Истёк бюджет чтения WireGuard restore","STATE_UNAVAILABLE")} - const state=await readWireguardInterfaceDeleteState(server,"*0",authorize) + const state=await readWireguardInterfaceDeleteState(server,"*0",authorize,true) if(new Set(state.base.interfaces.map(row=>row.name)).size!==state.base.interfaces.length||state.base.interfaces.some(row=>!row.name)||state.base.peers.some(peer=>state.base.interfaces.filter(row=>row.name===peer.interface||row[".id"]===peer.interface).length!==1))throw fail("Неоднозначные родители WireGuard") // Selected-parent reads corroborate dynamic origins; the *0 inventory alone does not. for(const parent of state.base.interfaces){ - const selected=await readWireguardInterfaceDeleteState(server,parent[".id"],authorize),comparison=structuredClone(selected) + const selected=await readWireguardInterfaceDeleteState(server,parent[".id"],authorize,false),comparison=structuredClone(selected) for(const resource of ["ipv4","ipv6"]as const)for(const row of comparison[resource]){const previous=state[resource].find(a=>a[".id"]===row[".id"]);if(previous?.dynamic===undefined)delete row.dynamic;else row.dynamic??=previous.dynamic} if(await wireguardRestoreStateProof(comparison)!==await wireguardRestoreStateProof(state))throw fail("WireGuard изменился во время инвентаризации") for(const resource of ["ipv4","ipv6"]as const)for(const row of state[resource]){const observed=selected[resource].find(a=>a[".id"]===row[".id"]&&a.interface===row.interface);if(observed?.dynamic!==undefined)row.dynamic=observed.dynamic}