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

This commit is contained in:
Denozordec committed 2026-11-23 11:00:47 +07:00
1 parent be1cb6381a
commit e11e67b3a1
10 files changed
+472 -87

No files matched your search

+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()))