Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
be1cb6381a |
No files matched your search
@@ -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>
|
||||
}
|
||||
@@ -13,6 +13,7 @@ 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]
|
||||
@@ -47,8 +48,8 @@ export function SegmentGrid({ rows, nodes, loading, open, empty }: {
|
||||
return <DataGridShell table={table} recordCount={rows.length} isLoading={loading} loadingMode="skeleton" emptyMessage={empty} />
|
||||
}
|
||||
|
||||
export function ConfigurationFields({ configuration, nodes, readOnly, change }: {
|
||||
configuration: IxConfiguration; nodes: IxNode[]; readOnly: boolean; change: (value: IxConfiguration) => void
|
||||
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) })
|
||||
@@ -109,15 +110,9 @@ export function ConfigurationFields({ configuration, nodes, readOnly, change }:
|
||||
onChange={event => updateSite(index, { routerId: event.target.value })} />
|
||||
</Field>
|
||||
</div>
|
||||
<dl className="grid grid-cols-2 gap-3 border-t pt-3 text-sm sm:grid-cols-4">
|
||||
{[
|
||||
["Интерфейсы", site.interfaces.length], ["Группы шлюзов", site.groups.length],
|
||||
["Маршруты", site.routes.length], ["BGP-соседи", site.neighbors.length],
|
||||
].map(([label, count]) => <div className="grid gap-0.5" key={label}>
|
||||
<dt className="text-xs text-muted-foreground">{label}</dt>
|
||||
<dd className="font-medium tabular-nums">{count}</dd>
|
||||
</div>)}
|
||||
</dl>
|
||||
<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>
|
||||
})}
|
||||
|
||||
+152
-111
@@ -3,62 +3,50 @@
|
||||
import { useEffect, useRef, useState } from "react"
|
||||
import Link from "next/link"
|
||||
import { ArrowLeftIcon, CircleAlertIcon, NetworkIcon, PlusIcon, RefreshCwIcon } from "lucide-react"
|
||||
import { ixSegmentConfigurationSchema, type IxChange, type IxConfiguration, type IxRouterObject, type IxSegment, type IxSiteObservation } from "@mmapp/contracts/internet-exchange"
|
||||
import { ixSegmentConfigurationSchema, type IxChange, type IxConfiguration, type IxLinuxAccess, type IxLinuxBinding, type IxWebPlan, type IxSegment, type IxSiteObservation } from "@mmapp/contracts/internet-exchange"
|
||||
import { Alert, AlertDescription, AlertTitle } from "@/components/reui/alert"
|
||||
import { Badge } from "@/components/reui/badge"
|
||||
import { Frame, FrameDescription, FrameHeader, FramePanel, FrameTitle } from "@/components/reui/frame"
|
||||
import { EmptyState } from "@/components/empty-state"
|
||||
import { PageHeader } from "@/components/page-header"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Field, FieldLabel } from "@/components/ui/field"
|
||||
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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||
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, RouteGrid, SegmentGrid, SegmentStatus, type IxNode } from "./ix-view"
|
||||
import { ConfigurationFields, newSite, nodeLabel, RouteGrid, SegmentGrid, SegmentStatus, type IxNode } from "./ix-view"
|
||||
|
||||
type Connection = { id: string; name: string }
|
||||
type Plan = { planId: string; state: string }
|
||||
type Tab = "configuration" | "routes" | "changes"
|
||||
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) })
|
||||
|
||||
const planStates: Record<string, string> = {
|
||||
draft: "Черновик плана", "awaiting-approval": "Ждёт подтверждения", approved: "Подтверждён",
|
||||
pending: "В очереди", running: "Выполняется", completed: "Завершён", applied: "Применён",
|
||||
rejected: "Отклонён", expired: "Истёк", failed: "Ошибка", partial: "Выполнен частично", unknown: "Нужна сверка",
|
||||
}
|
||||
const actionLabels = { create: "Создать", update: "Обновить", delete: "Удалить" } as const
|
||||
|
||||
export default function IxPage() {
|
||||
const { backendUrl, mode, prefsHydrated } = useDataSource()
|
||||
const [segments, setSegments] = useState<IxSegment[]>([])
|
||||
const [nodes, setNodes] = useState<IxNode[]>([])
|
||||
const [connections, setConnections] = useState<Connection[]>([])
|
||||
const [connectionId, setConnectionId] = useState("")
|
||||
const [connectionError, setConnectionError] = useState("")
|
||||
const [peers, setPeers] = useState<IxNode[]>([])
|
||||
const [selected, setSelected] = useState<IxSegment | null>(null)
|
||||
const [draft, setDraft] = useState<IxConfiguration | null>(null)
|
||||
const [advanced, setAdvanced] = useState<string | null>(null)
|
||||
const [filter, setFilter] = useState("")
|
||||
const [observations, setObservations] = useState<IxSiteObservation[] | null>(null)
|
||||
const [preview, setPreview] = useState<IxRouterObject[] | null>(null)
|
||||
const [linux, setLinux] = useState("")
|
||||
const [plan, setPlan] = useState<Plan | null>(null)
|
||||
const [linuxBindings, setLinuxBindings] = useState<IxLinuxBinding[]>([])
|
||||
const [linux, setLinux] = useState<(IxLinuxAccess & IxLinuxBinding) | null>(null)
|
||||
const [plan, setPlan] = 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
|
||||
@@ -66,34 +54,15 @@ export default function IxPage() {
|
||||
async function load(signal?: AbortSignal) {
|
||||
if (signal?.aborted) return
|
||||
setWrite(can("mm:network:write"))
|
||||
setApprove(can("mm:mcp:approve"))
|
||||
const [segmentsResult, nodesResult] = await Promise.all([
|
||||
requestJson<{ items: IxSegment[] }>(backendUrl, "/api/ix/segments?limit=100", { signal }),
|
||||
requestJson<{ items: IxNode[] }>(backendUrl, "/api/ix/nodes", { signal }),
|
||||
requestJson<{ items: IxNode[]; peers?: IxNode[] }>(backendUrl, "/api/ix/nodes", { signal }),
|
||||
])
|
||||
if (signal?.aborted) return
|
||||
setSegments(segmentsResult.items)
|
||||
setNodes(nodesResult.items)
|
||||
|
||||
setConnectionError("")
|
||||
if (!can("mm:mcp:read")) {
|
||||
setConnections([])
|
||||
setConnectionId("")
|
||||
return
|
||||
}
|
||||
try {
|
||||
const result = await mcpApi(backendUrl).connections(signal)
|
||||
if (signal?.aborted) return
|
||||
const available = result.connections.filter(connection => connection.policy.status === "active" &&
|
||||
connection.policy.scope.operationIds.includes("network.ix.configure"))
|
||||
setConnections(available.map(connection => ({ id: connection.id, name: connection.name })))
|
||||
setConnectionId(current => available.some(connection => connection.id === current) ? current : available.length === 1 ? available[0].id : "")
|
||||
} catch (error) {
|
||||
if (signal?.aborted) return
|
||||
setConnections([])
|
||||
setConnectionId("")
|
||||
setConnectionError(describe(error))
|
||||
}
|
||||
setPeers(nodesResult.peers ?? nodesResult.items)
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
@@ -123,10 +92,12 @@ export default function IxPage() {
|
||||
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)
|
||||
setPreview(null)
|
||||
setNotice("")
|
||||
}
|
||||
|
||||
@@ -136,7 +107,8 @@ export default function IxPage() {
|
||||
setDraft(segment?.configuration ?? { name: "", sites: [{ ...newSite(), serverId: enabledNodes.length === 1 ? enabledNodes[0].id : 0 }] })
|
||||
setAdvanced(null)
|
||||
setObservations(null)
|
||||
setLinux("")
|
||||
setLinux(null)
|
||||
setLinuxBindings([])
|
||||
setTab("configuration")
|
||||
setError("")
|
||||
invalidateReview()
|
||||
@@ -171,25 +143,65 @@ export default function IxPage() {
|
||||
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 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."
|
||||
const linuxBindings = selected?.appliedRevision ? selected.configuration.sites.flatMap(site =>
|
||||
site.interfaces.filter(binding => binding.provisionWireguard?.hubEndpoint).map(binding => ({ site, binding }))) : []
|
||||
|
||||
return <>
|
||||
<PageHeader crumbs={inDetail ? [{ label: "Сегменты IX" }, { label: selected?.configuration.name ?? "Новый сегмент" }] : [{ label: title }]} />
|
||||
@@ -237,22 +249,23 @@ export default function IxPage() {
|
||||
<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} readOnly={!write || busy}
|
||||
{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={!write || busy} rows={14}
|
||||
<Textarea aria-label="Конфигурация JSON" spellCheck={false} readOnly={!live || !write || busy} rows={14}
|
||||
className="font-mono" value={advanced} onChange={event => { setAdvanced(event.target.value); invalidateReview() }} />
|
||||
</FramePanel>
|
||||
</Frame>}
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{write && <Button type="button" size="sm" disabled={busy} onClick={() => void perform(save)}>Сохранить черновик</Button>}
|
||||
{write && <Button type="button" size="sm" disabled={busy || !live} onClick={() => void perform(save)}>Сохранить черновик</Button>}
|
||||
{advanced === null ? <Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => setAdvanced(json(draft))}>
|
||||
{write ? "Редактировать JSON" : "Показать JSON"}
|
||||
</Button> : <Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => void perform(async () => {
|
||||
@@ -269,80 +282,108 @@ export default function IxPage() {
|
||||
<Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => void perform(observe)}>
|
||||
<RefreshCwIcon aria-hidden />Обновить состояние
|
||||
</Button>
|
||||
{linuxBindings.map(({ site, binding }) => <Button key={site.serverId + ":" + binding.name}
|
||||
type="button" size="sm" variant="outline" disabled={busy} onClick={() => void perform(async () => {
|
||||
const query = new URLSearchParams({ serverId: String(site.serverId), interfaceName: binding.name })
|
||||
const result = await requestJson<{ template: string }>(backendUrl, `/api/ix/segments/${selected.id}/linux?${query}`)
|
||||
setLinux(result.template)
|
||||
})}>Linux · {binding.name}</Button>)}
|
||||
</div>
|
||||
{linux && <Frame spacing="sm"><FrameHeader><FrameTitle>Конфигурация Linux</FrameTitle></FrameHeader>
|
||||
<FramePanel><pre className="overflow-x-auto text-xs">{linux}</pre></FramePanel></Frame>}
|
||||
{busy && observations === null && <Skeleton className="h-28 w-full" role="status" aria-label="Загрузка маршрутов" />}
|
||||
{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>Предпросмотр</FrameTitle>
|
||||
<FrameDescription>Объекты RouterOS, которые создаёт текущая конфигурация.</FrameDescription>
|
||||
<FrameTitle>Изменения RouterOS</FrameTitle>
|
||||
<FrameDescription>Предпросмотр сравнивает сохранённую ревизию с текущим состоянием узлов.</FrameDescription>
|
||||
</FrameHeader>
|
||||
<FramePanel className="grid min-w-0 gap-3">
|
||||
<Button type="button" size="sm" variant="outline" className="w-fit" disabled={busy} onClick={() => void perform(async () => {
|
||||
const result = await requestJson<{ objects: IxRouterObject[] }>(backendUrl, "/api/ix/preview", post(change()))
|
||||
setPreview(result.objects)
|
||||
})}>Построить предпросмотр</Button>
|
||||
{preview && <details className="min-w-0 border-t pt-3">
|
||||
<summary className="cursor-pointer text-sm font-medium">Объекты RouterOS · {preview.length}</summary>
|
||||
<pre className="mt-2 overflow-x-auto text-xs">{json(preview)}</pre>
|
||||
</details>}
|
||||
</FramePanel>
|
||||
</Frame>
|
||||
|
||||
{write && <Frame spacing="sm">
|
||||
<FrameHeader>
|
||||
<FrameTitle>Применение через MCP</FrameTitle>
|
||||
<FrameDescription>План, подтверждение и применение к площадкам сегмента.</FrameDescription>
|
||||
</FrameHeader>
|
||||
<FramePanel className="grid min-w-0 gap-4">
|
||||
{connectionError && <p role="status" className="wrap-anywhere text-sm text-muted-foreground">{connectionError}</p>}
|
||||
<div className="flex flex-wrap items-end gap-3">
|
||||
<Field className="w-full min-w-0 sm:w-64">
|
||||
<FieldLabel htmlFor="ix-connection">Подключение MCP</FieldLabel>
|
||||
<Select value={connectionId || null} items={connections.map(connection => ({ value: connection.id, label: connection.name }))}
|
||||
disabled={busy || connections.length === 0} onValueChange={value => { setConnectionId(value ?? ""); setPlan(null) }}>
|
||||
<SelectTrigger id="ix-connection" className="w-full"><SelectValue placeholder={connections.length ? "Выберите подключение" : "Нет доступных подключений"} /></SelectTrigger>
|
||||
<SelectContent>{connections.map(connection => <SelectItem key={connection.id} value={connection.id}>{connection.name}</SelectItem>)}</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
<Button type="button" size="sm" disabled={!connectionId || busy} onClick={() => void perform(async () => {
|
||||
setPlan(await requestJson<Plan>(backendUrl, "/api/mcp/ix/plan", post({ connectionId, change: change() })))
|
||||
})}>Подготовить план MCP</Button>
|
||||
{connections.length === 0 && <Button render={<Link href="/mcp?tab=connections" />} nativeButton={false} variant="outline" size="sm">Открыть подключения</Button>}
|
||||
</div>
|
||||
{plan && <div className="flex flex-wrap items-center gap-2 border-t pt-3">
|
||||
<Badge variant={plan.state === "awaiting-approval" ? "warning-light" : plan.state === "applied" ? "success-light" : "info-light"}>{planStates[plan.state] ?? plan.state}</Badge>
|
||||
<Button render={<Link href="/mcp?tab=plans" />} nativeButton={false} size="sm" variant="link">Планы и операции</Button>
|
||||
{plan.state === "awaiting-approval" && approve && <Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => void perform(async () => {
|
||||
await mcpApi(backendUrl).decision(plan.planId, true)
|
||||
setPlan({ ...plan, state: "approved" })
|
||||
})}>Подтвердить</Button>}
|
||||
{["draft", "approved"].includes(plan.state) && <Button type="button" size="sm" disabled={busy} onClick={() => void perform(async () => {
|
||||
const name = change().configuration.name
|
||||
const result = await mcpApi(backendUrl).apply(plan.planId)
|
||||
setPlan({ ...plan, state: result.state })
|
||||
if (result.state === "applied") {
|
||||
const refreshed = await requestJson<{ items: IxSegment[] }>(backendUrl, "/api/ix/segments?limit=100")
|
||||
setSegments(refreshed.items)
|
||||
const applied = refreshed.items.find(segment => segment.id === selected?.id || segment.configuration.name === name)
|
||||
if (applied) setSelected(applied)
|
||||
}
|
||||
})}>Применить план</Button>}
|
||||
{!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>}
|
||||
{plan.changes.length > 0 && <ul className="max-h-80 min-w-0 divide-y overflow-auto rounded-md border">
|
||||
{plan.changes.map((operation, index) => <li key={index} className="min-w-0 p-2.5 text-sm">
|
||||
<details className="min-w-0">
|
||||
<summary className="cursor-pointer wrap-anywhere">{actionLabels[operation.action]} · {nodeLabel(nodes, operation.serverId)} · <code>{operation.path}</code>
|
||||
{operation.target && <> · <code>{operation.target}</code></>}
|
||||
</summary>
|
||||
<dl className="grid min-w-0 grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-1 py-2 text-xs">
|
||||
{operation.placeBefore && <><dt className="text-muted-foreground">Перед объектом</dt><dd className="font-mono">{operation.placeBefore}</dd></>}
|
||||
{Object.entries(operation.fields).map(([key, value]) => <div key={key} className="contents">
|
||||
<dt className="max-w-32 wrap-anywhere text-muted-foreground">{key}</dt>
|
||||
<dd className="wrap-anywhere font-mono">{value}</dd>
|
||||
</div>)}
|
||||
</dl>
|
||||
</details>
|
||||
</li>)}
|
||||
</ul>}
|
||||
<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>}
|
||||
</Frame>
|
||||
</TabsContent>
|
||||
</Tabs>}
|
||||
</div>
|
||||
|
||||
@@ -1604,6 +1604,20 @@
|
||||
"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",
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
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 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
|
||||
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 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
|
||||
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) {
|
||||
const reply = await fetch(origin + "/api/ix/segments" + path, { method: "POST",
|
||||
headers: { "content-type": "application/json", ...(jwt ? { authorization: "Bearer " + jwt } : {}) },
|
||||
body: JSON.stringify(payload), signal: AbortSignal.timeout(30_000) })
|
||||
const data = 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)
|
||||
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 }))
|
||||
} finally {
|
||||
await app?.close()
|
||||
await new Promise<void>(resolve => router.close(() => resolve()))
|
||||
await pool.end()
|
||||
await pg.stop()
|
||||
}
|
||||
@@ -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, readIxLinuxClient } 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,33 @@ 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 })
|
||||
}
|
||||
|
||||
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.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 +48,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 +70,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 +94,35 @@ 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: prepared.native.tasks.map(task => ({
|
||||
serverId: task.serverId, path: task.path,
|
||||
action: task.fields ? task.rosId ? "update" : "create" : "delete",
|
||||
target: task.before?.name ?? task.before?.comment ?? task.fields?.name ?? task.fields?.comment ?? task.rosId,
|
||||
placeBefore: task.placeBefore,
|
||||
fields: task.fields ?? Object.fromEntries(Object.entries(task.before ?? {}).filter(([key]) => ["name", "comment", "dst-address", "chain"].includes(key))),
|
||||
})),
|
||||
}
|
||||
})
|
||||
|
||||
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 }
|
||||
})
|
||||
}
|
||||
|
||||
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 { compileIxConfiguration, IxConflict, ixDeviceIds, ixDiscardInterface, ixEgressList, ixNamespace } from "./internet-exchange-plan.js"
|
||||
import { 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))) {
|
||||
@@ -127,9 +148,10 @@ async function readDevice(server: ServerRow, objects: IxRouterObject[]): Promise
|
||||
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 +162,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,17 +202,7 @@ 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"))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -191,6 +218,7 @@ async function prepareNative(id: string, configuration: IxConfiguration, previou
|
||||
before.push(await readDevice(server, [...objects, ...previous].filter(object => object.serverId === serverId)))
|
||||
}
|
||||
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 device = before.find(device => device.serverId === old.serverId)!
|
||||
@@ -218,7 +246,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 +256,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 +271,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,35 +320,69 @@ 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) {
|
||||
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 изменилась после предпросмотра")
|
||||
if (nativePlanDigest(native) !== expected.devices) throw new IxConflict("Конфигурация IX изменилась после предпросмотра")
|
||||
for (const task of native.tasks) {
|
||||
await assertVerifiedConfigurationAccess()
|
||||
await authorize()
|
||||
const server = await getServerRowById(task.serverId)
|
||||
if (!server?.enabled || fingerprint(server) !== native.before.find(device => device.serverId === task.serverId)?.source) {
|
||||
throw new IxConflict("Изменился источник конфигурации IX")
|
||||
@@ -333,13 +397,13 @@ export async function applyIxChange(id: string, change: IxChange, expected: { re
|
||||
throw new IxConflict("Объект IX был создан после подготовки плана")
|
||||
}
|
||||
if (!task.fields) {
|
||||
await client.delete(nativePath)
|
||||
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)
|
||||
: await client.put<NativeRow>(nativePath, { ...task.fields, ...(task.placeBefore ? { "place-before": task.placeBefore } : {}) })
|
||||
? 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)
|
||||
@@ -353,19 +417,20 @@ export async function applyIxChange(id: string, change: IxChange, expected: { re
|
||||
}
|
||||
}
|
||||
}
|
||||
await assertVerifiedConfigurationAccess()
|
||||
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 })
|
||||
|
||||
+6
-1
@@ -53,7 +53,12 @@
|
||||
}
|
||||
```
|
||||
|
||||
Для создания 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 по командам из вкладки. При использовании статической маршрутизации назначьте согласованный адрес внутри туннеля и добавьте нужные маршруты.
|
||||
|
||||
## 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
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { expect, test } from "@playwright/test"
|
||||
import { ixChangeSchema, ixSegmentConfigurationSchema } from "@mmapp/contracts/internet-exchange"
|
||||
import { mcpLimitsSchema } from "@mmapp/contracts/mcp"
|
||||
|
||||
const id = "fa58fa40-4bcb-4616-9316-cb69463b3150"
|
||||
const observedAt = "2026-11-20T00:00:00Z"
|
||||
@@ -9,39 +8,59 @@ const nodes = [
|
||||
{ id: 2, name: "ix-node-02", site: "TEST-2", country: "FI", enabled: true },
|
||||
]
|
||||
|
||||
test("IX: карточка доступна на узком экране, сохранение удерживает настройки маршрутизации", async ({ page }, testInfo) => {
|
||||
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 })
|
||||
if (path === "/api/mcp/connections") return json({ connections: [{
|
||||
id, name: "IX Lab", ownerId: "test", createdAt: observedAt, updatedAt: observedAt, lastUsedAt: null, generationValid: true,
|
||||
policy: { id, version: 1, status: "active", mode: "approval", expiresAt: "2099-01-01T00:00:00Z",
|
||||
permissions: ["mm:network:write"], scope: { serverIds: [1, 2], operationIds: ["network.ix.configure"], allowGlobal: false },
|
||||
dangerousPolicy: "approval", autonomousDangerousOperationIds: [], limits: mcpLimitsSchema.parse({}) },
|
||||
}] })
|
||||
if (path === "/api/mcp/ix/plan") return json({ planId: id, state: "awaiting-approval" })
|
||||
if (path === `/api/mcp/plans/${id}/decision`) return json({ ok: true })
|
||||
if (path === `/api/mcp/plans/${id}/apply`) return json({ id, state: "pending" })
|
||||
if (path === "/api/ix/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/preview") return json({ objects: [] })
|
||||
if (path === `/api/ix/segments/${id}/plan`) {
|
||||
expect(request.postDataJSON()).toEqual({ revision: segment.revision })
|
||||
return json({ revision: segment.revision, digest, changes: [
|
||||
{ serverId: 1, action: "create", path: "/ipv6/route", fields: { "dst-address": "2001:db8:120::/48" } },
|
||||
] })
|
||||
}
|
||||
if (path === `/api/ix/segments/${id}/apply`) {
|
||||
expect(request.postDataJSON()).toEqual({ revision: segment.revision, digest })
|
||||
applies++
|
||||
segment = { ...segment, revision: segment.revision + 1, appliedRevision: segment.revision + 1 }
|
||||
return json({ segment })
|
||||
}
|
||||
if (path === "/api/servers") return json([])
|
||||
return json({})
|
||||
})
|
||||
@@ -61,12 +80,28 @@ test("IX: карточка доступна на узком экране, сох
|
||||
|
||||
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]).toEqual({ ...configuration.sites[0], autonomousSystem: 64513 })
|
||||
expect(segment.configuration.sites[0]).toMatchObject({
|
||||
autonomousSystem: 64513,
|
||||
interfaces: [{ name: "wg-member", prefixes: ["2001:db8:120::/48"] }],
|
||||
groups: [{ id: "member", primary: { interface: "wg-member", nextHop: "2001:db8::2" } }],
|
||||
routes: [{ prefix: "2001:db8:120::/48", group: "member" }],
|
||||
})
|
||||
expect(segment.configuration.sites[1]).toEqual(configuration.sites[1])
|
||||
|
||||
await page.getByRole("tab", { name: "Маршруты и BGP" }).click()
|
||||
@@ -74,12 +109,24 @@ test("IX: карточка доступна на узком экране, сох
|
||||
await expect(page.getByText("BGP 1 из 1")).toBeVisible()
|
||||
await page.getByRole("tab", { name: "План изменений" }).click()
|
||||
await page.getByRole("button", { name: "Построить предпросмотр" }).click()
|
||||
await expect(page.getByText("Объекты RouterOS · 0")).toBeVisible()
|
||||
await expect(page.getByText("IX Lab", { exact: true })).toBeVisible()
|
||||
await page.getByRole("button", { name: "Подготовить план MCP" }).click()
|
||||
await expect(page.getByText("Ждёт подтверждения")).toBeVisible()
|
||||
await page.getByRole("button", { name: "Подтвердить", exact: true }).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.getByText("В очереди", { exact: true })).toBeVisible()
|
||||
await expect(page.getByRole("alertdialog")).toBeVisible()
|
||||
expect(applies).toBe(0)
|
||||
await page.getByRole("button", { name: "Применить", exact: true }).click()
|
||||
await expect(page.getByText("Конфигурация IX применена")).toBeVisible()
|
||||
expect(segment.appliedRevision).toBe(3)
|
||||
expect(applies).toBe(1)
|
||||
await page.getByRole("tab", { name: "Linux-клиенты" }).click()
|
||||
await page.getByRole("button", { name: "Получить конфиг wg-linux" }).click()
|
||||
await expect(page.getByText(/Table = off/)).toBeVisible()
|
||||
const download = page.waitForEvent("download")
|
||||
await page.getByRole("link", { name: "Скачать wg-linux.conf" }).click()
|
||||
expect((await download).suggestedFilename()).toBe("wg-linux.conf")
|
||||
await page.getByRole("button", { name: "Получить конфиг gre-linux" }).click()
|
||||
await expect(page.getByText("mode = transport", { exact: true })).toBeVisible()
|
||||
await expect(page.getByText("swanctl --initiate --child gre-linux", { exact: true })).toBeVisible()
|
||||
expect(mcpCalls).toEqual([])
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(390)
|
||||
})
|
||||
Reference in new issue
Block a user