Compare commits

...
9 Commits
Author SHA1 Message Date
Denozordec 94c50b9660 fix(mcp): разрешить правила обнаружения отказа по адресу соседа
Docker images / prepare-release (push) Successful in 12s
Docker images / backend-test (push) Successful in 10m46s
Docker images / backend-image (push) Successful in 2m44s
Docker images / frontend-image (push) Successful in 2m19s
Docker images / updater-image (push) Successful in 39s
Docker images / netflow-agent-image (push) Successful in 32s
Docker images / notify-webhook (push) Successful in 2s
Docker images / publish-release (push) Successful in 10s
2026-11-30 23:45:06 +07:00
Denozordec fc39b0da3c fix(mcp): учитывать контекст экземпляра при настройке маршрутизации
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 10m42s
Docker images / frontend-image (push) Successful in 2m17s
Docker images / updater-image (push) Successful in 40s
Docker images / netflow-agent-image (push) Successful in 33s
Docker images / backend-image (push) Successful in 2m36s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
2026-11-30 22:40:29 +07:00
Denozordec 3c06a72349 fix(mcp): снимать свойство встроенного ключа туннеля вместо пустого значения
Docker images / prepare-release (push) Successful in 12s
Docker images / backend-test (push) Successful in 11m44s
Docker images / frontend-image (push) Successful in 5m2s
Docker images / updater-image (push) Successful in 4m40s
Docker images / netflow-agent-image (push) Successful in 34s
Docker images / backend-image (push) Successful in 3m30s
Docker images / publish-release (push) Successful in 13s
Docker images / notify-webhook (push) Successful in 2s
2026-11-30 21:32:41 +07:00
Denozordec ea13365f37 fix(mcp): принимать перечень команд при выполнении плана туннеля
Docker images / prepare-release (push) Successful in 13s
Docker images / backend-test (push) Successful in 11m46s
Docker images / frontend-image (push) Successful in 2m21s
Docker images / updater-image (push) Successful in 41s
Docker images / netflow-agent-image (push) Successful in 38s
Docker images / backend-image (push) Successful in 2m25s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
2026-11-30 20:00:42 +07:00
Denozordec 8a962c1984 fix(mcp): продолжать настройку туннелей со штатным набором алгоритмов
Docker images / prepare-release (push) Successful in 12s
Docker images / backend-test (push) Successful in 11m34s
Docker images / frontend-image (push) Successful in 2m23s
Docker images / updater-image (push) Successful in 46s
Docker images / netflow-agent-image (push) Successful in 37s
Docker images / backend-image (push) Successful in 2m8s
Docker images / publish-release (push) Successful in 15s
Docker images / notify-webhook (push) Successful in 2s
2026-11-30 19:28:43 +07:00
Denozordec 0a568f1640 feat(mcp): добавить отдельный режим шифрования для пары туннелей
Docker images / prepare-release (push) Successful in 15s
Docker images / backend-test (push) Successful in 11m43s
Docker images / frontend-image (push) Successful in 2m34s
Docker images / updater-image (push) Successful in 54s
Docker images / netflow-agent-image (push) Successful in 40s
Docker images / backend-image (push) Successful in 2m29s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
2026-11-30 17:50:41 +07:00
Denozordec 5233a9f194 fix(mcp): учесть большие таблицы маршрутов при создании туннелей
Docker images / prepare-release (push) Successful in 12s
Docker images / backend-test (push) Successful in 11m11s
Docker images / frontend-image (push) Successful in 2m25s
Docker images / updater-image (push) Successful in 1m4s
Docker images / netflow-agent-image (push) Successful in 37s
Docker images / backend-image (push) Successful in 2m22s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
2026-11-30 17:05:23 +07:00
Denozordec 645045a5d5 feat(mcp): добавить создание пары туннелей с автоматическим ключом
Docker images / prepare-release (push) Successful in 17s
Docker images / backend-test (push) Successful in 11m1s
Docker images / frontend-image (push) Successful in 2m30s
Docker images / updater-image (push) Successful in 1m0s
Docker images / netflow-agent-image (push) Successful in 49s
Docker images / backend-image (push) Successful in 2m16s
Docker images / publish-release (push) Successful in 15s
Docker images / notify-webhook (push) Successful in 1s
2026-11-30 16:00:45 +07:00
Denozordec b896e469a7 feat(mcp): добавить диагностику инцидентов и проверку отказоустойчивости сети
Docker images / prepare-release (push) Successful in 12s
Docker images / backend-test (push) Successful in 10m31s
Docker images / frontend-image (push) Successful in 2m18s
Docker images / updater-image (push) Successful in 39s
Docker images / netflow-agent-image (push) Successful in 31s
Docker images / backend-image (push) Successful in 2m11s
Docker images / publish-release (push) Successful in 11s
Docker images / notify-webhook (push) Successful in 2s
2026-11-27 17:21:20 +07:00
44 changed files with 2510 additions and 98 deletions

No files matched your search

