Compare commits

...
1 Commits
Author SHA1 Message Date
Denozordec e11e67b3a1 feat(ix): добавить удаление сегментов
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 10m30s
Docker images / frontend-image (push) Successful in 2m11s
Docker images / updater-image (push) Successful in 39s
Docker images / netflow-agent-image (push) Successful in 32s
Docker images / backend-image (push) Successful in 2m0s
Docker images / publish-release (push) Successful in 11s
Docker images / notify-webhook (push) Successful in 2s
2026-11-23 11:00:47 +07:00
10 changed files with 472 additions and 87 deletions

No files matched your search

+62 -17
View File
@@ -2,7 +2,7 @@
import { useEffect, useRef, useState } from "react"
import Link from "next/link"
import { ArrowLeftIcon, CircleAlertIcon, NetworkIcon, PlusIcon, RefreshCwIcon } from "lucide-react"
import { ArrowLeftIcon, CircleAlertIcon, NetworkIcon, PlusIcon, RefreshCwIcon, Trash2Icon } from "lucide-react"
import { ixSegmentConfigurationSchema, type IxChange, type IxConfiguration, type IxLinuxAccess, type IxLinuxBinding, type IxWebPlan, type IxSegment, type IxSiteObservation } from "@mmapp/contracts/internet-exchange"
import { Alert, AlertDescription, AlertTitle } from "@/components/reui/alert"
import { Frame, FrameDescription, FrameHeader, FramePanel, FrameTitle } from "@/components/reui/frame"
@@ -28,6 +28,26 @@ const post = (value: unknown) => ({ method: "POST", body: JSON.stringify(value)
const actionLabels = { create: "Создать", update: "Обновить", delete: "Удалить" } as const
function RouterOsChanges({ changes, nodes }: { changes: IxWebPlan["changes"]; nodes: IxNode[] }) {
if (!changes.length) return null
return <ul className="max-h-56 min-w-0 divide-y overflow-auto rounded-md border">
{changes.map((operation, index) => <li key={index} className="min-w-0 p-2.5 text-sm">
<details>
<summary className="cursor-pointer wrap-anywhere">{actionLabels[operation.action]} · {nodeLabel(nodes, operation.serverId)} · <code>{operation.path}</code>
{operation.target && <> · <code>{operation.target}</code></>}
</summary>
<dl className="grid min-w-0 grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-1 py-2 text-xs">
{operation.placeBefore && <><dt className="text-muted-foreground">Перед объектом</dt><dd className="font-mono">{operation.placeBefore}</dd></>}
{Object.entries(operation.fields).map(([key, value]) => <div key={key} className="contents">
<dt className="max-w-32 wrap-anywhere text-muted-foreground">{key}</dt>
<dd className="wrap-anywhere font-mono">{value}</dd>
</div>)}
</dl>
</details>
</li>)}
</ul>
}
export default function IxPage() {
const { backendUrl, mode, prefsHydrated } = useDataSource()
const [segments, setSegments] = useState<IxSegment[]>([])
@@ -41,6 +61,7 @@ export default function IxPage() {
const [linuxBindings, setLinuxBindings] = useState<IxLinuxBinding[]>([])
const [linux, setLinux] = useState<(IxLinuxAccess & IxLinuxBinding) | null>(null)
const [plan, setPlan] = useState<IxWebPlan | null>(null)
const [removalPlan, setRemovalPlan] = useState<IxWebPlan | null>(null)
const [tab, setTab] = useState<Tab>("configuration")
const [loading, setLoading] = useState(true)
const [busy, setBusy] = useState(false)
@@ -98,6 +119,7 @@ export default function IxPage() {
function invalidateReview() {
setPlan(null)
setRemovalPlan(null)
setNotice("")
}
@@ -117,6 +139,7 @@ export default function IxPage() {
function close() {
focusAfterNavigation.current = true
setDraft(null)
setRemovalPlan(null)
setError("")
setNotice("")
}
@@ -149,6 +172,22 @@ export default function IxPage() {
setPlan(await requestJson<IxWebPlan>(backendUrl, "/api/ix/segments/" + selected.id + "/plan", post({ revision: selected.revision })))
}
async function prepareRemoval() {
if (!selected) return
setRemovalPlan(await requestJson<IxWebPlan>(backendUrl, "/api/ix/segments/" + selected.id + "/removal-plan", post({ revision: selected.revision })))
}
async function removeSegment() {
if (!selected || !removalPlan) return
setRemovalPlan(null)
await requestJson<void>(backendUrl, "/api/ix/segments/" + selected.id, {
method: "DELETE", body: JSON.stringify({ revision: removalPlan.revision, digest: removalPlan.digest }),
})
setSegments(current => current.filter(segment => segment.id !== selected.id))
close()
setNotice("Сегмент " + selected.configuration.name + " удалён")
}
async function apply() {
if (!selected || !plan || !canPlan) return
setPlan(null)
@@ -222,6 +261,27 @@ export default function IxPage() {
Ревизия {selected.revision}{selected.appliedRevision ? ` · Применена ревизия ${selected.appliedRevision}` : ""}
</p>) : <p className="mt-1 text-sm text-muted-foreground">Сегменты IX, площадки и маршрутизация</p>}
</div>
{inDetail && selected && live && write && <AlertDialog open={removalPlan !== null}
onOpenChange={open => { if (open) void perform(prepareRemoval); else setRemovalPlan(null) }}>
<AlertDialogTrigger render={<Button type="button" variant="outline" size="sm" disabled={busy} />}>
<Trash2Icon aria-hidden />Удалить сегмент
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle className="wrap-anywhere">Удалить {selected.configuration.name}?</AlertDialogTitle>
<AlertDialogDescription>
{selected.appliedRevision
? "Этот сегмент перестанет передавать трафик. Управляемая конфигурация будет удалена с узлов IX."
: "Черновик будет удалён из списка сегментов. Конфигурация роутеров останется прежней."}
</AlertDialogDescription>
</AlertDialogHeader>
{removalPlan && <RouterOsChanges changes={removalPlan.changes} nodes={nodes} />}
<AlertDialogFooter>
<AlertDialogCancel>Отмена</AlertDialogCancel>
<AlertDialogAction variant="destructive" disabled={busy} onClick={() => void perform(removeSegment)}>Удалить</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>}
{!inDetail && <div className="flex flex-wrap items-center gap-2">
<Button type="button" size="icon-sm" variant="outline" disabled={busy || loading || !live} aria-label="Обновить список"
onClick={() => void perform(() => load())}><RefreshCwIcon aria-hidden /></Button>
@@ -350,22 +410,7 @@ export default function IxPage() {
{plan && <div className="grid min-w-0 gap-3 border-t pt-3">
<p className="text-sm font-medium">Ревизия {plan.revision} · операций RouterOS: {plan.changes.length}</p>
{plan.changes.length === 0 && <p className="text-sm text-muted-foreground">Конфигурация RouterOS совпадает с черновиком. Применение обновит ревизию в MikrotikManager.</p>}
{plan.changes.length > 0 && <ul className="max-h-80 min-w-0 divide-y overflow-auto rounded-md border">
{plan.changes.map((operation, index) => <li key={index} className="min-w-0 p-2.5 text-sm">
<details className="min-w-0">
<summary className="cursor-pointer wrap-anywhere">{actionLabels[operation.action]} · {nodeLabel(nodes, operation.serverId)} · <code>{operation.path}</code>
{operation.target && <> · <code>{operation.target}</code></>}
</summary>
<dl className="grid min-w-0 grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-1 py-2 text-xs">
{operation.placeBefore && <><dt className="text-muted-foreground">Перед объектом</dt><dd className="font-mono">{operation.placeBefore}</dd></>}
{Object.entries(operation.fields).map(([key, value]) => <div key={key} className="contents">
<dt className="max-w-32 wrap-anywhere text-muted-foreground">{key}</dt>
<dd className="wrap-anywhere font-mono">{value}</dd>
</div>)}
</dl>
</details>
</li>)}
</ul>}
<RouterOsChanges changes={plan.changes} nodes={nodes} />
<AlertDialog>
<AlertDialogTrigger render={<Button type="button" size="sm" className="w-fit" disabled={busy || !canPlan} />}>
Применить план
+14
View File
@@ -1618,6 +1618,20 @@
"operations": ["network.ix.configure"],
"reason": "Пользователь WebUI подтверждает просмотренную ревизию. MCP применяет свой подтверждённый план через общий исполнитель IX."
},
{
"method": "POST",
"path": "/api/ix/segments/:id/removal-plan",
"status": "mediated",
"operations": ["network.ix.delete"],
"reason": "Предпросмотр управляемых объектов перед явным подтверждением удаления сегмента."
},
{
"method": "DELETE",
"path": "/api/ix/segments/:id",
"status": "mediated",
"operations": ["network.ix.delete"],
"reason": "Общий исполнитель удаления проверяет ревизию и очищает управляемые объекты IX."
},
{
"method": "POST",
"path": "/api/ix/segments",
+113 -4
View File
@@ -4,6 +4,8 @@ import { mkdtemp } from "node:fs/promises"
import { createServer } from "node:http"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { setTimeout as delay } from "node:timers/promises"
import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client"
import EmbeddedPostgres from "embedded-postgres"
const dir = await mkdtemp(join(tmpdir(), "mm-ix-web-"))
@@ -29,6 +31,8 @@ const rows: Record<string, Record<string, string>[]> = {
protocol: "gre", action: "encrypt", level: "require", tunnel: "false", disabled: "false" }],
}
let writes = 0
let deletes = 0
let failDeleteAt = -1
const router = createServer(async (request, response) => {
try {
const path = new URL(request.url!, "http://127.0.0.1").pathname.replace(/^\/rest/, "")
@@ -48,6 +52,18 @@ const router = createServer(async (request, response) => {
type: path === "/interface/wireguard" ? "wg" : path.split("/").at(-1)!, comment: row.comment })
}
result = row
} else if (request.method === "DELETE") {
if (deletes === failDeleteAt) throw Error("Synthetic RouterOS deletion failure")
const parent = path.slice(0, path.lastIndexOf("/"))
const id = decodeURIComponent(path.slice(path.lastIndexOf("/") + 1))
const index = (rows[parent] ?? []).findIndex(row => row[".id"] === id)
assert(index >= 0)
const [deleted] = rows[parent].splice(index, 1)
rows["/interface"] = rows["/interface"].filter(row => row.name !== deleted.name || row[".id"] !== id)
deletes++
response.statusCode = 204
response.end()
return
} else throw Error("Unexpected native verb: " + request.method)
response.setHeader("content-type", "application/json")
response.end(JSON.stringify(result))
@@ -59,6 +75,7 @@ const router = createServer(async (request, response) => {
const { initDatabase } = await import("../../src/db/bootstrap.js")
const { pool } = await import("../../src/db/index.js")
let app: Awaited<ReturnType<typeof import("../../src/index.js").buildApp>> | undefined
let mcp: Client | undefined
try {
await initDatabase()
assert.equal((await pool.query("SELECT enabled FROM mcp_settings WHERE id=1")).rows[0].enabled, false)
@@ -76,11 +93,11 @@ try {
const writer = token("ix-web-owner", "mm:network:write")
const reader = token("ix-web-reader", "mm:network:read")
const otherWriter = token("ix-web-other-owner", "mm:network:write")
async function post(path: string, payload: object, status: number, jwt = writer) {
const reply = await fetch(origin + "/api/ix/segments" + path, { method: "POST",
async function post(path: string, payload: object, status: number, jwt = writer, method = "POST") {
const reply = await fetch(origin + "/api/ix/segments" + path, { method,
headers: { "content-type": "application/json", ...(jwt ? { authorization: "Bearer " + jwt } : {}) },
body: JSON.stringify(payload), signal: AbortSignal.timeout(30_000) })
const data = await reply.json()
const data = reply.status === 204 ? undefined : await reply.json()
assert.equal(reply.status, status, JSON.stringify(data))
return data
}
@@ -161,11 +178,103 @@ try {
assert.equal(audit.n, writes)
const { rows: [connections] } = await pool.query("SELECT count(*)::int AS n FROM mcp_connections")
assert.equal(connections.n, 0)
const draftConfig = { ...configuration, name: "ix-web-draft" }
const draft = (await post("", { revision: 0, configuration: draftConfig }, 200)).segment
const draftPath = "/" + draft.id
const draftRemoval = await post(draftPath + "/removal-plan", { revision: 1 }, 200)
assert.deepEqual(draftRemoval.changes, [])
const deleteDraft = { revision: 1, digest: draftRemoval.digest }
await post(draftPath, deleteDraft, 403, reader, "DELETE")
await post(draftPath, deleteDraft, 409, otherWriter, "DELETE")
await post(draftPath, deleteDraft, 204, writer, "DELETE")
assert.equal(deletes, 0)
await post(draftPath, deleteDraft, 404, writer, "DELETE")
const recreated = (await post("", { revision: 0, configuration: draftConfig }, 200)).segment
const removalInput = { revision: 4 }
const blocked = await post(path + "/removal-plan", removalInput, 409)
assert.match(blocked.error, /Отключите интерфейс.*gre-client/)
rows["/interface"].find(row => row.name === "gre-client")!.disabled = "true"
rows["/ip/address"].push({ ".id": "*FE", interface: "wg-ix-web", address: "192.0.2.1/32" })
assert.match((await post(path + "/removal-plan", removalInput, 409)).error, /нет в применённой ревизии/)
rows["/ip/address"].pop()
const removal = await post(path + "/removal-plan", removalInput, 200)
assert.equal(removal.changes.length, writes)
assert(removal.changes.every((change: { action: string }) => change.action === "delete"))
failDeleteAt = 1
await post(path, { ...removalInput, digest: removal.digest }, 503, writer, "DELETE")
assert.equal(deletes, 1)
assert.equal((await pool.query("SELECT configuration->>'deleted' AS deleted FROM ix_segments WHERE id=$1", [segment.id])).rows[0].deleted, null)
await post(path, { ...removalInput, digest: removal.digest }, 409, writer, "DELETE")
failDeleteAt = -1
const remaining = await post(path + "/removal-plan", removalInput, 200)
assert.equal(remaining.changes.length, removal.changes.length - 1)
await post(path, { ...removalInput, digest: remaining.digest }, 204, writer, "DELETE")
assert.equal(deletes, writes)
assert.equal(rows["/ip/ipsec/policy"].length, 1)
assert.deepEqual(rows["/interface"].map(row => row.name), ["gre-client", "test-drift"])
const { rows: [archive] } = await pool.query(`SELECT s.configuration->>'deleted' AS deleted,
(SELECT count(*)::int FROM ix_segment_revisions WHERE segment_id=s.id) AS revisions,
(SELECT count(*)::int FROM ix_segment_devices WHERE segment_id=s.id) AS devices
FROM ix_segments s WHERE id=$1`, [segment.id])
assert.deepEqual(archive, { deleted: "true", revisions: 4, devices: 0 })
const listReply = await fetch(origin + "/api/ix/segments", { headers: { authorization: "Bearer " + reader } })
assert.equal(listReply.status, 200)
assert.deepEqual((await listReply.json()).items.map((item: { configuration: { name: string } }) => item.configuration.name), [draftConfig.name])
process.env.MCP_PUBLIC_URL = origin + "/mcp"
const ownerPermissions = ["mm:network:write", "mm:network:read", "mm:mcp:admin", "mm:mcp:approve"]
const issuedAt = Math.floor(Date.now() / 1000) - 1
const ownerId = "ix-mcp-owner"
const mcpJwt = app.jwt.sign({ iss: env.authIssuer, sub: ownerId, apps: ["mm"], permissions: ownerPermissions, iat: issuedAt, exp: issuedAt + 600 })
const { updateMcpSettings } = await import("../../src/modules/mcp/store.js")
await updateMcpSettings({ enabled: true }, { id: ownerId, email: "[email protected]", name: "IX acceptance", apps: ["mm"],
permissions: ownerPermissions, issuedAt: issuedAt * 1000, expiresAt: (issuedAt + 600) * 1000 })
async function mcpPost(path: string, body: object) {
const reply = await fetch(origin + "/api/mcp/" + path, { method: "POST",
headers: { authorization: "Bearer " + mcpJwt, "content-type": "application/json" }, body: JSON.stringify(body) })
const data = await reply.json()
assert(reply.ok, JSON.stringify(data))
return data
}
const { token: mcpToken } = await mcpPost("connections", { name: "IX removal acceptance", mode: "approval",
permissions: ["mm:network:write", "mm:network:read"], expiresAt: new Date(Date.now() + 300_000).toISOString(),
scope: { allowGlobal: false, serverIds: [Number(server.id)], operationIds: ["network.ix.delete", "changes.apply", "operations.read"] } })
mcp = new Client({ name: "ix-removal-acceptance", version: "1.0.0" })
await mcp.connect(new StreamableHTTPClientTransport(new URL(origin + "/mcp"),
{ requestInit: { headers: { authorization: "Bearer " + mcpToken } } }))
async function call<T>(name: string, args: object, error = false) {
const reply = await mcp!.callTool({ name, arguments: args })
assert.equal(Boolean(reply.isError), error, JSON.stringify(reply.structuredContent ?? reply.content))
return (reply.structuredContent as { result: T } | undefined)?.result as T
}
const mcpPlan = await call<{ planId: string; state: string }>(
"mm_ix_delete_plan", { id: recreated.id, revision: 1 })
assert.equal(mcpPlan.state, "awaiting-approval")
const mcpApply = { planId: mcpPlan.planId, idempotencyKey: randomUUID() }
await call("mm_change_apply", mcpApply, true)
await mcpPost("plans/" + mcpPlan.planId + "/decision", { approve: true })
type Operation = { id: string; state: string; verification: string }
const operation = await call<Operation>("mm_change_apply", mcpApply)
let terminal = operation
for (let attempts = 0; attempts < 30 && ["pending", "running"].includes(terminal.state); attempts++) {
await delay(200)
terminal = await call<Operation>("mm_operation_get", { operationId: operation.id })
}
assert.equal(terminal.state, "applied", JSON.stringify(terminal))
assert.equal(terminal.verification, "passed")
assert.equal(deletes, writes)
console.log(JSON.stringify({ appliedRevisions: [2, 4], writes, audit: audit.n, mcpConnections: connections.n,
unauthenticated: 401, readOnly: 403, ownerMismatch: 409, drift: 409, replay: 409, protected: 409, linuxClients: clients.items.length }))
unauthenticated: 401, readOnly: 403, ownerMismatch: 409, drift: 409, replay: 409, protected: 409, linuxClients: clients.items.length,
deletedDraft: true, removedNativeObjects: deletes, revisionsRetained: archive.revisions, mcpRemovalVerified: true }))
} finally {
await mcp?.close()
await app?.close()
await new Promise<void>(resolve => router.close(() => resolve()))
await pool.end()
await pg.stop()
}
// As in the MCP integration suite, close the standalone runner after teardown and log flushing.
process.stderr.write("", () => process.stdout.write("", () => process.exit()))
@@ -1,9 +1,9 @@
import { z } from "zod"
import { ixChangeSchema, type IxChange } from "@mmapp/contracts/internet-exchange"
import { pool } from "../../db/index.js"
import { applyIxChange, currentIxChange, ixTarget, observeIxSegment, prepareIxChange, reconcileIxChange } from "../../services/internet-exchange-execution.js"
import { applyIxChange, currentIxChange, ixTarget, observeIxSegment, prepareIxChange, prepareIxRemoval, reconcileIxChange, removeIxSegment } from "../../services/internet-exchange-execution.js"
import { IxConflict, ixDeviceIds } from "../../services/internet-exchange-plan.js"
import { listIxSegments, readIxRevision, readIxSegment } from "../../services/internet-exchange-store.js"
import { assertIxRevision, isIxSegmentArchived, listIxSegments, readIxRevision, readIxSegment } from "../../services/internet-exchange-store.js"
import type { add } from "./actions.js"
import type { ActionContext } from "./action-types.js"
import { McpError } from "./security.js"
@@ -12,10 +12,13 @@ import { registerMcpService } from "./service-registry.js"
export const ixOperation = "network.ix.configure"
export const ixRestoreOperation = "network.ix.restore"
const service = "network.ix.configure"
const removeService = "network.ix.delete"
const id = z.string().uuid()
const revision = z.number().int().positive()
const changeArgs = z.object({ change: ixChangeSchema }).strict()
const restoreArgs = z.object({ id, revision, restoreRevision: revision }).strict()
const removeArgs = z.object({ id, revision }).strict()
const sealedRemoval = removeArgs.extend({ actorId: z.string().min(1), digest: z.string().regex(/^[a-f0-9]{64}$/) })
const sealedInput = z.object({
id, change: ixChangeSchema, actorId: z.string().min(1),
before: z.object({ revision: z.number().int().nonnegative(), devices: z.string().regex(/^[a-f0-9]{64}$/) }).strict(),
@@ -32,14 +35,9 @@ async function prepare(change: IxChange, context: ActionContext) {
const serverIds = await ixTarget(change)
if (serverIds.some(id => !context.connection.policy.scope.serverIds.includes(id))) throw new McpError("SERVER_DENIED", "Нет доступа ко всем устройствам сегмента")
const result = await prepareIxChange(change)
const protections = await pool.query("SELECT object_ref FROM mcp_protections WHERE object_ref->>'serverId'=ANY($1::text[]) LIMIT 1001", [serverIds.map(String)])
const objects = [...new Map(result.objects.concat(protections.rows.map(({ object_ref: object }) => ({
kind: object.kind, id: object.id, serverId: object.serverId,
}))).map(object => [JSON.stringify(object), object])).values()]
if (objects.length > 1000) throw new McpError("STATE_UNAVAILABLE", "Превышен лимит защищённых ресурсов плана IX", 409)
return {
target: { scope: "servers" as const, serverIds },
before: result.before, objects, snapshots: [],
before: result.before, objects: await ixPlanObjects(serverIds, result.objects.map(object => object.serverId)), snapshots: [],
steps: [{ kind: "service" as const, service, input: { id: result.id, change, before: result.before, actorId: context.connection.owner_id } }],
mutationCost: result.native.tasks.length + 1,
warnings: [
@@ -49,6 +47,28 @@ async function prepare(change: IxChange, context: ActionContext) {
}
}
async function ixPlanObjects(serverIds: number[], nativeIds = serverIds) {
const protections = await pool.query("SELECT object_ref FROM mcp_protections WHERE object_ref->>'serverId'=ANY($1::text[]) LIMIT 1001", [serverIds.map(String)])
const servers = nativeIds.map(serverId => ({ kind: "server", id: String(serverId), serverId }))
const objects = [...new Map(servers.concat(protections.rows.map(({ object_ref: object }) => ({
kind: object.kind, id: object.id, serverId: object.serverId,
}))).map(object => [JSON.stringify(object), object])).values()]
if (objects.length > 1000) throw new McpError("STATE_UNAVAILABLE", "Превышен лимит защищённых ресурсов плана IX", 409)
return objects
}
async function removalTarget(input: Record<string, unknown>, context: ActionContext) {
const args = removeArgs.parse(input)
const current = await readIxSegment(args.id, context.transactionClient)
if (!current) throw new IxConflict("Сегмент IX не найден", 404)
assertIxRevision(current, args.revision)
const serverIds = await ixTarget({ id: current.id, revision: current.revision, configuration: current.configuration })
if (serverIds.some(id => !context.connection.policy.scope.serverIds.includes(id))) {
throw new McpError("SERVER_DENIED", "Нет доступа ко всем устройствам сегмента")
}
return { scope: "servers" as const, serverIds }
}
async function restore(input: Record<string, unknown>, context: ActionContext) {
const args = restoreArgs.parse(input)
const current = await readIxSegment(args.id, context.transactionClient)
@@ -78,6 +98,35 @@ export function registerIxActions(register: typeof add) {
return reconcileIxChange(args.id, args.change, args.before, authorize)
},
})
registerMcpService(removeService, {
current: input => present(async () => {
const { id, revision } = sealedRemoval.parse(input)
return { revision, digest: (await prepareIxRemoval(id, revision)).digest }
}),
execute: input => present(() => {
const { id, revision, digest, actorId } = sealedRemoval.parse(input)
return removeIxSegment(id, revision, digest, actorId)
}),
verify: async (input, result) => {
const { id, revision } = sealedRemoval.parse(input)
return (result as { configurationVerified?: boolean } | undefined)?.configurationVerified === true && isIxSegmentArchived(id, revision)
},
})
register(removeService, "mm_ix_delete_plan", "План удаления сегмента IX", "network", "mm:network:write", "write", "servers", removeArgs, {
target: (input, context) => present(() => removalTarget(input, context)),
prepare: (input, context) => present(async () => {
const args = removeArgs.parse(input)
const target = await removalTarget(input, context)
const { segment, native, digest } = await prepareIxRemoval(args.id, args.revision)
return {
target, before: { revision: args.revision, digest }, objects: await ixPlanObjects(target.serverIds), snapshots: [],
steps: [{ kind: "service" as const, service: removeService, input: { ...args, digest, actorId: context.connection.owner_id } }],
mutationCost: native.tasks.length + 1, requiresHuman: true, verificationScope: "configuration" as const,
warnings: [`Сегмент ${segment.configuration.name} будет удалён. Операций RouterOS: ${native.tasks.length}. История ревизий сохранится.`,
...native.tasks.slice(0, 12).map(task => `Узел ${task.serverId} · удалить ${task.path}`)],
}
}),
})
register("network.ix.list", "mm_ix_segments_list", "Сегменты обмена трафиком", "network", "mm:network:read", "read", "servers",
z.object({ limit: z.number().int().min(1).max(25).default(10), offset: z.number().int().nonnegative().max(1000000).default(0) }).strict(), {
read: async (input, context) => {
@@ -34,6 +34,10 @@ export function publicRoutingCommunityChanges(evidence: ChangeEvidence) {
/** Service recovery has the same private native bodies as its forward plan. */
export function publicMcpChangeEvidence(operationId: string, evidence: ChangeEvidence) {
if (operationId === "network.ix.delete") {
return { ...evidence, before: { revision: record(evidence.before).revision }, steps: evidence.steps.map(step => step.kind === "service"
? { ...step, input: { id: step.input.id, revision: step.input.revision } } : step) }
}
if (operationId === "network.ix.configure" || operationId === "network.ix.restore") {
return { ...evidence, before: { revision: record(evidence.before).revision }, steps: evidence.steps.map(step => step.kind === "service"
? { ...step, input: { id: step.input.id, change: step.input.change } } : step) }
+41 -9
View File
@@ -6,7 +6,7 @@ import { fingerprint, McpError } from "../modules/mcp/security.js"
import { captureVerifiedRestRequest, inspectVerifiedRestRequest, RestRequestProvenanceError } from "../plugins/auth.js"
import { withApplicationMutationLock } from "../services/config-mutation-lock.js"
import { withConfigurationActor } from "../services/config-mutation-policy.js"
import { applyIxChange, listIxLinuxClients, observeIxSegment, prepareIxChange, readIxLinuxClient } from "../services/internet-exchange-execution.js"
import { applyIxChange, listIxLinuxClients, observeIxSegment, prepareIxChange, prepareIxRemoval, readIxLinuxClient, removeIxSegment } from "../services/internet-exchange-execution.js"
import { compileIxConfiguration, IxConflict } from "../services/internet-exchange-plan.js"
import { assertIxRevision, listIxSegments, readIxSegment, writeIxRevision } from "../services/internet-exchange-store.js"
@@ -30,6 +30,20 @@ function reviewDigest(prepared: Awaited<ReturnType<typeof prepareSavedRevision>>
return fingerprint({ operation: "ix.web.apply", actorId, change: prepared.change, before: prepared.before, tasks: prepared.native.tasks })
}
function removalDigest(id: string, revision: number, actorId: string, nativeDigest: string) {
return fingerprint({ operation: "ix.web.delete", id, revision, actorId, nativeDigest })
}
function summarizeTasks(tasks: Awaited<ReturnType<typeof prepareIxChange>>["native"]["tasks"]): IxWebPlan["changes"] {
return tasks.map(task => ({
serverId: task.serverId, path: task.path,
action: task.fields ? task.rosId ? "update" : "create" : "delete",
target: task.before?.name ?? task.before?.comment ?? task.fields?.name ?? task.fields?.comment ?? task.rosId,
placeBefore: task.placeBefore,
fields: task.fields ?? Object.fromEntries(Object.entries(task.before ?? {}).filter(([key]) => ["name", "comment", "dst-address", "chain"].includes(key))),
}))
}
const ixRoutes: FastifyPluginAsync = async app => {
app.setErrorHandler((error, request, reply) => {
if (error instanceof z.ZodError) return reply.code(400).send({ error: "Некорректные параметры IX", details: error.issues })
@@ -37,7 +51,8 @@ const ixRoutes: FastifyPluginAsync = async app => {
if (error instanceof McpError) return reply.code(error.statusCode).send({ error: error.message })
if (error instanceof RestRequestProvenanceError) return reply.code(403).send({ error: "Нет действующего права изменения IX" })
request.log.error({ error: error instanceof Error ? error.name : "unknown" }, "IX request failed")
const errorMessage = request.routeOptions.url?.endsWith("/apply")
const errorMessage = request.method === "DELETE" ? "Удаление сегмента IX не подтверждено. Обновите данные и проверьте план."
: request.routeOptions.url?.endsWith("/apply")
? "Результат применения IX не подтверждён"
: "Не удалось получить данные для операции IX"
return reply.code(503).send({ error: errorMessage })
@@ -101,13 +116,7 @@ const ixRoutes: FastifyPluginAsync = async app => {
const prepared = await prepareSavedRevision(id, revision)
return {
revision, digest: reviewDigest(prepared, request.authUser?.id ?? "local-operator"),
changes: prepared.native.tasks.map(task => ({
serverId: task.serverId, path: task.path,
action: task.fields ? task.rosId ? "update" : "create" : "delete",
target: task.before?.name ?? task.before?.comment ?? task.fields?.name ?? task.fields?.comment ?? task.rosId,
placeBefore: task.placeBefore,
fields: task.fields ?? Object.fromEntries(Object.entries(task.before ?? {}).filter(([key]) => ["name", "comment", "dst-address", "chain"].includes(key))),
})),
changes: summarizeTasks(prepared.native.tasks),
}
})
@@ -123,6 +132,29 @@ const ixRoutes: FastifyPluginAsync = async app => {
const result = await withConfigurationActor(ownerId, () => applyIxChange(id, prepared.change, prepared.before, ownerId, async () => { await inspect() }))
return { segment: await readIxSegment(result.segmentId), result }
})
app.post("/ix/segments/:id/removal-plan", async (request): Promise<IxWebPlan> => {
const { id } = segmentParams.parse(request.params)
const { revision } = planRequest.parse(request.body)
const prepared = await prepareIxRemoval(id, revision)
return { revision, digest: removalDigest(id, revision, request.authUser?.id ?? "local-operator", prepared.digest),
changes: summarizeTasks(prepared.native.tasks) }
})
app.delete("/ix/segments/:id", async (request, reply) => {
const { id } = segmentParams.parse(request.params)
const { revision, digest } = applyRequest.parse(request.body)
const scope = { deadlineAt: Date.now() + 180_000 }
const token = await captureVerifiedRestRequest(request, scope)
const inspect = () => inspectVerifiedRestRequest(token, scope, "mm:network:write")
const { ownerId } = await inspect()
const prepared = await prepareIxRemoval(id, revision)
if (digest !== removalDigest(id, revision, ownerId, prepared.digest)) {
throw new IxConflict("План удаления IX устарел. Подготовьте новый план")
}
await withConfigurationActor(ownerId, () => removeIxSegment(id, revision, prepared.digest, ownerId, async () => { await inspect() }))
return reply.code(204).send()
})
}
export default ixRoutes
@@ -7,7 +7,7 @@ import { getServerRowById, type ServerRow } from "../modules/servers/repository/
import { withApplicationMutationLock, withConfigMutationLock } from "./config-mutation-lock.js"
import { assertVerifiedConfigurationAccess } from "./config-mutation-policy.js"
import { compileIxConfiguration, IxConflict, ixDeviceIds, ixDiscardInterface, ixEgressList, ixNamespace } from "./internet-exchange-plan.js"
import { assertIxName, assertIxRevision, assertIxSites, readIxRevision, readIxSegment, writeIxRevision } from "./internet-exchange-store.js"
import { archiveIxSegment, assertIxName, assertIxRevision, assertIxSites, readIxRevision, readIxSegment, writeIxRevision } from "./internet-exchange-store.js"
import { MikrotikClient } from "./mikrotik.js"
import { ixGreClientTemplate, ixLinuxBindingKind, ixLinuxInterfaceName, ixWireguardClientTemplate } from "./internet-exchange-client.js"
@@ -140,10 +140,13 @@ async function readRows(client: IpCore, path: string, props: readonly string[])
}))) as NativeRow[]
}
async function readDevice(server: ServerRow, objects: IxRouterObject[]): Promise<NativeDevice> {
async function readDevice(server: ServerRow, objects: IxRouterObject[], removing = false): Promise<NativeDevice> {
const client = MikrotikClient.fromServer(server)
const fieldsByPath = new Map<string, string[]>([["/interface", columns], ["/interface/bridge/port", [".id", "bridge", "interface"]],
["/ip/vrf", columns], ["/ip/route", columns], ["/ipv6/route", columns]])
if (removing) {
for (const path of ["/ip/address", "/ipv6/address"]) fieldsByPath.set(path, [...columns, "interface"])
}
for (const object of objects) {
fieldsByPath.set(object.path, [...new Set([...(fieldsByPath.get(object.path) ?? columns),
...(filterPath(object.path) ? ["invalid"] : []), ...Object.keys(object.fields)])])
@@ -208,27 +211,59 @@ function validateBindings(configuration: IxConfiguration, id: string, devices: N
}
}
async function prepareNative(id: string, configuration: IxConfiguration, previousConfiguration: IxConfiguration | null): Promise<IxNativeChange> {
const objects = compileIxConfiguration(id, configuration)
async function prepareNative(id: string, configuration: IxConfiguration | null, previousConfiguration: IxConfiguration | null): Promise<IxNativeChange> {
const objects = configuration ? compileIxConfiguration(id, configuration) : []
const previous = previousConfiguration ? compileIxConfiguration(id, previousConfiguration) : []
const before: NativeDevice[] = []
for (const serverId of [...new Set([...objects, ...previous].map(object => object.serverId))].sort((a, b) => a - b)) {
const server = await getServerRowById(serverId)
if (!server?.enabled || server.type !== "ix-node") throw new IxConflict("Площадка IX отключена или изменила тип")
before.push(await readDevice(server, [...objects, ...previous].filter(object => object.serverId === serverId)))
before.push(await readDevice(server, [...objects, ...previous].filter(object => object.serverId === serverId), !configuration))
}
validateBindings(configuration, id, before)
if (configuration) validateBindings(configuration, id, before)
for (const device of before) verifyEgressMembers(device, id, previous)
for (const old of previousConfiguration?.sites ?? []) {
const next = configuration.sites.find(site => site.serverId === old.serverId)
const next = configuration?.sites.find(site => site.serverId === old.serverId)
const device = before.find(device => device.serverId === old.serverId)!
if (!configuration) verifyRemovalScope(id, device, previous)
for (const binding of old.interfaces.filter(binding => !next?.interfaces.some(candidate => candidate.name === binding.name))) {
if (!rowsFor(device, "/interface").some(row => row.name === binding.name && isTrue(row.disabled))) {
const iface = rowsFor(device, "/interface").find(row => row.name === binding.name)
if (!configuration && (!iface || binding.provisionWireguard || !rowsFor(device, "/ip/vrf").some(row => row.name === ixNamespace(id)))) continue
if (!isTrue(iface?.disabled)) {
throw new IxConflict("Отключите интерфейс перед исключением из VRF IX: " + binding.name)
}
}
}
return { objects, before, tasks: planIxNative(id, objects, previous, before) }
const remaining = configuration ? previous : previous.filter(object =>
managedRow(before.find(device => device.serverId === object.serverId)!, object))
return { objects, before, tasks: planIxNative(id, objects, remaining, before) }
}
function verifyRemovalScope(id: string, device: NativeDevice, previous: IxRouterObject[]) {
const namespace = ixNamespace(id)
const managed = previous.filter(object => object.serverId === device.serverId)
const known = new Set(managed.map(objectMarker))
const interfaces = new Set(managed.filter(object => ["/interface/wireguard", "/interface/bridge", "/ip/vrf"].includes(object.path))
.map(object => object.fields.name))
for (const [path, rows] of Object.entries(device.rows)) {
if (path === "/interface") continue // RouterOS mirrors WireGuard and bridge objects here.
if (rows.some(row => !isTrue(row.dynamic) && !known.has(marker(path, row.comment ?? "")) &&
(row.comment?.startsWith(namespace + ":") || row["routing-table"] === namespace ||
[row.interface, row.bridge, row["in-interface"], row["out-interface"], ...(row.gateway?.split(/[@%]/) ?? [])].some(value => interfaces.has(value)) ||
[row["in-interface-list"], row["out-interface-list"]].includes(ixEgressList(id)) ||
managed.some(object => object.path === path && object.fields.name && object.fields.name === row.name)))) {
throw new IxConflict("На узле остались объекты, которых нет в применённой ревизии IX")
}
}
}
export async function prepareIxRemoval(id: string, revision: number) {
const segment = await readIxSegment(id)
if (!segment) throw new IxConflict("Сегмент IX не найден", 404)
assertIxRevision(segment, revision)
const applied = segment.appliedRevision === null ? null : await readIxRevision(id, segment.appliedRevision)
const native = await prepareNative(id, null, applied)
return { segment, native, digest: nativePlanDigest(native) }
}
export async function ixTarget(change: IxChange) {
@@ -370,6 +405,67 @@ export async function readIxLinuxClient(segment: IxSegment, serverId: number, na
}
}
async function applyNativeTasks(native: IxNativeChange, authorize: () => Promise<void>) {
for (const task of native.tasks) {
await authorize()
const server = await getServerRowById(task.serverId)
if (!server?.enabled || fingerprint(server) !== native.before.find(device => device.serverId === task.serverId)?.source) {
throw new IxConflict("Изменился источник конфигурации IX")
}
const client = MikrotikClient.fromServer(server)
const nativePath = task.rosId ? task.path + "/" + encodeURIComponent(task.rosId) : task.path
if (task.before) {
const observed = (await readRows(client, task.path, Object.keys(task.before))).find(row => row[".id"] === task.rosId)
if (!observed || !matches(observed, task.before)) throw new IxConflict("Объект IX изменился перед записью")
} else if (task.fields && (await readRows(client, task.path, [".id", "comment", "name"])).some(row =>
row.comment === task.fields?.comment || task.fields?.name && row.name === task.fields.name)) {
throw new IxConflict("Объект IX был создан после подготовки плана")
}
if (!task.fields) {
await client.delete(nativePath, undefined, authorize)
if ((await readRows(client, task.path, [".id"])).some(row => row[".id"] === task.rosId)) throw new IxConflict("Удаление объекта IX не подтверждено")
continue
}
const result = task.rosId
? await client.patch<NativeRow>(nativePath, task.fields, undefined, authorize)
: await client.put<NativeRow>(nativePath, { ...task.fields, ...(task.placeBefore ? { "place-before": task.placeBefore } : {}) }, undefined, authorize)
const returnedId = task.rosId ?? result?.[".id"]
if (!returnedId || !routerId.test(returnedId)) throw new IxConflict("RouterOS не подтвердил ID объекта IX")
const row = (await readRows(client, task.path, [".id", ...Object.keys(task.fields)])).find(entry => entry[".id"] === returnedId)
if (!row || !matches(row, task.fields)) throw new IxConflict("Перечитанный объект IX не совпал с планом")
const vrfName = task.path === "/ip/vrf" ? task.fields.name : undefined
if (vrfName) {
const deadline = Date.now() + 3000
while (!(await readRows(client, "/interface", ["name"])).some(entry => entry.name === vrfName)) {
if (Date.now() >= deadline) throw new IxConflict("RouterOS не создал интерфейс VRF IX")
await delay(100)
}
}
}
}
export async function removeIxSegment(id: string, revision: number, expectedDigest: string, actorId: string,
authorize = assertVerifiedConfigurationAccess) {
return withApplicationMutationLock(async () => {
await authorize()
const segment = await readIxSegment(id)
assertIxRevision(segment, revision)
const applied = segment?.appliedRevision ? await readIxRevision(id, segment.appliedRevision) : null
return withConfigMutationLock(applied ? ixDeviceIds(applied) : [], async () => {
const native = await prepareNative(id, null, applied)
if (nativePlanDigest(native) !== expectedDigest) throw new IxConflict("Конфигурация IX изменилась после предпросмотра")
await applyNativeTasks(native, authorize)
await authorize()
if (applied && (await prepareNative(id, null, applied)).tasks.length) {
throw new IxConflict("Удаление объектов IX не подтверждено")
}
await authorize()
await archiveIxSegment(id, revision, actorId)
return { segmentId: id, revision, configurationVerified: true, removedObjects: native.tasks.length }
})
}, { waitMs: 30_000 })
}
export async function applyIxChange(id: string, change: IxChange, expected: { revision: number; devices: string }, actorId: string,
authorize = assertVerifiedConfigurationAccess) {
return withApplicationMutationLock(async () => withConfigMutationLock(await ixTarget(change), async () => {
@@ -381,42 +477,7 @@ export async function applyIxChange(id: string, change: IxChange, expected: { re
const applied = current?.appliedRevision ? await readIxRevision(id, current.appliedRevision) : null
const native = await prepareNative(id, change.configuration, applied)
if (nativePlanDigest(native) !== expected.devices) throw new IxConflict("Конфигурация IX изменилась после предпросмотра")
for (const task of native.tasks) {
await authorize()
const server = await getServerRowById(task.serverId)
if (!server?.enabled || fingerprint(server) !== native.before.find(device => device.serverId === task.serverId)?.source) {
throw new IxConflict("Изменился источник конфигурации IX")
}
const client = MikrotikClient.fromServer(server)
const nativePath = task.rosId ? task.path + "/" + encodeURIComponent(task.rosId) : task.path
if (task.before) {
const observed = (await readRows(client, task.path, Object.keys(task.before))).find(row => row[".id"] === task.rosId)
if (!observed || !matches(observed, task.before)) throw new IxConflict("Объект IX изменился перед записью")
} else if (task.fields && (await readRows(client, task.path, [".id", "comment", "name"])).some(row =>
row.comment === task.fields?.comment || task.fields?.name && row.name === task.fields.name)) {
throw new IxConflict("Объект IX был создан после подготовки плана")
}
if (!task.fields) {
await client.delete(nativePath, undefined, authorize)
if ((await readRows(client, task.path, [".id"])).some(row => row[".id"] === task.rosId)) throw new IxConflict("Удаление объекта IX не подтверждено")
continue
}
const result = task.rosId
? await client.patch<NativeRow>(nativePath, task.fields, undefined, authorize)
: await client.put<NativeRow>(nativePath, { ...task.fields, ...(task.placeBefore ? { "place-before": task.placeBefore } : {}) }, undefined, authorize)
const returnedId = task.rosId ?? result?.[".id"]
if (!returnedId || !routerId.test(returnedId)) throw new IxConflict("RouterOS не подтвердил ID объекта IX")
const row = (await readRows(client, task.path, [".id", ...Object.keys(task.fields)])).find(entry => entry[".id"] === returnedId)
if (!row || !matches(row, task.fields)) throw new IxConflict("Перечитанный объект IX не совпал с планом")
const vrfName = task.path === "/ip/vrf" ? task.fields.name : undefined
if (vrfName) {
const deadline = Date.now() + 3000
while (!(await readRows(client, "/interface", ["name"])).some(entry => entry.name === vrfName)) {
if (Date.now() >= deadline) throw new IxConflict("RouterOS не создал интерфейс VRF IX")
await delay(100)
}
}
}
await applyNativeTasks(native, authorize)
await authorize()
for (const device of native.before) {
const server = await getServerRowById(device.serverId)
@@ -1,6 +1,7 @@
import type { PoolClient } from "pg"
import { ixSegmentConfigurationSchema, type IxConfiguration, type IxSegment } from "@mmapp/contracts/internet-exchange"
import { pool } from "../db/index.js"
import { audit } from "../modules/mcp/store.js"
import { IxConflict, ixDeviceIds } from "./internet-exchange-plan.js"
import { admitPartitionWriter } from "./partition-write-transaction.js"
@@ -13,6 +14,7 @@ interface SegmentRow {
}
const columns = "id,revision,applied_revision,configuration,updated_at"
const visible = "(configuration->>'deleted') IS DISTINCT FROM 'true'"
function segment(row: SegmentRow): IxSegment {
return { id: row.id, revision: row.revision, appliedRevision: row.applied_revision,
configuration: ixSegmentConfigurationSchema.parse(row.configuration), updatedAt: row.updated_at.toISOString() }
@@ -21,18 +23,23 @@ function segment(row: SegmentRow): IxSegment {
export async function listIxSegments(limit: number, offset: number, allowedIds?: readonly number[]) {
const { rows } = await pool.query<SegmentRow>(
`SELECT ${columns} FROM ix_segments s
WHERE $1::bigint[] IS NULL OR NOT EXISTS (
WHERE ${visible} AND ($1::bigint[] IS NULL OR NOT EXISTS (
SELECT 1 FROM ix_segment_devices d WHERE d.segment_id=s.id AND NOT (d.server_id=ANY($1::bigint[]))
)
))
ORDER BY name,id LIMIT $2 OFFSET $3`, [allowedIds ?? null, limit, offset])
return rows.map(segment)
}
export async function readIxSegment(id: string, sql: Pick<PoolClient, "query"> = pool) {
const { rows: [row] } = await sql.query<SegmentRow>(`SELECT ${columns} FROM ix_segments WHERE id=$1`, [id])
const { rows: [row] } = await sql.query<SegmentRow>(`SELECT ${columns} FROM ix_segments WHERE id=$1 AND ${visible}`, [id])
return row ? segment(row) : null
}
export async function isIxSegmentArchived(id: string, revision: number) {
const { rowCount } = await pool.query("SELECT 1 FROM ix_segments WHERE id=$1 AND revision=$2 AND configuration->>'deleted'='true'", [id, revision])
return rowCount === 1
}
export async function readIxRevision(id: string, revision: number) {
const { rows: [row] } = await pool.query("SELECT configuration FROM ix_segment_revisions WHERE segment_id=$1 AND revision=$2", [id, revision])
if (!row) throw new IxConflict("Ревизия IX не найдена", 404)
@@ -70,7 +77,7 @@ export async function writeIxRevision(id: string, expected: number, configuratio
[id, configuration.name, revision, JSON.stringify(configuration), applied ? revision : null])
: await client.query<SegmentRow>(`UPDATE ix_segments SET name=$2,revision=$3,configuration=$4::jsonb,
applied_revision=CASE WHEN $5::boolean THEN $3 ELSE applied_revision END,updated_at=now()
WHERE id=$1 AND revision=$6 RETURNING ${columns}`,
WHERE id=$1 AND revision=$6 AND ${visible} RETURNING ${columns}`,
[id, configuration.name, revision, JSON.stringify(configuration), applied, expected])
if (!row) throw new IxConflict("Имя IX уже занято или ревизия сменилась")
// Keep references to the applied topology while it can still hold live resources.
@@ -90,3 +97,24 @@ export async function writeIxRevision(id: string, expected: number, configuratio
throw error
} finally { client.release() }
}
export async function archiveIxSegment(id: string, revision: number, actorId: string) {
const client = await pool.connect()
try {
await client.query("BEGIN")
await admitPartitionWriter(client)
// Keep the revision journal and free the name and device references using the existing writer grants.
const { rowCount } = await client.query(`UPDATE ix_segments
SET name='deleted:' || id::text, configuration=configuration || '{"deleted":true}'::jsonb, updated_at=now()
WHERE id=$1 AND revision=$2 AND ${visible}`, [id, revision])
if (rowCount !== 1) throw new IxConflict("Ревизия IX изменилась. Обновите данные и подготовьте новый план")
await client.query("DELETE FROM ix_segment_devices WHERE segment_id=$1", [id])
await audit(client, actorId, "ix.segment.deleted", null, { segmentId: id, revision })
await client.query("COMMIT")
} catch (error) {
await client.query("ROLLBACK").catch(() => {})
throw error
} finally {
client.release()
}
}
+4
View File
@@ -60,6 +60,10 @@
- **WireGuard.** Создайте пару ключей на Linux и внесите в форму публичный ключ. Включите создание интерфейса и пира. Укажите порт, адреса туннеля, внешний адрес IX и префиксы за клиентом. Шаблон `wg-quick` использует `Table = off`. Добавьте на Linux нужные маршруты или настройте BGP по параметрам из карточки.
- **GRE/IPsec.** Подготовьте на узле выделенный GRE с отключённым FastPath и обязательной политикой IKEv2/IPsec в транспортном режиме. Задайте оба фиксированных внешних IPv4-адреса в IX. Скачайте шаблон strongSwan, согласуйте предложения и идентификаторы IKE с узлом, подставьте отдельный PSK клиента. После установки IPsec поднимите GRE по командам из вкладки. При использовании статической маршрутизации назначьте согласованный адрес внутри туннеля и добавьте нужные маршруты.
### Удаление сегмента
Откройте карточку сегмента, нажмите «Удалить сегмент» и подтвердите. Черновик исчезнет из списка. Для применённого сегмента WebUI показывает план очистки RouterOS. Перед удалением отключите вручную подключённые интерфейсы из этого сегмента, если WebUI сообщает об этом. Запись скрывается после проверки удаления управляемых объектов, история ревизий сохраняется.
## MCP и ввод в эксплуатацию
`mm_ix_segments_list` и `mm_ix_segment_get` читают конфигурацию и наблюдения в разрешённой области. `mm_ix_change_plan` готовит изменение, `mm_ix_restore_plan` готовит восстановление сохранённой ревизии. Применение, сверка и журнал общие с остальными функциями MCP.
+39
View File
@@ -130,3 +130,42 @@ test("IX: редактирование и применение сохранён
expect(mcpCalls).toEqual([])
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(390)
})
test("IX: черновик удаляется после подтверждения в карточке", async ({ page }) => {
const draft = { id, revision: 1, appliedRevision: null, updatedAt: observedAt,
configuration: ixSegmentConfigurationSchema.parse({ name: "ix-eu", sites: [{ serverId: 1, autonomousSystem: 64512, routerId: "192.0.2.10" }] }) }
const digest = "b".repeat(64)
let deleted = false
await page.route("**/health", route => route.fulfill({ json: { ok: true } }))
await page.route("**/api/**", async route => {
const request = route.request()
const path = new URL(request.url()).pathname
if (path === "/api/auth/config") return route.fulfill({ json: { required: false } })
if (path === "/api/ix/nodes") return route.fulfill({ json: { items: nodes } })
if (path === "/api/ix/segments") return route.fulfill({ json: { items: deleted ? [] : [draft] } })
if (path === `/api/ix/segments/${id}/removal-plan`) {
expect(request.postDataJSON()).toEqual({ revision: 1 })
return route.fulfill({ json: { revision: 1, digest, changes: [] } })
}
if (path === `/api/ix/segments/${id}`) {
expect(request.method()).toBe("DELETE")
expect(request.postDataJSON()).toEqual({ revision: 1, digest })
deleted = true
return route.fulfill({ status: 204 })
}
return route.fulfill({ json: {} })
})
await page.goto("/ix")
await page.getByRole("button", { name: "ix-eu", exact: true }).click()
const remove = page.getByRole("button", { name: "Удалить сегмент", exact: true })
await remove.click()
await expect(page.getByRole("alertdialog", { name: "Удалить ix-eu?" })).toBeVisible()
await page.getByRole("button", { name: "Отмена", exact: true }).click()
expect(deleted).toBe(false)
await remove.click()
await page.getByRole("button", { name: "Удалить", exact: true }).click()
await expect(page.getByText("Сегмент ix-eu удалён")).toBeVisible()
await expect(page.getByText("Нет сегментов IX")).toBeVisible()
expect(deleted).toBe(true)
})