fix(mcp): довести базовые сценарии и проверку маршрутизации

This commit is contained in:
Codex committed 2026-11-11 20:28:37 +07:00
1 parent 1f0704add0
commit 04225886e0
101 files changed
+6118 -329

No files matched your search

+42 -11
View File
@@ -19,7 +19,7 @@ import { hasPermission } from "../../lib/permissions.js"
import { assertOperationReplayScope, findOperationReplayTombstone, operationHistoryExpired } from "./operation-replay-tombstones.js"
import { pool } from "../../db/index.js"
import { getServerReadById } from "../servers/service/servers-service.js"
import { listUsers, getUserById, listInterfaceCatalog, getInterfaceCatalogState } from "../users/service/users-service.js"
import { listUsers, getUserById, listInterfaceCatalog, getInterfaceCatalogState, validateUserBindingCreate, UsersServiceError } from "../users/service/users-service.js"
import { getLogSettings } from "../../services/router-logs-collector.js"
import { readLogPage, readLogSummary, readLogContext, readLogEntry } from "../../services/router-logs-query.js"
import { logWhere } from "../../services/router-logs-model.js"
@@ -106,6 +106,7 @@ import { registerRecursiveRecovery } from "./recursive-recovery.js"
import { registerNetworkHostActions } from "./network-host-actions.js"
import { registerBgpFilterBindingActions } from "./bgp-filter-binding-actions.js"
import { registerBgpCommunityPolicyActions } from "./bgp-community-policy-actions.js"
import { registerBridgeVlanActions, prepareGenericBridgeVlanChange } from "./bridge-vlan-actions.js"
const serverId = z.number().int().positive().max(Number.MAX_SAFE_INTEGER)
const rowId = z.string().trim().min(1).max(200)
@@ -129,6 +130,7 @@ registerRecursiveRecovery(add)
registerNetworkHostActions(add)
registerBgpFilterBindingActions(add)
registerBgpCommunityPolicyActions(add)
registerBridgeVlanActions(add)
registerTrafficHistoryActions(add)
registerSidebarCountsActions(add)
registerLogArtifactActions(add)
@@ -156,7 +158,7 @@ for (const resource of rosResources) {
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 previousVersion = action === "create" ? (["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" ? 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 === "ospf_template" ? 1 : 0) + (resource.id === "vrf" ? 1 : 0),
version: resource.id === "ipsec_peer" ? (action === "create" ? 5 : 3) : resource.id === "certificate" ? (action === "update" ? 4 : 3) : previousVersion + (delegated ? 0 : 1) + (resource.id === "ospf_template" ? 1 : 0) + (resource.id === "vrf" ? (action === "delete" ? 3 : 2) : 0) + (["bridge", "bridge_port", "bridge_vlan"].includes(resource.id) ? 1 : 0),
prepare: async (input, context) => {
if (resource.id === "vrf" && input.productionAdmission !== true) throw new McpError("UNSUPPORTED_CAPABILITY", "VRF требует явного productionAdmission:true для проверенного native executor; raw план недоступен", 409)
const sid = Number(input.serverId), id = input.id as string | undefined
@@ -252,13 +254,24 @@ for (const resource of rosResources) {
if (dependent) throw new McpError("STATE_CONFLICT", "Объект используется: сначала подготовьте явное изменение зависимостей", 409)
}
}
const linkedVlan = await prepareGenericBridgeVlanChange({ serverId: sid, resource: resource.id, action, id, fields }, context)
if (linkedVlan) {
const captured = new Map(snapshots.map(snapshot => [snapshot.resource, snapshot]))
for (const snapshot of linkedVlan.snapshots) {
const previous = captured.get(snapshot.resource)
if (previous && (previous.fingerprint !== snapshot.fingerprint || previous.sourceProof !== snapshot.sourceProof)) throw new McpError("STATE_CONFLICT", "Зависимости VLAN изменились во время подготовки", 409)
captured.set(snapshot.resource, snapshot)
}
const objects = new Map([...references, ...linkedVlan.objects].map(object => [`${object.serverId}/${object.kind}/${object.id}`, object]))
return { ...linkedVlan, snapshots: [...captured.values()], objects: [...objects.values()] }
}
const placeBeforeId = resource.id === "vrf" && action === "create" ? before.rows[0]?.[".id"] : undefined
if (resource.id === "vrf" && action === "create" && typeof placeBeforeId !== "string") throw new McpError("STATE_CONFLICT", "Не подтверждён порядок существующих VRF", 409)
return { target: { scope: "servers", serverIds: [sid] }, objects: references, snapshots,
...(resource.id === "vrf" && input.productionAdmission === true ? { vrfProductionAdmission: true as const } : {}),
steps: splitOspfPassiveUpdate({ serverId: sid, resource: resource.id, action, id, fields, ...(typeof placeBeforeId === "string" ? { placeBeforeId } : {}) }).map(step => ({ kind: "ros" as const, step })),
requiresHuman: true,
warnings: ["Нативное изменение может затронуть управление устройством и требует подтверждения человеком.", "Автоматическое каскадное изменение зависимостей не выполняется.", ...(placeBeforeId ? [`VRF создаётся перед записью ${placeBeforeId}; порядок определяет принадлежность интерфейсов.`] : [])],
warnings: ["Нативное изменение может затронуть управление устройством и требует подтверждения человеком.", "Автоматическое каскадное изменение зависимостей не выполняется.", ...(resource.id === "vrf" && action === "delete" ? ["При удалении VRF RouterOS может удалить автоматический IPv6 link-local и его connected-маршрут пустого bridge; статические адреса сохраняются."] : []), ...(placeBeforeId ? [`VRF создаётся перед записью ${placeBeforeId}; порядок определяет принадлежность интерфейсов.`] : [])],
}
},
})
@@ -270,7 +283,7 @@ for (const definition of [
{ id: "firewall.update", tool: "mm_firewall_rule_update_plan", title: "План изменения правила firewall", resources: ["ip_filter", "ip_nat", "ip_mangle", "ip_raw", "ipv6_filter", "ipv6_nat", "ipv6_mangle", "ipv6_raw"] },
] as const) {
add(definition.id, definition.tool, definition.title, "network", "mm:network:write", "write", "servers", z.object({ serverId, resource: z.enum(definition.resources), id: rowId, fields: z.record(z.string().max(100), z.union([z.string().max(1000), z.number().finite(), z.boolean()])) }).strict(), {
version: definition.id === "interfaces.update" ? 4 : 2,
version: definition.id === "interfaces.update" ? 5 : 2,
prepare: async (input, context) => {
const resource = resourceById(String(input.resource)), fields = resource.fields.safeParse(input.fields)
if (!fields.success) throw new McpError("INVALID_INPUT", "Поля не соответствуют типизированной схеме выбранного объекта", 400)
@@ -324,6 +337,21 @@ for (const action of ["create", "update", "delete", "binding_add", "binding_remo
const ids = [...new Set([...(user?.servers ?? []).map(server => Number(server.serverId)), ...(binding?.serverId ? [binding.serverId] : []),
...(before?.bindings ?? []).map(binding => binding.serverId), ...(before?.servers ?? []).map(server => Number(server.serverId))])]
if (ids.some(id => !context.connection.policy.scope.serverIds.includes(id))) throw new McpError("SERVER_DENIED", "Сервер не разрешён")
if (action === "binding_remove" && !before?.bindings.some(binding => binding.id === input.bindingId)) {
throw new McpError("NOT_FOUND", "Привязка не найдена", 404)
}
if (action === "binding_add") {
try {
await validateUserBindingCreate(String(input.id), userBindingCreateSchema.parse(input.binding), { signal: context.signal })
} catch (error) {
if (error instanceof UsersServiceError) {
if (error.status === 409) throw new McpError("STATE_CONFLICT", error.message, 409)
if (error.status === 400) throw new McpError("INVALID_INPUT", error.message, 400)
if (error.status === 404) throw new McpError("NOT_FOUND", error.message, 404)
}
throw error
}
}
return { target: { scope: "global" }, objects: [{ kind: "user", id: String(input.id ?? "new") }, ...ids.map(id => ({ kind: "server", id: String(id), serverId: id }))], snapshots: [], before,
steps: [{ kind: "service", service: `users.${action}`, input }], warnings: ["Изменение /users не меняет JWT-права портала."] }
},
@@ -352,16 +380,17 @@ function logFilters(input: Record<string, unknown>, context: ActionContext) {
}
add("logs.query", "mm_logs_query", "История логов", "logs", "mm:servers:read", "read", "servers", logInput, {
read: async (input, context) => {
const filters = logFilters(input, context), generation = await accessGeneration()
const generation = await accessGeneration()
let filters: ReturnType<typeof logFilters>
let cursor: string | undefined, watermark: string | undefined
if (input.cursor) {
try {
const state = JSON.parse(await decryptSecret(String(input.cursor))) as { generation: string; scope: string; cursor: string; watermark: string; from: string }
if (input.from === undefined) filters.from = state.from
filters = logFilters({ ...input, from: input.from ?? state.from }, context)
if (state.generation !== generation || state.scope !== fingerprint({ filters, connection: context.connection.id })) throw new Error("cursor")
cursor = state.cursor; watermark = state.watermark
} catch { throw new McpError("RESET_REQUIRED", "Курсор устарел или относится к другим фильтрам", 409) }
}
} else filters = logFilters(input, context)
const result = await readLogPage(filters, { cursor, watermark, limit: Number(input.limit) })
return { ...result, nextCursor: result.nextCursor ? await encryptSecret(JSON.stringify({ generation, scope: fingerprint({ filters, connection: context.connection.id }), cursor: result.nextCursor, watermark: result.watermark, from: filters.from })) : null }
},
@@ -376,7 +405,7 @@ for (const context of [false, true]) add(context ? "logs.context" : "logs.get",
return context ? readLogContext(String(input.id)) : entry
},
})
add("logs.follow", "mm_logs_follow", "Новые события", "logs", "mm:servers:read", "read", "servers", logInput.safeExtend({ serverId, cursor: z.string().max(8192).optional(), waitSeconds: z.number().int().min(0).max(30).default(30) }), {
add("logs.follow", "mm_logs_follow", "Новые события", "logs", "mm:servers:read", "read", "servers", logInput.safeExtend({ serverId, limit: logInput.shape.limit.default(200), cursor: z.string().max(8192).optional(), waitSeconds: z.number().int().min(0).max(30).default(30) }), {
read: async (input, context) => {
const maintenance = context.logsFollowMaintenance
const signal = context.signal
@@ -387,16 +416,18 @@ add("logs.follow", "mm_logs_follow", "Новые события", "logs", "mm:se
assertActive()
const release = subscribeLogDevice(Number(input.serverId)), until = Date.now() + Number(input.waitSeconds) * 1000
try {
const filters = logFilters(input, context), generation = await accessGeneration()
const generation = await accessGeneration()
let filters: ReturnType<typeof logFilters>
let cursor = "0"
if (input.cursor) {
try {
const saved = JSON.parse(await decryptSecret(String(input.cursor)))
filters.from = saved.from
filters = logFilters({ ...input, from: input.from ?? saved.from }, context)
if (saved.kind !== "follow" || saved.generation !== generation || saved.scope !== fingerprint({ filters, connection: context.connection.id }) || !/^\d{1,20}$/.test(saved.cursor)) throw new Error("cursor")
cursor = saved.cursor
} catch { throw new McpError("RESET_REQUIRED", "Курсор follow устарел или относится к другим фильтрам", 409) }
} else {
filters = logFilters(input, context)
cursor = (await pool.query("SELECT COALESCE(max(id),0)::text AS cursor FROM router_log_entries WHERE server_id=$1", [input.serverId])).rows[0].cursor
}
while (true) {
@@ -404,7 +435,7 @@ add("logs.follow", "mm_logs_follow", "Новые события", "logs", "mm:se
const current = await validatePrincipal(context.principal)
assertActive()
if (current.policy.version !== context.connection.policy.version) throw new McpError("RESET_REQUIRED", "Права или область доступа изменились; начните новое чтение", 409)
const batch = await readLogStream(filters, cursor)
const batch = await readLogStream(filters, cursor, Number(input.limit))
assertActive()
cursor = batch.cursor
if (batch.entries.length || !batch.enabled || Date.now() >= until) return { ...batch, cursor: await encryptSecret(JSON.stringify({ kind: "follow", generation, scope: fingerprint({ filters, connection: context.connection.id }), cursor, from: filters.from })) }
@@ -17,6 +17,7 @@ try{
await pool.query("INSERT INTO backup_storage_settings(id) VALUES(1) ON CONFLICT(id) DO NOTHING")
await updateMcpSettings({enabled:true},actor)
app=await buildApp({startScheduler:false});await app.ready()
await (await import("../../test/mcp-users-bindings.js")).verifyMcpUserBindings(actor)
await (await import("./routing-community-context-acceptance.js")).acceptRouteCommunityContextMcp(actor)
await (await import("../../test/mcp-acme-test.js")).verifyMcpAcmeTest(actor)
await (await import("../../test/mcp-acme-settings.js")).verifyMcpAcmeSettings(actor)
@@ -0,0 +1,153 @@
import { z } from "zod"
import { isIP } from "node:net"
import { bridgeVlanConfigurationRequestSchema } from "@mmapp/contracts/bridge-vlan"
import { buildBridgeVlanConfiguration, bridgeVlanCurrentDesired, BridgeVlanConfigurationError, type BridgeVlanState } from "../../services/bridge-vlan-configuration.js"
import { readRosSnapshot, routerClient, rosSnapshotSourceProof, type RosSnapshot, type RosStep } from "./resources.js"
import { verifyBridgeManagementChannel } from "./management.js"
import { McpError } from "./security.js"
import { canonicalBridgeVlanValue } from "../../services/bridge-vlan-values.js"
import type { ActionContext, ChangeEvidence } from "./action-types.js"
import type { add } from "./actions.js"
const interfaceResources = ["ethernet", "bridge", "vlan", "gre", "wireguard", "vxlan"]
const resources = [...interfaceResources, "bridge_port", "bridge_vlan", "ipv4_address", "ipv6_address"]
export async function readBridgeVlanState(serverId: number, context: Pick<ActionContext, "signal">): Promise<{ state: BridgeVlanState; snapshots: RosSnapshot[] }> {
const snapshots: RosSnapshot[] = []
const active = async () => { if (context.signal?.aborted) throw new McpError("READ_CANCELLED", "Чтение конфигурации VLAN отменено", 409) }
// Bind every catalogue to the same configured device source. The executor
// rechecks these complete configuration snapshots before each native write.
for (const resource of resources) snapshots.push(await readRosSnapshot(serverId, resource, active, snapshots[0]?.sourceProof))
const rows = (resource: string) => snapshots.find(snapshot => snapshot.resource === resource)!.rows
const state: BridgeVlanState = {
bridges: rows("bridge"), ports: rows("bridge_port"), vlans: rows("bridge_vlan"),
interfaces: snapshots.filter(snapshot => interfaceResources.includes(snapshot.resource)).flatMap(snapshot => snapshot.rows.map(row => ({
resource: snapshot.resource, id: String(row[".id"]), name: String(row.name), disabled: row.disabled,
}))),
vlanInterfaces: rows("vlan"), ipv4Addresses: rows("ipv4_address"), ipv6Addresses: rows("ipv6_address"),
}
return { state, snapshots }
}
export async function prepareBridgeVlanConfiguration(raw: unknown, context: ActionContext): Promise<ChangeEvidence> {
const input = bridgeVlanConfigurationRequestSchema.parse(raw)
let management: Awaited<ReturnType<typeof verifyBridgeManagementChannel>> | undefined
try { management = await verifyBridgeManagementChannel(input.serverId) }
catch (error) {
// Only lack of a current alternate channel permits primary-path admission.
// Identity, transport and other verification failures stay fail-closed.
if (!(error instanceof McpError) || error.code !== "APPROVAL_REQUIRED") throw error
}
const { state, snapshots } = await readBridgeVlanState(input.serverId, context)
const primaryManagement = management === undefined
if (!management) {
const { server } = await routerClient(input.serverId)
if (!isIP(server.host)) throw new McpError("MANAGEMENT_UNSAFE", "Основной адрес управления должен быть буквальным IP, подтверждённым в конфигурации устройства", 409)
if (!snapshots[0]?.sourceProof || await rosSnapshotSourceProof(server) !== snapshots[0].sourceProof) throw new McpError("STATE_CONFLICT", "Источник основного управления изменился во время подготовки VLAN", 409)
const expiresAt = Math.min(Date.parse(context.connection.policy.expiresAt), context.connection.owner_valid_until.getTime(), Date.parse(context.principal.credentialExpiresAt))
if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) throw new McpError("APPROVAL_REQUIRED", "Нет действующего допуска для основного канала управления", 409)
management = { channelId: "primary", serverId: input.serverId, host: server.host, expiresAt: new Date(expiresAt).toISOString() }
}
try {
const plan = buildBridgeVlanConfiguration({ ...input, state, management, now: Date.now() })
if (!plan.steps.length) throw new McpError("STATE_CONFLICT", "Конфигурация VLAN уже соответствует плану", 409)
return {
target: { scope: "servers", serverIds: [input.serverId] }, objects: plan.objects,
snapshots, steps: plan.steps.map(step => ({ kind: "ros" as const, step })),
requiresHuman: true, validUntil: management.expiresAt,
...(primaryManagement ? {} : { managementChannels: [{ channelId: management.channelId, serverId: management.serverId, expiresAt: management.expiresAt }] }),
warnings: ["Связанный план изменяет VLAN memberships и PVID в указанном порядке; включение filtering выполняется последним.",
"Каждая подтверждённая запись проверяется до следующей. При неизвестном результате дальнейшие записи останавливаются.",
primaryManagement ? "Используется основной адрес управления; независимость канала не подтверждена. Обязательно подтверждение человеком; каждый префикс плана сохраняет подтверждённый management-доступ."
: "Проверяется конфигурация и доступность зарегистрированного management-канала. Передача пользовательского трафика требует отдельной сетевой проверки."],
}
} catch (error) {
if (error instanceof BridgeVlanConfigurationError) throw new McpError(error.code, error.message, 409)
throw error
}
}
/** A legacy single-row tool must pass the same effective-state checks, but may
* not acquire authority to edit other resource kinds through this delegation. */
export async function prepareGenericBridgeVlanChange(step: RosStep, context: ActionContext): Promise<ChangeEvidence | undefined> {
const sensitive = step.resource === "bridge" ? ["pvid", "vlan-filtering", "frame-types", "ingress-filtering"] : step.resource === "bridge_port"
? ["bridge", "interface", "pvid", "ingress-filtering", "frame-types", "disabled"] : ["bridge", "vlan-ids", "tagged", "untagged", "disabled"]
if (!["bridge", "bridge_port", "bridge_vlan"].includes(step.resource) || step.resource === "bridge" && step.action !== "update"
|| step.action === "update" && !Object.keys(step.fields).some(key => sensitive.includes(key))) return undefined
const { state } = await readBridgeVlanState(step.serverId, context)
const rows = step.resource === "bridge" ? state.bridges : step.resource === "bridge_port" ? state.ports : state.vlans
const row = rows.find(item => item[".id"] === step.id)
const bridgeName = step.resource === "bridge" ? row?.name : step.fields.bridge ?? row?.bridge
const bridges = state.bridges.filter(item => item.name === bridgeName)
if (bridges.length !== 1 || step.resource !== "bridge" && row && row.bridge !== bridgeName) throw new McpError("STATE_CONFLICT", "Смена bridge требует отдельных явных планов удаления и добавления порта", 409)
const bridgeId = String(bridges[0][".id"])
try {
const desired = bridgeVlanCurrentDesired(state, bridgeId)
const bool = (value: unknown): boolean => {
if (value === "true" || value === true) return true
if (value === "false" || value === false) return false
throw new McpError("INVALID_INPUT", "Нужны явные параметры порта VLAN", 400)
}
const ref = (name: unknown) => {
const matches = state.interfaces.filter(iface => iface.name === name)
if (matches.length !== 1) throw new McpError("INVALID_INPUT", "Не подтверждён стабильный ID участника VLAN", 400)
return { resource: matches[0].resource, id: matches[0].id }
}
if (step.resource === "bridge") {
if (Object.keys(step.fields).some(key => !sensitive.includes(key))) throw new McpError("INVALID_INPUT", "Подготовьте свойства bridge и VLAN filtering отдельными планами", 400)
if (step.fields.pvid !== undefined) desired.pvid = Number(step.fields.pvid)
if (step.fields["vlan-filtering"] !== undefined) desired.filtering = bool(step.fields["vlan-filtering"])
if (step.fields["frame-types"] !== undefined) desired.frameTypes = bridgeVlanConfigurationRequestSchema.shape.desired.shape.frameTypes.parse(step.fields["frame-types"])
if (step.fields["ingress-filtering"] !== undefined) desired.ingressFiltering = bool(step.fields["ingress-filtering"])
} else if (step.resource === "bridge_port") {
const index = desired.ports.findIndex(port => port.id === step.id)
if (step.action === "delete") {
if (index < 0) throw new McpError("NOT_FOUND", "Статический порт не найден", 404)
desired.ports.splice(index, 1); desired.removePortIds.push(step.id!)
} else {
const effective = { ...row, ...step.fields }
const port = { ...(step.action === "update" ? { id: step.id } : {}), interface: ref(effective.interface), pvid: Number(effective.pvid),
ingressFiltering: bool(effective["ingress-filtering"]), frameTypes: effective["frame-types"], disabled: bool(effective.disabled),
...(effective.comment === undefined ? {} : { comment: effective.comment }) }
const parsed = bridgeVlanConfigurationRequestSchema.shape.desired.shape.ports.element.parse(port)
if (step.action === "create") desired.ports.push(parsed)
else { if (index < 0) throw new McpError("NOT_FOUND", "Статический порт не найден", 404); desired.ports[index] = parsed }
}
} else {
const index = desired.vlans.findIndex(vlan => vlan.id === step.id)
if (step.action === "delete") {
if (index < 0) throw new McpError("NOT_FOUND", "Статическая VLAN membership не найдена", 404)
desired.vlans.splice(index, 1); desired.removeVlanIds.push(step.id!)
} else {
const effective = { ...row, ...step.fields }
const members = (value: unknown) => value === undefined || value === "" ? [] : String(value).split(",").map(ref)
const vlan = { ...(step.action === "update" ? { id: step.id } : {}), vlanIds: effective["vlan-ids"], tagged: members(effective.tagged), untagged: members(effective.untagged),
disabled: effective.disabled === undefined && step.action === "create" ? false : bool(effective.disabled), ...(effective.comment === undefined ? {} : { comment: effective.comment }) }
const parsed = bridgeVlanConfigurationRequestSchema.shape.desired.shape.vlans.element.parse(vlan)
if (step.action === "create") desired.vlans.push(parsed)
else { if (index < 0) throw new McpError("NOT_FOUND", "Статическая VLAN membership не найдена", 404); desired.vlans[index] = parsed }
}
}
const evidence = await prepareBridgeVlanConfiguration({ serverId: step.serverId, bridgeId, desired }, context)
if (evidence.steps.length !== 1 || evidence.steps[0].kind !== "ros" || evidence.steps[0].step.resource !== step.resource || evidence.steps[0].step.action !== step.action || evidence.steps[0].step.id !== step.id) {
throw new McpError("APPROVAL_REQUIRED", "Для связанных изменений используйте явный план mm_bridge_vlan_configuration_plan с соответствующим разрешением", 409)
}
const native = evidence.steps[0].step
if (step.action === "update" && Object.entries(native.fields).some(([key, value]) => !Object.hasOwn(step.fields, key)
|| (step.resource === "bridge_vlan" ? canonicalBridgeVlanValue(key, value) !== canonicalBridgeVlanValue(key, step.fields[key]) : value !== step.fields[key]))) {
throw new McpError("STATE_CONFLICT", "Состояние VLAN изменилось во время подготовки; незапрошенные поля не будут перезаписаны", 409)
}
return evidence
} catch (error) {
if (error instanceof BridgeVlanConfigurationError) throw new McpError(error.code, error.message, 409)
throw error
}
}
export function registerBridgeVlanActions(register: typeof add) {
register("network.bridge-vlan.read", "mm_bridge_vlan_configuration_get", "Полная конфигурация bridge VLAN и стабильные ID участников", "network", "mm:network:read", "read", "servers", z.object({ serverId: z.number().int().positive() }).strict(), {
read: async (input, context) => ({ state: (await readBridgeVlanState(Number(input.serverId), context)).state }),
})
register("network.bridge-vlan.configure", "mm_bridge_vlan_configuration_plan", "Связанный план VLAN membership, PVID и bridge filtering", "network", "mm:network:write", "write", "servers", bridgeVlanConfigurationRequestSchema, {
prepare: prepareBridgeVlanConfiguration,
})
}
@@ -0,0 +1,21 @@
import assert from "node:assert/strict"
process.env.AUTH_REQUIRED = "true"
process.env.AUTH_JWT_SECRET = "bridge-vlan-owned-acceptance-secret"
process.env.AUTH_ISSUER = "https://auth.test.local"
const { pool, closePool } = await import("../../db/index.js")
const { applySqlMigrations } = await import("../../db/migrate.js")
const { updateMcpSettings } = await import("./store.js")
const { buildApp } = await import("../../index.js")
const actor = { id: "bridge-vlan-owner", email: "[email protected]", name: "Bridge VLAN owner", apps: ["mm"], permissions: ["mm:settings:admin", "mm:network:admin"], expiresAt: Date.now() + 3600000 }
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, "Disposable empty database required")
await updateMcpSettings({ enabled: true }, actor)
app = await buildApp({ startScheduler: false }); await app.ready()
await (await import("../../test/mcp-bridge-vlan-configuration.js")).verifyMcpBridgeVlanConfiguration(actor, app)
} finally {
await (await import("../../services/scheduler.js")).stopSchedulerForDatabaseOperation()
await (await import("../../services/traffic-flow-ingest.js")).stopTrafficFlowListenerForDatabaseOperation()
await app?.close(); await closePool()
}
@@ -0,0 +1,76 @@
import assert from "node:assert/strict"
import test from "node:test"
import { configurationRows, resourceById, rosSnapshotVersion, type ConfigurationRow, type RosSnapshot, type RosStep } from "./resources.js"
import { createRosPrefix } from "./ros-prefix.js"
import { verifyRosStepSnapshots } from "./ros-step-verification.js"
import { fingerprint, McpError } from "./security.js"
const snapshot = (resource: string, raw: ConfigurationRow[]): RosSnapshot => {
const rows = configurationRows(resourceById(resource), raw)
return { serverId: 1, resource, rows, fingerprint: fingerprint(rows), sourceProof: "a".repeat(64), projectionVersion: rosSnapshotVersion(resource) }
}
const membership = { ".id": "*1", bridge: "br", "vlan-ids": "20-22", tagged: "ether2,ether3", dynamic: "false", disabled: "false" }
test("VLAN readback accepts equivalent VID/member sets and omitted empty fields, retaining exact native identity", () => {
const before = snapshot("bridge_vlan", [membership])
const after = snapshot("bridge_vlan", [{ ...membership, "vlan-ids": "22,20,21", tagged: "ether3,ether2" }])
const step: RosStep = { serverId: 1, resource: "bridge_vlan", action: "update", id: "*1", fields: { "vlan-ids": "20-22", tagged: "ether3,ether2", untagged: "", comment: "" } }
assert.equal(verifyRosStepSnapshots(step, {}, before, after), true)
assert.equal(verifyRosStepSnapshots(step, {}, before, snapshot("bridge_vlan", [{ ...membership, "vlan-ids": "20-23" }])), false)
assert.equal(verifyRosStepSnapshots(step, {}, before, snapshot("bridge_vlan", [{ ...membership, ".id": "*2" }])), false)
assert.throws(() => snapshot("bridge_vlan", [{ ...membership, "vlan-ids": "20,20-22" }]), /Недостоверная/)
})
test("PVID-generated rows may change while the sealed static VLAN configuration remains exact", async () => {
const port = { ".id": "*2", bridge: "br", interface: "ether2", pvid: "10", disabled: "false" }
const dynamic = { ".id": "*D", bridge: "br", "vlan-ids": "10", untagged: "ether2", dynamic: "true" }
const raw = new Map<string, ConfigurationRow[]>([["bridge_port", [port]], ["bridge_vlan", [membership, dynamic]]])
const initial = [...raw].map(([resource, rows]) => snapshot(resource, rows))
const read = async (_server: number, resource: string, active: () => Promise<unknown> = async () => {}) => { await active(); return snapshot(resource, raw.get(resource)!) }
const prefix = createRosPrefix(initial, read)
await prefix.check()
raw.set("bridge_port", [{ ...port, pvid: "20" }])
raw.set("bridge_vlan", [membership, { ...dynamic, ".id": "*E", "vlan-ids": "20" }])
const step: RosStep = { serverId: 1, resource: "bridge_port", action: "update", id: "*2", fields: { pvid: "20" } }
await prefix.advance(step, {}, await read(1, "bridge_port"))
await prefix.check()
raw.set("bridge_vlan", [{ ...membership, tagged: "ether2" }, dynamic])
await assert.rejects(prefix.check(), error => error instanceof McpError && error.code === "STATE_CONFLICT")
})
test("full VLAN ranges and long sparse VID sets stay representable in plans and inverse snapshots", () => {
const resource = resourceById("bridge_vlan")
const expanded = Array.from({ length: 4094 }, (_, index) => String(index + 1)).join(",")
const sparse = Array.from({ length: 2047 }, (_, index) => String(index * 2 + 1)).join(",")
assert.ok(sparse.length > 100)
for (const value of ["1-4094", sparse]) assert.equal(resource.fields.safeParse({ "vlan-ids": value }).success, true)
for (const value of ["0", "4095", "10-9", "10,10-12"]) assert.equal(resource.fields.safeParse({ "vlan-ids": value }).success, false)
const before = snapshot("bridge_vlan", [membership])
const after = snapshot("bridge_vlan", [{ ...membership, "vlan-ids": expanded }])
assert.equal(after.rows[0]["vlan-ids"], "1-4094", "Native expansion must not overflow the public inverse DTO")
assert.equal(verifyRosStepSnapshots({ serverId: 1, resource: "bridge_vlan", action: "update", id: "*1", fields: { "vlan-ids": "1-4094" } }, {}, before, after), true)
})
test("unknown dynamic flags are retained; only explicit RouterOS-generated VLAN rows are excluded", () => {
assert.equal(snapshot("bridge_vlan", [{ ...membership, dynamic: "unknown" }]).rows.length, 1)
for (const dynamic of [true, "true", "yes"]) assert.equal(snapshot("bridge_vlan", [{ ...membership, dynamic }]).rows.length, 0)
assert.equal(snapshot("bridge_vlan", [{ ...membership, dynamic: "false" }]).rows.length, 1)
})
test("old bridge CPU, port and VLAN projection contracts cannot execute after semantic projection changes", () => {
for (const resource of ["bridge", "bridge_port", "bridge_vlan"]) {
const current = snapshot(resource, resource === "bridge_vlan" ? [membership] : [{ ".id": "*2", bridge: "br", interface: "ether2", pvid: "10" }])
assert.equal(current.projectionVersion, 4)
assert.throws(() => createRosPrefix([{ ...current, projectionVersion: 3 }]), error => error instanceof McpError && error.code === "PLAN_EXPIRED")
}
})
test("CPU frame admission and MVRP configuration are sealed, with no MVRP write permission", () => {
const bridge = { ".id": "*1", name: "br", pvid: "10", "vlan-filtering": "true", "frame-types": "admit-all", "ingress-filtering": "true", mvrp: "false", running: "true" }
const original = snapshot("bridge", [bridge])
for (const field of ["frame-types", "ingress-filtering", "mvrp"]) {
const changed = snapshot("bridge", [{ ...bridge, [field]: field === "frame-types" ? "admit-only-vlan-tagged" : "false" === bridge[field as keyof typeof bridge] ? "true" : "false" }])
assert.notEqual(changed.fingerprint, original.fingerprint)
}
assert.equal(snapshot("bridge", [{ ...bridge, running: "false" }]).fingerprint, original.fingerprint)
assert.equal(resourceById("bridge").fields.safeParse({ mvrp: true }).success, false)
})
@@ -0,0 +1,135 @@
import { bridgeVlanStateSchema, type BridgeVlanDesired, type BridgeVlanState } from "@mmapp/contracts/bridge-vlan"
import { bridgeVlanCurrentDesired } from "../../services/bridge-vlan-configuration.js"
import type { ActionContext, ChangeEvidence } from "./action-types.js"
import { prepareBridgeVlanConfiguration, readBridgeVlanState } from "./bridge-vlan-actions.js"
import { acknowledgedCreateId, assertNoCallerCreateId, recoveryRosStepId } from "./native-create-identity.js"
import { readRosSnapshot, rosSnapshotVersion, type RosSnapshot, type RosStep } from "./resources.js"
import { verifyRosStepSnapshots } from "./ros-step-verification.js"
import { decryptSecret, fingerprint, McpError } from "./security.js"
type Checkpoint = { step_index: number; before_sealed: string; after_sealed: string | null }
type Intended = { step_index: number; state: string; result: unknown }
const key = (snapshot: Pick<RosSnapshot, "serverId" | "resource">) => `${snapshot.serverId}:${snapshot.resource}`
function conflict(message: string): never { throw new McpError("STATE_CONFLICT", message, 409) }
export function needsBridgeVlanRecovery(sourceAction: string, evidence: ChangeEvidence): boolean {
if (sourceAction === "network.bridge-vlan.configure") return true
return evidence.steps.some(change => {
if (change.kind !== "ros") return false
const step = change.step
if (step.resource === "bridge") return step.action === "update" && Object.keys(step.fields).some(field => ["pvid", "vlan-filtering", "frame-types", "ingress-filtering"].includes(field))
const sensitive = step.resource === "bridge_port" ? ["bridge", "interface", "pvid", "ingress-filtering", "frame-types", "disabled"]
: step.resource === "bridge_vlan" ? ["bridge", "vlan-ids", "tagged", "untagged", "disabled"] : []
return sensitive.length > 0 && (step.action !== "update" || Object.keys(step.fields).some(field => sensitive.includes(field)))
})
}
function validSnapshot(snapshot: RosSnapshot): boolean {
return snapshot.projectionVersion === rosSnapshotVersion(snapshot.resource) && !!snapshot.sourceProof && Array.isArray(snapshot.rows) && snapshot.fingerprint === fingerprint(snapshot.rows)
}
function sameSnapshot(left: RosSnapshot, right: RosSnapshot): boolean {
return validSnapshot(left) && validSnapshot(right) && key(left) === key(right) && left.fingerprint === right.fingerprint && left.sourceProof === right.sourceProof
}
function stateFromSnapshots(serverId: number, snapshots: Map<string, RosSnapshot>): BridgeVlanState {
const rows = (resource: string) => {
const snapshot = snapshots.get(key({ serverId, resource }))
if (!snapshot || !validSnapshot(snapshot)) conflict("Нет полного исходного снимка bridge VLAN с актуальной проекцией")
return snapshot.rows
}
return bridgeVlanStateSchema.parse({ bridges: rows("bridge"), ports: rows("bridge_port"), vlans: rows("bridge_vlan"),
vlanInterfaces: rows("vlan"), ipv4Addresses: rows("ipv4_address"), ipv6Addresses: rows("ipv6_address"),
interfaces: ["ethernet", "bridge", "vlan", "gre", "wireguard", "vxlan"].flatMap(resource => rows(resource).map(row => ({ resource, id: String(row[".id"]), name: String(row.name), disabled: row.disabled }))),
})
}
/** Fresh typed inverse of a completely verified transition. Deleted port/VLAN
* rows are recreated without their old IDs; new rows are removed only by ACK. */
export async function prepareBridgeVlanRecovery(input: {
operationId: string; evidence: ChangeEvidence; checkpoints: Checkpoint[]; intended: Intended[];
}, context: ActionContext): Promise<ChangeEvidence> {
const { operationId, evidence, checkpoints, intended } = input
if (!evidence.steps.length || evidence.steps.some(change => change.kind !== "ros" || !["bridge", "bridge_port", "bridge_vlan"].includes(change.step.resource))) {
throw new McpError("UNSUPPORTED_CAPABILITY", "Обратный VLAN план не поддерживает смешанные ресурсы", 409)
}
const native = evidence.steps.map(change => (change as { kind: "ros"; step: RosStep }).step)
if (native.some(step => step.resource === "bridge" && step.action !== "update")) {
throw new McpError("UNSUPPORTED_CAPABILITY", "Создание или удаление самого bridge не поддерживает типизированный обратный VLAN план", 409)
}
const serverIds = [...new Set(native.map(step => step.serverId))]
if (serverIds.length !== 1 || evidence.target.scope !== "servers" || evidence.target.serverIds.length !== 1 || evidence.target.serverIds[0] !== serverIds[0]) conflict("Нет однозначного сервера исходного VLAN плана")
const serverId = serverIds[0]
if (!context.connection.policy.scope.serverIds.includes(serverId)) throw new McpError("SERVER_DENIED", "VLAN сервер вне текущего допуска")
if (intended.length !== native.length || checkpoints.length !== native.length || new Set(intended.map(item => item.step_index)).size !== native.length || new Set(checkpoints.map(item => item.step_index)).size !== native.length) conflict("Нет полного набора подтверждённых шагов VLAN")
const baseline = new Map<string, RosSnapshot>()
for (const snapshot of evidence.snapshots) {
if (snapshot.serverId !== serverId || !validSnapshot(snapshot) || baseline.has(key(snapshot))) conflict("Исходные VLAN снимки или их версии не подтверждены")
baseline.set(key(snapshot), snapshot)
}
const baselineState = stateFromSnapshots(serverId, baseline), expected = new Map(baseline)
const created: Array<{ resource: "bridge_port" | "bridge_vlan"; id: string }> = []
const deleted: Array<{ resource: "bridge_port" | "bridge_vlan"; id: string }> = []
for (let index = 0; index < native.length; index++) {
const step = native[index], checkpoint = checkpoints.find(item => item.step_index === index), receipt = intended.find(item => item.step_index === index)
assertNoCallerCreateId(step)
if (!checkpoint?.before_sealed || !checkpoint.after_sealed || receipt?.state !== "verified") conflict("Нет полного проверенного checkpoint VLAN; требуется ручная сверка")
const before = JSON.parse(await decryptSecret(checkpoint.before_sealed)) as RosSnapshot
const after = JSON.parse(await decryptSecret(checkpoint.after_sealed)) as RosSnapshot
const previous = expected.get(key({ serverId, resource: step.resource }))
if (!previous || !sameSnapshot(previous, before) || !validSnapshot(after) || before.sourceProof !== after.sourceProof || !verifyRosStepSnapshots(step, receipt.result, before, after)) conflict("Исходный переход VLAN или источник не подтверждён")
if (step.action === "create") {
const ack = acknowledgedCreateId(receipt.result), actual = recoveryRosStepId(step, before.rows, after.rows)
if (!ack || actual !== ack || !["bridge_port", "bridge_vlan"].includes(step.resource)) conflict("Нет точного ACK и checkpoint ID созданного VLAN объекта")
created.push({ resource: step.resource as "bridge_port" | "bridge_vlan", id: ack })
} else if (step.action === "delete") {
if (!step.id || !["bridge_port", "bridge_vlan"].includes(step.resource)) conflict("Не подтверждён ID удалённого VLAN объекта")
deleted.push({ resource: step.resource as "bridge_port" | "bridge_vlan", id: step.id })
}
expected.set(key(after), after)
}
const bridgeNames = new Set(native.map(step => {
const rows = step.resource === "bridge" ? baselineState.bridges : step.resource === "bridge_port" ? baselineState.ports : baselineState.vlans
const row = rows.find(item => item[".id"] === step.id)
const name = step.resource === "bridge" ? row?.name : step.fields.bridge ?? row?.bridge
if (typeof name !== "string" || !name) conflict("Не подтверждён исходный bridge VLAN")
return name
}))
const bridges = baselineState.bridges.filter(row => bridgeNames.has(String(row.name)))
if (bridgeNames.size !== 1 || bridges.length !== 1) conflict("Обратный VLAN план требует один однозначный bridge")
const bridgeId = String(bridges[0][".id"]), desired: BridgeVlanDesired = bridgeVlanCurrentDesired(baselineState, bridgeId)
for (const item of deleted) {
const terminal = expected.get(key({ serverId, resource: item.resource }))
const original = item.resource === "bridge_port" ? desired.ports.find(row => row.id === item.id) : desired.vlans.find(row => row.id === item.id)
if (!original || !terminal || terminal.rows.some(row => row[".id"] === item.id)) conflict("Нет подтверждённого удаления исходной VLAN identity")
delete original.id
}
for (const item of created) {
const originalRows = baseline.get(key({ serverId, resource: item.resource }))!.rows
const terminalRows = expected.get(key({ serverId, resource: item.resource }))!.rows
if (originalRows.some(row => row[".id"] === item.id) || !terminalRows.some(row => row[".id"] === item.id)) conflict("ACK ID VLAN не является подтверждённым новым объектом")
if (item.resource === "bridge_port") desired.removePortIds.push(item.id)
else desired.removeVlanIds.push(item.id)
}
const compare = async (snapshots: RosSnapshot[]): Promise<RosSnapshot[]> => {
const captured = new Map(snapshots.map(snapshot => [key(snapshot), snapshot]))
for (const snapshot of snapshots) {
const terminal = expected.get(key(snapshot))
if (!terminal || !sameSnapshot(terminal, snapshot)) conflict("После операции изменились VLAN конфигурация, зависимости или источник; обратный план запрещён")
}
for (const [resourceKey, terminal] of expected) {
const current = captured.get(resourceKey) ?? await readRosSnapshot(serverId, terminal.resource, undefined, terminal.sourceProof)
if (!sameSnapshot(terminal, current)) conflict("После операции обнаружен drift зависимости VLAN; обратный план запрещён")
captured.set(resourceKey, current)
}
return [...captured.values()]
}
await compare((await readBridgeVlanState(serverId, context)).snapshots)
// Reconstruct through the same model, with a freshly verified management
// channel. Old receipts never confer authority to run the inverse.
const inverse = await prepareBridgeVlanConfiguration({ serverId, bridgeId, desired }, context)
const snapshots = await compare(inverse.snapshots)
const objects = new Map([...evidence.objects, ...inverse.objects].map(object => [`${object.serverId}/${object.kind}/${object.id}`, object]))
return { ...inverse, snapshots, objects: [...objects.values()], requiresHuman: true,
warnings: [`Типизированный обратный VLAN план операции ${operationId}; все исходные шаги и ACK проверены.`, ...inverse.warnings,
"Удалённые port/VLAN rows создаются с новыми ID RouterOS. Unknown операции не повторяются; восстановление самого bridge не поддерживается."],
}
}
+25 -1
View File
@@ -2954,17 +2954,41 @@ try {
await (await import("../../test/mcp-host-files.js")).verifyMcpHostFiles(actor,app)
const readinessAccess = await createMcpConnection(mcpConnectionCreateSchema.parse({ ...input, name: "Actual readiness handshake", scope: { ...input.scope, operationIds: ["servers.list"] } }), actor)
const readinessHeaders = { authorization: "Bearer " + jwt }
const simulatorHeaders = { authorization: "Bearer " + await new SignJWT({ sub: "policy-preview-admin", apps: ["mm"], permissions: ["mm:mcp:admin"] })
.setProtectedHeader({ alg: "HS256" }).setIssuer(env.authIssuer).setExpirationTime("1h").sign(new TextEncoder().encode(env.jwtSecret)) }
const policyPreview = (payload: Record<string, unknown>) => app!.inject({ method: "POST", url: "/api/mcp/policy/preview", headers: simulatorHeaders, payload })
const simulatedServerRead = { connectionId: readinessAccess.connection.id, operationId: "servers.list", target: { scope: "servers", serverIds: [1] } }
const simulation = await policyPreview(simulatedServerRead)
assert.equal(simulation.statusCode, 200, simulation.body)
assert.equal(simulation.json().result.decision, "allowed", "an administrator simulates the stored owner's rights, not the administrator's rights")
assert.equal(simulation.json().executionAvailable, false)
assert.equal((await policyPreview({ ...simulatedServerRead, ownerPermissions: ["mm:settings:admin"] })).statusCode, 400)
const ready = await app.inject({ method: "POST", url: `/api/mcp/connections/${readinessAccess.connection.id}/check`, headers: readinessHeaders, payload: {} })
assert.equal(ready.statusCode, 200, ready.body)
assert.equal(ready.json().ok, true, ready.body); assert.equal(ready.json().checks.protocolHandshake, true)
assert.equal(ready.json().protocolProbe.status, "passed"); assert.equal(ready.json().protocolProbe.clientCredentialsVerified, false)
assert.equal(ready.json().protocolProbe.capabilitiesRead, "skipped")
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_credentials WHERE connection_id=$1 AND client_id='mcp-readiness-probe'", [readinessAccess.connection.id])).rows[0].n, 0)
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_grants WHERE connection_id=$1", [readinessAccess.connection.id])).rows[0].n, 0)
const duplicateReady = await app.inject({ method: "POST", url: `/api/mcp/connections/${readinessAccess.connection.id}/check`, headers: readinessHeaders, payload: {} })
assert.equal(duplicateReady.statusCode, 429)
await setConnectionStatus(readinessAccess.connection.id, "paused", actor)
const pausedSimulation = await policyPreview(simulatedServerRead)
assert.equal(pausedSimulation.statusCode, 200, pausedSimulation.body)
assert.equal(pausedSimulation.json().result.decision, "denied")
assert.ok(pausedSimulation.json().result.reasons.some((reason: { code: string }) => reason.code === "CONNECTION_INACTIVE"))
const pausedReady = await app.inject({ method: "POST", url: `/api/mcp/connections/${readinessAccess.connection.id}/check`, headers: readinessHeaders, payload: {} })
assert.equal(pausedReady.statusCode, 200); assert.equal(pausedReady.json().protocolProbe.status, "skipped")
const readableAccess = await createMcpConnection(mcpConnectionCreateSchema.parse({ ...input, name: "Actual readiness capability read", scope: { ...input.scope, operationIds: ["servers.list", "capabilities.read"] } }), actor)
const readable = await app.inject({ method: "POST", url: `/api/mcp/connections/${readableAccess.connection.id}/check`, headers: readinessHeaders, payload: {} })
assert.equal(readable.statusCode, 200, readable.body)
assert.equal(readable.json().ok, true, readable.body)
assert.equal(readable.json().protocolProbe.capabilitiesRead, "passed")
assert.equal(readable.json().protocolProbe.credentialType, "temporary-capabilities-read")
const readinessReads = (await pool.query("SELECT tool FROM mcp_requests WHERE connection_id=$1 AND tool NOT LIKE 'protocol:%'", [readableAccess.connection.id])).rows
assert.deepEqual(readinessReads.map(row => row.tool), ["mm_capabilities_get"])
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_credentials WHERE connection_id=$1 AND client_id='mcp-readiness-probe'", [readableAccess.connection.id])).rows[0].n, 0)
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_grants WHERE connection_id=$1", [readableAccess.connection.id])).rows[0].n, 0)
const emptyGrantAccess = await createMcpConnection(mcpConnectionCreateSchema.parse({ ...input, name: "Readiness has no operation authority" }), actor)
const { withMcpProbeCredential } = await import("./readiness.js")
let endedProbeToken = ""
@@ -2980,7 +3004,7 @@ try {
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_grants WHERE connection_id=$1", [emptyGrantAccess.connection.id])).rows[0].n, 0)
const readinessAudit = (await pool.query("SELECT payload FROM mcp_audit WHERE connection_id=$1", [emptyGrantAccess.connection.id])).rows
assert.ok(!JSON.stringify(readinessAudit).includes(endedProbeToken))
console.log("✓ Actual readiness initialize/tools-list over public HTTP: temporary empty grant, no tool authority, cleanup on success/error, cooldown and paused precheck skip")
console.log("✓ Actual readiness initialize/tools-list and optional capabilities read over public HTTP: narrow grant, cleanup on success/error, cooldown and paused precheck skip")
const deviceConnection = await createMcpConnection(mcpConnectionCreateSchema.parse({ ...input, name: "Web interfaces", scope: { ...input.scope, operationIds: ["ros.bridge.list", "ros.bridge.create"] } }), actor)
const deviceHeaders = { authorization: "Bearer " + jwt }
const deviceCatalog = await app.inject({ url: "/api/mcp/devices/catalog?connectionId=" + deviceConnection.connection.id, headers: deviceHeaders })
@@ -1,4 +1,5 @@
import assert from "node:assert/strict"
import { randomUUID } from "node:crypto"
import type { IncomingMessage, ServerResponse } from "node:http"
import { setTimeout as delay } from "node:timers/promises"
import type { FastifyInstance } from "fastify"
@@ -12,7 +13,7 @@ export async function verifyLogsFollowSdkCancellation(app: FastifyInstance, endp
const access = await createMcpConnection(mcpConnectionCreateSchema.parse({
name: "Logs follow SDK cancellation", mode: "approval", permissions: ["mm:servers:read"],
expiresAt: new Date(Math.min(actor.expiresAt ?? Infinity, Date.now() + 600_000)).toISOString(),
scope: { serverIds: [1], operationIds: ["logs.follow"], allowGlobal: false },
scope: { serverIds: [1], operationIds: ["logs.follow", "logs.query"], allowGlobal: false },
}), actor)
const client = new Client({ name: "logs-follow-sdk-cancellation", version: "1.0.0" }, {
versionNegotiation: { mode: { pin: "2026-07-28" } },
@@ -76,6 +77,63 @@ export async function verifyLogsFollowSdkCancellation(app: FastifyInstance, endp
release()
await refused.catch(() => undefined)
}
pool.query = originalQuery
const from = "2000-01-01T00:00:00Z", to = "2000-01-01T00:30:00Z"
const followOnce = (filters: { from?: string; cursor?: string }) => client.callTool({
name: "mm_logs_follow", arguments: { serverId: 1, waitSeconds: 0, to, ...filters },
})
const initial = await followOnce({ from })
assert.ok(!initial.isError)
const cursor = (initial.structuredContent as { result?: { cursor?: unknown } } | undefined)?.result?.cursor
assert.ok(typeof cursor === "string" && cursor.length > 0)
assert.ok(!(await followOnce({ from, cursor })).isError)
assert.ok(!(await followOnce({ cursor })).isError, "omitting from must resume the historical cursor's period")
const changed = await followOnce({ from: "2000-01-01T00:01:00Z", cursor })
assert.equal(changed.isError, true)
assert.match(JSON.stringify(changed), /RESET_REQUIRED/)
assert.doesNotMatch(JSON.stringify(changed), /"cursor"/)
console.log("✓ MCP logs follow: historical cursor resumes, changed from requires reset")
const marker = `mcp-logs-cursor-${randomUUID()}`
const readFollowPage = async (options: { cursor?: string; limit?: number }) => {
const result = await client.callTool({ name: "mm_logs_follow", arguments: { serverId: 1, from, to, q: marker, waitSeconds: 0, ...options } })
assert.ok(!result.isError)
return (result.structuredContent as { result: { entries: { id: string }[]; cursor: string } }).result
}
const start = await readFollowPage({})
assert.deepEqual(start.entries, [])
try {
await pool.query(`INSERT INTO router_log_entries(server_id,server_name,host,router_id,raw_time,received_at,effective_at,topics,level,message,generation)
SELECT 1,'cursor fixture','127.0.0.1','fixture','00:02:00',now(),$1::timestamptz+n*interval '2 minutes',ARRAY['system'],'info',$2,0
FROM generate_series(1,2) AS n`, [from, marker])
const defaultFollow = await readFollowPage({ cursor: start.cursor })
assert.equal(defaultFollow.entries.length, 2)
const firstFollow = await readFollowPage({ cursor: start.cursor, limit: 1 })
const secondFollow = await readFollowPage({ cursor: firstFollow.cursor, limit: 1 })
assert.equal(firstFollow.entries.length, 1)
assert.equal(secondFollow.entries.length, 1)
assert.deepEqual([...firstFollow.entries, ...secondFollow.entries].map(row => row.id), defaultFollow.entries.map(row => row.id))
assert.deepEqual((await readFollowPage({ cursor: secondFollow.cursor, limit: 1 })).entries, [])
console.log("✓ MCP logs follow: requested batch limit and lossless cursor progression")
const query = (filters: { from?: string; cursor?: string }) => client.callTool({
name: "mm_logs_query", arguments: { serverId: 1, q: marker, limit: 1, to, ...filters },
})
type Page = { entries: { id: string }[]; nextCursor: string | null }
const first = await query({ from })
assert.ok(!first.isError)
const firstPage = (first.structuredContent as { result: Page }).result
assert.equal(firstPage.entries.length, 1)
assert.ok(firstPage.nextCursor)
const next = await query({ cursor: firstPage.nextCursor })
assert.ok(!next.isError)
const nextPage = (next.structuredContent as { result: Page }).result
assert.equal(nextPage.entries.length, 1)
assert.notEqual(nextPage.entries[0].id, firstPage.entries[0].id)
assert.equal(nextPage.nextCursor, null)
console.log("✓ MCP logs query: historical pagination resumes without resending from")
} finally {
await pool.query("DELETE FROM router_log_entries WHERE server_id=1 AND message=$1", [marker])
}
} finally {
bound.abort()
pool.query = originalQuery
+12 -2
View File
@@ -41,7 +41,7 @@ export async function registerManagementChannel(raw: unknown, actor: AuthUser) {
})
return { id, serverId: input.serverId, expiresAt: input.expiresAt, verification: "identity-and-reachability", independence: "human-attestation" }
}
export async function verifyManagementChannel(serverId: number, requiredId?: string) {
async function verifiedManagementChannel(serverId: number, requiredId?: string) {
const { rows: [row] } = await pool.query("SELECT * FROM mcp_management_channels WHERE server_id=$1 AND revoked_at IS NULL AND expires_at>now()", [serverId])
if (!row || requiredId && row.id !== requiredId || row.generation !== await accessGeneration()) throw new McpError("APPROVAL_REQUIRED", "Нет актуального проверенного независимого канала управления", 409)
const config = JSON.parse(await decryptSecret(row.config_sealed)) as MikrotikConnectParams
@@ -50,7 +50,17 @@ export async function verifyManagementChannel(serverId: number, requiredId?: str
if (hashes.some(value => value !== row.identity_hash)) throw new McpError("STATE_CONFLICT", "Идентичность основного или management-канала изменилась", 409)
const changed = await pool.query("UPDATE mcp_management_channels SET verified_at=now() WHERE id=$1 AND revoked_at IS NULL AND expires_at>now() RETURNING id", [row.id])
if (!changed.rowCount) throw new McpError("APPROVAL_REQUIRED", "Допуск management-канала был отозван во время проверки", 409)
return { channelId: row.id as string, serverId, expiresAt: row.expires_at.toISOString() as string }
return { channelId: row.id as string, serverId, expiresAt: row.expires_at.toISOString() as string, host: config.host }
}
export async function verifyManagementChannel(serverId: number, requiredId?: string) {
const { host: _host, ...receipt } = await verifiedManagementChannel(serverId, requiredId)
return receipt
}
/** Internal VLAN preparation uses the verified endpoint to trace its actual
* address/interface. It is not accepted from tool input or returned in the
* public channel receipt. */
export async function verifyBridgeManagementChannel(serverId: number, requiredId?: string) {
return verifiedManagementChannel(serverId, requiredId)
}
export async function managementEvidence(serverIds: number[]) {
try { return { requiresHuman: false, managementChannels: await Promise.all([...new Set(serverIds)].map(serverId => verifyManagementChannel(serverId))) } }
@@ -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, ["ospf_template", "ipsec_peer"].includes(resource.id) ? 5 : ["wireguard", "vrf"].includes(resource.id) ? 4 : 3)
assert.equal(action.operation.version, ["ospf_template", "ipsec_peer", "vrf"].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 })
@@ -38,7 +38,7 @@ assert.throws(() => action.schema.parse({ serverId: 1, expectedServerProof: "for
assert.throws(() => action.schema.parse({ serverId: 1, version: 1 }))
assert.equal(action.schema.parse({ serverId: 1 }).family, "ipv4")
assert.equal(findAction("mm_routing_measurement_plan").operation.version, 2)
assert.equal(findAction("mm_operation_recovery_plan").operation.version, 7)
assert.equal(findAction("mm_operation_recovery_plan").operation.version, 8)
assert.equal(findAction("mm_ospf_template_create_plan").operation.version, 5)
assert.equal(findAction("mm_ospf_template_update_plan").operation.version, 4)
assert.equal(findAction("mm_ospf_template_delete_plan").operation.version, 3)
@@ -49,11 +49,11 @@ assert.equal(findAction("mm_wireguard_update_plan").operation.version, 3)
assert.equal(findAction("mm_wireguard_interface_edit_plan").operation.version, 3)
assert.equal(findAction("mm_wireguard_interface_create_plan").operation.version, 3)
assert.equal(findAction("mm_wireguard_create_plan").operation.version, 4)
assert.equal(findAction("mm_interfaces_update_plan").operation.version, 4)
assert.equal(findAction("mm_interfaces_update_plan").operation.version, 5)
assert.equal(findAction("mm_ipsec_peer_delete_plan").operation.version, 3)
assert.equal(findAction("mm_ipsec_peer_update_plan").operation.version, 3)
assert.equal(findAction("mm_certificate_delete_plan").operation.version, 3)
for (const [tool, version] of [["mm_route_optimizer_plan", 7], ["mm_route_profile_save_plan", 4], ["mm_route_path_verify", 2], ["mm_operation_recovery_plan", 7], ["mm_ecmp_plan", 2], ["mm_rpf_plan", 2], ["mm_vrf_plan", 3], ["mm_firewall_rule_update_plan", 2]] as const) {
for (const [tool, version] of [["mm_route_optimizer_plan", 7], ["mm_route_profile_save_plan", 4], ["mm_route_path_verify", 2], ["mm_operation_recovery_plan", 8], ["mm_ecmp_plan", 2], ["mm_rpf_plan", 2], ["mm_vrf_plan", 4], ["mm_firewall_rule_update_plan", 2]] as const) {
const routed = findAction(tool)
assert.equal(routed.operation.version, version)
assert.equal(findMcpOperation(routed.operation.id)?.version, version)
@@ -2,7 +2,7 @@ import assert from "node:assert/strict"
import { createOspfOwnerSourceGuard, verifyOspfOwnerGraph, verifyOspfOwnerGraphAtPhase } from "./ospf-owner-graph.js"
import { fingerprint, McpError, redact } from "./security.js"
import { createRosPrefix } from "./ros-prefix.js"
import { ROS_SNAPSHOT_VERSION, type RosSnapshot } from "./resources.js"
import { rosSnapshotVersion, type RosSnapshot } from "./resources.js"
const ids = [1, 2, 3]
const graph = { family: "ipv4" as const, sourceSecretProofs: ids.map(serverId => ({ serverId, proof: fingerprint({ serverId }) })), instances: ids.map(serverId => ({ serverId, fingerprint: fingerprint({ serverId, native: "instances" }) })) }
@@ -54,7 +54,7 @@ const catalogAuthorize = async () => {
await sourceGuard()
}
const catalogRows = [{ ".id": "*A", name: "keep", disabled: "false" }]
const catalog: RosSnapshot = { serverId: 1, resource: "bridge", rows: catalogRows, fingerprint: fingerprint(catalogRows), projectionVersion: ROS_SNAPSHOT_VERSION, sourceProof: "a".repeat(64) }
const catalog: RosSnapshot = { serverId: 1, resource: "bridge", rows: catalogRows, fingerprint: fingerprint(catalogRows), projectionVersion: rosSnapshotVersion("bridge"), sourceProof: "a".repeat(64) }
reads = []
const catalogPrefix = createRosPrefix([catalog], async (_id, _resource, beforeRead = async () => {}) => {
// Match readRosSnapshot's normal three grant/source fences without polling a
+47 -1
View File
@@ -21,7 +21,7 @@ test("failed/malformed/redirected and stalled protocol probes are bounded and ne
try {
for (const state of ["malformed", "redirect", "large", "announced", "stalled"]) {
mode = state
const started = performance.now(), result = await runMcpProtocolProbe(endpoint, "private-readiness-fixture", 300)
const started = performance.now(), result = await runMcpProtocolProbe(endpoint, "private-readiness-fixture", { timeoutMs: 300 })
assert.equal(result.status, "failed", state)
assert.ok(performance.now() - started < 3000, state)
assert.ok(!JSON.stringify(result).includes("private-readiness-fixture"))
@@ -29,3 +29,49 @@ test("failed/malformed/redirected and stalled protocol probes are bounded and ne
assert.equal(forwarded, 0); assert.ok(requests >= 5)
} finally { server.closeAllConnections(); await new Promise<void>(resolve => server.close(() => resolve())) }
})
test("capabilities readiness refuses widened scope and checks the tool result", async () => {
const capability = { id: "capabilities.read", toolName: "mm_capabilities_get" }
const tool = { name: capability.toolName, inputSchema: { type: "object" } }
let mode = "extra-tool", calls = 0
const server = createServer(async (req, res) => {
if (req.method !== "POST") { res.writeHead(405).end(); return }
const chunks: Buffer[] = []
for await (const chunk of req) chunks.push(chunk)
const { id, method, params } = JSON.parse(Buffer.concat(chunks).toString())
if (id === undefined) { res.writeHead(202).end(); return }
let result: unknown
if (method === "initialize") result = { protocolVersion: params.protocolVersion, capabilities: { tools: {} }, serverInfo: { name: "fixture", version: "1.0.0" } }
if (method === "tools/list") result = { tools: mode === "extra-tool" ? [tool, { ...tool, name: "mm_servers_list" }] : [tool] }
if (method === "tools/call") {
calls++
assert.equal(params.name, capability.toolName)
if (mode === "timeout") { res.writeHead(200, { "content-type": "application/json" }).write("{"); return }
const operations = mode === "extra-operation" ? [capability, { id: "servers.list" }] : [capability]
result = { content: [], isError: mode === "tool-error", structuredContent: { result: { schemaVersion: 1, operations } } }
}
res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ jsonrpc: "2.0", id, result }))
})
await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve))
const endpoint = new URL(`http://127.0.0.1:${(server.address() as { port: number }).port}/mcp`)
const probe = () => runMcpProtocolProbe(endpoint, "private-readiness-fixture", { timeoutMs: 400, readCapabilities: true })
try {
const widened = await probe()
assert.equal(widened.reason, "SCOPE_NOT_ENFORCED")
assert.equal(widened.capabilitiesRead, "skipped")
assert.equal(calls, 0)
for (const state of ["tool-error", "extra-operation", "timeout"]) {
mode = state
const result = await probe()
assert.equal(result.status, "failed", state)
assert.equal(result.capabilitiesRead, "failed", state)
assert.equal(result.reason, state === "timeout" ? "TIMEOUT" : "CAPABILITIES_READ_FAILED", state)
}
mode = "valid"
const valid = await probe()
assert.equal(valid.status, "passed")
assert.equal(valid.capabilitiesRead, "passed")
assert.equal(valid.clientCredentialsVerified, false)
assert.equal(calls, 4)
} finally { server.closeAllConnections(); await new Promise<void>(resolve => server.close(() => resolve())) }
})
+28 -12
View File
@@ -9,15 +9,19 @@ export interface ProtocolProbe {
status: "passed" | "failed" | "skipped";
elapsedMs: number;
reason?: string;
credentialType: "temporary-no-operations";
credentialType: "temporary-no-operations" | "temporary-capabilities-read";
capabilitiesRead: "passed" | "failed" | "skipped";
clientCredentialsVerified: false;
}
/** A temporary access credential may negotiate metadata, but its empty grant
* permits no tools. The ordinary connection credentials are never recovered. */
export async function withMcpProbeCredential<T>(connectionId: string, actor: AuthUser, work: (token: string) => Promise<T>): Promise<T> {
const capabilitiesOperation = "capabilities.read"
const capabilitiesTool = "mm_capabilities_get"
/** The probe may read its own narrowed capabilities when the connection grants
* that operation. The ordinary connection credentials are never recovered. */
export async function withMcpProbeCredential<T>(connectionId: string, actor: AuthUser, work: (token: string, readCapabilities: boolean) => Promise<T>): Promise<T> {
const credentialId = randomUUID(), grantId = randomUUID(), token = randomToken("access")
await transaction(async client => {
const readCapabilities = await transaction(async client => {
await client.query("SELECT id FROM mcp_connections WHERE id=$1 FOR UPDATE", [connectionId])
const connection = await getConnection(connectionId, client)
assertConnectionVisible(connection, actor)
@@ -27,14 +31,16 @@ export async function withMcpProbeCredential<T>(connectionId: string, actor: Aut
const expired = (await client.query("DELETE FROM mcp_credentials WHERE connection_id=$1 AND client_id='mcp-readiness-probe' AND expires_at<=now() RETURNING id", [connectionId])).rows.map(row => row.id)
if (expired.length) await client.query("DELETE FROM mcp_grants WHERE connection_id=$1 AND payload->>'credentialId'=ANY($2::text[])", [connectionId, expired])
const expiresAt = new Date(Math.min(Date.now() + 20000, Date.parse(connection.policy.expiresAt), connection.owner_valid_until.getTime())).toISOString()
const grant = mcpTemporaryGrantSchema.parse({ id: grantId, startsAt: new Date(Date.now() - 1000).toISOString(), expiresAt, scope: { serverIds: [], operationIds: [], allowGlobal: false } })
const allowed = connection.policy.scope.operationIds.includes(capabilitiesOperation)
const grant = mcpTemporaryGrantSchema.parse({ id: grantId, startsAt: new Date(Date.now() - 1000).toISOString(), expiresAt, scope: { serverIds: [], operationIds: allowed ? [capabilitiesOperation] : [], allowGlobal: false } })
await client.query("INSERT INTO mcp_credentials(id,connection_id,digest,kind,expires_at,audience,client_id) VALUES($1,$2,$3,'access',$4,$5,'mcp-readiness-probe')", [credentialId, connectionId, tokenDigest(token), expiresAt, canonicalMcpUrl().href])
await client.query("INSERT INTO mcp_grants(id,connection_id,payload) VALUES($1,$2,$3::jsonb)", [grantId, connectionId, JSON.stringify({ ...grant, credentialId })])
await validatePrincipal({ connectionId, credentialId, credentialExpiresAt: expiresAt }, client)
await audit(client, actor.id, "connection.handshake.start", connectionId, { credentialId, expiresAt })
return allowed
})
let completed = false
try { const result = await work(token); completed = true; return result }
try { const result = await work(token, readCapabilities); completed = true; return result }
finally {
await transaction(async client => {
await client.query("DELETE FROM mcp_grants WHERE id=$1 AND connection_id=$2", [grantId, connectionId])
@@ -45,11 +51,12 @@ export async function withMcpProbeCredential<T>(connectionId: string, actor: Aut
}
/** One deadline covers negotiation, metadata and HTTP response bodies. */
export async function runMcpProtocolProbe(endpoint: URL, token: string, timeoutMs = 8000): Promise<ProtocolProbe> {
export async function runMcpProtocolProbe(endpoint: URL, token: string, { timeoutMs = 8000, readCapabilities = false } = {}): Promise<ProtocolProbe> {
const started = performance.now(), controller = new AbortController()
const timer = setTimeout(() => controller.abort(), timeoutMs)
const client = new Client({ name: "MikrotikManager readiness", version: "1.0.0" })
const result = (status: ProtocolProbe["status"], reason?: string): ProtocolProbe => ({ status, reason, elapsedMs: Math.round(performance.now() - started), credentialType: "temporary-no-operations", clientCredentialsVerified: false })
let capabilitiesRead: ProtocolProbe["capabilitiesRead"] = "skipped"
const result = (status: ProtocolProbe["status"], reason?: string): ProtocolProbe => ({ status, reason, elapsedMs: Math.round(performance.now() - started), credentialType: readCapabilities ? "temporary-capabilities-read" : "temporary-no-operations", capabilitiesRead, clientCredentialsVerified: false })
try {
const transport = new StreamableHTTPClientTransport(endpoint, { requestInit: { headers: { Authorization: `Bearer ${token}` }, redirect: "error" }, redirectPolicy: "follow",
fetch: async (url, init) => {
@@ -67,13 +74,22 @@ export async function runMcpProtocolProbe(endpoint: URL, token: string, timeoutM
} })
await client.connect(transport, { timeout: timeoutMs })
const tools = await client.listTools({}, { timeout: timeoutMs })
if (tools.tools.length !== 0 || tools.nextCursor) return result("failed", "SCOPE_NOT_ENFORCED")
const expectedTools = readCapabilities ? [capabilitiesTool] : []
if (tools.nextCursor || tools.tools.length !== expectedTools.length || tools.tools.some((tool, index) => tool.name !== expectedTools[index])) return result("failed", "SCOPE_NOT_ENFORCED")
if (readCapabilities) {
capabilitiesRead = "failed"
const call = await client.callTool({ name: capabilitiesTool, arguments: {} }, { timeout: timeoutMs })
const output = (call.structuredContent as { result?: { schemaVersion?: unknown; operations?: unknown } } | undefined)?.result
const operations = output?.operations
if (call.isError || output?.schemaVersion !== 1 || !Array.isArray(operations) || operations.length !== 1 || operations[0]?.id !== capabilitiesOperation || operations[0]?.toolName !== capabilitiesTool) return result("failed", "CAPABILITIES_READ_FAILED")
capabilitiesRead = "passed"
}
return result("passed")
} catch { return result("failed", controller.signal.aborted ? "TIMEOUT" : "TRANSPORT_FAILED") }
} catch { return result("failed", controller.signal.aborted ? "TIMEOUT" : capabilitiesRead === "failed" ? "CAPABILITIES_READ_FAILED" : "TRANSPORT_FAILED") }
finally { clearTimeout(timer); controller.abort(); await client.close().catch(() => {}) }
}
export async function checkMcpProtocol(connectionId: string, actor: AuthUser) {
const endpoint = canonicalMcpUrl()
return withMcpProbeCredential(connectionId, actor, token => runMcpProtocolProbe(endpoint, token))
return withMcpProbeCredential(connectionId, actor, (token, readCapabilities) => runMcpProtocolProbe(endpoint, token, { readCapabilities }))
}
+6 -4
View File
@@ -6,13 +6,14 @@ import { decryptSecret, fingerprint, McpError } from "./security.js"
import { effectiveMcpConnection } from "./store.js"
import { findMcpService } from "./service-registry.js"
import { findMcpOperation } from "./registry.js"
import { readRosSnapshot, resourceById, routerClient, validateRosStep, splitOspfPassiveUpdate, ROS_SNAPSHOT_VERSION, type RosSnapshot, type RosStep } from "./resources.js"
import { readRosSnapshot, resourceById, routerClient, validateRosStep, splitOspfPassiveUpdate, rosSnapshotVersion, type RosSnapshot, type RosStep } from "./resources.js"
import { verifyRosStepSnapshots } from "./ros-step-verification.js"
import type { add } from "./actions.js"
import type { ActionContext, ChangeEvidence, ChangeStep } from "./action-types.js"
import { loadScopedRecoverySource } from "./routing-community-scoped-recovery-source.js"
import { prepareScopedRecovery, registerScopedRecoveryService } from "./routing-community-scoped-recovery.js"
import { reconcileVrfProductionStep } from "../../services/vrf-production-execution.js"
import { needsBridgeVlanRecovery, prepareBridgeVlanRecovery } from "./bridge-vlan-recovery.js"
async function source(operationId: string, context: ActionContext, allowServices = false) {
const { rows: [row] } = await pool.query("SELECT o.*,p.operation_id AS source_action,p.operation_version AS source_version,p.evidence FROM mcp_operations o JOIN mcp_plans p ON p.id=o.plan_id WHERE o.id=$1 AND o.connection_id=$2", [operationId, context.connection.id])
@@ -86,7 +87,7 @@ export function registerRecoveryActions(register: typeof add) {
},
})
register("operations.recover", "mm_operation_recovery_plan", "Подготовить отдельный обратный план сетевой операции", "network", "mm:network:write", "write", "servers", z.object({ operationId: z.string().uuid() }).strict(), {
version: 7,
version: 8,
target: async (input, context) => {
const { evidence } = await source(String(input.operationId), context, true)
if (evidence.steps.some(step => step.kind === "ros" && step.step.resource === "vrf")) throw new McpError("UNSUPPORTED_CAPABILITY", "VRF не имеет проверенной обратной ревизии; используйте read-only сверку и отдельный approved план", 409)
@@ -106,6 +107,7 @@ export function registerRecoveryActions(register: typeof add) {
const checkpoints = (await pool.query("SELECT step_index,before_sealed,after_sealed FROM mcp_operation_checkpoints WHERE operation_id=$1 ORDER BY step_index DESC", [row.id])).rows
const intended = (await pool.query("SELECT step_index,state,result FROM mcp_operation_steps WHERE operation_id=$1 ORDER BY step_index DESC", [row.id])).rows
if (!intended.length || intended.some(step => step.state !== "verified") || intended.length !== checkpoints.length || checkpoints.some(checkpoint => !checkpoint.after_sealed)) throw new McpError("STATE_CONFLICT", "Нет полного набора подтверждённых снимков; требуется ручная сверка", 409)
if (needsBridgeVlanRecovery(row.source_action, evidence)) return prepareBridgeVlanRecovery({ operationId: row.id, evidence, checkpoints, intended }, context)
const snapshots = new Map<string, RosSnapshot>(), steps: ChangeStep[] = [], objects: ChangeEvidence["objects"] = [...evidence.objects]
for (const checkpoint of checkpoints) {
const original = evidence.steps[checkpoint.step_index]
@@ -113,7 +115,7 @@ export function registerRecoveryActions(register: typeof add) {
const step = original.step, resource = resourceById(step.resource)
if (!context.connection.policy.scope.serverIds.includes(step.serverId)) throw new McpError("SERVER_DENIED", "Зависимость вне допуска")
const before = JSON.parse(await decryptSecret(checkpoint.before_sealed)) as RosSnapshot, after = JSON.parse(await decryptSecret(checkpoint.after_sealed)) as RosSnapshot
if (before.projectionVersion !== ROS_SNAPSHOT_VERSION || after.projectionVersion !== ROS_SNAPSHOT_VERSION || !before.sourceProof || before.sourceProof !== after.sourceProof || before.fingerprint !== fingerprint(before.rows) || after.fingerprint !== fingerprint(after.rows) || !verifyRosStepSnapshots(step, intended.find(item => item.step_index === checkpoint.step_index)?.result, before, after)) throw new McpError("STATE_CONFLICT", "Исходный переход каталога или источник не подтверждён; обратный план запрещён", 409)
if (before.projectionVersion !== rosSnapshotVersion(step.resource) || after.projectionVersion !== rosSnapshotVersion(step.resource) || !before.sourceProof || before.sourceProof !== after.sourceProof || before.fingerprint !== fingerprint(before.rows) || after.fingerprint !== fingerprint(after.rows) || !verifyRosStepSnapshots(step, intended.find(item => item.step_index === checkpoint.step_index)?.result, before, after)) throw new McpError("STATE_CONFLICT", "Исходный переход каталога или источник не подтверждён; обратный план запрещён", 409)
const key = `${step.serverId}:${step.resource}`
if (!snapshots.has(key)) {
const current = await readRosSnapshot(step.serverId, step.resource, undefined, after.sourceProof)
@@ -143,7 +145,7 @@ export function registerRecoveryActions(register: typeof add) {
const key = `${dependency.serverId}:${dependency.resource}`
if (snapshots.has(key)) continue
const current = await readRosSnapshot(dependency.serverId, dependency.resource, undefined, dependency.sourceProof)
if (current.fingerprint !== dependency.fingerprint || current.sourceProof !== dependency.sourceProof || dependency.projectionVersion !== ROS_SNAPSHOT_VERSION) throw new McpError("STATE_CONFLICT", "Зависимость или источник исходного плана изменились", 409)
if (current.fingerprint !== dependency.fingerprint || current.sourceProof !== dependency.sourceProof || dependency.projectionVersion !== rosSnapshotVersion(dependency.resource)) throw new McpError("STATE_CONFLICT", "Зависимость или источник исходного плана изменились", 409)
snapshots.set(key, current)
}
objects.push(...[...new Set([...snapshots.values()].map(snapshot => snapshot.serverId))].map(serverId => ({ kind: "server", id: String(serverId), serverId })))
+22 -6
View File
@@ -5,14 +5,19 @@ import { eq } from "drizzle-orm"
import { db } from "../../db/index.js"
import { servers } from "../../db/schema.js"
import { MikrotikClient } from "../../services/mikrotik.js"
import { readRouterOsSnapshotGet } from "../../services/routeros-snapshot-read.js"
import { McpError, fingerprint, privateSecretFingerprint } from "./security.js"
import { readOspfEffectiveDisabled } from "../../services/ospf-effective-disabled.js"
import { greNativeFieldsSchema } from "../../services/gre-mutation-input.js"
import { canonicalVrfMembers } from "../../services/vrf-members.js"
import { canonicalBridgeVlanValue } from "../../services/bridge-vlan-values.js"
const text = z.string().max(1000)
const name = z.string().trim().min(1).max(100)
const bool = z.boolean()
const vlanIds = z.string().min(1).max(16384).refine(value => {
try { canonicalBridgeVlanValue("vlan-ids", value); return true } catch { return false }
}, "Требуется непересекающийся список VLAN ID/диапазонов 1..4094")
const integer = (min: number, max: number) => z.number().int().min(min).max(max)
const common = { name: name.optional(), comment: text.optional(), disabled: bool.optional() }
const ipv4 = name.refine(value => isIP(value) === 4, "Требуется IPv4 router/area ID")
@@ -31,13 +36,15 @@ const route = {
export interface RosResourceSpec {
id: string; path: string; title: string; permission: string; fields: z.ZodObject;
create: boolean; remove: boolean; requiredOnCreate?: string[]; readOnly?: boolean
/** Native configuration sealed for drift checks, never accepted as writes. */
observeFields?: readonly string[]
}
export const rosResources: RosResourceSpec[] = [
{ id: "routing_filter", path: "/routing/filter/rule", title: "Фильтры маршрутизации", permission: "mm:filters", fields: z.object({ chain: text.optional(), rule: text.optional(), comment: text.optional(), disabled: bool.optional() }).strict(), create: false, remove: false, readOnly: true },
{ id: "ethernet", path: "/interface/ethernet", title: "Ethernet", permission: "mm:network", fields: z.object({ ...common, mtu: integer(68, 65535).optional(), "auto-negotiation": bool.optional() }).strict(), create: false, remove: false },
{ id: "bridge", path: "/interface/bridge", title: "Bridge", permission: "mm:network", fields: z.object({ ...common, mtu: integer(68, 65535).optional(), "vlan-filtering": bool.optional(), pvid: integer(1, 4094).optional(), "protocol-mode": z.enum(["none", "stp", "rstp", "mstp"]).optional() }).strict(), create: true, remove: true, requiredOnCreate: ["name"] },
{ id: "bridge", path: "/interface/bridge", title: "Bridge", permission: "mm:network", fields: z.object({ ...common, mtu: integer(68, 65535).optional(), "vlan-filtering": bool.optional(), pvid: integer(1, 4094).optional(), "frame-types": z.enum(["admit-all", "admit-only-vlan-tagged", "admit-only-untagged-and-priority-tagged"]).optional(), "ingress-filtering": bool.optional(), "protocol-mode": z.enum(["none", "stp", "rstp", "mstp"]).optional() }).strict(), observeFields: ["mvrp"], create: true, remove: true, requiredOnCreate: ["name"] },
{ id: "bridge_port", path: "/interface/bridge/port", title: "Порты bridge", permission: "mm:network", fields: z.object({ bridge: name.optional(), interface: name.optional(), pvid: integer(1, 4094).optional(), "ingress-filtering": bool.optional(), "frame-types": z.enum(["admit-all", "admit-only-vlan-tagged", "admit-only-untagged-and-priority-tagged"]).optional(), disabled: bool.optional(), comment: text.optional() }).strict(), create: true, remove: true, requiredOnCreate: ["bridge", "interface"] },
{ id: "bridge_vlan", path: "/interface/bridge/vlan", title: "Bridge VLAN membership", permission: "mm:network", fields: z.object({ bridge: name.optional(), "vlan-ids": name.optional(), tagged: text.optional(), untagged: text.optional(), disabled: bool.optional(), comment: text.optional() }).strict(), create: true, remove: true, requiredOnCreate: ["bridge", "vlan-ids"] },
{ id: "bridge_vlan", path: "/interface/bridge/vlan", title: "Bridge VLAN membership", permission: "mm:network", fields: z.object({ bridge: name.optional(), "vlan-ids": vlanIds.optional(), tagged: text.optional(), untagged: text.optional(), disabled: bool.optional(), comment: text.optional() }).strict(), create: true, remove: true, requiredOnCreate: ["bridge", "vlan-ids"] },
{ id: "vlan", path: "/interface/vlan", title: "VLAN", permission: "mm:network", fields: z.object({ ...common, interface: name.optional(), "vlan-id": integer(1, 4094).optional(), mtu: integer(68, 65535).optional(), "use-service-tag": bool.optional() }).strict(), create: true, remove: true, requiredOnCreate: ["name", "interface", "vlan-id"] },
{ id: "ipv4_address", path: "/ip/address", title: "IPv4-адреса", permission: "mm:network", fields: z.object({ address: name.optional(), interface: name.optional(), network: name.optional(), comment: text.optional(), disabled: bool.optional() }).strict(), create: true, remove: true, requiredOnCreate: ["address", "interface"] },
{ id: "ipv6_address", path: "/ipv6/address", title: "IPv6-адреса", permission: "mm:network", fields: z.object({ address: name.optional(), interface: name.optional(), advertise: bool.optional(), comment: text.optional(), disabled: bool.optional() }).strict(), create: true, remove: true, requiredOnCreate: ["address", "interface"] },
@@ -70,6 +77,7 @@ export const rosResources: RosResourceSpec[] = [
export type ConfigurationRow = Record<string, unknown>
export interface RosStep { serverId: number; resource: string; action: "create" | "update" | "delete"; id?: string; fields: Record<string, string>; placeBeforeId?: string; expectedCost?: number; expectedServerProof?: string }
export const ROS_SNAPSHOT_VERSION = 3
export const rosSnapshotVersion = (resource: string): number => ["bridge", "bridge_port", "bridge_vlan"].includes(resource) ? 4 : ROS_SNAPSHOT_VERSION
export interface RosSnapshot { serverId: number; resource: string; rows: ConfigurationRow[]; fingerprint: string; projectionVersion?: number; sourceProof?: string }
export function resourceById(id: string): RosResourceSpec {
const resource = rosResources.find(item => item.id === id)
@@ -93,13 +101,21 @@ export function configurationRows(resource: RosResourceSpec, payload: unknown):
// RouterOS creates/removes IPv6 link-local rows with interface runtime state.
// They cannot be configured independently and must not invalidate a sealed
// inverse plan when its own GRE is disabled. Explicit addresses remain sealed.
const configuration = rows.filter(row => !(resource.id === "ipv6_address" && [true, "true"].includes((row as ConfigurationRow).dynamic as boolean | string) && /^fe80:/i.test(String((row as ConfigurationRow).address))))
const configuration = rows.filter(row => !(resource.id === "ipv6_address" && [true, "true"].includes((row as ConfigurationRow).dynamic as boolean | string) && /^fe80:/i.test(String((row as ConfigurationRow).address)))
// These rows are generated from bridge/port PVID, not independently
// configurable VLAN entries. Their inputs remain sealed in bridge/ports.
&& !(resource.id === "bridge_vlan" && [true, "true", "yes"].includes((row as ConfigurationRow).dynamic as boolean | string)))
const selectedRows = configuration.map(row => {
const selected = Object.fromEntries(Object.entries(row as ConfigurationRow).filter(([key]) => [".id", "dynamic", "builtin", "default", ...fields].includes(key)))
const selected = Object.fromEntries(Object.entries(row as ConfigurationRow).filter(([key]) => [".id", "dynamic", "builtin", "default", ...fields, ...(resource.observeFields ?? [])].includes(key)))
// RouterOS 7.24.5 returns an explicit empty fib flag for non-FIB tables.
// Normalize only this observed field; missing values must remain unknown.
if (resource.id === "routing_table" && selected.fib === "") selected.fib = "false"
if (resource.id === "vrf" && selected.interfaces !== undefined) selected.interfaces = canonicalVrfMembers(selected.interfaces)
if (["bridge_port", "bridge_vlan"].includes(resource.id) && selected.comment === undefined) selected.comment = ""
if (resource.id === "bridge_vlan") {
try { for (const field of ["vlan-ids", "tagged", "untagged"]) selected[field] = canonicalBridgeVlanValue(field, selected[field]) }
catch { throw new McpError("STATE_CONFLICT", "Недостоверная конфигурация VLAN membership", 409) }
}
return selected
})
// Reordering an ordered catalog changes configuration even with unchanged rows.
@@ -118,10 +134,10 @@ export async function readRosSnapshot(serverId: number, resourceId: string, befo
const payload = resourceId === "ospf_template" ? await client.getOspfInterfaceTemplates(checkSource) : ["ospf_instance", "ospf_area", "bgp_instance", "bgp_connection"].includes(resourceId) ? await readOspfEffectiveDisabled(await client.get<unknown>(resource.path), async id => {
await checkSource()
return client.post(resource.path + "/get", { ".id": id, "value-name": "disabled" })
}) : await client.get<unknown>(resource.path)
}) : await readRouterOsSnapshotGet<unknown>({ client, path: resource.path, assertCurrent: checkSource })
await checkSource()
const rows = configurationRows(resource, payload)
return { serverId, resource: resourceId, rows, fingerprint: fingerprint(rows), projectionVersion: ROS_SNAPSHOT_VERSION, sourceProof }
return { serverId, resource: resourceId, rows, fingerprint: fingerprint(rows), projectionVersion: rosSnapshotVersion(resourceId), sourceProof }
}
export async function rosSnapshotSourceProof(server: Awaited<ReturnType<typeof routerClient>>["server"]): Promise<string> {
return privateSecretFingerprint(fingerprint({ id: server.id, enabled: server.enabled, host: server.host, port: server.port, useSsl: server.useSsl, verifySsl: server.verifySsl, username: server.username, password: server.password, epoch: server.routingEndpointEpoch }), "mcp-ros-snapshot-source-v3")
+2 -2
View File
@@ -1,11 +1,11 @@
import { fingerprint, McpError } from "./security.js"
import { readRosSnapshot, ROS_SNAPSHOT_VERSION, type RosSnapshot, type RosStep } from "./resources.js"
import { readRosSnapshot, rosSnapshotVersion, type RosSnapshot, type RosStep } from "./resources.js"
import { verifyRosStepSnapshots } from "./ros-step-verification.js"
import { acknowledgedCreateId } from "./native-create-identity.js"
const key = (snapshot: Pick<RosSnapshot, "serverId" | "resource">) => `${snapshot.serverId}:${snapshot.resource}`
function valid(snapshot: RosSnapshot): boolean {
if (snapshot.projectionVersion !== ROS_SNAPSHOT_VERSION || typeof snapshot.sourceProof !== "string" || !/^[a-f0-9]{64}$/.test(snapshot.sourceProof) || !Array.isArray(snapshot.rows) || snapshot.fingerprint !== fingerprint(snapshot.rows)) return false
if (snapshot.projectionVersion !== rosSnapshotVersion(snapshot.resource) || typeof snapshot.sourceProof !== "string" || !/^[a-f0-9]{64}$/.test(snapshot.sourceProof) || !Array.isArray(snapshot.rows) || snapshot.fingerprint !== fingerprint(snapshot.rows)) return false
if (["ip_settings", "ipv6_settings"].includes(snapshot.resource)) return snapshot.rows.length === 1 && !!snapshot.rows[0] && typeof snapshot.rows[0] === "object" && !Array.isArray(snapshot.rows[0])
const ids = snapshot.rows.map(acknowledgedCreateId)
return ids.every(id => id !== undefined) && new Set(ids).size === ids.length
@@ -1,5 +1,6 @@
import { isDeepStrictEqual } from "node:util"
import { acknowledgedCreateId } from "./native-create-identity.js"
import { canonicalBridgeVlanValue } from "../../services/bridge-vlan-values.js"
import { isOrderedRosResource, resourceById, type ConfigurationRow, type RosResourceSpec, type RosSnapshot, type RosStep } from "./resources.js"
function booleanValue(value: unknown): unknown {
@@ -23,6 +24,9 @@ function requested(resource: RosResourceSpec, fields: RosStep["fields"], row: Co
const schema = resource.fields.shape[key]
if (!schema || typeof value !== "string" || !Object.hasOwn(row, key) || row[key] === undefined || row[key] === null) return false
if (schema.safeParse(true).success) return ["true", "false"].includes(value) && booleanValue(row[key]) === (value === "true")
if (resource.id === "bridge_vlan" && ["vlan-ids", "tagged", "untagged"].includes(key)) {
try { return canonicalBridgeVlanValue(key, row[key]) === canonicalBridgeVlanValue(key, value) } catch { return false }
}
return String(row[key]) === value
})
}
@@ -34,13 +34,15 @@ import { registerManagementChannel } from "./management.js"
import { isSchedulerJobsPaused, pauseSchedulerJobsAndWait, resumeSchedulerJobs } from "../../services/scheduler-running.js"
/** Disposable SQL + loopback HTTP only. Does not access or configure CHR. */
export async function acceptScopedRouteCommunitySwitch(actor: AuthUser, options: { originalEffectsOnly?: boolean; originalCredentialRevocationOnly?: boolean; forwardRoundsOnly?: boolean; manualInverseChargeOnly?: boolean; manualInverseChargeCase?: "positive" | "quota" | "concurrent" | "unknown" | "revoked" | "nonpersistent" | "mixed-forward"; lateInverseAuthorityChange?: "edit" | "disable" | "grant" } = {}) {
export async function acceptScopedRouteCommunitySwitch(actor: AuthUser, options: { originalEffectsOnly?: boolean; controllerFailoverOnly?: boolean; originalCredentialRevocationOnly?: boolean; forwardRoundsOnly?: boolean; manualInverseChargeOnly?: boolean; manualInverseChargeCase?: "positive" | "quota" | "concurrent" | "unknown" | "revoked" | "nonpersistent" | "mixed-forward"; lateInverseAuthorityChange?: "edit" | "disable" | "grant" } = {}) {
const sid = options.lateInverseAuthorityChange ? { edit: 131, disable: 132, grant: 133 }[options.lateInverseAuthorityChange] : 131
const writer: AuthUser = { ...actor, permissions: [...new Set([...actor.permissions, "mm:filters:write"])] }
const initial = compileManagedFilterRules([{ community: "65000:10", gateway: "192.0.2.1", outIface: "", action: "route", description: "" }, { community: "65000:20", gateway: "192.0.2.5", outIface: "", action: "route", description: "" }])
const filters = ["a", "b"].map(key => ({ ".id": "*f" + key, chain: "custom-" + key, rule: initial, disabled: "false", comment: managedComment("NEVER_SCOPED_COMMENT_" + key), opaque: "NEVER_SCOPED_OPAQUE" }))
let mode: "normal" | "ignored" | "lost" | "collateral" | "post-failed" | "post-unknown" = "normal", writes = 0, requests = 0
let controllerProbeUnknown = false
let controllerFailoverProbeSources: string[] | undefined
let controllerFailoverReserveHealthy = true
let pendingPostCheckpoint = false, postCheckpointsObserved = 0
let afterForwardWrite: (() => Promise<void>) | undefined
let afterConfigurationCheckpoint: ((operationId: string) => Promise<void>) | undefined
@@ -65,6 +67,9 @@ export async function acceptScopedRouteCommunitySwitch(actor: AuthUser, options:
const effectConnection = { ".id": "*ca", name: "peer-a", instance: "default", vrf: "main", "routing-table": "tenant-a", afi: "ip",
"input.filter": "custom-a", "output.filter-chain": "", templates: "", disabled: "false", "use-bfd": "false",
"local.address": "198.18.0.1", "remote.address": "198.18.0.2", "remote.as": "65001" }
const { vrf: effectTransportVrf, ...effectSessionFields } = effectConnection
const effectSession = { ...effectSessionFields, ".id": "*sa", "local.afi": "ip", "remote.afi": "ip", established: "true",
"local.address": `${effectConnection["local.address"]}@${effectTransportVrf}`, "remote.address": `${effectConnection["remote.address"]}@${effectTransportVrf}` }
const collections = (path: string): Record<string, unknown>[] => ({
"/system/resource": [{ version: "7.20.1" }],
"/routing/table": ["main", "tenant-a", "tenant-b", "probe-a", "probe-b"].map((name, index) => ({ ".id": "*t" + index, name, fib: "true", disabled: "false", invalid: "false" })),
@@ -72,10 +77,13 @@ export async function acceptScopedRouteCommunitySwitch(actor: AuthUser, options:
"/routing/bgp/connection": [effectConnection, { ...effectConnection, ".id": "*cb", name: "peer-b", "routing-table": "tenant-b", "input.filter": "custom-b" }],
"/routing/bgp/instance": [{ ".id": "*i", name: "default", vrf: "main", "routing-table": "main", disabled: "false" }],
"/routing/bgp/template": [], "/routing/filter/rule": filters,
"/ip/route": [1, 9].map(value => ({ ".id": "*r" + value, "dst-address": "192.0.2." + value + "/32", "routing-table": "main", disabled: "false",
"/ip/route": (controllerFailoverProbeSources ? [1, 9, 10, 11] : [1, 9]).map(value => ({ ".id": "*r" + value, "dst-address": "192.0.2." + value + "/32", "routing-table": "main", disabled: "false",
"immediate-gw": "203.0.113." + value + "%wan-a", comment: managedComment("recursive"), opaque: "NEVER_SCOPED_ROUTE" })),
"/interface": ["wan-a", "wan-b", "hop", "target"].map((name, index) => ({ ".id": "*if" + index, name, disabled: "false", running: "true" })),
"/ip/address": ["wan-a", "wan-b", "hop", "target"].map((name, index) => ({ ".id": "*ad" + index, interface: name, address: "198.51.100." + (index + 1) + "/32", disabled: "false", invalid: "false" })),
"/ip/address": [
...["wan-a", "wan-b", "hop", "target"].map((name, index) => ({ ".id": "*ad" + index, interface: name, address: "198.51.100." + (index + 1) + "/32", disabled: "false", invalid: "false" })),
...(controllerFailoverProbeSources ? [11, 12, 13].map(index => ({ ".id": "*ad" + index, interface: "wan-a", address: "198.51.100." + index + "/32", disabled: "false", invalid: "false" })) : []),
],
...(options.originalEffectsOnly ? {
"/routing/table": ["main", "tenant-a", "tenant-b", "probe-a", "probe-b"].map((name, index) => ({ ".id": "*t" + index, name, fib: "", disabled: "false", invalid: "false" })),
"/routing/bgp/connection": [effectConnection],
@@ -83,7 +91,7 @@ export async function acceptScopedRouteCommunitySwitch(actor: AuthUser, options:
} : {}),
...(exposeEffectCatalogue || options.originalEffectsOnly ? {
"/routing/route": effectRoutes(),
"/routing/bgp/session": [{ ...effectConnection, ".id": "*sa", "local.afi": "ip", "remote.afi": "ip", established: "true" }],
"/routing/bgp/session": [effectSession],
} : {}),
} as Record<string, Record<string, unknown>[]>)[path] ?? []
let requestFailure: { error: unknown } | undefined
@@ -113,23 +121,27 @@ export async function acceptScopedRouteCommunitySwitch(actor: AuthUser, options:
if (req.method === "POST" && path.endsWith("/get")) { const row = collections(path.slice(0, -4)).find(row => row[".id"] === args[".id"]), value = row?.[args["value-name"]]; res.end(JSON.stringify(value === undefined ? [] : { ret: value })); return }
if (req.method === "POST" && path === "/tool/ping") {
if (pendingInversePost) {
const intents = (await pool.query("SELECT source_operation_id FROM mcp_scoped_recovery_intents WHERE state='intent'")).rows
assert.ok(connectionId)
const intents = (await pool.query("SELECT i.source_operation_id FROM mcp_scoped_recovery_intents i JOIN mcp_operations o ON o.id=i.recovery_operation_id WHERE i.state='intent' AND o.connection_id=$1", [connectionId])).rows
assert.equal(intents.length, 1, "Post-inverse probe must follow one durable single-use inverse intent")
pendingInversePost = false; inversePostChecks++
}
if (pendingPostCheckpoint) {
const checkpoint = (await pool.query("SELECT c.configuration_sealed,c.configuration_proof FROM mcp_operation_checkpoints c JOIN mcp_operations o ON o.id=c.operation_id WHERE o.state='running' AND c.configuration_sealed IS NOT NULL")).rows
assert.ok(connectionId)
const checkpoint = (await pool.query("SELECT c.configuration_sealed,c.configuration_proof FROM mcp_operation_checkpoints c JOIN mcp_operations o ON o.id=c.operation_id WHERE o.state='running' AND c.configuration_sealed IS NOT NULL AND o.connection_id=$1", [connectionId])).rows
assert.equal(checkpoint.length, 1, "Exact CONFIG_APPLIED must commit before the post-change network probe")
const packet = JSON.parse(await decryptSecret(checkpoint[0].configuration_sealed))
assert.equal(packet.phase, "CONFIG_APPLIED"); assert.equal(packet.originalRule, initial)
assert.equal(packet.originalCandidateId, "a"); assert.equal(packet.desiredCandidateId, "b")
assert.equal(packet.originalCandidateId, "a"); assert.equal(packet.desiredCandidateId, controllerFailoverProbeSources ? "d" : "b")
assert.equal(packet.desiredRule, filters.find(row => row[".id"] === packet.nativeId)!.rule)
assert.ok(checkpoint[0].configuration_proof); pendingPostCheckpoint = false; postCheckpointsObserved++
const sharedCheck = afterConfigurationCheckpoint; afterConfigurationCheckpoint = undefined
await sharedCheck?.(packet.operationId)
}
observedVrfs.add(args.vrf)
res.end(JSON.stringify(controllerProbeUnknown || mode === "post-unknown" && writes ? [{ message: "unsupported fixture output" }] : [{ sent: "3", received: mode === "post-failed" && writes ? "0" : "3", "packet-loss": mode === "post-failed" && writes ? "100" : "0", "avg-rtt": "1ms" }]))
if (controllerFailoverProbeSources) controllerFailoverProbeSources.push(args["src-address"])
const probeFailed = controllerFailoverProbeSources && (!controllerFailoverReserveHealthy || args["src-address"] !== "198.51.100.13") || mode === "post-failed" && writes
res.end(JSON.stringify(controllerProbeUnknown || mode === "post-unknown" && writes ? [{ message: "unsupported fixture output" }] : [{ sent: "3", received: probeFailed ? "0" : "3", "packet-loss": probeFailed ? "100" : "0", "avg-rtt": "1ms" }]))
return
}
if (req.method === "POST" && path === "/tool/traceroute") { observedVrfs.add(args.vrf); res.end(JSON.stringify([3, 4].map(index => ({ address: "198.51.100." + index, sent: "1", loss: "0" })))); return }
@@ -264,6 +276,74 @@ export async function acceptScopedRouteCommunitySwitch(actor: AuthUser, options:
return operation
} finally { observer.close() }
}
const acceptControllerFailover = async () => {
reset(); await refresh(); exposeEffectCatalogue = true; originalEffectCase = "transition"
controllerFailoverProbeSources = []
const profileId = randomUUID(), initialWrites = writes
persistentProfileIds.push(profileId)
try {
const configured = profile("a"), original = configured.candidates[0]
configured.candidates = [1, 10, 11, 9].map((gateway, index) => ({ ...original,
id: ["a", "b", "c", "d"][index], gateway: "192.0.2." + gateway,
gatewayRef: { resource: "ipv4_route", id: "*r" + gateway },
controlProbe: { ...original.controlProbe!, sourceAddress: "198.51.100." + [1, 11, 12, 13][index] },
}))
const analysis = await invokeMcpTool(principal, "mm_route_optimizer_analyze", { profile: configured }) as { currentCandidateId: string; ranking: Array<{ eligible: boolean; candidate: { id: string } }> }
assert.equal(analysis.currentCandidateId, "a")
assert.deepEqual(analysis.ranking.filter(row => row.eligible).map(row => row.candidate.id), ["a", "b", "c", "d"])
const enrollment = await invokeMcpTool(principal, "mm_route_profile_save_plan", {
profileId, profile: configured, enabled: true, expiresAt: new Date(Date.now() + 600000).toISOString(),
}) as { planId: string }
await approvePlan(enrollment.planId, writer, true)
assert.equal((await execute(enrollment.planId)).state, "applied")
const readController = async () => (await pool.query("SELECT enabled,state FROM mcp_routing_profiles WHERE id=$1", [profileId])).rows[0]
const failures = new Set<string>()
let switchPlanId: string | undefined
for (const [index, alternate] of [12, 13, 13, 12, 13].entries()) {
// Drive the normal scheduled entry point without waiting a minute.
await pool.query("UPDATE mcp_routing_profiles SET state=state-'probedAt' WHERE id=$1", [profileId])
controllerFailoverProbeSources.length = 0
// The previously passing reserve must be rechecked, and its prior
// pass cannot authorize failover if the current check fails.
controllerFailoverReserveHealthy = index !== 2
await tickRoutingProfiles()
const row = await readController()
assert.equal(row.enabled, true, String(row.state.pausedReason))
assert.deepEqual(controllerFailoverProbeSources, [1, 11, alternate].map(last => "198.51.100." + last))
failures.add(row.state.failureKey)
assert.equal(failures.size, index + 1, "Each counted failure must come from a distinct path check")
assert.equal(writes, initialWrites)
if (index < 4) {
assert.equal(row.state.failureCount, index + 1)
assert.equal(row.state.planId, undefined, "Earlier healthy reserve evidence cannot replace a fresh passing probe")
} else {
assert.equal(row.state.candidateId, "d")
switchPlanId = row.state.planId
}
}
assert.ok(switchPlanId)
assert.equal((await loadPlan(switchPlanId)).state, "awaiting-approval")
await tickRoutingProfiles()
assert.equal(writes, initialWrites)
await approvePlan(switchPlanId, writer, true)
await tickRoutingProfiles()
const operationId: string = (await readController()).state.operationId
assert.ok(operationId)
assert.equal(await waitForOperation(operationId), "applied")
await tickRoutingProfiles()
const completed = await readController()
assert.equal(completed.enabled, true, String(completed.state.pausedReason))
assert.equal(completed.state.baseline.packet.candidateId, "d")
assert.equal(completed.state.baseline.packet.transition.operationId, operationId)
assert.equal(completed.state.failoverReserveCursor, undefined)
assert.equal(writes, initialWrites + 1)
const result = { accepted: true, stableRanking: ["a", "b", "c", "d"], selectedReserve: "d", probeCallsPerTick: 3,
distinctFailuresBeforePlan: failures.size, priorPassedProbeNotReused: true, humanApproval: true, nativeWrites: 1 }
console.log("Bounded controller reserve SQL/HTTP:", JSON.stringify(result))
return result
} finally { await disablePersistent(profileId); controllerFailoverProbeSources = undefined; controllerFailoverReserveHealthy = true }
}
if (options.controllerFailoverOnly) return { ...await acceptControllerFailover(), persistentAuthorityCases: 0 }
if (options.originalEffectsOnly) {
const cases: Array<Record<string, unknown>> = []
let publicManualRevision2: Record<string, unknown> | undefined
@@ -546,8 +626,9 @@ export async function acceptScopedRouteCommunitySwitch(actor: AuthUser, options:
assert.equal(switched.state.baseline.packet.transition.planId, switchPlanId)
assert.equal(writes - beforeControllerWrites, 1)
await disablePersistent(activeProfileId)
const boundedReserveFailover = await acceptControllerFailover()
assert.deepEqual((await pool.query("SELECT * FROM filter_rules WHERE server_id=$1 ORDER BY id", [sid])).rows, dbBefore)
const result = { accepted: true, cases, publicManualRevision2, persistentAuthorityCases: 0, realMcpDispatcher: true, realSql: true, routerOsTransport: "declared-synthetic-localhost-http",
const result = { accepted: true, cases, publicManualRevision2, boundedReserveFailover, persistentAuthorityCases: 0, realMcpDispatcher: true, realSql: true, routerOsTransport: "declared-synthetic-localhost-http",
genuineApprovedRunningOrigin: true, actualConfigurationCheckpoint: true, signedEffectTamperRejected: true,
originalAutoRecoveryEnabled: false, fullRoutingAccepted: false, scopedControllerEnabled: true, publicScopedControllerLifecycle: true, nativeChrAccepted: false, forwardingVerified: false }
console.log("Original effect SQL/runtime component:", JSON.stringify(result))
@@ -700,10 +781,20 @@ export async function acceptScopedRouteCommunitySwitch(actor: AuthUser, options:
const recovery = await invokeMcpTool(principal, "mm_operation_recovery_plan", { operationId: source.id }) as { planId: string; state: string }
assert.equal(recovery.state, "awaiting-approval")
assert.equal((await loadPlan(recovery.planId)).operation_id, "operations.recover")
assert.equal((await loadPlan(recovery.planId)).operation_version, 7)
assert.equal((await loadPlan(recovery.planId)).operation_version, 8)
await assert.rejects(applyPlan(principal, recovery.planId, randomUUID()))
assert.deepEqual(await snapshot(), afterForward, "No approval means no debit/charge/native write")
await approvePlan(recovery.planId, writer, true)
if (chargeCase === "positive" && !options.lateInverseAuthorityChange) {
await pool.query("UPDATE mcp_plans SET operation_version=7 WHERE id=$1", [recovery.planId])
try {
await assert.rejects(applyPlan(principal, recovery.planId, randomUUID()), { code: "PLAN_EXPIRED" })
assert.equal((await pool.query("SELECT id FROM mcp_operations WHERE plan_id=$1", [recovery.planId])).rowCount, 0)
assert.deepEqual(await snapshot(), afterForward, "Superseded approved inverse cannot create an operation, debit or native write")
} finally {
await pool.query("UPDATE mcp_plans SET operation_version=8 WHERE id=$1", [recovery.planId])
}
}
if (chargeCase === "mixed-forward") {
assert(competingForward)
const attempts = [
@@ -827,9 +918,14 @@ export async function acceptScopedRouteCommunitySwitch(actor: AuthUser, options:
assert.equal(afterInverse.forward, persistent ? 1 : 0); assert.equal(afterInverse.manualInverse, persistent ? 1 : 0); assert.equal(afterInverse.total, persistent ? 2 : 0)
assert.equal(afterInverse.reserved, 0); assert.equal(afterInverse.legacy, 0)
assert.equal(afterInverse.writes, 2); if (chargeCase !== "unknown") assert.equal(inversePostChecks, 1)
const charges = (await pool.query("SELECT recovery_operation_id,recovery_plan_id,source_operation_id,profile_id,charge_units FROM mcp_routing_manual_inverse_charges WHERE source_operation_id=$1", [source.id])).rows
const charges = (await pool.query("SELECT recovery_operation_id,recovery_plan_id,source_operation_id,profile_id,charge_units,binding_sealed FROM mcp_routing_manual_inverse_charges WHERE source_operation_id=$1", [source.id])).rows
assert.equal(charges.length, persistent ? 1 : 0);
if (persistent) { assert.equal(charges[0].recovery_operation_id, inverse.id); assert.equal(charges[0].recovery_plan_id, inverse.plan_id); assert.equal(charges[0].profile_id,id); assert.equal(charges[0].charge_units,1) }
if (persistent) {
assert.equal(charges[0].recovery_operation_id, inverse.id); assert.equal(charges[0].recovery_plan_id, inverse.plan_id); assert.equal(charges[0].profile_id,id); assert.equal(charges[0].charge_units,1)
const binding = JSON.parse(await decryptSecret(charges[0].binding_sealed))
assert.equal(binding.operationVersion, 8)
assert.equal(binding.sourceVersion, 7)
}
const intent = (await pool.query("SELECT state,verified_sealed,recovery_operation_id,authority_profile_id,authority_profile_version,reservation_id FROM mcp_scoped_recovery_intents WHERE source_operation_id=$1 AND source_step_index=0", [source.id])).rows
assert.equal(intent.length, 1); assert.equal(intent[0].state, chargeCase === "unknown" ? "unknown" : "verified"); assert.equal(intent[0].recovery_operation_id, inverse.id)
assert.equal(intent[0].authority_profile_id, null); assert.equal(intent[0].authority_profile_version, persistent ? 1 : null); assert.equal(intent[0].reservation_id, null)
@@ -1235,9 +1331,12 @@ export async function acceptScopedRouteCommunitySwitch(actor: AuthUser, options:
console.log("Worker exclusion preserved exact running CONFIG_APPLIED profile")
}
const action = { principal, connection: await effectiveMcpConnection(principal) }
// Reuse the approved plan's original deadline: now +90s would extend
// its preparation-time probe horizon and mask the duplicate-owner guard.
const deadline = (await loadPlan(plan.planId)).expires_at.getTime()
const reads = requests
await assert.rejects(createRoutingNetworkNativeSession({ sourceOperationId: operationId, context: action,
authorize: async () => {}, deadline: Date.now() + 90000, manifest: { servers: [sid], probes: [] } }), /Source native session уже создавалась/)
authorize: async () => {}, deadline, manifest: { servers: [sid], probes: [] } }), /Source native session уже создавалась/)
assert.equal(requests, reads); assert.equal(writes, before + 1)
})
assert.equal(op.state, "applied"); assert.equal(writes, before + 1)
+1 -1
View File
@@ -243,7 +243,7 @@ export function registerRoutingControls(register: typeof add) {
},
})
register("routing.vrf.update", "mm_vrf_plan", "Проверенный состав существующего VRF", "network", "mm:network:write", "write", "servers", z.object({ serverId, id: objectId, interfaces: z.array(text).min(1).max(100).refine(values => new Set(values).size === values.length) }).strict(), {
version: 3,
version: 4,
prepare: async (input, context) => {
const sid = Number(input.serverId), { client } = await routerClient(sid), snapshot = await readRosSnapshot(sid, "vrf"), current = snapshot.rows.find(row => row[".id"] === input.id)
if (!current || current.name === "main" || !hasManagedCommentPrefix(String(current.comment ?? ""))) throw new McpError("PROTECTED_OBJECT", "Изменять состав можно только у существующего VRF приложения")
@@ -57,7 +57,7 @@ function cursor(rows:unknown[],onFetch?:()=>void) {
test("historical cursor authenticates more than two pages of genuine nonpersistent classifications",async()=>{
const dir=await mkdtemp(join(tmpdir(),"mm-manual-history-unit-")),previous=process.env.MCP_STATE_DIR;process.env.MCP_STATE_DIR=dir
try {
const rows=[];for(let n=0;n<25;n++)rows.push((await fixture(false,n%2?6:7)).row)
const rows=[];for(let n=0;n<25;n++)rows.push((await fixture(false,6+n%3)).row)
const f=cursor(rows)
await assertLegacyManualHistoryWithinOwner(f.db,randomUUID(),at,()=>{})
assert.equal(f.calls.filter(sql=>sql.startsWith("FETCH")).length,3)
@@ -76,8 +76,10 @@ test("historical authentication, active persistent refusal, future rejection and
await assertLegacyManualHistoryWithinOwner(cursor([f.row]).db,f.profileId,"2026-11-01T13:01:00.001Z",()=>{})
const expiredTamper={...f.row,source_evidence:null}
await assert.rejects(assertLegacyManualHistoryWithinOwner(cursor([expiredTamper]).db,f.profileId,"2026-11-01T14:00:00.000Z",()=>{}))
const current={...f.row,recovery_version:7}
await assert.rejects(assertLegacyManualHistoryWithinOwner(cursor([current]).db,f.profileId,"2026-11-01T14:00:00.000Z",()=>{}),/lacks durable charge/)
for (const version of [7,8]) {
const current={...f.row,recovery_version:version}
await assert.rejects(assertLegacyManualHistoryWithinOwner(cursor([current]).db,f.profileId,"2026-11-01T14:00:00.000Z",()=>{}),/lacks durable charge/)
}
const stripped={...f.input};delete stripped.persistentProfileAuthority
await assert.rejects(assertLegacyManualHistoryWithinOwner(cursor([{...f.row,source_evidence:await encryptSecret(JSON.stringify({steps:[{kind:"service",service:"routing.community.scoped",input:stripped}]}))}]).db,f.profileId,at,()=>{}))
const future={...f.intent,createdAt:"2026-11-01T12:00:00.001Z"}
@@ -112,14 +114,14 @@ test("state transfer cap MODEL refuses oversized or NULL history as a whole, wit
}finally{if(previous===undefined)delete process.env.MCP_STATE_DIR;else process.env.MCP_STATE_DIR=previous;await rm(dir,{recursive:true,force:true})}
})
async function retentionFixture() {
const f=await fixture(true,7), authority=f.input.persistentProfileAuthority as {packet:{profileVersion:number;scope:number[]};proof:string}
async function retentionFixture(version = 7) {
const f=await fixture(true,version), authority=f.input.persistentProfileAuthority as {packet:{profileVersion:number;scope:number[]};proof:string}
const payload=await encryptSecret(JSON.stringify({MODEL:true}))
const row={...f.row,recovery_payload:payload,authority_profile_version:1}
const binding=manualInverseReceiptSchema.shape.binding.parse({revision:1,recoveryOperationId:f.intent.operationId,recoveryPlanId:row.recovery_plan_id,
sourceOperationId:f.intent.sourceOperationId,sourcePlanId:row.source_plan_id,sourceStepIndex:0,profileId:f.profileId,profileVersion:1,
connectionId:f.intent.connectionId,ownerId:f.intent.ownerId,originalPrincipal:f.input.principal,recoveryPrincipal:f.input.principal,
operationVersion:7,sourceVersion:7,authorityProof:authority.proof,sourceProof:f.intent.sourceProof,sourceRequestProof:f.input.requestProof,
operationVersion:version,sourceVersion:7,authorityProof:authority.proof,sourceProof:f.intent.sourceProof,sourceRequestProof:f.input.requestProof,
recoveryRequestProof:f.intent.requestSeal,sourceEvidenceProof:fingerprint(row.source_evidence),recoveryEvidenceProof:fingerprint(row.recovery_evidence),
recoveryPayloadProof:fingerprint(payload),scope:authority.packet.scope,createdAt:at,chargeUnits:1})
const receipt={binding,proof:await sign(binding,"routing-manual-inverse-charge-v1")}
@@ -153,17 +155,19 @@ function retentionOwner(f:Awaited<ReturnType<typeof retentionFixture>>,present=t
test('retention MODEL intent2 authenticates SQL clock after parent GC; unknown noReplay anchor survives',async()=>{
const dir=await mkdtemp(join(tmpdir(),'mm-intent2-retention-')),previous=process.env.MCP_STATE_DIR;process.env.MCP_STATE_DIR=dir
try {
const f=await retentionFixture(),owner=retentionOwner(f),before=fingerprint(f.row)
// SQL aging and the transaction owner below are MODELS, never genuine SQL.
await assertLegacyManualHistoryWithinOwner(owner.db,f.profileId,'2026-11-03T12:00:00.000Z',()=>{})
assert.deepEqual(await retainManualInverseChargesWithinOwner(owner.db,1),{deleted:1})
assert.equal(owner.deleted.length,1);assert.equal(fingerprint(f.row),before)
for(const profile of [f.profileId,randomUUID()])await assertLegacyManualHistoryWithinOwner(owner.db,profile,'2026-11-03T12:00:00.000Z',()=>{})
assert(owner.calls.findIndex(s=>s.includes('pg_advisory_xact_lock'))<owner.calls.findIndex(s=>s.startsWith('SELECT c.recovery_operation_id')))
const candidate=owner.calls.find(s=>s.startsWith('SELECT c.recovery_operation_id'))!
assert(candidate.indexOf("state IN('pending','running')")<candidate.indexOf('LIMIT 100'))
assert(candidate.includes('r.authority_profile_version IS NOT NULL'))
assert.equal(f.intent.revision,2);assert.equal(await decryptSecretExisting(f.row.intent_sealed),JSON.stringify(f.intent))
for (const version of [7,8]) {
const f=await retentionFixture(version),owner=retentionOwner(f),before=fingerprint(f.row)
// SQL aging and the transaction owner below are MODELS, never genuine SQL.
await assertLegacyManualHistoryWithinOwner(owner.db,f.profileId,'2026-11-03T12:00:00.000Z',()=>{})
assert.deepEqual(await retainManualInverseChargesWithinOwner(owner.db,1),{deleted:1})
assert.equal(owner.deleted.length,1);assert.equal(fingerprint(f.row),before)
for(const profile of [f.profileId,randomUUID()])await assertLegacyManualHistoryWithinOwner(owner.db,profile,'2026-11-03T12:00:00.000Z',()=>{})
assert(owner.calls.findIndex(s=>s.includes('pg_advisory_xact_lock'))<owner.calls.findIndex(s=>s.startsWith('SELECT c.recovery_operation_id')))
const candidate=owner.calls.find(s=>s.startsWith('SELECT c.recovery_operation_id'))!
assert(candidate.indexOf("state IN('pending','running')")<candidate.indexOf('LIMIT 100'))
assert(candidate.includes('r.authority_profile_version IS NOT NULL'))
assert.equal(f.intent.revision,2);assert.equal(await decryptSecretExisting(f.row.intent_sealed),JSON.stringify(f.intent))
}
}finally{if(previous===undefined)delete process.env.MCP_STATE_DIR;else process.env.MCP_STATE_DIR=previous;await rm(dir,{recursive:true,force:true})}
})
@@ -182,6 +186,11 @@ test('retention MODEL refuses recent/future/malformed copy, present corrupt pare
const t=retentionOwner(tamper);await assert.rejects(retainManualInverseChargesWithinOwner(t.db,1),/MAC/);assert.equal(t.deleted.length,0)
const legacy=await fixture(true,7)
await assert.rejects(assertLegacyManualHistoryWithinOwner(cursor([legacy.row]).db,legacy.profileId,'2026-11-03T12:00:00.000Z',()=>{}),/lacks durable/)
const wrongVersion=await retentionFixture(7);wrongVersion.row.recovery_version=8
const mismatched=retentionOwner(wrongVersion)
await assert.rejects(assertLegacyManualHistoryWithinOwner(mismatched.db,wrongVersion.profileId,'2026-11-03T12:00:00.000Z',()=>{}),/signed allocation/)
await assert.rejects(retainManualInverseChargesWithinOwner(mismatched.db,1),/hint/)
assert.equal(mismatched.deleted.length,0)
// Revision2 payload proof cannot be replaced by an authentic stamp from a different payload.
const payload=await retentionFixture();payload.row.recovery_payload=await encryptSecret('{}')
await assert.rejects(assertLegacyManualHistoryWithinOwner(retentionOwner(payload,false).db,payload.profileId,'2026-11-03T12:00:00.000Z',()=>{}),/payload/)
@@ -40,7 +40,7 @@ export async function classifyManualInverseHistory(row:HistoricalRow,observedAt:
intent.receiptId!==row.recovery_receipt_id || intent.validUntil!==iso(row.deadline) ||
row.source_connection_id!==intent.connectionId || row.recovery_connection_id!==intent.connectionId ||
row.source_action!=="routing.community.switch" || row.source_version!==7 ||
row.recovery_action!=="operations.recover" || ![6,7].includes(row.recovery_version??0) ||
row.recovery_action!=="operations.recover" || ![6,7,8].includes(row.recovery_version??0) ||
!["partial","applied"].includes(row.source_state??"")) throw fail("Historical manual intent/source identity differs")
const source=await sealedJson(row.source_evidence) as ChangeEvidence, recovery=await sealedJson(row.recovery_evidence) as ChangeEvidence
const step=source.steps?.[0], inverse=recovery.steps?.[0]
@@ -141,7 +141,7 @@ export async function assertLegacyManualHistoryWithinOwner(db:PoolClient,profile
// Authenticate any durable inverse row before treating this old manual
// identity as represented by the normal profile ledger.
const {authenticateManualInverseHistoryWithinOwner}=await import("./routing-manual-inverse-store.js")
if(await authenticateManualInverseHistoryWithinOwner(db,classified.intent,classified.authority,observedAt,{sourceEvidenceProof:fingerprint(row.source_evidence),recoveryEvidenceProof:fingerprint(row.recovery_evidence),recoveryPlanId:row.recovery_plan_id,sourcePlanId:row.source_plan_id,sourceRequestProof:classified.sourceRequestProof,sourcePrincipal:classified.sourcePrincipal,recoveryPrincipal:classified.recoveryPrincipal})) continue
if(await authenticateManualInverseHistoryWithinOwner(db,classified.intent,classified.authority,observedAt,{sourceEvidenceProof:fingerprint(row.source_evidence),recoveryEvidenceProof:fingerprint(row.recovery_evidence),recoveryPlanId:row.recovery_plan_id,recoveryVersion:row.recovery_version,sourcePlanId:row.source_plan_id,sourceRequestProof:classified.sourceRequestProof,sourcePrincipal:classified.sourcePrincipal,recoveryPrincipal:classified.recoveryPrincipal})) continue
if(row.recovery_version!==6) throw fail("Current persistent manual inverse lacks durable charge")
if(classified.authority.packet.profileId!==profileId) continue
// Historical v6 sealed evidence.validUntil bounded admission; source and
@@ -7,6 +7,7 @@ import { effectiveMcpConnection } from "./store.js"
import { decryptSecretExisting, encryptSecret, fingerprint, McpError, privateFingerprinterExisting, privateSecretFingerprint } from "./security.js"
import { routingProfileAuthorityBindingSchema } from "./routing-profile-authority.js"
import type { RoutingSwitchLedgerEntry } from "./routing-switch-ledger-contract.js"
import { findMcpOperation } from "./registry.js"
const fail = (message: string) => new McpError("STATE_CONFLICT", message, 409)
const uuid = z.string().uuid(), proof = z.string().regex(/^[a-f0-9]{64}$/), stamp = z.string().datetime()
@@ -14,7 +15,7 @@ const principal = z.object({ connectionId: uuid, credentialId: uuid, credentialE
export const manualInverseBindingSchema = z.object({ revision: z.literal(1), recoveryOperationId: uuid, recoveryPlanId: uuid,
sourceOperationId: uuid, sourcePlanId: uuid, sourceStepIndex: z.literal(0), profileId: uuid, profileVersion: z.number().int().positive(),
connectionId: uuid, ownerId: z.string().min(1).max(1000), originalPrincipal: principal, recoveryPrincipal: principal,
operationVersion: z.literal(7), sourceVersion: z.literal(7), authorityProof: proof, sourceProof: proof,
operationVersion: z.union([z.literal(7), z.literal(8)]), sourceVersion: z.literal(7), authorityProof: proof, sourceProof: proof,
sourceRequestProof: proof, recoveryRequestProof: proof, sourceEvidenceProof: proof,
recoveryEvidenceProof: proof, recoveryPayloadProof: proof,
scope: z.array(z.number().int().positive().safe()).min(1).max(1000), createdAt: stamp, chargeUnits: z.literal(1) }).strict()
@@ -74,7 +75,8 @@ export async function selectManualInverseAdmissionWithinOwner(db: PoolClient, pl
if (plan.operation_id!=="operations.recover") return undefined
const step=evidence.steps[0]
if (evidence.steps.length!==1 || step.kind!=="service" || step.service!=="routing.community.scoped.recover") return undefined
if (plan.operation_version!==7 || step.input.mode!=="manual") throw fail("Manual recovery action version/mode differs")
if (plan.operation_version!==findMcpOperation(plan.operation_id)?.version) throw new McpError("PLAN_EXPIRED", "Версия операции изменилась; подготовьте новый план", 409)
if (step.input.mode!=="manual") throw fail("Manual recovery mode differs")
const { loadScopedManualRecoveryAdmissionWithinOwner } = await import("./routing-community-scoped-recovery.js")
const loaded = await loadScopedManualRecoveryAdmissionWithinOwner(step.input, actor, db)
const { source } = loaded
@@ -92,7 +94,7 @@ function expectedBinding(selected: NonNullable<Awaited<ReturnType<typeof selectM
return manualInverseBindingSchema.parse({revision:1,recoveryOperationId:operationId,recoveryPlanId:plan.id,
sourceOperationId:selected.source.row.id,sourcePlanId:selected.source.row.source_plan_id,sourceStepIndex:0,profileId:authority.profileId,profileVersion:authority.profileVersion,
connectionId:actor.connectionId,ownerId:authority.ownerId,originalPrincipal:principal.parse(selected.input.principal),recoveryPrincipal:actor,
operationVersion:7,sourceVersion:7,authorityProof:selected.authority.proof,sourceProof:selected.source.sourceProof,
operationVersion:plan.operation_version,sourceVersion:selected.source.row.source_version,authorityProof:selected.authority.proof,sourceProof:selected.source.sourceProof,
sourceRequestProof:selected.input.requestProof,recoveryRequestProof:selected.recoveryInput.requestProof,
sourceEvidenceProof:selected.sourceEvidenceProof,recoveryEvidenceProof:fingerprint(plan.evidence.sealed),
recoveryPayloadProof:fingerprint(plan.payload.sealed),scope:authority.scope,createdAt:observedAt,chargeUnits:1})
@@ -134,7 +136,7 @@ export async function admitManualInverseWithinOwner(db: PoolClient, operationId:
/** A committed charge is required before the existing manual native intent.
* This authenticates identity only; existing live/native authority still runs. */
export async function assertManualInverseChargeWithinOwner(db:PoolClient,operationId:string,input:Record<string,unknown>,actor:McpPrincipal) {
const rows=(await db.query<StoredPlan>("SELECT p.* FROM mcp_operations o JOIN mcp_plans p ON p.id=o.plan_id WHERE o.id=$1 AND o.connection_id=$2 AND o.state='running' AND p.state='executing' AND p.operation_id='operations.recover' AND p.operation_version=7",[operationId,actor.connectionId])).rows
const rows=(await db.query<StoredPlan>("SELECT p.* FROM mcp_operations o JOIN mcp_plans p ON p.id=o.plan_id WHERE o.id=$1 AND o.connection_id=$2 AND o.state='running' AND p.state='executing' AND p.operation_id='operations.recover' AND p.operation_version=$3",[operationId,actor.connectionId,findMcpOperation("operations.recover")?.version])).rows
if(rows.length!==1) throw fail("Manual native claim requires current running action version")
const plan=rows[0], evidence=JSON.parse(await decryptSecretExisting(plan.evidence.sealed)) as ChangeEvidence
const step=evidence.steps[0]
@@ -154,7 +156,7 @@ export async function assertManualInverseChargeWithinOwner(db:PoolClient,operati
export async function authenticateManualInverseHistoryWithinOwner(db:PoolClient,
intent:{revision?:number;manualInverseCharge?:ManualInverseReceipt;operationId:string;sourceOperationId:string;sourceReceiptId:string;sourceProof:string;requestSeal:string;connectionId:string;ownerId:string},
authority:z.infer<typeof routingProfileAuthorityBindingSchema>,observedAt:string,
identity:{sourceEvidenceProof:string;recoveryEvidenceProof:string;recoveryPlanId:string|null;sourcePlanId:string|null;sourceRequestProof:unknown;sourcePrincipal:unknown;recoveryPrincipal:unknown}) {
identity:{sourceEvidenceProof:string;recoveryEvidenceProof:string;recoveryPlanId:string|null;recoveryVersion:number|null;sourcePlanId:string|null;sourceRequestProof:unknown;sourcePrincipal:unknown;recoveryPrincipal:unknown}) {
const rows=(await db.query<ChargeRow>(`SELECT ${columns} FROM mcp_routing_manual_inverse_charges WHERE recovery_operation_id=$1 OR source_operation_id=$2 LIMIT 3`,[intent.operationId,intent.sourceOperationId])).rows
const copy = intent.revision === 2 ? await authenticateCopy(intent.manualInverseCharge, observedAt) : undefined
if (!rows.length && !copy) return false
@@ -166,7 +168,8 @@ export async function authenticateManualInverseHistoryWithinOwner(db:PoolClient,
value.profileId!==authority.packet.profileId || value.profileVersion!==authority.packet.profileVersion || value.authorityProof!==authority.proof ||
value.connectionId!==intent.connectionId || value.ownerId!==intent.ownerId || value.sourceProof!==intent.sourceProof ||
value.recoveryRequestProof!==intent.requestSeal || value.sourceEvidenceProof!==identity.sourceEvidenceProof ||
value.recoveryEvidenceProof!==identity.recoveryEvidenceProof || value.recoveryPlanId!==identity.recoveryPlanId || value.sourcePlanId!==identity.sourcePlanId)throw fail("Historical inverse is not represented by its signed allocation")
value.recoveryEvidenceProof!==identity.recoveryEvidenceProof || value.recoveryPlanId!==identity.recoveryPlanId ||
value.operationVersion!==identity.recoveryVersion || value.sourcePlanId!==identity.sourcePlanId)throw fail("Historical inverse is not represented by its signed allocation")
// Only revision2 needs this extra one-row bounded projection; preserve the
// existing cursor page payload ceiling and legacy protocol untouched.
const payload = copy ? (await db.query<{sealed:string|null}>("SELECT CASE WHEN octet_length(payload::text)<=1048576 THEN payload->>'sealed' END AS sealed FROM mcp_plans WHERE id=$1 LIMIT 2",[identity.recoveryPlanId])).rows : []
@@ -201,11 +204,11 @@ export async function retainManualInverseChargesWithinOwner(db: PoolClient, rete
" WHERE r.mode='manual' AND r.source_operation_id=$1 AND r.source_step_index=0 AND r.recovery_operation_id=$2",[candidate.source_operation_id,candidate.recovery_operation_id])).rows
if(rows.length!==1)throw fail("Retention intent/source pair disappeared")
const row=rows[0],classified=await classifyManualInverseHistory(row,observedAt)
if(classified.kind!=="persistent" || classified.intent.revision!==2 || row.recovery_version!==7 ||
if(classified.kind!=="persistent" || classified.intent.revision!==2 || row.recovery_version!==classified.intent.manualInverseCharge.binding.operationVersion ||
row.authority_profile_version!==candidate.profile_version || row.authority_profile_version!==classified.intent.manualInverseCharge.binding.profileVersion)
throw fail("Retention hint is not an authenticated persistent intent2")
if(!await authenticateManualInverseHistoryWithinOwner(db,classified.intent,classified.authority,observedAt,{
sourceEvidenceProof:fingerprint(row.source_evidence),recoveryEvidenceProof:fingerprint(row.recovery_evidence),recoveryPlanId:row.recovery_plan_id,sourcePlanId:row.source_plan_id,sourceRequestProof:classified.sourceRequestProof,sourcePrincipal:classified.sourcePrincipal,recoveryPrincipal:classified.recoveryPrincipal}))
sourceEvidenceProof:fingerprint(row.source_evidence),recoveryEvidenceProof:fingerprint(row.recovery_evidence),recoveryPlanId:row.recovery_plan_id,recoveryVersion:row.recovery_version,sourcePlanId:row.source_plan_id,sourceRequestProof:classified.sourceRequestProof,sourcePrincipal:classified.sourcePrincipal,recoveryPrincipal:classified.recoveryPrincipal}))
throw fail("Retention parent is not authenticated")
const result=await db.query("DELETE FROM mcp_routing_manual_inverse_charges WHERE recovery_operation_id=$1 AND source_operation_id=$2",[candidate.recovery_operation_id,candidate.source_operation_id])
if(result.rowCount!==1)throw fail("Retention parent delete was not confirmed")
+21 -1
View File
@@ -1,7 +1,7 @@
import assert from "node:assert/strict"
import { test } from "node:test"
import { routeAiProfileSchema, type RouteObservation } from "@mmapp/contracts/mcp-routing"
import { rankRoutingCandidates, decideRoutingSwitch, type ControllerState, type PathHealth } from "./routing-model.js"
import { rankRoutingCandidates, decideRoutingSwitch, selectFailoverReserveProbes, type ControllerState, type PathHealth } from "./routing-model.js"
const now = Date.parse("2026-10-17T10:00:00Z"), at = new Date(now).toISOString()
const profile = routeAiProfileSchema.parse({ name: "Test", serverId: 1, community: "65000:10", family: "ipv4", candidates: [
@@ -81,6 +81,26 @@ test("failover starts a fresh series after downtime or legacy state and ignores
assert.equal(result.state.failureObservedAt, new Date(time).toISOString())
}
})
test("bounded failover probing keeps the highest eligible reserve and eventually visits every other eligible probe", () => {
const controlProbe = { targetInterface: "exit-a", expectedHops: [{ serverId: 3, interface: "exit-a" }] }
const configured = routeAiProfileSchema.parse({ ...profile, excludedCandidateIds: ["05"],
candidates: Array.from({ length: 100 }, (_, index) => ({ ...profile.candidates[0], id: String(index).padStart(2, "0"),
controlProbe: index === 4 ? undefined : controlProbe })) })
const ranking = rankRoutingCandidates(configured, a, now)
const expected = ranking.filter(row => row.eligible && row.candidate.controlProbe && !["00", "01"].includes(row.candidate.id)).map(row => row.candidate.id)
let cursor: string | undefined
for (const alternate of expected) {
const probes = selectFailoverReserveProbes(ranking, "00", cursor)
assert.deepEqual(probes.candidateIds, ["01", alternate])
assert.equal(probes.cursor, alternate)
cursor = probes.cursor
}
assert.deepEqual(selectFailoverReserveProbes(ranking, "00", cursor).candidateIds, ["01", "02"])
assert.deepEqual(selectFailoverReserveProbes(ranking, "00", "05").candidateIds, ["01", "02"])
const pinned = rankRoutingCandidates({ ...configured, pinnedCandidateId: "09" }, a, now)
assert.deepEqual(selectFailoverReserveProbes(pinned, "00"), { candidateIds: ["09"], cursor: undefined })
assert.deepEqual(selectFailoverReserveProbes(pinned, "09"), { candidateIds: [], cursor: undefined })
})
test("routing combines RTT, independent losses and bottleneck speed, never claims an observed path", () => {
const ranked = rankRoutingCandidates(profile, a, now).find(row => row.candidate.id === "a")!
assert.equal(ranked.pingMs, 20); assert.ok(Math.abs(ranked.lossPct! - 1.99) < 0.00001)
+11
View File
@@ -52,6 +52,17 @@ export function rankRoutingCandidates(profile: RouteAiProfile, observations: Rou
export interface PathHealth { id: string; candidateId: string; status: "passed" | "failed" | "unknown"; observedAt: string }
export interface ControllerState { pendingCandidateId?: string; consecutive?: number; observationKey?: string; lastSwitchAt?: string; switches?: string[]; operationId?: string; pausedReason?: string; failureCount?: number; failureKey?: string; failureObservedAt?: string; failingCandidateId?: string }
export function selectFailoverReserveProbes(ranking: ReturnType<typeof rankRoutingCandidates>, currentCandidateId: string, previous?: string) {
const standbys = ranking.filter(({ candidate, eligible }) => eligible && candidate.id !== currentCandidateId && candidate.controlProbe)
.map(({ candidate }) => candidate.id)
const [preferred, ...remaining] = standbys
if (remaining.length === 0) return { candidateIds: standbys, cursor: undefined }
const index = remaining.indexOf(previous ?? "")
const cursor = remaining[(index + 1) % remaining.length]
return { candidateIds: [preferred, cursor], cursor }
}
const pathHealthFreshnessSec = 90
export function decideRoutingSwitch(profile: RouteAiProfile, state: ControllerState, ranking: ReturnType<typeof rankRoutingCandidates>, currentCandidateId: string | null, now = Date.now(), health: PathHealth[] = [], chargedSwitchesPerHour?: number) {
const next: ControllerState = { ...state, switches: (state.switches ?? []).filter(at => now - Date.parse(at) < 3600000) }
@@ -0,0 +1,28 @@
import { isIP } from "node:net"
export function parseRoutingEndpoint(value: unknown) {
if (typeof value !== "string" || !value.length || value.length > 256) throw Error("missing-or-unsupported-field")
const match = /^([^%@/,\s]+)(?:\/(\d+))?(?:%([^%@/,\s]+))?(?:@([^%@/,\s]+))?$/.exec(value)
if (!match) throw Error("unsupported-endpoint")
const [, address, prefix, interfaceName, vrf] = match
const family = isIP(address)
if (!family) throw Error("unsupported-address")
if (prefix !== undefined && prefix !== String(family === 4 ? 32 : 128)) throw Error("unsupported-peer-range")
return { address, interface: interfaceName, vrf }
}
export function matchesBgpSessionContext(
row: Record<string, unknown>,
expected: { table: string; vrf: string },
local: ReturnType<typeof parseRoutingEndpoint>,
remote: ReturnType<typeof parseRoutingEndpoint>,
) {
if (!Object.hasOwn(row, "routing-table") || row["routing-table"] !== expected.table) return false
if (Object.hasOwn(row, "vrf")) {
return row.vrf === expected.vrf && (local.vrf === undefined || local.vrf === expected.vrf) &&
(remote.vrf === undefined || remote.vrf === expected.vrf)
}
// RouterOS may report the transport VRF only in the two runtime addresses.
// The installation table alone cannot identify it.
return local.vrf === expected.vrf && remote.vrf === expected.vrf
}
@@ -16,6 +16,8 @@ assert(process.env.MCP_STATE_DIR && isAbsolute(process.env.MCP_STATE_DIR))
assert.equal(basename(resolve(process.env.MCP_STATE_DIR)), "state")
assert(basename(dirname(resolve(process.env.MCP_STATE_DIR))).startsWith("mm-mcp-test-"))
const originalEffects = process.env.MMAPP_OWN_ROUTING_ORIGINAL_EFFECTS === "true"
const controllerFailoverOnly = process.env.MMAPP_OWN_ROUTING_CONTROLLER_FAILOVER_ONLY === "true"
assert(!controllerFailoverOnly || originalEffects, "Focused controller failover requires the owned original-effects fixture")
assert(!(originalEffects && process.env.MMAPP_OWN_ROUTING_WORKER_REPRO === "true"), "Owned effect acceptance cannot mix with the worker repro profile")
process.env.AUTH_REQUIRED = "true"
process.env.AUTH_JWT_SECRET = "owned-routing-forward-rounds-acceptance-secret"
@@ -35,7 +37,7 @@ try {
console.log("Worker fixture repro:",await (await import("./routing-worker-fixture-isolation.sql-helper.js")).acceptRoutingWorkerFixtureIsolation(actor))
}
const result = await (await import("./routing-community-scoped-acceptance.js")).acceptScopedRouteCommunitySwitch(actor,
originalEffects ? { originalEffectsOnly: true } : process.env.MMAPP_OWN_ROUTING_WORKER_REPRO==="true"?{}:{ forwardRoundsOnly: true })
originalEffects ? { originalEffectsOnly: true, controllerFailoverOnly } : process.env.MMAPP_OWN_ROUTING_WORKER_REPRO==="true"?{}:{ forwardRoundsOnly: true })
assert.equal(result.accepted, true)
} finally {
await (await import("../../services/scheduler.js")).stopSchedulerForDatabaseOperation()
@@ -154,6 +154,25 @@ for (const mutation of ["duplicate-config", "wrong-config-id", "unresolved-templ
assert.equal(f.parser.parseBgp("peer1", raw).status, "unknown")
})
for (const ipv6 of [false, true]) test("BGP runtime context can come from both exact qualified " + (ipv6 ? "IPv6" : "IPv4") + " endpoints", () => {
const f = fixture(ipv6), raw = structuredClone(f.bgp) as unknown as RawMutation, session = raw.payload[0]
const local = session["local.address"], remote = session["remote.address"]
delete session.vrf
session["local.address"] = `${local}@main`
session["remote.address"] = `${remote}@main`
const observation = f.parser.parseBgp("peer1", raw)
assert.equal(observation.status, "observed", JSON.stringify(observation))
assert.equal(observation.securityProof, false)
for (const mutation of [
{ "remote.address": remote }, { "remote.address": `${remote}@tenant` },
{ "remote.address": `${remote}@main@main` }, { "routing-table": "main" },
{ vrf: "tenant" }, { vrf: null },
]) {
assert.equal(f.parser.parseBgp("peer1", { ...raw, payload: [{ ...session, ...mutation }] }).status, "unknown")
}
assert.equal(f.parser.parseBgp("peer1", { ...raw, payload: [session, { ...session, ".id": "*B3" }] }).status, "unknown")
})
test("native cached non-established BGP cannot invent a model FSM state from an undocumented field", () => {
const f = fixture(), raw = structuredClone(f.bgp) as unknown as RawMutation
raw.payload[0].established = "false"
@@ -2,6 +2,7 @@ import { isIP } from "node:net"
import { z } from "zod"
import { canonicalBgpPolicyPrefix } from "../../services/bgp-community-policy-model.js"
import { captureRoutingNetworkManifest, type RoutingNetworkRound } from "./routing-network-verifier-model.js"
import { matchesBgpSessionContext, parseRoutingEndpoint } from "./routing-native-endpoint.js"
/** Pure decoded-response parsers, NOT source authentication or completeness
* proof. Only the explicit RouterOS7.20–7.26 field subset below is recognized.
@@ -32,11 +33,8 @@ function canonicalAddress(value: unknown): string {
return canonicalBgpPolicyPrefix(text + "/" + (family === 4 ? 32 : 128)).split("/")[0]
}
function endpoint(value: unknown) {
const text = literal(value), match = /^([^%@/,\s]+)(?:\/(\d+))?(?:%([^%@/,\s]+))?(?:@([^%@/,\s]+))?$/.exec(text)
if (!match) return fail("unsupported-endpoint")
const address = canonicalAddress(match[1])
if (match[2] !== undefined && match[2] !== String(isIP(address) === 4 ? 32 : 128)) return fail("unsupported-peer-range")
return { address, interface: match[3], vrf: match[4] }
const parsed = parseRoutingEndpoint(value)
return { ...parsed, address: canonicalAddress(parsed.address) }
}
function decodedRows(payload: unknown, maximum = 1000, ids = true): Row[] {
let nodes = 0
@@ -144,7 +142,7 @@ export function captureRoutingNetworkNativeParser(rawManifest: unknown) {
if (instance !== wanted.instance) continue
if (local.address !== wanted.localAddress || remote.address !== wanted.remoteAddress) continue
if (integer(row["remote.as"], 4294967295) !== wanted.remoteAsn || !afi(row["remote.afi"]).includes(expectedAfi) || !afi(row["local.afi"]).includes(expectedAfi)) return unknown("bgp-session-asn-or-afi-drift")
if (row.vrf !== binding.vrf || row["routing-table"] !== binding.table || [local.vrf, remote.vrf].some(vrf => vrf !== undefined && vrf !== binding.vrf) || local.interface !== binding.local.interface || remote.interface !== binding.remote.interface) return unknown("bgp-session-context-drift")
if (!matchesBgpSessionContext(row, binding, local, remote) || local.interface !== binding.local.interface || remote.interface !== binding.remote.interface) return unknown("bgp-session-context-drift")
relevant.push(row)
}
if (relevant.length !== 1) return unknown("missing-or-ambiguous-bgp-session")
@@ -7,7 +7,9 @@ const require=createRequire(new URL('../../../package.json',import.meta.url)),ts
const hash=value=>createHash('sha256').update(JSON.stringify(value)).digest('hex'),sign=async(value,purpose)=>hash([purpose,value]);
const code=ts.transpileModule(await readFile(new URL('./routing-controller-baseline.ts',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022}}).outputText;
const effectCode=ts.transpileModule(await readFile(new URL('./routing-original-effects.ts',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022}}).outputText,effectExports={};
new Function('exports','require',effectCode)(effectExports,name=>{if(name==='node:net')return require('node:net');if(name==='zod')return{z};if(name==='./security.js')return{fingerprint:hash};if(name==='./routing-community-context-model.js')return{};throw Error(name);});
const endpointCode=ts.transpileModule(await readFile(new URL('./routing-native-endpoint.ts',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022}}).outputText,endpointExports={};
new Function('exports','require',endpointCode)(endpointExports,require);
new Function('exports','require',effectCode)(effectExports,name=>{if(name==='node:net')return require('node:net');if(name==='zod')return{z};if(name==='./security.js')return{fingerprint:hash};if(name==='./routing-community-context-model.js')return{};if(name==='./routing-native-endpoint.js')return endpointExports;throw Error(name);});
const preparedValue={status:'prepared',revision:1,serverId:1,routeSelectionScope:'table-afi-community-observation',candidateId:'b',family:'ipv4',table:'tenant',community:'65000:10',expectedGateway:'192.0.2.9',expectedImmediate:{address:'198.51.100.2',interface:'ether2'},binding:{connectionId:'*c',sessionId:'*s',instance:'default',table:'tenant',vrf:'main',localAddress:'192.0.2.1',remoteAddress:'192.0.2.2',remoteAsn:65001,afi:'ip'},bfd:{applicability:'not-configured',evidence:'explicit-use-bfd-false'},routes:[{nativeId:'*r',prefix:'203.0.113.0/24',originalGateway:'192.0.2.8'}],probe:{key:'b',serverId:1,destination:'198.51.100.20',source:'198.51.100.10',interface:'wan',probeVrf:'probe',expectedHops:['198.51.100.20']}};
async function fixture(selection='absent',effectStatus='observed-expected',switched=true){
const principal={connectionId:randomUUID(),credentialId:randomUUID(),credentialExpiresAt:new Date(Date.now()+120000).toISOString()},profileId=randomUUID(),planId=randomUUID(),operationId=randomUUID(),grant=new Date(Date.now()+60000).toISOString();
@@ -6,9 +6,11 @@ import { isIP } from 'node:net';
import { randomUUID, createHash } from 'node:crypto';
const require=createRequire(new URL('../../../package.json',import.meta.url)), ts=require('typescript'),{z}=require('zod');
const source=await readFile(new URL('./routing-original-effects.ts',import.meta.url),'utf8');
const exports={};
const exports={}, endpointExports={};
const endpointSource=await readFile(new URL('./routing-native-endpoint.ts',import.meta.url),'utf8');
new Function('exports','require',ts.transpileModule(endpointSource,{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022}}).outputText)(endpointExports,require);
const gateway=value=>{const match=/^([^@%\s,]+)(?:%([^@%\s,]+))?(?:@([^@%\s,]+))?$/.exec(value);if(!match||!isIP(match[1]))throw Error();return {address:match[1],family:isIP(match[1]),interface:match[2]??null,resolverTable:match[3]??'main'};};
const providers={ 'node:net':{isIP},'node:crypto':{randomUUID},zod:{z},'./routing-community-context-model.js':{routeGatewayContext:gateway},'./security.js':{fingerprint:value=>createHash('sha256').update(JSON.stringify(value)).digest('hex')},
const providers={ 'node:net':{isIP},'node:crypto':{randomUUID},zod:{z},'./routing-community-context-model.js':{routeGatewayContext:gateway},'./routing-native-endpoint.js':endpointExports,'./security.js':{fingerprint:value=>createHash('sha256').update(JSON.stringify(value)).digest('hex')},
'./path-verification.js':{inspectControlPing:rows=>{const row=rows.at(-1),sent=Number(row.sent),received=Number(row.received);return {confirmedFailure:sent===3&&received===0,ping:{measured:sent===3&&Number.isInteger(received)&&received>=0&&received<=3,loss:(sent-received)/sent*100}};},
inspectTrace:(rows,destination,expected)=>({verified:Array.isArray(rows)&&rows.at(-1)?.address===destination&&expected.every(x=>rows.some(r=>r.address===x))})}};
new Function('exports','require',ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022}}).outputText)(exports,name=>{assert.ok(providers[name],name);return providers[name];});
@@ -26,11 +28,33 @@ function fixture(){
}
test('actual captured predicate seals BGP destinations separately from static resolver ID',()=>{const f=fixture();assert.equal(f.selection.status,'prepared');assert.equal(f.selection.routes[0].nativeId,'*r');assert.notEqual(f.selection.routes[0].nativeId,f.raw.candidate['.id']);assert.equal(f.selection.binding.sessionId,'*s');assert.equal('sessionKey'in f.selection.routes[0],false);});
test('two real effect captures can observe expected FIB/adjacency/probe while logcoverage and stronger claims stay false',async()=>{const f=fixture(),result=await f.inspect([f.sample(),f.sample()]);assert.equal(result.status,'observed-expected');assert.equal(result.logCoverage,'unknown');assert.equal(result.routeOriginVerified,false);assert.equal(result.recursiveChainVerified,false);assert.equal(result.forwardingVerified,false);assert.equal(result.autoRecoveryAllowed,false);assert.equal(result.rounds[0].relatedTopicRows,1);});
function qualifyRuntimeSession(row) {
delete row.vrf;
row['local.address'] += '@main';
row['remote.address'] += '@main';
}
test('BGP session uses exact runtime endpoint qualifiers when VRF is absent and the installation table is separate',async()=>{
const f=fixture();
qualifyRuntimeSession(f.raw.sessions[0]);
const selection=f.prepare();
assert.equal(selection.status,'prepared');
assert.equal(selection.binding.vrf,'main');
assert.equal(selection.binding.table,'tenant');
const samples=[f.sample(),f.sample()];
const report=await exports.inspectOriginalEffectRounds(selection,samples,f.baseline);
assert.equal(report.status,'observed-expected');
assert.equal(report.routeOriginVerified,false);
});
for(const [name,change]of[
['missing affected BGP route',f=>{f.raw.routes=[];}],['ambiguous prefix',f=>{f.raw.routes.push({...f.raw.routes[0],'.id':'*r2'});}],
['connected resolver is not affected BGP route',f=>{f.raw.routes[0].bgp='false';f.raw.routes[0].connect='true';}],
['unresolved inheritance',f=>{f.raw.connections[0].templates='template';}],['BFD not explicitly known',f=>{delete f.raw.connections[0]['use-bfd'];}],
['router-selected source retained as unsupported effect subset',f=>{delete f.raw.probe.source;}],['mixed session identity',f=>{f.raw.sessions.push({...f.raw.sessions[0],'.id':'*s2'});}],
['implicit VRF without both endpoint qualifiers',f=>{qualifyRuntimeSession(f.raw.sessions[0]);f.raw.sessions[0]['local.address']='192.0.2.1';}],
['qualified endpoints in the installation table',f=>{qualifyRuntimeSession(f.raw.sessions[0]);f.raw.sessions[0]['remote.address']='192.0.2.2@tenant';}],
['contradictory explicit VRF',f=>{qualifyRuntimeSession(f.raw.sessions[0]);f.raw.sessions[0].vrf='tenant';}],
['malformed peer ASN',f=>{f.raw.sessions[0]['remote.as']='0xfde9';}],
['duplicate native ID even with unrelated tuple',f=>{f.raw.sessions.push({...f.raw.sessions[0],instance:'unrelated'});}],
['noncanonical AFI prefix',f=>{f.raw.routes[0]['dst-address']='2001:db8::/64';}]
])test(`prepared ambiguity/unsupported remains unknown: ${name}`,()=>{const f=fixture();change(f);assert.equal(f.prepare().status,'unknown');});
test('baseline binds saved route IDs/prefix/gateway and does not infer operation UUID',()=>{const f=fixture(),base=f.sample();base.servers[0].routes.payload=structuredClone(f.raw.routes);assert.equal(exports.originalEffectBaselineMatches(f.selection,base),true);base.servers[0].routes.payload[0]['.id']='*different';assert.equal(exports.originalEffectBaselineMatches(f.selection,base),false);});
@@ -2,6 +2,7 @@ import { isIP } from "node:net"
import { z } from "zod"
import type { RouteAiProfile } from "@mmapp/contracts/mcp-routing"
import { routeGatewayContext } from "./routing-community-context-model.js"
import { matchesBgpSessionContext, parseRoutingEndpoint } from "./routing-native-endpoint.js"
import { fingerprint } from "./security.js"
type Row = Record<string, unknown>
@@ -43,10 +44,27 @@ export type OriginalEffectReport = z.infer<typeof originalEffectReportSchema>
export const unknownOriginalEffects = (reason: string): OriginalEffectReport => ({ scope: "prepared-route-fib-adjacency-control-effects", status: "unknown", reason,
rounds: [], logSource: "routeros-rest-ring", logCoverage: "unknown", selectionIdentity: null, routeSelectionScope: "table-afi-community-observation", transitionAttribution: "unproven", switchEffectObserved: false, semanticProof: false, routeOriginVerified: false, recursiveChainVerified: false, forwardingVerified: false, autoRecoveryAllowed: false })
function tuple(row: Row, expected: Prepared["binding"], session: boolean) {
function connectionMatches(row: Row, expected: Prepared["binding"]) {
return row.instance === expected.instance && row["routing-table"] === expected.table && row.vrf === expected.vrf &&
row["local.address"] === expected.localAddress && row["remote.address"] === expected.remoteAddress && Number(row["remote.as"]) === expected.remoteAsn &&
(session ? row["local.afi"] === expected.afi && row["remote.afi"] === expected.afi : row.afi === expected.afi)
row["local.address"] === expected.localAddress && row["remote.address"] === expected.remoteAddress &&
(row["remote.as"] === expected.remoteAsn || row["remote.as"] === String(expected.remoteAsn)) &&
row.afi === expected.afi
}
function selectBgpSession(rows: Row[], expected: Prepared["binding"]) {
try {
let match: Row | undefined
for (const row of rows) {
if (row.instance !== expected.instance) continue
const local = parseRoutingEndpoint(row["local.address"]), remote = parseRoutingEndpoint(row["remote.address"])
if (local.address !== expected.localAddress || remote.address !== expected.remoteAddress) continue
if (match || local.interface !== undefined || remote.interface !== undefined || !matchesBgpSessionContext(row, expected, local, remote) ||
(row["remote.as"] !== expected.remoteAsn && row["remote.as"] !== String(expected.remoteAsn)) || row["local.afi"] !== expected.afi || row["remote.afi"] !== expected.afi ||
row.state !== undefined || flag(row.established) === undefined || !id.safeParse(row[".id"]).success) return undefined
match = row
}
return match && unique(rows, String(match[".id"])).length === 1 ? match : undefined
} catch { return undefined }
}
function selectedRows(rows: Row[], selection: Pick<Prepared, "table" | "family" | "community">) {
return rows.filter(row => row["routing-table"] === selection.table && family(row) === selection.family && flag(row.bgp) === true && communities(row).includes(selection.community))
@@ -69,10 +87,10 @@ export function prepareOriginalEffectSelection(profile: RouteAiProfile, candidat
const peer = connection[0], afi = profile.family === "ipv4" ? "ip" : "ipv6"
const wanted = tupleSchema.parse({ connectionId: peer[".id"], sessionId: "*0", instance: binding.instance, table: binding.table, vrf: binding.vrf,
localAddress: peer["local.address"], remoteAddress: peer["remote.address"], remoteAsn: Number(peer["remote.as"]), afi })
if (!tuple(peer, wanted, false)) throw Error()
const sessions = raw.sessions.filter(row => tuple(row, wanted, true))
if (sessions.length !== 1 || flag(sessions[0].established) === undefined) throw Error()
wanted.sessionId = id.parse(sessions[0][".id"])
if (!connectionMatches(peer, wanted)) throw Error()
const session = selectBgpSession(raw.sessions, wanted)
if (!session) throw Error()
wanted.sessionId = id.parse(session[".id"])
const affected = selectedRows(raw.routes, profile)
if (!affected.length || affected.length > 32 || new Set(affected.map(row => row["dst-address"])).size !== affected.length || new Set(affected.map(row => row[".id"])).size !== affected.length) throw Error()
for (const row of affected) {
@@ -130,10 +148,10 @@ export async function inspectOriginalEffectRounds(rawSelection: unknown, samples
return { prefix: wanted.prefix, status }
})
const connections = unique(source.bgp.connectionsPayload, selection.binding.connectionId)
const sessions = source.bgp.payload.filter(row => tuple(row, selection.binding, true))
const session = selectBgpSession(source.bgp.payload, selection.binding)
let bgp: z.infer<typeof state> = "unknown"
if (connections.length === 1 && tuple(connections[0], selection.binding, false) && flag(connections[0].disabled) === false && flag(connections[0]["use-bfd"]) === false &&
sessions.length === 1 && sessions[0][".id"] === selection.binding.sessionId && flag(sessions[0].established) !== undefined) bgp = flag(sessions[0].established) ? "observed-expected" : "observed-other"
if (connections.length === 1 && connectionMatches(connections[0], selection.binding) && flag(connections[0].disabled) === false && flag(connections[0]["use-bfd"]) === false &&
session?.[".id"] === selection.binding.sessionId) bgp = flag(session.established) ? "observed-expected" : "observed-other"
const probe = sample.probes.find(row => row.key === selection.probe.key)
let controlProbe: "passed" | "failed" | "unknown" = "unknown"
if (probe) {
+31 -14
View File
@@ -9,7 +9,7 @@ import { pool } from "../../db/index.js"
import { registerMcpService } from "./service-registry.js"
import { accessGeneration, McpError } from "./security.js"
import { audit, validatePrincipal, type McpPrincipal } from "./store.js"
import { decideRoutingSwitch, type ControllerState, type PathHealth, type rankRoutingCandidates } from "./routing-model.js"
import { decideRoutingSwitch, selectFailoverReserveProbes, type ControllerState, type PathHealth, type rankRoutingCandidates } from "./routing-model.js"
import type { add } from "./actions.js"
import { COMMUNITY_PATH_MAX_AGE_MS } from "./path-proof-purpose.js"
import { controllerProfileCurrent, publishControllerState, saveControllerProfileCas, withControllerProfileLease } from "./routing-controller-fence.js"
@@ -61,7 +61,7 @@ export function registerRoutingProfileActions(register: typeof add) {
})
}
interface PersistentController extends ControllerState { baseline?:RoutingControllerBaseline; planId?: string; candidateId?: string; expectedCandidateId?: string; reason?: string; checkedAt?: string; probedAt?: string }
interface PersistentController extends ControllerState { baseline?:RoutingControllerBaseline; planId?: string; candidateId?: string; expectedCandidateId?: string; reason?: string; checkedAt?: string; probedAt?: string; failoverReserveCursor?: string }
/** Also fenced per profile so direct/concurrent ticks cannot publish stale state. */
export async function tickRoutingProfiles() {
const { invokeMcpTool, applyPlan } = await import("./runtime.js")
@@ -95,6 +95,7 @@ export async function tickRoutingProfiles() {
next.lastSwitchAt = at; next.switches = [...(state.switches ?? [])]; next.consecutive = 0
next.expectedCandidateId = state.candidateId
delete next.planId; delete next.candidateId; delete next.pendingCandidateId; delete next.operationId
delete next.failoverReserveCursor
next.reason = "Изменение конфигурации проверено; ожидаются новые измерения сети"
} else if (plan.operation_id) next.reason = "Операция выполняется"
else if (plan.expires_at.getTime() <= Date.now()) { await stop("План истёк без подтверждения"); return }
@@ -111,26 +112,42 @@ export async function tickRoutingProfiles() {
const analysis = await invokeMcpTool(principal, "mm_route_optimizer_analyze", { profile }) as { ranking: ReturnType<typeof rankRoutingCandidates>; currentCandidateId: string | null }
if (state.expectedCandidateId && analysis.currentCandidateId !== state.expectedCandidateId) { await stop("Наблюдаемый путь изменился вне ожидаемого переключения; требуется проверка вмешательства или дрейфа"); return }
if (analysis.currentCandidateId) next.expectedCandidateId = analysis.currentCandidateId
const health: PathHealth[] = []
const selected = [analysis.currentCandidateId, ...analysis.ranking.filter(value => value.eligible).slice(0, 2).map(value => value.candidate.id)]
if (profile.candidates.some(candidate => candidate.controlProbe) && !connection.policy.scope.operationIds.includes("routing.path.verify")) { await stop("Не выдано право контрольной проверки пути"); return }
for (const candidateId of [...new Set(selected)].filter((id): id is string => !!id)) {
const probeCandidate = async (candidateId: string): Promise<PathHealth | undefined> => {
if (!profile.candidates.find(candidate => candidate.id === candidateId)?.controlProbe) return
await current()
if (profile.candidates.find(candidate => candidate.id === candidateId)?.controlProbe) health.push(await invokeMcpTool(principal, "mm_route_path_verify", { profile, candidateId }) as PathHealth)
return await invokeMcpTool(principal, "mm_route_path_verify", { profile, candidateId }) as PathHealth
}
const currentHealth = analysis.currentCandidateId ? await probeCandidate(analysis.currentCandidateId) : undefined
const health = currentHealth ? [currentHealth] : []
const failoverProbes = analysis.currentCandidateId && currentHealth?.status === "failed"
? selectFailoverReserveProbes(analysis.ranking, analysis.currentCandidateId, state.failoverReserveCursor) : undefined
const candidates = failoverProbes?.candidateIds ?? analysis.ranking.filter(value => value.eligible).slice(0, 2)
.map(value => value.candidate.id).filter(id => id !== analysis.currentCandidateId)
for (const candidateId of candidates) {
const observed = await probeCandidate(candidateId)
if (observed) health.push(observed)
}
await assertRoutingControllerBaseline(state.baseline,row.id,row.version,profile,row.grant_expires_at.toISOString(),{principal,connection})
const charges = await createRoutingReservationStore().readHourlyCharges(row.id, principal)
await current()
const decision = decideRoutingSwitch(profile, state, analysis.ranking, analysis.currentCandidateId, Date.now(), health, charges.totalCharges)
Object.assign(next, decision.state, { reason: decision.reason })
next.probedAt = new Date().toISOString()
if (decision.state.pausedReason) { await stop(decision.state.pausedReason); return }
const hasFreshSelectedProbe = health.some(probe => {
if (probe.candidateId !== decision.switchTo || probe.status !== "passed") return false
const age = Date.now() - Date.parse(probe.observedAt)
const decisionAt = Date.now()
const hasFreshPassedProbe = (candidateId: string | null) => health.some(probe => {
if (probe.candidateId !== candidateId || probe.status !== "passed") return false
const age = decisionAt - Date.parse(probe.observedAt)
return age >= 0 && age < COMMUNITY_PATH_MAX_AGE_MS
})
if (decision.switchTo && usesScopedRouteAiContext(profile) && !hasFreshSelectedProbe) {
const decision = decideRoutingSwitch(profile, state, analysis.ranking, analysis.currentCandidateId, decisionAt, health, charges.totalCharges)
Object.assign(next, decision.state, { reason: decision.reason })
if (!failoverProbes?.cursor) delete next.failoverReserveCursor
else if (!hasFreshPassedProbe(failoverProbes.cursor)) {
// Advance past failed/unknown reserves. Keep rechecking a passing
// reserve while the current path accumulates independent failures.
next.failoverReserveCursor = failoverProbes.cursor
}
next.probedAt = new Date().toISOString()
if (decision.state.pausedReason) { await stop(decision.state.pausedReason); return }
if (decision.switchTo && usesScopedRouteAiContext(profile) && !hasFreshPassedProbe(decision.switchTo)) {
next.reason = "Ожидается успешная контрольная проба выбранного пути"
} else if (decision.switchTo) {
await current()
@@ -14,8 +14,10 @@ try {
issuedAt: Date.now() - 1000, expiresAt: Date.now() + 900000 }
await (await import("./store.js")).updateMcpSettings({ enabled: true }, actor)
await import("./actions.js")
const mixed = await (await import("./routing-community-scoped-acceptance.js")).acceptScopedRouteCommunitySwitch(actor,
{ manualInverseChargeOnly: true, manualInverseChargeCase: "mixed-forward" })
const { acceptScopedRouteCommunitySwitch } = await import("./routing-community-scoped-acceptance.js")
const inverse = await acceptScopedRouteCommunitySwitch(actor, { manualInverseChargeOnly: true })
console.log("private routing v8 manual inverse charge and intent SQL acceptance:", JSON.stringify(inverse))
const mixed = await acceptScopedRouteCommunitySwitch(actor, { manualInverseChargeOnly: true, manualInverseChargeCase: "mixed-forward" })
console.log("private routing mixed forward/manual inverse admission SQL acceptance:", JSON.stringify(mixed))
} finally {
await (await import("../../services/scheduler.js")).stopSchedulerForDatabaseOperation()
+36 -5
View File
@@ -1,4 +1,6 @@
import { pollErrorLog } from "../../services/server-poll-error-provenance.js"
import { vrfPreparationDiagnostic } from "./vrf-preparation-diagnostic.js"
import { createVrfRuntimeDiagnosticBoundary } from "../../services/vrf-execution-diagnostic.js"
import { capturePublishedServerProbeTerminalProof } from "../../services/server-probe-operation-retirement.js"
import { SERVER_PROBE_OPERATION } from "../../services/server-probe-authority.js"
import { preparedPlanExpiry } from "./plan-expiry.js"
@@ -13,6 +15,7 @@ import { logSettingsPatchSchema } from "@mmapp/contracts"
import { pool } from "../../db/index.js"
import { hasPermission, type AuthUser } from "../../lib/permissions.js"
import { createUser, updateUser, deleteUser, addBinding, removeBinding, getUserById } from "../users/service/users-service.js"
import { normalizeBindingPeer } from "../users/peer-bind.js"
import { getLogSettings, updateLogSettings } from "../../services/router-logs-collector.js"
import { refreshScheduler } from "../../services/scheduler.js"
import { withApplicationMutationLock, withConfigMutationLock } from "../../services/config-mutation-lock.js"
@@ -20,7 +23,7 @@ import { withOperationConfigurationLockClient, assertOperationConfigurationLockS
import { sharedDatabaseGate } from "../../services/shared-database-gate.js"
import { withRuntimePollPrincipalSource, executeRuntimePollPolicyTransaction, type RuntimePollPolicyLoan } from "./runtime-poll-principal-boundary.js"
import { readPollRuntimePolicySource, type PollRuntimePolicySource } from "./poll-runtime-policy-source.js"
import { withVerifiedConfigurationChange } from "../../services/config-mutation-policy.js"
import { withVerifiedConfigurationChange, assertVerifiedConfigurationAccess } from "../../services/config-mutation-policy.js"
import { beginMcpOperationAdmission, insertMcpOperationAdmission, retireMcpOperationAdmission, withMcpOperationExecutionOrigin, stripMcpOperationExecutionPrivateResult, type McpOperationAdmission } from "./operation-execution-origin.js"
import { createOspfOwnerSourceGuard, verifyOspfOwnerGraph, verifyOspfOwnerGraphAtPhase } from "./ospf-owner-graph.js"
import { evaluateMcpPolicy } from "./policy.js"
@@ -78,6 +81,12 @@ async function policyInput(client: Pick<PoolClient, "query">, connection: Connec
usage: { callsInMinute: Number(usage.calls), mutationsInHour: Number(usage.mutations), concurrentReads: Number(usage.reads) }, auditAvailable: true,
}
}
export async function readMcpPolicyPreviewInput(connection: ConnectionRow, input: Pick<McpPolicyPreviewRequest, "operationId" | "target" | "objects" | "objectCount">): Promise<McpPolicyPreviewRequest> {
const current = await policyInput(pool, connection, input.operationId, input.target)
return { ...current, objects: input.objects, objectCount: input.objectCount }
}
async function temporaryScope(client: Pick<PoolClient, "query">, connection: ConnectionRow, credentialId: string) {
const { rows } = await client.query("SELECT payload FROM mcp_grants WHERE connection_id=$1 AND revoked_at IS NULL AND payload->>'credentialId'=$2", [connection.id, credentialId])
if (!rows.length) return undefined
@@ -127,6 +136,7 @@ async function invokeMcpToolInner(principal: McpPrincipal, toolName: string, raw
const call = await reserveCall(principal, toolName, input, signal)
const cancelled = () => logsFollowMaintenance && logsFollowCancellation(logsFollowMaintenance, signal)
const assertActive = () => { const failure = cancelled(); if (failure) throw failure }
let vrfPreparing = false
try {
assertActive()
if (logsFollowMaintenance) call.context.logsFollowMaintenance = logsFollowMaintenance
@@ -137,6 +147,7 @@ async function invokeMcpToolInner(principal: McpPrincipal, toolName: string, raw
let result: unknown
if (action.read) result = await action.read(input, call.context)
else if (action.prepare) {
vrfPreparing = ["ros.vrf.create", "ros.vrf.update", "ros.vrf.delete"].includes(action.operation.id)
const evidence = await action.prepare(input, call.context)
result = await transaction(async client => {
await client.query("SELECT id FROM mcp_connections WHERE id=$1 FOR UPDATE", [principal.connectionId])
@@ -184,6 +195,7 @@ async function invokeMcpToolInner(principal: McpPrincipal, toolName: string, raw
await audit(client, connection.owner_id, "plan.create", connection.id, { planId: id, operationId: action.operation.id, decision })
return { planId: id, expiresAt: expiresAt.toISOString(), state: decision.decision === "approval-required" ? "awaiting-approval" : "draft", decision, changes: redact(publicMcpChangeEvidence(action.operation.id, evidence)), ...(vrfTicket ? { vrfTicket } : {}), executionAvailable: true }
})
vrfPreparing = false
} else throw new McpError("UNSUPPORTED_CAPABILITY", "Нет обработчика операции", 409)
assertActive()
const current = await effectiveMcpConnection(principal)
@@ -194,6 +206,12 @@ async function invokeMcpToolInner(principal: McpPrincipal, toolName: string, raw
assertActive()
return output
} catch (error) {
if (vrfPreparing) {
try {
const diagnostic = vrfPreparationDiagnostic(call.requestId, action.operation.id, error)
if (diagnostic) console.error(JSON.stringify(diagnostic))
} catch { /* Diagnostics must never replace the original failure. */ }
}
const failure = cancelled() ?? error
await completeRequest(call.requestId, started, null, failure)
throw failure
@@ -262,7 +280,7 @@ async function serviceExecute(service: string, input: Record<string, unknown>, c
if (service === "users.create") return createUser(appUserCreateSchema.parse(input.user))
if (service === "users.update") return updateUser(String(input.id), appUserUpdateSchema.parse(input.user))
if (service === "users.delete") return deleteUser(String(input.id))
if (service === "users.binding_add") return addBinding(String(input.id), userBindingCreateSchema.parse(input.binding))
if (service === "users.binding_add") return addBinding(String(input.id), userBindingCreateSchema.parse(input.binding), { assertCurrent: assertVerifiedConfigurationAccess })
if (service === "users.binding_remove") return removeBinding(String(input.id), String(input.bindingId))
if (service === "logs.settings.update") { const result = await updateLogSettings(logSettingsPatchSchema.parse(input.settings)); await refreshScheduler(); return result }
throw new McpError("UNSUPPORTED_CAPABILITY", "Неизвестный сервис", 409)
@@ -286,7 +304,11 @@ export async function verifyStep(step: ChangeStep, result: unknown, before?: Ros
if (step.service === "users.binding_remove") { const current = await getUserById(String(step.input.id)); return !!current && !current.bindings.some(binding => binding.id === step.input.bindingId) }
if (step.service === "users.binding_add") {
const binding = userBindingCreateSchema.parse(step.input.binding), current = await getUserById(String(step.input.id))
return !!current?.bindings.some(item => item.serverId === binding.serverId && item.interfaceName === binding.interfaceName && item.peerPublicKey === (binding.peerPublicKey ?? ""))
const createdId = result && typeof result === "object" ? (result as { id?: unknown }).id : undefined
return typeof createdId === "string" && !!current?.bindings.some(item => item.id === createdId
&& item.serverId === binding.serverId && item.interfaceName === binding.interfaceName.trim()
&& (binding.interfaceType === undefined || item.interfaceType === binding.interfaceType)
&& item.peerPublicKey === normalizeBindingPeer(item.interfaceType, binding.peerPublicKey))
}
if (step.service === "logs.settings.update") {
const current = await getLogSettings() as unknown as Record<string, unknown>
@@ -441,6 +463,7 @@ async function executeOperationWithLease(operationId: string, principal: McpPrin
const plan = await loadPlan(operation.plan_id), evidence = JSON.parse(await decryptSecret(plan.evidence.sealed)) as ChangeEvidence
const serverIds = evidence.target.scope === "servers" ? evidence.target.serverIds : evidence.objects.flatMap(object => object.serverId ? [object.serverId] : [])
let attempted = false, confirmed = 0, activeServiceStep = false
let vrfDiagnosticFallback: ReturnType<typeof createVrfRuntimeDiagnosticBoundary> | undefined
let reservedForwardPassed = false
let reservedRecoverySummary: Record<string, unknown> | undefined
const diagnosticOnly = evidence.steps.length === 1 && evidence.steps.every(step => step.kind === "service" && findMcpService(step.service)?.cancellableDiagnostic === true)
@@ -548,17 +571,23 @@ async function executeOperationWithLease(operationId: string, principal: McpPrin
originalExpiresAt:Math.min(plan.expires_at.getTime(),evidence.validUntil?Date.parse(evidence.validUntil):Infinity,Date.parse(principal.credentialExpiresAt),Date.parse(connection.policy.expiresAt),connection.owner_valid_until.getTime(),originalServiceGrant!.admissionExpiresAt),
serviceInput:step.input}:undefined
const reservedStep: { outcome?: ReservedRoutingStepOutcome<unknown> } = {}
vrfDiagnosticFallback = productionVrf && step.kind === "ros" && step.step.resource === "vrf" && ["ros.vrf.create", "ros.vrf.update", "ros.vrf.delete", "routing.vrf.update"].includes(plan.operation_id)
? createVrfRuntimeDiagnosticBoundary(operationId, step.step.action === "update" ? "patch" : step.step.action, diagnostic => { console.error(JSON.stringify(diagnostic)) }) : undefined
const result = await withVerifiedConfigurationChange({ actorId: connection.owner_id, connectionId: connection.id, serverIds, objects: evidence.objects, approved: !!plan.approved_by, serverWide: step.kind === "service", ...(serviceExecution?{serviceExecution}:{}), authorize: async () => { await (step.kind === "ros" ? authorizeCatalog() : authorize()) }, ...(step.kind === "ros" ? { beforeDispatch: async () => { await prefix!.check(authorizeCatalog); await authorize(); await authorizeCatalog(); if (productionVrf) { if (!vrfBeforeDispatch) throw new McpError("STATE_CONFLICT", "VRF command guard отсутствует", 409); await vrfBeforeDispatch() } } } : {}) },
async () => {
vrfDiagnosticFallback?.executorEntered()
if (step.kind === "ros") {
if (!productionVrf) return executeRosStep(step.step)
const before = evidence.snapshots.find(snapshot => snapshot.resource === "vrf" && snapshot.serverId === step.step.serverId)
if (!before?.sourceProof) throw new McpError("STATE_CONFLICT", "Нет VRF source-v3 proof", 409)
if (!["ros.vrf.create", "ros.vrf.update", "ros.vrf.delete", "routing.vrf.update"].includes(plan.operation_id)) throw new McpError("STATE_CONFLICT", "VRF action binding изменён", 409)
return executeVrfProductionStep({ operationId, planId: plan.id, connectionId: connection.id, ownerId: connection.owner_id,
const receipt = await executeVrfProductionStep({ operationId, planId: plan.id, connectionId: connection.id, ownerId: connection.owner_id,
operationName: plan.operation_id as "ros.vrf.create" | "ros.vrf.update" | "ros.vrf.delete" | "routing.vrf.update", operationVersion: plan.operation_version,
stepIndex: index, step: step.step, sourceProof: before.sourceProof, originalSnapshots: evidence.snapshots, authorize: authorizeCatalog,
assertDependencies: () => prefix!.check(authorizeCatalog), installBeforeDispatch: guard => { vrfBeforeDispatch = guard } })
assertDependencies: () => prefix!.check(authorizeCatalog), installBeforeDispatch: guard => { vrfBeforeDispatch = guard },
onDiagnostic: diagnostic => { vrfDiagnosticFallback?.observed(diagnostic) } })
vrfDiagnosticFallback?.executorReturned()
return receipt
}
const forward = () => serviceExecute(step.service, step.input, { operationId, phase: "forward", stepIndex: index, ...(routingReservationForward ? { routingReservationForward } : {}) })
if (!routingReservationId) return step.service === "servers.poll" ? withRuntimePollPrincipalSource(principal, async (current, policyLoan) => {
@@ -571,6 +600,7 @@ async function executeOperationWithLease(operationId: string, principal: McpPrin
reservedStep.outcome = await executeReservedRoutingStep({ reservationId: routingReservationId, sourceOperationId: operationId, principal, forward })
return reservedStep.outcome.forwardResult
})
vrfDiagnosticFallback = undefined
if (reservedStep.outcome?.kind === "recovered") {
// The generic source remains intent/result=null until the private
// inverse has finished. Record the forward ACK, never B VERIFIED
@@ -636,6 +666,7 @@ async function executeOperationWithLease(operationId: string, principal: McpPrin
assertOperationConfigurationLockCheckpoint()
if (receiptId && finishedAt) return { receiptId, operationId, connectionId:operation.connection_id, finishedAt }
} catch (error) {
vrfDiagnosticFallback?.failure(error)
if (routingReservationId && hasConfirmedReservedRoutingForward(error)) confirmed = Math.max(confirmed, 1)
if (error instanceof VrfProductionAcknowledgedFailure) confirmed = Math.max(confirmed, error.acknowledgedWrites)
const code = error instanceof VrfProductionClaimOutcomeUnknown ? "VRF_CLAIM_OUTCOME_UNKNOWN" : error instanceof McpError ? error.code : "DEVICE_UNAVAILABLE"
@@ -0,0 +1,15 @@
import assert from "node:assert/strict"
process.env.AUTH_REQUIRED = "true"
process.env.AUTH_JWT_SECRET = "users-bindings-owned-acceptance-secret"
const { pool, closePool } = await import("../../db/index.js")
const { applySqlMigrations } = await import("../../db/migrate.js")
const { updateMcpSettings } = await import("./store.js")
const actor = { id: "users-bindings-owner", email: "[email protected]", name: "User binding owner", apps: ["mm"], permissions: ["mm:settings:admin"], expiresAt: Date.now() + 3600000 }
try {
await applySqlMigrations(pool)
assert.equal((await pool.query("SELECT count(*)::int AS n FROM servers")).rows[0].n, 0, "Disposable empty database required")
await updateMcpSettings({ enabled: true }, actor)
await (await import("../../test/mcp-users-bindings.js")).verifyMcpUserBindings(actor)
} finally {
await closePool()
}
@@ -0,0 +1,97 @@
import assert from "node:assert/strict"
import { test } from "node:test"
import { vrfPreparationDiagnostic } from "./vrf-preparation-diagnostic.js"
const requestId = "12345678-1234-4123-8123-123456789abc"
const operationId = "ros.vrf.update"
function fixture(message = "VRF production transition refused: static address provenance/context", stack?: string) {
const error = new Error(message)
if (stack !== undefined) Object.defineProperty(error, "stack", { value: stack, configurable: true, writable: true })
return error
}
const stack = "Error: SECRET-PASSWORD 192.0.2.9 native-body\n at must (C:\\private\\backend\\src\\services\\vrf-production-transition.ts:80:82)\n at wrapped (C:\\private\\backend\\src\\modules\\mcp\\vrf-ticket-runtime.ts:76:9)"
test("plain Error at known refusal produces bounded first owned source, stage and constant reason", () => {
const diagnostic = vrfPreparationDiagnostic(requestId, operationId, fixture(undefined, stack))
assert.deepEqual(diagnostic, { event: "mcp.vrf.preparation-failed", requestId, operationId, stage: "transition", errorClass: "Error", firstOwnedFrame: { source: "vrf-production-transition", line: 80 }, reason: "static-address-context" })
for (const secret of ["SECRET-PASSWORD", "192.0.2.9", "private", "native-body", "must", "stack", "message"]) assert.ok(!JSON.stringify(diagnostic).includes(secret), secret)
})
test("real constructed Error with native stack never returns function names or raw text", () => {
const diagnostic = vrfPreparationDiagnostic(requestId, "ros.vrf.create", new Error("SECRET native payload"))!
assert.equal(diagnostic.errorClass, "Error"); assert.equal(diagnostic.reason, "other")
assert.ok(!JSON.stringify(diagnostic).includes("SECRET"))
const known = new Error("VRF production transition refused: dependency connected route identity")
const result = vrfPreparationDiagnostic(requestId, operationId, known)!
assert.equal(result.reason, "connected-route-identity"); assert.equal(result.stage, "transition")
// Native lazy stack accessors stay unmaterialized. No prepareStackTrace hook
// is needed to classify the actual own-data refusal message.
assert.equal(typeof Object.getOwnPropertyDescriptor(known, "stack")?.get, "function")
assert.equal(result.firstOwnedFrame, undefined)
})
test("exact known messages map to enums; appended secrets remain other", () => {
for (const [message, reason] of [
["VRF production ticket refused: original dependency projection changed during preparation", "original-dependency-projection"],
["VRF production transition refused: dependency connected route identity", "connected-route-identity"],
["VRF production transition refused: missing ordered main VRF", "main-vrf-context"],
["VRF production transition refused: main VRF shape", "main-vrf-context"],
]) {
assert.equal(vrfPreparationDiagnostic(requestId, operationId, fixture(message))!.reason, reason)
assert.equal(vrfPreparationDiagnostic(requestId, operationId, fixture(message + " SECRET"))!.reason, "other")
}
})
test("actual native Error unknown refusal suffix maps only reviewed stage without exposing secrets", () => {
for (const [prefix, stage] of [["VRF production read refused: ", "read"], ["VRF production admission refused: ", "admission"], ["VRF production transition refused: ", "transition"], ["VRF production ticket refused: ", "ticket"]]) {
const error = new Error(prefix + "SECRET-PASSWORD 192.0.2.9 native-body")
Object.defineProperty(error, "name", { get() { throw Error("SECRET name getter invoked") } })
const result = vrfPreparationDiagnostic(requestId, operationId, error)!
assert.equal(result.stage, stage); assert.equal(result.reason, "other"); assert.equal(result.firstOwnedFrame, undefined)
for (const secret of ["SECRET-PASSWORD", "192.0.2.9", "native-body", prefix]) assert.ok(!JSON.stringify(result).includes(secret))
}
const tooLong = fixture("VRF production read refused: " + "S".repeat(512))
assert.equal(vrfPreparationDiagnostic(requestId, operationId, tooLong)!.stage, "other")
})
test("proxy, prototype and toStringTag spoofing reject without triggering traps", () => {
let traps = 0
const fail = () => { traps++; throw Error("SECRET getter called") }
const proxy = new Proxy(fixture(), { get: fail, getPrototypeOf: fail, getOwnPropertyDescriptor: fail, ownKeys: fail })
const spoof = Object.create(Error.prototype) as object
Object.defineProperties(spoof, { message: { get: fail }, stack: { get: fail }, [Symbol.toStringTag]: { get: fail } })
for (const error of [proxy, spoof, { name: "Error", message: "SECRET", stack }]) assert.deepEqual(vrfPreparationDiagnostic(requestId, operationId, error), { event: "mcp.vrf.preparation-failed", requestId, operationId, stage: "other", errorClass: "NonError", reason: "other" })
assert.equal(traps, 0)
})
test("actual Error own accessors and constructor/name getters are never invoked", () => {
for (const field of ["message", "stack"]) {
const error = fixture(undefined, stack), calls = { count: 0 }
Object.defineProperty(error, field, { get() { calls.count++; throw Error("SECRET") } })
Object.defineProperty(error, "name", { get() { calls.count++; throw Error("SECRET") } })
Object.defineProperty(error, "constructor", { get() { calls.count++; throw Error("SECRET") } })
const diagnostic = vrfPreparationDiagnostic(requestId, operationId, error)!
assert.equal(diagnostic.reason, field === "stack" ? "static-address-context" : "other"); assert.equal(diagnostic.stage, field === "stack" ? "transition" : "other"); assert.equal(diagnostic.firstOwnedFrame, undefined)
assert.equal(calls.count, 0)
}
})
test("built-in error classes use prototype identity and subclasses remain a fixed enum", () => {
for (const [error, expected] of [[new TypeError("SECRET"), "TypeError"], [new RangeError("SECRET"), "RangeError"], [new SyntaxError("SECRET"), "SyntaxError"], [new (class SecretError extends Error {})("SECRET"), "OtherNativeError"]] as const) assert.equal(vrfPreparationDiagnostic(requestId, operationId, error)!.errorClass, expected)
})
test("nested Linux/Windows/compiled paths return source enums with bounded line only", () => {
for (const path of ["/app/dist/services/vrf-production-read.js", "file:///app/dist/services/vrf-production-read.js", "file:///C:/workspace/backend/src/services/vrf-production-read.ts", "C:\\workspace\\backend\\src\\services\\vrf-production-read.ts"]) {
const diagnostic = vrfPreparationDiagnostic(requestId, operationId, fixture("unexpected", `Error: SECRET\n at external (/tmp/node_modules/native.js:99:2)\n at closure (${path}:203:12)`))!
assert.equal(diagnostic.stage, "read"); assert.deepEqual(diagnostic.firstOwnedFrame, { source: "vrf-production-read", line: 203 })
assert.ok(!JSON.stringify(diagnostic).includes(path))
}
})
test("non-owned paths, wrong directories and invalid line numbers never pass through", () => {
for (const path of ["/app/dist/services/private-secret.ts:1:1", "/app/dist/other/vrf-production-read.ts:1:1", "/app/dist/services/vrf-production-read.ts:0:1", "/app/dist/services/vrf-production-read.ts:1000001:1", "https://secret.example/src/services/vrf-production-read.ts:1:1"]) assert.equal(vrfPreparationDiagnostic(requestId, operationId, fixture("unexpected", `Error: SECRET\n at run (${path})`))!.firstOwnedFrame, undefined)
})
test("stack scan has fixed byte/line bounds and never inspects error causes", () => {
const error = fixture("SECRET", "Error: SECRET\n" + " at external (/tmp/external.js:1:1)\n".repeat(70) + " at internal (/app/dist/services/vrf-production-transition.js:80:1)")
Object.defineProperty(error, "cause", { get() { throw Error("SECRET cause accessed") } })
assert.equal(vrfPreparationDiagnostic(requestId, operationId, error)!.firstOwnedFrame, undefined)
error.stack = "Error: " + "S".repeat(17000) + "\n at internal (/app/dist/services/vrf-production-transition.js:80:1)"
assert.equal(vrfPreparationDiagnostic(requestId, operationId, error)!.firstOwnedFrame, undefined)
})
test("nonerrors have no copied fields; non-VRF/non-UUID calls have no diagnostic", () => {
for (const error of [null, undefined, "SECRET", 42, Symbol("SECRET"), () => { throw Error("SECRET") }]) assert.equal(vrfPreparationDiagnostic(requestId, operationId, error)!.errorClass, "NonError")
for (const operation of ["ros.vrf.list", "routing.vrf.update", "mcp.operation.apply", "ros.bridge.update", "ros.vrf.update SECRET"]) assert.equal(vrfPreparationDiagnostic(requestId, operation, fixture()), undefined)
assert.equal(vrfPreparationDiagnostic("SECRET-not-a-uuid", operationId, fixture()), undefined)
})
@@ -0,0 +1,86 @@
import { types } from "node:util"
const ownedSources = {
"vrf-production-read": { directory: "services", stage: "read" },
"vrf-production-admission": { directory: "services", stage: "admission" },
"vrf-production-transition": { directory: "services", stage: "transition" },
"vrf-production-ticket-store": { directory: "services", stage: "ticket" },
"vrf-production-action-binding": { directory: "services", stage: "admission" },
"vrf-members": { directory: "services", stage: "read" },
"vrf-ticket-runtime": { directory: "modules/mcp", stage: "ticket" },
"resources": { directory: "modules/mcp", stage: "read" },
"actions": { directory: "modules/mcp", stage: "other" },
"runtime": { directory: "modules/mcp", stage: "runtime" },
} as const
type Source = keyof typeof ownedSources
type Stage = typeof ownedSources[Source]["stage"]
type Reason = "original-dependency-projection" | "static-address-context" | "connected-route-identity" | "main-vrf-context" | "other"
type ErrorClass = "Error" | "TypeError" | "RangeError" | "SyntaxError" | "ReferenceError" | "URIError" | "EvalError" | "OtherNativeError" | "NonError"
type Operation = "ros.vrf.create" | "ros.vrf.update" | "ros.vrf.delete"
export interface VrfPreparationDiagnostic {
event: "mcp.vrf.preparation-failed"; requestId: string; operationId: Operation;
stage: Stage; errorClass: ErrorClass;
firstOwnedFrame?: { source: Source; line: number };
reason: Reason;
}
// Only complete, reviewed constant refusals. No user/native text is copied and
// appending any text (including secrets) intentionally maps back to "other".
const reasons = new Map<string, Reason>([
["VRF production ticket refused: original dependency projection changed during preparation", "original-dependency-projection"],
["VRF production transition refused: static address provenance/context", "static-address-context"],
["VRF production transition refused: dependency connected route identity", "connected-route-identity"],
["VRF production transition refused: missing ordered main VRF", "main-vrf-context"],
["VRF production transition refused: main VRF shape", "main-vrf-context"],
])
const refusalStages: ReadonlyArray<readonly [string, Stage]> = [
["VRF production read refused: ", "read"],
["VRF production admission refused: ", "admission"],
["VRF production transition refused: ", "transition"],
["VRF production ticket refused: ", "ticket"],
]
const classes: Array<[object, ErrorClass]> = [
[Error.prototype, "Error"], [TypeError.prototype, "TypeError"], [RangeError.prototype, "RangeError"], [SyntaxError.prototype, "SyntaxError"],
[ReferenceError.prototype, "ReferenceError"], [URIError.prototype, "URIError"], [EvalError.prototype, "EvalError"],
]
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
function dataString(error: object, key: "message" | "stack"): string | undefined {
const descriptor = Object.getOwnPropertyDescriptor(error, key)
return descriptor && Object.hasOwn(descriptor, "value") && typeof descriptor.value === "string" ? descriptor.value : undefined
}
function ownedFrame(stack: string | undefined): VrfPreparationDiagnostic["firstOwnedFrame"] {
if (!stack) return undefined
// Bound work before splitting, and ignore the first error-message line.
for (const line of stack.slice(0, 16384).split(/\r?\n/).slice(1, 65)) {
if (line.length > 2048 || !/^\s+at\s/.test(line)) continue
const match = /(?:^|[ (])(?:file:\/\/)?(?:[A-Za-z]:[\\/]|\/)[^\r\n]*?[\\/](?:src|dist)[\\/](services|modules[\\/]mcp)[\\/]([a-z-]+)\.(?:ts|js):([1-9]\d{0,6}):[1-9]\d{0,6}\)?$/.exec(line)
if (!match || !Object.hasOwn(ownedSources, match[2])) continue
const source = match[2] as Source, lineNumber = Number(match[3])
if (match[1].replaceAll("\\", "/") !== ownedSources[source].directory || lineNumber > 1000000) continue
return { source, line: lineNumber }
}
return undefined
}
/** Pure bounded diagnostic. Never inspect arbitrary error getters/proxies,
* retain original objects, or expose messages, paths, addresses or stack text. */
export function vrfPreparationDiagnostic(requestId: string, operationId: string, error: unknown): VrfPreparationDiagnostic | undefined {
if (typeof requestId !== "string" || !uuid.test(requestId) || !["ros.vrf.create", "ros.vrf.update", "ros.vrf.delete"].includes(operationId)) return undefined
const result: VrfPreparationDiagnostic = { event: "mcp.vrf.preparation-failed", requestId, operationId: operationId as Operation, stage: "other", errorClass: "NonError", reason: "other" }
// isNativeError is an internal-slot check, unlike instanceof/toString. It
// rejects Proxy(Error) and prototype/toStringTag imitations without traps.
if (!types.isNativeError(error)) return result
result.errorClass = classes.find(([prototype]) => Object.getPrototypeOf(error) === prototype)?.[1] ?? "OtherNativeError"
const message = dataString(error, "message"), stack = dataString(error, "stack")
if (message !== undefined && message.length <= 512) {
result.reason = reasons.get(message) ?? "other"
result.stage = refusalStages.find(([prefix]) => message.startsWith(prefix))?.[1] ?? "other"
}
// Node 22 uses a native lazy stack accessor. We deliberately do not invoke
// it (nor Error.prepareStackTrace); exact own-message reasons still work.
if (message === undefined || stack === undefined) return result
const frame = ownedFrame(stack)
if (frame) { result.firstOwnedFrame = frame; result.stage = ownedSources[frame.source].stage }
return result
}
@@ -49,7 +49,7 @@ export async function prepareRuntimeVrfTicket(input: VrfRuntimeTicketInput, depe
const actionId = vrfNativeActionFor(input.operationId, request)
const context: PrepareVrfProductionTicketInput["context"] = { binding: { planId: input.planId, actorId: input.ownerId, serverId: native.serverId, sourceProof }, connectionId: input.connectionId, actionId,
actionVersion: input.operationId === "routing.vrf.update" ? Number(findMcpOperation(actionId)?.version) : input.operationVersion,
...(input.operationId === "routing.vrf.update" ? { authorityAction: { id: "routing.vrf.update" as const, version: input.operationVersion as 3 } } : {}) }
...(input.operationId === "routing.vrf.update" ? { authorityAction: { id: "routing.vrf.update" as const, version: input.operationVersion as 4 } } : {}) }
assertVrfActionContext(context, request); assertVrfAliasEvidence(context, request, evidence)
const authority = async () => {
await input.assertAuthority()
@@ -0,0 +1,26 @@
import type { UserBindingCreate } from "@mmapp/contracts/users"
import { getServerRowById } from "../servers/repository/servers-repository.js"
import { MikrotikClient } from "../../services/mikrotik.js"
import { sameWireguardEndpoint } from "../../services/wireguard-source.js"
import { ipsecClientBindingKeys, type IpsecServerState } from "../../services/ipsec-live.js"
import { bindingNativeRows, readBindingTarget, UserBindingTargetError } from "./binding-target.js"
export function readNativeUserBindingTarget(input: UserBindingCreate, options: { signal?: AbortSignal; assertCurrent?: () => Promise<unknown> } = {}) {
return readBindingTarget(input, async () => {
const server = await getServerRowById(input.serverId)
if (!server?.enabled) throw new UserBindingTargetError("Сервер отключён или не найден", 404)
const client = MikrotikClient.fromServer(server)
return {
async assertCurrent() {
const fresh = await getServerRowById(input.serverId)
if (!fresh || !sameWireguardEndpoint(fresh, server)) throw new UserBindingTargetError("Источник привязки изменился", 409)
},
get: (path, timeout, signal, maximum) => client.get(path, timeout, signal, maximum),
ipsecKeys: (certs, peers, identities) => ipsecClientBindingKeys({ server,
certs: bindingNativeRows(certs, [".id", "name"]) as IpsecServerState["certs"],
peers: bindingNativeRows(peers, [".id"]) as IpsecServerState["peers"],
identities: bindingNativeRows(identities, [".id"]) as IpsecServerState["identities"],
}),
}
}, options)
}
@@ -0,0 +1,61 @@
import assert from "node:assert/strict"
import { resolveBindingInterface, resolveBindingPeer, readBindingTarget, UserBindingTargetError } from "./binding-target.js"
const row = (name: string, type: string, id = "*1") => ({ ".id": id, name, type })
const refused = (status: number) => (error: unknown) => error instanceof UserBindingTargetError && error.status === status
let cases = 0
for (const [native, expected] of [["ether", "ether"], ["bridge", "bridge"], ["vlan", "vlan"], ["vxlan", "vxlan"], ["gre-tunnel", "gre"], ["wg", "wg"], ["wireguard", "wg"], ["dummy", "other"]]) {
const iface = resolveBindingInterface({ serverId: 1, interfaceName: "actual" }, [row("actual", native)])
assert.equal(iface.type, expected); cases++
}
for (const raw of [undefined, {}, [{ ".id": "*1", name: "ether-guess" }], [row("actual", "")], [row("actual", "ether", "*G1")], [row("actual", "ether"), row("duplicate-id", "ether")]]) {
assert.throws(() => resolveBindingInterface({ serverId: 1, interfaceName: "actual" }, raw), refused(502)); cases++
}
assert.throws(() => resolveBindingInterface({ serverId: 1, interfaceName: "missing" }, []), refused(404)); cases++
assert.throws(() => resolveBindingInterface({ serverId: 1, interfaceName: "actual" }, [row("actual", "ether"), row("actual", "ether", "*2")]), refused(409)); cases++
assert.throws(() => resolveBindingInterface({ serverId: 1, interfaceName: "actual", interfaceType: "ether" }, [row("actual", "wg")]), refused(409)); cases++
const wgInput = { serverId: 1, interfaceName: "wg-real", peerPublicKey: "actual-key" }
const wg = resolveBindingInterface(wgInput, [row("wg-real", "wg")])
const peer = { ".id": "*2", interface: "wg-real", "public-key": "actual-key", "preshared-key": "PRIVATE_VALUE" }
assert.equal(resolveBindingPeer(wgInput, wg, [peer]).peerPublicKey, "actual-key"); cases++
assert.equal(JSON.stringify(resolveBindingPeer(wgInput, wg, [peer])).includes("PRIVATE_VALUE"), false); cases++
for (const peers of [[], [{ ...peer, interface: "foreign" }], [{ ...peer, "public-key": "foreign" }]]) {
assert.throws(() => resolveBindingPeer(wgInput, wg, peers), refused(404)); cases++
}
assert.throws(() => resolveBindingPeer(wgInput, wg, [peer, { ...peer, ".id": "*3" }]), refused(409)); cases++
assert.throws(() => resolveBindingPeer({ ...wgInput, peerPublicKey: "" }, wg, [peer]), refused(400)); cases++
for (const key of ["client-cn", "managed-psk-name"]) {
const input = { serverId: 1, interfaceName: "ipsec-vpn", peerPublicKey: key }
const iface = resolveBindingInterface(input)
assert.equal(resolveBindingPeer(input, iface, undefined, ["client-cn", "managed-psk-name"]).peerPublicKey, key); cases++
assert.throws(() => resolveBindingPeer(input, iface, undefined, [key, key]), refused(409)); cases++
assert.throws(() => resolveBindingPeer(input, iface, undefined, []), refused(404)); cases++
}
let current = true, authority = true, nativeCalls = 0
const open = async () => ({
async assertCurrent() { if (!current) throw new UserBindingTargetError("Источник привязки изменился", 409) },
async get(path: string, timeout: number, signal: AbortSignal, maximum: number) {
assert(timeout > 0 && timeout <= 10000); assert.equal(maximum, 1048576); assert(signal instanceof AbortSignal)
nativeCalls++
return path === "/interface" ? [row("wg-real", "wg")] : [peer]
},
ipsecKeys() { return ["client-cn", "managed-psk-name"] },
})
const selected = await readBindingTarget(wgInput, open, { assertCurrent: async () => { assert(authority, "current authority") } })
assert.equal(nativeCalls, 2); cases++
current = false; await assert.rejects(selected.assertCurrent(), refused(409)); cases++
current = true; authority = false; await assert.rejects(selected.assertCurrent(), /current authority/); cases++
authority = true
await assert.rejects(readBindingTarget(wgInput, async () => ({ ...await open(), async get() { current = false; return [row("wg-real", "wg")] } })), refused(409)); cases++
current = true
const cancelled = new AbortController(); cancelled.abort()
await assert.rejects(readBindingTarget(wgInput, open, { signal: cancelled.signal })); cases++
const ipsecPaths: string[] = []
const psk = await readBindingTarget({ serverId: 1, interfaceName: "ipsec-vpn", peerPublicKey: "managed-psk-name" }, async () => ({
...await open(), async get(path) { ipsecPaths.push(path); return [] },
}))
assert.equal(psk.peerPublicKey, "managed-psk-name")
assert.deepEqual(ipsecPaths, ["/certificate", "/ip/ipsec/peer", "/ip/ipsec/identity"]); cases++
await assert.rejects(readBindingTarget(wgInput, async () => ({ ...await open(), async get() { throw Error("PRIVATE_UPSTREAM_BODY") } })), error =>
refused(502)(error) && !(error as Error).message.includes("PRIVATE_UPSTREAM_BODY")); cases++
console.log("User binding native selectors, eight types, peer keys, scope/source/authority and privacy cases:", cases)
@@ -0,0 +1,90 @@
import type { InterfaceType, UserBindingCreate } from "@mmapp/contracts/users"
import { mapRosInterfaceType } from "./iface-type.js"
import { normalizeBindingPeer, PeerBindError, peerDisplayName } from "./peer-bind.js"
import { nativeNetworkRows } from "../../services/network-observed-read.js"
export class UserBindingTargetError extends Error {
constructor(message: string, readonly status: 400 | 404 | 409 | 502) { super(message) }
}
export interface BindingInterface { ifaceName: string; type: InterfaceType; nativeId?: string }
export interface BindingTarget extends BindingInterface { peerPublicKey: string; peerName: string }
export function bindingNativeRows(raw: unknown, required: string[]) {
try {
const rows = nativeNetworkRows(raw, required)
if (rows.some(row => !/^\*[a-f0-9]+$/i.test(row[".id"]!))) throw new Error("native ID")
return rows
}
catch { throw new UserBindingTargetError("Не подтверждён native-каталог привязки.", 502) }
}
export function resolveBindingInterface(input: UserBindingCreate, raw?: unknown): BindingInterface {
const ifaceName = input.interfaceName.trim()
if (!ifaceName) throw new UserBindingTargetError("Имя интерфейса обязательно", 400)
let type: InterfaceType, nativeId: string | undefined
if (ifaceName === "ipsec-vpn") type = "ipsec"
else {
const rows = bindingNativeRows(raw, [".id", "name", "type"])
const matches = rows.filter(row => row.name === ifaceName)
if (!matches.length) throw new UserBindingTargetError("Интерфейс не найден", 404)
if (matches.length !== 1) throw new UserBindingTargetError("Неоднозначное имя интерфейса", 409)
type = mapRosInterfaceType(matches[0].type)
nativeId = matches[0][".id"]
if (type === "ipsec") throw new UserBindingTargetError("Для IPsec выберите каталог ipsec-vpn", 409)
}
if (input.interfaceType !== undefined && input.interfaceType !== type) throw new UserBindingTargetError("Тип интерфейса изменился или не соответствует устройству", 409)
return { ifaceName, type, ...(nativeId ? { nativeId } : {}) }
}
export function resolveBindingPeer(input: UserBindingCreate, iface: BindingInterface, rawPeers?: unknown, ipsecKeys?: string[]): BindingTarget {
let peerPublicKey: string
try { peerPublicKey = normalizeBindingPeer(iface.type, input.peerPublicKey) }
catch (error) { if (error instanceof PeerBindError) throw new UserBindingTargetError(error.message, 400); throw error }
if (iface.type === "wg") {
const matches = bindingNativeRows(rawPeers, [".id", "interface", "public-key"]).filter(row =>
[iface.ifaceName, iface.nativeId].includes(row.interface) && row["public-key"] === peerPublicKey)
if (!matches.length) throw new UserBindingTargetError("Пир WireGuard не найден на выбранном интерфейсе", 404)
if (matches.length !== 1) throw new UserBindingTargetError("Неоднозначный пир WireGuard", 409)
}
if (iface.type === "ipsec") {
if (!Array.isArray(ipsecKeys) || ipsecKeys.length > 10000 || ipsecKeys.some(key => typeof key !== "string" || !key.trim())) throw new UserBindingTargetError("Не подтверждён native-каталог клиентов IPsec", 502)
const matches = ipsecKeys.filter(key => key === peerPublicKey)
if (!matches.length) throw new UserBindingTargetError("Клиент IPsec не найден", 404)
if (matches.length !== 1) throw new UserBindingTargetError("Неоднозначный ключ клиента IPsec", 409)
}
return { ...iface, peerPublicKey, peerName: iface.type === "wg" ? peerDisplayName({ publicKey: peerPublicKey, name: input.peerName }) : "" }
}
export interface BindingReadSession {
assertCurrent(): Promise<unknown>
get(path: string, timeoutMs: number, signal: AbortSignal, maxResponseBytes: number): Promise<unknown>
ipsecKeys(certs: unknown, peers: unknown, identities: unknown): string[]
}
/** Fixed catalogues only; no UI snapshot/history, writes, retries or authority token. */
export async function readBindingTarget(input: UserBindingCreate, open: () => Promise<BindingReadSession>, options: { signal?: AbortSignal; assertCurrent?: () => Promise<unknown> } = {}) {
const end = performance.now() + 10000, signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(10000)]) : AbortSignal.timeout(10000)
const session = await open()
const assertCurrent = async () => {
signal.throwIfAborted()
if (performance.now() >= end) throw new UserBindingTargetError("Истёк срок проверки привязки", 502)
await options.assertCurrent?.()
await session.assertCurrent()
signal.throwIfAborted()
if (performance.now() >= end) throw new UserBindingTargetError("Истёк срок проверки привязки", 502)
}
const read = async (path: string) => {
await assertCurrent()
let value: unknown
try { value = await session.get(path, Math.max(1, Math.ceil(end - performance.now())), signal, 1048576) }
catch { throw new UserBindingTargetError("Native-каталог привязки недоступен", 502) }
await assertCurrent()
return value
}
const iface = resolveBindingInterface(input, input.interfaceName.trim() === "ipsec-vpn" ? undefined : await read("/interface"))
let rawPeers: unknown, ipsecKeys: string[] | undefined
if (iface.type === "wg") rawPeers = await read("/interface/wireguard/peers")
if (iface.type === "ipsec") {
const certs = await read("/certificate"), peers = await read("/ip/ipsec/peer"), identities = await read("/ip/ipsec/identity")
ipsecKeys = session.ipsecKeys(certs, peers, identities)
}
const target = resolveBindingPeer(input, iface, rawPeers, ipsecKeys)
await assertCurrent()
return { ...target, assertCurrent }
}
@@ -41,10 +41,10 @@ import {
parseRawInterfaces,
} from "../iface-type.js"
import {
normalizeBindingPeer,
PeerBindError,
peerDisplayName,
} from "../peer-bind.js"
import { readNativeUserBindingTarget } from "../binding-native-read.js"
import { UserBindingTargetError } from "../binding-target.js"
import { listWireGuardPeersForCatalog } from "../../../services/wireguard-live.js"
import { listIpsecClientsForCatalog } from "../../../services/ipsec-live.js"
@@ -190,28 +190,22 @@ async function deleteUserImpl(id: string): Promise<void> {
await deleteUserRowById(id)
}
export function addBinding(userId: string, input: UserBindingCreate): Promise<UserBinding> { return executeGuardedApplicationWrite({ kind: "user", id: userId }, () => userMutationDependencies(userId, [input.serverId]), () => addBindingImpl(userId, input)) }
async function addBindingImpl(userId: string, input: UserBindingCreate): Promise<UserBinding> {
type BindingReadOptions = { signal?: AbortSignal; assertCurrent?: () => Promise<unknown> }
export function addBinding(userId: string, input: UserBindingCreate, options: BindingReadOptions = {}): Promise<UserBinding> { return executeGuardedApplicationWrite({ kind: "user", id: userId }, () => userMutationDependencies(userId, [input.serverId]), () => addBindingImpl(userId, input, options)) }
/** Read-only validation shared by plan preparation and the guarded write. */
export async function validateUserBindingCreate(userId: string, input: UserBindingCreate, options: BindingReadOptions = {}): Promise<{ ifaceName: string; type: InterfaceType; peerPublicKey: string; peerName: string; assertCurrent(): Promise<void> }> {
const user = await getUserRowById(userId)
if (!user) throw new UsersServiceError("Пользователь не найден", 404)
const serverRows = await db.select().from(servers).where(eq(servers.id, input.serverId)).limit(1)
if (!serverRows[0]) throw new UsersServiceError("Сервер не найден", 404)
const ifaceName = input.interfaceName.trim()
if (!ifaceName) throw new UsersServiceError("Имя интерфейса обязательно", 400)
const type: InterfaceType = input.interfaceType ?? await inferIfaceType(input.serverId, ifaceName)
let peerPublicKey = ""
let target: Awaited<ReturnType<typeof readNativeUserBindingTarget>>
try {
peerPublicKey = normalizeBindingPeer(type, input.peerPublicKey)
target = await readNativeUserBindingTarget(input, options)
} catch (err) {
if (err instanceof PeerBindError) throw new UsersServiceError(err.message, err.status)
if (err instanceof UserBindingTargetError) throw new UsersServiceError(err.message, err.status)
throw err
}
const peerName = type === "wg"
? peerDisplayName({
publicKey: peerPublicKey,
name: input.peerName,
})
: ""
const { ifaceName, type, peerPublicKey, peerName, assertCurrent } = target
const taken = await getBindingByServerIfacePeer(input.serverId, ifaceName, peerPublicKey)
if (taken) {
throw new UsersServiceError(
@@ -221,8 +215,14 @@ async function addBindingImpl(userId: string, input: UserBindingCreate): Promise
409,
)
}
return { ifaceName, type, peerPublicKey, peerName, assertCurrent }
}
async function addBindingImpl(userId: string, input: UserBindingCreate, options: BindingReadOptions): Promise<UserBinding> {
const { ifaceName, type, peerPublicKey, peerName, assertCurrent } = await validateUserBindingCreate(userId, input, options)
const now = new Date().toISOString()
try {
await assertCurrent()
const row = await createBindingRow({
id: randomUUID(),
userId,
@@ -237,6 +237,7 @@ async function addBindingImpl(userId: string, input: UserBindingCreate): Promise
})
return await toBindingDto(row)
} catch (err) {
if (err instanceof UserBindingTargetError) throw new UsersServiceError(err.message, err.status)
if (isUniqueConstraintError(err)) {
throw new UsersServiceError(
type === "wg"
@@ -258,13 +259,6 @@ async function removeBindingImpl(userId: string, bindingId: string): Promise<voi
await deleteBindingRowById(bindingId)
}
async function inferIfaceType(serverId: number, ifaceName: string): Promise<InterfaceType> {
const snap = await getLatestSnapshot(serverId)
const parsed = parseRawInterfaces(snap?.rawInterfaces)
const found = parsed.find((i) => i.name === ifaceName)
return found?.type ?? "other"
}
export async function getInterfaceCatalogState(serverId: number): Promise<InterfaceCatalogState> {
const serverRows = await db.select().from(servers).where(eq(servers.id, serverId)).limit(1)
if (!serverRows[0]) throw new UsersServiceError("Сервер не найден", 404)