feat(ix): добавить управление группами туннелей для резервирования и балансировки
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Failing after 4m0s
Docker images / backend-image (push) Skipped
Docker images / frontend-image (push) Successful in 3m55s
Docker images / updater-image (push) Successful in 2m11s
Docker images / netflow-agent-image (push) Successful in 37s
Docker images / publish-release (push) Skipped
Docker images / notify-webhook (push) Skipped

This commit is contained in:
Denozordec committed 2026-11-24 00:29:50 +07:00
1 parent 676be13251
commit 350ae34862
17 files changed
+790 -54

No files matched your search

+154
View File
@@ -0,0 +1,154 @@
"use client"
import { useEffect, useState } from "react"
import type { IxBondBundle, IxBondCandidate, IxBondCatalog, IxBondEdit, IxBondMode, IxSavedBond } from "@mmapp/contracts/internet-exchange"
import { Frame, FrameHeader, FramePanel, FrameTitle } from "@/components/reui/frame"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Field, FieldLabel } from "@/components/ui/field"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Sheet, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle } from "@/components/ui/sheet"
import { requestJson } from "@/shared/api/http-client"
import { nodeLabel, type IxNode } from "./ix-view"
const modes = [
{ value: "failover", label: "Основной и резервные" },
{ value: "equal", label: "Параллельно, поровну" },
{ value: "weighted", label: "Параллельно, по весам" },
] as const
type Member = IxBondEdit["members"][number]
const memberKey = (m: Pick<Member, "segmentId" | "interfaceName" | "serverId">) => [m.segmentId, m.serverId, m.interfaceName].join("/")
const modeLabel = (mode: IxBondMode) => modes.find(item => item.value === mode)?.label
export function IxClientBonds({ segmentId, backendUrl, nodes, readOnly, download }: {
segmentId: string; backendUrl: string; nodes: IxNode[]; readOnly: boolean
download: (filename: string, text: string) => void
}) {
const [catalog, setCatalog] = useState<IxBondCatalog>({ groups: [], candidates: [] })
const [reload, setReload] = useState(0)
const [draft, setDraft] = useState<IxBondEdit | null>(null)
const [direct, setDirect] = useState("")
const [error, setError] = useState("")
const [busy, setBusy] = useState(false)
const [remove, setRemove] = useState(false)
useEffect(() => {
const ctl = new AbortController()
void requestJson<IxBondCatalog>(backendUrl, "/api/ix/linux-bonds", { signal: ctl.signal })
.then(result => { if (!ctl.signal.aborted) setCatalog(result) })
.catch(e => { if (!ctl.signal.aborted) setError(e.message) })
return () => ctl.abort()
}, [backendUrl, segmentId, reload])
const available = new Map(catalog.candidates.map(c => [memberKey(c), c]))
const label = (c: IxBondCandidate) => [c.name, c.segmentName, nodeLabel(nodes, c.serverId), c.kind === "wireguard" ? "WG" : "GRE/IPsec", c.endpoint, c.interfaceName].join(" · ")
function open(group?: IxSavedBond) {
setError("")
setRemove(false)
setDirect(group?.directCidrs.join("\n") ?? "")
setDraft(group ? {
id: group.id, revision: group.revision, name: group.name, mode: group.mode, directCidrs: group.directCidrs,
members: group.members.map(m => ({ ...m, appliedRevision: available.get(memberKey(m))?.appliedRevision ?? m.appliedRevision })),
} : { revision: 0, name: "", mode: "failover", members: [], directCidrs: [] })
}
async function perform(action: () => Promise<void>) {
if (busy || readOnly) return
setBusy(true)
setError("")
try { await action() } catch (e) { setError(e instanceof Error ? e.message : "Ошибка операции с группой") }
finally { setBusy(false) }
}
const patch = (fields: Partial<IxBondEdit>) => setDraft(old => old && { ...old, ...fields })
const ownedGroups = catalog.groups.filter(g => g.members.some(m => m.segmentId === segmentId))
const owner = catalog.groups.find(g => g.id === draft?.id)?.ownerSegmentId ?? segmentId
const root = "/api/ix/segments/" + owner + "/linux-bonds"
const occupied = new Set(catalog.groups.filter(g => g.id !== draft?.id).flatMap(g => g.members.map(memberKey)))
const choices = catalog.candidates.filter(c => !occupied.has(memberKey(c)) && !draft?.members.some(m => memberKey(m) === memberKey(c)))
.map(c => ({ value: memberKey(c), label: label(c) }))
const issue = error && <p role="alert" className="text-sm text-destructive">{error}</p>
return <Frame spacing="sm">
<FrameHeader className="flex-row flex-wrap items-center justify-between gap-2">
<FrameTitle>Группы туннелей VPS</FrameTitle>
{!readOnly && <Button size="sm" variant="outline" onClick={() => open()}>Создать группу</Button>}
</FrameHeader>
<FramePanel className="grid gap-3">
{!draft && issue}
{!ownedGroups.length && <p className="text-sm text-muted-foreground">Туннели этого сегмента используются отдельно.</p>}
{ownedGroups.map(g => <div key={g.id} className="grid gap-1.5">
<span className="font-medium">{g.name} · {modeLabel(g.mode)}</span>
<ol className="grid gap-1 text-sm">{g.members.map((m, i) => {
const c = available.get(memberKey(m))
const role = g.mode === "failover" ? (i ? "Резерв " + i : "Основной") : "Вес " + (g.mode === "weighted" ? m.weight : 1)
return <li key={memberKey(m)}>{role} · {c ? label(c) : m.interfaceName + " · недоступен"}
{c && c.appliedRevision !== m.appliedRevision ? " · изменена ревизия" : ""}</li>
})}</ol>
{!readOnly && <div className="flex flex-wrap gap-2">
<Button size="sm" variant="outline" disabled={busy} onClick={() => open(g)}>Изменить</Button>
<Button size="sm" variant="outline" disabled={busy} onClick={() => void perform(async () => {
const bundle = await requestJson<IxBondBundle>(backendUrl, "/api/ix/segments/" + g.ownerSegmentId + "/linux-bonds/" + g.id + "/export",
{ method: "POST", body: JSON.stringify({ revision: g.revision }) })
download("ix-bond-" + g.id + ".json", JSON.stringify(bundle, null, 2))
})}>Скачать для ix-client</Button>
</div>}
</div>)}
{!!ownedGroups.length && <p className="text-sm text-muted-foreground">Подготовьте интерфейсы на VPS в режиме транспорта и импортируйте JSON в ix-client. Активный путь показывает TUI клиента.</p>}
</FramePanel>
<Sheet open={!!draft} onOpenChange={value => !value && !busy && setDraft(null)}>
<SheetContent className="data-[side=right]:w-full data-[side=right]:sm:max-w-xl">
<SheetHeader><SheetTitle>Группа туннелей VPS</SheetTitle>
<SheetDescription>Выберите применённые подключения одного VPS. В режиме резервирования первый туннель в списке основной.</SheetDescription>
</SheetHeader>
{draft && <form className="flex min-h-0 flex-1 flex-col" onSubmit={e => { e.preventDefault(); void perform(async () => {
await requestJson(backendUrl, root, { method: "POST", body: JSON.stringify({ ...draft,
directCidrs: direct.split(/[\s,]+/).filter(Boolean) }) })
setDraft(null); setReload(n => n + 1)
}) }}>
<div className="grid min-h-0 gap-4 overflow-y-auto px-4">
{issue}
<Field><FieldLabel htmlFor="ix-bond-name">Имя группы</FieldLabel><Input id="ix-bond-name" value={draft.name} required maxLength={80} onChange={e => patch({ name: e.target.value })} /></Field>
<Field><FieldLabel htmlFor="ix-bond-mode">Режим</FieldLabel>
<Select value={draft.mode} items={[...modes]} onValueChange={v => v && patch({ mode: v })}>
<SelectTrigger id="ix-bond-mode"><SelectValue /></SelectTrigger>
<SelectContent>{modes.map(m => <SelectItem key={m.value} value={m.value}>{m.label}</SelectItem>)}</SelectContent>
</Select></Field>
{draft.members.map((m, index) => {
const candidate = available.get(memberKey(m))
return <div key={memberKey(m)} className="grid gap-2 rounded-md border p-2 text-sm">
<span>{index + 1}. {candidate ? label(candidate) : m.interfaceName + " · недоступен"}</span>
{draft.mode === "weighted" && <Field><FieldLabel htmlFor={"ix-bond-weight-" + index}>Вес</FieldLabel>
<Input id={"ix-bond-weight-" + index} type="number" min={1} max={100} required value={m.weight}
onChange={e => patch({ members: draft.members.map((item, n) => n === index ? { ...item, weight: Number(e.target.value) } : item) })} /></Field>}
<div className="flex gap-2">
<Button size="sm" variant="outline" type="button" disabled={!index} onClick={() => {
const members = [...draft.members]; members.splice(index - 1, 0, ...members.splice(index, 1)); patch({ members })
}}>Выше</Button>
<Button size="sm" variant="outline" type="button" onClick={() => patch({ members: draft.members.filter((_, i) => i !== index) })}>Исключить</Button>
</div>
</div>
})}
<Field><FieldLabel htmlFor="ix-bond-member">Добавить туннель этого VPS</FieldLabel>
<Select<string> key={draft.members.length} value={null} items={choices} disabled={!choices.length || draft.members.length >= 16} onValueChange={v => {
const c = v && available.get(v)
if (c) patch({ members: [...draft.members, { serverId: c.serverId, segmentId: c.segmentId, appliedRevision: c.appliedRevision, interfaceName: c.interfaceName, weight: 1 }] })
}}>
<SelectTrigger id="ix-bond-member"><SelectValue placeholder="Выберите интерфейс" /></SelectTrigger>
<SelectContent alignItemWithTrigger={false}>{choices.map(c => <SelectItem key={c.value} value={c.value}>{c.label}</SelectItem>)}</SelectContent>
</Select></Field>
<Field><FieldLabel htmlFor="ix-bond-direct">Прямой выход для сетей (CIDR)</FieldLabel>
<Textarea id="ix-bond-direct" rows={3} value={direct} onChange={e => setDirect(e.target.value)} /></Field>
</div>
<SheetFooter>
<Button type="submit" disabled={busy || readOnly || draft.members.length < 2}>Сохранить</Button>
{draft.id && <Button type="button" variant="outline" disabled={busy || readOnly} onClick={() => {
if (!remove) { setRemove(true); return }
void perform(async () => {
await requestJson(backendUrl, root + "/" + draft.id, { method: "DELETE", body: JSON.stringify({ revision: draft.revision }) })
setDraft(null); setReload(n => n + 1)
})
}}>{remove ? "Подтвердить удаление группы" : "Удалить группу"}</Button>}
<Button type="button" variant="outline" disabled={busy} onClick={() => setDraft(null)}>Отмена</Button>
</SheetFooter>
</form>}
</SheetContent>
</Sheet>
</Frame>
}
+35 -11
View File
@@ -1,9 +1,9 @@
"use client"
import { useMemo, useState } from "react"
import { useEffect, useMemo, useState } from "react"
import { type ColumnDef, useTable } from "@tanstack/react-table"
import { EllipsisIcon, PencilIcon, PlusIcon, RefreshCwIcon } from "lucide-react"
import type { IxLinuxBinding, IxLinuxClientRequest, IxSegment, IxSite } from "@mmapp/contracts/internet-exchange"
import type { IxBondCatalog, IxLinuxBinding, IxLinuxClientRequest, IxSegment, IxSite } from "@mmapp/contracts/internet-exchange"
import { DataGridShell } from "@/components/data-grids/shared/data-grid-shell"
import { Badge } from "@/components/reui/badge"
import { dataGridFeatures, type DataGridFeatures } from "@/components/reui/data-grid"
@@ -19,9 +19,10 @@ import { Textarea } from "@/components/ui/textarea"
import { isIpv4String } from "@/lib/gre-endpoint-resolve"
import { publicEndpoint, transitName } from "./ix-exits"
import { nodeLabel, useIxNodeInventory, type IxNode } from "./ix-view"
import { requestJson } from "@/shared/api/http-client"
type Binding = IxSite["interfaces"][number]
type ClientSelection = { site: IxSite; binding: Binding; addProtocol?: boolean }
type ClientSelection = { site: IxSite; binding: Binding; addProtocol?: boolean; chooseTransport?: boolean }
type FormState = {
serverId: number
name: string
@@ -89,6 +90,19 @@ function ClientForm({ segment, edit, setAddProtocol, nodes, backendUrl, busy, sa
const wireguard = form.kind !== "gre-ipsec"
const gre = form.kind !== "wireguard"
const [rotate, setRotate] = useState(false)
const [vpsId, setVpsId] = useState("")
const [knownVps, setKnownVps] = useState<{ value: string; label: string }[]>([])
useEffect(() => {
if (edit) return
const controller = new AbortController()
void requestJson<IxBondCatalog>(backendUrl, "/api/ix/linux-bonds", { signal: controller.signal }).then(result => {
const labels = new Map<string, string>()
for (const c of result.candidates) if (c.clientId) labels.set(c.clientId, c.name + " · " + c.segmentName)
for (const group of result.groups) labels.set(group.clientId, group.name)
if (!controller.signal.aborted) setKnownVps([...labels].map(([value, label]) => ({ value, label: label + " · " + value.slice(0, 8) })))
}).catch(() => {})
return () => controller.abort()
}, [backendUrl, edit])
const origin = useIxNodeInventory(backendUrl, form.serverId, segment.id)
const site = segment.configuration.sites.find(site => site.serverId === form.serverId)
const suggested = publicEndpoint(origin.inventory)
@@ -120,6 +134,7 @@ function ClientForm({ segment, edit, setAddProtocol, nodes, backendUrl, busy, sa
if (!valid || busy) return
void save({
revision: segment.revision, serverId: form.serverId, interfaceName: binding?.name, name: form.name,
vpsClientId: !edit && vpsId || undefined,
kind: wireguard ? "wireguard" : "gre-ipsec", additionalGre: form.kind === "both" || undefined, companionOf: companion?.name,
hubEndpoint: hub, peerEndpoint: form.peer.trim() || undefined,
peerPublicKey: wireguard ? form.key.trim() || undefined : undefined,
@@ -134,6 +149,13 @@ function ClientForm({ segment, edit, setAddProtocol, nodes, backendUrl, busy, sa
<div className="grid min-h-0 gap-4 overflow-y-auto px-4 pb-4">
<Field><FieldLabel htmlFor="ix-linux-name">Имя клиента</FieldLabel>
<Input id="ix-linux-name" value={form.name} placeholder="vps-01" readOnly={!!companion} required onChange={event => patch({ name: event.target.value })} /></Field>
{!edit && !!knownVps.length && <Field><FieldLabel htmlFor="ix-linux-vps">Привязка к VPS</FieldLabel>
<Select value={vpsId || "separate"} items={[{ value: "separate", label: "Отдельное подключение" }, ...knownVps]}
onValueChange={v => setVpsId(v && v !== "separate" ? v : "")}>
<SelectTrigger id="ix-linux-vps"><SelectValue /></SelectTrigger>
<SelectContent><SelectItem value="separate">Отдельное подключение</SelectItem>
{knownVps.map(v => <SelectItem key={v.value} value={v.value}>{v.label}</SelectItem>)}</SelectContent>
</Select></Field>}
{nodeChoices.length > 1 && <Field><FieldLabel htmlFor="ix-linux-node">Узел IX</FieldLabel>
<Select value={String(form.serverId)} items={nodeChoices} disabled={!!edit}
onValueChange={value => value && patch({ serverId: Number(value), hub: "", exit: "isolated" })}>
@@ -144,10 +166,11 @@ function ClientForm({ segment, edit, setAddProtocol, nodes, backendUrl, busy, sa
<FieldTitle id="ix-linux-transport">Протоколы подключения</FieldTitle>
<ButtonGroup aria-labelledby="ix-linux-transport" className="max-w-full">
{protocols.map(({ kind, label }) => {
const selected = paired || !!companion || form.kind === "both" || form.kind === kind
const choosing = !!companion && edit?.chooseTransport
const selected = choosing ? form.kind === kind : paired || !!companion || form.kind === "both" || form.kind === kind
return <Button key={kind} type="button" size="sm" variant={selected ? "secondary" : "outline"} aria-pressed={selected}
disabled={busy || (existing ? paired || existing.kind === kind : form.kind === kind)}
onClick={() => existing ? setAddProtocol(!companion)
disabled={busy || (choosing ? form.kind === kind : existing ? paired || existing.kind === kind : form.kind === kind)}
onClick={() => choosing ? patch({ kind }) : existing ? setAddProtocol(!companion)
: patch({ kind: form.kind === "both" ? (kind === "wireguard" ? "gre-ipsec" : "wireguard") : "both" })}>{label}</Button>
})}
</ButtonGroup>
@@ -211,7 +234,7 @@ function ClientForm({ segment, edit, setAddProtocol, nodes, backendUrl, busy, sa
export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly, busy, error, save, refresh, revoke, view, inspect }: {
segment: IxSegment; nodes: IxNode[]; backendUrl: string; applied: IxLinuxBinding[]; readOnly: boolean; busy: boolean; error?: string
save: (input: IxLinuxClientRequest) => Promise<boolean>; refresh: () => void
view: (binding: IxLinuxBinding) => void; revoke: (binding: IxLinuxBinding) => void
view: (binding: IxLinuxBinding, transportOnly?: boolean) => void; revoke: (binding: IxLinuxBinding) => void
inspect: (binding: IxLinuxBinding) => void
}) {
const [open, setOpen] = useState(false)
@@ -227,7 +250,7 @@ export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly,
const columns = useMemo<ColumnDef<DataGridFeatures, IxLinuxBinding>[]>(() => [
{ id: "name", header: "Клиент", size: 170, cell: ({ row }) => <div className="grid gap-0.5">
<span className="font-medium">{row.original.name ?? row.original.interfaceName}</span>
<span className="text-xs text-muted-foreground">{nodeLabel(nodes, row.original.serverId)}</span>
<span className="text-xs text-muted-foreground">{nodeLabel(nodes, row.original.serverId)} · {row.original.interfaceName}</span>
</div> },
{ id: "transport", header: "Туннель", size: 105, cell: ({ row }) => row.original.kind === "wireguard" ? "WireGuard" : "GRE/IPsec" },
{ id: "egress", header: "Выход трафика", size: 205, cell: ({ row }) => {
@@ -270,9 +293,10 @@ export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly,
<EllipsisIcon aria-hidden />
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{live && <DropdownMenuItem onClick={() => view(live, true)}>Конфиг для группы ix-client</DropdownMenuItem>}
{live && <DropdownMenuItem onClick={() => inspect(live)}>Проверить путь</DropdownMenuItem>}
{!readOnly && site && saved?.linux && !paired && <DropdownMenuItem
onClick={() => { setEdit({ site, binding: saved, addProtocol: true }); setOpen(true) }}>Добавить другой протокол</DropdownMenuItem>}
{!readOnly && site && saved?.linux && <DropdownMenuItem
onClick={() => { setEdit({ site, binding: saved, addProtocol: true, chooseTransport: true }); setOpen(true) }}>Добавить туннель</DropdownMenuItem>}
{!readOnly && saved?.linux && <DropdownMenuItem variant="destructive" onClick={() => revoke(binding)}>Отозвать доступ…</DropdownMenuItem>}
</DropdownMenuContent>
</DropdownMenu>}
@@ -294,7 +318,7 @@ export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly,
</FramePanel>
<Sheet open={open} onOpenChange={value => !busy && setOpen(value)}>
<SheetContent className="data-[side=right]:w-full data-[side=right]:sm:max-w-lg" showCloseButton={!busy}>
<SheetHeader><SheetTitle>{edit?.addProtocol ? "Добавить другой протокол" : edit ? "Доступ и выход клиента" : "Подключить Linux"}</SheetTitle>
<SheetHeader><SheetTitle>{edit?.chooseTransport ? "Добавить туннель" : edit?.addProtocol ? "Добавить другой протокол" : edit ? "Доступ и выход клиента" : "Подключить Linux"}</SheetTitle>
<SheetDescription>Укажите VPS и выберите, куда направлять его трафик.</SheetDescription>
{error && <p className="text-sm text-destructive" role="alert">{error}</p>}
</SheetHeader>
+14 -8
View File
@@ -23,6 +23,7 @@ import { requestJson } from "@/shared/api/http-client"
import { ConfigurationFields, newSite, nodeLabel, RouteGrid, SegmentGrid, SegmentStatus, type IxNode } from "./ix-view"
import { IxLinuxClients } from "./ix-linux-clients"
import { IxExits } from "./ix-exits"
import { IxClientBonds } from "./ix-client-bonds"
type Tab = "configuration" | "routes" | "linux"
@@ -74,7 +75,7 @@ export default function IxPage() {
const [activeNode, setActiveNode] = useState(ALL_SERVERS_ID)
const [observations, setObservations] = useState<IxSiteObservation[] | null>(null)
const [linuxBindings, setLinuxBindings] = useState<IxLinuxBinding[]>([])
const [linux, setLinux] = useState<(IxLinuxAccess & IxLinuxBinding) | null>(null)
const [linux, setLinux] = useState<(IxLinuxAccess & IxLinuxBinding & { transportOnly: boolean }) | null>(null)
const [linuxPath, setLinuxPath] = useState<(IxLinuxPath & Pick<IxLinuxBinding, "name" | "interfaceName">) | null>(null)
const [review, setReview] = useState("")
const [reviewError, setReviewError] = useState("")
@@ -261,22 +262,23 @@ export default function IxPage() {
setLinuxBindings(items)
}
async function exportLinux(binding: IxLinuxBinding) {
async function exportLinux(binding: IxLinuxBinding, transportOnly = false) {
if (!selected) return
setLinux(null)
const query = new URLSearchParams({ serverId: String(binding.serverId), interfaceName: binding.interfaceName })
if (transportOnly) query.set("transportOnly", "true")
if (binding.managedWireguard && write) {
const access = await requestJson<IxLinuxAccess>(backendUrl, `/api/ix/segments/${selected.id}/linux/credential`,
post({ serverId: binding.serverId, interfaceName: binding.interfaceName }))
post({ serverId: binding.serverId, interfaceName: binding.interfaceName, ...(transportOnly && { transportOnly }) }))
download(access.filename, access.template)
setNotice("Конфигурация WireGuard скачана")
return
}
const access = binding.policy && binding.kind === "gre-ipsec" && write
? await requestJson<IxLinuxAccess>(backendUrl, `/api/ix/segments/${selected.id}/linux/credential`,
post({ serverId: binding.serverId, interfaceName: binding.interfaceName }))
post({ serverId: binding.serverId, interfaceName: binding.interfaceName, ...(transportOnly && { transportOnly }) }))
: await requestJson<IxLinuxAccess>(backendUrl, `/api/ix/segments/${selected.id}/linux?${query}`)
setLinux({ ...binding, ...access })
setLinux({ ...binding, ...access, transportOnly })
}
async function inspectLinux(binding: IxLinuxBinding) {
@@ -468,9 +470,11 @@ export default function IxPage() {
{selected ? <IxLinuxClients key={selected.id} segment={selected} nodes={peers} backendUrl={backendUrl}
applied={linuxBindings} busy={busy} error={error} readOnly={!live || !write || dirty}
save={input => perform(() => stageClient(input))} revoke={binding => void perform(() => stageClient(binding))}
refresh={() => void perform(loadLinuxBindings)} view={binding => void perform(() => exportLinux(binding))}
refresh={() => void perform(loadLinuxBindings)} view={(binding, transportOnly) => void perform(() => exportLinux(binding, transportOnly))}
inspect={binding => void perform(() => inspectLinux(binding))} />
: <EmptyState title="Сохраните сегмент" description="После сохранения можно подключать клиентов." />}
: <EmptyState title="Сохраните сегмент" description="После сохранения можно подключать клиентов." />}
{selected && live && <IxClientBonds key={selected.id + ":" + selected.appliedRevision} segmentId={selected.id}
backendUrl={backendUrl} nodes={peers} readOnly={!write || busy || dirty} download={download} />}
{linuxPath && <Frame spacing="sm">
<FrameHeader>
<FrameTitle>Маршруты клиента · {linuxPath.name ?? linuxPath.interfaceName}</FrameTitle>
@@ -489,7 +493,9 @@ export default function IxPage() {
<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"
<p className="text-sm text-muted-foreground">{linux.transportOnly
? "Подготовьте туннель на VPS с указанным именем интерфейса. Маршруты назначит ix-client после включения группы."
: linux.kind === "wireguard"
? linux.managedWireguard ? "Готовый файл с ключом доступен пользователю с правом управления сетью."
: "Подставьте приватный ключ Linux. После установки проверьте, куда направляются трафик и соединение управления."
: linux.policy && write ? "Скачайте оба файла в одну папку на VPS. Скрипт установит профиль strongSwan и поднимет GRE. SSH по внешнему IPv4 VPS останется прямым."
+77 -7
View File
@@ -1,7 +1,7 @@
import assert from "node:assert/strict"
import { createPrivateKey, createPublicKey, randomBytes, randomUUID } from "node:crypto"
import { mkdtemp } from "node:fs/promises"
import { createServer } from "node:http"
import { mkdtemp, writeFile } from "node:fs/promises"
import { createServer, type RequestListener } from "node:http"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { setTimeout as delay } from "node:timers/promises"
@@ -23,7 +23,8 @@ Object.assign(process.env, {
})
await pg.initialise()
await pg.start()
const rows: Record<string, Record<string, string>[]> = {
type RouterRows = Record<string, Record<string, string>[]>
const rows: RouterRows = {
"/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" }],
@@ -34,7 +35,8 @@ let writes = 0
let deletes = 0
let failPutAt = -1
let failDeleteAt = -1
const router = createServer(async (request, response) => {
const fixtureHubPublicKey = Buffer.alloc(32, 11).toString("base64")
const serveRouter = (rows: RouterRows): RequestListener => async (request, response) => {
try {
const path = new URL(request.url!, "http://127.0.0.1").pathname.replace(/^\/rest/, "")
let result: unknown
@@ -44,7 +46,7 @@ const router = createServer(async (request, response) => {
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) + "=" }),
const row = { ...fields, ...(path === "/interface/wireguard" && { "public-key": fixtureHubPublicKey }),
".id": "*" + (++writes + 1).toString(16).toUpperCase() }
const list = rows[path] ??= []
const index = list.findIndex(entry => entry[".id"] === place)
@@ -83,7 +85,15 @@ const router = createServer(async (request, response) => {
response.statusCode = 500
response.end(JSON.stringify({ error: String(error) }))
}
})
}
const router = createServer(serveRouter(rows))
const backupRouter = createServer(serveRouter({
"/ip/vrf": [{ ".id": "*1", name: "main", interfaces: "all", builtin: "true" }],
"/interface": [{ ".id": "*2", name: "ether1", type: "ether", running: "true" }],
"/ip/address": [{ ".id": "*3", interface: "ether1", address: "198.51.100.20/24" }],
"/ip/route": [{ ".id": "*4", "routing-table": "main", "dst-address": "0.0.0.0/0",
gateway: "198.51.100.1%ether1", "immediate-gw": "198.51.100.1%ether1", active: "true" }],
}))
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
@@ -393,6 +403,26 @@ try {
assert(greCredential.setup.indexOf(" lookup main\n") < greCredential.setup.indexOf("swanctl --initiate"))
assert.equal((await post(managedPath + "/linux/credential", clientKey, 200)).template, credential.template)
const bondPath = managedPath + "/linux-bonds"
const bondInput = { revision: 0, name: "mixed", mode: "weighted", directCidrs: ["192.0.2.0/24"],
members: [wireguard, greBinding].map((binding, i) => ({ segmentId: managed.id, serverId: clientKey.serverId,
interfaceName: binding.name, weight: i ? 1 : 3, appliedRevision: pairedApplied.segment.revision })) }
await post(bondPath, bondInput, 403, reader)
const bond = await post(bondPath, bondInput, 200)
assert.equal(bond.clientId, wireguard.linux.clientId)
await post(bondPath, bondInput, 409)
const bundlePath = bondPath + "/" + bond.id + "/export"
const bundle = await post(bundlePath, { revision: 1 }, 200)
assert.deepEqual(bundle.members.map(member => [member.kind, member.weight]), [["wireguard", 3], ["gre-ipsec", 1]])
assert.equal(bundle.members[0].peerPublicKey, fixtureHubPublicKey)
assert.deepEqual(bundle.destinations, ["0.0.0.0/0"])
assert(!JSON.stringify(bundle).includes(privateKey))
if (process.env.IX_BOND_TEST_EXPORT) {
await writeFile(process.env.IX_BOND_TEST_EXPORT, JSON.stringify(bundle, null, 2) + "\n", { flag: "wx" })
}
await post(bundlePath, { revision: 1 }, 403, reader)
await post(managedPath + "/removal-plan", { revision: pairedApplied.segment.revision }, 409)
const { rows: [exit] } = await pool.query(`INSERT INTO servers
(name,host,port,enabled,type,username,password,use_ssl,verify_ssl)
VALUES('owned-exit','127.0.0.1',$1,true,'exit-node','synthetic','synthetic',false,true) RETURNING id`, [port])
@@ -402,6 +432,18 @@ try {
const beforeStage = writes
await post(managedPath + "/linux", { ...remoteClient, localAddress: "10.254.21.1/30" }, 400)
const stagedRemote = await post(managedPath + "/linux", remoteClient, 200)
assert(!Object.hasOwn(stagedRemote.segment.configuration, "linuxBonds"))
assert.deepEqual(await post(bundlePath, { revision: 1 }, 200), bundle)
const racing = await Promise.all(["equal", "failover"].map(mode => fetch(origin + "/api/ix/segments" + bondPath, {
method: "POST", headers: { authorization: "Bearer " + writer, "content-type": "application/json" },
body: JSON.stringify({ ...bondInput, id: bond.id, revision: 1, mode }),
})))
assert.deepEqual(racing.map(r => r.status).sort(), [200, 409])
const revised = await racing.find(r => r.ok)!.json()
assert.equal(revised.revision, 2)
await post(bundlePath, { revision: 1 }, 409)
await post(bondPath + "/" + bond.id, { revision: 2 }, 204, writer, "DELETE")
await post(bundlePath, { revision: 2 }, 409)
assert.equal(writes, beforeStage)
assert.equal(stagedRemote.segment.revision, appliedRevision + 1)
assert.equal(stagedRemote.segment.appliedRevision, appliedRevision)
@@ -423,14 +465,42 @@ try {
assert.ok(added[0].linux.clientId)
assert.equal(added[0].linux.clientId, added[1].linux.clientId)
await new Promise<void>(resolve => backupRouter.listen(0, "127.0.0.1", resolve))
const { rows: [secondIx] } = await pool.query(`INSERT INTO servers
(name,host,port,enabled,type,username,password,use_ssl,verify_ssl)
VALUES('owned-bond-peer','127.0.0.1',$1,true,'ix-node','synthetic','synthetic',false,true) RETURNING id`,
[(backupRouter.address() as { port: number }).port])
const secondSegment = (await post("", { revision: 0, configuration: { name: "ix-web-bond-peer", sites: [
{ serverId: Number(secondIx.id), autonomousSystem: 64513, routerId: "192.0.2.8" },
] } }, 200)).segment
const secondPath = "/" + secondSegment.id
const secondInput = { ...clientInput, hubEndpoint: "198.51.100.20", serverId: Number(secondIx.id), revision: secondSegment.revision }
await post(secondPath + "/linux", { ...secondInput, vpsClientId: randomUUID() }, 409)
const secondWg = await post(secondPath + "/linux", { ...secondInput, vpsClientId: bond.clientId }, 200)
const newTunnel = secondWg.segment.configuration.sites[0].interfaces[0]
assert.equal(newTunnel.linux.clientId, bond.clientId)
assert.notEqual(newTunnel.provisionWireguard.peerAddress, wireguard.provisionWireguard.peerAddress)
const secondaryPlan = await post(secondPath + "/plan", { revision: secondWg.segment.revision }, 200)
const secondaryApplied = (await post(secondPath + "/apply", { revision: secondWg.segment.revision, digest: secondaryPlan.digest }, 200)).segment
const cross = await post(bondPath, { ...bondInput, members: [bondInput.members[0], {
segmentId: secondSegment.id, appliedRevision: secondaryApplied.revision, serverId: secondInput.serverId, interfaceName: secondWg.interfaceName, weight: 1,
}] }, 200)
await post(secondPath + "/removal-plan", { revision: secondaryApplied.revision }, 409)
const crossBundle = await post(bondPath + "/" + cross.id + "/export", { revision: 1 }, 200)
assert.equal(crossBundle.members[1].address, newTunnel.provisionWireguard.peerAddress)
await post(bondPath + "/" + cross.id, { revision: 1 }, 204, writer, "DELETE")
await post(secondPath + "/removal-plan", { revision: secondaryApplied.revision }, 200)
console.log(JSON.stringify({ appliedRevisions: [2, 4], writes, audit: audit.n, mcpConnections: connections.n,
unauthenticated: 401, readOnly: 403, ownerMismatch: 409, drift: 409, replay: 409, protected: 409, linuxClients: clients.items.length,
deletedDraft: true, removedNativeObjects: deletes, revisionsRetained: archive.revisions,
mcpRemovalVerified: true, managedWireguardVerified: true, clientWithTransitStagedAtomically: true, bothProtocolsInOneVrf: true }))
mcpRemovalVerified: true, managedWireguardVerified: true, clientWithTransitStagedAtomically: true, bothProtocolsInOneVrf: true,
mixedBondExport: true, crossSegmentBond: true, concurrentBondEdits: true }))
} finally {
await mcp?.close()
await app?.close()
await new Promise<void>(resolve => router.close(() => resolve()))
if (backupRouter.listening) await new Promise<void>(resolve => backupRouter.close(() => resolve()))
await pool.end()
await pg.stop()
}
+34 -6
View File
@@ -1,16 +1,17 @@
import { randomUUID } from "node:crypto"
import type { FastifyPluginAsync } from "fastify"
import { z } from "zod"
import { ixChangeSchema, ixLinuxClientRequest, ixTransitRequest, type IxWebPlan } from "@mmapp/contracts/internet-exchange"
import { ixBondEditSchema, ixChangeSchema, ixLinuxClientRequest, ixTransitRequest, type IxWebPlan } from "@mmapp/contracts/internet-exchange"
import { fingerprint, McpError } from "../modules/mcp/security.js"
import { audit } from "../modules/mcp/store.js"
import { pool } from "../db/index.js"
import { captureVerifiedRestRequest, inspectVerifiedRestRequest, RestRequestProvenanceError } from "../plugins/auth.js"
import { withApplicationMutationLock } from "../services/config-mutation-lock.js"
import { withApplicationCollectorLock, withApplicationMutationLock } from "../services/config-mutation-lock.js"
import { withConfigurationActor } from "../services/config-mutation-policy.js"
import { applyIxChange, assignIxRouterIds, configureIxLinuxClient, configureIxTransit, listIxLinuxClients, observeIxLinuxPath, observeIxSegment, prepareIxChange, prepareIxRemoval, readIxLinuxClient, readIxNodeInventory, removeIxSegment } from "../services/internet-exchange-execution.js"
import { compileIxConfiguration, IxConflict } from "../services/internet-exchange-plan.js"
import { assertIxRevision, listIxSegments, readIxSegment, writeIxRevision } from "../services/internet-exchange-store.js"
import { changeIxBond, exportIxBond, ixBondCatalog } from "../services/internet-exchange-bonds.js"
const paging = z.object({
limit: z.coerce.number().int().min(1).max(100).default(25),
@@ -65,6 +66,33 @@ const ixRoutes: FastifyPluginAsync = async app => {
const input = paging.parse(request.query)
return { items: await listIxSegments(input.limit, input.offset) }
})
app.get("/ix/linux-bonds", async () => ixBondCatalog())
app.post("/ix/segments/:id/linux-bonds", async request => {
const { id } = segmentParams.parse(request.params)
const edit = ixBondEditSchema.parse(request.body)
return withApplicationMutationLock(() => changeIxBond(id, edit, request.authUser?.id ?? "local-operator"), { waitMs: 5000 })
})
app.delete("/ix/segments/:id/linux-bonds/:bondId", async (request, reply) => {
const { id, bondId } = segmentParams.extend({ bondId: z.uuid() }).parse(request.params)
const { revision } = planRequest.parse(request.body)
await withApplicationMutationLock(() => changeIxBond(id, { id: bondId, revision }, request.authUser?.id ?? "local-operator"), { waitMs: 5000 })
return reply.code(204).send()
})
app.post("/ix/segments/:id/linux-bonds/:bondId/export", async (request, reply) => {
const { id, bondId } = segmentParams.extend({ bondId: z.uuid() }).parse(request.params)
const { revision } = planRequest.parse(request.body)
const scope = { deadlineAt: Date.now() + 90_000 }
const token = await captureVerifiedRestRequest(request, scope)
const authorize = () => inspectVerifiedRestRequest(token, scope, "mm:network:write")
const { ownerId } = await authorize()
return withApplicationCollectorLock(async () => {
const bundle = await exportIxBond(id, bondId, revision, authorize)
await audit(pool, ownerId, "ix.bond.exported", null, { segmentId: id, bondId, revision })
await authorize()
reply.header("Cache-Control", "no-store")
return bundle
})
})
app.get("/ix/nodes", async () => {
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"),
@@ -96,12 +124,12 @@ 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 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({ serverId: z.coerce.number().positive().int().safe(), interfaceName: z.string().regex(/^[A-Za-z0-9_.-]{1,48}$/), transportOnly: z.literal("true").optional() }).strict(),
z.object({}).strict(),
]).parse(request.query)
const segment = await readIxSegment(id)
if (!segment) throw new IxConflict("Сегмент IX не найден", 404)
return "serverId" in query ? readIxLinuxClient(segment, query.serverId, query.interfaceName) : listIxLinuxClients(segment)
return "serverId" in query ? readIxLinuxClient(segment, query.serverId, query.interfaceName, false, query.transportOnly === "true") : listIxLinuxClients(segment)
})
app.post("/ix/segments/:id/linux", async request => {
const { id } = segmentParams.parse(request.params)
@@ -129,13 +157,13 @@ const ixRoutes: FastifyPluginAsync = async app => {
})
app.post("/ix/segments/:id/linux/credential", async (request, reply) => {
const { id } = segmentParams.parse(request.params)
const { serverId, interfaceName } = clientKey.parse(request.body)
const { serverId, interfaceName, transportOnly } = clientKey.extend({ transportOnly: z.boolean().optional() }).parse(request.body)
const scope = { deadlineAt: Date.now() + 60_000 }
const token = await captureVerifiedRestRequest(request, scope)
const { ownerId } = await inspectVerifiedRestRequest(token, scope, "mm:network:write")
const segment = await readIxSegment(id)
if (!segment) throw new IxConflict("Сегмент IX не найден", 404)
const access = await readIxLinuxClient(segment, serverId, interfaceName, true)
const access = await readIxLinuxClient(segment, serverId, interfaceName, true, transportOnly)
await inspectVerifiedRestRequest(token, scope, "mm:network:write")
await audit(pool, ownerId, "ix.linux.credential_exported", null, { segmentId: id, serverId, interfaceName, revision: access.revision })
reply.header("Cache-Control", "no-store")
@@ -0,0 +1,38 @@
import assert from "node:assert/strict"
import { test } from "node:test"
import type { IxBondCandidate, IxBondEdit, IxSavedBond } from "@mmapp/contracts/internet-exchange"
import { resolveBondMembers } from "./internet-exchange-bonds.js"
const owner = "a213a2c7-53cd-4325-8e43-e2d953cd761b"
const other = "5c1364bd-6147-46ea-b726-273a7e933302"
const client = "5a7fa65a-f94f-475a-96cd-a2ece0ed77ce"
const primary: IxBondCandidate = { segmentId: owner, appliedRevision: 3, serverId: 5, segmentName: "eu",
interfaceName: "wg-vps", name: "alpha", kind: "wireguard", probe: "10.255.0.1", address: "10.255.0.2", endpoint: "192.0.2.1", destinations: ["0.0.0.0/0"] }
const backup: IxBondCandidate = { ...primary, segmentId: other, segmentName: "asia", clientId: client,
serverId: 6, kind: "gre-ipsec", interfaceName: "gre-vps", probe: "10.255.0.5", address: "10.255.0.6" }
const edit: IxBondEdit = { name: "vps", mode: "weighted", directCidrs: [], revision: 0,
members: [primary, backup].map(({ segmentId, appliedRevision, serverId, interfaceName }, i) =>
({ segmentId, appliedRevision, serverId, interfaceName, weight: i ? 1 : 3 })) }
test("cross-segment members retain order, declared VPS identity and revision", () => {
const { members, clientId } = resolveBondMembers(edit, [backup, primary], [], owner)
assert.deepEqual(members, [primary, backup])
assert.equal(clientId, client)
const saved: IxSavedBond = { ...edit, id: other, ownerSegmentId: owner, revision: 1, clientId }
assert.throws(() => resolveBondMembers(edit, [primary, backup], [saved], owner), /уже входит/)
assert.equal(resolveBondMembers(saved, [primary, backup], [saved], owner, saved).clientId, client)
})
test("reject stale, revoked, foreign-client and conflicting routing paths", () => {
const invalid: Array<[IxBondCandidate, RegExp]> = [
[{ ...backup, appliedRevision: 4 }, /изменилось/],
[{ ...backup, destinations: ["198.51.100.0/24"] }, /назначения/],
[{ ...backup, address: primary.probe }, /внутренние адреса/],
]
for (const [candidate, reason] of invalid) {
assert.throws(() => resolveBondMembers(edit, [primary, candidate], [], owner), reason)
}
assert.throws(() => resolveBondMembers(edit, [primary], [], owner), /недоступно/)
assert.throws(() => resolveBondMembers(edit, [{ ...primary, clientId: owner }, backup], [], owner), /разными VPS/)
assert.throws(() => resolveBondMembers(edit, [primary, backup], [], client), /текущего сегмента/)
})
@@ -0,0 +1,138 @@
import { randomUUID } from "node:crypto"
import { isIP } from "node:net"
import type { PoolClient } from "pg"
import {
ixBondBundleSchema, ixSavedBondSchema, ixSegmentConfigurationSchema, type IxBondCandidate,
type IxBondEdit, type IxSavedBond, type IxConfiguration, type IxBondBundle,
} from "@mmapp/contracts/internet-exchange"
import { pool } from "../db/index.js"
import { audit } from "../modules/mcp/store.js"
import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js"
import { ixLinuxBindingKind } from "./internet-exchange-client.js"
import { readIxLinuxClient } from "./internet-exchange-execution.js"
import { IxConflict } from "./internet-exchange-plan.js"
import { readIxSegment } from "./internet-exchange-store.js"
import { admitPartitionWriter } from "./partition-write-transaction.js"
type Query = Pick<PoolClient, "query">
type MemberRef = IxBondEdit["members"][number]
const visible = "(s.configuration->>'deleted') IS DISTINCT FROM 'true'"
const key = (m: Pick<MemberRef, "segmentId" | "serverId" | "interfaceName">) => [m.segmentId, m.serverId, m.interfaceName].join("/")
export function bondCandidates(segmentId: string, appliedRevision: number, config: IxConfiguration): IxBondCandidate[] {
return config.sites.flatMap(site => site.interfaces.flatMap(binding => {
const kind = ixLinuxBindingKind(binding)
const linux = binding.linux
const tunnel = binding.provisionWireguard ?? binding.provisionGre
if (!kind || !linux?.enabled || !tunnel || binding.peerServerId) return []
return [{
segmentId, appliedRevision, segmentName: config.name, serverId: site.serverId, interfaceName: binding.name,
name: linux.name, clientId: linux.clientId, kind, address: tunnel.peerAddress, probe: tunnel.localAddress.split("/")[0],
endpoint: (binding.provisionWireguard?.hubEndpoint ?? binding.localEndpoint)!,
destinations: linux.exit ? [isIP(tunnel.peerAddress) === 6 ? "::/0" : "0.0.0.0/0"]
: [...new Set(linux.destinations.map(canonicalBgpPolicyPrefix))].sort(),
}]
}))
}
async function candidates(sql: Query, ids?: string[]) {
const { rows } = await sql.query(`SELECT s.id,s.applied_revision,r.configuration FROM ix_segments s
JOIN ix_segment_revisions r ON r.segment_id=s.id AND r.revision=s.applied_revision
WHERE ${visible} AND ($1::uuid[] IS NULL OR s.id=ANY($1)) ORDER BY s.name,s.id`, [ids ?? null])
return rows.flatMap(row => bondCandidates(row.id, row.applied_revision, ixSegmentConfigurationSchema.parse(row.configuration)))
}
async function savedGroups(sql: Query, ownerId?: string): Promise<IxSavedBond[]> {
const { rows } = await sql.query(`SELECT item FROM ix_segments s
CROSS JOIN LATERAL jsonb_array_elements(s.configuration->'linuxBonds') item
WHERE ${visible} AND ($1::uuid IS NULL OR s.id=$1) ORDER BY s.id`, [ownerId ?? null])
return rows.map(row => ixSavedBondSchema.parse(row.item))
}
export async function ixBondCatalog() {
const [groups, available] = await Promise.all([savedGroups(pool), candidates(pool)])
return { groups, candidates: available }
}
export function resolveBondMembers(edit: IxBondEdit, available: IxBondCandidate[], groups: IxSavedBond[], ownerId: string, previous?: IxSavedBond) {
const occupied = new Set(groups.filter(g => g.id !== previous?.id).flatMap(g => g.members.map(key)))
const owned = new Map(available.map(m => [key(m), m]))
const addresses = new Set<string>()
const members = edit.members.map(member => {
const label = member.interfaceName
const found = owned.get(key(member))
if (!found || found.appliedRevision !== member.appliedRevision) throw new IxConflict("Подключение изменилось или недоступно: " + label)
if (occupied.has(key(member))) throw new IxConflict("Интерфейс уже входит в группу: " + label)
occupied.add(key(member))
for (const address of [found.address, found.probe]) {
const host = canonicalBgpPolicyPrefix(address + (isIP(address) === 6 ? "/128" : "/32"))
if (addresses.has(host)) throw new IxConflict("Назначьте разные внутренние адреса участникам группы: " + address)
addresses.add(host)
}
return found
})
const first = members[0]
if (!members.some(m => m.segmentId === ownerId)) throw new IxConflict("Выберите подключение из текущего сегмента")
if (!first?.destinations.length || members.some(m => isIP(m.address) !== isIP(first.address) ||
JSON.stringify(m.destinations) !== JSON.stringify(first.destinations))) {
throw new IxConflict("Участникам нужны одинаковые непустые назначения и одно семейство адресов")
}
const identities = new Set(members.flatMap(m => m.clientId ? [m.clientId] : []))
if (previous) identities.add(previous.clientId)
if (identities.size > 1) throw new IxConflict("Выбранные подключения зарегистрированы за разными VPS")
return { members, clientId: [...identities][0] ?? randomUUID() }
}
export async function changeIxBond(ownerId: string, edit: IxBondEdit | { id: string; revision: number }, actor: string) {
const sql = await pool.connect()
try {
await sql.query("BEGIN")
await admitPartitionWriter(sql)
// A member can belong to only one group, including groups owned by another segment.
await sql.query("SELECT pg_advisory_xact_lock(hashtextextended('ix-linux-bonds',0))")
if (!await readIxSegment(ownerId, sql)) throw new IxConflict("Сегмент IX не найден", 404)
const groups = await savedGroups(sql)
const previous = groups.find(group => group.ownerSegmentId === ownerId && group.id === edit.id)
if (edit.id && !previous) throw new IxConflict("Группа не найдена", 404)
if ((previous?.revision ?? 0) !== edit.revision) throw new IxConflict("Группа изменилась. Обновите данные")
let next: IxSavedBond | null = null
if ("members" in edit) {
const available = await candidates(sql, [...new Set(edit.members.map(m => m.segmentId))])
const { clientId } = resolveBondMembers(edit, available, groups, ownerId, previous)
next = ixSavedBondSchema.parse({ ...edit, id: previous?.id ?? randomUUID(), ownerSegmentId: ownerId, clientId,
revision: edit.revision + 1, directCidrs: [...new Set(edit.directCidrs.map(canonicalBgpPolicyPrefix))] })
}
const owned = groups.filter(group => group.ownerSegmentId === ownerId && group.id !== edit.id)
if (next) owned.push(next)
const result = await sql.query(`UPDATE ix_segments s SET configuration=jsonb_set(configuration,'{linuxBonds}',$2::jsonb)
WHERE s.id=$1 AND ${visible}`, [ownerId, JSON.stringify(owned)])
if (result.rowCount !== 1) throw new IxConflict("Сегмент IX недоступен")
await audit(sql, actor, next ? "ix.bond.saved" : "ix.bond.removed", null, { ownerId, id: next?.id ?? edit.id, revision: next?.revision ?? edit.revision })
await sql.query("COMMIT")
return next
} catch (error) {
await sql.query("ROLLBACK").catch(() => {})
throw error
} finally { sql.release() }
}
export async function exportIxBond(ownerId: string, id: string, revision: number, authorize: () => Promise<unknown>): Promise<IxBondBundle> {
const group = (await savedGroups(pool, ownerId)).find(g => g.id === id)
if (!group || group.revision !== revision) throw new IxConflict("Группа отсутствует или её ревизия изменилась")
const segments = [...new Set(group.members.map(m => m.segmentId))]
const { members } = resolveBondMembers(group, await candidates(pool, segments), [], ownerId, group)
const result = []
for (const [index, m] of members.entries()) {
await authorize()
const segment = await readIxSegment(m.segmentId)
if (!segment || segment.appliedRevision !== m.appliedRevision) throw new IxConflict("Изменилась площадка " + m.segmentName)
const access = await readIxLinuxClient(segment, m.serverId, m.interfaceName)
result.push({ kind: m.kind, interfaceName: access.filename.replace(/\.conf$/, ""), address: m.address, probe: m.probe,
endpoint: m.endpoint, weight: group.mode === "weighted" ? group.members[index].weight : 1,
...(m.kind === "wireguard" && { peerPublicKey: access.hubPublicKey }) })
}
const bundle = ixBondBundleSchema.parse({ version: 1, id, revision, name: group.name, clientId: group.clientId, mode: group.mode,
destinations: members[0].destinations, directCidrs: group.directCidrs, members: result })
await authorize()
return bundle
}
@@ -16,7 +16,7 @@ export function ixLinuxInterfaceName(prefix: "ixw" | "ixg", serverId: number, bi
return prefix + createHash("sha256").update(JSON.stringify([serverId, binding.name])).digest("hex").slice(0, 12)
}
export function ixWireguardClientTemplate(binding: Binding, hubPublicKey: string, routes: string[], privateKey = "<локальный_приватный_ключ>") {
export function ixWireguardClientTemplate(binding: Binding, hubPublicKey: string, routes: string[], privateKey = "<локальный_приватный_ключ>", transportOnly = false) {
const config = binding.provisionWireguard
if (binding.kind !== "wireguard" || !config?.hubEndpoint || !/^[A-Za-z0-9+/]{43}=$/.test(hubPublicKey)) {
throw new IxConflict("Для Linux нужны публичный ключ узла и заданный внешний адрес IX")
@@ -29,8 +29,8 @@ export function ixWireguardClientTemplate(binding: Binding, hubPublicKey: string
"[Interface]",
"Address = " + address(config.peerAddress),
"PrivateKey = " + privateKey,
binding.linux ? "Table = auto" : "Table = off",
...(binding.linux?.exit && binding.linux.peerEndpoint && isIP(binding.linux.peerEndpoint) === family ? [
binding.linux && !transportOnly ? "Table = auto" : "Table = off",
...(!transportOnly && binding.linux?.exit && binding.linux.peerEndpoint && isIP(binding.linux.peerEndpoint) === family ? [
"PostUp = ip -" + family + " rule add pref 10450 from " + address(binding.linux.peerEndpoint) + " lookup main",
"PreDown = ip -" + family + " rule del pref 10450 from " + address(binding.linux.peerEndpoint) + " lookup main",
] : []),
@@ -44,7 +44,7 @@ export function ixWireguardClientTemplate(binding: Binding, hubPublicKey: string
].join("\n")
}
export function ixGreClientTemplate(binding: Binding, serverId: number, bgp?: { address: string; localAddress: string }, credential?: string) {
export function ixGreClientTemplate(binding: Binding, serverId: number, bgp?: { address: string; localAddress: string }, credential?: string, transportOnly = false) {
const hub = binding.localEndpoint
const client = binding.endpoint
if (binding.kind !== "gre-ipsec" || !hub || !client || isIP(hub) !== 4 || isIP(client) !== 4 || hub === client) {
@@ -68,6 +68,30 @@ export function ixGreClientTemplate(binding: Binding, serverId: number, bgp?: {
"swanctl --initiate --child " + id + " --timeout 20",
"ip tunnel add " + greParameters,
]
const addressCommand = tunnel && "ip address add " + tunnel.peerAddress + (family === 4 ? "/32" : "/128") + " dev " + id
const transportSetup = transportOnly && tunnel && [
'conf="$(dirname -- "$0")/' + id + '.conf"',
'unit=/etc/systemd/system/ix-gre-' + id + '.service',
'profile=/etc/swanctl/conf.d/' + id + '.conf',
'if [ ! -r "$conf" ]; then echo "Положите ' + id + '.conf рядом со скриптом."; exit 1; fi',
'candidate=$(mktemp)',
'trap \'rm -f "$candidate"\' EXIT',
'cat >"$candidate" <<\'IX_GRE_UNIT\'',
"[Unit]", "Description=IX Client GRE/IPsec " + id, "Wants=network-online.target", "After=network-online.target strongswan.service",
"Requires=strongswan.service", "[Service]", "Type=oneshot", "RemainAfterExit=yes",
"ExecStartPre=/usr/sbin/swanctl --load-all",
"ExecStart=/bin/sh -ec '/usr/sbin/ip tunnel add " + greParameters + '; trap "/usr/sbin/ip link del dev ' + id +
'" EXIT; /usr/sbin/' + addressCommand + "; /usr/sbin/ip link set " + id + " up; trap - EXIT'",
"ExecStop=/usr/sbin/ip link del dev " + id,
"[Install]", "WantedBy=multi-user.target", "IX_GRE_UNIT",
'if [ -e "$unit" ] && ! cmp -s "$candidate" "$unit"; then echo "Служба уже принадлежит другой конфигурации."; exit 1; fi',
'if [ -e "$profile" ] && ! cmp -s "$conf" "$profile"; then echo "Профиль strongSwan отличается от существующего."; exit 1; fi',
'if [ ! -e "$unit" ] && ip link show dev ' + id + ' >/dev/null 2>&1; then echo "Интерфейс уже существует."; exit 1; fi',
'install -d -m 0700 /etc/swanctl/conf.d',
'if [ ! -e "$profile" ]; then install -m 0600 "$conf" "$profile"; fi',
'install -m 0644 "$candidate" "$unit"',
"systemctl daemon-reload", "systemctl enable --now ix-gre-" + id + ".service",
].join("\n")
return {
filename: id + ".conf",
template: [
@@ -107,7 +131,7 @@ export function ixGreClientTemplate(binding: Binding, serverId: number, bgp?: {
"}",
"",
].join("\n"),
setup: (tunnel ? [
setup: transportSetup || (tunnel ? [
'conf="$(dirname -- "$0")/' + id + '.conf"',
'if [ ! -r "$conf" ]; then echo "Положите файл ' + id + '.conf рядом со скриптом" >&2; exit 1; fi',
'if ip link show dev ' + id + ' >/dev/null 2>&1; then echo "GRE уже поднят" >&2; exit 1; fi',
@@ -122,7 +146,7 @@ export function ixGreClientTemplate(binding: Binding, serverId: number, bgp?: {
"trap cleanup 0",
...managementRules.map(([ip, selector]) => ip + " rule add pref " + management + " " + selector),
...common,
"ip address add " + tunnel.peerAddress + (family === 4 ? "/32" : "/128") + " dev " + id,
addressCommand!,
"ip link set " + id + " up",
...[...new Set([
tunnel.localAddress.split("/")[0] + (family === 4 ? "/32" : "/128"),
@@ -9,7 +9,7 @@ import { getServerRowById, type ServerRow } from "../modules/servers/repository/
import { withApplicationMutationLock, withConfigMutationLock } from "./config-mutation-lock.js"
import { assertVerifiedConfigurationAccess } from "./config-mutation-policy.js"
import { compileIxConfiguration, inIxNetwork, IxConflict, ixClientRoutingTable, ixDeviceIds, ixDiscardInterface, ixEgressList, ixNamespace } from "./internet-exchange-plan.js"
import { archiveIxSegment, assertIxName, assertIxRevision, assertIxRouterIds, assertIxSites, ixReservedRouterIds, ixReservedTunnelBindings, nextIxRouterId, readIxRevision, readIxSegment, writeIxRevision } from "./internet-exchange-store.js"
import { archiveIxSegment, assertIxName, assertIxRevision, assertIxRouterIds, assertIxSites, assertIxSegmentWithoutBonds, ixBondClientId, ixKnownVpsClient, ixReservedLinuxPoolBlocks, ixReservedRouterIds, ixReservedTunnelBindings, nextIxRouterId, readIxRevision, readIxSegment, writeIxRevision } from "./internet-exchange-store.js"
import { MikrotikClient } from "./mikrotik.js"
import { ixGreClientTemplate, ixLinuxBindingKind, ixLinuxInterfaceName, ixWireguardClientTemplate } from "./internet-exchange-client.js"
@@ -260,17 +260,14 @@ export async function assignIxRouterIds(id: string, configuration: IxConfigurati
}
export async function configureIxLinuxClient(segment: IxSegment, input: IxLinuxClientRequest) {
if (input.vpsClientId && !await ixKnownVpsClient(input.vpsClientId)) throw new IxConflict("VPS больше не зарегистрирован в применённой конфигурации IX")
if (input.additionalGre && (isIP(input.peerEndpoint ?? "") !== 4 || isIP(input.hubEndpoint) !== 4)) {
throw new IxConflict("Для подключения по обоим протоколам укажите два внешних IPv4-адреса", 400)
}
const site = segment.configuration.sites.find(candidate => candidate.serverId === input.serverId)
const companion = input.companionOf && site?.interfaces.find(binding => binding.name === input.companionOf && binding.linux)
if (input.companionOf && !companion) throw new IxConflict("Исходное подключение Linux не найдено", 404)
const existingId = companion ? companion.linux?.clientId : undefined
if (companion && (companion.kind === input.kind || existingId &&
site?.interfaces.some(binding => binding.linux?.clientId === existingId && binding.kind === input.kind))) {
throw new IxConflict("Этот протокол уже подключён для клиента")
}
const existingId = companion ? companion.linux?.clientId ?? await ixBondClientId(segment.id, input.serverId, companion.name) : undefined
const name = companion ? companion.linux!.name : input.name
const first = await configureIxLinuxTunnel(segment, { ...input, name })
const second = input.additionalGre ? await configureIxLinuxTunnel({ ...segment, configuration: first.configuration }, {
@@ -278,7 +275,7 @@ export async function configureIxLinuxClient(segment: IxSegment, input: IxLinuxC
}) : undefined
const result = second ?? first
const currentId = site?.interfaces.find(binding => binding.name === input.interfaceName)?.linux?.clientId
const clientId = existingId ?? currentId ?? (companion || second ? randomUUID() : undefined)
const clientId = existingId ?? currentId ?? input.vpsClientId ?? (companion || second ? randomUUID() : undefined)
if (!clientId) return result
const siblings = new Set([first.interfaceName, second?.interfaceName, companion ? companion.name : undefined])
return { interfaceName: first.interfaceName, configuration: {
@@ -304,11 +301,13 @@ async function configureIxLinuxTunnel(segment: IxSegment, input: IxLinuxClientRe
let localAddress = input.localAddress ?? currentTunnel?.localAddress
let peerAddress = input.peerAddress ?? currentTunnel?.peerAddress
if (!localAddress && !peerAddress) {
const occupiedBlocks = await ixReservedLinuxPoolBlocks()
const used = inventory.interfaces.flatMap(item => item.addresses).concat(reserved
.concat(segment.configuration.sites.flatMap(candidate => candidate.interfaces))
.flatMap(binding => [binding.provisionWireguard?.localAddress, binding.provisionGre?.localAddress,
binding.provisionTransit?.localAddress, ...binding.prefixes].filter(value => value !== undefined)))
for (let index = 0; index < 65536; index += 4) {
if (occupiedBlocks.has(index)) continue
const base = "10.254." + (index >> 8) + "."
const next = base + ((index & 255) + 1) + "/30"
if (used.some(network => inIxNetwork(network, next) || inIxNetwork(next, network))) continue
@@ -361,6 +360,10 @@ async function configureIxLinuxTunnel(segment: IxSegment, input: IxLinuxClientRe
localAddress, peerAddress, hubEndpoint: input.hubEndpoint }
} else {
if (isIP(input.peerEndpoint ?? "") !== 4 || isIP(input.hubEndpoint) !== 4) throw new IxConflict("Укажите два внешних IPv4 для GRE/IPsec", 400)
if (site.interfaces.some(item => item !== previous && item.kind === "gre-ipsec" &&
item.localEndpoint === input.hubEndpoint && item.endpoint === input.peerEndpoint)) {
throw new IxConflict("Эта пара внешних адресов уже используется для GRE/IPsec")
}
binding.endpoint = input.peerEndpoint
binding.localEndpoint = input.hubEndpoint
binding.provisionGre = { localAddress, peerAddress,
@@ -615,12 +618,13 @@ async function assertIxResume(id: string, revision: number, native: IxNativeChan
function verifyRemovalScope(id: string, device: NativeDevice, previous: IxRouterObject[]) {
const namespace = ixNamespace(id)
const managed = previous.filter(object => object.serverId === device.serverId)
const known = new Set(managed.map(objectMarker))
const known = new Set(managed.filter(object => object.fields.comment).map(objectMarker))
const named = new Set(managed.filter(object => !object.fields.comment && object.fields.name).map(objectMarker))
const interfaces = new Set(managed.filter(object => ["/interface/wireguard", "/interface/bridge", "/ip/vrf"].includes(object.path))
.map(object => object.fields.name))
for (const [path, rows] of Object.entries(device.rows)) {
if (path === "/interface") continue // RouterOS mirrors WireGuard and bridge objects here.
if (rows.some(row => !isTrue(row.dynamic) && !known.has(marker(path, row.comment ?? "")) &&
if (rows.some(row => !isTrue(row.dynamic) && !known.has(marker(path, row.comment ?? "")) && !named.has(marker(path, row.name ?? "")) &&
(row.comment?.startsWith(namespace + ":") || row["routing-table"] === namespace ||
[row.interface, row.bridge, row["in-interface"], row["out-interface"], ...(row.gateway?.split(/[@%]/) ?? [])].some(value => interfaces.has(value)) ||
[row["in-interface-list"], row["out-interface-list"]].includes(ixEgressList(id)) ||
@@ -631,6 +635,7 @@ function verifyRemovalScope(id: string, device: NativeDevice, previous: IxRouter
}
export async function prepareIxRemoval(id: string, revision: number) {
await assertIxSegmentWithoutBonds(id)
const segment = await readIxSegment(id)
if (!segment) throw new IxConflict("Сегмент IX не найден", 404)
assertIxRevision(segment, revision)
@@ -793,7 +798,7 @@ export async function observeIxLinuxPath(segment: IxSegment, serverId: number, n
})) }
}
export async function readIxLinuxClient(segment: IxSegment, serverId: number, name: string, includeCredential: boolean | "wireguard" = false): Promise<IxLinuxAccess> {
export async function readIxLinuxClient(segment: IxSegment, serverId: number, name: string, includeCredential: boolean | "wireguard" = false, transportOnly = false): 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)
@@ -825,7 +830,7 @@ export async function readIxLinuxClient(segment: IxSegment, serverId: number, na
throw new IxConflict("Действующий PSK не совпал с применённой ревизией. Выполните сверку")
}
}
return { ...clientInfo, kind: "gre-ipsec", ...ixGreClientTemplate(binding, serverId, peer, credential) }
return { ...clientInfo, kind: "gre-ipsec", ...ixGreClientTemplate(binding, serverId, peer, credential, transportOnly) }
}
if (ixLinuxBindingKind(binding) !== "wireguard") throw new IxConflict("Нет параметров WireGuard для Linux")
const wireguard = await readRows(client, "/interface/wireguard", ["name", "public-key", "listen-port", "comment", "disabled"])
@@ -854,7 +859,8 @@ export async function readIxLinuxClient(segment: IxSegment, serverId: number, na
...clientInfo,
kind: "wireguard",
filename: ixLinuxInterfaceName("ixw", serverId, binding) + ".conf",
template: ixWireguardClientTemplate(binding, iface?.["public-key"] ?? "", routes, privateKey),
hubPublicKey: iface?.["public-key"],
template: ixWireguardClientTemplate(binding, iface?.["public-key"] ?? "", routes, privateKey, transportOnly),
}
}
@@ -904,6 +910,7 @@ export async function removeIxSegment(id: string, revision: number, expectedDige
authorize = assertVerifiedConfigurationAccess) {
return withApplicationMutationLock(async () => {
await authorize()
await assertIxSegmentWithoutBonds(id)
const segment = await readIxSegment(id)
assertIxRevision(segment, revision)
const applied = segment?.appliedRevision ? await readIxRevision(id, segment.appliedRevision) : null
@@ -14,7 +14,8 @@ interface SegmentRow {
updated_at: Date
}
const columns = "id,revision,applied_revision,configuration,updated_at"
// VPS bond metadata has its own revision and never enters a RouterOS plan or segment export.
const columns = "id,revision,applied_revision,(configuration - 'linuxBonds') AS configuration,updated_at"
const visible = "(configuration->>'deleted') IS DISTINCT FROM 'true'"
function segment(row: SegmentRow): IxSegment {
return { id: row.id, revision: row.revision, appliedRevision: row.applied_revision,
@@ -41,6 +42,32 @@ export async function isIxSegmentArchived(id: string, revision: number) {
return rowCount === 1
}
export async function assertIxSegmentWithoutBonds(id: string) {
const { rowCount } = await pool.query(`SELECT 1 FROM ix_segments s
CROSS JOIN LATERAL jsonb_array_elements(s.configuration->'linuxBonds') g
WHERE (s.configuration->>'deleted') IS DISTINCT FROM 'true'
AND (s.id=$1::uuid OR EXISTS (SELECT FROM jsonb_array_elements(g->'members') m WHERE m->>'segmentId'=$1::text))
LIMIT 1`, [id])
if (rowCount) throw new IxConflict("Сначала исключите сегмент из групп туннелей Linux")
}
export async function ixBondClientId(segmentId: string, serverId: number, interfaceName: string) {
const { rows } = await pool.query<{ id: string }>(`SELECT g->>'clientId' AS id FROM ix_segments s
CROSS JOIN LATERAL jsonb_array_elements(s.configuration->'linuxBonds') g
WHERE (s.configuration->>'deleted') IS DISTINCT FROM 'true' AND g->'members' @> $1::jsonb LIMIT 1`,
[JSON.stringify([{ segmentId, serverId, interfaceName }])])
return rows[0]?.id
}
export async function ixKnownVpsClient(id: string) {
const { rowCount } = await pool.query(`SELECT 1 FROM ix_segments s
JOIN ix_segment_revisions r ON r.segment_id=s.id AND r.revision=s.applied_revision
WHERE (s.configuration->>'deleted') IS DISTINCT FROM 'true' AND
(s.configuration->'linuxBonds' @> $1::jsonb OR r.configuration->'sites' @> $2::jsonb) LIMIT 1`,
[JSON.stringify([{ clientId: id }]), JSON.stringify([{ interfaces: [{ linux: { clientId: id, enabled: true } }] }])])
return !!rowCount
}
export async function readIxRevision(id: string, revision: number) {
const { rows: [row] } = await pool.query("SELECT configuration FROM ix_segment_revisions WHERE segment_id=$1 AND revision=$2", [id, revision])
if (!row) throw new IxConflict("Ревизия IX не найдена", 404)
@@ -80,7 +107,7 @@ export async function ixReservedRouterIds(id?: string, sql: Pick<PoolClient, "qu
export async function ixReservedTunnelBindings(serverId: number) {
const { rows } = await pool.query<{ configuration: unknown }>(`
SELECT s.configuration FROM ix_segments s JOIN ix_segment_devices d ON d.segment_id=s.id
SELECT s.configuration - 'linuxBonds' AS configuration FROM ix_segments s JOIN ix_segment_devices d ON d.segment_id=s.id
WHERE d.server_id=$1 AND (s.configuration->>'deleted') IS DISTINCT FROM 'true'
UNION ALL
SELECT r.configuration FROM ix_segments s JOIN ix_segment_devices d ON d.segment_id=s.id
@@ -91,6 +118,23 @@ export async function ixReservedTunnelBindings(serverId: number) {
.flatMap(site => site.interfaces.filter(binding => site.serverId === serverId || binding.peerServerId === serverId)))
}
export async function ixReservedLinuxPoolBlocks() {
const { rows } = await pool.query<{ address: string }>(`
SELECT DISTINCT address
FROM ix_segments s LEFT JOIN ix_segment_revisions r ON r.segment_id=s.id AND r.revision=s.applied_revision
CROSS JOIN LATERAL jsonb_array_elements(COALESCE(s.configuration->'sites','[]'::jsonb) ||
COALESCE(r.configuration->'sites','[]'::jsonb)) site
CROSS JOIN LATERAL jsonb_array_elements(site->'interfaces') binding
CROSS JOIN LATERAL (VALUES
(split_part(COALESCE(binding->'provisionWireguard'->>'localAddress',binding->'provisionGre'->>'localAddress'),'/',1)),
(COALESCE(binding->'provisionWireguard'->>'peerAddress',binding->'provisionGre'->>'peerAddress'))) hosts(address)
WHERE (s.configuration->>'deleted') IS DISTINCT FROM 'true' AND binding ? 'linux' AND address LIKE '10.254.%'`)
return new Set(rows.map(row => {
const [, , third, last] = row.address.split(".").map(Number)
return third * 256 + (last & ~3)
}))
}
export function nextIxRouterId(used: ReadonlySet<string>) {
const [address, mask] = (process.env.MMAPP_IX_ROUTER_ID_POOL ?? "10.255.0.0/16").split("/")
const length = Number(mask)
@@ -134,7 +178,8 @@ export async function writeIxRevision(id: string, expected: number, configuratio
? await client.query<SegmentRow>(`INSERT INTO ix_segments(id,name,revision,configuration,applied_revision)
VALUES ($1,$2,$3,$4::jsonb,$5) ON CONFLICT DO NOTHING RETURNING ${columns}`,
[id, configuration.name, revision, JSON.stringify(configuration), applied ? revision : null])
: await client.query<SegmentRow>(`UPDATE ix_segments SET name=$2,revision=$3,configuration=$4::jsonb,
: await client.query<SegmentRow>(`UPDATE ix_segments SET name=$2,revision=$3,configuration=$4::jsonb ||
CASE WHEN configuration ? 'linuxBonds' THEN jsonb_build_object('linuxBonds', configuration->'linuxBonds') ELSE '{}'::jsonb END,
applied_revision=CASE WHEN $5::boolean THEN $3 ELSE applied_revision END,updated_at=now()
WHERE id=$1 AND revision=$6 AND ${visible} RETURNING ${columns}`,
[id, configuration.name, revision, JSON.stringify(configuration), applied, expected])
@@ -0,0 +1,42 @@
import assert from "node:assert/strict"
import { readFileSync } from "node:fs"
import { test } from "node:test"
import { ixBondBundleSchema, type IxSite } from "@mmapp/contracts/internet-exchange"
import { ixGreClientTemplate, ixWireguardClientTemplate } from "./internet-exchange-client.js"
const bundle = ixBondBundleSchema.parse(JSON.parse(readFileSync(
new URL("../../../packages/contracts/testdata/ix-bond-v1.json", import.meta.url), "utf8")))
test("the shared ix-client fixture accepts weighted members and rejects overlapping tunnel addresses", () => {
assert.deepEqual(bundle.members.map(path => path.weight), [3, 1])
const changed = structuredClone(bundle)
changed.members[0].probe = changed.members[1].address
assert.equal(ixBondBundleSchema.safeParse(changed).success, false)
const invalidKey = structuredClone(bundle)
invalidKey.members[0].peerPublicKey = "B".repeat(43) + "="
assert.equal(ixBondBundleSchema.safeParse(invalidKey).success, false)
})
test("group transport brings up an encrypted link without claiming routes used by other members", () => {
const [wg, gre] = bundle.members
const linux = { name: bundle.name, enabled: true, exit: "wan", destinations: [], peerEndpoint: "192.0.2.99" }
const binding: IxSite["interfaces"][number] = {
name: "wg-test", kind: "wireguard", linux, prefixes: [], provisionWireguard: {
listenPort: 51820, endpointPort: 51820, localAddress: wg.probe + "/30", peerAddress: wg.address,
hubEndpoint: wg.endpoint, peerPublicKey: wg.peerPublicKey!,
},
}
const wgConfig = ixWireguardClientTemplate(binding, wg.peerPublicKey!, bundle.destinations, undefined, true)
assert.match(wgConfig, /Table = off/)
assert.doesNotMatch(wgConfig, /PostUp|PreDown/)
assert.match(wgConfig, /0\.0\.0\.0\/0/)
assert.match(ixWireguardClientTemplate(binding, wg.peerPublicKey!, bundle.destinations), /Table = auto/)
const greConfig = ixGreClientTemplate({ name: "gre-test", kind: "gre-ipsec", linux, prefixes: [],
localEndpoint: gre.endpoint, endpoint: linux.peerEndpoint, provisionGre: {
localAddress: gre.probe + "/30", peerAddress: gre.address, credentialId: bundle.id,
} }, 17, undefined, undefined, true)
assert.match(greConfig.template, /start_action = trap/)
assert.match(greConfig.setup, /systemctl enable --now ix-gre-/)
assert.match(greConfig.setup, /ExecStart=.*ip address add 10\.123\.2\.2\/32/)
assert.doesNotMatch(greConfig.setup, /ip -[46] rule|route replace|secret =/)
})
+8
View File
@@ -64,6 +64,14 @@
- **Два протокола.** Отметьте WireGuard и GRE/IPsec при создании. Для существующего клиента откройте **Доступ и выход**, выберите свободный протокол и нажмите **Добавить туннель**. Туннели имеют отдельные адреса и ключи, входят в одну VRF сегмента на выбранном IX, настраиваются и отключаются отдельно. Для второго туннеля по умолчанию предложен доступ к разрешённым сетям. Если на VPS одновременно запущены оба туннеля с маршрутом по умолчанию, сгенерированные правила GRE направляют обычный трафик через GRE.
- **GRE/IPsec.** Укажите два фиксированных внешних IPv4-адреса. После применения скачайте конфиг strongSwan и скрипт GRE в одну папку на VPS. На Ubuntu установите `charon-systemd strongswan-swanctl`, запустите `sudo systemctl start strongswan` и выполните показанную в карточке команду `sudo sh ./…-setup.sh`. Скрипт копирует профиль с правами `0600`, устанавливает IKEv2/IPsec, создаёт GRE и использует отдельную таблицу для туннельных маршрутов. Транспорт до IX и ответы с внешнего IPv4 VPS, включая SSH, идут по основной таблице Linux.
### Несколько туннелей на одном VPS
1. Для каждого подключения WireGuard или GRE/IPsec откройте меню клиента и скачайте **Конфиг для группы ix-client**. Установите транспорт на VPS по инструкции в файлах. Можно использовать туннели к разным IX.
2. В разделе **Группы туннелей VPS** нажмите **Создать группу**. Выберите подключения одного семейства адресов с одинаковыми сетями назначения. Для резервирования поставьте основной первым, затем укажите резервы в порядке предпочтения. Для параллельной работы выберите равное распределение новых соединений или задайте веса. В прямые исключения внесите сети, к которым VPS должен обращаться через WAN.
3. Нажмите **Скачать для ix-client** и импортируйте JSON группы в `ix-client` через **B → I**. Нажмите **F2** для просмотра изменений, **Enter** для применения и **Y** для подтверждения. Без подтверждения через 60 секунд восстановится предыдущая конфигурация. Одиночные интерфейсы можно продолжать использовать отдельно.
Фактический активный путь, состояние резервов и распределение соединений видны на VPS в **B → Группы** или в выводе `sudo ix-client bond status`. Клиент раз в секунду посылает ICMP-пробу на внутренний адрес IX через каждый туннель, в том числе в отсутствие пользовательского трафика. Разрешите ответы на эти пробы. После трёх пропущенных ответов клиент исключает путь. Если резерв работает, клиент возвращает новые соединения на основной после 30 секунд устойчивых ответов. Уже открытое соединение через упавший туннель может потребовать переподключения. Ответы на входящие прямые соединения возвращаются через тот WAN, на который пришёл запрос.
### Выход и резерв
**Интернет с этого IX** использует действующий WAN из `main`. WAN остаётся в своей таблице, для клиента на этом выходе добавляются отдельные правила и обратный маршрут. **Добавить удалённый выход** готовит оба конца межузлового WireGuard с возвратом и IPv4 SNAT на целевом IX или ExitNode. Такой выход доступен в карточке клиента как группа шлюзов. В конфигурации группы можно выбрать другой интерфейс резерва или взять параметры заранее подготовленного выхода.
@@ -1,4 +1,6 @@
import { z } from "zod"
export * from "./ix-bond-management.js"
export * from "./ix-bond.js"
const key = z.string().regex(/^[a-z][a-z0-9-]{0,23}$/)
const interfaceName = z.string().regex(/^[A-Za-z0-9_.-]{1,48}$/)
@@ -141,6 +143,7 @@ export const ixLinuxClientRequest = z.object({
enabled: z.boolean().default(true),
kind: z.enum(["wireguard", "gre-ipsec"]),
additionalGre: z.boolean().optional(),
vpsClientId: z.uuid().optional(),
companionOf: interfaceName.optional(),
hubEndpoint: address,
peerEndpoint: address.optional(),
@@ -154,6 +157,8 @@ export const ixLinuxClientRequest = z.object({
rotate: z.boolean().optional(),
}).strict().refine(input => !input.transit || !input.exit || input.exit === input.transit.name,
{ path: ["exit"], message: "Выход клиента должен совпадать с выбранным транзитом" })
.refine(input => !input.vpsClientId || !input.interfaceName && !input.companionOf,
"Выбрать существующий VPS можно при создании подключения.")
.refine(input => (!input.companionOf || !input.interfaceName) &&
(!input.additionalGre || input.kind === "wireguard" && !input.interfaceName && !input.companionOf),
"Оба протокола можно создать для нового клиента. Для существующего добавьте второй протокол.")
@@ -215,6 +220,7 @@ export interface IxLinuxBinding {
}
export interface IxLinuxAccess {
hubPublicKey?: string
kind: IxLinuxBinding["kind"]
revision: number
filename: string
@@ -0,0 +1,32 @@
import { z } from "zod"
import { ixBondModeSchema } from "./ix-bond.js"
const memberRef = z.object({
segmentId: z.uuid(), serverId: z.number().int().positive().safe(),
interfaceName: z.string().regex(/^[A-Za-z0-9_.-]{1,48}$/),
appliedRevision: z.number().int().positive().safe(), weight: z.number().int().min(1).max(100),
}).strict()
export const ixBondEditSchema = z.object({
id: z.uuid().optional(), revision: z.number().int().nonnegative().safe(),
name: z.string().trim().min(1).max(80).regex(/^[^\x00-\x1f\x7f]+$/), mode: ixBondModeSchema,
directCidrs: z.array(z.union([z.cidrv4(), z.cidrv6()])).max(64),
members: z.array(memberRef).min(2).max(16),
}).strict().refine(value => !!value.id === (value.revision > 0), "Укажите текущую ревизию группы")
export type IxBondEdit = z.infer<typeof ixBondEditSchema>
export const ixSavedBondSchema = ixBondEditSchema.safeExtend({
id: z.uuid(), revision: z.number().int().positive().safe(), clientId: z.uuid(), ownerSegmentId: z.uuid(),
})
export type IxSavedBond = z.infer<typeof ixSavedBondSchema>
export interface IxBondCandidate extends Omit<IxBondEdit["members"][number], "weight"> {
segmentName: string
clientId?: string
name: string
kind: "wireguard" | "gre-ipsec"
endpoint: string
address: string
probe: string
destinations: string[]
}
export interface IxBondCatalog { groups: IxSavedBond[]; candidates: IxBondCandidate[] }
+49
View File
@@ -0,0 +1,49 @@
import { z } from "zod"
const ip = z.union([z.ipv4(), z.ipv6()])
const cidr = z.union([z.cidrv4(), z.cidrv6()])
export const ixBondModeSchema = z.enum(["failover", "equal", "weighted"])
const member = z.object({
interfaceName: z.string().regex(/^[a-zA-Z0-9_=-][a-zA-Z0-9_.=-]{0,14}$/),
kind: z.enum(["wireguard", "gre-ipsec"]),
address: ip,
probe: ip,
endpoint: ip,
weight: z.number().int().min(1).max(100),
// A 32-byte WireGuard key ends with two zero padding bits and one '='.
peerPublicKey: z.string().regex(/^[A-Za-z0-9+/]{42}[AEIMQUYcgkosw048]=$/)
.refine(key => key !== "A".repeat(43) + "=", "Недопустимый нулевой ключ WireGuard").optional(),
}).strict()
export const ixBondBundleSchema = z.object({
version: z.literal(1),
id: z.string().uuid(),
revision: z.number().int().positive().safe(),
clientId: z.string().uuid(),
name: z.string().trim().min(1).max(80).regex(/^[^\x00-\x1f\x7f]+$/),
mode: ixBondModeSchema,
destinations: z.array(cidr).min(1).max(64),
directCidrs: z.array(cidr).max(64),
members: z.array(member).min(2).max(16),
}).strict().superRefine((group, ctx) => {
const problem = (message: string) => ctx.addIssue({ code: "custom", message })
const names = new Set<string>()
const hosts = new Set<string>()
const ipv6 = group.destinations[0]?.includes(":")
if (group.destinations.some(prefix => prefix.includes(":") !== ipv6)) problem("Назначения должны быть одного семейства")
for (const path of group.members) {
if (names.has(path.interfaceName)) problem("Интерфейс повторяется в группе")
names.add(path.interfaceName)
for (const address of [path.address, path.probe]) {
if (address.includes(":") !== ipv6) problem("Адрес туннеля и назначения должны быть одного семейства")
const canonical = ipv6 && z.ipv6().safeParse(address).success ? new URL("http://[" + address + "]").hostname : address
if (hosts.has(canonical)) problem("Внутренние адреса путей должны быть уникальны")
hosts.add(canonical)
}
if (path.kind === "gre-ipsec" && path.peerPublicKey) problem("Ключ WireGuard указан для GRE")
}
})
export type IxBondMode = z.infer<typeof ixBondModeSchema>
export type IxBondBundle = z.infer<typeof ixBondBundleSchema>
export type IxBondMember = z.infer<typeof member>
+14
View File
@@ -0,0 +1,14 @@
{
"version": 1,
"id": "50b82c5c-4ada-4ffd-a907-510dce60ac50",
"revision": 1,
"clientId": "6761aeb0-7b3d-45f0-9bea-c6166839490b",
"name": "vps-01",
"mode": "weighted",
"destinations": ["0.0.0.0/0"],
"directCidrs": ["203.0.113.64/27"],
"members": [
{"interfaceName": "wg-ix-a", "kind": "wireguard", "address": "10.123.1.2", "probe": "10.123.1.1", "endpoint": "192.0.2.2", "weight": 3, "peerPublicKey": "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8="},
{"interfaceName": "gre-ix-b", "kind": "gre-ipsec", "address": "10.123.2.2", "probe": "10.123.2.1", "endpoint": "198.51.100.2", "weight": 1}
]
}
+52 -1
View File
@@ -1,6 +1,6 @@
import { readFile } from "node:fs/promises"
import { expect, test } from "@playwright/test"
import { ixChangeSchema, ixSegmentConfigurationSchema } from "@mmapp/contracts/internet-exchange"
import { ixBondEditSchema, ixChangeSchema, ixSegmentConfigurationSchema, type IxSavedBond } from "@mmapp/contracts/internet-exchange"
const id = "fa58fa40-4bcb-4616-9316-cb69463b3150"
const observedAt = "2026-11-20T00:00:00Z"
@@ -9,6 +9,53 @@ const nodes = [
{ id: 2, name: "ix-node-02", site: "TEST-2", country: "FI", enabled: true },
]
test("IX: сборка группы VPS из двух площадок с весами и исключением WAN", async ({ page }) => {
const remote = "0b59555b-c920-4b74-b350-977309a4b84a"
const segments = [id, remote].map((segmentId, i) => ({
id: segmentId, revision: 1, appliedRevision: 1, updatedAt: observedAt,
configuration: ixSegmentConfigurationSchema.parse({ name: "site-" + (i + 1),
sites: [{ serverId: nodes[i].id, autonomousSystem: 64512, routerId: "192.0.2." + (i + 1) }] }),
}))
const candidates = segments.map((s, i) => ({ segmentId: s.id, serverId: nodes[i].id,
interfaceName: i ? "gre-vps" : "wg-vps", appliedRevision: 1, segmentName: s.configuration.name, name: "vps",
kind: i ? "gre-ipsec" : "wireguard", endpoint: "192.0.2." + (i + 1), address: "10.0." + i + ".2", probe: "10.0." + i + ".1", destinations: ["0.0.0.0/0"] }))
let groups: IxSavedBond[] = []
await page.route("**/health", route => route.fulfill({ json: { ok: true } }))
await page.route("**/api/**", async route => {
const p = new URL(route.request().url()).pathname
const json = (body: unknown) => route.fulfill({ json: body })
if (p === "/api/auth/config") return json({ required: false })
if (p === "/api/ix/nodes") return json({ items: nodes })
if (p === "/api/ix/segments") return json({ items: segments })
if (p === "/api/ix/linux-bonds") return json({ groups, candidates })
if (p === "/api/ix/segments/" + id + "/linux-bonds") {
const body = ixBondEditSchema.parse(route.request().postDataJSON())
expect(body.members.map(m => [m.segmentId, m.weight])).toEqual([[remote, 3], [id, 1]])
expect(body.directCidrs).toEqual(["192.0.2.0/24"])
groups = [{ ...body, id: remote, revision: 1, clientId: id, ownerSegmentId: id }]
return json(groups[0])
}
return json({ items: [], revision: 1 })
})
await page.goto("/ix")
await page.getByRole("button", { name: "site-1", exact: true }).click()
await page.getByRole("button", { name: "Создать группу", exact: true }).click()
const editor = page.getByRole("dialog", { name: "Группа туннелей VPS" })
await editor.getByLabel("Имя группы").fill("vps-01")
await editor.getByLabel("Режим", { exact: true }).click()
await page.getByRole("option", { name: "Параллельно, по весам" }).click()
for (const match of [/wg-vps/, /gre-vps/]) {
await editor.getByLabel("Добавить туннель этого VPS").click()
await page.getByRole("option", { name: match }).click()
}
await editor.getByRole("button", { name: "Выше" }).last().click()
await editor.getByLabel("Вес", { exact: true }).first().fill("3")
await editor.getByLabel("Прямой выход для сетей (CIDR)").fill("192.0.2.0/24")
await editor.getByRole("button", { name: "Сохранить" }).click()
await expect(page.getByText("vps-01 · Параллельно, по весам")).toBeVisible()
await expect(page.getByRole("button", { name: "Скачать для ix-client" })).toBeVisible()
})
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" }] },
@@ -24,6 +71,7 @@ test("IX: редактирование и применение сохранён
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/linux-bonds") return json({ groups: [], candidates: [] })
if (path === "/api/ix/nodes") return json({ items: nodes, peers: nodes })
if (/\/api\/ix\/nodes\/\d+\/inventory$/.test(path)) return json({ observedAt, routerId: "10.255.0.1", defaultRoutes: [], wireguardPorts: [],
interfaces: [{ name: "wg-member", type: "wg", running: true, disabled: false, addresses: [], restriction: null }] })
@@ -146,6 +194,7 @@ test("IX: черновик удаляется после подтвержден
const path = new URL(request.url()).pathname
if (path === "/api/auth/config") return route.fulfill({ json: { required: false } })
if (path === "/api/ix/nodes") return route.fulfill({ json: { items: nodes } })
if (path === "/api/ix/linux-bonds") return route.fulfill({ json: { groups: [], candidates: [] } })
if (path === "/api/ix/segments") return route.fulfill({ json: { items: deleted ? [] : [draft] } })
if (path === `/api/ix/segments/${id}/removal-plan`) {
expect(request.postDataJSON()).toEqual({ revision: 1 })
@@ -187,6 +236,7 @@ test("IX: новый сегмент сохраняется одним подтв
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[0]] })
if (path === "/api/ix/linux-bonds") return json({ groups: [], candidates: [] })
if (path === "/api/ix/segments" && req.method() === "POST") {
const change = ixChangeSchema.parse(req.postDataJSON())
expect(change.configuration.sites[0]).toMatchObject({ serverId: 1, autoRouterId: true })
@@ -237,6 +287,7 @@ for (const mode of ["WAN IX", "два протокола", "новый ExitNode"
const json = (body: unknown) => route.fulfill({ json: body })
if (path === "/api/auth/config") return json({ required: false })
if (path === "/api/ix/nodes") return json({ items: nodes, peers: [...nodes, { id: 3, name: "exit-arn", type: "exit-node", enabled: true }] })
if (path === "/api/ix/linux-bonds") return json({ groups: [], candidates: [] })
if (path === "/api/ix/nodes/3/inventory") return json({ interfaces: [{ name: "wan", disabled: false, addresses: manual ? ["192.0.2.12/24", "192.0.2.13/24"] : ["192.0.2.13/24"] }],
defaultRoutes: [{ family: 4, interface: "wan" }] })
if (path === "/api/ix/nodes/1/inventory") return json({ observedAt, routerId: "10.255.0.1", wireguardPorts: [],