Compare commits

...
2 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
Denozordec be1cb6381a fix(ix): восстановить применение и подключение клиентов
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 10m17s
Docker images / backend-image (push) Successful in 1m59s
Docker images / frontend-image (push) Successful in 2m10s
Docker images / updater-image (push) Successful in 38s
Docker images / netflow-agent-image (push) Successful in 33s
Docker images / notify-webhook (push) Successful in 1s
Docker images / publish-release (push) Successful in 10s
2026-11-23 10:22:45 +07:00
17 changed files with 1395 additions and 236 deletions

No files matched your search

+228
View File
@@ -0,0 +1,228 @@
"use client"
import { useId, type ReactNode } from "react"
import Link from "next/link"
import { PlusIcon, XIcon } from "lucide-react"
import type { IxSite } from "@mmapp/contracts/internet-exchange"
import { Button } from "@/components/ui/button"
import { Field, FieldLabel } from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Checkbox } from "@/components/ui/checkbox"
import { Textarea } from "@/components/ui/textarea"
type Binding = IxSite["interfaces"][number]
type Group = IxSite["groups"][number]
type Path = Group["primary"]
type Peer = IxSite["neighbors"][number]
type Choice = { value: string; label: string }
function TextField({ label, value, edit, numeric, placeholder }: {
label: string; value: string | number; edit: (value: string) => void; numeric?: boolean; placeholder?: string
}) {
const id = useId()
return <Field className="min-w-0">
<FieldLabel htmlFor={id}>{label}</FieldLabel>
<Input id={id} value={value} inputMode={numeric ? "numeric" : undefined} placeholder={placeholder}
onChange={event => { if (!numeric || /^\d*$/.test(event.target.value)) edit(event.target.value) }} />
</Field>
}
function Pick<T extends string>({ label, value, options, edit, disabled }: {
label: string; value?: T; options: readonly { value: T; label: string }[]; edit: (value: T) => void; disabled: boolean
}) {
const id = useId()
return <Field className="min-w-0">
<FieldLabel htmlFor={id}>{label}</FieldLabel>
<Select value={value ?? null} items={options} disabled={disabled}
onValueChange={next => { if (next !== null) edit(next) }}>
<SelectTrigger className="w-full" id={id}><SelectValue placeholder="Выберите значение" /></SelectTrigger>
<SelectContent>{options.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}</SelectContent>
</Select>
</Field>
}
function Flag({ label, checked, edit, disabled }: {
label: string; checked: boolean; edit: (value: boolean) => void; disabled: boolean
}) {
const id = useId()
return <Field orientation="horizontal" className="w-fit">
<Checkbox id={id} checked={checked} onCheckedChange={edit} disabled={disabled} />
<FieldLabel htmlFor={id}>{label}</FieldLabel>
</Field>
}
function Lines({ label, value, edit }: { label: string; value: string[]; edit: (value: string[]) => void }) {
const id = useId()
return <Field className="min-w-0">
<FieldLabel htmlFor={id}>{label}</FieldLabel>
<Textarea id={id} value={value.join("\n")} rows={2} placeholder="По одному префиксу на строку"
onChange={event => edit(event.target.value.split("\n"))}
onBlur={event => edit(event.target.value.split("\n").map(line => line.trim()).filter(Boolean))} />
</Field>
}
function Entries<T>({ title, items, edit, make, addLabel, max, readOnly, children }: {
title: string; items: T[]; edit: (items: T[]) => void; make: () => T
addLabel: string; max: number; readOnly: boolean; children: (item: T, edit: (item: T) => void) => ReactNode
}) {
return <details className="min-w-0 rounded-lg border">
<summary className="cursor-pointer px-3 py-2 text-sm font-medium">{title} · {items.length}</summary>
<div className="grid gap-3 border-t p-3">
{items.map((item, index) => <div className="grid min-w-0 gap-3 rounded-md border p-3" key={index}>
<div className="flex items-center justify-between gap-2 text-sm text-muted-foreground">
<span>Запись {index + 1}</span>
{!readOnly && <Button type="button" size="icon-sm" variant="ghost" aria-label={title + " — удалить запись " + (index + 1)}
onClick={() => edit(items.filter((_, position) => position !== index))}><XIcon aria-hidden /></Button>}
</div>
{children(item, update => edit(items.map((entry, position) => position === index ? update : entry)))}
</div>)}
{!readOnly && <Button type="button" variant="outline" size="sm" className="w-fit" disabled={items.length >= max}
onClick={() => edit([...items, make()])}><PlusIcon aria-hidden />{addLabel}</Button>}
</div>
</details>
}
const columns = "grid min-w-0 gap-3 sm:grid-cols-2"
const none = {value: "", label: "Нет"}
const emptyPath = (name: string): Path => ({ interface: name, nextHop: "", probe: "" })
const emptyWireGuard = { peerPublicKey: "", listenPort: 51820, localAddress: "", peerAddress: "" }
const kinds = [
{ value: "wireguard", label: "WireGuard" }, { value: "gre-ipsec", label: "GRE/IPsec" }, { value: "uplink", label: "Аплинк" },
] as const
function InterfaceFields({ value, edit, peers, readOnly, segmentName }: {
value: Binding; edit: (value: Binding) => void; peers: Choice[]; readOnly: boolean; segmentName: string
}) {
const wireGuard = value.provisionWireguard
return <>
<div className={columns}>
<TextField label="Имя интерфейса" value={value.name} edit={name => edit({ ...value, name })} />
<Pick label="Тип подключения" value={value.kind} options={kinds} disabled={readOnly}
edit={kind => edit({ ...value, kind, ...(kind !== "wireguard" && {provisionWireguard: undefined}), ...(kind !== "uplink" && {natIpv4: undefined}) })} />
<Pick label="Удалённый узел" value={value.peerServerId ? String(value.peerServerId) : ""} options={[{ value: "", label: "Внешний сервер" }, ...peers]} disabled={readOnly}
edit={id => edit({ ...value, peerServerId: id ? Number(id) : undefined })} />
<TextField label="Локальный внешний адрес" value={value.localEndpoint ?? ""} edit={address => edit({ ...value, localEndpoint: address || undefined })} />
<TextField label="Удалённый внешний адрес" value={value.endpoint ?? ""} edit={address => edit({ ...value, endpoint: address || undefined })} />
</div>
<Lines label="Префиксы подключения" value={value.prefixes} edit={prefixes => edit({ ...value, prefixes })} />
{value.kind === "gre-ipsec" && <p className="text-sm text-muted-foreground">
Создайте выделенный туннель в разделе <Link className="underline" href="/gre">GRE-туннели</Link>.
Укажите комментарий <code>IX:{segmentName || "<имя сегмента>"}</code>, включите IPsec и отключите FastPath.
IX проверит обязательную транспортную политику GRE между указанными IPv4-адресами.
</p>}
{(value.kind === "uplink" || (value.kind === "wireguard" && !wireGuard)) && <p className="text-sm text-muted-foreground">
Для подключения существующего интерфейса выделите его под этот сегмент и задайте комментарий <code>IX:{segmentName || "<имя сегмента>"}</code>.
</p>}
{value.kind === "uplink" && <Flag label="NAT IPv4" checked={!!value.natIpv4} disabled={readOnly} edit={natIpv4 => edit({ ...value, natIpv4 })} />}
{value.kind === "wireguard" && <Flag label="Создать интерфейс и пир WireGuard на узле IX" checked={!!wireGuard} disabled={readOnly}
edit={enabled => edit({ ...value, provisionWireguard: enabled ? { ...emptyWireGuard } : undefined })} />}
{wireGuard && <div className={columns}>
<TextField label="Публичный ключ пира" value={wireGuard.peerPublicKey} edit={peerPublicKey => edit({ ...value, provisionWireguard: { ...wireGuard, peerPublicKey } })} />
<TextField label="Порт WireGuard на IX" numeric value={wireGuard.listenPort || ""} edit={port => edit({ ...value, provisionWireguard: { ...wireGuard, listenPort: Number(port) } })} />
<TextField label="Локальный адрес туннеля (CIDR)" value={wireGuard.localAddress} edit={localAddress => edit({ ...value, provisionWireguard: { ...wireGuard, localAddress } })} />
<TextField label="Адрес пира в туннеле" value={wireGuard.peerAddress} edit={peerAddress => edit({ ...value, provisionWireguard: { ...wireGuard, peerAddress } })} />
<TextField label="Внешний адрес IX для шаблона Linux" value={wireGuard.hubEndpoint ?? ""} edit={address => edit({ ...value, provisionWireguard: { ...wireGuard, hubEndpoint: address || undefined } })} />
<TextField label="Порт удалённого WireGuard" numeric value={wireGuard.endpointPort ?? ""} edit={port => edit({ ...value, provisionWireguard: { ...wireGuard, endpointPort: port ? Number(port) : undefined } })} />
</div>}
</>
}
function PathFields({ title, value, edit, interfaces, readOnly }: {
title: string; value: Path; edit: (value: Path) => void; interfaces: Choice[]; readOnly: boolean
}) {
return <fieldset className="grid min-w-0 gap-3 rounded-md border p-3 sm:grid-cols-3">
<legend className="px-1 text-sm font-medium">{title}</legend>
<Pick label="Интерфейс пути" value={value.interface} options={interfaces} edit={name => edit({ ...value, interface: name })} disabled={readOnly} />
<TextField label="Адрес следующего шлюза" value={value.nextHop} edit={nextHop => edit({ ...value, nextHop })} />
<TextField label="Контрольный адрес" value={value.probe} edit={probe => edit({ ...value, probe })} />
</fieldset>
}
function GroupFields({ value, edit, interfaces, readOnly }: {
value: Group; edit: (value: Group) => void; interfaces: Choice[]; readOnly: boolean
}) {
return <>
<div className={columns}>
<TextField label="Имя группы шлюзов" value={value.id} edit={id => edit({ ...value, id })} />
<TextField label="Служебный адрес шлюза" value={value.gateway} edit={gateway => edit({ ...value, gateway })} />
<Pick label="Если оба пути недоступны" value={value.onFailure} disabled={readOnly} options={[
{value: "block", label: "Отбрасывать трафик"}, {value: "segment-exit", label: "Использовать выход сегмента"},
]} edit={onFailure => edit({ ...value, onFailure })} />
</div>
<PathFields title="Основной путь" value={value.primary} interfaces={interfaces} readOnly={readOnly} edit={primary => edit({ ...value, primary })} />
<Flag label="Резервный путь" checked={!!value.backup} disabled={readOnly}
edit={enabled => edit({ ...value, backup: enabled ? emptyPath(interfaces.find(item => item.value !== value.primary.interface)?.value ?? "") : undefined })} />
{value.backup && <PathFields title="Резервный путь" value={value.backup} interfaces={interfaces} readOnly={readOnly} edit={backup => edit({ ...value, backup })} />}
</>
}
function PeerFields({ value, edit, interfaces, groups, readOnly }: {
value: Peer; edit: (value: Peer) => void; interfaces: Choice[]; groups: Choice[]; readOnly: boolean
}) {
const publicFeed = value.type === "public-feed"
return <>
<div className={columns}>
<TextField label="Имя BGP-соседа" value={value.id} edit={id => edit({ ...value, id })} />
<Pick label="Тип BGP-соседа" value={value.type} disabled={readOnly} options={[
{value: "member", label: "Участник IX"}, {value: "exchange", label: "Вторая площадка"}, {value: "public-feed", label: "Публичный фид"},
]} edit={type => edit({ ...value, type, ...(type === "public-feed" ? { group: undefined, exportPrefixes: [] } : { rules: [] }) })} />
<TextField label="Адрес BGP-соседа" value={value.address} edit={address => edit({ ...value, address })} />
<TextField label="Локальный адрес BGP" value={value.localAddress} edit={localAddress => edit({ ...value, localAddress })} />
<TextField label="ASN соседа" numeric value={value.remoteAs || ""} edit={asn => edit({ ...value, remoteAs: Number(asn) })} />
<Pick label="Интерфейс BGP" value={value.binding} options={interfaces} disabled={readOnly} edit={binding => edit({ ...value, binding })} />
<Pick label="Лимит префиксов" value={String(value.limit)} options={[10, 100, 1000, 10000].map(limit => ({value: String(limit), label: String(limit)}))}
disabled={readOnly} edit={limit => edit({ ...value, limit: Number(limit) as Peer["limit"] })} />
{!publicFeed && <Pick label="Группа шлюзов для импорта" value={value.group} options={groups} disabled={readOnly} edit={group => edit({ ...value, group })} />}
</div>
<Lines label="Префиксы импорта" value={value.prefixes} edit={prefixes => edit({ ...value, prefixes })} />
{publicFeed
? <Entries title="Правила по BGP community" items={value.rules} edit={rules => edit({ ...value, rules })}
make={() => ({ community: "", group: groups[0]?.value ?? "" })} max={100} addLabel="Добавить правило" readOnly={readOnly}>
{(rule, update) => <div className={columns}>
<TextField label="BGP community" value={rule.community} placeholder="65000:10" edit={community => update({ ...rule, community })} />
<Pick label="Группа шлюзов правила" value={rule.group} options={groups} edit={group => update({ ...rule, group })} disabled={readOnly} />
</div>}
</Entries>
: <Lines label="Префиксы экспорта" value={value.exportPrefixes} edit={exportPrefixes => edit({ ...value, exportPrefixes })} />}
</>
}
export function IxSiteEditor({ site, edit, peers, readOnly, segmentName }: {
site: IxSite; edit: (fields: Partial<IxSite>) => void; peers: Choice[]; readOnly: boolean; segmentName: string
}) {
const interfaces = site.interfaces.filter(item => item.name).map(item => ({ value: item.name, label: item.name }))
const groups = site.groups.filter(item => item.id).map(item => ({ value: item.id, label: item.id }))
return <fieldset className="grid min-w-0 gap-2" disabled={readOnly}>
<Entries<Binding> title="Подключения" items={site.interfaces} edit={interfaces => edit({ interfaces })}
make={() => ({ name: "", kind: "wireguard", prefixes: [] })} max={20} addLabel="Добавить подключение" readOnly={readOnly}>
{(value, update) => <InterfaceFields value={value} edit={update} peers={peers} readOnly={readOnly} segmentName={segmentName} />}
</Entries>
<Entries<Group> title="Группы шлюзов" items={site.groups} edit={groups => edit({ groups })}
make={() => ({ id: "", gateway: "", primary: emptyPath(interfaces[0]?.value ?? ""), onFailure: "block" })}
max={24} addLabel="Добавить группу шлюзов" readOnly={readOnly}>
{(value, update) => <GroupFields value={value} edit={update} interfaces={interfaces} readOnly={readOnly} />}
</Entries>
<Entries title="Статические маршруты" items={site.routes} edit={routes => edit({ routes })}
make={() => ({ prefix: "", group: groups[0]?.value ?? "" })} max={250} addLabel="Добавить маршрут" readOnly={readOnly}>
{(route, update) => <div className={columns}>
<TextField label="Префикс маршрута" value={route.prefix} edit={prefix => update({ ...route, prefix })} />
<Pick label="Группа шлюзов маршрута" value={route.group} options={groups} edit={group => update({ ...route, group })} disabled={readOnly} />
</div>}
</Entries>
<Entries<Peer> title="BGP-соседи" items={site.neighbors} edit={neighbors => edit({ neighbors })} max={16} addLabel="Добавить BGP-соседа" readOnly={readOnly}
make={() => ({ id: "", type: "member", address: "", localAddress: "", remoteAs: 0,
binding: interfaces[0]?.value ?? "", group: groups[0]?.value, prefixes: [], exportPrefixes: [], rules: [], limit: 1000 })}>
{(value, update) => <PeerFields value={value} edit={update} interfaces={interfaces} groups={groups} readOnly={readOnly} />}
</Entries>
<details className="rounded-lg border">
<summary className="cursor-pointer px-3 py-2 text-sm font-medium">Выходы по умолчанию и маршруты отбрасывания</summary>
<div className="grid gap-3 border-t p-3">
{[0, 1].map(index => <Pick key={index} label={"Группа выхода " + (index + 1)} value={site.exits[index] ?? ""}
options={[none, ...groups.filter(group => group.value !== site.exits[1 - index])]} disabled={readOnly}
edit={id => { const exits = [...site.exits]; exits[index] = id; edit({ exits: exits.filter(Boolean) }) }} />)}
<Lines label="Префиксы отбрасывания" value={site.discardNetworks} edit={discardNetworks => edit({ discardNetworks })} />
</div>
</details>
</fieldset>
}
+6 -11
View File
@@ -13,6 +13,7 @@ import { Button } from "@/components/ui/button"
import { Field, FieldDescription, FieldLabel } from "@/components/ui/field" import { Field, FieldDescription, FieldLabel } from "@/components/ui/field"
import { Input } from "@/components/ui/input" import { Input } from "@/components/ui/input"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select" import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { IxSiteEditor } from "./ix-site-editor"
export type IxNode = { id: number; name: string; site: string; country: string; enabled: boolean } export type IxNode = { id: number; name: string; site: string; country: string; enabled: boolean }
type Route = IxSiteObservation["routes"][number] type Route = IxSiteObservation["routes"][number]
@@ -47,8 +48,8 @@ export function SegmentGrid({ rows, nodes, loading, open, empty }: {
return <DataGridShell table={table} recordCount={rows.length} isLoading={loading} loadingMode="skeleton" emptyMessage={empty} /> return <DataGridShell table={table} recordCount={rows.length} isLoading={loading} loadingMode="skeleton" emptyMessage={empty} />
} }
export function ConfigurationFields({ configuration, nodes, readOnly, change }: { export function ConfigurationFields({ configuration, nodes, peers, readOnly, change }: {
configuration: IxConfiguration; nodes: IxNode[]; readOnly: boolean; change: (value: IxConfiguration) => void configuration: IxConfiguration; nodes: IxNode[]; peers: IxNode[]; readOnly: boolean; change: (value: IxConfiguration) => void
}) { }) {
function updateSite(index: number, fields: Partial<IxSite>) { function updateSite(index: number, fields: Partial<IxSite>) {
change({ ...configuration, sites: configuration.sites.map((site, position) => position === index ? { ...site, ...fields } : site) }) change({ ...configuration, sites: configuration.sites.map((site, position) => position === index ? { ...site, ...fields } : site) })
@@ -109,15 +110,9 @@ export function ConfigurationFields({ configuration, nodes, readOnly, change }:
onChange={event => updateSite(index, { routerId: event.target.value })} /> onChange={event => updateSite(index, { routerId: event.target.value })} />
</Field> </Field>
</div> </div>
<dl className="grid grid-cols-2 gap-3 border-t pt-3 text-sm sm:grid-cols-4"> <IxSiteEditor site={site} segmentName={configuration.name} readOnly={readOnly} edit={fields => updateSite(index, fields)}
{[ peers={peers.filter(node => node.id !== site.serverId && (node.enabled || site.interfaces.some(binding => binding.peerServerId === node.id)))
["Интерфейсы", site.interfaces.length], ["Группы шлюзов", site.groups.length], .map(node => ({ value: String(node.id), label: node.name }))} />
["Маршруты", site.routes.length], ["BGP-соседи", site.neighbors.length],
].map(([label, count]) => <div className="grid gap-0.5" key={label}>
<dt className="text-xs text-muted-foreground">{label}</dt>
<dd className="font-medium tabular-nums">{count}</dd>
</div>)}
</dl>
</FramePanel> </FramePanel>
</Frame> </Frame>
})} })}
+197 -111
View File
@@ -2,63 +2,72 @@
import { useEffect, useRef, useState } from "react" import { useEffect, useRef, useState } from "react"
import Link from "next/link" 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 IxRouterObject, type IxSegment, type IxSiteObservation } from "@mmapp/contracts/internet-exchange" 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 { Alert, AlertDescription, AlertTitle } from "@/components/reui/alert"
import { Badge } from "@/components/reui/badge"
import { Frame, FrameDescription, FrameHeader, FramePanel, FrameTitle } from "@/components/reui/frame" import { Frame, FrameDescription, FrameHeader, FramePanel, FrameTitle } from "@/components/reui/frame"
import { EmptyState } from "@/components/empty-state" import { EmptyState } from "@/components/empty-state"
import { PageHeader } from "@/components/page-header" import { PageHeader } from "@/components/page-header"
import { Button } from "@/components/ui/button" import { Button, buttonVariants } from "@/components/ui/button"
import { Field, FieldLabel } from "@/components/ui/field" import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from "@/components/ui/alert-dialog"
import { Input } from "@/components/ui/input" import { Input } from "@/components/ui/input"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Skeleton } from "@/components/ui/skeleton" import { Skeleton } from "@/components/ui/skeleton"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs" import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Textarea } from "@/components/ui/textarea" import { Textarea } from "@/components/ui/textarea"
import { can, ensureAuthConfig } from "@/lib/auth" import { can, ensureAuthConfig } from "@/lib/auth"
import { useDataSource } from "@/lib/data-source" import { useDataSource } from "@/lib/data-source"
import { requestJson } from "@/shared/api/http-client" import { requestJson } from "@/shared/api/http-client"
import { mcpApi } from "@/shared/api/mcp" import { ConfigurationFields, newSite, nodeLabel, RouteGrid, SegmentGrid, SegmentStatus, type IxNode } from "./ix-view"
import { ConfigurationFields, newSite, RouteGrid, SegmentGrid, SegmentStatus, type IxNode } from "./ix-view"
type Connection = { id: string; name: string } type Tab = "configuration" | "routes" | "changes" | "linux"
type Plan = { planId: string; state: string }
type Tab = "configuration" | "routes" | "changes"
const title = "Точки обмена трафиком" const title = "Точки обмена трафиком"
const describe = (error: unknown) => error instanceof Error ? error.message : "Не удалось выполнить операцию IX" const describe = (error: unknown) => error instanceof Error ? error.message : "Не удалось выполнить операцию IX"
const json = (value: unknown) => JSON.stringify(value, null, 2) const json = (value: unknown) => JSON.stringify(value, null, 2)
const post = (value: unknown) => ({ method: "POST", body: JSON.stringify(value) }) const post = (value: unknown) => ({ method: "POST", body: JSON.stringify(value) })
const planStates: Record<string, string> = { const actionLabels = { create: "Создать", update: "Обновить", delete: "Удалить" } as const
draft: "Черновик плана", "awaiting-approval": "Ждёт подтверждения", approved: "Подтверждён",
pending: "В очереди", running: "Выполняется", completed: "Завершён", applied: "Применён", function RouterOsChanges({ changes, nodes }: { changes: IxWebPlan["changes"]; nodes: IxNode[] }) {
rejected: "Отклонён", expired: "Истёк", failed: "Ошибка", partial: "Выполнен частично", unknown: "Нужна сверка", 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() { export default function IxPage() {
const { backendUrl, mode, prefsHydrated } = useDataSource() const { backendUrl, mode, prefsHydrated } = useDataSource()
const [segments, setSegments] = useState<IxSegment[]>([]) const [segments, setSegments] = useState<IxSegment[]>([])
const [nodes, setNodes] = useState<IxNode[]>([]) const [nodes, setNodes] = useState<IxNode[]>([])
const [connections, setConnections] = useState<Connection[]>([]) const [peers, setPeers] = useState<IxNode[]>([])
const [connectionId, setConnectionId] = useState("")
const [connectionError, setConnectionError] = useState("")
const [selected, setSelected] = useState<IxSegment | null>(null) const [selected, setSelected] = useState<IxSegment | null>(null)
const [draft, setDraft] = useState<IxConfiguration | null>(null) const [draft, setDraft] = useState<IxConfiguration | null>(null)
const [advanced, setAdvanced] = useState<string | null>(null) const [advanced, setAdvanced] = useState<string | null>(null)
const [filter, setFilter] = useState("") const [filter, setFilter] = useState("")
const [observations, setObservations] = useState<IxSiteObservation[] | null>(null) const [observations, setObservations] = useState<IxSiteObservation[] | null>(null)
const [preview, setPreview] = useState<IxRouterObject[] | null>(null) const [linuxBindings, setLinuxBindings] = useState<IxLinuxBinding[]>([])
const [linux, setLinux] = useState("") const [linux, setLinux] = useState<(IxLinuxAccess & IxLinuxBinding) | null>(null)
const [plan, setPlan] = useState<Plan | null>(null) const [plan, setPlan] = useState<IxWebPlan | null>(null)
const [removalPlan, setRemovalPlan] = useState<IxWebPlan | null>(null)
const [tab, setTab] = useState<Tab>("configuration") const [tab, setTab] = useState<Tab>("configuration")
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
const [busy, setBusy] = useState(false) const [busy, setBusy] = useState(false)
const [error, setError] = useState("") const [error, setError] = useState("")
const [notice, setNotice] = useState("") const [notice, setNotice] = useState("")
const [write, setWrite] = useState(false) const [write, setWrite] = useState(false)
const [approve, setApprove] = useState(false)
const heading = useRef<HTMLHeadingElement>(null) const heading = useRef<HTMLHeadingElement>(null)
const focusAfterNavigation = useRef(false) const focusAfterNavigation = useRef(false)
const inDetail = draft !== null const inDetail = draft !== null
@@ -66,34 +75,15 @@ export default function IxPage() {
async function load(signal?: AbortSignal) { async function load(signal?: AbortSignal) {
if (signal?.aborted) return if (signal?.aborted) return
setWrite(can("mm:network:write")) setWrite(can("mm:network:write"))
setApprove(can("mm:mcp:approve"))
const [segmentsResult, nodesResult] = await Promise.all([ const [segmentsResult, nodesResult] = await Promise.all([
requestJson<{ items: IxSegment[] }>(backendUrl, "/api/ix/segments?limit=100", { signal }), requestJson<{ items: IxSegment[] }>(backendUrl, "/api/ix/segments?limit=100", { signal }),
requestJson<{ items: IxNode[] }>(backendUrl, "/api/ix/nodes", { signal }), requestJson<{ items: IxNode[]; peers?: IxNode[] }>(backendUrl, "/api/ix/nodes", { signal }),
]) ])
if (signal?.aborted) return if (signal?.aborted) return
setSegments(segmentsResult.items) setSegments(segmentsResult.items)
setNodes(nodesResult.items) setNodes(nodesResult.items)
setConnectionError("") setPeers(nodesResult.peers ?? nodesResult.items)
if (!can("mm:mcp:read")) {
setConnections([])
setConnectionId("")
return
}
try {
const result = await mcpApi(backendUrl).connections(signal)
if (signal?.aborted) return
const available = result.connections.filter(connection => connection.policy.status === "active" &&
connection.policy.scope.operationIds.includes("network.ix.configure"))
setConnections(available.map(connection => ({ id: connection.id, name: connection.name })))
setConnectionId(current => available.some(connection => connection.id === current) ? current : available.length === 1 ? available[0].id : "")
} catch (error) {
if (signal?.aborted) return
setConnections([])
setConnectionId("")
setConnectionError(describe(error))
}
} }
useEffect(() => { useEffect(() => {
@@ -123,10 +113,13 @@ export default function IxPage() {
const enabledNodes = nodes.filter(node => node.enabled) const enabledNodes = nodes.filter(node => node.enabled)
const live = prefsHydrated && mode === "live" const live = prefsHydrated && mode === "live"
const canCreate = live && write && !loading && enabledNodes.length > 0 const canCreate = live && write && !loading && enabledNodes.length > 0
const savedConfiguration = selected ? json(selected.configuration) : null
const dirty = (advanced ?? json(draft)) !== savedConfiguration
const canPlan = live && write && selected !== null && selected.appliedRevision !== selected.revision && !dirty
function invalidateReview() { function invalidateReview() {
setPlan(null) setPlan(null)
setPreview(null) setRemovalPlan(null)
setNotice("") setNotice("")
} }
@@ -136,7 +129,8 @@ export default function IxPage() {
setDraft(segment?.configuration ?? { name: "", sites: [{ ...newSite(), serverId: enabledNodes.length === 1 ? enabledNodes[0].id : 0 }] }) setDraft(segment?.configuration ?? { name: "", sites: [{ ...newSite(), serverId: enabledNodes.length === 1 ? enabledNodes[0].id : 0 }] })
setAdvanced(null) setAdvanced(null)
setObservations(null) setObservations(null)
setLinux("") setLinux(null)
setLinuxBindings([])
setTab("configuration") setTab("configuration")
setError("") setError("")
invalidateReview() invalidateReview()
@@ -145,6 +139,7 @@ export default function IxPage() {
function close() { function close() {
focusAfterNavigation.current = true focusAfterNavigation.current = true
setDraft(null) setDraft(null)
setRemovalPlan(null)
setError("") setError("")
setNotice("") setNotice("")
} }
@@ -171,25 +166,81 @@ export default function IxPage() {
setNotice("Черновик сохранён") setNotice("Черновик сохранён")
} }
async function prepare() {
if (!selected || !canPlan) return
setPlan(null)
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)
try {
const { segment } = await requestJson<{ segment: IxSegment }>(backendUrl,
"/api/ix/segments/" + selected.id + "/apply", post({ revision: plan.revision, digest: plan.digest }))
setSelected(segment)
setDraft(segment.configuration)
setAdvanced(null)
setObservations(null)
setLinux(null)
setLinuxBindings([])
setSegments(current => current.map(item => item.id === segment.id ? segment : item))
setNotice("Конфигурация IX применена")
} catch (error) {
throw new Error(describe(error) + " Проверьте состояние сегмента перед повторным применением.")
}
}
async function observe() { async function observe() {
if (!selected?.appliedRevision) return if (!selected?.appliedRevision) return
const { sites } = await requestJson<{ sites: IxSiteObservation[] }>(backendUrl, `/api/ix/segments/${selected.id}/status`) const { sites } = await requestJson<{ sites: IxSiteObservation[] }>(backendUrl, `/api/ix/segments/${selected.id}/status`)
setObservations(sites) setObservations(sites)
} }
async function loadLinuxBindings() {
if (!selected) return
setLinux(null)
setLinuxBindings([])
const { items } = await requestJson<{ items: IxLinuxBinding[] }>(backendUrl, `/api/ix/segments/${selected.id}/linux`)
setLinuxBindings(items)
}
async function exportLinux(binding: IxLinuxBinding) {
if (!selected) return
setLinux(null)
const query = new URLSearchParams({ serverId: String(binding.serverId), interfaceName: binding.interfaceName })
const access = await requestJson<IxLinuxAccess>(backendUrl, `/api/ix/segments/${selected.id}/linux?${query}`)
setLinux({ ...binding, ...access })
}
function showTab(next: Tab) { function showTab(next: Tab) {
if (next === tab || busy) return if (next === tab || busy) return
setError("") setError("")
setTab(next) setTab(next)
if (next === "routes" && observations === null && selected?.appliedRevision) void perform(observe) if (next === "routes" && observations === null && selected?.appliedRevision) void perform(observe)
if (next === "linux" && selected?.appliedRevision) void perform(loadLinuxBindings)
} }
const listEmpty = error ? "Не удалось загрузить список" : const listEmpty = error ? "Не удалось загрузить список" :
filter.trim() ? "Сегменты не найдены" : !live ? "Подключите backend" : "Нет сегментов IX" filter.trim() ? "Сегменты не найдены" : !live ? "Подключите backend" : "Нет сегментов IX"
const listDescription = error ? "Повторите загрузку списка." : filter.trim() ? "Попробуйте другое имя сегмента." : const listDescription = error ? "Повторите загрузку списка." : filter.trim() ? "Попробуйте другое имя сегмента." :
!live ? "Откройте раздел в режиме «Живые»." : enabledNodes.length ? undefined : "Сначала добавьте сервер типа IX Node." !live ? "Откройте раздел в режиме «Живые»." : enabledNodes.length ? undefined : "Сначала добавьте сервер типа IX Node."
const linuxBindings = selected?.appliedRevision ? selected.configuration.sites.flatMap(site =>
site.interfaces.filter(binding => binding.provisionWireguard?.hubEndpoint).map(binding => ({ site, binding }))) : []
return <> return <>
<PageHeader crumbs={inDetail ? [{ label: "Сегменты IX" }, { label: selected?.configuration.name ?? "Новый сегмент" }] : [{ label: title }]} /> <PageHeader crumbs={inDetail ? [{ label: "Сегменты IX" }, { label: selected?.configuration.name ?? "Новый сегмент" }] : [{ label: title }]} />
@@ -210,6 +261,27 @@ export default function IxPage() {
Ревизия {selected.revision}{selected.appliedRevision ? ` · Применена ревизия ${selected.appliedRevision}` : ""} Ревизия {selected.revision}{selected.appliedRevision ? ` · Применена ревизия ${selected.appliedRevision}` : ""}
</p>) : <p className="mt-1 text-sm text-muted-foreground">Сегменты IX, площадки и маршрутизация</p>} </p>) : <p className="mt-1 text-sm text-muted-foreground">Сегменты IX, площадки и маршрутизация</p>}
</div> </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"> {!inDetail && <div className="flex flex-wrap items-center gap-2">
<Button type="button" size="icon-sm" variant="outline" disabled={busy || loading || !live} aria-label="Обновить список" <Button type="button" size="icon-sm" variant="outline" disabled={busy || loading || !live} aria-label="Обновить список"
onClick={() => void perform(() => load())}><RefreshCwIcon aria-hidden /></Button> onClick={() => void perform(() => load())}><RefreshCwIcon aria-hidden /></Button>
@@ -237,22 +309,23 @@ export default function IxPage() {
<div className="min-w-0 overflow-x-auto border-b pb-1"> <div className="min-w-0 overflow-x-auto border-b pb-1">
<TabsList variant="line" aria-label="Разделы сегмента"> <TabsList variant="line" aria-label="Разделы сегмента">
<TabsTrigger value="configuration">Конфигурация</TabsTrigger> <TabsTrigger value="configuration">Конфигурация</TabsTrigger>
<TabsTrigger value="linux">Linux-клиенты</TabsTrigger>
<TabsTrigger value="routes">Маршруты и BGP</TabsTrigger> <TabsTrigger value="routes">Маршруты и BGP</TabsTrigger>
<TabsTrigger value="changes">План изменений</TabsTrigger> <TabsTrigger value="changes">План изменений</TabsTrigger>
</TabsList> </TabsList>
</div> </div>
<TabsContent value="configuration" className="grid min-w-0 gap-3"> <TabsContent value="configuration" className="grid min-w-0 gap-3">
{advanced === null ? <ConfigurationFields configuration={draft} nodes={nodes} readOnly={!write || busy} {advanced === null ? <ConfigurationFields configuration={draft} nodes={nodes} peers={peers} readOnly={!live || !write || busy}
change={value => { setDraft(value); invalidateReview() }} /> : <Frame spacing="sm"> change={value => { setDraft(value); invalidateReview() }} /> : <Frame spacing="sm">
<FrameHeader><FrameTitle>Конфигурация JSON</FrameTitle><FrameDescription>Интерфейсы, группы шлюзов, маршруты и BGP-политики.</FrameDescription></FrameHeader> <FrameHeader><FrameTitle>Конфигурация JSON</FrameTitle><FrameDescription>Интерфейсы, группы шлюзов, маршруты и BGP-политики.</FrameDescription></FrameHeader>
<FramePanel> <FramePanel>
<Textarea aria-label="Конфигурация JSON" spellCheck={false} readOnly={!write || busy} rows={14} <Textarea aria-label="Конфигурация JSON" spellCheck={false} readOnly={!live || !write || busy} rows={14}
className="font-mono" value={advanced} onChange={event => { setAdvanced(event.target.value); invalidateReview() }} /> className="font-mono" value={advanced} onChange={event => { setAdvanced(event.target.value); invalidateReview() }} />
</FramePanel> </FramePanel>
</Frame>} </Frame>}
<div className="flex flex-wrap items-center gap-2"> <div className="flex flex-wrap items-center gap-2">
{write && <Button type="button" size="sm" disabled={busy} onClick={() => void perform(save)}>Сохранить черновик</Button>} {write && <Button type="button" size="sm" disabled={busy || !live} onClick={() => void perform(save)}>Сохранить черновик</Button>}
{advanced === null ? <Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => setAdvanced(json(draft))}> {advanced === null ? <Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => setAdvanced(json(draft))}>
{write ? "Редактировать JSON" : "Показать JSON"} {write ? "Редактировать JSON" : "Показать JSON"}
</Button> : <Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => void perform(async () => { </Button> : <Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => void perform(async () => {
@@ -269,80 +342,93 @@ export default function IxPage() {
<Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => void perform(observe)}> <Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => void perform(observe)}>
<RefreshCwIcon aria-hidden />Обновить состояние <RefreshCwIcon aria-hidden />Обновить состояние
</Button> </Button>
{linuxBindings.map(({ site, binding }) => <Button key={site.serverId + ":" + binding.name}
type="button" size="sm" variant="outline" disabled={busy} onClick={() => void perform(async () => {
const query = new URLSearchParams({ serverId: String(site.serverId), interfaceName: binding.name })
const result = await requestJson<{ template: string }>(backendUrl, `/api/ix/segments/${selected.id}/linux?${query}`)
setLinux(result.template)
})}>Linux · {binding.name}</Button>)}
</div> </div>
{linux && <Frame spacing="sm"><FrameHeader><FrameTitle>Конфигурация Linux</FrameTitle></FrameHeader>
<FramePanel><pre className="overflow-x-auto text-xs">{linux}</pre></FramePanel></Frame>}
{busy && observations === null && <Skeleton className="h-28 w-full" role="status" aria-label="Загрузка маршрутов" />} {busy && observations === null && <Skeleton className="h-28 w-full" role="status" aria-label="Загрузка маршрутов" />}
{observations?.map(site => <RouteGrid key={site.serverId} observation={site} nodes={nodes} />)} {observations?.map(site => <RouteGrid key={site.serverId} observation={site} nodes={nodes} />)}
</>} </>}
</TabsContent> </TabsContent>
<TabsContent value="linux" className="grid min-w-0 gap-3">
<Frame spacing="sm">
<FrameHeader>
<FrameTitle>Доступ для Linux-серверов</FrameTitle>
<FrameDescription>Выдайте каждому серверу отдельное подключение из применённой ревизии сегмента.</FrameDescription>
</FrameHeader>
<FramePanel className="grid min-w-0 gap-3">
{write && <div className="grid gap-2 text-sm text-muted-foreground">
<p>В «Конфигурации» добавьте подключение на нужной площадке и выберите «Внешний сервер» в поле «Удалённый узел».</p>
<p>Для WireGuard включите создание пира и укажите публичный ключ Linux, адреса, внешний адрес IX и разрешённые префиксы. Для GRE привяжите выделенный туннель с IKEv2/IPsec и отдельным PSK.</p>
<Button type="button" variant="outline" size="sm" className="w-fit" disabled={busy}
onClick={() => showTab("configuration")}>Открыть подключения</Button>
</div>}
{busy && linuxBindings.length === 0 ? <Skeleton className="h-12 w-full" role="status" aria-label="Загрузка Linux-клиентов" />
: !error && linuxBindings.length === 0 ? <p className="text-sm text-muted-foreground">В применённой ревизии пока нет подключений Linux.</p>
: linuxBindings.map(binding => <div key={binding.serverId + ":" + binding.interfaceName}
className="flex min-w-0 flex-wrap items-center justify-between gap-2 border-t pt-2">
<div className="min-w-0 text-sm">
<p className="wrap-anywhere font-medium">{binding.interfaceName}</p>
<p className="wrap-anywhere text-muted-foreground">{binding.kind === "wireguard" ? "WireGuard" : "GRE/IPsec"} · {nodeLabel(nodes, binding.serverId)}</p>
</div>
<Button type="button" size="sm" variant="outline" disabled={busy}
aria-label={"Получить конфиг " + binding.interfaceName} onClick={() => void perform(() => exportLinux(binding))}>Получить конфиг</Button>
</div>)}
</FramePanel>
</Frame>
{linux && <Frame spacing="sm">
<FrameHeader>
<FrameTitle>Конфигурация Linux · {linux.interfaceName}</FrameTitle>
<FrameDescription>Ревизия {linux.revision} · {nodeLabel(nodes, linux.serverId)}</FrameDescription>
</FrameHeader>
<FramePanel className="grid min-w-0 gap-3">
<p className="text-sm text-muted-foreground">{linux.kind === "wireguard"
? "Подставьте приватный ключ, сгенерированный на Linux. Шаблон wg-quick оставляет управление маршрутами на стороне Linux."
: "Подставьте PSK этого клиента и подключите файл к конфигурации strongSwan. Сверьте параметры IKE с подготовленным узлом IX."}</p>
<pre className="max-h-64 min-w-0 overflow-auto rounded-md border p-3 text-xs">{linux.template}</pre>
<a className={buttonVariants({ variant: "outline", size: "sm", className: "w-fit" })}
href={"data:text/plain;charset=utf-8," + encodeURIComponent(linux.template)} download={linux.filename}>Скачать {linux.filename}</a>
{linux.setup && <pre className="min-w-0 overflow-auto rounded-md border p-3 text-xs">{linux.setup}</pre>}
{linux.bgp && <p className="wrap-anywhere text-sm text-muted-foreground">
BGP · ASN Linux {linux.bgp.localAs} · ASN IX {linux.bgp.remoteAs} · сосед {linux.bgp.neighbor}
{linux.bgp.advertisedPrefixes.length > 0 && <> · анонсы Linux {linux.bgp.advertisedPrefixes.join(", ")}</>}
</p>}
</FramePanel>
</Frame>}
</TabsContent>
<TabsContent value="changes" className="grid min-w-0 gap-3"> <TabsContent value="changes" className="grid min-w-0 gap-3">
<Frame spacing="sm"> <Frame spacing="sm">
<FrameHeader> <FrameHeader>
<FrameTitle>Предпросмотр</FrameTitle> <FrameTitle>Изменения RouterOS</FrameTitle>
<FrameDescription>Объекты RouterOS, которые создаёт текущая конфигурация.</FrameDescription> <FrameDescription>Предпросмотр сравнивает сохранённую ревизию с текущим состоянием узлов.</FrameDescription>
</FrameHeader> </FrameHeader>
<FramePanel className="grid min-w-0 gap-3"> <FramePanel className="grid min-w-0 gap-3">
<Button type="button" size="sm" variant="outline" className="w-fit" disabled={busy} onClick={() => void perform(async () => { {!write ? <p className="text-sm text-muted-foreground">Нужно право изменять сетевую конфигурацию.</p>
const result = await requestJson<{ objects: IxRouterObject[] }>(backendUrl, "/api/ix/preview", post(change())) : dirty ? <p className="text-sm text-muted-foreground">Сохраните черновик на вкладке «Конфигурация».</p>
setPreview(result.objects) : selected?.appliedRevision === selected?.revision ? <p className="text-sm text-muted-foreground">Текущая ревизия применена.</p>
})}>Построить предпросмотр</Button> : <Button type="button" size="sm" variant="outline" className="w-fit" disabled={!canPlan || busy}
{preview && <details className="min-w-0 border-t pt-3"> onClick={() => void perform(prepare)}>Построить предпросмотр</Button>}
<summary className="cursor-pointer text-sm font-medium">Объекты RouterOS · {preview.length}</summary> {plan && <div className="grid min-w-0 gap-3 border-t pt-3">
<pre className="mt-2 overflow-x-auto text-xs">{json(preview)}</pre> <p className="text-sm font-medium">Ревизия {plan.revision} · операций RouterOS: {plan.changes.length}</p>
</details>} {plan.changes.length === 0 && <p className="text-sm text-muted-foreground">Конфигурация RouterOS совпадает с черновиком. Применение обновит ревизию в MikrotikManager.</p>}
</FramePanel> <RouterOsChanges changes={plan.changes} nodes={nodes} />
</Frame> <AlertDialog>
<AlertDialogTrigger render={<Button type="button" size="sm" className="w-fit" disabled={busy || !canPlan} />}>
{write && <Frame spacing="sm"> Применить план
<FrameHeader> </AlertDialogTrigger>
<FrameTitle>Применение через MCP</FrameTitle> <AlertDialogContent>
<FrameDescription>План, подтверждение и применение к площадкам сегмента.</FrameDescription> <AlertDialogHeader>
</FrameHeader> <AlertDialogTitle>Применить конфигурацию IX?</AlertDialogTitle>
<FramePanel className="grid min-w-0 gap-4"> <AlertDialogDescription>Будет применена ревизия {plan.revision} сегмента {selected?.configuration.name}. Операций RouterOS: {plan.changes.length}.</AlertDialogDescription>
{connectionError && <p role="status" className="wrap-anywhere text-sm text-muted-foreground">{connectionError}</p>} </AlertDialogHeader>
<div className="flex flex-wrap items-end gap-3"> <AlertDialogFooter>
<Field className="w-full min-w-0 sm:w-64"> <AlertDialogCancel>Отмена</AlertDialogCancel>
<FieldLabel htmlFor="ix-connection">Подключение MCP</FieldLabel> <AlertDialogAction onClick={() => void perform(apply)}>Применить</AlertDialogAction>
<Select value={connectionId || null} items={connections.map(connection => ({ value: connection.id, label: connection.name }))} </AlertDialogFooter>
disabled={busy || connections.length === 0} onValueChange={value => { setConnectionId(value ?? ""); setPlan(null) }}> </AlertDialogContent>
<SelectTrigger id="ix-connection" className="w-full"><SelectValue placeholder={connections.length ? "Выберите подключение" : "Нет доступных подключений"} /></SelectTrigger> </AlertDialog>
<SelectContent>{connections.map(connection => <SelectItem key={connection.id} value={connection.id}>{connection.name}</SelectItem>)}</SelectContent>
</Select>
</Field>
<Button type="button" size="sm" disabled={!connectionId || busy} onClick={() => void perform(async () => {
setPlan(await requestJson<Plan>(backendUrl, "/api/mcp/ix/plan", post({ connectionId, change: change() })))
})}>Подготовить план MCP</Button>
{connections.length === 0 && <Button render={<Link href="/mcp?tab=connections" />} nativeButton={false} variant="outline" size="sm">Открыть подключения</Button>}
</div>
{plan && <div className="flex flex-wrap items-center gap-2 border-t pt-3">
<Badge variant={plan.state === "awaiting-approval" ? "warning-light" : plan.state === "applied" ? "success-light" : "info-light"}>{planStates[plan.state] ?? plan.state}</Badge>
<Button render={<Link href="/mcp?tab=plans" />} nativeButton={false} size="sm" variant="link">Планы и операции</Button>
{plan.state === "awaiting-approval" && approve && <Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => void perform(async () => {
await mcpApi(backendUrl).decision(plan.planId, true)
setPlan({ ...plan, state: "approved" })
})}>Подтвердить</Button>}
{["draft", "approved"].includes(plan.state) && <Button type="button" size="sm" disabled={busy} onClick={() => void perform(async () => {
const name = change().configuration.name
const result = await mcpApi(backendUrl).apply(plan.planId)
setPlan({ ...plan, state: result.state })
if (result.state === "applied") {
const refreshed = await requestJson<{ items: IxSegment[] }>(backendUrl, "/api/ix/segments?limit=100")
setSegments(refreshed.items)
const applied = refreshed.items.find(segment => segment.id === selected?.id || segment.configuration.name === name)
if (applied) setSelected(applied)
}
})}>Применить план</Button>}
</div>} </div>}
</FramePanel> </FramePanel>
</Frame>} </Frame>
</TabsContent> </TabsContent>
</Tabs>} </Tabs>}
</div> </div>
+28
View File
@@ -1604,6 +1604,34 @@
"operations": [], "operations": [],
"reason": "Локальный предпросмотр объектов из компилятора. План MCP дополнительно фиксирует состояние площадок и требует подтверждения." "reason": "Локальный предпросмотр объектов из компилятора. План MCP дополнительно фиксирует состояние площадок и требует подтверждения."
}, },
{
"method": "POST",
"path": "/api/ix/segments/:id/plan",
"status": "mediated",
"operations": ["network.ix.configure"],
"reason": "Предпросмотр сохранённой ревизии для оператора. MCP строит отдельный план через общий сервис IX."
},
{
"method": "POST",
"path": "/api/ix/segments/:id/apply",
"status": "mediated",
"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", "method": "POST",
"path": "/api/ix/segments", "path": "/api/ix/segments",
+280
View File
@@ -0,0 +1,280 @@
import assert from "node:assert/strict"
import { randomBytes, randomUUID } from "node:crypto"
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-"))
const socket = createServer()
await new Promise<void>(resolve => socket.listen(0, "127.0.0.1", resolve))
const pgPort = (socket.address() as { port: number }).port
await new Promise<void>(resolve => socket.close(() => resolve()))
const password = randomBytes(24).toString("hex")
const pg = new EmbeddedPostgres({ databaseDir: join(dir, "pg"), user: "ixlab", password,
port: pgPort, persistent: false, initdbFlags: ["--encoding=UTF8", "--no-locale"], onLog() {} })
Object.assign(process.env, {
NODE_ENV: "test", DATABASE_URL: `postgres://ixlab:${password}@127.0.0.1:${pgPort}/postgres`,
MCP_STATE_DIR: join(dir, "state"), AUTH_REQUIRED: "true", AUTH_JWT_SECRET: randomBytes(32).toString("hex"),
DATABASE_PATH: join(dir, "no-legacy.sqlite"),
})
await pg.initialise()
await pg.start()
const rows: Record<string, Record<string, string>[]> = {
"/ip/vrf": [{ ".id": "*1", name: "main", interfaces: "all", builtin: "true" }],
"/interface": [{ ".id": "*A0", name: "gre-client", type: "gre", comment: "IX:ix-web-fixture" }],
"/interface/gre": [{ ".id": "*A0", name: "gre-client", "local-address": "192.0.2.20", "remote-address": "192.0.2.21", "allow-fast-path": "false" }],
"/ip/ipsec/policy": [{ ".id": "*A1", "src-address": "192.0.2.20/32", "dst-address": "192.0.2.21/32",
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/, "")
let result: unknown
if (request.method === "GET") result = rows[path] ?? []
else if (request.method === "PUT") {
let raw = ""
for await (const chunk of request) raw += chunk
const { "place-before": place, ...fields } = JSON.parse(raw)
const row = { ...fields, ...(path === "/interface/wireguard" && { "public-key": "B".repeat(43) + "=" }),
".id": "*" + (++writes + 1).toString(16).toUpperCase() }
const list = rows[path] ??= []
const index = list.findIndex(entry => entry[".id"] === place)
list.splice(index < 0 ? list.length : index, 0, row)
if (path === "/ip/vrf" || path === "/interface/wireguard" || path === "/interface/bridge") {
rows["/interface"].push({ ".id": row[".id"], name: row.name,
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))
} catch (error) {
response.statusCode = 500
response.end(JSON.stringify({ error: String(error) }))
}
})
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)
await new Promise<void>(resolve => router.listen(0, "127.0.0.1", resolve))
const port = (router.address() as { port: number }).port
const { rows: [server] } = await pool.query(`INSERT INTO servers
(name,host,port,enabled,type,username,password,use_ssl,verify_ssl)
VALUES('owned-ix','127.0.0.1',$1,true,'ix-node','synthetic','synthetic',false,true) RETURNING id`, [port])
const { buildApp } = await import("../../src/index.js")
const { env } = await import("../../src/config.js")
app = await buildApp({ logger: false, startScheduler: false })
const origin = await app.listen({ host: "127.0.0.1", port: 0 })
const token = (owner: string, permission: string) => app!.jwt.sign({ iss: env.authIssuer, sub: owner,
apps: ["mm"], permissions: [permission], iat: Math.floor(Date.now() / 1000) - 1, exp: Math.floor(Date.now() / 1000) + 600 })
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, 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 = reply.status === 204 ? undefined : await reply.json()
assert.equal(reply.status, status, JSON.stringify(data))
return data
}
const configuration = { name: "ix-web-fixture", sites: [{ serverId: Number(server.id),
autonomousSystem: 64512, routerId: "192.0.2.5", interfaces: [{ name: "wg-ix-web", kind: "wireguard",
prefixes: ["2001:db8:12::/48"], provisionWireguard: { peerPublicKey: "A".repeat(43) + "=",
listenPort: 51820, localAddress: "10.20.30.1/30", peerAddress: "10.20.30.2", hubEndpoint: "192.0.2.20" } },
{ name: "gre-client", kind: "gre-ipsec", localEndpoint: "192.0.2.20", endpoint: "192.0.2.21" }] }] }
const { segment } = await post("", { revision: 0, configuration }, 200)
assert.equal(segment.revision, 1)
assert.equal(segment.appliedRevision, null)
const path = "/" + segment.id
const linux = async (name?: string, status = 200) => {
const query = name ? "?" + new URLSearchParams({ serverId: String(server.id), interfaceName: name }) : ""
const response = await fetch(origin + "/api/ix/segments" + path + "/linux" + query, { headers: { authorization: "Bearer " + reader } })
const body = await response.json()
assert.equal(response.status, status, JSON.stringify(body))
return body
}
assert.deepEqual(await linux(), { revision: null, items: [] })
const { digest, changes } = await post(path + "/plan", { revision: 1 }, 200)
assert(changes.some((step: { path: string }) => step.path === "/interface/wireguard/peers"))
await post(path + "/apply", { revision: 1, digest }, 401, "")
await post(path + "/apply", { revision: 1, digest }, 403, reader)
await post(path + "/apply", { revision: 1, digest }, 409, otherWriter)
await post(path + "/apply", { revision: 1, digest: "0".repeat(64) }, 409)
rows["/interface"].push({ ".id": "*F0", name: "test-drift", type: "ether" })
await post(path + "/apply", { revision: 1, digest }, 409)
assert.equal(writes, 0)
const fresh = await post(path + "/plan", { revision: 1 }, 200)
const protectionId = randomUUID()
await pool.query("INSERT INTO mcp_protections(id,object_ref,created_by) VALUES ($1,$2,'ix-web-owner')",
[protectionId, { kind: "server", id: String(server.id), protection: "deny" }])
await post(path + "/apply", { revision: 1, digest: fresh.digest }, 409)
assert.equal(writes, 0)
await pool.query("DELETE FROM mcp_protections WHERE id=$1", [protectionId])
const applied = await post(path + "/apply", { revision: 1, digest: fresh.digest }, 200)
assert.equal(applied.segment.appliedRevision, 2)
assert.equal(applied.result.configurationVerified, true)
assert.equal(applied.result.forwardingVerified, false)
const resultWrites = writes
assert.equal(resultWrites, changes.length)
const clients = await linux()
assert.equal(clients.revision, 2)
assert.deepEqual(clients.items.map((item: { kind: string }) => item.kind), ["wireguard", "gre-ipsec"])
const wg = await linux("wg-ix-web")
assert.match(wg.template, /Endpoint = 192\.0\.2\.20:51820/)
assert.match(wg.template, /Table = off/)
assert(!wg.template.includes("A".repeat(43)))
const gre = await linux("gre-client")
assert.match(gre.template, /local_ts = 192\.0\.2\.21\/32\[47\]/)
assert.match(gre.template, /remote_ts = 192\.0\.2\.20\/32\[47\]/)
assert.match(gre.template, /mode = transport/)
assert.match(gre.setup, /mode gre local 192\.0\.2\.21 remote 192\.0\.2\.20/)
rows["/ip/ipsec/policy"][0].disabled = "true"
await linux("gre-client", 409)
rows["/ip/ipsec/policy"][0].disabled = "false"
rows["/interface/wireguard/peers"][0].disabled = "true"
await linux("wg-ix-web", 409)
delete rows["/interface/wireguard/peers"][0].disabled
await post(path + "/apply", { revision: 1, digest: fresh.digest }, 409)
assert.equal(writes, resultWrites)
const next = await post("", { id: segment.id, revision: 2, configuration: { ...configuration,
sites: [{ ...configuration.sites[0], discardNetworks: ["2001:db8:ff::/48"] }] } }, 200)
assert.equal(next.segment.appliedRevision, 2)
assert.equal((await linux("wg-ix-web")).revision, 2)
const members = rows["/interface/list/member"]
members.push({ ".id": "*FE", list: rows["/interface/list"][0].name, interface: "test-drift" })
const foreign = await post(path + "/plan", { revision: 3 }, 409)
assert.match(foreign.error, /посторонний интерфейс/)
members.pop()
const nextPlan = await post(path + "/plan", { revision: 3 }, 200)
await post(path + "/apply", { revision: 3, digest: nextPlan.digest }, 200)
assert(rows["/ipv6/route"].some(row => row["dst-address"] === "2001:db8:ff::/48"))
const { rows: [audit] } = await pool.query(`SELECT count(*)::int AS n FROM mcp_audit
WHERE actor_id='ix-web-owner' AND action='configuration.acknowledged' AND connection_id IS NULL`)
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,
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 { z } from "zod"
import { ixChangeSchema, type IxChange } from "@mmapp/contracts/internet-exchange" import { ixChangeSchema, type IxChange } from "@mmapp/contracts/internet-exchange"
import { pool } from "../../db/index.js" 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 { 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 { add } from "./actions.js"
import type { ActionContext } from "./action-types.js" import type { ActionContext } from "./action-types.js"
import { McpError } from "./security.js" import { McpError } from "./security.js"
@@ -12,10 +12,13 @@ import { registerMcpService } from "./service-registry.js"
export const ixOperation = "network.ix.configure" export const ixOperation = "network.ix.configure"
export const ixRestoreOperation = "network.ix.restore" export const ixRestoreOperation = "network.ix.restore"
const service = "network.ix.configure" const service = "network.ix.configure"
const removeService = "network.ix.delete"
const id = z.string().uuid() const id = z.string().uuid()
const revision = z.number().int().positive() const revision = z.number().int().positive()
const changeArgs = z.object({ change: ixChangeSchema }).strict() const changeArgs = z.object({ change: ixChangeSchema }).strict()
const restoreArgs = z.object({ id, revision, restoreRevision: revision }).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({ const sealedInput = z.object({
id, change: ixChangeSchema, actorId: z.string().min(1), 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(), 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) const serverIds = await ixTarget(change)
if (serverIds.some(id => !context.connection.policy.scope.serverIds.includes(id))) throw new McpError("SERVER_DENIED", "Нет доступа ко всем устройствам сегмента") if (serverIds.some(id => !context.connection.policy.scope.serverIds.includes(id))) throw new McpError("SERVER_DENIED", "Нет доступа ко всем устройствам сегмента")
const result = await prepareIxChange(change) 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 { return {
target: { scope: "servers" as const, serverIds }, 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 } }], 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, mutationCost: result.native.tasks.length + 1,
warnings: [ 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) { async function restore(input: Record<string, unknown>, context: ActionContext) {
const args = restoreArgs.parse(input) const args = restoreArgs.parse(input)
const current = await readIxSegment(args.id, context.transactionClient) 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) 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", 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(), { 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) => { 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. */ /** Service recovery has the same private native bodies as its forward plan. */
export function publicMcpChangeEvidence(operationId: string, evidence: ChangeEvidence) { 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") { 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" 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) } ? { ...step, input: { id: step.input.id, change: step.input.change } } : step) }
+97 -7
View File
@@ -1,9 +1,12 @@
import { randomUUID } from "node:crypto" import { randomUUID } from "node:crypto"
import type { FastifyPluginAsync } from "fastify" import type { FastifyPluginAsync } from "fastify"
import { z } from "zod" import { z } from "zod"
import { ixChangeSchema } from "@mmapp/contracts/internet-exchange" import { ixChangeSchema, type IxWebPlan } from "@mmapp/contracts/internet-exchange"
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 { withApplicationMutationLock } from "../services/config-mutation-lock.js"
import { observeIxSegment, readIxLinuxClient } from "../services/internet-exchange-execution.js" import { withConfigurationActor } from "../services/config-mutation-policy.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 { compileIxConfiguration, IxConflict } from "../services/internet-exchange-plan.js"
import { assertIxRevision, listIxSegments, readIxSegment, writeIxRevision } from "../services/internet-exchange-store.js" import { assertIxRevision, listIxSegments, readIxSegment, writeIxRevision } from "../services/internet-exchange-store.js"
@@ -11,13 +14,48 @@ const paging = z.object({
limit: z.coerce.number().int().min(1).max(100).default(25), limit: z.coerce.number().int().min(1).max(100).default(25),
offset: z.coerce.number().int().min(0).max(1000000).default(0), offset: z.coerce.number().int().min(0).max(1000000).default(0),
}).strict() }).strict()
const segmentParams = z.object({ id: z.string().uuid() })
const planRequest = z.object({ revision: z.number().int().positive() }).strict()
const applyRequest = planRequest.extend({ digest: z.string().regex(/^[a-f0-9]{64}$/) })
async function prepareSavedRevision(id: string, revision: number) {
const segment = await readIxSegment(id)
if (!segment) throw new IxConflict("Сегмент IX не найден", 404)
assertIxRevision(segment, revision)
if (segment.appliedRevision === revision) throw new IxConflict("Эта ревизия IX уже применена")
return prepareIxChange({ id, revision, configuration: segment.configuration })
}
function reviewDigest(prepared: Awaited<ReturnType<typeof prepareSavedRevision>>, actorId: string) {
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 => { const ixRoutes: FastifyPluginAsync = async app => {
app.setErrorHandler((error, request, reply) => { app.setErrorHandler((error, request, reply) => {
if (error instanceof z.ZodError) return reply.code(400).send({ error: "Некорректные параметры IX", details: error.issues }) if (error instanceof z.ZodError) return reply.code(400).send({ error: "Некорректные параметры IX", details: error.issues })
if (error instanceof IxConflict) return reply.code(error.statusCode).send({ error: error.message }) if (error instanceof IxConflict) return reply.code(error.statusCode).send({ error: error.message })
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") request.log.error({ error: error instanceof Error ? error.name : "unknown" }, "IX request failed")
return reply.code(503).send({ error: "Хранилище IX недоступно" }) const errorMessage = request.method === "DELETE" ? "Удаление сегмента IX не подтверждено. Обновите данные и проверьте план."
: request.routeOptions.url?.endsWith("/apply")
? "Результат применения IX не подтверждён"
: "Не удалось получить данные для операции IX"
return reply.code(503).send({ error: errorMessage })
}) })
app.get("/ix/segments", async request => { app.get("/ix/segments", async request => {
const input = paging.parse(request.query) const input = paging.parse(request.query)
@@ -25,8 +63,11 @@ const ixRoutes: FastifyPluginAsync = async app => {
}) })
app.get("/ix/nodes", async () => { app.get("/ix/nodes", async () => {
const { pool } = await import("../db/index.js") const { pool } = await import("../db/index.js")
const { rows } = await pool.query("SELECT id,name,site,country,enabled FROM servers WHERE type='ix-node' ORDER BY name,id LIMIT 500") const [nodes, peers] = await Promise.all([
return { items: rows } pool.query("SELECT id,name,site,country,enabled FROM servers WHERE type='ix-node' ORDER BY name,id LIMIT 500"),
pool.query("SELECT id,name,site,country,enabled FROM servers ORDER BY name,id LIMIT 1000"),
])
return { items: nodes.rows, peers: peers.rows }
}) })
app.get("/ix/topology", async () => { app.get("/ix/topology", async () => {
const segments = await listIxSegments(100, 0) const segments = await listIxSegments(100, 0)
@@ -44,10 +85,13 @@ const ixRoutes: FastifyPluginAsync = async app => {
}) })
app.get("/ix/segments/:id/linux", async request => { app.get("/ix/segments/:id/linux", async request => {
const { id } = z.object({ id: z.string().uuid() }).parse(request.params) const { id } = z.object({ id: z.string().uuid() }).parse(request.params)
const { serverId, interfaceName } = z.object({ serverId: z.coerce.number().positive().int().safe(), interfaceName: z.string().regex(/^[A-Za-z0-9_.-]{1,48}$/) }).strict().parse(request.query) const query = z.union([
z.object({ serverId: z.coerce.number().positive().int().safe(), interfaceName: z.string().regex(/^[A-Za-z0-9_.-]{1,48}$/) }).strict(),
z.object({}).strict(),
]).parse(request.query)
const segment = await readIxSegment(id) const segment = await readIxSegment(id)
if (!segment) throw new IxConflict("Сегмент IX не найден", 404) if (!segment) throw new IxConflict("Сегмент IX не найден", 404)
return readIxLinuxClient(segment, serverId, interfaceName) return "serverId" in query ? readIxLinuxClient(segment, query.serverId, query.interfaceName) : listIxLinuxClients(segment)
}) })
app.post("/ix/segments", async request => { app.post("/ix/segments", async request => {
const input = ixChangeSchema.parse(request.body) const input = ixChangeSchema.parse(request.body)
@@ -65,6 +109,52 @@ const ixRoutes: FastifyPluginAsync = async app => {
assertIxRevision(input.id ? await readIxSegment(id) : null, input.revision) assertIxRevision(input.id ? await readIxSegment(id) : null, input.revision)
return { id, objects: compileIxConfiguration(id, input.configuration) } return { id, objects: compileIxConfiguration(id, input.configuration) }
}) })
app.post("/ix/segments/:id/plan", async (request): Promise<IxWebPlan> => {
const { id } = segmentParams.parse(request.params)
const { revision } = planRequest.parse(request.body)
const prepared = await prepareSavedRevision(id, revision)
return {
revision, digest: reviewDigest(prepared, request.authUser?.id ?? "local-operator"),
changes: summarizeTasks(prepared.native.tasks),
}
})
app.post("/ix/segments/:id/apply", async request => {
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 prepareSavedRevision(id, revision)
if (digest !== reviewDigest(prepared, ownerId)) throw new IxConflict("План IX устарел. Постройте новый предпросмотр")
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 export default ixRoutes
@@ -1,3 +1,4 @@
import { createHash } from "node:crypto"
import { isIP } from "node:net" import { isIP } from "node:net"
import type { IxSite } from "@mmapp/contracts/internet-exchange" import type { IxSite } from "@mmapp/contracts/internet-exchange"
import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js" import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js"
@@ -5,6 +6,16 @@ import { IxConflict } from "./internet-exchange-plan.js"
type Binding = IxSite["interfaces"][number] type Binding = IxSite["interfaces"][number]
export function ixLinuxBindingKind(binding: Binding) {
if (binding.kind === "wireguard" && binding.provisionWireguard?.hubEndpoint) return "wireguard"
if (binding.kind === "gre-ipsec" && binding.localEndpoint && binding.endpoint) return "gre-ipsec"
return null
}
export function ixLinuxInterfaceName(prefix: "ixw" | "ixg", serverId: number, binding: Binding) {
return prefix + createHash("sha256").update(JSON.stringify([serverId, binding.name])).digest("hex").slice(0, 12)
}
export function ixWireguardClientTemplate(binding: Binding, hubPublicKey: string, routes: string[]) { export function ixWireguardClientTemplate(binding: Binding, hubPublicKey: string, routes: string[]) {
const config = binding.provisionWireguard const config = binding.provisionWireguard
if (binding.kind !== "wireguard" || !config?.hubEndpoint || !/^[A-Za-z0-9+/]{43}=$/.test(hubPublicKey)) { if (binding.kind !== "wireguard" || !config?.hubEndpoint || !/^[A-Za-z0-9+/]{43}=$/.test(hubPublicKey)) {
@@ -28,3 +39,62 @@ export function ixWireguardClientTemplate(binding: Binding, hubPublicKey: string
"", "",
].join("\n") ].join("\n")
} }
export function ixGreClientTemplate(binding: Binding, serverId: number, bgp?: { address: string; localAddress: string }) {
const hub = binding.localEndpoint
const client = binding.endpoint
if (binding.kind !== "gre-ipsec" || !hub || !client || isIP(hub) !== 4 || isIP(client) !== 4 || hub === client) {
throw new IxConflict("Для Linux GRE/IPsec нужны два разных внешних IPv4-адреса")
}
const id = ixLinuxInterfaceName("ixg", serverId, binding)
const hostMask = bgp && isIP(bgp.address) === 6 ? "/128" : "/32"
return {
filename: id + ".conf",
template: [
"# Сверьте предложения и идентификаторы IKE с профилем узла IX.",
"connections {",
" " + id + " {",
" version = 2",
" local_addrs = " + client,
" remote_addrs = " + hub,
" proposals = aes256-sha256-modp2048",
" mobike = no",
" local {",
" auth = psk",
" id = " + client,
" }",
" remote {",
" auth = psk",
" id = " + hub,
" }",
" children {",
" " + id + " {",
" local_ts = " + client + "/32[47]",
" remote_ts = " + hub + "/32[47]",
" mode = transport",
" esp_proposals = aes256-sha256-modp2048",
" start_action = trap",
" }",
" }",
" }",
"}",
"secrets {",
" ike-" + id + " {",
" id-1 = " + client,
" id-2 = " + hub,
' secret = "<PSK этого клиента>"',
" }",
"}",
"",
].join("\n"),
setup: [
"swanctl --load-all",
"swanctl --initiate --child " + id,
"# Создайте GRE после успешного установления IPsec.",
"ip tunnel add " + id + " mode gre local " + client + " remote " + hub,
bgp ? "ip address add " + bgp.address + hostMask + " dev " + id : "# Назначьте согласованный адрес Linux внутри туннеля.",
"ip link set " + id + " up",
...(bgp ? ["ip route add " + bgp.localAddress + hostMask + " dev " + id + " src " + bgp.address] : []),
].join("\n"),
}
}
@@ -55,3 +55,31 @@ test("RouterOS REST host matches allow only the equivalent explicit host length"
assert.throws(() => planIxNative(id, [rule], [rule], rows(address + "/" + wider)), /изменён вне операции/) assert.throws(() => planIxNative(id, [rule], [rule], rows(address + "/" + wider)), /изменён вне операции/)
} }
}) })
test("RouterOS REST encodes an enabled blackhole route as a present empty flag", () => {
const fields = { comment: name + ":default-discard-4", "routing-table": name, "dst-address": "0.0.0.0/0", blackhole: "yes" }
const discard = { ...route, fields }
const { blackhole: _blackhole, ...unflagged } = fields
const observed = (fields: Record<string, string>) => device({ "/ip/route": [{ ".id": "*B", ...fields }] })
assert.deepEqual(planIxNative(id, [discard], [discard], observed({ ...fields, blackhole: "" })), [])
assert.throws(() => planIxNative(id, [discard], [discard], observed(unflagged)), /изменён вне операции/)
assert.throws(() => planIxNative(id, [discard], [discard], observed({ ...fields, blackhole: "false" })), /изменён вне операции/)
})
test("the complete member filter can be added to a legacy applied segment", () => {
const path = "/ip/firewall/filter"
const object = (suffix: string, fields: Record<string, string>) => ({
serverId: 17, path, fields: { comment: name + ":" + suffix, chain: "forward", ...fields },
})
const boundary = object("deny-outside-4", { action: "drop", "in-interface": name })
const allow = object("egress-allow-4", { action: "accept", "in-interface": name, "out-interface-list": name })
const deny = object("egress-deny-4", { action: "drop", "out-interface-list": name })
const objects = [allow, boundary, deny]
const legacy = { ".id": "*B", ...boundary.fields }
assert.deepEqual(planIxNative(id, objects, objects, device({ [path]: [legacy] })).map(task => [task.fields, task.placeBefore]),
[[allow.fields, "*B"], [deny.fields, "*B"]])
assert.throws(() => planIxNative(id, objects, objects, device({ [path]: [{ ".id": "*C", ...allow.fields }, legacy] })),
/предыдущей ревизии IX исчез/)
})
@@ -1,15 +1,15 @@
import { randomUUID } from "node:crypto" import { randomUUID } from "node:crypto"
import { isIP } from "node:net" import { isIP } from "node:net"
import { setTimeout as delay } from "node:timers/promises" import { setTimeout as delay } from "node:timers/promises"
import { ixChangeSchema, type IxChange, type IxConfiguration, type IxRouterObject, type IxSegment, type IxSiteObservation } from "@mmapp/contracts/internet-exchange" import { ixChangeSchema, type IxChange, type IxConfiguration, type IxLinuxAccess, type IxLinuxBinding, type IxRouterObject, type IxSegment, type IxSite, type IxSiteObservation } from "@mmapp/contracts/internet-exchange"
import { fingerprint } from "../modules/mcp/security.js" import { fingerprint } from "../modules/mcp/security.js"
import { getServerRowById, type ServerRow } from "../modules/servers/repository/servers-repository.js" import { getServerRowById, type ServerRow } from "../modules/servers/repository/servers-repository.js"
import { withApplicationMutationLock, withConfigMutationLock } from "./config-mutation-lock.js" import { withApplicationMutationLock, withConfigMutationLock } from "./config-mutation-lock.js"
import { assertVerifiedConfigurationAccess } from "./config-mutation-policy.js" import { assertVerifiedConfigurationAccess } from "./config-mutation-policy.js"
import { compileIxConfiguration, IxConflict, ixDeviceIds, ixDiscardInterface, ixNamespace } from "./internet-exchange-plan.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 { MikrotikClient } from "./mikrotik.js"
import { ixWireguardClientTemplate } from "./internet-exchange-client.js" import { ixGreClientTemplate, ixLinuxBindingKind, ixLinuxInterfaceName, ixWireguardClientTemplate } from "./internet-exchange-client.js"
type NativeRow = Record<string, string> type NativeRow = Record<string, string>
type IpCore = Pick<MikrotikClient, "get" | "put" | "patch" | "delete"> type IpCore = Pick<MikrotikClient, "get" | "put" | "patch" | "delete">
@@ -25,6 +25,8 @@ interface IxNativeChange {
tasks: Task[] tasks: Task[]
} }
const nativePlanDigest = ({ before, tasks }: IxNativeChange) => fingerprint({ before, tasks })
const routerId = /^\*[a-z\d]+$/i const routerId = /^\*[a-z\d]+$/i
const marker = (path: string, comment: string) => path + "\0" + comment const marker = (path: string, comment: string) => path + "\0" + comment
const objectMarker = (object: IxRouterObject) => marker(object.path, object.fields.comment) const objectMarker = (object: IxRouterObject) => marker(object.path, object.fields.comment)
@@ -32,8 +34,11 @@ const deviceMarker = (object: IxRouterObject) => object.serverId + "\0" + object
const isTrue = (value: unknown) => value === true || value === "true" || value === "yes" const isTrue = (value: unknown) => value === true || value === "true" || value === "yes"
const columns = [".id", "comment", "name", "type", "disabled", "dynamic", "builtin", "interfaces", "routing-table", "dst-address", "gateway", "chain"] const columns = [".id", "comment", "name", "type", "disabled", "dynamic", "builtin", "interfaces", "routing-table", "dst-address", "gateway", "chain"]
const filterPath = (path: string) => /^\/(ip|ipv6)\/firewall\/(filter|nat)$/.test(path) const filterPath = (path: string) => /^\/(ip|ipv6)\/firewall\/(filter|nat)$/.test(path)
const greColumns = [".id", "name", "local-address", "remote-address", "allow-fast-path"]
const ipsecPolicyColumns = [".id", "action", "level", "tunnel", "protocol", "src-address", "dst-address", "disabled", "template"]
function normalize(field: string, value: string | undefined) { function normalize(field: string, value: string | undefined) {
if (field === "blackhole" && value === "") return "yes"
if (["disabled", "advertise", "blackhole", "multihop"].includes(field)) return value === undefined ? null : isTrue(value) ? "yes" : "no" if (["disabled", "advertise", "blackhole", "multihop"].includes(field)) return value === undefined ? null : isTrue(value) ? "yes" : "no"
if (field === "rule") return value?.trim() if (field === "rule") return value?.trim()
if (field === "interfaces") return value?.split(",").sort().join(",") if (field === "interfaces") return value?.split(",").sort().join(",")
@@ -63,6 +68,11 @@ function verifyNativeId(row: NativeRow) {
export function planIxNative(id: string, desired: IxRouterObject[], previous: IxRouterObject[], devices: NativeDevice[]): Task[] { export function planIxNative(id: string, desired: IxRouterObject[], previous: IxRouterObject[], devices: NativeDevice[]): Task[] {
const namespace = ixNamespace(id) const namespace = ixNamespace(id)
const egressObject = (comment = "") => comment.startsWith(namespace + ":egress-")
const withEgressList = new Set(devices.filter(device => Object.values(device.rows).some(rows =>
rows.some(row => egressObject(row.comment)))).map(device => device.serverId))
// An older applied revision had no egress list. A partial set still needs reconciliation.
previous = previous.filter(object => !egressObject(object.fields.comment) || withEgressList.has(object.serverId))
const desiredKeys = new Set(desired.map(deviceMarker)) const desiredKeys = new Set(desired.map(deviceMarker))
const previousKeys = new Set(previous.map(deviceMarker)) const previousKeys = new Set(previous.map(deviceMarker))
const result: Task[] = [] const result: Task[] = []
@@ -108,6 +118,17 @@ export function planIxNative(id: string, desired: IxRouterObject[], previous: Ix
return result.concat(interfaceCleanup) return result.concat(interfaceCleanup)
} }
function verifyEgressMembers(device: NativeDevice, id: string, objects: IxRouterObject[]) {
const path = "/interface/list/member"
const list = ixEgressList(id)
const catalogue = rowsFor(device, "/interface/list").find(row => row.name === list)
const expected = objects.filter(object => object.serverId === device.serverId && object.path === path)
if ([catalogue?.include, catalogue?.exclude].some(value => value && value !== "none") ||
rowsFor(device, path).some(row => row.list === list && (isTrue(row.disabled) || !expected.some(object => matches(row, object.fields))))) {
throw new IxConflict("В списке выходов IX есть посторонний интерфейс")
}
}
async function readRows(client: IpCore, path: string, props: readonly string[]) { async function readRows(client: IpCore, path: string, props: readonly string[]) {
const raw = await client.get<unknown>(path + "?" + new URLSearchParams({ ".proplist": [...new Set(props)].join(",") })) const raw = await client.get<unknown>(path + "?" + new URLSearchParams({ ".proplist": [...new Set(props)].join(",") }))
if (!Array.isArray(raw) || raw.length > 10000 || raw.some(value => !value || typeof value !== "object" || Array.isArray(value))) { if (!Array.isArray(raw) || raw.length > 10000 || raw.some(value => !value || typeof value !== "object" || Array.isArray(value))) {
@@ -119,17 +140,21 @@ async function readRows(client: IpCore, path: string, props: readonly string[])
}))) as NativeRow[] }))) 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 client = MikrotikClient.fromServer(server)
const fieldsByPath = new Map<string, string[]>([["/interface", columns], ["/interface/bridge/port", [".id", "bridge", "interface"]], const fieldsByPath = new Map<string, string[]>([["/interface", columns], ["/interface/bridge/port", [".id", "bridge", "interface"]],
["/ip/vrf", columns], ["/ip/route", columns], ["/ipv6/route", columns]]) ["/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) { for (const object of objects) {
fieldsByPath.set(object.path, [...new Set([...(fieldsByPath.get(object.path) ?? columns), fieldsByPath.set(object.path, [...new Set([...(fieldsByPath.get(object.path) ?? columns),
...(filterPath(object.path) ? ["invalid"] : []), ...Object.keys(object.fields)])]) ...(filterPath(object.path) ? ["invalid"] : []), ...Object.keys(object.fields)])])
} }
if (fieldsByPath.has("/interface/list")) fieldsByPath.get("/interface/list")!.push("include", "exclude")
if (objects.some(object => object.fields["ipsec-policy"])) { if (objects.some(object => object.fields["ipsec-policy"])) {
fieldsByPath.set("/interface/gre", [".id", "name", "local-address", "remote-address", "allow-fast-path"]) fieldsByPath.set("/interface/gre", greColumns)
fieldsByPath.set("/ip/ipsec/policy", [".id", "action", "level", "tunnel", "protocol", "src-address", "dst-address", "disabled", "template"]) fieldsByPath.set("/ip/ipsec/policy", ipsecPolicyColumns)
} }
const rows: Record<string, NativeRow[]> = {} const rows: Record<string, NativeRow[]> = {}
for (const [path, keys] of fieldsByPath) rows[path] = await readRows(client, path, keys) for (const [path, keys] of fieldsByPath) rows[path] = await readRows(client, path, keys)
@@ -140,6 +165,21 @@ async function readDevice(server: ServerRow, objects: IxRouterObject[]): Promise
return { serverId: server.id, source: fingerprint(server), rows } return { serverId: server.id, source: fingerprint(server), rows }
} }
function verifyGreBinding(binding: IxSite["interfaces"][number], interfaces: NativeRow[], policies: NativeRow[]) {
const gre = interfaces.find(row => row.name === binding.name)
const policy = policies.some(row =>
!isTrue(row.disabled) && !isTrue(row.template) && !isTrue(row.tunnel) &&
row.action === "encrypt" && ["require", "unique"].includes(row.level) && ["gre", "47"].includes(row.protocol) &&
row["src-address"] === binding.localEndpoint + "/32" && row["dst-address"] === binding.endpoint + "/32")
if (!gre || gre["local-address"] !== binding.localEndpoint || gre["remote-address"] !== binding.endpoint || !policy) {
throw new IxConflict("Для " + binding.name + " не подтверждены адреса и обязательная политика GRE/IPsec")
}
if (!["false", "no"].includes(gre["allow-fast-path"])) {
throw new IxConflict("Отключите FastPath на интерфейсе GRE/IPsec " + binding.name)
}
return gre
}
function validateBindings(configuration: IxConfiguration, id: string, devices: NativeDevice[]) { function validateBindings(configuration: IxConfiguration, id: string, devices: NativeDevice[]) {
for (const site of configuration.sites) { for (const site of configuration.sites) {
const device = devices.find(entry => entry.serverId === site.serverId)! const device = devices.find(entry => entry.serverId === site.serverId)!
@@ -165,42 +205,65 @@ function validateBindings(configuration: IxConfiguration, id: string, devices: N
throw new IxConflict("Интерфейс " + binding.name + " уже используется другой маршрутизацией") throw new IxConflict("Интерфейс " + binding.name + " уже используется другой маршрутизацией")
} }
if (binding.kind === "gre-ipsec") { if (binding.kind === "gre-ipsec") {
const gre = rowsFor(device, "/interface/gre").find(row => row.name === binding.name) verifyGreBinding(binding, rowsFor(device, "/interface/gre"), rowsFor(device, "/ip/ipsec/policy"))
const policy = rowsFor(device, "/ip/ipsec/policy").some(row =>
!isTrue(row.disabled) && !isTrue(row.template) && !isTrue(row.tunnel) &&
row.action === "encrypt" && ["require", "unique"].includes(row.level) && ["gre", "47"].includes(row.protocol) &&
row["src-address"] === binding.localEndpoint + "/32" && row["dst-address"] === binding.endpoint + "/32")
if (!gre || gre["local-address"] !== binding.localEndpoint || gre["remote-address"] !== binding.endpoint || !policy) {
throw new IxConflict("Для " + binding.name + " не подтверждены адреса и обязательная политика GRE/IPsec")
}
if (!["false", "no"].includes(gre["allow-fast-path"])) {
throw new IxConflict("Отключите FastPath на интерфейсе GRE/IPsec " + binding.name)
}
} }
} }
} }
} }
async function prepareNative(id: string, configuration: IxConfiguration, previousConfiguration: IxConfiguration | null): Promise<IxNativeChange> { async function prepareNative(id: string, configuration: IxConfiguration | null, previousConfiguration: IxConfiguration | null): Promise<IxNativeChange> {
const objects = compileIxConfiguration(id, configuration) const objects = configuration ? compileIxConfiguration(id, configuration) : []
const previous = previousConfiguration ? compileIxConfiguration(id, previousConfiguration) : [] const previous = previousConfiguration ? compileIxConfiguration(id, previousConfiguration) : []
const before: NativeDevice[] = [] const before: NativeDevice[] = []
for (const serverId of [...new Set([...objects, ...previous].map(object => object.serverId))].sort((a, b) => a - b)) { for (const serverId of [...new Set([...objects, ...previous].map(object => object.serverId))].sort((a, b) => a - b)) {
const server = await getServerRowById(serverId) const server = await getServerRowById(serverId)
if (!server?.enabled || server.type !== "ix-node") throw new IxConflict("Площадка IX отключена или изменила тип") 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 ?? []) { 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)! 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))) { 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) 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) { export async function ixTarget(change: IxChange) {
@@ -218,7 +281,7 @@ export async function prepareIxChange(raw: unknown) {
await assertIxSites(change.configuration) await assertIxSites(change.configuration)
const previous = current?.appliedRevision ? await readIxRevision(id, current.appliedRevision) : null const previous = current?.appliedRevision ? await readIxRevision(id, current.appliedRevision) : null
const native = await prepareNative(id, change.configuration, previous) const native = await prepareNative(id, change.configuration, previous)
const before = { revision: current?.revision ?? 0, devices: fingerprint(native.before) } const before = { revision: current?.revision ?? 0, devices: nativePlanDigest(native) }
const objects = native.before.flatMap(device => [{ kind: "server", id: String(device.serverId), serverId: device.serverId }]) const objects = native.before.flatMap(device => [{ kind: "server", id: String(device.serverId), serverId: device.serverId }])
return { id, change, before, native, objects } return { id, change, before, native, objects }
} }
@@ -228,7 +291,7 @@ export async function currentIxChange(id: string, change: IxChange) {
if (current?.revision !== change.revision && !(current === null && change.revision === 0)) return { revision: current?.revision ?? 0 } if (current?.revision !== change.revision && !(current === null && change.revision === 0)) return { revision: current?.revision ?? 0 }
const applied = current?.appliedRevision ? await readIxRevision(id, current.appliedRevision) : null const applied = current?.appliedRevision ? await readIxRevision(id, current.appliedRevision) : null
const native = await prepareNative(id, change.configuration, applied) const native = await prepareNative(id, change.configuration, applied)
return { revision: current?.revision ?? 0, devices: fingerprint(native.before) } return { revision: current?.revision ?? 0, devices: nativePlanDigest(native) }
} }
export async function reconcileIxChange(id: string, change: IxChange, expected: { revision: number; devices: string }, authorize: () => Promise<void>) { export async function reconcileIxChange(id: string, change: IxChange, expected: { revision: number; devices: string }, authorize: () => Promise<void>) {
@@ -243,6 +306,8 @@ export async function reconcileIxChange(id: string, change: IxChange, expected:
if (!server?.enabled) return { matchesDesiredState: false, matchesOriginalState: false } if (!server?.enabled) return { matchesDesiredState: false, matchesOriginalState: false }
const objects = desired.filter(object => object.serverId === site.serverId) const objects = desired.filter(object => object.serverId === site.serverId)
const observed = await readDevice(server, objects) const observed = await readDevice(server, objects)
try { verifyEgressMembers(observed, id, objects) }
catch { return { matchesDesiredState: false, matchesOriginalState: false } }
matchesDesiredState &&= objects.every(object => { matchesDesiredState &&= objects.every(object => {
const row = managedRow(observed, object) const row = managedRow(observed, object)
return row && !isTrue(row.invalid) && matches(row, object.fields) return row && !isTrue(row.invalid) && matches(row, object.fields)
@@ -290,82 +355,143 @@ export async function observeIxSegment(segment: IxSegment): Promise<IxSiteObserv
})) }))
} }
export async function readIxLinuxClient(segment: IxSegment, serverId: number, name: string) { export async function listIxLinuxClients(segment: IxSegment) {
const revision = segment.appliedRevision
if (revision === null) return { revision, items: [] }
const configuration = await readIxRevision(segment.id, revision)
const items: IxLinuxBinding[] = configuration.sites.flatMap(site => site.interfaces.flatMap(binding => {
const kind = ixLinuxBindingKind(binding)
return kind && binding.peerServerId === undefined ? [{ serverId: site.serverId, interfaceName: binding.name, kind }] : []
}))
return { revision, items }
}
export async function readIxLinuxClient(segment: IxSegment, serverId: number, name: string): Promise<IxLinuxAccess> {
if (segment.appliedRevision === null) throw new IxConflict("Сначала примените конфигурацию площадки") if (segment.appliedRevision === null) throw new IxConflict("Сначала примените конфигурацию площадки")
const configuration = await readIxRevision(segment.id, segment.appliedRevision) const configuration = await readIxRevision(segment.id, segment.appliedRevision)
const site = configuration.sites.find(site => site.serverId === serverId) const site = configuration.sites.find(site => site.serverId === serverId)
const binding = site?.interfaces.find(entry => entry.name === name) const binding = site?.interfaces.find(entry => entry.name === name)
const server = await getServerRowById(serverId) const server = await getServerRowById(serverId)
if (!site || !binding || !server?.enabled || server.type !== "ix-node") throw new IxConflict("Подключение IX не найдено", 404) if (!site || !binding || !server?.enabled || server.type !== "ix-node") throw new IxConflict("Подключение IX не найдено", 404)
const wireguard = await readRows(MikrotikClient.fromServer(server), "/interface/wireguard", ["name", "public-key", "comment"]) const peer = site.neighbors.find(entry => entry.binding === name && entry.type !== "public-feed")
const iface = wireguard.find(row => row.name === binding.name && row.comment?.startsWith(ixNamespace(segment.id) + ":wg-")) const clientInfo = {
revision: segment.appliedRevision,
...(peer ? { bgp: { localAs: peer.remoteAs, remoteAs: site.autonomousSystem, neighbor: peer.localAddress, advertisedPrefixes: peer.prefixes } } : {}),
}
const client = MikrotikClient.fromServer(server)
if (binding.kind === "gre-ipsec") {
const [interfaces, policies] = await Promise.all([
readRows(client, "/interface/gre", [...greColumns, "disabled"]),
readRows(client, "/ip/ipsec/policy", ipsecPolicyColumns),
])
if (isTrue(verifyGreBinding(binding, interfaces, policies).disabled)) throw new IxConflict("Интерфейс GRE/IPsec отключён")
return { ...clientInfo, kind: "gre-ipsec", ...ixGreClientTemplate(binding, serverId, peer) }
}
if (ixLinuxBindingKind(binding) !== "wireguard") throw new IxConflict("Нет параметров WireGuard для Linux")
const wireguard = await readRows(client, "/interface/wireguard", ["name", "public-key", "comment", "disabled"])
const iface = wireguard.find(row => row.name === binding.name && row.comment?.startsWith(ixNamespace(segment.id) + ":wg-") && !isTrue(row.disabled))
const peers = await readRows(client, "/interface/wireguard/peers", ["interface", "public-key", "comment", "disabled"])
if (!peers.some(row => row.interface === name && row["public-key"] === binding.provisionWireguard?.peerPublicKey &&
row.comment?.startsWith(ixNamespace(segment.id) + ":wg-peer-") && !isTrue(row.disabled))) {
throw new IxConflict("Пир WireGuard из применённой ревизии отсутствует или отключён")
}
const routes = configuration.sites.flatMap(entry => entry.interfaces const routes = configuration.sites.flatMap(entry => entry.interfaces
.filter(connection => connection !== binding && connection.kind !== "uplink").flatMap(connection => connection.prefixes)) .filter(connection => connection !== binding && connection.kind !== "uplink").flatMap(connection => connection.prefixes))
const peer = site.neighbors.find(entry => entry.binding === name)
return { return {
...clientInfo,
kind: "wireguard",
filename: ixLinuxInterfaceName("ixw", serverId, binding) + ".conf",
template: ixWireguardClientTemplate(binding, iface?.["public-key"] ?? "", routes), template: ixWireguardClientTemplate(binding, iface?.["public-key"] ?? "", routes),
...(peer ? { bgp: { localAs: peer.remoteAs, remoteAs: site.autonomousSystem, neighbor: peer.localAddress, advertisedPrefixes: peer.prefixes } } : {}),
} }
} }
export async function applyIxChange(id: string, change: IxChange, expected: { revision: number; devices: string }, actorId: string) { 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 () => { return withApplicationMutationLock(async () => withConfigMutationLock(await ixTarget(change), async () => {
await assertVerifiedConfigurationAccess() await authorize()
const current = await readIxSegment(id) const current = await readIxSegment(id)
assertIxRevision(current, expected.revision) assertIxRevision(current, expected.revision)
await assertIxName(id, change.configuration.name) await assertIxName(id, change.configuration.name)
await assertIxSites(change.configuration)
const applied = current?.appliedRevision ? await readIxRevision(id, current.appliedRevision) : null const applied = current?.appliedRevision ? await readIxRevision(id, current.appliedRevision) : null
const native = await prepareNative(id, change.configuration, applied) const native = await prepareNative(id, change.configuration, applied)
if (fingerprint(native.before) !== expected.devices) throw new IxConflict("Конфигурация IX изменилась после предпросмотра") if (nativePlanDigest(native) !== expected.devices) throw new IxConflict("Конфигурация IX изменилась после предпросмотра")
for (const task of native.tasks) { await applyNativeTasks(native, authorize)
await assertVerifiedConfigurationAccess() 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)
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)
: await client.put<NativeRow>(nativePath, { ...task.fields, ...(task.placeBefore ? { "place-before": task.placeBefore } : {}) })
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 assertVerifiedConfigurationAccess()
for (const device of native.before) { for (const device of native.before) {
const server = await getServerRowById(device.serverId) const server = await getServerRowById(device.serverId)
if (!server || fingerprint(server) !== device.source) throw new IxConflict("Источник IX изменился во время проверки") if (!server || fingerprint(server) !== device.source) throw new IxConflict("Источник IX изменился во время проверки")
const desired = native.objects.filter(object => object.serverId === device.serverId) const desired = native.objects.filter(object => object.serverId === device.serverId)
const after = await readDevice(server, desired) const after = await readDevice(server, desired)
verifyEgressMembers(after, id, desired)
if (rowsFor(after, "/interface/bridge/port").some(row => row.bridge === ixDiscardInterface(id))) throw new IxConflict("Нарушена изоляция bridge отбрасывания IX") if (rowsFor(after, "/interface/bridge/port").some(row => row.bridge === ixDiscardInterface(id))) throw new IxConflict("Нарушена изоляция bridge отбрасывания IX")
if (!desired.every(object => { if (!desired.every(object => {
const row = managedRow(after, object) const row = managedRow(after, object)
return row && !isTrue(row.invalid) && matches(row, object.fields) return row && !isTrue(row.invalid) && matches(row, object.fields)
})) throw new IxConflict("Итоговая конфигурация IX не совпала с планом") })) throw new IxConflict("Итоговая конфигурация IX не совпала с планом")
} }
await assertVerifiedConfigurationAccess() await authorize()
const segment = await writeIxRevision(id, expected.revision, change.configuration, actorId, true) const segment = await writeIxRevision(id, expected.revision, change.configuration, actorId, true)
return { segmentId: segment.id, revision: segment.revision, configurationVerified: true, forwardingVerified: false, changedObjects: native.tasks.length } return { segmentId: segment.id, revision: segment.revision, configurationVerified: true, forwardingVerified: false, changedObjects: native.tasks.length }
}), { waitMs: 30_000 }) }), { waitMs: 30_000 })
@@ -1,7 +1,7 @@
import assert from "node:assert/strict" import assert from "node:assert/strict"
import { test } from "node:test" import { test } from "node:test"
import { ixSegmentConfigurationSchema, type IxConfiguration } from "@mmapp/contracts/internet-exchange" import { ixSegmentConfigurationSchema, type IxConfiguration } from "@mmapp/contracts/internet-exchange"
import { compileIxConfiguration, ixDiscardInterface, ixNamespace } from "./internet-exchange-plan.js" import { compileIxConfiguration, ixDiscardInterface, ixEgressList, ixNamespace } from "./internet-exchange-plan.js"
const id = "aaaaaaaa-1111-4222-8333-123456789abc" const id = "aaaaaaaa-1111-4222-8333-123456789abc"
const table = ixNamespace(id) const table = ixNamespace(id)
@@ -22,6 +22,24 @@ const fixture = (): IxConfiguration => ixSegmentConfigurationSchema.parse({
}], }],
}) })
test("forwarding permits the VRF to exit through its own members before isolation drops", () => {
const objects = compileIxConfiguration(id, fixture())
const egress = ixEgressList(id)
const members = objects.filter(object => object.path === "/interface/list/member")
assert.deepEqual(members.map(object => [object.fields.list, object.fields.interface]),
["wg-eu", "wg-arn", "uplink", "wg-feed"].map(member => [egress, member]))
for (const [family, path] of [[4, "/ip/firewall/filter"], [6, "/ipv6/firewall/filter"]] as const) {
const forward = objects.filter(object => object.path === path && object.fields.chain === "forward")
const boundary = forward.findIndex(object => object.fields.comment === table + ":deny-outside-" + family)
assert.deepEqual(forward.slice(0, boundary).map(object => [object.fields["in-interface"], object.fields["out-interface"] ?? object.fields["out-interface-list"]]),
[[table, table], [table, egress]])
assert.equal(forward[boundary - 1].fields["out-interface-list"], egress)
assert.equal(forward[boundary].fields.action, "drop")
assert.equal(forward.at(-1)?.fields.action, "drop")
assert.equal(forward.at(-1)?.fields["out-interface-list"], egress)
}
})
test("a BGP community uses a stable recursive next hop with independent probes and a final discard", () => { test("a BGP community uses a stable recursive next hop with independent probes and a final discard", () => {
const objects = compileIxConfiguration(id, fixture()) const objects = compileIxConfiguration(id, fixture())
const policy = objects.find(object => object.fields.comment.endsWith(":bgp-in-evo"))!.fields.rule const policy = objects.find(object => object.fields.comment.endsWith(":bgp-in-evo"))!.fields.rule
@@ -26,6 +26,7 @@ const forbiddenPublic = {
export function ixNamespace(id: string) { return "ix-" + id.replace(/-/g, "").slice(0, 18) } export function ixNamespace(id: string) { return "ix-" + id.replace(/-/g, "").slice(0, 18) }
// RouterOS accepts unambiguous prefixes for interface names before the VRF interface appears. // RouterOS accepts unambiguous prefixes for interface names before the VRF interface appears.
export function ixDiscardInterface(id: string) { return "ix-drop-" + ixNamespace(id).slice(3) } export function ixDiscardInterface(id: string) { return "ix-drop-" + ixNamespace(id).slice(3) }
export function ixEgressList(id: string) { return "ix-out-" + ixNamespace(id).slice(3) }
export function ixDeviceIds(configuration: IxConfiguration) { export function ixDeviceIds(configuration: IxConfiguration) {
return [...new Set(configuration.sites.flatMap(site => [site.serverId, ...site.interfaces.flatMap(binding => binding.peerServerId === undefined ? [] : [binding.peerServerId])]))].sort((a, b) => a - b) return [...new Set(configuration.sites.flatMap(site => [site.serverId, ...site.interfaces.flatMap(binding => binding.peerServerId === undefined ? [] : [binding.peerServerId])]))].sort((a, b) => a - b)
} }
@@ -164,6 +165,11 @@ export function compileIxConfiguration(id: string, configuration: IxConfiguratio
add("/interface/bridge", "drop-bridge", { name: dropInterface, "protocol-mode": "none" }) add("/interface/bridge", "drop-bridge", { name: dropInterface, "protocol-mode": "none" })
add("/ip/vrf", "vrf", { name: namespace, interfaces: [dropInterface, ...site.interfaces.map(binding => binding.name)].join(",") }) add("/ip/vrf", "vrf", { name: namespace, interfaces: [dropInterface, ...site.interfaces.map(binding => binding.name)].join(",") })
if (site.interfaces.length) { if (site.interfaces.length) {
const egress = ixEgressList(id)
add("/interface/list", "egress-list", { name: egress })
for (const binding of site.interfaces) {
add("/interface/list/member", "egress-member-" + binding.name, { list: egress, interface: binding.name })
}
for (const family of families) { for (const family of families) {
const filter = family === 4 ? "/ip/firewall/filter" : "/ipv6/firewall/filter" const filter = family === 4 ? "/ip/firewall/filter" : "/ipv6/firewall/filter"
for (const peer of site.neighbors.filter(peer => familyOf(peer.address) === family)) { for (const peer of site.neighbors.filter(peer => familyOf(peer.address) === family)) {
@@ -174,8 +180,10 @@ export function compileIxConfiguration(id: string, configuration: IxConfiguratio
add(filter, "allow-control-" + family, { chain: "input", "in-interface": namespace, protocol: family === 4 ? "icmp" : "icmpv6", action: "accept" }) add(filter, "allow-control-" + family, { chain: "input", "in-interface": namespace, protocol: family === 4 ? "icmp" : "icmpv6", action: "accept" })
add(filter, "deny-input-" + family, { chain: "input", "in-interface": namespace, action: "drop" }) add(filter, "deny-input-" + family, { chain: "input", "in-interface": namespace, action: "drop" })
add(filter, "allow-segment-" + family, { chain: "forward", "in-interface": namespace, "out-interface": namespace, action: "accept" }) add(filter, "allow-segment-" + family, { chain: "forward", "in-interface": namespace, "out-interface": namespace, action: "accept" })
add(filter, "egress-allow-" + family, { chain: "forward", "in-interface": namespace, "out-interface-list": egress, action: "accept" })
add(filter, "deny-outside-" + family, { chain: "forward", "in-interface": namespace, action: "drop" }) add(filter, "deny-outside-" + family, { chain: "forward", "in-interface": namespace, action: "drop" })
add(filter, "deny-inside-" + family, { chain: "forward", "out-interface": namespace, action: "drop" }) add(filter, "deny-inside-" + family, { chain: "forward", "out-interface": namespace, action: "drop" })
add(filter, "egress-deny-" + family, { chain: "forward", "out-interface-list": egress, action: "drop" })
} }
for (const [index, binding] of site.interfaces.entries()) { for (const [index, binding] of site.interfaces.entries()) {
if (binding.natIpv4) add("/ip/firewall/nat", "nat-" + index, { chain: "srcnat", action: "masquerade", "out-interface": binding.name }) if (binding.natIpv4) add("/ip/firewall/nat", "nat-" + index, { chain: "srcnat", action: "masquerade", "out-interface": binding.name })
@@ -1,6 +1,7 @@
import type { PoolClient } from "pg" import type { PoolClient } from "pg"
import { ixSegmentConfigurationSchema, type IxConfiguration, type IxSegment } from "@mmapp/contracts/internet-exchange" import { ixSegmentConfigurationSchema, type IxConfiguration, type IxSegment } from "@mmapp/contracts/internet-exchange"
import { pool } from "../db/index.js" import { pool } from "../db/index.js"
import { audit } from "../modules/mcp/store.js"
import { IxConflict, ixDeviceIds } from "./internet-exchange-plan.js" import { IxConflict, ixDeviceIds } from "./internet-exchange-plan.js"
import { admitPartitionWriter } from "./partition-write-transaction.js" import { admitPartitionWriter } from "./partition-write-transaction.js"
@@ -13,6 +14,7 @@ interface SegmentRow {
} }
const columns = "id,revision,applied_revision,configuration,updated_at" const columns = "id,revision,applied_revision,configuration,updated_at"
const visible = "(configuration->>'deleted') IS DISTINCT FROM 'true'"
function segment(row: SegmentRow): IxSegment { function segment(row: SegmentRow): IxSegment {
return { id: row.id, revision: row.revision, appliedRevision: row.applied_revision, return { id: row.id, revision: row.revision, appliedRevision: row.applied_revision,
configuration: ixSegmentConfigurationSchema.parse(row.configuration), updatedAt: row.updated_at.toISOString() } 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[]) { export async function listIxSegments(limit: number, offset: number, allowedIds?: readonly number[]) {
const { rows } = await pool.query<SegmentRow>( const { rows } = await pool.query<SegmentRow>(
`SELECT ${columns} FROM ix_segments s `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[])) 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]) ORDER BY name,id LIMIT $2 OFFSET $3`, [allowedIds ?? null, limit, offset])
return rows.map(segment) return rows.map(segment)
} }
export async function readIxSegment(id: string, sql: Pick<PoolClient, "query"> = pool) { 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 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) { 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]) 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) 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]) [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, : 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() 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]) [id, configuration.name, revision, JSON.stringify(configuration), applied, expected])
if (!row) throw new IxConflict("Имя IX уже занято или ревизия сменилась") if (!row) throw new IxConflict("Имя IX уже занято или ревизия сменилась")
// Keep references to the applied topology while it can still hold live resources. // 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 throw error
} finally { client.release() } } 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()
}
}
+10 -1
View File
@@ -53,7 +53,16 @@
} }
``` ```
Для создания WireGuard самим планом используйте `provisionWireguard` с `listenPort`, `localAddress`, `peerAddress` и `peerPublicKey`. Если задан `hubEndpoint`, после применения вкладка маршрутов выдаёт шаблон Linux с публичным ключом CHR. Шаблон использует `Table = off`. Оператор устанавливает маршруты и политику выбора источника на Linux отдельно. Для GRE/IPsec перед привязкой туннеля настройте IKEv2 и политику transport mode на обоих концах и отключите FastPath на интерфейсах GRE. В конфигурации IX укажите фиксированные `localEndpoint` и `endpoint`. ### Доступ конечных Linux-серверов
На нужной площадке добавьте по одному подключению на сервер. В поле «Удалённый узел» выберите «Внешний сервер». Сохраните черновик, просмотрите изменения и примените их через WebUI. Во вкладке «Linux-клиенты» скачайте конфигурацию конкретного подключения из применённой ревизии.
- **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 и ввод в эксплуатацию ## MCP и ввод в эксплуатацию
@@ -106,6 +106,32 @@ export interface IxRouterObject {
fields: Record<string, string> fields: Record<string, string>
} }
export interface IxWebPlan {
revision: number
digest: string
changes: Array<IxRouterObject & { action: "create" | "update" | "delete"; target?: string; placeBefore?: string }>
}
export interface IxLinuxBinding {
serverId: number
interfaceName: string
kind: "wireguard" | "gre-ipsec"
}
export interface IxLinuxAccess {
kind: IxLinuxBinding["kind"]
revision: number
filename: string
template: string
setup?: string
bgp?: {
localAs: number
remoteAs: number
neighbor: string
advertisedPrefixes: string[]
}
}
export interface IxSiteObservation { export interface IxSiteObservation {
serverId: number serverId: number
observedAt: string observedAt: string
+106 -20
View File
@@ -1,6 +1,5 @@
import { expect, test } from "@playwright/test" import { expect, test } from "@playwright/test"
import { ixChangeSchema, ixSegmentConfigurationSchema } from "@mmapp/contracts/internet-exchange" import { ixChangeSchema, ixSegmentConfigurationSchema } from "@mmapp/contracts/internet-exchange"
import { mcpLimitsSchema } from "@mmapp/contracts/mcp"
const id = "fa58fa40-4bcb-4616-9316-cb69463b3150" const id = "fa58fa40-4bcb-4616-9316-cb69463b3150"
const observedAt = "2026-11-20T00:00:00Z" const observedAt = "2026-11-20T00:00:00Z"
@@ -9,39 +8,59 @@ const nodes = [
{ id: 2, name: "ix-node-02", site: "TEST-2", country: "FI", enabled: true }, { id: 2, name: "ix-node-02", site: "TEST-2", country: "FI", enabled: true },
] ]
test("IX: карточка доступна на узком экране, сохранение удерживает настройки маршрутизации", async ({ page }, testInfo) => { test("IX: редактирование и применение сохранённой ревизии из WebUI без MCP", async ({ page }, testInfo) => {
const configuration = ixSegmentConfigurationSchema.parse({ name: "ix-central", sites: [ const configuration = ixSegmentConfigurationSchema.parse({ name: "ix-central", sites: [
{ serverId: 1, autonomousSystem: 64512, routerId: "192.0.2.10", interfaces: [{ name: "wg-member", kind: "wireguard" }] }, { serverId: 1, autonomousSystem: 64512, routerId: "192.0.2.10", interfaces: [{ name: "wg-member", kind: "wireguard" }] },
{ serverId: 2, autonomousSystem: 64512, routerId: "192.0.2.11" }, { serverId: 2, autonomousSystem: 64512, routerId: "192.0.2.11" },
] }) ] })
let segment = { id, revision: 1, appliedRevision: 1, configuration, updatedAt: observedAt } let segment = { id, revision: 1, appliedRevision: 1, configuration, updatedAt: observedAt }
const digest = "a".repeat(64)
const mcpCalls: string[] = []
let applies = 0
await page.route("**/health", route => route.fulfill({ json: { ok: true } })) await page.route("**/health", route => route.fulfill({ json: { ok: true } }))
await page.route("**/api/**", async route => { await page.route("**/api/**", async route => {
const request = route.request() const request = route.request()
const path = new URL(request.url()).pathname const path = new URL(request.url()).pathname
const json = (body: unknown) => route.fulfill({ json: body }) const json = (body: unknown) => route.fulfill({ json: body })
if (path === "/api/auth/config") return json({ required: false }) if (path === "/api/auth/config") return json({ required: false })
if (path === "/api/ix/nodes") return json({ items: nodes }) if (path === "/api/ix/nodes") return json({ items: nodes, peers: nodes })
if (path === "/api/mcp/connections") return json({ connections: [{ if (path.startsWith("/api/mcp/")) {
id, name: "IX Lab", ownerId: "test", createdAt: observedAt, updatedAt: observedAt, lastUsedAt: null, generationValid: true, mcpCalls.push(path)
policy: { id, version: 1, status: "active", mode: "approval", expiresAt: "2099-01-01T00:00:00Z", return route.fulfill({ status: 503, json: { error: "MCP недоступен" } })
permissions: ["mm:network:write"], scope: { serverIds: [1, 2], operationIds: ["network.ix.configure"], allowGlobal: false }, }
dangerousPolicy: "approval", autonomousDangerousOperationIds: [], limits: mcpLimitsSchema.parse({}) },
}] })
if (path === "/api/mcp/ix/plan") return json({ planId: id, state: "awaiting-approval" })
if (path === `/api/mcp/plans/${id}/decision`) return json({ ok: true })
if (path === `/api/mcp/plans/${id}/apply`) return json({ id, state: "pending" })
if (path === "/api/ix/segments" && request.method() === "POST") { if (path === "/api/ix/segments" && request.method() === "POST") {
const change = ixChangeSchema.parse(request.postDataJSON()) const change = ixChangeSchema.parse(request.postDataJSON())
segment = { ...segment, configuration: change.configuration, revision: change.revision + 1 } segment = { ...segment, configuration: change.configuration, revision: change.revision + 1 }
return json({ segment }) return json({ segment })
} }
if (path === "/api/ix/segments") return json({ items: [segment] }) if (path === "/api/ix/segments") return json({ items: [segment] })
if (path === `/api/ix/segments/${id}/linux`) {
const kind = new URL(request.url()).searchParams.get("interfaceName")
if (kind === "wg-linux") return json({ revision: segment.appliedRevision, kind: "wireguard",
filename: "wg-linux.conf", template: "[Interface]\nTable = off\n" })
if (kind === "gre-linux") return json({ revision: segment.appliedRevision, kind: "gre-ipsec",
filename: "gre-linux.conf", template: "mode = transport\n", setup: "swanctl --initiate --child gre-linux" })
return json({ revision: segment.appliedRevision, items: [
{ serverId: 1, kind: "wireguard", interfaceName: "wg-linux" },
{ serverId: 2, kind: "gre-ipsec", interfaceName: "gre-linux" },
] })
}
if (path === `/api/ix/segments/${id}/status`) return json({ sites: [{ if (path === `/api/ix/segments/${id}/status`) return json({ sites: [{
serverId: 1, available: true, observedAt, neighbors: [{ name: "member", established: true }], serverId: 1, available: true, observedAt, neighbors: [{ name: "member", established: true }],
routes: [{ prefix: "2001:db8:120::/48", gateway: "2001:db8::1", immediateGateway: "2001:db8::2%wg-member", active: true }], routes: [{ prefix: "2001:db8:120::/48", gateway: "2001:db8::1", immediateGateway: "2001:db8::2%wg-member", active: true }],
}] }) }] })
if (path === "/api/ix/preview") return json({ objects: [] }) if (path === `/api/ix/segments/${id}/plan`) {
expect(request.postDataJSON()).toEqual({ revision: segment.revision })
return json({ revision: segment.revision, digest, changes: [
{ serverId: 1, action: "create", path: "/ipv6/route", fields: { "dst-address": "2001:db8:120::/48" } },
] })
}
if (path === `/api/ix/segments/${id}/apply`) {
expect(request.postDataJSON()).toEqual({ revision: segment.revision, digest })
applies++
segment = { ...segment, revision: segment.revision + 1, appliedRevision: segment.revision + 1 }
return json({ segment })
}
if (path === "/api/servers") return json([]) if (path === "/api/servers") return json([])
return json({}) return json({})
}) })
@@ -61,12 +80,28 @@ test("IX: карточка доступна на узком экране, сох
await page.setViewportSize({ width: 390, height: 760 }) await page.setViewportSize({ width: 390, height: 760 })
await page.getByLabel("Локальный ASN", { exact: true }).first().fill("64513") await page.getByLabel("Локальный ASN", { exact: true }).first().fill("64513")
await page.getByText("Подключения · 1", { exact: true }).click()
await page.getByLabel("Префиксы подключения").fill("2001:db8:120::/48")
await page.getByText("Группы шлюзов · 0", { exact: true }).first().click()
await page.getByRole("button", { name: "Добавить группу шлюзов" }).click()
await page.getByLabel("Имя группы шлюзов").fill("member")
await page.getByLabel("Служебный адрес шлюза").fill("2001:db8:ff::1")
await page.getByLabel("Адрес следующего шлюза").fill("2001:db8::2")
await page.getByLabel("Контрольный адрес").fill("2001:db8::2")
await page.getByText("Статические маршруты · 0", { exact: true }).first().click()
await page.getByRole("button", { name: "Добавить маршрут" }).click()
await page.getByLabel("Префикс маршрута").fill("2001:db8:120::/48")
const save = page.getByRole("button", { name: "Сохранить черновик" }) const save = page.getByRole("button", { name: "Сохранить черновик" })
await save.scrollIntoViewIfNeeded() await save.scrollIntoViewIfNeeded()
await expect(save).toBeInViewport() await expect(save).toBeInViewport()
await save.click() await save.click()
await expect(page.getByText("Черновик сохранён")).toBeVisible() await expect(page.getByText("Черновик сохранён")).toBeVisible()
expect(segment.configuration.sites[0]).toEqual({ ...configuration.sites[0], autonomousSystem: 64513 }) expect(segment.configuration.sites[0]).toMatchObject({
autonomousSystem: 64513,
interfaces: [{ name: "wg-member", prefixes: ["2001:db8:120::/48"] }],
groups: [{ id: "member", primary: { interface: "wg-member", nextHop: "2001:db8::2" } }],
routes: [{ prefix: "2001:db8:120::/48", group: "member" }],
})
expect(segment.configuration.sites[1]).toEqual(configuration.sites[1]) expect(segment.configuration.sites[1]).toEqual(configuration.sites[1])
await page.getByRole("tab", { name: "Маршруты и BGP" }).click() await page.getByRole("tab", { name: "Маршруты и BGP" }).click()
@@ -74,12 +109,63 @@ test("IX: карточка доступна на узком экране, сох
await expect(page.getByText("BGP 1 из 1")).toBeVisible() await expect(page.getByText("BGP 1 из 1")).toBeVisible()
await page.getByRole("tab", { name: "План изменений" }).click() await page.getByRole("tab", { name: "План изменений" }).click()
await page.getByRole("button", { name: "Построить предпросмотр" }).click() await page.getByRole("button", { name: "Построить предпросмотр" }).click()
await expect(page.getByText("Объекты RouterOS · 0")).toBeVisible() await expect(page.getByText("Ревизия 2 · операций RouterOS: 1")).toBeVisible()
await expect(page.getByText("IX Lab", { exact: true })).toBeVisible() await expect(page.getByText("/ipv6/route", { exact: true })).toBeVisible()
await page.getByRole("button", { name: "Подготовить план MCP" }).click()
await expect(page.getByText("Ждёт подтверждения")).toBeVisible()
await page.getByRole("button", { name: "Подтвердить", exact: true }).click()
await page.getByRole("button", { name: "Применить план" }).click() await page.getByRole("button", { name: "Применить план" }).click()
await expect(page.getByText("В очереди", { exact: true })).toBeVisible() await expect(page.getByRole("alertdialog")).toBeVisible()
expect(applies).toBe(0)
await page.getByRole("button", { name: "Применить", exact: true }).click()
await expect(page.getByText("Конфигурация IX применена")).toBeVisible()
expect(segment.appliedRevision).toBe(3)
expect(applies).toBe(1)
await page.getByRole("tab", { name: "Linux-клиенты" }).click()
await page.getByRole("button", { name: "Получить конфиг wg-linux" }).click()
await expect(page.getByText(/Table = off/)).toBeVisible()
const download = page.waitForEvent("download")
await page.getByRole("link", { name: "Скачать wg-linux.conf" }).click()
expect((await download).suggestedFilename()).toBe("wg-linux.conf")
await page.getByRole("button", { name: "Получить конфиг gre-linux" }).click()
await expect(page.getByText("mode = transport", { exact: true })).toBeVisible()
await expect(page.getByText("swanctl --initiate --child gre-linux", { exact: true })).toBeVisible()
expect(mcpCalls).toEqual([])
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(390) 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)
})