Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 10m33s
Docker images / frontend-image (push) Successful in 2m11s
Docker images / updater-image (push) Successful in 39s
Docker images / backend-image (push) Canceled after 0s
Docker images / netflow-agent-image (push) Canceled after 8s
Docker images / publish-release (push) Canceled after 0s
Docker images / notify-webhook (push) Canceled after 0s
292 lines
19 KiB
TypeScript
292 lines
19 KiB
TypeScript
import { isIP } from "node:net"
|
|
import { ospfFilterFields, readRosSnapshot, readRoutingPolicySnapshot, type ConfigurationRow, type RosSnapshot, type RosStep } from "./resources.js"
|
|
import { McpError } from "./security.js"
|
|
import type { ChangeEvidence } from "./action-types.js"
|
|
import { gatewayReferencesTable, isDynamicRouteInsideTable } from "../../services/routing-gateway-reference.js"
|
|
import { resolveOspfRouterIdRow } from "../../services/ospf-identity-catalog.js"
|
|
import { canonicalBgpPolicyPrefix } from "../../services/bgp-community-policy-model.js"
|
|
import type { McpObjectRef } from "@mmapp/contracts/mcp"
|
|
|
|
export const ospfInterfaceResources = ["ethernet", "bridge", "vlan", "gre", "wireguard", "vxlan"]
|
|
|
|
export async function addOspfPrefixListDependencies(serverId: number, oldList: unknown, desiredList: unknown, snapshots: RosSnapshot[], objects: ChangeEvidence["objects"], beforeRead?: () => Promise<unknown>) {
|
|
if (desiredList !== undefined && (typeof desiredList !== "string" || desiredList !== desiredList.trim())) {
|
|
throw new McpError("STATE_UNAVAILABLE", "Не подтверждено имя prefix-list OSPFv3", 409)
|
|
}
|
|
const references = new Set([oldList, desiredList].filter(value => typeof value === "string" && value))
|
|
if (!references.size) return
|
|
const kind = "ipv6_address_list"
|
|
let snapshot = snapshots.find(row => row.resource === "routing_policy:" + kind && row.serverId === serverId)
|
|
if (!snapshot) {
|
|
snapshot = await readRoutingPolicySnapshot(serverId, kind, snapshots[0]?.sourceProof, beforeRead)
|
|
snapshots.push(snapshot)
|
|
}
|
|
let found = false
|
|
for (const row of snapshot.rows) {
|
|
if (!references.has(row.list)) continue
|
|
const id = row[".id"]
|
|
if (typeof id !== "string" || objects.length >= 1000) throw new McpError("STATE_UNAVAILABLE", "Не подтверждены записи prefix-list OSPFv3", 409)
|
|
objects.push({ kind, id, serverId })
|
|
if (row.list !== desiredList || [true, "true", "yes"].includes(row.disabled as string | boolean)) continue
|
|
const address = String(row.address)
|
|
try {
|
|
if (isIP(address.split("/")[0]) !== 6) throw new Error("Expected IPv6")
|
|
canonicalBgpPolicyPrefix(address.includes("/") ? address : address + "/128")
|
|
} catch {
|
|
throw new McpError("STATE_CONFLICT", "Prefix-list OSPFv3 требует явных адресов или префиксов IPv6", 409)
|
|
}
|
|
if (![null, false, "false", "no"].includes(row.dynamic as string | boolean | null) || row.timed !== false) {
|
|
throw new McpError("STATE_CONFLICT", "Prefix-list OSPFv3 содержит временную запись", 409)
|
|
}
|
|
if (![null, false, "false", "no"].includes(row.disabled as string | boolean | null)) {
|
|
throw new McpError("STATE_UNAVAILABLE", "Не подтверждена активность записи prefix-list OSPFv3", 409)
|
|
}
|
|
found = true
|
|
}
|
|
if (desiredList && !found) throw new McpError("NOT_FOUND", "Не найдены активные IPv6-записи prefix-list OSPFv3", 404)
|
|
}
|
|
|
|
export async function resolveOspfInterfaceSelectors(serverId: number, selectors: string[], knownInterfaces: Set<string>, snapshots: RosSnapshot[], objects: McpObjectRef[], beforeRead?: () => Promise<unknown>) {
|
|
const source = snapshots[0]?.sourceProof
|
|
const read = async (kind: string) => {
|
|
const existing = snapshots.find(row => row.serverId === serverId && row.resource === kind)
|
|
if (existing) return existing
|
|
const snapshot = await readRosSnapshot(serverId, kind, beforeRead, source)
|
|
snapshots.push(snapshot)
|
|
return snapshot
|
|
}
|
|
const lists = await read("interface_list")
|
|
const builtins = ["all", "none", "static", "dynamic"]
|
|
if (selectors.every(name => !builtins.includes(name) && knownInterfaces.has(name) && !lists.rows.some(row => row.name === name))) {
|
|
return new Set(selectors)
|
|
}
|
|
const [members, interfaces] = await Promise.all([read("interface_list_member"), read("interface_inventory")])
|
|
const fail = () => new McpError("STATE_CONFLICT", "Не подтверждён состав списка интерфейсов OSPF", 409)
|
|
const refs = new Set(objects.map(object => `${object.kind}/${object.id}`))
|
|
const add = (kind: string, row: ConfigurationRow) => {
|
|
const id = row[".id"]
|
|
if (typeof id !== "string" || !/^\*[a-z0-9]+$/i.test(id)) throw fail()
|
|
const key = `${kind}/${id}`
|
|
if (refs.has(key)) return
|
|
if (objects.length >= 1000) throw fail()
|
|
refs.add(key)
|
|
objects.push({ kind, id, serverId })
|
|
}
|
|
const flag = (value: unknown) => {
|
|
if ([true, "true", "yes"].includes(value as boolean | string)) return true
|
|
if ([undefined, false, "false", "no"].includes(value as boolean | string | undefined)) return false
|
|
throw fail()
|
|
}
|
|
const lookup = (rows: ConfigurationRow[], key: string) => {
|
|
const matches = rows.filter(row => row.name === key || row[".id"] === key)
|
|
if (matches.length > 1) throw fail()
|
|
return matches[0]
|
|
}
|
|
const includeNames = (value: unknown) => {
|
|
if (value === undefined || value === "") return []
|
|
if (typeof value !== "string") throw fail()
|
|
const names = value.split(",").map(name => name.trim())
|
|
if (names.some(name => !name)) throw fail()
|
|
return names
|
|
}
|
|
const cache = new Map<string, Set<ConfigurationRow>>()
|
|
const visiting = new Set<ConfigurationRow>()
|
|
const resolve = (key: string, nested: boolean): Set<ConfigurationRow> => {
|
|
if (!key) throw fail()
|
|
const list = lookup(lists.rows, key)
|
|
const direct = nested ? undefined : lookup(interfaces.rows, key)
|
|
if (direct && (list || builtins.includes(key))) throw fail()
|
|
if (direct) return new Set([direct])
|
|
const name = String(list?.name ?? key)
|
|
if (list && builtins.includes(name)) add("interface_list", list)
|
|
if (name === "none") return new Set()
|
|
if (name === "all" || name === "static" || name === "dynamic") {
|
|
if ([...knownInterfaces].some(interfaceName => !lookup(interfaces.rows, interfaceName))) throw fail()
|
|
return new Set(interfaces.rows.filter(row => name === "all" || flag(row.dynamic) === (name === "dynamic")))
|
|
}
|
|
if (!list || flag(list.dynamic) || visiting.has(list)) throw fail()
|
|
const id = String(list[".id"])
|
|
const cached = cache.get(id)
|
|
if (cached) return cached
|
|
add("interface_list", list)
|
|
visiting.add(list)
|
|
const selection = new Set<ConfigurationRow>()
|
|
for (const reference of includeNames(list.include)) for (const row of resolve(reference, true)) selection.add(row)
|
|
for (const reference of includeNames(list.exclude)) for (const row of resolve(reference, true)) selection.delete(row)
|
|
for (const row of members.rows.filter(row => row.list === name || row.list === id)) {
|
|
add("interface_list_member", row)
|
|
if (flag(row.disabled)) continue
|
|
if (flag(row.dynamic)) throw fail()
|
|
const member = typeof row.interface === "string" ? lookup(interfaces.rows, row.interface) : undefined
|
|
if (!member) throw fail()
|
|
selection.add(member)
|
|
}
|
|
visiting.delete(list)
|
|
cache.set(id, selection)
|
|
return selection
|
|
}
|
|
const names = new Set<string>()
|
|
for (const selector of selectors) for (const row of resolve(selector, false)) {
|
|
if (typeof row.name !== "string" || !row.name || lookup(interfaces.rows, row.name) !== row) throw fail()
|
|
add("interface", row)
|
|
names.add(row.name)
|
|
}
|
|
return names
|
|
}
|
|
|
|
function bgpAddressFamily(value: string): number {
|
|
if (!value.includes("/")) return isIP(value)
|
|
try {
|
|
return isIP(canonicalBgpPolicyPrefix(value).split("/")[0])
|
|
} catch {
|
|
return 0
|
|
}
|
|
}
|
|
|
|
export async function addRoutingDependencies(serverId: number, resource: string, action: RosStep["action"], current: ConfigurationRow | undefined, fields: Record<string, string>, snapshots: RosSnapshot[], objects: ChangeEvidence["objects"]) {
|
|
const read = async (id: string) => {
|
|
const existing = snapshots.find(snapshot => snapshot.resource === id)
|
|
if (existing) return existing
|
|
const snapshot = await readRosSnapshot(serverId, id); snapshots.push(snapshot); return snapshot
|
|
}
|
|
const parent = async (resource: string, reference: unknown) => {
|
|
const snapshot = await read(resource)
|
|
const row = snapshot.rows.find(row => row.name === reference || row[".id"] === reference)
|
|
if (!row || typeof row[".id"] !== "string" || action !== "delete" && row.disabled === "true") throw new McpError("STATE_CONFLICT", "Не подтверждена зависимость маршрутизации: " + resource, 409)
|
|
objects.push({ kind: resource, id: row[".id"], serverId })
|
|
return row
|
|
}
|
|
const vrf = async (reference: unknown) => {
|
|
const row = await parent("vrf", reference ?? "main")
|
|
await parent("routing_table", row.name)
|
|
}
|
|
const instance = async (reference: unknown) => {
|
|
const row = await parent("ospf_instance", reference)
|
|
await vrf(row.vrf ?? "main")
|
|
if (row["routing-table"]) await parent("routing_table", row["routing-table"])
|
|
return row
|
|
}
|
|
if (["ospf_instance", "bgp_instance", "bfd_configuration", "bgp_connection"].includes(resource)) {
|
|
for (const reference of new Set([current?.vrf, fields.vrf].filter(value => value !== undefined))) await vrf(reference)
|
|
if (["ospf_instance", "bgp_instance"].includes(resource)) for (const reference of new Set([current?.["routing-table"], fields["routing-table"]].filter(value => value !== undefined))) await parent("routing_table", reference)
|
|
}
|
|
if (resource === "bfd_configuration" && (current?.["address-list"] || fields["address-list"])) {
|
|
const desired = action === "delete" ? undefined : fields["address-list"] ?? current?.["address-list"]
|
|
const names = new Set([current?.["address-list"], desired].filter(value => typeof value === "string" && value))
|
|
let foundDesired = false
|
|
for (const kind of ["ip_address_list", "ipv6_address_list"]) {
|
|
const snapshot = await readRoutingPolicySnapshot(serverId, kind, snapshots[0]?.sourceProof)
|
|
snapshots.push(snapshot)
|
|
for (const row of snapshot.rows.filter(row => names.has(row.list))) {
|
|
const id = row[".id"]
|
|
if (typeof id !== "string" || !/^\*[a-z0-9]+$/i.test(id) || objects.length >= 1000) throw new McpError("STATE_UNAVAILABLE", "Не подтверждены записи address-list BFD", 409)
|
|
objects.push({ kind, id, serverId })
|
|
if (row.list !== desired) continue
|
|
try {
|
|
const address = String(row.address), family = kind === "ip_address_list" ? 4 : 6
|
|
if (isIP(address.split("/")[0]) !== family) throw new Error("Invalid address")
|
|
canonicalBgpPolicyPrefix(address.includes("/") ? address : `${address}/${family === 4 ? 32 : 128}`)
|
|
} catch { throw new McpError("STATE_CONFLICT", "Список BFD требует явных IP-адресов или префиксов", 409) }
|
|
if (![null, false, "false", "no"].includes(row.dynamic as string | boolean | null) || row.timed !== false) throw new McpError("STATE_CONFLICT", "Список BFD содержит временную запись", 409)
|
|
if ([null, false, "false", "no"].includes(row.disabled as string | boolean | null)) foundDesired = true
|
|
}
|
|
}
|
|
if (desired && !foundDesired) throw new McpError("NOT_FOUND", "Не найдены действующие записи address-list BFD", 404)
|
|
}
|
|
if (resource === "ospf_instance") {
|
|
const filterKeys = Object.keys(ospfFilterFields.shape)
|
|
if (filterKeys.some(key => fields[key] !== undefined)) {
|
|
const regular = await readRoutingPolicySnapshot(serverId, "routing_filter", snapshots[0]?.sourceProof)
|
|
const useSelection = Boolean(fields["out-filter-select"] ?? current?.["out-filter-select"]) || Boolean(current?.["out-filter-select"])
|
|
const selection = useSelection ? await readRoutingPolicySnapshot(serverId, "routing_filter_select", snapshots[0]?.sourceProof) : undefined
|
|
for (const key of filterKeys) {
|
|
const desired = fields[key]
|
|
if (!desired) continue
|
|
const rows = (key === "out-filter-select" ? selection : regular)?.rows.filter(row => row.chain === desired) ?? []
|
|
if (!rows.length) throw new McpError("NOT_FOUND", "Цепочка фильтра OSPF не найдена", 404)
|
|
if (rows.some(row => [true, "true", "yes"].some(flag => flag === row.invalid || flag === row.inactive))) throw new McpError("STATE_CONFLICT", "Цепочка OSPF содержит недействительное правило", 409)
|
|
}
|
|
for (const snapshot of [regular, ...(selection ? [selection] : [])]) {
|
|
snapshots.push(snapshot)
|
|
for (const row of snapshot.rows) {
|
|
if (objects.length >= 1000 || typeof row[".id"] !== "string" || !/^\*[a-z0-9]+$/i.test(row[".id"])) throw new McpError("STATE_UNAVAILABLE", "Не подтверждён каталог зависимостей фильтра OSPF", 409)
|
|
objects.push({ kind: snapshot.resource.replace("routing_policy:", ""), id: row[".id"], serverId })
|
|
}
|
|
}
|
|
}
|
|
const names = new Set([current?.["router-id"], fields["router-id"]].filter((value): value is string => typeof value === "string" && value !== "" && isIP(value) !== 4))
|
|
if (names.size) {
|
|
const snapshot = await read("ospf_router_id")
|
|
for (const name of names) {
|
|
const matches = snapshot.rows.filter(row => row.name === name)
|
|
if (action === "delete" && matches.length === 0) continue
|
|
if (matches.length !== 1 || typeof matches[0][".id"] !== "string") throw new McpError("STATE_CONFLICT", "Не подтверждена единственная ссылка Router ID OSPF", 409)
|
|
if (action !== "delete" && name === (fields["router-id"] ?? current?.["router-id"])) {
|
|
try { resolveOspfRouterIdRow(matches[0]) }
|
|
catch { throw new McpError("STATE_CONFLICT", "Не подтверждён действующий Router ID OSPF", 409) }
|
|
}
|
|
objects.push({ kind: snapshot.resource, id: matches[0][".id"], serverId })
|
|
}
|
|
}
|
|
}
|
|
if (resource === "bgp_connection") for (const reference of new Set([current?.instance, fields.instance].filter(value => value !== undefined))) {
|
|
const row = await parent("bgp_instance", reference)
|
|
await vrf(row.vrf ?? "main")
|
|
if (row["routing-table"]) await parent("routing_table", row["routing-table"])
|
|
}
|
|
if (resource === "bgp_connection") {
|
|
const local = fields["local.address"] ?? current?.["local.address"], remote = fields["remote.address"] ?? current?.["remote.address"]
|
|
if (typeof local === "string" && typeof remote === "string") {
|
|
const localFamily = bgpAddressFamily(local), remoteFamily = bgpAddressFamily(remote)
|
|
if (!localFamily || !remoteFamily) throw new McpError("INVALID_INPUT", "Некорректный адрес или префикс BGP-соединения", 400)
|
|
if (localFamily !== remoteFamily) throw new McpError("INVALID_INPUT", "Адреса BGP-соединения должны быть одного семейства", 400)
|
|
}
|
|
}
|
|
if (resource === "bgp_instance" && current && ["as", "router-id", "disabled"].some(key => fields[key] !== undefined && fields[key] !== current[key])) {
|
|
for (const row of (await read("bgp_connection")).rows.filter(row => [current.name, current[".id"]].includes(row.instance))) objects.push({ kind: "bgp_connection", id: String(row[".id"]), serverId })
|
|
}
|
|
if (resource === "bgp_instance" && current && (action === "delete" || fields.name && fields.name !== current.name || fields.vrf && fields.vrf !== current.vrf || fields["routing-table"] && fields["routing-table"] !== current["routing-table"])) {
|
|
if ((await read("bgp_connection")).rows.some(row => [current.name, current[".id"]].includes(row.instance))) throw new McpError("STATE_CONFLICT", "BGP instance используется подключением", 409)
|
|
}
|
|
if (resource === "ospf_area") for (const reference of new Set([current?.instance, fields.instance].filter(value => value !== undefined))) await instance(reference)
|
|
if (resource === "ospf_template") {
|
|
const oldList = current?.["prefix-list"]
|
|
const desiredList = action === "delete" ? undefined : fields["prefix-list"] ?? oldList
|
|
const desiredArea = fields.area ?? current?.area
|
|
for (const reference of new Set([current?.area, fields.area].filter(value => value !== undefined))) {
|
|
const area = await parent("ospf_area", reference)
|
|
const owner = await instance(area.instance)
|
|
if (desiredList && reference === desiredArea && owner.version !== "3" && owner.version !== 3) {
|
|
throw new McpError("INVALID_INPUT", "Prefix-list доступен только для шаблонов OSPFv3", 400)
|
|
}
|
|
}
|
|
if (desiredList && !desiredArea) throw new McpError("STATE_UNAVAILABLE", "Не подтверждена область prefix-list OSPFv3", 409)
|
|
await addOspfPrefixListDependencies(serverId, oldList, desiredList, snapshots, objects)
|
|
}
|
|
if (resource === "ospf_instance" && current && (action === "delete" || fields.name && fields.name !== current.name || fields.version && fields.version !== current.version || fields.vrf && fields.vrf !== current.vrf)) {
|
|
if ((await read("ospf_area")).rows.some(row => [current.name, current[".id"]].includes(row.instance))) throw new McpError("STATE_CONFLICT", "OSPF instance используется областью", 409)
|
|
}
|
|
if (resource === "ospf_area" && current && (action === "delete" || fields.name && fields.name !== current.name || fields.instance && fields.instance !== current.instance)) {
|
|
if ((await read("ospf_template")).rows.some(row => [current.name, current[".id"]].includes(row.area))) throw new McpError("STATE_CONFLICT", "Область OSPF используется шаблоном", 409)
|
|
}
|
|
if (resource === "vrf" && current && (action === "delete" || fields.name && fields.name !== current.name || fields.disabled === "true")) {
|
|
if (typeof current.name !== "string" || !current.name || typeof current[".id"] !== "string") throw new McpError("STATE_UNAVAILABLE", "Не подтверждено имя/ID VRF", 409)
|
|
for (const routeResource of ["ipv4_route", "ipv6_route"]) {
|
|
const routes = await read(routeResource)
|
|
try {
|
|
const names = [String(current.name), String(current[".id"])]
|
|
if (routes.rows.some(row => names.includes(String(row["routing-table"])) && !isDynamicRouteInsideTable(row, names))) throw new McpError("STATE_CONFLICT", "VRF используется настроенным маршрутом", 409)
|
|
// Kernel-derived routes inside this VRF disappear/move with its
|
|
// membership. They are not external gateway lookup references.
|
|
if (routes.rows.some(row => !isDynamicRouteInsideTable(row, names) && gatewayReferencesTable(row.gateway, names))) throw new McpError("STATE_CONFLICT", "VRF используется gateway маршрута, включая другую таблицу", 409)
|
|
} catch (error) {
|
|
if (error instanceof McpError) throw error
|
|
throw new McpError("STATE_UNAVAILABLE", "Не подтверждены gateway dependencies VRF; изменение не выполняется", 409)
|
|
}
|
|
}
|
|
if ((await read("ospf_instance")).rows.some(row => [current.name, current[".id"]].includes(row.vrf))) throw new McpError("STATE_CONFLICT", "VRF используется OSPF instance", 409)
|
|
if ((await read("bfd_configuration")).rows.some(row => [current.name, current[".id"]].includes(row.vrf))) throw new McpError("STATE_CONFLICT", "VRF используется правилом BFD", 409)
|
|
if ((await read("bgp_instance")).rows.some(row => [current.name, current[".id"]].includes(row.vrf))) throw new McpError("STATE_CONFLICT", "VRF используется BGP instance", 409)
|
|
}
|
|
}
|