Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
545a9bbcd2 | ||
|
|
37025f1f94 | ||
|
|
c49e01299c | ||
|
|
187a0cd45e | ||
|
|
731c19a14d | ||
|
|
94c50b9660 | ||
|
|
fc39b0da3c | ||
|
|
3c06a72349 | ||
|
|
ea13365f37 | ||
|
|
8a962c1984 | ||
|
|
0a568f1640 |
No files matched your search
+471
-234
File diff suppressed because it is too large.
Load diff
@@ -7,7 +7,7 @@
|
|||||||
"test:mcp:module-completion": "tsx src/services/ipsec-server-init-model.test.ts && tsx src/modules/mcp/ipsec-server-init-actions.test.ts && tsx src/services/wireguard-revision-restore.test.ts && tsx src/modules/mcp/vrf-ticket-runtime.test.ts && tsx src/services/ipsec-restore.test.ts && tsx src/services/ipsec-pool-dependencies.test.ts && tsx src/services/vrf-production-transition.test.ts && tsx src/services/vrf-production-action-binding.test.ts && tsx src/services/ipsec-revision-restore-model.test.ts && tsx src/modules/mcp/ipsec-revision-actions.test.ts && tsx src/modules/mcp/service-native-progress.test.ts && tsx src/services/ipsec-revision-restore.test.ts && tsx src/services/ipsec-revision-secret.test.ts",
|
"test:mcp:module-completion": "tsx src/services/ipsec-server-init-model.test.ts && tsx src/modules/mcp/ipsec-server-init-actions.test.ts && tsx src/services/wireguard-revision-restore.test.ts && tsx src/modules/mcp/vrf-ticket-runtime.test.ts && tsx src/services/ipsec-restore.test.ts && tsx src/services/ipsec-pool-dependencies.test.ts && tsx src/services/vrf-production-transition.test.ts && tsx src/services/vrf-production-action-binding.test.ts && tsx src/services/ipsec-revision-restore-model.test.ts && tsx src/modules/mcp/ipsec-revision-actions.test.ts && tsx src/modules/mcp/service-native-progress.test.ts && tsx src/services/ipsec-revision-restore.test.ts && tsx src/services/ipsec-revision-secret.test.ts",
|
||||||
"test:mcp:module-completion:pg": "node scripts/test-mcp-postgres.mjs --module-completion --restore",
|
"test:mcp:module-completion:pg": "node scripts/test-mcp-postgres.mjs --module-completion --restore",
|
||||||
"test:mcp:pg": "node scripts/test-mcp-postgres.mjs",
|
"test:mcp:pg": "node scripts/test-mcp-postgres.mjs",
|
||||||
"test:mcp:network-diagnostics": "node --experimental-test-module-mocks --import tsx --test src/modules/mcp/incident-actions.test.ts src/modules/mcp/network-diagnostic-actions.test.ts src/modules/mcp/resilience-actions.test.ts src/modules/mcp/gre-ipsec-pair-actions.test.ts",
|
"test:mcp:network-diagnostics": "node --experimental-test-module-mocks --import tsx --test src/modules/mcp/incident-actions.test.ts src/modules/mcp/network-diagnostic-actions.test.ts src/modules/mcp/resilience-actions.test.ts src/modules/mcp/gre-ipsec-pair-actions.test.ts src/modules/mcp/gre-ikev2-pair-actions.test.ts",
|
||||||
"test:mcp:network-diagnostics:pg": "node scripts/test-mcp-postgres.mjs --network-diagnostics",
|
"test:mcp:network-diagnostics:pg": "node scripts/test-mcp-postgres.mjs --network-diagnostics",
|
||||||
"test:mcp:pg:sharded": "node scripts/test-mcp-postgres-sharded.mjs",
|
"test:mcp:pg:sharded": "node scripts/test-mcp-postgres-sharded.mjs",
|
||||||
"test:mcp:users-bindings:pg": "node scripts/test-mcp-postgres.mjs --users-bindings",
|
"test:mcp:users-bindings:pg": "node scripts/test-mcp-postgres.mjs --users-bindings",
|
||||||
@@ -183,7 +183,7 @@
|
|||||||
"test:traffic-flow:read-budget": "tsx --test src/services/traffic-flow-read-budget.test.ts src/modules/mcp/flow-read-quality.test.ts && node scripts/test-flow-read-adapters.mjs",
|
"test:traffic-flow:read-budget": "tsx --test src/services/traffic-flow-read-budget.test.ts src/modules/mcp/flow-read-quality.test.ts && node scripts/test-flow-read-adapters.mjs",
|
||||||
"test:traffic-flow:read-http:pg": "node scripts/test-flow-read-http-owned.mjs",
|
"test:traffic-flow:read-http:pg": "node scripts/test-flow-read-http-owned.mjs",
|
||||||
"test:traffic-flow:read-source:pg": "tsx scripts/test-flow-read-sql-owned.mts",
|
"test:traffic-flow:read-source:pg": "tsx scripts/test-flow-read-sql-owned.mts",
|
||||||
"test:mcp:routing-baseline": "tsx --test src/modules/mcp/routing-controller-active-writer.test.ts src/modules/mcp/routing-controller-baseline.test.ts src/modules/mcp/routing-controller-fence.test.ts src/modules/mcp/routing-community-public.test.ts src/modules/mcp/routing-controller-overlap.test.ts",
|
"test:mcp:routing-baseline": "tsx --test src/modules/mcp/routing-controller-active-writer.test.ts src/modules/mcp/routing-controller-baseline.test.ts src/modules/mcp/routing-controller-fence.test.ts src/modules/mcp/routing-community-public.test.ts src/modules/mcp/routing-controller-overlap.test.ts src/services/bgp-rib-observation.test.ts",
|
||||||
"test:mcp:routing-baseline:pg": "node scripts/test-routing-controller-baseline.mjs",
|
"test:mcp:routing-baseline:pg": "node scripts/test-routing-controller-baseline.mjs",
|
||||||
"test:mcp:routing-baseline-inverse:pg": "node scripts/test-routing-controller-baseline.mjs --default-scoped",
|
"test:mcp:routing-baseline-inverse:pg": "node scripts/test-routing-controller-baseline.mjs --default-scoped",
|
||||||
"test:sqlite-import-control:pg": "node scripts/test-sqlite-import-control-postgres.mjs",
|
"test:sqlite-import-control:pg": "node scripts/test-sqlite-import-control-postgres.mjs",
|
||||||
|
|||||||
@@ -81,6 +81,7 @@ import { registerFirewallActions } from "./firewall-actions.js"
|
|||||||
import { registerBfdMoveActions } from "./bfd-move-actions.js"
|
import { registerBfdMoveActions } from "./bfd-move-actions.js"
|
||||||
import { registerGreMutationActions } from "./gre-mutation-actions.js"
|
import { registerGreMutationActions } from "./gre-mutation-actions.js"
|
||||||
import { registerGreIpsecPairActions } from "./gre-ipsec-pair-actions.js"
|
import { registerGreIpsecPairActions } from "./gre-ipsec-pair-actions.js"
|
||||||
|
import { registerGreIke2PairActions } from "./gre-ikev2-pair-actions.js"
|
||||||
import { registerIxActions } from "./internet-exchange-actions.js"
|
import { registerIxActions } from "./internet-exchange-actions.js"
|
||||||
import { registerGreRevisionActions } from "./gre-revision-actions.js"
|
import { registerGreRevisionActions } from "./gre-revision-actions.js"
|
||||||
import { prepareGreNativeChange, registerGreNativeServices } from "./gre-native-actions.js"
|
import { prepareGreNativeChange, registerGreNativeServices } from "./gre-native-actions.js"
|
||||||
@@ -179,7 +180,7 @@ for (const resource of rosResources) {
|
|||||||
: z.object({ serverId, id: rowId.optional(), fields: publicFields.default({}), ...(resource.id === "vrf" ? { productionAdmission: z.literal(true).optional() } : {}) }).strict()
|
: z.object({ serverId, id: rowId.optional(), fields: publicFields.default({}), ...(resource.id === "vrf" ? { productionAdmission: z.literal(true).optional() } : {}) }).strict()
|
||||||
const delegated = resource.id === "wireguard" && action !== "create" || resource.id === "wireguard_peer" || resource.id === "gre" && action !== "create" || resource.id === "ipsec_peer" && action !== "create" || resource.id === "certificate" && action === "delete" || resource.id === "container" && action === "delete"
|
const delegated = resource.id === "wireguard" && action !== "create" || resource.id === "wireguard_peer" || resource.id === "gre" && action !== "create" || resource.id === "ipsec_peer" && action !== "create" || resource.id === "certificate" && action === "delete" || resource.id === "container" && action === "delete"
|
||||||
const guardsOspfInterfaceUse = action !== "create" && !delegated && ospfInterfaceResources.includes(resource.id)
|
const guardsOspfInterfaceUse = action !== "create" && !delegated && ospfInterfaceResources.includes(resource.id)
|
||||||
const previousVersion = action === "create" ? (["ospf_template", "wireguard_peer", "wireguard", "bfd_configuration"].includes(resource.id) ? 3 : 2) : resource.id === "ipsec_peer" || resource.id === "certificate" && action === "delete" ? 2 : resource.id === "wireguard" && action === "update" ? 3 : resource.id === "ospf_template" && action !== "delete" || resource.id === "wireguard_peer" || resource.id === "wireguard" || resource.id === "ip_settings" ? 2 : 1
|
const previousVersion = action === "create" ? (resource.id === "bfd_configuration" ? 4 : ["ospf_template", "wireguard_peer", "wireguard"].includes(resource.id) ? 3 : 2) : resource.id === "ipsec_peer" || resource.id === "certificate" && action === "delete" ? 2 : resource.id === "wireguard" && action === "update" ? 3 : resource.id === "ospf_template" && action !== "delete" || resource.id === "wireguard_peer" || resource.id === "wireguard" || resource.id === "ip_settings" ? 2 : 1
|
||||||
add(`ros.${resource.id}.${action}`, `mm_${resource.id}_${action}_plan`, `${resource.title}: ${action}`, resource.permission.split(":")[1], resource.id === "certificate" && action === "update" ? ["mm:certificates:write", "mm:network:write"] : resource.permission + ":write", "write", "servers", schema, {
|
add(`ros.${resource.id}.${action}`, `mm_${resource.id}_${action}_plan`, `${resource.title}: ${action}`, resource.permission.split(":")[1], resource.id === "certificate" && action === "update" ? ["mm:certificates:write", "mm:network:write"] : resource.permission + ":write", "write", "servers", schema, {
|
||||||
version: resource.id === "ipsec_peer" ? (action === "create" ? 5 : 3) : resource.id === "certificate" ? (action === "update" ? 4 : 3) : previousVersion + (delegated ? 0 : 1) + (resource.id === "bfd_configuration" ? 4 : resource.id === "ospf_template" ? (action === "update" ? 8 : 7) : 0) + (resource.id === "vrf" ? (action === "delete" ? 3 : 2) : 0) + (resource.id === "ospf_instance" ? 2 : 0) + (["bridge", "bridge_port", "bridge_vlan", "ip_settings", "ipv6_settings"].includes(resource.id) ? 1 : 0) + (guardsOspfInterfaceUse ? 1 : 0),
|
version: resource.id === "ipsec_peer" ? (action === "create" ? 5 : 3) : resource.id === "certificate" ? (action === "update" ? 4 : 3) : previousVersion + (delegated ? 0 : 1) + (resource.id === "bfd_configuration" ? 4 : resource.id === "ospf_template" ? (action === "update" ? 8 : 7) : 0) + (resource.id === "vrf" ? (action === "delete" ? 3 : 2) : 0) + (resource.id === "ospf_instance" ? 2 : 0) + (["bridge", "bridge_port", "bridge_vlan", "ip_settings", "ipv6_settings"].includes(resource.id) ? 1 : 0) + (guardsOspfInterfaceUse ? 1 : 0),
|
||||||
prepare: async (input, context) => {
|
prepare: async (input, context) => {
|
||||||
@@ -709,6 +710,7 @@ registerFirewallActions(add)
|
|||||||
registerBfdMoveActions(add)
|
registerBfdMoveActions(add)
|
||||||
registerGreMutationActions(add)
|
registerGreMutationActions(add)
|
||||||
registerGreIpsecPairActions(add)
|
registerGreIpsecPairActions(add)
|
||||||
|
registerGreIke2PairActions(add)
|
||||||
registerIxActions(add)
|
registerIxActions(add)
|
||||||
registerGreRevisionActions(add)
|
registerGreRevisionActions(add)
|
||||||
registerGreNativeServices()
|
registerGreNativeServices()
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { z } from "zod"
|
import { z } from "zod"
|
||||||
import { readStaticBgpConnection } from "../../services/bgp-connection-read.js"
|
import { readBgpInstanceContext, readStaticBgpConnection } from "../../services/bgp-connection-read.js"
|
||||||
import { bgpExportConnection, bgpExportSources, bgpRedistributionMode, bgpTemplateReferences, nativeBgpExportValue, nativeBgpRows, type BgpExportMode, type NativeBgpRow } from "../../services/bgp-export-model.js"
|
import { bgpExportConnection, bgpExportSources, bgpRedistributionMode, bgpTemplateReferences, nativeBgpExportValue, nativeBgpRows, type BgpExportMode, type NativeBgpRow } from "../../services/bgp-export-model.js"
|
||||||
import { readOspfEffectiveDisabled } from "../../services/ospf-effective-disabled.js"
|
import { readOspfEffectiveDisabled } from "../../services/ospf-effective-disabled.js"
|
||||||
import { executeGuardedApplicationWrite } from "../../services/config-mutation-policy.js"
|
import { executeGuardedApplicationWrite } from "../../services/config-mutation-policy.js"
|
||||||
@@ -70,9 +70,18 @@ async function readState(input: Record<string, unknown>) {
|
|||||||
return found[0]
|
return found[0]
|
||||||
}
|
}
|
||||||
const instance = unique("bgp_instance", connection.instance), vrf = unique("vrf", connection.vrf), table = unique("routing_table", connection["routing-table"])
|
const instance = unique("bgp_instance", connection.instance), vrf = unique("vrf", connection.vrf), table = unique("routing_table", connection["routing-table"])
|
||||||
if (instance.vrf !== connection.vrf || instance["routing-table"] !== connection["routing-table"] || vrf.name !== table.name) throw new McpError("STATE_CONFLICT", "Экспорт требует одинаковые явные instance/connection VRF и таблицу", 409)
|
const instanceContext = await readBgpInstanceContext(client, { ...instance, ".id": String(instance[".id"]) })
|
||||||
const [v4, v6] = await Promise.all([client.get<unknown>("/ip/route"), client.get<unknown>("/ipv6/route")])
|
if (unique("vrf", instanceContext.vrf)[".id"] !== vrf[".id"] || unique("routing_table", instanceContext.table)[".id"] !== table[".id"]) throw new McpError("STATE_CONFLICT", "Контекст VRF и таблицы у BGP instance и connection расходится", 409)
|
||||||
const sources = [...parseState("IPv4 source origins/table/prefixes", () => bgpExportSources(v4, String(table.name), sourceModes, 4)), ...parseState("IPv6 source origins/table/prefixes", () => bgpExportSources(v6, String(table.name), sourceModes, 6))]
|
const tableName = String(table.name)
|
||||||
|
const sourceGroups = await Promise.all(([4, 6] as const).flatMap(family => sourceModes.filter(kind => kind !== "disabled").map(async kind => {
|
||||||
|
const params = new URLSearchParams({ "routing-table": tableName, [kind === "connected" ? "connect" : "static"]: "true" })
|
||||||
|
const rows = nativeBgpRows(await client.get<unknown>(`${family === 4 ? "/ip/route" : "/ipv6/route"}?${params}`))
|
||||||
|
const candidates = parseState(`IPv${family} source origins/table/prefixes`, () => bgpExportSources(rows, tableName, [kind], family))
|
||||||
|
if (candidates.length !== rows.length) throw new McpError("STATE_UNAVAILABLE", "Ответ RouterOS не соответствует запросу источников BGP", 409)
|
||||||
|
return candidates
|
||||||
|
})))
|
||||||
|
const sources = sourceGroups.flat().sort((a, b) => a.family - b.family || a.id.localeCompare(b.id))
|
||||||
|
if (new Set(sources.map(row => `${row.family}:${row.id}`)).size !== sources.length) throw new McpError("STATE_UNAVAILABLE", "Повторяющиеся источники экспорта BGP", 409)
|
||||||
if (sources.length > 500) throw new McpError("LIMIT_EXCEEDED", "Экспорт BGP превышает 500 исходных маршрутов", 409)
|
if (sources.length > 500) throw new McpError("LIMIT_EXCEEDED", "Экспорт BGP превышает 500 исходных маршрутов", 409)
|
||||||
const objects: ChangeEvidence["objects"] = [
|
const objects: ChangeEvidence["objects"] = [
|
||||||
{ kind: "bgp-export", id, serverId }, { kind: "bgp_connection", id, serverId },
|
{ kind: "bgp-export", id, serverId }, { kind: "bgp_connection", id, serverId },
|
||||||
@@ -87,7 +96,7 @@ async function readState(input: Record<string, unknown>) {
|
|||||||
const before = { serverId, serverProof, id, instance: connection.instance, vrf: connection.vrf, table: connection["routing-table"], mode: currentMode, localMode, inheritedMode,
|
const before = { serverId, serverProof, id, instance: connection.instance, vrf: connection.vrf, table: connection["routing-table"], mode: currentMode, localMode, inheritedMode,
|
||||||
templates: templateProof.map(value => ({ id: value.row[".id"], name: value.row.name, mode: value.mode })),
|
templates: templateProof.map(value => ({ id: value.row[".id"], name: value.row.name, mode: value.mode })),
|
||||||
sourceModes, sources: sources.map(({ proof: _proof, ...row }) => row),
|
sourceModes, sources: sources.map(({ proof: _proof, ...row }) => row),
|
||||||
connectionProof: await configurationProof(serverId, id, connection), sourceProof: await privateSecretFingerprint(fingerprint({ serverProof, parentProof, sources, templateProof }), `bgp-export-sources:${serverId}:${id}`) }
|
connectionProof: await configurationProof(serverId, id, connection), sourceProof: await privateSecretFingerprint(fingerprint({ serverProof, parentProof, instanceContext, sources, templateProof }), `bgp-export-sources:${serverId}:${id}`) }
|
||||||
return { server, client, connection, before, objects }
|
return { server, client, connection, before, objects }
|
||||||
}
|
}
|
||||||
async function state(input: Record<string, unknown>) {
|
async function state(input: Record<string, unknown>) {
|
||||||
@@ -117,6 +126,7 @@ export function registerBgpExportActions(register: typeof add) {
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
register("routing.bgp.export", "mm_bgp_export_plan", "Человеческий план перераспределения connected/static в BGP с проверкой источников; disabled отключает только перераспределение", "bgp", ["mm:bgp:write", "mm:network:read", "mm:filters:read"], "write", "servers", schema, {
|
register("routing.bgp.export", "mm_bgp_export_plan", "Человеческий план перераспределения connected/static в BGP с проверкой источников; disabled отключает только перераспределение", "bgp", ["mm:bgp:write", "mm:network:read", "mm:filters:read"], "write", "servers", schema, {
|
||||||
|
version: 2,
|
||||||
prepare: async input => {
|
prepare: async input => {
|
||||||
const initial = await state(input), before = initial.before, request = { ...input, sourceModes: before.sourceModes, beforeFingerprint: fingerprint(before), expectedServerProof: before.serverProof }
|
const initial = await state(input), before = initial.before, request = { ...input, sourceModes: before.sourceModes, beforeFingerprint: fingerprint(before), expectedServerProof: before.serverProof }
|
||||||
return { target: { scope: "servers", serverIds: [Number(input.serverId)] }, objects: initial.objects, snapshots: [], before,
|
return { target: { scope: "servers", serverIds: [Number(input.serverId)] }, objects: initial.objects, snapshots: [], before,
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { z } from "zod"
|
import { z } from "zod"
|
||||||
import { pool } from "../../db/index.js"
|
import { pool } from "../../db/index.js"
|
||||||
import { readStaticBgpConnection } from "../../services/bgp-connection-read.js"
|
import { readBgpInstanceContext, readStaticBgpConnection } from "../../services/bgp-connection-read.js"
|
||||||
import { nativeBgpRows, bgpTemplateReferences, type NativeBgpRow } from "../../services/bgp-export-model.js"
|
import { nativeBgpRows, bgpTemplateReferences, type NativeBgpRow } from "../../services/bgp-export-model.js"
|
||||||
import { bgpFilterName, bgpFilterProperty, effectiveBgpFilter, stableBgpPolicyRow, type BgpFilterDirection } from "../../services/bgp-filter-binding-model.js"
|
import { bgpFilterName, bgpFilterProperty, effectiveBgpFilter, stableBgpPolicyRow, type BgpFilterDirection } from "../../services/bgp-filter-binding-model.js"
|
||||||
import { readOspfEffectiveDisabled } from "../../services/ospf-effective-disabled.js"
|
import { readOspfEffectiveDisabled } from "../../services/ospf-effective-disabled.js"
|
||||||
@@ -60,12 +60,14 @@ async function readState(input: Record<string, unknown>) {
|
|||||||
const [effectiveInstance] = await readOspfEffectiveDisabled<NativeBgpRow & { disabled?: string }>([instance], nativeId => client.post("/routing/bgp/instance/get", { ".id": nativeId, "value-name": "disabled" }))
|
const [effectiveInstance] = await readOspfEffectiveDisabled<NativeBgpRow & { disabled?: string }>([instance], nativeId => client.post("/routing/bgp/instance/get", { ".id": nativeId, "value-name": "disabled" }))
|
||||||
if (!["false", "no"].includes(String(effectiveInstance.disabled))) throw new Error("BGP instance disabled/unknown")
|
if (!["false", "no"].includes(String(effectiveInstance.disabled))) throw new Error("BGP instance disabled/unknown")
|
||||||
Object.assign(instance, effectiveInstance)
|
Object.assign(instance, effectiveInstance)
|
||||||
for (const key of ["vrf", "routing-table"]) if (instance[key] === undefined || instance[key] === "") {
|
const instanceContext = await readBgpInstanceContext(client, instance)
|
||||||
const value = bgpFilterName(await client.post("/routing/bgp/instance/get", { ".id": String(instance[".id"]), "value-name": key }))
|
if (unique("vrf", instanceContext.vrf)[".id"] !== vrf[".id"]) throw new Error("BGP instance/connection VRFs disagree")
|
||||||
if (!value) throw new Error("BGP instance effective context not confirmed")
|
const instanceTable = unique("routing_table", instanceContext.table)
|
||||||
instance[key] = value
|
const separateTables = instanceTable[".id"] !== table[".id"]
|
||||||
|
if (separateTables && snapshots.find(row => row.resource === "vrf")!.rows.some(owner =>
|
||||||
|
owner[".id"] !== vrf[".id"] && (owner.name === table.name || owner.name === instanceTable.name))) {
|
||||||
|
throw new Error("BGP routing table belongs to a different VRF")
|
||||||
}
|
}
|
||||||
if (unique("vrf", instance.vrf)[".id"] !== vrf[".id"] || unique("routing_table", instance["routing-table"])[".id"] !== table[".id"] || vrf.name !== table.name) throw new Error("BGP instance/connection contexts disagree")
|
|
||||||
const filters = nativeBgpRows(await client.get("/routing/filter/rule"))
|
const filters = nativeBgpRows(await client.get("/routing/filter/rule"))
|
||||||
if (filters.length > 1000) throw new McpError("LIMIT_EXCEEDED", "Каталог BGP filters превышает 1000 строк", 409)
|
if (filters.length > 1000) throw new McpError("LIMIT_EXCEEDED", "Каталог BGP filters превышает 1000 строк", 409)
|
||||||
const selected = filters.filter(row => row.chain === desired)
|
const selected = filters.filter(row => row.chain === desired)
|
||||||
@@ -75,13 +77,14 @@ async function readState(input: Record<string, unknown>) {
|
|||||||
const protections = (await pool.query("SELECT object_ref FROM mcp_protections WHERE object_ref->>'serverId'=$1 OR (object_ref->>'kind'='server' AND object_ref->>'id'=$1) LIMIT 1001", [String(serverId)])).rows
|
const protections = (await pool.query("SELECT object_ref FROM mcp_protections WHERE object_ref->>'serverId'=$1 OR (object_ref->>'kind'='server' AND object_ref->>'id'=$1) LIMIT 1001", [String(serverId)])).rows
|
||||||
if (protections.length > 1000) throw new Error("BGP protection closure exceeds limit")
|
if (protections.length > 1000) throw new Error("BGP protection closure exceeds limit")
|
||||||
const objects: ChangeEvidence["objects"] = [{ kind: "bgp-policy", id, serverId }, { kind: "bgp_connection", id, serverId },
|
const objects: ChangeEvidence["objects"] = [{ kind: "bgp-policy", id, serverId }, { kind: "bgp_connection", id, serverId },
|
||||||
...[["bgp_instance", instance], ["vrf", vrf], ["routing_table", table]].map(([kind, row]) => ({ kind: String(kind), id: String((row as Record<string, unknown>)[".id"]), serverId })),
|
...[["bgp_instance", instance], ["vrf", vrf], ["routing_table", table], ["routing_table", instanceTable]].map(([kind, row]) => ({ kind: String(kind), id: String((row as Record<string, unknown>)[".id"]), serverId })),
|
||||||
...filters.map(row => ({ kind: "routing_filter", id: row[".id"], serverId })), ...[...used.keys()].map(nativeId => ({ kind: "bgp_template", id: nativeId, serverId })),
|
...filters.map(row => ({ kind: "routing_filter", id: row[".id"], serverId })), ...[...used.keys()].map(nativeId => ({ kind: "bgp_template", id: nativeId, serverId })),
|
||||||
...protections.map(({ object_ref: ref }) => ({ kind: ref.kind, id: ref.id, serverId }))]
|
...protections.map(({ object_ref: ref }) => ({ kind: ref.kind, id: ref.id, serverId }))]
|
||||||
const uniqueObjects = [...new Map(objects.map(row => [fingerprint(row), row])).values()]
|
const uniqueObjects = [...new Map(objects.map(row => [fingerprint(row), row])).values()]
|
||||||
if (uniqueObjects.length > 1000) throw new Error("BGP dependency closure exceeds limit")
|
if (uniqueObjects.length > 1000) throw new Error("BGP dependency closure exceeds limit")
|
||||||
const canonicalConnection = { ...stableBgpPolicyRow(connection), [property]: effectiveChain }
|
const canonicalConnection = { ...stableBgpPolicyRow(connection), [property]: effectiveChain }
|
||||||
const dependencyProof = await proof(serverId, id, "dependencies", { serverProof, otherConnections: connections.filter(row => row[".id"] !== id).map(stableBgpPolicyRow), instance: stableBgpPolicyRow(instance), vrf: { ...stableBgpPolicyRow(vrf), ...(vrf.interfaces !== undefined ? { interfaces: canonicalVrfMembers(vrf.interfaces) } : {}) }, table: stableBgpPolicyRow(table),
|
const dependencyProof = await proof(serverId, id, "dependencies", { serverProof, otherConnections: connections.filter(row => row[".id"] !== id).map(stableBgpPolicyRow), instance: stableBgpPolicyRow(instance), instanceContext, vrf: { ...stableBgpPolicyRow(vrf), ...(vrf.interfaces !== undefined ? { interfaces: canonicalVrfMembers(vrf.interfaces) } : {}) }, table: stableBgpPolicyRow(table),
|
||||||
|
...(separateTables ? { instanceTable: stableBgpPolicyRow(instanceTable) } : {}),
|
||||||
filters: filters.map(stableBgpPolicyRow), used: [...used.values()], references, protections })
|
filters: filters.map(stableBgpPolicyRow), used: [...used.values()], references, protections })
|
||||||
const before = { serverId, id, direction: input.direction, property, instance: instance.name, vrf: vrf.name, table: table.name, localChain, inheritedChain, effectiveChain,
|
const before = { serverId, id, direction: input.direction, property, instance: instance.name, vrf: vrf.name, table: table.name, localChain, inheritedChain, effectiveChain,
|
||||||
selectedRuleCount: selected.length, selectedEnabledRuleCount: effectiveFilters.filter(row => ["false", "no"].includes(String(row.disabled))).length, serverProof, dependencyProof,
|
selectedRuleCount: selected.length, selectedEnabledRuleCount: effectiveFilters.filter(row => ["false", "no"].includes(String(row.disabled))).length, serverProof, dependencyProof,
|
||||||
@@ -112,6 +115,7 @@ export function registerBgpFilterBindingActions(register: typeof add) {
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
register("routing.bgp.filter.bind", "mm_bgp_filter_binding_plan", "Человеческий план локальной input/output привязки BGP к существующей цепочке; пустая chain очищает local binding", "bgp", ["mm:bgp:write", "mm:filters:read", "mm:network:read"], "write", "servers", schema, {
|
register("routing.bgp.filter.bind", "mm_bgp_filter_binding_plan", "Человеческий план локальной input/output привязки BGP к существующей цепочке; пустая chain очищает local binding", "bgp", ["mm:bgp:write", "mm:filters:read", "mm:network:read"], "write", "servers", schema, {
|
||||||
|
version: 2,
|
||||||
prepare: async input => {
|
prepare: async input => {
|
||||||
const initial = await state(input)
|
const initial = await state(input)
|
||||||
return { target: { scope: "servers", serverIds: [initial.server.id] }, objects: initial.objects, snapshots: [], before: initial.before, requiresHuman: true, verificationScope: "configuration", mutationCost: 1,
|
return { target: { scope: "servers", serverIds: [initial.server.id] }, objects: initial.objects, snapshots: [], before: initial.before, requiresHuman: true, verificationScope: "configuration", mutationCost: 1,
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
import { z } from "zod"
|
import { z } from "zod"
|
||||||
import { hasPermission } from "../../lib/permissions.js"
|
import { hasPermission } from "../../lib/permissions.js"
|
||||||
import { bgpPrefixRows } from "../../services/bgp-prefix-model.js"
|
import { bgpPrefixRows } from "../../services/bgp-prefix-model.js"
|
||||||
|
import { BgpRibChanged, bgpRibSelection, readBgpRib } from "../../services/bgp-rib-observation.js"
|
||||||
import { nativeBgpRows } from "../../services/bgp-export-model.js"
|
import { nativeBgpRows } from "../../services/bgp-export-model.js"
|
||||||
import { getServerRowById } from "../servers/repository/servers-repository.js"
|
import { getServerRowById } from "../servers/repository/servers-repository.js"
|
||||||
import { routerClient } from "./resources.js"
|
import { routerClient } from "./resources.js"
|
||||||
import { effectiveMcpConnection } from "./store.js"
|
import { effectiveMcpConnection } from "./store.js"
|
||||||
|
import { createRoutingSourceContext, readRoutingEndpoints } from "./routing-observation-source.js"
|
||||||
import { fingerprint, McpError } from "./security.js"
|
import { fingerprint, McpError } from "./security.js"
|
||||||
import type { ActionContext } from "./action-types.js"
|
import type { ActionContext } from "./action-types.js"
|
||||||
import type { add } from "./actions.js"
|
import type { add } from "./actions.js"
|
||||||
@@ -17,6 +19,27 @@ async function access(context: ActionContext) {
|
|||||||
if (fingerprint(current.policy) !== fingerprint(context.connection.policy)) throw new McpError("RESET_REQUIRED", "Область чтения BGP изменилась", 409)
|
if (fingerprint(current.policy) !== fingerprint(context.connection.policy)) throw new McpError("RESET_REQUIRED", "Область чтения BGP изменилась", 409)
|
||||||
}
|
}
|
||||||
export function registerBgpPrefixActions(register: typeof add) {
|
export function registerBgpPrefixActions(register: typeof add) {
|
||||||
|
const observation = bgpRibSelection.safeExtend({ serverId: z.number().int().positive().safe() })
|
||||||
|
register("routing.bgp.rib.read", "mm_bgp_rib_get", "IPv4 BGP RIB с filtered-путями. Для соседа укажите sessionName или peerCacheId. Для следующих страниц сохраните expectedFingerprint первой страницы", "bgp", permissions, "read", "servers", observation, { read: async (input, context) => {
|
||||||
|
const { serverId, ...selection } = observation.parse(input)
|
||||||
|
await access(context)
|
||||||
|
const source = await createRoutingSourceContext(await readRoutingEndpoints([serverId]))
|
||||||
|
if (source.expected.length !== 1) throw new McpError("DEVICE_UNAVAILABLE", "Источник RIB недоступен", 409)
|
||||||
|
const check = async () => { await access(context); await source.assertCurrent() }
|
||||||
|
try {
|
||||||
|
await check()
|
||||||
|
const { client } = await routerClient(serverId)
|
||||||
|
const startedAt = new Date().toISOString()
|
||||||
|
const result = await readBgpRib(client, selection, check, context.signal)
|
||||||
|
await check()
|
||||||
|
return { serverId, ...result, startedAt, observedAt: new Date().toISOString(), timestampKind: "backend-receipt", forwardingVerified: false }
|
||||||
|
} catch (error) {
|
||||||
|
await check()
|
||||||
|
if (error instanceof McpError) throw error
|
||||||
|
if (error instanceof BgpRibChanged) throw new McpError("STATE_CONFLICT", "Состояние RIB изменилось; повторите чтение с первой страницы", 409)
|
||||||
|
throw new McpError("STATE_UNAVAILABLE", "Полнота нативного чтения IPv4 BGP RIB не подтверждена", 409)
|
||||||
|
}
|
||||||
|
} })
|
||||||
register("routing.bgp.prefixes.read", "mm_bgp_prefixes_get", "Наблюдаемые BGP-префиксы IPv4/IPv6 в явной таблице; active nullable, без доказательства forwarding или attribution к peer", "bgp", permissions, "read", "servers", z.object({
|
register("routing.bgp.prefixes.read", "mm_bgp_prefixes_get", "Наблюдаемые BGP-префиксы IPv4/IPv6 в явной таблице; active nullable, без доказательства forwarding или attribution к peer", "bgp", permissions, "read", "servers", z.object({
|
||||||
serverId: z.number().int().positive().safe(), family: z.enum(["ipv4", "ipv6"]).default("ipv4"),
|
serverId: z.number().int().positive().safe(), family: z.enum(["ipv4", "ipv6"]).default("ipv4"),
|
||||||
table: z.string().trim().min(1).max(100).refine(value => !/[\u0000-\u001f\u007f]/.test(value)).default("main"),
|
table: z.string().trim().min(1).max(100).refine(value => !/[\u0000-\u001f\u007f]/.test(value)).default("main"),
|
||||||
|
|||||||
@@ -0,0 +1,103 @@
|
|||||||
|
import assert from "node:assert/strict"
|
||||||
|
import test from "node:test"
|
||||||
|
import { greIpsecPaths } from "../../services/gre-ipsec-transport.js"
|
||||||
|
import { greIke2DefaultProposal, greIke2SideCommands, greIke2StableCatalogues, greIke2StepInput, greIke2StepSchema, planGreIke2Side, validateGreIke2Defaults, verifyGreIke2Create, verifyGreIke2Update } from "./gre-ikev2-pair-actions.js"
|
||||||
|
import { redact } from "./security.js"
|
||||||
|
|
||||||
|
const pair = { endpoints: [
|
||||||
|
{ serverId: 3, greName: "gre-jh-test-home", outerAddress: "192.0.2.3" },
|
||||||
|
{ serverId: 6, greName: "gre-jh-test-nov", outerAddress: "198.51.100.6" },
|
||||||
|
] }
|
||||||
|
const secret = "ab".repeat(32)
|
||||||
|
const empty = () => Object.fromEntries(Object.values(greIpsecPaths).map(path => [path, [] as Record<string, string>[]]))
|
||||||
|
|
||||||
|
test("emits the IX transport suite with a fixed GRE selector and independent identities", () => {
|
||||||
|
const [left, right] = ([0, 1] as const).map(side => greIke2SideCommands(pair, side, secret))
|
||||||
|
assert.equal(left.length, 6)
|
||||||
|
assert.equal(right.length, 6)
|
||||||
|
assert.equal(left.some(command => command.path === greIpsecPaths.proposal), false)
|
||||||
|
assert.deepEqual(left.find(command => command.path === greIpsecPaths.profile), right.find(command => command.path === greIpsecPaths.profile))
|
||||||
|
assert.equal(left.find(command => command.path === greIpsecPaths.peer)?.fields.passive, "true")
|
||||||
|
assert.equal(right.find(command => command.path === greIpsecPaths.peer)?.fields.passive, "false")
|
||||||
|
assert.equal(left.find(command => command.path === greIpsecPaths.identity)?.fields.secret, secret)
|
||||||
|
assert.equal(right.find(command => command.path === greIpsecPaths.identity)?.fields.secret, secret)
|
||||||
|
assert.equal(JSON.stringify(redact({ ipsecSecret: secret, commands: left })).includes(secret), false)
|
||||||
|
const leftPolicy = left.find(command => command.path === greIpsecPaths.policy)!.fields
|
||||||
|
const rightPolicy = right.find(command => command.path === greIpsecPaths.policy)!.fields
|
||||||
|
assert.deepEqual([leftPolicy["src-address"], leftPolicy["dst-address"], leftPolicy.protocol, leftPolicy.level, leftPolicy.tunnel],
|
||||||
|
["192.0.2.3/32", "198.51.100.6/32", "gre", "require", "false"])
|
||||||
|
assert.equal(rightPolicy["src-address"], leftPolicy["dst-address"])
|
||||||
|
assert.equal(leftPolicy.proposal, "default")
|
||||||
|
assert.equal(rightPolicy["dst-address"], leftPolicy["src-address"])
|
||||||
|
assert.deepEqual(left.slice(0, 2).map(command => command.fields["ipsec-policy"]), ["in,none", "out,none"])
|
||||||
|
})
|
||||||
|
|
||||||
|
test("rejects existing objects and opposing IPv4 selectors without touching other peers", () => {
|
||||||
|
const commands = greIke2SideCommands(pair, 0, secret), catalogs = empty()
|
||||||
|
catalogs[greIpsecPaths.policy].push({ ".id": "*A", template: "true", protocol: "all", "src-address": "0.0.0.0/0", "dst-address": "0.0.0.0/0" })
|
||||||
|
catalogs[greIpsecPaths.peer].push({ ".id": "*B", address: "0.0.0.0/0", "exchange-mode": "ike2" })
|
||||||
|
assert.doesNotThrow(() => planGreIke2Side(pair, 0, catalogs, commands))
|
||||||
|
catalogs[greIpsecPaths.policy].push({ ".id": "*C", "src-address": "192.0.2.0/24", "dst-address": "198.51.100.0/24", protocol: "all" })
|
||||||
|
assert.throws(() => planGreIke2Side(pair, 0, catalogs, commands), /перекрывает GRE/)
|
||||||
|
catalogs[greIpsecPaths.policy].pop()
|
||||||
|
catalogs[greIpsecPaths.peer].push({ ".id": "*D", address: "198.51.100.6/32", "exchange-mode": "ike2" })
|
||||||
|
assert.throws(() => planGreIke2Side(pair, 0, catalogs, commands), /Уже настроен IKEv2 peer/)
|
||||||
|
catalogs[greIpsecPaths.peer].pop()
|
||||||
|
catalogs[greIpsecPaths.filter].push({ ".id": "*E", comment: commands[0].fields.comment! })
|
||||||
|
assert.throws(() => planGreIke2Side(pair, 0, catalogs, commands), /изменённый объект/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test("checks the existing defaults for a common encrypted suite and equal PFS", () => {
|
||||||
|
const catalogs = empty()
|
||||||
|
const first = { ".id": "*A", name: "default", "pfs-group": "modp1024", "enc-algorithms": "3des,aes-128-cbc,aes-256-cbc", "auth-algorithms": "sha1,sha256" }
|
||||||
|
catalogs[greIpsecPaths.proposal].push(first)
|
||||||
|
assert.equal(greIke2DefaultProposal(catalogs), first)
|
||||||
|
const second = { ...first, "enc-algorithms": "aes-256-cbc", "auth-algorithms": "sha256" }
|
||||||
|
assert.doesNotThrow(() => validateGreIke2Defaults(first, second))
|
||||||
|
assert.throws(() => validateGreIke2Defaults(first, { ...second, "pfs-group": "modp2048" }), /несовместимы/)
|
||||||
|
assert.throws(() => validateGreIke2Defaults(first, { ...second, "enc-algorithms": "null" }), /несовместимы/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test("resumes a partial side and changes only the verified old test policy's proposal", () => {
|
||||||
|
const commands = greIke2SideCommands(pair, 0, secret), catalogs = empty()
|
||||||
|
const name = commands.find(command => command.path === greIpsecPaths.profile)!.fields.name!
|
||||||
|
for (const [index, command] of commands.entries()) catalogs[command.path].push({ ...command.fields, ".id": `*${index + 1}` })
|
||||||
|
const [policy] = catalogs[greIpsecPaths.policy]
|
||||||
|
policy.proposal = name
|
||||||
|
const [patch] = planGreIke2Side(pair, 0, catalogs, commands)
|
||||||
|
assert.deepEqual(patch, { path: greIpsecPaths.policy, id: policy[".id"], fields: { proposal: "default" } })
|
||||||
|
const after = structuredClone(catalogs)
|
||||||
|
delete after[greIpsecPaths.policy][0].proposal
|
||||||
|
assert.equal(verifyGreIke2Update(catalogs, after, patch), true)
|
||||||
|
assert.deepEqual(planGreIke2Side(pair, 0, after, commands), [])
|
||||||
|
after[greIpsecPaths.policy][0].level = "use"
|
||||||
|
assert.equal(verifyGreIke2Update(catalogs, after, patch), false)
|
||||||
|
})
|
||||||
|
|
||||||
|
test("the runner can parse the prepared plan after its JSON round trip", () => {
|
||||||
|
const planned = greIke2StepInput(pair, 0, secret, "source-proof", [
|
||||||
|
{ path: greIpsecPaths.peer, fields: {} },
|
||||||
|
{ path: greIpsecPaths.policy, id: "*4", fields: { proposal: "default" } },
|
||||||
|
])
|
||||||
|
assert.deepEqual(greIke2StepSchema.parse(JSON.parse(JSON.stringify(planned))), planned)
|
||||||
|
assert.deepEqual(planned.writes, [
|
||||||
|
{ path: greIpsecPaths.peer, action: "create" },
|
||||||
|
{ path: greIpsecPaths.policy, id: "*4", action: "update" },
|
||||||
|
])
|
||||||
|
assert.throws(() => greIke2StepSchema.parse({ ...planned, writes: [{ path: greIpsecPaths.proposal, id: "*4", action: "update" }] }))
|
||||||
|
})
|
||||||
|
|
||||||
|
test("requires the new plaintext drop to precede existing rules and preserve every prior object", () => {
|
||||||
|
const [command] = greIke2SideCommands(pair, 0, secret), before = empty()
|
||||||
|
before[greIpsecPaths.filter] = [{ ".id": "*A", chain: "input", action: "accept", packets: "19" }]
|
||||||
|
const after = structuredClone(before)
|
||||||
|
after[greIpsecPaths.filter][0].packets = "20"
|
||||||
|
after[greIpsecPaths.filter].unshift({ ...command.fields, ".id": "*B", packets: "0" })
|
||||||
|
const verified = () => verifyGreIke2Create(greIke2StableCatalogues(before), greIke2StableCatalogues(after), command, "*B", "*A")
|
||||||
|
assert.equal(verified(), true)
|
||||||
|
after[greIpsecPaths.filter].reverse()
|
||||||
|
assert.equal(verified(), false)
|
||||||
|
after[greIpsecPaths.filter].reverse()
|
||||||
|
after[greIpsecPaths.filter][1].action = "drop"
|
||||||
|
assert.equal(verified(), false)
|
||||||
|
})
|
||||||
@@ -0,0 +1,281 @@
|
|||||||
|
import { randomBytes } from "node:crypto"
|
||||||
|
import { isIP } from "node:net"
|
||||||
|
import { z } from "zod"
|
||||||
|
import { greMutationProof, greTarget, readGreMutationState } from "../../services/gre-mutation-state.js"
|
||||||
|
import { greIke2TransportFields, greIpsecPaths, greIpsecPlaintextDrops } from "../../services/gre-ipsec-transport.js"
|
||||||
|
import { inIxNetwork } from "../../services/internet-exchange-plan.js"
|
||||||
|
import { ipsecPeerDeleteRows } from "../../services/ipsec-peer-delete.js"
|
||||||
|
import { IpsecServerInitExecutionError } from "../../services/ipsec-server-init.js"
|
||||||
|
import { observedBoolean } from "../../services/ospf-observed-values.js"
|
||||||
|
import { assertVerifiedConfigurationAccess } from "../../services/config-mutation-policy.js"
|
||||||
|
import type { add } from "./actions.js"
|
||||||
|
import type { ChangeEvidence } from "./action-types.js"
|
||||||
|
import { greMutationProtectionObjects } from "./gre-mutation-actions.js"
|
||||||
|
import { routerClient } from "./resources.js"
|
||||||
|
import { fingerprint, McpError, privateFingerprinter } from "./security.js"
|
||||||
|
import { registerMcpService } from "./service-registry.js"
|
||||||
|
|
||||||
|
const operation = "network.gre.ikev2_pair.configure"
|
||||||
|
const endpoint = z.object({
|
||||||
|
serverId: z.number().int().positive().safe(),
|
||||||
|
greName: z.string().trim().min(1).max(100),
|
||||||
|
outerAddress: z.string().refine(value => isIP(value) === 4 && value !== "0.0.0.0", "Требуется фиксированный внешний IPv4"),
|
||||||
|
}).strict()
|
||||||
|
const schema = z.object({ endpoints: z.array(endpoint).length(2) }).strict()
|
||||||
|
const writePath = z.enum([greIpsecPaths.filter, greIpsecPaths.profile, greIpsecPaths.peer, greIpsecPaths.identity, greIpsecPaths.policy])
|
||||||
|
export const greIke2StepSchema = schema.extend({
|
||||||
|
side: z.union([z.literal(0), z.literal(1)]),
|
||||||
|
ipsecSecret: z.string().regex(/^[a-f0-9]{64}$/),
|
||||||
|
beforeFingerprint: z.string(),
|
||||||
|
writes: z.array(z.discriminatedUnion("action", [
|
||||||
|
z.object({ path: writePath, action: z.literal("create") }).strict(),
|
||||||
|
z.object({ path: z.literal(greIpsecPaths.policy), action: z.literal("update"), id: z.string().regex(/^\*[a-z0-9]+$/i) }).strict(),
|
||||||
|
])).max(6),
|
||||||
|
})
|
||||||
|
type Pair = z.infer<typeof schema>
|
||||||
|
type Side = 0 | 1
|
||||||
|
type Fields = Record<string, string>
|
||||||
|
type Catalogue = Record<string, Fields[]>
|
||||||
|
type RouterWrite = { path: string; fields: Fields; id?: string }
|
||||||
|
export function greIke2StepInput(input: Pair, side: Side, ipsecSecret: string, beforeFingerprint: string, commands: RouterWrite[]) {
|
||||||
|
const writes = commands.map(({ path, id }) => id ? { path, id, action: "update" } : { path, action: "create" })
|
||||||
|
return greIke2StepSchema.parse({ endpoints: input.endpoints, side, ipsecSecret, beforeFingerprint, writes })
|
||||||
|
}
|
||||||
|
const sides = [0, 1] as const
|
||||||
|
const paths = Object.values(greIpsecPaths)
|
||||||
|
const runtimeFields: Readonly<Record<string, ReadonlySet<string>>> = {
|
||||||
|
[greIpsecPaths.filter]: new Set(["bytes", "packets"]),
|
||||||
|
[greIpsecPaths.policy]: new Set(["active", "invalid", "ph2-count", "ph2-state"]),
|
||||||
|
}
|
||||||
|
|
||||||
|
function target(input: Pair): ChangeEvidence["target"] {
|
||||||
|
const [first, second] = input.endpoints
|
||||||
|
if (first.serverId === second.serverId || first.outerAddress === second.outerAddress) {
|
||||||
|
throw new McpError("INVALID_INPUT", "Требуются два разных CHR и два разных внешних адреса")
|
||||||
|
}
|
||||||
|
return { scope: "servers", serverIds: [first.serverId, second.serverId] }
|
||||||
|
}
|
||||||
|
|
||||||
|
const nameFor = (input: Pair) => "mm-gre-ike2-" + fingerprint([...input.endpoints].sort((a, b) => a.serverId - b.serverId)).slice(0, 14)
|
||||||
|
export function greIke2SideCommands(input: Pair, side: Side, secret: string) {
|
||||||
|
const name = nameFor(input), local = input.endpoints[side].outerAddress, remote = input.endpoints[side === 0 ? 1 : 0].outerAddress
|
||||||
|
const [inbound, outbound] = greIpsecPlaintextDrops(local, remote)
|
||||||
|
const fields = greIke2TransportFields(name, local, remote, side === 0, secret, false)
|
||||||
|
return [
|
||||||
|
{ path: greIpsecPaths.filter, fields: { ...inbound, comment: `${name}:plain-in` } },
|
||||||
|
{ path: greIpsecPaths.filter, fields: { ...outbound, comment: `${name}:plain-out` } },
|
||||||
|
...(["profile", "peer"] as const).map(kind => ({ path: greIpsecPaths[kind], fields: fields[kind] })),
|
||||||
|
{ path: greIpsecPaths.identity, fields: { ...fields.identity, comment: `${name}:identity` } },
|
||||||
|
{ path: greIpsecPaths.policy, fields: { ...fields.policy, proposal: "default", comment: `${name}:policy` } },
|
||||||
|
] satisfies Array<{ path: string; fields: Fields }>
|
||||||
|
}
|
||||||
|
|
||||||
|
function includesIp(selector: string | undefined, address: string) {
|
||||||
|
if (!selector) return true
|
||||||
|
const [host, length] = selector.split("/")
|
||||||
|
if (isIP(host) === 6) return false
|
||||||
|
if (isIP(host) !== 4 || (length !== undefined && (!/^\d+$/.test(length) || Number(length) > 32))) {
|
||||||
|
throw new McpError("STATE_UNAVAILABLE", "Не подтверждён адресный селектор IPsec", 502)
|
||||||
|
}
|
||||||
|
return inIxNetwork(`${host}/${length ?? "32"}`, address)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ownedRows(catalogs: Catalogue, command: RouterWrite) {
|
||||||
|
return catalogs[command.path].filter(row => command.fields.comment ? row.comment === command.fields.comment : row.name === command.fields.name)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function greIke2DefaultProposal(catalogs: Catalogue) {
|
||||||
|
const rows = catalogs[greIpsecPaths.proposal].filter(row => row.name === "default")
|
||||||
|
const row = rows[0]
|
||||||
|
if (rows.length !== 1 || observedBoolean(row.disabled) === true || !row["pfs-group"] || !row["enc-algorithms"] || row["auth-algorithms"] === undefined) {
|
||||||
|
throw new McpError("STATE_UNAVAILABLE", "Не подтверждены действующие параметры IPsec proposal default", 502)
|
||||||
|
}
|
||||||
|
return row
|
||||||
|
}
|
||||||
|
|
||||||
|
export function validateGreIke2Defaults(first: Fields, second: Fields) {
|
||||||
|
const list = (row: Fields, field: string) => row[field].split(",").map(value => value.trim())
|
||||||
|
const shared = (field: string) => list(first, field).filter(value => list(second, field).includes(value))
|
||||||
|
const encryption = shared("enc-algorithms").filter(value => !!value && value !== "null")
|
||||||
|
const compatible = first["pfs-group"] === second["pfs-group"] && encryption.some(value => value.endsWith("-gcm") || value === "chacha20-poly1305" || shared("auth-algorithms").some(auth => !!auth && auth !== "null"))
|
||||||
|
if (!compatible || (list(first, "enc-algorithms").includes("null") && list(second, "enc-algorithms").includes("null"))) {
|
||||||
|
throw new McpError("DEPENDENCY_CONFLICT", "IPsec proposal default на двух CHR несовместимы или допускают GRE без шифрования", 409)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function planGreIke2Side(input: Pair, side: Side, catalogs: Catalogue, commands: ReturnType<typeof greIke2SideCommands>): RouterWrite[] {
|
||||||
|
const name = nameFor(input), local = input.endpoints[side].outerAddress, remote = input.endpoints[side === 0 ? 1 : 0].outerAddress
|
||||||
|
if (catalogs[greIpsecPaths.peer].some(row => row.name !== name && row["exchange-mode"] === "ike2" && observedBoolean(row.disabled) !== true &&
|
||||||
|
[remote, `${remote}/32`].includes(row.address) && (!row["local-address"] || ["0.0.0.0", local].includes(row["local-address"])))) {
|
||||||
|
throw new McpError("DEPENDENCY_CONFLICT", "Уже настроен IKEv2 peer для этих внешних адресов", 409)
|
||||||
|
}
|
||||||
|
if (catalogs[greIpsecPaths.policy].some(row => row.comment !== `${name}:policy` && observedBoolean(row.template) !== true && observedBoolean(row.disabled) !== true &&
|
||||||
|
[undefined, "", "all", "0", "255", "gre", "47"].includes(row.protocol) &&
|
||||||
|
((includesIp(row["src-address"], local) && includesIp(row["dst-address"], remote)) ||
|
||||||
|
(includesIp(row["src-address"], remote) && includesIp(row["dst-address"], local))))) {
|
||||||
|
throw new McpError("DEPENDENCY_CONFLICT", "Существующая IPsec policy перекрывает GRE между выбранными адресами", 409)
|
||||||
|
}
|
||||||
|
return commands.flatMap<RouterWrite>(command => {
|
||||||
|
const found = ownedRows(catalogs, command), row = found[0]
|
||||||
|
if (!row) return [command]
|
||||||
|
if (found.length === 1 && observedBoolean(row.dynamic) !== true && observedBoolean(row.builtin) !== true && observedBoolean(row.disabled) !== true) {
|
||||||
|
if (matches(command.fields, row)) {
|
||||||
|
if (command.path === greIpsecPaths.filter && catalogs[command.path].slice(0, catalogs[command.path].indexOf(row)).some(previous =>
|
||||||
|
observedBoolean(previous.dynamic) !== true && observedBoolean(previous.disabled) !== true && previous.chain === row.chain && previous.action !== "drop" &&
|
||||||
|
[undefined, "", "all", "0", "255", "gre", "47"].includes(previous.protocol) && !previous["ipsec-policy"]?.endsWith(",ipsec"))) {
|
||||||
|
throw new McpError("DEPENDENCY_CONFLICT", "Правило против незашифрованного GRE находится после правила, которое может пропустить его", 409)
|
||||||
|
}
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
if (command.path === greIpsecPaths.policy && matches({ ...command.fields, proposal: name }, row)) {
|
||||||
|
return [{ path: command.path, id: row[".id"], fields: { proposal: "default" } }]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new McpError("STATE_CONFLICT", `Пара IKEv2 имеет неоднозначный или изменённый объект в ${command.path}`, 409)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function greIke2StableCatalogues(catalogs: Catalogue) {
|
||||||
|
return Object.fromEntries(paths.map(path => [path, catalogs[path]
|
||||||
|
.filter(row => observedBoolean(row.dynamic) !== true)
|
||||||
|
.map(row => Object.fromEntries(Object.entries(row).filter(([key]) => !runtimeFields[path]?.has(key))))]))
|
||||||
|
}
|
||||||
|
|
||||||
|
function matches(expected: Fields, observed: Fields) {
|
||||||
|
return Object.entries(expected).every(([key, value]) => {
|
||||||
|
const actual = observed[key]
|
||||||
|
if (["disabled", "tunnel", "passive"].includes(key)) return (observedBoolean(actual) ?? (actual === undefined ? false : null)) === observedBoolean(value)
|
||||||
|
if (["address", "src-address", "dst-address"].includes(key)) return actual?.replace(/\/32$/, "") === value.replace(/\/32$/, "")
|
||||||
|
if (key === "protocol" && value === "gre") return actual === "gre" || actual === "47"
|
||||||
|
if (key === "proposal" && value === "default") return actual === undefined || actual === "default"
|
||||||
|
return actual === value
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function verifyGreIke2Update(before: Catalogue, after: Catalogue, command: RouterWrite) {
|
||||||
|
const source = before[command.path].find(row => row[".id"] === command.id)
|
||||||
|
const observed = after[command.path].find(row => row[".id"] === command.id)
|
||||||
|
if (!source || !observed || !matches(command.fields, observed)) return false
|
||||||
|
const projected = { ...source }
|
||||||
|
for (const key of Object.keys(command.fields)) {
|
||||||
|
if (observed[key] === undefined) delete projected[key]
|
||||||
|
else projected[key] = observed[key]
|
||||||
|
}
|
||||||
|
return fingerprint({ ...before, [command.path]: before[command.path].map(row => row === source ? projected : row) }) === fingerprint(after)
|
||||||
|
}
|
||||||
|
|
||||||
|
function pairSecret(input: Pair, sides: Catalogue[]) {
|
||||||
|
const name = nameFor(input)
|
||||||
|
const identities = sides.flatMap(catalogs => catalogs[greIpsecPaths.identity].filter(row => row.comment === `${name}:identity`))
|
||||||
|
const values = new Set(identities.map(row => row.secret))
|
||||||
|
if (values.size === 0) return randomBytes(32).toString("hex")
|
||||||
|
const [value] = values
|
||||||
|
if (values.size !== 1 || typeof value !== "string" || !/^[a-f0-9]{64}$/.test(value)) throw new McpError("STATE_CONFLICT", "Не подтверждён общий PSK частично настроенной пары", 409)
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
|
||||||
|
function completedPairProof(input: Pair, side: Side, catalogs: Catalogue, commands: ReturnType<typeof greIke2SideCommands>) {
|
||||||
|
if (planGreIke2Side(input, side, catalogs, commands).length !== 0) throw new McpError("VERIFICATION_FAILED", "IKEv2 остался настроен не полностью", 502)
|
||||||
|
return fingerprint({ proposal: greIke2DefaultProposal(catalogs), objects: commands.map(command => ({ path: command.path, id: ownedRows(catalogs, command)[0][".id"] })) })
|
||||||
|
}
|
||||||
|
|
||||||
|
export function verifyGreIke2Create(before: Catalogue, after: Catalogue, command: { path: string; fields: Fields }, nativeId: string | undefined, first: string | undefined) {
|
||||||
|
const created = after[command.path].find(row => row[".id"] === nativeId)
|
||||||
|
return !!created && !before[command.path].some(row => row[".id"] === nativeId) && matches(command.fields, created) &&
|
||||||
|
(first === undefined || after[command.path][0] === created) &&
|
||||||
|
fingerprint({ ...after, [command.path]: after[command.path].filter(row => row !== created) }) === fingerprint(before)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function readSide(input: Pair, side: Side) {
|
||||||
|
const local = input.endpoints[side], remote = input.endpoints[side === 0 ? 1 : 0]
|
||||||
|
const { server, client } = await routerClient(local.serverId)
|
||||||
|
const mutation = { operation: "update" as const, name: local.greName, fields: { ipsecSecret: "" } }
|
||||||
|
const readCatalogues = async () => Object.fromEntries(await Promise.all(paths.map(async path =>
|
||||||
|
[path, ipsecPeerDeleteRows(await client.get<unknown>(path, 10000, undefined, 1048576))] as const)))
|
||||||
|
const [gre, catalogs] = await Promise.all([readGreMutationState(server, mutation), readCatalogues()])
|
||||||
|
const row = greTarget(mutation, gre)
|
||||||
|
if (!row || observedBoolean(row.dynamic) === true || observedBoolean(row.disabled) !== true || observedBoolean(row["allow-fast-path"]) !== false ||
|
||||||
|
row["local-address"] !== local.outerAddress || row["remote-address"] !== remote.outerAddress || row["ipsec-secret"] !== "") {
|
||||||
|
throw new McpError("STATE_CONFLICT", `На сервере ${local.serverId} требуется статический отключённый GRE с указанными адресами, без FastPath и встроенного PSK`, 409)
|
||||||
|
}
|
||||||
|
const seal = await privateFingerprinter("mcp-gre-ikev2-pair-v1")
|
||||||
|
const proof = seal(fingerprint({ gre: greMutationProof(gre), catalogs: greIke2StableCatalogues(catalogs) }))
|
||||||
|
return { server, client, gre, catalogs, readCatalogues, proof }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function registerGreIke2PairActions(register: typeof add) {
|
||||||
|
registerMcpService(operation, {
|
||||||
|
current: async raw => {
|
||||||
|
const input = greIke2StepSchema.parse(raw)
|
||||||
|
return await Promise.all(sides.map(async side => (await readSide(input, side)).proof))
|
||||||
|
},
|
||||||
|
execute: async raw => {
|
||||||
|
const input = greIke2StepSchema.parse(raw), side = input.side, state = await readSide(input, side)
|
||||||
|
if (state.proof !== input.beforeFingerprint) throw new McpError("STATE_CONFLICT", "GRE или IPsec изменился после подготовки", 409)
|
||||||
|
const desired = greIke2SideCommands(input, side, input.ipsecSecret)
|
||||||
|
const commands = planGreIke2Side(input, side, state.catalogs, desired)
|
||||||
|
const reviewed = greIke2StepInput(input, side, input.ipsecSecret, state.proof, commands).writes
|
||||||
|
if (fingerprint(reviewed) !== fingerprint(input.writes)) throw new McpError("STATE_CONFLICT", "Подготовленные команды IKEv2 отличаются от плана", 409)
|
||||||
|
let before = greIke2StableCatalogues(state.catalogs), confirmed = 0, verified = 0
|
||||||
|
for (const command of commands) {
|
||||||
|
let dispatched = false
|
||||||
|
try {
|
||||||
|
const first = command.path === greIpsecPaths.filter ? before[command.path][0]?.[".id"] : undefined
|
||||||
|
const fence = async () => {
|
||||||
|
await assertVerifiedConfigurationAccess()
|
||||||
|
if (fingerprint((await routerClient(Number(state.server.id))).server) !== fingerprint(state.server)) throw new McpError("STATE_CONFLICT", "Источник RouterOS изменился перед записью", 409)
|
||||||
|
if (fingerprint(greIke2StableCatalogues(await state.readCatalogues())) !== fingerprint(before)) throw new McpError("STATE_CONFLICT", "IPsec изменился перед записью", 409)
|
||||||
|
dispatched = true
|
||||||
|
}
|
||||||
|
const ack = command.id
|
||||||
|
? await state.client.patch<Fields>(`${command.path}/${encodeURIComponent(command.id)}`, command.fields, 10000, fence)
|
||||||
|
: await state.client.put<Fields>(command.path, { ...command.fields, ...(first ? { "place-before": first } : {}) }, 10000, fence)
|
||||||
|
confirmed++
|
||||||
|
const after = greIke2StableCatalogues(await state.readCatalogues())
|
||||||
|
const exact = command.id ? verifyGreIke2Update(before, after, command) : verifyGreIke2Create(before, after, command, ack?.[".id"], first)
|
||||||
|
if (!exact) {
|
||||||
|
throw new McpError("VERIFICATION_FAILED", "Ответ RouterOS не подтверждает точное добавление объекта", 502)
|
||||||
|
}
|
||||||
|
before = after
|
||||||
|
verified++
|
||||||
|
} catch (error) {
|
||||||
|
if (!dispatched && !confirmed && error instanceof McpError) throw error
|
||||||
|
throw new IpsecServerInitExecutionError(error instanceof McpError && error.code === "VERIFICATION_FAILED" || !dispatched ? "VERIFICATION_FAILED" : "MUTATION_OUTCOME_UNKNOWN",
|
||||||
|
`Настройка IKEv2 остановлена на ${command.path}. GRE оставлен отключённым, требуется сверка перед повтором.`, confirmed, verified, commands.length)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const after = await readSide(input, side)
|
||||||
|
const afterFingerprint = completedPairProof(input, side, after.catalogs, desired)
|
||||||
|
return { verified: true, commandCount: commands.length, afterFingerprint, greEnabled: false, forwardingVerified: false }
|
||||||
|
},
|
||||||
|
verify: async (raw, result) => {
|
||||||
|
const input = greIke2StepSchema.parse(raw)
|
||||||
|
const receipt = result as { verified?: boolean; afterFingerprint?: string } | null
|
||||||
|
return receipt?.verified === true && receipt.afterFingerprint === completedPairProof(input, input.side,
|
||||||
|
(await readSide(input, input.side)).catalogs, greIke2SideCommands(input, input.side, input.ipsecSecret))
|
||||||
|
},
|
||||||
|
})
|
||||||
|
register(operation, "mm_gre_ikev2_pair_configure_plan", "План настройки отдельного IKEv2 для двух существующих GRE", "network", "mm:network:write", "write", "servers", schema, {
|
||||||
|
version: 3,
|
||||||
|
target: raw => target(schema.parse(raw)),
|
||||||
|
prepare: async raw => {
|
||||||
|
const input = schema.parse(raw), scope = target(input)
|
||||||
|
const before = await Promise.all(sides.map(side => readSide(input, side)))
|
||||||
|
const catalogs = before.map(state => state.catalogs)
|
||||||
|
validateGreIke2Defaults(greIke2DefaultProposal(catalogs[0]), greIke2DefaultProposal(catalogs[1]))
|
||||||
|
const ipsecSecret = pairSecret(input, catalogs)
|
||||||
|
const changes = sides.map(side => planGreIke2Side(input, side, catalogs[side], greIke2SideCommands(input, side, ipsecSecret)))
|
||||||
|
const steps = sides.map(side => ({ kind: "service" as const, service: operation,
|
||||||
|
input: greIke2StepInput(input, side, ipsecSecret, before[side].proof, changes[side]),
|
||||||
|
}))
|
||||||
|
const objects = (await Promise.all(before.map(state => greMutationProtectionObjects(Number(state.server.id), state.gre)))).flat()
|
||||||
|
return { target: scope, objects, snapshots: [], before: before.map(state => state.proof), steps, mutationCost: Math.max(1, changes.flat().length), requiresHuman: true,
|
||||||
|
warnings: [
|
||||||
|
`На каждом CHR настраиваются выделенные объекты ${nameFor(input)}: profile, peer, identity, транспортная policy GRE с proposal default и два правила против GRE без IPsec. Первая сторона — responder, вторая — инициатор.`,
|
||||||
|
"GRE остаются отключёнными. Proposal default используется после проверки совместимости и не изменяется. Для IKE/ESP требуются разрешения действующего firewall.",
|
||||||
|
"Ранее созданные объекты пары переиспользуются только при совпадении параметров. У старой политики пары разрешена смена proposal на default. IPsec SA проверяется после отдельного включения GRE.",
|
||||||
|
],
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -36,11 +36,15 @@ export function registerGreMutationActions(register: typeof add) {
|
|||||||
return receipt?.verified===true && fingerprint(await current(input))===receipt.afterFingerprint
|
return receipt?.verified===true && fingerprint(await current(input))===receipt.afterFingerprint
|
||||||
}})
|
}})
|
||||||
register(service,"mm_gre_tunnel_"+operation+"_plan","План "+["создания","изменения","удаления"][index]+" GRE и его внутренних адресов", "network","mm:network:write","write","servers",schemas[index],{
|
register(service,"mm_gre_tunnel_"+operation+"_plan","План "+["создания","изменения","удаления"][index]+" GRE и его внутренних адресов", "network","mm:network:write","write","servers",schemas[index],{
|
||||||
|
version: operation === "delete" ? 1 : 2,
|
||||||
prepare:async(input,context)=>{
|
prepare:async(input,context)=>{
|
||||||
const serverId = Number(input.serverId), {server} = await routerClient(serverId)
|
const serverId = Number(input.serverId), {server} = await routerClient(serverId)
|
||||||
let mutation = greMutationSchema.parse({operation,...(operation==="create"?{fields:input.fields}:{...("rosId" in input?{rosId:input.rosId}:{}),...("name" in input?{name:input.name}:{}),...(operation==="update"?{fields:input.fields}:{})})})
|
|
||||||
const state = await readGreMutationState(server,mutation), target = greTarget(mutation,state)
|
|
||||||
if (input.ipsecSecretRef && input.clearIpsecSecret) throw new McpError("INVALID_INPUT","Выберите новый PSK или явное удаление",400)
|
if (input.ipsecSecretRef && input.clearIpsecSecret) throw new McpError("INVALID_INPUT","Выберите новый PSK или явное удаление",400)
|
||||||
|
let mutation = greMutationSchema.parse({operation,...(operation==="create"?{fields:input.fields}:{...("rosId" in input?{rosId:input.rosId}:{}),...("name" in input?{name:input.name}:{}),...(operation==="update"?{fields:input.fields}:{})})})
|
||||||
|
if (mutation.operation === "update" && (input.ipsecSecretRef || input.clearIpsecSecret)) {
|
||||||
|
mutation = { ...mutation, fields: { ...mutation.fields, ipsecSecret: "" } }
|
||||||
|
}
|
||||||
|
const state = await readGreMutationState(server,mutation), target = greTarget(mutation,state)
|
||||||
if (mutation.operation!=="delete" && (input.ipsecSecretRef || input.clearIpsecSecret)) {
|
if (mutation.operation!=="delete" && (input.ipsecSecretRef || input.clearIpsecSecret)) {
|
||||||
const name = mutation.operation==="create"?mutation.fields.name:target?.name
|
const name = mutation.operation==="create"?mutation.fields.name:target?.name
|
||||||
let value = ""
|
let value = ""
|
||||||
|
|||||||
@@ -69,6 +69,7 @@ export function registerGreRevisionActions(register:typeof add){
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
register(service,"mm_gre_revision_restore_plan","Восстановить GRE и все статические адреса из ревизии после подтверждения","network","mm:network:write","write","servers",z.object({serverId:z.number().int().positive().safe(),revisionId:z.string().uuid()}).strict(),{
|
register(service,"mm_gre_revision_restore_plan","Восстановить GRE и все статические адреса из ревизии после подтверждения","network","mm:network:write","write","servers",z.object({serverId:z.number().int().positive().safe(),revisionId:z.string().uuid()}).strict(),{
|
||||||
|
version:2,
|
||||||
prepare:async(input,context)=>{
|
prepare:async(input,context)=>{
|
||||||
const req=request(input,context),source=await read(req,context.signal)
|
const req=request(input,context),source=await read(req,context.signal)
|
||||||
const desired=materializeGreRestore(source.revision.desired,source.state),steps=planGreRevisionRestore(desired,source.state)
|
const desired=materializeGreRestore(source.revision.desired,source.state),steps=planGreRevisionRestore(desired,source.state)
|
||||||
|
|||||||
@@ -34,14 +34,19 @@ const native=createServer(async(req,res)=>{
|
|||||||
}
|
}
|
||||||
assert.ok(base,"Only typed GRE/address writes allowed")
|
assert.ok(base,"Only typed GRE/address writes allowed")
|
||||||
writes++
|
writes++
|
||||||
if(base==="/interface/gre"&&data["ipsec-secret"]===""&&["yes","true"].includes(data["allow-fast-path"])){
|
if(base==="/interface/gre"&&data["ipsec-secret"]===""){
|
||||||
res.statusCode=400;res.end(JSON.stringify({error:400,detail:"failure: cannot enable fastpath together with ipsec yet"}));return
|
res.statusCode=400;res.end(JSON.stringify({error:400,detail:"unexpected empty IPsec secret assignment"}));return
|
||||||
}
|
}
|
||||||
const fields=Object.fromEntries(Object.entries(data).map(([k,v])=>[k,v==="yes"?"true":v==="no"?"false":String(v)]))
|
const fields=Object.fromEntries(Object.entries(data).map(([k,v])=>[k,v==="yes"?"true":v==="no"?"false":String(v)]))
|
||||||
if(!ignored){
|
if(!ignored){
|
||||||
if(req.method==="PUT"){
|
if(req.method==="PUT"){
|
||||||
const row=base==="/interface/gre"?{".id":"*G"+(++nextId),"local-address":"0.0.0.0",mtu:"1476",keepalive:"10s,10",dscp:"inherit",disabled:"false",dynamic:"false",running:"false","clamp-tcp-mss":"true","allow-fast-path":"true","ipsec-secret":"",comment:"",...fields}:{".id":"*A"+(++nextId),disabled:"false",dynamic:"false",invalid:"false",advertise:"false","no-dad":"false","eui-64":"false","from-pool":"",comment:"",...fields}
|
const row=base==="/interface/gre"?{".id":"*G"+(++nextId),"local-address":"0.0.0.0",mtu:"1476",keepalive:"10s,10",dscp:"inherit",disabled:"false",dynamic:"false",running:"false","clamp-tcp-mss":"true","allow-fast-path":"true","ipsec-secret":"",comment:"",...fields}:{".id":"*A"+(++nextId),disabled:"false",dynamic:"false",invalid:"false",advertise:"false","no-dad":"false","eui-64":"false","from-pool":"",comment:"",...fields}
|
||||||
;(collections[base]??=[]).push(row)
|
;(collections[base]??=[]).push(row)
|
||||||
|
}else if(req.method==="POST"&&path==="/interface/gre/unset"){
|
||||||
|
assert.equal(data["value-name"],"ipsec-secret")
|
||||||
|
const row=collections[base].find(r=>r[".id"]===data[".id"])
|
||||||
|
assert.ok(row)
|
||||||
|
row["ipsec-secret"]=""
|
||||||
}else if(req.method==="PATCH")Object.assign(collections[base].find(r=>r[".id"]===path.slice(base.length+1))!,fields)
|
}else if(req.method==="PATCH")Object.assign(collections[base].find(r=>r[".id"]===path.slice(base.length+1))!,fields)
|
||||||
else if(req.method==="DELETE")collections[base]=collections[base].filter(r=>r[".id"]!==path.slice(base.length+1))
|
else if(req.method==="DELETE")collections[base]=collections[base].filter(r=>r[".id"]!==path.slice(base.length+1))
|
||||||
else assert.fail("Unsupported native write")
|
else assert.fail("Unsupported native write")
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ const creates = rosResources.filter(resource => !resource.readOnly && resource.c
|
|||||||
assert.equal(creates.length, 30)
|
assert.equal(creates.length, 30)
|
||||||
for (const resource of creates) {
|
for (const resource of creates) {
|
||||||
const action = findAction(`mm_${resource.id}_create_plan`)
|
const action = findAction(`mm_${resource.id}_create_plan`)
|
||||||
assert.equal(action.operation.version, resource.id === "bfd_configuration" ? 8 : resource.id === "ospf_template" ? 11 : ["ipsec_peer", "vrf", "ospf_instance"].includes(resource.id) ? 5 : ["wireguard", "bridge", "bridge_port", "bridge_vlan"].includes(resource.id) ? 4 : 3)
|
assert.equal(action.operation.version, resource.id === "bfd_configuration" ? 9 : resource.id === "ospf_template" ? 11 : ["ipsec_peer", "vrf", "ospf_instance"].includes(resource.id) ? 5 : ["wireguard", "bridge", "bridge_port", "bridge_vlan"].includes(resource.id) ? 4 : 3)
|
||||||
assert.equal(action.schema.safeParse({ serverId: 1, fields: {} }).success, true)
|
assert.equal(action.schema.safeParse({ serverId: 1, fields: {} }).success, true)
|
||||||
for (const id of ["*OLD", undefined, null, ""]) {
|
for (const id of ["*OLD", undefined, null, ""]) {
|
||||||
const rejected = action.schema.safeParse({ serverId: 1, fields: {}, id })
|
const rejected = action.schema.safeParse({ serverId: 1, fields: {}, id })
|
||||||
@@ -27,6 +27,7 @@ assert.throws(() => validateRosStep(bfdConfig, "create", { vrf: "main" }), inval
|
|||||||
assert.deepEqual(validateRosStep(bfdConfig, "create", { interfaces: "bridge1", vrf: "main" }), { interfaces: "bridge1", vrf: "main" })
|
assert.deepEqual(validateRosStep(bfdConfig, "create", { interfaces: "bridge1", vrf: "main" }), { interfaces: "bridge1", vrf: "main" })
|
||||||
for (const interfaces of ["all", "none", "bridge1,all", "bridge1,"]) assert.throws(() => validateRosStep(bfdConfig, "create", { interfaces, vrf: "main" }), invalid)
|
for (const interfaces of ["all", "none", "bridge1,all", "bridge1,"]) assert.throws(() => validateRosStep(bfdConfig, "create", { interfaces, vrf: "main" }), invalid)
|
||||||
for (const [addresses, expected] of [["192.0.2.9/24", "192.0.2.0/24"], ["FD00::20/64", "fd00::/64"], ["192.0.2.9/32", "192.0.2.9/32"], ["fd00::20/128", "fd00::20/128"]]) {
|
for (const [addresses, expected] of [["192.0.2.9/24", "192.0.2.0/24"], ["FD00::20/64", "fd00::/64"], ["192.0.2.9/32", "192.0.2.9/32"], ["fd00::20/128", "fd00::20/128"]]) {
|
||||||
|
assert.deepEqual(validateRosStep(bfdConfig, "create", { addresses, vrf: "main" }), { addresses: expected, vrf: "main" })
|
||||||
assert.deepEqual(validateRosStep(bfdConfig, "update", { addresses }, "*A"), { addresses: expected })
|
assert.deepEqual(validateRosStep(bfdConfig, "update", { addresses }, "*A"), { addresses: expected })
|
||||||
}
|
}
|
||||||
for (const addresses of ["0.0.0.0/0", "::/0", "192.0.2.1", "fd00::/129", "192.0.2.1/32/extra", "192.0.2.0/24,192.0.3.0/24", "fe80::%ether1/64"]) assert.equal(bfdConfig.fields.safeParse({ addresses }).success, false)
|
for (const addresses of ["0.0.0.0/0", "::/0", "192.0.2.1", "fd00::/129", "192.0.2.1/32/extra", "192.0.2.0/24,192.0.3.0/24", "fe80::%ether1/64"]) assert.equal(bfdConfig.fields.safeParse({ addresses }).success, false)
|
||||||
|
|||||||
@@ -381,7 +381,7 @@ export function validateRosStep(resource: RosResourceSpec, action: RosStep["acti
|
|||||||
const parsed = resource.fields.parse(fields ?? {}) as Record<string, unknown>
|
const parsed = resource.fields.parse(fields ?? {}) as Record<string, unknown>
|
||||||
if (action === "create" && resource.requiredOnCreate?.some(field => parsed[field] === undefined)) throw new McpError("INVALID_INPUT", "Не заполнены обязательные поля создания", 400)
|
if (action === "create" && resource.requiredOnCreate?.some(field => parsed[field] === undefined)) throw new McpError("INVALID_INPUT", "Не заполнены обязательные поля создания", 400)
|
||||||
if (resource.id === "bfd_configuration" && action === "create") {
|
if (resource.id === "bfd_configuration" && action === "create") {
|
||||||
if (!parsed.interfaces && !parsed["address-list"]) throw new McpError("INVALID_INPUT", "Для правила BFD укажите интерфейсы или address-list", 400)
|
if (!parsed.interfaces && !parsed.addresses && !parsed["address-list"]) throw new McpError("INVALID_INPUT", "Для правила BFD укажите interfaces, addresses или address-list", 400)
|
||||||
if (parsed.interfaces && parsed.addresses === undefined && String(parsed.interfaces).split(",").some(value => !value.trim() || /^(?:all|none)$/i.test(value.trim()))) {
|
if (parsed.interfaces && parsed.addresses === undefined && String(parsed.interfaces).split(",").some(value => !value.trim() || /^(?:all|none)$/i.test(value.trim()))) {
|
||||||
throw new McpError("INVALID_INPUT", "Для правила BFD без адреса укажите конкретные интерфейсы", 400)
|
throw new McpError("INVALID_INPUT", "Для правила BFD без адреса укажите конкретные интерфейсы", 400)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,24 @@
|
|||||||
import type { MikrotikClient } from "./mikrotik.js"
|
import type { MikrotikClient } from "./mikrotik.js"
|
||||||
import { nativeBgpRows, type NativeBgpRow } from "./bgp-export-model.js"
|
import { nativeBgpRows, type NativeBgpRow } from "./bgp-export-model.js"
|
||||||
|
import { bgpFilterName } from "./bgp-filter-binding-model.js"
|
||||||
import { readOspfEffectiveDisabled } from "./ospf-effective-disabled.js"
|
import { readOspfEffectiveDisabled } from "./ospf-effective-disabled.js"
|
||||||
import { McpError } from "../modules/mcp/security.js"
|
import { McpError } from "../modules/mcp/security.js"
|
||||||
|
|
||||||
|
export async function readBgpInstanceContext(client: Pick<MikrotikClient, "post">, row: NativeBgpRow) {
|
||||||
|
const read = async (key: "vrf" | "routing-table") => {
|
||||||
|
const value = row[key]
|
||||||
|
return value === undefined || value === ""
|
||||||
|
? bgpFilterName(await client.post("/routing/bgp/instance/get", { ".id": row[".id"], "value-name": key }))
|
||||||
|
: bgpFilterName({ ret: value })
|
||||||
|
}
|
||||||
|
const [observedVrf, observedTable] = await Promise.all([read("vrf"), read("routing-table")])
|
||||||
|
const vrf = observedVrf || "main"
|
||||||
|
// Only infer the routing table when the instance uses the built-in VRF.
|
||||||
|
const table = observedTable || (vrf === "main" ? "main" : null)
|
||||||
|
if (!table) throw new McpError("STATE_UNAVAILABLE", "Не подтверждена таблица BGP instance", 409)
|
||||||
|
return { vrf, table }
|
||||||
|
}
|
||||||
|
|
||||||
/** Prove a configured peer, including RouterOS releases that omit the D flag. */
|
/** Prove a configured peer, including RouterOS releases that omit the D flag. */
|
||||||
export async function readStaticBgpConnection(client: Pick<MikrotikClient, "get" | "post">, id: string) {
|
export async function readStaticBgpConnection(client: Pick<MikrotikClient, "get" | "post">, id: string) {
|
||||||
const connections = nativeBgpRows(await client.get("/routing/bgp/connection")), target = connections.find(row => row[".id"] === id)
|
const connections = nativeBgpRows(await client.get("/routing/bgp/connection")), target = connections.find(row => row[".id"] === id)
|
||||||
|
|||||||
@@ -0,0 +1,172 @@
|
|||||||
|
import assert from "node:assert/strict"
|
||||||
|
import { test } from "node:test"
|
||||||
|
import { readBgpRib } from "./bgp-rib-observation.js"
|
||||||
|
|
||||||
|
const table = "rtab-antiblock"
|
||||||
|
const primary = "*B000001"
|
||||||
|
const standby = "*B000002"
|
||||||
|
const selection = { table, mode: "page" as const, limit: 500, offset: 0 }
|
||||||
|
|
||||||
|
function route(index: number, overrides: Record<string, string> = {}): Record<string, string> {
|
||||||
|
return {
|
||||||
|
".id": "*" + (index + 1).toString(16).toUpperCase(),
|
||||||
|
afi: "ip", bgp: "true", dynamic: "true", "routing-table": table,
|
||||||
|
"dst-address": `198.18.${Math.floor(index / 256)}.${index % 256}/32`,
|
||||||
|
contribution: "active", active: "true", "bgp.peer-cache-id": primary,
|
||||||
|
gateway: "10.255.255.100", "immediate-gw": "10.253.250.1%gre-jh-test-msk",
|
||||||
|
...overrides,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function fixture(rows: Record<string, string>[]) {
|
||||||
|
const reads = { routePages: 0, counts: 0, sessionFilters: new Set<string>() }
|
||||||
|
const client = {
|
||||||
|
async get<T>(path: string, _timeout?: number, _signal?: AbortSignal, maxResponseBytes?: number) {
|
||||||
|
assert((maxResponseBytes ?? 8 * 1024 * 1024) <= 8 * 1024 * 1024, "MikrotikClient rejects GET limits above 8 MiB")
|
||||||
|
const { pathname, searchParams } = new URL(path, "http://router.invalid")
|
||||||
|
if (pathname === "/routing/table") return [{ ".id": "*1", name: table }] as T
|
||||||
|
assert.equal(pathname, "/routing/route")
|
||||||
|
assert(!searchParams.has("bgp") && !searchParams.has("afi"), "Independent RIB read must include unclassified rows")
|
||||||
|
assert.equal(searchParams.get("routing-table"), table)
|
||||||
|
reads.routePages++
|
||||||
|
const properties = searchParams.get(".proplist")?.split(",")
|
||||||
|
assert(properties)
|
||||||
|
return rows.filter(row => row["routing-table"] === table)
|
||||||
|
.map(row => Object.fromEntries(Object.entries(row).filter(([key]) => properties.includes(key)))) as T
|
||||||
|
},
|
||||||
|
async post<T>(path: string, body: Record<string, string | string[]>) {
|
||||||
|
assert.equal(path, "/routing/route/print")
|
||||||
|
assert.equal(body["count-only"], "")
|
||||||
|
const query = body[".query"]
|
||||||
|
assert(Array.isArray(query))
|
||||||
|
const peer = query.find(word => word.startsWith("bgp.peer-cache-id="))?.split("=")[1]
|
||||||
|
const session = query.find(word => word.startsWith("bgp.session="))?.slice("bgp.session=".length)
|
||||||
|
assert.deepEqual(query, [
|
||||||
|
"routing-table=" + table, "bgp=true", "afi=ip", "afi=ip4", "#|",
|
||||||
|
...(peer ? ["bgp.peer-cache-id=" + peer] : []),
|
||||||
|
...(session ? ["bgp.session=" + session] : []),
|
||||||
|
])
|
||||||
|
reads.counts++
|
||||||
|
if (session !== undefined) reads.sessionFilters.add(session)
|
||||||
|
const count = rows.filter(row =>
|
||||||
|
row["routing-table"] === table && row.bgp === "true" && (row.afi === "ip" || row.afi === "ip4") &&
|
||||||
|
(!peer || row["bgp.peer-cache-id"] === peer) && (!session || row["bgp.session"] === session),
|
||||||
|
).length
|
||||||
|
return { ret: String(count) } as T
|
||||||
|
},
|
||||||
|
}
|
||||||
|
return { client, reads }
|
||||||
|
}
|
||||||
|
|
||||||
|
test("positive native count is cheap; a verified zero independently reads the target table", async () => {
|
||||||
|
const nonempty = fixture([route(0)])
|
||||||
|
assert.equal((await readBgpRib(nonempty.client, { ...selection, mode: "count" })).total, 1)
|
||||||
|
assert.equal(nonempty.reads.routePages, 0)
|
||||||
|
const { client, reads } = fixture([route(0, { "routing-table": "main" }), route(1, { afi: "ip6", "dst-address": "2001:db8::/32" })])
|
||||||
|
const result = await readBgpRib(client, { ...selection, mode: "count" })
|
||||||
|
assert.equal(result.total, 0)
|
||||||
|
assert(reads.counts > 0)
|
||||||
|
assert.equal(reads.routePages, 1)
|
||||||
|
|
||||||
|
for (const invalid of [[], {}, { ret: "" }, { ret: "0oops" }, { ret: "-1" }]) {
|
||||||
|
const broken = { ...client, post: async <T>() => invalid as T }
|
||||||
|
await assert.rejects(readBgpRib(broken, { ...selection, mode: "count" }))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test("zero fails closed on a missed IPv4 BGP route or ambiguous native BGP evidence", async () => {
|
||||||
|
const staticRow = { ".id": "*70", afi: "ip", static: "true", "routing-table": table, "dst-address": "198.18.250.1/32", contribution: "active", active: "true" }
|
||||||
|
const justStatic = fixture([staticRow])
|
||||||
|
assert.equal((await readBgpRib(justStatic.client, { ...selection, mode: "count" })).total, 0)
|
||||||
|
assert.equal(justStatic.reads.routePages, 1)
|
||||||
|
for (const ambiguous of [route(0), { ...staticRow, "bgp.peer-cache-id": primary }, { ...staticRow, "belongs-to": "BGP IP routes from 192.0.2.1" }]) {
|
||||||
|
const { client } = fixture([ambiguous])
|
||||||
|
const wrongZero = { ...client, post: async <T>() => ({ ret: "0" }) as T }
|
||||||
|
await assert.rejects(readBgpRib(wrongZero, { ...selection, mode: "count" }))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test("matching peer paths include filtered and inactive alternatives with distinct IDs", async () => {
|
||||||
|
const filtered = route(1, { "dst-address": "198.18.0.0/32", contribution: "filtered", filtered: "true", active: "false", "bgp.peer-cache-id": standby })
|
||||||
|
const candidate = route(2, { afi: "ip4", contribution: "candidate", active: "false" })
|
||||||
|
const { client } = fixture([route(0), filtered, candidate, route(3, { afi: "ip6", "dst-address": "2001:db8::/32" })])
|
||||||
|
const result = await readBgpRib(client, selection)
|
||||||
|
assert.equal(result.total, 3)
|
||||||
|
assert(result.items)
|
||||||
|
const samePrefix = result.items.filter(item => item.prefix === "198.18.0.0/32")
|
||||||
|
assert.equal(samePrefix.length, 2)
|
||||||
|
assert.equal(new Set(samePrefix.map(item => item.id)).size, 2)
|
||||||
|
assert.equal(samePrefix.find(item => item.peerCacheId === standby)?.filtered, true)
|
||||||
|
assert.equal(result.items.find(item => item.id === candidate[".id"])?.active, false)
|
||||||
|
const otherPeer = await readBgpRib(client, { ...selection, peerCacheId: standby })
|
||||||
|
assert.equal(otherPeer.total, 1)
|
||||||
|
assert.equal(otherPeer.items?.[0]?.id, filtered[".id"])
|
||||||
|
})
|
||||||
|
|
||||||
|
test("RouterOS static rows without afi coexist with BGP paths identified by session name", async () => {
|
||||||
|
const nativeStatic = {
|
||||||
|
".id": "*800002F2", "dst-address": "5.180.136.242/32", "routing-table": table,
|
||||||
|
contribution: "(unknown)", static: "true",
|
||||||
|
}
|
||||||
|
const sessionName = "ibgp-jh-test-anycast-1"
|
||||||
|
const received = route(0, { "bgp.session": sessionName })
|
||||||
|
delete received["bgp.peer-cache-id"]
|
||||||
|
const { client, reads } = fixture([nativeStatic, received])
|
||||||
|
const mixed = await readBgpRib(client, selection)
|
||||||
|
assert.equal(mixed.total, 1)
|
||||||
|
assert.deepEqual(mixed.items.map(item => [item.id, item.prefix, item.peerCacheId, item.session]), [
|
||||||
|
[received[".id"], received["dst-address"], null, sessionName],
|
||||||
|
])
|
||||||
|
const bySession = await readBgpRib(client, { ...selection, sessionName })
|
||||||
|
assert.equal(bySession.sessionName, sessionName)
|
||||||
|
assert.equal(bySession.total, 1)
|
||||||
|
assert.equal(bySession.items[0].id, received[".id"])
|
||||||
|
assert.equal((await readBgpRib(client, { ...selection, mode: "count", sessionName: "ibgp-other-1" })).total, 0)
|
||||||
|
assert.deepEqual(reads.sessionFilters, new Set([sessionName, "ibgp-other-1"]))
|
||||||
|
assert(bySession.fingerprint)
|
||||||
|
await assert.rejects(readBgpRib(client, { ...selection, expectedFingerprint: bySession.fingerprint }))
|
||||||
|
await assert.rejects(readBgpRib(client, { ...selection, sessionName, peerCacheId: primary }))
|
||||||
|
await assert.rejects(readBgpRib(fixture([received, route(1)]).client, { ...selection, mode: "count", sessionName: "ibgp-other-1" }))
|
||||||
|
for (const invalid of [" ", sessionName + "\r"]) {
|
||||||
|
const malformed = fixture([{ ...received, "bgp.session": invalid }]).client
|
||||||
|
await assert.rejects(readBgpRib(malformed, { ...selection, mode: "count", sessionName }))
|
||||||
|
}
|
||||||
|
const onlyStatic = fixture([nativeStatic])
|
||||||
|
assert.equal((await readBgpRib(onlyStatic.client, { ...selection, mode: "count" })).total, 0)
|
||||||
|
assert.equal(onlyStatic.reads.routePages, 1)
|
||||||
|
|
||||||
|
const noOrigin: Record<string, string> = { ...nativeStatic }
|
||||||
|
delete noOrigin.static
|
||||||
|
for (const ambiguous of [noOrigin, { ...nativeStatic, "bgp.session": "ibgp-to-jh-1" }, { ...noOrigin, bgp: "true" }]) {
|
||||||
|
await assert.rejects(readBgpRib(fixture([ambiguous]).client, { ...selection, mode: "count" }))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test("missing table and missing peer attribution cannot prove a scoped zero", async () => {
|
||||||
|
const { client } = fixture([])
|
||||||
|
const missingTable = { ...client, get: async <T>() => [] as T }
|
||||||
|
await assert.rejects(readBgpRib(missingTable, { ...selection, mode: "count" }), /table/i)
|
||||||
|
const unknownPeer = route(0)
|
||||||
|
delete unknownPeer["bgp.peer-cache-id"]
|
||||||
|
const result = await readBgpRib(fixture([unknownPeer]).client, selection)
|
||||||
|
assert.equal(result.items?.[0].peerCacheId, null)
|
||||||
|
await assert.rejects(readBgpRib(fixture([unknownPeer]).client, { ...selection, mode: "count", peerCacheId: standby }), /peer/i)
|
||||||
|
})
|
||||||
|
|
||||||
|
test("pages beyond 13,000 preserve snapshot identity and reject a changed next page", async () => {
|
||||||
|
const rows = Array.from({ length: 13_705 }, (_, i) => route(i))
|
||||||
|
const { client } = fixture(rows)
|
||||||
|
const first = await readBgpRib(client, selection)
|
||||||
|
assert.equal(first.total, rows.length)
|
||||||
|
assert.equal(first.items?.length, selection.limit)
|
||||||
|
assert.equal(first.nextOffset, selection.limit)
|
||||||
|
assert(first.fingerprint)
|
||||||
|
rows.reverse()
|
||||||
|
const tailSelection = { ...selection, offset: 13_700, expectedFingerprint: first.fingerprint }
|
||||||
|
const tail = await readBgpRib(client, tailSelection)
|
||||||
|
assert.equal(tail.items?.length, 5)
|
||||||
|
assert.equal(tail.nextOffset, null)
|
||||||
|
assert.equal(tail.fingerprint, first.fingerprint)
|
||||||
|
rows[0] = { ...rows[0], gateway: "10.255.255.101" }
|
||||||
|
await assert.rejects(readBgpRib(client, tailSelection))
|
||||||
|
})
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
import { createHash } from "node:crypto"
|
||||||
|
import { isIP } from "node:net"
|
||||||
|
import { z } from "zod"
|
||||||
|
import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js"
|
||||||
|
import type { MikrotikClient } from "./mikrotik.js"
|
||||||
|
|
||||||
|
const rosId = z.string().regex(/^\*[0-9a-z]+$/i).max(64)
|
||||||
|
const exactName = z.string().min(1).refine(name => name.trim() === name && !/[\u0000-\u001f\u007f]/.test(name))
|
||||||
|
const sessionIdentity = exactName.max(512)
|
||||||
|
export const bgpRibSelection = z.object({
|
||||||
|
table: exactName.max(100),
|
||||||
|
peerCacheId: rosId.optional(),
|
||||||
|
sessionName: sessionIdentity.optional(),
|
||||||
|
mode: z.enum(["count", "page"]).default("count"),
|
||||||
|
offset: z.number().int().min(0).max(100_000).default(0),
|
||||||
|
limit: z.number().int().min(1).max(500).default(100),
|
||||||
|
expectedFingerprint: z.string().regex(/^[a-f0-9]{64}$/).optional(),
|
||||||
|
}).strict().refine(input => !(input.peerCacheId && input.sessionName), { message: "Choose only one BGP peer selector" })
|
||||||
|
|
||||||
|
const nativeRow = z.record(z.string(), z.unknown())
|
||||||
|
const otherProtocols = ["static", "connect", "ospf", "dhcp", "rip", "isis", "modem", "slaac", "vpn", "fantasy"]
|
||||||
|
const properties = [".id", "afi", "dst-address", "routing-table", "bgp", "bgp.peer-cache-id", "bgp.session", "belongs-to", "contribution", "active", "filtered", "gateway", "immediate-gw", ...otherProtocols].join(",")
|
||||||
|
const otherFamilies = new Set(["ip6", "ipv6", "link", "vpnv4", "vpnv6", "l2vpn", "l2vpn-cisco", "l2vpn-link", "evpn", "mip4", "mip6"])
|
||||||
|
type Selection = z.infer<typeof bgpRibSelection>
|
||||||
|
const text = z.string().max(512)
|
||||||
|
export class BgpRibChanged extends Error {}
|
||||||
|
const contributions = new Set(["active", "filtered", "candidate", "best-candidate", "unreachable"])
|
||||||
|
|
||||||
|
function optionalFlag(value: unknown) {
|
||||||
|
if (value === undefined) return null
|
||||||
|
if (value === true || value === "true" || value === "yes") return true
|
||||||
|
if (value === false || value === "false" || value === "no") return false
|
||||||
|
throw new Error("Unrecognized RouterOS flag")
|
||||||
|
}
|
||||||
|
|
||||||
|
function ipv4Row(row: Record<string, unknown>, table: string) {
|
||||||
|
if (row["routing-table"] !== table) throw new Error("Unexpected native route table")
|
||||||
|
if (otherFamilies.has(String(row.afi))) return null
|
||||||
|
const bgp = optionalFlag(row.bgp)
|
||||||
|
const other = otherProtocols.some(key => optionalFlag(row[key]) === true)
|
||||||
|
// Disabled static routes on RouterOS can omit afi. Their explicit origin still has to agree with the BGP evidence below.
|
||||||
|
const missingNonBgpAfi = row.afi === undefined && other && bgp !== true
|
||||||
|
if (row.afi !== "ip" && row.afi !== "ip4" && !missingNonBgpAfi) throw new Error("Unrecognized RouterOS address family")
|
||||||
|
if (bgp !== true) {
|
||||||
|
// Missing origin flags occur on some RouterOS REST projections. Do not lose filtered paths or certify a false zero.
|
||||||
|
if (row["bgp.peer-cache-id"] || row["bgp.session"] || /\bbgp\b/i.test(String(row["belongs-to"] ?? "")) || bgp === null && !other) throw new Error("Unconfirmed native route origin")
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
if (other) throw new Error("Conflicting native route origins")
|
||||||
|
const dst = text.parse(row["dst-address"])
|
||||||
|
const prefix = isIP(dst) === 4 ? dst + "/32" : dst
|
||||||
|
if (isIP(prefix.split("/")[0]) !== 4 || canonicalBgpPolicyPrefix(prefix) !== prefix) throw new Error("Invalid IPv4 destination")
|
||||||
|
const id = rosId.parse(row[".id"])
|
||||||
|
const peerCacheId = row["bgp.peer-cache-id"] === undefined ? null : rosId.parse(row["bgp.peer-cache-id"])
|
||||||
|
const contribution = text.nullable().parse(row.contribution ?? null)
|
||||||
|
const activeFlag = optionalFlag(row.active), filteredFlag = optionalFlag(row.filtered)
|
||||||
|
const known = contribution !== null && contributions.has(contribution)
|
||||||
|
if (known && (activeFlag !== null && activeFlag !== (contribution === "active") ||
|
||||||
|
filteredFlag !== null && filteredFlag !== (contribution === "filtered"))) throw new Error("Conflicting native route flags")
|
||||||
|
return {
|
||||||
|
id, prefix, table, peerCacheId, contribution,
|
||||||
|
active: activeFlag ?? (known ? contribution === "active" : null),
|
||||||
|
filtered: filteredFlag ?? (known ? contribution === "filtered" : null),
|
||||||
|
session: sessionIdentity.nullable().parse(row["bgp.session"] ?? null),
|
||||||
|
gateway: text.nullable().parse(row.gateway ?? null), immediateGateway: text.nullable().parse(row["immediate-gw"] ?? null),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Counts run on RouterOS. Page offsets use deterministic route IDs and a digest over the full selection. */
|
||||||
|
export async function readBgpRib(client: Pick<MikrotikClient, "get" | "post">, input: Selection,
|
||||||
|
beforeRead: () => Promise<unknown> = async () => {}, signal?: AbortSignal) {
|
||||||
|
const { table, peerCacheId, sessionName, mode, limit, offset, expectedFingerprint } = bgpRibSelection.parse(input)
|
||||||
|
if (offset > 0 && !expectedFingerprint || mode === "count" && (offset || expectedFingerprint)) throw new Error("Invalid RIB page cursor")
|
||||||
|
const query = ["routing-table=" + table, "bgp=true", "afi=ip", "afi=ip4", "#|"]
|
||||||
|
const peer = peerCacheId ? { field: "peerCacheId", native: "bgp.peer-cache-id", value: peerCacheId } as const
|
||||||
|
: sessionName ? { field: "session", native: "bgp.session", value: sessionName } as const : null
|
||||||
|
const tablePath = "/routing/table?.proplist=.id,name,disabled,invalid&name=" + encodeURIComponent(table)
|
||||||
|
const tableIdentity = async () => {
|
||||||
|
const raw = await client.get<unknown>(tablePath, 10_000, signal, 16_384, beforeRead)
|
||||||
|
if (!Array.isArray(raw) || raw.length !== 1) throw new Error("Missing or ambiguous routing table")
|
||||||
|
const row = nativeRow.parse(raw[0])
|
||||||
|
if (row.name !== table || optionalFlag(row.disabled) || optionalFlag(row.invalid)) throw new Error("Routing table unavailable")
|
||||||
|
return rosId.parse(row[".id"])
|
||||||
|
}
|
||||||
|
const nativeCount = async (scoped = false) => {
|
||||||
|
const filter = scoped && peer ? [...query, peer.native + "=" + peer.value] : query
|
||||||
|
const raw = await client.post<unknown>("/routing/route/print", { "count-only": "", ".query": filter }, 15_000, signal, beforeRead)
|
||||||
|
const { ret } = z.object({ ret: z.string().regex(/^(?:0|[1-9]\d{0,14})$/) }).strict().parse(raw)
|
||||||
|
return Number(ret)
|
||||||
|
}
|
||||||
|
const identity = await tableIdentity()
|
||||||
|
const allCount = await nativeCount()
|
||||||
|
type Item = NonNullable<ReturnType<typeof ipv4Row>>
|
||||||
|
let items: Item[] = [], fingerprint: string | null = null, total = allCount, nextOffset: number | null = null
|
||||||
|
if (mode === "page" || peer || allCount === 0) {
|
||||||
|
if (allCount > 100_000) throw new Error("RIB row limit exceeded")
|
||||||
|
const path = "/routing/route?.proplist=" + properties + "&routing-table=" + encodeURIComponent(table)
|
||||||
|
const raw = await client.get<unknown>(path, 30_000, signal, 8 * 1024 * 1024, beforeRead)
|
||||||
|
if (!Array.isArray(raw) || raw.length > 100_000) throw new Error("Invalid or oversized RIB view")
|
||||||
|
const ids = new Set<string>(), selected: Item[] = []
|
||||||
|
for (const rawRow of raw) {
|
||||||
|
const observed = ipv4Row(nativeRow.parse(rawRow), table)
|
||||||
|
if (!observed) continue
|
||||||
|
if (ids.has(observed.id)) throw new Error("Duplicate native RIB identity")
|
||||||
|
ids.add(observed.id)
|
||||||
|
if (peer && !observed[peer.field]) throw new Error("Native peer identity unavailable")
|
||||||
|
if (!peer || observed[peer.field] === peer.value) selected.push(observed)
|
||||||
|
}
|
||||||
|
if (allCount !== ids.size || selected.length !== await nativeCount(true)) throw new BgpRibChanged("Native RIB count changed or view incomplete")
|
||||||
|
total = selected.length
|
||||||
|
if (mode === "page") {
|
||||||
|
selected.sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0)
|
||||||
|
const peerScope = sessionName ? { sessionName } : peerCacheId ?? null
|
||||||
|
fingerprint = createHash("sha256").update(JSON.stringify([table, identity, peerScope, selected])).digest("hex")
|
||||||
|
if (expectedFingerprint && fingerprint !== expectedFingerprint || offset > total) throw new BgpRibChanged("RIB snapshot changed; restart at offset 0")
|
||||||
|
items = selected.slice(offset, offset + limit)
|
||||||
|
nextOffset = offset + items.length < total ? offset + items.length : null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (identity !== await tableIdentity()) throw new BgpRibChanged("Routing table changed during observation")
|
||||||
|
return { family: "ipv4", table, peerCacheId: peerCacheId ?? null, sessionName: sessionName ?? null, mode, total, items, nextOffset, fingerprint, source: "/routing/route", atomicSnapshot: false }
|
||||||
|
}
|
||||||
@@ -907,7 +907,7 @@ export function greInterfaceBody(t: GreSnapshotTunnel): Record<string, string> {
|
|||||||
"allow-fast-path": t.allowFastPath ? "yes" : "no",
|
"allow-fast-path": t.allowFastPath ? "yes" : "no",
|
||||||
comment: writeGreComment(t.comment, peer),
|
comment: writeGreComment(t.comment, peer),
|
||||||
disabled: rosYesNo(t.disabled),
|
disabled: rosYesNo(t.disabled),
|
||||||
"ipsec-secret": isHiddenSecret(t.ipsecSecret) ? undefined : t.ipsecSecret,
|
"ipsec-secret": !t.ipsecSecret || isHiddenSecret(t.ipsecSecret) ? undefined : t.ipsecSecret,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
export const greIpsecPaths = {
|
||||||
|
filter: "/ip/firewall/filter",
|
||||||
|
profile: "/ip/ipsec/profile",
|
||||||
|
proposal: "/ip/ipsec/proposal",
|
||||||
|
peer: "/ip/ipsec/peer",
|
||||||
|
identity: "/ip/ipsec/identity",
|
||||||
|
policy: "/ip/ipsec/policy",
|
||||||
|
} as const
|
||||||
|
|
||||||
|
export function greIpsecPlaintextDrops(local: string, remote: string) {
|
||||||
|
return [
|
||||||
|
{ chain: "input", protocol: "gre", "src-address": `${remote}/32`, "dst-address": `${local}/32`, "ipsec-policy": "in,none", action: "drop" },
|
||||||
|
{ chain: "output", protocol: "gre", "src-address": `${local}/32`, "dst-address": `${remote}/32`, "ipsec-policy": "out,none", action: "drop" },
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
export function greIke2TransportFields(name: string, local: string, remote: string, passive: boolean, secret: string, disabled: boolean) {
|
||||||
|
return {
|
||||||
|
profile: { name, "enc-algorithm": "aes-256", "hash-algorithm": "sha256", "dh-group": "modp2048" },
|
||||||
|
proposal: { name, "enc-algorithms": "aes-256-cbc", "auth-algorithms": "sha256", "pfs-group": "modp2048" },
|
||||||
|
peer: { name, address: `${remote}/32`, "local-address": local, profile: name, "exchange-mode": "ike2", passive: String(passive) },
|
||||||
|
identity: { peer: name, "auth-method": "pre-shared-key", secret, disabled: String(disabled) },
|
||||||
|
policy: { peer: name, "src-address": `${local}/32`, "dst-address": `${remote}/32`, protocol: "gre", action: "encrypt", level: "require", tunnel: "false", proposal: name },
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -27,6 +27,7 @@ function apply(state:GreMutationState,op:RosWriteOp) {
|
|||||||
next[key].push(row)
|
next[key].push(row)
|
||||||
if (key==="gre") next.dependencies["/interface"].push({".id":"*C",name:row.name,type:"gre"})
|
if (key==="gre") next.dependencies["/interface"].push({".id":"*C",name:row.name,type:"gre"})
|
||||||
} else if (op.op === "patch") Object.assign(next[key].find(row=>row[".id"]===id)!,body)
|
} else if (op.op === "patch") Object.assign(next[key].find(row=>row[".id"]===id)!,body)
|
||||||
|
else if (op.op === "post" && op.path === "/interface/gre/unset") next.gre.find(row=>row[".id"]===body[".id"])!["ipsec-secret"] = ""
|
||||||
else if (op.op === "delete") {
|
else if (op.op === "delete") {
|
||||||
next[key]=next[key].filter(row=>row[".id"]!==id)
|
next[key]=next[key].filter(row=>row[".id"]!==id)
|
||||||
if (key==="gre") next.dependencies["/interface"]=next.dependencies["/interface"].filter(row=>row[".id"]!==id)
|
if (key==="gre") next.dependencies["/interface"]=next.dependencies["/interface"].filter(row=>row[".id"]!==id)
|
||||||
@@ -40,6 +41,10 @@ let state = empty(), commands = 0
|
|||||||
const ops = planGreMutation(server,create,state)
|
const ops = planGreMutation(server,create,state)
|
||||||
assert.equal(ops.length,3); assert.equal(ops[0].op,"put"); assert.equal("body" in ops[0]&&ops[0].body.disabled,"yes"); assert.equal(ops[2].path,"/interface/gre/@created")
|
assert.equal(ops.length,3); assert.equal(ops[0].op,"put"); assert.equal("body" in ops[0]&&ops[0].body.disabled,"yes"); assert.equal(ops[2].path,"/interface/gre/@created")
|
||||||
assert.equal("body" in ops[0] && ops[0].body.mtu, "1476")
|
assert.equal("body" in ops[0] && ops[0].body.mtu, "1476")
|
||||||
|
assert.ok("body" in ops[0] && !("ipsec-secret" in ops[0].body))
|
||||||
|
const createWithClear = greMutationSchema.parse({operation:"create",fields:{name:"clear-gre",remoteAddress:"192.0.2.2",ipsecSecret:""}})
|
||||||
|
const createWithClearOp = planGreMutation(server,createWithClear,state)[0]
|
||||||
|
assert.ok("body" in createWithClearOp && !("ipsec-secret" in createWithClearOp.body))
|
||||||
const autoCreate = greMutationSchema.parse({operation:"create",fields:{name:"own-gre",remoteAddress:"192.0.2.2",mtu:"auto"}})
|
const autoCreate = greMutationSchema.parse({operation:"create",fields:{name:"own-gre",remoteAddress:"192.0.2.2",mtu:"auto"}})
|
||||||
const autoPut = planGreMutation(server,autoCreate,state)[0]
|
const autoPut = planGreMutation(server,autoCreate,state)[0]
|
||||||
assert.equal("body" in autoPut && autoPut.body.mtu, "auto")
|
assert.equal("body" in autoPut && autoPut.body.mtu, "auto")
|
||||||
@@ -62,7 +67,19 @@ assert.equal(verifyGreMutationOp(autoState, autoAfter, autoPatch), false)
|
|||||||
const commentPlan = planGreMutation(server,greMutationSchema.parse({operation:"update",rosId:"*G",fields:{mtu:1400}}),preserve)
|
const commentPlan = planGreMutation(server,greMutationSchema.parse({operation:"update",rosId:"*G",fields:{mtu:1400}}),preserve)
|
||||||
assert.equal(commentPlan[0].op,"patch"); assert.equal("body" in commentPlan[0]&&commentPlan[0].body.keepalive,"1m,3"); assert.equal("body" in commentPlan[0]&&commentPlan[0].body.comment,native.comment); assert.ok(!("body" in commentPlan[0]&&"ipsec-secret" in commentPlan[0].body))
|
assert.equal(commentPlan[0].op,"patch"); assert.equal("body" in commentPlan[0]&&commentPlan[0].body.keepalive,"1m,3"); assert.equal("body" in commentPlan[0]&&commentPlan[0].body.comment,native.comment); assert.ok(!("body" in commentPlan[0]&&"ipsec-secret" in commentPlan[0].body))
|
||||||
const clear = planGreMutation(server,greMutationSchema.parse({operation:"update",rosId:"*G",fields:{comment:"",remoteInnerIp:"",localAddress:"",ipsecSecret:""}}),preserve)
|
const clear = planGreMutation(server,greMutationSchema.parse({operation:"update",rosId:"*G",fields:{comment:"",remoteInnerIp:"",localAddress:"",ipsecSecret:""}}),preserve)
|
||||||
assert.equal(clear[0].op,"patch"); assert.equal("body" in clear[0]&&clear[0].body.comment,""); assert.equal("body" in clear[0]&&clear[0].body["ipsec-secret"],"")
|
assert.deepEqual(clear[0],{op:"post",path:"/interface/gre/unset",body:{".id":"*G","value-name":"ipsec-secret"}})
|
||||||
|
assert.equal(clear[1].op,"patch"); assert.equal("body" in clear[1]&&clear[1].body.comment,""); assert.ok("body" in clear[1]&&!("ipsec-secret" in clear[1].body))
|
||||||
|
const runningWithKey = structuredClone(preserve)
|
||||||
|
Object.assign(runningWithKey.gre[0], {disabled:"false","ipsec-secret":"fixture-key","allow-fast-path":"false"})
|
||||||
|
const clearRunning = greMutationSchema.parse({operation:"update",rosId:"*G",fields:{ipsecSecret:"",allowFastPath:true}})
|
||||||
|
const clearRunningOps = planGreMutation(server,clearRunning,runningWithKey)
|
||||||
|
assert.deepEqual(clearRunningOps.map(op=>op.op),["patch","post","patch","patch"])
|
||||||
|
assert.equal(verifyGreMutationOp(runningWithKey,runningWithKey,clearRunningOps[1]),false)
|
||||||
|
let afterClear = runningWithKey
|
||||||
|
const cleared = await executeGreMutationOps(clearRunning,runningWithKey,clearRunningOps,{read:async()=>afterClear,command:async op=>{afterClear=apply(afterClear,op)}})
|
||||||
|
assert.equal(cleared.verified,true)
|
||||||
|
assert.equal(afterClear.gre[0]["ipsec-secret"],"")
|
||||||
|
assert.equal(afterClear.gre[0].disabled,"false")
|
||||||
const collision = empty(); collision.dependencies["/interface"]=[{".id":"*E",name:"own-gre",type:"ether"}]
|
const collision = empty(); collision.dependencies["/interface"]=[{".id":"*E",name:"own-gre",type:"ether"}]
|
||||||
assert.throws(()=>planGreMutation(server,create,collision),/используется/)
|
assert.throws(()=>planGreMutation(server,create,collision),/используется/)
|
||||||
assert.throws(()=>planGreMutation(server,greMutationSchema.parse({operation:"delete",rosId:"*G",name:"different"}),preserve),/разные/)
|
assert.throws(()=>planGreMutation(server,greMutationSchema.parse({operation:"delete",rosId:"*G",name:"different"}),preserve),/разные/)
|
||||||
|
|||||||
@@ -12,6 +12,11 @@ import { greMutationSchema, greTunnelFromBody, type GreMutation } from "./gre-mu
|
|||||||
import { assertGreDeleteDependencies, greMutationProblem, greMutationProof, greNativeValue, greStableRows, greTarget, readGreMutationState, type GreMutationState } from "./gre-mutation-state.js"
|
import { assertGreDeleteDependencies, greMutationProblem, greMutationProof, greNativeValue, greStableRows, greTarget, readGreMutationState, type GreMutationState } from "./gre-mutation-state.js"
|
||||||
|
|
||||||
const same = (a: unknown,b: unknown) => fingerprint(a) === fingerprint(b)
|
const same = (a: unknown,b: unknown) => fingerprint(a) === fingerprint(b)
|
||||||
|
|
||||||
|
export function greSecretUnsetOp(id: string): RosWriteOp {
|
||||||
|
return { op: "post", path: "/interface/gre/unset", body: { ".id": id, "value-name": "ipsec-secret" } }
|
||||||
|
}
|
||||||
|
|
||||||
export async function recordGreMutationRevision(server:ServerRow){
|
export async function recordGreMutationRevision(server:ServerRow){
|
||||||
try{
|
try{
|
||||||
const revisionRecorded=(await captureAndAppendRevision({serverId:server.id,section:"gre",source:"apply",capture:async()=>{
|
const revisionRecorded=(await captureAndAppendRevision({serverId:server.id,section:"gre",source:"apply",capture:async()=>{
|
||||||
@@ -61,17 +66,29 @@ export function planGreMutation(server: ServerRow, input: GreMutation, before: G
|
|||||||
const ops = planGreRestore({tunnels:[desired]},selected)
|
const ops = planGreRestore({tunnels:[desired]},selected)
|
||||||
if (ops[0]?.op !== "patch") throw greMutationProblem("Не подготовлено изменение GRE")
|
if (ops[0]?.op !== "patch") throw greMutationProblem("Не подготовлено изменение GRE")
|
||||||
const body = ops[0].body
|
const body = ops[0].body
|
||||||
if (fields.ipsecSecret === undefined) delete body["ipsec-secret"]
|
const clearSecret = fields.ipsecSecret === ""
|
||||||
|
if (!fields.ipsecSecret) delete body["ipsec-secret"]
|
||||||
else body["ipsec-secret"] = fields.ipsecSecret
|
else body["ipsec-secret"] = fields.ipsecSecret
|
||||||
if (fields.localAddress !== undefined) body["local-address"] = fields.localAddress || "0.0.0.0"
|
if (fields.localAddress !== undefined) body["local-address"] = fields.localAddress || "0.0.0.0"
|
||||||
body.comment = fields.comment !== undefined || fields.remoteInnerIp !== undefined ? desired.comment : target.comment ?? ""
|
body.comment = fields.comment !== undefined || fields.remoteInnerIp !== undefined ? desired.comment : target.comment ?? ""
|
||||||
if (ops.length === 1 && Object.entries(body).every(([key,value])=>same(greNativeValue(key,target[key]),greNativeValue(key,value)))) throw greMutationProblem("GRE уже имеет запрошенную конфигурацию")
|
if (!clearSecret && ops.length === 1 && Object.entries(body).every(([key,value])=>same(greNativeValue(key,target[key]),greNativeValue(key,value)))) throw greMutationProblem("GRE уже имеет запрошенную конфигурацию")
|
||||||
body.disabled = "yes"
|
body.disabled = "yes"
|
||||||
|
if (clearSecret) {
|
||||||
|
// Clear even a configured empty value. RouterOS can create dynamic IKEv1 objects for it.
|
||||||
|
const path = ops[0].path
|
||||||
|
ops.unshift(greSecretUnsetOp(live.rosId))
|
||||||
|
if (!live.disabled) ops.unshift({ op: "patch", path, body: { disabled: "yes" } })
|
||||||
|
}
|
||||||
if (!desired.disabled) ops.push({op:"patch",path:"/interface/gre/"+live.rosId,body:{disabled:"no"}})
|
if (!desired.disabled) ops.push({op:"patch",path:"/interface/gre/"+live.rosId,body:{disabled:"no"}})
|
||||||
return ops
|
return ops
|
||||||
}
|
}
|
||||||
|
|
||||||
export function verifyGreMutationOp(before: GreMutationState, after: GreMutationState, op: RosWriteOp) {
|
export function verifyGreMutationOp(before: GreMutationState, after: GreMutationState, op: RosWriteOp) {
|
||||||
|
if (op.op === "post" && op.path === "/interface/gre/unset" && op.body["value-name"] === "ipsec-secret") {
|
||||||
|
const id = op.body[".id"]
|
||||||
|
if (after.gre.find(row => row[".id"] === id)?.["ipsec-secret"] !== "") return false
|
||||||
|
return verifyGreMutationOp(before, after, { op: "patch", path: "/interface/gre/" + id, body: { "ipsec-secret": "" } })
|
||||||
|
}
|
||||||
const paths = {"/interface/gre":"gre","/ip/address":"ipv4","/ipv6/address":"ipv6"} as const
|
const paths = {"/interface/gre":"gre","/ip/address":"ipv4","/ipv6/address":"ipv6"} as const
|
||||||
const path = Object.keys(paths).find(path=>op.path===path||op.path.startsWith(path+"/")) as keyof typeof paths|undefined
|
const path = Object.keys(paths).find(path=>op.path===path||op.path.startsWith(path+"/")) as keyof typeof paths|undefined
|
||||||
if (!path || !["put","patch","delete"].includes(op.op)) return false
|
if (!path || !["put","patch","delete"].includes(op.op)) return false
|
||||||
@@ -79,8 +96,11 @@ export function verifyGreMutationOp(before: GreMutationState, after: GreMutation
|
|||||||
const id = op.path === path ? undefined : decodeURIComponent(op.path.slice(path.length+1))
|
const id = op.path === path ? undefined : decodeURIComponent(op.path.slice(path.length+1))
|
||||||
if (op.op === "put") {
|
if (op.op === "put") {
|
||||||
const added = next[key].filter(row=>!prior[key].some(previous=>previous[".id"]===row[".id"]))
|
const added = next[key].filter(row=>!prior[key].some(previous=>previous[".id"]===row[".id"]))
|
||||||
if (added.length !== 1 || !same(next[key].filter(row=>row!==added[0]),prior[key]) || !Object.entries(op.body).every(([field,value])=>same(greNativeValue(field,after[key].find(row=>row[".id"]===added[0][".id"])?.[field]),greNativeValue(field,value)))) return false
|
if (added.length !== 1 || !same(next[key].filter(row=>row!==added[0]),prior[key])) return false
|
||||||
if (key!=="gre"&&observedBoolean(after[key].find(row=>row[".id"]===added[0][".id"])?.dynamic)!==false) return false
|
const created = after[key].find(row => row[".id"] === added[0][".id"])
|
||||||
|
const expected = key === "gre" ? { "ipsec-secret": "", ...op.body } : op.body
|
||||||
|
if (!created || !Object.entries(expected).every(([field,value])=>same(greNativeValue(field,created[field]),greNativeValue(field,value)))) return false
|
||||||
|
if (key!=="gre"&&observedBoolean(created.dynamic)!==false) return false
|
||||||
// An address on our deliberately disabled GRE can legitimately be invalid.
|
// An address on our deliberately disabled GRE can legitimately be invalid.
|
||||||
// This proof confirms configuration, not link/DAD/forwarding readiness.
|
// This proof confirms configuration, not link/DAD/forwarding readiness.
|
||||||
} else {
|
} else {
|
||||||
@@ -124,6 +144,7 @@ export async function mutateGreTunnel(server: ServerRow, raw: GreMutation, expec
|
|||||||
const client = MikrotikClient.fromServer(fresh)
|
const client = MikrotikClient.fromServer(fresh)
|
||||||
const receipt = await executeGreMutationOps(input,before,ops,{read:()=>readGreMutationState(fresh,input),...(input.operation==="delete"?{validate:(state:GreMutationState)=>{planGreMutation(fresh,input,state)}}:{}),command:op=>{
|
const receipt = await executeGreMutationOps(input,before,ops,{read:()=>readGreMutationState(fresh,input),...(input.operation==="delete"?{validate:(state:GreMutationState)=>{planGreMutation(fresh,input,state)}}:{}),command:op=>{
|
||||||
if (op.op === "put") return client.put(op.path,op.body)
|
if (op.op === "put") return client.put(op.path,op.body)
|
||||||
|
if (op.op === "post") return client.post(op.path,op.body)
|
||||||
const slash = op.path.lastIndexOf("/"), path = op.path.slice(0,slash+1)+encodeURIComponent(op.path.slice(slash+1))
|
const slash = op.path.lastIndexOf("/"), path = op.path.slice(0,slash+1)+encodeURIComponent(op.path.slice(slash+1))
|
||||||
if (op.op === "delete") return client.delete(path)
|
if (op.op === "delete") return client.delete(path)
|
||||||
if (op.op === "patch") return client.patch(path,op.body)
|
if (op.op === "patch") return client.patch(path,op.body)
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import assert from "node:assert/strict"
|
import assert from "node:assert/strict"
|
||||||
import {validateGreRestoreSnapshot,materializeGreRestore,planGreRevisionRestore,executeGreRevisionSteps,readGreRestoreState,greRestoreWireOp} from "./gre-revision-restore.js"
|
import {validateGreRestoreSnapshot,materializeGreRestore,planGreRevisionRestore,executeGreRevisionSteps,readGreRestoreState} from "./gre-revision-restore.js"
|
||||||
import {canonicalGreSnapshot,type GreSnapshot,type RosWriteOp} from "./entity-snapshots.js"
|
import {canonicalGreSnapshot,type GreSnapshot,type RosWriteOp} from "./entity-snapshots.js"
|
||||||
import {greDependencyPaths,type GreMutationState} from "./gre-mutation-state.js"
|
import {greDependencyPaths,type GreMutationState} from "./gre-mutation-state.js"
|
||||||
import {mapGreLive} from "./gre-live.js"
|
import {mapGreLive} from "./gre-live.js"
|
||||||
@@ -12,13 +12,6 @@ assert.equal(expiredAccess,0)
|
|||||||
const empty=():GreMutationState=>({serverConfiguration:"source",restoreProtectionProof:"protections",gre:[],ipv4:[],ipv6:[],dependencies:Object.fromEntries(greDependencyPaths.map(p=>[p,[]])),bindings:[],filters:[]})
|
const empty=():GreMutationState=>({serverConfiguration:"source",restoreProtectionProof:"protections",gre:[],ipv4:[],ipv6:[],dependencies:Object.fromEntries(greDependencyPaths.map(p=>[p,[]])),bindings:[],filters:[]})
|
||||||
const native={".id":"*G",name:"old","local-address":"192.0.2.1","remote-address":"192.0.2.2",mtu:"1476",keepalive:"1m,3",dscp:"inherit",disabled:"false",dynamic:"false",running:"true","clamp-tcp-mss":"true","allow-fast-path":"false","ipsec-secret":" key ",comment:"old-comment","dont-fragment":"yes"}
|
const native={".id":"*G",name:"old","local-address":"192.0.2.1","remote-address":"192.0.2.2",mtu:"1476",keepalive:"1m,3",dscp:"inherit",disabled:"false",dynamic:"false",running:"true","clamp-tcp-mss":"true","allow-fast-path":"false","ipsec-secret":" key ",comment:"old-comment","dont-fragment":"yes"}
|
||||||
const wanted=(name:string)=>({name,localAddress:"",remoteAddress:"192.0.2.2",localInnerIp:"",remoteInnerIp:"",innerAddresses:[],comment:"",disabled:false,mtu:1400,keepalive:"0",dscp:"inherit",clampTcpMss:true,allowFastPath:false,ipsecSecret:""})
|
const wanted=(name:string)=>({name,localAddress:"",remoteAddress:"192.0.2.2",localInnerIp:"",remoteInnerIp:"",innerAddresses:[],comment:"",disabled:false,mtu:1400,keepalive:"0",dscp:"inherit",clampTcpMss:true,allowFastPath:false,ipsecSecret:""})
|
||||||
const defaultCreate:RosWriteOp={op:"put",path:"/interface/gre",body:{name:"gre","ipsec-secret":"","allow-fast-path":"yes"}}
|
|
||||||
const defaultWire=greRestoreWireOp(defaultCreate,empty())
|
|
||||||
assert.ok("body"in defaultWire&&!("ipsec-secret"in defaultWire.body));assert.equal(defaultCreate.body["ipsec-secret"],"")
|
|
||||||
const keyState=empty();keyState.gre=[{...native}]
|
|
||||||
const clearKey:RosWriteOp={op:"patch",path:"/interface/gre/*G",body:{"ipsec-secret":"","allow-fast-path":"no"}}
|
|
||||||
assert.equal(greRestoreWireOp(clearKey,keyState),clearKey,"A real key removal must not be silently omitted")
|
|
||||||
keyState.gre[0]["ipsec-secret"]="";assert.ok("body"in greRestoreWireOp(clearKey,keyState)&&!("ipsec-secret"in(greRestoreWireOp(clearKey,keyState)as{body:Record<string,string>}).body))
|
|
||||||
const snapshot=(...names:string[])=>canonicalGreSnapshot({tunnels:names.map(wanted)})
|
const snapshot=(...names:string[])=>canonicalGreSnapshot({tunnels:names.map(wanted)})
|
||||||
let sequence=0
|
let sequence=0
|
||||||
function apply(state:GreMutationState,op:RosWriteOp){
|
function apply(state:GreMutationState,op:RosWriteOp){
|
||||||
@@ -26,10 +19,11 @@ function apply(state:GreMutationState,op:RosWriteOp){
|
|||||||
const key=path==="/interface/gre"?"gre":path==="/ip/address"?"ipv4":"ipv6",id=op.path.slice(path.length+1)
|
const key=path==="/interface/gre"?"gre":path==="/ip/address"?"ipv4":"ipv6",id=op.path.slice(path.length+1)
|
||||||
const body="body"in op?Object.fromEntries(Object.entries(op.body).map(([k,v])=>[k,v==="yes"?"true":v==="no"?"false":v])):{}
|
const body="body"in op?Object.fromEntries(Object.entries(op.body).map(([k,v])=>[k,v==="yes"?"true":v==="no"?"false":v])):{}
|
||||||
if(op.op==="put"){
|
if(op.op==="put"){
|
||||||
const added={...(key==="gre"?native:{dynamic:"false",invalid:"false","no-dad":"false","eui-64":"false","from-pool":""}),...body,".id":"*N"+(++sequence)}
|
const added={...(key==="gre"?{...native,"ipsec-secret":""}:{dynamic:"false",invalid:"false","no-dad":"false","eui-64":"false","from-pool":""}),...body,".id":"*N"+(++sequence)}
|
||||||
next[key].push(added)
|
next[key].push(added)
|
||||||
if(key==="gre")next.dependencies["/interface"].push({".id":added[".id"],name:added.name,type:"gre"})
|
if(key==="gre")next.dependencies["/interface"].push({".id":added[".id"],name:added.name,type:"gre"})
|
||||||
}else if(op.op==="patch")Object.assign(next[key].find(r=>r[".id"]===id)!,body)
|
}else if(op.op==="patch")Object.assign(next[key].find(r=>r[".id"]===id)!,body)
|
||||||
|
else if(op.op==="post"&&op.path==="/interface/gre/unset")next.gre.find(r=>r[".id"]===body[".id"])!["ipsec-secret"]=""
|
||||||
else if(op.op==="delete"){
|
else if(op.op==="delete"){
|
||||||
next[key]=next[key].filter(r=>r[".id"]!==id)
|
next[key]=next[key].filter(r=>r[".id"]!==id)
|
||||||
if(key==="gre")next.dependencies["/interface"]=next.dependencies["/interface"].filter(r=>r[".id"]!==id)
|
if(key==="gre")next.dependencies["/interface"]=next.dependencies["/interface"].filter(r=>r[".id"]!==id)
|
||||||
@@ -74,6 +68,13 @@ assert.deepEqual(state.ipv6.find(r=>r.interface==="ether1"),original.ipv6[0]);as
|
|||||||
const firstAddress=commands.findIndex(op=>!op.path.startsWith("/interface/gre")),oldDisable=commands.findIndex(op=>op.path==="/interface/gre/*G"&&"body"in op&&op.body.disabled==="yes")
|
const firstAddress=commands.findIndex(op=>!op.path.startsWith("/interface/gre")),oldDisable=commands.findIndex(op=>op.path==="/interface/gre/*G"&&"body"in op&&op.body.disabled==="yes")
|
||||||
assert.ok(oldDisable>=0&&oldDisable<firstAddress);assert.ok(commands.slice(-2).every(op=>"body"in op&&op.body.disabled==="no"))
|
assert.ok(oldDisable>=0&&oldDisable<firstAddress);assert.ok(commands.slice(-2).every(op=>"body"in op&&op.body.disabled==="no"))
|
||||||
assert.deepEqual(planGreRevisionRestore(fixed,state),[])
|
assert.deepEqual(planGreRevisionRestore(fixed,state),[])
|
||||||
|
assert.ok(commands.every(op=>!("body" in op)||op.body["ipsec-secret"]!==""))
|
||||||
|
const clearRevision=structuredClone(fixed)
|
||||||
|
clearRevision.tunnels.find(row=>row.name==="old")!.ipsecSecret=""
|
||||||
|
commands=[]
|
||||||
|
assert.equal((await execute(clearRevision)).verified,true)
|
||||||
|
assert.deepEqual(commands.find(op=>op.op==="post"),{op:"post",path:"/interface/gre/unset",body:{".id":"*G","value-name":"ipsec-secret"}})
|
||||||
|
assert.ok(commands.every(op=>!("body" in op)||!("ipsec-secret" in op.body)))
|
||||||
const deletion=planGreRevisionRestore({tunnels:[]},original)
|
const deletion=planGreRevisionRestore({tunnels:[]},original)
|
||||||
assert.deepEqual(deletion[0],{kind:"native",op:{op:"patch",path:"/interface/gre/*G",body:{disabled:"yes"}}})
|
assert.deepEqual(deletion[0],{kind:"native",op:{op:"patch",path:"/interface/gre/*G",body:{disabled:"yes"}}})
|
||||||
assert.equal(deletion.at(-1)?.kind,"native");state=structuredClone(original);commands=[]
|
assert.equal(deletion.at(-1)?.kind,"native");state=structuredClone(original);commands=[]
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import { canonicalGreSnapshot,greAddressKey,greAddressPath,greInterfaceBody,isHi
|
|||||||
import { mapGreLive } from "./gre-live.js"
|
import { mapGreLive } from "./gre-live.js"
|
||||||
import { greMtuSchema } from "./gre-mutation-input.js"
|
import { greMtuSchema } from "./gre-mutation-input.js"
|
||||||
import { assertGreDeleteDependencies,greMutationProblem,greMutationProof,greNativeValue,readGreMutationState,type GreMutationState } from "./gre-mutation-state.js"
|
import { assertGreDeleteDependencies,greMutationProblem,greMutationProof,greNativeValue,readGreMutationState,type GreMutationState } from "./gre-mutation-state.js"
|
||||||
import { verifyGreMutationOp } from "./gre-mutation.js"
|
import { greSecretUnsetOp, verifyGreMutationOp } from "./gre-mutation.js"
|
||||||
import { observedBoolean } from "./ospf-observed-values.js"
|
import { observedBoolean } from "./ospf-observed-values.js"
|
||||||
import { MikrotikClient } from "./mikrotik.js"
|
import { MikrotikClient } from "./mikrotik.js"
|
||||||
import { withApplicationMutationLock,withConfigMutationLock } from "./config-mutation-lock.js"
|
import { withApplicationMutationLock,withConfigMutationLock } from "./config-mutation-lock.js"
|
||||||
@@ -69,17 +69,6 @@ export function materializeGreRestore(desired:GreSnapshot,before:GreMutationStat
|
|||||||
})})
|
})})
|
||||||
}
|
}
|
||||||
export type GreRestoreStep={kind:"native";op:RosWriteOp}|{kind:"enable";name:string}
|
export type GreRestoreStep={kind:"native";op:RosWriteOp}|{kind:"enable";name:string}
|
||||||
/** RouterOS treats presence of an empty ipsec-secret as an IPsec write and
|
|
||||||
* rejects it together with FastPath. Omit a redundant empty assignment on the
|
|
||||||
* wire only; per-command verification still uses the original expected body. */
|
|
||||||
export function greRestoreWireOp(op:RosWriteOp,before:GreMutationState):RosWriteOp{
|
|
||||||
if((op.op!=="put"&&op.op!=="patch")||op.body["ipsec-secret"]!=="")return op
|
|
||||||
const creating=op.op==="put"&&op.path==="/interface/gre"
|
|
||||||
const live=op.op==="patch"&&op.path.startsWith("/interface/gre/")?before.gre.find(row=>row[".id"]===decodeURIComponent(op.path.slice("/interface/gre/".length))):undefined
|
|
||||||
if(!creating&&live?.["ipsec-secret"]!=="")return op
|
|
||||||
const body={...op.body};delete body["ipsec-secret"]
|
|
||||||
return{...op,body}
|
|
||||||
}
|
|
||||||
export function planGreRevisionRestore(desired:GreSnapshot,before:GreMutationState):GreRestoreStep[]{
|
export function planGreRevisionRestore(desired:GreSnapshot,before:GreMutationState):GreRestoreStep[]{
|
||||||
const wanted=new Set(desired.tunnels.map(row=>row.name))
|
const wanted=new Set(desired.tunnels.map(row=>row.name))
|
||||||
for(const live of before.gre){
|
for(const live of before.gre){
|
||||||
@@ -95,10 +84,15 @@ export function planGreRevisionRestore(desired:GreSnapshot,before:GreMutationSta
|
|||||||
let op=item
|
let op=item
|
||||||
if((op.op==="put"&&op.path==="/interface/gre")||(op.op==="patch"&&op.path.startsWith("/interface/gre/"))){
|
if((op.op==="put"&&op.path==="/interface/gre")||(op.op==="patch"&&op.path.startsWith("/interface/gre/"))){
|
||||||
const want=desired.tunnels.find(row=>row.name===("body"in op?op.body.name:undefined))!
|
const want=desired.tunnels.find(row=>row.name===("body"in op?op.body.name:undefined))!
|
||||||
const body:Record<string,string>={...op.body,"local-address":want.localAddress||"0.0.0.0",comment:greInterfaceBody(want).comment??"","ipsec-secret":want.ipsecSecret}
|
const body:Record<string,string>={...op.body,"local-address":want.localAddress||"0.0.0.0",comment:greInterfaceBody(want).comment??""}
|
||||||
const live=before.gre.find(row=>row.name===want.name)
|
const live=before.gre.find(row=>row.name===want.name)
|
||||||
|
const clearSecret=live&&Boolean(live["ipsec-secret"])&&!want.ipsecSecret
|
||||||
const addressChanges=legacy.some(row=>!row.path.startsWith("/interface/gre")&&("body"in row?row.body.interface===want.name:mapped.addrs.some(a=>a.interfaceName===want.name&&row.path===greAddressPath(a.address)+"/"+a.rosId)))
|
const addressChanges=legacy.some(row=>!row.path.startsWith("/interface/gre")&&("body"in row?row.body.interface===want.name:mapped.addrs.some(a=>a.interfaceName===want.name&&row.path===greAddressPath(a.address)+"/"+a.rosId)))
|
||||||
if(live&&Object.entries(body).every(([key,value])=>same(greNativeValue(key,live[key]),greNativeValue(key,value)))&&!addressChanges)continue
|
if(live&&!clearSecret&&Object.entries(body).every(([key,value])=>same(greNativeValue(key,live[key]),greNativeValue(key,value)))&&!addressChanges)continue
|
||||||
|
if(live&&clearSecret){
|
||||||
|
if(observedBoolean(live.disabled)===false)staging.push({kind:"native",op:{op:"patch",path:op.path,body:{disabled:"yes"}}})
|
||||||
|
staging.push({kind:"native",op:greSecretUnsetOp(live[".id"])})
|
||||||
|
}
|
||||||
body.disabled="yes";op={...op,body};if(!want.disabled)enable.add(want.name)
|
body.disabled="yes";op={...op,body};if(!want.disabled)enable.add(want.name)
|
||||||
staging.push({kind:"native",op});continue
|
staging.push({kind:"native",op});continue
|
||||||
}
|
}
|
||||||
@@ -132,12 +126,12 @@ export async function restoreGreRevision(server:ServerRow,id:string,options:{bef
|
|||||||
const desired=options.desired?validateGreRestoreSnapshot(options.desired):materializeGreRestore(revision.desired,before),steps=planGreRevisionRestore(desired,before),client=MikrotikClient.fromServer(server)
|
const desired=options.desired?validateGreRestoreSnapshot(options.desired):materializeGreRestore(revision.desired,before),steps=planGreRevisionRestore(desired,before),client=MikrotikClient.fromServer(server)
|
||||||
const checkRevision=async()=>{if((await readGreRestoreRevision(server.id,id,authorize)).revisionProof!==revision.revisionProof)throw problem("Ревизия изменилась во время GRE restore")}
|
const checkRevision=async()=>{if((await readGreRestoreRevision(server.id,id,authorize)).revisionProof!==revision.revisionProof)throw problem("Ревизия изменилась во время GRE restore")}
|
||||||
const receipt=await executeGreRevisionSteps(before,steps,{read:()=>readGreRestoreState(server,authorize,undefined,deadlineAt),authorizeRevision:checkRevision,validate:state=>{planGreRevisionRestore(desired,state)},command:(op,gate)=>{
|
const receipt=await executeGreRevisionSteps(before,steps,{read:()=>readGreRestoreState(server,authorize,undefined,deadlineAt),authorizeRevision:checkRevision,validate:state=>{planGreRevisionRestore(desired,state)},command:(op,gate)=>{
|
||||||
const wire=greRestoreWireOp(op,before)
|
|
||||||
const slash=op.path.lastIndexOf("/"),path=op.path.slice(0,slash+1)+encodeURIComponent(op.path.slice(slash+1))
|
const slash=op.path.lastIndexOf("/"),path=op.path.slice(0,slash+1)+encodeURIComponent(op.path.slice(slash+1))
|
||||||
const timeout=Math.max(1,Math.min(op.op==="delete"?10000:15000,deadlineAt-Date.now()))
|
const timeout=Math.max(1,Math.min(op.op==="delete"?10000:15000,deadlineAt-Date.now()))
|
||||||
if(wire.op==="put")return client.put(wire.path,wire.body,timeout,gate)
|
if(op.op==="put")return client.put(op.path,op.body,timeout,gate)
|
||||||
|
if(op.op==="post")return client.post(op.path,op.body,timeout,undefined,gate)
|
||||||
if(op.op==="delete")return client.delete(path,timeout,gate)
|
if(op.op==="delete")return client.delete(path,timeout,gate)
|
||||||
if(wire.op==="patch")return client.patch(path,wire.body,timeout,gate)
|
if(op.op==="patch")return client.patch(path,op.body,timeout,gate)
|
||||||
throw problem("Недопустимая команда GRE restore")
|
throw problem("Недопустимая команда GRE restore")
|
||||||
}})
|
}})
|
||||||
const verified=receipt.verified&&planGreRevisionRestore(desired,receipt.after).length===0
|
const verified=receipt.verified&&planGreRevisionRestore(desired,receipt.after).length===0
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { createHash } from "node:crypto"
|
|||||||
import type { IxConfiguration, IxRouterObject, IxSite } from "@mmapp/contracts/internet-exchange"
|
import type { IxConfiguration, IxRouterObject, IxSite } from "@mmapp/contracts/internet-exchange"
|
||||||
import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js"
|
import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js"
|
||||||
import { compileIxTransit, ixTransitSourceObjects } from "./internet-exchange-transit.js"
|
import { compileIxTransit, ixTransitSourceObjects } from "./internet-exchange-transit.js"
|
||||||
|
import { greIke2TransportFields, greIpsecPaths, greIpsecPlaintextDrops } from "./gre-ipsec-transport.js"
|
||||||
|
|
||||||
export class IxConflict extends Error {
|
export class IxConflict extends Error {
|
||||||
constructor(message: string, readonly statusCode = 409) { super(message) }
|
constructor(message: string, readonly statusCode = 409) { super(message) }
|
||||||
@@ -282,8 +283,9 @@ export function compileIxConfiguration(id: string, configuration: IxConfiguratio
|
|||||||
result.push({ serverId: site.serverId, path, fields: nameOnly ? fields : { ...fields, comment: namespace + ":" + key } })
|
result.push({ serverId: site.serverId, path, fields: nameOnly ? fields : { ...fields, comment: namespace + ":" + key } })
|
||||||
}
|
}
|
||||||
const protectGre = (binding: IxSite["interfaces"][number], key: string) => {
|
const protectGre = (binding: IxSite["interfaces"][number], key: string) => {
|
||||||
add("/ip/firewall/filter", "gre-in-" + key, { chain: "input", protocol: "gre", "src-address": host(binding.endpoint!), "dst-address": host(binding.localEndpoint!), "ipsec-policy": "in,none", action: "drop" })
|
const [inbound, outbound] = greIpsecPlaintextDrops(binding.localEndpoint!, binding.endpoint!)
|
||||||
add("/ip/firewall/filter", "gre-out-" + key, { chain: "output", protocol: "gre", "src-address": host(binding.localEndpoint!), "dst-address": host(binding.endpoint!), "ipsec-policy": "out,none", action: "drop" })
|
add(greIpsecPaths.filter, "gre-in-" + key, inbound)
|
||||||
|
add(greIpsecPaths.filter, "gre-out-" + key, outbound)
|
||||||
}
|
}
|
||||||
const dropInterface = ixDiscardInterface(id)
|
const dropInterface = ixDiscardInterface(id)
|
||||||
for (const [index, binding] of site.interfaces.entries()) {
|
for (const [index, binding] of site.interfaces.entries()) {
|
||||||
@@ -296,14 +298,10 @@ export function compileIxConfiguration(id: string, configuration: IxConfiguratio
|
|||||||
if (gre) {
|
if (gre) {
|
||||||
const transport = namespace + "-" + key
|
const transport = namespace + "-" + key
|
||||||
protectGre(binding, key)
|
protectGre(binding, key)
|
||||||
add("/ip/ipsec/profile", key, { name: transport, "enc-algorithm": "aes-256", "hash-algorithm": "sha256", "dh-group": "modp2048" })
|
const fields = greIke2TransportFields(transport, binding.localEndpoint!, binding.endpoint!, true, "ix-credential:" + gre.credentialId, !binding.linux!.enabled)
|
||||||
add("/ip/ipsec/proposal", key, { name: transport, "enc-algorithms": "aes-256-cbc", "auth-algorithms": "sha256", "pfs-group": "modp2048" })
|
for (const kind of ["profile", "proposal", "peer"] as const) add(greIpsecPaths[kind], key, fields[kind])
|
||||||
add("/ip/ipsec/peer", key, { name: transport, address: host(binding.endpoint!), "local-address": binding.localEndpoint!,
|
add(greIpsecPaths.identity, "gre-identity-" + key, fields.identity)
|
||||||
profile: transport, "exchange-mode": "ike2", passive: "true" })
|
add(greIpsecPaths.policy, "gre-policy-" + key, fields.policy)
|
||||||
add("/ip/ipsec/identity", "gre-identity-" + key, { peer: transport, "auth-method": "pre-shared-key",
|
|
||||||
secret: "ix-credential:" + gre.credentialId, disabled: String(!binding.linux!.enabled) })
|
|
||||||
add("/ip/ipsec/policy", "gre-policy-" + key, { peer: transport, "src-address": host(binding.localEndpoint!),
|
|
||||||
"dst-address": host(binding.endpoint!), protocol: "gre", action: "encrypt", level: "require", tunnel: "false", proposal: transport })
|
|
||||||
add("/interface/gre", "gre-" + key, { name: binding.name, "local-address": binding.localEndpoint!,
|
add("/interface/gre", "gre-" + key, { name: binding.name, "local-address": binding.localEndpoint!,
|
||||||
"remote-address": binding.endpoint!, "allow-fast-path": "false", disabled: String(!binding.linux!.enabled) })
|
"remote-address": binding.endpoint!, "allow-fast-path": "false", disabled: String(!binding.linux!.enabled) })
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -423,6 +423,7 @@ try {
|
|||||||
assert.ok(!def.conversationsList.some((r) => r.proto === 47))
|
assert.ok(!def.conversationsList.some((r) => r.proto === 47))
|
||||||
assert.equal(def.conversationsList[0]?.service, "YouTube")
|
assert.equal(def.conversationsList[0]?.service, "YouTube")
|
||||||
assert.equal(def.conversationsList[0]?.category, "Видео / стриминг")
|
assert.equal(def.conversationsList[0]?.category, "Видео / стриминг")
|
||||||
|
assert.equal(def.conversationsList[0]?.serviceBasis, "heuristic")
|
||||||
assert.equal(def.conversationsList[0]?.clientName, "Alice")
|
assert.equal(def.conversationsList[0]?.clientName, "Alice")
|
||||||
assert.equal(def.conversationsList[0]?.enName, "NSK-SERVHOST-RTK")
|
assert.equal(def.conversationsList[0]?.enName, "NSK-SERVHOST-RTK")
|
||||||
assert.equal(def.conversationsList[0]?.plane, "payload")
|
assert.equal(def.conversationsList[0]?.plane, "payload")
|
||||||
|
|||||||
@@ -382,7 +382,7 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
|
|||||||
const pathKey = JSON.stringify([client?.userId ?? "unknown", r.serverId, en?.id ?? "", dst, resolved.name, outIface,
|
const pathKey = JSON.stringify([client?.userId ?? "unknown", r.serverId, en?.id ?? "", dst, resolved.name, outIface,
|
||||||
classified.service, classified.category, plane])
|
classified.service, classified.category, plane])
|
||||||
const ckey = JSON.stringify([flowTupleKey(r), pathKey, accounted.name, app, asnId, dstCountry, ep.internetPeer,
|
const ckey = JSON.stringify([flowTupleKey(r), pathKey, accounted.name, app, asnId, dstCountry, ep.internetPeer,
|
||||||
ep.clientIp, ep.peerPort, ep.direction, r.nextHop])
|
ep.clientIp, ep.peerPort, ep.direction, r.nextHop, classified.basis])
|
||||||
const prev = conv.get(ckey)
|
const prev = conv.get(ckey)
|
||||||
if (prev) {
|
if (prev) {
|
||||||
prev.rawBytes += r.bytes
|
prev.rawBytes += r.bytes
|
||||||
@@ -411,6 +411,7 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
|
|||||||
application: app,
|
application: app,
|
||||||
category: classified.category,
|
category: classified.category,
|
||||||
service: classified.service,
|
service: classified.service,
|
||||||
|
serviceBasis: classified.basis,
|
||||||
dstCountry,
|
dstCountry,
|
||||||
dstAsn: destMeta.asn || undefined,
|
dstAsn: destMeta.asn || undefined,
|
||||||
clientId: client?.userId,
|
clientId: client?.userId,
|
||||||
|
|||||||
@@ -734,6 +734,7 @@ ingestClosed(7, [
|
|||||||
nextHop: "",
|
nextHop: "",
|
||||||
},
|
},
|
||||||
{ ...payloadFlow("1.2.3.4", 6000), proto: 17, dstPort: 53, inIface: "gre-client", outIface: "ether1", nextHop: "" },
|
{ ...payloadFlow("1.2.3.4", 6000), proto: 17, dstPort: 53, inIface: "gre-client", outIface: "ether1", nextHop: "" },
|
||||||
|
{ ...payloadFlow("1.2.3.4", 3000), proto: 6, dstPort: 53, inIface: "ether1", outIface: "ether1", nextHop: "" },
|
||||||
])
|
])
|
||||||
try {
|
try {
|
||||||
resetFlowMapHopsCacheForTests()
|
resetFlowMapHopsCacheForTests()
|
||||||
@@ -743,15 +744,24 @@ try {
|
|||||||
assert.deepEqual(youtube.serviceEvidence, [{basis: "heuristic", bytes: 9000}])
|
assert.deepEqual(youtube.serviceEvidence, [{basis: "heuristic", bytes: 9000}])
|
||||||
assert.deepEqual(youtube.trafficTypes, [{transport: "TCP", application: "HTTPS", bytes: 9000}])
|
assert.deepEqual(youtube.trafficTypes, [{transport: "TCP", application: "HTTPS", bytes: 9000}])
|
||||||
assert.deepEqual(wanOnly.services?.find(s => s.id === "svc:dns")?.trafficTypes,
|
assert.deepEqual(wanOnly.services?.find(s => s.id === "svc:dns")?.trafficTypes,
|
||||||
[{transport: "UDP", application: "DNS", bytes: 6000}])
|
[{transport: "UDP", application: "DNS", bytes: 6000}, {transport: "TCP", application: "DNS", bytes: 3000}])
|
||||||
assert.deepEqual(wanOnly.services?.find(s => s.id === "svc:dns")?.serviceEvidence, [{basis: "port", bytes: 6000}])
|
assert.deepEqual(wanOnly.services?.find(s => s.id === "svc:dns")?.serviceEvidence, [{basis: "port", bytes: 9000}])
|
||||||
const dns = wanOnly.serviceEdges?.find(e => e.toId === "svc:dns")
|
const dns = wanOnly.serviceEdges?.find(e => e.toId === "svc:dns")
|
||||||
assert.deepEqual(dns && [dns.fromId, dns.observedOnly, dns.bytes], ["7", true, 6000])
|
assert.deepEqual(dns && [dns.fromId, dns.observedOnly, dns.bytes], ["7", true, 9000])
|
||||||
const dnsPath = wanOnly.servicePaths?.find(p => p.serviceId === "svc:dns")
|
const dnsPath = wanOnly.servicePaths?.find(p => p.serviceId === "svc:dns" && p.clientId === "u1")
|
||||||
assert.deepEqual(dnsPath && [dnsPath.viaId, dnsPath.viaIface, dnsPath.enId, dnsPath.clientName], ["7", "ether1", "", "Alice"])
|
assert.deepEqual(dnsPath && [dnsPath.viaId, dnsPath.viaIface, dnsPath.enId, dnsPath.clientName], ["7", "ether1", "", "Alice"])
|
||||||
|
const dnsPaths = wanOnly.servicePaths?.filter(p => p.serviceId === "svc:dns")
|
||||||
|
const nestedDnsPaths = wanOnly.countryServiceGroups?.flatMap(group => group.paths.filter(p => p.serviceId.endsWith("|svc:dns")))
|
||||||
|
for (const paths of [dnsPaths, nestedDnsPaths]) {
|
||||||
|
assert.deepEqual(paths?.map(p => [p.clientName, p.trafficTypes, p.serviceEvidence]), [
|
||||||
|
["Alice", [{transport: "UDP", application: "DNS", bytes: 6000}], [{basis: "port", bytes: 6000}]],
|
||||||
|
["—", [{transport: "TCP", application: "DNS", bytes: 3000}], [{basis: "port", bytes: 3000}]],
|
||||||
|
])
|
||||||
|
}
|
||||||
|
assert.ok(wanOnly.countryPaths?.every(p => p.serviceEvidence === undefined && p.trafficTypes === undefined))
|
||||||
assert.ok(wanOnly.countryEdges?.every(e => e.observedOnly && e.fromId === "7"))
|
assert.ok(wanOnly.countryEdges?.every(e => e.observedOnly && e.fromId === "7"))
|
||||||
assert.ok(wanOnly.countryServiceGroups?.some(group => group.edges.some(e => e.toId.endsWith("|svc:dns"))))
|
assert.ok(wanOnly.countryServiceGroups?.some(group => group.edges.some(e => e.toId.endsWith("|svc:dns"))))
|
||||||
assert.deepEqual(wanOnly.nodeUsers?.["7"]?.map(u => [u.clientName, u.bytes]), [["—", 9000], ["Alice", 6000]])
|
assert.deepEqual(wanOnly.nodeUsers?.["7"]?.map(u => [u.clientName, u.bytes]), [["—", 12000], ["Alice", 6000]])
|
||||||
assert.equal(wanOnly.nodeUsers?.["9"], undefined)
|
assert.equal(wanOnly.nodeUsers?.["9"], undefined)
|
||||||
|
|
||||||
} finally {
|
} finally {
|
||||||
|
|||||||
@@ -83,13 +83,18 @@ interface DstAcc {
|
|||||||
fromBytes: Map<string, FromAcc>
|
fromBytes: Map<string, FromAcc>
|
||||||
}
|
}
|
||||||
|
|
||||||
interface DestTotal {
|
interface ClassificationCounters {
|
||||||
|
trafficTypes?: Map<string, NonNullable<FlowMapService["trafficTypes"]>[number]>
|
||||||
|
serviceEvidence?: Map<FlowServiceBasis, number>
|
||||||
|
}
|
||||||
|
|
||||||
|
type ClassificationDetail = { transport: string; application: string | null; basis: FlowServiceBasis }
|
||||||
|
|
||||||
|
interface DestTotal extends ClassificationCounters {
|
||||||
label: string
|
label: string
|
||||||
category: string
|
category: string
|
||||||
bytes: number
|
bytes: number
|
||||||
lastBucketAt: string
|
lastBucketAt: string
|
||||||
trafficTypes?: Map<string, NonNullable<FlowMapService["trafficTypes"]>[number]>
|
|
||||||
serviceEvidence?: Map<FlowServiceBasis, number>
|
|
||||||
}
|
}
|
||||||
|
|
||||||
interface DestEdgeAcc {
|
interface DestEdgeAcc {
|
||||||
@@ -102,7 +107,7 @@ interface DestEdgeAcc {
|
|||||||
observedOnly?: true
|
observedOnly?: true
|
||||||
}
|
}
|
||||||
|
|
||||||
interface DestPathAcc {
|
interface DestPathAcc extends ClassificationCounters {
|
||||||
clientId: string
|
clientId: string
|
||||||
clientName: string
|
clientName: string
|
||||||
viaId: string
|
viaId: string
|
||||||
@@ -162,11 +167,7 @@ export function pickMapServices(
|
|||||||
.slice(0, cap)
|
.slice(0, cap)
|
||||||
}
|
}
|
||||||
|
|
||||||
function bumpDestTotal(totals: Map<string, DestTotal>, id: string, label: string, category: string, bytes: number, lastBucketAt: string,
|
function bumpClassification(total: ClassificationCounters, bytes: number, detail?: ClassificationDetail): void {
|
||||||
detail?: { transport: string; application: string | null; basis: FlowServiceBasis }): void {
|
|
||||||
const total = totals.get(id) ?? { label, category, bytes: 0, lastBucketAt }
|
|
||||||
total.bytes += bytes
|
|
||||||
if (lastBucketAt > total.lastBucketAt) total.lastBucketAt = lastBucketAt
|
|
||||||
if (detail && bytes > 0) {
|
if (detail && bytes > 0) {
|
||||||
const { transport, application, basis } = detail
|
const { transport, application, basis } = detail
|
||||||
const types = total.trafficTypes ??= new Map()
|
const types = total.trafficTypes ??= new Map()
|
||||||
@@ -177,6 +178,21 @@ function bumpDestTotal(totals: Map<string, DestTotal>, id: string, label: string
|
|||||||
const evidence = total.serviceEvidence ??= new Map()
|
const evidence = total.serviceEvidence ??= new Map()
|
||||||
evidence.set(basis, (evidence.get(basis) ?? 0) + bytes)
|
evidence.set(basis, (evidence.get(basis) ?? 0) + bytes)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function classificationFields(total: ClassificationCounters) {
|
||||||
|
return {
|
||||||
|
...(total.trafficTypes ? { trafficTypes: [...total.trafficTypes.values()].sort((a, b) => b.bytes - a.bytes).slice(0, 5) } : {}),
|
||||||
|
...(total.serviceEvidence ? { serviceEvidence: [...total.serviceEvidence].map(([basis, bytes]) => ({ basis, bytes })).sort((a, b) => b.bytes - a.bytes) } : {}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function bumpDestTotal(totals: Map<string, DestTotal>, id: string, label: string, category: string, bytes: number, lastBucketAt: string,
|
||||||
|
detail?: ClassificationDetail): void {
|
||||||
|
const total = totals.get(id) ?? { label, category, bytes: 0, lastBucketAt }
|
||||||
|
total.bytes += bytes
|
||||||
|
if (lastBucketAt > total.lastBucketAt) total.lastBucketAt = lastBucketAt
|
||||||
|
bumpClassification(total, bytes, detail)
|
||||||
totals.set(id, total)
|
totals.set(id, total)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -189,6 +205,7 @@ function bumpDestFrom(
|
|||||||
fromId: string,
|
fromId: string,
|
||||||
enName: string,
|
enName: string,
|
||||||
viaName: string,
|
viaName: string,
|
||||||
|
detail?: ClassificationDetail,
|
||||||
/** fromId ребра, если отличается от EN (вложенный слой: страна → сервис). */
|
/** fromId ребра, если отличается от EN (вложенный слой: страна → сервис). */
|
||||||
edgeFromId: string = fromId || exporterId,
|
edgeFromId: string = fromId || exporterId,
|
||||||
): void {
|
): void {
|
||||||
@@ -216,12 +233,9 @@ function bumpDestFrom(
|
|||||||
}
|
}
|
||||||
for (const [clientId, c] of from.clients) {
|
for (const [clientId, c] of from.clients) {
|
||||||
const pathKey = JSON.stringify([clientId, exporterId, fromId, toId, from.viaIface])
|
const pathKey = JSON.stringify([clientId, exporterId, fromId, toId, from.viaIface])
|
||||||
const prevPath = paths.get(pathKey)
|
let path = paths.get(pathKey)
|
||||||
if (prevPath) {
|
if (!path) {
|
||||||
prevPath.bytes += c.bytes
|
path = {
|
||||||
if (prevPath.clientName === "—" && c.name !== "—") prevPath.clientName = c.name
|
|
||||||
} else {
|
|
||||||
paths.set(pathKey, {
|
|
||||||
clientId,
|
clientId,
|
||||||
clientName: c.name,
|
clientName: c.name,
|
||||||
viaId: exporterId,
|
viaId: exporterId,
|
||||||
@@ -230,9 +244,13 @@ function bumpDestFrom(
|
|||||||
enId: fromId,
|
enId: fromId,
|
||||||
enName,
|
enName,
|
||||||
serviceId: toId,
|
serviceId: toId,
|
||||||
bytes: c.bytes,
|
bytes: 0,
|
||||||
})
|
}
|
||||||
|
paths.set(pathKey, path)
|
||||||
}
|
}
|
||||||
|
if (path.clientName === "—" && c.name !== "—") path.clientName = c.name
|
||||||
|
path.bytes += c.bytes
|
||||||
|
bumpClassification(path, c.bytes, detail)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -256,8 +274,7 @@ function finalizeDestLayer(
|
|||||||
...(s.lastBucketAt ? { lastBucketAt: minuteBucketIso(Date.parse(s.lastBucketAt)) } : {}),
|
...(s.lastBucketAt ? { lastBucketAt: minuteBucketIso(Date.parse(s.lastBucketAt)) } : {}),
|
||||||
bps: (s.bytes * 8) / windowSec,
|
bps: (s.bytes * 8) / windowSec,
|
||||||
share: shareBase > 0 ? s.bytes / shareBase : 0,
|
share: shareBase > 0 ? s.bytes / shareBase : 0,
|
||||||
...(s.trafficTypes ? { trafficTypes: [...s.trafficTypes.values()].sort((a, b) => b.bytes - a.bytes).slice(0, 5) } : {}),
|
...classificationFields(s),
|
||||||
...(s.serviceEvidence ? { serviceEvidence: [...s.serviceEvidence].map(([basis, bytes]) => ({ basis, bytes })).sort((a, b) => b.bytes - a.bytes) } : {}),
|
|
||||||
}))
|
}))
|
||||||
.sort((a, b) => b.bytes - a.bytes),
|
.sort((a, b) => b.bytes - a.bytes),
|
||||||
minSharePct,
|
minSharePct,
|
||||||
@@ -296,6 +313,7 @@ function finalizeDestLayer(
|
|||||||
serviceId: p.serviceId,
|
serviceId: p.serviceId,
|
||||||
bytes: p.bytes,
|
bytes: p.bytes,
|
||||||
bps: (p.bytes * 8) / windowSec,
|
bps: (p.bytes * 8) / windowSec,
|
||||||
|
...classificationFields(p),
|
||||||
}))
|
}))
|
||||||
.sort((a, b) => b.bps - a.bps)
|
.sort((a, b) => b.bps - a.bps)
|
||||||
return { nodes, edges: outEdges, paths: outPaths }
|
return { nodes, edges: outEdges, paths: outPaths }
|
||||||
@@ -818,9 +836,9 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
|||||||
const { exporterId, enId: fromId } = from
|
const { exporterId, enId: fromId } = from
|
||||||
const enName = nodeName(fromId)
|
const enName = nodeName(fromId)
|
||||||
const viaName = nodeName(exporterId)
|
const viaName = nodeName(exporterId)
|
||||||
bumpDestFrom(svcEdges, svcPaths, svcId, from, exporterId, fromId, enName, viaName)
|
bumpDestFrom(svcEdges, svcPaths, svcId, from, exporterId, fromId, enName, viaName, detail)
|
||||||
bumpDestFrom(ccEdges, ccPaths, country.id, from, exporterId, fromId, enName, viaName)
|
bumpDestFrom(ccEdges, ccPaths, country.id, from, exporterId, fromId, enName, viaName)
|
||||||
bumpDestFrom(nestedEdges, nestedPaths, nestedId, from, exporterId, fromId, enName, viaName, country.id)
|
bumpDestFrom(nestedEdges, nestedPaths, nestedId, from, exporterId, fromId, enName, viaName, detail, country.id)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -9,10 +9,10 @@ import { createMcpConnection, authenticateMcpToken } from "../modules/mcp/store.
|
|||||||
import { approvePlan, applyPlan, invokeMcpTool } from "../modules/mcp/runtime.js"
|
import { approvePlan, applyPlan, invokeMcpTool } from "../modules/mcp/runtime.js"
|
||||||
|
|
||||||
export async function verifyMcpBgpExport(actor: AuthUser) {
|
export async function verifyMcpBgpExport(actor: AuthUser) {
|
||||||
let mode = "", templateMode = "", writes = 0, reads = 0, ignored = false, unexpected = false, lost = false
|
let mode = "", templateMode = "", writes = 0, reads = 0, ignored = false, unexpected = false, lost = false, ignoreRouteQuery = false
|
||||||
let staticQueryReply: unknown = [{ ".id": "*peer" }]
|
let staticQueryReply: unknown = [{ ".id": "*peer" }]
|
||||||
const connection: Record<string, string> = { ".id": "*peer", name: "export-peer", disabled: "false", instance: "lab", vrf: "lab", "routing-table": "lab", templates: "default", "remote.address": "192.0.2.2", "remote.as": "64513", "tcp-md5-key": "NEVER_BGP_EXPORT_MD5" }
|
const connection: Record<string, string> = { ".id": "*peer", name: "export-peer", disabled: "false", instance: "lab", vrf: "lab", "routing-table": "lab", templates: "default", "remote.address": "192.0.2.2", "remote.as": "64513", "tcp-md5-key": "NEVER_BGP_EXPORT_MD5" }
|
||||||
const routes: Record<string, unknown[]> = {
|
const routes: Record<string, Record<string, unknown>[]> = {
|
||||||
"/ip/route": [{ ".id": "*c4", "routing-table": "lab", "dst-address": "192.0.2.0/30", connect: "true", dynamic: "true", active: "true", comment: "NEVER_BGP_EXPORT_ROUTE_NOTE" },
|
"/ip/route": [{ ".id": "*c4", "routing-table": "lab", "dst-address": "192.0.2.0/30", connect: "true", dynamic: "true", active: "true", comment: "NEVER_BGP_EXPORT_ROUTE_NOTE" },
|
||||||
{ ".id": "*s4", "routing-table": "lab", "dst-address": "198.18.0.1/32", static: "true", dynamic: "false", active: "true" },
|
{ ".id": "*s4", "routing-table": "lab", "dst-address": "198.18.0.1/32", static: "true", dynamic: "false", active: "true" },
|
||||||
{ ".id": "*b4", "routing-table": "lab", "dst-address": "198.18.1.1/32", bgp: "true", dynamic: "true", active: "true" }],
|
{ ".id": "*b4", "routing-table": "lab", "dst-address": "198.18.1.1/32", bgp: "true", dynamic: "true", active: "true" }],
|
||||||
@@ -29,10 +29,17 @@ export async function verifyMcpBgpExport(actor: AuthUser) {
|
|||||||
"/routing/filter/rule": [{ ".id": "*f", chain: "export-out", rule: "NEVER_BGP_EXPORT_FILTER_SECRET", disabled: "false" }],
|
"/routing/filter/rule": [{ ".id": "*f", chain: "export-out", rule: "NEVER_BGP_EXPORT_FILTER_SECRET", disabled: "false" }],
|
||||||
}
|
}
|
||||||
const mock = createServer(async (req, res) => {
|
const mock = createServer(async (req, res) => {
|
||||||
const path = (req.url ?? "").replace(/^\/rest/, "")
|
const url = new URL(req.url ?? "/", "http://127.0.0.1")
|
||||||
|
const path = url.pathname.replace(/^\/rest/, "")
|
||||||
if (req.method === "GET") {
|
if (req.method === "GET") {
|
||||||
reads++; res.setHeader("content-type", "application/json")
|
reads++; res.setHeader("content-type", "application/json")
|
||||||
res.end(JSON.stringify(path === "/routing/bgp/connection" ? [connection] : collections[path] ?? routes[path] ?? [])); return
|
const candidates = routes[path]
|
||||||
|
if (candidates) {
|
||||||
|
const table = url.searchParams.get("routing-table"), kind = url.searchParams.has("connect") ? "connect" : "static"
|
||||||
|
assert.ok(table); assert.equal(url.searchParams.get(kind), "true")
|
||||||
|
res.end(JSON.stringify(ignoreRouteQuery ? candidates : candidates.filter(row => row["routing-table"] === table && row[kind] === "true"))); return
|
||||||
|
}
|
||||||
|
res.end(JSON.stringify(path === "/routing/bgp/connection" ? [connection] : collections[path] ?? [])); return
|
||||||
}
|
}
|
||||||
let raw = ""; for await (const data of req) raw += data
|
let raw = ""; for await (const data of req) raw += data
|
||||||
const body = raw ? JSON.parse(raw) as Record<string, string> : {}
|
const body = raw ? JSON.parse(raw) as Record<string, string> : {}
|
||||||
@@ -49,6 +56,7 @@ export async function verifyMcpBgpExport(actor: AuthUser) {
|
|||||||
const property = body["value-name"]
|
const property = body["value-name"]
|
||||||
res.end(JSON.stringify(property === "output.redistribute" ? templateMode ? { ret: templateMode } : [] : property === "templates" ? { ret: collections["/routing/bgp/template"][0].templates ?? "" } : { ret: "false" })); return
|
res.end(JSON.stringify(property === "output.redistribute" ? templateMode ? { ret: templateMode } : [] : property === "templates" ? { ret: collections["/routing/bgp/template"][0].templates ?? "" } : { ret: "false" })); return
|
||||||
}
|
}
|
||||||
|
if (path === "/routing/bgp/instance/get") { res.end(JSON.stringify([])); return }
|
||||||
if (req.method === "PATCH" && path === "/routing/bgp/connection/*peer") {
|
if (req.method === "PATCH" && path === "/routing/bgp/connection/*peer") {
|
||||||
writes++
|
writes++
|
||||||
assert.deepEqual(Object.keys(body), ["output.redistribute"])
|
assert.deepEqual(Object.keys(body), ["output.redistribute"])
|
||||||
@@ -100,6 +108,7 @@ export async function verifyMcpBgpExport(actor: AuthUser) {
|
|||||||
staticQueryReply = invalid; await assert.rejects(plan("connected")); assert.equal(writes, 0)
|
staticQueryReply = invalid; await assert.rejects(plan("connected")); assert.equal(writes, 0)
|
||||||
}
|
}
|
||||||
staticQueryReply = [{ ".id": "*peer" }]
|
staticQueryReply = [{ ".id": "*peer" }]
|
||||||
|
ignoreRouteQuery = true; await assert.rejects(plan("connected"), /не соответствует запросу источников/); ignoreRouteQuery = false
|
||||||
let prepared = await plan("connected")
|
let prepared = await plan("connected")
|
||||||
assert.equal(prepared.state, "awaiting-approval"); assert.equal(prepared.changes.before.mode, "disabled"); assert.equal(prepared.changes.before.sources.length, 2)
|
assert.equal(prepared.state, "awaiting-approval"); assert.equal(prepared.changes.before.mode, "disabled"); assert.equal(prepared.changes.before.sources.length, 2)
|
||||||
assert(prepared.changes.objects.some(row => row.kind === "ipv4_route" && row.id === "*c4")); assert(!prepared.changes.objects.some(row => row.kind === "ipv4_route" && row.id === "*b4"))
|
assert(prepared.changes.objects.some(row => row.kind === "ipv4_route" && row.id === "*c4")); assert(!prepared.changes.objects.some(row => row.kind === "ipv4_route" && row.id === "*b4"))
|
||||||
@@ -146,6 +155,16 @@ export async function verifyMcpBgpExport(actor: AuthUser) {
|
|||||||
const lostPlan = await plan("disabled"), lostOperation = await apply(lostPlan.planId)
|
const lostPlan = await plan("disabled"), lostOperation = await apply(lostPlan.planId)
|
||||||
assert.equal(lostOperation.state, "unknown"); assert.equal(writes, beforeLost + 1); lost = false
|
assert.equal(lostOperation.state, "unknown"); assert.equal(writes, beforeLost + 1); lost = false
|
||||||
assert.equal((await applyPlan(principal, lostPlan.planId, randomUUID())).id, lostOperation.id); assert.equal(writes, beforeLost + 1)
|
assert.equal((await applyPlan(principal, lostPlan.planId, randomUUID())).id, lostOperation.id); assert.equal(writes, beforeLost + 1)
|
||||||
|
const instance = collections["/routing/bgp/instance"][0]
|
||||||
|
delete instance.vrf; delete instance["routing-table"]
|
||||||
|
Object.assign(connection, { vrf: "main", "routing-table": "main" }); mode = ""
|
||||||
|
collections["/ip/vrf"].push({ ".id": "*mainVrf", name: "main", interfaces: "all" })
|
||||||
|
collections["/routing/table"].push({ ".id": "*mainTable", name: "main", fib: "" })
|
||||||
|
const baseRoute = routes["/ip/route"][0]
|
||||||
|
routes["/ip/route"].push({ ...baseRoute, ".id": "*mainRoute", "routing-table": "main" })
|
||||||
|
const defaultContextPlan = await plan("connected")
|
||||||
|
assert.equal(defaultContextPlan.changes.before.sources.length, 1)
|
||||||
|
assert.equal((await apply(defaultContextPlan.planId)).state, "applied")
|
||||||
const requests = (await pool.query("SELECT input,result FROM mcp_requests WHERE connection_id=ANY($1::uuid[])", [connections])).rows
|
const requests = (await pool.query("SELECT input,result FROM mcp_requests WHERE connection_id=ANY($1::uuid[])", [connections])).rows
|
||||||
const audit = (await pool.query("SELECT payload FROM mcp_audit WHERE connection_id=ANY($1::uuid[])", [connections])).rows
|
const audit = (await pool.query("SELECT payload FROM mcp_audit WHERE connection_id=ANY($1::uuid[])", [connections])).rows
|
||||||
assert.equal(JSON.stringify({ requests, audit }).includes("NEVER_BGP_EXPORT_"), false)
|
assert.equal(JSON.stringify({ requests, audit }).includes("NEVER_BGP_EXPORT_"), false)
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import { createMcpConnection, authenticateMcpToken } from "../modules/mcp/store.
|
|||||||
import { approvePlan, applyPlan, invokeMcpTool } from "../modules/mcp/runtime.js"
|
import { approvePlan, applyPlan, invokeMcpTool } from "../modules/mcp/runtime.js"
|
||||||
|
|
||||||
export async function verifyMcpBgpFilterBinding(actor: AuthUser) {
|
export async function verifyMcpBgpFilterBinding(actor: AuthUser) {
|
||||||
let reads = 0, writes = 0, ignored = false, corrupt = false, lost = false, lateDrift = false, lateFenceReached = false, intentBaseline = 0
|
let reads = 0, writes = 0, ignored = false, corrupt = false, lost = false, lateDrift = false, lateFenceReached = false, intentBaseline = 0, unsetInstanceContext = false
|
||||||
const peer: Record<string, string> = { ".id": "*peer", name: "binding-peer", disabled: "false", instance: "lab", vrf: "lab", "routing-table": "lab", templates: "default", "tcp-md5-key": "NEVER_BIND_PEER_SECRET", "output.redistribute": "connected,static,ospf" }
|
const peer: Record<string, string> = { ".id": "*peer", name: "binding-peer", disabled: "false", instance: "lab", vrf: "lab", "routing-table": "lab", templates: "default", "tcp-md5-key": "NEVER_BIND_PEER_SECRET", "output.redistribute": "connected,static,ospf" }
|
||||||
const local: Record<string, string | null> = { "input.filter": null, "output.filter-chain": null }, inherited: Record<string, string | null> = { "input.filter": null, "output.filter-chain": null }
|
const local: Record<string, string | null> = { "input.filter": null, "output.filter-chain": null }, inherited: Record<string, string | null> = { "input.filter": null, "output.filter-chain": null }
|
||||||
const context: Record<string, string> = { instance: "lab", vrf: "lab", "routing-table": "lab" }
|
const context: Record<string, string> = { instance: "lab", vrf: "lab", "routing-table": "lab" }
|
||||||
@@ -29,7 +29,7 @@ export async function verifyMcpBgpFilterBinding(actor: AuthUser) {
|
|||||||
if (path === "/routing/bgp/connection/get") { const value = property === "dynamic" ? null : property === "templates" ? peer.templates : property in local ? local[property] : property in peer ? peer[property] : context[property] ?? "false"; res.end(JSON.stringify(value === null ? [] : { ret: value })); return }
|
if (path === "/routing/bgp/connection/get") { const value = property === "dynamic" ? null : property === "templates" ? peer.templates : property in local ? local[property] : property in peer ? peer[property] : context[property] ?? "false"; res.end(JSON.stringify(value === null ? [] : { ret: value })); return }
|
||||||
if (path === "/routing/bgp/connection/print") { assert.deepEqual(body[".query"], [".id=*peer", "-dynamic", "#&"]); res.end(JSON.stringify([{ ".id": "*peer" }])); return }
|
if (path === "/routing/bgp/connection/print") { assert.deepEqual(body[".query"], [".id=*peer", "-dynamic", "#&"]); res.end(JSON.stringify([{ ".id": "*peer" }])); return }
|
||||||
if (path === "/routing/bgp/template/get") { const value = property in inherited ? inherited[property] : property === "templates" ? collections["/routing/bgp/template"][0].templates ?? "" : "false"; res.end(JSON.stringify(value === null ? [] : { ret: value })); return }
|
if (path === "/routing/bgp/template/get") { const value = property in inherited ? inherited[property] : property === "templates" ? collections["/routing/bgp/template"][0].templates ?? "" : "false"; res.end(JSON.stringify(value === null ? [] : { ret: value })); return }
|
||||||
if (path === "/routing/bgp/instance/get") { res.end(JSON.stringify({ ret: context[property] ?? "false" })); return }
|
if (path === "/routing/bgp/instance/get") { res.end(JSON.stringify(unsetInstanceContext && ["vrf", "routing-table"].includes(property) ? [] : { ret: context[property] ?? "false" })); return }
|
||||||
if (path === "/routing/filter/rule/get") { res.end(JSON.stringify({ ret: "false" })); return }
|
if (path === "/routing/filter/rule/get") { res.end(JSON.stringify({ ret: "false" })); return }
|
||||||
if (req.method === "PATCH" && path === "/routing/bgp/connection/*peer") {
|
if (req.method === "PATCH" && path === "/routing/bgp/connection/*peer") {
|
||||||
writes++; assert.equal(Object.keys(body).length, 1); const key = Object.keys(body)[0]; assert.ok(key in local)
|
writes++; assert.equal(Object.keys(body).length, 1); const key = Object.keys(body)[0]; assert.ok(key in local)
|
||||||
@@ -51,7 +51,7 @@ export async function verifyMcpBgpFilterBinding(actor: AuthUser) {
|
|||||||
try {
|
try {
|
||||||
await pool.query("INSERT INTO servers(id,name,host,port,use_ssl,username,password) VALUES(79,'binding-fixture','127.0.0.1',$1,false,'fixture','NEVER_BIND_LOGIN')", [address.port])
|
await pool.query("INSERT INTO servers(id,name,host,port,use_ssl,username,password) VALUES(79,'binding-fixture','127.0.0.1',$1,false,'fixture','NEVER_BIND_LOGIN')", [address.port])
|
||||||
const issued = await create(), principal = await authenticateMcpToken(issued.token)
|
const issued = await create(), principal = await authenticateMcpToken(issued.token)
|
||||||
const prepare = (chain = "in", direction = "input") => invokeMcpTool(principal, "mm_bgp_filter_binding_plan", { serverId: 79, id: "*peer", chain, direction }) as Promise<{ planId: string; state: string }>
|
const prepare = (chain = "in", direction = "input") => invokeMcpTool(principal, "mm_bgp_filter_binding_plan", { serverId: 79, id: "*peer", chain, direction }) as Promise<{ planId: string; state: string; changes: { objects: { kind: string; id: string }[] } }>
|
||||||
const wait = async (id: string) => { for (let n = 0; n < 400; n++) { const row = (await pool.query("SELECT id,state,error_code FROM mcp_operations WHERE id=$1", [id])).rows[0]; if (row && !["pending", "running"].includes(row.state)) return row; await delay(25) } assert.fail("Binding operation did not terminate") }
|
const wait = async (id: string) => { for (let n = 0; n < 400; n++) { const row = (await pool.query("SELECT id,state,error_code FROM mcp_operations WHERE id=$1", [id])).rows[0]; if (row && !["pending", "running"].includes(row.state)) return row; await delay(25) } assert.fail("Binding operation did not terminate") }
|
||||||
const apply = async (planId: string) => { await approvePlan(planId, actor, true); return wait((await applyPlan(principal, planId, randomUUID())).id) }
|
const apply = async (planId: string) => { await approvePlan(planId, actor, true); return wait((await applyPlan(principal, planId, randomUUID())).id) }
|
||||||
for (const permission of permissions) { const denied = await create(permissions.filter(value => value !== permission)), before = reads; await assert.rejects(invokeMcpTool(await authenticateMcpToken(denied.token), "mm_bgp_filter_binding_plan", { serverId: 79, id: "*peer", chain: "in", direction: "input" })); assert.equal(reads, before) }
|
for (const permission of permissions) { const denied = await create(permissions.filter(value => value !== permission)), before = reads; await assert.rejects(invokeMcpTool(await authenticateMcpToken(denied.token), "mm_bgp_filter_binding_plan", { serverId: 79, id: "*peer", chain: "in", direction: "input" })); assert.equal(reads, before) }
|
||||||
@@ -69,6 +69,39 @@ export async function verifyMcpBgpFilterBinding(actor: AuthUser) {
|
|||||||
assert.equal((await apply((await prepare()).planId)).state, "applied", "Effective default context comes from native /get, not guessed main")
|
assert.equal((await apply((await prepare()).planId)).state, "applied", "Effective default context comes from native /get, not guessed main")
|
||||||
Object.assign(peer, context); Object.assign(collections["/routing/bgp/instance"][0], { vrf: "lab", "routing-table": "lab" })
|
Object.assign(peer, context); Object.assign(collections["/routing/bgp/instance"][0], { vrf: "lab", "routing-table": "lab" })
|
||||||
Object.assign(peer, { instance: "*instance", vrf: "*vrf", "routing-table": "*table" }); assert.equal((await apply((await prepare()).planId)).state, "applied"); Object.assign(peer, context)
|
Object.assign(peer, { instance: "*instance", vrf: "*vrf", "routing-table": "*table" }); assert.equal((await apply((await prepare()).planId)).state, "applied"); Object.assign(peer, context)
|
||||||
|
collections["/ip/vrf"].push({ ".id": "*mainVrf", name: "main", interfaces: "all" })
|
||||||
|
const mainTable: Record<string, string> = { ".id": "*mainTable", name: "main", fib: "" }
|
||||||
|
const peerTable: Record<string, string> = { ".id": "*peerTable", name: "rtab-antiblock", fib: "true" }
|
||||||
|
collections["/routing/table"].push(mainTable, peerTable)
|
||||||
|
const instance = collections["/routing/bgp/instance"][0]
|
||||||
|
delete instance.vrf; delete instance["routing-table"]
|
||||||
|
Object.assign(peer, { vrf: "main", "routing-table": "main" }); unsetInstanceContext = true
|
||||||
|
assert.equal((await apply((await prepare()).planId)).state, "applied")
|
||||||
|
Object.assign(instance, { vrf: "main", "routing-table": "main" })
|
||||||
|
peer["routing-table"] = peerTable.name
|
||||||
|
for (const table of [mainTable, peerTable]) {
|
||||||
|
const stale = await prepare("in", "output")
|
||||||
|
const writesBefore: number = writes
|
||||||
|
table.comment = "changed after preview"
|
||||||
|
assert.notEqual((await apply(stale.planId)).state, "applied")
|
||||||
|
assert.equal(writes, writesBefore)
|
||||||
|
delete table.comment
|
||||||
|
}
|
||||||
|
const overrideTablePlan = await prepare("in", "output")
|
||||||
|
assert.deepEqual(overrideTablePlan.changes.objects.filter(row => row.kind === "routing_table").map(row => row.id).sort(), ["*mainTable", "*peerTable"])
|
||||||
|
assert.equal((await apply(overrideTablePlan.planId)).state, "applied")
|
||||||
|
assert.equal(local["output.filter-chain"], "in")
|
||||||
|
assert.equal(peer["routing-table"], "rtab-antiblock")
|
||||||
|
assert.equal(instance["routing-table"], "main")
|
||||||
|
peer.vrf = "lab"; await assert.rejects(prepare()); peer.vrf = "main"
|
||||||
|
for (const foreignTableRef of ["lab", "*table"]) {
|
||||||
|
peer["routing-table"] = foreignTableRef
|
||||||
|
await assert.rejects(prepare(), "A table owned by another VRF cannot override the main instance table")
|
||||||
|
}
|
||||||
|
peer["routing-table"] = "lab"
|
||||||
|
Object.assign(instance, { vrf: "main", "routing-table": "lab" })
|
||||||
|
assert.equal((await apply((await prepare("out", "output")).planId)).state, "applied")
|
||||||
|
Object.assign(peer, context); Object.assign(instance, { vrf: "lab", "routing-table": "lab" }); unsetInstanceContext = false
|
||||||
collections["/routing/bgp/template"][0].templates = "default"; await assert.rejects(prepare()); delete collections["/routing/bgp/template"][0].templates
|
collections["/routing/bgp/template"][0].templates = "default"; await assert.rejects(prepare()); delete collections["/routing/bgp/template"][0].templates
|
||||||
await assert.rejects(prepare("In")); await assert.rejects(prepare("missing"))
|
await assert.rejects(prepare("In")); await assert.rejects(prepare("missing"))
|
||||||
const beforeInvalid = reads; await assert.rejects(invokeMcpTool(principal, "mm_bgp_filter_binding_plan", { serverId: 79, id: "all", chain: "in", direction: "input" })); assert.equal(reads, beforeInvalid)
|
const beforeInvalid = reads; await assert.rejects(invokeMcpTool(principal, "mm_bgp_filter_binding_plan", { serverId: 79, id: "all", chain: "in", direction: "input" })); assert.equal(reads, beforeInvalid)
|
||||||
|
|||||||
@@ -0,0 +1,91 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { ChevronDownIcon, ChevronRightIcon } from "lucide-react"
|
||||||
|
import type { KeyboardEvent } from "react"
|
||||||
|
import { MAP_CARD_H, MAP_CARD_W, placeMapLinkLabels, type MapBox } from "@/lib/network-map-layout"
|
||||||
|
import type { MapGroupLink } from "@/lib/network-map-group-links"
|
||||||
|
|
||||||
|
function activate(event: KeyboardEvent<SVGGElement>, action: () => void) {
|
||||||
|
if (event.key !== "Enter" && event.key !== " ") return
|
||||||
|
event.preventDefault()
|
||||||
|
event.stopPropagation()
|
||||||
|
action()
|
||||||
|
}
|
||||||
|
|
||||||
|
const roleColors: Record<string, string> = {
|
||||||
|
HR: "var(--chart-2)", JH: "var(--chart-1)", EN: "var(--chart-3)", IX: "var(--chart-4)", WAN: "var(--muted-foreground)",
|
||||||
|
}
|
||||||
|
|
||||||
|
export function MapGroupMark({ id, x, y, name, code, count, expanded, problems = 0, unknownCount = 0, onToggle, visible = true }: {
|
||||||
|
id: string; x: number; y: number; name: string; code: string; count: number; expanded: boolean
|
||||||
|
problems?: number; unknownCount?: number; onToggle: () => void; visible?: boolean
|
||||||
|
}) {
|
||||||
|
const width = MAP_CARD_W, height = MAP_CARD_H
|
||||||
|
const color = roleColors[code] ?? "var(--muted-foreground)"
|
||||||
|
const Chevron = expanded ? ChevronDownIcon : ChevronRightIcon
|
||||||
|
const health = problems ? `Проблемы · ${problems}` : unknownCount ? `Нет данных · ${unknownCount}` : ""
|
||||||
|
const label = [name, `${code} × ${count}`, health, problems && unknownCount ? `Нет данных · ${unknownCount}` : ""].filter(Boolean).join(" · ")
|
||||||
|
return <g transform={`translate(${x - width / 2},${y - height / 2})`} data-map-group={id}
|
||||||
|
role="button" tabIndex={visible ? 0 : -1} aria-expanded={expanded} aria-label={`${expanded ? "Свернуть" : "Раскрыть"} группу · ${label}`}
|
||||||
|
className="network-map-focusable cursor-pointer" opacity={visible ? 1 : 0.1}
|
||||||
|
onPointerDown={event => event.stopPropagation()} onClick={event => { event.stopPropagation(); onToggle() }}
|
||||||
|
onKeyDown={event => activate(event, onToggle)}>
|
||||||
|
<title>{label}</title>
|
||||||
|
<rect className="network-map-focus-ring" x="-4" y="-4" width={width + 8} height={height + 8} rx="14" fill="none" stroke="var(--ring)" strokeWidth="2" />
|
||||||
|
<rect data-map-box="group" width={width} height={height} rx="11" fill="var(--card)" stroke={problems ? "var(--warning)" : "var(--border)"} strokeWidth="1.5" strokeDasharray={expanded ? "4 3" : undefined} />
|
||||||
|
<rect x="8" y="7" width="50" height="19" rx="5" fill={color} fillOpacity=".15" />
|
||||||
|
<text x="33" y="20" textAnchor="middle" fill={color} fontSize="10.5" fontFamily="Geist Mono,monospace" fontWeight="600">{code} ×{count}</text>
|
||||||
|
<text x="64" y="20" fill={problems ? "var(--status-degraded-fg)" : "var(--muted-foreground)"} fontSize="10.5">{health}</text>
|
||||||
|
<Chevron x={width - 19} y="32" width="14" height="14" color="var(--muted-foreground)" />
|
||||||
|
<text x="10" y="43" fill="var(--foreground)" fontSize={name.length > 18 ? 11 : 12} fontWeight="600">{name.length > 21 ? name.slice(0, 20) + "…" : name}</text>
|
||||||
|
</g>
|
||||||
|
}
|
||||||
|
|
||||||
|
const linkNames: Record<MapGroupLink["type"], string> = {
|
||||||
|
gre: "GRE", "wan-jh": "WAN → JH", wan: "WAN", ix: "IX", user: "Привязки", service: "Пути к назначению", observation: "Наблюдения IPFIX",
|
||||||
|
}
|
||||||
|
|
||||||
|
function linkColor(link: MapGroupLink) {
|
||||||
|
if (link.down === link.count) return "var(--status-offline)"
|
||||||
|
if (link.down || link.degraded) return "var(--status-degraded)"
|
||||||
|
if (link.type === "gre") return "var(--status-online)"
|
||||||
|
if (link.type === "user") return "var(--chart-2)"
|
||||||
|
if (link.type === "service" || link.type === "ix") return "var(--chart-4)"
|
||||||
|
return "var(--muted-foreground)"
|
||||||
|
}
|
||||||
|
|
||||||
|
export function MapGroupLinks({ links, obstacles, onExpand, layer = "all" }: {
|
||||||
|
links: MapGroupLink[]; obstacles: MapBox[]; onExpand: (ids: string[]) => void; layer?: "all" | "lines" | "labels"
|
||||||
|
}) {
|
||||||
|
// Place outage labels first so that a routine count cannot occupy their available space.
|
||||||
|
const entries = [...links].sort((a, b) => b.down - a.down || b.degraded - a.degraded).map(row => {
|
||||||
|
const type = linkNames[row.type], color = linkColor(row)
|
||||||
|
const summary = [`${type} ×${row.count}`, row.down ? `недоступно ${row.down} из ${row.count}` : "", row.degraded ? `ухудшено · ${row.degraded}` : ""].filter(Boolean).join(" · ")
|
||||||
|
const texts = row.down ? [`Недоступно ${row.down} из ${row.count}`, `↓ ${row.down}/${row.count}`] :
|
||||||
|
row.degraded ? [`Ухудшено ${row.degraded} из ${row.count}`, `! ${row.degraded}/${row.count}`] : [`${type} ×${row.count}`, `×${row.count}`]
|
||||||
|
return { ...row, color, texts, title: `${row.from.name} → ${row.to.name} · ${summary}` }
|
||||||
|
})
|
||||||
|
const labels = layer === "lines" ? [] : placeMapLinkLabels(entries, obstacles)
|
||||||
|
return <>
|
||||||
|
{layer !== "labels" && entries.map(row => (
|
||||||
|
<g key={row.id} data-map-group-link={row.type} data-channel-count={row.count} data-channel-down={row.down} role="button" tabIndex={0}
|
||||||
|
aria-label={`${row.title} · Раскрыть группу`} className="network-map-focusable cursor-pointer"
|
||||||
|
onPointerDown={event => event.stopPropagation()} onClick={event => { event.stopPropagation(); onExpand(row.groups) }}
|
||||||
|
onKeyDown={event => activate(event, () => onExpand(row.groups))}>
|
||||||
|
<title>{row.title}</title>
|
||||||
|
<path className="network-map-focus-ring" d={row.link.d} fill="none" stroke="var(--ring)" strokeWidth="6" />
|
||||||
|
<path d={row.link.d} fill="none" stroke={row.color} strokeWidth={row.type === "gre" ? 2.5 : 1.7}
|
||||||
|
strokeDasharray={row.down || row.degraded || row.type === "observation" ? "5 4" : undefined} strokeLinecap="round" />
|
||||||
|
<path d={row.link.d} fill="none" stroke="transparent" strokeWidth="16" />
|
||||||
|
</g>
|
||||||
|
))}
|
||||||
|
{labels.map(row => (
|
||||||
|
<g key={row.id} transform={`translate(${row.x},${row.y})`} data-map-group-link-label={row.type} className="cursor-pointer" aria-hidden="true"
|
||||||
|
onPointerDown={event => event.stopPropagation()} onClick={event => { event.stopPropagation(); onExpand(row.groups) }}>
|
||||||
|
<title>{row.title}</title>
|
||||||
|
<rect data-map-box="pill" x={-row.w / 2} y="-10" width={row.w} height="20" rx="10" fill="var(--card)" stroke={row.down || row.degraded ? row.color : "var(--border)"} />
|
||||||
|
<text textAnchor="middle" dy="4" fill={row.down === row.count ? "var(--status-offline-fg)" : row.down || row.degraded ? "var(--status-degraded-fg)" : "var(--foreground)"} fontSize="11" fontFamily="Geist Mono,monospace">{row.text}</text>
|
||||||
|
</g>
|
||||||
|
))}
|
||||||
|
</>
|
||||||
|
}
|
||||||
@@ -17,6 +17,7 @@ import { projectTrafficObservations } from "@/lib/traffic-observations"
|
|||||||
import { getFlowAnalytics, getFlowMapHops } from "@/shared/api/traffic-flow"
|
import { getFlowAnalytics, getFlowMapHops } from "@/shared/api/traffic-flow"
|
||||||
import { requestJson } from "@/shared/api/http-client"
|
import { requestJson } from "@/shared/api/http-client"
|
||||||
import { matchesMapService } from "@/lib/flow-map-service-match"
|
import { matchesMapService } from "@/lib/flow-map-service-match"
|
||||||
|
import { mapTrafficCategory } from "@/lib/map-traffic-category"
|
||||||
|
|
||||||
const evidenceLabel: Record<FlowServiceBasis, string> = {
|
const evidenceLabel: Record<FlowServiceBasis, string> = {
|
||||||
catalog: "По каталогу",
|
catalog: "По каталогу",
|
||||||
@@ -27,6 +28,27 @@ const evidenceLabel: Record<FlowServiceBasis, string> = {
|
|||||||
}
|
}
|
||||||
const percent = new Intl.NumberFormat("ru-RU", {style: "percent", maximumFractionDigits: 1})
|
const percent = new Intl.NumberFormat("ru-RU", {style: "percent", maximumFractionDigits: 1})
|
||||||
|
|
||||||
|
function CategoryEvidence({service, path, onCategory}: {
|
||||||
|
service: FlowMapService
|
||||||
|
path?: FlowMapServicePath
|
||||||
|
onCategory?: (category: string) => void
|
||||||
|
}) {
|
||||||
|
const category = mapTrafficCategory(service, path)
|
||||||
|
const observation = path ?? service
|
||||||
|
const evidence = observation.serviceEvidence ?? []
|
||||||
|
return <div className="space-y-1.5 text-xs">
|
||||||
|
<div className="flex flex-wrap items-baseline gap-x-2">
|
||||||
|
<span className="text-muted-foreground">Категория трафика</span>
|
||||||
|
{onCategory ? <Button type="button" size="xs" variant="link" className="h-auto p-0" onClick={() => onCategory(category)}>{category}</Button> : <strong>{category}</strong>}
|
||||||
|
</div>
|
||||||
|
{evidence.length ? <ul aria-label="Основание классификации" className="flex flex-wrap gap-1">
|
||||||
|
{evidence.map(row => <li key={row.basis}><Badge size="sm" variant={row.basis === "heuristic" ? "info-light" : "secondary"}>
|
||||||
|
{evidenceLabel[row.basis]}{observation.bytes > 0 && row.bytes < observation.bytes && ` · ${percent.format(row.bytes / observation.bytes)}`}
|
||||||
|
</Badge></li>)}
|
||||||
|
</ul> : <p className="text-muted-foreground">Основание классификации в этом снимке не передано</p>}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
|
||||||
export function InspectorMetrics({ rows }: { rows: [string, ReactNode, string?][] }) {
|
export function InspectorMetrics({ rows }: { rows: [string, ReactNode, string?][] }) {
|
||||||
return <dl className="grid grid-cols-2 gap-px overflow-hidden rounded-t-lg border-b bg-border">
|
return <dl className="grid grid-cols-2 gap-px overflow-hidden rounded-t-lg border-b bg-border">
|
||||||
{rows.map(([name, value, title]) => <div key={name} title={title} className="flex min-w-0 flex-col gap-0.5 bg-card px-3.5 py-2.5">
|
{rows.map(([name, value, title]) => <div key={name} title={title} className="flex min-w-0 flex-col gap-0.5 bg-card px-3.5 py-2.5">
|
||||||
@@ -112,11 +134,13 @@ export function NodeHistory({ base, id, refresh, degraded }: { base: string | nu
|
|||||||
</>
|
</>
|
||||||
}
|
}
|
||||||
|
|
||||||
export function ServiceInspector({ service, paths, exits, exitName, country, base, refresh, windowLabel, history, shareOfVisible, flowAt, stale, activePath, onPath, onClose, filtered, onFilter, userId, ix, topology }: {
|
export function ServiceInspector({ service, paths, exits, exitName, country, base, refresh, windowLabel, history, shareOfVisible, shareKnown = true, flowAt, stale, activePath, onPath, onClose, onCategory, filtered, onFilter, userId, ix, topology }: {
|
||||||
service: FlowMapService; paths: FlowMapServicePath[]; exits: FlowMapServiceEdge[]; exitName: (id: string) => string
|
service: FlowMapService; paths: FlowMapServicePath[]; exits: FlowMapServiceEdge[]; exitName: (id: string) => string
|
||||||
country?: string; base: string | null; refresh: number; windowLabel: string; flowAt: string | null; stale: boolean
|
country?: string; base: string | null; refresh: number; windowLabel: string; flowAt: string | null; stale: boolean
|
||||||
history?: {service?: FlowMapService; window: string}
|
history?: {service?: FlowMapService; window: string}
|
||||||
shareOfVisible: boolean
|
shareOfVisible: boolean
|
||||||
|
shareKnown?: boolean
|
||||||
|
onCategory?: (category: string) => void
|
||||||
activePath: FlowMapServicePath | null; onPath: (path: FlowMapServicePath) => void
|
activePath: FlowMapServicePath | null; onPath: (path: FlowMapServicePath) => void
|
||||||
onClose: () => void; filtered: boolean; onFilter: () => void
|
onClose: () => void; filtered: boolean; onFilter: () => void
|
||||||
userId?: string; ix?: boolean; topology?: ReadonlySet<string>
|
userId?: string; ix?: boolean; topology?: ReadonlySet<string>
|
||||||
@@ -151,7 +175,7 @@ export function ServiceInspector({ service, paths, exits, exitName, country, bas
|
|||||||
const countryFilter = service.id.startsWith("cc:other|") ? "unknown" : country
|
const countryFilter = service.id.startsWith("cc:other|") ? "unknown" : country
|
||||||
const flows = recent?.data.conversationsList.filter(row => (!topology || topology.has(row.enId || row.serverId)) && matchesMapService(row, service.label, countryFilter))
|
const flows = recent?.data.conversationsList.filter(row => (!topology || topology.has(row.enId || row.serverId)) && matchesMapService(row, service.label, countryFilter))
|
||||||
.sort((a, b) => b.bps - a.bps).slice(0, 5) ?? []
|
.sort((a, b) => b.bps - a.bps).slice(0, 5) ?? []
|
||||||
const asns = [...new Set(flows.flatMap(flow => flow.dstAsn ? [flow.dstAsn] : []))]
|
const selectedPath = activePath && paths.find(path => servicePathKey(path) === servicePathKey(activePath))
|
||||||
const rates = [...exits].sort((a, b) => b.bps - a.bps)
|
const rates = [...exits].sort((a, b) => b.bps - a.bps)
|
||||||
const exitIds = [...new Set([...rates.filter(e => !e.observedOnly).map(e => e.fromId), ...paths.map(p => p.enId).filter(Boolean)])]
|
const exitIds = [...new Set([...rates.filter(e => !e.observedOnly).map(e => e.fromId), ...paths.map(p => p.enId).filter(Boolean)])]
|
||||||
const exporterIds = [...new Set([...rates.filter(e => e.observedOnly).map(e => e.fromId), ...paths.filter(p => !p.enId).map(p => p.viaId)])]
|
const exporterIds = [...new Set([...rates.filter(e => e.observedOnly).map(e => e.fromId), ...paths.filter(p => !p.enId).map(p => p.viaId)])]
|
||||||
@@ -163,7 +187,6 @@ export function ServiceInspector({ service, paths, exits, exitName, country, bas
|
|||||||
const averageWindow = history?.window ?? windowLabel
|
const averageWindow = history?.window ?? windowLabel
|
||||||
const volumeBytes = currentVolume ? average?.bytes : volume?.bytes
|
const volumeBytes = currentVolume ? average?.bytes : volume?.bytes
|
||||||
const trafficTypes = service.trafficTypes ?? []
|
const trafficTypes = service.trafficTypes ?? []
|
||||||
const serviceEvidence = service.serviceEvidence ?? []
|
|
||||||
const otherTypeBytes = Math.max(0, service.bytes - trafficTypes.reduce((sum, row) => sum + row.bytes, 0))
|
const otherTypeBytes = Math.max(0, service.bytes - trafficTypes.reduce((sum, row) => sum + row.bytes, 0))
|
||||||
const typeShare = (bytes: number) => percent.format(Math.min(1, bytes / service.bytes))
|
const typeShare = (bytes: number) => percent.format(Math.min(1, bytes / service.bytes))
|
||||||
const trafficQuery = new URLSearchParams({ view: "flows", service: service.label, serviceId: service.id, from: "map" })
|
const trafficQuery = new URLSearchParams({ view: "flows", service: service.label, serviceId: service.id, from: "map" })
|
||||||
@@ -180,39 +203,42 @@ export function ServiceInspector({ service, paths, exits, exitName, country, bas
|
|||||||
<header className="flex items-center gap-2 px-3 py-3">
|
<header className="flex items-center gap-2 px-3 py-3">
|
||||||
<div className="grid size-8 shrink-0 place-items-center rounded-md bg-muted"><ServiceBrandIcon label={service.label} size={18} /></div>
|
<div className="grid size-8 shrink-0 place-items-center rounded-md bg-muted"><ServiceBrandIcon label={service.label} size={18} /></div>
|
||||||
<div className="min-w-0 flex-1"><h2 className="truncate text-sm font-semibold" title={service.label}>{service.label}</h2>
|
<div className="min-w-0 flex-1"><h2 className="truncate text-sm font-semibold" title={service.label}>{service.label}</h2>
|
||||||
<p className="truncate text-[11px] text-muted-foreground" title={flowAt ? new Date(flowAt).toLocaleString("ru-RU") : undefined}>{[service.category, asns.length === 1 ? "AS" + asns[0] : null, country, windowLabel].filter(Boolean).join(" · ")}</p></div>
|
<p className="truncate text-[11px] text-muted-foreground" title={flowAt ? new Date(flowAt).toLocaleString("ru-RU") : undefined}>{[country, "IPFIX", windowLabel].filter(Boolean).join(" · ")}</p></div>
|
||||||
<Badge size="sm" variant={observed ? "success-light" : "secondary"} title="Наличие трафика в окне NetFlow"><span aria-hidden>•</span>{stale ? "Архив" : observed ? "Есть трафик" : "Нет трафика"}</Badge>
|
<Badge size="sm" variant={observed ? "success-light" : "secondary"} title="Наличие трафика в окне NetFlow"><span aria-hidden>•</span>{stale ? "Архив" : observed ? "Есть трафик" : "Нет трафика"}</Badge>
|
||||||
<Button size="icon-xs" variant="ghost" aria-label="Закрыть детали назначения" onClick={onClose}><XIcon /></Button>
|
<Button size="icon-xs" variant="ghost" aria-label="Закрыть детали назначения" onClick={onClose}><XIcon /></Button>
|
||||||
</header>
|
</header>
|
||||||
<div className="mx-0.5 mb-0.5 min-h-0 overflow-y-auto rounded-lg border">
|
<div className="mx-0.5 mb-0.5 min-h-0 overflow-y-auto rounded-lg border">
|
||||||
<InspectorMetrics rows={[
|
<InspectorMetrics rows={[
|
||||||
["Средняя за " + averageWindow, average ? formatNetflowRate(average) : "—", "Скорость по сохранённым потокам IPFIX"],
|
["Средняя за " + averageWindow, average ? formatNetflowRate(average) : "—", "Скорость по сохранённым потокам IPFIX"],
|
||||||
[shareOfVisible ? "Доля показанных сервисов" : country ? "Доля страны" : "Доля трафика", percent.format(service.share), "IPFIX · " + windowLabel],
|
[shareOfVisible ? "Доля показанных сервисов" : country ? "Доля страны" : "Доля трафика", shareKnown ? percent.format(service.share) : "Нет данных", "IPFIX · " + windowLabel],
|
||||||
["Объём · " + (currentVolume ? averageWindow : volume?.window ?? "24 ч"), <>{volumeBytes == null ? "—" : formatBytes(volumeBytes)}{!currentVolume && volume && <time dateTime={volume.at} title={new Date(volume.at).toLocaleString("ru-RU")} className="block text-[10px] font-normal text-muted-foreground">ответ {new Date(volume.at).toLocaleTimeString("ru-RU")}</time>}</>],
|
["Объём · " + (currentVolume ? averageWindow : volume?.window ?? "24 ч"), <>{volumeBytes == null ? "—" : formatBytes(volumeBytes)}{!currentVolume && volume && <time dateTime={volume.at} title={new Date(volume.at).toLocaleString("ru-RU")} className="block text-[10px] font-normal text-muted-foreground">ответ {new Date(volume.at).toLocaleTimeString("ru-RU")}</time>}</>],
|
||||||
exitIds.length || !exporterIds.length
|
exitIds.length || !exporterIds.length
|
||||||
? ["Exit-узел", exitIds.map(exitName).join(", ") || "—", remainder || exporterIds.length ? "Часть трафика без подтверждённого выхода" : undefined]
|
? ["Exit-узел", exitIds.map(exitName).join(", ") || "—", remainder || exporterIds.length ? "Часть трафика без подтверждённого выхода" : undefined]
|
||||||
: ["Экспортёр", exporterIds.map(exitName).join(", "), "Наблюдение IPFIX, дальнейший маршрут не подтверждён"],
|
: ["Экспортёр", exporterIds.map(exitName).join(", "), "Наблюдение IPFIX, дальнейший маршрут не подтверждён"],
|
||||||
]} />
|
]} />
|
||||||
{trafficTypes.length > 0 && service.bytes > 0 && <section className="space-y-2 border-b px-3.5 py-3 text-xs" aria-label="Состав трафика IPFIX">
|
{selectedPath && <section aria-label="Выбранный поток" className="space-y-2 border-b px-3.5 py-3 text-xs">
|
||||||
|
<h3 className="font-medium">Выбранный поток</h3>
|
||||||
|
<p className="break-words">{[selectedPath.clientId === "—" ? "Без привязки" : selectedPath.clientName, selectedPath.viaName || selectedPath.viaId, selectedPath.enId !== selectedPath.viaId && (selectedPath.enName || selectedPath.enId), service.label].filter(Boolean).join(" → ")}</p>
|
||||||
|
<p>{selectedPath.enId ? "Выход подтверждён" : "Наблюдение IPFIX · выход не подтверждён"}</p>
|
||||||
|
<CategoryEvidence service={service} path={selectedPath} onCategory={onCategory} />
|
||||||
|
{selectedPath.trafficTypes?.map(row => <p key={JSON.stringify([row.application,row.transport])} className="text-muted-foreground">
|
||||||
|
{[row.application,row.transport].filter(Boolean).join(" · ")} · {formatBytes(row.bytes)}
|
||||||
|
</p>)}
|
||||||
|
<p className="font-mono tabular-nums">IPFIX · среднее за {windowLabel} · {formatNetflowRate(selectedPath)} · {formatBytes(selectedPath.bytes)}</p>
|
||||||
|
</section>}
|
||||||
|
<section className="space-y-2 border-b px-3.5 py-3 text-xs" aria-label="Состав трафика IPFIX">
|
||||||
<h3 className="flex justify-between gap-2 font-medium"><span>Состав трафика</span><span className="font-normal text-muted-foreground">IPFIX · {windowLabel}</span></h3>
|
<h3 className="flex justify-between gap-2 font-medium"><span>Состав трафика</span><span className="font-normal text-muted-foreground">IPFIX · {windowLabel}</span></h3>
|
||||||
<dl className="space-y-1">
|
<CategoryEvidence service={service} onCategory={onCategory} />
|
||||||
|
{trafficTypes.length > 0 && service.bytes > 0 && <dl className="space-y-1">
|
||||||
{trafficTypes.map(({transport, application, bytes}) => <div key={JSON.stringify([transport, application])} className="flex justify-between gap-2">
|
{trafficTypes.map(({transport, application, bytes}) => <div key={JSON.stringify([transport, application])} className="flex justify-between gap-2">
|
||||||
<dt>{application ? `${application} · ${transport}` : transport}</dt>
|
<dt>{application ? `${application} · ${transport}` : transport}</dt>
|
||||||
<dd className="shrink-0 font-mono tabular-nums">{typeShare(bytes)}</dd>
|
<dd className="shrink-0 font-mono tabular-nums">{typeShare(bytes)}</dd>
|
||||||
</div>)}
|
</div>)}
|
||||||
{otherTypeBytes > 0 && <div className="flex justify-between gap-2"><dt>Остальные типы</dt><dd className="font-mono tabular-nums">{typeShare(otherTypeBytes)}</dd></div>}
|
{otherTypeBytes > 0 && <div className="flex justify-between gap-2"><dt>Остальные типы</dt><dd className="font-mono tabular-nums">{typeShare(otherTypeBytes)}</dd></div>}
|
||||||
</dl>
|
</dl>}
|
||||||
{trafficTypes.some(row => row.application) && <p className="text-muted-foreground">Приложения определены по портам.</p>}
|
{trafficTypes.some(row => row.application) && <p className="text-muted-foreground">Приложения определены по портам.</p>}
|
||||||
{service.lastBucketAt && <p className="text-muted-foreground">Последняя минута с потоками <time dateTime={service.lastBucketAt} className="font-mono">{new Date(service.lastBucketAt).toLocaleTimeString("ru-RU", {hour: "2-digit", minute: "2-digit"})}</time></p>}
|
{service.lastBucketAt && <p className="text-muted-foreground">Последняя минута с потоками <time dateTime={service.lastBucketAt} className="font-mono">{new Date(service.lastBucketAt).toLocaleTimeString("ru-RU", {hour: "2-digit", minute: "2-digit"})}</time></p>}
|
||||||
{serviceEvidence.length ? <ul aria-label="Основание классификации" className="flex flex-wrap gap-1">
|
</section>
|
||||||
{serviceEvidence.map(row => <li key={row.basis}>
|
|
||||||
<Badge size="sm" variant={row.basis === "heuristic" ? "info-light" : "secondary"}
|
|
||||||
title={row.basis === "heuristic" ? "Сервис предполагается по сети назначения и порту 443" : undefined}>
|
|
||||||
{evidenceLabel[row.basis]}{serviceEvidence.length > 1 && ` · ${typeShare(row.bytes)}`}
|
|
||||||
</Badge>
|
|
||||||
</li>)}
|
|
||||||
</ul> : null}
|
|
||||||
</section>}
|
|
||||||
<InspectorUsers users={serviceUsers(service, paths)} windowLabel={windowLabel} />
|
<InspectorUsers users={serviceUsers(service, paths)} windowLabel={windowLabel} />
|
||||||
<section className="space-y-2 border-b px-3.5 py-3"><h3 className="text-[11px] text-muted-foreground">Путь трафика</h3>
|
<section className="space-y-2 border-b px-3.5 py-3"><h3 className="text-[11px] text-muted-foreground">Путь трафика</h3>
|
||||||
{paths.map(p => {
|
{paths.map(p => {
|
||||||
@@ -222,26 +248,27 @@ export function ServiceInspector({ service, paths, exits, exitName, country, bas
|
|||||||
const active = activePath && servicePathKey(activePath) === key
|
const active = activePath && servicePathKey(activePath) === key
|
||||||
return <button type="button" key={key} onClick={() => onPath(p)} aria-pressed={Boolean(active)} title={formatNetflowRate(p)} className={cn("flex w-full flex-wrap items-center gap-1 rounded-sm text-left", active && "ring-1 ring-primary")}>
|
return <button type="button" key={key} onClick={() => onPath(p)} aria-pressed={Boolean(active)} title={formatNetflowRate(p)} className={cn("flex w-full flex-wrap items-center gap-1 rounded-sm text-left", active && "ring-1 ring-primary")}>
|
||||||
{parts.map((name, i) => <span key={i} className="inline-flex max-w-full items-center gap-1">{i > 0 && <ChevronRightIcon aria-hidden className="size-3 shrink-0 text-muted-foreground" />}<span className={cn("truncate rounded-md bg-muted px-1.5 py-1 font-mono text-[10px] font-semibold", i === parts.length - 1 && "bg-chart-4/20")}>{name}</span></span>)}
|
{parts.map((name, i) => <span key={i} className="inline-flex max-w-full items-center gap-1">{i > 0 && <ChevronRightIcon aria-hidden className="size-3 shrink-0 text-muted-foreground" />}<span className={cn("truncate rounded-md bg-muted px-1.5 py-1 font-mono text-[10px] font-semibold", i === parts.length - 1 && "bg-chart-4/20")}>{name}</span></span>)}
|
||||||
{!p.enId && <span className="basis-full text-[10px] text-muted-foreground">
|
<span className="basis-full text-[10px] text-muted-foreground">{p.enId ? "Выход подтверждён" :
|
||||||
Наблюдение IPFIX{p.viaIface ? ` · интерфейс ${p.viaIface}` : ""} · выход не подтверждён
|
`Наблюдение IPFIX${p.viaIface ? ` · интерфейс ${p.viaIface}` : ""} · выход не подтверждён`}</span>
|
||||||
</span>}
|
|
||||||
</button>
|
</button>
|
||||||
})}
|
})}
|
||||||
{rates.filter(e => !paths.some(p => (p.enId || p.viaId) === e.fromId && Boolean(p.enId) !== Boolean(e.observedOnly))).map(e => <div key={e.fromId} className="flex justify-between gap-2 text-xs"><span>{exitName(e.fromId)} → {service.label}{e.observedOnly && " · наблюдение IPFIX"}</span><span className="shrink-0 font-mono">{formatNetflowRate(e)}</span></div>)}
|
{rates.filter(e => !paths.some(p => (p.enId || p.viaId) === e.fromId && Boolean(p.enId) !== Boolean(e.observedOnly))).map(e => <div key={e.fromId} className="flex justify-between gap-2 text-xs"><span>{exitName(e.fromId)} → {service.label}{e.observedOnly && " · наблюдение IPFIX"}</span><span className="shrink-0 font-mono">{formatNetflowRate(e)}</span></div>)}
|
||||||
{remainder > 0 && <div className="flex justify-between gap-2 text-xs text-muted-foreground"><span>Выход не определён</span><span className="font-mono">{formatNetflowRate({bps:service.bps * remainder / service.bytes})}</span></div>}
|
{remainder > 0 && <div className="flex justify-between gap-2 text-xs text-muted-foreground"><span>Выход не определён</span><span className="font-mono">{formatNetflowRate({bps:service.bps * remainder / service.bytes})}</span></div>}
|
||||||
{!paths.length && !rates.length && !remainder && <p className="text-xs text-muted-foreground">Маршрут не определён</p>}
|
{!paths.length && !rates.length && !remainder && <p className="text-xs text-muted-foreground">Маршрут не определён</p>}
|
||||||
</section>
|
</section>
|
||||||
<section className="space-y-3 border-b px-3.5 py-3"><h3 className="flex items-center justify-between font-mono text-[11px] text-muted-foreground"><span>Крупные потоки · {recent?.data.sourceWindow?.effectiveMinutes ?? 5} мин</span><span title="Наблюдения экспортёров">{recent ? flows.length : "—"}</span></h3>
|
<section className="space-y-3 border-b px-3.5 py-3"><h3 className="flex items-center justify-between font-mono text-[11px] text-muted-foreground"><span>Крупные потоки · IPFIX{recent ? ` · ${recent.data.sourceWindow?.effectiveMinutes ?? 5} мин` : ""}</span><span title="Наблюдения экспортёров">{recent ? flows.length : "—"}</span></h3>
|
||||||
{flows.map((f,i) => {
|
{flows.map((f,i) => {
|
||||||
const port = f.internetPeerPort || f.dstPort
|
const port = f.internetPeerPort ?? (f.direction === "to_client" ? f.srcPort : f.dstPort)
|
||||||
const transport = port ? `${f.protoName}/${port}` : f.protoName
|
const transport = port ? `${f.protoName}/${port}` : f.protoName
|
||||||
return <div key={i} className="flex items-center gap-2 text-xs">
|
return <div key={i} className="flex items-center gap-2 text-xs">
|
||||||
<span aria-hidden className="size-1.5 shrink-0 rounded-full bg-[var(--status-online)]" />
|
<span aria-hidden className="size-1.5 shrink-0 rounded-full bg-[var(--status-online)]" />
|
||||||
<div className="min-w-0 flex-1">
|
<div className="min-w-0 flex-1">
|
||||||
<p className="font-medium [overflow-wrap:anywhere]">{f.src} → {f.dst}</p>
|
<p className="font-medium [overflow-wrap:anywhere]">{f.src} → {f.dst}</p>
|
||||||
<p className="truncate text-[11px] text-muted-foreground" title={`Экспортёр: ${f.serverName || f.serverId}`}>
|
<p className="truncate text-[11px] text-muted-foreground" title={`Экспортёр: ${f.serverName || f.serverId}`}>
|
||||||
{transport}{f.application && f.application !== transport && f.application !== f.protoName && ` · ${f.application}`} · {f.serverName || f.serverId}
|
{[transport, f.application !== transport && f.application !== f.protoName && f.application, f.serverName || f.serverId].filter(Boolean).join(" · ")}
|
||||||
</p>
|
</p>
|
||||||
|
<p className="text-[11px] text-muted-foreground">{[mapTrafficCategory(f), f.serviceBasis ? evidenceLabel[f.serviceBasis] : "Основание не передано", f.dstAsn && "AS" + f.dstAsn].filter(Boolean).join(" · ")}</p>
|
||||||
|
<p className="text-[11px] text-muted-foreground">{f.enId ? `Выход подтверждён · ${f.enName || f.enId}` : "Наблюдение IPFIX · выход не подтверждён"}</p>
|
||||||
</div>
|
</div>
|
||||||
<span className="font-mono text-[11px] text-muted-foreground">{formatNetflowRate({bps:f.bps})}</span>
|
<span className="font-mono text-[11px] text-muted-foreground">{formatNetflowRate({bps:f.bps})}</span>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import { useState, type ReactNode } from "react"
|
import { useMemo, useState, type ReactNode } from "react"
|
||||||
import { ChevronDownIcon, ChevronUpIcon } from "lucide-react"
|
import { ChevronDownIcon, ChevronUpIcon } from "lucide-react"
|
||||||
import { FramePanel } from "@/components/reui/frame"
|
import { FramePanel } from "@/components/reui/frame"
|
||||||
import { Badge } from "@/components/reui/badge"
|
import { Badge } from "@/components/reui/badge"
|
||||||
@@ -8,10 +8,16 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
|||||||
import { SectionFrame, ToneBadge, TONE_COLOR, type Tone } from "@/components/reui-kit/ops-blocks"
|
import { SectionFrame, ToneBadge, TONE_COLOR, type Tone } from "@/components/reui-kit/ops-blocks"
|
||||||
import { cn } from "@/lib/utils"
|
import { cn } from "@/lib/utils"
|
||||||
import { Button } from "@/components/ui/button"
|
import { Button } from "@/components/ui/button"
|
||||||
|
import { CompactDataGrid, type CompactDataGridColumn } from "@/components/data-grids/compact-data-grid"
|
||||||
|
import { ServiceBrandIcon } from "@/components/network-map/service-brand-icon"
|
||||||
|
import { Flag } from "@/components/flag"
|
||||||
|
|
||||||
export type MapFlowRow = { id: string; client: string; exit: string; dest: string; rate: string; volume: string; hl: boolean }
|
export type MapFlowRow = { id: string; client: string; exit: string; dest: string; rate: string; volume: string; hl: boolean }
|
||||||
export type MapRttRow = { id: string; name: string; route: string; rtt: string; speed: string; tone: Tone; status: string; hl: boolean }
|
export type MapRttRow = { id: string; name: string; route: string; rtt: string; speed: string; tone: Tone; status: string; hl: boolean }
|
||||||
export type MapDestRow = { id: string; label: string; category: string; rate: string; share: number; hl: boolean }
|
export type MapDestRow = {
|
||||||
|
id: string; label: string; category: string; rate: string; bps: number; share: number | null; hl: boolean
|
||||||
|
kind?: "service" | "country" | "category"; countryCode?: string
|
||||||
|
}
|
||||||
export type MapEventRow = { id: string; ts: number; tone: Tone; label: string; title: string; message: string; serverId?: string }
|
export type MapEventRow = { id: string; ts: number; tone: Tone; label: string; title: string; message: string; serverId?: string }
|
||||||
export type MapBottomTab = "flows" | "rtt" | "dest" | "events"
|
export type MapBottomTab = "flows" | "rtt" | "dest" | "events"
|
||||||
|
|
||||||
@@ -34,14 +40,43 @@ function Row({ cols, hl, children }: { cols: string; hl?: boolean; children: Rea
|
|||||||
|
|
||||||
const FLOW_COLS = "grid-cols-[minmax(160px,1.4fr)_minmax(120px,1fr)_minmax(140px,1.2fr)_110px_100px]"
|
const FLOW_COLS = "grid-cols-[minmax(160px,1.4fr)_minmax(120px,1fr)_minmax(140px,1.2fr)_110px_100px]"
|
||||||
const RTT_COLS = "grid-cols-[minmax(140px,1fr)_minmax(200px,1.6fr)_90px_minmax(120px,1fr)_110px]"
|
const RTT_COLS = "grid-cols-[minmax(140px,1fr)_minmax(200px,1.6fr)_90px_minmax(120px,1fr)_110px]"
|
||||||
const DEST_COLS = "grid-cols-[minmax(160px,1.4fr)_minmax(120px,1fr)_110px_minmax(140px,1fr)]"
|
|
||||||
const EVENT_COLS = "grid-cols-[70px_110px_minmax(200px,1.4fr)_minmax(200px,2fr)]"
|
const EVENT_COLS = "grid-cols-[70px_110px_minmax(200px,1.4fr)_minmax(200px,2fr)]"
|
||||||
|
|
||||||
|
function Destinations({ rows, onDestination, onCategory }: {
|
||||||
|
rows: MapDestRow[]
|
||||||
|
onDestination: (id: string) => void
|
||||||
|
onCategory?: (category: string) => void
|
||||||
|
}) {
|
||||||
|
const columns = useMemo<CompactDataGridColumn<MapDestRow>[]>(() => [
|
||||||
|
{ id: "label", header: "Назначение", size: 125, cell: row => (
|
||||||
|
<Button type="button" variant="link" size="xs" className="max-w-full justify-start" title={row.label}
|
||||||
|
data-map-highlight={row.hl || undefined} onClick={() => onDestination(row.id)}>
|
||||||
|
{row.countryCode ? <span aria-hidden><Flag code={row.countryCode} size={16} /></span> :
|
||||||
|
(row.kind ?? "service") === "service" && <ServiceBrandIcon label={row.label} size={16} />}
|
||||||
|
<span className="truncate">{row.label}</span>
|
||||||
|
</Button>
|
||||||
|
) },
|
||||||
|
{ id: "category", header: "Категория", size: 145, cell: row => onCategory && (row.kind ?? "service") === "service" ?
|
||||||
|
<Button type="button" variant="link" size="xs" className="max-w-full justify-start" title={row.category}
|
||||||
|
onClick={() => onCategory(row.category)}><span className="truncate">{row.category}</span></Button> :
|
||||||
|
<span className="text-muted-foreground">{row.category}</span> },
|
||||||
|
{ id: "bps", header: "Скорость", size: 124, cell: row => <span className="font-mono tabular-nums">{row.rate}</span> },
|
||||||
|
{ id: "share", header: "Доля окна", size: 145, cell: row => row.share == null ? "Нет данных" :
|
||||||
|
<span className="flex items-center gap-2">
|
||||||
|
<span aria-hidden className="bg-muted h-1.5 w-14 overflow-hidden rounded-full"><i className="block h-full rounded-full bg-chart-4" style={{width: `${Math.round(row.share * 100)}%`}} /></span>
|
||||||
|
<span className="font-mono text-xs tabular-nums">{Math.round(row.share * 100)}%</span>
|
||||||
|
</span> },
|
||||||
|
], [onDestination, onCategory])
|
||||||
|
return <div className="max-h-[min(34svh,310px)] overflow-y-auto [&_tr:has([data-map-highlight])]:bg-primary/8">
|
||||||
|
<CompactDataGrid data={rows} columns={columns} horizontalScroll emptyTitle="Назначений за окно нет" />
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Рабочая панель под картой (макет v3): потоки NetFlow, RTT каналов, назначения и события.
|
* Рабочая панель под картой (макет v3): потоки NetFlow, RTT каналов, назначения и события.
|
||||||
* Строки выбранного объекта подсвечены.
|
* Строки выбранного объекта подсвечены.
|
||||||
*/
|
*/
|
||||||
export function MapBottomPanel({ tab, onTab, open, onOpenChange, flows, rtt, destinations, events, onEvent, onFlow, onDestination, eventsError, stat }: {
|
export function MapBottomPanel({ tab, onTab, open, onOpenChange, flows, rtt, destinations, events, onEvent, onFlow, onDestination, onCategory, eventsError, stat }: {
|
||||||
tab: MapBottomTab
|
tab: MapBottomTab
|
||||||
onTab: (tab: MapBottomTab) => void
|
onTab: (tab: MapBottomTab) => void
|
||||||
open: boolean
|
open: boolean
|
||||||
@@ -53,6 +88,7 @@ export function MapBottomPanel({ tab, onTab, open, onOpenChange, flows, rtt, des
|
|||||||
onEvent: (event: MapEventRow) => void
|
onEvent: (event: MapEventRow) => void
|
||||||
onFlow: (id: string) => void
|
onFlow: (id: string) => void
|
||||||
onDestination: (id: string) => void
|
onDestination: (id: string) => void
|
||||||
|
onCategory?: (category: string) => void
|
||||||
eventsError: string | null
|
eventsError: string | null
|
||||||
stat: string
|
stat: string
|
||||||
}) {
|
}) {
|
||||||
@@ -77,10 +113,10 @@ export function MapBottomPanel({ tab, onTab, open, onOpenChange, flows, rtt, des
|
|||||||
</TabsTrigger>
|
</TabsTrigger>
|
||||||
))}
|
))}
|
||||||
</TabsList></div>
|
</TabsList></div>
|
||||||
{open && <span className="hidden text-xs text-muted-foreground xl:inline">{stat}</span>}
|
|
||||||
<Button type="button" variant="ghost" size="icon-sm" aria-expanded={open} aria-controls="network-map-analysis" aria-label={open ? "Свернуть рабочую панель" : "Открыть рабочую панель"} onClick={() => onOpenChange(!open)}>{open ? <ChevronDownIcon /> : <ChevronUpIcon />}</Button>
|
<Button type="button" variant="ghost" size="icon-sm" aria-expanded={open} aria-controls="network-map-analysis" aria-label={open ? "Свернуть рабочую панель" : "Открыть рабочую панель"} onClick={() => onOpenChange(!open)}>{open ? <ChevronDownIcon /> : <ChevronUpIcon />}</Button>
|
||||||
</div>
|
</div>
|
||||||
<FramePanel id="network-map-analysis" hidden={!open} className="p-0">
|
<FramePanel id="network-map-analysis" hidden={!open} className="p-0">
|
||||||
|
{open && <p className="px-3 py-1 text-[11px] text-muted-foreground">{stat}</p>}
|
||||||
<TabsContent value="flows">
|
<TabsContent value="flows">
|
||||||
<Table head={["Пользователь", "Выход / экспортёр", "Назначение", "Скорость", "Объём"]} cols={FLOW_COLS} empty={flows.length ? null : "NetFlow за окно не прислал потоков к назначениям"}>
|
<Table head={["Пользователь", "Выход / экспортёр", "Назначение", "Скорость", "Объём"]} cols={FLOW_COLS} empty={flows.length ? null : "NetFlow за окно не прислал потоков к назначениям"}>
|
||||||
{flows.map((r) => (
|
{flows.map((r) => (
|
||||||
@@ -108,19 +144,7 @@ export function MapBottomPanel({ tab, onTab, open, onOpenChange, flows, rtt, des
|
|||||||
</Table>
|
</Table>
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
<TabsContent value="dest">
|
<TabsContent value="dest">
|
||||||
<Table head={["Назначение", "Категория", "Скорость", "Доля окна"]} cols={DEST_COLS} empty={destinations.length ? null : "Назначений за окно нет"}>
|
<Destinations rows={destinations} onDestination={onDestination} onCategory={onCategory} />
|
||||||
{destinations.map((r) => (
|
|
||||||
<Row key={r.id} cols={DEST_COLS} hl={r.hl}>
|
|
||||||
<Button type="button" variant="link" size="xs" className="min-w-0 justify-start" onClick={() => onDestination(r.id)}><span className="truncate">{r.label}</span></Button>
|
|
||||||
<span className="text-muted-foreground truncate">{r.category}</span>
|
|
||||||
<span className="font-mono tabular-nums">{r.rate}</span>
|
|
||||||
<span className="flex items-center gap-2">
|
|
||||||
<span className="bg-muted h-1.5 w-20 overflow-hidden rounded-full"><i className="block h-full rounded-full" style={{ width: `${Math.round(Math.min(1, r.share) * 100)}%`, background: "var(--chart-4)" }} /></span>
|
|
||||||
<span className="font-mono text-xs tabular-nums">{Math.round(r.share * 100)}%</span>
|
|
||||||
</span>
|
|
||||||
</Row>
|
|
||||||
))}
|
|
||||||
</Table>
|
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
<TabsContent value="events">
|
<TabsContent value="events">
|
||||||
<div className="flex items-center gap-2 border-b px-3 py-1">
|
<div className="flex items-center gap-2 border-b px-3 py-1">
|
||||||
@@ -149,7 +173,7 @@ export function MapBottomPanel({ tab, onTab, open, onOpenChange, flows, rtt, des
|
|||||||
* «Момент времени» (макет v3): инциденты за 24 часа на шкале и текущий Live-снимок.
|
* «Момент времени» (макет v3): инциденты за 24 часа на шкале и текущий Live-снимок.
|
||||||
* Архив снимков карты не хранится, поэтому прошлые моменты не выбираются.
|
* Архив снимков карты не хранится, поэтому прошлые моменты не выбираются.
|
||||||
*/
|
*/
|
||||||
export function MapTimeline({ events, now, state, onPick }: { events: MapEventRow[]; now: number; state?: string; onPick: (event: MapEventRow) => void }) {
|
export function MapTimeline({ events, now, state, onPick, onJournal }: { events: MapEventRow[]; now: number; state?: string; onPick: (event: MapEventRow) => void; onJournal: () => void }) {
|
||||||
const from = now - 24 * 3_600_000
|
const from = now - 24 * 3_600_000
|
||||||
const hours = new Map<number, MapEventRow[]>()
|
const hours = new Map<number, MapEventRow[]>()
|
||||||
for (const event of events) {
|
for (const event of events) {
|
||||||
@@ -192,7 +216,7 @@ export function MapTimeline({ events, now, state, onPick }: { events: MapEventRo
|
|||||||
<i className="bg-success border-success block size-2.5 rounded-full border-2 shadow-[0_0_0_4px_color-mix(in_oklch,var(--success)_25%,transparent)]" />Live
|
<i className="bg-success border-success block size-2.5 rounded-full border-2 shadow-[0_0_0_4px_color-mix(in_oklch,var(--success)_25%,transparent)]" />Live
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<small className="text-muted-foreground font-mono text-xs">{new Date(now).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" })}</small>
|
<Button type="button" variant="ghost" size="xs" onClick={onJournal}>Журнал</Button>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { ChevronRightIcon } from "lucide-react"
|
||||||
|
import { Button } from "@/components/ui/button"
|
||||||
|
import { StatusBadge } from "@/components/status-badge"
|
||||||
|
import type { Server, ServerType } from "@/lib/data"
|
||||||
|
import type { GreMapEdge } from "@/lib/network-map-layout"
|
||||||
|
import { channelStatus, countGroupGre } from "@/lib/network-map-group-links"
|
||||||
|
import { ruPlural } from "./map-kpi-strip"
|
||||||
|
|
||||||
|
export function mapSiteName(server: Server) {
|
||||||
|
const site = server.site?.trim()
|
||||||
|
return site && site !== "—" ? site : "Без площадки"
|
||||||
|
}
|
||||||
|
|
||||||
|
export function MapChannelList({ edges, selected, onChannel }: {
|
||||||
|
edges: GreMapEdge[]; selected?: GreMapEdge; onChannel: (edge: GreMapEdge) => void
|
||||||
|
}) {
|
||||||
|
return <div className="max-h-56 overflow-y-auto">{edges.map(edge => {
|
||||||
|
const state = channelStatus(edge)
|
||||||
|
return <Button type="button" key={JSON.stringify([edge.tunnel.serverId, edge.tunnel.id])} aria-pressed={selected ? edge === selected : undefined}
|
||||||
|
variant={edge === selected ? "secondary" : "ghost"} className="h-auto min-h-9 w-full justify-between gap-2 whitespace-normal text-left" onClick={() => onChannel(edge)}>
|
||||||
|
<span className="min-w-0 break-words">{edge.tunnel.name}<small className="block text-muted-foreground">{edge.fromServer.name} ↔ {edge.toServer.name}</small></span>
|
||||||
|
<StatusBadge status={state === "up" ? "online" : state === "down" ? "offline" : "degraded"} />
|
||||||
|
</Button>
|
||||||
|
})}</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
export function MapSiteDirectory({ servers, edges, sites, active, onSite, onServer, onChannel, roleLabels }: {
|
||||||
|
servers: Server[]
|
||||||
|
edges: GreMapEdge[]
|
||||||
|
sites: string[]
|
||||||
|
active: string | null
|
||||||
|
onSite: (site: string | null) => void
|
||||||
|
onServer: (server: Server) => void
|
||||||
|
onChannel: (edge: GreMapEdge) => void
|
||||||
|
roleLabels: Record<ServerType, string>
|
||||||
|
}) {
|
||||||
|
const members = new Map<string, Server[]>()
|
||||||
|
for (const server of servers) {
|
||||||
|
const site = mapSiteName(server)
|
||||||
|
if (!members.has(site)) members.set(site, [])
|
||||||
|
members.get(site)!.push(server)
|
||||||
|
}
|
||||||
|
const neighbors = new Map<string, GreMapEdge[]>()
|
||||||
|
for (const edge of edges) {
|
||||||
|
const a = mapSiteName(edge.fromServer), b = mapSiteName(edge.toServer)
|
||||||
|
if (a === b || (active !== a && active !== b)) continue
|
||||||
|
const other = active === a ? b : a
|
||||||
|
if (!neighbors.has(other)) neighbors.set(other, [])
|
||||||
|
neighbors.get(other)!.push(edge)
|
||||||
|
}
|
||||||
|
if (!sites.length) return null
|
||||||
|
return <section aria-label="Площадки" className="space-y-2">
|
||||||
|
<h3 className="text-sm font-semibold">Площадки</h3>
|
||||||
|
<div className="divide-y rounded-lg border">
|
||||||
|
{sites.map(site => {
|
||||||
|
const devices = members.get(site) ?? []
|
||||||
|
const open = site === active
|
||||||
|
const problems = devices.filter(s => s.enabled !== false && (s.status === "offline" || s.status === "degraded")).length
|
||||||
|
return <div key={site}>
|
||||||
|
<Button type="button" variant="ghost" aria-expanded={open} className="h-auto min-h-10 w-full justify-start gap-2 whitespace-normal px-3 text-left" onClick={() => onSite(open ? null : site)}>
|
||||||
|
<ChevronRightIcon aria-hidden className={open ? "rotate-90" : ""} />
|
||||||
|
<span className="min-w-0 flex-1 break-words">{site}</span>
|
||||||
|
{problems > 0 && <span className="text-xs text-warning">Требуют внимания · {problems}</span>}
|
||||||
|
<span className="text-xs text-muted-foreground">{devices.length} {ruPlural(devices.length, "узел", "узла", "узлов")}</span>
|
||||||
|
</Button>
|
||||||
|
{open && <div className="space-y-2 border-t bg-muted/20 p-2">
|
||||||
|
{devices.map(server => <Button key={server.id} type="button" variant="ghost" className="h-auto min-h-9 w-full justify-start gap-2 whitespace-normal text-left" onClick={() => onServer(server)}>
|
||||||
|
<span className="min-w-0 flex-1 break-words">{server.name}{" "}<small className="ml-2 text-muted-foreground">{roleLabels[server.type]}</small></span>
|
||||||
|
<StatusBadge status={server.status} />
|
||||||
|
</Button>)}
|
||||||
|
{Array.from(neighbors, ([neighbor, channels]) => {
|
||||||
|
const { count, down, degraded } = countGroupGre(channels)
|
||||||
|
return <details key={neighbor} className="border-t px-2 pt-2">
|
||||||
|
<summary className="cursor-pointer text-sm">{site} ↔ {neighbor}
|
||||||
|
{down > 0 && <span className="ml-2 text-warning">Недоступно {down} из {count}</span>}
|
||||||
|
{degraded > 0 && <span className="ml-2 text-warning">С деградацией · {degraded}</span>}
|
||||||
|
</summary>
|
||||||
|
<MapChannelList edges={channels} onChannel={onChannel} />
|
||||||
|
</details>
|
||||||
|
})}
|
||||||
|
</div>}
|
||||||
|
</div>
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
}
|
||||||
@@ -137,6 +137,8 @@ npm --prefix backend run mcp:stdio
|
|||||||
|
|
||||||
Применение создаёт две отключённые стороны. Сверьте обе через `mm_gre_state_get`, затем включите их через `mm_gre_tunnel_update_plan` и проверьте IPsec и связность. При ошибке сверяйте обе стороны перед следующей операцией. Первая сторона может остаться созданной и отключённой.
|
Применение создаёт две отключённые стороны. Сверьте обе через `mm_gre_state_get`, затем включите их через `mm_gre_tunnel_update_plan` и проверьте IPsec и связность. При ошибке сверяйте обе стороны перед следующей операцией. Первая сторона может остаться созданной и отключённой.
|
||||||
|
|
||||||
|
Для выделенных профилей, как в управляемом GRE/IPsec на IX, используйте `mm_gre_ikev2_pair_configure_plan` с допуском `network.gre.ikev2_pair.configure`. Ему нужны два существующих отключённых GRE с выключенным FastPath и пустым `ipsec-secret`. Передайте в `endpoints` по одному объекту с `serverId`, `greName` и локальным `outerAddress`. Первая сторона отвечает на IKEv2, вторая инициирует соединение. Manager создаёт отдельные профили, общий PSK для пары и статические политики транспортного режима только для GRE между этими адресами. Политики используют существующие proposal `default` после проверки их совместимости. Повторный план сверяет и переиспользует совпадающие объекты пары, а у проверенной политики предыдущей версии переключает только proposal. После проверки плана включите GRE отдельно и проверьте SA и связность. Если ранее для GRE был задан встроенный PSK, очистите его через `mm_gre_tunnel_update_plan` с `clearIpsecSecret: true` при отключённом интерфейсе.
|
||||||
|
|
||||||
### Разбор отказа и проверка резерва
|
### Разбор отказа и проверка резерва
|
||||||
|
|
||||||
1. Зафиксируйте источник, назначение, ожидаемый выход и максимальный допустимый перерыв. Проверьте доступ через `mm_capabilities_get` и давность наблюдений через `mm_telemetry_health_get`. Обрыв экспорта NetFlow оставляет пробел в наблюдениях.
|
1. Зафиксируйте источник, назначение, ожидаемый выход и максимальный допустимый перерыв. Проверьте доступ через `mm_capabilities_get` и давность наблюдений через `mm_telemetry_health_get`. Обрыв экспорта NetFlow оставляет пробел в наблюдениях.
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import type { FlowMapService, FlowServiceBasis } from "@mmapp/contracts/traffic-flow"
|
||||||
|
|
||||||
|
export const unknownTrafficCategory = "Не определена"
|
||||||
|
|
||||||
|
type Classification = Pick<FlowMapService, "serviceEvidence">
|
||||||
|
|
||||||
|
export function mapTrafficCategory(service: Classification & { category?: string; serviceBasis?: FlowServiceBasis }, path?: Classification): string {
|
||||||
|
const category = service.category?.trim()
|
||||||
|
const evidence = (path ?? service).serviceEvidence
|
||||||
|
if (!category || category === "Прочее" || (path ? !evidence?.length : service.serviceBasis === "unknown")) return unknownTrafficCategory
|
||||||
|
if (evidence?.length && evidence.every(row => row.basis === "unknown")) return unknownTrafficCategory
|
||||||
|
return category
|
||||||
|
}
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
import assert from "node:assert/strict"
|
||||||
|
import { test } from "node:test"
|
||||||
|
import type { GreTunnel, Server } from "./data"
|
||||||
|
import { densityWanKey, projectNetworkMapDensity } from "./network-map-density"
|
||||||
|
import { collectGroupLinks } from "./network-map-group-links"
|
||||||
|
import { buildGreMapEdges, computeNetworkMapLayout, MAP_CARD_H, MAP_WAN_H } from "./network-map-layout"
|
||||||
|
|
||||||
|
function server(id: string, type: Server["type"], site: string, wanCount = 0): Server {
|
||||||
|
return {
|
||||||
|
id, name: id, type, site, enabled: true, status: "online", host: id, country: "", asn: "", os: "", model: "",
|
||||||
|
sessions: 0, latency: null, wanUplinks: Array.from({ length: wanCount }, (_, i) => ({
|
||||||
|
id: String(i), name: "WAN " + i, isp: "", iface: "ether" + i, ip: "", maxDl: 100, maxUl: 100,
|
||||||
|
})),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
test("12 узлов и 12 WAN сворачиваются независимо, раскрытый столбец растёт без наложений", () => {
|
||||||
|
const home = server("hr", "home-router", "Москва", 12)
|
||||||
|
const members = Array.from({ length: 12 }, (_, i) => server("jh" + i, "jump-host", "Москва"))
|
||||||
|
members[5].status = "offline"
|
||||||
|
members[7].status = "degraded"
|
||||||
|
members[9].status = "unknown"
|
||||||
|
const separate = server("other-site", "jump-host", "Новосибирск")
|
||||||
|
const exit = server("en", "exit-node", "Москва")
|
||||||
|
const servers = [home, ...members, separate, exit]
|
||||||
|
const base = computeNetworkMapLayout(servers)
|
||||||
|
const project = (expanded: string[], reveal?: Parameters<typeof projectNetworkMapDensity>[4]) =>
|
||||||
|
projectNetworkMapDensity(servers, base.nodePos, base.wanSatPos, new Set(expanded), reveal)
|
||||||
|
const closed = project([])
|
||||||
|
const [role, wan] = closed.groups
|
||||||
|
assert.equal(closed.groups.length, 2)
|
||||||
|
assert.deepEqual([role.count, role.problemCount, role.unknownCount, role.expanded], [12, 2, 1, false])
|
||||||
|
assert.deepEqual([wan.count, wan.routerId, wan.expanded], [12, home.id, false])
|
||||||
|
assert.equal(closed.hiddenServers.size, 12)
|
||||||
|
assert.equal(closed.hiddenWans.size, 12)
|
||||||
|
assert.deepEqual(closed.nodePos[exit.id], base.nodePos[exit.id])
|
||||||
|
assert.deepEqual(closed.nodePos.jh6, { x: role.x, y: role.y })
|
||||||
|
assert.deepEqual(closed.wanSatPos.hr[4], { x: wan.x, y: wan.y })
|
||||||
|
|
||||||
|
const found = project([], { serverIds: new Set(["jh6"]) })
|
||||||
|
assert.equal(found.hiddenServers.size, 0)
|
||||||
|
assert.equal(found.hiddenWans.size, 12)
|
||||||
|
const open = project([role.id], { wanKeys: new Set([densityWanKey(home.id, 4)]) })
|
||||||
|
assert.equal(open.hiddenServers.size + open.hiddenWans.size, 0)
|
||||||
|
const [roleHeader, wanHeader] = open.groups
|
||||||
|
function assertSpacing(ys: number[], minGap: number) {
|
||||||
|
ys.sort((a, b) => a - b)
|
||||||
|
for (let i = 1; i < ys.length; i++) assert.ok(ys[i] - ys[i - 1] >= minGap)
|
||||||
|
}
|
||||||
|
assertSpacing([roleHeader.y, ...[...members, separate].map(s => open.nodePos[s.id].y)], MAP_CARD_H + 12)
|
||||||
|
assertSpacing([wanHeader.y, ...open.wanSatPos.hr.map(p => p.y)], MAP_WAN_H + 12)
|
||||||
|
assert.deepEqual(base, computeNetworkMapLayout(servers))
|
||||||
|
assert.deepEqual(project([]), closed)
|
||||||
|
})
|
||||||
|
|
||||||
|
test("шесть однотипных устройств и аплинков остаются отдельными, поиск WAN раскрывает обе родительские группы", () => {
|
||||||
|
const six = Array.from({ length: 6 }, (_, i) => server("hr" + i, "home-router", "", 0))
|
||||||
|
six[0] = server("hr0", "home-router", "—", 6)
|
||||||
|
const project = (servers: Server[], wanKeys?: Set<string>) => {
|
||||||
|
const base = computeNetworkMapLayout(servers)
|
||||||
|
return projectNetworkMapDensity(servers, base.nodePos, base.wanSatPos, new Set(), { wanKeys })
|
||||||
|
}
|
||||||
|
assert.equal(project(six).groups.length, 0)
|
||||||
|
const seven = [...six, server("hr6", "home-router", "", 7)]
|
||||||
|
const closed = project(seven)
|
||||||
|
assert.equal(closed.groups.length, 1)
|
||||||
|
assert.equal(closed.groups[0].label, "Без площадки · Домашние роутеры")
|
||||||
|
assert.equal(closed.hiddenWans.get(densityWanKey("hr6", 3)), closed.groups[0].id)
|
||||||
|
const found = project(seven, new Set([densityWanKey("hr6", 3)]))
|
||||||
|
assert.equal(found.groups.length, 2)
|
||||||
|
assert.ok(found.groups.every(g => g.expanded))
|
||||||
|
assert.equal(found.hiddenServers.size + found.hiddenWans.size, 0)
|
||||||
|
})
|
||||||
|
|
||||||
|
test("обычная колонка сохраняет все координаты вплоть до касания и ручного сдвига по X", () => {
|
||||||
|
const servers = [server("h", "home-router", "A", 3), server("j", "jump-host", "A"), server("k", "jump-host", "B"),
|
||||||
|
server("e", "exit-node", "A"), server("x", "ix-node", "B")]
|
||||||
|
const nodePos = { h: { x: 133, y: -3 }, j: { x: 401, y: 170 }, k: { x: 562, y: 170 },
|
||||||
|
e: { x: 692, y: 280 }, x: { x: 690, y: 280 + MAP_CARD_H } }
|
||||||
|
const wanSatPos = { h: [{ x: 310, y: 3 }, { x: 311, y: 3 + MAP_WAN_H }, { x: 495, y: 3 + MAP_WAN_H }] }
|
||||||
|
const unchanged = projectNetworkMapDensity(servers, nodePos, wanSatPos, new Set())
|
||||||
|
assert.deepEqual(unchanged.nodePos, nodePos)
|
||||||
|
assert.deepEqual(unchanged.wanSatPos, wanSatPos)
|
||||||
|
})
|
||||||
|
|
||||||
|
test("колонка с пересечениями между площадками раздвигается без ложного группирования", () => {
|
||||||
|
const servers = Array.from({ length: 12 }, (_, i) => server("j" + i, "jump-host", "site" + Math.floor(i / 4)))
|
||||||
|
const base = computeNetworkMapLayout(servers)
|
||||||
|
const layout = projectNetworkMapDensity(servers, base.nodePos, base.wanSatPos, new Set())
|
||||||
|
assert.equal(layout.groups.length, 0)
|
||||||
|
const ys = Object.values(layout.nodePos).map(p => p.y).sort((a, b) => a - b)
|
||||||
|
assert.ok(ys.slice(1).every((y, i) => y - ys[i] >= MAP_CARD_H + 12))
|
||||||
|
})
|
||||||
|
|
||||||
|
test("обратный отчёт GRE привязан к нужному WAN, группа считает физические каналы и отказ", () => {
|
||||||
|
const home = server("hr","home-router","Москва",12)
|
||||||
|
home.wanUplinks![1].ip = "192.0.2.2"
|
||||||
|
const jh = server("jh","jump-host","Москва")
|
||||||
|
jh.host = "192.0.2.7"
|
||||||
|
const pair = [home,jh]
|
||||||
|
const base = computeNetworkMapLayout(pair)
|
||||||
|
const reverse: GreTunnel = {
|
||||||
|
id:"jh-report",name:"gre-hr",serverId:jh.id,localAddress:jh.host,remoteAddress:home.wanUplinks![1].ip,
|
||||||
|
localInnerIp:"198.51.100.1",remoteInnerIp:"198.51.100.2",poolId:"",ipsec:null,mtu:1476,keepaliveInterval:0,
|
||||||
|
keepaliveRetries:3,dscp:"inherit",clampTcpMss:true,allowFastPath:true,comment:"",enabled:true,status:"up",
|
||||||
|
}
|
||||||
|
const reports: GreTunnel[] = [reverse, {...reverse,id:"hr-report",serverId:home.id,localAddress:reverse.remoteAddress,
|
||||||
|
remoteAddress:reverse.localAddress,localInnerIp:reverse.remoteInnerIp,remoteInnerIp:reverse.localInnerIp},
|
||||||
|
{...reverse,id:"second",localInnerIp:"198.51.100.5",remoteInnerIp:"198.51.100.6"},
|
||||||
|
{...reverse,id:"third",localInnerIp:"198.51.100.9",remoteInnerIp:"198.51.100.10",status:"down"}]
|
||||||
|
const edges = buildGreMapEdges(reports,pair,base.nodePos,base.wanSatPos)
|
||||||
|
assert.equal(edges.length,3)
|
||||||
|
for (const edge of edges) {
|
||||||
|
assert.equal(edge.fromServer.id,home.id)
|
||||||
|
assert.equal(edge.fromWanIndex,1)
|
||||||
|
assert.deepEqual(edge.from,base.wanSatPos.hr[1])
|
||||||
|
}
|
||||||
|
const [group] = projectNetworkMapDensity(pair,base.nodePos,base.wanSatPos,new Set()).groups
|
||||||
|
const [bundle] = collectGroupLinks(edges.map(gre => ({type:"gre",gre,
|
||||||
|
from:{...group,name:group.label,groupId:group.id,halfWidth:80},to:{...gre.to,id:jh.id,name:jh.name,halfWidth:80}})))
|
||||||
|
assert.deepEqual([bundle.count,bundle.down,bundle.degraded],[3,1,0])
|
||||||
|
})
|
||||||
@@ -0,0 +1,158 @@
|
|||||||
|
import type { Server, ServerType } from "./data"
|
||||||
|
import { MAP_CARD_H, MAP_CARD_W, MAP_LANES, MAP_WAN_H, MAP_WAN_W, NETWORK_MAP_PIPELINE_Y } from "./network-map-layout"
|
||||||
|
|
||||||
|
export interface MapPoint { x: number; y: number }
|
||||||
|
|
||||||
|
export interface DensityGroup extends MapPoint {
|
||||||
|
id: string
|
||||||
|
kind: "role" | "wan"
|
||||||
|
type: ServerType
|
||||||
|
site: string
|
||||||
|
label: string
|
||||||
|
count: number
|
||||||
|
problemCount: number
|
||||||
|
unknownCount: number
|
||||||
|
serverIds: string[]
|
||||||
|
routerId?: string
|
||||||
|
expanded: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export function densityWanKey(serverId: string, index: number) {
|
||||||
|
return `${serverId}:${index}`
|
||||||
|
}
|
||||||
|
|
||||||
|
const groupLimit = 6
|
||||||
|
const roleLane = { "home-router": "home", "jump-host": "jh", "exit-node": "en", "ix-node": "en" } as const
|
||||||
|
const roleLabel = { "home-router": "Домашние роутеры", "jump-host": "Узлы доступа", "exit-node": "Интернет-выходы", "ix-node": "IX" } as const
|
||||||
|
type Lane = "home" | "jh" | "en" | "wan"
|
||||||
|
type Row = { point: MapPoint; height: number; place: (point: MapPoint) => void }
|
||||||
|
type Block = { id: string; center: number; rows: Row[]; grouped?: boolean }
|
||||||
|
|
||||||
|
// Keep a group's header with its children; the world may grow below the original viewport.
|
||||||
|
function placeColumn(blocks: Block[], width: number) {
|
||||||
|
const gap = 12
|
||||||
|
blocks.sort((a, b) => a.center - b.center || a.id.localeCompare(b.id))
|
||||||
|
const needsLayout = blocks.some(block => block.grouped) || blocks.some(({ rows: [row] }, i) => {
|
||||||
|
for (let j = i - 1; j >= 0; j--) {
|
||||||
|
const previous = blocks[j].rows[0]
|
||||||
|
if (row.point.y - previous.point.y >= row.height) break
|
||||||
|
if (Math.abs(row.point.x - previous.point.x) < width) return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
})
|
||||||
|
if (!needsLayout) {
|
||||||
|
for (const { rows: [row] } of blocks) row.place(row.point)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
let bottom = 40
|
||||||
|
for (const { center, rows } of blocks) {
|
||||||
|
const height = rows.reduce((sum, row) => sum + row.height, gap * (rows.length - 1))
|
||||||
|
let top = Math.max(bottom + gap, center - height / 2)
|
||||||
|
for (const row of rows) {
|
||||||
|
row.place({ x: row.point.x, y: top + row.height / 2 })
|
||||||
|
top += row.height + gap
|
||||||
|
}
|
||||||
|
bottom = top - gap
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function projectNetworkMapDensity(
|
||||||
|
servers: readonly Server[],
|
||||||
|
baseNodePos: Record<string, MapPoint>,
|
||||||
|
baseWanPos: Record<string, MapPoint[]>,
|
||||||
|
expanded: ReadonlySet<string>,
|
||||||
|
reveal: { serverIds?: ReadonlySet<string>; wanKeys?: ReadonlySet<string> } = {},
|
||||||
|
) {
|
||||||
|
const groups: DensityGroup[] = []
|
||||||
|
const hiddenServers = new Map<string, string>()
|
||||||
|
const hiddenWans = new Map<string, string>()
|
||||||
|
const nodePos = { ...baseNodePos }
|
||||||
|
const wanSatPos = { ...baseWanPos }
|
||||||
|
const columns: Record<Lane, Block[]> = { home: [], jh: [], en: [], wan: [] }
|
||||||
|
const cohorts = new Map<string, Server[]>()
|
||||||
|
const siteOf = (s: Server) => s.site?.trim() === "—" ? "" : s.site?.trim() || ""
|
||||||
|
const serverPoint = (s: Server) => baseNodePos[s.id] ?? { x: MAP_LANES[roleLane[s.type]].cx, y: NETWORK_MAP_PIPELINE_Y }
|
||||||
|
const serverRow = (s: Server): Row => ({
|
||||||
|
point: serverPoint(s), height: MAP_CARD_H, place: p => { nodePos[s.id] = p },
|
||||||
|
})
|
||||||
|
const groupRow = (g: DensityGroup): Row => ({
|
||||||
|
point: g, height: MAP_CARD_H, place: p => { g.x = p.x; g.y = p.y },
|
||||||
|
})
|
||||||
|
const revealWan = (s: Server) => s.wanUplinks?.some((_, index) => reveal.wanKeys?.has(densityWanKey(s.id, index)))
|
||||||
|
|
||||||
|
for (const s of servers) {
|
||||||
|
const id = `role:${s.type}:${siteOf(s)}`
|
||||||
|
const cohort = cohorts.get(id)
|
||||||
|
if (cohort) cohort.push(s)
|
||||||
|
else cohorts.set(id, [s])
|
||||||
|
}
|
||||||
|
for (const [id, members] of cohorts) {
|
||||||
|
const first = members[0], column = columns[roleLane[first.type]]
|
||||||
|
if (members.length <= groupLimit) {
|
||||||
|
for (const s of members) column.push({ id: s.id, center: serverPoint(s).y, rows: [serverRow(s)] })
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
const site = siteOf(first)
|
||||||
|
const center = members.reduce((ys, s) => ys + serverPoint(s).y, 0) / members.length
|
||||||
|
const open = expanded.has(id) || members.some(s => reveal.serverIds?.has(s.id) || revealWan(s))
|
||||||
|
const group: DensityGroup = {
|
||||||
|
id, kind: "role", type: first.type, site, label: `${site || "Без площадки"} · ${roleLabel[first.type]}`,
|
||||||
|
count: members.length, expanded: open, x: serverPoint(first).x, y: center,
|
||||||
|
problemCount: members.filter(s => s.status === "offline" || s.status === "degraded").length,
|
||||||
|
unknownCount: members.filter(s => s.status === "unknown").length, serverIds: members.map(s => s.id),
|
||||||
|
}
|
||||||
|
groups.push(group)
|
||||||
|
const rows = [groupRow(group)]
|
||||||
|
if (open) {
|
||||||
|
for (const s of members.sort((a, b) => a.name.localeCompare(b.name, "ru", { numeric: true }) || a.id.localeCompare(b.id))) rows.push(serverRow(s))
|
||||||
|
} else {
|
||||||
|
for (const s of members) hiddenServers.set(s.id, id)
|
||||||
|
}
|
||||||
|
column.push({ id, center, rows, grouped: true })
|
||||||
|
}
|
||||||
|
for (const lane of ["home", "jh", "en"] as const) placeColumn(columns[lane], MAP_CARD_W)
|
||||||
|
const groupById = new Map(groups.map(g => [g.id, g]))
|
||||||
|
for (const [serverId, groupId] of hiddenServers) {
|
||||||
|
const { x, y } = groupById.get(groupId)!
|
||||||
|
nodePos[serverId] = { x, y }
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const router of servers) {
|
||||||
|
const uplinks = router.wanUplinks ?? []
|
||||||
|
if (router.type !== "home-router" || !uplinks.length) continue
|
||||||
|
wanSatPos[router.id] = [...(baseWanPos[router.id] ?? [])]
|
||||||
|
const ownerGroup = hiddenServers.get(router.id)
|
||||||
|
if (ownerGroup) {
|
||||||
|
uplinks.forEach((_, index) => {
|
||||||
|
hiddenWans.set(densityWanKey(router.id, index), ownerGroup)
|
||||||
|
wanSatPos[router.id][index] = nodePos[router.id]
|
||||||
|
})
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
const rows: Row[] = uplinks.map((_, index) => ({
|
||||||
|
point: baseWanPos[router.id]?.[index] ?? { x: MAP_LANES.wan.cx, y: nodePos[router.id].y },
|
||||||
|
height: MAP_WAN_H, place: p => { wanSatPos[router.id][index] = p },
|
||||||
|
}))
|
||||||
|
if (rows.length <= groupLimit) {
|
||||||
|
rows.forEach((row, i) => columns.wan.push({ id: densityWanKey(router.id, i), center: row.point.y, rows: [row] }))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
const id = "wan:" + router.id
|
||||||
|
const open = expanded.has(id) || Boolean(revealWan(router))
|
||||||
|
const group: DensityGroup = {
|
||||||
|
id, kind: "wan", type: router.type, site: siteOf(router), label: "WAN · " + router.name, routerId: router.id,
|
||||||
|
count: rows.length, expanded: open, x: rows[0].point.x, y: nodePos[router.id].y, serverIds: [router.id],
|
||||||
|
// The WAN catalog has no per-uplink operational status.
|
||||||
|
problemCount: 0, unknownCount: rows.length,
|
||||||
|
}
|
||||||
|
groups.push(group)
|
||||||
|
const header = groupRow(group)
|
||||||
|
if (!open) {
|
||||||
|
uplinks.forEach((_, index) => hiddenWans.set(densityWanKey(router.id, index), id))
|
||||||
|
header.place = p => { group.y = p.y; rows.forEach(row => row.place(p)) }
|
||||||
|
}
|
||||||
|
columns.wan.push({ id, center: group.y, rows: open ? [header, ...rows] : [header], grouped: true })
|
||||||
|
}
|
||||||
|
placeColumn(columns.wan, MAP_WAN_W)
|
||||||
|
return { groups, hiddenServers, hiddenWans, nodePos, wanSatPos }
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import { strict as assert } from "node:assert"
|
||||||
|
import { test } from "node:test"
|
||||||
|
import type { FlowMapService, FlowMapServicePath } from "@mmapp/contracts/traffic-flow"
|
||||||
|
import { groupMapCategories, mapCategoryId, smallMapServices } from "./network-map-destinations"
|
||||||
|
import { readNetworkMapUrl } from "./network-map-url-state"
|
||||||
|
|
||||||
|
const service: FlowMapService = { id: "s", label: "Example", category: "Видео", bytes: 100, bps: 80, share: 0.4 }
|
||||||
|
const path: FlowMapServicePath = { clientId: "a", clientName: "A", viaId: "1", viaName: "Вход", enId: "", enName: "", serviceId: "s", bytes: 100, bps: 80 }
|
||||||
|
const edge = { fromId: "1", toId: "s", bytes: 100, bps: 80, bpsFwd: 30, bpsRev: 50 }
|
||||||
|
|
||||||
|
test("category drilldown preserves partial evidence, the source window and route certainty", () => {
|
||||||
|
const serviceEvidence = [{ basis: "network" as const, bytes: 60 }, { basis: "unknown" as const, bytes: 40 }]
|
||||||
|
const second = { ...service, id: "second", bytes: 25, bps: 20, share: 0.1 }
|
||||||
|
const layer = groupMapCategories([{ ...service, serviceEvidence }, second], [
|
||||||
|
{ ...edge, observedOnly: true },
|
||||||
|
{ ...edge, toId: second.id, bytes: 25, bps: 20, bpsFwd: 15, bpsRev: 5 },
|
||||||
|
], [{ ...path, serviceEvidence }, { ...path, serviceId: second.id, enId: "1", bytes: 25, bps: 20 }])
|
||||||
|
const video = mapCategoryId("Видео"), unknown = mapCategoryId("Не определена")
|
||||||
|
assert.deepEqual(layer.services.map(s => [s.id, s.bytes, s.bps]), [[video, 85, 68], [unknown, 40, 32]])
|
||||||
|
assert.ok(Math.abs(layer.services[0].share - 0.34) < Number.EPSILON)
|
||||||
|
assert.deepEqual(layer.members.get(video)?.map(s => [s.id, s.bytes]), [["s", 60], ["second", 25]])
|
||||||
|
assert.deepEqual(layer.paths.get(unknown)?.map(p => [p.enId, p.serviceId, p.bytes]), [["", "s", 40]])
|
||||||
|
assert.deepEqual(layer.edges.filter(e => e.toId === video).map(e => [!!e.observedOnly, e.bytes, e.bpsFwd]), [[true, 60, 0], [false, 25, 15]])
|
||||||
|
assert.equal(readNetworkMapUrl(new URLSearchParams("dest=categories&user=a")).dest, "categories")
|
||||||
|
})
|
||||||
|
|
||||||
|
test("services at exactly ten percent collapse only for a known share in the current scope", () => {
|
||||||
|
const items = [0.09, 0.10, 0.1001, 0.01].map((share, i) => ({...service, id: String(i), share}))
|
||||||
|
assert.deepEqual(smallMapServices(items, true, "0", "3").map(s => s.id), ["1"])
|
||||||
|
assert.deepEqual(smallMapServices(items, false, null, null), [])
|
||||||
|
assert.deepEqual(smallMapServices([{ ...items[0], share: 0.9 }], true, null, null), [])
|
||||||
|
})
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
import type { FlowMapService, FlowMapServiceEdge, FlowMapServicePath } from "@mmapp/contracts/traffic-flow"
|
||||||
|
import { mapTrafficCategory, unknownTrafficCategory } from "./map-traffic-category"
|
||||||
|
|
||||||
|
export function mapCategoryId(label: string) {
|
||||||
|
return "category:" + label
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Source node and route certainty stay separate when several destinations share a link. */
|
||||||
|
export function groupDestinationEdges(edges: FlowMapServiceEdge[], target: (serviceId: string) => string | undefined) {
|
||||||
|
const grouped = new Map<string, FlowMapServiceEdge>()
|
||||||
|
const missingDirection = new Set<string>()
|
||||||
|
for (const edge of edges) {
|
||||||
|
const toId = target(edge.toId)
|
||||||
|
if (!toId) continue
|
||||||
|
const key = JSON.stringify([edge.fromId, toId, Boolean(edge.observedOnly)])
|
||||||
|
const total = grouped.get(key) ?? {
|
||||||
|
fromId: edge.fromId, toId, bytes: 0, bps: 0, bpsFwd: 0, bpsRev: 0,
|
||||||
|
...(edge.observedOnly && { observedOnly: true as const }),
|
||||||
|
}
|
||||||
|
total.bytes += edge.bytes
|
||||||
|
total.bps += edge.bps
|
||||||
|
total.bpsFwd += edge.bpsFwd
|
||||||
|
total.bpsRev += edge.bpsRev
|
||||||
|
if (edge.bps > 0 && !edge.bpsFwd && !edge.bpsRev) missingDirection.add(key)
|
||||||
|
grouped.set(key, total)
|
||||||
|
}
|
||||||
|
for (const key of missingDirection) {
|
||||||
|
const total = grouped.get(key)!
|
||||||
|
total.bpsFwd = 0
|
||||||
|
total.bpsRev = 0
|
||||||
|
}
|
||||||
|
return [...grouped.values()]
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Every byte belongs to a single bucket, including the part without classification evidence. */
|
||||||
|
function categoryVolumes(service: FlowMapService, bytes: number, evidence: FlowMapService["serviceEvidence"]) {
|
||||||
|
const label = mapTrafficCategory(service)
|
||||||
|
if (!evidence?.length || label === unknownTrafficCategory) return new Map([[label, bytes]])
|
||||||
|
const known = Math.min(bytes, evidence.reduce((sum, row) => sum + (row.basis === "unknown" ? 0 : row.bytes), 0))
|
||||||
|
const volumes = new Map<string, number>()
|
||||||
|
if (known) volumes.set(label, known)
|
||||||
|
if (bytes > known || !bytes) volumes.set(unknownTrafficCategory, bytes - known)
|
||||||
|
return volumes
|
||||||
|
}
|
||||||
|
|
||||||
|
export function groupMapCategories(services: FlowMapService[], edges: FlowMapServiceEdge[], paths: FlowMapServicePath[]) {
|
||||||
|
const categories = new Map<string, FlowMapService>()
|
||||||
|
const members = new Map<string, FlowMapService[]>()
|
||||||
|
const categoryPaths = new Map<string, FlowMapServicePath[]>()
|
||||||
|
const byService = new Map<string, string>()
|
||||||
|
const partialEdges: FlowMapServiceEdge[] = []
|
||||||
|
for (const service of services) {
|
||||||
|
const servicePaths = paths.filter(path => path.serviceId === service.id)
|
||||||
|
const evidence = service.serviceEvidence ?? servicePaths.flatMap(path => path.serviceEvidence ?? [])
|
||||||
|
const volumes = categoryVolumes(service, service.bytes, evidence)
|
||||||
|
const onlyLabel = volumes.size === 1 ? [...volumes.keys()][0] : undefined
|
||||||
|
if (onlyLabel) byService.set(service.id, mapCategoryId(onlyLabel))
|
||||||
|
for (const [label, bytes] of volumes) {
|
||||||
|
const id = mapCategoryId(label)
|
||||||
|
const fraction = service.bytes ? bytes / service.bytes : 1
|
||||||
|
const item = { ...service, bytes, share: service.share * fraction, bps: service.bps * fraction }
|
||||||
|
const category = categories.get(id) ?? { id, label, category: "Категория трафика", bytes: 0, bps: 0, share: 0 }
|
||||||
|
category.bytes += item.bytes
|
||||||
|
category.bps += item.bps
|
||||||
|
category.share += item.share
|
||||||
|
categories.set(id, category)
|
||||||
|
const items = members.get(id) ?? []
|
||||||
|
items.push(item)
|
||||||
|
members.set(id, items)
|
||||||
|
}
|
||||||
|
|
||||||
|
const routed = new Map<string, Map<string, number>>()
|
||||||
|
for (const path of servicePaths) {
|
||||||
|
// Older snapshots can associate a path with a single service category, never split a mixed service by guesswork.
|
||||||
|
const parts = path.serviceEvidence?.length ? categoryVolumes(service, path.bytes, path.serviceEvidence) : onlyLabel ? new Map([[onlyLabel, path.bytes]]) : []
|
||||||
|
const source = JSON.stringify([path.enId || path.viaId, !path.enId])
|
||||||
|
const totals = routed.get(source) ?? new Map<string, number>()
|
||||||
|
for (const [label, bytes] of parts) {
|
||||||
|
const id = mapCategoryId(label)
|
||||||
|
const items = categoryPaths.get(id) ?? []
|
||||||
|
items.push(bytes === path.bytes ? path : {
|
||||||
|
...path, bytes, bps: path.bps * bytes / path.bytes, trafficTypes: undefined,
|
||||||
|
serviceEvidence: path.serviceEvidence?.filter(row => mapTrafficCategory(service, {serviceEvidence:[row]}) === label),
|
||||||
|
})
|
||||||
|
categoryPaths.set(id, items)
|
||||||
|
totals.set(label, (totals.get(label) ?? 0) + bytes)
|
||||||
|
}
|
||||||
|
routed.set(source, totals)
|
||||||
|
}
|
||||||
|
for (const edge of edges.filter(item => item.toId === service.id)) {
|
||||||
|
if (onlyLabel) {
|
||||||
|
partialEdges.push({ ...edge, toId: mapCategoryId(onlyLabel) })
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
const source = JSON.stringify([edge.fromId, Boolean(edge.observedOnly)])
|
||||||
|
for (const [label, bytes] of routed.get(source) ?? []) {
|
||||||
|
if (!edge.bytes || bytes > edge.bytes) continue
|
||||||
|
const whole = bytes === edge.bytes
|
||||||
|
partialEdges.push({ ...edge, toId: mapCategoryId(label), bytes, bps: edge.bps * bytes / edge.bytes,
|
||||||
|
bpsFwd: whole ? edge.bpsFwd : 0, bpsRev: whole ? edge.bpsRev : 0 })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
services: [...categories.values()].sort((a, b) => b.bytes - a.bytes || a.label.localeCompare(b.label, "ru")),
|
||||||
|
edges: groupDestinationEdges(partialEdges, id => id), members, byService, paths: categoryPaths,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function smallMapServices(services: FlowMapService[], knownShare: boolean, selectedId: string | null, filteredId: string | null) {
|
||||||
|
return services.filter(service => knownShare && service.share <= 0.1 && service.id !== selectedId && service.id !== filteredId)
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
import { mapLinkPath, type GreMapEdge } from "./network-map-layout"
|
||||||
|
|
||||||
|
export type GroupLinkEnd = {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
x: number
|
||||||
|
y: number
|
||||||
|
halfWidth: number
|
||||||
|
groupId?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
type ChannelCounts = { count: number; down: number; degraded: number }
|
||||||
|
type ConnectionType = "gre" | "wan-jh" | "wan" | "ix" | "service" | "observation" | "user"
|
||||||
|
|
||||||
|
export type MapGroupConnection = Partial<ChannelCounts> & {
|
||||||
|
from: GroupLinkEnd
|
||||||
|
to: GroupLinkEnd
|
||||||
|
type: ConnectionType
|
||||||
|
gre?: GreMapEdge
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Unmatched reports from opposite ends of one outer GRE pair can describe the same tunnels. */
|
||||||
|
export function countGroupGre(edges: Iterable<GreMapEdge>): ChannelCounts {
|
||||||
|
const total = { count: 0, down: 0, degraded: 0 }
|
||||||
|
const ambiguous = new Map<string, Map<string, ChannelCounts>>()
|
||||||
|
for (const edge of edges) {
|
||||||
|
const { tunnel, ambiguousPeerKey } = edge
|
||||||
|
let counts = total
|
||||||
|
if (ambiguousPeerKey) {
|
||||||
|
const byOwner = ambiguous.get(ambiguousPeerKey) ?? new Map<string, ChannelCounts>()
|
||||||
|
ambiguous.set(ambiguousPeerKey, byOwner)
|
||||||
|
counts = byOwner.get(tunnel.serverId) ?? { count: 0, down: 0, degraded: 0 }
|
||||||
|
byOwner.set(tunnel.serverId, counts)
|
||||||
|
}
|
||||||
|
counts.count++
|
||||||
|
const status = channelStatus(edge)
|
||||||
|
if (status === "down") counts.down++
|
||||||
|
else if (status === "degraded") counts.degraded++
|
||||||
|
}
|
||||||
|
for (const byOwner of ambiguous.values()) {
|
||||||
|
const reports = [...byOwner.values()]
|
||||||
|
const count = Math.max(...reports.map(row => row.count))
|
||||||
|
const down = Math.min(Math.max(...reports.map(row => row.down)), count - Math.max(...reports.map(row => row.count - row.down)))
|
||||||
|
// Conflicting reports indicate a problem but do not establish that the whole channel is down.
|
||||||
|
const affected = Math.max(...reports.map(row => row.down + row.degraded))
|
||||||
|
total.count += count
|
||||||
|
total.down += down
|
||||||
|
total.degraded += affected - down
|
||||||
|
}
|
||||||
|
return total
|
||||||
|
}
|
||||||
|
|
||||||
|
export function channelStatus({ tunnel, peerTunnel }: GreMapEdge) {
|
||||||
|
return peerTunnel && peerTunnel.status !== tunnel.status ? "degraded" : tunnel.status
|
||||||
|
}
|
||||||
|
|
||||||
|
export function collectGroupLinks(rows: Iterable<MapGroupConnection>) {
|
||||||
|
const buckets = new Map<string, MapGroupConnection[]>()
|
||||||
|
for (const row of rows) {
|
||||||
|
if (!(row.from.groupId || row.to.groupId) || row.from.id === row.to.id) continue
|
||||||
|
const key = JSON.stringify([row.type, ...[row.from.id, row.to.id].sort()])
|
||||||
|
const bucket = buckets.get(key)
|
||||||
|
if (bucket) bucket.push(row)
|
||||||
|
else buckets.set(key, [row])
|
||||||
|
}
|
||||||
|
return [...buckets].map(([id, bucket]) => {
|
||||||
|
const { from, to, type } = bucket[0]
|
||||||
|
const totals = countGroupGre(bucket.flatMap(row => row.gre ? [row.gre] : []))
|
||||||
|
for (const row of bucket) {
|
||||||
|
if (row.gre) continue
|
||||||
|
totals.count += row.count ?? 1
|
||||||
|
totals.down += row.down ?? 0
|
||||||
|
totals.degraded += row.degraded ?? 0
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
id, from, to, type, ...totals,
|
||||||
|
groups: [from.groupId, to.groupId].filter((group): group is string => Boolean(group)),
|
||||||
|
link: mapLinkPath(from, from.halfWidth, to, to.halfWidth),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export type MapGroupLink = ReturnType<typeof collectGroupLinks>[number]
|
||||||
@@ -877,35 +877,6 @@ export function greSourceWanIndexOnMap(
|
|||||||
return wanIdx
|
return wanIdx
|
||||||
}
|
}
|
||||||
|
|
||||||
function greEndpointAnchor(
|
|
||||||
server: Server,
|
|
||||||
tunnel: GreTunnel,
|
|
||||||
role: "source" | "peer",
|
|
||||||
nodePos: Record<string, { x: number; y: number }>,
|
|
||||||
wanSatPos: Record<string, { x: number; y: number }[]>,
|
|
||||||
resolvedIpv4ByHost?: ReadonlyMap<string, string>,
|
|
||||||
): { x: number; y: number } {
|
|
||||||
const center = (): { x: number; y: number } =>
|
|
||||||
nodePos[server.id] ?? { x: W / 2, y: H / 2 }
|
|
||||||
|
|
||||||
if (server.type !== "home-router") return center()
|
|
||||||
|
|
||||||
const wans = server.wanUplinks ?? []
|
|
||||||
let wanIdx: number | null = null
|
|
||||||
if (role === "source") {
|
|
||||||
const la = tunnel.localAddress?.trim() ?? ""
|
|
||||||
if (la === "0.0.0.0" || la === "") wanIdx = wans.length > 0 ? 0 : null
|
|
||||||
else wanIdx = wanIndexMatchingOuterIp(server, tunnel.localAddress, resolvedIpv4ByHost)
|
|
||||||
if (wanIdx == null && wans.length > 0) wanIdx = 0
|
|
||||||
} else {
|
|
||||||
wanIdx = wanIndexMatchingOuterIp(server, tunnel.remoteAddress, resolvedIpv4ByHost)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (wanIdx != null && wanSatPos[server.id]?.[wanIdx])
|
|
||||||
return wanSatPos[server.id][wanIdx]!
|
|
||||||
return center()
|
|
||||||
}
|
|
||||||
|
|
||||||
/** GRE на карте только между узлами каталога; у HR конец туннеля — у соответствующего WAN-спутника. */
|
/** GRE на карте только между узлами каталога; у HR конец туннеля — у соответствующего WAN-спутника. */
|
||||||
export interface GreMapEdge {
|
export interface GreMapEdge {
|
||||||
tunnel: GreTunnel
|
tunnel: GreTunnel
|
||||||
@@ -915,6 +886,8 @@ export interface GreMapEdge {
|
|||||||
to: { x: number; y: number }
|
to: { x: number; y: number }
|
||||||
fromServer: Server
|
fromServer: Server
|
||||||
toServer: Server
|
toServer: Server
|
||||||
|
fromWanIndex?: number | null
|
||||||
|
toWanIndex?: number | null
|
||||||
}
|
}
|
||||||
|
|
||||||
export function buildGreMapEdges(
|
export function buildGreMapEdges(
|
||||||
@@ -974,9 +947,13 @@ export function buildGreMapEdges(
|
|||||||
toServer = a
|
toServer = a
|
||||||
}
|
}
|
||||||
|
|
||||||
const from = greEndpointAnchor(fromServer, t, "source", nodePos, wanSatPos, resolvedIpv4ByHost)
|
const sourceWan = greSourceWanIndexOnMap(a, t, resolvedIpv4ByHost)
|
||||||
const to = greEndpointAnchor(toServer, t, "peer", nodePos, wanSatPos, resolvedIpv4ByHost)
|
const peerWan = wanIndexMatchingOuterIp(b, t.remoteAddress, resolvedIpv4ByHost)
|
||||||
const edge: GreMapEdge = { tunnel: t, from, to, fromServer, toServer }
|
const fromWanIndex = fromServer === a ? sourceWan : peerWan
|
||||||
|
const toWanIndex = toServer === a ? sourceWan : peerWan
|
||||||
|
const point = (server: Server, index: number | null) =>
|
||||||
|
(index !== null && wanSatPos[server.id]?.[index]) || nodePos[server.id] || { x: W / 2, y: H / 2 }
|
||||||
|
const edge: GreMapEdge = { tunnel: t, from:point(fromServer, fromWanIndex), to:point(toServer, toWanIndex), fromServer, toServer, fromWanIndex, toWanIndex }
|
||||||
const key = canonicalLinkKey(t, fromServer, toServer)
|
const key = canonicalLinkKey(t, fromServer, toServer)
|
||||||
const group = links.get(key)
|
const group = links.get(key)
|
||||||
if (group) group.push(edge)
|
if (group) group.push(edge)
|
||||||
|
|||||||
@@ -34,3 +34,18 @@ test("a filtered topology does not inherit a service's full-network traffic comp
|
|||||||
assert.equal(complete.share, 0.4)
|
assert.equal(complete.share, 0.4)
|
||||||
assert.equal(partial.share, 1)
|
assert.equal(partial.share, 1)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test("a scoped service uses only the classification of its contributing paths", () => {
|
||||||
|
const service = {id:"svc:video", label:"Видео", category:"Видео", bytes:100, bps:20, share:1,
|
||||||
|
serviceEvidence:[{basis:"network" as const, bytes:60}, {basis:"heuristic" as const, bytes:40}]}
|
||||||
|
const endpoint = {viaId:"1", viaName:"Экспортёр", enId:"", enName:"", serviceId:service.id}
|
||||||
|
const paths = [
|
||||||
|
{...endpoint, clientId:"a", clientName:"А", bytes:40, bps:8, serviceEvidence:[{basis:"heuristic" as const,bytes:40}]},
|
||||||
|
{...endpoint, clientId:"b", clientName:"Б", bytes:60, bps:12, serviceEvidence:[{basis:"network" as const,bytes:60}]},
|
||||||
|
]
|
||||||
|
const scoped = scopeMapDestinations([service], [], paths, () => true, "a").services[0]
|
||||||
|
assert.deepEqual(scoped.serviceEvidence, paths[0].serviceEvidence)
|
||||||
|
assert.equal(scoped.bytes,40)
|
||||||
|
const legacy = scopeMapDestinations([service], [], paths.map(path => ({...path, serviceEvidence:undefined})), () => true,"a").services[0]
|
||||||
|
assert.equal(legacy.serviceEvidence,undefined)
|
||||||
|
})
|
||||||
@@ -12,6 +12,25 @@ export function isolatedIxServers(servers: Pick<Server, "id" | "type">[], links:
|
|||||||
return new Set(servers.filter(server => server.type === "ix-node" && !connected.has(server.id)).map(server => server.id))
|
return new Set(servers.filter(server => server.type === "ix-node" && !connected.has(server.id)).map(server => server.id))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function scopedClassification(paths: FlowMapServicePath[], bytes: number) {
|
||||||
|
if (!paths.length || paths.reduce((sum, path) => sum + path.bytes, 0) !== bytes) return {}
|
||||||
|
const bases = new Map<string, NonNullable<FlowMapService["serviceEvidence"]>[number]>()
|
||||||
|
const types = new Map<string, NonNullable<FlowMapService["trafficTypes"]>[number]>()
|
||||||
|
for (const path of paths) {
|
||||||
|
for (const row of path.serviceEvidence ?? []) {
|
||||||
|
bases.set(row.basis, { ...row, bytes: (bases.get(row.basis)?.bytes ?? 0) + row.bytes })
|
||||||
|
}
|
||||||
|
for (const row of path.trafficTypes ?? []) {
|
||||||
|
const key = JSON.stringify([row.transport, row.application])
|
||||||
|
types.set(key, { ...row, bytes: (types.get(key)?.bytes ?? 0) + row.bytes })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
...(bases.size && {serviceEvidence: [...bases.values()].sort((a,b) => b.bytes - a.bytes)}),
|
||||||
|
...(types.size && {trafficTypes: [...types.values()].sort((a,b) => b.bytes - a.bytes).slice(0,5)}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export function scopeMapDestinations(
|
export function scopeMapDestinations(
|
||||||
services: FlowMapService[], edges: FlowMapServiceEdge[], paths: FlowMapServicePath[],
|
services: FlowMapService[], edges: FlowMapServiceEdge[], paths: FlowMapServicePath[],
|
||||||
includes: (id: string) => boolean, userId?: string, retainUnassigned = false,
|
includes: (id: string) => boolean, userId?: string, retainUnassigned = false,
|
||||||
@@ -56,13 +75,14 @@ export function scopeMapDestinations(
|
|||||||
const shareOfVisible = Boolean(userId) || services.some(service => (totals.get(service.id)?.bytes ?? 0) !== service.bytes)
|
const shareOfVisible = Boolean(userId) || services.some(service => (totals.get(service.id)?.bytes ?? 0) !== service.bytes)
|
||||||
return {
|
return {
|
||||||
shareOfVisible,
|
shareOfVisible,
|
||||||
services: services.flatMap(service => {
|
services: services.flatMap<FlowMapService>(service => {
|
||||||
const total = totals.get(service.id)
|
const total = totals.get(service.id)
|
||||||
if (!total) return []
|
if (!total) return []
|
||||||
const { trafficTypes, serviceEvidence, lastBucketAt, ...destination } = service
|
const { trafficTypes, serviceEvidence, lastBucketAt, ...destination } = service
|
||||||
const visibleShare = bytes ? total.bytes / bytes : 0
|
const visibleShare = bytes ? total.bytes / bytes : 0
|
||||||
return [{ ...destination, ...total, share: shareOfVisible ? visibleShare : service.share,
|
return [{ ...destination, ...total, share: shareOfVisible ? visibleShare : service.share,
|
||||||
...(total.bytes === service.bytes ? { trafficTypes, serviceEvidence, lastBucketAt } : {}) }]
|
...(total.bytes === service.bytes ? { trafficTypes, serviceEvidence, lastBucketAt } :
|
||||||
|
scopedClassification(visiblePaths.filter(path => path.serviceId === service.id), total.bytes)) }]
|
||||||
}).sort((a, b) => b.bytes - a.bytes || a.label.localeCompare(b.label)),
|
}).sort((a, b) => b.bytes - a.bytes || a.label.localeCompare(b.label)),
|
||||||
edges: visibleEdges,
|
edges: visibleEdges,
|
||||||
paths: visiblePaths,
|
paths: visiblePaths,
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
export const networkMapFilters=["all","online","degraded","offline","unknown","jump-host","exit-node","home-router","ix-node"] as const
|
export const networkMapFilters=["all","online","degraded","offline","unknown","jump-host","exit-node","home-router","ix-node"] as const
|
||||||
export type NetworkMapFilter=typeof networkMapFilters[number]
|
export type NetworkMapFilter=typeof networkMapFilters[number]
|
||||||
|
export type MapDestinationMode = "services" | "countries" | "categories"
|
||||||
export function readNetworkMapUrl(params:URLSearchParams){
|
export function readNetworkMapUrl(params:URLSearchParams){
|
||||||
const server=params.get("server"),search=params.get("q")??"",filter=params.get("filter")??"all",dest=params.get("dest")??"services",wan=params.get("wan")
|
const server=params.get("server"),search=params.get("q")??"",filter=params.get("filter")??"all",dest=params.get("dest")??"services",wan=params.get("wan")
|
||||||
let error:string|null=null
|
let error:string|null=null
|
||||||
@@ -7,9 +8,9 @@ export function readNetworkMapUrl(params:URLSearchParams){
|
|||||||
else if(server!==null&&!/^[a-zA-Z0-9_.:-]{1,64}$/.test(server))error="В ссылке указан некорректный сервер карты."
|
else if(server!==null&&!/^[a-zA-Z0-9_.:-]{1,64}$/.test(server))error="В ссылке указан некорректный сервер карты."
|
||||||
else if(search.length>256)error="Поиск карты в ссылке слишком длинный."
|
else if(search.length>256)error="Поиск карты в ссылке слишком длинный."
|
||||||
else if(!(networkMapFilters as readonly string[]).includes(filter))error="В ссылке указан неизвестный фильтр карты."
|
else if(!(networkMapFilters as readonly string[]).includes(filter))error="В ссылке указан неизвестный фильтр карты."
|
||||||
else if(!["services","countries"].includes(dest))error="В ссылке указан неизвестный режим назначений."
|
else if(!["services","countries","categories"].includes(dest))error="В ссылке указан неизвестный режим назначений."
|
||||||
else if(wan!==null&&(!server||!/^\d{1,4}$/.test(wan)))error="В ссылке указан некорректный аплинк карты."
|
else if(wan!==null&&(!server||!/^\d{1,4}$/.test(wan)))error="В ссылке указан некорректный аплинк карты."
|
||||||
return {server,search,filter:filter as NetworkMapFilter,dest:dest as "services"|"countries",wan:wan===null?null:Number(wan),error}
|
return {server,search,filter:filter as NetworkMapFilter,dest:dest as MapDestinationMode,wan:wan===null?null:Number(wan),error}
|
||||||
}
|
}
|
||||||
export function patchNetworkMapUrl(params:URLSearchParams,values:Record<string,string|null>){
|
export function patchNetworkMapUrl(params:URLSearchParams,values:Record<string,string|null>){
|
||||||
const next=new URLSearchParams(params)
|
const next=new URLSearchParams(params)
|
||||||
|
|||||||
@@ -132,6 +132,9 @@ export const trafficFlowOverlayResultSchema = z.object({
|
|||||||
hostError: z.string().optional(),
|
hostError: z.string().optional(),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
export const flowServiceBasisSchema = z.enum(["catalog", "network", "heuristic", "port", "unknown"])
|
||||||
|
export type FlowServiceBasis = z.infer<typeof flowServiceBasisSchema>
|
||||||
|
|
||||||
export const flowTalkerDtoSchema = z.object({
|
export const flowTalkerDtoSchema = z.object({
|
||||||
serverId: z.string(),
|
serverId: z.string(),
|
||||||
serverName: z.string(),
|
serverName: z.string(),
|
||||||
@@ -152,6 +155,7 @@ export const flowTalkerDtoSchema = z.object({
|
|||||||
application: z.string().optional(),
|
application: z.string().optional(),
|
||||||
category: z.string().optional(),
|
category: z.string().optional(),
|
||||||
service: z.string().optional(),
|
service: z.string().optional(),
|
||||||
|
serviceBasis: flowServiceBasisSchema.optional(),
|
||||||
dstCountry: z.string().optional(),
|
dstCountry: z.string().optional(),
|
||||||
dstAsn: z.number().int().optional(),
|
dstAsn: z.number().int().optional(),
|
||||||
clientId: z.string().optional(),
|
clientId: z.string().optional(),
|
||||||
@@ -366,17 +370,7 @@ export const flowMapHopDtoSchema = z.object({
|
|||||||
bpsRev: z.number().nonnegative(),
|
bpsRev: z.number().nonnegative(),
|
||||||
})
|
})
|
||||||
|
|
||||||
export const flowServiceBasisSchema = z.enum(["catalog", "network", "heuristic", "port", "unknown"])
|
const flowMapClassificationFields = {
|
||||||
export type FlowServiceBasis = z.infer<typeof flowServiceBasisSchema>
|
|
||||||
|
|
||||||
export const flowMapServiceDtoSchema = z.object({
|
|
||||||
id: z.string(),
|
|
||||||
label: z.string(),
|
|
||||||
category: z.string(),
|
|
||||||
bytes: z.number().nonnegative(),
|
|
||||||
bps: z.number().nonnegative(),
|
|
||||||
share: z.number().min(0).max(1),
|
|
||||||
lastBucketAt: z.string().datetime().optional(),
|
|
||||||
trafficTypes: z.array(z.object({
|
trafficTypes: z.array(z.object({
|
||||||
transport: z.string(),
|
transport: z.string(),
|
||||||
application: z.string().nullable(),
|
application: z.string().nullable(),
|
||||||
@@ -386,6 +380,17 @@ export const flowMapServiceDtoSchema = z.object({
|
|||||||
basis: flowServiceBasisSchema,
|
basis: flowServiceBasisSchema,
|
||||||
bytes: z.number().positive(),
|
bytes: z.number().positive(),
|
||||||
})).max(flowServiceBasisSchema.options.length).optional(),
|
})).max(flowServiceBasisSchema.options.length).optional(),
|
||||||
|
}
|
||||||
|
|
||||||
|
export const flowMapServiceDtoSchema = z.object({
|
||||||
|
id: z.string(),
|
||||||
|
label: z.string(),
|
||||||
|
category: z.string(),
|
||||||
|
bytes: z.number().nonnegative(),
|
||||||
|
bps: z.number().nonnegative(),
|
||||||
|
share: z.number().min(0).max(1),
|
||||||
|
lastBucketAt: z.string().datetime().optional(),
|
||||||
|
...flowMapClassificationFields,
|
||||||
})
|
})
|
||||||
|
|
||||||
export const flowMapServiceEdgeDtoSchema = z.object({
|
export const flowMapServiceEdgeDtoSchema = z.object({
|
||||||
@@ -416,6 +421,7 @@ export const flowMapServicePathDtoSchema = z.object({
|
|||||||
serviceId: z.string(),
|
serviceId: z.string(),
|
||||||
bytes: z.number().nonnegative(),
|
bytes: z.number().nonnegative(),
|
||||||
bps: z.number().nonnegative(),
|
bps: z.number().nonnegative(),
|
||||||
|
...flowMapClassificationFields,
|
||||||
})
|
})
|
||||||
|
|
||||||
/** Сервисы внутри одной страны: id вида `cc:us|svc:google`, рёбра от `countryId`. */
|
/** Сервисы внутри одной страны: id вида `cc:us|svc:google`, рёбра от `countryId`. */
|
||||||
|
|||||||
@@ -36,3 +36,64 @@ for(const change of ["backend","mode"])for(const part of ["snapshot","flow","dns
|
|||||||
if(change==="backend")await expect(page.getByRole("button",{name:"Устройство Новая карта",exact:true})).toBeVisible()
|
if(change==="backend")await expect(page.getByRole("button",{name:"Устройство Новая карта",exact:true})).toBeVisible()
|
||||||
expect(newReads).toBe(before)
|
expect(newReads).toBe(before)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test("Карта: плотные группы WAN и узлов раскрывают отказ и найденный объект", async ({page}) => {
|
||||||
|
const uplinks = Array.from({length: 12}, (_, i) => ({
|
||||||
|
...wan, id: "wan-" + i, name: "Uplink-" + (i + 1), iface: "ether" + (i + 1), ip: "198.51.100." + (i + 1),
|
||||||
|
}))
|
||||||
|
const routers = Array.from({length: 12}, (_, i) => ({
|
||||||
|
id: i + 2, name: "NSK-JH-" + String(i + 1).padStart(2, "0"), host: "192.0.2." + (i + 2),
|
||||||
|
type: "jump-host", site: "Новосибирск", country: "RU", enabled: true, status: "online",
|
||||||
|
}))
|
||||||
|
const exit = {id: 20, name: "ARN-EXIT", host: "192.0.2.20", type: "exit-node", site: "Стокгольм", country: "SE", enabled: true, status: "online"}
|
||||||
|
const tunnels = ["up", "down", "up"].map((status, i) => ({
|
||||||
|
id: "gre-" + i, name: "gre-arn-" + i, serverId: String(routers[0].id), localAddress: routers[0].host, remoteAddress: exit.host,
|
||||||
|
localInnerIp: `10.60.${i}.1/30`, remoteInnerIp: `10.60.${i}.2/30`, poolId: "pool", ipsec: null, mtu: 1476,
|
||||||
|
keepaliveInterval: 10, keepaliveRetries: 3, dscp: "inherit", clampTcpMss: true, allowFastPath: true, comment: "", enabled: true, status,
|
||||||
|
}))
|
||||||
|
await page.route("**/health", route => route.fulfill({headers, json: {ok: true}}))
|
||||||
|
await page.route("**/api/**", route => {
|
||||||
|
const url = new URL(route.request().url())
|
||||||
|
const replies: Record<string, unknown> = {
|
||||||
|
"/api/auth/config": {required: false},
|
||||||
|
"/api/servers": [{...row("NSK-HOME"), site: "Новосибирск", wanUplinks: uplinks}, ...routers, exit],
|
||||||
|
"/api/filters/gre-tunnels": {tunnels, failures: []},
|
||||||
|
"/api/uptime/speed-probes": {probes: []},
|
||||||
|
"/api/traffic/flow/map-hops": emptyMapFlow(url),
|
||||||
|
}
|
||||||
|
return route.fulfill({headers, json: replies[url.pathname] ?? {}})
|
||||||
|
})
|
||||||
|
await page.goto("/network-map")
|
||||||
|
const roleGroup = page.locator("[data-map-group]").filter({hasText: "JH ×12"})
|
||||||
|
const wanGroup = page.locator("[data-map-group]").filter({hasText: "WAN ×12"})
|
||||||
|
const hiddenServer = page.getByRole("button", {name: "Устройство NSK-JH-12", exact: true})
|
||||||
|
const hiddenWan = page.getByRole("button", {name: "Аплинк Uplink-12", exact: true})
|
||||||
|
await expect(roleGroup).toHaveAttribute("aria-expanded", "false")
|
||||||
|
await expect(roleGroup).toContainText("Проблемы · 1")
|
||||||
|
await expect(wanGroup).toHaveAttribute("aria-expanded", "false")
|
||||||
|
await expect(hiddenServer).toHaveCount(0)
|
||||||
|
await expect(hiddenWan).toHaveCount(0)
|
||||||
|
|
||||||
|
const line = page.locator('[data-map-group-link="gre"]')
|
||||||
|
await expect(line).toHaveAttribute("data-channel-count", "3")
|
||||||
|
await expect(line).toHaveAttribute("data-channel-down", "1")
|
||||||
|
const marker = page.locator('[data-map-group-link-label="gre"]')
|
||||||
|
await expect(marker).toBeVisible()
|
||||||
|
await marker.click()
|
||||||
|
await expect(roleGroup).toHaveAttribute("aria-expanded", "true")
|
||||||
|
await expect(page.getByRole("button", {name: /^Устройство NSK-JH-/})).toHaveCount(12)
|
||||||
|
await expect(wanGroup).toHaveAttribute("aria-expanded", "false")
|
||||||
|
await roleGroup.press("Enter")
|
||||||
|
await expect(hiddenServer).toHaveCount(0)
|
||||||
|
|
||||||
|
const search = page.getByRole("textbox", {name: "Поиск узла или назначения"})
|
||||||
|
const results = page.getByRole("group", {name: "Подсказки поиска"})
|
||||||
|
await search.fill("NSK-JH-12")
|
||||||
|
await results.getByRole("button", {name: /NSK-JH-12/}).click()
|
||||||
|
await expect(hiddenServer).toHaveAttribute("aria-pressed", "true")
|
||||||
|
await expect(roleGroup).toHaveAttribute("aria-expanded", "true")
|
||||||
|
await search.fill("Uplink-12")
|
||||||
|
await results.getByRole("button", {name: /Uplink-12/}).click()
|
||||||
|
await expect(hiddenWan).toHaveAttribute("aria-pressed", "true")
|
||||||
|
await expect(wanGroup).toHaveAttribute("aria-expanded", "true")
|
||||||
|
})
|
||||||
@@ -145,6 +145,43 @@ test("Карта показывает скорость и долю за коро
|
|||||||
await expect(dns).toContainText("72 Кбит/с")
|
await expect(dns).toContainText("72 Кбит/с")
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test("На узком экране таблица назначений сортирует категории и открывает их сервисы", async ({page}) => {
|
||||||
|
await page.setViewportSize({width:320,height:780})
|
||||||
|
const services = [
|
||||||
|
{id:"svc:youtube", label:"YouTube", category:"Видео / стриминг", bytes:60, bps:6, share:0.6},
|
||||||
|
{id:"svc:cloudflare", label:"Cloudflare", category:"CDN", bytes:40, bps:4, share:0.4},
|
||||||
|
]
|
||||||
|
await page.route("**/api/**",route => {
|
||||||
|
const url = new URL(route.request().url())
|
||||||
|
const responses: Record<string,unknown> = {
|
||||||
|
"/api/auth/config":{required:false}, "/api/servers":[server], "/api/filters/gre-tunnels":{tunnels:[],failures:[]},
|
||||||
|
"/api/uptime/speed-probes":{probes:[]},
|
||||||
|
[flowPath]:{...emptyMapFlow(url),services,totalBytes:100,namedBytes:100},
|
||||||
|
}
|
||||||
|
return route.fulfill({json:responses[url.pathname] ?? {}})
|
||||||
|
})
|
||||||
|
await page.goto("/network-map")
|
||||||
|
const analysis = page.getByRole("region", {name:"Рабочая панель карты"})
|
||||||
|
await analysis.getByRole("tab", {name:/Назначения/}).click()
|
||||||
|
const grid = analysis.getByRole("table")
|
||||||
|
const sorter = grid.getByRole("button", {name:"Категория",exact:true})
|
||||||
|
await expect(sorter).toBeVisible()
|
||||||
|
const viewport = analysis.locator('[data-slot="scroll-area-viewport"]')
|
||||||
|
const bounds = await viewport.boundingBox()
|
||||||
|
const header = await sorter.boundingBox()
|
||||||
|
expect(header && bounds && header.x + header.width <= bounds.x + bounds.width).toBe(true)
|
||||||
|
expect(await viewport.evaluate(el => el.scrollWidth > el.clientWidth)).toBe(true)
|
||||||
|
await sorter.click()
|
||||||
|
const first = grid.locator("tbody tr").first()
|
||||||
|
await expect(first).toContainText("Cloudflare")
|
||||||
|
await sorter.click()
|
||||||
|
await expect(first).toContainText("YouTube")
|
||||||
|
await grid.getByRole("button", {name:"CDN",exact:true}).click()
|
||||||
|
const members = page.getByRole("region", {name:"Сервисы категории"})
|
||||||
|
await expect(members).toContainText("Cloudflare")
|
||||||
|
await expect(members).not.toContainText("YouTube")
|
||||||
|
})
|
||||||
|
|
||||||
test("Карта не приписывает весь YouTube единственному выходу ARN", async ({page}) => {
|
test("Карта не приписывает весь YouTube единственному выходу ARN", async ({page}) => {
|
||||||
const service = {id: "svc:youtube", label: "YouTube", category: "Видео", bytes: 900000, bps: 24000, share: 1,
|
const service = {id: "svc:youtube", label: "YouTube", category: "Видео", bytes: 900000, bps: 24000, share: 1,
|
||||||
trafficTypes: [{transport: "UDP", application: "QUIC", bytes: 900000}],
|
trafficTypes: [{transport: "UDP", application: "QUIC", bytes: 900000}],
|
||||||
@@ -191,7 +228,8 @@ test("Карта: DNS виден от экспортёра, пользовате
|
|||||||
{clientId: "u1", clientName: "Алиса", bytes: 225000, bps: 6000},
|
{clientId: "u1", clientName: "Алиса", bytes: 225000, bps: 6000},
|
||||||
{clientId: "—", clientName: "—", bytes: 75000, bps: 2000},
|
{clientId: "—", clientName: "—", bytes: 75000, bps: 2000},
|
||||||
]
|
]
|
||||||
const servicePaths = users.map(u => ({...u, viaId: "1", viaName: "MSK", viaIface: "ether1", enId: "", enName: "", serviceId: dns.id}))
|
const servicePaths = users.map(u => ({...u, viaId: "1", viaName: "MSK", viaIface: "ether1", enId: "", enName: "", serviceId: dns.id,
|
||||||
|
...(u.clientId === "u1" && {serviceEvidence: [{basis: "port", bytes: u.bytes}], trafficTypes: [{transport: "UDP", application: "DNS", bytes: u.bytes}]})}))
|
||||||
await page.route("**/api/**", route => {
|
await page.route("**/api/**", route => {
|
||||||
const url = new URL(route.request().url())
|
const url = new URL(route.request().url())
|
||||||
const path = url.pathname
|
const path = url.pathname
|
||||||
@@ -229,6 +267,14 @@ test("Карта: DNS виден от экспортёра, пользовате
|
|||||||
await expect(panel.getByText(/интерфейс ether1 · выход не подтверждён/i).first()).toBeVisible()
|
await expect(panel.getByText(/интерфейс ether1 · выход не подтверждён/i).first()).toBeVisible()
|
||||||
await panel.getByRole("button").filter({hasText: /Алиса.*Наблюдение IPFIX/}).click()
|
await panel.getByRole("button").filter({hasText: /Алиса.*Наблюдение IPFIX/}).click()
|
||||||
await expect(panel.getByRole("button", {pressed: true}).filter({hasText: "Наблюдение IPFIX"})).toHaveCount(1)
|
await expect(panel.getByRole("button", {pressed: true}).filter({hasText: "Наблюдение IPFIX"})).toHaveCount(1)
|
||||||
|
const flow = panel.getByRole("region", {name: "Выбранный поток"})
|
||||||
|
await expect(flow.getByText("По протоколу / порту", {exact: true})).toBeVisible()
|
||||||
|
await expect(flow).toContainText("DNS · UDP")
|
||||||
|
await expect(flow).toContainText("выход не подтверждён")
|
||||||
|
await panel.getByRole("button", {pressed: false}).filter({hasText: "Наблюдение IPFIX"}).click()
|
||||||
|
await expect(flow).toContainText("Не определена")
|
||||||
|
await expect(flow).toContainText("Основание классификации в этом снимке не передано")
|
||||||
|
await expect(flow).not.toContainText("По протоколу / порту")
|
||||||
await page.getByRole("button", {name: "Устройство MSK", exact: true}).press("Enter")
|
await page.getByRole("button", {name: "Устройство MSK", exact: true}).press("Enter")
|
||||||
await expect(breakdown.getByText("Алиса", {exact: true}).locator("..")).toContainText("75%")
|
await expect(breakdown.getByText("Алиса", {exact: true}).locator("..")).toContainText("75%")
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -8,6 +8,71 @@ test.beforeEach(async({page})=>{
|
|||||||
await page.route("**/health",r=>r.fulfill({json:{ok:true}}))
|
await page.route("**/health",r=>r.fulfill({json:{ok:true}}))
|
||||||
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p==="/api/servers"?[{...home,name:"Домашний роутер с очень длинным названием и описанием устройства"},{...jh,name:"Промежуточный узел с длинной подписью"}]:p==="/api/filters/gre-tunnels"?{tunnels:[tunnel],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/traffic/flow/map-hops"?emptyMapFlow(r.request().url()):p==="/api/auth/config"?{required:false}:{}})})
|
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p==="/api/servers"?[{...home,name:"Домашний роутер с очень длинным названием и описанием устройства"},{...jh,name:"Промежуточный узел с длинной подписью"}]:p==="/api/filters/gre-tunnels"?{tunnels:[tunnel],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/traffic/flow/map-hops"?emptyMapFlow(r.request().url()):p==="/api/auth/config"?{required:false}:{}})})
|
||||||
})
|
})
|
||||||
|
for (const width of [320, 390]) test("Карта: мобильные колонки, выбор отказа и поиск WAN " + width, async ({page}) => {
|
||||||
|
const uplinks = Array.from({length: 8}, (_, i) => ({...wan, id: "wan-" + i, name: "Провайдер " + (i + 1), iface: "ether" + (i + 1)}))
|
||||||
|
await page.route("**/api/servers", r => r.fulfill({json: [{...home, wanUplinks: uplinks}, jh]}))
|
||||||
|
await page.route("**/api/filters/gre-tunnels", r => r.fulfill({json: {tunnels: [{...tunnel, status: "down"}], failures: []}}))
|
||||||
|
await page.setViewportSize({width, height: 900})
|
||||||
|
await page.goto("/network-map")
|
||||||
|
const map = page.getByRole("group", {name: "Интерактивная карта сети"})
|
||||||
|
const nav = page.getByRole("navigation", {name: "Колонки карты"})
|
||||||
|
const lane = nav.getByRole("combobox", {name: "Перейти к колонке"})
|
||||||
|
await expect(lane).toHaveValue("home")
|
||||||
|
await nav.getByRole("button", {name: "Следующая колонка"}).click()
|
||||||
|
await expect(lane).toHaveValue("wan")
|
||||||
|
await nav.getByRole("button", {name: "Предыдущая колонка"}).click()
|
||||||
|
await expect(lane).toHaveValue("home")
|
||||||
|
await lane.selectOption("access-nodes")
|
||||||
|
await expect(nav.getByRole("button", {name: "Следующая колонка"})).toBeDisabled()
|
||||||
|
await nav.getByRole("button", {name: "К отказу"}).click()
|
||||||
|
const panel = page.getByRole("complementary", {name: "Детали объекта карты"})
|
||||||
|
await expect(panel).toContainText(tunnel.name)
|
||||||
|
await page.keyboard.press("Escape")
|
||||||
|
await expect(panel).toHaveCount(0)
|
||||||
|
const search = page.getByRole("textbox", {name: "Поиск узла или назначения"})
|
||||||
|
await search.fill("ether8")
|
||||||
|
await page.getByRole("group", {name: "Подсказки поиска"}).getByRole("button", {name: /Провайдер 8/}).click()
|
||||||
|
await expect(page).toHaveURL(/[?&]wan=7\b/)
|
||||||
|
await expect(lane).toHaveValue("wan")
|
||||||
|
const uplink = map.getByRole("button", {name: "Аплинк Провайдер 8"})
|
||||||
|
await expect(uplink).toHaveAttribute("aria-pressed", "true")
|
||||||
|
await expect.poll(() => uplink.evaluate(node => {
|
||||||
|
const r = node.getBoundingClientRect(), view = node.closest("svg")!.getBoundingClientRect()
|
||||||
|
return r.left >= view.left && r.right <= view.right && r.top >= view.top && r.bottom <= view.bottom
|
||||||
|
})).toBe(true)
|
||||||
|
await map.focus()
|
||||||
|
const before = await map.getAttribute("viewBox")
|
||||||
|
await map.press("+")
|
||||||
|
await expect(map).not.toHaveAttribute("viewBox", before!)
|
||||||
|
const after = await map.getAttribute("viewBox")
|
||||||
|
await page.waitForResponse(response => response.url().includes("/api/traffic/flow/map-hops") && new URL(response.url()).searchParams.get("range") === "1m")
|
||||||
|
await expect(map).toHaveAttribute("viewBox", after!)
|
||||||
|
await expect(uplink).toHaveAttribute("aria-pressed", "true")
|
||||||
|
expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true)
|
||||||
|
})
|
||||||
|
test("Карта: поиск и прямая ссылка показывают устройство из плотной группы рядом с инспектором", async ({page}) => {
|
||||||
|
const servers = Array.from({length: 12}, (_, i) => ({...jh, id: i + 1, name: "Шлюз " + (i + 1), host: "192.0.2." + (i + 1), site: "Тест"}))
|
||||||
|
await page.route("**/api/servers", r => r.fulfill({json: servers}))
|
||||||
|
await page.route("**/api/filters/gre-tunnels", r => r.fulfill({json: {tunnels: [], failures: []}}))
|
||||||
|
await page.goto("/network-map")
|
||||||
|
const map = page.getByRole("group", {name: "Интерактивная карта сети"})
|
||||||
|
const node = map.getByRole("button", {name: "Устройство Шлюз 12", exact: true})
|
||||||
|
const search = page.getByRole("textbox", {name: "Поиск узла или назначения"})
|
||||||
|
await search.fill("Шлюз 12")
|
||||||
|
await page.getByRole("group", {name: "Подсказки поиска"}).getByRole("button", {name: /Шлюз 12/}).click()
|
||||||
|
await expect(page).toHaveURL(/[?&]server=12\b/)
|
||||||
|
async function checkFraming() {
|
||||||
|
await expect(node).toHaveAttribute("aria-pressed", "true")
|
||||||
|
await expect.poll(() => node.evaluate(el => {
|
||||||
|
const card = el.getBoundingClientRect(), canvas = el.closest("svg")!.getBoundingClientRect()
|
||||||
|
const panel = document.querySelector('[aria-label="Детали объекта карты"]')!.getBoundingClientRect()
|
||||||
|
return card.left >= canvas.left && card.right <= panel.left && card.top >= canvas.top && card.bottom <= canvas.bottom
|
||||||
|
})).toBe(true)
|
||||||
|
}
|
||||||
|
await checkFraming()
|
||||||
|
await page.reload()
|
||||||
|
await checkFraming()
|
||||||
|
})
|
||||||
for(const width of [1440,390,320])test("Карта: доступные детали и адаптивная оболочка "+width,async({page},testInfo)=>{
|
for(const width of [1440,390,320])test("Карта: доступные детали и адаптивная оболочка "+width,async({page},testInfo)=>{
|
||||||
await page.setViewportSize({width,height:900});await page.goto("/network-map")
|
await page.setViewportSize({width,height:900});await page.goto("/network-map")
|
||||||
await expect(page.getByRole("button",{name:/^Устройство Домашний/})).toBeVisible()
|
await expect(page.getByRole("button",{name:/^Устройство Домашний/})).toBeVisible()
|
||||||
@@ -34,6 +99,25 @@ for(const width of [1440,390,320])test("Карта: доступные дета
|
|||||||
await page.getByRole("button",{name:"Слои",exact:true}).click();await expect(page.getByRole("dialog",{name:"Слои карты"})).toBeVisible()
|
await page.getByRole("button",{name:"Слои",exact:true}).click();await expect(page.getByRole("dialog",{name:"Слои карты"})).toBeVisible()
|
||||||
await page.keyboard.press("Escape");await expect(page.getByRole("button",{name:"Слои",exact:true})).toBeFocused();await expect(page).toHaveURL(/server=1/)
|
await page.keyboard.press("Escape");await expect(page.getByRole("button",{name:"Слои",exact:true})).toBeFocused();await expect(page).toHaveURL(/server=1/)
|
||||||
})
|
})
|
||||||
|
test("Из площадки в сводке можно открыть соседний канал и устройство без площадки", async ({ page }) => {
|
||||||
|
await page.route("**/api/servers", route => route.fulfill({ json: [{ ...home, site: "Москва" }, { ...jh, site: "" }] }))
|
||||||
|
await page.goto("/network-map")
|
||||||
|
await expect(page.getByRole("button", { name: "Устройство Домашний", exact: true })).toBeVisible()
|
||||||
|
await page.getByRole("button", { name: "Сводка сети" }).click()
|
||||||
|
const directory = page.getByRole("region", { name: "Площадки" })
|
||||||
|
await directory.getByRole("button", { name: /^Москва/ }).click()
|
||||||
|
await directory.getByText("Москва ↔ Без площадки").click()
|
||||||
|
await directory.getByRole("button", { name: /gre-home/ }).click()
|
||||||
|
await expect(page.getByRole("complementary", { name: "Детали объекта карты" })).toContainText("gre-home")
|
||||||
|
const search = page.getByRole("textbox", { name: "Поиск узла или назначения" })
|
||||||
|
await search.fill("Без площадки")
|
||||||
|
await page.getByRole("button", { name: "Без площадки Площадка" }).click()
|
||||||
|
await directory.getByRole("button", { name: /^Jump JumpHost/ }).click()
|
||||||
|
await expect(page).toHaveURL(/server=2/)
|
||||||
|
await page.getByRole("button", { name: "Журнал", exact: true }).click()
|
||||||
|
await expect(page.getByRole("tab", { name: /События/ })).toHaveAttribute("aria-selected", "true")
|
||||||
|
})
|
||||||
|
|
||||||
test("Карта: шкала и рабочая панель фокусируют сбой устройства",async({page})=>{
|
test("Карта: шкала и рабочая панель фокусируют сбой устройства",async({page})=>{
|
||||||
const now = new Date().toISOString()
|
const now = new Date().toISOString()
|
||||||
await page.route("**/api/events?*", route => route.fulfill({json:{events:[
|
await page.route("**/api/events?*", route => route.fulfill({json:{events:[
|
||||||
|
|||||||
@@ -35,6 +35,34 @@ async function overlaps(page: Page) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
test("Категория открывает сервисы, фильтрует потоки и сохраняет контекст при возврате", async ({ page }) => {
|
||||||
|
const services = [
|
||||||
|
{ id: "svc:video", label: "Видео A", category: "Видео", bytes: 900, bps: 120, share: 0.9 },
|
||||||
|
{ id: "svc:tiny", label: "Видео B", category: "Видео", bytes: 50, bps: 6, share: 0.05 },
|
||||||
|
{ id: "svc:dns", label: "DNS", category: "DNS", bytes: 50, bps: 6, share: 0.05 },
|
||||||
|
]
|
||||||
|
const paths = services.map(s => ({clientId: "a", clientName: "A", viaId: "1", viaName: "Вход", enId: "", enName: "", serviceId: s.id, bytes: s.bytes, bps: s.bps}))
|
||||||
|
const edges = services.map(s => ({fromId: "1", toId: s.id, observedOnly: true, bytes: s.bytes, bps: s.bps, bpsFwd: s.bps, bpsRev: 0}))
|
||||||
|
await serve(page, [srv(1, "Вход", "jump-host")], [], {services, servicePaths: paths, serviceEdges: edges, totalBytes: 1000, namedBytes: 1000})
|
||||||
|
await page.goto("/network-map")
|
||||||
|
await page.getByRole("button", {name: "Категории", exact: true}).click()
|
||||||
|
const map = page.getByRole("group", {name: "Интерактивная карта сети"})
|
||||||
|
const category = map.getByRole("button", {name: "Категория Видео", exact: true})
|
||||||
|
await expect(category).toContainText("95%")
|
||||||
|
await category.press("Enter")
|
||||||
|
const details = page.getByRole("complementary", {name: "Детали объекта карты"})
|
||||||
|
await expect(details.getByRole("heading", {name: "Видео", exact: true})).toBeVisible()
|
||||||
|
await details.getByRole("button", {name: "Потоки категории (2)"}).click()
|
||||||
|
const panel = page.getByRole("region", {name: "Рабочая панель карты"})
|
||||||
|
await expect(panel.getByText("Видео A", {exact: true})).toBeVisible()
|
||||||
|
await expect(panel.getByText("DNS", {exact: true})).toHaveCount(0)
|
||||||
|
await details.getByRole("button", {name: /Видео B/}).click()
|
||||||
|
await expect(page).toHaveURL(/service=svc%3Atiny/)
|
||||||
|
await expect(map.getByRole("button", {name: "Сервис Видео B", exact: true})).toBeVisible()
|
||||||
|
await page.goBack()
|
||||||
|
await expect(details.getByRole("heading", {name: "Видео", exact: true})).toBeVisible()
|
||||||
|
})
|
||||||
|
|
||||||
test("Карта: 3 JH → Exit + IX, параллельные GRE и 8 сервисов без наложений", async ({ page }) => {
|
test("Карта: 3 JH → Exit + IX, параллельные GRE и 8 сервисов без наложений", async ({ page }) => {
|
||||||
const servers = [
|
const servers = [
|
||||||
srv(1, "msk-gw01.example.net", "jump-host"), srv(2, "msk-gw02.example.net", "jump-host"), srv(3, "nov-gw01.example.net", "jump-host"),
|
srv(1, "msk-gw01.example.net", "jump-host"), srv(2, "msk-gw02.example.net", "jump-host"), srv(3, "nov-gw01.example.net", "jump-host"),
|
||||||
|
|||||||
Reference in new issue
Block a user