Files
MikrotikManager/backend/src/modules/mcp/ros-prefix.test.ts
T
DenozordecandClaude Opus 5.5 6584644112 fix(mcp): проверять права раз на этап, читать каталоги параллельно, отказ VRF только повторный
Решение владельца 2026-11-19 (ускорение и упрощение проверок при той же итоговой защите):
- права шага RouterOS доказываются свежей проверкой на границах этапа (начало шага,
  прямо перед отправкой, сразу после ACK, перед каждой записью); чтения внутри этапа
  повторно используют доказательство моложе 2 с. Сервисные шаги проверяют права на
  каждый вызов, как раньше: их проверка общая для чтений и записей;
- независимые каталоги при проверках и в снимке VRF читаются параллельно (пул REST
  ограничивает 2 соединениями на роутер), порядок снимка прежний; после ACK изменённый
  каталог читается один раз;
- конфликт каталога в проверке перед отправкой помечает операцию «не отправлено»;
- VRF: помеченный отказ классификатора окончательный, только если тот же отказ
  повторился на свежем чтении (в пределах 8 повторов).

Интеграционный набор PostgreSQL: 164 проверки пройдены; общие 92 проверки 401 -> 354 с.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-19 11:06:29 +07:00

68 lines
5.0 KiB
TypeScript

import assert from "node:assert/strict"
import { createRosPrefix } from "./ros-prefix.js"
import { fingerprint, McpError } from "./security.js"
import { rosSnapshotVersion, type RosSnapshot, type RosStep, type ConfigurationRow } from "./resources.js"
const snapshot = (resource: string, rows: ConfigurationRow[], sourceProof = "a".repeat(64)): RosSnapshot => ({ serverId: 1, resource, rows, fingerprint: fingerprint(rows), projectionVersion: rosSnapshotVersion(resource), sourceProof })
const old = snapshot("ip_filter", [{ ".id": "*a", chain: "forward", action: "accept", comment: "old" }, { ".id": "*b", chain: "forward", action: "drop", comment: "keep" }])
const dependency = snapshot("routing_table", [{ ".id": "*main", name: "main", fib: "true" }])
const changed = snapshot("ip_filter", [{ ...old.rows[0], comment: "new" }, old.rows[1]])
const step: RosStep = { serverId: 1, resource: "ip_filter", action: "update", id: "*a", fields: { comment: "new" } }
const actual = new Map([[old.resource, old], [dependency.resource, dependency]])
const read = async (_serverId: number, resource: string, beforeRead: () => Promise<unknown> = async () => {}) => { await beforeRead(); return structuredClone(actual.get(resource)!) }
const isConflict = (error: unknown) => error instanceof McpError && error.code === "STATE_CONFLICT"
const isFailed = (error: unknown) => error instanceof McpError && error.code === "VERIFICATION_FAILED"
for (const invalid of [{ ...old, sourceProof: undefined }, { ...old, projectionVersion: 1 }, { ...old, projectionVersion: 2 }, { ...old, fingerprint: "forged" }]) assert.throws(() => createRosPrefix([invalid]), error => error instanceof McpError && error.code === "PLAN_EXPIRED")
assert.throws(() => createRosPrefix([old, changed]), isConflict)
assert.throws(() => createRosPrefix([{ ...dependency, projectionVersion: 3 }]), { code: "PLAN_EXPIRED" })
const ospf = snapshot("ospf_template", [{ ".id": "*a", "prefix-list": "announced", cost: "80" }])
assert.throws(() => createRosPrefix([{ ...ospf, projectionVersion: 8 }]), { code: "PLAN_EXPIRED" })
for (const [resource, fields] of [["ip_settings", { "rp-filter": "loose" }], ["ipv6_settings", { "multipath-hash-policy": "l4" }]] as const) {
const current = snapshot(resource, [fields])
assert.doesNotThrow(() => createRosPrefix([current]))
assert.throws(() => createRosPrefix([{ ...current, projectionVersion: 3 }]), { code: "PLAN_EXPIRED" })
}
const prefix = createRosPrefix([old, dependency, structuredClone(old)], read)
await prefix.check()
actual.set(old.resource, changed)
await prefix.advance(step, {}, changed)
assert.equal(prefix.before(step).rows[0].comment, "new")
await prefix.check()
actual.set(old.resource, old)
await assert.rejects(prefix.check(), isConflict)
actual.set(old.resource, changed)
actual.set(dependency.resource, { ...dependency, sourceProof: "b".repeat(64) })
await assert.rejects(prefix.check(), isConflict)
actual.set(old.resource, old); actual.set(dependency.resource, dependency)
const unadvanced = createRosPrefix([old, dependency], read)
const collateral = snapshot("ip_filter", [changed.rows[0], { ...old.rows[1], action: "accept" }])
actual.set(old.resource, collateral)
await assert.rejects(unadvanced.advance(step, {}, collateral), isFailed)
assert.equal(unadvanced.before(step).rows[0].comment, "old")
actual.set(old.resource, changed)
actual.set(dependency.resource, snapshot("routing_table", [{ ".id": "*main", name: "renamed", fib: "true" }]))
await assert.rejects(unadvanced.advance(step, {}, changed), isFailed)
assert.equal(unadvanced.before(step).rows[0].comment, "old", "A failed dependency check cannot advance the expected prefix")
actual.set(old.resource, old); actual.set(dependency.resource, dependency)
await unadvanced.check()
await assert.rejects(unadvanced.check(async () => { throw new McpError("PERMISSION_DENIED", "revoked") }), error => error instanceof McpError && error.code === "PERMISSION_DENIED")
assert.equal(unadvanced.before(step).rows[0].comment, "old")
// Catalogs are read concurrently; advance trusts the caller's fresh target read and re-reads only the others.
const reads: string[] = []
let inFlight = 0, peak = 0
const counted = async (_serverId: number, resource: string, beforeRead: () => Promise<unknown> = async () => {}) => {
reads.push(resource); inFlight++; peak = Math.max(peak, inFlight)
await beforeRead(); await new Promise(resolve => setTimeout(resolve, 5)); inFlight--
return structuredClone(actual.get(resource)!)
}
const concurrent = createRosPrefix([old, dependency], counted)
await concurrent.check()
assert.deepEqual(reads.sort(), ["ip_filter", "routing_table"]); assert.equal(peak, 2)
reads.length = 0; actual.set(old.resource, changed)
await concurrent.advance(step, {}, changed)
assert.deepEqual(reads, ["routing_table"], "advance does not re-read the target it was just given")
console.log("ROS prefix: version/source/fingerprint and duplicate-baseline guards, verified advancement, inter-step drift/source changes, failed conservation/dependency do not advance, live revocation, concurrent reads, no target re-read on advance")