Files
MikrotikManager/backend/src/modules/mcp/control-path-context.ts
T

89 lines
7.6 KiB
TypeScript

import { isConfirmedRoutingFibTable } from "../../services/routing-table-fib.js"
import type { RouteAiProfile } from "@mmapp/contracts/mcp-routing"
import { nativeBgpRows, type NativeBgpRow } from "../../services/bgp-export-model.js"
import { stableBgpPolicyRow } from "../../services/bgp-filter-binding-model.js"
import { readOspfEffectiveDisabled } from "../../services/ospf-effective-disabled.js"
import { fingerprint, McpError, privateFingerprinter, constantEqual } from "./security.js"
import { createRoutingSourceContext, readRoutingEndpoints } from "./routing-observation-source.js"
import { routeContextClients } from "./routing-community-context-native.js"
import { readMeasurementAddress } from "./routing-measurement-address.js"
import type { RouteContextOptions } from "./routing-community-context.js"
import { controlPathVrfOwner } from "./control-path-model.js"
import { pathProofTag } from "./path-proof-purpose.js"
/** A diagnostic proof has no BGP/community dependency and cannot authorize a
* Community switch. Its endpoint, membership and address evidence is private. */
export async function readControlPathContext(profile: RouteAiProfile, candidateId: string, options: RouteContextOptions = {}) {
try {
const candidate = profile.candidates.find(candidate => candidate.id === candidateId), probe = candidate?.controlProbe
if (!candidate || !probe) throw new McpError("MEASUREMENT_UNKNOWN", "Контрольный probe пути не настроен", 409)
const authorize = async () => {
if (options.signal?.aborted) throw new McpError("READ_CANCELLED", "Контрольный путь отменён", 409)
await options.authorize?.()
}
await authorize()
const ids = [...new Set([profile.serverId, candidate.jumpHostId, candidate.exitNodeId, ...probe.expectedHops.map(hop => hop.serverId)])].sort((a, b) => a - b)
const endpoints = await readRoutingEndpoints(ids)
if (endpoints.length !== ids.length || endpoints.some(endpoint => !endpoint.enabled)) throw new McpError("DEVICE_UNAVAILABLE", "Источник контрольного пути отсутствует или отключён", 409)
const sources = await createRoutingSourceContext(endpoints)
if (options.expectedSources && fingerprint(sources.expected) !== fingerprint(options.expectedSources)) throw new McpError("STATE_CONFLICT", "Источник контрольного пути изменился; новый endpoint не опрашивается", 409)
const sign = await privateFingerprinter("route-control-path-context-v1"), clients = routeContextClients(endpoints, options.signal)
const fence = async () => { await authorize(); await sources.assertCurrent() }
const snapshots: unknown[] = [], cache = new Map<string, NativeBgpRow[]>()
let rowsRead = 0
const get = async (serverId: number, path: string) => {
const key = serverId + path, cached = cache.get(key)
if (cached) return cached
await fence()
const rows = nativeBgpRows(await clients.get(serverId)!.get<unknown>(path))
if (rows.length > 1000 || (rowsRead += rows.length) > 10000) throw new McpError("LIMIT_EXCEEDED", "Каталог контрольного пути превышает лимит", 409)
cache.set(key, rows)
snapshots.push({ serverId, path, rows: rows.map(row => path === "/interface" ? Object.fromEntries(Object.entries(row).filter(([key]) => !/^(?:rx-|tx-|fp-|last-link-|link-downs$|driver-)/.test(key))) : stableBgpPolicyRow(row)) })
return rows
}
const post = async (serverId: number, path: string, body: Record<string, string>) => {
await fence()
const value = await clients.get(serverId)!.post<unknown>(path, body)
snapshots.push({ serverId, path, body, value }); return value
}
const enabled = async (serverId: number, path: string, row: NativeBgpRow) => {
const [effective] = await readOspfEffectiveDisabled<NativeBgpRow & { disabled?: string }>([row], id => post(serverId, path + "/get", { ".id": id, "value-name": "disabled" }))
if (![false, "false", "no"].includes(effective.disabled as string | boolean) || [true, "true", "yes"].includes(effective.invalid as string | boolean)) throw new McpError("STATE_UNAVAILABLE", "Зависимость контрольного пути отключена или неизвестна", 409)
return effective
}
const unique = (rows: NativeBgpRow[], name: string) => {
const matching = rows.filter(row => row.name === name)
if (matching.length !== 1) throw new McpError("STATE_UNAVAILABLE", "Имя зависимости контрольного пути неоднозначно", 409)
return matching[0]
}
const sourceId = profile.serverId, table = unique(await get(sourceId, "/routing/table"), profile.probeVrf)
if (!isConfirmedRoutingFibTable(table)) throw new McpError("STATE_UNAVAILABLE", "FIB probe VRF контрольного пути не подтверждён", 409)
const vrfs = await get(sourceId, "/ip/vrf"), effectiveVrfs: NativeBgpRow[] = []
await enabled(sourceId, "/ip/vrf", unique(vrfs, profile.probeVrf))
for (const row of vrfs) effectiveVrfs.push([true, "true", "yes"].includes(row.disabled as string | boolean) ? row : await enabled(sourceId, "/ip/vrf", row))
const interfaces = await get(sourceId, "/interface")
await enabled(sourceId, "/interface", unique(interfaces, candidate.wanInterface))
if (controlPathVrfOwner(effectiveVrfs, new Set(interfaces.map(row => String(row.name))), candidate.wanInterface) !== profile.probeVrf) throw new McpError("STATE_CONFLICT", "WAN интерфейс не принадлежит probe VRF контрольного пути", 409)
const address = async (serverId: number, iface: string, selected?: string) => {
await enabled(serverId, "/interface", unique(await get(serverId, "/interface"), iface))
const path = profile.family === "ipv4" ? "/ip/address" : "/ipv6/address"
const result = await readMeasurementAddress(await get(serverId, path), { dstInterface: iface, dstAddress: selected, family: profile.family }, id => post(serverId, path + "/get", { ".id": id, "value-name": "disabled" }))
if (result.linkLocal) throw new McpError("STATE_UNAVAILABLE", "Link-local контрольный путь требует отдельного scoped probe", 409)
return result.address
}
const destination = await address(candidate.exitNodeId, probe.targetInterface, probe.targetAddress), expected: string[] = []
for (const hop of probe.expectedHops) expected.push(await address(hop.serverId, hop.interface, hop.address))
const source = await address(sourceId, candidate.wanInterface, probe.sourceAddress)
await fence()
const dependencyProof = sign("dependencies:" + fingerprint({ profile, candidateId, sources: sources.expected, snapshots }))
const before = { contextVerified: true, proofPurpose: "control-path" as const, probeVrf: profile.probeVrf, family: profile.family, dependencyProof, targetRuleProof: null, sourceProofs: sources.expected }
return { before, clients, fence, probeEndpoints: new Map([[candidateId, { destination, expected, source }]]),
signEvidence: (value: unknown) => sign(pathProofTag("control-path") + fingerprint({ dependencyProof, value })),
verifyEvidence: (value: unknown, proof: unknown) => typeof proof === "string" && constantEqual(sign(pathProofTag("control-path") + fingerprint({ dependencyProof, value })), proof),
}
} catch (error) {
if (error instanceof McpError) throw error
throw new McpError("STATE_UNAVAILABLE", "Не подтверждены ограниченные зависимости контрольного пути", 409)
}
}