Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d255694cda |
No files matched your search
@@ -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() }
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
@@ -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", () => {
|
||||
|
||||
@@ -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<unknown>) | 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 }
|
||||
|
||||
@@ -26,7 +26,9 @@ export async function acceptWireguardInterfaceDeletion(actor: AuthUser) {
|
||||
let duringRead: (() => Promise<unknown>) | 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" }],
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -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 = ""
|
||||
|
||||
@@ -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<string,string>:{},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}
|
||||
|
||||
@@ -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<typeof readOspfRouteProof>[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" }]) {
|
||||
|
||||
@@ -25,10 +25,18 @@ async function readBoundedRows(client: Pick<MikrotikClient, "get">, 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<MikrotikClient, "get">, selection: { prefix: string; table: string }, beforeRead: () => Promise<unknown>) {
|
||||
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<MikrotikClient, "get" | "p
|
||||
const prefix = canonicalOspfRouteProofPrefix(selection.prefix)
|
||||
if (!prefix || !selection.table || !selection.interface || selection.table.length > 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<MikrotikClient, "get" | "p
|
||||
if (metric === null) throw new OspfRouteProofError("OSPF route metric not confirmed")
|
||||
const gateway = typeof row["immediate-gw"] === "string" ? row["immediate-gw"] : ""
|
||||
const context = /^([^%@]+)%([^@]+)(?:@([^@]+))?$/.exec(gateway)
|
||||
if (!context || isIP(context[1]) !== family || context[2] !== selection.interface || context[3] && context[3] !== selection.table) throw new OspfRouteProofError("OSPF route does not resolve through the selected interface/VRF")
|
||||
const directInterface = gateway === selection.interface && !isIP(gateway)
|
||||
const scopedInterface = context && isIP(context[1]) === family && context[2] === selection.interface && (!context[3] || context[3] === selection.table)
|
||||
if (!directInterface && !scopedInterface) throw new OspfRouteProofError("OSPF route does not resolve through the selected interface/VRF")
|
||||
await beforeRead()
|
||||
return { id: String(row[".id"]), family: family === 4 ? "ipv4" : "ipv6", prefix: selection.prefix, table: selection.table, interface: selection.interface, immediateGateway: gateway, ospf: true, active: true, metric }
|
||||
}
|
||||
@@ -3,12 +3,39 @@ import { EventEmitter } from "node:events"
|
||||
import http from "node:http"
|
||||
import { test, type TestContext } from "node:test"
|
||||
import { isRouterOsPreHeaderGetReset, MikrotikClient } from "./mikrotik.js"
|
||||
import { createWireguardDependencyReader } from "./wireguard-interface-delete.js"
|
||||
import { createWireguardDependencyReader, readWireguardRouteDependencies } from "./wireguard-interface-delete.js"
|
||||
import { assertGreDeleteDependencies } from "./gre-mutation-state.js"
|
||||
import { wireguardReadDiagnostic } from "./wireguard-read-diagnostic.js"
|
||||
|
||||
type Outcome = "reset" | "late-reset" | "informational-reset" | "body-reset" | "ok" | "refused" | "invalid-json"
|
||||
const reset = () => 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<typeof createWireguardDependencyReader> = 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<string, string>[]) => 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) => {
|
||||
|
||||
@@ -41,22 +41,22 @@ async function source(server: ServerRow, authorize: () => Promise<unknown>) {
|
||||
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<MikrotikClient, "get">, authorizeSource: () => Promise<unknown>, 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<string>()
|
||||
return async (path: string): Promise<unknown> => {
|
||||
return async (path: string, query = "", maxBytes = 1_048_576): Promise<unknown> => {
|
||||
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<MikrotikClient, "ge
|
||||
const remaining = Math.floor(deadline - now())
|
||||
if (remaining < 1) throw markWireguardReadFailure(unavailable(), path, 2, "read-deadline")
|
||||
try {
|
||||
return await client.get(path, remaining, undefined, maxBytes)
|
||||
return await client.get(path + query, remaining, undefined, maxBytes)
|
||||
} catch (error) {
|
||||
throw markWireguardGetFailure(unavailable(), path, 2, error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function readWireguardInterfaceDeleteState(server: ServerRow, id: string, authorize: () => Promise<unknown> = async () => {}): Promise<WireguardInterfaceDeleteState> {
|
||||
const routePaths = new Set(["/ip/route", "/ipv6/route"])
|
||||
const routeRowLimit = 50_000
|
||||
const routeByteLimit = 8 * 1024 * 1024
|
||||
|
||||
export async function readWireguardRouteDependencies(read: ReturnType<typeof createWireguardDependencyReader>, 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<unknown> = async () => {}, includeLearnedRoutes?: boolean): Promise<WireguardInterfaceDeleteState> {
|
||||
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<string, Row[]> = {}
|
||||
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 {
|
||||
|
||||
@@ -69,11 +69,11 @@ export const wireguardRestoreStateProof=(state:WireguardRestoreState)=>wireguard
|
||||
export async function readWireguardRestoreState(server:ServerRow,beforeRead:()=>Promise<unknown>=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}
|
||||
|
||||
Reference in new issue
Block a user