+3 -1
View File
@@ -7,6 +7,8 @@
"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: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 src/modules/mcp/gre-ikev2-pair-actions.test.ts",
"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:users-bindings:pg": "node scripts/test-mcp-postgres.mjs --users-bindings",
"test:mcp:bridge-vlan:pg": "node scripts/test-mcp-postgres.mjs --bridge-vlan-configuration",
@@ -46,7 +48,7 @@
"test:probes": "npm run test:speed-workflow && tsx src/services/manual-data-collection-execution.test.ts && tsx src/routes/manual-data-collection.test.ts && tsx src/services/network-host-resolution.test.ts && tsx src/routes/probes.test.ts && tsx src/routes/probes.cancel.test.ts && tsx src/services/ping-measurement.test.ts && tsx src/services/uptime-probe-observations.test.ts && tsx src/services/ping-measurement-sql.test.ts",
"test:exec": "tsx src/services/mikrotik-logs.test.ts && tsx src/services/terminal-diagnostics.test.ts && tsx src/routes/exec.test.ts && tsx src/plugins/auth.exec.test.ts",
"test:auth": "tsx --test src/modules/mcp/routing-manual-inverse-history.test.ts && tsx src/db/application-writer-profile-registry-structure.test.ts && tsx src/db/application-writer-profile-registry-read.test.ts && tsx src/db/application-writer-profile-registry-read-parity.test.ts && tsx src/db/application-writer-profile-format.test.ts && tsx src/plugins/auth-path.test.ts && tsx src/lib/permissions.test.ts && tsx src/plugins/auth-provenance.test.ts && tsx src/services/bandwidth-rest-speed-original.test.ts && tsx src/plugins/auth.smoke.test.ts && tsx src/plugins/auth.ospf-optimizer.test.ts && npm run test:mcp",
"test:mcp": "node scripts/vrf-production-profile.test.mjs && node src/services/vrf-production-peer-telemetry.test.mjs && node src/services/vrf-execution-diagnostic.test.mjs && node src/services/vrf-transition-refusal.test.mjs && node src/services/vrf-production-gre-cycle.test.mjs && tsx src/services/vrf-production-gre-link-local.test.ts && tsx src/services/vrf-production-bridge-delete.test.ts && tsx src/services/vrf-production-transition.test.ts && tsx --test src/services/routeros-snapshot-read.test.ts src/services/bridge-vlan-configuration.test.ts src/modules/mcp/bridge-vlan-projection.test.ts src/modules/mcp/vrf-preparation-diagnostic.test.ts && tsx --test src/services/server-poll-error-provenance.test.ts && tsx --test src/modules/mcp/plan-expiry.test.ts src/modules/mcp/result-budget.test.ts src/modules/mcp/result-delivery.test.ts src/modules/mcp/wire-admission.test.ts src/modules/mcp/flow-envelope-allowance.test.ts src/modules/mcp/sdk-terminal-budget.test.ts src/modules/mcp/inflight-owner.test.ts && npm run test:database-source-binding && tsx --test src/modules/mcp/integration-fixture-expiry.test.ts && npm run test:mcp:operation-origin && npm run test:mcp:service-context && npm run test:mcp:operation-locks && tsx --test src/modules/mcp/routing-community-public.test.ts src/modules/mcp/management-transport.test.ts src/modules/mcp/routing-community-context-model.test.ts src/modules/mcp/routing-community-context-native.test.ts ../packages/contracts/src/mcp-routing.test.ts && tsx src/modules/mcp/human-artifact-receipts.test.ts && tsx src/modules/mcp/chr-overlay-readiness.test.ts && tsx src/modules/mcp/chr-recovery-source.test.ts && tsx src/modules/mcp/chr-native-failure.test.ts && tsx src/modules/mcp/ospf-owner-graph.test.ts && tsx src/modules/mcp/routing-measurement-address.test.ts && tsx src/modules/mcp/routing-observation-source.test.ts && tsx src/services/traffic-flow-talkers-model.test.ts && tsx src/services/bgp-prefix-model.test.ts && tsx src/services/vrf-members.test.ts && tsx src/services/routing-gateway-reference.test.ts && tsx src/services/bgp-export-model.test.ts && tsx src/services/traffic-history-model.test.ts && tsx src/services/internet-path-snapshot.test.ts && tsx src/services/internet-path-observation.test.ts && tsx src/modules/mcp/coverage.test.ts && tsx src/modules/mcp/policy.test.ts && tsx src/modules/mcp/events-batch-model.test.ts && tsx src/modules/mcp/operation-revisions.test.ts && tsx src/modules/mcp/native-create-identity.test.ts && tsx src/modules/mcp/ros-step-verification.test.ts && tsx src/modules/mcp/ros-prefix.test.ts && tsx src/modules/mcp/native-conservation-http.test.ts && tsx src/modules/mcp/security.test.ts && tsx src/modules/mcp/state-file-publish.test.ts && tsx src/modules/mcp/routing-model.test.ts && tsx src/modules/mcp/routing-observations-model.test.ts && tsx src/modules/mcp/ospf-health.test.ts && tsx src/modules/mcp/ecmp-preflight.test.ts && tsx src/modules/mcp/recursive-recovery.test.ts && tsx src/modules/mcp/control-path-model.test.ts && tsx src/modules/mcp/routing-community-scoped-model.test.ts && tsx src/modules/mcp/routing-community-scoped-native.test.ts && tsx src/modules/mcp/path-verification.test.ts && tsx src/modules/mcp/database-maintenance.test.ts && tsx src/routes/mcp.test.ts && tsx ../lib/auth-mcp.test.ts && tsx --test src/modules/mcp/routing-controller-fence.test.ts && tsx src/test/chr-vrf-companion-proof.test.ts && tsx src/test/chr-vrf-companion-telemetry.test.ts && tsx src/test/chr-vrf-companion-address-space.test.ts && tsx src/modules/mcp/flow-facts-rebuild-actions.test.ts && tsx src/modules/mcp/ipsec-peer-create-dependencies.test.ts && tsx src/services/ipsec-certificate-update-model.test.ts && tsx src/modules/mcp/ipsec-native-dispatch.test.ts && tsx src/modules/mcp/ipsec-user-update-actions.test.ts && tsx src/modules/mcp/ipsec-server-delete-actions.test.ts && tsx src/services/ipsec-proof-telemetry.test.ts && tsx src/services/vrf-production-admission.test.ts && tsx src/modules/mcp/flow-host-keys-actions.test.ts && tsx src/services/vrf-production-read.test.ts && tsx --test src/services/vrf-production-wireguard-alias.test.ts && tsx src/modules/mcp/ipsec-user-create-actions.test.ts && tsx src/modules/mcp/flow-settings-actions.test.ts && tsx src/services/vrf-production-ticket-store.test.ts && npm run test:mcp:routing-baseline",
"test:mcp": "node scripts/vrf-production-profile.test.mjs && node src/services/vrf-production-peer-telemetry.test.mjs && node src/services/vrf-execution-diagnostic.test.mjs && node src/services/vrf-transition-refusal.test.mjs && node src/services/vrf-production-gre-cycle.test.mjs && tsx src/services/vrf-production-gre-link-local.test.ts && tsx src/services/vrf-production-bridge-delete.test.ts && tsx src/services/vrf-production-transition.test.ts && tsx --test src/services/routeros-snapshot-read.test.ts src/services/bridge-vlan-configuration.test.ts src/modules/mcp/bridge-vlan-projection.test.ts src/modules/mcp/vrf-preparation-diagnostic.test.ts && tsx --test src/services/server-poll-error-provenance.test.ts && tsx --test src/modules/mcp/plan-expiry.test.ts src/modules/mcp/result-budget.test.ts src/modules/mcp/result-delivery.test.ts src/modules/mcp/wire-admission.test.ts src/modules/mcp/flow-envelope-allowance.test.ts src/modules/mcp/sdk-terminal-budget.test.ts src/modules/mcp/inflight-owner.test.ts && npm run test:database-source-binding && tsx --test src/modules/mcp/integration-fixture-expiry.test.ts && npm run test:mcp:operation-origin && npm run test:mcp:service-context && npm run test:mcp:operation-locks && tsx --test src/modules/mcp/routing-community-public.test.ts src/modules/mcp/management-transport.test.ts src/modules/mcp/routing-community-context-model.test.ts src/modules/mcp/routing-community-context-native.test.ts ../packages/contracts/src/mcp-routing.test.ts && tsx src/modules/mcp/human-artifact-receipts.test.ts && tsx src/modules/mcp/chr-overlay-readiness.test.ts && tsx src/modules/mcp/chr-recovery-source.test.ts && tsx src/modules/mcp/chr-native-failure.test.ts && tsx src/modules/mcp/ospf-owner-graph.test.ts && tsx src/modules/mcp/routing-measurement-address.test.ts && tsx src/modules/mcp/routing-observation-source.test.ts && tsx src/services/traffic-flow-talkers-model.test.ts && tsx src/services/bgp-prefix-model.test.ts && tsx src/services/vrf-members.test.ts && tsx src/services/routing-gateway-reference.test.ts && tsx src/services/bgp-export-model.test.ts && tsx src/services/traffic-history-model.test.ts && tsx src/services/internet-path-snapshot.test.ts && tsx src/services/internet-path-observation.test.ts && tsx src/modules/mcp/coverage.test.ts && tsx src/modules/mcp/policy.test.ts && tsx src/modules/mcp/events-batch-model.test.ts && tsx src/modules/mcp/operation-revisions.test.ts && tsx src/modules/mcp/native-create-identity.test.ts && tsx src/modules/mcp/ros-step-verification.test.ts && tsx src/modules/mcp/ros-prefix.test.ts && tsx src/modules/mcp/native-conservation-http.test.ts && tsx src/modules/mcp/security.test.ts && tsx src/modules/mcp/state-file-publish.test.ts && tsx src/modules/mcp/routing-model.test.ts && tsx src/modules/mcp/routing-observations-model.test.ts && tsx src/modules/mcp/ospf-health.test.ts && tsx src/modules/mcp/ecmp-preflight.test.ts && tsx src/modules/mcp/recursive-recovery.test.ts && tsx src/modules/mcp/control-path-model.test.ts && tsx src/modules/mcp/routing-community-scoped-model.test.ts && tsx src/modules/mcp/routing-community-scoped-native.test.ts && tsx src/modules/mcp/path-verification.test.ts && tsx src/modules/mcp/database-maintenance.test.ts && tsx src/routes/mcp.test.ts && tsx ../lib/auth-mcp.test.ts && tsx --test src/modules/mcp/routing-controller-fence.test.ts && tsx src/test/chr-vrf-companion-proof.test.ts && tsx src/test/chr-vrf-companion-telemetry.test.ts && tsx src/test/chr-vrf-companion-address-space.test.ts && tsx src/modules/mcp/flow-facts-rebuild-actions.test.ts && tsx src/modules/mcp/ipsec-peer-create-dependencies.test.ts && tsx src/services/ipsec-certificate-update-model.test.ts && tsx src/modules/mcp/ipsec-native-dispatch.test.ts && tsx src/modules/mcp/ipsec-user-update-actions.test.ts && tsx src/modules/mcp/ipsec-server-delete-actions.test.ts && tsx src/services/ipsec-proof-telemetry.test.ts && tsx src/services/vrf-production-admission.test.ts && tsx src/modules/mcp/flow-host-keys-actions.test.ts && tsx src/services/vrf-production-read.test.ts && tsx --test src/services/vrf-production-wireguard-alias.test.ts && tsx src/modules/mcp/ipsec-user-create-actions.test.ts && tsx src/modules/mcp/flow-settings-actions.test.ts && tsx src/services/vrf-production-ticket-store.test.ts && npm run test:mcp:routing-baseline && npm run test:mcp:network-diagnostics",
"test:wireguard": "tsx src/services/mikrotik-response-bounds.test.ts && tsx --test src/services/wireguard-dependency-read.test.ts && tsx src/services/wireguard-interface-update.test.ts && tsx src/services/wireguard-peer-update.test.ts && npx tsx src/services/wireguard-config.test.ts && npx tsx src/services/wireguard-ipv6.test.ts && npx tsx --test src/services/wireguard-import.test.ts src/services/wireguard-import-apply.test.ts src/services/wireguard-import-revision.test.ts src/services/wireguard-delete.test.ts && npx tsx src/routes/wireguard-import.test.ts && tsx src/services/wireguard-interface-create.test.ts && tsx src/services/wireguard-peer-create.test.ts && tsx src/services/wireguard-import-plan.test.ts && tsx src/services/wireguard-import-execution.test.ts && tsx src/modules/mcp/wireguard-import-actions.test.ts && tsx --test src/services/wireguard-export.test.ts",
"test:traffic-rate": "tsx src/services/traffic-rate.test.ts && tsx src/services/traffic-observation.test.ts && tsx src/services/traffic-freshness.test.ts && tsx src/services/traffic-live.test.ts && tsx src/services/traffic-observation-sql.test.ts && tsx src/services/traffic-history-sql.test.ts && tsx src/services/traffic-live-sql.test.ts && tsx src/services/traffic-volume-sql.test.ts && tsx src/services/traffic-binding-status.test.ts && tsx src/services/traffic-status-sql.test.ts && tsx src/services/traffic-gap.test.ts && tsx src/services/traffic-identity.test.ts && tsx src/services/traffic-membership.test.ts && tsx src/services/traffic-aggregate-peak.test.ts && tsx src/services/traffic-users-cache.test.ts && tsx src/services/traffic-collection-lock.test.ts && tsx src/services/traffic-concurrency-sql.test.ts",
"test:traffic-flow": "tsx --test src/services/traffic-flow-heartbeat.test.ts src/services/traffic-flow-heartbeat-wiring.test.ts src/services/traffic-flow-heartbeat-receiver.test.ts src/services/traffic-flow-ingest-quality.test.ts src/services/traffic-flow-quality-contract.test.ts && tsx src/services/traffic-flow-catalog-read.test.ts && tsx src/routes/traffic-flow-query.test.ts && tsx src/services/traffic-flow-month.test.ts && tsx src/services/traffic-flow-parse.test.ts && tsx src/services/traffic-flow-ipv6-pipeline.test.ts && tsx src/services/traffic-flow-map-exporter.test.ts && tsx src/services/traffic-flow-ifaces.test.ts && tsx src/services/traffic-flow-ifindex.test.ts && tsx src/services/traffic-flow-dedup.test.ts && tsx src/services/traffic-flow-planes.test.ts && tsx src/services/traffic-flow-ip.test.ts && tsx src/services/traffic-flow-dest.test.ts && tsx src/services/traffic-flow-classify.test.ts && tsx src/services/traffic-flow-ripe.test.ts && tsx src/services/traffic-flow-brands.test.ts && tsx src/services/traffic-flow-ingest.test.ts && tsx src/services/traffic-flow-analytics.test.ts && tsx src/services/traffic-flow-map-hops.test.ts && tsx src/services/traffic-flow-purge.test.ts && tsx src/services/geoip-download.test.ts && tsx src/services/traffic-flow-geoip.test.ts && tsx src/services/traffic-flow-fact-accumulator.test.ts && tsx src/services/traffic-flow-facts.test.ts && tsx src/services/traffic-flow-facts-filter.test.ts && tsx src/services/traffic-flow-facts-rebuild.test.ts && tsx src/services/statistics-aggregate.test.ts && tsx src/services/geoip-manual-update.test.ts && tsx src/services/traffic-flow-overlay-model.test.ts && npm run test:traffic-flow:ownership && tsx src/services/traffic-flow-worker-platform.test.ts && tsx src/services/traffic-flow-template-cache.test.ts && tsx --test src/services/traffic-flow-template-lifetime.test.ts && tsx src/services/traffic-flow-protocol-scope.test.ts && npm run test:traffic-flow:read-budget && npm run test:traffic-flow:resource-profile",
+7 -3
View File
@@ -178,6 +178,8 @@ if (usersBindings && (process.argv.length !== 3 || process.argv[2] !== '--users-
const bridgeVlanConfiguration = process.argv.includes('--bridge-vlan-configuration')
if (bridgeVlanConfiguration && process.argv.slice(2).some(arg => arg !== '--bridge-vlan-configuration')) throw new Error('Bridge VLAN acceptance requires its own disposable cluster')
const applicationAdapters = process.argv.includes('--application-adapters')
const networkDiagnostics = process.argv.includes('--network-diagnostics')
if (networkDiagnostics && process.argv.length !== 3) throw new Error('Network diagnostics require their own disposable cluster')
const scopedRoutingDiagnostics = process.argv.includes('--scoped-routing-diagnostics')
const interfaceEventsCompatibility = process.argv.includes('--interface-events-compatibility')
const eventsOnly = process.argv.includes('--events-only')
@@ -262,7 +264,7 @@ try {
await postgres.start()
const binaries = await import(`@embedded-postgres/${process.platform === 'win32' ? 'windows' : process.platform}-${process.arch}`)
const testPath = [process.env.MMAPP_PG_CLIENT_BIN, dirname(binaries.postgres), process.env.PATH ?? process.env.Path ?? ''].filter(Boolean).join(delimiter)
if (!profilesOnly && (restoreQuarantineOnly || process.argv.includes('--restore') || process.env.MMAPP_PG_CLIENT_BIN)) {
if (!profilesOnly && !networkDiagnostics && (restoreQuarantineOnly || process.argv.includes('--restore') || process.env.MMAPP_PG_CLIENT_BIN)) {
for (const command of ['pg_dump', 'pg_restore']) await new Promise((resolve, reject) => {
execFile(command, ['--version'], { env: { ...process.env, PATH: testPath }, windowsHide: true, timeout: 5000, maxBuffer: 4096 }, error => {
if (error) reject(new Error(`Restore acceptance requires working ${command}; set MMAPP_PG_CLIENT_BIN to the PostgreSQL client bin directory`))
@@ -274,8 +276,9 @@ try {
if (regressionOnly) console.log('Selected regression only: primary integration and terminal restore are not run')
if (profilesOnly) console.log('Profiles-only regression matrix: primary integration NOT RUN; terminal restore NOT RUN; full acceptance is not claimed')
const result = regressionOnly || profilesOnly ? 0 : await new Promise((resolve, reject) => {
const child = spawn(process.execPath, pollMemory ? ['--max-old-space-size=192', '--max-semi-space-size=16', fileURLToPath(new URL('../dist-mcp-memory/services/server-poll-memory.owned.test.js', import.meta.url))] : ['--import', 'tsx', ...(flowActiveRebuild ? ['--import', new URL('../src/services/traffic-flow-active-rebuild-preload.mjs', import.meta.url).href] : []), acceptanceShard ? 'src/modules/mcp/acceptance-shard.test.ts' : usersBindings ? 'src/modules/mcp/users-bindings-owned.test.ts' : bridgeVlanConfiguration ? 'src/modules/mcp/bridge-vlan-configuration-http.test.ts' : protocolLimits ? 'src/modules/mcp/protocol-limits.owned.test.ts' : principalSecuritySource ? 'src/modules/mcp/principal-security-source.owned.test.ts' : pollJournalSnapshot ? 'src/services/server-poll-journal-snapshot.owned.test.ts' : pollTerminalArchive ? 'src/services/server-poll-terminal-archive.owned.test.ts' : pollArchiveSchema ? 'src/db/server-poll-terminal-archives.sql.test.ts' : telemetrySettingsConfiguration ? 'src/modules/mcp/telemetry-settings-configuration.owned.test.ts' : routingReservationSchema ? 'src/db/routing-reservation-schema.owned.test.ts' : routingForwardRounds ? 'src/modules/mcp/routing-network-forward-rounds.owned.test.ts' : flowActiveServices ? 'src/services/traffic-flow-active-services.owned.test.ts' : flowActiveRebuild ? 'src/services/traffic-flow-active-rebuild.owned.test.ts' : flowQuality ? 'src/services/traffic-flow-quality.owned.test.ts' : flowWorkerIpc ? 'src/services/traffic-flow-worker-ipc.owned.test.ts' : manualUptime ? 'src/modules/mcp/manual-uptime-http.test.ts' : manualPingGroup ? 'src/modules/mcp/manual-ping-group-http.test.ts' : manualTraffic ? 'src/modules/mcp/manual-traffic-http.test.ts' : manualApiPing ? 'src/modules/mcp/manual-api-ping-http.test.ts' : simpleSpeedChr ? 'src/modules/mcp/simple-speed-chr.test.ts' : simpleSpeed ? 'src/modules/mcp/simple-speed-http.test.ts' : externalPeerMetadata ? 'src/services/bandwidth-external-peer-metadata.sql.test.ts' : operatorPeerMetadata ? 'src/services/bandwidth-operator-metadata.sql.test.ts' : publicRegistryMetadata ? 'src/services/bandwidth-public-registry.sql.test.ts' : operatorDockerSql ? 'src/services/bandwidth-operator-docker-stop.sql.test.ts' : probeOperationRetirement ? 'src/services/server-probe-operation-retirement.owned.test.ts' : ordinaryOperationRetirement ? 'src/modules/mcp/ordinary-operation-retirement.owned.test.ts' : pollOperationRetirement ? 'src/services/server-poll-operation-retirement.owned.test.ts' : mcpOperationOrigin ? 'src/modules/mcp/operation-execution-origin.sql.test.ts' : mcpSpeedOriginal ? 'src/modules/mcp/speed-bandwidth-original.sql.test.ts' : routerConfigurationGuard ? 'src/services/router-configuration-guard.sql.test.ts' : scheduledSpeedOriginal ? 'src/services/bandwidth-scheduled-speed-original.sql.test.ts' : bandwidthSpeedWorkflow ? 'src/services/bandwidth-speed-workflow.sql.test.ts' : restSpeedOriginal ? 'src/services/bandwidth-rest-speed-original.sql.test.ts' : operationLocks ? 'src/services/operation-config-lock-lease.sql.test.ts' : serviceExecutionOrigin ? 'src/modules/mcp/service-execution-origin.sql.test.ts' : bandwidthNodeSource ? 'src/services/bandwidth-node-source.sql.test.ts' : bandwidthExternalRegistry ? 'src/services/bandwidth-external-node-registry.sql.test.ts' : bandwidthNodeRegistry ? 'src/services/bandwidth-node-registry.sql.test.ts' : bandwidthControlSource ? 'src/services/bandwidth-control-source.sql.test.ts' : bandwidthAdmission ? 'src/services/bandwidth-admission.sql.test.ts' : serverPollStorageFresh ? 'src/services/server-poll-storage-fresh.sql.test.ts' : serverPollStorage ? 'src/services/server-poll-storage.sql.test.ts' : probeStorageFresh ? 'src/services/server-probe-storage-fresh.sql.test.ts' : probeLegacyOrphans ? 'src/services/server-probe-legacy-orphans.sql.test.ts' : diagnosticCancelHost ? 'src/modules/mcp/diagnostic-cancellation-storage.sql.test.ts' : ipsecExportHttp ? 'src/modules/mcp/ipsec-existing-certificate-export-http.sql.test.ts' : ipsecExportJournal ? 'src/services/ipsec-existing-certificate-export-rest-journal.sql.test.ts' : migrationDataInventory ? 'src/db/migration-data-inventory.sql.test.ts' : probeStorageHistory ? 'src/services/server-probe-storage-history.sql.test.ts' : probeStorageJournal ? 'src/services/server-probe-storage-journal.sql.test.ts' : controlledSchemaReference ? 'src/db/controlled-schema-reference.sql.test.ts' : controlledMigrations ? 'src/db/controlled-migrations.sql.test.ts' : databaseSchemaControl ? 'src/db/database-schema-control.sql.test.ts' : migrationSchemaInventory ? 'src/db/migration-schema-inventory.sql.test.ts' : routingNetworkNative ? 'src/modules/mcp/routing-network-native.sql.test.ts' : routingReservationRuntime ? 'src/modules/mcp/routing-reservation-runtime.sql.test.ts' : routingReservations ? 'src/modules/mcp/routing-reservation.sql.test.ts' : collectorPartitionWriters ? 'src/services/collector-partition-writes.sql.test.ts' : serverPollDurableLine truncated
const child = spawn(process.execPath, pollMemory ? ['--max-old-space-size=192', '--max-semi-space-size=16', fileURLToPath(new URL('../dist-mcp-memory/services/server-poll-memory.owned.test.js', import.meta.url))] : ['--import', 'tsx', ...(flowActiveRebuild ? ['--import', new URL('../src/services/traffic-flow-active-rebuild-preload.mjs', import.meta.url).href] : []), networkDiagnostics ? 'src/modules/mcp/network-diagnostics.owned.test.ts' : acceptanceShard ? 'src/modules/mcp/acceptance-shard.test.ts' : usersBindings ? 'src/modules/mcp/users-bindings-owned.test.ts' : bridgeVlanConfiguration ? 'src/modules/mcp/bridge-vlan-configuration-http.test.ts' : protocolLimits ? 'src/modules/mcp/protocol-limits.owned.test.ts' : principalSecuritySource ? 'src/modules/mcp/principal-security-source.owned.test.ts' : pollJournalSnapshot ? 'src/services/server-poll-journal-snapshot.owned.test.ts' : pollTerminalArchive ? 'src/services/server-poll-terminal-archive.owned.test.ts' : pollArchiveSchema ? 'src/db/server-poll-terminal-archives.sql.test.ts' : telemetrySettingsConfiguration ? 'src/modules/mcp/telemetry-settings-configuration.owned.test.ts' : routingReservationSchema ? 'src/db/routing-reservation-schema.owned.test.ts' : routingForwardRounds ? 'src/modules/mcp/routing-network-forward-rounds.owned.test.ts' : flowActiveServices ? 'src/services/traffic-flow-active-services.owned.test.ts' : flowActiveRebuild ? 'src/services/traffic-flow-active-rebuild.owned.test.ts' : flowQuality ? 'src/services/traffic-flow-quality.owned.test.ts' : flowWorkerIpc ? 'src/services/traffic-flow-worker-ipc.owned.test.ts' : manualUptime ? 'src/modules/mcp/manual-uptime-http.test.ts' : manualPingGroup ? 'src/modules/mcp/manual-ping-group-http.test.ts' : manualTraffic ? 'src/modules/mcp/manual-traffic-http.test.ts' : manualApiPing ? 'src/modules/mcp/manual-api-ping-http.test.ts' : simpleSpeedChr ? 'src/modules/mcp/simple-speed-chr.test.ts' : simpleSpeed ? 'src/modules/mcp/simple-speed-http.test.ts' : externalPeerMetadata ? 'src/services/bandwidth-external-peer-metadata.sql.test.ts' : operatorPeerMetadata ? 'src/services/bandwidth-operator-metadata.sql.test.ts' : publicRegistryMetadata ? 'src/services/bandwidth-public-registry.sql.test.ts' : operatorDockerSql ? 'src/services/bandwidth-operator-docker-stop.sql.test.ts' : probeOperationRetirement ? 'src/services/server-probe-operation-retirement.owned.test.ts' : ordinaryOperationRetirement ? 'src/modules/mcp/ordinary-operation-retirement.owned.test.ts' : pollOperationRetirement ? 'src/services/server-poll-operation-retirement.owned.test.ts' : mcpOperationOrigin ? 'src/modules/mcp/operation-execution-origin.sql.test.ts' : mcpSpeedOriginal ? 'src/modules/mcp/speed-bandwidth-original.sql.test.ts' : routerConfigurationGuard ? 'src/services/router-configuration-guard.sql.test.ts' : scheduledSpeedOriginal ? 'src/services/bandwidth-scheduled-speed-original.sql.test.ts' : bandwidthSpeedWorkflow ? 'src/services/bandwidth-speed-workflow.sql.test.ts' : restSpeedOriginal ? 'src/services/bandwidth-rest-speed-original.sql.test.ts' : operationLocks ? 'src/services/operation-config-lock-lease.sql.test.ts' : serviceExecutionOrigin ? 'src/modules/mcp/service-execution-origin.sql.test.ts' : bandwidthNodeSource ? 'src/services/bandwidth-node-source.sql.test.ts' : bandwidthExternalRegistry ? 'src/services/bandwidth-external-node-registry.sql.test.ts' : bandwidthNodeRegistry ? 'src/services/bandwidth-node-registry.sql.test.ts' : bandwidthControlSource ? 'src/services/bandwidth-control-source.sql.test.ts' : bandwidthAdmission ? 'src/services/bandwidth-admission.sql.test.ts' : serverPollStorageFresh ? 'src/services/server-poll-storage-fresh.sql.test.ts' : serverPollStorage ? 'src/services/server-poll-storage.sql.test.ts' : probeStorageFresh ? 'src/services/server-probe-storage-fresh.sql.test.ts' : probeLegacyOrphans ? 'src/services/server-probe-legacy-orphans.sql.test.ts' : diagnosticCancelHost ? 'src/modules/mcp/diagnostic-cancellation-storage.sql.test.ts' : ipsecExportHttp ? 'src/modules/mcp/ipsec-existing-certificate-export-http.sql.test.ts' : ipsecExportJournal ? 'src/services/ipsec-existing-certificate-export-rest-journal.sql.test.ts' : migrationDataInventory ? 'src/db/migration-data-inventory.sql.test.ts' : probeStorageHistory ? 'src/services/server-probe-storage-history.sql.test.ts' : probeStorageJournal ? 'src/services/server-probe-storage-journal.sql.test.ts' : controlledSchemaReference ? 'src/db/controlled-schema-reference.sql.test.ts' : controlledMigrations ? 'src/db/controlled-migrations.sql.test.ts' : databaseSchemaControl ? 'src/db/database-schema-control.sql.test.ts' : migrationSchemaInventory ? 'src/db/migration-schema-inventory.sql.test.ts' : routingNetworkNative ? 'src/modules/mcp/routing-network-native.sql.test.ts' : routingReservationRuntime ? 'src/modules/mcp/routing-reservation-runtime.sql.test.ts' : routingReservations ? 'src/modules/mcp/routing-reservation.sql.test.ts' : collectorPartitionWriters Line truncated
cwd: pollMemory ? directory : new URL('../', import.meta.url), stdio: 'inherit', env: { ...(pollMemory ? pollMemoryEnvironment : process.env),
MMAPP_OWN_NETWORK_DIAGNOSTICS: String(networkDiagnostics),
MMAPP_OWN_SKIP_POLL_CAPACITY: String(pollRetirementFocused),
MMAPP_OWN_PROTOCOL_LIMITS: String(protocolLimits),
MMAPP_OWN_EVENTS_ONLY: String(eventsOnly),
@@ -300,7 +303,7 @@ try {
})
exitCode = result
if (result === 0 && restoreQuarantineOnly) console.log('Restore quarantine: focused real PostgreSQL restore scenario complete')
else if (result === 0 && !acceptanceShard && !regressionOnly && !profilesOnly && !usersBindings && !bridgeVlanConfiguration && !protocolLimits && !pollMemory && !principalSecuritySource && !pollJournalSnapshot && !pollArchiveSchema && !telemetrySettingsConfiguration && !routingReservationSchema && !routingForwardRounds && !flowActiveServices && !flowActiveRebuild && !flowQuality && !flowWorkerIpc && !manualUptime && !manualPingGroup && !manualTraffic && !manualApiPing && !simpleSpeed && !simpleSpeedChr && !externalPeerMetadata && !operatorPeerMetadata && !publicRegistryMetadata && !operatorDockerSql && !mcpOperationOrigin && !mcpSpeedOriginal && !routerConfigurationGuard && !scheduledSpeedOriginal && !bandwidthSpeedWorkflow && !restSpeedOriginal && !operationLocks && !serviceExecutionOrigin && !bandwidthNodeSource && !bandwidthNodeRegistry && !bandwidthExternalRegistry && !bandwidthControlSource && !bandwidthAdmission && !probeLegacyOrphans && !probeStorageJournal && !probeStorageHistory && !probeJournal && !chr && !flowWrites && !flowRebuild && !flowRebuildMcp && (process.argv.includes('--restore') || process.env.MMAPP_PG_CLIENT_BIN)) {
else if (result === 0 && !networkDiagnostics && !acceptanceShard && !regressionOnly && !profilesOnly && !usersBindings && !bridgeVlanConfiguration && !protocolLimits && !pollMemory && !principalSecuritySource && !pollJournalSnapshot && !pollArchiveSchema && !telemetrySettingsConfiguration && !routingReservationSchema && !routingForwardRounds && !flowActiveServices && !flowActiveRebuild && !flowQuality && !flowWorkerIpc && !manualUptime && !manualPingGroup && !manualTraffic && !manualApiPing && !simpleSpeed && !simpleSpeedChr && !externalPeerMetadata && !operatorPeerMetadata && !publicRegistryMetadata && !operatorDockerSql && !mcpOperationOrigin && !mcpSpeedOriginal && !routerConfigurationGuard && !scheduledSpeedOriginal && !bandwidthSpeedWorkflow && !restSpeedOriginal && !operationLocks && !serviceExecutionOrigin && !bandwidthNodeSource && !bandwidthNodeRegistry && !bandwidthExternalRegistry && !bandwidthControlSource && !bandwidthAdmission && !probeLegacyOrphans && !probeStorageJournal && !probeStorageHistory && !probeJournal && !chr && !flowWrites && !flowRebuild && !flowRebuildMcp && (process.argv.includes('--restore') || process.env.MMAPP_PG_CLIENT_BIN)) {
exitCode = await new Promise((resolve, reject) => {
const child = spawn(process.execPath, ['--import', 'tsx', 'src/modules/mcp/database-restore.test.ts'], {
cwd: new URL('../', import.meta.url), stdio: 'inherit', env: { ...process.env,
@@ -313,6 +316,7 @@ try {
child.once('error', reject); child.once('exit', code => resolve(code ?? 1))
})
}
else if (result === 0 && networkDiagnostics) console.log('Network diagnostics: scoped MCP SDK and disposable PostgreSQL')
else if (result === 0 && pollArchiveSchema) console.log('Poll archive schema: owned nonempty40 preservation, numbered41 and structural refusal guards; no positive MCP archive claim')
else if (result === 0 && telemetrySettingsConfiguration) console.log('Telemetry settings: genuine MCP/SQL configuration binding, collector metadata tolerated; no native or external sources')
else if (result === 0 && routingReservationSchema) console.log('Routing reservation numbered0040: ownSQL fresh/legacy/manual preservation; no READY, backfill, capabilities or public native activation')
+14 -5
View File
@@ -1,4 +1,8 @@
import { registerIpsecServerDeleteActions } from "./ipsec-server-delete-actions.js"
import { registerCapabilityActions } from "./capability-actions.js"
import { registerIncidentActions } from "./incident-actions.js"
import { registerNetworkDiagnosticActions } from "./network-diagnostic-actions.js"
import { registerResilienceActions } from "./resilience-actions.js"
import { registerIpsecServerInitActions } from "./ipsec-server-init-actions.js"
import { registerIpsecRevisionActions } from "./ipsec-revision-actions.js"
import { registerWireguardRevisionActions } from "./wireguard-revision-actions.js"
@@ -30,7 +34,7 @@ import { gatewayReferencesTable, isDynamicRouteInsideTable } from "../../service
import { readLogStream } from "../../services/router-logs-query.js"
import { subscribeLogDevice } from "../../services/router-logs-collector.js"
import { ospfFilterFields, rosResources, readRosSnapshot, resourceById, routerClient, validateRosStep, splitOspfUnsetUpdate } from "./resources.js"
import { registerMcpOperation, listMcpOperations } from "./registry.js"
import { registerMcpOperation } from "./registry.js"
import { accessGeneration, decryptSecret, encryptSecret, fingerprint, MAX_MCP_PUBLIC_ARRAY_ITEMS, MAX_MCP_PUBLIC_STRING_LENGTH, McpError, redact } from "./security.js"
import { hasUnattendedPlanAuthority } from "./policy.js"
import { effectiveMcpConnection } from "./store.js"
@@ -76,6 +80,8 @@ import { prepareWireguardPeerDeletion, registerWireguardPeerDeleteActions } from
import { registerFirewallActions } from "./firewall-actions.js"
import { registerBfdMoveActions } from "./bfd-move-actions.js"
import { registerGreMutationActions } from "./gre-mutation-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 { registerGreRevisionActions } from "./gre-revision-actions.js"
import { prepareGreNativeChange, registerGreNativeServices } from "./gre-native-actions.js"
@@ -174,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()
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 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, {
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) => {
@@ -386,9 +392,8 @@ for (const definition of [
})
}
add("capabilities.read", "mm_capabilities_get", "Доступные возможности", "mcp", null, "read", "connection", z.object({}).strict(), {
read: async (_input, context) => ({ operations: listMcpOperations().filter(operation => operation.implementation === "available" && context.connection.policy.scope.operationIds.includes(operation.id)), schemaVersion: 1 }),
})
registerCapabilityActions(add)
registerIncidentActions(add)
add("servers.list", "mm_servers_list", "Серверы", "servers", "mm:servers:read", "read", "servers", z.object({ serverId: serverId.optional(), ...paging }).strict(), {
read: async (input, context) => {
const ids = typeof input.serverId === "number" ? [input.serverId] : context.connection.policy.scope.serverIds
@@ -664,6 +669,8 @@ add("operations.read", "mm_operation_get", "Результат своей опе
})
registerRoutingActions(add)
registerNetworkDiagnosticActions(add)
registerResilienceActions(add)
registerRoutingProfileActions(add)
registerRoutingControls(add)
registerLifecycleActions(add)
@@ -702,6 +709,8 @@ registerWireguardInterfaceDeleteActions(add)
registerFirewallActions(add)
registerBfdMoveActions(add)
registerGreMutationActions(add)
registerGreIpsecPairActions(add)
registerGreIke2PairActions(add)
registerIxActions(add)
registerGreRevisionActions(add)
registerGreNativeServices()
+15 -5
View File
@@ -1,5 +1,5 @@
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 { readOspfEffectiveDisabled } from "../../services/ospf-effective-disabled.js"
import { executeGuardedApplicationWrite } from "../../services/config-mutation-policy.js"
@@ -70,9 +70,18 @@ async function readState(input: Record<string, unknown>) {
return found[0]
}
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 [v4, v6] = await Promise.all([client.get<unknown>("/ip/route"), client.get<unknown>("/ipv6/route")])
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 instanceContext = await readBgpInstanceContext(client, { ...instance, ".id": String(instance[".id"]) })
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 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)
const objects: ChangeEvidence["objects"] = [
{ 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,
templates: templateProof.map(value => ({ id: value.row[".id"], name: value.row.name, mode: value.mode })),
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 }
}
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, {
version: 2,
prepare: async input => {
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,
@@ -1,6 +1,6 @@
import { z } from "zod"
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 { bgpFilterName, bgpFilterProperty, effectiveBgpFilter, stableBgpPolicyRow, type BgpFilterDirection } from "../../services/bgp-filter-binding-model.js"
import { readOspfEffectiveDisabled } from "../../services/ospf-effective-disabled.js"
@@ -60,12 +60,8 @@ 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" }))
if (!["false", "no"].includes(String(effectiveInstance.disabled))) throw new Error("BGP instance disabled/unknown")
Object.assign(instance, effectiveInstance)
for (const key of ["vrf", "routing-table"]) if (instance[key] === undefined || instance[key] === "") {
const value = bgpFilterName(await client.post("/routing/bgp/instance/get", { ".id": String(instance[".id"]), "value-name": key }))
if (!value) throw new Error("BGP instance effective context not confirmed")
instance[key] = value
}
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 instanceContext = await readBgpInstanceContext(client, instance)
if (unique("vrf", instanceContext.vrf)[".id"] !== vrf[".id"] || unique("routing_table", instanceContext.table)[".id"] !== table[".id"]) throw new Error("BGP instance/connection contexts disagree")
const filters = nativeBgpRows(await client.get("/routing/filter/rule"))
if (filters.length > 1000) throw new McpError("LIMIT_EXCEEDED", "Каталог BGP filters превышает 1000 строк", 409)
const selected = filters.filter(row => row.chain === desired)
@@ -81,7 +77,7 @@ async function readState(input: Record<string, unknown>) {
const uniqueObjects = [...new Map(objects.map(row => [fingerprint(row), row])).values()]
if (uniqueObjects.length > 1000) throw new Error("BGP dependency closure exceeds limit")
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),
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,
selectedRuleCount: selected.length, selectedEnabledRuleCount: effectiveFilters.filter(row => ["false", "no"].includes(String(row.disabled))).length, serverProof, dependencyProof,
@@ -112,6 +108,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, {
version: 2,
prepare: async 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,
@@ -0,0 +1,53 @@
import { z } from "zod"
import type { McpPolicyPreviewRequest } from "@mmapp/contracts/mcp"
import type { ActionContext } from "./action-types.js"
import type { add } from "./actions.js"
import { evaluateMcpPolicy } from "./policy.js"
import { listMcpOperations } from "./registry.js"
const identifier = z.string().trim().min(1).max(200).optional()
const capabilityInput = z.object({
operationId: identifier,
toolName: identifier,
section: identifier,
effect: z.enum(["read", "write", "diagnostic"]).optional(),
scope: z.enum(["servers", "global", "connection"]).optional(),
serverId: z.number().int().positive().safe().optional(),
includeApplicability: z.boolean().optional(),
applicable: z.boolean().optional(),
}).strict()
export function readCapabilities(input: z.infer<typeof capabilityInput>, connection: ActionContext["connection"], now = new Date()) {
const { policy, owner_permissions: ownerPermissions } = connection
const granted = new Set(policy.scope.operationIds)
const operations = listMcpOperations().filter(operation =>
operation.implementation === "available" && granted.has(operation.id) &&
(input.operationId === undefined || operation.id === input.operationId) &&
(input.toolName === undefined || operation.toolName === input.toolName) &&
(input.section === undefined || operation.section === input.section) &&
(input.effect === undefined || operation.effect === input.effect) &&
(input.scope === undefined || operation.scope === input.scope) &&
(input.serverId === undefined || operation.scope === "servers"))
if (!input.includeApplicability && input.serverId === undefined && input.applicable === undefined) return { operations, schemaVersion: 1 }
const assessed = operations.map(operation => {
const serverId = input.serverId ?? policy.scope.serverIds[0]
const target: McpPolicyPreviewRequest["target"] | null = operation.scope === "servers"
? serverId === undefined ? null : { scope: "servers", serverIds: [serverId] }
: { scope: operation.scope }
const assessment = target
? evaluateMcpPolicy({ operationId: operation.id, policy, ownerPermissions, target, objects: [], protections: [], objectCount: 0,
usage: { callsInMinute: 0, concurrentReads: 0, mutationsInHour: 0 }, auditAvailable: true }, now)
: { decision: "denied" as const, reasons: [{ code: "SERVER_DENIED", message: "Подключению не выдан доступ к серверам" }] }
return { ...operation, applicability: { decision: assessment.decision, reasons: assessment.reasons,
serverId: operation.scope === "servers" ? serverId ?? null : null } }
})
return { operations: assessed.filter(operation => input.applicable === undefined || input.applicable === (operation.applicability.decision !== "denied")),
schemaVersion: 1, applicabilityBasis: "effective-policy-before-arguments-and-runtime-checks", observedAt: now.toISOString() }
}
export function registerCapabilityActions(register: typeof add) {
register("capabilities.read", "mm_capabilities_get", "Доступные возможности", "mcp", null, "read", "connection", capabilityInput, {
read: async (input, context) => readCapabilities(capabilityInput.parse(input), context.connection),
})
}
@@ -42,11 +42,21 @@ export function registerLegacyFlowAnalyticsAction(register: typeof add) {
})
}
const flowTupleSchema = z.object({
srcIp: z.union([z.ipv4(), z.ipv6()]).optional().describe("Точный IP источника в экспортированной записи"),
dstIp: z.union([z.ipv4(), z.ipv6()]).optional().describe("Точный IP назначения в экспортированной записи"),
srcPort: z.number().int().min(0).max(65535).optional(),
dstPort: z.number().int().min(0).max(65535).optional(),
protocol: z.number().int().min(0).max(255).optional().describe("Номер IP-протокола IANA"),
})
const REPORT_ROW_LIMIT = 20000
export function registerFlowAnalyticsActions(register: typeof add) {
register("traffic.flow.analytics.read", "mm_netflow_analytics_report_get", "NetFlow: нагрузка, приложения и разговоры выбранного сервера", "traffic", "mm:traffic:read", "read", "servers", z.object({
register("traffic.flow.analytics.read", "mm_netflow_analytics_report_get", "NetFlow: нагрузка, приложения и разговоры выбранного сервера по сохранённым top-N данным", "traffic", "mm:traffic:read", "read", "servers", z.object({
serverId: z.number().int().positive().safe(), minutes: z.number().int().min(1).max(1440).default(15),
userId: z.string().min(1).max(100).optional(),
interface: z.string().trim().min(1).max(200).refine(value => !/[\u0000-\u001f\u007f]/.test(value) && value !== "__all__").optional(),
...flowTupleSchema.shape,
dedup: z.boolean().default(true), excludeMesh: z.boolean().default(true), excludeOverlay: z.boolean().default(true),
offset: z.number().int().min(0).max(100000).default(0), limit: z.number().int().min(1).max(100).default(50),
}).strict(), {
@@ -57,11 +67,15 @@ export function registerFlowAnalyticsActions(register: typeof add) {
const authorize = () => assertTrafficHistorySource(context, server)
const startedAt = new Date().toISOString()
try {
const filters = flowTupleSchema.parse(input)
const tuple = Object.values(filters).some(value => value !== undefined) ? filters : undefined
const requestedMinutes = Number(input.minutes)
const limits = await readFlowSourceLimits()
await authorize()
const { sourceWindow, ...raw } = await readFlowWindow(Number(input.minutes), minutes => buildFlowAnalytics({ serverId: server.id, minutes, userId: input.userId as string | undefined,
iface: input.interface as string | undefined, dedup: input.dedup === true, excludeMesh: input.excludeMesh === true, excludeOverlay: input.excludeOverlay === true },
{ serverIds: context.connection.policy.scope.serverIds, maxRows: 20000, authorize }), context.signal)
const { sourceWindow: reducedWindow, ...raw } = await readFlowWindow(requestedMinutes, minutes => buildFlowAnalytics({ serverId: server.id, minutes, userId: input.userId as string | undefined,
iface: input.interface as string | undefined, tuple, dedup: input.dedup === true, excludeMesh: input.excludeMesh === true, excludeOverlay: input.excludeOverlay === true },
{ serverIds: context.connection.policy.scope.serverIds, maxRows: REPORT_ROW_LIMIT, authorize }), context.signal)
const sourceWindow = { requestedMinutes, effectiveMinutes: reducedWindow?.effectiveMinutes ?? requestedMinutes, incomplete: reducedWindow !== undefined }
const result = flowAnalyticsDtoSchema.parse(raw)
const offset = Number(input.offset), limit = Number(input.limit), pages: Record<string, { total: number; nextOffset: number | null }> = {}
const analytics: Record<string, unknown> = { ...result }
@@ -74,12 +88,14 @@ export function registerFlowAnalyticsActions(register: typeof add) {
await authorize()
if ((await readFlowSourceLimits()).topN !== limits.topN) throw new McpError("STATE_CONFLICT", "Предел источника NetFlow изменился во время чтения", 409)
await authorize()
const output = { serverId: server.id, minutes: sourceWindow?.effectiveMinutes ?? Number(input.minutes), sourceWindow, interface: input.interface ?? null, userId: input.userId ?? null,
const output = { serverId: server.id, minutes: sourceWindow.effectiveMinutes, sourceWindow, interface: input.interface ?? null, userId: input.userId ?? null, filters,
analytics: retained, pages, contextRates: { bpsNowEstimate: _bpsNow, bpsWireEstimate: _bpsWire, bpsOverlayEstimate: _bpsOverlay, bytesWireEstimate: _bytesWire,
listenerBound: _live, userAttributionVerified: false, semantics: "REST estimates: filtered or overlay-inclusive rates use the latest complete retained minute with a window-average fallback; wire uses current interface snapshots" },
listenerBound: _live, userAttributionVerified: false, semantics: "REST estimates: filtered or overlay-inclusive rates use the latest complete retained minute with a window-average fallback; wire uses unfiltered current interface snapshots" },
readStartedAt: startedAt, observedAt: new Date().toISOString(), live: false,
source: "retained flow_buckets plus pending; same REST analytics engine with scoped topology",
rowLimit: 20000, topRowsPerBucketLimit: Math.max(20, limits.topN), engineTopListLimit: Math.min(50, Math.max(10, limits.topN)),
rowLimit: REPORT_ROW_LIMIT, topRowsPerBucketLimit: Math.max(20, limits.topN), engineTopListLimit: Math.min(50, Math.max(10, limits.topN)),
historicalDetail: { filtersAppliedTo: "retained rows before aggregation and pagination", rowLimitAppliedBeforeFilters: true,
discardedRowsRecoverable: false, exactTupleTotalsVerified: false },
incomplete: true, coverageVerified: false, rowSumIsNetworkTotal: false, forwardingVerified: false,
inferredPathsVerified: false, historicalOwnershipVerified: false, attribution: "current exclusive interface bindings, including confirmed single-peer WireGuard; users with hidden bindings excluded",
backgroundEnrichmentStarted: false, collectorStarted: false }
@@ -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.",
],
}
},
})
}
@@ -0,0 +1,78 @@
import assert from "node:assert/strict"
import test, { mock } from "node:test"
import type { add } from "./actions.js"
import type { McpAction } from "./action-types.js"
import type { GreMutation } from "../../services/gre-mutation-input.js"
const routerStates = new Map([
[3, { ipv4: [{ address: "192.0.2.3/24" }], gre: new Array<Record<string, string>>() }],
[6, { ipv4: [{ address: "198.51.100.6/24" }], gre: new Array<Record<string, string>>() }],
])
const writes: Array<{ id: number; mutation: GreMutation }> = []
mock.module("./resources.js", { namedExports: { async routerClient(id: number) { return { server: { id } } } } })
mock.module("./gre-mutation-actions.js", { namedExports: { async greMutationProtectionObjects(serverId: number) {
return [{ kind: "server", id: String(serverId), serverId }]
} } })
mock.module("../../services/gre-mutation-state.js", { namedExports: {
greMutationProof: (state: unknown) => state,
async readGreMutationState(server: { id: number }) { return structuredClone(routerStates.get(server.id)) },
} })
const { fingerprint, redact } = await import("./security.js")
mock.module("../../services/gre-mutation.js", { namedExports: {
planGreMutation: () => [{}],
async mutateGreTunnel(server: { id: number }, mutation: GreMutation, beforeFingerprint: string) {
const state = routerStates.get(server.id)!
assert.equal(beforeFingerprint, fingerprint(state))
assert.equal(mutation.operation, "create")
if (mutation.operation !== "create") throw new Error("expected create")
writes.push({ id: server.id, mutation })
state.gre.push({ name: mutation.fields.name, "remote-address": mutation.fields.remoteAddress })
return { verified: true, afterFingerprint: fingerprint(state), tunnel: { ipsecSecret: mutation.fields.ipsecSecret } }
},
} })
const { registerGreIpsecPairActions } = await import("./gre-ipsec-pair-actions.js")
const { findMcpService } = await import("./service-registry.js")
let action: Pick<McpAction, "prepare" | "target"> | undefined
let definition: { id: string; toolName: string } | undefined
const register: typeof add = (id, toolName, _title, _section, _permission, _effect, _scope, _schema, handlers) => {
definition = { id, toolName }
if (handlers.target) action = { prepare: handlers.prepare, target: handlers.target }
}
registerGreIpsecPairActions(register)
const input = { endpoints: [
{ serverId: 3, endpoint: "192.0.2.3", name: "gre-test-home", localInnerIp: "10.253.0.1/30" },
{ serverId: 6, endpoint: "198.51.100.6", name: "gre-test-nov", localInnerIp: "10.253.0.2/30" },
] }
const context = {} as Parameters<NonNullable<McpAction["prepare"]>>[1]
test("GRE/IPsec pair creates two disabled endpoints using one private key", async () => {
assert.equal(definition?.toolName, "mm_gre_ipsec_pair_create_plan")
const prepare = action!.prepare!, service = findMcpService(definition!.id)!
const evidence = await prepare(input, context), another = await prepare(input, context)
assert.deepEqual(await action!.target(input, context), { scope: "servers", serverIds: [3, 6] })
assert.deepEqual(evidence.objects.map(object => object.serverId), [3, 6])
assert.equal(writes.length, 0)
const [first, second] = evidence.steps.map(step => { assert.equal(step.kind, "service"); return step.kind === "service" ? step.input : {} })
const [other] = another.steps
assert.ok(other.kind === "service" && first.ipsecSecret !== other.input.ipsecSecret)
assert.match(String(first.ipsecSecret), /^[a-f0-9]{64}$/)
assert.equal(first.ipsecSecret, second.ipsecSecret)
assert.ok(!JSON.stringify(redact(evidence)).includes(String(first.ipsecSecret)))
await assert.rejects(prepare({ ...input, ipsecSecret: "caller-supplied" }, context))
await assert.rejects(prepare({ endpoints: input.endpoints.slice(0, 1) }, context))
await assert.rejects(prepare({ endpoints: [input.endpoints[0], input.endpoints[0]] }, context), /два разных сервера/)
await assert.rejects(prepare({ endpoints: [input.endpoints[0], { ...input.endpoints[1], endpoint: "203.0.113.6" }] }, context), /Внешний адрес GRE не найден/)
assert.deepEqual(await service.current(first), evidence.before)
for (const step of [first, second]) {
const receipt = await service.execute(step)
assert.ok(await service.verify!(step, receipt))
assert.ok(!JSON.stringify(receipt).includes(String(first.ipsecSecret)))
}
assert.deepEqual(writes.map(({ id, mutation }) => mutation.operation === "create" ?
[id, mutation.fields.localAddress, mutation.fields.remoteAddress, mutation.fields.enabled, mutation.fields.allowFastPath] : []), [
[3, "192.0.2.3", "198.51.100.6", false, false],
[6, "198.51.100.6", "192.0.2.3", false, false],
])
await assert.rejects(prepare(input, context), /уже есть GRE/)
})
@@ -0,0 +1,106 @@
import { randomBytes } from "node:crypto"
import { z } from "zod"
import { greCreateFieldsSchema, type GreMutation } from "../../services/gre-mutation-input.js"
import { greMutationProof, readGreMutationState } from "../../services/gre-mutation-state.js"
import { mutateGreTunnel, planGreMutation } from "../../services/gre-mutation.js"
import { observedBoolean } from "../../services/ospf-observed-values.js"
import type { ChangeEvidence } from "./action-types.js"
import type { add } from "./actions.js"
import { greMutationProtectionObjects } from "./gre-mutation-actions.js"
import { routerClient } from "./resources.js"
import { fingerprint, McpError } from "./security.js"
import { registerMcpService } from "./service-registry.js"
const operation = "network.gre.ipsec_pair.create"
const endpointSchema = greCreateFieldsSchema.pick({ name: true, localInnerIp: true, comment: true }).extend({
serverId: z.number().int().positive().safe(), endpoint: greCreateFieldsSchema.shape.remoteAddress,
})
const schema = z.object({
endpoints: z.array(endpointSchema).length(2),
mtu: greCreateFieldsSchema.shape.mtu,
}).strict()
const stepSchema = schema.extend({
side: z.union([z.literal(0), z.literal(1)]),
ipsecSecret: z.string().regex(/^[a-f0-9]{64}$/),
beforeFingerprint: z.string(),
})
type Pair = z.infer<typeof schema>
type Side = 0 | 1
const sides = [0, 1] as const
function target(input: Pair): ChangeEvidence["target"] {
const [first, second] = input.endpoints
if (first.serverId === second.serverId || first.endpoint === second.endpoint) {
throw new McpError("INVALID_INPUT", "Нужны два разных сервера и два разных внешних IPv4")
}
return { scope: "servers", serverIds: [first.serverId, second.serverId] }
}
function mutationFor(input: Pair, side: Side, ipsecSecret: string): GreMutation {
const local = input.endpoints[side], remote = input.endpoints[side === 0 ? 1 : 0]
return { operation: "create", fields: {
name: local.name, localAddress: local.endpoint, remoteAddress: remote.endpoint,
localInnerIp: local.localInnerIp, comment: local.comment, mtu: input.mtu ?? "auto",
enabled: false, allowFastPath: false, ipsecSecret,
} }
}
async function readSide(input: Pair, side: Side, ipsecSecret: string) {
const { server } = await routerClient(input.endpoints[side].serverId)
const mutation = mutationFor(input, side, ipsecSecret)
const state = await readGreMutationState(server, mutation)
return { server, mutation, state, proof: fingerprint(greMutationProof(state)) }
}
export function registerGreIpsecPairActions(register: typeof add) {
registerMcpService(operation, {
current: async raw => {
const input = stepSchema.parse(raw)
const before = await Promise.all(sides.map(side => readSide(input, side, input.ipsecSecret)))
return before.map(item => item.proof)
},
execute: async raw => {
const input = stepSchema.parse(raw)
const { server } = await routerClient(input.endpoints[input.side].serverId)
const { tunnel: _tunnel, ...receipt } = await mutateGreTunnel(server, mutationFor(input, input.side, input.ipsecSecret), input.beforeFingerprint)
return receipt
},
verify: async (raw, result) => {
const input = stepSchema.parse(raw)
const receipt = result as { verified?: boolean; afterFingerprint?: string } | null
return receipt?.verified === true && receipt.afterFingerprint === (await readSide(input, input.side, input.ipsecSecret)).proof
},
})
register(operation, "mm_gre_ipsec_pair_create_plan", "План создания пары GRE/IPsec с автоматическим PSK",
"network", "mm:network:write", "write", "servers", schema, {
target: raw => target(schema.parse(raw)),
prepare: async raw => {
const input = schema.parse(raw), scope = target(input)
const ipsecSecret = randomBytes(32).toString("hex")
const before = await Promise.all(sides.map(side => readSide(input, side, ipsecSecret)))
const mutationCost = sides.reduce<number>((cost, side) => {
const item = before[side]!, local = input.endpoints[side], remote = input.endpoints[side === 0 ? 1 : 0]
if (!item.state.ipv4.some(row => row.address.split("/")[0] === local.endpoint &&
observedBoolean(row.disabled) !== true && observedBoolean(row.invalid) !== true)) {
throw new McpError("STATE_CONFLICT", `Внешний адрес GRE не найден на сервере ${local.serverId}`, 409)
}
if (item.state.gre.some(row => [row["remote-address"], row["current-remote-address"]].includes(remote.endpoint))) {
throw new McpError("STATE_CONFLICT", `На сервере ${local.serverId} уже есть GRE с этим удалённым адресом`, 409)
}
return cost + planGreMutation(item.server, item.mutation, item.state).length + 1
}, 0)
return {
target: scope, objects: (await Promise.all(before.map(item => greMutationProtectionObjects(Number(item.server.id), item.state)))).flat(),
snapshots: [], before: before.map(item => item.proof), mutationCost, requiresHuman: true,
steps: sides.map(side => ({ kind: "service" as const, service: operation, input: {
...input, side, ipsecSecret, beforeFingerprint: before[side]!.proof,
} })),
warnings: [
"Создаются только два новых отключённых GRE. Стороны получают один автоматически сгенерированный PSK; FastPath отключён.",
"Стороны применяются и проверяются последовательно. При отказе второй стороны первая может остаться созданной и отключённой.",
"Установка IPsec SA и передача трафика проверяются после отдельного включения обоих интерфейсов.",
],
}
},
})
}
@@ -36,11 +36,15 @@ export function registerGreMutationActions(register: typeof add) {
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],{
version: operation === "delete" ? 1 : 2,
prepare:async(input,context)=>{
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)
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)) {
const name = mutation.operation==="create"?mutation.fields.name:target?.name
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(),{
version:2,
prepare:async(input,context)=>{
const req=request(input,context),source=await read(req,context.signal)
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")
writes++
if(base==="/interface/gre"&&data["ipsec-secret"]===""&&["yes","true"].includes(data["allow-fast-path"])){
res.statusCode=400;res.end(JSON.stringify({error:400,detail:"failure: cannot enable fastpath together with ipsec yet"}));return
if(base==="/interface/gre"&&data["ipsec-secret"]===""){
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)]))
if(!ignored){
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}
;(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==="DELETE")collections[base]=collections[base].filter(r=>r[".id"]!==path.slice(base.length+1))
else assert.fail("Unsupported native write")
@@ -0,0 +1,208 @@
import assert from "node:assert/strict"
import { mkdtemp, rm } from "node:fs/promises"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { after, mock, test } from "node:test"
import { mcpConnectionPolicySchema, mcpOperationDescriptorSchema } from "@mmapp/contracts/mcp"
import type { ActionContext } from "./action-types.js"
import type { add } from "./actions.js"
import { registerMcpOperation } from "./registry.js"
const queries: Array<{ sql: string; values: unknown[] }> = []
const from = "2026-11-27T00:00:00Z"
const to = "2026-11-27T01:00:00Z"
const observed = new Date("2026-11-27T00:15:00Z")
const newer = new Date("2026-11-27T00:30:00Z")
const observedPrecise = "2026-11-27T00:15:00.000000Z", newerPrecise = "2026-11-27T00:30:00.000002Z"
const fixtures = await mkdtemp(join(tmpdir(), "mcp-incident-test-"))
process.env.MCP_STATE_DIR = fixtures
after(() => rm(fixtures, { recursive: true, force: true }))
let paginate = false
mock.module("../../db/index.js", { namedExports: { pool: { async query(sql: string, values: unknown[]) {
queries.push({ sql, values })
if (sql === "SELECT enabled FROM servers WHERE id=$1") return { rows: [{ enabled: true }] }
if (sql.startsWith("SELECT id,enabled FROM servers")) {
assert.match(sql, /id=ANY\(\$1::bigint\[\]\) AND id>\$2/)
assert.deepEqual(values[0], [7, 9])
return { rows: values[1] === 0 ? [{ id: 7, enabled: true }, { id: 9, enabled: false }] : [{ id: 9, enabled: false }] }
}
if (sql.includes("FROM mcp_requests")) {
assert.match(sql, /server_ids=ARRAY\[\$1\]::bigint\[\]/)
assert.match(sql, /connection_id=\$5 AND actor_id=\$6 AND tool=ANY\(\$7::text\[\]\)/)
assert.deepEqual(values, [7, from, to, 51, "fixture-connection", "fixture-owner", ["mm_fixture_server"]])
return { rows: [{ at: newerPrecise, key: "request-id", id: "request-id", status: "completed", timestampKind: "request-created", toolName: "mm_fixture_server" }] }
}
assert.match(sql, /server_id=\$1/)
assert.ok(values[0] === 7 || values[0] === 9)
if (sql.includes("servers_rest_ping_samples")) {
if (values.length === 3) return { rows: [{ enabled: true, intervalSec: 60, observedAt: null, status: null }] }
return { rows: [{ at: observedPrecise, key: "", id: "poll", status: "ok", timestampKind: "backend-sample" }] }
}
if (sql.includes("router_log_entries")) {
const make = (at: string, id: string) => ({ at, id, key: id.padStart(20, "0"), status: "warning", timestampKind: "router", receivedAt: newer })
if (!paginate) return { rows: [make(newerPrecise, "41")] }
const rows = [make(newerPrecise, "100"), make(newerPrecise, "9"), make("2026-11-27T00:30:00.000001Z", "99")]
if (values.length === 4) return { rows: rows.slice(0, Number(values[3])) }
assert.match(sql, /\(effective_at,\(lpad\(id::text,20,'0'\)\) COLLATE "C"\) < \(\$5::timestamptz,\$6::text COLLATE "C"\)/)
assert.equal(values[4], newerPrecise)
return { rows: rows.filter(row => row.at < String(values[4]) || row.at === values[4] && row.key < String(values[5])).slice(0, Number(values[3])) }
}
if (sql.includes("router_log_collection_state")) throw Error("Sample source unavailable")
if (sql.includes("uptime_probe_samples")) {
assert.match(sql, /p\.src_server_id=\$1/)
assert.match(sql, /sampled_at>=p\.updated_at/)
assert.doesNotMatch(sql, /\bp\.(target|name|src_interface)\b/)
if (values.length === 3) return { rows: [{ enabled: true, intervalSec: 60, observedAt: observed, status: "warn" }] }
return { rows: [{ at: observedPrecise, key: "probe-1", id: "probe-1", status: "warn",
timestampKind: "backend-sample", rttMs: 50, lossPct: 25 }] }
}
if (sql.includes("uptime_resource_samples")) return { rows: [] }
throw Error("Unexpected source")
} } } })
const { registerIncidentActions, telemetryFreshness } = await import("./incident-actions.js")
const { readCapabilities } = await import("./capability-actions.js")
const registered = new Map<string, Parameters<typeof add>>()
registerIncidentActions((...args) => registered.set(args[1], args))
const connection = {
policy: mcpConnectionPolicySchema.parse({
id: "fixture", version: 1, status: "active", expiresAt: "2027-01-01T00:00:00Z", mode: "observer",
permissions: ["mm:servers:read", "mm:traffic:read"],
scope: { serverIds: [7], operationIds: ["catalog.global.read", "catalog.server.read", "catalog.server.write"] },
}), owner_permissions: ["mm:servers:read", "mm:uptime:read"],
} as ActionContext["connection"]
const context = { connection } as ActionContext
test("timeline limits interval and evidence, keeps order and timestamps, checks both source permission grants", async () => {
const registration = registered.get("mm_incident_timeline_get")!
const schema = registration[7], read = registration[8].read!
const input = { serverId: 7, from, to, limit: 1 }
assert.equal(schema.safeParse({ ...input, to: from }).success, false)
assert.equal(schema.safeParse({ ...input, to: "2026-11-29T00:00:00Z" }).success, false)
assert.equal(schema.safeParse({ ...input, to: "2026-11-27T01:00:00" }).success, false)
for (const source of ["uptime", "netflow"]) {
await assert.rejects(read(schema.parse({ ...input, sources: [source] }), context),
{ code: "PERMISSION_DENIED" })
}
assert.equal(queries.length, 0)
const result = await read(schema.parse(input), context)
assert.deepEqual(result, {
serverId: 7, from: new Date(from).toISOString(), to: new Date(to).toISOString(),
observedAt: (result as { observedAt: string }).observedAt,
order: "newest-first", sources: ["routeros-poll", "logs"],
items: [{ id: "41", status: "warning", timestampKind: "router", source: "logs", at: newerPrecise, receivedAt: newer.toISOString() }],
nextCursor: (result as { nextCursor: string }).nextCursor,
truncated: true, coverageVerified: false, managerEventsIncluded: false,
})
assert.deepEqual(queries.map(query => query.values), [[7], [7, from, to, 2], [7, from, to, 2]])
})
test("health separates disabled, absent, stale and unknown freshness from observed status", async () => {
const row = { enabled: true, intervalSec: 30, observedAt: observed, status: "error" }
assert.equal(telemetryFreshness(row, observed.getTime() + 90_000, true).freshness, "fresh")
assert.equal(telemetryFreshness(row, observed.getTime() + 90_001, true).freshness, "stale")
assert.equal(telemetryFreshness(row, observed.getTime(), false).freshness, "disabled")
assert.equal(telemetryFreshness({ ...row, intervalSec: null }, observed.getTime(), true).freshness, "unknown")
const registration = registered.get("mm_telemetry_health_get")!
const result = await registration[8].read!(registration[7].parse({ serverId: 7, sources: ["routeros-poll", "logs"] }), context)
assert.deepEqual((result as { observations: unknown[] }).observations, [{
source: "routeros-poll", freshness: "unobserved", observedAt: null, ageMs: null,
lastStatus: null,
}, {
source: "logs", freshness: "unavailable", observedAt: null, ageMs: null,
lastStatus: null,
}])
})
test("capabilities keeps legacy shape and assesses filtered candidates under effective policy", () => {
for (const [id, toolName, scope, effect, requiredPermissions] of [
["catalog.global.read", "mm_fixture_global", "global", "read", []],
["catalog.server.read", "mm_fixture_server", "servers", "read", ["mm:servers:read"]],
["catalog.server.write", "mm_fixture_server_plan", "servers", "write", ["mm:traffic:read"]],
["catalog.hidden.read", "mm_fixture_hidden", "global", "read", []],
]) registerMcpOperation(mcpOperationDescriptorSchema.parse({ id, toolName, scope, effect, requiredPermissions, version: 1,
title: "Fixture", section: "fixture", risk: "ordinary", implementation: "available",
annotations: { readOnlyHint: effect === "read", destructiveHint: effect === "write", idempotentHint: true, openWorldHint: true } }))
const baseline = readCapabilities({}, connection, observed)
assert.deepEqual(Object.keys(baseline).sort(), ["operations", "schemaVersion"])
assert.equal(baseline.operations.length, 3)
assert.ok(baseline.operations.every(operation => !("applicability" in operation)))
const applicability = (input: Parameters<typeof readCapabilities>[0]) => readCapabilities({ includeApplicability: true, ...input }, connection, observed)
.operations.flatMap(operation => "applicability" in operation ? [operation.applicability] : [])
assert.equal(applicability({ toolName: "mm_fixture_global" })[0]?.reasons[0]?.code, "GLOBAL_DENIED")
assert.equal(applicability({ serverId: 7, effect: "read" })[0]?.decision, "allowed")
assert.equal(applicability({ serverId: 8, effect: "read" })[0]?.reasons[0]?.code, "SERVER_DENIED")
assert.deepEqual(applicability({ effect: "write" })[0]?.reasons.map(reason => reason.code), ["OWNER_PERMISSION_MISSING", "OBSERVER_WRITE_DENIED"])
assert.equal(applicability({ section: "fixture", applicable: true }).length, 1)
})
test("optional manager evidence requires both audit grants and selects current single-server tool metadata", async () => {
const registration = registered.get("mm_incident_timeline_get")!
const raw = registration[7].parse({ serverId: 7, from, to, sources: ["routeros-poll"], includeManagerEvents: true })
const read = registration[8].read!
const before = queries.length
const audit = {
...connection, id: "fixture-connection", owner_id: "fixture-owner",
policy: { ...connection.policy, permissions: [...connection.policy.permissions, "mm:mcp:read"] },
}
await assert.rejects(read(raw, { ...context, connection: audit }), { code: "PERMISSION_DENIED" })
assert.equal(queries.length, before)
audit.owner_permissions = [...audit.owner_permissions, "mm:mcp:read"]
const result = await read(raw, { ...context, connection: audit })
assert.deepEqual((result as { sources: string[] }).sources, ["routeros-poll", "mcp-request"])
assert.deepEqual((result as { items: unknown[] }).items[0], {
id: "request-id", status: "completed", timestampKind: "request-created", toolName: "mm_fixture_server",
source: "mcp-request", at: newerPrecise,
})
})
test("timeline paginates equal timestamps and microseconds with a bound opaque cursor", async () => {
const registration = registered.get("mm_incident_timeline_get")!
const base = { serverId: 7, from, to, sources: ["logs"], limit: 1 }
const read = async (raw: typeof base & { cursor?: string }) => await registration[8].read!(registration[7].parse(raw), context) as {
nextCursor: string | null; items: Array<{ id: string; at: string }>
}
paginate = true
try {
const one = await read(base)
assert.ok(one.nextCursor)
const two = await read({ ...base, cursor: one.nextCursor })
assert.ok(two.nextCursor)
const three = await read({ ...base, cursor: two.nextCursor })
assert.equal(three.nextCursor, null)
assert.deepEqual([one, two, three].flatMap(page => page.items.map(({ id, at }) => [id, at])), [
["100", newerPrecise], ["9", newerPrecise], ["99", "2026-11-27T00:30:00.000001Z"],
])
await assert.rejects(read({ ...base, serverId: 9, cursor: one.nextCursor }), { code: "RESET_REQUIRED" })
await assert.rejects(read({ ...base, cursor: "bogus" }), { code: "RESET_REQUIRED" })
} finally { paginate = false }
})
test("fleet health pages over the effective server allowlist only", async () => {
const registration = registered.get("mm_telemetry_health_get")!
const scoped = { ...context, connection: { ...connection, policy: { ...connection.policy,
scope: { ...connection.policy.scope, serverIds: [7, 9] } } } }
const raw = { sources: ["routeros-poll"], limit: 1 }
const read = async (input: typeof raw & { afterServerId?: number }) => await registration[8].read!(registration[7].parse(input), scoped) as {
nextAfterServerId: number | null; items: Array<{ serverId: number }>
}
assert.deepEqual(registration[8].target!(raw, scoped), { scope: "servers", serverIds: [7, 9] })
const one = await read(raw), two = await read({ ...raw, afterServerId: 7 })
assert.deepEqual([one.nextAfterServerId, two.nextAfterServerId], [7, null])
assert.deepEqual([one, two].flatMap(page => page.items.map(item => item.serverId)), [7, 9])
})
test("uptime combines scoped resource and retained probe evidence without target details", async () => {
const scoped = { ...context, connection: { ...connection, policy: { ...connection.policy,
permissions: [...connection.policy.permissions, "mm:uptime:read"] } } }
const health = registered.get("mm_telemetry_health_get")!
const sources = ["uptime"]
const state = await health[8].read!(health[7].parse({ serverId: 7, sources }), scoped) as {
observations: Array<{ source: string; lastStatus: string | null }>
}
assert.deepEqual(state.observations.map(row => [row.source, row.lastStatus]), [["uptime", null], ["uptime-probe", "warn"]])
const timeline = registered.get("mm_incident_timeline_get")!
const evidence = await timeline[8].read!(timeline[7].parse({ serverId: 7, from, to, sources }), scoped) as { items: unknown[] }
assert.deepEqual(evidence.items, [{ at: observedPrecise, id: "probe-1", status: "warn", source: "uptime-probe",
timestampKind: "backend-sample", rttMs: 50, lossPct: 25 }])
})
+213
View File
@@ -0,0 +1,213 @@
import { z } from "zod"
import { pool } from "../../db/index.js"
import { hasPermission } from "../../lib/permissions.js"
import { listMcpOperations } from "./registry.js"
import { accessGeneration, decryptSecret, encryptSecret, fingerprint, McpError } from "./security.js"
import type { ActionContext } from "./action-types.js"
import type { add } from "./actions.js"
const sources = ["routeros-poll", "uptime", "logs", "netflow"] as const
type Source = typeof sources[number]
const permissions: Record<Source, string> = {
"routeros-poll": "mm:servers:read", uptime: "mm:uptime:read", logs: "mm:servers:read", netflow: "mm:traffic:read",
}
const selection = {
serverId: z.number().int().positive().safe(),
sources: z.array(z.enum(sources)).min(1).max(sources.length).optional(),
}
const healthInput = z.object({ ...selection, serverId: selection.serverId.optional(),
afterServerId: selection.serverId.optional(), limit: z.number().int().min(1).max(20).default(10),
}).strict().refine(input => input.serverId === undefined || input.afterServerId === undefined, "Курсор доступен для списка серверов")
const hourMs = 3_600_000
const timelineSourceNames = [...sources, "uptime-probe", "mcp-request"] as const
type TimelineSource = typeof timelineSourceNames[number]
const cursorSchema = z.object({ scope: z.string(), at: z.iso.datetime({ precision: 6 }),
source: z.enum(timelineSourceNames), key: z.string().max(1000),
}).strict()
const timelineInput = z.object({
...selection, from: z.iso.datetime({ offset: true }), to: z.iso.datetime({ offset: true }),
limit: z.number().int().min(1).max(200).default(50),
includeManagerEvents: z.boolean().default(false),
cursor: z.string().min(1).max(3000).optional(),
}).strict().refine(({ from, to }) => {
const duration = Date.parse(to) - Date.parse(from)
return duration > 0 && duration <= 24 * hourMs
}, "Требуется положительное окно до 24 часов")
function permittedSources(context: ActionContext, requested?: Source[]) {
const permitted = (source: Source) => [context.connection.policy.permissions, context.connection.owner_permissions]
.every(granted => hasPermission(granted, permissions[source]))
if (requested?.some(source => !permitted(source))) throw new McpError("PERMISSION_DENIED", "Чтение выбранного источника запрещено", 403)
return [...new Set(requested ?? sources.filter(permitted))]
}
type HealthRow = { enabled: boolean | null; intervalSec: number | null; observedAt: Date | null; status: string | null; gapAt?: Date | null }
type EvidenceRow = { at: string; key: string; id: string; status: string | null; timestampKind: string; receivedAt?: Date; topics?: string[]; message?: string; toolName?: string }
const healthSources: Record<Source, string> = {
"routeros-poll": `SELECT cfg.enabled,cfg.interval_sec AS "intervalSec",sample.sampled_at AS "observedAt",
CASE sample.ok WHEN true THEN 'ok' WHEN false THEN 'error' END AS status
FROM servers_api_ping_settings cfg LEFT JOIN LATERAL (
SELECT sampled_at,ok FROM servers_rest_ping_samples WHERE server_id=$1 AND sampled_at BETWEEN $2 AND $3
ORDER BY sampled_at DESC LIMIT 1
) sample ON true WHERE cfg.id=1`,
uptime: `SELECT cfg.enabled AND cfg.resources_enabled AS enabled,cfg.interval_sec AS "intervalSec",
sample.sampled_at AS "observedAt",sample.status
FROM uptime_settings cfg LEFT JOIN LATERAL (
SELECT sampled_at,status FROM uptime_resource_samples WHERE server_id=$1 AND sampled_at BETWEEN $2 AND $3
ORDER BY sampled_at DESC LIMIT 1
) sample ON true WHERE cfg.id=1`,
logs: `SELECT cfg.enabled,cfg.interval_sec AS "intervalSec",
CASE WHEN sample.last_collected_at BETWEEN $2 AND $3 THEN sample.last_collected_at END AS "observedAt",
CASE WHEN sample.gap_at BETWEEN $2 AND $3 THEN sample.gap_at END AS "gapAt",
CASE WHEN sample.last_error IS NOT NULL AND sample.last_error <> '' THEN 'error'
WHEN sample.last_collected_at BETWEEN $2 AND $3 THEN 'ok' END AS status
FROM router_log_settings cfg LEFT JOIN router_log_collection_state sample ON sample.server_id=$1 WHERE cfg.id=1`,
netflow: `SELECT NULL::boolean AS enabled,NULL::integer AS "intervalSec",bucket_at AS "observedAt",'retained-bucket' AS status
FROM flow_minute_stats WHERE server_id=$1 AND bucket_at BETWEEN $2 AND $3
ORDER BY bucket_at DESC LIMIT 1`,
}
const uptimeProbeHealth = `SELECT cfg.enabled AND cfg.ping_enabled AS enabled,
COALESCE(NULLIF(sample.interval_sec,0),cfg.probe_interval_sec) AS "intervalSec",
sample.sampled_at AS "observedAt",sample.status
FROM uptime_settings cfg LEFT JOIN LATERAL (
SELECT p.interval_sec,s.sampled_at,s.status FROM uptime_probes p CROSS JOIN LATERAL (
SELECT sampled_at,status FROM uptime_probe_samples WHERE probe_id=p.id AND sampled_at BETWEEN $2 AND $3 AND sampled_at>=p.updated_at
ORDER BY sampled_at DESC LIMIT 1
) s WHERE p.src_server_id=$1 AND p.enabled ORDER BY s.sampled_at DESC,p.id LIMIT 1
) sample ON true WHERE cfg.id=1`
const timelineSources: Record<TimelineSource, { time: string; key: string; evidence: string }> = {
"routeros-poll": { time: "sampled_at", key: "''::text", evidence: `sampled_at::text AS id,CASE ok WHEN true THEN 'ok' ELSE 'error' END AS status,
'backend-sample' AS "timestampKind" FROM servers_rest_ping_samples WHERE server_id=$1` },
uptime: { time: "sampled_at", key: "''::text", evidence: `sampled_at::text AS id,status,'backend-sample' AS "timestampKind"
FROM uptime_resource_samples WHERE server_id=$1` },
"uptime-probe": { time: "s.sampled_at", key: "p.id", evidence: `p.id,status,'backend-sample' AS "timestampKind",
s.rtt_ms AS "rttMs",s.loss_pct AS "lossPct" FROM uptime_probes p
JOIN uptime_probe_samples s ON s.probe_id=p.id WHERE p.src_server_id=$1 AND s.sampled_at>=p.updated_at` },
logs: { time: "effective_at", key: "lpad(id::text,20,'0')", evidence: `id::text,level AS status,
CASE WHEN event_at IS NULL THEN 'receipt' ELSE 'router' END AS "timestampKind",
received_at AS "receivedAt",topics[1:20] AS topics,left(message,500) AS message FROM router_log_entries WHERE server_id=$1` },
netflow: { time: "bucket_at", key: "''::text", evidence: `bucket_at::text AS id,'retained-bucket' AS status,'bucket' AS "timestampKind"
FROM flow_minute_stats WHERE server_id=$1` },
"mcp-request": { time: "created_at", key: "id::text", evidence: `id::text,CASE WHEN finished_at <= $3 THEN status END AS status,
'request-created' AS "timestampKind",tool AS "toolName" FROM mcp_requests WHERE server_ids=ARRAY[$1]::bigint[]
AND connection_id=$5 AND actor_id=$6 AND tool=ANY($7::text[])` },
}
function timelineQuery(source: TimelineSource, parameters: unknown[], cursor?: z.infer<typeof cursorSchema>) {
const { time, key, evidence } = timelineSources[source]
const tie = `(${key}) COLLATE "C"`
let clause = ""
if (cursor) {
const mark = `$${parameters.push(cursor.at)}::timestamptz`
if (source === cursor.source) clause = `AND (${time},${tie}) < (${mark},$${parameters.push(cursor.key)}::text COLLATE "C")`
else clause = `AND ${time} ${source > cursor.source ? "<=" : "<"} ${mark}`
}
return `SELECT to_char(${time} AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS at,
${key} AS key,${evidence} AND ${time} BETWEEN $2 AND $3 ${clause}
ORDER BY ${time} DESC,${tie} DESC LIMIT $4`
}
function managerEventTools(context: ActionContext) {
const { policy, owner_permissions } = context.connection
const hasBoth = (permission: string) => hasPermission(policy.permissions, permission) && hasPermission(owner_permissions, permission)
if (!hasBoth("mm:mcp:read")) throw new McpError("PERMISSION_DENIED", "Чтение аудита MCP запрещено", 403)
const allowed = new Set(policy.scope.operationIds)
return listMcpOperations().filter(operation => operation.implementation === "available" && operation.scope === "servers" &&
allowed.has(operation.id) && operation.requiredPermissions.every(hasBoth)).map(operation => operation.toolName)
}
async function requireServer(serverId: number) {
const { rows } = await pool.query<{ enabled: boolean }>("SELECT enabled FROM servers WHERE id=$1", [serverId])
if (!rows.length) throw new McpError("NOT_FOUND", "Сервер не найден", 404)
return rows[0].enabled
}
export function telemetryFreshness(row: HealthRow | undefined, asOf: number, serverEnabled: boolean) {
const ageMs = row?.observedAt ? asOf - row.observedAt.getTime() : null
const staleAfterMs = row?.intervalSec ? row.intervalSec * 3000 : null
const freshness = !serverEnabled || row?.enabled === false ? "disabled"
: ageMs === null ? "unobserved" : staleAfterMs === null ? "unknown" : ageMs > staleAfterMs ? "stale" : "fresh"
return { freshness, observedAt: row?.observedAt?.toISOString() ?? null, ageMs, lastStatus: row?.status ?? null,
...(row?.gapAt && { gapAt: row.gapAt.toISOString() }) }
}
export function registerIncidentActions(register: typeof add) {
register("telemetry.health.read", "mm_telemetry_health_get", "Здоровье источников телеметрии сервера", "logs",
"mm:servers:read", "read", "servers", healthInput, {
target: (raw, context) => {
const serverIds = typeof raw.serverId === "number" ? [raw.serverId] : context.connection.policy.scope.serverIds
if (!serverIds.length) throw new McpError("SERVER_DENIED", "Подключению не выдан доступ к серверам", 403)
return { scope: "servers", serverIds }
},
read: async (raw, context) => {
const input = healthInput.parse(raw), selected = permittedSources(context, input.sources)
const asOf = Date.now(), from = new Date(asOf - 24 * hourMs), to = new Date(asOf)
const healthQueries = selected.map(source => ({ source: source as Source | "uptime-probe", sql: healthSources[source] }))
if (selected.includes("uptime")) healthQueries.push({ source: "uptime-probe", sql: uptimeProbeHealth })
const readServer = async (serverId: number, serverEnabled: boolean) => ({
serverId, serverEnabled, observations: await Promise.all(healthQueries.map(async ({ source, sql }) => {
const expectsActiveServer = source === "netflow" || serverEnabled
try {
const { rows } = await pool.query<HealthRow>(sql, [serverId, from, to])
return { source, ...telemetryFreshness(rows[0], asOf, expectsActiveServer) }
} catch {
context.signal?.throwIfAborted()
return { source, ...telemetryFreshness(undefined, asOf, expectsActiveServer), freshness: "unavailable" as const }
}
})),
})
const metadata = { observedAt: to.toISOString(), lookbackFrom: from.toISOString(),
sourceOmissions: sources.filter(source => !selected.includes(source)).map(source => ({
source, reason: input.sources ? "not-requested" : "permission-denied",
})),
netflowDataQuality: { available: false, reason: "no-server-scoped-collector-quality", exportCoverage: "unverified" } }
if (input.serverId !== undefined) return { ...await readServer(input.serverId, await requireServer(input.serverId)), ...metadata }
const { rows } = await pool.query<{ id: number; enabled: boolean }>(
"SELECT id,enabled FROM servers WHERE id=ANY($1::bigint[]) AND id>$2 ORDER BY id LIMIT $3",
[context.connection.policy.scope.serverIds, input.afterServerId ?? 0, input.limit + 1])
const page = rows.slice(0, input.limit)
const items = await Promise.all(page.map(row => readServer(Number(row.id), row.enabled)))
return { ...metadata, items, nextAfterServerId: rows.length > input.limit ? Number(page.at(-1)?.id) : null }
},
})
register("incident.timeline.read", "mm_incident_timeline_get", "Хронология наблюдений по серверу", "logs",
"mm:servers:read", "read", "servers", timelineInput, {
read: async (raw, context) => {
const input = timelineInput.parse(raw), selected = permittedSources(context, input.sources)
const managerTools = input.includeManagerEvents ? managerEventTools(context) : null
const { cursor: token, limit, ...filters } = input
const scope = async () => fingerprint({ purpose: "incident-timeline-v1", filters, generation: await accessGeneration(),
connection: context.connection.id, credential: context.principal?.credentialId,
policy: context.connection.policy, ownerPermissions: context.connection.owner_permissions })
let cursor: z.infer<typeof cursorSchema> | undefined
if (token) {
try {
cursor = cursorSchema.parse(JSON.parse(await decryptSecret(token)))
if (cursor.scope !== await scope()) throw Error("scope")
} catch { throw new McpError("RESET_REQUIRED", "Курсор устарел или относится к другим фильтрам", 409) }
}
await requireServer(input.serverId)
const parameters = [input.serverId, input.from, input.to, limit + 1]
const queries: Array<{ source: TimelineSource; parameters: unknown[] }> =
selected.map(source => ({ source, parameters: [...parameters] }))
if (selected.includes("uptime")) queries.push({ source: "uptime-probe", parameters: [...parameters] })
if (managerTools) queries.push({ source: "mcp-request",
parameters: [...parameters, context.connection.id, context.connection.owner_id, managerTools] })
const batches = await Promise.all(queries.map(async ({ source, parameters }) => {
const { rows } = await pool.query<EvidenceRow>(timelineQuery(source, parameters, cursor), parameters)
return rows.map(row => ({ ...row, source }))
}))
const items = batches.flat().sort((a, b) => a.at < b.at ? 1 : a.at > b.at ? -1 : a.source < b.source ? -1 : a.source > b.source ? 1 : 0)
const page = items.slice(0, limit)
const last = page.at(-1)
const nextCursor = last && items.length > limit
? await encryptSecret(JSON.stringify({ at: last.at, key: last.key, source: last.source, scope: cursor?.scope ?? await scope() }))
: null
return { serverId: input.serverId, from: new Date(input.from).toISOString(), to: new Date(input.to).toISOString(),
observedAt: new Date().toISOString(), order: "newest-first", sources: queries.map(query => query.source),
items: page.map(({ key: _key, receivedAt, ...row }) => ({
...row, ...(receivedAt && { receivedAt: receivedAt.toISOString() }),
})), nextCursor, truncated: nextCursor !== null, coverageVerified: false, managerEventsIncluded: input.includeManagerEvents }
},
})
}
@@ -11,7 +11,7 @@ const creates = rosResources.filter(resource => !resource.readOnly && resource.c
assert.equal(creates.length, 30)
for (const resource of creates) {
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)
for (const id of ["*OLD", undefined, null, ""]) {
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" })
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"]]) {
assert.deepEqual(validateRosStep(bfdConfig, "create", { addresses, vrf: "main" }), { addresses: expected, vrf: "main" })
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)
@@ -0,0 +1,84 @@
import assert from "node:assert/strict"
import test from "node:test"
import { projectDnsState, projectFibTableState, projectRouteLookup } from "./network-diagnostic-actions.js"
const route = (prefix: string, immediateGateway: string, table = "tenant") => ({
"routing-table": table, "dst-address": prefix, active: "true",
gateway: immediateGateway, "immediate-gw": immediateGateway,
})
test("requires positive FIB evidence in the explicitly selected table", () => {
const main = { name: "main", fib: true, invalid: false }
assert.equal(projectFibTableState([main], "main"), "ready")
assert.equal(projectFibTableState([main], "tenant"), "table-not-found")
assert.equal(projectFibTableState([main, main], "main"), "partial")
assert.equal(projectFibTableState([{ ...main, fib: "" }], "main"), "partial")
assert.equal(projectFibTableState([{ ...main, fib: "false" }], "main"), "table-not-fib")
assert.equal(projectFibTableState([{ ...main, invalid: true }], "main"), "table-inactive")
})
test("looks up IPv4 by longest active prefix and preserves ECMP path multiplicity", () => {
const prefix = "203.0.113.0/24"
const result = projectRouteLookup([
route("0.0.0.0/0", "192.0.2.1%wan"),
route("203.0.113.10/32", "192.0.2.2%main", "main"),
{ ...route("203.0.113.10/32", "192.0.2.3%disabled"), disabled: "true" },
{ ...route("203.0.113.10/32", "192.0.2.4%inactive"), active: "false" },
route(prefix, "192.0.2.5%uplink,192.0.2.6%uplink"),
route(prefix, "192.0.2.5%uplink"),
], "tenant", "203.0.113.10")
assert.equal(result.status, "matched")
assert.deepEqual(result.routes.map(item => item.prefix), [prefix, prefix])
assert.deepEqual(result.nextHops, ["192.0.2.5%uplink", "192.0.2.6%uplink", "192.0.2.5%uplink"])
assert.deepEqual(result.nextHopDetails.map(hop => hop.interface), ["uplink", "uplink", "uplink"])
})
test("matches IPv6 blackhole and distinguishes absent and partial observations", () => {
const blackhole = { "routing-table": "tenant", "dst-address": "2001:db8:1::/48", active: "true", blackhole: "yes" }
const result = projectRouteLookup([route("::/0", "fe80::1%uplink"), blackhole], "tenant", "2001:db8:1:2::15")
assert.equal(result.status, "matched")
assert.equal(result.routes[0].disposition, "blackhole")
assert.deepEqual(result.nextHops, [])
assert.equal(projectRouteLookup([blackhole], "tenant", "2001:db8:2::1").status, "no-route")
assert.equal(projectRouteLookup([{ ...blackhole, active: undefined }], "tenant", "2001:db8:1::1").status, "partial")
assert.equal(projectRouteLookup([route("::/0", "")], "tenant", "2001:db8:1::1").status, "partial")
assert.equal(projectRouteLookup([route("::/0", "fe80::1%uplink"), { ...blackhole, "dst-address": "2001:db8:1::/129" }], "tenant", "2001:db8:1::1").status, "partial")
assert.equal(projectRouteLookup([{ ...blackhole, blackhole: "" }], "tenant", "2001:db8:1::1").routes[0].disposition, "blackhole")
assert.equal(projectRouteLookup([route("::/0", "bridge wan")], "tenant", "2001:db8:1::1").nextHopDetails[0].interface, "bridge wan")
})
test("bounds ECMP output and exposes omissions as partial", () => {
const rows = Array.from({ length: 129 }, () => route("0.0.0.0/0", "192.0.2.1%uplink"))
const result = projectRouteLookup(rows, "tenant", "203.0.113.10")
assert.equal(result.status, "partial")
assert.equal(result.nextHops.length, 128)
})
test("retains duplicate native array nexthops across active default rows", () => {
const defaults = Array.from({ length: 2 }, () => ({
"routing-table": "main", "dst-address": "0.0.0.0/0", active: true,
gateway: ["192.0.2.1"], "immediate-gw": ["192.0.2.1%ether1"],
}))
const result = projectRouteLookup(defaults, "main", "203.0.113.10")
assert.equal(result.status, "matched")
assert.deepEqual(result.nextHops, ["192.0.2.1%ether1", "192.0.2.1%ether1"])
assert.deepEqual(result.routes.map(item => item.gateways), [["192.0.2.1"], ["192.0.2.1"]])
assert.equal(projectRouteLookup([{ ...defaults[0], "immediate-gw": ["192.0.2.1%ether1", 1] }], "main", "203.0.113.10").status, "partial")
})
test("DNS reports ordered upstream addresses and projects DoH to a boolean", () => {
assert.deepEqual(projectDnsState({
"allow-remote-requests": "yes", servers: "192.0.2.53@tenant,2001:db8::53", "dynamic-servers": "",
"use-doh-server": "https://example.invalid/dns-query?secret=private", "cache-used": "private",
}), {
allowRemoteRequests: true, staticServers: ["192.0.2.53@tenant", "2001:db8::53"],
dynamicServers: [], dohEnabled: true, incomplete: false,
})
assert.deepEqual(projectDnsState({ "allow-remote-requests": false, servers: "", "use-doh-server": "" }), {
allowRemoteRequests: false, staticServers: [], dynamicServers: null, dohEnabled: false, incomplete: true,
})
assert.deepEqual(projectDnsState([{ "allow-remote-requests": false, servers: ["192.0.2.53", "2001:db8::53"], "dynamic-servers": [], "use-doh-server": "" }]), {
allowRemoteRequests: false, staticServers: ["192.0.2.53", "2001:db8::53"], dynamicServers: [], dohEnabled: false, incomplete: false,
})
assert.throws(() => projectDnsState([{}, {}]))
})
@@ -0,0 +1,184 @@
import { isIP } from "node:net"
import { z } from "zod"
import { observedBoolean } from "../../services/ospf-observed-values.js"
import { isConfirmedRoutingFibTable } from "../../services/routing-table-fib.js"
import { ipv4ToInt, ipv6ToInt, parseCidrV4, parseCidrV6 } from "../../services/traffic-flow-ip.js"
import type { add } from "./actions.js"
import { readNetworkValue } from "./network-neighbor-actions.js"
import { parseRoutingEndpoint } from "./routing-native-endpoint.js"
import { McpError } from "./security.js"
const serverIdSchema = z.number().int().positive().safe()
const tableSchema = z.string().min(1).max(200).refine(value => !/[\u0000-\u001f\u007f]/.test(value))
const destinationSchema = z.string().max(45).refine(value => !value.includes("%") && isIP(value) !== 0)
const rowSchema = z.record(z.string(), z.unknown())
const tablePath = "/routing/table?.proplist=name,fib,disabled,invalid"
const dnsPath = "/ip/dns?.proplist=allow-remote-requests,servers,dynamic-servers,use-doh-server"
const flags = z.union([z.boolean(), z.string()]).transform(value => typeof value === "boolean" ? value : observedBoolean(value))
const flag = (value: unknown) => flags.safeParse(value).data ?? null
const routeRows = z.array(rowSchema).max(10000)
const maxRoutePaths = 128
export function projectFibTableState(raw: unknown, table: string) {
const rows = routeRows.parse(raw)
if (rows.some(row => typeof row.name !== "string")) return "partial"
const matches = rows.filter(row => row.name === table)
if (matches.length > 1) return "partial"
if (!matches.length) return "table-not-found"
const row = matches[0]
if (flag(row.fib) === false) return "table-not-fib"
if (flag(row.disabled) === true || flag(row.invalid) === true) return "table-inactive"
// This REST catalog has produced an empty fib value for non-FIB tables as well.
return row.fib !== "" && isConfirmedRoutingFibTable(row) ? "ready" : "partial"
}
function matchingLength(value: unknown, destination: string): number | null {
const family = isIP(destination)
if (typeof value !== "string" || value.length > 50 || !/^[^/%]+\/\d+$/.test(value)) return null
if (isIP(value.split("/")[0]) !== family) return null
if (family === 4) {
const prefix = parseCidrV4(value)
if (!prefix) return null
return ((ipv4ToInt(destination)! & prefix.mask) >>> 0) === prefix.net ? prefix.prefixLen : -1
}
const prefix = parseCidrV6(value)
if (!prefix) return null
return (ipv6ToInt(destination)! >> prefix.shift) === prefix.net ? prefix.prefixLen : -1
}
const routePath = z.string().min(1).max(512).refine(value => !/[\u0000-\u001f\u007f]/.test(value))
function nativeList(value: unknown, maxCharacters: number, maxItems: number): string[] | null {
if (value === "") return []
const items = typeof value === "string" && value.length <= maxCharacters ? value.split(",") : value
if (!Array.isArray(items) || items.length > maxItems) return null
let characters = 0
const result = []
for (const item of items) {
if (typeof item !== "string") return null
characters += item.length
const entry = item.trim()
if (!entry || characters > maxCharacters) return null
result.push(entry)
}
return result
}
function splitNexthops(value: unknown) {
const paths = nativeList(value, 16384, 1024)
return paths?.every(path => !path.includes(",") && routePath.safeParse(path).success) ? paths : []
}
function nexthopDetails(value: string) {
try {
const hop = parseRoutingEndpoint(value)
return { address: hop.address, interface: hop.interface ?? null, vrf: hop.vrf ?? null }
} catch {
const direct = /^([^%@/]+)(?:@([^%@/]+))?$/.exec(value)
return { address: null, interface: direct?.[1] ?? null, vrf: direct?.[2] ?? null }
}
}
export function projectRouteLookup(raw: unknown, table: string, destination: string) {
const routes: { prefix: string; disposition: "blackhole" | "unreachable" | "prohibit" | "forward"; gateways: string[]; immediateGateways: string[] }[] = []
let longest = -1
let unknownLongest = -1
let limited = false
let hopCount = 0
for (const row of routeRows.parse(raw)) {
if (typeof row["routing-table"] === "string" && row["routing-table"] !== table) continue
if (flag(row.active) === false || flag(row.disabled) === true || flag(row.inactive) === true) continue
const length = matchingLength(row["dst-address"], destination)
if (length === null) {
unknownLongest = isIP(destination) === 4 ? 32 : 128
continue
}
if (length < 0) continue
if (row["routing-table"] !== table || flag(row.active) !== true) {
unknownLongest = Math.max(unknownLongest, length)
continue
}
if (length < longest) continue
if (length > longest) {
routes.length = 0
limited = false
hopCount = 0
longest = length
}
if (routes.length === maxRoutePaths) {
limited = true
continue
}
const disposition = row.blackhole === "" ? "blackhole" : (["blackhole", "unreachable", "prohibit"] as const)
.find(kind => flag(row[kind]) === true || row.type === kind || row.gateway === kind) ?? "forward"
const remaining = maxRoutePaths - hopCount
const configured = disposition === "forward" ? splitNexthops(row.gateway) : []
const resolved = disposition === "forward" ? splitNexthops(row["immediate-gw"]) : []
const paths = Math.max(configured.length, resolved.length)
limited ||= paths > remaining
hopCount += Math.min(paths, remaining)
const gateways = configured.slice(0, remaining)
const immediateGateways = resolved.slice(0, remaining)
routes.push({ prefix: String(row["dst-address"]), disposition, gateways, immediateGateways })
}
const nextHops = routes.flatMap(route => route.immediateGateways)
const nextHopDetails = nextHops.map(nexthopDetails)
const incomplete = (unknownLongest >= 0 && unknownLongest >= longest) || limited
|| routes.some(route => route.disposition === "forward" && !route.immediateGateways.length)
|| nextHopDetails.some(hop => !hop.address && !hop.interface)
return { status: incomplete ? "partial" : routes.length ? "matched" : "no-route", incomplete, routes, nextHops, nextHopDetails }
}
function dnsServers(value: unknown) {
const items = nativeList(value, 8192, 128)
if (!items || items.some(server => {
const [address, vrf, extra] = server.split("@")
return !isIP(address) || extra !== undefined || (vrf !== undefined && !tableSchema.safeParse(vrf).success)
})) return null
return items
}
export function projectDnsState(raw: unknown) {
const row = Array.isArray(raw) ? z.tuple([rowSchema]).parse(raw)[0] : rowSchema.parse(raw)
const allowRemoteRequests = flag(row["allow-remote-requests"])
const staticServers = dnsServers(row.servers)
const dynamicServers = dnsServers(row["dynamic-servers"])
const dohEnabled = typeof row["use-doh-server"] === "string" ? row["use-doh-server"].trim().length > 0 : null
return { allowRemoteRequests, staticServers, dynamicServers, dohEnabled,
incomplete: [allowRemoteRequests, staticServers, dynamicServers, dohEnabled].includes(null) }
}
export function registerNetworkDiagnosticActions(register: typeof add) {
register("network.route.lookup.read", "mm_route_lookup_get",
"Поиск самого специфичного активного маршрута IPv4/IPv6 в явно выбранной таблице FIB RouterOS",
"network", "mm:network:read", "read", "servers",
z.object({ serverId: serverIdSchema, destination: destinationSchema, table: tableSchema }).strict(),
{ read: async (input, context) => {
const serverId = Number(input.serverId), destination = String(input.destination), table = String(input.table)
const family = isIP(destination) === 4 ? "ipv4" : "ipv6"
const empty = { routes: [], nextHops: [], nextHopDetails: [] }
const observed = { serverId, family, table, destination, forwardingVerified: false, timestampKind: "backend-receipt" }
try {
const result = await readNetworkValue(serverId, context, tablePath, async (raw, get) => {
const state = projectFibTableState(raw, table)
if (state !== "ready") return { ...empty, status: state, incomplete: state === "partial" }
const resource = family === "ipv4" ? "/ip/route" : "/ipv6/route"
const path = `${resource}?.proplist=dst-address,routing-table,active,disabled,inactive,gateway,immediate-gw,blackhole,type&${new URLSearchParams({ "routing-table": table })}`
return projectRouteLookup(await get(path), table, destination)
})
return { ...observed, ...result, observedAt: new Date().toISOString() }
} catch (error) {
if (!(error instanceof McpError) || error.code !== "STATE_UNAVAILABLE") throw error
return { ...observed, ...empty, status: "partial", incomplete: true, reason: "source-unavailable", observedAt: null }
}
} },
)
register("network.dns.state.read", "mm_dns_state_get",
"Состояние DNS RouterOS: удалённые запросы, статические и динамические серверы и признак настройки DoH",
"network", "mm:network:read", "read", "servers", z.object({ serverId: serverIdSchema }).strict(),
{ read: async (input, context) => {
const serverId = Number(input.serverId)
const state = await readNetworkValue(serverId, context, dnsPath, projectDnsState)
return { serverId, ...state, observedAt: new Date().toISOString(), timestampKind: "backend-receipt" }
} },
)
}
@@ -0,0 +1,225 @@
import assert from "node:assert/strict"
import { randomUUID } from "node:crypto"
import { createServer } from "node:http"
import type { AddressInfo } from "node:net"
import { basename, dirname, isAbsolute } from "node:path"
import { mcpConnectionCreateSchema } from "@mmapp/contracts/mcp"
import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client"
assert.equal(process.env.MMAPP_OWN_NETWORK_DIAGNOSTICS, "true")
assert.equal(process.env.NODE_ENV, "test")
const database = new URL(process.env.DATABASE_URL ?? "")
assert.equal(database.protocol, "postgresql:")
assert.equal(database.hostname, "127.0.0.1")
assert.equal(database.username, "mcp_test")
assert.equal(database.pathname, "/postgres")
assert(database.port && database.password && !database.search && !database.hash)
const stateDir = process.env.MCP_STATE_DIR ?? ""
assert(isAbsolute(stateDir))
assert.equal(basename(stateDir), "state")
assert.match(basename(dirname(stateDir)), /^mm-mcp-test-/)
const { pool, closePool } = await import("../../db/index.js")
const { applySqlMigrations } = await import("../../db/migrate.js")
const { buildApp } = await import("../../index.js")
const { createMcpConnection, updateMcpSettings } = await import("./store.js")
const actor = {
id: "network-diagnostics-owner", apps: ["mm"],
permissions: ["mm:settings:admin", "mm:network:read", "mm:servers:read", "mm:traffic:read", "mm:mcp:read"],
expiresAt: Date.now() + 3_600_000,
}
const operations = {
mm_capabilities_get: "capabilities.read",
mm_telemetry_health_get: "telemetry.health.read",
mm_incident_timeline_get: "incident.timeline.read",
mm_route_lookup_get: "network.route.lookup.read",
mm_dns_state_get: "network.dns.state.read",
mm_resilience_topology_get: "network.resilience.topology.read",
mm_resilience_design_preview: "network.resilience.design.read",
mm_failover_report_get: "network.resilience.failover.read",
}
const dnsSecret = "private-doh-url-fixture"
const nativeReads: string[] = []
const nativeRoutes = new Map<string, unknown>([
["/rest/routing/table", [{ name: "main", fib: "true" }]],
["/rest/ip/route", [{ "routing-table": "main", "dst-address": "0.0.0.0/0", active: "true",
gateway: "192.0.2.1", "immediate-gw": "192.0.2.1%ether1" }]],
["/rest/ip/dns", { "allow-remote-requests": "false", servers: "1.1.1.1", "dynamic-servers": "",
"use-doh-server": `https://example.invalid/${dnsSecret}` }],
])
const router = createServer((request, response) => {
const path = new URL(request.url ?? "/", "http://127.0.0.1").pathname
nativeReads.push(`${request.method} ${path}`)
const value = nativeRoutes.get(path)
response.writeHead(request.method === "GET" && value !== undefined ? 200 : 404, { "content-type": "application/json" })
response.end(JSON.stringify(value ?? {}))
})
const sdkClient = () => new Client({ name: "owned-network-diagnostics", version: "1.0.0" })
let client = sdkClient()
const call = (name: keyof typeof operations, args: Record<string, unknown>) => client.callTool({ name, arguments: args })
async function read<T>(name: keyof typeof operations, args: Record<string, unknown>) {
const response = await call(name, args)
assert(!response.isError, `${name}: ${JSON.stringify(response.content)}`)
const result = (response.structuredContent as { result?: T } | undefined)?.result
assert(result !== undefined, `Missing structured result for ${name}`)
return result
}
async function deny(name: keyof typeof operations, args: Record<string, unknown>, code: string) {
const response = await call(name, args)
assert.equal(response.isError, true, name)
assert(JSON.stringify(response.content).includes(code), `${name}: ${JSON.stringify(response.content)}`)
}
let app: Awaited<ReturnType<typeof buildApp>> | undefined
try {
await applySqlMigrations(pool)
assert.equal((await pool.query("SELECT count(*)::int AS n FROM servers")).rows[0].n, 0)
await new Promise<void>(resolve => router.listen(0, "127.0.0.1", resolve))
const port = (router.address() as AddressInfo).port
await pool.query(`INSERT INTO servers(id,name,host,port,use_ssl,verify_ssl,username,password,enabled)
VALUES (1,'scoped-router','127.0.0.1',$1,false,false,'owned','fixture',true),
(2,'foreign-router','127.0.0.1',$1,false,false,'owned','fixture',true)`, [port])
const now = Date.now()
const instant = (offset: number) => new Date(now + offset).toISOString()
const [localAt, foreignAt] = [instant(-2_000), instant(-1_000)]
await pool.query("UPDATE router_log_settings SET enabled=true,interval_sec=3600 WHERE id=1")
for (const [id, eventAt, message] of [[1, localAt, "local-log-fixture"], [2, foreignAt, "foreign-log-fixture"]] as const) {
await pool.query(`INSERT INTO router_log_collection_state(server_id,server_name,host,last_collected_at)
VALUES ($1,'fixture','127.0.0.1',$2)`, [id, eventAt])
await pool.query(`INSERT INTO router_log_entries(server_id,server_name,host,router_id,raw_time,event_at,received_at,effective_at,topics,level,message,generation)
VALUES ($1,'fixture','127.0.0.1','fixture','fixture',NULL,$2,$2,ARRAY['system'],'info',$3,1)`, [id, eventAt, message])
}
const segment = async (name: string, peerServerId?: number) => {
const id = randomUUID()
const configuration = { name, sites: [{ serverId: 1, autonomousSystem: 64512, routerId: "192.0.2.5",
interfaces: [{ name: "ether1", kind: "uplink", peerServerId }],
groups: [{ id: "internet", gateway: "192.0.2.1", primary: { interface: "ether1", nextHop: "192.0.2.1", probe: "192.0.2.8" } }],
exits: ["internet"],
}] }
await pool.query(`INSERT INTO ix_segments(id,name,revision,configuration) VALUES ($1,$2,1,$3)`, [id, name, configuration])
return { kind: "ix-segment", segmentId: id }
}
const target = await segment("scoped-segment"), foreignTarget = await segment("foreign-segment", 2)
await updateMcpSettings({ enabled: true }, actor)
const issue = (audit: boolean) => createMcpConnection(mcpConnectionCreateSchema.parse({
name: "Scoped network diagnostics", mode: "observer", expiresAt: instant(600_000),
permissions: ["mm:network:read", "mm:servers:read", ...(audit ? ["mm:mcp:read"] : [])],
scope: { serverIds: [1], operationIds: Object.values(operations), allowGlobal: false },
limits: { callsPerMinute: 120 },
}), actor)
app = await buildApp({ startScheduler: false, logger: false })
const address = await app.listen({ host: "127.0.0.1", port: 0 })
const connect = (token: string) => client.connect(new StreamableHTTPClientTransport(new URL(`${address}/mcp`),
{ requestInit: { headers: { Authorization: `Bearer ${token}` } } }))
const access = await issue(false)
await connect(access.token)
const { tools } = await client.listTools()
assert.deepEqual(tools.map(tool => tool.name).sort(), Object.keys(operations).sort())
assert(tools.every(tool => tool.annotations?.readOnlyHint === true))
const legacy = await read<{ operations: Array<{ id: string; applicability?: unknown }>; schemaVersion: number }>("mm_capabilities_get", {})
assert.deepEqual(Object.keys(legacy).sort(), ["operations", "schemaVersion"])
assert.equal(legacy.schemaVersion, 1)
assert.deepEqual(legacy.operations.map(row => row.id).sort(), Object.values(operations).sort())
assert(legacy.operations.every(row => !Object.hasOwn(row, "applicability")))
const applicable = await read<{ operations: Array<{ applicability: { decision: string; reasons: Array<{ code: string }> } }> }>(
"mm_capabilities_get", { toolName: "mm_route_lookup_get", serverId: 2 })
assert.equal(applicable.operations.length, 1)
assert.equal(applicable.operations[0].applicability.decision, "denied")
assert(applicable.operations[0].applicability.reasons.some(reason => reason.code === "SERVER_DENIED"))
const health = await read<{ observations: Array<{ source: string; freshness: string; observedAt: string }>; netflowDataQuality: { available: boolean } }>(
"mm_telemetry_health_get", { serverId: 1 })
assert.deepEqual(health.observations.map(row => row.source).sort(), ["logs", "routeros-poll"])
const logs = health.observations.find(row => row.source === "logs")
assert.equal(logs?.observedAt, localAt)
assert.equal(logs?.freshness, "fresh")
assert.equal(health.netflowDataQuality.available, false)
assert(!JSON.stringify(health).includes(foreignAt))
const fleet = await read<{ items: Array<{ serverId: number }>; nextAfterServerId: number | null }>(
"mm_telemetry_health_get", { sources: ["logs"], limit: 1 })
assert.deepEqual(fleet.items.map(row => row.serverId), [1])
assert.equal(fleet.nextAfterServerId, null)
assert(!JSON.stringify(fleet).includes(foreignAt))
const window = { from: instant(-60_000), outageAt: instant(-40_000), restoreAt: instant(-20_000), to: instant(0) }
const range = { from: window.from, to: window.to, sources: ["logs"] }
const timeline = await read<{ items: Array<{ message: string; timestampKind: string }>; coverageVerified: boolean }>(
"mm_incident_timeline_get", { serverId: 1, ...range })
assert.equal(timeline.items.length, 1)
assert.equal(timeline.items[0].message, "local-log-fixture")
assert.equal(timeline.items[0].timestampKind, "receipt")
assert.equal(timeline.coverageVerified, false)
await deny("mm_telemetry_health_get", { serverId: 2 }, "SERVER_DENIED")
await deny("mm_incident_timeline_get", { serverId: 2, ...range }, "SERVER_DENIED")
await deny("mm_telemetry_health_get", { serverId: 1, sources: ["netflow"] }, "PERMISSION_DENIED")
await deny("mm_incident_timeline_get", { serverId: 1, ...range, sources: ["uptime"] }, "PERMISSION_DENIED")
await deny("mm_incident_timeline_get", { serverId: 1, ...range, includeManagerEvents: true }, "PERMISSION_DENIED")
const lookup = { destination: "198.51.100.10", table: "main" }
const route = await read<{ status: string; nextHops: string[]; forwardingVerified: boolean }>("mm_route_lookup_get", { serverId: 1, ...lookup })
assert.equal(route.status, "matched")
assert.deepEqual(route.nextHops, ["192.0.2.1%ether1"])
assert.equal(route.forwardingVerified, false)
const dns = await read<{ staticServers: string[]; dohEnabled: boolean }>("mm_dns_state_get", { serverId: 1 })
assert.deepEqual(dns.staticServers, ["1.1.1.1"])
assert.equal(dns.dohEnabled, true)
assert(!JSON.stringify(dns).includes(dnsSecret))
await deny("mm_route_lookup_get", { serverId: 2, ...lookup }, "SERVER_DENIED")
await deny("mm_dns_state_get", { serverId: 2 }, "SERVER_DENIED")
const topology = await read<{ serverIds: number[]; paths: unknown[]; physicalIndependenceVerified: boolean }>("mm_resilience_topology_get", { target })
assert.deepEqual(topology.serverIds, [1])
assert.equal(topology.paths.length, 1)
assert.equal(topology.physicalIndependenceVerified, false)
const design = { scenario: "wan" }
const preview = await read<{ suggestedTools: string[] }>("mm_resilience_design_preview", { target, ...design })
assert(preview.suggestedTools.includes("mm_ix_segment_get"))
const reportArgs = { window, targetFailoverMs: 1000, targetFailbackMs: 1000 }
const report = await read<{ status: string; reason: string; managementSsh: string }>("mm_failover_report_get", { target, ...reportArgs })
assert.equal(report.status, "inconclusive")
assert.equal(report.reason, "NO_SAVED_IX_CONTROL_PROBE_HISTORY")
assert.equal(report.managementSsh, "inconclusive")
await deny("mm_resilience_topology_get", { target: foreignTarget }, "NOT_FOUND")
await deny("mm_resilience_design_preview", { target: foreignTarget, ...design }, "NOT_FOUND")
await deny("mm_failover_report_get", { target: foreignTarget, ...reportArgs }, "NOT_FOUND")
assert.deepEqual(nativeReads, ["GET /rest/routing/table", "GET /rest/ip/route", "GET /rest/ip/dns"])
const auditedAccess = await issue(true)
const requestId = randomUUID()
await pool.query(`INSERT INTO mcp_requests(id,connection_id,actor_id,tool,server_ids,status,input,created_at,finished_at)
VALUES ($1,$2,$4,'mm_dns_state_get',ARRAY[1]::bigint[],'succeeded','{"credential":"audit-secret-fixture"}',$5,$5),
($6,$3,$4,'mm_dns_state_get',ARRAY[1]::bigint[],'succeeded','{}',$5,$5),
($7,$2,$4,'mm_dns_state_get',ARRAY[1,2]::bigint[],'succeeded','{}',$5,$5)`,
[requestId, auditedAccess.connection.id, access.connection.id, actor.id, foreignAt, randomUUID(), randomUUID()])
await client.close()
client = sdkClient()
await connect(auditedAccess.token)
type TimelinePage = { items: Array<{ id: string; source: string; toolName?: string }>; nextCursor: string | null }
const auditArgs = { serverId: 1, ...range, includeManagerEvents: true, limit: 1 }
const audited = await read<TimelinePage>("mm_incident_timeline_get", auditArgs)
assert.deepEqual(audited.items.map(item => item.source), ["mcp-request"])
assert.equal(audited.items[0].id, requestId)
assert.equal(audited.items[0].toolName, "mm_dns_state_get")
assert(!JSON.stringify(audited).includes("audit-secret-fixture"))
assert(audited.nextCursor)
const pageArgs = { ...auditArgs, cursor: audited.nextCursor }
const next = await read<TimelinePage>("mm_incident_timeline_get", pageArgs)
assert.deepEqual(next.items.map(item => item.source), ["logs"])
assert.equal(next.nextCursor, null)
await deny("mm_incident_timeline_get", { ...pageArgs, includeManagerEvents: false }, "RESET_REQUIRED")
const { assertSignedResilienceHistory } = await import("../../test/resilience-report-acceptance.js")
await assertSignedResilienceHistory({
connectionId: auditedAccess.connection.id,
foreignConnectionId: access.connection.id,
serverId: 1,
callReport: input => read("mm_failover_report_get", input),
})
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_plans")).rows[0].n, 0)
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_operations")).rows[0].n, 0)
} finally {
await client.close()
await app?.close()
if (router.listening) await new Promise<void>((resolve, reject) => router.close(error => error ? reject(error) : resolve()))
await closePool()
}
@@ -44,7 +44,7 @@ function catalogRows<T>(value: unknown, project: (text: (key: string) => string
}).sort((left, right) => left.id.localeCompare(right.id))
}
async function readNetworkValue<T>(serverId: number, context: ActionContext, path: string, project: (raw: unknown) => T) {
export async function readNetworkValue<T>(serverId: number, context: ActionContext, path: string, project: (raw: unknown, get: (path: string) => Promise<unknown>) => T | Promise<T>) {
const authorize = async () => {
if (context.signal?.aborted) throw new McpError("READ_CANCELLED", "Чтение сетевого каталога отменено", 409)
const current = await effectiveMcpConnection(context.principal)
@@ -57,8 +57,8 @@ async function readNetworkValue<T>(serverId: number, context: ActionContext, pat
const check = async () => { await authorize(); await source.assertCurrent(); await authorize() }
try {
const { client } = await routerClient(serverId)
const raw = await client.get<unknown>(path, 10000, context.signal, 1048576, check)
const value = project(raw)
const get = (resource: string) => client.get<unknown>(resource, 10000, context.signal, 1048576, check)
const value = await project(await get(path), get)
await check()
return value
} catch (error) {
@@ -0,0 +1,98 @@
import assert from "node:assert/strict"
import { test } from "node:test"
import { routeAiProfileSchema } from "@mmapp/contracts/mcp-routing"
import { assessFailover, routePaths, summarizePaths } from "./resilience-actions.js"
const first = { id: "a", wanInterface: "ether1", jumpHostId: 2, exitNodeId: 3,
downstreamInterface: "wg-a", gateway: "192.0.2.1", gatewayRef: { resource: "ipv4_route", id: "*a" } }
const second = { ...first, id: "b", jumpHostId: 4, exitNodeId: 5, downstreamInterface: "wg-b" }
function topology(reserve: typeof second) {
const profile = routeAiProfileSchema.parse({ name: "failover", community: "65000:1", family: "ipv4", serverId: 1, candidates: [first, reserve] })
return summarizePaths(routePaths(profile))
}
test("different jump and exit nodes still share a WAN on the origin router", () => {
const result = topology(second)
assert.deepEqual(result.sharedDomains, [
{ kind: "source", serverId: 1, pathIds: ["a", "b"] },
{ kind: "wan", serverId: 1, interfaceName: "ether1", pathIds: ["a", "b"] },
])
assert.equal(result.physicalIndependenceVerified, false)
})
test("logically disjoint WAN, jump and exit nodes retain an unknown physical domain", () => {
const result = topology({ ...second, wanInterface: "ether2" })
assert.deepEqual(result.sharedDomains, [{ kind: "source", serverId: 1, pathIds: ["a", "b"] }])
assert.ok(result.unknownDomains.includes("carrier"))
assert.equal(result.physicalIndependenceVerified, false)
})
test("pinned profiles retain the other path for inspection and exclude it from eligible reserve", () => {
const profile = routeAiProfileSchema.parse({
name: "pinned", community: "65000:1", family: "ipv4", serverId: 1, pinnedCandidateId: "a",
candidates: [{ ...first, wanRemoteInterface: "wan-up", downstreamRemoteInterface: "wg-remote" }, second],
})
const result = summarizePaths(routePaths(profile))
assert.deepEqual(result.eligiblePathIds, ["a"])
assert.deepEqual(result.sharedDomains, [])
assert.deepEqual(result.paths[0].dependencies.slice(-2), [
{ kind: "wan", serverId: 2, interfaceName: "wan-up" },
{ kind: "tunnel", serverId: 3, interfaceName: "wg-remote" },
])
})
test("separate IX groups with a single eligible path do not form a reserve pair", () => {
const profile = routeAiProfileSchema.parse({ name: "failover", community: "65000:1", family: "ipv4", serverId: 1, candidates: [first, second] })
const paths = routePaths(profile).map((path, index) => ({ ...path, groupId: `${index + 2}/exit` }))
assert.deepEqual(summarizePaths(paths).alternativeGroups, [
{ groupId: "2/exit", eligiblePathIds: ["a"] },
{ groupId: "3/exit", eligiblePathIds: ["b"] },
])
})
const time = (offset: number) => new Date(Date.UTC(2026, 0, 1, 0, 0, 0, offset)).toISOString()
const request = {
target: { kind: "route-ai" as const, profileId: "1551445f-7c71-4411-976f-ce30302dcefe" },
window: { from: time(0), outageAt: time(3000), restoreAt: time(10000), to: time(20000) },
controlProbe: { primaryCandidateId: "a", backupCandidateId: "b" },
targetFailoverMs: 1000, targetFailbackMs: 1000,
}
const probe = (candidateId: string, status: "passed" | "failed" | "unknown", begin: number, end: number) => ({
id: candidateId + begin, candidateId, status, startedAt: time(begin), observedAt: time(end),
})
const baseline = probe("a", "passed", 2500, 2700)
const failure = probe("a", "failed", 3100, 3300)
const recovered = probe("a", "passed", 10100, 10500)
test("report passes each probe deadline and leaves HTTPS, SSH and existing connections unverified", () => {
const result = assessFailover(request, [baseline, failure, probe("b", "failed", 3100, 3400), probe("b", "passed", 3500, 3800), recovered])
assert.equal(result.status, "passed")
assert.equal(result.failover.lowerBoundMs, 100)
assert.equal(result.failover.upperBoundMs, 800)
assert.equal(result.failover.firstGood?.id, "b3500")
assert.equal(result.failback.upperBoundMs, 500)
assert.equal(result.https, "inconclusive")
assert.equal(result.serviceFailover, "inconclusive")
assert.equal(result.existingConnections, "inconclusive")
assert.equal(result.managementSsh, "inconclusive")
assert.equal(result.returnPathVerified, false)
})
test("report fails when the latest definitive failed probe started after the deadline", () => {
const result = assessFailover(request, [baseline, failure, probe("b", "failed", 4500, 4700), probe("b", "passed", 4800, 5000), recovered])
assert.equal(result.status, "failed")
assert.equal(result.failover.lowerBoundMs, 1500)
assert.equal(result.failover.upperBoundMs, 2000)
assert.equal(result.failover.lastBad?.id, "b4500")
})
test("late first success, unknown evidence, flap, or truncated history cannot establish success", () => {
const history = [baseline, failure, recovered]
assert.equal(assessFailover(request, [...history, probe("b", "passed", 4500, 4700)]).status, "inconclusive")
assert.equal(assessFailover(request, [...history, probe("b", "unknown", 4500, 4700)]).status, "inconclusive")
const pass = probe("b", "passed", 3500, 3700)
assert.equal(assessFailover(request, [...history, pass, probe("b", "failed", 3800, 4000)]).status, "inconclusive")
assert.equal(assessFailover(request, [...history, pass], true).status, "inconclusive")
assert.equal(assessFailover(request, [baseline, probe("a", "unknown", 3100, 3300), recovered, pass]).status, "inconclusive")
})
@@ -0,0 +1,352 @@
import { z } from "zod"
import { routeAiProfileSchema, type RouteAiProfile } from "@mmapp/contracts/mcp-routing"
import type { IxSegment } from "@mmapp/contracts/internet-exchange"
import { pool } from "../../db/index.js"
import { ixDeviceIds } from "../../services/internet-exchange-plan.js"
import { readIxRevision, readIxSegment } from "../../services/internet-exchange-store.js"
import type { add } from "./actions.js"
import type { ActionContext } from "./action-types.js"
import { PATH_PROOF_VERSION, pathProofTag } from "./path-proof-purpose.js"
import { constantEqual, fingerprint, McpError, privateFingerprinterExisting } from "./security.js"
const siteId = z.number().int().positive().safe()
const name = z.string().trim().min(1).max(100)
const targetSchema = z.discriminatedUnion("kind", [
z.object({ kind: z.literal("route-ai"), profileId: z.uuid() }).strict(),
z.object({ kind: z.literal("ix-segment"), segmentId: z.uuid() }).strict(),
z.object({ kind: z.literal("ix-client"), segmentId: z.uuid(), serverId: siteId, interfaceName: z.string().regex(/^[A-Za-z0-9_.-]{1,48}$/) }).strict(),
])
const topologyArgs = z.object({ target: targetSchema }).strict()
const serviceEndpoint = z.object({
serverId: siteId.optional(), interfaceName: z.string().regex(/^[A-Za-z0-9_.-]{1,48}$/).optional(),
address: z.union([z.ipv4(), z.ipv6()]).optional(),
}).strict().refine(endpoint => endpoint.serverId !== undefined || endpoint.address !== undefined)
const designArgs = topologyArgs.extend({
scenario: z.enum(["wan", "jump-host", "exit", "tunnel", "return", "flap"]),
offset: z.number().int().min(0).max(1000).default(0),
limit: z.number().int().min(1).max(25).default(10),
protectedService: z.object({
name, source: serviceEndpoint.optional(), destination: serviceEndpoint.optional(),
maxInterruptionMs: z.number().int().min(1).max(3600000).optional(),
}).strict().optional(),
})
const timestamp = z.iso.datetime({ offset: true })
const reportArgs = topologyArgs.extend({
controlProbe: z.object({ primaryCandidateId: name, backupCandidateId: name }).strict().optional(),
window: z.object({ from: timestamp, outageAt: timestamp, restoreAt: timestamp, to: timestamp }).strict(),
targetFailoverMs: z.number().int().min(1).max(3600000),
targetFailbackMs: z.number().int().min(1).max(3600000),
})
type Target = z.infer<typeof targetSchema>
type ReportArgs = z.infer<typeof reportArgs>
type Domain = { kind: "source" | "wan" | "jump-host" | "exit" | "tunnel" | "peer"; serverId: number; interfaceName?: string }
type Path = { id: string; groupId: string; eligible: boolean; dependencies: Domain[] }
type Source = { target: Target; serverIds: number[] } & (
{ kind: "route-ai"; profile: RouteAiProfile; revision: number } |
{ kind: "ix"; segment: IxSegment; paths: Path[] }
)
export function routePaths(profile: RouteAiProfile): Path[] {
return profile.candidates.map(candidate => ({
id: candidate.id,
groupId: "route-ai",
eligible: !profile.excludedCandidateIds.includes(candidate.id) &&
(profile.pinnedCandidateId === null || profile.pinnedCandidateId === candidate.id),
dependencies: [
{ kind: "source", serverId: profile.serverId },
{ kind: "wan", serverId: profile.serverId, interfaceName: candidate.wanInterface },
{ kind: "jump-host", serverId: candidate.jumpHostId },
{ kind: "exit", serverId: candidate.exitNodeId },
{ kind: "tunnel", serverId: candidate.jumpHostId, interfaceName: candidate.downstreamInterface },
...(candidate.wanRemoteInterface ? [{ kind: "wan" as const, serverId: candidate.jumpHostId, interfaceName: candidate.wanRemoteInterface }] : []),
...(candidate.downstreamRemoteInterface ? [{ kind: "tunnel" as const, serverId: candidate.exitNodeId, interfaceName: candidate.downstreamRemoteInterface }] : []),
],
}))
}
export function summarizePaths(paths: Path[]) {
const domains = new Map<string, { domain: Domain; pathIds: Set<string> }>()
const eligibleGroups = new Map<string, string[]>()
for (const path of paths.filter(path => path.eligible)) {
const alternatives = eligibleGroups.get(path.groupId) ?? []
alternatives.push(path.id)
eligibleGroups.set(path.groupId, alternatives)
for (const domain of path.dependencies) {
const key = domain.kind === "wan" || domain.kind === "tunnel"
? JSON.stringify([domain.serverId, domain.interfaceName])
: JSON.stringify([domain.serverId])
const record = domains.get(key) ?? { domain, pathIds: new Set<string>() }
record.pathIds.add(path.id)
domains.set(key, record)
}
}
return {
paths,
eligiblePathIds: paths.filter(path => path.eligible).map(path => path.id),
alternativeGroups: [...eligibleGroups].map(([groupId, eligiblePathIds]) => ({ groupId, eligiblePathIds })),
sharedDomains: [...domains.values()].filter(value => value.pathIds.size > 1).map(value => ({
...value.domain, pathIds: [...value.pathIds],
})),
unknownDomains: ["physical-uplink", "carrier", "power", "facility", "management", "return-path"],
physicalIndependenceVerified: false,
}
}
function ixPaths(segment: IxSegment, target: Extract<Target, { kind: "ix-segment" | "ix-client" }>): Path[] {
const paths: Path[] = []
let bindingFound = false
for (const site of segment.configuration.sites) {
const client = target.kind === "ix-client" && target.serverId === site.serverId
? site.interfaces.find(binding => binding.name === target.interfaceName && binding.linux)
: undefined
if (target.kind === "ix-client" && !client) continue
if (client) bindingFound = true
const selectedExits = client?.linux?.exit ? [client.linux.exit] : site.exits
for (const group of site.groups) {
if (client && !selectedExits.includes(group.id)) continue
for (const role of ["primary", "backup"] as const) {
const path = group[role]
if (!path) continue
const binding = site.interfaces.find(item => item.name === path.interface)
const remote = binding?.peerServerId
const dependencies: Domain[] = [
{ kind: "source", serverId: site.serverId },
{ kind: path.viaMain || binding?.kind === "uplink" ? "wan" : "tunnel", serverId: site.serverId, interfaceName: path.interface },
]
if (client) dependencies.push({ kind: "tunnel", serverId: site.serverId, interfaceName: client.name })
if (remote !== undefined) {
dependencies.push({ kind: selectedExits.includes(group.id) ? "exit" : "peer", serverId: remote })
const remoteWan = binding?.provisionTransit?.remoteWan.interface
if (remoteWan) dependencies.push({ kind: "wan", serverId: remote, interfaceName: remoteWan })
}
paths.push({
id: `${site.serverId}/${group.id}/${role}`,
groupId: `${site.serverId}/${group.id}`,
eligible: client?.linux?.enabled ?? true,
dependencies,
})
}
}
}
if (target.kind === "ix-client" && !bindingFound) throw new McpError("NOT_FOUND", "Подключение IX не найдено", 404)
return paths
}
async function resolve(target: Target, context: ActionContext): Promise<Source> {
const allowed = context.connection.policy.scope.serverIds
const inScope = (ids: number[]) => ids.every(id => allowed.includes(id))
if (target.kind === "route-ai") {
const { rows: [row] } = await (context.transactionClient ?? pool).query(
"SELECT version,config FROM mcp_routing_profiles WHERE id=$1 AND connection_id=$2",
[target.profileId, context.connection.id],
)
if (!row) throw new McpError("NOT_FOUND", "Профиль Route AI не найден", 404)
const profile = routeAiProfileSchema.parse(row.config)
const serverIds = [...new Set([profile.serverId, ...profile.candidates.flatMap(candidate => [candidate.jumpHostId, candidate.exitNodeId])])]
if (!inScope(serverIds)) throw new McpError("NOT_FOUND", "Профиль Route AI не найден", 404)
return { kind: target.kind, target, profile, serverIds, revision: row.version }
}
const segment = await readIxSegment(target.segmentId, context.transactionClient)
if (!segment || !inScope(ixDeviceIds(segment.configuration))) throw new McpError("NOT_FOUND", "Сегмент IX не найден", 404)
const applied = segment.appliedRevision !== null && segment.appliedRevision !== segment.revision
? await readIxRevision(segment.id, segment.appliedRevision)
: null
const serverIds = [...new Set([...ixDeviceIds(segment.configuration), ...(applied ? ixDeviceIds(applied) : [])])]
if (!inScope(serverIds)) throw new McpError("NOT_FOUND", "Сегмент IX не найден", 404)
return { kind: "ix", target, segment, serverIds, paths: ixPaths(segment, target) }
}
function topology(source: Source) {
const { target, serverIds } = source
const details = source.kind === "route-ai"
? { source: "saved-route-ai-profile", revision: source.revision, pinnedCandidateId: source.profile.pinnedCandidateId }
: { source: "saved-ix-configuration", revision: source.segment.revision, appliedRevision: source.segment.appliedRevision }
return { target, serverIds, ...details, ...summarizePaths(source.kind === "route-ai" ? routePaths(source.profile) : source.paths) }
}
const design = {
wan: { tools: ["mm_server_wan_runtime_get", "mm_recursive_routes_get", "mm_recursive_routes_replace_plan"], criteria: "Разные WAN и next hop, с проверкой физической независимости линий." },
"jump-host": { tools: ["mm_route_optimizer_analyze", "mm_ospf_application_preview"], criteria: "Разнести транзит по разным узлам и проверить общие зависимости кандидатов." },
exit: { tools: ["mm_route_optimizer_analyze", "mm_bgp_sessions_get", "mm_ecmp_plan"], criteria: "Проверить независимость выходов, NAT, анонсы и доступность префиксов со стороны назначения." },
tunnel: { tools: ["mm_wireguard_state_get", "mm_ospf_state_get", "mm_recursive_routes_get"], criteria: "Проверить тоннели, выбранный маршрут и детектирование отказа подложки." },
return: { tools: ["mm_route_optimizer_analyze", "mm_route_path_verify"], criteria: "Проверить предпочтительный путь после восстановления, обратное направление и сохранение доступа управления вне переключаемого пути." },
flap: { tools: ["mm_route_controller_get", "mm_route_profile_save_plan"], criteria: "Сопоставить интервалы наблюдений, подтверждения, гистерезис, cooldown и бюджет переключений с допустимым временем восстановления." },
} as const
function scenarioFailures(paths: Path[], scenario: keyof typeof design) {
if (scenario === "return" || scenario === "flap") return []
const eligible = paths.filter(path => path.eligible)
const failures = new Map<string, { groupId: string; domain: Domain }>()
for (const path of eligible) {
for (const domain of path.dependencies.filter(domain => domain.kind === scenario)) {
failures.set(JSON.stringify([path.groupId, domain.serverId, domain.interfaceName]), { groupId: path.groupId, domain })
}
}
return [...failures.values()].map(({ groupId, domain }) => ({
groupId, domain,
remainingEligiblePathIds: eligible.filter(path => path.groupId === groupId && !path.dependencies.some(dependency =>
dependency.serverId === domain.serverId &&
(domain.interfaceName === undefined || dependency.interfaceName === domain.interfaceName),
)).map(path => path.id),
}))
}
type Observation = { id: string; candidateId: string; status: "passed" | "failed" | "unknown"; startedAt: string; observedAt: string }
type PhaseStatus = "passed" | "failed" | "inconclusive"
const at = (date: string) => Date.parse(date)
function phase(observations: Observation[], start: number, end: number, targetMs: number, goodAfter = start) {
const samples = observations.filter(row => at(row.startedAt) >= start && at(row.observedAt) <= end)
.sort((left, right) => at(left.observedAt) - at(right.observedAt))
const firstGood = samples.find(row => row.status === "passed" && at(row.startedAt) >= goodAfter)
const lastBad = samples.filter(row => row.status === "failed" && (!firstGood || at(row.observedAt) <= at(firstGood.startedAt))).at(-1)
const subsequentFailure = firstGood && samples.find(row => row.status === "failed" && at(row.startedAt) >= at(firstGood.observedAt))
const lowerBoundMs = (lastBad ? at(lastBad.startedAt) : start) - start
const upperBoundMs = firstGood ? at(firstGood.observedAt) - start : null
const ambiguous = firstGood && samples.some(row => row.status === "failed" &&
at(row.startedAt) < at(firstGood.observedAt) && at(row.observedAt) > at(firstGood.startedAt))
const status: PhaseStatus = ambiguous || subsequentFailure ? "inconclusive"
: upperBoundMs !== null && upperBoundMs <= targetMs ? "passed"
: lowerBoundMs > targetMs ? "failed" : "inconclusive"
return { status, lowerBoundMs, upperBoundMs, targetMs, firstGood: firstGood ?? null, lastBad: lastBad ?? null, subsequentFailure: subsequentFailure ?? null }
}
export function assessFailover(input: ReportArgs, observations: Observation[], truncated = false) {
const { window, controlProbe } = input
const ordered = [...observations].sort((left, right) => at(left.observedAt) - at(right.observedAt))
const primary = ordered.filter(row => row.candidateId === controlProbe?.primaryCandidateId)
const backup = ordered.filter(row => row.candidateId === controlProbe?.backupCandidateId)
const outage = at(window.outageAt), restore = at(window.restoreAt)
const latestBaseline = primary.filter(row => at(row.startedAt) >= at(window.from) && at(row.observedAt) < outage).at(-1)
const baseline = latestBaseline?.status === "passed" ? latestBaseline : null
const primaryFailure = primary.find(row => row.status === "failed" && at(row.startedAt) >= outage && at(row.observedAt) < restore) ?? null
const failover = phase(backup, outage, restore - 1, input.targetFailoverMs, primaryFailure ? at(primaryFailure.observedAt) : restore)
const failback = phase(primary, restore, at(window.to), input.targetFailbackMs)
const status: PhaseStatus = truncated || !baseline || !primaryFailure ? "inconclusive"
: [failover.status, failback.status].includes("failed") ? "failed"
: failover.status === "passed" && failback.status === "passed" ? "passed" : "inconclusive"
return {
status, scope: "configured-control-probe-reachability", baseline, primaryFailure, failover, failback,
restoredPath: failback.firstGood ? "control-probe-observed" : "inconclusive",
serviceFailover: "inconclusive", https: "inconclusive", existingConnections: "inconclusive", managementSsh: "inconclusive",
forwardingSelectionVerified: false, returnPathVerified: false, truncated,
}
}
const savedObservation = z.object({
id: z.uuid(), connectionId: z.uuid(), profileHash: z.string(), candidateId: name,
proofPurpose: z.literal("control-path"), proofVersion: z.literal(PATH_PROOF_VERSION),
dependencyProof: z.string().regex(/^[a-f0-9]{64}$/), status: z.enum(["passed", "failed", "unknown"]), startedAt: timestamp, observedAt: timestamp,
sourceProofs: z.array(z.object({ serverId: siteId, proof: z.string().regex(/^[a-f0-9]{64}$/) }).strict()).min(1).max(3),
})
async function report(input: ReportArgs, source: Source, context: ActionContext) {
const { window, controlProbe } = input
const from = at(window.from), outage = at(window.outageAt), restore = at(window.restoreAt), to = at(window.to)
if (!(from < outage && outage < restore && restore < to && to <= Date.now() && to - from <= 86400000)) {
throw new McpError("INVALID_INPUT", "Окно должно быть завершено, не длиннее 24 часов и включать фазы до отказа, после отказа и после восстановления", 400)
}
if (source.kind !== "route-ai") return { ...assessFailover(input, []), target: input.target, window, reason: "NO_SAVED_IX_CONTROL_PROBE_HISTORY" }
if (!controlProbe || controlProbe.primaryCandidateId === controlProbe.backupCandidateId ||
![controlProbe.primaryCandidateId, controlProbe.backupCandidateId].every(id => source.profile.candidates.some(candidate => candidate.id === id && candidate.controlProbe))) {
throw new McpError("INVALID_INPUT", "Выберите два разных кандидата с контрольной пробой из сохранённого профиля", 400)
}
const connectionId = context.connection.id
const profileHash = fingerprint(source.profile)
const { rows } = await pool.query<{ id: string; candidate_id: string; status: string; evidence: Record<string, unknown> | null }>(
`SELECT id,candidate_id,status,CASE WHEN octet_length(evidence::text)<=32768 THEN evidence END AS evidence FROM mcp_path_checks
WHERE connection_id=$1 AND profile_hash=$2 AND candidate_id=ANY($3::text[])
AND created_at >= $4::timestamptz AND created_at <= $5::timestamptz
AND evidence->>'proofPurpose' IS DISTINCT FROM 'community'
ORDER BY created_at,id LIMIT 501`,
[connectionId, profileHash, [controlProbe.primaryCandidateId, controlProbe.backupCandidateId], window.from, window.to],
)
const sign = rows.length ? await privateFingerprinterExisting("route-control-path-context-v1").catch(error => {
if (error instanceof McpError && error.code === "STATE_UNAVAILABLE") return null
throw error
}) : null
const observations: Observation[] = []
const sourceProofs = new Map<number, string>()
let evidenceError: "INVALID_CONTROL_PATH_EVIDENCE" | "SOURCE_IDENTITY_CHANGED" | null = null
for (const row of rows.slice(0, 500)) {
const { proof, ...payload } = row.evidence ?? {}
const parsed = savedObservation.safeParse(payload)
if (!parsed.success || !sign || typeof proof !== "string") {
evidenceError = "INVALID_CONTROL_PATH_EVIDENCE"
break
}
const { id, status, candidateId, startedAt, observedAt, dependencyProof } = parsed.data
const candidate = source.profile.candidates.find(candidate => candidate.id === candidateId)
const expected = new Set([source.profile.serverId, candidate?.jumpHostId, candidate?.exitNodeId])
const observed = new Set(parsed.data.sourceProofs.map(source => source.serverId))
if (id !== row.id || status !== row.status || candidateId !== row.candidate_id ||
parsed.data.connectionId !== connectionId || parsed.data.profileHash !== profileHash ||
at(startedAt) > at(observedAt) || observed.size !== parsed.data.sourceProofs.length ||
expected.size !== observed.size || ![...expected].every(id => id !== undefined && observed.has(id)) ||
!constantEqual(sign(pathProofTag("control-path") + fingerprint({ dependencyProof, value: payload })), proof)) {
evidenceError = "INVALID_CONTROL_PATH_EVIDENCE"
break
}
if (at(startedAt) < from || at(observedAt) > to) continue
for (const source of parsed.data.sourceProofs) {
if (sourceProofs.has(source.serverId) && sourceProofs.get(source.serverId) !== source.proof) evidenceError = "SOURCE_IDENTITY_CHANGED"
sourceProofs.set(source.serverId, source.proof)
}
observations.push({ id, status, candidateId, startedAt, observedAt })
}
const result = assessFailover(input, evidenceError ? [] : observations, rows.length > 500)
const eligible = routePaths(source.profile).filter(path => path.eligible).map(path => path.id)
const reason = rows.length && !sign ? "PROOF_KEY_UNAVAILABLE" : evidenceError ?? (
!eligible.includes(controlProbe.primaryCandidateId) || !eligible.includes(controlProbe.backupCandidateId) ? "CANDIDATE_UNAVAILABLE_IN_PROFILE" : null)
return { target: input.target, window, controlProbe, ...result,
...(reason ? { status: "inconclusive" as const, reason } : {}),
}
}
export function registerResilienceActions(register: typeof add) {
const target = async (input: Record<string, unknown>, context: ActionContext) => ({
scope: "servers" as const, serverIds: (await resolve(targetSchema.parse(input.target), context)).serverIds,
})
register("network.resilience.topology.read", "mm_resilience_topology_get", "Зависимости путей и общие домены отказа", "network", "mm:network:read", "read", "servers", topologyArgs, {
target,
read: async (input, context) => topology(await resolve(topologyArgs.parse(input).target, context)),
})
register("network.resilience.design.read", "mm_resilience_design_preview", "Предпросмотр резервирования по сценарию отказа", "network", "mm:network:read", "read", "servers", designArgs, {
target,
read: async (input, context) => {
const args = designArgs.parse(input)
const source = await resolve(args.target, context)
const serviceServers = [args.protectedService?.source?.serverId, args.protectedService?.destination?.serverId]
if (serviceServers.some(id => id !== undefined && !source.serverIds.includes(id))) {
throw new McpError("INVALID_INPUT", "Устройство защищаемого сервиса вне выбранной топологии", 400)
}
const observed = topology(source)
const proposal = design[args.scenario]
const failures = scenarioFailures(observed.paths, args.scenario)
const tools = source.kind === "ix"
? ["mm_ix_segment_get", "mm_ix_change_plan", ...(args.target.kind === "ix-client" ? ["mm_ix_linux_path_get"] : []),
...proposal.tools.filter(tool => !tool.startsWith("mm_route_") && !tool.endsWith("_plan"))]
: [...proposal.tools]
return {
target: args.target, scenario: args.scenario, protectedService: args.protectedService ?? null,
criteria: proposal.criteria, suggestedTools: tools,
eligiblePathIds: observed.eligiblePathIds, alternativeGroups: observed.alternativeGroups,
configuredReserve: observed.alternativeGroups.some(group => group.eligiblePathIds.length > 1),
configuredPathsAfterFailure: failures.slice(args.offset, args.offset + args.limit),
nextOffset: args.offset + args.limit < failures.length ? args.offset + args.limit : null,
sharedDomains: observed.sharedDomains, unknownDomains: observed.unknownDomains,
missingEvidence: ["usable-capacity", "path-mtu", "return-path", "service-interruption", "management-reachability"],
requiredChecks: ["Отдельная проверка активного маршрута и обратного направления", "Непрерывность HTTPS, действующих соединений и независимого SSH-управления по отдельным измерениям"],
}
},
})
register("network.resilience.failover.read", "mm_failover_report_get", "Оценка failover и failback по сохранённым контрольным пробам", "network", "mm:network:read", "read", "servers", reportArgs, {
target,
read: async (input, context) => {
const args = reportArgs.parse(input)
return report(args, await resolve(args.target, context), context)
},
})
}
+1 -1
View File
@@ -381,7 +381,7 @@ export function validateRosStep(resource: RosResourceSpec, action: RosStep["acti
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 (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()))) {
throw new McpError("INVALID_INPUT", "Для правила BFD без адреса укажите конкретные интерфейсы", 400)
}
@@ -1,7 +1,7 @@
import { z } from "zod"
import { pool } from "../../db/index.js"
import { hasPermission } from "../../lib/permissions.js"
import { executeTerminalDiagnostic, terminalDiagnosticSchema, type TerminalDiagnosticClient } from "../../services/terminal-diagnostics.js"
import { executeTerminalDiagnostic, readTerminalInterfaceCounters, terminalDiagnosticNames, terminalDiagnosticSchema, terminalInterfaceCountersSchema, type TerminalDiagnosticClient } from "../../services/terminal-diagnostics.js"
import { withTerminalDiagnosticClient } from "../../services/terminal-diagnostic-client.js"
import { readRoutingEndpoints } from "./routing-observation-source.js"
import { effectiveMcpConnection } from "./store.js"
@@ -10,11 +10,20 @@ import type { add } from "./actions.js"
export const TERMINAL_DIAGNOSTIC_MAX_OUTPUT_BYTES = 12000
export function registerTerminalDiagnosticActions(register: typeof add) {
const schema = terminalDiagnosticSchema.safeExtend({ serverId: z.number().int().positive().safe() })
const schema = z.object({
...terminalDiagnosticSchema.shape,
serverId: z.number().int().positive().safe(),
diagnostic: z.enum([...terminalDiagnosticNames, "interface_counters"]),
interface: terminalInterfaceCountersSchema.shape.interface,
}).strict().superRefine(({ serverId: _id, ...args }, ctx) => {
const parsed = args.diagnostic === "interface_counters" ? terminalInterfaceCountersSchema.safeParse(args) : terminalDiagnosticSchema.safeParse(args)
if (!parsed.success) for (const issue of parsed.error.issues) ctx.addIssue({ code: "custom", message: issue.message, path: issue.path })
})
register("servers.terminal.read", "mm_server_terminal_diagnostic", "Разрешённая типизированная диагностика REST-терминала", "servers", "mm:servers:write", "read", "servers", schema, {
read: async (input, context) => {
const serverId = Number(input.serverId), { serverId: _id, ...args } = input
const command = terminalDiagnosticSchema.parse(args), generation = await accessGeneration()
const command = args.diagnostic === "interface_counters" ? terminalInterfaceCountersSchema.parse(args) : terminalDiagnosticSchema.parse(args)
const generation = await accessGeneration()
const initial = (await pool.query("SELECT id,enabled,routing_endpoint_epoch FROM servers WHERE id=$1", [serverId])).rows[0]
const authorize = async () => {
context.signal?.throwIfAborted()
@@ -33,11 +42,20 @@ export function registerTerminalDiagnosticActions(register: typeof add) {
await authorize()
if (endpoints.length !== 1 || endpoints[0].routingEndpointEpoch !== initial.routing_endpoint_epoch || !endpoints[0].enabled) throw new McpError("STATE_CONFLICT", "Источник диагностики изменился", 409)
const endpoint = endpoints[0]
try { output = await withTerminalDiagnosticClient(endpoint, { signal: context.signal, authorize }, client => executeTerminalDiagnostic(client, command)) }
const secrets = [endpoint.password, Buffer.from(`${endpoint.username}:${endpoint.password}`).toString("base64")].filter(Boolean)
try {
if (command.diagnostic === "interface_counters") {
const protect = (value: string) => secrets.some(secret => value.includes(secret)) ? "[redacted]" : String(redact(value))
const interfaceCounters = await withTerminalDiagnosticClient(endpoint, { signal: context.signal, authorize }, client => readTerminalInterfaceCounters(client, command, protect))
await authorize()
return { serverId, diagnostic: command.diagnostic, interfaceCounters, activity: { kind: "read", configurationApplied: false } }
}
output = await withTerminalDiagnosticClient(endpoint, { signal: context.signal, authorize }, client => executeTerminalDiagnostic(client, command))
}
catch (error) { if (error instanceof McpError) throw error; throw new McpError("STATE_UNAVAILABLE", "Терминальная диагностика не вернула подтверждённый результат", 409) }
// Free-form comments and log text may echo stored credentials. Mask exact
// credentials as well as labelled secrets before returning or auditing.
for (const value of [endpoint.password, Buffer.from(`${endpoint.username}:${endpoint.password}`).toString("base64")].filter(Boolean)) output = output.split(value).join("[redacted]")
for (const value of secrets) output = output.split(value).join("[redacted]")
}
await authorize()
const redactionTruncated = output.length > MAX_MCP_PUBLIC_STRING_LENGTH
@@ -1,8 +1,24 @@
import type { MikrotikClient } from "./mikrotik.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 { 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. */
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)
+1 -1
View File
@@ -907,7 +907,7 @@ export function greInterfaceBody(t: GreSnapshotTunnel): Record<string, string> {
"allow-fast-path": t.allowFastPath ? "yes" : "no",
comment: writeGreComment(t.comment, peer),
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 },
}
}
+12 -1
View File
@@ -117,9 +117,20 @@ export async function readGreMutationState(server: ServerRow, input: GreMutation
try{const value=bounded(raw);await check();return value}catch(error){throw stop(error)}
}
}
// Create and compound edit prove preservation of configured routes. Learned routes
// remain necessary for delete, rename and restore dependency checks.
const configuredRoutesOnly = input?.operation === "create" || (input?.operation === "update" && !options.identityOnly)
const [greRaw, ipv4Raw, ipv6Raw, dependencies, bindings, filters] = await settledGreReads([
client.get<unknown>("/interface/gre").then(value=>readGreNativeRows(rows(value,[".id","name"],100))),client.get<unknown>("/ip/address").then(value=>rows(value,[".id","address","interface"])),client.get<unknown>("/ipv6/address").then(value=>rows(value,[".id","address","interface"])),
settledGreReads(greDependencyPaths.map(async path => [path, rows(await client.get<unknown>(path), path === "/interface" ? [".id", "name"] : [".id"])] as const),stop),
settledGreReads(greDependencyPaths.map(async path => {
const configuredRoute = configuredRoutesOnly && (path === "/ip/route" || path === "/ipv6/route")
const requestPath = configuredRoute ? path + "?static=true" : path
const catalogue = rows(await client.get<unknown>(requestPath), path === "/interface" ? [".id", "name"] : [".id"])
if (configuredRoute && catalogue.some(row => observedBoolean(row.dynamic) === true || observedBoolean(row.static) === false)) {
throw greMutationProblem("RouterOS вернул маршруты вне запрошенного фильтра GRE")
}
return [path, catalogue] as const
}),stop),
pool.query('SELECT id,interface_name AS "interfaceName" FROM user_interface_bindings WHERE server_id=$1 ORDER BY id LIMIT 1001', [server.id]),
pool.query('SELECT id,gateway_tunnel_id AS "gatewayTunnelId",gateway FROM filter_rules WHERE server_id=$1 ORDER BY id LIMIT 1001', [server.id]),
]as const,stop)
+54 -2
View File
@@ -1,7 +1,9 @@
import assert from "node:assert/strict"
import { greMutationSchema } from "./gre-mutation-input.js"
import { planGreMutation, verifyGreMutationOp, executeGreMutationOps } from "./gre-mutation.js"
import { assertGreDeleteDependencies, greDependencyPaths, greMutationProof, readGrePskValue, type GreMutationState } from "./gre-mutation-state.js"
import { assertGreDeleteDependencies, greDependencyPaths, greMutationProof, readGreMutationState, readGrePskValue, type GreMutationState } from "./gre-mutation-state.js"
import { pool } from "../db/index.js"
import { MikrotikClient } from "./mikrotik.js"
import type { ServerRow } from "../modules/servers/repository/servers-repository.js"
import type { RosWriteOp } from "./entity-snapshots.js"
@@ -25,6 +27,7 @@ function apply(state:GreMutationState,op:RosWriteOp) {
next[key].push(row)
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 === "post" && op.path === "/interface/gre/unset") next.gre.find(row=>row[".id"]===body[".id"])!["ipsec-secret"] = ""
else if (op.op === "delete") {
next[key]=next[key].filter(row=>row[".id"]!==id)
if (key==="gre") next.dependencies["/interface"]=next.dependencies["/interface"].filter(row=>row[".id"]!==id)
@@ -38,6 +41,10 @@ let state = empty(), commands = 0
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("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 autoPut = planGreMutation(server,autoCreate,state)[0]
assert.equal("body" in autoPut && autoPut.body.mtu, "auto")
@@ -60,7 +67,19 @@ assert.equal(verifyGreMutationOp(autoState, autoAfter, autoPatch), false)
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))
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"}]
assert.throws(()=>planGreMutation(server,create,collision),/используется/)
assert.throws(()=>planGreMutation(server,greMutationSchema.parse({operation:"delete",rosId:"*G",name:"different"}),preserve),/разные/)
@@ -95,4 +114,37 @@ assert.equal(commands,1); assert.equal(state.gre[0].disabled,"true")
const deletion = greMutationSchema.parse({operation:"delete",name:"own-gre"})
const deleteOps = planGreMutation(server,deletion,state)
assert.equal(deleteOps.at(-1)?.path,"/interface/gre/*C")
const originalClient = MikrotikClient.fromServer, originalQuery = pool.query
const routeRequests: string[] = []
const configured = { ".id": "*S", static: "true", dynamic: "false" }
const learned = Array.from({ length: 25_626 }, (_, i) => ({ ".id": `*${(i + 100).toString(16)}`, dynamic: "true", bgp: "true" }))
let ignoresFilter = false
MikrotikClient.fromServer = (() => ({
async get(path: string) {
if (!/^\/(?:ip|ipv6)\/route(?:\?|$)/.test(path)) return []
routeRequests.push(path)
if (path.endsWith("?static=true")) return ignoresFilter ? [configured, learned[0]] : [configured]
return [configured, ...learned]
},
async post() { throw new Error("Unexpected native read in route catalogue test") },
})) as unknown as typeof MikrotikClient.fromServer
pool.query = (async () => ({ rows: [] })) as unknown as typeof pool.query
try {
const configuredPaths = ["/ip/route?static=true", "/ipv6/route?static=true"]
for (const input of [create, greMutationSchema.parse({ operation: "update", name: "test-gre", fields: { enabled: true } })]) {
routeRequests.length = 0
const snapshot = await readGreMutationState(server, input)
assert.deepEqual(routeRequests.sort(), configuredPaths.sort())
assert.deepEqual(snapshot.dependencies["/ip/route"], [configured])
}
ignoresFilter = true
await assert.rejects(readGreMutationState(server, create), /вне запрошенного фильтра GRE/)
routeRequests.length = 0
await assert.rejects(readGreMutationState(server, deletion), /каталог зависимостей GRE/)
assert.deepEqual(routeRequests.sort(), ["/ip/route", "/ipv6/route"].sort())
} finally {
MikrotikClient.fromServer = originalClient
pool.query = originalQuery
}
console.log("GRE mutations: disabled staging, v4→v6 primary replacement, opaque/timer/secret preservation, native identity, parent/application dependencies, link-local exclusion, per-command proof and ignored/lost stop")
+25 -4
View File
@@ -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"
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){
try{
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)
if (ops[0]?.op !== "patch") throw greMutationProblem("Не подготовлено изменение GRE")
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
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 ?? ""
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"
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"}})
return ops
}
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 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
@@ -79,8 +96,11 @@ export function verifyGreMutationOp(before: GreMutationState, after: GreMutation
const id = op.path === path ? undefined : decodeURIComponent(op.path.slice(path.length+1))
if (op.op === "put") {
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 (key!=="gre"&&observedBoolean(after[key].find(row=>row[".id"]===added[0][".id"])?.dynamic)!==false) return false
if (added.length !== 1 || !same(next[key].filter(row=>row!==added[0]),prior[key])) 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.
// This proof confirms configuration, not link/DAD/forwarding readiness.
} else {
@@ -124,6 +144,7 @@ export async function mutateGreTunnel(server: ServerRow, raw: GreMutation, expec
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=>{
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))
if (op.op === "delete") return client.delete(path)
if (op.op === "patch") return client.patch(path,op.body)
@@ -1,5 +1,5 @@
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 {greDependencyPaths,type GreMutationState} from "./gre-mutation-state.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 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 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)})
let sequence=0
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 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"){
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)
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==="post"&&op.path==="/interface/gre/unset")next.gre.find(r=>r[".id"]===body[".id"])!["ipsec-secret"]=""
else if(op.op==="delete"){
next[key]=next[key].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")
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.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)
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=[]
+11 -17
View File
@@ -9,7 +9,7 @@ import { canonicalGreSnapshot,greAddressKey,greAddressPath,greInterfaceBody,isHi
import { mapGreLive } from "./gre-live.js"
import { greMtuSchema } from "./gre-mutation-input.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 { MikrotikClient } from "./mikrotik.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}
/** 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[]{
const wanted=new Set(desired.tunnels.map(row=>row.name))
for(const live of before.gre){
@@ -95,10 +84,15 @@ export function planGreRevisionRestore(desired:GreSnapshot,before:GreMutationSta
let op=item
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 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 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)))
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)
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 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 wire=greRestoreWireOp(op,before)
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()))
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(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")
}})
const verified=receipt.verified&&planGreRevisionRestore(desired,receipt.after).length===0
+8 -10
View File
@@ -3,6 +3,7 @@ import { createHash } from "node:crypto"
import type { IxConfiguration, IxRouterObject, IxSite } from "@mmapp/contracts/internet-exchange"
import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js"
import { compileIxTransit, ixTransitSourceObjects } from "./internet-exchange-transit.js"
import { greIke2TransportFields, greIpsecPaths, greIpsecPlaintextDrops } from "./gre-ipsec-transport.js"
export class IxConflict extends Error {
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 } })
}
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" })
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" })
const [inbound, outbound] = greIpsecPlaintextDrops(binding.localEndpoint!, binding.endpoint!)
add(greIpsecPaths.filter, "gre-in-" + key, inbound)
add(greIpsecPaths.filter, "gre-out-" + key, outbound)
}
const dropInterface = ixDiscardInterface(id)
for (const [index, binding] of site.interfaces.entries()) {
@@ -296,14 +298,10 @@ export function compileIxConfiguration(id: string, configuration: IxConfiguratio
if (gre) {
const transport = namespace + "-" + key
protectGre(binding, key)
add("/ip/ipsec/profile", key, { name: transport, "enc-algorithm": "aes-256", "hash-algorithm": "sha256", "dh-group": "modp2048" })
add("/ip/ipsec/proposal", key, { name: transport, "enc-algorithms": "aes-256-cbc", "auth-algorithms": "sha256", "pfs-group": "modp2048" })
add("/ip/ipsec/peer", key, { name: transport, address: host(binding.endpoint!), "local-address": binding.localEndpoint!,
profile: transport, "exchange-mode": "ike2", passive: "true" })
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 })
const fields = greIke2TransportFields(transport, binding.localEndpoint!, binding.endpoint!, true, "ix-credential:" + gre.credentialId, !binding.linux!.enabled)
for (const kind of ["profile", "proposal", "peer"] as const) add(greIpsecPaths[kind], key, fields[kind])
add(greIpsecPaths.identity, "gre-identity-" + key, fields.identity)
add(greIpsecPaths.policy, "gre-policy-" + key, fields.policy)
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) })
}
@@ -1,7 +1,7 @@
import assert from "node:assert/strict"
import { setTimeout as delay } from "node:timers/promises"
import { MikrotikClient } from "./mikrotik.js"
import { dispatchTerminalCommand, executeTerminalDiagnostic, parseTerminalCommand, terminalDiagnosticSchema } from "./terminal-diagnostics.js"
import { dispatchTerminalCommand, executeTerminalDiagnostic, parseTerminalCommand, readTerminalInterfaceCounters, terminalDiagnosticSchema, terminalInterfaceCountersSchema } from "./terminal-diagnostics.js"
import { withTerminalDiagnosticClient } from "./terminal-diagnostic-client.js"
import { createTerminalDiagnosticFixture, terminalDiagnosticCases } from "../test/terminal-diagnostic-fixture.js"
@@ -22,6 +22,24 @@ try {
for (const bad of [{ diagnostic: "execute", command: "/system reboot" }, { diagnostic: "interfaces", target: "host" }, { diagnostic: "logs", count: 2 }, { diagnostic: "ping" }, { diagnostic: "ping", target: "192.0.2.1", count: 21 }, { diagnostic: "logs", limit: 201 }]) assert.equal(terminalDiagnosticSchema.safeParse(bad).success, false)
for (const bad of ["/system reboot", ":execute /system resource print", "ip address print;system reboot", "log print limit=0", "ping host count=1junk"]) assert.throws(() => parseTerminalCommand(bad))
const oldInterfaces = fixture.payloads["/interface"]
fixture.payloads["/interface"] = [
{ name: "ether-a", running: "true", "rx-byte": "18446744073709551615", "rx-error": "0", "tx-error": "-1", "rx-drop": "2", "link-downs": "3", "last-link-down-time": "2026-01-01 00:00:00", comment: endpoint.password },
{ name: "ether-b", "tx-queue-drop": "4" },
]
const counters = (args: object) => withTerminalDiagnosticClient(endpoint, { authorize }, native => readTerminalInterfaceCounters(native,
terminalInterfaceCountersSchema.parse({ diagnostic: "interface_counters", ...args }), value => value))
const first = await counters({ limit: 1 })
assert.equal(first.total, 2)
assert.equal(first.truncated, true)
assert.equal(first.rows.length, 1)
assert.equal(first.rows[0].lastLinkDownAt, "2026-01-01 00:00:00")
assert.equal(first.rows[0].running, true)
assert.deepEqual(first.rows[0].counters, { rxBytes: "18446744073709551615", txBytes: null, rxPackets: null, txPackets: null, rxDrops: "2", txDrops: null, txQueueDrops: null, rxErrors: "0", txErrors: null, linkDowns: "3" })
assert.equal(first.resetHistoryAvailable, false)
assert.ok(first.routerUptime)
assert.ok(!JSON.stringify(first).includes(endpoint.password))
assert.equal((await counters({ interface: "ether-b" })).rows[0].counters.txQueueDrops, "4")
assert.equal(terminalInterfaceCountersSchema.safeParse({ diagnostic: "interface_counters", limit: 51 }).success, false)
fixture.payloads["/interface"] = Array.from({ length: 1001 }, () => ({ name: "x" }))
await assert.rejects(withTerminalDiagnosticClient(endpoint, { authorize }, native => native.getInterfaces()))
fixture.payloads["/interface"] = [{ name: "x".repeat(1048577) }]
@@ -236,6 +236,46 @@ export const terminalDiagnosticSchema = z.object({
})
export type TerminalDiagnostic = z.infer<typeof terminalDiagnosticSchema>
export type TerminalDiagnosticClient = Pick<MikrotikClient, "getIpAddresses" | "getInterfaces" | "getResource" | "getIdentity" | "getIpRoutes" | "getFirewallFilters" | "getBgpSessions" | "getOspfNeighbors" | "getOspfAreas" | "getOspfInstances" | "getOspfInterfaceTemplates" | "getBfdSessions" | "getLogs" | "ping">
export const terminalInterfaceCountersSchema = z.object({
diagnostic: z.literal("interface_counters"),
interface: z.string().min(1).max(128).regex(/^[^\p{Cc}]+$/u).optional(),
limit: z.number().int().min(1).max(50).default(20),
}).strict()
export async function readTerminalInterfaceCounters(
client: Pick<TerminalDiagnosticClient, "getInterfaces" | "getResource">,
input: z.infer<typeof terminalInterfaceCountersSchema>,
protect: (value: string) => string,
) {
const [interfaces, resource] = await Promise.all([client.getInterfaces(), client.getResource()])
const properties = {
rxBytes: "rx-byte", txBytes: "tx-byte", rxPackets: "rx-packet", txPackets: "tx-packet",
rxDrops: "rx-drop", txDrops: "tx-drop", txQueueDrops: "tx-queue-drop",
rxErrors: "rx-error", txErrors: "tx-error", linkDowns: "link-downs",
} as const
const text = (value: unknown, max: number) =>
typeof value === "string" && value.length <= max && /^[^\p{Cc}]+$/u.test(value) ? protect(value) : null
const counter = (value: unknown) => {
if (typeof value !== "string" || !/^\d{1,20}$/.test(value) || BigInt(value) > 18446744073709551615n) return null
return protect(value) === value ? value : null
}
const flag = (value: unknown) => value === "true" ? true : value === "false" ? false : null
const selected = interfaces.filter(row => input.interface === undefined || row.name === input.interface)
const rows = selected.slice(0, input.limit).map(row => {
const native = row as typeof row & Partial<Record<(typeof properties)[keyof typeof properties] | "last-link-down-time" | "last-link-up-time", unknown>>
const counters = Object.fromEntries(Object.entries(properties).map(([key, property]) => [key, counter(native[property])])) as Record<keyof typeof properties, string | null>
return {
name: text(row.name, 128), type: text(row.type, 64), running: flag(row.running), disabled: flag(row.disabled),
counters,
lastLinkDownAt: text(native["last-link-down-time"], 40), lastLinkUpAt: text(native["last-link-up-time"], 40),
}
})
return {
rows, total: selected.length, limit: input.limit, truncated: rows.length < selected.length,
observedAt: new Date().toISOString(), routerUptime: text(resource.uptime, 64),
countersAreCumulative: true, lastCounterResetAt: null, resetHistoryAvailable: false,
}
}
export class ExecValidationError extends Error { readonly statusCode = 400 }
/** REST grammar is intentionally an allowlist, never a RouterOS script. */
+19 -3
View File
@@ -27,6 +27,7 @@ import { resolveIfaceName } from "./traffic-flow-ifaces.js"
import { factIfaceAliases } from "./traffic-flow-ifindex.js"
import { getTrafficFlowSettingsRow } from "./traffic-flow-settings.js"
import { applicationName, flowRowMatchesFilter } from "./traffic-flow-apps.js"
import { canonicalIp, ipv6ToInt } from "./traffic-flow-ip.js"
import { collapseGreEspRows, dedupFlowRowsMaxBytes, flowTupleKey } from "./traffic-flow-dedup.js"
import { enqueueRipeMisses } from "./traffic-flow-ripe.js"
import { classifyFlowPlane, flowBps, shouldKeepPlane } from "./traffic-flow-planes.js"
@@ -50,6 +51,7 @@ export interface FlowAnalyticsQuery {
serverId?: number
userId?: string
iface?: string
tuple?: { srcIp?: string; dstIp?: string; srcPort?: number; dstPort?: number; protocol?: number }
/** Default true: один 5-tuple за минуту = max байт по ifaces. */
dedup?: boolean
/** Default true: скрыть GRE/WG между клиентами JH. */
@@ -171,6 +173,7 @@ function analyticsQueryKey(q: FlowAnalyticsQuery): string {
serverId: q.serverId ?? null,
userId: q.userId ?? null,
iface: q.iface ?? null,
tuple: q.tuple ?? null,
dedup: q.dedup !== false,
excludeMesh: q.excludeMesh !== false,
excludeOverlay: q.excludeOverlay !== false,
@@ -242,8 +245,21 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
const ingress = matchesIngress(row), egress = matchesEgress(row)
return ingress === egress ? null : ingress ? "rx" : "tx"
}
const selected = ifaceFilter || allow ? raw.filter(row => (matchesIngress(row) || matchesEgress(row)) &&
const visible = ifaceFilter || allow ? raw.filter(row => (matchesIngress(row) || matchesEgress(row)) &&
(!q.userId || resolveFlowClient(topo, row.serverId, resolveIfaceName(row.serverId, row.inIface).name, resolveIfaceName(row.serverId, row.outIface).name)?.userId === q.userId)) : raw
const tuple = q.tuple
const ipKey = (value: string) => {
const ip = canonicalIp(value)
return ip.includes(":") ? ipv6ToInt(ip) ?? ip : ip
}
const src = tuple?.srcIp === undefined ? undefined : ipKey(tuple.srcIp)
const dst = tuple?.dstIp === undefined ? undefined : ipKey(tuple.dstIp)
const selected = tuple ? visible.filter(row =>
(src === undefined || src === ipKey(row.src)) &&
(dst === undefined || dst === ipKey(row.dst)) &&
(tuple.srcPort === undefined || tuple.srcPort === row.srcPort) &&
(tuple.dstPort === undefined || tuple.dstPort === row.dstPort) &&
(tuple.protocol === undefined || tuple.protocol === row.proto)) : visible
const { rows, espDirections } = collapseGreEspRows(selected, ifaceFilter ? interfaceDirection : serverDirection)
const previousMinute = new Date(Math.floor(now / 60_000) * 60_000 - 60_000).toISOString()
const ifacesForWire = new Set<string>()
@@ -479,7 +495,7 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
const topCategory = topLabel(categories)
const ringServer = q.serverId ?? (matched[0]?.serverId ?? 0)
const ring = ringServer && !ifaceFilter && !allow && excludeOverlay ? getRingMbps(ringServer) : null
const ring = ringServer && !ifaceFilter && !allow && !tuple && excludeOverlay ? getRingMbps(ringServer) : null
// The live ring covers about one minute; historical charts must use the requested window.
const fromBuckets = seriesFromRows(working, q.minutes, row => {
@@ -540,7 +556,7 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
await authorize()
const wire = ringServer ? await latestWireBps(ringServer, greNames, Boolean(scope)) : { bps: 0, bytes: 0 }
await authorize()
const admittedTotals = q.serverId !== undefined && !q.userId
const admittedTotals = q.serverId !== undefined && !q.userId && !tuple
? await readAdmittedFlowTotals(q.serverId, ifaceFilter, q.minutes, now)
: undefined
@@ -165,6 +165,21 @@ try{
assert.equal(series.rxSeries.reduce((sum,value)=>sum+value,0),50*8/60/1e6)
assert.equal(series.txSeries.reduce((sum,value)=>sum+value,0),100*8/60/1e6)
}
const tuple = await client.callTool({name:'mm_netflow_analytics_report_get',arguments:{
serverId:1, minutes:5, srcIp:'::ffff:198.18.1.1', dstIp:'8.8.8.8', srcPort:1, dstPort:443, protocol:6, limit:1,
}})
assert.ok(!tuple.isError,JSON.stringify(tuple))
const filtered = (tuple.structuredContent as {result:{
analytics:{bytes:number;admittedTotals?:unknown}; sourceWindow:unknown;
pages:{conversationsList:{total:number;nextOffset:number|null}};
historicalDetail:{rowLimitAppliedBeforeFilters:boolean;exactTupleTotalsVerified:boolean};
}}).result
assert.equal(filtered.analytics.bytes,100)
assert.equal(filtered.analytics.admittedTotals,undefined)
assert.deepEqual(filtered.pages.conversationsList,{total:1,nextOffset:null})
assert.deepEqual(filtered.sourceWindow,{requestedMinutes:5,effectiveMinutes:5,incomplete:false})
assert.equal(filtered.historicalDetail.rowLimitAppliedBeforeFilters,true)
assert.equal(filtered.historicalDetail.exactTupleTotalsVerified,false)
} finally {
applyHeartbeatForTests(heartbeat)
invalidateFlowAnalyticsCache()
+23 -4
View File
@@ -9,10 +9,10 @@ import { createMcpConnection, authenticateMcpToken } from "../modules/mcp/store.
import { approvePlan, applyPlan, invokeMcpTool } from "../modules/mcp/runtime.js"
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" }]
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" },
{ ".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" }],
@@ -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" }],
}
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") {
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
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"]
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") {
writes++
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 = [{ ".id": "*peer" }]
ignoreRouteQuery = true; await assert.rejects(plan("connected"), /не соответствует запросу источников/); ignoreRouteQuery = false
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(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)
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)
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 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)
+12 -2
View File
@@ -9,7 +9,7 @@ import { createMcpConnection, authenticateMcpToken } from "../modules/mcp/store.
import { approvePlan, applyPlan, invokeMcpTool } from "../modules/mcp/runtime.js"
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 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" }
@@ -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/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/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 (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)
@@ -69,6 +69,16 @@ 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")
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)
collections["/ip/vrf"].push({ ".id": "*mainVrf", name: "main", interfaces: "all" })
collections["/routing/table"].push({ ".id": "*mainTable", name: "main", fib: "" })
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")
peer["routing-table"] = "lab"; await assert.rejects(prepare())
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
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)
+11
View File
@@ -48,6 +48,17 @@ export async function verifyMcpFlowAnalytics(actor: AuthUser) {
assert.equal((await read({offset:1,limit:1})).analytics.conversationsList.length,1)
assert.equal((await read({interface:"analytics-in"})).analytics.bytes,100)
assert.equal((await read({userId:users[0]})).analytics.bytes,100)
const tuple = { srcIp: "::ffff:198.18.241.2", dstIp: "8.8.8.8", srcPort: 12345, dstPort: 443, protocol: 6 }
result = await read({ ...tuple, limit: 1 })
assert.equal(result.analytics.bytes, 200)
assert.equal(result.analytics.admittedTotals, undefined)
assert.equal(result.pages.conversationsList.total, 1)
assert.equal(result.pages.conversationsList.nextOffset, null)
assert.equal((await read({ ...tuple, offset: 1 })).analytics.conversationsList.length, 0)
for (const mismatch of [{ srcIp: "198.18.241.9" }, { dstIp: "8.8.4.4" }, { srcPort: 12346 }, { dstPort: 0 }, { protocol: 17 }]) {
assert.equal((await read({ ...tuple, ...mismatch })).analytics.bytes, 0)
}
for (const invalid of [{ srcIp: "198.18.241.0/24" }, { dstPort: 65536 }, { protocol: 256 }]) await assert.rejects(read(invalid))
await put(110,"analytics-duplicate-in",50,"198.18.241.1")
assert.equal((await read()).analytics.bytes,300)
assert.equal((await read({dedup:false,excludeMesh:false,excludeOverlay:false})).analytics.bytes,350)
+12 -1
View File
@@ -61,7 +61,18 @@ export async function verifyMcpTerminalDiagnostics(actor: AuthUser, app: Fastify
assert.equal(fixture.requests.length, beforeDenied)
await pool.query("UPDATE servers SET enabled=true WHERE id=$1", [sourceId])
const interfaces = fixture.payloads["/interface"], logs = fixture.payloads["/log"], resource = fixture.payloads["/system/resource"]
fixture.payloads["/interface"] = [{ ".id": "*1", name: "private-fixture", comment: `password=${password} token=NEVER_LOG_TOKEN`, type: "ether" }]
fixture.payloads["/interface"] = [{ ".id": "*1", name: "private-fixture", comment: `password=${password} token=NEVER_LOG_TOKEN`, type: "ether", "rx-error": "7", "link-downs": "0" }]
const typed = await invoke({ diagnostic: "interface_counters", interface: "private-fixture", limit: 1 }) as unknown as {
interfaceCounters: { rows: { name: string; counters: { rxErrors: string; linkDowns: string } }[]; routerUptime: string; resetHistoryAvailable: boolean }
}
assert.equal(typed.interfaceCounters.rows[0].name, "private-fixture")
assert.equal(typed.interfaceCounters.rows[0].counters.rxErrors, "7")
assert.equal(typed.interfaceCounters.rows[0].counters.linkDowns, "0")
assert.equal(typed.interfaceCounters.resetHistoryAvailable, false)
assert.ok(typed.interfaceCounters.routerUptime)
assert.ok(!JSON.stringify(typed).includes(password))
await assert.rejects(invoke({ diagnostic: "interface_counters", count: 1 }))
await assert.rejects(invoke({ diagnostic: "interfaces", interface: "private-fixture" }))
const redacted = await invoke({ diagnostic: "interfaces" })
assert.ok(!redacted.output.includes(password)); assert.ok(!redacted.output.includes("NEVER_LOG_TOKEN")); assert.ok(redacted.output.includes("[redacted]"))
fixture.payloads["/log"] = [{ ".id": "*1", time: "0", topics: "system,info", message: `${password} password=NEVER_PRINT_LOG_PASSWORD token=NEVER_PRINT_LOG_TOKEN` }]
@@ -0,0 +1,83 @@
import assert from "node:assert/strict"
import { randomUUID } from "node:crypto"
import { routeAiProfileSchema } from "@mmapp/contracts/mcp-routing"
import { pool } from "../db/index.js"
import { PATH_PROOF_VERSION, pathProofTag } from "../modules/mcp/path-proof-purpose.js"
import { fingerprint, privateFingerprinter } from "../modules/mcp/security.js"
export async function assertSignedResilienceHistory({ connectionId, foreignConnectionId, serverId, callReport }: {
connectionId: string
foreignConnectionId?: string
serverId: number
callReport: (input: Record<string, unknown>) => Promise<unknown>
}) {
const profileId = randomUUID()
const profile = routeAiProfileSchema.parse({
name: "Failover acceptance", serverId, community: "65000:911", family: "ipv4",
candidates: ["primary", "backup"].map(id => ({
id, wanInterface: id + "-wan", downstreamInterface: id + "-down", jumpHostId: serverId, exitNodeId: serverId,
gateway: "192.0.2.1", gatewayRef: { resource: "ipv4_route", id: "*a" },
controlProbe: { targetInterface: id + "-exit", expectedHops: [{ serverId, interface: id + "-exit" }] },
})),
})
const profileHash = fingerprint(profile)
const sign = await privateFingerprinter("route-control-path-context-v1")
const base = Date.now() - 60000
const time = (offset: number) => new Date(base + offset).toISOString()
const window = { from: time(0), outageAt: time(10000), restoreAt: time(20000), to: time(30000) }
const run = () => callReport({
target: { kind: "route-ai", profileId },
controlProbe: { primaryCandidateId: "primary", backupCandidateId: "backup" },
window, targetFailoverMs: 1500, targetFailbackMs: 1500,
})
const fixtureIds: string[] = []
async function store(candidateId: string, status: "passed" | "failed", started: number, ended: number, owner = connectionId, epoch = "1") {
const id = randomUUID()
const dependencyProof = "f".repeat(64)
const payload = {
id, connectionId: owner, profileHash, candidateId, status, dependencyProof,
proofPurpose: "control-path", proofVersion: PATH_PROOF_VERSION,
startedAt: time(started), observedAt: time(ended), sourceProofs: [{ serverId, proof: epoch.repeat(64) }],
}
const proof = sign(pathProofTag("control-path") + fingerprint({ dependencyProof, value: payload }))
await pool.query(
"INSERT INTO mcp_path_checks(id,connection_id,profile_hash,candidate_id,status,evidence,created_at) VALUES ($1,$2,$3,$4,$5,$6::jsonb,$7)",
[id, owner, profileHash, candidateId, status, JSON.stringify({ ...payload, proof }), payload.observedAt],
)
fixtureIds.push(id)
return id
}
try {
await pool.query(
"INSERT INTO mcp_routing_profiles(id,connection_id,config,grant_expires_at) VALUES ($1,$2,$3::jsonb,$4)",
[profileId, connectionId, JSON.stringify(profile), time(30000)],
)
const baseline = await store("primary", "passed", 8000, 9000)
await store("primary", "failed", 10100, 10400)
const firstGood = await store("backup", "passed", 10500, 11000)
await store("primary", "passed", 20400, 20900)
if (foreignConnectionId) await store("backup", "failed", 16000, 16500, foreignConnectionId)
const passed = await run() as { status: string; baseline: { id: string }; failover: { firstGood: { id: string }; upperBoundMs: number }; serviceFailover: string; https: string; managementSsh: string }
assert.equal(passed.status, "passed")
assert.equal(passed.baseline.id, baseline)
assert.equal(passed.failover.firstGood.id, firstGood)
assert.equal(passed.failover.upperBoundMs, 1000)
assert.equal(passed.serviceFailover, "inconclusive")
assert.equal(passed.https, "inconclusive")
assert.equal(passed.managementSsh, "inconclusive")
const moved = await store("backup", "passed", 13000, 13500, connectionId, "2")
const changed = await run() as { status: string; reason: string }
assert.equal(changed.status, "inconclusive")
assert.equal(changed.reason, "SOURCE_IDENTITY_CHANGED")
await pool.query("DELETE FROM mcp_path_checks WHERE id=$1", [moved])
await pool.query("UPDATE mcp_path_checks SET evidence=evidence-'proofPurpose' WHERE id=$1", [firstGood])
const tampered = await run() as { status: string; reason: string }
assert.equal(tampered.status, "inconclusive")
assert.equal(tampered.reason, "INVALID_CONTROL_PATH_EVIDENCE")
} finally {
await pool.query("DELETE FROM mcp_path_checks WHERE id=ANY($1::uuid[])", [fixtureIds])
await pool.query("DELETE FROM mcp_routing_profiles WHERE id=$1", [profileId])
}
}
+19
View File
@@ -131,6 +131,25 @@ npm --prefix backend run mcp:stdio
Наличие инструмента не означает, что каждый сценарий раздела проверен на стенде. Статусы — в [манифесте](mcp-final-manifest.md).
### Прямой GRE/IPsec между двумя CHR
`mm_gre_ipsec_pair_create_plan` требует разрешение `network.gre.ipsec_pair.create` и допуск к обоим серверам. Передайте в `endpoints` два объекта с `serverId`, `name` и локальным внешним IPv4 в `endpoint`. При необходимости укажите `localInnerIp` на каждой стороне и общий `mtu`. Manager генерирует единый PSK для обеих сторон. Ключ скрыт в плане и квитанции, ручная регистрация `secretRef` не нужна.
Применение создаёт две отключённые стороны. Сверьте обе через `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 оставляет пробел в наблюдениях.
2. В `mm_incident_timeline_get` выберите окно до 24 часов, включающее последний успешный запрос перед отказом и первые успешные запросы после него. С правом чтения аудита параметр `includeManagerEvents: true` добавляет записи запросов текущего MCP-подключения, привязанных к одному выбранному серверу. Сопоставьте события с текущей конфигурацией.
3. Через `mm_route_lookup_get` проверьте адрес в нужной таблице. Выбор таблицы клиентским пакетом дополнительно зависит от входного интерфейса, VRF, правил и маркировки. Проверьте обратный путь и маршрут управления. Если IP доступен, а имя не разрешается, посмотрите `mm_dns_state_get`.
4. Для профиля Route AI или подключения IX изучите общие узлы двух путей в `mm_resilience_topology_get`. Разные туннели через один WAN или один exit разделяют эту точку отказа. Физическую независимость провайдера, трассы и питания подтверждает оператор. `mm_resilience_design_preview` помогает выбрать последующие проверки и профильные планы.
5. До испытания включите независимые проверки нового клиентского соединения HTTPS, сохранения существующего соединения и доступа SSH к VPS. Задайте интервалы измерений согласно целевому времени восстановления. Испытайте отказ и возврат по отдельности.
6. Сопоставьте `mm_failover_report_get` с результатами клиентских проверок. Для цели 10 секунд два измерения с интервалом 30 секунд могут дать только неопределённый результат. Смена маршрута и успешный ping от роутера подтверждают лишь соответствующие наблюдения.
Если метод отсутствует в клиенте, сравните реестр установленной версии в «Система» → «MCP» с операциями, выданными подключению, правами владельца и режимом подключения. После изменения допуска обновите каталог MCP-клиента. Видимый глобальный метод может вернуть `GLOBAL_DENIED` при запрете глобальной области.
## Route AI
Постоянный контроллер переключает маршруты по профилю через обычные планы MCP. Настройка, требования к допуску и причины остановки — в [инструкции](mcp-enable-guide.md#постоянный-контроллер-route-ai).