Compare commits

..
3 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
Denozordec 4900101b5e fix(ui): обновить раздел точек обмена и выбор типа узла
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 3s
Docker images / backend-image (push) Successful in 16s
Docker images / frontend-image (push) Successful in 3m34s
Docker images / updater-image (push) Successful in 2m36s
Docker images / netflow-agent-image (push) Successful in 36s
Docker images / notify-webhook (push) Successful in 2s
Docker images / publish-release (push) Successful in 10s
2026-11-23 02:07:56 +07:00
19 changed files with 1830 additions and 291 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>
}
+154
View File
@@ -0,0 +1,154 @@
"use client"
import { useMemo } from "react"
import { type ColumnDef, useTable } from "@tanstack/react-table"
import { FileTextIcon, PlusIcon, XIcon } from "lucide-react"
import type { IxConfiguration, IxSegment, IxSite, IxSiteObservation } from "@mmapp/contracts/internet-exchange"
import { DataGridShell } from "@/components/data-grids/shared/data-grid-shell"
import { EmptyState } from "@/components/empty-state"
import { Badge } from "@/components/reui/badge"
import { dataGridFeatures, type DataGridFeatures } from "@/components/reui/data-grid"
import { Frame, FrameDescription, FrameHeader, FramePanel, FrameTitle } from "@/components/reui/frame"
import { Button } from "@/components/ui/button"
import { Field, FieldDescription, FieldLabel } from "@/components/ui/field"
import { Input } from "@/components/ui/input"
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 }
type Route = IxSiteObservation["routes"][number]
export const nodeLabel = (nodes: readonly IxNode[], id: number) => nodes.find(node => node.id === id)?.name || `Узел ${id}`
export const newSite = (): IxSite => ({
serverId: 0, autonomousSystem: 64512, routerId: "",
interfaces: [], groups: [], exits: [], routes: [], neighbors: [], discardNetworks: [],
})
export function SegmentStatus({ segment }: { segment: IxSegment }) {
return segment.revision === segment.appliedRevision
? <Badge variant="success-light">Применена</Badge>
: <Badge variant="warning-light">{segment.appliedRevision ? "Есть черновик" : "Черновик"}</Badge>
}
export function SegmentGrid({ rows, nodes, loading, open, empty }: {
rows: IxSegment[]; nodes: IxNode[]; loading: boolean; open: (segment: IxSegment) => void; empty: React.ReactNode
}) {
const columns = useMemo<ColumnDef<DataGridFeatures, IxSegment>[]>(() => [
{ id: "name", header: "Сегмент", size: 210, cell: ({ row }) => (
<Button type="button" variant="link" size="sm" className="max-w-full justify-start" onClick={() => open(row.original)}>
<span className="truncate">{row.original.configuration.name}</span>
</Button>
) },
{ id: "sites", header: "Площадки", size: 230, cell: ({ row }) => row.original.configuration.sites.map(site => nodeLabel(nodes, site.serverId)).join(", ") },
{ id: "neighbors", header: "BGP-соседи", size: 115, cell: ({ row }) =>
<span className="tabular-nums">{row.original.configuration.sites.reduce((total, site) => total + site.neighbors.length, 0)}</span> },
{ id: "state", header: "Состояние", size: 140, cell: ({ row }) => <SegmentStatus segment={row.original} /> },
], [nodes, open])
const table = useTable({ features: dataGridFeatures, manualPagination: true, data: rows, columns, getRowId: row => row.id })
return <DataGridShell table={table} recordCount={rows.length} isLoading={loading} loadingMode="skeleton" emptyMessage={empty} />
}
export function ConfigurationFields({ configuration, nodes, peers, readOnly, change }: {
configuration: IxConfiguration; nodes: IxNode[]; peers: IxNode[]; readOnly: boolean; change: (value: IxConfiguration) => void
}) {
function updateSite(index: number, fields: Partial<IxSite>) {
change({ ...configuration, sites: configuration.sites.map((site, position) => position === index ? { ...site, ...fields } : site) })
}
const canAddSite = configuration.sites.length < 2 && nodes.filter(node => node.enabled).length > configuration.sites.length
return <div className="grid min-w-0 gap-3">
<Frame spacing="sm">
<FrameHeader><FrameTitle>Сегмент</FrameTitle></FrameHeader>
<FramePanel>
<Field className="max-w-md">
<FieldLabel htmlFor="ix-name">Имя сегмента</FieldLabel>
<Input id="ix-name" placeholder="ix-central" value={configuration.name} readOnly={readOnly}
onChange={event => change({ ...configuration, name: event.target.value })} />
{!readOnly && <FieldDescription>Латинские строчные буквы, цифры и дефисы.</FieldDescription>}
</Field>
</FramePanel>
</Frame>
{configuration.sites.map((site, index) => {
const fieldId = `ix-site-${index}`
const choices = nodes.filter(node => node.id === site.serverId || (node.enabled && !configuration.sites.some((other, i) => i !== index && other.serverId === node.id)))
return <Frame key={fieldId} spacing="sm">
<FrameHeader className="flex-row items-center justify-between gap-2">
<div className="min-w-0">
<FrameTitle>Площадка {index + 1}</FrameTitle>
{site.serverId > 0 && <FrameDescription className="wrap-anywhere">{nodeLabel(nodes, site.serverId)}</FrameDescription>}
</div>
{!readOnly && configuration.sites.length > 1 && <Button type="button" size="icon-sm" variant="ghost"
aria-label={`Убрать площадку ${index + 1}`}
onClick={() => change({ ...configuration, sites: configuration.sites.filter((_, position) => position !== index) })}>
<XIcon aria-hidden />
</Button>}
</FrameHeader>
<FramePanel className="grid gap-4">
<div className="grid min-w-0 gap-3 sm:grid-cols-2 lg:grid-cols-3">
<Field className="min-w-0">
<FieldLabel htmlFor={fieldId}>Узел IX</FieldLabel>
<Select
value={site.serverId ? String(site.serverId) : null}
items={choices.map(node => ({ value: String(node.id), label: node.name }))}
disabled={readOnly}
onValueChange={value => { if (value) updateSite(index, { serverId: Number(value) }) }}
>
<SelectTrigger id={fieldId} className="w-full"><SelectValue placeholder="Выберите узел" /></SelectTrigger>
<SelectContent>
{choices.map(node => <SelectItem key={node.id} value={String(node.id)} disabled={!node.enabled}>{node.name}</SelectItem>)}
</SelectContent>
</Select>
</Field>
<Field className="min-w-0">
<FieldLabel htmlFor={fieldId + "-asn"}>Локальный ASN</FieldLabel>
<Input id={fieldId + "-asn"} inputMode="numeric" value={site.autonomousSystem || ""} readOnly={readOnly}
onChange={event => { if (/^\d*$/.test(event.target.value)) updateSite(index, { autonomousSystem: Number(event.target.value) }) }} />
</Field>
<Field className="min-w-0">
<FieldLabel htmlFor={fieldId + "-router"}>Router ID</FieldLabel>
<Input id={fieldId + "-router"} placeholder="192.0.2.10" value={site.routerId} readOnly={readOnly}
onChange={event => updateSite(index, { routerId: event.target.value })} />
</Field>
</div>
<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)))
.map(node => ({ value: String(node.id), label: node.name }))} />
</FramePanel>
</Frame>
})}
{!readOnly && canAddSite && <Button type="button" variant="outline" size="sm" className="w-fit"
onClick={() => change({ ...configuration, sites: [...configuration.sites, newSite()] })}>
<PlusIcon aria-hidden />Добавить площадку
</Button>}
</div>
}
const routeColumns: ColumnDef<DataGridFeatures, Route>[] = [
{ id: "prefix", header: "Префикс", size: 160, cell: ({ row }) => <span className="font-mono">{row.original.prefix}</span> },
{ id: "gateway", header: "Шлюз", size: 140, cell: ({ row }) => row.original.gateway || "—" },
{ id: "immediate", header: "Фактический next hop", size: 200, cell: ({ row }) => row.original.immediateGateway ?? "—" },
{ id: "active", header: "Состояние", size: 112, cell: ({ row }) => row.original.active
? <Badge variant="success-light">Активен</Badge>
: <Badge variant="secondary">Неактивен</Badge> },
]
export function RouteGrid({ observation, nodes }: { observation: IxSiteObservation; nodes: IxNode[] }) {
const table = useTable({ features: dataGridFeatures, manualPagination: true, data: observation.routes, columns: routeColumns })
return <Frame spacing="sm" className="min-w-0">
<FrameHeader className="flex-row flex-wrap items-center justify-between gap-2">
<div className="min-w-0">
<FrameTitle className="wrap-anywhere">{nodeLabel(nodes, observation.serverId)}</FrameTitle>
<FrameDescription>{new Date(observation.observedAt).toLocaleString("ru-RU")}</FrameDescription>
</div>
{observation.available ? <Badge variant="info-light">
BGP {observation.neighbors.filter(peer => peer.established).length} из {observation.neighbors.length}
</Badge> : <Badge variant="warning-light">Состояние недоступно</Badge>}
</FrameHeader>
{observation.available && <FramePanel className="min-w-0 p-0">
<div className="overflow-x-auto">
<DataGridShell table={table} recordCount={observation.routes.length}
emptyMessage={<EmptyState icon={<FileTextIcon />} title="Маршруты не найдены" className="py-8" />} />
</div>
</FramePanel>}
</Frame>
}
+371 -184
View File
@@ -1,250 +1,437 @@
"use client"
import { useEffect, useMemo, useState } from "react"
import { useEffect, useRef, useState } from "react"
import Link from "next/link"
import { NetworkIcon, PlusIcon, RefreshCwIcon } from "lucide-react"
import { type ColumnDef, useTable } from "@tanstack/react-table"
import { ixSegmentConfigurationSchema, type IxChange, type IxRouterObject, type IxSegment, type IxSiteObservation } from "@mmapp/contracts/internet-exchange"
import { Badge } from "@/components/reui/badge"
import { dataGridFeatures, type DataGridFeatures } from "@/components/reui/data-grid"
import { DataGridShell } from "@/components/data-grids/shared/data-grid-shell"
import { ArrowLeftIcon, CircleAlertIcon, NetworkIcon, PlusIcon, RefreshCwIcon, Trash2Icon } from "lucide-react"
import { ixSegmentConfigurationSchema, type IxChange, type IxConfiguration, type IxLinuxAccess, type IxLinuxBinding, type IxWebPlan, type IxSegment, type IxSiteObservation } from "@mmapp/contracts/internet-exchange"
import { Alert, AlertDescription, AlertTitle } from "@/components/reui/alert"
import { Frame, FrameDescription, FrameHeader, FramePanel, FrameTitle } from "@/components/reui/frame"
import { EmptyState } from "@/components/empty-state"
import { PageHeader } from "@/components/page-header"
import { Button, buttonVariants } from "@/components/ui/button"
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from "@/components/ui/alert-dialog"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Skeleton } from "@/components/ui/skeleton"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Textarea } from "@/components/ui/textarea"
import { can, ensureAuthConfig } from "@/lib/auth"
import { useDataSource } from "@/lib/data-source"
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"
type Node = { id: number; name: string; site: string; country: string; enabled: boolean }
type Connection = { id: string; name: string }
type Plan = { planId: string; state: string }
type Tab = "configuration" | "routes" | "changes" | "linux"
const title = "Точки обмена трафиком"
const describe = (error: unknown) => error instanceof Error ? error.message : "Не удалось выполнить операцию IX"
const json = (value: unknown) => JSON.stringify(value, null, 2)
const post = (value: unknown) => ({ method: "POST", body: JSON.stringify(value) })
function SegmentGrid({ rows, open }: { rows: IxSegment[]; open: (segment: IxSegment) => void }) {
const columns: ColumnDef<DataGridFeatures, IxSegment>[] = [
{ id: "name", header: "Сегмент", cell: ({ row }) => <Button variant="ghost" size="sm" onClick={() => open(row.original)}>{row.original.configuration.name}</Button> },
{ id: "sites", header: "Площадки", cell: ({ row }) => row.original.configuration.sites.length },
{ id: "neighbors", header: "BGP-соседи", cell: ({ row }) => row.original.configuration.sites.reduce((total, site) => total + site.neighbors.length, 0) },
{ id: "state", header: "Состояние конфигурации", cell: ({ row }) => row.original.revision === row.original.appliedRevision
? <Badge variant="success-light">Применена</Badge>
: <Badge variant="warning-light">Черновик</Badge> },
]
const table = useTable({ features: dataGridFeatures, manualPagination: true, data: rows, columns, getRowId: row => row.id })
return <DataGridShell table={table} recordCount={rows.length} />
const actionLabels = { create: "Создать", update: "Обновить", delete: "Удалить" } as const
function RouterOsChanges({ changes, nodes }: { changes: IxWebPlan["changes"]; nodes: IxNode[] }) {
if (!changes.length) return null
return <ul className="max-h-56 min-w-0 divide-y overflow-auto rounded-md border">
{changes.map((operation, index) => <li key={index} className="min-w-0 p-2.5 text-sm">
<details>
<summary className="cursor-pointer wrap-anywhere">{actionLabels[operation.action]} · {nodeLabel(nodes, operation.serverId)} · <code>{operation.path}</code>
{operation.target && <> · <code>{operation.target}</code></>}
</summary>
<dl className="grid min-w-0 grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-1 py-2 text-xs">
{operation.placeBefore && <><dt className="text-muted-foreground">Перед объектом</dt><dd className="font-mono">{operation.placeBefore}</dd></>}
{Object.entries(operation.fields).map(([key, value]) => <div key={key} className="contents">
<dt className="max-w-32 wrap-anywhere text-muted-foreground">{key}</dt>
<dd className="wrap-anywhere font-mono">{value}</dd>
</div>)}
</dl>
</details>
</li>)}
</ul>
}
export default function IxPage() {
const { backendUrl, mode, prefsHydrated } = useDataSource()
const [segments, setSegments] = useState<IxSegment[]>([])
const [nodes, setNodes] = useState<Node[]>([])
const [connections, setConnections] = useState<Connection[]>([])
const [connectionId, setConnectionId] = useState("")
const [nodes, setNodes] = useState<IxNode[]>([])
const [peers, setPeers] = useState<IxNode[]>([])
const [selected, setSelected] = useState<IxSegment | null>(null)
const [editing, setEditing] = useState(false)
const [body, setBody] = useState("")
const [draft, setDraft] = useState<IxConfiguration | null>(null)
const [advanced, setAdvanced] = useState<string | null>(null)
const [filter, setFilter] = useState("")
const [nodeId, setNodeId] = useState("")
const [name, setName] = useState("")
const [asn, setAsn] = useState("64512")
const [routerId, setRouterId] = useState("")
const [observations, setObservations] = useState<IxSiteObservation[]>([])
const [preview, setPreview] = useState<IxRouterObject[] | null>(null)
const [linux, setLinux] = useState("")
const [plan, setPlan] = useState<Plan | null>(null)
const [tab, setTab] = useState<"configuration" | "routes" | "changes">("configuration")
const [observations, setObservations] = useState<IxSiteObservation[] | null>(null)
const [linuxBindings, setLinuxBindings] = useState<IxLinuxBinding[]>([])
const [linux, setLinux] = useState<(IxLinuxAccess & IxLinuxBinding) | null>(null)
const [plan, setPlan] = useState<IxWebPlan | null>(null)
const [removalPlan, setRemovalPlan] = useState<IxWebPlan | null>(null)
const [tab, setTab] = useState<Tab>("configuration")
const [loading, setLoading] = useState(true)
const [busy, setBusy] = useState(false)
const [error, setError] = useState("")
const [notice, setNotice] = useState("")
const [write, setWrite] = useState(false)
const [approve, setApprove] = useState(false)
const heading = useRef<HTMLHeadingElement>(null)
const focusAfterNavigation = useRef(false)
const inDetail = draft !== null
async function load(signal?: AbortSignal) {
const options = { signal }
if (signal?.aborted) return
setWrite(can("mm:network:write"))
const [segmentsResult, nodesResult] = await Promise.all([
requestJson<{ items: IxSegment[] }>(backendUrl, "/api/ix/segments?limit=100", options),
requestJson<{ items: Node[] }>(backendUrl, "/api/ix/nodes", options),
requestJson<{ items: IxSegment[] }>(backendUrl, "/api/ix/segments?limit=100", { signal }),
requestJson<{ items: IxNode[]; peers?: IxNode[] }>(backendUrl, "/api/ix/nodes", { signal }),
])
if (signal?.aborted) return
setSegments(segmentsResult.items)
setNodes(nodesResult.items)
if (can("mm:mcp:read")) {
const { connections } = await mcpApi(backendUrl).connections(signal)
setConnections(connections.filter(connection => connection.policy.status === "active" &&
connection.policy.scope.operationIds.includes("network.ix.configure")).map(connection => ({ id: connection.id, name: connection.name })))
}
setPeers(nodesResult.peers ?? nodesResult.items)
}
useEffect(() => {
if (!prefsHydrated || mode !== "live") return
const controller = new AbortController()
void ensureAuthConfig().then(async () => {
void ensureAuthConfig().then(() => {
if (controller.signal.aborted) return
setWrite(can("mm:network:write"))
setApprove(can("mm:mcp:approve"))
await load(controller.signal)
}).catch(error => { if (!controller.signal.aborted) setError(describe(error)) })
setLoading(true)
setError("")
return load(controller.signal)
})
.catch(error => { if (!controller.signal.aborted) setError(describe(error)) })
.finally(() => { if (!controller.signal.aborted) setLoading(false) })
return () => controller.abort()
// Load only when the project source changes.
// Reload when the project data source changes.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [backendUrl, mode, prefsHydrated])
const rows = useMemo(() => segments.filter(segment => segment.configuration.name.includes(filter.toLowerCase().trim())), [filter, segments])
function open(segment: IxSegment | null) {
setSelected(segment)
setBody(segment ? json(segment.configuration) : "")
setPreview(null)
useEffect(() => {
if (focusAfterNavigation.current) {
focusAfterNavigation.current = false
heading.current?.focus()
}
}, [inDetail])
const rows = segments.filter(segment => segment.configuration.name.includes(filter.trim().toLowerCase()))
const enabledNodes = nodes.filter(node => node.enabled)
const live = prefsHydrated && mode === "live"
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() {
setPlan(null)
setObservations([])
setLinux("")
setRemovalPlan(null)
setNotice("")
}
function open(segment: IxSegment | null) {
focusAfterNavigation.current = !inDetail
setSelected(segment)
setDraft(segment?.configuration ?? { name: "", sites: [{ ...newSite(), serverId: enabledNodes.length === 1 ? enabledNodes[0].id : 0 }] })
setAdvanced(null)
setObservations(null)
setLinux(null)
setLinuxBindings([])
setTab("configuration")
setError("")
setEditing(true)
invalidateReview()
}
function close() {
focusAfterNavigation.current = true
setDraft(null)
setRemovalPlan(null)
setError("")
setNotice("")
}
function change(): IxChange {
const configuration = ixSegmentConfigurationSchema.parse(JSON.parse(body))
const configuration = ixSegmentConfigurationSchema.parse(advanced === null ? draft : JSON.parse(advanced))
return { ...(selected ? { id: selected.id } : {}), revision: selected?.revision ?? 0, configuration }
}
async function perform(work: () => Promise<void>) {
setBusy(true)
setError("")
setNotice("")
try { await work() } catch (error) { setError(describe(error)) }
finally { setBusy(false) }
}
async function save() {
const { segment } = await requestJson<{ segment: IxSegment }>(backendUrl, "/api/ix/segments", post(change()))
open(segment)
await load()
}
async function observe() {
if (!selected) return
const { sites } = await requestJson<{ sites: IxSiteObservation[] }>(backendUrl, `/api/ix/segments/${selected.id}/status`)
setObservations(sites)
setTab("routes")
setSegments(current => current.some(item => item.id === segment.id)
? current.map(item => item.id === segment.id ? segment : item)
: [segment, ...current])
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() {
if (!selected?.appliedRevision) return
const { sites } = await requestJson<{ sites: IxSiteObservation[] }>(backendUrl, `/api/ix/segments/${selected.id}/status`)
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) {
if (next === tab || busy) return
setError("")
setTab(next)
if (next === "routes" && observations === null && selected?.appliedRevision) void perform(observe)
if (next === "linux" && selected?.appliedRevision) void perform(loadLinuxBindings)
}
const listEmpty = error ? "Не удалось загрузить список" :
filter.trim() ? "Сегменты не найдены" : !live ? "Подключите backend" : "Нет сегментов IX"
const listDescription = error ? "Повторите загрузку списка." : filter.trim() ? "Попробуйте другое имя сегмента." :
!live ? "Откройте раздел в режиме «Живые»." : enabledNodes.length ? undefined : "Сначала добавьте сервер типа IX Node."
return <>
<PageHeader crumbs={[{ label: "Сеть" }, { label: "Точки обмена трафиком" }]} />
<div className="mx-auto flex w-full max-w-6xl flex-1 flex-col gap-6 p-4 md:p-6">
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<h1 className="text-2xl font-semibold tracking-tight">Точки обмена трафиком</h1>
<p className="mt-1 text-sm text-muted-foreground">IX-сегменты, маршруты и BGP-политики в отдельных VRF.</p>
</div>
<div className="flex gap-2">
<Button variant="outline" size="icon" disabled={busy || mode !== "live"} aria-label="Обновить список" onClick={() => void perform(() => load())}><RefreshCwIcon /></Button>
{write && <Button onClick={() => open(null)} disabled={busy}><PlusIcon />Добавить сегмент</Button>}
</div>
</div>
{error && <p role="alert" className="rounded-md border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive">{error}</p>}
<div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
{[{ name: "Узлы IX", count: nodes.length }, { name: "Сегменты", count: segments.length }, { name: "Применённые ревизии", count: segments.filter(segment => segment.appliedRevision === segment.revision).length }].map(item =>
<div key={item.name} className="rounded-lg border bg-card p-4">
<div className="text-sm text-muted-foreground">{item.name}</div>
<div className="mt-1 text-2xl font-semibold tabular-nums">{item.count}</div>
</div>
)}
</div>
<section className="flex flex-col gap-3" aria-label="IX-сегменты">
<Input aria-label="Поиск сегментов" placeholder="Найти сегмент" className="max-w-xs" value={filter} onChange={event => setFilter(event.target.value)} />
{rows.length ? <SegmentGrid rows={rows} open={open} /> :
<EmptyState icon={<NetworkIcon className="size-4" />} title={filter ? "Сегменты не найдены" : "Нет IX-сегментов"}
description={mode !== "live" ? "Сегменты доступны при подключении к серверу." : "Добавьте сервер типа IX Node, чтобы создать сегмент."} />}
</section>
{editing && <section className="flex flex-col gap-4 rounded-lg border bg-card p-4" aria-label="Карточка IX">
<div className="flex flex-wrap items-center justify-between gap-2">
<h2 className="text-lg font-semibold">{selected?.configuration.name ?? "Новый сегмент"}</h2>
<Button variant="ghost" size="sm" onClick={() => setEditing(false)}>Закрыть</Button>
</div>
<div className="flex flex-wrap gap-2">
<Button size="sm" variant={tab === "configuration" ? "secondary" : "ghost"} onClick={() => setTab("configuration")}>Конфигурация</Button>
<Button size="sm" variant={tab === "routes" ? "secondary" : "ghost"} disabled={!selected?.appliedRevision || busy} onClick={() => void perform(observe)}>Маршруты и BGP</Button>
<Button size="sm" variant={tab === "changes" ? "secondary" : "ghost"} disabled={!preview && !plan} onClick={() => setTab("changes")}>Изменения</Button>
</div>
{tab === "configuration" && <>
{!body && <div className="grid gap-3 sm:grid-cols-2">
<div className="grid gap-2"><Label htmlFor="ix-name">Имя сегмента</Label><Input id="ix-name" placeholder="compute" value={name} onChange={event => setName(event.target.value)} /></div>
<div className="grid gap-2"><Label htmlFor="ix-site">Площадка</Label><select id="ix-site" className="h-9 rounded-md border bg-background px-3 text-sm" value={nodeId} onChange={event => setNodeId(event.target.value)}>
<option value="">Выберите IX Node</option>
{nodes.filter(node => node.enabled).map(node => <option key={node.id} value={node.id}>{node.name || node.id}</option>)}
</select></div>
<div className="grid gap-2"><Label htmlFor="ix-asn">Локальный ASN</Label><Input id="ix-asn" inputMode="numeric" value={asn} onChange={event => setAsn(event.target.value)} /></div>
<div className="grid gap-2"><Label htmlFor="ix-router-id">Router ID</Label><Input id="ix-router-id" placeholder="192.0.2.10" value={routerId} onChange={event => setRouterId(event.target.value)} /></div>
<Button variant="outline" disabled={!nodeId || !name || !routerId} onClick={() => void perform(async () => {
setBody(json(ixSegmentConfigurationSchema.parse({ name, sites: [{ serverId: Number(nodeId), autonomousSystem: Number(asn), routerId }] })))
})}>Подготовить конфигурацию</Button>
<Link className={buttonVariants({ variant: "link" })} href="/servers">Открыть каталог серверов</Link>
</div>}
{body && <div className="grid gap-2">
<Label htmlFor="ix-configuration">Конфигурация сегмента</Label>
<Textarea id="ix-configuration" spellCheck={false} readOnly={!write} rows={13} className="font-mono" value={body} onChange={event => {
setBody(event.target.value); setPlan(null); setPreview(null)
}} />
</div>}
{body && write && <div className="flex flex-wrap items-end gap-2">
<Button onClick={() => void perform(save)} disabled={busy}>Сохранить черновик</Button>
<Button variant="outline" disabled={busy} onClick={() => void perform(async () => {
const result = await requestJson<{ objects: IxRouterObject[] }>(backendUrl, "/api/ix/preview", post(change()))
setPreview(result.objects); setTab("changes")
})}>Предпросмотр</Button>
<div className="grid gap-2"><Label htmlFor="ix-connection">Подключение MCP</Label><select id="ix-connection" className="h-9 rounded-md border bg-background px-3 text-sm" value={connectionId} onChange={event => setConnectionId(event.target.value)}>
<option value="">Выберите подключение</option>
{connections.map(connection => <option key={connection.id} value={connection.id}>{connection.name}</option>)}
</select></div>
<Button variant="outline" disabled={!connectionId || busy} onClick={() => void perform(async () => {
setPlan(await requestJson<Plan>(backendUrl, "/api/mcp/ix/plan", post({ connectionId, change: change() })))
setTab("changes")
})}>Подготовить план MCP</Button>
</div>}
</>}
{tab === "changes" && <>
{preview && <div className="grid gap-2"><p className="text-sm">{preview.length} объектов в желаемой конфигурации</p>
<pre className="max-h-96 overflow-auto rounded-md border bg-muted/30 p-3 text-sm">{json(preview)}</pre></div>}
{plan && <div className="flex flex-wrap items-center gap-2">
<Badge variant="info-light">{plan.state}</Badge>
<span className="text-sm text-muted-foreground">{plan.planId}</span>
<Link className={buttonVariants({ variant: "link" })} href="/mcp">Планы и операции</Link>
{plan.state === "awaiting-approval" && approve && <Button 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 disabled={busy} onClick={() => void perform(async () => {
const result = await mcpApi(backendUrl).apply(plan.planId)
setPlan({ ...plan, state: result.state })
})}>Применить план</Button>}
</div>}
</>}
{tab === "routes" && <div className="grid gap-4">
{selected?.configuration.sites.flatMap(site => site.interfaces.filter(binding => binding.provisionWireguard?.hubEndpoint).map(binding =>
<Button key={site.serverId + ":" + binding.name} size="sm" variant="outline" className="w-fit" 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>
))}
{linux && <pre className="overflow-auto rounded-md border bg-muted/30 p-3 text-sm">{linux}</pre>}
{observations.map(site => <div key={site.serverId} className="grid gap-2">
<div className="flex flex-wrap justify-between gap-2 text-sm">
<span className="font-medium">{nodes.find(node => node.id === site.serverId)?.name || site.serverId}</span>
<span className="text-muted-foreground">{new Date(site.observedAt).toLocaleString()}</span>
<PageHeader crumbs={inDetail ? [{ label: "Сегменты IX" }, { label: selected?.configuration.name ?? "Новый сегмент" }] : [{ label: title }]} />
<div className="min-h-0 min-w-0 flex-1 overflow-y-auto">
<div className="mx-auto flex w-full max-w-6xl min-w-0 flex-col gap-4 p-4 md:gap-5 md:p-6" aria-busy={busy}>
{inDetail && <Button type="button" variant="ghost" size="sm" className="w-fit" disabled={busy} onClick={close}>
<ArrowLeftIcon aria-hidden />Все сегменты
</Button>}
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="min-w-0">
<div className="flex flex-wrap items-center gap-2">
<h1 ref={heading} tabIndex={-1} className="text-xl font-semibold tracking-tight wrap-anywhere md:text-2xl">
{inDetail ? selected?.configuration.name ?? "Новый сегмент" : title}
</h1>
{inDetail && selected && <SegmentStatus segment={selected} />}
</div>
{site.available ? <>
<p className="text-sm text-muted-foreground">Активные BGP-сессии {site.neighbors.filter(peer => peer.established).length} из {site.neighbors.length}</p>
<div className="overflow-x-auto"><table className="w-full text-left text-sm">
<thead><tr className="border-b"><th className="p-2">Префикс</th><th className="p-2">Шлюз</th><th className="p-2">Фактический next hop</th><th className="p-2">Активен</th></tr></thead>
<tbody>{site.routes.map((route, index) => <tr key={route.prefix + ":" + index} className="border-b">
<td className="p-2 font-mono">{route.prefix}</td><td className="p-2">{route.gateway || "—"}</td>
<td className="p-2">{route.immediateGateway ?? "Не подтверждён"}</td><td className="p-2">{route.active ? "Да" : "Нет"}</td>
</tr>)}</tbody>
</table></div>
</> : <Badge variant="warning-light">Состояние недоступно</Badge>}
</div>)}
</div>}
</section>}
{inDetail ? (selected && <p className="mt-1 text-sm text-muted-foreground">
Ревизия {selected.revision}{selected.appliedRevision ? ` · Применена ревизия ${selected.appliedRevision}` : ""}
</p>) : <p className="mt-1 text-sm text-muted-foreground">Сегменты IX, площадки и маршрутизация</p>}
</div>
{inDetail && selected && live && write && <AlertDialog open={removalPlan !== null}
onOpenChange={open => { if (open) void perform(prepareRemoval); else setRemovalPlan(null) }}>
<AlertDialogTrigger render={<Button type="button" variant="outline" size="sm" disabled={busy} />}>
<Trash2Icon aria-hidden />Удалить сегмент
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle className="wrap-anywhere">Удалить {selected.configuration.name}?</AlertDialogTitle>
<AlertDialogDescription>
{selected.appliedRevision
? "Этот сегмент перестанет передавать трафик. Управляемая конфигурация будет удалена с узлов IX."
: "Черновик будет удалён из списка сегментов. Конфигурация роутеров останется прежней."}
</AlertDialogDescription>
</AlertDialogHeader>
{removalPlan && <RouterOsChanges changes={removalPlan.changes} nodes={nodes} />}
<AlertDialogFooter>
<AlertDialogCancel>Отмена</AlertDialogCancel>
<AlertDialogAction variant="destructive" disabled={busy} onClick={() => void perform(removeSegment)}>Удалить</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>}
{!inDetail && <div className="flex flex-wrap items-center gap-2">
<Button type="button" size="icon-sm" variant="outline" disabled={busy || loading || !live} aria-label="Обновить список"
onClick={() => void perform(() => load())}><RefreshCwIcon aria-hidden /></Button>
{canCreate && <Button type="button" size="sm" onClick={() => open(null)} disabled={busy}><PlusIcon aria-hidden />Добавить сегмент</Button>}
</div>}
</div>
{error && <Alert variant="destructive"><CircleAlertIcon aria-hidden /><AlertTitle>Ошибка IX</AlertTitle><AlertDescription className="wrap-anywhere">{error}</AlertDescription></Alert>}
{notice && <p role="status" className="text-sm text-muted-foreground">{notice}</p>}
{!draft ? <Frame spacing="sm" className="min-w-0">
<FrameHeader className="flex-row flex-wrap items-center justify-between gap-2">
<div><FrameTitle>Сегменты</FrameTitle><FrameDescription>{live && !loading ? `Найдено: ${rows.length}` : ""}</FrameDescription></div>
<Input type="search" aria-label="Поиск сегментов" placeholder="Найти сегмент" className="w-full sm:w-56"
value={filter} onChange={event => setFilter(event.target.value)} />
</FrameHeader>
<FramePanel className="min-w-0 p-0">
<div className="overflow-x-auto">
<SegmentGrid rows={rows} nodes={nodes} loading={!prefsHydrated || (live && loading)} open={open} empty={
<EmptyState icon={<NetworkIcon aria-hidden />} title={listEmpty} description={listDescription}
action={live && !filter.trim() && !error && enabledNodes.length === 0 ? <Button render={<Link href="/servers" />} nativeButton={false} size="sm" variant="outline">Открыть серверы</Button> : undefined} />
} />
</div>
</FramePanel>
</Frame> : <Tabs value={tab} onValueChange={value => showTab(value as Tab)} className="min-w-0 gap-3">
<div className="min-w-0 overflow-x-auto border-b pb-1">
<TabsList variant="line" aria-label="Разделы сегмента">
<TabsTrigger value="configuration">Конфигурация</TabsTrigger>
<TabsTrigger value="linux">Linux-клиенты</TabsTrigger>
<TabsTrigger value="routes">Маршруты и BGP</TabsTrigger>
<TabsTrigger value="changes">План изменений</TabsTrigger>
</TabsList>
</div>
<TabsContent value="configuration" className="grid min-w-0 gap-3">
{advanced === null ? <ConfigurationFields configuration={draft} nodes={nodes} peers={peers} readOnly={!live || !write || busy}
change={value => { setDraft(value); invalidateReview() }} /> : <Frame spacing="sm">
<FrameHeader><FrameTitle>Конфигурация JSON</FrameTitle><FrameDescription>Интерфейсы, группы шлюзов, маршруты и BGP-политики.</FrameDescription></FrameHeader>
<FramePanel>
<Textarea aria-label="Конфигурация JSON" spellCheck={false} readOnly={!live || !write || busy} rows={14}
className="font-mono" value={advanced} onChange={event => { setAdvanced(event.target.value); invalidateReview() }} />
</FramePanel>
</Frame>}
<div className="flex flex-wrap items-center gap-2">
{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))}>
{write ? "Редактировать JSON" : "Показать JSON"}
</Button> : <Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => void perform(async () => {
setDraft(change().configuration)
setAdvanced(null)
})}>К форме</Button>}
</div>
</TabsContent>
<TabsContent value="routes" className="grid min-w-0 gap-3">
{!selected?.appliedRevision ? <EmptyState title="Конфигурация ещё не применена"
description="Маршруты и BGP-сессии появятся после применения плана." className="py-8" /> : <>
<div className="flex flex-wrap gap-2">
<Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => void perform(observe)}>
<RefreshCwIcon aria-hidden />Обновить состояние
</Button>
</div>
{busy && observations === null && <Skeleton className="h-28 w-full" role="status" aria-label="Загрузка маршрутов" />}
{observations?.map(site => <RouteGrid key={site.serverId} observation={site} nodes={nodes} />)}
</>}
</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">
<Frame spacing="sm">
<FrameHeader>
<FrameTitle>Изменения RouterOS</FrameTitle>
<FrameDescription>Предпросмотр сравнивает сохранённую ревизию с текущим состоянием узлов.</FrameDescription>
</FrameHeader>
<FramePanel className="grid min-w-0 gap-3">
{!write ? <p className="text-sm text-muted-foreground">Нужно право изменять сетевую конфигурацию.</p>
: dirty ? <p className="text-sm text-muted-foreground">Сохраните черновик на вкладке «Конфигурация».</p>
: selected?.appliedRevision === selected?.revision ? <p className="text-sm text-muted-foreground">Текущая ревизия применена.</p>
: <Button type="button" size="sm" variant="outline" className="w-fit" disabled={!canPlan || busy}
onClick={() => void perform(prepare)}>Построить предпросмотр</Button>}
{plan && <div className="grid min-w-0 gap-3 border-t pt-3">
<p className="text-sm font-medium">Ревизия {plan.revision} · операций RouterOS: {plan.changes.length}</p>
{plan.changes.length === 0 && <p className="text-sm text-muted-foreground">Конфигурация RouterOS совпадает с черновиком. Применение обновит ревизию в MikrotikManager.</p>}
<RouterOsChanges changes={plan.changes} nodes={nodes} />
<AlertDialog>
<AlertDialogTrigger render={<Button type="button" size="sm" className="w-fit" disabled={busy || !canPlan} />}>
Применить план
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Применить конфигурацию IX?</AlertDialogTitle>
<AlertDialogDescription>Будет применена ревизия {plan.revision} сегмента {selected?.configuration.name}. Операций RouterOS: {plan.changes.length}.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Отмена</AlertDialogCancel>
<AlertDialogAction onClick={() => void perform(apply)}>Применить</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>}
</FramePanel>
</Frame>
</TabsContent>
</Tabs>}
</div>
</div>
</>
}
+25 -13
View File
@@ -38,6 +38,8 @@ import { cn } from "@/lib/utils"
import { KpiStatGrid } from "@/components/reui-kit/kpi-stat-grid"
import { DataPageCard } from "@/components/data-page-card"
import { Button } from "@/components/ui/button"
import { ButtonGroup } from "@/components/ui/button-group"
import { Field, FieldTitle } from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import {
Sheet, SheetContent, SheetHeader, SheetTitle,
@@ -772,19 +774,29 @@ function ServersPageContent() {
value={form.name} onChange={e => set("name", e.target.value)} />
</FormField>
<FormField label="Тип узла" required>
<SegmentedControl
className="max-w-full flex-wrap"
value={form.type}
onChange={v => set("type", v)}
options={[
{ value: "home-router", label: "Home Router" },
{ value: "jump-host", label: "JumpHost" },
{ value: "exit-node", label: "Exit Node" },
{ value: "ix-node", label: "IX Node" },
]}
/>
</FormField>
<Field>
<FieldTitle id="server-node-type-label">Тип узла <span aria-hidden className="text-destructive">*</span></FieldTitle>
<ButtonGroup aria-labelledby="server-node-type-label" className="max-w-full">
{([
["home-router", "Home Router"],
["jump-host", "JumpHost"],
["exit-node", "Exit Node"],
["ix-node", "IX Node"],
] as const).map(([value, label]) => (
<Button
key={value}
type="button"
variant={form.type === value ? "default" : "outline"}
size="sm"
aria-pressed={form.type === value}
className="h-auto min-h-7 min-w-0 flex-auto shrink whitespace-normal py-1"
onClick={() => set("type", value)}
>
{label}
</Button>
))}
</ButtonGroup>
</Field>
<div className="grid grid-cols-2 gap-3">
<FormField label="Площадка" required hint="MSK, SPB, FRA…">
+28
View File
@@ -1604,6 +1604,34 @@
"operations": [],
"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",
"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 { ixChangeSchema, type IxChange } from "@mmapp/contracts/internet-exchange"
import { pool } from "../../db/index.js"
import { applyIxChange, currentIxChange, ixTarget, observeIxSegment, prepareIxChange, reconcileIxChange } from "../../services/internet-exchange-execution.js"
import { applyIxChange, currentIxChange, ixTarget, observeIxSegment, prepareIxChange, prepareIxRemoval, reconcileIxChange, removeIxSegment } from "../../services/internet-exchange-execution.js"
import { IxConflict, ixDeviceIds } from "../../services/internet-exchange-plan.js"
import { listIxSegments, readIxRevision, readIxSegment } from "../../services/internet-exchange-store.js"
import { assertIxRevision, isIxSegmentArchived, listIxSegments, readIxRevision, readIxSegment } from "../../services/internet-exchange-store.js"
import type { add } from "./actions.js"
import type { ActionContext } from "./action-types.js"
import { McpError } from "./security.js"
@@ -12,10 +12,13 @@ import { registerMcpService } from "./service-registry.js"
export const ixOperation = "network.ix.configure"
export const ixRestoreOperation = "network.ix.restore"
const service = "network.ix.configure"
const removeService = "network.ix.delete"
const id = z.string().uuid()
const revision = z.number().int().positive()
const changeArgs = z.object({ change: ixChangeSchema }).strict()
const restoreArgs = z.object({ id, revision, restoreRevision: revision }).strict()
const removeArgs = z.object({ id, revision }).strict()
const sealedRemoval = removeArgs.extend({ actorId: z.string().min(1), digest: z.string().regex(/^[a-f0-9]{64}$/) })
const sealedInput = z.object({
id, change: ixChangeSchema, actorId: z.string().min(1),
before: z.object({ revision: z.number().int().nonnegative(), devices: z.string().regex(/^[a-f0-9]{64}$/) }).strict(),
@@ -32,14 +35,9 @@ async function prepare(change: IxChange, context: ActionContext) {
const serverIds = await ixTarget(change)
if (serverIds.some(id => !context.connection.policy.scope.serverIds.includes(id))) throw new McpError("SERVER_DENIED", "Нет доступа ко всем устройствам сегмента")
const result = await prepareIxChange(change)
const protections = await pool.query("SELECT object_ref FROM mcp_protections WHERE object_ref->>'serverId'=ANY($1::text[]) LIMIT 1001", [serverIds.map(String)])
const objects = [...new Map(result.objects.concat(protections.rows.map(({ object_ref: object }) => ({
kind: object.kind, id: object.id, serverId: object.serverId,
}))).map(object => [JSON.stringify(object), object])).values()]
if (objects.length > 1000) throw new McpError("STATE_UNAVAILABLE", "Превышен лимит защищённых ресурсов плана IX", 409)
return {
target: { scope: "servers" as const, serverIds },
before: result.before, objects, snapshots: [],
before: result.before, objects: await ixPlanObjects(serverIds, result.objects.map(object => object.serverId)), snapshots: [],
steps: [{ kind: "service" as const, service, input: { id: result.id, change, before: result.before, actorId: context.connection.owner_id } }],
mutationCost: result.native.tasks.length + 1,
warnings: [
@@ -49,6 +47,28 @@ async function prepare(change: IxChange, context: ActionContext) {
}
}
async function ixPlanObjects(serverIds: number[], nativeIds = serverIds) {
const protections = await pool.query("SELECT object_ref FROM mcp_protections WHERE object_ref->>'serverId'=ANY($1::text[]) LIMIT 1001", [serverIds.map(String)])
const servers = nativeIds.map(serverId => ({ kind: "server", id: String(serverId), serverId }))
const objects = [...new Map(servers.concat(protections.rows.map(({ object_ref: object }) => ({
kind: object.kind, id: object.id, serverId: object.serverId,
}))).map(object => [JSON.stringify(object), object])).values()]
if (objects.length > 1000) throw new McpError("STATE_UNAVAILABLE", "Превышен лимит защищённых ресурсов плана IX", 409)
return objects
}
async function removalTarget(input: Record<string, unknown>, context: ActionContext) {
const args = removeArgs.parse(input)
const current = await readIxSegment(args.id, context.transactionClient)
if (!current) throw new IxConflict("Сегмент IX не найден", 404)
assertIxRevision(current, args.revision)
const serverIds = await ixTarget({ id: current.id, revision: current.revision, configuration: current.configuration })
if (serverIds.some(id => !context.connection.policy.scope.serverIds.includes(id))) {
throw new McpError("SERVER_DENIED", "Нет доступа ко всем устройствам сегмента")
}
return { scope: "servers" as const, serverIds }
}
async function restore(input: Record<string, unknown>, context: ActionContext) {
const args = restoreArgs.parse(input)
const current = await readIxSegment(args.id, context.transactionClient)
@@ -78,6 +98,35 @@ export function registerIxActions(register: typeof add) {
return reconcileIxChange(args.id, args.change, args.before, authorize)
},
})
registerMcpService(removeService, {
current: input => present(async () => {
const { id, revision } = sealedRemoval.parse(input)
return { revision, digest: (await prepareIxRemoval(id, revision)).digest }
}),
execute: input => present(() => {
const { id, revision, digest, actorId } = sealedRemoval.parse(input)
return removeIxSegment(id, revision, digest, actorId)
}),
verify: async (input, result) => {
const { id, revision } = sealedRemoval.parse(input)
return (result as { configurationVerified?: boolean } | undefined)?.configurationVerified === true && isIxSegmentArchived(id, revision)
},
})
register(removeService, "mm_ix_delete_plan", "План удаления сегмента IX", "network", "mm:network:write", "write", "servers", removeArgs, {
target: (input, context) => present(() => removalTarget(input, context)),
prepare: (input, context) => present(async () => {
const args = removeArgs.parse(input)
const target = await removalTarget(input, context)
const { segment, native, digest } = await prepareIxRemoval(args.id, args.revision)
return {
target, before: { revision: args.revision, digest }, objects: await ixPlanObjects(target.serverIds), snapshots: [],
steps: [{ kind: "service" as const, service: removeService, input: { ...args, digest, actorId: context.connection.owner_id } }],
mutationCost: native.tasks.length + 1, requiresHuman: true, verificationScope: "configuration" as const,
warnings: [`Сегмент ${segment.configuration.name} будет удалён. Операций RouterOS: ${native.tasks.length}. История ревизий сохранится.`,
...native.tasks.slice(0, 12).map(task => `Узел ${task.serverId} · удалить ${task.path}`)],
}
}),
})
register("network.ix.list", "mm_ix_segments_list", "Сегменты обмена трафиком", "network", "mm:network:read", "read", "servers",
z.object({ limit: z.number().int().min(1).max(25).default(10), offset: z.number().int().nonnegative().max(1000000).default(0) }).strict(), {
read: async (input, context) => {
@@ -34,6 +34,10 @@ export function publicRoutingCommunityChanges(evidence: ChangeEvidence) {
/** Service recovery has the same private native bodies as its forward plan. */
export function publicMcpChangeEvidence(operationId: string, evidence: ChangeEvidence) {
if (operationId === "network.ix.delete") {
return { ...evidence, before: { revision: record(evidence.before).revision }, steps: evidence.steps.map(step => step.kind === "service"
? { ...step, input: { id: step.input.id, revision: step.input.revision } } : step) }
}
if (operationId === "network.ix.configure" || operationId === "network.ix.restore") {
return { ...evidence, before: { revision: record(evidence.before).revision }, steps: evidence.steps.map(step => step.kind === "service"
? { ...step, input: { id: step.input.id, change: step.input.change } } : step) }
+97 -7
View File
@@ -1,9 +1,12 @@
import { randomUUID } from "node:crypto"
import type { FastifyPluginAsync } from "fastify"
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 { 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 { 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),
offset: z.coerce.number().int().min(0).max(1000000).default(0),
}).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 => {
app.setErrorHandler((error, request, reply) => {
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 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")
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 => {
const input = paging.parse(request.query)
@@ -25,8 +63,11 @@ const ixRoutes: FastifyPluginAsync = async app => {
})
app.get("/ix/nodes", async () => {
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")
return { items: rows }
const [nodes, peers] = await Promise.all([
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 () => {
const segments = await listIxSegments(100, 0)
@@ -44,10 +85,13 @@ const ixRoutes: FastifyPluginAsync = async app => {
})
app.get("/ix/segments/:id/linux", async request => {
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)
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 => {
const input = ixChangeSchema.parse(request.body)
@@ -65,6 +109,52 @@ const ixRoutes: FastifyPluginAsync = async app => {
assertIxRevision(input.id ? await readIxSegment(id) : null, input.revision)
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
@@ -1,3 +1,4 @@
import { createHash } from "node:crypto"
import { isIP } from "node:net"
import type { IxSite } from "@mmapp/contracts/internet-exchange"
import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js"
@@ -5,6 +6,16 @@ import { IxConflict } from "./internet-exchange-plan.js"
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[]) {
const config = binding.provisionWireguard
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")
}
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)), /изменён вне операции/)
}
})
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 { isIP } from "node:net"
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 { getServerRowById, type ServerRow } from "../modules/servers/repository/servers-repository.js"
import { withApplicationMutationLock, withConfigMutationLock } from "./config-mutation-lock.js"
import { assertVerifiedConfigurationAccess } from "./config-mutation-policy.js"
import { compileIxConfiguration, IxConflict, ixDeviceIds, ixDiscardInterface, ixNamespace } from "./internet-exchange-plan.js"
import { assertIxName, assertIxRevision, assertIxSites, readIxRevision, readIxSegment, writeIxRevision } from "./internet-exchange-store.js"
import { compileIxConfiguration, IxConflict, ixDeviceIds, ixDiscardInterface, ixEgressList, ixNamespace } from "./internet-exchange-plan.js"
import { archiveIxSegment, assertIxName, assertIxRevision, assertIxSites, readIxRevision, readIxSegment, writeIxRevision } from "./internet-exchange-store.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 IpCore = Pick<MikrotikClient, "get" | "put" | "patch" | "delete">
@@ -25,6 +25,8 @@ interface IxNativeChange {
tasks: Task[]
}
const nativePlanDigest = ({ before, tasks }: IxNativeChange) => fingerprint({ before, tasks })
const routerId = /^\*[a-z\d]+$/i
const marker = (path: string, comment: string) => path + "\0" + 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 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 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) {
if (field === "blackhole" && value === "") return "yes"
if (["disabled", "advertise", "blackhole", "multihop"].includes(field)) return value === undefined ? null : isTrue(value) ? "yes" : "no"
if (field === "rule") return value?.trim()
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[] {
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 previousKeys = new Set(previous.map(deviceMarker))
const result: Task[] = []
@@ -108,6 +118,17 @@ export function planIxNative(id: string, desired: IxRouterObject[], previous: Ix
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[]) {
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))) {
@@ -119,17 +140,21 @@ async function readRows(client: IpCore, path: string, props: readonly string[])
}))) as NativeRow[]
}
async function readDevice(server: ServerRow, objects: IxRouterObject[]): Promise<NativeDevice> {
async function readDevice(server: ServerRow, objects: IxRouterObject[], removing = false): Promise<NativeDevice> {
const client = MikrotikClient.fromServer(server)
const fieldsByPath = new Map<string, string[]>([["/interface", columns], ["/interface/bridge/port", [".id", "bridge", "interface"]],
["/ip/vrf", columns], ["/ip/route", columns], ["/ipv6/route", columns]])
if (removing) {
for (const path of ["/ip/address", "/ipv6/address"]) fieldsByPath.set(path, [...columns, "interface"])
}
for (const object of objects) {
fieldsByPath.set(object.path, [...new Set([...(fieldsByPath.get(object.path) ?? columns),
...(filterPath(object.path) ? ["invalid"] : []), ...Object.keys(object.fields)])])
}
if (fieldsByPath.has("/interface/list")) fieldsByPath.get("/interface/list")!.push("include", "exclude")
if (objects.some(object => object.fields["ipsec-policy"])) {
fieldsByPath.set("/interface/gre", [".id", "name", "local-address", "remote-address", "allow-fast-path"])
fieldsByPath.set("/ip/ipsec/policy", [".id", "action", "level", "tunnel", "protocol", "src-address", "dst-address", "disabled", "template"])
fieldsByPath.set("/interface/gre", greColumns)
fieldsByPath.set("/ip/ipsec/policy", ipsecPolicyColumns)
}
const rows: Record<string, NativeRow[]> = {}
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 }
}
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[]) {
for (const site of configuration.sites) {
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 + " уже используется другой маршрутизацией")
}
if (binding.kind === "gre-ipsec") {
const gre = rowsFor(device, "/interface/gre").find(row => row.name === binding.name)
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)
}
verifyGreBinding(binding, rowsFor(device, "/interface/gre"), rowsFor(device, "/ip/ipsec/policy"))
}
}
}
}
async function prepareNative(id: string, configuration: IxConfiguration, previousConfiguration: IxConfiguration | null): Promise<IxNativeChange> {
const objects = compileIxConfiguration(id, configuration)
async function prepareNative(id: string, configuration: IxConfiguration | null, previousConfiguration: IxConfiguration | null): Promise<IxNativeChange> {
const objects = configuration ? compileIxConfiguration(id, configuration) : []
const previous = previousConfiguration ? compileIxConfiguration(id, previousConfiguration) : []
const before: NativeDevice[] = []
for (const serverId of [...new Set([...objects, ...previous].map(object => object.serverId))].sort((a, b) => a - b)) {
const server = await getServerRowById(serverId)
if (!server?.enabled || server.type !== "ix-node") throw new IxConflict("Площадка IX отключена или изменила тип")
before.push(await readDevice(server, [...objects, ...previous].filter(object => object.serverId === serverId)))
before.push(await readDevice(server, [...objects, ...previous].filter(object => object.serverId === serverId), !configuration))
}
validateBindings(configuration, id, before)
if (configuration) validateBindings(configuration, id, before)
for (const device of before) verifyEgressMembers(device, id, previous)
for (const old of previousConfiguration?.sites ?? []) {
const next = configuration.sites.find(site => site.serverId === old.serverId)
const next = configuration?.sites.find(site => site.serverId === old.serverId)
const device = before.find(device => device.serverId === old.serverId)!
if (!configuration) verifyRemovalScope(id, device, previous)
for (const binding of old.interfaces.filter(binding => !next?.interfaces.some(candidate => candidate.name === binding.name))) {
if (!rowsFor(device, "/interface").some(row => row.name === binding.name && isTrue(row.disabled))) {
const iface = rowsFor(device, "/interface").find(row => row.name === binding.name)
if (!configuration && (!iface || binding.provisionWireguard || !rowsFor(device, "/ip/vrf").some(row => row.name === ixNamespace(id)))) continue
if (!isTrue(iface?.disabled)) {
throw new IxConflict("Отключите интерфейс перед исключением из VRF IX: " + binding.name)
}
}
}
return { objects, before, tasks: planIxNative(id, objects, previous, before) }
const remaining = configuration ? previous : previous.filter(object =>
managedRow(before.find(device => device.serverId === object.serverId)!, object))
return { objects, before, tasks: planIxNative(id, objects, remaining, before) }
}
function verifyRemovalScope(id: string, device: NativeDevice, previous: IxRouterObject[]) {
const namespace = ixNamespace(id)
const managed = previous.filter(object => object.serverId === device.serverId)
const known = new Set(managed.map(objectMarker))
const interfaces = new Set(managed.filter(object => ["/interface/wireguard", "/interface/bridge", "/ip/vrf"].includes(object.path))
.map(object => object.fields.name))
for (const [path, rows] of Object.entries(device.rows)) {
if (path === "/interface") continue // RouterOS mirrors WireGuard and bridge objects here.
if (rows.some(row => !isTrue(row.dynamic) && !known.has(marker(path, row.comment ?? "")) &&
(row.comment?.startsWith(namespace + ":") || row["routing-table"] === namespace ||
[row.interface, row.bridge, row["in-interface"], row["out-interface"], ...(row.gateway?.split(/[@%]/) ?? [])].some(value => interfaces.has(value)) ||
[row["in-interface-list"], row["out-interface-list"]].includes(ixEgressList(id)) ||
managed.some(object => object.path === path && object.fields.name && object.fields.name === row.name)))) {
throw new IxConflict("На узле остались объекты, которых нет в применённой ревизии IX")
}
}
}
export async function prepareIxRemoval(id: string, revision: number) {
const segment = await readIxSegment(id)
if (!segment) throw new IxConflict("Сегмент IX не найден", 404)
assertIxRevision(segment, revision)
const applied = segment.appliedRevision === null ? null : await readIxRevision(id, segment.appliedRevision)
const native = await prepareNative(id, null, applied)
return { segment, native, digest: nativePlanDigest(native) }
}
export async function ixTarget(change: IxChange) {
@@ -218,7 +281,7 @@ export async function prepareIxChange(raw: unknown) {
await assertIxSites(change.configuration)
const previous = current?.appliedRevision ? await readIxRevision(id, current.appliedRevision) : null
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 }])
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 }
const applied = current?.appliedRevision ? await readIxRevision(id, current.appliedRevision) : null
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>) {
@@ -243,6 +306,8 @@ export async function reconcileIxChange(id: string, change: IxChange, expected:
if (!server?.enabled) return { matchesDesiredState: false, matchesOriginalState: false }
const objects = desired.filter(object => object.serverId === site.serverId)
const observed = await readDevice(server, objects)
try { verifyEgressMembers(observed, id, objects) }
catch { return { matchesDesiredState: false, matchesOriginalState: false } }
matchesDesiredState &&= objects.every(object => {
const row = managedRow(observed, object)
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("Сначала примените конфигурацию площадки")
const configuration = await readIxRevision(segment.id, segment.appliedRevision)
const site = configuration.sites.find(site => site.serverId === serverId)
const binding = site?.interfaces.find(entry => entry.name === name)
const server = await getServerRowById(serverId)
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 iface = wireguard.find(row => row.name === binding.name && row.comment?.startsWith(ixNamespace(segment.id) + ":wg-"))
const peer = site.neighbors.find(entry => entry.binding === name && entry.type !== "public-feed")
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
.filter(connection => connection !== binding && connection.kind !== "uplink").flatMap(connection => connection.prefixes))
const peer = site.neighbors.find(entry => entry.binding === name)
return {
...clientInfo,
kind: "wireguard",
filename: ixLinuxInterfaceName("ixw", serverId, binding) + ".conf",
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 () => {
await assertVerifiedConfigurationAccess()
await authorize()
const current = await readIxSegment(id)
assertIxRevision(current, expected.revision)
await assertIxName(id, change.configuration.name)
await assertIxSites(change.configuration)
const applied = current?.appliedRevision ? await readIxRevision(id, current.appliedRevision) : null
const native = await prepareNative(id, change.configuration, applied)
if (fingerprint(native.before) !== expected.devices) throw new IxConflict("Конфигурация IX изменилась после предпросмотра")
for (const task of native.tasks) {
await assertVerifiedConfigurationAccess()
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()
if (nativePlanDigest(native) !== expected.devices) throw new IxConflict("Конфигурация IX изменилась после предпросмотра")
await applyNativeTasks(native, authorize)
await authorize()
for (const device of native.before) {
const server = await getServerRowById(device.serverId)
if (!server || fingerprint(server) !== device.source) throw new IxConflict("Источник IX изменился во время проверки")
const desired = native.objects.filter(object => object.serverId === device.serverId)
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 (!desired.every(object => {
const row = managedRow(after, object)
return row && !isTrue(row.invalid) && matches(row, object.fields)
})) throw new IxConflict("Итоговая конфигурация IX не совпала с планом")
}
await assertVerifiedConfigurationAccess()
await authorize()
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 }
}), { waitMs: 30_000 })
@@ -1,7 +1,7 @@
import assert from "node:assert/strict"
import { test } from "node:test"
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 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", () => {
const objects = compileIxConfiguration(id, fixture())
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) }
// 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 ixEgressList(id: string) { return "ix-out-" + ixNamespace(id).slice(3) }
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)
}
@@ -164,6 +165,11 @@ export function compileIxConfiguration(id: string, configuration: IxConfiguratio
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(",") })
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) {
const filter = family === 4 ? "/ip/firewall/filter" : "/ipv6/firewall/filter"
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, "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, "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-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()) {
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 { ixSegmentConfigurationSchema, type IxConfiguration, type IxSegment } from "@mmapp/contracts/internet-exchange"
import { pool } from "../db/index.js"
import { audit } from "../modules/mcp/store.js"
import { IxConflict, ixDeviceIds } from "./internet-exchange-plan.js"
import { admitPartitionWriter } from "./partition-write-transaction.js"
@@ -13,6 +14,7 @@ interface SegmentRow {
}
const columns = "id,revision,applied_revision,configuration,updated_at"
const visible = "(configuration->>'deleted') IS DISTINCT FROM 'true'"
function segment(row: SegmentRow): IxSegment {
return { id: row.id, revision: row.revision, appliedRevision: row.applied_revision,
configuration: ixSegmentConfigurationSchema.parse(row.configuration), updatedAt: row.updated_at.toISOString() }
@@ -21,18 +23,23 @@ function segment(row: SegmentRow): IxSegment {
export async function listIxSegments(limit: number, offset: number, allowedIds?: readonly number[]) {
const { rows } = await pool.query<SegmentRow>(
`SELECT ${columns} FROM ix_segments s
WHERE $1::bigint[] IS NULL OR NOT EXISTS (
WHERE ${visible} AND ($1::bigint[] IS NULL OR NOT EXISTS (
SELECT 1 FROM ix_segment_devices d WHERE d.segment_id=s.id AND NOT (d.server_id=ANY($1::bigint[]))
)
))
ORDER BY name,id LIMIT $2 OFFSET $3`, [allowedIds ?? null, limit, offset])
return rows.map(segment)
}
export async function readIxSegment(id: string, sql: Pick<PoolClient, "query"> = pool) {
const { rows: [row] } = await sql.query<SegmentRow>(`SELECT ${columns} FROM ix_segments WHERE id=$1`, [id])
const { rows: [row] } = await sql.query<SegmentRow>(`SELECT ${columns} FROM ix_segments WHERE id=$1 AND ${visible}`, [id])
return row ? segment(row) : null
}
export async function isIxSegmentArchived(id: string, revision: number) {
const { rowCount } = await pool.query("SELECT 1 FROM ix_segments WHERE id=$1 AND revision=$2 AND configuration->>'deleted'='true'", [id, revision])
return rowCount === 1
}
export async function readIxRevision(id: string, revision: number) {
const { rows: [row] } = await pool.query("SELECT configuration FROM ix_segment_revisions WHERE segment_id=$1 AND revision=$2", [id, revision])
if (!row) throw new IxConflict("Ревизия IX не найдена", 404)
@@ -70,7 +77,7 @@ export async function writeIxRevision(id: string, expected: number, configuratio
[id, configuration.name, revision, JSON.stringify(configuration), applied ? revision : null])
: await client.query<SegmentRow>(`UPDATE ix_segments SET name=$2,revision=$3,configuration=$4::jsonb,
applied_revision=CASE WHEN $5::boolean THEN $3 ELSE applied_revision END,updated_at=now()
WHERE id=$1 AND revision=$6 RETURNING ${columns}`,
WHERE id=$1 AND revision=$6 AND ${visible} RETURNING ${columns}`,
[id, configuration.name, revision, JSON.stringify(configuration), applied, expected])
if (!row) throw new IxConflict("Имя IX уже занято или ревизия сменилась")
// Keep references to the applied topology while it can still hold live resources.
@@ -90,3 +97,24 @@ export async function writeIxRevision(id: string, expected: number, configuratio
throw error
} finally { client.release() }
}
export async function archiveIxSegment(id: string, revision: number, actorId: string) {
const client = await pool.connect()
try {
await client.query("BEGIN")
await admitPartitionWriter(client)
// Keep the revision journal and free the name and device references using the existing writer grants.
const { rowCount } = await client.query(`UPDATE ix_segments
SET name='deleted:' || id::text, configuration=configuration || '{"deleted":true}'::jsonb, updated_at=now()
WHERE id=$1 AND revision=$2 AND ${visible}`, [id, revision])
if (rowCount !== 1) throw new IxConflict("Ревизия IX изменилась. Обновите данные и подготовьте новый план")
await client.query("DELETE FROM ix_segment_devices WHERE segment_id=$1", [id])
await audit(client, actorId, "ix.segment.deleted", null, { segmentId: id, revision })
await client.query("COMMIT")
} catch (error) {
await client.query("ROLLBACK").catch(() => {})
throw error
} finally {
client.release()
}
}
+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 и ввод в эксплуатацию
@@ -106,6 +106,32 @@ export interface IxRouterObject {
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 {
serverId: number
observedAt: string
+171
View File
@@ -0,0 +1,171 @@
import { expect, test } from "@playwright/test"
import { ixChangeSchema, ixSegmentConfigurationSchema } from "@mmapp/contracts/internet-exchange"
const id = "fa58fa40-4bcb-4616-9316-cb69463b3150"
const observedAt = "2026-11-20T00:00:00Z"
const nodes = [
{ id: 1, name: "ix-node-01", site: "TEST-1", country: "DE", enabled: true },
{ id: 2, name: "ix-node-02", site: "TEST-2", country: "FI", enabled: true },
]
test("IX: редактирование и применение сохранённой ревизии из WebUI без MCP", async ({ page }, testInfo) => {
const configuration = ixSegmentConfigurationSchema.parse({ name: "ix-central", sites: [
{ serverId: 1, autonomousSystem: 64512, routerId: "192.0.2.10", interfaces: [{ name: "wg-member", kind: "wireguard" }] },
{ serverId: 2, autonomousSystem: 64512, routerId: "192.0.2.11" },
] })
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("**/api/**", async route => {
const request = route.request()
const path = new URL(request.url()).pathname
const json = (body: unknown) => route.fulfill({ json: body })
if (path === "/api/auth/config") return json({ required: false })
if (path === "/api/ix/nodes") return json({ items: nodes, peers: nodes })
if (path.startsWith("/api/mcp/")) {
mcpCalls.push(path)
return route.fulfill({ status: 503, json: { error: "MCP недоступен" } })
}
if (path === "/api/ix/segments" && request.method() === "POST") {
const change = ixChangeSchema.parse(request.postDataJSON())
segment = { ...segment, configuration: change.configuration, revision: change.revision + 1 }
return json({ 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: [{
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 }],
}] })
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([])
return json({})
})
await page.goto("/ix")
const row = page.getByRole("button", { name: "ix-central", exact: true })
await expect(row).toBeVisible()
const search = page.getByRole("searchbox", { name: "Поиск сегментов" })
await search.fill("no-match")
await expect(page.getByText("Сегменты не найдены")).toBeVisible()
await search.clear()
await expect(row).toBeVisible()
await page.screenshot({ path: testInfo.outputPath("ix-list-desktop.png"), animations: "disabled" })
await row.click()
await expect(page.getByRole("heading", { name: "ix-central" })).toBeFocused()
await page.screenshot({ path: testInfo.outputPath("ix-detail-desktop.png"), animations: "disabled" })
await page.setViewportSize({ width: 390, height: 760 })
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: "Сохранить черновик" })
await save.scrollIntoViewIfNeeded()
await expect(save).toBeInViewport()
await save.click()
await expect(page.getByText("Черновик сохранён")).toBeVisible()
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])
await page.getByRole("tab", { name: "Маршруты и BGP" }).click()
await expect(page.getByText("2001:db8:120::/48")).toBeVisible()
await expect(page.getByText("BGP 1 из 1")).toBeVisible()
await page.getByRole("tab", { name: "План изменений" }).click()
await page.getByRole("button", { name: "Построить предпросмотр" }).click()
await expect(page.getByText("Ревизия 2 · операций RouterOS: 1")).toBeVisible()
await expect(page.getByText("/ipv6/route", { exact: true })).toBeVisible()
await page.getByRole("button", { name: "Применить план" }).click()
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)
})
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)
})
+23
View File
@@ -45,6 +45,29 @@ async function edit(page: Page, id = 1) {
await page.getByRole("menuitem", { name: "Редактировать", exact: true }).click()
}
test("типы узлов в узкой форме выбираются кнопкой и с клавиатуры", async ({ page }, testInfo) => {
await setup(page)
await page.setViewportSize({ width: 390, height: 844 })
await page.getByRole("button", { name: "Добавить сервер", exact: true }).click()
const types = page.getByRole("group", { name: "Тип узла" })
const exit = types.getByRole("button", { name: "Exit Node" })
const ix = types.getByRole("button", { name: "IX Node" })
await expect(exit).toHaveAttribute("aria-pressed", "true")
await expect(types).toBeInViewport({ ratio: 1 })
const buttonTops = await types.getByRole("button").evaluateAll(buttons => buttons.map(button => button.getBoundingClientRect().top))
expect(buttonTops).toHaveLength(4)
expect(new Set(buttonTops).size).toBe(1)
await ix.click()
await expect(ix).toHaveAttribute("aria-pressed", "true")
await expect(types.getByRole("button", { pressed: true })).toHaveCount(1)
await expect(page.getByPlaceholder("AS65001")).toBeVisible()
await page.screenshot({ path: testInfo.outputPath("node-type-mobile.png"), animations: "disabled" })
await page.keyboard.press("Shift+Tab")
await expect(exit).toBeFocused()
await page.keyboard.press("Space")
await expect(exit).toHaveAttribute("aria-pressed", "true")
})
test("ссылка на сервер: выбор, опрос одного устройства, сброс и возврат", async ({ page }) => {
const calls: string[] = []
await setup(page, async (route, path) => {