Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1337325697 | ||
|
|
f9b742b730 | ||
|
|
b395c06ffb | ||
|
|
2da1b17b65 | ||
|
|
876a61f705 | ||
|
|
545a9bbcd2 | ||
|
|
37025f1f94 | ||
|
|
c49e01299c | ||
|
|
187a0cd45e | ||
|
|
731c19a14d | ||
|
|
94c50b9660 | ||
|
|
fc39b0da3c | ||
|
|
3c06a72349 | ||
|
|
ea13365f37 | ||
|
|
8a962c1984 | ||
|
|
0a568f1640 | ||
|
|
5233a9f194 | ||
|
|
645045a5d5 | ||
|
|
b896e469a7 | ||
|
|
c44bcd8f59 | ||
|
|
ed7b1e0350 | ||
|
|
4097e1a6fc | ||
|
|
7cf17c7283 | ||
|
|
4eafc78c8e | ||
|
|
d174bca5d6 | ||
|
|
2ca40fbb4d | ||
|
|
589fc782f9 | ||
|
|
fcbf219725 | ||
|
|
95a0ebeb18 | ||
|
|
2b0b9a5fa5 | ||
|
|
9b2c2327a6 | ||
|
|
ec2fb54e04 | ||
|
|
c94d417f1b | ||
|
|
63c0fc6506 | ||
|
|
682d6c8d55 | ||
|
|
a41c70b104 | ||
|
|
dd6e6b0b77 | ||
|
|
a4694b8481 | ||
|
|
640726aa86 | ||
|
|
67b1d9cde2 | ||
|
|
8781f68674 | ||
|
|
5fd028800a | ||
|
|
01779d7ee6 | ||
|
|
1b927dcf68 | ||
|
|
af82497f20 | ||
|
|
ca65969728 | ||
|
|
ee6fd675ac | ||
|
|
5a46594ec9 | ||
|
|
31f75a8eed | ||
|
|
2a759ae5e5 | ||
|
|
fad89c7059 | ||
|
|
350ae34862 | ||
|
|
676be13251 | ||
|
|
ca1bc1ab38 | ||
|
|
d9f623ccda | ||
|
|
9951035448 | ||
|
|
95be5178d0 | ||
|
|
c9152bb106 | ||
|
|
ef3d7b6779 |
No files matched your search
+394
-306
@@ -1,349 +1,437 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { useEffect, useMemo, useState } from "react"
|
||||
import Link from "next/link"
|
||||
import {
|
||||
ActivityIcon,
|
||||
BellIcon,
|
||||
CableIcon,
|
||||
FilterIcon,
|
||||
GitMergeIcon,
|
||||
HardDriveIcon,
|
||||
ChartColumnIcon,
|
||||
CircleAlertIcon,
|
||||
HeartPulseIcon,
|
||||
MapIcon,
|
||||
LayoutDashboardIcon,
|
||||
ServerIcon,
|
||||
ShieldIcon,
|
||||
SlidersHorizontalIcon,
|
||||
TableIcon,
|
||||
} from "lucide-react"
|
||||
import { Button, buttonVariants } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuCheckboxItem,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
||||
import { Alert, AlertAction, AlertDescription, AlertTitle } from "@/components/reui/alert"
|
||||
import { Badge } from "@/components/reui/badge"
|
||||
import { PageHeader } from "@/components/page-header"
|
||||
import { OpsPanel } from "@/components/ops-panel"
|
||||
import { KpiStatGrid } from "@/components/reui-kit/kpi-stat-grid"
|
||||
import { QuickActionGrid } from "@/components/reui-kit/quick-action-grid"
|
||||
import { AttentionQueue } from "@/components/reui-kit/attention-queue"
|
||||
import { PageTitle } from "@/components/page-title"
|
||||
import { DataFreshness } from "@/components/data-freshness"
|
||||
import { EmptyState } from "@/components/empty-state"
|
||||
import { CapacityGrid, SectionFrame, SparkKpiGrid, ToneBadge, seriesDelta, type Tone } from "@/components/reui-kit/ops-blocks"
|
||||
import { TrafficRxTxChart } from "@/components/reui-kit/traffic-rx-tx-chart"
|
||||
import { LatencyChart } from "@/components/dashboard/latency-chart"
|
||||
import { DashboardEventsTimeline } from "@/components/dashboard/dashboard-events-timeline"
|
||||
import { InternetPathPanel } from "@/components/dashboard/internet-path-panel"
|
||||
import { DashboardSourcesSummary, dashboardSourceRows, sourceErrorText } from "@/components/dashboard/dashboard-sources-summary"
|
||||
import {
|
||||
DashboardAttentionGrid,
|
||||
DashboardHealth,
|
||||
DashboardIncidents,
|
||||
DashboardQuickLinks,
|
||||
type AttentionGridRow,
|
||||
} from "@/components/dashboard/dashboard-overview-blocks"
|
||||
import { DashboardActiveProbesDataGrid } from "@/components/data-grids/dashboard-active-probes-data-grid"
|
||||
import { EmptyState } from "@/components/empty-state"
|
||||
import { DashboardDataStatus } from "@/components/dashboard/dashboard-data-status"
|
||||
import { Badge } from "@/components/reui/badge"
|
||||
import { buttonVariants } from "@/components/ui/button"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { fmtRate } from "@/lib/fmt-rate"
|
||||
import { DASHBOARD_SOURCES, type DashboardSource, type DashboardSources } from "@/lib/dashboard-source-state"
|
||||
import { useDashboardLive, type AttentionRow } from "@/hooks/use-dashboard-live"
|
||||
|
||||
const WIDGETS = {
|
||||
cap: "Ёмкость",
|
||||
spark: "Показатели",
|
||||
sources: "Сводка источников",
|
||||
health: "Здоровье сети",
|
||||
timeline: "Лента инцидентов",
|
||||
path: "Internet path",
|
||||
attention: "Требует внимания",
|
||||
latency: "Задержка до серверов",
|
||||
traffic: "Пропускная способность",
|
||||
probes: "Активные пробы",
|
||||
links: "Быстрые переходы",
|
||||
} as const
|
||||
type Widget = keyof typeof WIDGETS
|
||||
const HIDDEN_WIDGETS_LS = "mm:dashboard-hidden-widgets"
|
||||
|
||||
function useHiddenWidgets() {
|
||||
const [hidden, setHidden] = useState<Set<Widget>>(new Set())
|
||||
useEffect(() => {
|
||||
try {
|
||||
const raw = JSON.parse(localStorage.getItem(HIDDEN_WIDGETS_LS) ?? "[]")
|
||||
if (Array.isArray(raw)) queueMicrotask(() => setHidden(new Set(raw.filter((key): key is Widget => key in WIDGETS))))
|
||||
} catch {
|
||||
/* повреждённое значение — показываем все виджеты */
|
||||
}
|
||||
}, [])
|
||||
function toggle(key: Widget, visible: boolean) {
|
||||
setHidden((previous) => {
|
||||
const next = new Set(previous)
|
||||
if (visible) next.delete(key)
|
||||
else next.add(key)
|
||||
try {
|
||||
localStorage.setItem(HIDDEN_WIDGETS_LS, JSON.stringify([...next]))
|
||||
} catch {
|
||||
/* хранилище недоступно — настройка действует до перезагрузки */
|
||||
}
|
||||
return next
|
||||
})
|
||||
}
|
||||
return { hidden, toggle }
|
||||
}
|
||||
|
||||
function fmtIntRu(n: number): string {
|
||||
return n.toLocaleString("ru-RU")
|
||||
}
|
||||
|
||||
function AttentionRows({ rows }: { rows: AttentionRow[] }) {
|
||||
const [expanded,setExpanded]=useState(false)
|
||||
const [visible,setVisible]=useState(55)
|
||||
function renderRow(row: AttentionRow) {
|
||||
return (
|
||||
<Link
|
||||
key={row.id}
|
||||
href={row.href}
|
||||
className="hover:bg-muted/40 focus-visible:ring-ring flex min-w-0 items-start justify-between gap-2 rounded-md px-1 py-1.5 focus-visible:ring-2"
|
||||
>
|
||||
<span className="min-w-0 wrap-anywhere text-sm font-medium">{row.title}</span>
|
||||
<Badge
|
||||
size="sm"
|
||||
variant={row.tone === "warning" ? "warning-light" : "destructive-light"}
|
||||
className="shrink-0"
|
||||
>
|
||||
{row.hint}
|
||||
</Badge>
|
||||
</Link>
|
||||
)
|
||||
function averageSeries(series: Record<string, (number | null)[]>): number[] {
|
||||
const rows = Object.values(series)
|
||||
const length = Math.max(0, ...rows.map((values) => values.length))
|
||||
const out: number[] = []
|
||||
for (let i = 0; i < length; i++) {
|
||||
const values = rows.map((row) => row[i]).filter((v): v is number => typeof v === "number" && Number.isFinite(v))
|
||||
if (values.length) out.push(values.reduce((sum, v) => sum + v, 0) / values.length)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-0.5">
|
||||
{rows.slice(0, 5).map(renderRow)}
|
||||
{rows.length > 5 && (
|
||||
<details onToggle={event=>{setExpanded(event.currentTarget.open);if(!event.currentTarget.open)setVisible(55)}}>
|
||||
<summary className="cursor-pointer rounded-md px-1 py-2 text-xs text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring">Ещё {rows.length - 5}</summary>
|
||||
{expanded && rows.slice(5,visible).map(renderRow)}
|
||||
{expanded && rows.length>visible && <Button type="button" variant="ghost" size="sm" onClick={()=>setVisible(count=>Math.min(count+50,rows.length))}>Показать ещё {Math.min(50,rows.length-visible)}</Button>}
|
||||
</details>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
function toGridRows(rows: AttentionRow[], kind: AttentionGridRow["kind"]): AttentionGridRow[] {
|
||||
return rows.map((row) => ({
|
||||
id: row.id,
|
||||
title: row.title,
|
||||
kind,
|
||||
hint: row.hint,
|
||||
href: row.href,
|
||||
tone: row.tone === "destructive" ? "er" : "wn",
|
||||
confirmed: row.hint !== "Статус неизвестен",
|
||||
}))
|
||||
}
|
||||
|
||||
export default function DashboardPage() {
|
||||
const dash = useDashboardLive()
|
||||
const { hidden, toggle } = useHiddenWidgets()
|
||||
const [tab, setTab] = useState("over")
|
||||
const [mockAt] = useState(() => Date.now())
|
||||
const show = (key: Widget) => !hidden.has(key)
|
||||
|
||||
// Демо-режим не опрашивает API: показываем источники полученными в момент открытия страницы.
|
||||
const sources: DashboardSources = useMemo(
|
||||
() => dash.isLive ? dash.sources : Object.fromEntries((Object.keys(DASHBOARD_SOURCES) as DashboardSource[]).map((key) => [key, { receivedAt: mockAt, error: null }])),
|
||||
[dash.isLive, dash.sources, mockAt],
|
||||
)
|
||||
const sourceRows = dashboardSourceRows(sources)
|
||||
const failedSources = sourceRows.filter((row) => row.error)
|
||||
const received = sourceRows.map((row) => row.receivedAt).filter((at): at is number => at != null)
|
||||
const freshAt = received.length ? Math.max(...received) : null
|
||||
|
||||
const offline = dash.offlineCount
|
||||
const health = dash.probeDown + dash.probeWarn
|
||||
const problems = dash.probeDown + dash.probeWarn
|
||||
const serverTrouble = offline > 0 || dash.unknownServerCount > 0 || dash.degradedServerCount > 0
|
||||
const serverCaption = !dash.availability.servers ? "нет данных" : !dash.isLive
|
||||
? "демо"
|
||||
: serverTrouble
|
||||
? [offline > 0 ? `${offline} не в сети` : null, dash.unknownServerCount > 0 ? `Статус неизвестен: ${dash.unknownServerCount}` : null, dash.degradedServerCount > 0 ? `Ухудшение: ${dash.degradedServerCount}` : null].filter(Boolean).join(" · ")
|
||||
: dash.totalServers > 0 ? "все в сети" : "нет серверов"
|
||||
|
||||
const latencySeries = dash.latency.kind === "mock" || dash.latency.kind === "live" ? averageSeries(dash.latency.series) : []
|
||||
const rttNow = latencySeries.length ? Math.round(latencySeries[latencySeries.length - 1]) : null
|
||||
|
||||
const probesMeasured = useMemo(() => dash.enabledProbes.filter((p) => p.status !== "unknown"), [dash.enabledProbes])
|
||||
const avgLoss = probesMeasured.length ? probesMeasured.reduce((sum, p) => sum + (p.loss ?? 0), 0) / probesMeasured.length : null
|
||||
const okSources = sourceRows.filter((row) => row.tone === "ok").length
|
||||
|
||||
const attentionRows = [
|
||||
...toGridRows(dash.attentionServers, "Сервер"),
|
||||
...toGridRows(dash.attentionOverlay, "Туннель"),
|
||||
...toGridRows(dash.attentionProbes, "Проверка"),
|
||||
]
|
||||
const emptyNotes = [
|
||||
dash.attentionServers.length ? null : dash.reliable.servers ? (dash.totalServers > 0 ? "Серверы без проблем" : "Нет серверов") : "Серверы: состояние не подтверждено",
|
||||
dash.attentionOverlay.length ? null : dash.reliable.overlay ? (dash.overlay.total > 0 ? "Туннели работают" : "Нет туннелей") : "Туннели: состояние не подтверждено",
|
||||
dash.attentionProbes.length ? null : dash.reliable.probes ? (dash.probeCount > 0 ? "Проверки без ошибок" : "Нет активных проверок") : "Проверки: состояние не подтверждено",
|
||||
].filter((note): note is string => note != null)
|
||||
|
||||
const latencyBody = dash.latency.kind === "loading" ? (
|
||||
<div className="bg-muted/50 h-[220px] w-full animate-pulse rounded-md" />
|
||||
) : dash.latency.kind === "empty" ? (
|
||||
<p className="text-muted-foreground px-4 py-10 text-center text-sm">{dash.latency.message}</p>
|
||||
) : (
|
||||
<LatencyChart series={dash.latency.series} labels={dash.latency.labels} />
|
||||
)
|
||||
const latencyDescription = dash.latency.kind === "mock" || dash.latency.kind === "live" ? dash.latency.subtitle : dash.latency.kind === "loading" ? "Загрузка…" : "Нет серии RTT"
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col">
|
||||
<PageHeader crumbs={[{ label: "Обзор" }, { label: "Дашборд" }]} />
|
||||
<PageHeader crumbs={[{ label: "Главная", href: "/dashboard" }, { label: "Обзор" }, { label: "Дашборд" }]} status={<DataFreshness at={freshAt} live={dash.isLive} />} />
|
||||
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
<div className="flex flex-col gap-4 px-4 py-4 md:gap-6 md:px-6 md:py-5">
|
||||
{dash.isLive && <DashboardDataStatus sources={dash.sources} refreshing={dash.refreshing} onRefresh={dash.retry} />}
|
||||
|
||||
<KpiStatGrid
|
||||
aria-label="Сводка дашборда"
|
||||
isLoading={dash.loading}
|
||||
items={[
|
||||
{
|
||||
id: "fleet",
|
||||
label: "Серверы онлайн",
|
||||
value: dash.availability.servers ? `${dash.onlineCount} / ${dash.totalServers}` : "—",
|
||||
hint: !dash.availability.servers ? "нет данных" : !dash.isLive
|
||||
? "демо"
|
||||
: offline > 0 || dash.unknownServerCount > 0 || dash.degradedServerCount > 0
|
||||
? [offline > 0 ? `${offline} не в сети` : null,dash.unknownServerCount > 0 ? `Статус неизвестен: ${dash.unknownServerCount}` : null,dash.degradedServerCount > 0 ? `Ухудшение: ${dash.degradedServerCount}` : null].filter(Boolean).join(" · ")
|
||||
: dash.totalServers > 0
|
||||
? "все в сети"
|
||||
: "нет серверов",
|
||||
href: "/servers",
|
||||
icon: <ServerIcon />,
|
||||
iconClassName: "text-muted-foreground",
|
||||
variant: offline > 0 || dash.unknownServerCount > 0 || dash.degradedServerCount > 0 ? "warning" : "default",
|
||||
},
|
||||
{
|
||||
id: "overlay",
|
||||
label: "Туннели работают",
|
||||
value: dash.availability.overlay ? String(dash.overlay.up) : "—",
|
||||
hint: !dash.availability.overlay ? "не все источники доступны" : !dash.reliable.overlay ? "Последний успешный снимок; не все источники обновлены" : dash.overlay.total > 0 ? `Не работают: ${dash.overlay.down}` : "нет туннелей",
|
||||
href: "/gre",
|
||||
icon: <CableIcon />,
|
||||
iconClassName: "text-info",
|
||||
variant: dash.overlay.down > 0 ? "warning" : "default",
|
||||
},
|
||||
{
|
||||
id: "bgp",
|
||||
label: "Префиксы BGP",
|
||||
value: dash.bgp?.prefixSum != null ? fmtIntRu(dash.bgp.prefixSum) : "—",
|
||||
hint: dash.bgp ? `Сессий установлено: ${dash.bgp.establishedCount ?? "неизвестно"}${dash.bgp.prefixSum === null ? " · префиксы неизвестны" : ""}` : "нет данных",
|
||||
href: "/bgp",
|
||||
icon: <GitMergeIcon />,
|
||||
iconClassName: "text-primary",
|
||||
},
|
||||
{
|
||||
id: "health",
|
||||
label: "Проверки с проблемами",
|
||||
value: dash.availability.probes && dash.unknownProbeCount===0 ? String(health) : "—",
|
||||
hint: dash.availability.probes ? `${dash.probeDown} ошибок · ${dash.probeWarn} предупреждений${dash.unknownProbeCount>0?` · неизвестны: ${dash.unknownProbeCount}`:""}` : "нет данных",
|
||||
href: "/uptime",
|
||||
icon: <BellIcon />,
|
||||
iconClassName: health > 0 ? "text-destructive" : "text-muted-foreground",
|
||||
variant: health > 0 ? "destructive" : "default",
|
||||
},
|
||||
]}
|
||||
<div className="flex flex-col gap-6 px-4 pt-5 pb-10 md:px-7 md:pt-6">
|
||||
<PageTitle
|
||||
icon={<LayoutDashboardIcon />}
|
||||
title="Дашборд"
|
||||
description="Здоровье сети: индекс, события за период, Internet path, пробы и источники"
|
||||
actions={
|
||||
<>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger render={<Button type="button" variant="outline"><SlidersHorizontalIcon data-icon="inline-start" />Настроить виджеты</Button>} />
|
||||
<DropdownMenuContent align="end" className="w-60">
|
||||
<DropdownMenuGroup>
|
||||
<DropdownMenuLabel>Виджеты дашборда</DropdownMenuLabel>
|
||||
{(Object.keys(WIDGETS) as Widget[]).map((key) => (
|
||||
<DropdownMenuCheckboxItem key={key} checked={show(key)} onCheckedChange={(value) => toggle(key, !!value)}>
|
||||
{WIDGETS[key]}
|
||||
</DropdownMenuCheckboxItem>
|
||||
))}
|
||||
</DropdownMenuGroup>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<Button type="button" onClick={dash.retry} disabled={dash.refreshing}>Обновить данные</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
|
||||
<section aria-labelledby="dashboard-attention-title" className="flex min-w-0 flex-col gap-2">
|
||||
<h2 id="dashboard-attention-title" className="text-sm font-semibold">Требует внимания</h2>
|
||||
<AttentionQueue
|
||||
className="lg:grid-cols-3"
|
||||
columns={[
|
||||
{
|
||||
id: "nodes",
|
||||
title: "Серверы",
|
||||
icon: ServerIcon,
|
||||
count: dash.attentionServers.length,
|
||||
countVariant: "warning-light",
|
||||
emptyTitle: dash.reliable.servers ? (dash.totalServers > 0 ? "Серверы без проблем" : "Нет серверов") : "Состояние не подтверждено",
|
||||
emptyDescription: dash.reliable.servers ? "Нет включённых серверов с ошибками доступности." : "Проверьте состояние источников выше.",
|
||||
children: <AttentionRows rows={dash.attentionServers} />,
|
||||
},
|
||||
{
|
||||
id: "overlay",
|
||||
title: "Туннели",
|
||||
icon: CableIcon,
|
||||
iconClassName: "text-info",
|
||||
count: dash.attentionOverlay.length,
|
||||
countVariant: "destructive-light",
|
||||
emptyTitle: dash.reliable.overlay ? (dash.overlay.total > 0 ? "Туннели работают" : "Нет туннелей") : "Состояние не подтверждено",
|
||||
emptyDescription: dash.reliable.overlay ? "В GRE, WireGuard и VXLAN проблем не обнаружено." : "Проверьте состояние источников выше.",
|
||||
children: <AttentionRows rows={dash.attentionOverlay} />,
|
||||
},
|
||||
{
|
||||
id: "probes",
|
||||
title: "Проверки",
|
||||
icon: HeartPulseIcon,
|
||||
iconClassName: "text-destructive",
|
||||
count: dash.attentionProbes.length,
|
||||
countVariant: "destructive-light",
|
||||
emptyTitle: dash.reliable.probes ? (dash.probeCount > 0 ? "Проверки без ошибок" : "Нет активных проверок") : "Состояние не подтверждено",
|
||||
emptyDescription: dash.reliable.probes ? "Нет ошибок и предупреждений активных проверок." : "Проверьте состояние источников выше.",
|
||||
children: <AttentionRows rows={dash.attentionProbes} />,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</section>
|
||||
<div className="flex flex-col gap-5">
|
||||
{failedSources.length > 0 ? (
|
||||
<Alert variant="warning">
|
||||
<CircleAlertIcon />
|
||||
<AlertTitle>Не все источники доступны.</AlertTitle>
|
||||
<AlertDescription>
|
||||
Последний успешный снимок; не все источники обновлены. Не обновлены: {failedSources.map((row) => row.name).join(", ")}. Проверьте состояние источников ниже.
|
||||
</AlertDescription>
|
||||
<AlertAction>
|
||||
<Button type="button" size="sm" variant="outline" onClick={() => setTab("src")}>Объяснить</Button>
|
||||
</AlertAction>
|
||||
</Alert>
|
||||
) : null}
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 lg:grid-cols-[2fr_1fr]">
|
||||
<OpsPanel
|
||||
title="Задержка до серверов"
|
||||
description={
|
||||
dash.latency.kind === "mock" || dash.latency.kind === "live"
|
||||
? dash.latency.subtitle
|
||||
: dash.latency.kind === "loading"
|
||||
? "Загрузка…"
|
||||
: "Нет серии RTT"
|
||||
}
|
||||
contentClassName="px-3 pb-3"
|
||||
>
|
||||
{dash.latency.kind === "loading" && (
|
||||
<div className="bg-muted/50 h-[220px] w-full animate-pulse rounded-md" />
|
||||
)}
|
||||
{dash.latency.kind === "empty" && (
|
||||
<p className="text-muted-foreground px-4 py-10 text-center text-sm">{dash.latency.message}</p>
|
||||
)}
|
||||
{(dash.latency.kind === "mock" || dash.latency.kind === "live") && (
|
||||
<LatencyChart series={dash.latency.series} labels={dash.latency.labels} />
|
||||
)}
|
||||
</OpsPanel>
|
||||
|
||||
<OpsPanel
|
||||
title="Последние события"
|
||||
description="Система и BGP"
|
||||
headerRight={
|
||||
<Link href="/alerts" className={cn(buttonVariants({ variant: "ghost", size: "sm" }), "h-7 text-xs")}>
|
||||
Все →
|
||||
</Link>
|
||||
}
|
||||
>
|
||||
<DashboardEventsTimeline
|
||||
events={dash.recentEvents}
|
||||
loading={dash.eventsLoading}
|
||||
error={dash.eventsError}
|
||||
{show("cap") ? (
|
||||
<CapacityGrid
|
||||
label="Ёмкость сети"
|
||||
items={[
|
||||
{
|
||||
id: "fleet",
|
||||
title: "Серверы онлайн",
|
||||
caption: serverCaption,
|
||||
value: dash.availability.servers ? dash.onlineCount : null,
|
||||
total: dash.availability.servers ? dash.totalServers : null,
|
||||
tone: serverTrouble ? "wn" : "ok",
|
||||
icon: <ServerIcon />,
|
||||
href: "/servers",
|
||||
},
|
||||
{
|
||||
id: "overlay",
|
||||
title: "Туннели работают",
|
||||
caption: !dash.availability.overlay ? "не все источники доступны" : !dash.reliable.overlay ? "Последний успешный снимок; не все источники обновлены" : dash.overlay.total > 0 ? `GRE · WireGuard · VXLAN · не работают: ${dash.overlay.down}` : "нет туннелей",
|
||||
value: dash.availability.overlay ? dash.overlay.up : null,
|
||||
total: dash.availability.overlay ? dash.overlay.total : null,
|
||||
tone: dash.overlay.down > 0 ? "wn" : "ok",
|
||||
icon: <CableIcon />,
|
||||
href: "/gre",
|
||||
},
|
||||
{
|
||||
id: "health",
|
||||
title: "Проверки с проблемами",
|
||||
caption: dash.availability.probes ? `${dash.probeDown} ошибок · ${dash.probeWarn} предупреждений${dash.unknownProbeCount > 0 ? ` · неизвестны: ${dash.unknownProbeCount}` : ""}` : "нет данных",
|
||||
value: dash.availability.probes && dash.unknownProbeCount === 0 ? problems : null,
|
||||
total: dash.availability.probes && dash.unknownProbeCount === 0 ? dash.probeCount : null,
|
||||
tone: problems > 0 ? "er" : "ok",
|
||||
icon: <HeartPulseIcon />,
|
||||
href: "/uptime",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</OpsPanel>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div>
|
||||
<OpsPanel
|
||||
title="Пропускная способность"
|
||||
description={dash.traffic?.demo ? "Суммарный RX / TX · демо" : "Суммарная история RX / TX · 1 ч; значения — последний измеренный снимок"}
|
||||
headerRight={<Link href="/traffic" className={cn(buttonVariants({ variant: "outline", size: "sm" }), "h-7 text-xs")}>Трафик →</Link>}
|
||||
contentClassName="px-3 pb-3"
|
||||
>
|
||||
{dash.loading && !dash.traffic ? (
|
||||
<div className="bg-muted/50 h-[220px] w-full animate-pulse rounded-md" />
|
||||
) : !dash.traffic ? (
|
||||
<p className="text-muted-foreground px-4 py-10 text-center text-sm">
|
||||
Нет данных трафика за последний час.{" "}
|
||||
<Link href="/traffic" className="underline underline-offset-2">
|
||||
Открыть трафик
|
||||
</Link>
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<div className="flex flex-wrap items-center gap-3 px-2 py-3 text-xs">
|
||||
{dash.traffic.demo ? <Badge variant="outline" size="sm">демо</Badge> : !dash.traffic.observationsKnown ? <Badge variant="outline" size="sm">Измерения не подтверждены API</Badge> : null}
|
||||
<span className="tabular-nums">RX {dash.traffic.rxNow===null?"—":fmtRate(dash.traffic.rxNow)}</span>
|
||||
<span className="tabular-nums">TX {dash.traffic.txNow===null?"—":fmtRate(dash.traffic.txNow)}</span>
|
||||
{show("spark") ? (
|
||||
<SparkKpiGrid
|
||||
label="Показатели сети"
|
||||
items={[
|
||||
{
|
||||
id: "bgp",
|
||||
title: "Префиксы BGP",
|
||||
value: dash.bgp?.prefixSum != null ? fmtIntRu(dash.bgp.prefixSum) : "—",
|
||||
footnote: dash.bgp ? `Сессий установлено: ${dash.bgp.establishedCount ?? "неизвестно"}${dash.bgp.prefixSum === null ? " · префиксы неизвестны" : ""}` : "нет данных",
|
||||
href: "/bgp",
|
||||
},
|
||||
{
|
||||
id: "rtt",
|
||||
title: "Средний RTT",
|
||||
value: rttNow ?? "—",
|
||||
unit: rttNow != null ? " мс" : undefined,
|
||||
series: latencySeries,
|
||||
delta: seriesDelta(latencySeries, "wn", "ok"),
|
||||
footnote: "за 1 ч",
|
||||
href: "/uptime",
|
||||
},
|
||||
{
|
||||
id: "rx",
|
||||
title: "RX",
|
||||
value: dash.traffic?.rxNow != null ? fmtRate(dash.traffic.rxNow) : "—",
|
||||
series: dash.traffic?.rx.filter((v): v is number => typeof v === "number"),
|
||||
delta: seriesDelta(dash.traffic?.rx.filter((v): v is number => typeof v === "number")),
|
||||
footnote: "суммарно · 1 ч",
|
||||
href: "/traffic",
|
||||
},
|
||||
{
|
||||
id: "tx",
|
||||
title: "TX",
|
||||
value: dash.traffic?.txNow != null ? fmtRate(dash.traffic.txNow) : "—",
|
||||
series: dash.traffic?.tx.filter((v): v is number => typeof v === "number"),
|
||||
delta: seriesDelta(dash.traffic?.tx.filter((v): v is number => typeof v === "number")),
|
||||
footnote: "суммарно · 1 ч",
|
||||
href: "/traffic",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{show("sources") ? <DashboardSourcesSummary rows={sourceRows} refreshing={dash.refreshing} onRefresh={dash.retry} /> : null}
|
||||
|
||||
<Tabs value={tab} onValueChange={(value) => setTab(String(value))} className="gap-5">
|
||||
<TabsList variant="line" className="h-auto w-full justify-start gap-1 overflow-x-auto border-b p-0">
|
||||
<TabsTrigger value="over" className="h-auto flex-none px-3 py-2.5 after:bottom-[-1px]">Обзор</TabsTrigger>
|
||||
<TabsTrigger value="src" className="h-auto flex-none px-3 py-2.5 after:bottom-[-1px]">
|
||||
Источники и время получения
|
||||
<Badge variant="secondary" className="font-mono">{sourceRows.length}</Badge>
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="rtt" className="h-auto flex-none px-3 py-2.5 after:bottom-[-1px]">История RTT</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="over" className="flex flex-col gap-5">
|
||||
{show("health") ? (
|
||||
<DashboardHealth
|
||||
factors={[
|
||||
{ label: "Потери пакетов", value: avgLoss == null ? "—" : `${avgLoss.toLocaleString("ru-RU", { maximumFractionDigits: 1 })}%`, ratio: probesMeasured.length ? probesMeasured.filter((p) => (p.loss ?? 0) === 0).length / probesMeasured.length : null },
|
||||
{ label: "Пробы в норме", value: probesMeasured.length ? `${probesMeasured.filter((p) => p.status === "up").length} из ${probesMeasured.length}` : "—", ratio: probesMeasured.length ? probesMeasured.filter((p) => p.status === "up").length / probesMeasured.length : null },
|
||||
{ label: "Свежесть данных", value: `${okSources} из ${sourceRows.length}`, ratio: sourceRows.length ? okSources / sourceRows.length : null },
|
||||
{ label: "Серверы в сети", value: dash.availability.servers ? `${dash.onlineCount} из ${dash.totalServers}` : "—", ratio: dash.availability.servers && dash.totalServers > 0 ? dash.onlineCount / dash.totalServers : null },
|
||||
{ label: "Туннели", value: dash.availability.overlay ? `${dash.overlay.up} из ${dash.overlay.total}` : "—", ratio: dash.availability.overlay && dash.overlay.total > 0 ? dash.overlay.up / dash.overlay.total : null },
|
||||
]}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{show("timeline") ? <DashboardIncidents events={dash.recentEvents} loading={dash.eventsLoading} error={dash.eventsError} /> : null}
|
||||
|
||||
{show("path") ? <InternetPathPanel model={dash.internetPath} loading={dash.internetPathLoading} error={dash.isLive ? dash.internetPathError : null} /> : null}
|
||||
|
||||
{show("attention") ? <DashboardAttentionGrid rows={attentionRows} emptyNotes={emptyNotes} /> : null}
|
||||
|
||||
{show("latency") ? (
|
||||
<SectionFrame title="Задержка до серверов" description={latencyDescription} panelClassName="px-3.5 pt-3.5">
|
||||
{latencyBody}
|
||||
</SectionFrame>
|
||||
) : null}
|
||||
|
||||
{show("traffic") ? (
|
||||
<SectionFrame
|
||||
title="Пропускная способность"
|
||||
description={dash.traffic?.demo ? "Суммарный RX / TX · демо" : "Суммарная история RX / TX · 1 ч; значения — последний измеренный снимок"}
|
||||
actions={<Link href="/traffic" className={buttonVariants({ variant: "outline", size: "sm" })}>Трафик →</Link>}
|
||||
panelClassName="px-3.5 pt-3.5 pb-2"
|
||||
>
|
||||
{dash.loading && !dash.traffic ? (
|
||||
<div className="bg-muted/50 h-[220px] w-full animate-pulse rounded-md" />
|
||||
) : !dash.traffic ? (
|
||||
<p className="text-muted-foreground px-4 py-10 text-center text-sm">
|
||||
Нет данных трафика за последний час.{" "}
|
||||
<Link href="/traffic" className="underline underline-offset-2">Открыть трафик</Link>
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<div className="flex flex-wrap items-center gap-3 px-1 pb-3 text-xs">
|
||||
{dash.traffic.demo ? <Badge variant="outline" size="sm">демо</Badge> : !dash.traffic.observationsKnown ? <Badge variant="outline" size="sm">Измерения не подтверждены API</Badge> : null}
|
||||
<span className="tabular-nums">RX {dash.traffic.rxNow === null ? "—" : fmtRate(dash.traffic.rxNow)}</span>
|
||||
<span className="tabular-nums">TX {dash.traffic.txNow === null ? "—" : fmtRate(dash.traffic.txNow)}</span>
|
||||
</div>
|
||||
<TrafficRxTxChart rx={dash.traffic.rx} tx={dash.traffic.tx} range="1h" embedded />
|
||||
</>
|
||||
)}
|
||||
</SectionFrame>
|
||||
) : null}
|
||||
|
||||
{show("probes") ? (
|
||||
<SectionFrame
|
||||
title="Активные пробы"
|
||||
description={<span className={dash.error && dash.isLive ? "text-destructive" : undefined}>{dash.probesSubtitle}</span>}
|
||||
icon={<TableIcon />}
|
||||
actions={<Link href="/uptime" className={buttonVariants({ variant: "outline", size: "sm" })}>Мониторинг →</Link>}
|
||||
>
|
||||
{dash.activeProbes.length === 0 && !dash.probesLoading ? (
|
||||
<EmptyState
|
||||
className="py-10"
|
||||
title={dash.availability.probes ? "Нет проб на дашборде" : "Данные проб недоступны"}
|
||||
description={dash.availability.probes ? "Включите пробу и отметьте ★ на странице мониторинга." : "Повторите обновление данных."}
|
||||
action={<Link href="/uptime" className={buttonVariants({ variant: "outline", size: "sm" })}>Открыть мониторинг</Link>}
|
||||
/>
|
||||
) : (
|
||||
<DashboardActiveProbesDataGrid probes={dash.activeProbes} catalog={dash.servers} isLoading={dash.probesLoading} emptyDescription="Нет проб с звездой на дашборде." />
|
||||
)}
|
||||
</SectionFrame>
|
||||
) : null}
|
||||
|
||||
{show("links") ? (
|
||||
<DashboardQuickLinks
|
||||
links={[
|
||||
{ id: "traffic", title: "Трафик", description: "Приём, передача и потоки IPFIX", href: "/traffic" },
|
||||
{ id: "map", title: "Карта сети", description: "Топология GRE и WAN", href: "/network-map" },
|
||||
{ id: "filters", title: "Фильтры", description: "Правила обхода и списки · цепочки filter / nat", href: "/filters" },
|
||||
{ id: "backups", title: "Бэкапы", description: "Снапшоты и расписание", href: "/backups" },
|
||||
{ id: "uptime", title: "Мониторинг", description: "Сессии и префиксы · пробы", href: "/uptime" },
|
||||
]}
|
||||
/>
|
||||
) : null}
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="src" className="flex flex-col gap-5">
|
||||
{failedSources.length > 0 ? (
|
||||
<Alert variant="destructive">
|
||||
<CircleAlertIcon />
|
||||
<AlertTitle>Не обновлены источники: {failedSources.length}</AlertTitle>
|
||||
<AlertDescription>Последние полученные данные сохранены. Если источник ещё не загрузился, его показатели неизвестны.</AlertDescription>
|
||||
</Alert>
|
||||
) : null}
|
||||
<SectionFrame title="Источники и время получения" description="Каждый источник дашборда: состояние, время получения и замера" icon={<ChartColumnIcon />}>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full min-w-[640px] text-sm">
|
||||
<thead className="bg-muted/55 text-muted-foreground text-xs">
|
||||
<tr className="h-10 border-b text-left">
|
||||
<th className="px-3.5 font-medium">Источник</th>
|
||||
<th className="px-3 font-medium">Статус</th>
|
||||
<th className="px-3 font-medium">Получено</th>
|
||||
<th className="px-3 font-medium">Замер</th>
|
||||
<th className="px-3 font-medium">Ошибка</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{sourceRows.map((row) => (
|
||||
<tr key={row.key} className="h-[52px] border-b last:border-b-0">
|
||||
<td className="px-3.5 font-mono text-[13px] font-medium">{row.name}</td>
|
||||
<td className="px-3"><ToneBadge tone={row.tone as Tone}>{row.label}</ToneBadge></td>
|
||||
<td className="px-3 font-mono text-[12.5px]">{row.receivedAt != null ? new Date(row.receivedAt).toLocaleString("ru-RU") : "—"}</td>
|
||||
<td className="px-3 font-mono text-[12.5px]">{row.sampledAt ? new Date(row.sampledAt).toLocaleString("ru-RU") : "—"}</td>
|
||||
<td className="text-muted-foreground px-3 text-xs">{sourceErrorText(row) ?? "—"}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<TrafficRxTxChart rx={dash.traffic.rx} tx={dash.traffic.tx} range="1h" embedded />
|
||||
</>
|
||||
)}
|
||||
</OpsPanel>
|
||||
|
||||
</SectionFrame>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="rtt" className="flex flex-col gap-5">
|
||||
<SectionFrame title="История RTT по источникам" description={latencyDescription} panelClassName="px-3.5 pt-3.5">
|
||||
{latencyBody}
|
||||
</SectionFrame>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
|
||||
<InternetPathPanel
|
||||
model={dash.internetPath}
|
||||
loading={dash.internetPathLoading}
|
||||
error={dash.isLive ? dash.internetPathError : null}
|
||||
/>
|
||||
|
||||
<OpsPanel
|
||||
title="Активные пробы"
|
||||
description={
|
||||
<span className={dash.error && dash.isLive ? "text-destructive" : undefined}>{dash.probesSubtitle}</span>
|
||||
}
|
||||
headerRight={
|
||||
<Link href="/uptime" className={cn(buttonVariants({ variant: "outline", size: "sm" }), "h-7 text-xs")}>
|
||||
Мониторинг →
|
||||
</Link>
|
||||
}
|
||||
contentClassName="px-0 pb-0"
|
||||
>
|
||||
{dash.activeProbes.length === 0 && !dash.probesLoading ? (
|
||||
<EmptyState
|
||||
className="py-10"
|
||||
title={dash.availability.probes ? "Нет проб на дашборде" : "Данные проб недоступны"}
|
||||
description={dash.availability.probes ? "Включите пробу и отметьте ★ на странице мониторинга." : "Повторите обновление данных."}
|
||||
action={
|
||||
<Link href="/uptime" className={cn(buttonVariants({ variant: "outline", size: "sm" }))}>
|
||||
Открыть мониторинг
|
||||
</Link>
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<DashboardActiveProbesDataGrid
|
||||
probes={dash.activeProbes}
|
||||
catalog={dash.servers}
|
||||
isLoading={dash.probesLoading}
|
||||
emptyDescription="Нет проб с звездой на дашборде."
|
||||
/>
|
||||
)}
|
||||
</OpsPanel>
|
||||
|
||||
<QuickActionGrid
|
||||
title="Быстрые переходы"
|
||||
description="Другие разделы управления сетью"
|
||||
actions={[
|
||||
{
|
||||
id: "traffic",
|
||||
title: "Трафик",
|
||||
description: "Приём, передача и потоки IPFIX",
|
||||
href: "/traffic",
|
||||
icon: <ActivityIcon />,
|
||||
iconClassName: "text-info",
|
||||
},
|
||||
{
|
||||
id: "map",
|
||||
title: "Карта сети",
|
||||
description: "Топология GRE и WAN",
|
||||
href: "/network-map",
|
||||
icon: <MapIcon />,
|
||||
iconClassName: "text-primary",
|
||||
},
|
||||
{
|
||||
id: "filters",
|
||||
title: "Фильтры",
|
||||
description: "Правила обхода и списки",
|
||||
href: "/filters",
|
||||
icon: <FilterIcon />,
|
||||
iconClassName: "text-info",
|
||||
},
|
||||
{
|
||||
id: "firewall",
|
||||
title: "Firewall",
|
||||
description: "Цепочки filter / nat",
|
||||
href: "/firewall",
|
||||
icon: <ShieldIcon />,
|
||||
iconClassName: "text-warning",
|
||||
},
|
||||
{
|
||||
id: "backups",
|
||||
title: "Бэкапы",
|
||||
description: "Снапшоты и расписание",
|
||||
href: "/backups",
|
||||
icon: <HardDriveIcon />,
|
||||
iconClassName: "text-muted-foreground",
|
||||
},
|
||||
{
|
||||
id: "bgp",
|
||||
title: "BGP",
|
||||
description: "Сессии и префиксы",
|
||||
href: "/bgp",
|
||||
icon: <GitMergeIcon />,
|
||||
iconClassName: "text-primary",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState, type ReactNode } from "react"
|
||||
import type { IxBondBundle, IxBondCandidate, IxBondCatalog, IxBondEdit, IxBondMode, IxSavedBond, IxSegment } from "@mmapp/contracts/internet-exchange"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
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"
|
||||
import { IxExistingTransport } from "./ix-existing-transport"
|
||||
import { toast } from "sonner"
|
||||
import { copyIxImportLink } from "./ix-import-link"
|
||||
|
||||
const modes = [
|
||||
{ value: "failover", label: "Основной и резервные" },
|
||||
{ value: "equal", label: "Параллельно, поровну" },
|
||||
{ value: "weighted", label: "Параллельно, по весам" },
|
||||
] as const
|
||||
type Member = IxBondEdit["members"][number]
|
||||
type Ref = Pick<Member, "segmentId" | "interfaceName" | "serverId">
|
||||
export type IxRowBondAction = (binding: Pick<Ref, "interfaceName" | "serverId">) => { label: string; open: () => void } | undefined
|
||||
const memberKey = (m: Pick<Member, "segmentId" | "interfaceName" | "serverId">) => [m.segmentId, m.serverId, m.interfaceName].join("/")
|
||||
const memberRef = ({ segmentId, serverId, appliedRevision, interfaceName }: IxBondCandidate): Member => ({ segmentId, serverId, appliedRevision, interfaceName, weight: 1 })
|
||||
const modeLabel = (mode: IxBondMode) => modes.find(item => item.value === mode)?.label
|
||||
|
||||
export function IxClientBonds({ segmentId, segments, backendUrl, nodes, readOnly, download, live, children }: {
|
||||
segmentId: string; segments: IxSegment[]; backendUrl: string; nodes: IxNode[]; readOnly: boolean; live: boolean
|
||||
download: (filename: string, text: string) => void
|
||||
children: (action: IxRowBondAction, catalog: IxBondCatalog, groups: (clientId: string) => ReactNode, unassigned: ReactNode) => ReactNode
|
||||
}) {
|
||||
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)
|
||||
const [confirmedMembers, setConfirmedMembers] = useState("")
|
||||
const [importing, setImporting] = useState(false)
|
||||
const [initialInterface, setInitialInterface] = useState<Pick<Ref, "serverId" | "interfaceName">>()
|
||||
useEffect(() => {
|
||||
if (!live) return
|
||||
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, live])
|
||||
const available = new Map(catalog.candidates.map(c => [memberKey(c), c]))
|
||||
for (const m of [...catalog.groups.flatMap(g => g.members), ...(draft?.members ?? [])]) {
|
||||
if (!m.existing) continue
|
||||
const segment = segments.find(s => s.id === m.segmentId)
|
||||
available.set(memberKey(m), { ...m, ...m.existing, name: m.existing.linuxInterface, segmentName: segment?.configuration.name ?? m.segmentId,
|
||||
appliedRevision: segment?.appliedRevision ?? m.appliedRevision, destinations: [...new Set(m.existing.destinations)].sort() })
|
||||
}
|
||||
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, first?: IxBondCandidate) {
|
||||
setError("")
|
||||
setRemove(false)
|
||||
setConfirmedMembers("")
|
||||
setImporting(false)
|
||||
setInitialInterface(undefined)
|
||||
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: first?.name ?? "", mode: "failover", members: first ? [memberRef(first)] : [], 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 previous = catalog.groups.find(g => g.id === draft?.id)
|
||||
const owner = previous?.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 selected = (draft?.members ?? []).flatMap(m => available.get(memberKey(m)) ?? [])
|
||||
const identity = previous?.clientId ?? selected.find(m => m.clientId)?.clientId
|
||||
const first = selected[0]
|
||||
const choices = catalog.candidates.filter(c => c.destinations.length && !occupied.has(memberKey(c)) && (!identity || !c.clientId || c.clientId === identity) &&
|
||||
(!first || c.address.includes(":") === first.address.includes(":") && JSON.stringify(c.destinations) === JSON.stringify(first.destinations) &&
|
||||
!selected.some(m => [m.address, m.probe].some(ip => ip === c.address || ip === c.probe))) &&
|
||||
!draft?.members.some(m => memberKey(m) === memberKey(c)))
|
||||
.map(c => ({ value: memberKey(c), label: label(c) }))
|
||||
const needsConfirmation = selected.length > 1 && selected.some(c => !c.clientId && !previous?.members.some(m => memberKey(m) === memberKey(c)))
|
||||
const selectionKey = selected.map(memberKey).sort().join(",")
|
||||
const issue = error && <p role="alert" className="text-sm text-destructive">{error}</p>
|
||||
const renderGroups = (clientId: string) => ownedGroups.filter(g => g.clientId === clientId).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>
|
||||
<Button size="sm" variant="outline" disabled={busy} onClick={() => void perform(async () => {
|
||||
try {
|
||||
await copyIxImportLink(backendUrl, `/api/ix/segments/${g.ownerSegmentId}/linux-bonds/${g.id}/export`, { revision: g.revision })
|
||||
toast.success("Ссылка скопирована. На VPS откройте ix-client → L.")
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : "Не удалось скопировать ссылку")
|
||||
}
|
||||
})}>Скопировать ссылку для ix-client</Button>
|
||||
</div>}
|
||||
</div>)
|
||||
const rows = children(binding => {
|
||||
const k = memberKey({ ...binding, segmentId })
|
||||
const current = ownedGroups.find(g => g.members.some(m => memberKey(m) === k))
|
||||
const candidate = available.get(k)
|
||||
if (current) return { label: "Открыть группу «" + current.name + "»", open: () => open(current) }
|
||||
if (candidate?.destinations.length) return { label: "Создать группу с этим туннелем", open: () => open(undefined, candidate) }
|
||||
const site = segments.find(s => s.id === segmentId)?.configuration.sites.find(s => s.serverId === binding.serverId)
|
||||
const saved = site?.interfaces.find(b => b.name === binding.interfaceName)
|
||||
if (saved && saved.kind !== "uplink" && !saved.peerServerId && !saved.linux && !saved.provisionWireguard && !saved.provisionGre &&
|
||||
!saved.provisionTransit && !site?.neighbors.some(p => p.binding === saved.name)) {
|
||||
return { label: "Создать группу с этим туннелем", open: () => { open(); setInitialInterface(binding); setImporting(true) } }
|
||||
}
|
||||
}, catalog, renderGroups, live && !readOnly &&
|
||||
<Button size="sm" variant="outline" onClick={() => open()}>Создать группу вручную</Button>)
|
||||
if (!live) return <>{rows}</>
|
||||
return <>{rows}{!draft && issue}
|
||||
<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()
|
||||
if (importing || needsConfirmation && confirmedMembers !== selectionKey) return
|
||||
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, memberRef(c)] })
|
||||
}}>
|
||||
<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>
|
||||
{!choices.length && draft.members.length < 2 && <p className="text-sm text-muted-foreground">Для второго туннеля нужны другой внутренний адрес, то же семейство и одинаковые назначения. Проверьте привязку к VPS и применение подключения на его площадке.</p>}
|
||||
{importing ? <IxExistingTransport backendUrl={backendUrl} segments={segments} segmentId={segmentId} nodes={nodes} initial={initialInterface}
|
||||
members={[...draft.members, ...catalog.groups.filter(g => g.id !== draft.id).flatMap(g => g.members)]} destinations={first?.destinations ?? []}
|
||||
cancel={() => setImporting(false)} add={m => { patch({ members: [...draft.members, m] }); setImporting(false) }} />
|
||||
: <Button type="button" variant="outline" disabled={draft.members.length >= 16} onClick={() => { setInitialInterface(undefined); setImporting(true) }}>Добавить из интерфейсов RouterOS</Button>}
|
||||
{needsConfirmation && <Field orientation="horizontal"><Checkbox id="ix-bond-same-vps" checked={confirmedMembers === selectionKey}
|
||||
onCheckedChange={checked => setConfirmedMembers(checked ? selectionKey : "")} />
|
||||
<FieldLabel htmlFor="ix-bond-same-vps">Подтверждаю, что выбранные интерфейсы настроены на одном VPS</FieldLabel></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 || importing || draft.members.length < 2 || needsConfirmation && confirmedMembers !== selectionKey}>Сохранить</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>
|
||||
</>
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { ixExistingTransportSchema, type IxBondEdit, type IxSegment } from "@mmapp/contracts/internet-exchange"
|
||||
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 { Textarea } from "@/components/ui/textarea"
|
||||
import { nodeLabel, useIxNodeInventory, type IxNode } from "./ix-view"
|
||||
|
||||
type Member = IxBondEdit["members"][number]
|
||||
|
||||
export function IxExistingTransport({ backendUrl, segmentId, segments, nodes, members, destinations, initial, add, cancel }: {
|
||||
backendUrl: string; segmentId: string; segments: IxSegment[]; nodes: IxNode[]; members: Member[]; destinations: string[]
|
||||
add: (ref: Member) => void; cancel: () => void
|
||||
initial?: Pick<Member, "serverId" | "interfaceName">
|
||||
}) {
|
||||
const sites = segments.filter(s => s.appliedRevision).flatMap(segment => segment.configuration.sites.map(site => ({
|
||||
value: segment.id + "/" + site.serverId, label: segment.configuration.name + " · " + nodeLabel(nodes, site.serverId), segment, site,
|
||||
})))
|
||||
const [selection, setSelection] = useState(sites.find(s => s.segment.id === segmentId && (!initial || s.site.serverId === initial.serverId))?.value ?? "")
|
||||
const site = sites.find(s => s.value === selection)
|
||||
const inventory = useIxNodeInventory(backendUrl, site?.site.serverId ?? 0, site?.segment.id)
|
||||
const [iface, setIface] = useState(initial?.interfaceName ?? "")
|
||||
const [linuxInterface, setLinuxInterface] = useState("")
|
||||
const [probe, setProbe] = useState("")
|
||||
const [address, setAddress] = useState("")
|
||||
const [endpoint, setEndpoint] = useState("")
|
||||
const [peer, setPeer] = useState("")
|
||||
const [routes, setRoutes] = useState(destinations.join("\n"))
|
||||
const interfaces = (inventory.inventory?.interfaces ?? []).filter(i => /^(wg|wireguard|gre|gre-tunnel)$/.test(i.type) && !i.disabled && i.addresses.length &&
|
||||
!site?.site.interfaces.some(b => b.name === i.name && (b.linux || b.provisionWireguard || b.provisionGre || b.provisionTransit || b.peerServerId)) &&
|
||||
!site?.site.neighbors.some(p => p.binding === i.name) && !members.some(m => m.serverId === site?.site.serverId && m.interfaceName === i.name))
|
||||
const active = interfaces.find(i => i.name === iface)
|
||||
const wg = active?.type === "wg" || active?.type === "wireguard"
|
||||
const probes = active?.addresses.map(a => a.split("/")[0]) ?? []
|
||||
const selectedProbe = probes.includes(probe) ? probe : probes[0] ?? ""
|
||||
const input = ixExistingTransportSchema.safeParse({ ...(wg ? { kind: "wireguard", clientPublicKey: peer.trim() } : { kind: "gre-ipsec", remoteEndpoint: peer.trim() }),
|
||||
linuxInterface: linuxInterface.trim(), probe: selectedProbe, address: address.trim(), endpoint: endpoint.trim(), destinations: routes.trim().split(/[\s,]+/) })
|
||||
return <div className="grid gap-3 rounded-md border p-3">
|
||||
<Field><FieldLabel htmlFor="ix-adopt-site">Площадка и узел IX</FieldLabel>
|
||||
<Select value={selection} items={sites} onValueChange={v => { setSelection(v ?? ""); setIface(""); setProbe(""); setPeer(""); setEndpoint("") }}>
|
||||
<SelectTrigger id="ix-adopt-site"><SelectValue /></SelectTrigger><SelectContent>{sites.map(s => <SelectItem key={s.value} value={s.value}>{s.label}</SelectItem>)}</SelectContent>
|
||||
</Select></Field>
|
||||
<Field><FieldLabel htmlFor="ix-adopt-interface">Интерфейс RouterOS</FieldLabel>
|
||||
<Select value={iface || null} items={interfaces.map(i => ({ value: i.name, label: i.name }))} onValueChange={v => {
|
||||
setIface(v ?? ""); setProbe(interfaces.find(i => i.name === v)?.addresses[0]?.split("/")[0] ?? ""); setPeer("")
|
||||
}}><SelectTrigger id="ix-adopt-interface"><SelectValue placeholder="Выберите WG или GRE" /></SelectTrigger>
|
||||
<SelectContent>{interfaces.map(i => <SelectItem value={i.name} key={i.name}>{i.name}</SelectItem>)}</SelectContent></Select>
|
||||
<FieldDescription>{inventory.error ?? (inventory.loading ? "Читаем интерфейсы узла…" : "Доступны включённые интерфейсы с внутренним IP. Настройки RouterOS сохраняются.")}</FieldDescription></Field>
|
||||
{active && <>
|
||||
<Field><FieldLabel htmlFor="ix-adopt-linux">Имя интерфейса на VPS</FieldLabel><Input id="ix-adopt-linux" value={linuxInterface} onChange={e => setLinuxInterface(e.target.value)} /></Field>
|
||||
<Field><FieldLabel htmlFor="ix-adopt-probe">Адрес IX внутри туннеля</FieldLabel>
|
||||
<Select value={selectedProbe} items={probes.map(value => ({ value, label: value }))} onValueChange={v => setProbe(v ?? "")}>
|
||||
<SelectTrigger id="ix-adopt-probe"><SelectValue /></SelectTrigger><SelectContent>{probes.map(v => <SelectItem key={v} value={v}>{v}</SelectItem>)}</SelectContent>
|
||||
</Select></Field>
|
||||
<Field><FieldLabel htmlFor="ix-adopt-address">Адрес VPS внутри туннеля</FieldLabel><Input id="ix-adopt-address" value={address} onChange={e => setAddress(e.target.value)} /></Field>
|
||||
<Field><FieldLabel htmlFor="ix-adopt-endpoint">Внешний адрес IX</FieldLabel><Input id="ix-adopt-endpoint" value={endpoint} onChange={e => setEndpoint(e.target.value)} /></Field>
|
||||
<Field><FieldLabel htmlFor="ix-adopt-peer">{wg ? "Публичный ключ WireGuard VPS" : "Внешний IPv4 VPS"}</FieldLabel><Input id="ix-adopt-peer" value={peer} onChange={e => setPeer(e.target.value)} /></Field>
|
||||
<Field><FieldLabel htmlFor="ix-adopt-routes">Назначения через туннель (CIDR)</FieldLabel><Textarea id="ix-adopt-routes" rows={2} value={routes} onChange={e => setRoutes(e.target.value)} /></Field>
|
||||
</>}
|
||||
<div className="flex gap-2"><Button type="button" variant="outline" size="sm" disabled={!site || !active || !input.success} onClick={() => {
|
||||
if (input.success && site?.segment.appliedRevision && active) add({ segmentId: site.segment.id, serverId: site.site.serverId,
|
||||
appliedRevision: site.segment.appliedRevision, interfaceName: active.name, existing: input.data, weight: 1 })
|
||||
}}>Включить в список</Button><Button type="button" size="sm" variant="ghost" onClick={cancel}>Отмена выбора</Button></div>
|
||||
</div>
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import type { IxNodeInventory, IxSegment, IxTransitRequest } from "@mmapp/contracts/internet-exchange"
|
||||
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 { Sheet, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle } from "@/components/ui/sheet"
|
||||
import { nodeLabel, useIxNodeInventory, type IxNode } from "./ix-view"
|
||||
|
||||
export function publicEndpoint(inventory?: IxNodeInventory) {
|
||||
if (!inventory) return ""
|
||||
const wan = new Set(inventory.defaultRoutes.filter(route => route.family === 4).map(route => route.interface))
|
||||
const addresses = new Set(inventory.interfaces.filter(iface => !iface.disabled && wan.has(iface.name))
|
||||
.flatMap(iface => iface.addresses.filter(address => !address.includes(":")).map(address => address.split("/")[0])))
|
||||
return addresses.size === 1 ? [...addresses][0] : ""
|
||||
}
|
||||
|
||||
export function transitName(segment: IxSegment, serverId: number, target: number, family: 4 | 6) {
|
||||
const used = segment.configuration.sites.find(site => site.serverId === serverId)?.groups ?? []
|
||||
const base = "via-" + target.toString(36) + "-v" + family
|
||||
let name = base
|
||||
for (let i = 2; used.some(group => group.id === name); i++) name = base + "-" + i
|
||||
return name
|
||||
}
|
||||
|
||||
function TransitEditor({ segment, nodes, backendUrl, busy, save, cancel }: {
|
||||
segment: IxSegment; nodes: IxNode[]; backendUrl: string; busy: boolean
|
||||
save: (input: IxTransitRequest) => void; cancel: () => void
|
||||
}) {
|
||||
const [serverId, setServerId] = useState(segment.configuration.sites[0].serverId)
|
||||
const [targetServerId, setTargetServerId] = useState(0)
|
||||
const [local, setLocal] = useState("")
|
||||
const [remote, setRemote] = useState("")
|
||||
const [name, setName] = useState("")
|
||||
const [probe, setProbe] = useState("")
|
||||
const [family, setFamily] = useState<4 | 6>(4)
|
||||
const origin = useIxNodeInventory(backendUrl, serverId, segment.id)
|
||||
const target = useIxNodeInventory(backendUrl, targetServerId, segment.id)
|
||||
const localEndpoint = local || publicEndpoint(origin.inventory)
|
||||
const remoteEndpoint = remote || publicEndpoint(target.inventory)
|
||||
const exitName = name || transitName(segment, serverId, targetServerId, family)
|
||||
const sourceChoices = segment.configuration.sites.map(site => ({ value: String(site.serverId), label: nodeLabel(nodes, site.serverId) }))
|
||||
const targets = nodes.filter(node => node.enabled && node.id !== serverId && ["ix-node", "exit-node"].includes(node.type ?? ""))
|
||||
.map(node => ({ value: String(node.id), label: node.name + (node.type === "ix-node" ? " · IX" : " · ExitNode") }))
|
||||
return <form className="flex min-h-0 flex-1 flex-col" onSubmit={event => {
|
||||
event.preventDefault()
|
||||
if (!busy && targetServerId && localEndpoint && remoteEndpoint && exitName) {
|
||||
save({ revision: segment.revision, name: exitName, serverId, targetServerId, localEndpoint, remoteEndpoint, family, probe: probe || undefined })
|
||||
}
|
||||
}}>
|
||||
<div className="grid min-h-0 gap-4 overflow-y-auto px-4">
|
||||
{sourceChoices.length > 1 && <Field><FieldLabel htmlFor="ix-egress-source">Узел входа</FieldLabel>
|
||||
<Select items={sourceChoices} value={String(serverId)} onValueChange={value => {
|
||||
if (value) { setServerId(Number(value)); setTargetServerId(0); setLocal(""); setRemote("") }
|
||||
}}>
|
||||
<SelectTrigger className="w-full" id="ix-egress-source"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>{sourceChoices.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}</SelectContent>
|
||||
</Select></Field>}
|
||||
<Field><FieldLabel htmlFor="ix-egress-target">Выходной узел</FieldLabel>
|
||||
<Select items={targets} value={targetServerId ? String(targetServerId) : null}
|
||||
onValueChange={value => { setTargetServerId(Number(value)); setRemote("") }}>
|
||||
<SelectTrigger className="w-full" id="ix-egress-target"><SelectValue placeholder="Другой IX или ExitNode" /></SelectTrigger>
|
||||
<SelectContent>{targets.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}</SelectContent>
|
||||
</Select></Field>
|
||||
<details key={serverId + ":" + targetServerId + ":" + (origin.loading || target.loading)} open={!!targetServerId && (!publicEndpoint(origin.inventory) || !publicEndpoint(target.inventory)) && !origin.loading && !target.loading}>
|
||||
<summary className="cursor-pointer text-sm font-medium">Параметры туннеля</summary>
|
||||
<div className="mt-3 grid gap-3">
|
||||
<Field><FieldLabel htmlFor="ix-egress-name">Имя выхода</FieldLabel>
|
||||
<Input id="ix-egress-name" value={exitName} pattern="[a-z][a-z0-9-]{0,23}" onChange={event => setName(event.target.value)} /></Field>
|
||||
<Field><FieldLabel htmlFor="ix-egress-local">Внешний IPv4 узла входа</FieldLabel>
|
||||
<Input id="ix-egress-local" value={localEndpoint} required onChange={event => setLocal(event.target.value)} /></Field>
|
||||
<Field><FieldLabel htmlFor="ix-egress-remote">Внешний IPv4 выходного узла</FieldLabel>
|
||||
<Input id="ix-egress-remote" value={remoteEndpoint} required onChange={event => setRemote(event.target.value)} /></Field>
|
||||
<Field><FieldLabel htmlFor="ix-egress-probe">Контрольный адрес</FieldLabel>
|
||||
<Input id="ix-egress-probe" value={probe} placeholder="Адрес второго конца туннеля" onChange={event => setProbe(event.target.value)} />
|
||||
<FieldDescription>Для проверки выхода за пределами туннеля укажите доступную цель за удалённым узлом.</FieldDescription>
|
||||
</Field>
|
||||
<Field><FieldLabel htmlFor="ix-egress-family">Семейство трафика</FieldLabel>
|
||||
<Select value={String(family)} items={[{ value: "4", label: "IPv4" }, { value: "6", label: "IPv6" }]}
|
||||
onValueChange={value => { setFamily(value === "6" ? 6 : 4); setProbe("") }}>
|
||||
<SelectTrigger className="w-full" id="ix-egress-family"><SelectValue /></SelectTrigger>
|
||||
<SelectContent><SelectItem value="4">IPv4</SelectItem><SelectItem value="6">IPv6</SelectItem></SelectContent>
|
||||
</Select>
|
||||
{family === 6 && <FieldDescription>Для выхода в Интернет IPv6 нужен маршрутизируемый префикс Linux с обратным маршрутом до выходной CHR.</FieldDescription>}
|
||||
</Field>
|
||||
</div>
|
||||
</details>
|
||||
{(origin.error || target.error) && <p role="status" className="text-sm text-muted-foreground">{origin.error ?? target.error}</p>}
|
||||
</div>
|
||||
<SheetFooter>
|
||||
<Button type="submit" disabled={busy || !targetServerId || !localEndpoint || !remoteEndpoint}>Сохранить</Button>
|
||||
<Button type="button" variant="outline" disabled={busy} onClick={cancel}>Отмена</Button>
|
||||
</SheetFooter>
|
||||
</form>
|
||||
}
|
||||
|
||||
export function IxExits({ segment, nodes, backendUrl, busy, error, save }: {
|
||||
segment: IxSegment; nodes: IxNode[]; backendUrl: string; busy: boolean; error: string
|
||||
save: (input: IxTransitRequest) => Promise<boolean>
|
||||
}) {
|
||||
const [open, setOpen] = useState(false)
|
||||
return <>
|
||||
<Button size="sm" className="w-fit" disabled={busy} onClick={() => setOpen(true)}>Добавить удалённый выход</Button>
|
||||
<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>Удалённый выход</SheetTitle>
|
||||
<SheetDescription>WireGuard, обратные маршруты и IPv4 SNAT будут подготовлены на обоих узлах.</SheetDescription>
|
||||
{error && <p className="text-sm text-destructive" role="alert">{error}</p>}
|
||||
</SheetHeader>
|
||||
{open && <TransitEditor segment={segment} nodes={nodes} backendUrl={backendUrl} busy={busy}
|
||||
save={input => void save(input).then(success => { if (success) setOpen(false) })} cancel={() => setOpen(false)} />}
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</>
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { requestJson } from "@/shared/api/http-client"
|
||||
|
||||
export async function copyIxImportLink(backendUrl: string, path: string, params: object) {
|
||||
const link = new URL(backendUrl.replace(/\/$/, "") + "/api/ix/import", window.location.origin)
|
||||
if (link.protocol !== "https:" || !navigator.clipboard) throw new Error("Для одноразовой ссылки откройте Manager по HTTPS")
|
||||
const { code } = await requestJson<{ code: string }>(backendUrl, path, {
|
||||
method: "POST", body: JSON.stringify({ ...params, importLink: true }),
|
||||
})
|
||||
if (!/^[A-Za-z0-9_-]{32}$/.test(code)) throw new Error("Manager вернул неверный код импорта")
|
||||
link.hash = code
|
||||
await navigator.clipboard.writeText(link.toString())
|
||||
}
|
||||
@@ -0,0 +1,376 @@
|
||||
"use client"
|
||||
|
||||
import { useMemo, useState, type ReactNode } from "react"
|
||||
import { type ColumnDef, useTable } from "@tanstack/react-table"
|
||||
import { EllipsisIcon, PencilIcon, PlusIcon, RefreshCwIcon } from "lucide-react"
|
||||
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"
|
||||
import { Frame, FrameHeader, FramePanel, FrameTitle } from "@/components/reui/frame"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { ButtonGroup } from "@/components/ui/button-group"
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
|
||||
import { Field, FieldDescription, FieldLabel, FieldTitle } from "@/components/ui/field"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||
import { Sheet, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle } from "@/components/ui/sheet"
|
||||
import { Textarea } from "@/components/ui/textarea"
|
||||
import { isIpv4String } from "@/lib/gre-endpoint-resolve"
|
||||
import { formatBytes } from "@/lib/fmt-rate"
|
||||
import { publicEndpoint, transitName } from "./ix-exits"
|
||||
import { nodeLabel, useIxNodeInventory, type IxNode } from "./ix-view"
|
||||
import type { IxRowBondAction } from "./ix-client-bonds"
|
||||
|
||||
type Binding = IxSite["interfaces"][number]
|
||||
type ClientSelection = { site: IxSite; binding: Binding; addProtocol?: boolean; chooseTransport?: boolean }
|
||||
type FormState = {
|
||||
serverId: number
|
||||
name: string
|
||||
kind: IxLinuxClientRequest["kind"] | "both"
|
||||
hub: string
|
||||
peer: string
|
||||
key: string
|
||||
localAddress: string
|
||||
peerAddress: string
|
||||
prefixes: string
|
||||
destinations: string
|
||||
exit: string
|
||||
enabled: boolean
|
||||
transitLocal: string
|
||||
transitRemote: string
|
||||
}
|
||||
|
||||
const lines = (value: string) => value.split(/[,\n]/).map(line => line.trim()).filter(Boolean)
|
||||
const protocols = [
|
||||
{ kind: "wireguard", label: "WireGuard" },
|
||||
{ kind: "gre-ipsec", label: "GRE/IPsec" },
|
||||
] as const
|
||||
|
||||
function hasCompanion(site: IxSite, binding: Binding) {
|
||||
const clientId = binding.linux?.clientId
|
||||
return !!clientId && site.interfaces.some(item => item.kind !== binding.kind && item.linux?.clientId === clientId)
|
||||
}
|
||||
|
||||
function groupLabel(group: IxSite["groups"][number], site: IxSite, nodes: IxNode[]) {
|
||||
const target = site.interfaces.find(binding => binding.name === group.primary.interface)?.peerServerId
|
||||
const label = target ? "Через " + nodeLabel(nodes, target) : group.primary.viaMain ? "Интернет с этого IX" : group.id
|
||||
return [label, group.backup && "с резервом"].filter(Boolean).join(" · ")
|
||||
}
|
||||
|
||||
function ClientForm({ segment, edit, setAddProtocol, nodes, backendUrl, catalog, busy, save, cancel }: {
|
||||
segment: IxSegment; edit: ClientSelection | null; nodes: IxNode[]; backendUrl: string
|
||||
catalog: IxBondCatalog
|
||||
setAddProtocol: (add: boolean) => void
|
||||
busy: boolean; save: (input: IxLinuxClientRequest) => Promise<void>; cancel: () => void
|
||||
}) {
|
||||
const existing = edit?.binding
|
||||
const companion = edit?.addProtocol ? existing : undefined
|
||||
const binding = companion ? undefined : existing
|
||||
const paired = !!edit && hasCompanion(edit.site, edit.binding)
|
||||
const initialForm = (addProtocol: boolean): FormState => {
|
||||
const current = addProtocol ? undefined : existing
|
||||
const tunnel = current?.provisionWireguard ?? current?.provisionGre
|
||||
return {
|
||||
serverId: edit?.site.serverId ?? segment.configuration.sites[0].serverId,
|
||||
name: existing?.linux?.name ?? "",
|
||||
kind: addProtocol ? (existing?.kind === "wireguard" ? "gre-ipsec" : "wireguard")
|
||||
: current?.kind === "gre-ipsec" ? "gre-ipsec" : "wireguard",
|
||||
hub: existing?.localEndpoint ?? existing?.provisionWireguard?.hubEndpoint ?? "",
|
||||
peer: existing?.linux?.peerEndpoint ?? existing?.endpoint ?? "",
|
||||
key: current?.provisionWireguard?.credentialId ? "" : current?.provisionWireguard?.peerPublicKey ?? "",
|
||||
localAddress: tunnel?.localAddress ?? "", peerAddress: tunnel?.peerAddress ?? "",
|
||||
prefixes: current?.prefixes.join("\n") ?? "", destinations: current?.linux?.destinations.join("\n") ?? "",
|
||||
exit: current?.linux?.exit ?? "isolated", enabled: current?.linux?.enabled ?? true,
|
||||
transitLocal: "", transitRemote: "",
|
||||
}
|
||||
}
|
||||
const [currentForm, setCurrentForm] = useState(() => initialForm(false))
|
||||
const [companionForm, setCompanionForm] = useState(() => initialForm(true))
|
||||
const form = companion ? companionForm : currentForm
|
||||
const setForm = companion ? setCompanionForm : setCurrentForm
|
||||
const wireguard = form.kind !== "gre-ipsec"
|
||||
const gre = form.kind !== "wireguard"
|
||||
const [rotate, setRotate] = useState(false)
|
||||
const [vpsId, setVpsId] = useState("")
|
||||
const currentGroup = edit && catalog.groups.find(g => g.members.some(m => m.segmentId === segment.id &&
|
||||
m.serverId === edit.site.serverId && m.interfaceName === edit.binding.name))
|
||||
const currentVps = currentGroup?.clientId ?? existing?.linux?.clientId
|
||||
const knownVps = useMemo(() => {
|
||||
const labels = new Map<string, string>()
|
||||
for (const c of catalog.candidates) if (c.clientId) labels.set(c.clientId, c.name + " · " + c.segmentName)
|
||||
for (const group of catalog.groups) labels.set(group.clientId, group.name)
|
||||
if (currentVps && !labels.has(currentVps)) labels.set(currentVps, existing?.linux?.name ?? "Текущий VPS")
|
||||
return [...labels].map(([value, label]) => ({ value, label: label + " · " + value.slice(0, 8) }))
|
||||
}, [catalog, currentVps, existing])
|
||||
const origin = useIxNodeInventory(backendUrl, form.serverId, segment.id)
|
||||
const site = segment.configuration.sites.find(site => site.serverId === form.serverId)
|
||||
const suggested = publicEndpoint(origin.inventory)
|
||||
const hub = form.hub.trim() || suggested
|
||||
const targetId = form.exit.startsWith("remote:") ? Number(form.exit.slice(7)) : 0
|
||||
const target = useIxNodeInventory(backendUrl, targetId, segment.id)
|
||||
const localEndpoint = form.transitLocal.trim() || suggested || (form.hub.includes(":") ? "" : form.hub.trim())
|
||||
const remoteEndpoint = form.transitRemote.trim() || publicEndpoint(target.inventory)
|
||||
const family = form.kind !== "both" && form.peerAddress.includes(":") ? 6 : 4
|
||||
const patch = (fields: Partial<FormState>) => setForm(value => ({ ...value, ...fields }))
|
||||
const nodeChoices = segment.configuration.sites.map(site => ({ value: String(site.serverId), label: nodeLabel(nodes, site.serverId) }))
|
||||
const groups = site?.groups.filter(group => group.onFailure === "block" && group.gateway.includes(":") === (family === 6)) ?? []
|
||||
const local = groups.find(group => group.id === "ix-wan" + family && group.primary.viaMain)
|
||||
const targets = nodes.filter(node => node.enabled && node.id !== form.serverId && ["ix-node", "exit-node"].includes(node.type ?? ""))
|
||||
const exits = [
|
||||
{ value: "isolated", label: "Только разрешённые сети" },
|
||||
{ value: local?.id ?? "local-wan", label: local ? groupLabel(local, site!, nodes) : "Интернет с этого IX" },
|
||||
...groups.filter(group => group !== local).map(group => ({ value: group.id, label: groupLabel(group, site!, nodes) + " · " + group.id })),
|
||||
...targets.filter(node => !groups.some(group => site?.interfaces.some(link => link.name === group.primary.interface && link.peerServerId === node.id)))
|
||||
.map(node => ({ value: "remote:" + node.id, label: "Через " + node.name + (node.type === "exit-node" ? " · ExitNode" : " · IX") })),
|
||||
]
|
||||
const valid = !!form.name.trim() && !!hub && (!gre || isIpv4String(form.peer.trim()) && isIpv4String(hub)) &&
|
||||
(!targetId || !!localEndpoint && !!remoteEndpoint) && exits.some(exit => exit.value === form.exit)
|
||||
const destinationsField = <Field><FieldLabel htmlFor="ix-linux-destinations">Разрешённые сети IX</FieldLabel>
|
||||
<Textarea id="ix-linux-destinations" rows={2} value={form.destinations} placeholder="По одному CIDR на строку" onChange={event => patch({ destinations: event.target.value })} />
|
||||
<FieldDescription>Перечислите префиксы для доступа через IX, например 10.2.0.0/24.</FieldDescription></Field>
|
||||
return <form className="flex min-h-0 flex-1 flex-col" onSubmit={event => {
|
||||
event.preventDefault()
|
||||
if (!valid || busy) return
|
||||
void save({
|
||||
revision: segment.revision, serverId: form.serverId, interfaceName: binding?.name, name: form.name,
|
||||
vpsClientId: !companion && vpsId && vpsId !== currentVps ? 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,
|
||||
localAddress: form.kind === "both" ? undefined : form.localAddress.trim() || undefined,
|
||||
peerAddress: form.kind === "both" ? undefined : form.peerAddress.trim() || undefined,
|
||||
prefixes: lines(form.prefixes), destinations: lines(form.destinations), exit: form.exit === "isolated" || targetId ? undefined : form.exit,
|
||||
transit: targetId ? { targetServerId: targetId, name: transitName(segment, form.serverId, targetId, family), family,
|
||||
localEndpoint, remoteEndpoint } : undefined,
|
||||
enabled: form.enabled, rotate: !!binding && rotate,
|
||||
})
|
||||
}}>
|
||||
<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>
|
||||
{!companion && !!knownVps.length && <Field><FieldLabel htmlFor="ix-linux-vps">Привязка к VPS</FieldLabel>
|
||||
<Select value={vpsId || currentVps || "separate"} disabled={!!currentGroup} items={[{ value: "separate", label: "Отдельное подключение" }, ...knownVps]}
|
||||
onValueChange={v => setVpsId(v && v !== "separate" ? v : "")}>
|
||||
<SelectTrigger id="ix-linux-vps"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>{!currentVps && <SelectItem value="separate">Отдельное подключение</SelectItem>}
|
||||
{knownVps.map(v => <SelectItem key={v.value} value={v.value}>{v.label}</SelectItem>)}</SelectContent>
|
||||
</Select>{currentGroup && <FieldDescription>Привязка задана группой «{currentGroup.name}».</FieldDescription>}</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" })}>
|
||||
<SelectTrigger id="ix-linux-node" className="w-full"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>{nodeChoices.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}</SelectContent>
|
||||
</Select></Field>}
|
||||
<Field>
|
||||
<FieldTitle id="ix-linux-transport">Протоколы подключения</FieldTitle>
|
||||
<ButtonGroup aria-labelledby="ix-linux-transport" className="max-w-full">
|
||||
{protocols.map(({ kind, label }) => {
|
||||
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 || (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>
|
||||
{form.kind === "both" ? <FieldDescription>Оба туннеля получат свои адреса в одной VRF сегмента.</FieldDescription>
|
||||
: companion ? <FieldDescription>Настройки ниже относятся к новому туннелю в той же VRF.</FieldDescription>
|
||||
: paired ? <FieldDescription>Оба протокола настроены. Здесь редактируется {binding?.kind === "gre-ipsec" ? "GRE/IPsec" : "WireGuard"}.</FieldDescription>
|
||||
: edit ? <FieldDescription>Выберите второй протокол, чтобы добавить туннель в ту же VRF.</FieldDescription>
|
||||
: <FieldDescription>Можно отметить оба протокола.</FieldDescription>}
|
||||
</Field>
|
||||
<Field><FieldLabel htmlFor="ix-linux-peer">Внешний адрес Linux</FieldLabel>
|
||||
<Input id="ix-linux-peer" value={form.peer} placeholder="123.123.123.123" required={gre} onChange={event => patch({ peer: event.target.value })} />
|
||||
<FieldDescription>{gre ? "Фиксированный IPv4 на VPS для GRE/IPsec. Ответы на SSH по этому адресу пойдут напрямую." : form.exit === "isolated"
|
||||
? "Для WireGuard это поле необязательно." : "Укажите публичный IP VPS, чтобы сохранить доступ по SSH при выходе через IX."}</FieldDescription></Field>
|
||||
<Field><FieldLabel htmlFor="ix-linux-exit">Выход трафика</FieldLabel>
|
||||
<Select value={form.exit} items={exits} onValueChange={value => { if (value) patch({ exit: value, transitLocal: "", transitRemote: "" }) }}>
|
||||
<SelectTrigger id="ix-linux-exit" className="w-full"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>{exits.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}</SelectContent>
|
||||
</Select>
|
||||
{!!targetId && <FieldDescription>IX создаст туннель до {nodeLabel(nodes, targetId)} для выхода в Интернет.</FieldDescription>}
|
||||
</Field>
|
||||
{!!targetId && !publicEndpoint(target.inventory) && (target.loading ? <p role="status" className="text-sm text-muted-foreground">Читаем WAN выходного узла…</p> :
|
||||
<Field><FieldLabel htmlFor="ix-transit-target">IPv4 выходного узла</FieldLabel>
|
||||
<Input id="ix-transit-target" value={form.transitRemote} onChange={event => patch({ transitRemote: event.target.value })} />
|
||||
<FieldDescription>Укажите адрес интерфейса CHR для межузлового туннеля.</FieldDescription></Field>)}
|
||||
{!!targetId && !suggested && !origin.loading && <Field><FieldLabel htmlFor="ix-transit-source">IPv4 узла IX для транзита</FieldLabel>
|
||||
<Input id="ix-transit-source" value={localEndpoint} onChange={event => patch({ transitLocal: event.target.value })} /></Field>}
|
||||
{form.exit === "isolated" && destinationsField}
|
||||
<details className="grid gap-3" key={form.serverId + ":" + origin.loading + ":" + gre}
|
||||
open={!origin.loading && (!hub || gre && !isIpv4String(hub)) || undefined}>
|
||||
<summary className="cursor-pointer text-sm font-medium">Параметры туннеля</summary>
|
||||
<div className="mt-3 grid gap-3">
|
||||
<Field><FieldLabel htmlFor="ix-linux-hub">Внешний адрес IX</FieldLabel>
|
||||
<Input id="ix-linux-hub" value={form.hub || suggested} onChange={event => patch({ hub: event.target.value })} />
|
||||
<FieldDescription>{origin.loading ? "Читаем адрес WAN с CHR…" : suggested ? "Адрес WAN для подключения VPS." : "Введите адрес IX, доступный с VPS."}</FieldDescription>
|
||||
</Field>
|
||||
{wireguard && <Field><FieldLabel htmlFor="ix-linux-key">Публичный ключ Linux</FieldLabel>
|
||||
<Input id="ix-linux-key" value={form.key} placeholder="Создать автоматически" onChange={event => patch({ key: event.target.value })} />
|
||||
<FieldDescription>Укажите ключ только для своей пары WireGuard.</FieldDescription></Field>}
|
||||
{form.exit !== "isolated" && destinationsField}
|
||||
{form.kind !== "both" && <><Field><FieldLabel htmlFor="ix-linux-tunnel-local">Адрес IX в туннеле (CIDR)</FieldLabel>
|
||||
<Input id="ix-linux-tunnel-local" value={form.localAddress} placeholder="Автоматический IPv4" onChange={event => patch({ localAddress: event.target.value })} /></Field>
|
||||
<Field><FieldLabel htmlFor="ix-linux-tunnel-peer">Адрес Linux в туннеле</FieldLabel>
|
||||
<Input id="ix-linux-tunnel-peer" value={form.peerAddress} placeholder="Автоматический IPv4" onChange={event => patch({ peerAddress: event.target.value })} /></Field></>}
|
||||
<Field><FieldLabel htmlFor="ix-linux-prefixes">Сети за Linux</FieldLabel>
|
||||
<Textarea id="ix-linux-prefixes" rows={2} value={form.prefixes} onChange={event => patch({ prefixes: event.target.value })} /></Field>
|
||||
</div>
|
||||
</details>
|
||||
{binding && <div className="flex flex-wrap gap-2">
|
||||
<Button type="button" size="sm" variant={form.enabled ? "outline" : "secondary"} aria-pressed={!form.enabled}
|
||||
onClick={() => patch({ enabled: !form.enabled })}>{form.enabled ? "Приостановить доступ" : "Возобновить доступ"}</Button>
|
||||
{form.kind === "gre-ipsec" && <Button type="button" size="sm" variant={rotate ? "secondary" : "outline"}
|
||||
aria-pressed={rotate} onClick={() => setRotate(!rotate)}>Выпустить новый PSK</Button>}
|
||||
</div>}
|
||||
</div>
|
||||
<SheetFooter>{(gre || !form.key) && <p className="text-sm text-muted-foreground">После подтверждения файлы подключения будут доступны в таблице.</p>}
|
||||
<Button type="submit" disabled={!valid || busy}>{companion ? "Добавить туннель" : "Сохранить"}</Button>
|
||||
<Button type="button" variant="outline" disabled={busy} onClick={cancel}>Отмена</Button></SheetFooter>
|
||||
</form>
|
||||
}
|
||||
|
||||
function TunnelTable({ data, columns, busy }: {
|
||||
data: IxLinuxBinding[]; columns: ColumnDef<DataGridFeatures, IxLinuxBinding>[]; busy: boolean
|
||||
}) {
|
||||
const table = useTable({ features: dataGridFeatures, manualPagination: true, data, columns,
|
||||
getRowId: row => row.serverId + ":" + row.interfaceName })
|
||||
return <DataGridShell table={table} recordCount={data.length} isLoading={busy && !data.length} loadingMode="skeleton" emptyMessage="В сегменте пока нет Linux-клиентов" />
|
||||
}
|
||||
|
||||
export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly, busy, error, save, refresh, revoke, view, copyImport, inspect, bondAction, catalog, renderGroups, manualGroup }: {
|
||||
segment: IxSegment; nodes: IxNode[]; backendUrl: string; applied: IxLinuxBinding[]; readOnly: boolean; busy: boolean; error?: string
|
||||
save: (input: IxLinuxClientRequest) => Promise<boolean>; refresh: () => void
|
||||
view: (binding: IxLinuxBinding, transportOnly?: boolean) => void; revoke: (binding: IxLinuxBinding) => void
|
||||
copyImport: (binding: IxLinuxBinding) => void; inspect: (binding: IxLinuxBinding) => void
|
||||
bondAction: IxRowBondAction; catalog: IxBondCatalog
|
||||
renderGroups: (clientId: string) => ReactNode; manualGroup: ReactNode
|
||||
}) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const [edit, setEdit] = useState<ClientSelection | null>(null)
|
||||
const rows = useMemo(() => {
|
||||
const saved = segment.configuration.sites.flatMap(site => site.interfaces.flatMap(binding => binding.linux ? [{
|
||||
serverId: site.serverId, interfaceName: binding.name, kind: binding.kind as IxLinuxBinding["kind"],
|
||||
policy: binding.linux, name: binding.linux.name, enabled: binding.linux.enabled,
|
||||
connection: applied.find(item => item.serverId === site.serverId && item.interfaceName === binding.name)?.connection,
|
||||
}] : []))
|
||||
return [...saved, ...applied.filter(binding => !saved.some(item => item.serverId === binding.serverId && item.interfaceName === binding.interfaceName))]
|
||||
}, [segment, applied])
|
||||
const clients = new Map<string, { name: string; tunnels: IxLinuxBinding[]; hasGroups: boolean }>()
|
||||
const relevantGroups = catalog.groups.filter(group => group.members.some(member => member.segmentId === segment.id))
|
||||
const tunnelKey = (binding: Pick<IxLinuxBinding, "serverId" | "interfaceName">) => binding.serverId + ":" + binding.interfaceName
|
||||
const affiliations = new Map(relevantGroups.flatMap(group => group.members.filter(member => member.segmentId === segment.id)
|
||||
.map(member => [tunnelKey(member), group.clientId] as const)))
|
||||
for (const row of rows) {
|
||||
const key = affiliations.get(tunnelKey(row)) ?? row.policy?.clientId ?? tunnelKey(row)
|
||||
const client = clients.get(key) ?? { name: row.name ?? row.interfaceName, tunnels: [], hasGroups: false }
|
||||
if (row.name && !client.tunnels.some(tunnel => tunnel.name)) client.name = row.name
|
||||
client.tunnels.push(row)
|
||||
clients.set(key, client)
|
||||
}
|
||||
for (const group of relevantGroups) {
|
||||
const client = clients.get(group.clientId) ?? { name: group.name, tunnels: [], hasGroups: false }
|
||||
client.hasGroups = true
|
||||
clients.set(group.clientId, client)
|
||||
}
|
||||
const columns = useMemo<ColumnDef<DataGridFeatures, IxLinuxBinding>[]>(() => [
|
||||
{ id: "name", header: "Интерфейс", size: 195, cell: ({ row }) => <div className="grid gap-0.5">
|
||||
<span className="break-all font-medium">{row.original.interfaceName}</span>
|
||||
<span className="text-xs text-muted-foreground">{nodeLabel(nodes, row.original.serverId)}</span>
|
||||
</div> },
|
||||
{ id: "transport", header: "Туннель", size: 105, cell: ({ row }) => row.original.kind === "wireguard" ? "WireGuard" : "GRE/IPsec" },
|
||||
{ id: "egress", header: "Выход трафика", size: 205, cell: ({ row }) => {
|
||||
const client = row.original
|
||||
const site = segment.configuration.sites.find(item => item.serverId === client.serverId)
|
||||
const binding = site?.interfaces.find(item => item.name === client.interfaceName)
|
||||
const group = site?.groups.find(item => item.id === client.policy?.exit)
|
||||
const label = site && group ? groupLabel(group, site, nodes) : client.policy ? client.policy.exit ?? "Только сети IX" : "По настройкам интерфейса"
|
||||
return readOnly || !site || !binding?.linux ? label : <Button type="button" size="sm" variant="link" className="max-w-full"
|
||||
disabled={busy} aria-label={"Доступ и выход клиента " + client.name} onClick={() => { setEdit({ site, binding }); setOpen(true) }}>
|
||||
<span className="truncate">{label}</span><PencilIcon aria-hidden />
|
||||
</Button>
|
||||
} },
|
||||
{ id: "state", header: "Состояние", size: 160, cell: ({ row }) => {
|
||||
const binding = row.original
|
||||
if (!binding.policy) return <div className="grid gap-1"><Badge className="w-fit" variant="secondary">Прежняя настройка</Badge>
|
||||
{!catalog.candidates.some(c => c.segmentId === segment.id && c.serverId === binding.serverId && c.interfaceName === binding.interfaceName) &&
|
||||
<span className="text-xs text-muted-foreground">Параметры ручного туннеля проверяются при добавлении из RouterOS.</span>}</div>
|
||||
const live = applied.find(item => item.serverId === binding.serverId && item.interfaceName === binding.interfaceName)
|
||||
const site = segment.configuration.sites.find(item => item.serverId === binding.serverId)
|
||||
if (!site?.interfaces.some(item => item.name === binding.interfaceName)) return <Badge variant="warning-light">Ожидает отзыва</Badge>
|
||||
if (!live || JSON.stringify(binding.policy) !== JSON.stringify(live.policy)) return <Badge variant="warning-light">Ожидает сохранения</Badge>
|
||||
if (!binding.enabled) return <Badge variant="secondary">Приостановлен</Badge>
|
||||
const { state, rx, tx } = binding.connection ?? {}
|
||||
return <div className="grid gap-1">
|
||||
<Badge className="w-fit" variant={state === "connected" ? "success-light" : "secondary"}>
|
||||
{state === "connected" ? "Подключён" : state === "waiting" ? "Ожидает туннель" : "Нет данных"}
|
||||
</Badge>
|
||||
{(rx !== undefined || tx !== undefined) && <span className="text-xs text-muted-foreground" title="Счётчики на узле IX">
|
||||
RX {rx !== undefined ? formatBytes(Number(rx)) : "—"} · TX {tx !== undefined ? formatBytes(Number(tx)) : "—"}
|
||||
</span>}
|
||||
</div>
|
||||
} },
|
||||
{ id: "actions", header: "Действия", size: 140, cell: ({ row }) => {
|
||||
const binding = row.original
|
||||
const site = segment.configuration.sites.find(site => site.serverId === binding.serverId)
|
||||
const saved = site?.interfaces.find(candidate => candidate.name === binding.interfaceName)
|
||||
const paired = !!site && !!saved && hasCompanion(site, saved)
|
||||
const live = applied.find(item => item.serverId === binding.serverId && item.interfaceName === binding.interfaceName && item.enabled !== false)
|
||||
const bond = !readOnly && bondAction(binding)
|
||||
return <div className="flex flex-wrap gap-1">
|
||||
{live && <Button size="sm" variant="outline" disabled={busy} aria-label={"Получить конфиг " + (binding.name ?? binding.interfaceName) +
|
||||
(paired ? binding.kind === "wireguard" ? " · WireGuard" : " · GRE/IPsec" : "")}
|
||||
onClick={() => view(live)}>Конфиг Linux</Button>}
|
||||
{(bond || binding.policy && (live || !readOnly && saved?.linux)) && <DropdownMenu>
|
||||
<DropdownMenuTrigger render={<Button type="button" size="icon-sm" variant="ghost" disabled={busy} aria-label={"Действия клиента " +
|
||||
(binding.name ?? binding.interfaceName) + (paired ? " · " + binding.interfaceName : "")} />}>
|
||||
<EllipsisIcon aria-hidden />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{bond && <DropdownMenuItem onClick={bond.open}>{bond.label}</DropdownMenuItem>}
|
||||
{live && (binding.policy || catalog.candidates.some(c => c.segmentId === segment.id && c.serverId === live.serverId && c.interfaceName === live.interfaceName)) &&
|
||||
<DropdownMenuItem onClick={() => view(live, true)}>Конфиг для группы ix-client</DropdownMenuItem>}
|
||||
{!readOnly && live?.policy && (live.managedWireguard || live.kind === "gre-ipsec") &&
|
||||
<DropdownMenuItem onClick={() => copyImport(live)}>Скопировать ссылку для ix-client</DropdownMenuItem>}
|
||||
{live?.policy && <DropdownMenuItem onClick={() => inspect(live)}>Проверить путь</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>}
|
||||
</div>
|
||||
} },
|
||||
], [nodes, applied, segment, readOnly, busy, view, copyImport, revoke, inspect, bondAction, catalog.candidates])
|
||||
return <Frame spacing="sm" className="min-w-0">
|
||||
<FrameHeader className="flex-row flex-wrap items-center justify-between gap-2">
|
||||
<FrameTitle>Linux-клиенты</FrameTitle>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button type="button" size="icon-sm" variant="outline" aria-label="Обновить клиентов" disabled={busy || !segment.appliedRevision} onClick={refresh}><RefreshCwIcon /></Button>
|
||||
{!readOnly && <Button type="button" size="sm" disabled={busy} onClick={() => { setEdit(null); setOpen(true) }}><PlusIcon />Подключить Linux</Button>}
|
||||
{manualGroup}
|
||||
</div>
|
||||
</FrameHeader>
|
||||
{clients.size ? [...clients].map(([key, client]) => <FramePanel key={key} className="grid min-w-0 gap-3 p-0">
|
||||
<section aria-label={"Клиент " + client.name} className="grid min-w-0 gap-3">
|
||||
<h3 className="px-4 pt-3 text-sm font-semibold">{client.name}</h3>
|
||||
{!!client.tunnels.length && <TunnelTable data={client.tunnels} columns={columns} busy={busy} />}
|
||||
{client.hasGroups && <div className="grid gap-3 px-4 pb-4">
|
||||
<h4 className="text-sm font-medium">Группы туннелей</h4>
|
||||
{renderGroups(key)}
|
||||
</div>}
|
||||
</section>
|
||||
</FramePanel>) : <FramePanel className="min-w-0 p-0"><TunnelTable data={rows} columns={columns} busy={busy} /></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?.chooseTransport ? "Добавить туннель" : edit?.addProtocol ? "Добавить другой протокол" : edit ? "Доступ и выход клиента" : "Подключить Linux"}</SheetTitle>
|
||||
<SheetDescription>Укажите VPS и выберите, куда направлять его трафик.</SheetDescription>
|
||||
{error && <p className="text-sm text-destructive" role="alert">{error}</p>}
|
||||
</SheetHeader>
|
||||
{open && <ClientForm segment={segment} edit={edit} nodes={nodes} backendUrl={backendUrl} catalog={catalog} busy={busy}
|
||||
setAddProtocol={addProtocol => setEdit(selection => selection && { ...selection, addProtocol })}
|
||||
save={async input => { if (await save(input)) setOpen(false) }} cancel={() => setOpen(false)} />}
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</Frame>
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
"use client"
|
||||
|
||||
import { useId, type ReactNode } from "react"
|
||||
import { useId, useState, type ReactNode } from "react"
|
||||
import Link from "next/link"
|
||||
import { PlusIcon, XIcon } from "lucide-react"
|
||||
import type { IxSite } from "@mmapp/contracts/internet-exchange"
|
||||
import type { IxNodeInventory, 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"
|
||||
@@ -15,7 +15,7 @@ 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 }
|
||||
type Choice = { value: string; label: string; disabled?: boolean }
|
||||
|
||||
function TextField({ label, value, edit, numeric, placeholder }: {
|
||||
label: string; value: string | number; edit: (value: string) => void; numeric?: boolean; placeholder?: string
|
||||
@@ -29,7 +29,7 @@ function TextField({ label, value, edit, numeric, placeholder }: {
|
||||
}
|
||||
|
||||
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
|
||||
label: string; value?: T; options: readonly { value: T; label: string; disabled?: boolean }[]; edit: (value: T) => void; disabled: boolean
|
||||
}) {
|
||||
const id = useId()
|
||||
return <Field className="min-w-0">
|
||||
@@ -37,7 +37,7 @@ function Pick<T extends string>({ label, value, options, edit, disabled }: {
|
||||
<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>
|
||||
<SelectContent>{options.map(item => <SelectItem key={item.value} value={item.value} disabled={item.disabled}>{item.label}</SelectItem>)}</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
}
|
||||
@@ -62,25 +62,29 @@ function Lines({ label, value, edit }: { label: string; value: string[]; edit: (
|
||||
</Field>
|
||||
}
|
||||
|
||||
function Entries<T>({ title, items, edit, make, addLabel, max, readOnly, children }: {
|
||||
function Entries<T>({ title, items, edit, make, addLabel, max, readOnly, children, label, visible }: {
|
||||
title: string; items: T[]; edit: (items: T[]) => void; make: () => T
|
||||
addLabel: string; max: number; readOnly: boolean; children: (item: T, edit: (item: T) => void) => ReactNode
|
||||
label?: (item: T) => string; visible?: (item: T) => boolean
|
||||
}) {
|
||||
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>}
|
||||
const [expanded, setExpanded] = useState<number | null>(null)
|
||||
const rows = items.map((item, index) => ({ item, index })).filter(({ item }) => !visible || visible(item))
|
||||
return <section className="grid min-w-0 gap-2 border-t py-3">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<h4 className="text-sm font-medium">{title} <span className="text-muted-foreground">· {rows.length}</span></h4>
|
||||
{!readOnly && <Button type="button" variant="outline" size="sm" disabled={items.length >= max}
|
||||
onClick={() => { setExpanded(items.length); edit([...items, make()]) }}><PlusIcon aria-hidden />{addLabel}</Button>}
|
||||
</div>
|
||||
</details>
|
||||
{rows.map(({ item, index }) => <div key={index} className="min-w-0 border-s-2 ps-3">
|
||||
<Button type="button" size="sm" variant="ghost" aria-expanded={expanded === index}
|
||||
onClick={() => setExpanded(expanded === index ? null : index)}>{label?.(item) || "Запись " + (index + 1)}</Button>
|
||||
{expanded === index && <fieldset disabled={readOnly} className="grid gap-3 py-2">
|
||||
{children(item, update => edit(items.map((entry, position) => position === index ? update : entry)))}
|
||||
{!readOnly && <Button type="button" size="sm" className="w-fit" variant="ghost" aria-label={title + " — удалить запись " + (index + 1)}
|
||||
onClick={() => { setExpanded(null); edit(items.filter((_, position) => position !== index)) }}><XIcon aria-hidden />Удалить</Button>}
|
||||
</fieldset>}
|
||||
</div>)}
|
||||
</section>
|
||||
}
|
||||
|
||||
const columns = "grid min-w-0 gap-3 sm:grid-cols-2"
|
||||
@@ -91,13 +95,21 @@ const kinds = [
|
||||
{ value: "wireguard", label: "WireGuard" }, { value: "gre-ipsec", label: "GRE/IPsec" }, { value: "uplink", label: "Аплинк" },
|
||||
] as const
|
||||
|
||||
function InterfaceFields({ value, edit, peers, readOnly, segmentName }: {
|
||||
function InterfaceFields({ value, edit, peers, readOnly, segmentName, inventory }: {
|
||||
value: Binding; edit: (value: Binding) => void; peers: Choice[]; readOnly: boolean; segmentName: string
|
||||
inventory: IxNodeInventory["interfaces"]
|
||||
}) {
|
||||
const wireGuard = value.provisionWireguard
|
||||
const choices = inventory.filter(item => item.name === value.name || value.kind === "uplink" ||
|
||||
(value.kind === "wireguard" ? ["wg", "wireguard"] : ["gre", "gre-tunnel"]).includes(item.type))
|
||||
.map(item => ({ value: item.name, label: [item.name, item.addresses.join(", "), item.restriction].filter(Boolean).join(" · "),
|
||||
disabled: item.name !== value.name && (item.disabled || !!item.restriction) }))
|
||||
if (value.name && !choices.some(item => item.value === value.name)) choices.unshift({ value: value.name, label: value.name, disabled: false })
|
||||
return <>
|
||||
<div className={columns}>
|
||||
<TextField label="Имя интерфейса" value={value.name} edit={name => edit({ ...value, name })} />
|
||||
{wireGuard || !inventory.length ? <TextField label="Имя интерфейса" value={value.name} edit={name => edit({ ...value, name })} />
|
||||
: <Pick label="Интерфейс CHR" value={value.name || undefined} options={choices} disabled={readOnly}
|
||||
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}
|
||||
@@ -128,21 +140,33 @@ function InterfaceFields({ value, edit, peers, readOnly, segmentName }: {
|
||||
</>
|
||||
}
|
||||
|
||||
function PathFields({ title, value, edit, interfaces, readOnly }: {
|
||||
title: string; value: Path; edit: (value: Path) => void; interfaces: Choice[]; readOnly: boolean
|
||||
function PathFields({ title, value, edit, interfaces, inventory, readOnly }: {
|
||||
title: string; value: Path; edit: (value: Path) => void; interfaces: Choice[]; inventory: IxNodeInventory["interfaces"]; readOnly: boolean
|
||||
}) {
|
||||
const choices = value.viaMain ? inventory.filter(item => !interfaces.some(choice => choice.value === item.name) && !item.disabled)
|
||||
.map(item => ({ value: item.name, label: item.name })) : [...interfaces]
|
||||
if (value.interface && !choices.some(item => item.value === value.interface)) choices.unshift({ value: value.interface, label: value.interface })
|
||||
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} />
|
||||
<div className="sm:col-span-3"><Flag label="WAN из таблицы main" checked={!!value.viaMain} disabled={readOnly}
|
||||
edit={viaMain => edit({ ...emptyPath(""), viaMain })} /></div>
|
||||
<Pick label="Интерфейс пути" value={value.interface || undefined} options={choices} 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
|
||||
function GroupFields({ value, edit, interfaces, inventory, alternatives, readOnly }: {
|
||||
value: Group; edit: (value: Group) => void; interfaces: Choice[]; inventory: IxNodeInventory["interfaces"]
|
||||
alternatives: Group[]; readOnly: boolean
|
||||
}) {
|
||||
const selectedBackup = alternatives.find(other => other.primary.interface === value.backup?.interface &&
|
||||
other.primary.nextHop === value.backup?.nextHop && other.primary.probe === value.backup?.probe)
|
||||
return <>
|
||||
<Pick label="Резервный выход" value={value.backup ? selectedBackup?.id ?? ":manual" : ""} disabled={readOnly}
|
||||
options={[none, ...alternatives.map(other => ({ value: other.id, label: other.id })), { value: ":manual", label: "Указать другой шлюз" }]}
|
||||
edit={id => edit({ ...value, backup: id === ":manual" ? emptyPath(interfaces.find(item => item.value !== value.primary.interface)?.value ?? "")
|
||||
: alternatives.find(other => other.id === id)?.primary })} />
|
||||
<div className={columns}>
|
||||
<TextField label="Имя группы шлюзов" value={value.id} edit={id => edit({ ...value, id })} />
|
||||
<TextField label="Служебный адрес шлюза" value={value.gateway} edit={gateway => edit({ ...value, gateway })} />
|
||||
@@ -150,10 +174,9 @@ function GroupFields({ value, edit, interfaces, readOnly }: {
|
||||
{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 })} />}
|
||||
<PathFields title="Основной путь" value={value.primary} interfaces={interfaces} inventory={inventory} readOnly={readOnly} edit={primary => edit({ ...value, primary })} />
|
||||
{value.backup && <PathFields title="Резервный путь" value={value.backup} interfaces={interfaces} inventory={inventory}
|
||||
readOnly={readOnly} edit={backup => edit({ ...value, backup })} />}
|
||||
</>
|
||||
}
|
||||
|
||||
@@ -188,41 +211,44 @@ function PeerFields({ value, edit, interfaces, groups, readOnly }: {
|
||||
</>
|
||||
}
|
||||
|
||||
export function IxSiteEditor({ site, edit, peers, readOnly, segmentName }: {
|
||||
export function IxSiteEditor({ site, edit, peers, readOnly, segmentName, inventory }: {
|
||||
site: IxSite; edit: (fields: Partial<IxSite>) => void; peers: Choice[]; readOnly: boolean; segmentName: string
|
||||
inventory: IxNodeInventory["interfaces"]
|
||||
}) {
|
||||
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} />}
|
||||
return <div className="grid min-w-0 gap-2">
|
||||
<Entries<Binding> title="Интерфейсы маршрутизации" label={item => item.name} visible={item => !item.linux && !item.provisionTransit} items={site.interfaces} edit={interfaces => edit({ interfaces })}
|
||||
make={() => ({ name: "", kind: "wireguard", prefixes: [] })} max={80} addLabel="Добавить интерфейс" readOnly={readOnly}>
|
||||
{(value, update) => <InterfaceFields value={value} edit={update} peers={peers} readOnly={readOnly} segmentName={segmentName} inventory={inventory} />}
|
||||
</Entries>
|
||||
<Entries<Group> title="Группы шлюзов" items={site.groups} edit={groups => edit({ groups })}
|
||||
<Entries<Group> title="Выходы и резерв" label={item => item.id} 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} />}
|
||||
{(value, update) => <GroupFields value={value} edit={update} interfaces={interfaces} inventory={inventory}
|
||||
alternatives={site.groups.filter(group => group.id !== value.id && group.primary.interface !== value.primary.interface &&
|
||||
group.gateway.includes(":") === value.gateway.includes(":"))} readOnly={readOnly} />}
|
||||
</Entries>
|
||||
<Entries title="Статические маршруты" items={site.routes} edit={routes => edit({ routes })}
|
||||
<Entries title="Статические маршруты" label={item => item.prefix} 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}
|
||||
<Entries<Peer> title="BGP-соседи" label={item => item.id} 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">
|
||||
<fieldset disabled={readOnly} 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>
|
||||
</fieldset>
|
||||
</details>
|
||||
</fieldset>
|
||||
</div>
|
||||
}
|
||||
+70
-26
@@ -1,9 +1,9 @@
|
||||
"use client"
|
||||
|
||||
import { useMemo } from "react"
|
||||
import { useEffect, useMemo, useState } from "react"
|
||||
import { type ColumnDef, useTable } from "@tanstack/react-table"
|
||||
import { FileTextIcon, PlusIcon, XIcon } from "lucide-react"
|
||||
import type { IxConfiguration, IxSegment, IxSite, IxSiteObservation } from "@mmapp/contracts/internet-exchange"
|
||||
import type { IxConfiguration, IxNodeInventory, IxSegment, IxSite, IxSiteObservation } from "@mmapp/contracts/internet-exchange"
|
||||
import { DataGridShell } from "@/components/data-grids/shared/data-grid-shell"
|
||||
import { EmptyState } from "@/components/empty-state"
|
||||
import { Badge } from "@/components/reui/badge"
|
||||
@@ -13,14 +13,15 @@ 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 { requestJson } from "@/shared/api/http-client"
|
||||
import { IxSiteEditor } from "./ix-site-editor"
|
||||
|
||||
export type IxNode = { id: number; name: string; site: string; country: string; enabled: boolean }
|
||||
export type IxNode = { id: number; name: string; site: string; country: string; enabled: boolean; type?: string }
|
||||
type Route = IxSiteObservation["routes"][number]
|
||||
|
||||
export const nodeLabel = (nodes: readonly IxNode[], id: number) => nodes.find(node => node.id === id)?.name || `Узел ${id}`
|
||||
export const newSite = (): IxSite => ({
|
||||
serverId: 0, autonomousSystem: 64512, routerId: "",
|
||||
serverId: 0, autonomousSystem: 64512, routerId: "", autoRouterId: true,
|
||||
interfaces: [], groups: [], exits: [], routes: [], neighbors: [], discardNetworks: [],
|
||||
})
|
||||
|
||||
@@ -40,16 +41,64 @@ export function SegmentGrid({ rows, nodes, loading, open, empty }: {
|
||||
</Button>
|
||||
) },
|
||||
{ id: "sites", header: "Площадки", size: 230, cell: ({ row }) => row.original.configuration.sites.map(site => nodeLabel(nodes, site.serverId)).join(", ") },
|
||||
{ id: "neighbors", header: "BGP-соседи", size: 115, cell: ({ row }) =>
|
||||
<span className="tabular-nums">{row.original.configuration.sites.reduce((total, site) => total + site.neighbors.length, 0)}</span> },
|
||||
{ id: "clients", header: "Linux-клиенты", size: 125, cell: ({ row }) =>
|
||||
<span className="tabular-nums">{row.original.configuration.sites.reduce((total, site) => total + site.interfaces.filter(item => item.linux).length, 0)}</span> },
|
||||
{ id: "state", header: "Состояние", size: 140, cell: ({ row }) => <SegmentStatus segment={row.original} /> },
|
||||
], [nodes, open])
|
||||
const table = useTable({ features: dataGridFeatures, manualPagination: true, data: rows, columns, getRowId: row => row.id })
|
||||
return <DataGridShell table={table} recordCount={rows.length} isLoading={loading} loadingMode="skeleton" emptyMessage={empty} />
|
||||
}
|
||||
|
||||
export function ConfigurationFields({ configuration, nodes, peers, readOnly, change }: {
|
||||
export function useIxNodeInventory(backendUrl: string, serverId: number, segmentId?: string) {
|
||||
const path = serverId > 0 ? `/api/ix/nodes/${serverId}/inventory${segmentId ? "?segmentId=" + segmentId : ""}` : null
|
||||
const [result, setResult] = useState<{ path: string; inventory?: IxNodeInventory; error?: string }>()
|
||||
const [refresh, setRefresh] = useState(0)
|
||||
useEffect(() => {
|
||||
if (!path) return
|
||||
const controller = new AbortController()
|
||||
void requestJson<IxNodeInventory>(backendUrl, path, { signal: controller.signal }).then(inventory => {
|
||||
if (!Array.isArray(inventory?.interfaces) || !Array.isArray(inventory.defaultRoutes)) throw new Error("Неполный каталог интерфейсов")
|
||||
if (!controller.signal.aborted) setResult({ path, inventory })
|
||||
}).catch(() => {
|
||||
if (!controller.signal.aborted) setResult({ path, error: "Не удалось прочитать интерфейсы CHR" })
|
||||
})
|
||||
return () => controller.abort()
|
||||
}, [backendUrl, path, refresh])
|
||||
return { ...(result?.path === path ? result : undefined), loading: path !== null && result?.path !== path,
|
||||
reload: () => { setResult(undefined); setRefresh(value => value + 1) } }
|
||||
}
|
||||
|
||||
function IxInventoryFields({ site, segmentId, backendUrl, fieldId, peers, readOnly, segmentName, edit }: {
|
||||
site: IxSite; segmentId?: string; backendUrl: string; fieldId: string; peers: { value: string; label: string }[]
|
||||
readOnly: boolean; segmentName: string; edit: (fields: Partial<IxSite>) => void
|
||||
}) {
|
||||
const { inventory, error, loading, reload } = useIxNodeInventory(backendUrl, site.serverId, segmentId)
|
||||
const suggested = site.routerId || (site.autoRouterId ? inventory?.routerId ?? "" : "")
|
||||
return <>
|
||||
<Field className="min-w-0">
|
||||
<FieldLabel htmlFor={fieldId + "-router"}>Router ID</FieldLabel>
|
||||
<Input id={fieldId + "-router"} value={suggested} placeholder="Подбирается автоматически" readOnly={readOnly}
|
||||
onChange={event => edit({ routerId: event.target.value, autoRouterId: !event.target.value })} />
|
||||
<FieldDescription>{suggested ? site.autoRouterId ? "Назначен автоматически" : "Задан вручную" :
|
||||
loading ? "Проверяем занятые идентификаторы…" : "Свободный ID будет выбран при сохранении."}</FieldDescription>
|
||||
</Field>
|
||||
<div className="grid min-w-0 gap-3 sm:col-span-2 lg:col-span-3">
|
||||
{site.serverId > 0 && <div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<span className="text-sm text-muted-foreground" role="status">
|
||||
{loading ? "Читаем интерфейсы CHR…" : error ?? `Интерфейсы CHR · ${inventory?.interfaces?.length ?? 0}`}
|
||||
</span>
|
||||
<Button type="button" size="sm" variant="outline" disabled={loading} onClick={reload}>Обновить интерфейсы</Button>
|
||||
</div>}
|
||||
<IxSiteEditor site={site} segmentName={segmentName} readOnly={readOnly} edit={edit} peers={peers}
|
||||
inventory={inventory?.interfaces ?? []} />
|
||||
</div>
|
||||
</>
|
||||
}
|
||||
|
||||
export function ConfigurationFields({ configuration, nodes, peers, readOnly, change, backendUrl, segmentId, section }: {
|
||||
section: "configuration" | "routes"
|
||||
configuration: IxConfiguration; nodes: IxNode[]; peers: IxNode[]; readOnly: boolean; change: (value: IxConfiguration) => void
|
||||
backendUrl: string; segmentId?: string
|
||||
}) {
|
||||
function updateSite(index: number, fields: Partial<IxSite>) {
|
||||
change({ ...configuration, sites: configuration.sites.map((site, position) => position === index ? { ...site, ...fields } : site) })
|
||||
@@ -57,7 +106,7 @@ export function ConfigurationFields({ configuration, nodes, peers, readOnly, cha
|
||||
const canAddSite = configuration.sites.length < 2 && nodes.filter(node => node.enabled).length > configuration.sites.length
|
||||
|
||||
return <div className="grid min-w-0 gap-3">
|
||||
<Frame spacing="sm">
|
||||
{section === "configuration" && <Frame spacing="sm">
|
||||
<FrameHeader><FrameTitle>Сегмент</FrameTitle></FrameHeader>
|
||||
<FramePanel>
|
||||
<Field className="max-w-md">
|
||||
@@ -67,17 +116,16 @@ export function ConfigurationFields({ configuration, nodes, peers, readOnly, cha
|
||||
{!readOnly && <FieldDescription>Латинские строчные буквы, цифры и дефисы.</FieldDescription>}
|
||||
</Field>
|
||||
</FramePanel>
|
||||
</Frame>
|
||||
</Frame>}
|
||||
{configuration.sites.map((site, index) => {
|
||||
const fieldId = `ix-site-${index}`
|
||||
const choices = nodes.filter(node => node.id === site.serverId || (node.enabled && !configuration.sites.some((other, i) => i !== index && other.serverId === node.id)))
|
||||
return <Frame key={fieldId} spacing="sm">
|
||||
<FrameHeader className="flex-row items-center justify-between gap-2">
|
||||
<div className="min-w-0">
|
||||
<FrameTitle>Площадка {index + 1}</FrameTitle>
|
||||
{site.serverId > 0 && <FrameDescription className="wrap-anywhere">{nodeLabel(nodes, site.serverId)}</FrameDescription>}
|
||||
<FrameTitle>{section === "configuration" ? "Площадка " + (index + 1) : nodeLabel(nodes, site.serverId)}</FrameTitle>
|
||||
</div>
|
||||
{!readOnly && configuration.sites.length > 1 && <Button type="button" size="icon-sm" variant="ghost"
|
||||
{section === "configuration" && !readOnly && configuration.sites.length > 1 && <Button type="button" size="icon-sm" variant="ghost"
|
||||
aria-label={`Убрать площадку ${index + 1}`}
|
||||
onClick={() => change({ ...configuration, sites: configuration.sites.filter((_, position) => position !== index) })}>
|
||||
<XIcon aria-hidden />
|
||||
@@ -85,38 +133,34 @@ export function ConfigurationFields({ configuration, nodes, peers, readOnly, cha
|
||||
</FrameHeader>
|
||||
<FramePanel className="grid gap-4">
|
||||
<div className="grid min-w-0 gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
<Field className="min-w-0">
|
||||
{section === "configuration" && <Field className="min-w-0">
|
||||
<FieldLabel htmlFor={fieldId}>Узел IX</FieldLabel>
|
||||
<Select
|
||||
value={site.serverId ? String(site.serverId) : null}
|
||||
items={choices.map(node => ({ value: String(node.id), label: node.name }))}
|
||||
disabled={readOnly}
|
||||
onValueChange={value => { if (value) updateSite(index, { serverId: Number(value) }) }}
|
||||
onValueChange={value => { if (value && Number(value) !== site.serverId) updateSite(index, { ...newSite(), serverId: Number(value) }) }}
|
||||
>
|
||||
<SelectTrigger id={fieldId} className="w-full"><SelectValue placeholder="Выберите узел" /></SelectTrigger>
|
||||
<SelectContent>
|
||||
{choices.map(node => <SelectItem key={node.id} value={String(node.id)} disabled={!node.enabled}>{node.name}</SelectItem>)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
<Field className="min-w-0">
|
||||
</Field>}
|
||||
{section === "routes" && <Field className="min-w-0">
|
||||
<FieldLabel htmlFor={fieldId + "-asn"}>Локальный ASN</FieldLabel>
|
||||
<Input id={fieldId + "-asn"} inputMode="numeric" value={site.autonomousSystem || ""} readOnly={readOnly}
|
||||
onChange={event => { if (/^\d*$/.test(event.target.value)) updateSite(index, { autonomousSystem: Number(event.target.value) }) }} />
|
||||
</Field>
|
||||
<Field className="min-w-0">
|
||||
<FieldLabel htmlFor={fieldId + "-router"}>Router ID</FieldLabel>
|
||||
<Input id={fieldId + "-router"} placeholder="192.0.2.10" value={site.routerId} readOnly={readOnly}
|
||||
onChange={event => updateSite(index, { routerId: event.target.value })} />
|
||||
</Field>
|
||||
</Field>}
|
||||
{section !== "configuration" && <IxInventoryFields site={site} segmentId={segmentId} backendUrl={backendUrl} fieldId={fieldId}
|
||||
readOnly={readOnly} segmentName={configuration.name} 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 }))} />}
|
||||
</div>
|
||||
<IxSiteEditor site={site} segmentName={configuration.name} readOnly={readOnly} edit={fields => updateSite(index, fields)}
|
||||
peers={peers.filter(node => node.id !== site.serverId && (node.enabled || site.interfaces.some(binding => binding.peerServerId === node.id)))
|
||||
.map(node => ({ value: String(node.id), label: node.name }))} />
|
||||
</FramePanel>
|
||||
</Frame>
|
||||
})}
|
||||
{!readOnly && canAddSite && <Button type="button" variant="outline" size="sm" className="w-fit"
|
||||
{section === "configuration" && !readOnly && canAddSite && <Button type="button" variant="outline" size="sm" className="w-fit"
|
||||
onClick={() => change({ ...configuration, sites: [...configuration.sites, newSite()] })}>
|
||||
<PlusIcon aria-hidden />Добавить площадку
|
||||
</Button>}
|
||||
|
||||
+252
-129
@@ -3,13 +3,16 @@
|
||||
import { useEffect, useRef, useState } from "react"
|
||||
import Link from "next/link"
|
||||
import { ArrowLeftIcon, CircleAlertIcon, NetworkIcon, PlusIcon, RefreshCwIcon, Trash2Icon } from "lucide-react"
|
||||
import { ixSegmentConfigurationSchema, type IxChange, type IxConfiguration, type IxLinuxAccess, type IxLinuxBinding, type IxWebPlan, type IxSegment, type IxSiteObservation } from "@mmapp/contracts/internet-exchange"
|
||||
import { ixSegmentConfigurationSchema, type IxChange, type IxConfiguration, type IxLinuxAccess, type IxLinuxBinding, type IxLinuxClientRequest, type IxLinuxPath, type IxTransitRequest, type IxWebPlan, type IxSegment, type IxSiteObservation } from "@mmapp/contracts/internet-exchange"
|
||||
import { Alert, AlertDescription, AlertTitle } from "@/components/reui/alert"
|
||||
import { Frame, FrameDescription, FrameHeader, FramePanel, FrameTitle } from "@/components/reui/frame"
|
||||
import { EmptyState } from "@/components/empty-state"
|
||||
import { PageHeader } from "@/components/page-header"
|
||||
import { Button, buttonVariants } from "@/components/ui/button"
|
||||
import { ServerRailLayout, ServerRailMobileButton } from "@/components/server-rail-layout"
|
||||
import { ALL_SERVERS_ID } from "@/components/server-tile-rail"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from "@/components/ui/alert-dialog"
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Skeleton } from "@/components/ui/skeleton"
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
||||
@@ -18,14 +21,27 @@ import { can, ensureAuthConfig } from "@/lib/auth"
|
||||
import { useDataSource } from "@/lib/data-source"
|
||||
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"
|
||||
import { copyIxImportLink } from "./ix-import-link"
|
||||
|
||||
type Tab = "configuration" | "routes" | "changes" | "linux"
|
||||
type Tab = "configuration" | "routes" | "linux"
|
||||
|
||||
const title = "Точки обмена трафиком"
|
||||
const describe = (error: unknown) => error instanceof Error ? error.message : "Не удалось выполнить операцию IX"
|
||||
const json = (value: unknown) => JSON.stringify(value, null, 2)
|
||||
const post = (value: unknown) => ({ method: "POST", body: JSON.stringify(value) })
|
||||
|
||||
function download(name: string, content: string) {
|
||||
const url = URL.createObjectURL(new Blob([content], { type: "text/plain;charset=utf-8" }))
|
||||
const link = document.createElement("a")
|
||||
link.href = url
|
||||
link.download = name
|
||||
link.click()
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000)
|
||||
}
|
||||
|
||||
const actionLabels = { create: "Создать", update: "Обновить", delete: "Удалить" } as const
|
||||
|
||||
function RouterOsChanges({ changes, nodes }: { changes: IxWebPlan["changes"]; nodes: IxNode[] }) {
|
||||
@@ -57,9 +73,13 @@ export default function IxPage() {
|
||||
const [draft, setDraft] = useState<IxConfiguration | null>(null)
|
||||
const [advanced, setAdvanced] = useState<string | null>(null)
|
||||
const [filter, setFilter] = useState("")
|
||||
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("")
|
||||
const [plan, setPlan] = useState<IxWebPlan | null>(null)
|
||||
const [removalPlan, setRemovalPlan] = useState<IxWebPlan | null>(null)
|
||||
const [tab, setTab] = useState<Tab>("configuration")
|
||||
@@ -109,8 +129,10 @@ export default function IxPage() {
|
||||
}
|
||||
}, [inDetail])
|
||||
|
||||
const rows = segments.filter(segment => segment.configuration.name.includes(filter.trim().toLowerCase()))
|
||||
const enabledNodes = nodes.filter(node => node.enabled)
|
||||
const rows = segments.filter(segment => (activeNode === ALL_SERVERS_ID ||
|
||||
segment.configuration.sites.some(site => String(site.serverId) === activeNode)) &&
|
||||
segment.configuration.name.includes(filter.trim().toLowerCase()))
|
||||
const enabledNodes = nodes.filter(node => node.enabled && (activeNode === ALL_SERVERS_ID || String(node.id) === activeNode))
|
||||
const live = prefsHydrated && mode === "live"
|
||||
const canCreate = live && write && !loading && enabledNodes.length > 0
|
||||
const savedConfiguration = selected ? json(selected.configuration) : null
|
||||
@@ -119,21 +141,25 @@ export default function IxPage() {
|
||||
|
||||
function invalidateReview() {
|
||||
setPlan(null)
|
||||
setReview("")
|
||||
setReviewError("")
|
||||
setRemovalPlan(null)
|
||||
setNotice("")
|
||||
}
|
||||
|
||||
function open(segment: IxSegment | null) {
|
||||
function open(segment: IxSegment | null, defaultTab: Tab = segment ? "linux" : "configuration") {
|
||||
focusAfterNavigation.current = !inDetail
|
||||
setSelected(segment)
|
||||
setDraft(segment?.configuration ?? { name: "", sites: [{ ...newSite(), serverId: enabledNodes.length === 1 ? enabledNodes[0].id : 0 }] })
|
||||
setAdvanced(null)
|
||||
setObservations(null)
|
||||
setLinux(null)
|
||||
setLinuxPath(null)
|
||||
setLinuxBindings([])
|
||||
setTab("configuration")
|
||||
setTab(defaultTab)
|
||||
setError("")
|
||||
invalidateReview()
|
||||
if (defaultTab === "linux" && segment?.appliedRevision) void perform(() => loadLinuxBindings(segment))
|
||||
}
|
||||
|
||||
function close() {
|
||||
@@ -145,7 +171,9 @@ export default function IxPage() {
|
||||
}
|
||||
|
||||
function change(): IxChange {
|
||||
const configuration = ixSegmentConfigurationSchema.parse(advanced === null ? draft : JSON.parse(advanced))
|
||||
const configuration = ixSegmentConfigurationSchema.parse(advanced === null && draft
|
||||
? { ...draft, sites: draft.sites.map(site => ({ ...site, routerId: site.routerId || (site.autoRouterId ? "0.0.0.0" : "") })) }
|
||||
: JSON.parse(advanced ?? "null"))
|
||||
return { ...(selected ? { id: selected.id } : {}), revision: selected?.revision ?? 0, configuration }
|
||||
}
|
||||
|
||||
@@ -153,23 +181,29 @@ export default function IxPage() {
|
||||
setBusy(true)
|
||||
setError("")
|
||||
setNotice("")
|
||||
try { await work() } catch (error) { setError(describe(error)) }
|
||||
try { await work(); return true } catch (error) { setError(describe(error)); return false }
|
||||
finally { setBusy(false) }
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (selected && !dirty) {
|
||||
await reviewSegment(selected, selected.configuration.name)
|
||||
return
|
||||
}
|
||||
const { segment } = await requestJson<{ segment: IxSegment }>(backendUrl, "/api/ix/segments", post(change()))
|
||||
open(segment)
|
||||
setSegments(current => current.some(item => item.id === segment.id)
|
||||
? current.map(item => item.id === segment.id ? segment : item)
|
||||
: [segment, ...current])
|
||||
setNotice("Черновик сохранён")
|
||||
await reviewSegment(segment, segment.configuration.name)
|
||||
}
|
||||
|
||||
async function prepare() {
|
||||
if (!selected || !canPlan) return
|
||||
async function prepare(segment: IxSegment, resume = false) {
|
||||
setPlan(null)
|
||||
setPlan(await requestJson<IxWebPlan>(backendUrl, "/api/ix/segments/" + selected.id + "/plan", post({ revision: selected.revision })))
|
||||
setReviewError("")
|
||||
try {
|
||||
setPlan(await requestJson<IxWebPlan>(backendUrl, "/api/ix/segments/" + segment.id + "/plan", post({
|
||||
revision: segment.revision, ...(resume && { resume }),
|
||||
})))
|
||||
} catch (error) {
|
||||
setReviewError(describe(error))
|
||||
}
|
||||
}
|
||||
|
||||
async function prepareRemoval() {
|
||||
@@ -193,59 +227,148 @@ export default function IxPage() {
|
||||
setPlan(null)
|
||||
try {
|
||||
const { segment } = await requestJson<{ segment: IxSegment }>(backendUrl,
|
||||
"/api/ix/segments/" + selected.id + "/apply", post({ revision: plan.revision, digest: plan.digest }))
|
||||
"/api/ix/segments/" + selected.id + "/apply", post({ revision: plan.revision, digest: plan.digest, ...(plan.resume && { resume: true }) }))
|
||||
setSelected(segment)
|
||||
setDraft(segment.configuration)
|
||||
setAdvanced(null)
|
||||
setObservations(null)
|
||||
setLinux(null)
|
||||
setLinuxPath(null)
|
||||
setLinuxBindings([])
|
||||
setSegments(current => current.map(item => item.id === segment.id ? segment : item))
|
||||
setReview("")
|
||||
setReviewError("")
|
||||
setNotice("Конфигурация IX применена")
|
||||
if (tab === "linux" || selected.appliedRevision === null) {
|
||||
setTab("linux")
|
||||
await loadLinuxBindings(segment).catch(error => setError(describe(error)))
|
||||
} else if (tab === "routes") {
|
||||
await observe(segment).catch(error => setError(describe(error)))
|
||||
}
|
||||
} catch (error) {
|
||||
throw new Error(describe(error) + " Проверьте состояние сегмента перед повторным применением.")
|
||||
setReviewError(describe(error))
|
||||
}
|
||||
}
|
||||
|
||||
async function observe() {
|
||||
if (!selected?.appliedRevision) return
|
||||
const { sites } = await requestJson<{ sites: IxSiteObservation[] }>(backendUrl, `/api/ix/segments/${selected.id}/status`)
|
||||
async function observe(segment = selected) {
|
||||
if (!segment?.appliedRevision) return
|
||||
const { sites } = await requestJson<{ sites: IxSiteObservation[] }>(backendUrl, `/api/ix/segments/${segment.id}/status`)
|
||||
setObservations(sites)
|
||||
}
|
||||
|
||||
async function loadLinuxBindings() {
|
||||
if (!selected) return
|
||||
async function loadLinuxBindings(segment = selected) {
|
||||
if (!segment) return
|
||||
setLinux(null)
|
||||
setLinuxBindings([])
|
||||
const { items } = await requestJson<{ items: IxLinuxBinding[] }>(backendUrl, `/api/ix/segments/${selected.id}/linux`)
|
||||
const { items } = await requestJson<{ items: IxLinuxBinding[] }>(backendUrl, `/api/ix/segments/${segment.id}/linux`)
|
||||
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 })
|
||||
const access = await requestJson<IxLinuxAccess>(backendUrl, `/api/ix/segments/${selected.id}/linux?${query}`)
|
||||
setLinux({ ...binding, ...access })
|
||||
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, ...(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, ...(transportOnly && { transportOnly }) }))
|
||||
: await requestJson<IxLinuxAccess>(backendUrl, `/api/ix/segments/${selected.id}/linux?${query}`)
|
||||
setLinux({ ...binding, ...access, transportOnly })
|
||||
}
|
||||
|
||||
async function copyLinuxImport(binding: IxLinuxBinding) {
|
||||
if (!selected) return
|
||||
await copyIxImportLink(backendUrl, `/api/ix/segments/${selected.id}/linux/credential`, {
|
||||
serverId: binding.serverId, interfaceName: binding.interfaceName,
|
||||
})
|
||||
setNotice("Ссылка скопирована. На VPS откройте ix-client → L. Ссылка действует до 5 минут.")
|
||||
}
|
||||
|
||||
async function inspectLinux(binding: IxLinuxBinding) {
|
||||
if (!selected) return
|
||||
setLinuxPath(null)
|
||||
const query = new URLSearchParams({ serverId: String(binding.serverId), interfaceName: binding.interfaceName })
|
||||
const path = await requestJson<IxLinuxPath>(backendUrl, `/api/ix/segments/${selected.id}/linux/path?${query}`)
|
||||
setLinuxPath({ name: binding.name, interfaceName: binding.interfaceName, ...path })
|
||||
}
|
||||
|
||||
async function stageClient(input: IxLinuxClientRequest | IxLinuxBinding) {
|
||||
if (!selected || dirty || !write) return
|
||||
const path = `/api/ix/segments/${selected.id}`
|
||||
const result = "revision" in input
|
||||
? await requestJson<{ segment: IxSegment; interfaceName: string }>(backendUrl, path + "/linux", post(input))
|
||||
: await requestJson<{ segment: IxSegment }>(backendUrl, path + "/linux/revoke",
|
||||
post({ revision: selected.revision, serverId: input.serverId, interfaceName: input.interfaceName }))
|
||||
await reviewSegment(result.segment, "revision" in input ? "Доступ клиента " + input.name : "Отзыв доступа " + (input.name ?? input.interfaceName))
|
||||
}
|
||||
|
||||
async function stageTransit(input: IxTransitRequest) {
|
||||
if (!selected || dirty || !write) return
|
||||
const { segment } = await requestJson<{ segment: IxSegment }>(backendUrl,
|
||||
`/api/ix/segments/${selected.id}/transit`, post(input))
|
||||
await reviewSegment(segment, "Выход через " + nodeLabel(peers, input.targetServerId))
|
||||
}
|
||||
|
||||
async function reviewSegment(segment: IxSegment, title: string) {
|
||||
setSelected(segment)
|
||||
setDraft(segment.configuration)
|
||||
setAdvanced(null)
|
||||
setSegments(current => current.some(item => item.id === segment.id)
|
||||
? current.map(item => item.id === segment.id ? segment : item) : [segment, ...current])
|
||||
setLinux(null)
|
||||
setLinuxPath(null)
|
||||
setReview(title)
|
||||
await prepare(segment)
|
||||
}
|
||||
|
||||
function closeReview() {
|
||||
if (busy) return
|
||||
setReview("")
|
||||
setPlan(null)
|
||||
setReviewError("")
|
||||
setNotice("Изменения сохранены в черновике. Нажмите «Сохранить», чтобы вернуться к подтверждению.")
|
||||
}
|
||||
|
||||
function showTab(next: Tab) {
|
||||
if (next === tab || busy) return
|
||||
if (advanced !== null) {
|
||||
try { setDraft(change().configuration); setAdvanced(null) } catch (error) { setError(describe(error)); return }
|
||||
}
|
||||
setError("")
|
||||
setTab(next)
|
||||
if (next === "routes" && observations === null && selected?.appliedRevision) void perform(observe)
|
||||
if (next === "linux" && selected?.appliedRevision) void perform(loadLinuxBindings)
|
||||
}
|
||||
|
||||
const settingsProps = draft && {
|
||||
configuration: draft, nodes, peers, backendUrl, segmentId: selected?.id, readOnly: !live || !write || busy,
|
||||
change: (value: IxConfiguration) => { setDraft(value); invalidateReview() },
|
||||
}
|
||||
|
||||
const listEmpty = error ? "Не удалось загрузить список" :
|
||||
filter.trim() ? "Сегменты не найдены" : !live ? "Подключите backend" : "Нет сегментов IX"
|
||||
const listDescription = error ? "Повторите загрузку списка." : filter.trim() ? "Попробуйте другое имя сегмента." :
|
||||
!live ? "Откройте раздел в режиме «Живые»." : enabledNodes.length ? undefined : "Сначала добавьте сервер типа IX Node."
|
||||
|
||||
return <>
|
||||
<PageHeader crumbs={inDetail ? [{ label: "Сегменты IX" }, { label: selected?.configuration.name ?? "Новый сегмент" }] : [{ label: title }]} />
|
||||
return <ServerRailLayout items={nodes.map(node => ({ ...node, id: String(node.id), type: "ix-node", selectable: node.enabled }))}
|
||||
selectedId={activeNode} allCount={nodes.length} loading={loading} showCount={false} preserveSelection onSelect={id => {
|
||||
if (busy || id === activeNode) return
|
||||
setActiveNode(id)
|
||||
setFilter("")
|
||||
const forNode = segments.filter(segment => segment.configuration.sites.some(site => String(site.serverId) === id))
|
||||
if (forNode.length === 1) open(forNode[0], "linux")
|
||||
else close()
|
||||
}}
|
||||
header={<PageHeader crumbs={inDetail ? [{ label: "Сегменты IX" }, { label: selected?.configuration.name ?? "Новый сегмент" }] : [{ label: title }]}
|
||||
actions={<ServerRailMobileButton />} />}>
|
||||
<div className="min-h-0 min-w-0 flex-1 overflow-y-auto">
|
||||
<div className="mx-auto flex w-full max-w-6xl min-w-0 flex-col gap-4 p-4 md:gap-5 md:p-6" aria-busy={busy}>
|
||||
<div className="flex w-full min-w-0 flex-col gap-4 p-4 md:gap-5 md:p-6" aria-busy={busy}>
|
||||
{inDetail && <Button type="button" variant="ghost" size="sm" className="w-fit" disabled={busy} onClick={close}>
|
||||
<ArrowLeftIcon aria-hidden />Все сегменты
|
||||
</Button>}
|
||||
@@ -258,30 +381,33 @@ export default function IxPage() {
|
||||
{inDetail && selected && <SegmentStatus segment={selected} />}
|
||||
</div>
|
||||
{inDetail ? (selected && <p className="mt-1 text-sm text-muted-foreground">
|
||||
Ревизия {selected.revision}{selected.appliedRevision ? ` · Применена ревизия ${selected.appliedRevision}` : ""}
|
||||
Ревизия {selected.revision}{selected.appliedRevision && selected.appliedRevision !== selected.revision ? ` · Применена ревизия ${selected.appliedRevision}` : ""}
|
||||
</p>) : <p className="mt-1 text-sm text-muted-foreground">Сегменты IX, площадки и маршрутизация</p>}
|
||||
</div>
|
||||
{inDetail && selected && live && write && <AlertDialog open={removalPlan !== null}
|
||||
onOpenChange={open => { if (open) void perform(prepareRemoval); else setRemovalPlan(null) }}>
|
||||
<AlertDialogTrigger render={<Button type="button" variant="outline" size="sm" disabled={busy} />}>
|
||||
<Trash2Icon aria-hidden />Удалить сегмент
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle className="wrap-anywhere">Удалить {selected.configuration.name}?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{selected.appliedRevision
|
||||
? "Этот сегмент перестанет передавать трафик. Управляемая конфигурация будет удалена с узлов IX."
|
||||
: "Черновик будет удалён из списка сегментов. Конфигурация роутеров останется прежней."}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
{removalPlan && <RouterOsChanges changes={removalPlan.changes} nodes={nodes} />}
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Отмена</AlertDialogCancel>
|
||||
<AlertDialogAction variant="destructive" disabled={busy} onClick={() => void perform(removeSegment)}>Удалить</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>}
|
||||
{inDetail && live && write && <div className="flex flex-wrap items-center gap-2">
|
||||
{(dirty || canPlan) && <Button type="button" size="sm" disabled={busy} onClick={() => void perform(save)}>Сохранить</Button>}
|
||||
{selected && <AlertDialog open={removalPlan !== null}
|
||||
onOpenChange={open => { if (open) void perform(prepareRemoval); else setRemovalPlan(null) }}>
|
||||
<AlertDialogTrigger render={<Button type="button" variant="outline" size="sm" disabled={busy} />}>
|
||||
<Trash2Icon aria-hidden />Удалить сегмент
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle className="wrap-anywhere">Удалить {selected.configuration.name}?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{selected.appliedRevision
|
||||
? "Этот сегмент перестанет передавать трафик. Управляемая конфигурация будет удалена с узлов IX."
|
||||
: "Черновик будет удалён из списка сегментов. Конфигурация роутеров останется прежней."}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
{removalPlan && <RouterOsChanges changes={removalPlan.changes} nodes={nodes} />}
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Отмена</AlertDialogCancel>
|
||||
<AlertDialogAction variant="destructive" disabled={busy} onClick={() => void perform(removeSegment)}>Удалить</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>}
|
||||
</div>}
|
||||
{!inDetail && <div className="flex flex-wrap items-center gap-2">
|
||||
<Button type="button" size="icon-sm" variant="outline" disabled={busy || loading || !live} aria-label="Обновить список"
|
||||
onClick={() => void perform(() => load())}><RefreshCwIcon aria-hidden /></Button>
|
||||
@@ -308,16 +434,16 @@ export default function IxPage() {
|
||||
</Frame> : <Tabs value={tab} onValueChange={value => showTab(value as Tab)} className="min-w-0 gap-3">
|
||||
<div className="min-w-0 overflow-x-auto border-b pb-1">
|
||||
<TabsList variant="line" aria-label="Разделы сегмента">
|
||||
<TabsTrigger value="configuration">Конфигурация</TabsTrigger>
|
||||
<TabsTrigger value="linux">Linux-клиенты</TabsTrigger>
|
||||
<TabsTrigger value="routes">Маршруты и BGP</TabsTrigger>
|
||||
<TabsTrigger value="changes">План изменений</TabsTrigger>
|
||||
{selected && <>
|
||||
<TabsTrigger value="linux">Linux-клиенты</TabsTrigger>
|
||||
<TabsTrigger value="routes">Маршрутизация</TabsTrigger>
|
||||
</>}
|
||||
<TabsTrigger value="configuration">Настройки IX</TabsTrigger>
|
||||
</TabsList>
|
||||
</div>
|
||||
|
||||
<TabsContent value="configuration" className="grid min-w-0 gap-3">
|
||||
{advanced === null ? <ConfigurationFields configuration={draft} nodes={nodes} peers={peers} readOnly={!live || !write || busy}
|
||||
change={value => { setDraft(value); invalidateReview() }} /> : <Frame spacing="sm">
|
||||
{advanced === null ? settingsProps && <ConfigurationFields {...settingsProps} section="configuration" /> : <Frame spacing="sm">
|
||||
<FrameHeader><FrameTitle>Конфигурация JSON</FrameTitle><FrameDescription>Интерфейсы, группы шлюзов, маршруты и BGP-политики.</FrameDescription></FrameHeader>
|
||||
<FramePanel>
|
||||
<Textarea aria-label="Конфигурация JSON" spellCheck={false} readOnly={!live || !write || busy} rows={14}
|
||||
@@ -325,7 +451,6 @@ export default function IxPage() {
|
||||
</FramePanel>
|
||||
</Frame>}
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{write && <Button type="button" size="sm" disabled={busy || !live} onClick={() => void perform(save)}>Сохранить черновик</Button>}
|
||||
{advanced === null ? <Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => setAdvanced(json(draft))}>
|
||||
{write ? "Редактировать JSON" : "Показать JSON"}
|
||||
</Button> : <Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => void perform(async () => {
|
||||
@@ -336,8 +461,10 @@ export default function IxPage() {
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="routes" className="grid min-w-0 gap-3">
|
||||
{!selected?.appliedRevision ? <EmptyState title="Конфигурация ещё не применена"
|
||||
description="Маршруты и BGP-сессии появятся после применения плана." className="py-8" /> : <>
|
||||
{selected && !dirty && live && write && <IxExits segment={selected} nodes={peers} backendUrl={backendUrl} busy={busy}
|
||||
error={error} save={input => perform(() => stageTransit(input))} />}
|
||||
{settingsProps && <ConfigurationFields {...settingsProps} section="routes" />}
|
||||
{!!selected?.appliedRevision && <>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => void perform(observe)}>
|
||||
<RefreshCwIcon aria-hidden />Обновить состояние
|
||||
@@ -349,44 +476,54 @@ export default function IxPage() {
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="linux" className="grid min-w-0 gap-3">
|
||||
<Frame spacing="sm">
|
||||
{selected ? <IxClientBonds key={selected.id + ":" + selected.appliedRevision} segmentId={selected.id} segments={segments}
|
||||
backendUrl={backendUrl} nodes={peers} readOnly={!write || busy || dirty} live={live} download={download}>
|
||||
{(bondAction, catalog, renderGroups, manualGroup) => <IxLinuxClients segment={selected} nodes={peers} backendUrl={backendUrl}
|
||||
bondAction={bondAction} catalog={catalog} renderGroups={renderGroups} manualGroup={manualGroup}
|
||||
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, transportOnly) => void perform(() => exportLinux(binding, transportOnly))}
|
||||
copyImport={binding => void perform(() => copyLinuxImport(binding))}
|
||||
inspect={binding => void perform(() => inspectLinux(binding))} />}
|
||||
</IxClientBonds>
|
||||
: <EmptyState title="Сохраните сегмент" description="После сохранения можно подключать клиентов." />}
|
||||
{linuxPath && <Frame spacing="sm">
|
||||
<FrameHeader>
|
||||
<FrameTitle>Доступ для Linux-серверов</FrameTitle>
|
||||
<FrameDescription>Выдайте каждому серверу отдельное подключение из применённой ревизии сегмента.</FrameDescription>
|
||||
<FrameTitle>Маршруты клиента · {linuxPath.name ?? linuxPath.interfaceName}</FrameTitle>
|
||||
<FrameDescription>{linuxPath.policy ?? "Только сети IX"} · {new Date(linuxPath.observedAt).toLocaleString("ru-RU")}</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 className="grid gap-2 text-sm">
|
||||
<p className="text-muted-foreground">Чтение FIB CHR. Доставку пакетов проверяют с Linux-клиента.</p>
|
||||
{linuxPath.routes.length ? <ul className="grid gap-2">{linuxPath.routes.map((route, index) => <li key={index}>
|
||||
<code>{route.prefix}</code> · {route.immediateGateway || route.gateway || "—"} · {route.active ? "активен" : "неактивен"}
|
||||
</li>)}</ul> : <p>Подходящих маршрутов сейчас нет.</p>}
|
||||
</FramePanel>
|
||||
</Frame>
|
||||
</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>}
|
||||
<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 останется прямым."
|
||||
: "Для подключения нужен индивидуальный PSK, выданный оператором."}</p>
|
||||
{(!linux.policy || linux.kind === "wireguard") && <pre className="max-h-64 min-w-0 overflow-auto rounded-md border p-3 text-xs">{linux.template}</pre>}
|
||||
<Button type="button" variant="outline" size="sm" className="w-fit" onClick={() => download(linux.filename, linux.template)}>
|
||||
Скачать {linux.managedWireguard ? "шаблон" : linux.filename}
|
||||
</Button>
|
||||
{linux.setup && <>
|
||||
{linux.policy && write ? <pre className="min-w-0 overflow-auto rounded-md border p-3 text-xs">{
|
||||
"sudo apt install charon-systemd strongswan-swanctl\nsudo systemctl start strongswan\nsudo sh ./" +
|
||||
linux.filename.replace(/\.conf$/, "-setup.sh")
|
||||
}</pre> : <pre className="min-w-0 overflow-auto rounded-md border p-3 text-xs">{linux.setup}</pre>}
|
||||
<Button type="button" variant="outline" size="sm" className="w-fit"
|
||||
onClick={() => download(linux.filename.replace(/\.conf$/, "-setup.sh"), "#!/bin/sh\nset -eu\n" + linux.setup + "\n")}>Скачать скрипт GRE</Button>
|
||||
</>}
|
||||
{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(", ")}</>}
|
||||
@@ -395,43 +532,29 @@ export default function IxPage() {
|
||||
</Frame>}
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="changes" className="grid min-w-0 gap-3">
|
||||
<Frame spacing="sm">
|
||||
<FrameHeader>
|
||||
<FrameTitle>Изменения RouterOS</FrameTitle>
|
||||
<FrameDescription>Предпросмотр сравнивает сохранённую ревизию с текущим состоянием узлов.</FrameDescription>
|
||||
</FrameHeader>
|
||||
<FramePanel className="grid min-w-0 gap-3">
|
||||
{!write ? <p className="text-sm text-muted-foreground">Нужно право изменять сетевую конфигурацию.</p>
|
||||
: dirty ? <p className="text-sm text-muted-foreground">Сохраните черновик на вкладке «Конфигурация».</p>
|
||||
: selected?.appliedRevision === selected?.revision ? <p className="text-sm text-muted-foreground">Текущая ревизия применена.</p>
|
||||
: <Button type="button" size="sm" variant="outline" className="w-fit" disabled={!canPlan || busy}
|
||||
onClick={() => void perform(prepare)}>Построить предпросмотр</Button>}
|
||||
{plan && <div className="grid min-w-0 gap-3 border-t pt-3">
|
||||
<p className="text-sm font-medium">Ревизия {plan.revision} · операций RouterOS: {plan.changes.length}</p>
|
||||
{plan.changes.length === 0 && <p className="text-sm text-muted-foreground">Конфигурация RouterOS совпадает с черновиком. Применение обновит ревизию в MikrotikManager.</p>}
|
||||
<RouterOsChanges changes={plan.changes} nodes={nodes} />
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger render={<Button type="button" size="sm" className="w-fit" disabled={busy || !canPlan} />}>
|
||||
Применить план
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Применить конфигурацию IX?</AlertDialogTitle>
|
||||
<AlertDialogDescription>Будет применена ревизия {plan.revision} сегмента {selected?.configuration.name}. Операций RouterOS: {plan.changes.length}.</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Отмена</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={() => void perform(apply)}>Применить</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>}
|
||||
</FramePanel>
|
||||
</Frame>
|
||||
</TabsContent>
|
||||
</Tabs>}
|
||||
<Dialog open={!!review} onOpenChange={open => { if (!open) closeReview() }}>
|
||||
<DialogContent showCloseButton={!busy} className="max-h-[85dvh] overflow-y-auto sm:max-w-xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Подтвердите сохранение</DialogTitle>
|
||||
<DialogDescription>{review} · ревизия {selected?.revision}. После подтверждения изменения вступят в силу на узлах IX.</DialogDescription>
|
||||
</DialogHeader>
|
||||
{reviewError ? <Alert variant="destructive"><AlertTitle>Не удалось подтвердить состояние IX</AlertTitle>
|
||||
<AlertDescription>{reviewError}</AlertDescription></Alert>
|
||||
: plan ? <>
|
||||
<p className="text-sm font-medium">{plan.changes.length ? "Операций RouterOS: " + plan.changes.length : "RouterOS уже настроена. Будет отмечена применённая ревизия."}</p>
|
||||
<RouterOsChanges changes={plan.changes} nodes={peers} />
|
||||
</> : <p role="status" className="text-sm text-muted-foreground">{busy ? "Проверяем конфигурацию на узлах…" : "Обновите сравнение перед сохранением."}</p>}
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" disabled={busy} onClick={closeReview}>Отмена</Button>
|
||||
{reviewError && selected && <Button type="button" variant="outline" disabled={busy}
|
||||
onClick={() => void perform(() => prepare(selected, true))}>Сверить и продолжить</Button>}
|
||||
{plan ? <Button type="button" disabled={busy || !canPlan} onClick={() => void perform(apply)}>Подтвердить</Button>
|
||||
: reviewError && selected && <Button type="button" disabled={busy} onClick={() => void perform(() => prepare(selected))}>Повторить проверку</Button>}
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
</ServerRailLayout>
|
||||
}
|
||||
+1907
-1771
File diff suppressed because it is too large.
Load diff
+202
-168
@@ -1,17 +1,22 @@
|
||||
"use client"
|
||||
|
||||
import { Suspense, useCallback, useEffect, useMemo, useState } from "react"
|
||||
import { Suspense, useCallback, useEffect, useMemo, useState, type ReactNode } from "react"
|
||||
import { useSearchParams } from "next/navigation"
|
||||
import {
|
||||
ActivityIcon,
|
||||
ChartColumnIcon,
|
||||
DatabaseIcon,
|
||||
GaugeIcon,
|
||||
GlobeIcon,
|
||||
ServerIcon,
|
||||
UsersIcon,
|
||||
} from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { PageHeader } from "@/components/page-header"
|
||||
import { PageTitle } from "@/components/page-title"
|
||||
import { KpiStatGrid } from "@/components/reui-kit/kpi-stat-grid"
|
||||
import { CapacityGrid, type CapacityItem } from "@/components/reui-kit/ops-blocks"
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
||||
import { DataPageCard } from "@/components/data-page-card"
|
||||
import { DataPageToolbar } from "@/components/data-page-toolbar"
|
||||
import { SegmentedControl } from "@/components/form-kit"
|
||||
@@ -35,6 +40,7 @@ import {
|
||||
} from "@/lib/statistics-dims"
|
||||
import { statisticsContextError, STATISTICS_CONTEXT_KEYS } from "@/lib/statistics-context"
|
||||
import { readStatisticsRange } from "@/lib/statistics-range"
|
||||
import { demoStatistics, demoStatisticsPivot } from "@/lib/statistics-demo"
|
||||
import { useDataSource } from "@/lib/data-source"
|
||||
import { fmtBps, formatBytes } from "@/lib/fmt-rate"
|
||||
import {
|
||||
@@ -102,8 +108,13 @@ function readDim(sp: URLSearchParams): StatisticsSliceKind {
|
||||
return t && isStatisticsSliceKind(t) ? t : "users"
|
||||
}
|
||||
|
||||
function readView(sp: URLSearchParams): "explore" | "pivot" {
|
||||
return sp.get("view") === "pivot" ? "pivot" : "explore"
|
||||
type StatisticsView = "overview" | "explore" | "pivot"
|
||||
|
||||
/** Вкладка макета v3: Обзор, Срезы (explore) или Сводная (pivot); старые ссылки с разрезом открывают Срезы. */
|
||||
function readView(sp: URLSearchParams): StatisticsView {
|
||||
const v = sp.get("view")
|
||||
if (v === "pivot" || v === "explore" || v === "overview") return v
|
||||
return sp.has("dim") || sp.has("tab") || SLICE_KEYS.some((key) => sp.has(key)) ? "explore" : "overview"
|
||||
}
|
||||
|
||||
function readPlanes(sp: URLSearchParams): "unique" | "all" {
|
||||
@@ -241,7 +252,9 @@ function StatisticsPageInner() {
|
||||
const pivotCol = useMemo(() => readPivotDim(searchParams, "pivotCol", "service"), [searchParams])
|
||||
|
||||
const [retry, setRetry] = useState(0)
|
||||
const requestKey = JSON.stringify({ backendUrl, isLive, range, slices, view, pivotRow, pivotCol, planes, retry, rangeError, paramsError })
|
||||
// Обзор и Срезы читают один и тот же куб — смена этих вкладок не перезапрашивает данные.
|
||||
const pivotView = view === "pivot"
|
||||
const requestKey = JSON.stringify({ backendUrl, isLive, range, slices, pivotView, pivotRow, pivotCol, planes, retry, rangeError, paramsError })
|
||||
const [result, setResult] = useState<{
|
||||
key: string; data: StatisticsDto; pivot: StatisticsPivotDto; error: string | null
|
||||
} | null>(null)
|
||||
@@ -249,7 +262,9 @@ function StatisticsPageInner() {
|
||||
const loading = isLive && !rangeError && !paramsError && current === null
|
||||
const error = rangeError ?? paramsError ?? current?.error ?? null
|
||||
const dataReady = isLive && current !== null && !error
|
||||
const pivot = dataReady ? current.pivot : EMPTY_PIVOT
|
||||
// Демо-режим без API: показываем демо-куб, чтобы раздел выглядел как с данными.
|
||||
const demo = useMemo(() => (isLive || rangeError ? null : demoStatistics(range.from, range.to, planes)), [isLive, rangeError, range, planes])
|
||||
const pivot = dataReady ? current.pivot : demo && !paramsError ? demoStatisticsPivot(pivotRow, pivotCol) : EMPTY_PIVOT
|
||||
|
||||
const updateParams = useCallback(
|
||||
(patch: Record<string, string | undefined>) => {
|
||||
@@ -295,7 +310,7 @@ function StatisticsPageInner() {
|
||||
const dto = await getStatistics(backendUrl, query)
|
||||
if (cancelled) return
|
||||
let matrix = EMPTY_PIVOT
|
||||
if (view === "pivot" && pivotRow !== pivotCol) {
|
||||
if (pivotView && pivotRow !== pivotCol) {
|
||||
matrix = await getStatisticsPivot(backendUrl, {
|
||||
...query,
|
||||
row: pivotRow,
|
||||
@@ -313,11 +328,11 @@ function StatisticsPageInner() {
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [backendUrl, isLive, prefsHydrated, range, slices, view, pivotRow, pivotCol, planes, requestKey, rangeError, paramsError])
|
||||
}, [backendUrl, isLive, prefsHydrated, range, slices, pivotView, pivotRow, pivotCol, planes, requestKey, rangeError, paramsError])
|
||||
|
||||
const viewData = dataReady ? current.data : EMPTY
|
||||
const viewData = dataReady ? current.data : demo && !paramsError ? demo : EMPTY
|
||||
const sliced = hasAnySlice(slices)
|
||||
const emptyCube = !isLive || (!loading && viewData.kpis.bytes === 0 && viewData.interfaces.length === 0)
|
||||
const emptyCube = !loading && viewData.kpis.bytes === 0 && viewData.interfaces.length === 0
|
||||
|
||||
function handleRowClick(kind: StatisticsSliceKind, row: StatisticsBreakdownRow) {
|
||||
if (kind === "users" && row.id === STATISTICS_UNBOUND_USER_ID) return
|
||||
@@ -348,175 +363,194 @@ function StatisticsPageInner() {
|
||||
: sliced
|
||||
? `${STATISTICS_DIMS.filter((d) => !hiddenKinds(slices).has(d.id)).length} разрезов`
|
||||
: `${rowsForKind(viewData, dim).length} строк`
|
||||
const hasContext = STATISTICS_CONTEXT_KEYS.some((key) => searchParams.has(key))
|
||||
const resetContext = () => updateParams(Object.fromEntries(STATISTICS_CONTEXT_KEYS.map((key) => [key, undefined])))
|
||||
const scope = planes === "all" ? "Все плоскости" : "GRE/WG клиентов, без hops"
|
||||
const bytesOf = (rows: StatisticsBreakdownRow[]) => rows.reduce((total, row) => total + row.bytes, 0)
|
||||
const shareOf = (bytes: number) => (kpis.bytes > 0 ? Math.min(1, bytes / kpis.bytes) : 0)
|
||||
const bytesItem = (id: string, title: string, caption: string, bytes: number, icon: ReactNode): CapacityItem => {
|
||||
const [valueText, ...unit] = formatBytes(bytes).split(" ")
|
||||
return { id, title, caption, value: bytes, total: kpis.bytes, ratio: shareOf(bytes), tone: shareOf(bytes) >= 0.999 ? "wn" : "ok", icon, valueText, unit: unit.join(" ") }
|
||||
}
|
||||
const planesControl = (
|
||||
<SegmentedControl
|
||||
value={planes}
|
||||
onChange={(next) => updateParams({ planes: next === "all" ? "all" : undefined })}
|
||||
options={[
|
||||
{ value: "all", label: "Все плоскости" },
|
||||
{ value: "unique", label: "GRE/WG клиентов" },
|
||||
]}
|
||||
/>
|
||||
)
|
||||
const cubeState = isLive && !dataReady ? (
|
||||
<div role="status" className="p-6 text-sm text-muted-foreground">{loading ? "Загрузка статистики…" : rangeError || paramsError ? "Исправьте параметры отчёта для загрузки статистики." : "Статистика недоступна. Повторите загрузку."}</div>
|
||||
) : emptyCube ? (
|
||||
<EmptyState
|
||||
title="Нет данных куба"
|
||||
description="За выбранный период нет IPFIX-фактов. Куб заполняется с момента деплоя, без бэкфилла за год."
|
||||
/>
|
||||
) : null
|
||||
const sliceChips = (
|
||||
<SliceChips
|
||||
chips={chips}
|
||||
onRemove={(key) => {
|
||||
const next = { ...slices }
|
||||
delete next[key as keyof CubeSlices]
|
||||
setSlices(next)
|
||||
}}
|
||||
/>
|
||||
)
|
||||
const filters = <StatisticsFilters key={JSON.stringify(slices)} slices={slices} onApply={setSlices} />
|
||||
const tabTrigger = "h-auto flex-none px-3 py-2.5 after:bottom-[-1px]"
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col">
|
||||
<PageHeader
|
||||
crumbs={[{ label: "Обзор", href: "/dashboard" }, { label: "Статистика" }]}
|
||||
actions={rangeError ? <Button type="button" variant="outline" onClick={() => setRange(rangeForPreset("7d"))}>Выбрать последние 7 дней</Button> : <PeriodSelector range={range} onChange={setRange} />}
|
||||
/>
|
||||
<PageHeader crumbs={[{ label: "Главная", href: "/dashboard" }, { label: "Обзор" }, { label: "Статистика" }]} />
|
||||
|
||||
<div className="flex flex-1 flex-col gap-4 overflow-y-auto px-4 py-4 md:gap-6 md:px-6 md:py-5">
|
||||
{!isLive ? (
|
||||
<Alert>
|
||||
<AlertTitle>Живые данные выключены</AlertTitle>
|
||||
<AlertDescription>
|
||||
Куб статистики строится из IPFIX. Переключитесь на живой источник, чтобы увидеть отчёт.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
) : null}
|
||||
<div className="flex flex-1 flex-col gap-6 overflow-y-auto px-4 pt-5 pb-10 md:px-7 md:pt-6">
|
||||
<PageTitle
|
||||
icon={<ChartColumnIcon />}
|
||||
title="Статистика"
|
||||
description="Куб NetFlow: измерения, срезы и период · уникальный объём без дублей"
|
||||
actions={
|
||||
<>
|
||||
{rangeError ? <Button type="button" variant="outline" onClick={() => setRange(rangeForPreset("7d"))}>Выбрать последние 7 дней</Button> : <PeriodSelector range={range} onChange={setRange} />}
|
||||
<Button type="button" variant="outline" onClick={resetContext} disabled={!hasContext}>Сбросить параметры отчёта</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
|
||||
{error ? (
|
||||
<Alert variant="destructive" role="alert">
|
||||
<AlertTitle>{rangeError ? "Некорректный период" : paramsError ? "Параметры отчёта требуют внимания" : "Ошибка загрузки"}</AlertTitle>
|
||||
<AlertDescription>{error}{!rangeError && !paramsError && <Button type="button" variant="outline" size="sm" onClick={() => setRetry(n => n + 1)}>Повторить загрузку</Button>}{paramsError && <Button type="button" variant="outline" size="sm" onClick={() => updateParams(Object.fromEntries(STATISTICS_CONTEXT_KEYS.map(key => [key, undefined])))}>Сбросить параметры отчёта</Button>}</AlertDescription>
|
||||
</Alert>
|
||||
) : null}
|
||||
<div className="flex flex-col gap-5">
|
||||
{!isLive ? (
|
||||
<Alert variant="warning">
|
||||
<AlertTitle>Живые данные выключены</AlertTitle>
|
||||
<AlertDescription>
|
||||
Показан демо-куб. Статистика строится из IPFIX — переключитесь на живой источник, чтобы увидеть свой отчёт.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
) : null}
|
||||
|
||||
{!slices.serverId && dataReady && !emptyCube ? (
|
||||
<Alert>
|
||||
<AlertTitle>Уникальный объём</AlertTitle>
|
||||
<AlertDescription>
|
||||
Объём — трафик клиентов на GRE/WG, без повторного учёта JH↔EN и WAN.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
) : null}
|
||||
{error ? (
|
||||
<Alert variant={paramsError ? "warning" : "destructive"} role="alert">
|
||||
<AlertTitle>{rangeError ? "Некорректный период" : paramsError ? "Параметры отчёта требуют внимания" : "Ошибка загрузки"}</AlertTitle>
|
||||
<AlertDescription>{error}{!rangeError && !paramsError && <Button type="button" variant="outline" size="sm" onClick={() => setRetry(n => n + 1)}>Повторить загрузку</Button>}</AlertDescription>
|
||||
</Alert>
|
||||
) : null}
|
||||
|
||||
{(dataReady || loading) && <KpiStatGrid
|
||||
aria-label="Сводка трафика"
|
||||
isLoading={loading}
|
||||
skeletonCount={5}
|
||||
items={[
|
||||
{
|
||||
id: "bytes",
|
||||
label: "Объём",
|
||||
value: formatBytes(kpis.bytes),
|
||||
hint: "GRE/WG клиентов, без hops",
|
||||
icon: <DatabaseIcon />,
|
||||
iconClassName: "text-muted-foreground",
|
||||
},
|
||||
{
|
||||
id: "packets",
|
||||
label: "Пакеты",
|
||||
value: kpis.packets.toLocaleString("ru-RU"),
|
||||
hint: kpis.topService ? `топ: ${kpis.topService}` : undefined,
|
||||
icon: <ActivityIcon />,
|
||||
iconClassName: "text-muted-foreground",
|
||||
},
|
||||
{
|
||||
id: "bps",
|
||||
label: "Средний bitrate",
|
||||
value: fmtBps(kpis.avgBps),
|
||||
icon: <GaugeIcon />,
|
||||
iconClassName: "text-muted-foreground",
|
||||
},
|
||||
{
|
||||
id: "users",
|
||||
label: "Пользователи",
|
||||
value: String(kpis.users),
|
||||
icon: <UsersIcon />,
|
||||
iconClassName: "text-muted-foreground",
|
||||
},
|
||||
{
|
||||
id: "servers",
|
||||
label: "Серверы",
|
||||
value: String(kpis.servers),
|
||||
hint: slices.serverId
|
||||
? (kpis.ifaces ? `${kpis.ifaces} iface` : undefined)
|
||||
: planes === "all"
|
||||
? "WAN и дубли в списке"
|
||||
: "без WAN и overlay",
|
||||
icon: <ServerIcon />,
|
||||
iconClassName: "text-muted-foreground",
|
||||
},
|
||||
]}
|
||||
/>}
|
||||
{(dataReady || loading || (demo && !paramsError)) && <KpiStatGrid
|
||||
aria-label="Сводка трафика"
|
||||
isLoading={loading}
|
||||
skeletonCount={4}
|
||||
items={[
|
||||
{
|
||||
id: "bytes",
|
||||
label: planes === "all" ? "Объём" : "Уникальный объём",
|
||||
value: formatBytes(kpis.bytes),
|
||||
hint: slices.serverId ? (kpis.ifaces ? `${kpis.ifaces} iface` : undefined) : planes === "all" ? "WAN и дубли в списке" : "без WAN и overlay",
|
||||
icon: <DatabaseIcon />,
|
||||
iconClassName: planes === "all" ? "text-muted-foreground" : "text-success",
|
||||
},
|
||||
{
|
||||
id: "packets",
|
||||
label: "Пакеты",
|
||||
value: kpis.packets.toLocaleString("ru-RU"),
|
||||
hint: kpis.topService ? `топ: ${kpis.topService}` : undefined,
|
||||
icon: <ActivityIcon />,
|
||||
iconClassName: "text-muted-foreground",
|
||||
},
|
||||
{
|
||||
id: "bps",
|
||||
label: "Средний bitrate",
|
||||
value: fmtBps(kpis.avgBps),
|
||||
icon: <GaugeIcon />,
|
||||
iconClassName: "text-muted-foreground",
|
||||
},
|
||||
{
|
||||
id: "users",
|
||||
label: "Пользователи",
|
||||
value: String(kpis.users),
|
||||
hint: `Серверы: ${kpis.servers}`,
|
||||
icon: <UsersIcon />,
|
||||
iconClassName: "text-muted-foreground",
|
||||
},
|
||||
]}
|
||||
/>}
|
||||
|
||||
{dataReady && <StatisticsVolumeChart series={viewData.series} grain={viewData.grain} />}
|
||||
<Tabs value={view} onValueChange={(next) => updateParams({ view: String(next) })} className="gap-5">
|
||||
<TabsList variant="line" className="h-auto w-full justify-start gap-1 overflow-x-auto border-b p-0">
|
||||
<TabsTrigger value="overview" className={tabTrigger}>Обзор</TabsTrigger>
|
||||
<TabsTrigger value="pivot" className={tabTrigger}>Сводная (куб)</TabsTrigger>
|
||||
<TabsTrigger value="explore" className={tabTrigger}>Срезы</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<DataPageCard>
|
||||
<DataPageToolbar
|
||||
leading={
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<SegmentedControl
|
||||
value={view}
|
||||
onChange={(next) => updateParams({ view: next === "pivot" ? "pivot" : "explore" })}
|
||||
options={[
|
||||
{ value: "explore", label: "Разрез" },
|
||||
{ value: "pivot", label: "Сводка" },
|
||||
]}
|
||||
/>
|
||||
<SegmentedControl
|
||||
value={planes}
|
||||
onChange={(next) => updateParams({ planes: next === "all" ? "all" : undefined })}
|
||||
options={[
|
||||
{ value: "unique", label: "Уникальный" },
|
||||
{ value: "all", label: "Все плоскости" },
|
||||
]}
|
||||
/>
|
||||
{view === "explore" && !sliced ? (
|
||||
<DimensionSelect
|
||||
label="Критерий"
|
||||
value={dim}
|
||||
onChange={(next) => updateParams({ dim: next, tab: undefined })}
|
||||
<TabsContent value="overview" className="flex flex-col gap-5">
|
||||
{cubeState ?? (
|
||||
<>
|
||||
<StatisticsVolumeChart series={viewData.series} grain={viewData.grain} scope={scope} actions={planesControl} />
|
||||
<CapacityGrid
|
||||
label="Доли объёма"
|
||||
items={[
|
||||
bytesItem("users", "Пользователи", "GRE/WG клиентов, без hops", bytesOf(viewData.users), <UsersIcon />),
|
||||
bytesItem("servers", "Серверы", planes === "all" ? "WAN и дубли в списке" : "без WAN и overlay", bytesOf(viewData.servers), <ServerIcon />),
|
||||
bytesItem("countries", "Страны", "Топ-10", bytesOf([...viewData.countries].sort((a, b) => b.bytes - a.bytes).slice(0, 10)), <GlobeIcon />),
|
||||
]}
|
||||
/>
|
||||
) : null}
|
||||
{view === "pivot" ? (
|
||||
<>
|
||||
<PivotDimSelect
|
||||
label="Строки"
|
||||
value={pivotRow}
|
||||
exclude={pivotCol}
|
||||
onChange={(next) => updateParams({ pivotRow: next })}
|
||||
/>
|
||||
<PivotDimSelect
|
||||
label="Колонки"
|
||||
value={pivotCol}
|
||||
exclude={pivotRow}
|
||||
onChange={(next) => updateParams({ pivotCol: next })}
|
||||
/>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
}
|
||||
filterControl={<StatisticsFilters key={JSON.stringify(slices)} slices={slices} onApply={setSlices} />}
|
||||
countLabel={dataReady ? countLabel : undefined}
|
||||
/>
|
||||
<SliceChips
|
||||
chips={chips}
|
||||
onRemove={(key) => {
|
||||
const next = { ...slices }
|
||||
delete next[key as keyof CubeSlices]
|
||||
setSlices(next)
|
||||
}}
|
||||
/>
|
||||
{isLive && !dataReady ? (
|
||||
<div role="status" className="p-6 text-sm text-muted-foreground">{loading ? "Загрузка статистики…" : rangeError || paramsError ? "Исправьте параметры отчёта для загрузки статистики." : "Статистика недоступна. Повторите загрузку."}</div>
|
||||
) : emptyCube ? (
|
||||
<EmptyState
|
||||
title="Нет данных куба"
|
||||
description="За выбранный период нет IPFIX-фактов. Куб заполняется с момента деплоя, без бэкфилла за год."
|
||||
/>
|
||||
) : view === "pivot" ? (
|
||||
<StatisticsPivotGrid data={isLive ? pivot : EMPTY_PIVOT} onCellClick={handlePivotCell} isLoading={loading} />
|
||||
) : sliced ? (
|
||||
<BreakdownDashboard
|
||||
data={viewData}
|
||||
hidden={hiddenKinds(slices)}
|
||||
selectedIdFor={(kind) => selectedIdForKind(kind, slices)}
|
||||
onRowClick={handleRowClick}
|
||||
isLoading={loading}
|
||||
/>
|
||||
) : (
|
||||
<StatisticsBreakdownDataGrid
|
||||
rows={rowsForKind(viewData, dim)}
|
||||
kind={dim}
|
||||
selectedId={selectedIdForKind(dim, slices)}
|
||||
onRowClick={(row) => handleRowClick(dim, row)}
|
||||
isLoading={loading}
|
||||
/>
|
||||
)}
|
||||
</DataPageCard>
|
||||
</>
|
||||
)}
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="pivot">
|
||||
<DataPageCard>
|
||||
<DataPageToolbar
|
||||
leading={
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
{planesControl}
|
||||
<PivotDimSelect label="Строки" value={pivotRow} exclude={pivotCol} onChange={(next) => updateParams({ pivotRow: next })} />
|
||||
<PivotDimSelect label="Колонки" value={pivotCol} exclude={pivotRow} onChange={(next) => updateParams({ pivotCol: next })} />
|
||||
</div>
|
||||
}
|
||||
filterControl={filters}
|
||||
countLabel={dataReady ? countLabel : undefined}
|
||||
/>
|
||||
{sliceChips}
|
||||
{cubeState ?? <StatisticsPivotGrid data={pivot} onCellClick={handlePivotCell} isLoading={loading} />}
|
||||
</DataPageCard>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="explore">
|
||||
<DataPageCard>
|
||||
<DataPageToolbar
|
||||
leading={
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
{planesControl}
|
||||
{!sliced ? <DimensionSelect label="Критерий" value={dim} onChange={(next) => updateParams({ dim: next, tab: undefined })} /> : null}
|
||||
</div>
|
||||
}
|
||||
filterControl={filters}
|
||||
countLabel={dataReady ? countLabel : undefined}
|
||||
/>
|
||||
{sliceChips}
|
||||
{cubeState ?? (sliced ? (
|
||||
<BreakdownDashboard
|
||||
data={viewData}
|
||||
hidden={hiddenKinds(slices)}
|
||||
selectedIdFor={(kind) => selectedIdForKind(kind, slices)}
|
||||
onRowClick={handleRowClick}
|
||||
isLoading={loading}
|
||||
/>
|
||||
) : (
|
||||
<StatisticsBreakdownDataGrid
|
||||
rows={rowsForKind(viewData, dim)}
|
||||
kind={dim}
|
||||
selectedId={selectedIdForKind(dim, slices)}
|
||||
onRowClick={(row) => handleRowClick(dim, row)}
|
||||
isLoading={loading}
|
||||
/>
|
||||
))}
|
||||
</DataPageCard>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
+364
-230
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,97 @@
|
||||
BEGIN;
|
||||
|
||||
ALTER TABLE public.server_poll_storage_usage
|
||||
DROP CONSTRAINT server_poll_storage_usage_check2,
|
||||
DROP CONSTRAINT server_poll_storage_usage_admissions_check,
|
||||
DROP CONSTRAINT server_poll_storage_rows_charge,
|
||||
DROP CONSTRAINT server_poll_storage_bytes_charge,
|
||||
ADD CONSTRAINT server_poll_storage_usage_admissions_check CHECK (admissions >= 0),
|
||||
ADD CONSTRAINT server_poll_storage_rows_charge CHECK (reserved_rows = admissions * 4019 + compacted_admissions * 2),
|
||||
ADD CONSTRAINT server_poll_storage_bytes_charge CHECK (reserved_bytes = admissions * 8421376 + compacted_admissions * 32768 + archive_bytes);
|
||||
|
||||
CREATE OR REPLACE FUNCTION server_poll_storage_admission_guard() RETURNS trigger LANGUAGE plpgsql SET TimeZone='UTC' SET search_path=pg_catalog,public AS $$
|
||||
DECLARE retention integer; charged integer; r public.server_poll_archives%ROWTYPE;
|
||||
BEGIN
|
||||
PERFORM pg_advisory_xact_lock(hashtextextended('server-poll-storage-v1',0));
|
||||
IF TG_OP='DELETE' THEN
|
||||
IF NOT public.server_poll_storage_gc_allowed(OLD.receipt_id) OR EXISTS(SELECT 1 FROM public.server_poll_executions WHERE receipt_id=OLD.receipt_id)
|
||||
OR EXISTS(SELECT 1 FROM public.server_poll_intents WHERE receipt_id=OLD.receipt_id) OR EXISTS(SELECT 1 FROM public.server_poll_acks WHERE receipt_id=OLD.receipt_id)
|
||||
OR EXISTS(SELECT 1 FROM public.server_poll_receipts WHERE receipt_id=OLD.receipt_id) OR EXISTS(SELECT 1 FROM public.server_poll_quarantines WHERE receipt_id=OLD.receipt_id)
|
||||
OR EXISTS(SELECT 1 FROM public.server_poll_archives WHERE receipt_id=OLD.receipt_id) THEN RAISE EXCEPTION 'poll lifetime or children prevent admission deletion'; END IF;
|
||||
UPDATE public.server_poll_storage_usage SET admissions=admissions-CASE WHEN OLD.storage_state='full' THEN 1 ELSE 0 END,
|
||||
compacted_admissions=compacted_admissions-CASE WHEN OLD.storage_state='compacted' THEN 1 ELSE 0 END,
|
||||
archive_bytes=archive_bytes-COALESCE(OLD.archive_bytes,0),
|
||||
reserved_rows=reserved_rows-CASE WHEN OLD.storage_state='full' THEN 4019 ELSE 2 END,
|
||||
reserved_bytes=reserved_bytes-CASE WHEN OLD.storage_state='full' THEN 8421376 ELSE 32768+OLD.archive_bytes END
|
||||
WHERE scope IN('global','owner:'||OLD.owner_id);
|
||||
GET DIAGNOSTICS charged=ROW_COUNT; IF charged<>2 THEN RAISE EXCEPTION 'poll quota refund mismatch'; END IF; RETURN OLD;
|
||||
END IF;
|
||||
IF TG_OP='UPDATE' THEN
|
||||
IF OLD.storage_state='compacted' AND NEW.storage_state='compacted'
|
||||
AND current_setting('mm.poll_retire_receipt',true)=OLD.receipt_id::text
|
||||
AND (to_jsonb(OLD)-'archive_bytes')=(to_jsonb(NEW)-'archive_bytes') THEN
|
||||
SELECT * INTO r FROM public.server_poll_archives WHERE receipt_id=OLD.receipt_id AND version=2;
|
||||
IF NOT FOUND OR r.ciphertext_bytes<>NEW.archive_bytes OR NEW.archive_bytes>OLD.archive_bytes
|
||||
OR r.execution_id<>OLD.execution_id OR r.connection_id<>OLD.connection_id OR r.owner_id<>OLD.owner_id
|
||||
THEN RAISE EXCEPTION 'retired poll charge source mismatch'; END IF;
|
||||
UPDATE public.server_poll_storage_usage
|
||||
SET archive_bytes=archive_bytes-OLD.archive_bytes+NEW.archive_bytes,
|
||||
reserved_bytes=reserved_bytes-OLD.archive_bytes+NEW.archive_bytes
|
||||
WHERE scope IN ('global','owner:'||OLD.owner_id) AND compacted_admissions>=1 AND archive_bytes>=OLD.archive_bytes;
|
||||
GET DIAGNOSTICS charged=ROW_COUNT;
|
||||
IF charged<>2 THEN RAISE EXCEPTION 'retired poll charge adjustment mismatch'; END IF;
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
-- This durable one-shot marker is written and ACKed in its OWN transaction
|
||||
-- before archive construction. A committed/unknown claim never resets and
|
||||
-- the worker never retries destructive work against an already claimed full
|
||||
-- source. Claim time is maintenance metadata, not renewed execution activity.
|
||||
IF OLD.storage_state='full' AND NEW.storage_state='full' AND OLD.compaction_claim IS NULL AND OLD.compaction_claimed_at IS NULL AND OLD.compaction_claim_xid IS NULL
|
||||
AND NEW.compaction_claim IS NOT NULL AND NEW.compaction_claim_xid IS NULL
|
||||
AND(to_jsonb(OLD)-ARRAY['compaction_claim','compaction_claimed_at','compaction_claim_xid'])=(to_jsonb(NEW)-ARRAY['compaction_claim','compaction_claimed_at','compaction_claim_xid'])
|
||||
AND public.server_poll_storage_compact_allowed(OLD.receipt_id)
|
||||
THEN NEW.compaction_claimed_at:=clock_timestamp(); NEW.compaction_claim_xid:=pg_current_xact_id(); RETURN NEW; END IF;
|
||||
IF(to_jsonb(OLD)-ARRAY['claim_token','claim_attempted_at','used_rows','used_bytes','storage_state','compact_at','archive_bytes','original_activity_at']) IS DISTINCT FROM
|
||||
(to_jsonb(NEW)-ARRAY['claim_token','claim_attempted_at','used_rows','used_bytes','storage_state','compact_at','archive_bytes','original_activity_at']) THEN RAISE EXCEPTION 'poll admission identity is immutable'; END IF;
|
||||
IF OLD.storage_state<>'full' THEN RAISE EXCEPTION 'compacted poll identity cannot reopen or change'; END IF;
|
||||
IF NEW.storage_state='compacted' THEN
|
||||
SELECT * INTO r FROM public.server_poll_archives WHERE receipt_id=OLD.receipt_id AND compaction_xid=pg_current_xact_id();
|
||||
IF NOT FOUND OR NEW.used_rows<>OLD.used_rows OR NEW.used_bytes<>OLD.used_bytes OR NEW.claim_token IS DISTINCT FROM OLD.claim_token
|
||||
OR NEW.claim_attempted_at IS DISTINCT FROM OLD.claim_attempted_at OR NEW.archive_bytes<>r.ciphertext_bytes OR NEW.original_activity_at<>r.original_activity_at
|
||||
OR EXISTS(SELECT 1 FROM public.server_poll_executions WHERE receipt_id=OLD.receipt_id)
|
||||
OR EXISTS(SELECT 1 FROM public.server_poll_intents WHERE receipt_id=OLD.receipt_id) OR EXISTS(SELECT 1 FROM public.server_poll_acks WHERE receipt_id=OLD.receipt_id)
|
||||
OR EXISTS(SELECT 1 FROM public.server_poll_receipts WHERE receipt_id=OLD.receipt_id) OR EXISTS(SELECT 1 FROM public.server_poll_quarantines WHERE receipt_id=OLD.receipt_id)
|
||||
THEN RAISE EXCEPTION 'poll compaction requires the complete current-transaction archive'; END IF;
|
||||
NEW.compact_at:=r.created_at;
|
||||
UPDATE public.server_poll_storage_usage SET admissions=admissions-1,compacted_admissions=compacted_admissions+1,
|
||||
archive_bytes=archive_bytes+r.ciphertext_bytes,reserved_rows=reserved_rows-4019+2,reserved_bytes=reserved_bytes-8421376+32768+r.ciphertext_bytes
|
||||
WHERE scope IN('global','owner:'||OLD.owner_id) AND admissions>=1;
|
||||
GET DIAGNOSTICS charged=ROW_COUNT; IF charged<>2 THEN RAISE EXCEPTION 'poll compaction charge mismatch'; END IF;
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
IF NEW.compact_at IS NOT NULL OR NEW.archive_bytes IS NOT NULL OR NEW.original_activity_at IS NOT NULL THEN RAISE EXCEPTION 'full poll cannot carry archive metadata'; END IF;
|
||||
IF OLD.claim_token IS NOT NULL AND NEW.claim_token IS NULL AND OLD.claim_attempted_at IS NULL AND NEW.claim_attempted_at IS NOT NULL
|
||||
AND NEW.used_rows=OLD.used_rows AND NEW.used_bytes=OLD.used_bytes AND OLD.authority_expires_at>clock_timestamp()
|
||||
THEN NEW.claim_attempted_at:=clock_timestamp(); RETURN NEW; END IF;
|
||||
IF OLD.claim_token IS NOT DISTINCT FROM NEW.claim_token AND OLD.claim_attempted_at IS NOT DISTINCT FROM NEW.claim_attempted_at
|
||||
AND NEW.used_rows=OLD.used_rows+1 AND NEW.used_bytes>OLD.used_bytes THEN RETURN NEW; END IF;
|
||||
RAISE EXCEPTION 'poll admission cannot refresh, reopen or refund itself';
|
||||
END IF;
|
||||
IF NEW.storage_state<>'full' OR NEW.compact_at IS NOT NULL OR NEW.archive_bytes IS NOT NULL OR NEW.original_activity_at IS NOT NULL
|
||||
OR NEW.compaction_claim IS NOT NULL OR NEW.compaction_claimed_at IS NOT NULL OR NEW.compaction_claim_xid IS NOT NULL
|
||||
OR NOT public.server_poll_storage_accounting_valid() THEN RAISE EXCEPTION 'new poll requires full reservation and exact ledger'; END IF;
|
||||
SELECT requests_retention_days INTO retention FROM public.mcp_settings WHERE id=1;
|
||||
IF retention IS NULL OR retention NOT BETWEEN 1 AND 365 OR NEW.authority_issued_at>clock_timestamp() OR NEW.authority_expires_at<=clock_timestamp()
|
||||
OR NEW.claim_token IS NULL OR NEW.claim_attempted_at IS NOT NULL OR NEW.used_rows<>0 OR NEW.used_bytes<>0 THEN RAISE EXCEPTION 'new poll admission needs original live authority'; END IF;
|
||||
IF EXISTS(SELECT 1 FROM public.server_poll_storage_admissions WHERE receipt_id=NEW.receipt_id OR(identity_kind=NEW.identity_kind AND execution_id=NEW.execution_id)) THEN RAISE EXCEPTION 'poll identity already spent'; END IF;
|
||||
NEW.created_at:=clock_timestamp(); NEW.retention_days:=retention; NEW.safety_ms:=60000;
|
||||
NEW.gc_not_before:=NEW.authority_expires_at+make_interval(days=>retention)+interval '60 seconds';
|
||||
INSERT INTO public.server_poll_storage_usage(scope) VALUES('owner:'||NEW.owner_id) ON CONFLICT DO NOTHING;
|
||||
UPDATE public.server_poll_storage_usage SET admissions=admissions+1,reserved_rows=reserved_rows+4019,reserved_bytes=reserved_bytes+8421376 WHERE scope IN('global','owner:'||NEW.owner_id);
|
||||
GET DIAGNOSTICS charged=ROW_COUNT; IF charged<>2 THEN RAISE EXCEPTION 'poll admission counters unavailable'; END IF;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
|
||||
INSERT INTO public.schema_migrations (id) VALUES ('0059_server_poll_journal_limits') ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
COMMIT;
|
||||
@@ -464,6 +464,20 @@
|
||||
],
|
||||
"reason": "Общий listRevisions с REST: только метаданные, максимум 50 записей; серверная область и права проверяются до SQL, payload ревизии не выдаётся."
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/api/ix/import",
|
||||
"status": "excluded",
|
||||
"operations": [],
|
||||
"reason": "Одноразовый импорт Linux-клиента: выдаёт конфигурацию только по коду, созданному оператором IX."
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"path": "/api/ix/linux-bonds",
|
||||
"status": "excluded",
|
||||
"operations": [],
|
||||
"reason": "Каталог для формы выбора туннелей одного VPS в WebUI. Оператор сопоставляет подключения разных площадок со своими локальными интерфейсами."
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"path": "/api/ix/nodes",
|
||||
@@ -471,6 +485,13 @@
|
||||
"operations": [],
|
||||
"reason": "Служебная проекция для выбора площадок в интерфейсе. В MCP доступ к серверам определяется областью подключения."
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"path": "/api/ix/nodes/:serverId/inventory",
|
||||
"status": "mediated",
|
||||
"operations": ["network.ix.inventory"],
|
||||
"reason": "Общее чтение интерфейсов, шлюзов и кандидата Router ID. MCP проверяет серверную область, а контекст редактируемого сегмента используется в WebUI."
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"path": "/api/ix/segments",
|
||||
@@ -485,6 +506,13 @@
|
||||
"operations": [],
|
||||
"reason": "Шаблон подключения Linux оператор получает в интерфейсе для локальной настройки клиента."
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"path": "/api/ix/segments/:id/linux/path",
|
||||
"status": "mediated",
|
||||
"operations": ["network.ix.linux-path"],
|
||||
"reason": "Общее чтение маршрутов Linux-клиента из применённой ревизии. MCP проверяет доступ к узлу клиента."
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"path": "/api/ix/segments/:id/status",
|
||||
@@ -1106,7 +1134,7 @@
|
||||
"operations": [
|
||||
"traffic.live.read"
|
||||
],
|
||||
"reason": "Общий readTrafficLiveSample; MCP возвращает ограниченную серию до трёх срезов вместо бесконечного SSE. Полнота суммы, направление RX/TX, отзыв доступа и смена источника проверяются перед каждым новым native-запросом."
|
||||
"reason": "Общий readTrafficLiveSample для разового чтения интерфейса, SSE и ограниченной MCP-серии. Источник проверяется перед каждым новым native-запросом."
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
@@ -1604,6 +1632,27 @@
|
||||
"operations": [],
|
||||
"reason": "Локальный предпросмотр объектов из компилятора. План MCP дополнительно фиксирует состояние площадок и требует подтверждения."
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/api/ix/segments/:id/linux-bonds",
|
||||
"status": "excluded",
|
||||
"operations": [],
|
||||
"reason": "WebUI сохраняет выбранные оператором интерфейсы и порядок путей для последующего импорта и подтверждения в локальном ix-client."
|
||||
},
|
||||
{
|
||||
"method": "DELETE",
|
||||
"path": "/api/ix/segments/:id/linux-bonds/:bondId",
|
||||
"status": "excluded",
|
||||
"operations": [],
|
||||
"reason": "Оператор удаляет сохранённое описание группы из WebUI. Снятие политики на самом VPS подтверждается отдельно в ix-client."
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/api/ix/segments/:id/linux-bonds/:bondId/export",
|
||||
"status": "excluded",
|
||||
"operations": [],
|
||||
"reason": "Оператор скачивает JSON группы из WebUI и локально сопоставляет его с интерфейсами VPS в ix-client."
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/api/ix/segments/:id/plan",
|
||||
@@ -1618,6 +1667,27 @@
|
||||
"operations": ["network.ix.configure"],
|
||||
"reason": "Пользователь WebUI подтверждает просмотренную ревизию. MCP применяет свой подтверждённый план через общий исполнитель IX."
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/api/ix/segments/:id/linux",
|
||||
"status": "excluded",
|
||||
"operations": [],
|
||||
"reason": "WebUI сохраняет одной ревизией клиента Linux и выбранный транзит. Записи на RouterOS идут после подтверждения изменений."
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/api/ix/segments/:id/linux/credential",
|
||||
"status": "excluded",
|
||||
"operations": [],
|
||||
"reason": "WebUI выдаёт действующий PSK или ключ WireGuard оператору с правом изменения сети и записью в журнале. Для WireGuard MCP возвращает защищённую ссылку через network.wireguard.export."
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/api/ix/segments/:id/linux/revoke",
|
||||
"status": "excluded",
|
||||
"operations": [],
|
||||
"reason": "WebUI сохраняет черновик отзыва клиента. Удаление конфигурации RouterOS выполняется отдельным подтверждённым планом."
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/api/ix/segments/:id/removal-plan",
|
||||
@@ -1625,6 +1695,13 @@
|
||||
"operations": ["network.ix.delete"],
|
||||
"reason": "Предпросмотр управляемых объектов перед явным подтверждением удаления сегмента."
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/api/ix/segments/:id/transit",
|
||||
"status": "excluded",
|
||||
"operations": [],
|
||||
"reason": "Мастер WebUI собирает черновик связи и выхода по инвентарю двух узлов. Применение к обоим маршрутизаторам требует отдельного подтверждения."
|
||||
},
|
||||
{
|
||||
"method": "DELETE",
|
||||
"path": "/api/ix/segments/:id",
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
"test:mcp:module-completion": "tsx src/services/ipsec-server-init-model.test.ts && tsx src/modules/mcp/ipsec-server-init-actions.test.ts && tsx src/services/wireguard-revision-restore.test.ts && tsx src/modules/mcp/vrf-ticket-runtime.test.ts && tsx src/services/ipsec-restore.test.ts && tsx src/services/ipsec-pool-dependencies.test.ts && tsx src/services/vrf-production-transition.test.ts && tsx src/services/vrf-production-action-binding.test.ts && tsx src/services/ipsec-revision-restore-model.test.ts && tsx src/modules/mcp/ipsec-revision-actions.test.ts && tsx src/modules/mcp/service-native-progress.test.ts && tsx src/services/ipsec-revision-restore.test.ts && tsx src/services/ipsec-revision-secret.test.ts",
|
||||
"test:mcp:module-completion:pg": "node scripts/test-mcp-postgres.mjs --module-completion --restore",
|
||||
"test:mcp:pg": "node scripts/test-mcp-postgres.mjs",
|
||||
"test:mcp:network-diagnostics": "node --experimental-test-module-mocks --import tsx --test src/modules/mcp/incident-actions.test.ts src/modules/mcp/network-diagnostic-actions.test.ts src/modules/mcp/resilience-actions.test.ts src/modules/mcp/gre-ipsec-pair-actions.test.ts src/modules/mcp/gre-ikev2-pair-actions.test.ts",
|
||||
"test:mcp:network-diagnostics:pg": "node scripts/test-mcp-postgres.mjs --network-diagnostics",
|
||||
"test:mcp:pg:sharded": "node scripts/test-mcp-postgres-sharded.mjs",
|
||||
"test:mcp:users-bindings:pg": "node scripts/test-mcp-postgres.mjs --users-bindings",
|
||||
"test:mcp:bridge-vlan:pg": "node scripts/test-mcp-postgres.mjs --bridge-vlan-configuration",
|
||||
@@ -46,7 +48,7 @@
|
||||
"test:probes": "npm run test:speed-workflow && tsx src/services/manual-data-collection-execution.test.ts && tsx src/routes/manual-data-collection.test.ts && tsx src/services/network-host-resolution.test.ts && tsx src/routes/probes.test.ts && tsx src/routes/probes.cancel.test.ts && tsx src/services/ping-measurement.test.ts && tsx src/services/uptime-probe-observations.test.ts && tsx src/services/ping-measurement-sql.test.ts",
|
||||
"test:exec": "tsx src/services/mikrotik-logs.test.ts && tsx src/services/terminal-diagnostics.test.ts && tsx src/routes/exec.test.ts && tsx src/plugins/auth.exec.test.ts",
|
||||
"test:auth": "tsx --test src/modules/mcp/routing-manual-inverse-history.test.ts && tsx src/db/application-writer-profile-registry-structure.test.ts && tsx src/db/application-writer-profile-registry-read.test.ts && tsx src/db/application-writer-profile-registry-read-parity.test.ts && tsx src/db/application-writer-profile-format.test.ts && tsx src/plugins/auth-path.test.ts && tsx src/lib/permissions.test.ts && tsx src/plugins/auth-provenance.test.ts && tsx src/services/bandwidth-rest-speed-original.test.ts && tsx src/plugins/auth.smoke.test.ts && tsx src/plugins/auth.ospf-optimizer.test.ts && npm run test:mcp",
|
||||
"test:mcp": "node scripts/vrf-production-profile.test.mjs && node src/services/vrf-production-peer-telemetry.test.mjs && node src/services/vrf-execution-diagnostic.test.mjs && node src/services/vrf-transition-refusal.test.mjs && node src/services/vrf-production-gre-cycle.test.mjs && tsx src/services/vrf-production-gre-link-local.test.ts && tsx src/services/vrf-production-bridge-delete.test.ts && tsx src/services/vrf-production-transition.test.ts && tsx --test src/services/routeros-snapshot-read.test.ts src/services/bridge-vlan-configuration.test.ts src/modules/mcp/bridge-vlan-projection.test.ts src/modules/mcp/vrf-preparation-diagnostic.test.ts && tsx --test src/services/server-poll-error-provenance.test.ts && tsx --test src/modules/mcp/plan-expiry.test.ts src/modules/mcp/result-budget.test.ts src/modules/mcp/result-delivery.test.ts src/modules/mcp/wire-admission.test.ts src/modules/mcp/flow-envelope-allowance.test.ts src/modules/mcp/sdk-terminal-budget.test.ts src/modules/mcp/inflight-owner.test.ts && npm run test:database-source-binding && tsx --test src/modules/mcp/integration-fixture-expiry.test.ts && npm run test:mcp:operation-origin && npm run test:mcp:service-context && npm run test:mcp:operation-locks && tsx --test src/modules/mcp/routing-community-public.test.ts src/modules/mcp/management-transport.test.ts src/modules/mcp/routing-community-context-model.test.ts src/modules/mcp/routing-community-context-native.test.ts ../packages/contracts/src/mcp-routing.test.ts && tsx src/modules/mcp/human-artifact-receipts.test.ts && tsx src/modules/mcp/chr-overlay-readiness.test.ts && tsx src/modules/mcp/chr-recovery-source.test.ts && tsx src/modules/mcp/chr-native-failure.test.ts && tsx src/modules/mcp/ospf-owner-graph.test.ts && tsx src/modules/mcp/routing-measurement-address.test.ts && tsx src/modules/mcp/routing-observation-source.test.ts && tsx src/services/traffic-flow-talkers-model.test.ts && tsx src/services/bgp-prefix-model.test.ts && tsx src/services/vrf-members.test.ts && tsx src/services/routing-gateway-reference.test.ts && tsx src/services/bgp-export-model.test.ts && tsx src/services/traffic-history-model.test.ts && tsx src/services/internet-path-snapshot.test.ts && tsx src/services/internet-path-observation.test.ts && tsx src/modules/mcp/coverage.test.ts && tsx src/modules/mcp/policy.test.ts && tsx src/modules/mcp/events-batch-model.test.ts && tsx src/modules/mcp/operation-revisions.test.ts && tsx src/modules/mcp/native-create-identity.test.ts && tsx src/modules/mcp/ros-step-verification.test.ts && tsx src/modules/mcp/ros-prefix.test.ts && tsx src/modules/mcp/native-conservation-http.test.ts && tsx src/modules/mcp/security.test.ts && tsx src/modules/mcp/state-file-publish.test.ts && tsx src/modules/mcp/routing-model.test.ts && tsx src/modules/mcp/routing-observations-model.test.ts && tsx src/modules/mcp/ospf-health.test.ts && tsx src/modules/mcp/ecmp-preflight.test.ts && tsx src/modules/mcp/recursive-recovery.test.ts && tsx src/modules/mcp/control-path-model.test.ts && tsx src/modules/mcp/routing-community-scoped-model.test.ts && tsx src/modules/mcp/routing-community-scoped-native.test.ts && tsx src/modules/mcp/path-verification.test.ts && tsx src/modules/mcp/database-maintenance.test.ts && tsx src/routes/mcp.test.ts && tsx ../lib/auth-mcp.test.ts && tsx --test src/modules/mcp/routing-controller-fence.test.ts && tsx src/test/chr-vrf-companion-proof.test.ts && tsx src/test/chr-vrf-companion-telemetry.test.ts && tsx src/test/chr-vrf-companion-address-space.test.ts && tsx src/modules/mcp/flow-facts-rebuild-actions.test.ts && tsx src/modules/mcp/ipsec-peer-create-dependencies.test.ts && tsx src/services/ipsec-certificate-update-model.test.ts && tsx src/modules/mcp/ipsec-native-dispatch.test.ts && tsx src/modules/mcp/ipsec-user-update-actions.test.ts && tsx src/modules/mcp/ipsec-server-delete-actions.test.ts && tsx src/services/ipsec-proof-telemetry.test.ts && tsx src/services/vrf-production-admission.test.ts && tsx src/modules/mcp/flow-host-keys-actions.test.ts && tsx src/services/vrf-production-read.test.ts && tsx --test src/services/vrf-production-wireguard-alias.test.ts && tsx src/modules/mcp/ipsec-user-create-actions.test.ts && tsx src/modules/mcp/flow-settings-actions.test.ts && tsx src/services/vrf-production-ticket-store.test.ts && npm run test:mcp:routing-baseline",
|
||||
"test:mcp": "node scripts/vrf-production-profile.test.mjs && node src/services/vrf-production-peer-telemetry.test.mjs && node src/services/vrf-execution-diagnostic.test.mjs && node src/services/vrf-transition-refusal.test.mjs && node src/services/vrf-production-gre-cycle.test.mjs && tsx src/services/vrf-production-gre-link-local.test.ts && tsx src/services/vrf-production-bridge-delete.test.ts && tsx src/services/vrf-production-transition.test.ts && tsx --test src/services/routeros-snapshot-read.test.ts src/services/bridge-vlan-configuration.test.ts src/modules/mcp/bridge-vlan-projection.test.ts src/modules/mcp/vrf-preparation-diagnostic.test.ts && tsx --test src/services/server-poll-error-provenance.test.ts && tsx --test src/modules/mcp/plan-expiry.test.ts src/modules/mcp/result-budget.test.ts src/modules/mcp/result-delivery.test.ts src/modules/mcp/wire-admission.test.ts src/modules/mcp/flow-envelope-allowance.test.ts src/modules/mcp/sdk-terminal-budget.test.ts src/modules/mcp/inflight-owner.test.ts && npm run test:database-source-binding && tsx --test src/modules/mcp/integration-fixture-expiry.test.ts && npm run test:mcp:operation-origin && npm run test:mcp:service-context && npm run test:mcp:operation-locks && tsx --test src/modules/mcp/routing-community-public.test.ts src/modules/mcp/management-transport.test.ts src/modules/mcp/routing-community-context-model.test.ts src/modules/mcp/routing-community-context-native.test.ts ../packages/contracts/src/mcp-routing.test.ts && tsx src/modules/mcp/human-artifact-receipts.test.ts && tsx src/modules/mcp/chr-overlay-readiness.test.ts && tsx src/modules/mcp/chr-recovery-source.test.ts && tsx src/modules/mcp/chr-native-failure.test.ts && tsx src/modules/mcp/ospf-owner-graph.test.ts && tsx src/modules/mcp/routing-measurement-address.test.ts && tsx src/modules/mcp/routing-observation-source.test.ts && tsx src/services/traffic-flow-talkers-model.test.ts && tsx src/services/bgp-prefix-model.test.ts && tsx src/services/vrf-members.test.ts && tsx src/services/routing-gateway-reference.test.ts && tsx src/services/bgp-export-model.test.ts && tsx src/services/traffic-history-model.test.ts && tsx src/services/internet-path-snapshot.test.ts && tsx src/services/internet-path-observation.test.ts && tsx src/modules/mcp/coverage.test.ts && tsx src/modules/mcp/policy.test.ts && tsx src/modules/mcp/events-batch-model.test.ts && tsx src/modules/mcp/operation-revisions.test.ts && tsx src/modules/mcp/native-create-identity.test.ts && tsx src/modules/mcp/ros-step-verification.test.ts && tsx src/modules/mcp/ros-prefix.test.ts && tsx src/modules/mcp/native-conservation-http.test.ts && tsx src/modules/mcp/security.test.ts && tsx src/modules/mcp/state-file-publish.test.ts && tsx src/modules/mcp/routing-model.test.ts && tsx src/modules/mcp/routing-observations-model.test.ts && tsx src/modules/mcp/ospf-health.test.ts && tsx src/modules/mcp/ecmp-preflight.test.ts && tsx src/modules/mcp/recursive-recovery.test.ts && tsx src/modules/mcp/control-path-model.test.ts && tsx src/modules/mcp/routing-community-scoped-model.test.ts && tsx src/modules/mcp/routing-community-scoped-native.test.ts && tsx src/modules/mcp/path-verification.test.ts && tsx src/modules/mcp/database-maintenance.test.ts && tsx src/routes/mcp.test.ts && tsx ../lib/auth-mcp.test.ts && tsx --test src/modules/mcp/routing-controller-fence.test.ts && tsx src/test/chr-vrf-companion-proof.test.ts && tsx src/test/chr-vrf-companion-telemetry.test.ts && tsx src/test/chr-vrf-companion-address-space.test.ts && tsx src/modules/mcp/flow-facts-rebuild-actions.test.ts && tsx src/modules/mcp/ipsec-peer-create-dependencies.test.ts && tsx src/services/ipsec-certificate-update-model.test.ts && tsx src/modules/mcp/ipsec-native-dispatch.test.ts && tsx src/modules/mcp/ipsec-user-update-actions.test.ts && tsx src/modules/mcp/ipsec-server-delete-actions.test.ts && tsx src/services/ipsec-proof-telemetry.test.ts && tsx src/services/vrf-production-admission.test.ts && tsx src/modules/mcp/flow-host-keys-actions.test.ts && tsx src/services/vrf-production-read.test.ts && tsx --test src/services/vrf-production-wireguard-alias.test.ts && tsx src/modules/mcp/ipsec-user-create-actions.test.ts && tsx src/modules/mcp/flow-settings-actions.test.ts && tsx src/services/vrf-production-ticket-store.test.ts && npm run test:mcp:routing-baseline && npm run test:mcp:network-diagnostics",
|
||||
"test:wireguard": "tsx src/services/mikrotik-response-bounds.test.ts && tsx --test src/services/wireguard-dependency-read.test.ts && tsx src/services/wireguard-interface-update.test.ts && tsx src/services/wireguard-peer-update.test.ts && npx tsx src/services/wireguard-config.test.ts && npx tsx src/services/wireguard-ipv6.test.ts && npx tsx --test src/services/wireguard-import.test.ts src/services/wireguard-import-apply.test.ts src/services/wireguard-import-revision.test.ts src/services/wireguard-delete.test.ts && npx tsx src/routes/wireguard-import.test.ts && tsx src/services/wireguard-interface-create.test.ts && tsx src/services/wireguard-peer-create.test.ts && tsx src/services/wireguard-import-plan.test.ts && tsx src/services/wireguard-import-execution.test.ts && tsx src/modules/mcp/wireguard-import-actions.test.ts && tsx --test src/services/wireguard-export.test.ts",
|
||||
"test:traffic-rate": "tsx src/services/traffic-rate.test.ts && tsx src/services/traffic-observation.test.ts && tsx src/services/traffic-freshness.test.ts && tsx src/services/traffic-live.test.ts && tsx src/services/traffic-observation-sql.test.ts && tsx src/services/traffic-history-sql.test.ts && tsx src/services/traffic-live-sql.test.ts && tsx src/services/traffic-volume-sql.test.ts && tsx src/services/traffic-binding-status.test.ts && tsx src/services/traffic-status-sql.test.ts && tsx src/services/traffic-gap.test.ts && tsx src/services/traffic-identity.test.ts && tsx src/services/traffic-membership.test.ts && tsx src/services/traffic-aggregate-peak.test.ts && tsx src/services/traffic-users-cache.test.ts && tsx src/services/traffic-collection-lock.test.ts && tsx src/services/traffic-concurrency-sql.test.ts",
|
||||
"test:traffic-flow": "tsx --test src/services/traffic-flow-heartbeat.test.ts src/services/traffic-flow-heartbeat-wiring.test.ts src/services/traffic-flow-heartbeat-receiver.test.ts src/services/traffic-flow-ingest-quality.test.ts src/services/traffic-flow-quality-contract.test.ts && tsx src/services/traffic-flow-catalog-read.test.ts && tsx src/routes/traffic-flow-query.test.ts && tsx src/services/traffic-flow-month.test.ts && tsx src/services/traffic-flow-parse.test.ts && tsx src/services/traffic-flow-ipv6-pipeline.test.ts && tsx src/services/traffic-flow-map-exporter.test.ts && tsx src/services/traffic-flow-ifaces.test.ts && tsx src/services/traffic-flow-ifindex.test.ts && tsx src/services/traffic-flow-dedup.test.ts && tsx src/services/traffic-flow-planes.test.ts && tsx src/services/traffic-flow-ip.test.ts && tsx src/services/traffic-flow-dest.test.ts && tsx src/services/traffic-flow-classify.test.ts && tsx src/services/traffic-flow-ripe.test.ts && tsx src/services/traffic-flow-brands.test.ts && tsx src/services/traffic-flow-ingest.test.ts && tsx src/services/traffic-flow-analytics.test.ts && tsx src/services/traffic-flow-map-hops.test.ts && tsx src/services/traffic-flow-purge.test.ts && tsx src/services/geoip-download.test.ts && tsx src/services/traffic-flow-geoip.test.ts && tsx src/services/traffic-flow-fact-accumulator.test.ts && tsx src/services/traffic-flow-facts.test.ts && tsx src/services/traffic-flow-facts-filter.test.ts && tsx src/services/traffic-flow-facts-rebuild.test.ts && tsx src/services/statistics-aggregate.test.ts && tsx src/services/geoip-manual-update.test.ts && tsx src/services/traffic-flow-overlay-model.test.ts && npm run test:traffic-flow:ownership && tsx src/services/traffic-flow-worker-platform.test.ts && tsx src/services/traffic-flow-template-cache.test.ts && tsx --test src/services/traffic-flow-template-lifetime.test.ts && tsx src/services/traffic-flow-protocol-scope.test.ts && npm run test:traffic-flow:read-budget && npm run test:traffic-flow:resource-profile",
|
||||
@@ -60,6 +62,7 @@
|
||||
"test:ipsec": "tsx src/services/ipsec-config.test.ts && tsx src/services/ipsec-state.test.ts && tsx src/routes/ipsec-history.test.ts && tsx src/services/ipsec-restore.test.ts && tsx src/services/ipsec-operation.test.ts && tsx src/routes/ipsec-mutation.test.ts && tsx src/routes/ipsec-nat.test.ts && tsx src/routes/ipsec-group.test.ts && tsx src/services/ipsec-peer-delete.test.ts && tsx src/modules/mcp/ipsec-peer-delete-actions.test.ts && tsx src/services/ipsec-user-delete.test.ts && tsx src/modules/mcp/ipsec-user-delete-actions.test.ts && tsx src/services/ipsec-certificate-delete.test.ts && tsx src/modules/mcp/ipsec-certificate-delete-actions.test.ts && tsx src/services/ipsec-peer-update.test.ts && tsx src/modules/mcp/ipsec-peer-update-actions.test.ts && tsx src/services/ipsec-user-update-model.test.ts && tsx src/modules/mcp/ipsec-user-update-actions.test.ts && tsx src/services/ipsec-server-delete-model.test.ts && tsx src/modules/mcp/ipsec-server-delete-actions.test.ts && tsx src/services/ipsec-proof-telemetry.test.ts && tsx src/services/ipsec-user-create-model.test.ts",
|
||||
"test:live-maps": "tsx src/services/gre-revision-restore.test.ts && tsx src/services/gre-native-mutation.test.ts && tsx src/services/gre-mutation.test.ts && tsx src/services/filter-rules-observed.test.ts && tsx src/services/firewall-revision-restore.test.ts && tsx src/services/firewall-address-write.test.ts && tsx src/services/firewall-rule-write.test.ts && tsx src/services/gre-observed-read.test.ts && tsx src/services/network-observed-read.test.ts && tsx src/services/firewall-rule-move.test.ts && tsx src/services/ospf-state-read.test.ts && tsx src/modules/mcp/readiness-http.test.ts && tsx src/services/probe-interface-model.test.ts && tsx src/services/wan-runtime-model.test.ts && tsx src/services/gre-keepalive.test.ts && tsx src/services/gre-read.test.ts && tsx src/services/ospf-route-parse.test.ts && tsx src/services/vxlan-live.test.ts && tsx src/routes/vxlan.test.ts && tsx src/services/containers-live.test.ts && tsx src/services/firewall-poll.test.ts && tsx src/services/gre-catalog-poll.test.ts && tsx src/routes/filters-gre-catalog.test.ts && tsx src/routes/bgp-catalog.test.ts && tsx src/services/bgp-catalog-parse.test.ts && tsx src/routes/ospf-catalog.test.ts && tsx src/services/ospf-observed-values.test.ts && tsx src/routes/ospf-legacy.test.ts",
|
||||
"test": "node scripts/test.mjs",
|
||||
"test:ix": "tsx --test src/services/internet-exchange-plan.test.ts src/services/internet-exchange-execution.test.ts src/services/internet-exchange-bonds.test.ts src/services/ix-bond-transport.test.ts src/services/ix-import-links.test.ts",
|
||||
"test:evolution": "tsx src/services/evobgp-catalog.test.ts && tsx src/services/evobgp-client.test.ts && tsx src/routes/evobgp-catalog.test.ts && tsx src/routes/evobgp-settings.test.ts && tsx src/plugins/auth.evolution-settings.test.ts",
|
||||
"test:netflow-purge": "tsx src/db/operation-lock.test.ts && tsx src/services/traffic-flow-purge-execution.test.ts && tsx src/services/flow-purge-partitions.test.ts && tsx --test src/services/traffic-flow-worker-lifecycle.test.ts && tsx src/routes/traffic-flow-purge.test.ts",
|
||||
"test:netflow-settings": "tsx src/services/traffic-flow-host-file-builders.test.ts && tsx src/services/traffic-flow-key-execution.test.ts && tsx src/routes/traffic-flow-settings.test.ts && tsx src/plugins/auth.netflow-settings.test.ts && tsx src/services/traffic-flow-agent-install.test.ts && tsx src/services/traffic-flow-agent-client.test.ts && tsx src/services/traffic-flow-operation-queue.test.ts && tsx src/routes/traffic-flow-host.test.ts && tsx src/services/traffic-flow-settings-execution.test.ts && tsx src/modules/mcp/flow-host-keys-actions.test.ts && tsx src/services/traffic-flow-lifecycle-fence.test.ts && tsx src/services/traffic-flow-settings-store.test.ts && tsx src/services/traffic-flow-settings-service.test.ts && tsx src/modules/mcp/flow-settings-actions.test.ts",
|
||||
@@ -68,7 +71,7 @@
|
||||
"test:containers": "tsx src/services/containers-live.test.ts && tsx src/services/containers-state.test.ts && tsx src/services/container-removal.test.ts && tsx src/routes/containers-state.test.ts",
|
||||
"test:certificates": "tsx src/services/certificate-installation.test.ts && tsx src/services/certificate-renew-collector.test.ts && tsx src/services/certificate-issue-execution.test.ts && tsx src/services/certificate-issue-request.test.ts && tsx src/routes/certificates-issue.test.ts && tsx src/services/certificate-issue-dto.test.ts && tsx src/services/certificate-parse.test.ts && tsx src/services/certificates-state.test.ts && tsx src/routes/certificates-state.test.ts && tsx src/services/acme-settings-test.test.ts && tsx src/services/acme-settings-update-model.test.ts && tsx src/modules/mcp/acme-settings-actions.test.ts",
|
||||
"test:system-database": "tsx src/services/bounded-database-dump.test.ts && tsx src/services/database-dump-connection.test.ts && tsx src/services/system-database-partition-restore.test.ts && tsx src/services/system-database-cache.test.ts && tsx src/services/database-background-work.test.ts && tsx src/services/database-request-gate.test.ts && tsx --test src/services/detached-database-admission.test.ts && tsx src/services/traffic-flow-worker-shutdown.test.ts && tsx src/services/system-database-restore-execution.test.ts && tsx src/services/system-database-operation.test.ts && tsx src/services/system-database-schema-readiness.test.ts && tsx --test src/routes/mcp-oauth-database-admission.test.ts && tsx src/routes/system-database.test.ts && tsx src/plugins/auth.system-database.test.ts && tsx src/services/database-control-archive-boundary.test.ts && tsx src/db/database-schema-control-model.test.ts && tsx src/db/database-schema-control.test.ts && tsx src/db/controlled-migrations.test.ts && tsx src/db/controlled-schema-verification.test.ts && tsx --test src/db/migration-data-inventory.test.ts && tsx --test src/services/database-maintenance-startup.test.ts && tsx --test src/services/database-restore-audit.test.ts && tsx --test src/services/database-maintenance-resolution.test.ts && tsx --test scripts/database-maintenance-resolution.test.mts && tsx src/db/database-runtime-schema.test.ts",
|
||||
"test:all": "npm run test:logs && npm run test:probes && npm run test:exec && npm run test:alert-engine && npm run test:alerts-telegram && npm run test:auth && npm run test:wireguard && npm run test:ipsec && npm run test:traffic-rate && npm run test:traffic-flow && npm run test:users && npm run test:pg && npm run test:sidebar-counts && npm run test:backups && npm run test:scheduler && npm run test:live-maps && npm run test:ospf-optimizer && npm run test:recursive-routes && npm run test:config-sync && npm run test:ros-file && npm run test:containers && npm run test:certificates && npm run test:netflow-settings && npm run test:netflow-purge && npm run test:evolution && npm run test:system-database && npm run test:server-privacy && npm run test:mcp:module-completion && npm run test:mcp:loopback-agent && npm run test:server-probe-management && npm run test:server-poll-management && npm run test:mcp:routing-authority && npm run test:mcp:native-readers && npm run test:mcp:chr-acquisition && npm run test:mcp:shared-context && npm run test:mcp:telemetry-configuration",
|
||||
"test:all": "npm run test:ix && npm run test:logs && npm run test:probes && npm run test:exec && npm run test:alert-engine && npm run test:alerts-telegram && npm run test:auth && npm run test:wireguard && npm run test:ipsec && npm run test:traffic-rate && npm run test:traffic-flow && npm run test:users && npm run test:pg && npm run test:sidebar-counts && npm run test:backups && npm run test:scheduler && npm run test:live-maps && npm run test:ospf-optimizer && npm run test:recursive-routes && npm run test:config-sync && npm run test:ros-file && npm run test:containers && npm run test:certificates && npm run test:netflow-settings && npm run test:netflow-purge && npm run test:evolution && npm run test:system-database && npm run test:server-privacy && npm run test:mcp:module-completion && npm run test:mcp:loopback-agent && npm run test:server-probe-management && npm run test:server-poll-management && npm run test:mcp:routing-authority && npm run test:mcp:native-readers && npm run test:mcp:chr-acquisition && npm run test:mcp:shared-context && npm run test:mcp:telemetry-configuration",
|
||||
"test:server-privacy": "tsx ../packages/contracts/src/servers.test.ts && tsx src/routes/server-secrets-sql.test.ts && tsx --test src/services/server-connection-test.test.ts",
|
||||
"test:mcp:flow-rebuild:pg": "node scripts/test-mcp-postgres.mjs --flow-rebuild-mcp",
|
||||
"test:mcp:flow-host-keys:pg": "node scripts/test-mcp-postgres.mjs --flow-host-keys",
|
||||
@@ -180,7 +183,7 @@
|
||||
"test:traffic-flow:read-budget": "tsx --test src/services/traffic-flow-read-budget.test.ts src/modules/mcp/flow-read-quality.test.ts && node scripts/test-flow-read-adapters.mjs",
|
||||
"test:traffic-flow:read-http:pg": "node scripts/test-flow-read-http-owned.mjs",
|
||||
"test:traffic-flow:read-source:pg": "tsx scripts/test-flow-read-sql-owned.mts",
|
||||
"test:mcp:routing-baseline": "tsx --test src/modules/mcp/routing-controller-active-writer.test.ts src/modules/mcp/routing-controller-baseline.test.ts src/modules/mcp/routing-controller-fence.test.ts src/modules/mcp/routing-community-public.test.ts src/modules/mcp/routing-controller-overlap.test.ts",
|
||||
"test:mcp:routing-baseline": "tsx --test src/modules/mcp/routing-controller-active-writer.test.ts src/modules/mcp/routing-controller-baseline.test.ts src/modules/mcp/routing-controller-fence.test.ts src/modules/mcp/routing-community-public.test.ts src/modules/mcp/routing-controller-overlap.test.ts src/services/bgp-rib-observation.test.ts",
|
||||
"test:mcp:routing-baseline:pg": "node scripts/test-routing-controller-baseline.mjs",
|
||||
"test:mcp:routing-baseline-inverse:pg": "node scripts/test-routing-controller-baseline.mjs --default-scoped",
|
||||
"test:sqlite-import-control:pg": "node scripts/test-sqlite-import-control-postgres.mjs",
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
import { execFileSync } from "node:child_process"
|
||||
import { isIPv4 } from "node:net"
|
||||
import { homedir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
|
||||
export const hosts = ["194.226.121.150", "104.165.244.7"] as const
|
||||
const targets = process.env.MMAPP_IX_CHR_HOSTS?.split(",").map(value => value.trim()) ?? []
|
||||
if (targets.length !== 2 || new Set(targets).size !== 2 || !targets.every(isIPv4)) {
|
||||
throw new Error("MMAPP_IX_CHR_HOSTS must identify two distinct, isolated CHR IPv4 addresses")
|
||||
}
|
||||
export const hosts = [targets[0], targets[1]] as const
|
||||
const key = join(homedir(), ".ssh", "chr_claude")
|
||||
const known = process.env.MMAPP_IX_TEST_KNOWN_HOSTS ?? join(homedir(), ".ssh", "known_hosts")
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { randomBytes, randomUUID } from "node:crypto"
|
||||
import { mkdtemp } from "node:fs/promises"
|
||||
import { createServer } from "node:http"
|
||||
import { createPrivateKey, createPublicKey, randomBytes, randomUUID } from "node:crypto"
|
||||
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" }],
|
||||
@@ -32,26 +33,49 @@ const rows: Record<string, Record<string, string>[]> = {
|
||||
}
|
||||
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
|
||||
if (request.method === "GET") result = rows[path] ?? []
|
||||
else if (request.method === "POST" && path === "/interface/print") {
|
||||
let raw = ""
|
||||
for await (const chunk of request) raw += chunk
|
||||
const body = JSON.parse(raw)
|
||||
assert.equal(body.stats, "")
|
||||
result = (rows["/interface"] ?? []).map(row => {
|
||||
const gre = rows["/interface/gre"]?.some(item => item.name === row.name)
|
||||
return { name: row.name, "rx-byte": gre ? "1536" : "9000", "tx-byte": gre ? "2048" : "8000" }
|
||||
})
|
||||
}
|
||||
else if (request.method === "PUT") {
|
||||
if (writes === failPutAt) throw Error("Synthetic RouterOS apply failure")
|
||||
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)
|
||||
list.splice(index < 0 ? list.length : index, 0, row)
|
||||
if (path === "/ip/vrf" || path === "/interface/wireguard" || path === "/interface/bridge") {
|
||||
if (["/ip/vrf", "/interface/wireguard", "/interface/bridge", "/interface/gre"].includes(path)) {
|
||||
rows["/interface"].push({ ".id": row[".id"], name: row.name,
|
||||
type: path === "/interface/wireguard" ? "wg" : path.split("/").at(-1)!, comment: row.comment })
|
||||
}
|
||||
result = row
|
||||
} else if (request.method === "PATCH") {
|
||||
const parent = path.slice(0, path.lastIndexOf("/"))
|
||||
const id = decodeURIComponent(path.slice(path.lastIndexOf("/") + 1))
|
||||
const row = rows[parent]?.find(entry => entry[".id"] === id)
|
||||
assert(row)
|
||||
let raw = ""
|
||||
for await (const chunk of request) raw += chunk
|
||||
Object.assign(row, JSON.parse(raw))
|
||||
writes++
|
||||
result = row
|
||||
} else if (request.method === "DELETE") {
|
||||
if (deletes === failDeleteAt) throw Error("Synthetic RouterOS deletion failure")
|
||||
const parent = path.slice(0, path.lastIndexOf("/"))
|
||||
@@ -71,7 +95,16 @@ const router = createServer(async (request, response) => {
|
||||
response.statusCode = 500
|
||||
response.end(JSON.stringify({ error: String(error) }))
|
||||
}
|
||||
})
|
||||
}
|
||||
const router = createServer(serveRouter(rows))
|
||||
const backupRows: RouterRows = {
|
||||
"/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 backupRouter = createServer(serveRouter(backupRows))
|
||||
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
|
||||
@@ -128,13 +161,21 @@ try {
|
||||
await post(path + "/apply", { revision: 1, digest }, 409)
|
||||
assert.equal(writes, 0)
|
||||
const fresh = await post(path + "/plan", { revision: 1 }, 200)
|
||||
await post(path + "/plan", { revision: 1, resume: true }, 409)
|
||||
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)
|
||||
failPutAt = 1
|
||||
await post(path + "/apply", { revision: 1, digest: fresh.digest }, 503)
|
||||
assert.equal(writes, 1)
|
||||
await post(path + "/plan", { revision: 1 }, 409)
|
||||
failPutAt = -1
|
||||
const resume = await post(path + "/plan", { revision: 1, resume: true }, 200)
|
||||
assert.equal(resume.changes.length, changes.length - 1)
|
||||
const applied = await post(path + "/apply", { revision: 1, digest: resume.digest, resume: true }, 200)
|
||||
assert.equal(applied.segment.appliedRevision, 2)
|
||||
assert.equal(applied.result.configurationVerified, true)
|
||||
assert.equal(applied.result.forwardingVerified, false)
|
||||
@@ -147,6 +188,7 @@ try {
|
||||
assert.match(wg.template, /Endpoint = 192\.0\.2\.20:51820/)
|
||||
assert.match(wg.template, /Table = off/)
|
||||
assert(!wg.template.includes("A".repeat(43)))
|
||||
await post(path + "/linux/credential", { serverId: Number(server.id), interfaceName: "wg-ix-web" }, 404)
|
||||
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\]/)
|
||||
@@ -240,7 +282,7 @@ try {
|
||||
}
|
||||
const { token: mcpToken } = await mcpPost("connections", { name: "IX removal acceptance", mode: "approval",
|
||||
permissions: ["mm:network:write", "mm:network:read"], expiresAt: new Date(Date.now() + 300_000).toISOString(),
|
||||
scope: { allowGlobal: false, serverIds: [Number(server.id)], operationIds: ["network.ix.delete", "changes.apply", "operations.read"] } })
|
||||
scope: { allowGlobal: false, serverIds: [Number(server.id)], operationIds: ["network.ix.delete", "network.wireguard.export", "changes.apply", "operations.read"] } })
|
||||
mcp = new Client({ name: "ix-removal-acceptance", version: "1.0.0" })
|
||||
await mcp.connect(new StreamableHTTPClientTransport(new URL(origin + "/mcp"),
|
||||
{ requestInit: { headers: { authorization: "Bearer " + mcpToken } } }))
|
||||
@@ -265,13 +307,261 @@ try {
|
||||
assert.equal(terminal.state, "applied", JSON.stringify(terminal))
|
||||
assert.equal(terminal.verification, "passed")
|
||||
assert.equal(deletes, writes)
|
||||
|
||||
const managed = (await post("", { revision: 0, configuration: { name: "ix-web-managed", sites: [
|
||||
{ serverId: Number(server.id), autonomousSystem: 64512, routerId: "192.0.2.6" },
|
||||
] } }, 200)).segment
|
||||
const managedPath = "/" + managed.id
|
||||
rows["/interface"].push({ ".id": "*FA", name: "ether1", type: "ether", running: "true" })
|
||||
;(rows["/ip/address"] ??= []).push(
|
||||
{ ".id": "*FB", interface: "ether1", address: "192.0.2.20/24" },
|
||||
{ ".id": "*FC", interface: "ether1", address: "192.0.2.30/24" },
|
||||
)
|
||||
;(rows["/ip/route"] ??= []).push({ ".id": "*FD", "routing-table": "main", "dst-address": "0.0.0.0/0",
|
||||
gateway: "192.0.2.1%ether1", "immediate-gw": "192.0.2.1%ether1", active: "true" })
|
||||
const clientInput = { serverId: Number(server.id), name: "linux-auto", kind: "wireguard", hubEndpoint: "192.0.2.20",
|
||||
peerEndpoint: "192.0.2.40", exit: "local-wan", prefixes: [], destinations: ["203.0.113.0/24"], enabled: true }
|
||||
const staged = await post(managedPath + "/linux", { ...clientInput, revision: managed.revision }, 200)
|
||||
assert.match(staged.interfaceName, /^il-wg-[a-z0-9-]+-[0-9a-f]{12}$/)
|
||||
assert.ok(staged.segment.configuration.sites[0].interfaces[0].linux.clientId)
|
||||
const clientKey = { serverId: clientInput.serverId, interfaceName: staged.interfaceName }
|
||||
await post(managedPath + "/linux/credential", clientKey, 409)
|
||||
await post(managedPath + "/linux/credential", clientKey, 403, reader)
|
||||
const edited = await post(managedPath + "/linux", { ...clientInput, ...clientKey, revision: staged.segment.revision, name: "linux-renamed" }, 200)
|
||||
const provision = edited.segment.configuration.sites[0].interfaces[0].provisionWireguard
|
||||
assert.deepEqual(provision, staged.segment.configuration.sites[0].interfaces[0].provisionWireguard)
|
||||
const plan = await post(managedPath + "/plan", { revision: edited.segment.revision }, 200)
|
||||
await post(managedPath + "/apply", { revision: edited.segment.revision, digest: plan.digest }, 200)
|
||||
const credential = await post(managedPath + "/linux/credential", clientKey, 200)
|
||||
const privateKey = credential.template.match(/^PrivateKey = ([A-Za-z0-9+/]{43}=)$/m)?.[1]
|
||||
assert.ok(privateKey)
|
||||
const scalar = Buffer.from(privateKey, "base64")
|
||||
const key = createPrivateKey({ key: Buffer.concat([Buffer.from("302e020100300506032b656e04220420", "hex"), scalar]),
|
||||
format: "der", type: "pkcs8" })
|
||||
const publicKey = createPublicKey(key).export({ format: "der", type: "spki" }).subarray(-32).toString("base64")
|
||||
assert.equal(publicKey, provision.peerPublicKey)
|
||||
assert.equal(rows["/interface/wireguard/peers"].find(row => row.interface === clientKey.interfaceName)?.["public-key"], publicKey)
|
||||
assert(!JSON.stringify([edited, plan, rows]).includes(privateKey))
|
||||
const templateResponse = await fetch(origin + "/api/ix/segments" + managedPath + "/linux?" + new URLSearchParams({
|
||||
serverId: String(clientKey.serverId), interfaceName: clientKey.interfaceName,
|
||||
}), { headers: { authorization: "Bearer " + reader } })
|
||||
assert.equal(templateResponse.status, 200)
|
||||
assert.match((await templateResponse.json()).template, /PrivateKey = <локальный_приватный_ключ>/)
|
||||
|
||||
const exportPlan = await call<{ planId: string; state: string }>("mm_wireguard_export_plan",
|
||||
{ ...clientKey, ixSegmentId: managed.id, format: "peer-conf" })
|
||||
assert.equal(exportPlan.state, "awaiting-approval")
|
||||
assert(!JSON.stringify(exportPlan).includes(privateKey))
|
||||
await mcpPost("plans/" + exportPlan.planId + "/decision", { approve: true })
|
||||
const exportOperation = await call<Operation>("mm_change_apply", { planId: exportPlan.planId, idempotencyKey: randomUUID() })
|
||||
let exported = exportOperation
|
||||
for (let attempts = 0; attempts < 50 && ["pending", "running"].includes(exported.state); attempts++) {
|
||||
await delay(200)
|
||||
exported = await call<Operation>("mm_operation_get", { operationId: exportOperation.id })
|
||||
}
|
||||
assert.equal(exported.state, "applied", JSON.stringify(exported))
|
||||
assert(!JSON.stringify(exported).includes(privateKey))
|
||||
const { rows: [{ result: receipt }] } = await pool.query("SELECT result FROM mcp_operation_steps WHERE operation_id=$1", [exported.id])
|
||||
assert.equal(receipt.humanDownloadOnly, true)
|
||||
const secretRecords = await pool.query(`SELECT to_jsonb(s) AS record FROM mcp_operation_steps s WHERE operation_id=$1
|
||||
UNION ALL SELECT to_jsonb(p) FROM mcp_plans p WHERE id=$2
|
||||
UNION ALL SELECT to_jsonb(a) FROM mcp_artifacts a WHERE id=$3
|
||||
UNION ALL SELECT to_jsonb(a) FROM mcp_audit a WHERE actor_id IN ('ix-web-owner','ix-mcp-owner')`,
|
||||
[exported.id, exportPlan.planId, receipt.artifactId])
|
||||
assert(!JSON.stringify(secretRecords.rows).includes(privateKey))
|
||||
const download = await fetch(origin + receipt.downloadPath, { headers: { authorization: "Bearer " + mcpJwt } })
|
||||
assert.equal(download.status, 200)
|
||||
assert.equal(await download.text(), credential.template)
|
||||
assert.equal(download.headers.get("cache-control"), "private, no-store")
|
||||
const denied = await fetch(origin + receipt.downloadPath, { headers: { authorization: "Bearer " + otherWriter } })
|
||||
assert.equal(denied.status, 403)
|
||||
const appliedPeer = rows["/interface/wireguard/peers"].find(row => row.interface === clientKey.interfaceName)!
|
||||
appliedPeer.disabled = "true"
|
||||
const inactive = await fetch(origin + receipt.downloadPath, { headers: { authorization: "Bearer " + mcpJwt } })
|
||||
assert.equal(inactive.status, 409)
|
||||
delete appliedPeer.disabled
|
||||
|
||||
const companionInput = { ...clientInput, kind: "gre-ipsec", companionOf: clientKey.interfaceName }
|
||||
const canceled = await post(managedPath + "/linux", { ...companionInput, revision: credential.revision }, 200)
|
||||
const canceledKey = { serverId: clientKey.serverId, interfaceName: canceled.interfaceName }
|
||||
const reverted = await post(managedPath + "/linux/revoke", { ...canceledKey, revision: canceled.segment.revision }, 200)
|
||||
const noChanges = await post(managedPath + "/plan", { revision: reverted.segment.revision }, 200)
|
||||
assert.deepEqual(noChanges.changes, [])
|
||||
const resumed = await post(managedPath + "/apply", { revision: reverted.segment.revision, digest: noChanges.digest }, 200)
|
||||
const paired = await post(managedPath + "/linux", { ...companionInput, revision: resumed.segment.revision }, 200)
|
||||
const bindings = paired.segment.configuration.sites[0].interfaces
|
||||
const [wireguard, greBinding] = bindings
|
||||
assert.match(greBinding.name, /^il-gre-[a-z0-9-]+-[0-9a-f]{12}$/)
|
||||
assert.ok(wireguard.linux.clientId)
|
||||
const original = resumed.segment.configuration.sites[0].interfaces[0]
|
||||
assert.deepEqual(wireguard, { ...original, linux: { ...original.linux, clientId: wireguard.linux.clientId } })
|
||||
assert.equal(wireguard.linux.clientId, greBinding.linux.clientId)
|
||||
assert.notEqual(wireguard.provisionWireguard.peerAddress, greBinding.provisionGre.peerAddress)
|
||||
const foreignRoute = { ".id": "*FE", "routing-table": "main", "dst-address": "198.51.100.0/24",
|
||||
gateway: "10.254.0.2%" + clientKey.interfaceName }
|
||||
rows["/ip/route"].push(foreignRoute)
|
||||
const blockedForeign = await post(managedPath + "/plan", { revision: paired.segment.revision }, 409)
|
||||
assert.match(blockedForeign.error, /другой маршрутизацией/)
|
||||
assert.equal(rows["/ip/route"].pop(), foreignRoute)
|
||||
const pairPlan = await post(managedPath + "/plan", { revision: paired.segment.revision }, 200)
|
||||
assert(!pairPlan.changes.some(change => change.path.startsWith("/interface/wireguard")))
|
||||
const pairedApplied = await post(managedPath + "/apply", { revision: paired.segment.revision, digest: pairPlan.digest }, 200)
|
||||
const countersResponse = await fetch(origin + "/api/ix/segments" + managedPath + "/linux", { headers: { authorization: "Bearer " + reader } })
|
||||
assert.equal(countersResponse.status, 200)
|
||||
const observedGre = (await countersResponse.json()).items.find(item => item.interfaceName === greBinding.name)
|
||||
assert.equal(observedGre.connection.rx, "1536")
|
||||
assert.equal(observedGre.connection.tx, "2048")
|
||||
const pairVrf = rows["/ip/vrf"].find(row => row.interfaces?.includes(wireguard.name))!
|
||||
assert(pairVrf.interfaces.split(",").includes(greBinding.name))
|
||||
const greCredential = await post(managedPath + "/linux/credential",
|
||||
{ serverId: clientKey.serverId, interfaceName: paired.interfaceName }, 200)
|
||||
assert.match(greCredential.template, /secret = "[a-f0-9]{64}"/)
|
||||
assert.match(greCredential.setup, /install -m 0600 "\$conf" \/etc\/swanctl\/conf\.d\//)
|
||||
assert.match(greCredential.setup, /ip -4 rule add pref \d+ from 192\.0\.2\.40\/32 lookup main/)
|
||||
assert.match(greCredential.setup, /ip -4 route replace default dev ixg\w+ src \S+ table \d+/)
|
||||
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])
|
||||
const transit = { targetServerId: Number(exit.id), localEndpoint: "192.0.2.20", remoteEndpoint: "192.0.2.30", family: 4, name: "remote-exit" }
|
||||
const appliedRevision = pairedApplied.segment.revision
|
||||
const remoteClient = { ...clientInput, name: "linux-remote", revision: appliedRevision, exit: undefined, transit }
|
||||
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)
|
||||
const remoteSite = stagedRemote.segment.configuration.sites[0]
|
||||
assert.equal(remoteSite.interfaces.find(row => row.name === stagedRemote.interfaceName).linux.exit, transit.name)
|
||||
const transitBinding = remoteSite.interfaces.find(row => row.name === remoteSite.groups.find(group => group.id === transit.name).primary.interface)
|
||||
assert.equal(transitBinding.peerServerId, Number(exit.id))
|
||||
const { ixReservedTunnelBindings } = await import("../../src/services/internet-exchange-store.js")
|
||||
assert((await ixReservedTunnelBindings(Number(exit.id))).some(binding => binding.name === transitBinding.name))
|
||||
const remotePlan = await post(managedPath + "/plan", { revision: stagedRemote.segment.revision }, 200)
|
||||
assert(remotePlan.changes.some(change => change.serverId === Number(exit.id) &&
|
||||
change.path === "/ip/firewall/nat" && change.fields["out-interface"] === "ether1"))
|
||||
assert(remotePlan.changes.some(change => change.serverId === Number(server.id) && change.path === "/interface/wireguard"))
|
||||
assert.equal(writes, beforeStage)
|
||||
const both = await post(managedPath + "/linux", { ...clientInput, name: "both", peerEndpoint: "192.0.2.41",
|
||||
revision: stagedRemote.segment.revision, additionalGre: true }, 200)
|
||||
const added = both.segment.configuration.sites[0].interfaces.filter(binding => binding.linux?.name === "both")
|
||||
assert.deepEqual(added.map(binding => binding.kind), ["wireguard", "gre-ipsec"])
|
||||
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 existingPair = await post(secondPath + "/linux", { ...secondInput, additionalGre: true }, 200)
|
||||
const initialPairPlan = await post(secondPath + "/plan", { revision: existingPair.segment.revision }, 200)
|
||||
const appliedPair = (await post(secondPath + "/apply", { revision: existingPair.segment.revision, digest: initialPairPlan.digest }, 200)).segment
|
||||
const [oldWg, oldGre] = appliedPair.configuration.sites[0].interfaces
|
||||
assert.notEqual(oldWg.linux.clientId, bond.clientId)
|
||||
const changeIdentity = { ...secondInput, interfaceName: oldWg.name, vpsClientId: bond.clientId, revision: appliedPair.revision }
|
||||
const secondWg = await post(secondPath + "/linux", changeIdentity, 200)
|
||||
const newTunnel = secondWg.segment.configuration.sites[0].interfaces[0]
|
||||
assert.deepEqual(newTunnel, { ...oldWg, linux: { ...oldWg.linux, clientId: bond.clientId } })
|
||||
assert.deepEqual(secondWg.segment.configuration.sites[0].interfaces[1], oldGre)
|
||||
assert.notEqual(newTunnel.provisionWireguard.peerAddress, wireguard.provisionWireguard.peerAddress)
|
||||
const secondaryPlan = await post(secondPath + "/plan", { revision: secondWg.segment.revision }, 200)
|
||||
assert.deepEqual(secondaryPlan.changes, [])
|
||||
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 groupedChange = await post(secondPath + "/linux", { ...changeIdentity, vpsClientId: oldGre.linux.clientId, revision: secondaryApplied.revision }, 409)
|
||||
assert.match(groupedChange.error, /исключите подключение/)
|
||||
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")
|
||||
const ownPublicKey = Buffer.alloc(32, 29).toString("base64")
|
||||
const manualVrf = backupRows["/ip/vrf"]
|
||||
const manualGrePolicy = { "src-address": "198.51.100.20/32", "dst-address": "192.0.2.22/32", protocol: "gre", action: "encrypt", level: "require", tunnel: "false" }
|
||||
backupRows["/interface/wireguard"].push({ name: "pre-wg", "public-key": fixtureHubPublicKey })
|
||||
backupRows["/interface/wireguard/peers"].push({ interface: "pre-wg", "public-key": ownPublicKey, "allowed-address": "10.7.0.2/32" })
|
||||
backupRows["/interface/gre"].push({ name: "pre-gre", "local-address": "198.51.100.20", "remote-address": "192.0.2.22", "allow-fast-path": "false" })
|
||||
backupRows["/ip/ipsec/policy"].push(manualGrePolicy)
|
||||
backupRows["/ip/address"].push({ interface: "pre-wg", address: "10.7.0.1/30" }, { interface: "pre-gre", address: "10.8.0.1/30" })
|
||||
const refs = ["pre-wg", "pre-gre"].map((interfaceName, i) => ({ interfaceName, segmentId: secondSegment.id, serverId: secondInput.serverId,
|
||||
appliedRevision: secondaryApplied.revision, weight: 1, existing: { linuxInterface: i ? "gre-manual" : "wg0", address: "10." + (7 + i) + ".0.2",
|
||||
probe: "10." + (7 + i) + ".0.1", endpoint: "198.51.100.20", destinations: ["10.250.0.0/24"],
|
||||
...(i ? { kind: "gre-ipsec", remoteEndpoint: "192.0.2.22" } : { kind: "wireguard", clientPublicKey: ownPublicKey }) } }))
|
||||
const manualPath = secondPath + "/linux-bonds"
|
||||
const manualInput = { ...bondInput, name: "existing", members: refs }
|
||||
const beforeManual = JSON.stringify(backupRows)
|
||||
const writesBeforeManual = writes
|
||||
await post(manualPath, manualInput, 403, reader)
|
||||
await post(manualPath, { ...manualInput, members: [{ ...refs[0], existing: { ...refs[0].existing, clientPublicKey: fixtureHubPublicKey } }, refs[1]] }, 409)
|
||||
manualVrf.unshift({ name: "another-vrf", interfaces: "pre-wg" })
|
||||
await post(manualPath, manualInput, 409)
|
||||
manualVrf.shift()
|
||||
const manual = await post(manualPath, manualInput, 200)
|
||||
const manualExport = manualPath + "/" + manual.id + "/export"
|
||||
const result = await post(manualExport, { revision: 1 }, 200)
|
||||
assert.deepEqual(result.members.map(p => p.interfaceName), ["wg0", "gre-manual"])
|
||||
assert.equal(result.members[0].peerPublicKey, fixtureHubPublicKey)
|
||||
manualGrePolicy.level = "use"
|
||||
await post(manualExport, { revision: 1 }, 409)
|
||||
manualGrePolicy.level = "require"
|
||||
await post(manualPath + "/" + manual.id, { revision: 1 }, 204, writer, "DELETE")
|
||||
assert.equal(writes, writesBeforeManual)
|
||||
assert.equal(JSON.stringify(backupRows), beforeManual)
|
||||
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 }))
|
||||
deletedDraft: true, removedNativeObjects: deletes, revisionsRetained: archive.revisions,
|
||||
mcpRemovalVerified: true, managedWireguardVerified: true, clientWithTransitStagedAtomically: true, bothProtocolsInOneVrf: true,
|
||||
mixedBondExport: true, crossSegmentBond: true, concurrentBondEdits: true, existingRouterOsTunnels: 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()
|
||||
}
|
||||
|
||||
@@ -20,11 +20,11 @@ test('fixed artifact is reproducible, resolves the compiled backend graph, and r
|
||||
const packageJson=JSON.parse(await readFile(path.join(backend,'package.json'),'utf8'))
|
||||
await mkdir(projectBackend,{recursive:true});await writeFile(path.join(projectBackend,'package.json'),JSON.stringify({type:'module',dependencies:packageJson.dependencies}))
|
||||
const first=await buildDatabaseOperator({backendDirectory:backend,outputDirectory:output}),second=await buildDatabaseOperator({backendDirectory:backend,outputDirectory:output})
|
||||
assert.deepEqual(first,second);assert.equal(first.modules.length,OPERATOR_SOURCES.length);assert.equal(first.modules.length,33);assert.deepEqual(first.runtimeDependencies,['dotenv','pg','zod']);assert.equal(first.backendDistModules.length,32)
|
||||
assert.deepEqual(first,second);assert.equal(first.modules.length,OPERATOR_SOURCES.length);assert.equal(first.modules.length,34);assert.deepEqual(first.runtimeDependencies,['dotenv','pg','zod']);assert.equal(first.backendDistModules.length,33)
|
||||
assert(first.modules.some(item=>item.file==='writer-profile/registry-enrollment.mjs'))
|
||||
assert(first.modules.some(item=>item.file==='writer-profile/marker-fence-enrollment.mjs'))
|
||||
assert(first.modules.some(item=>item.file==='writer-profile/fixed58-build-definition.js'))
|
||||
assert(first.modules.some(item=>item.file==='writer-profile/fixed59-build-definition.js'))
|
||||
assert(first.modules.some(item=>item.file==='writer-profile/fixed60-build-definition.js'))
|
||||
assert(first.backendDistImports.includes('db/database-restore-quarantine-profile.js'))
|
||||
assert(first.backendDistImports.includes('db/database-source-activation-record.js'))
|
||||
assert(first.backendDistImports.includes('services/server-probe-legacy-source-inventory.js'))
|
||||
|
||||
@@ -13,5 +13,5 @@ export const OPERATOR_SOURCES=Object.freeze([
|
||||
'writer-profile/catalogue.mts','writer-profile/catalogue-value-bridge.ts','writer-profile/catalogue-projection.ts','writer-profile/catalogue-leaves.ts',
|
||||
'writer-profile/application-writer-profile-catalogue.ts','writer-profile/application-writer-profile-catalogue-values.ts',
|
||||
'writer-profile/application-writer-profile-catalogue-parent-policy.ts','writer-profile/application-writer-profile-canonical.ts',
|
||||
'writer-profile/fixed44-build-sql.ts','writer-profile/fixed44-build-definition.ts','writer-profile/fixed56-build-definition.ts','writer-profile/fixed56-build-delta.ts','writer-profile/fixed57-build-definition.ts','writer-profile/fixed58-build-definition.ts','writer-profile/fixed59-build-definition.ts','writer-profile/fixed59-ix-delta.ts','writer-profile/expanded44-data-policy.ts',
|
||||
'writer-profile/fixed44-build-sql.ts','writer-profile/fixed44-build-definition.ts','writer-profile/fixed56-build-definition.ts','writer-profile/fixed56-build-delta.ts','writer-profile/fixed57-build-definition.ts','writer-profile/fixed58-build-definition.ts','writer-profile/fixed59-build-definition.ts','writer-profile/fixed59-ix-delta.ts','writer-profile/fixed60-build-definition.ts','writer-profile/expanded44-data-policy.ts',
|
||||
])
|
||||
@@ -57,11 +57,11 @@ export async function main(args:string[]){
|
||||
// import so a newly loaded NODE_PG_FORCE_NATIVE cannot select another driver.
|
||||
const {createProtectedDatabaseSourceBindingVerifier}=await import('./writer-profile/protected-source-registry.mjs')
|
||||
assertJsDriverEnvironment(process.env)
|
||||
const [{default:pg},{createConnectedPublisher,requireCurrentCatalogueDefinition},{collectSource44Catalogue,collectSource56Catalogue,collectSource57Catalogue,collectSource58Catalogue,collectSource59Catalogue,approvedDefinition}]=await Promise.all([
|
||||
const [{default:pg},{createConnectedPublisher,requireCurrentCatalogueDefinition},{collectSource44Catalogue,collectSource56Catalogue,collectSource57Catalogue,collectSource58Catalogue,collectSource59Catalogue,collectSource60Catalogue,approvedDefinition}]=await Promise.all([
|
||||
import('pg'),import('./writer-profile/publisher.mjs'),import('./writer-profile/catalogue.mjs')])
|
||||
assertJsDriverEnvironment(process.env)
|
||||
const reviewedDefinition=legacyInspection?undefined:approvedDefinition(definition)
|
||||
const collectCatalogues={44:collectSource44Catalogue,56:collectSource56Catalogue,57:collectSource57Catalogue,58:collectSource58Catalogue,59:collectSource59Catalogue}
|
||||
const collectCatalogues={44:collectSource44Catalogue,56:collectSource56Catalogue,57:collectSource57Catalogue,58:collectSource58Catalogue,59:collectSource59Catalogue,60:collectSource60Catalogue}
|
||||
const collectCatalogue=collectCatalogues[reviewedDefinition&&'edition' in reviewedDefinition?reviewedDefinition.edition:44]
|
||||
if(!legacyInspection&&!catalogueInspection){
|
||||
assert.equal(reviewedDefinition!.definitionSha256,pinned!.definitionSha256)
|
||||
|
||||
@@ -178,6 +178,8 @@ if (usersBindings && (process.argv.length !== 3 || process.argv[2] !== '--users-
|
||||
const bridgeVlanConfiguration = process.argv.includes('--bridge-vlan-configuration')
|
||||
if (bridgeVlanConfiguration && process.argv.slice(2).some(arg => arg !== '--bridge-vlan-configuration')) throw new Error('Bridge VLAN acceptance requires its own disposable cluster')
|
||||
const applicationAdapters = process.argv.includes('--application-adapters')
|
||||
const networkDiagnostics = process.argv.includes('--network-diagnostics')
|
||||
if (networkDiagnostics && process.argv.length !== 3) throw new Error('Network diagnostics require their own disposable cluster')
|
||||
const scopedRoutingDiagnostics = process.argv.includes('--scoped-routing-diagnostics')
|
||||
const interfaceEventsCompatibility = process.argv.includes('--interface-events-compatibility')
|
||||
const eventsOnly = process.argv.includes('--events-only')
|
||||
@@ -262,7 +264,7 @@ try {
|
||||
await postgres.start()
|
||||
const binaries = await import(`@embedded-postgres/${process.platform === 'win32' ? 'windows' : process.platform}-${process.arch}`)
|
||||
const testPath = [process.env.MMAPP_PG_CLIENT_BIN, dirname(binaries.postgres), process.env.PATH ?? process.env.Path ?? ''].filter(Boolean).join(delimiter)
|
||||
if (!profilesOnly && (restoreQuarantineOnly || process.argv.includes('--restore') || process.env.MMAPP_PG_CLIENT_BIN)) {
|
||||
if (!profilesOnly && !networkDiagnostics && (restoreQuarantineOnly || process.argv.includes('--restore') || process.env.MMAPP_PG_CLIENT_BIN)) {
|
||||
for (const command of ['pg_dump', 'pg_restore']) await new Promise((resolve, reject) => {
|
||||
execFile(command, ['--version'], { env: { ...process.env, PATH: testPath }, windowsHide: true, timeout: 5000, maxBuffer: 4096 }, error => {
|
||||
if (error) reject(new Error(`Restore acceptance requires working ${command}; set MMAPP_PG_CLIENT_BIN to the PostgreSQL client bin directory`))
|
||||
@@ -274,8 +276,9 @@ try {
|
||||
if (regressionOnly) console.log('Selected regression only: primary integration and terminal restore are not run')
|
||||
if (profilesOnly) console.log('Profiles-only regression matrix: primary integration NOT RUN; terminal restore NOT RUN; full acceptance is not claimed')
|
||||
const result = regressionOnly || profilesOnly ? 0 : await new Promise((resolve, reject) => {
|
||||
const child = spawn(process.execPath, pollMemory ? ['--max-old-space-size=192', '--max-semi-space-size=16', fileURLToPath(new URL('../dist-mcp-memory/services/server-poll-memory.owned.test.js', import.meta.url))] : ['--import', 'tsx', ...(flowActiveRebuild ? ['--import', new URL('../src/services/traffic-flow-active-rebuild-preload.mjs', import.meta.url).href] : []), acceptanceShard ? 'src/modules/mcp/acceptance-shard.test.ts' : usersBindings ? 'src/modules/mcp/users-bindings-owned.test.ts' : bridgeVlanConfiguration ? 'src/modules/mcp/bridge-vlan-configuration-http.test.ts' : protocolLimits ? 'src/modules/mcp/protocol-limits.owned.test.ts' : principalSecuritySource ? 'src/modules/mcp/principal-security-source.owned.test.ts' : pollJournalSnapshot ? 'src/services/server-poll-journal-snapshot.owned.test.ts' : pollTerminalArchive ? 'src/services/server-poll-terminal-archive.owned.test.ts' : pollArchiveSchema ? 'src/db/server-poll-terminal-archives.sql.test.ts' : telemetrySettingsConfiguration ? 'src/modules/mcp/telemetry-settings-configuration.owned.test.ts' : routingReservationSchema ? 'src/db/routing-reservation-schema.owned.test.ts' : routingForwardRounds ? 'src/modules/mcp/routing-network-forward-rounds.owned.test.ts' : flowActiveServices ? 'src/services/traffic-flow-active-services.owned.test.ts' : flowActiveRebuild ? 'src/services/traffic-flow-active-rebuild.owned.test.ts' : flowQuality ? 'src/services/traffic-flow-quality.owned.test.ts' : flowWorkerIpc ? 'src/services/traffic-flow-worker-ipc.owned.test.ts' : manualUptime ? 'src/modules/mcp/manual-uptime-http.test.ts' : manualPingGroup ? 'src/modules/mcp/manual-ping-group-http.test.ts' : manualTraffic ? 'src/modules/mcp/manual-traffic-http.test.ts' : manualApiPing ? 'src/modules/mcp/manual-api-ping-http.test.ts' : simpleSpeedChr ? 'src/modules/mcp/simple-speed-chr.test.ts' : simpleSpeed ? 'src/modules/mcp/simple-speed-http.test.ts' : externalPeerMetadata ? 'src/services/bandwidth-external-peer-metadata.sql.test.ts' : operatorPeerMetadata ? 'src/services/bandwidth-operator-metadata.sql.test.ts' : publicRegistryMetadata ? 'src/services/bandwidth-public-registry.sql.test.ts' : operatorDockerSql ? 'src/services/bandwidth-operator-docker-stop.sql.test.ts' : probeOperationRetirement ? 'src/services/server-probe-operation-retirement.owned.test.ts' : ordinaryOperationRetirement ? 'src/modules/mcp/ordinary-operation-retirement.owned.test.ts' : pollOperationRetirement ? 'src/services/server-poll-operation-retirement.owned.test.ts' : mcpOperationOrigin ? 'src/modules/mcp/operation-execution-origin.sql.test.ts' : mcpSpeedOriginal ? 'src/modules/mcp/speed-bandwidth-original.sql.test.ts' : routerConfigurationGuard ? 'src/services/router-configuration-guard.sql.test.ts' : scheduledSpeedOriginal ? 'src/services/bandwidth-scheduled-speed-original.sql.test.ts' : bandwidthSpeedWorkflow ? 'src/services/bandwidth-speed-workflow.sql.test.ts' : restSpeedOriginal ? 'src/services/bandwidth-rest-speed-original.sql.test.ts' : operationLocks ? 'src/services/operation-config-lock-lease.sql.test.ts' : serviceExecutionOrigin ? 'src/modules/mcp/service-execution-origin.sql.test.ts' : bandwidthNodeSource ? 'src/services/bandwidth-node-source.sql.test.ts' : bandwidthExternalRegistry ? 'src/services/bandwidth-external-node-registry.sql.test.ts' : bandwidthNodeRegistry ? 'src/services/bandwidth-node-registry.sql.test.ts' : bandwidthControlSource ? 'src/services/bandwidth-control-source.sql.test.ts' : bandwidthAdmission ? 'src/services/bandwidth-admission.sql.test.ts' : serverPollStorageFresh ? 'src/services/server-poll-storage-fresh.sql.test.ts' : serverPollStorage ? 'src/services/server-poll-storage.sql.test.ts' : probeStorageFresh ? 'src/services/server-probe-storage-fresh.sql.test.ts' : probeLegacyOrphans ? 'src/services/server-probe-legacy-orphans.sql.test.ts' : diagnosticCancelHost ? 'src/modules/mcp/diagnostic-cancellation-storage.sql.test.ts' : ipsecExportHttp ? 'src/modules/mcp/ipsec-existing-certificate-export-http.sql.test.ts' : ipsecExportJournal ? 'src/services/ipsec-existing-certificate-export-rest-journal.sql.test.ts' : migrationDataInventory ? 'src/db/migration-data-inventory.sql.test.ts' : probeStorageHistory ? 'src/services/server-probe-storage-history.sql.test.ts' : probeStorageJournal ? 'src/services/server-probe-storage-journal.sql.test.ts' : controlledSchemaReference ? 'src/db/controlled-schema-reference.sql.test.ts' : controlledMigrations ? 'src/db/controlled-migrations.sql.test.ts' : databaseSchemaControl ? 'src/db/database-schema-control.sql.test.ts' : migrationSchemaInventory ? 'src/db/migration-schema-inventory.sql.test.ts' : routingNetworkNative ? 'src/modules/mcp/routing-network-native.sql.test.ts' : routingReservationRuntime ? 'src/modules/mcp/routing-reservation-runtime.sql.test.ts' : routingReservations ? 'src/modules/mcp/routing-reservation.sql.test.ts' : collectorPartitionWriters ? 'src/services/collector-partition-writes.sql.test.ts' : serverPollDurableLine truncated
|
||||
const child = spawn(process.execPath, pollMemory ? ['--max-old-space-size=192', '--max-semi-space-size=16', fileURLToPath(new URL('../dist-mcp-memory/services/server-poll-memory.owned.test.js', import.meta.url))] : ['--import', 'tsx', ...(flowActiveRebuild ? ['--import', new URL('../src/services/traffic-flow-active-rebuild-preload.mjs', import.meta.url).href] : []), networkDiagnostics ? 'src/modules/mcp/network-diagnostics.owned.test.ts' : acceptanceShard ? 'src/modules/mcp/acceptance-shard.test.ts' : usersBindings ? 'src/modules/mcp/users-bindings-owned.test.ts' : bridgeVlanConfiguration ? 'src/modules/mcp/bridge-vlan-configuration-http.test.ts' : protocolLimits ? 'src/modules/mcp/protocol-limits.owned.test.ts' : principalSecuritySource ? 'src/modules/mcp/principal-security-source.owned.test.ts' : pollJournalSnapshot ? 'src/services/server-poll-journal-snapshot.owned.test.ts' : pollTerminalArchive ? 'src/services/server-poll-terminal-archive.owned.test.ts' : pollArchiveSchema ? 'src/db/server-poll-terminal-archives.sql.test.ts' : telemetrySettingsConfiguration ? 'src/modules/mcp/telemetry-settings-configuration.owned.test.ts' : routingReservationSchema ? 'src/db/routing-reservation-schema.owned.test.ts' : routingForwardRounds ? 'src/modules/mcp/routing-network-forward-rounds.owned.test.ts' : flowActiveServices ? 'src/services/traffic-flow-active-services.owned.test.ts' : flowActiveRebuild ? 'src/services/traffic-flow-active-rebuild.owned.test.ts' : flowQuality ? 'src/services/traffic-flow-quality.owned.test.ts' : flowWorkerIpc ? 'src/services/traffic-flow-worker-ipc.owned.test.ts' : manualUptime ? 'src/modules/mcp/manual-uptime-http.test.ts' : manualPingGroup ? 'src/modules/mcp/manual-ping-group-http.test.ts' : manualTraffic ? 'src/modules/mcp/manual-traffic-http.test.ts' : manualApiPing ? 'src/modules/mcp/manual-api-ping-http.test.ts' : simpleSpeedChr ? 'src/modules/mcp/simple-speed-chr.test.ts' : simpleSpeed ? 'src/modules/mcp/simple-speed-http.test.ts' : externalPeerMetadata ? 'src/services/bandwidth-external-peer-metadata.sql.test.ts' : operatorPeerMetadata ? 'src/services/bandwidth-operator-metadata.sql.test.ts' : publicRegistryMetadata ? 'src/services/bandwidth-public-registry.sql.test.ts' : operatorDockerSql ? 'src/services/bandwidth-operator-docker-stop.sql.test.ts' : probeOperationRetirement ? 'src/services/server-probe-operation-retirement.owned.test.ts' : ordinaryOperationRetirement ? 'src/modules/mcp/ordinary-operation-retirement.owned.test.ts' : pollOperationRetirement ? 'src/services/server-poll-operation-retirement.owned.test.ts' : mcpOperationOrigin ? 'src/modules/mcp/operation-execution-origin.sql.test.ts' : mcpSpeedOriginal ? 'src/modules/mcp/speed-bandwidth-original.sql.test.ts' : routerConfigurationGuard ? 'src/services/router-configuration-guard.sql.test.ts' : scheduledSpeedOriginal ? 'src/services/bandwidth-scheduled-speed-original.sql.test.ts' : bandwidthSpeedWorkflow ? 'src/services/bandwidth-speed-workflow.sql.test.ts' : restSpeedOriginal ? 'src/services/bandwidth-rest-speed-original.sql.test.ts' : operationLocks ? 'src/services/operation-config-lock-lease.sql.test.ts' : serviceExecutionOrigin ? 'src/modules/mcp/service-execution-origin.sql.test.ts' : bandwidthNodeSource ? 'src/services/bandwidth-node-source.sql.test.ts' : bandwidthExternalRegistry ? 'src/services/bandwidth-external-node-registry.sql.test.ts' : bandwidthNodeRegistry ? 'src/services/bandwidth-node-registry.sql.test.ts' : bandwidthControlSource ? 'src/services/bandwidth-control-source.sql.test.ts' : bandwidthAdmission ? 'src/services/bandwidth-admission.sql.test.ts' : serverPollStorageFresh ? 'src/services/server-poll-storage-fresh.sql.test.ts' : serverPollStorage ? 'src/services/server-poll-storage.sql.test.ts' : probeStorageFresh ? 'src/services/server-probe-storage-fresh.sql.test.ts' : probeLegacyOrphans ? 'src/services/server-probe-legacy-orphans.sql.test.ts' : diagnosticCancelHost ? 'src/modules/mcp/diagnostic-cancellation-storage.sql.test.ts' : ipsecExportHttp ? 'src/modules/mcp/ipsec-existing-certificate-export-http.sql.test.ts' : ipsecExportJournal ? 'src/services/ipsec-existing-certificate-export-rest-journal.sql.test.ts' : migrationDataInventory ? 'src/db/migration-data-inventory.sql.test.ts' : probeStorageHistory ? 'src/services/server-probe-storage-history.sql.test.ts' : probeStorageJournal ? 'src/services/server-probe-storage-journal.sql.test.ts' : controlledSchemaReference ? 'src/db/controlled-schema-reference.sql.test.ts' : controlledMigrations ? 'src/db/controlled-migrations.sql.test.ts' : databaseSchemaControl ? 'src/db/database-schema-control.sql.test.ts' : migrationSchemaInventory ? 'src/db/migration-schema-inventory.sql.test.ts' : routingNetworkNative ? 'src/modules/mcp/routing-network-native.sql.test.ts' : routingReservationRuntime ? 'src/modules/mcp/routing-reservation-runtime.sql.test.ts' : routingReservations ? 'src/modules/mcp/routing-reservation.sql.test.ts' : collectorPartitionWriters
Line truncated
|
||||
cwd: pollMemory ? directory : new URL('../', import.meta.url), stdio: 'inherit', env: { ...(pollMemory ? pollMemoryEnvironment : process.env),
|
||||
MMAPP_OWN_NETWORK_DIAGNOSTICS: String(networkDiagnostics),
|
||||
MMAPP_OWN_SKIP_POLL_CAPACITY: String(pollRetirementFocused),
|
||||
MMAPP_OWN_PROTOCOL_LIMITS: String(protocolLimits),
|
||||
MMAPP_OWN_EVENTS_ONLY: String(eventsOnly),
|
||||
@@ -300,7 +303,7 @@ try {
|
||||
})
|
||||
exitCode = result
|
||||
if (result === 0 && restoreQuarantineOnly) console.log('Restore quarantine: focused real PostgreSQL restore scenario complete')
|
||||
else if (result === 0 && !acceptanceShard && !regressionOnly && !profilesOnly && !usersBindings && !bridgeVlanConfiguration && !protocolLimits && !pollMemory && !principalSecuritySource && !pollJournalSnapshot && !pollArchiveSchema && !telemetrySettingsConfiguration && !routingReservationSchema && !routingForwardRounds && !flowActiveServices && !flowActiveRebuild && !flowQuality && !flowWorkerIpc && !manualUptime && !manualPingGroup && !manualTraffic && !manualApiPing && !simpleSpeed && !simpleSpeedChr && !externalPeerMetadata && !operatorPeerMetadata && !publicRegistryMetadata && !operatorDockerSql && !mcpOperationOrigin && !mcpSpeedOriginal && !routerConfigurationGuard && !scheduledSpeedOriginal && !bandwidthSpeedWorkflow && !restSpeedOriginal && !operationLocks && !serviceExecutionOrigin && !bandwidthNodeSource && !bandwidthNodeRegistry && !bandwidthExternalRegistry && !bandwidthControlSource && !bandwidthAdmission && !probeLegacyOrphans && !probeStorageJournal && !probeStorageHistory && !probeJournal && !chr && !flowWrites && !flowRebuild && !flowRebuildMcp && (process.argv.includes('--restore') || process.env.MMAPP_PG_CLIENT_BIN)) {
|
||||
else if (result === 0 && !networkDiagnostics && !acceptanceShard && !regressionOnly && !profilesOnly && !usersBindings && !bridgeVlanConfiguration && !protocolLimits && !pollMemory && !principalSecuritySource && !pollJournalSnapshot && !pollArchiveSchema && !telemetrySettingsConfiguration && !routingReservationSchema && !routingForwardRounds && !flowActiveServices && !flowActiveRebuild && !flowQuality && !flowWorkerIpc && !manualUptime && !manualPingGroup && !manualTraffic && !manualApiPing && !simpleSpeed && !simpleSpeedChr && !externalPeerMetadata && !operatorPeerMetadata && !publicRegistryMetadata && !operatorDockerSql && !mcpOperationOrigin && !mcpSpeedOriginal && !routerConfigurationGuard && !scheduledSpeedOriginal && !bandwidthSpeedWorkflow && !restSpeedOriginal && !operationLocks && !serviceExecutionOrigin && !bandwidthNodeSource && !bandwidthNodeRegistry && !bandwidthExternalRegistry && !bandwidthControlSource && !bandwidthAdmission && !probeLegacyOrphans && !probeStorageJournal && !probeStorageHistory && !probeJournal && !chr && !flowWrites && !flowRebuild && !flowRebuildMcp && (process.argv.includes('--restore') || process.env.MMAPP_PG_CLIENT_BIN)) {
|
||||
exitCode = await new Promise((resolve, reject) => {
|
||||
const child = spawn(process.execPath, ['--import', 'tsx', 'src/modules/mcp/database-restore.test.ts'], {
|
||||
cwd: new URL('../', import.meta.url), stdio: 'inherit', env: { ...process.env,
|
||||
@@ -313,6 +316,7 @@ try {
|
||||
child.once('error', reject); child.once('exit', code => resolve(code ?? 1))
|
||||
})
|
||||
}
|
||||
else if (result === 0 && networkDiagnostics) console.log('Network diagnostics: scoped MCP SDK and disposable PostgreSQL')
|
||||
else if (result === 0 && pollArchiveSchema) console.log('Poll archive schema: owned nonempty40 preservation, numbered41 and structural refusal guards; no positive MCP archive claim')
|
||||
else if (result === 0 && telemetrySettingsConfiguration) console.log('Telemetry settings: genuine MCP/SQL configuration binding, collector metadata tolerated; no native or external sources')
|
||||
else if (result === 0 && routingReservationSchema) console.log('Routing reservation numbered0040: ownSQL fresh/legacy/manual preservation; no READY, backfill, capabilities or public native activation')
|
||||
|
||||
@@ -8,6 +8,7 @@ import {BUILD56_PROVENANCE,FIXED56_ROLE_TEMPLATE} from './fixed56-build-definiti
|
||||
import {BUILD57_PROVENANCE,FIXED57_ROLE_TEMPLATE} from './fixed57-build-definition.js'
|
||||
import {BUILD58_PROVENANCE,FIXED58_ROLE_TEMPLATE,normalizeFixed58RestoreRows} from './fixed58-build-definition.js'
|
||||
import {BUILD59_PROVENANCE,FIXED59_ROLE_TEMPLATE} from './fixed59-build-definition.js'
|
||||
import {BUILD60_PROVENANCE,FIXED60_ROLE_TEMPLATE} from './fixed60-build-definition.js'
|
||||
import {GLOBALS,GROUPS,object,rows,sorted,text,projectCatalogueData,type CatalogueEdition,type Inventory,type Row,type Json} from './catalogue-projection.js'
|
||||
import {validateCatalogueLeafData} from './catalogue-leaves.js'
|
||||
import {catalogueTopologyPolicy,Expanded44TopologyBudgetData} from './expanded44-data-policy.js'
|
||||
@@ -22,6 +23,7 @@ const definitions = {
|
||||
57: { provenance: BUILD57_PROVENANCE, template: FIXED57_ROLE_TEMPLATE },
|
||||
58: { provenance: BUILD58_PROVENANCE, template: FIXED58_ROLE_TEMPLATE },
|
||||
59: { provenance: BUILD59_PROVENANCE, template: FIXED59_ROLE_TEMPLATE },
|
||||
60: { provenance: BUILD60_PROVENANCE, template: FIXED60_ROLE_TEMPLATE },
|
||||
}
|
||||
const exact=(a:unknown,b:unknown,label:string)=>{if(canonical(a)!==canonical(b))throw Error('Writer catalogue refused: '+label)}
|
||||
function captureBindings(input:InstallationRoleBindingsData):Readonly<Record<LogicalRole,string>> {
|
||||
|
||||
@@ -4,7 +4,7 @@ export type Json=null|boolean|number|string|Json[]|{[key:string]:Json}
|
||||
export type Row=Record<string,Json>
|
||||
export type Inventory=Record<string,Row[]>
|
||||
export const GROUPS=['columns','triggers','constraints','indexes','roleGrants','inheritance'] as const
|
||||
export type CatalogueEdition = 44 | 56 | 57 | 58 | 59
|
||||
export type CatalogueEdition = 44 | 56 | 57 | 58 | 59 | 60
|
||||
export const GLOBALS=['database','effectiveDatabase','effectiveFunctions','effectiveSchemas','effectiveSequences','events','functions','identities','memberships','parameters','roles','schemas','settings','sequences'] as const
|
||||
export const sorted=(rows:Row[])=>rows.slice().sort((a,b)=>canonical(a)<canonical(b)?-1:canonical(a)>canonical(b)?1:0)
|
||||
export const omit=(row:Row,names:readonly string[]):Row=>Object.fromEntries(Object.entries(row).filter(([key])=>!names.includes(key)))
|
||||
|
||||
@@ -6,6 +6,7 @@ import {BUILD56_PROVENANCE,FIXED56_ROLE_TEMPLATE} from './fixed56-build-definiti
|
||||
import {BUILD57_PROVENANCE,FIXED57_ROLE_TEMPLATE} from './fixed57-build-definition.js'
|
||||
import {BUILD58_PROVENANCE,FIXED58_ROLE_TEMPLATE} from './fixed58-build-definition.js'
|
||||
import {BUILD59_PROVENANCE,FIXED59_ROLE_TEMPLATE} from './fixed59-build-definition.js'
|
||||
import {BUILD60_PROVENANCE,FIXED60_ROLE_TEMPLATE} from './fixed60-build-definition.js'
|
||||
import {assertRestoreProfileQuarantine} from '../../src/db/database-restore-quarantine-profile.js'
|
||||
import {canonical,sha} from './application-writer-profile-canonical.js'
|
||||
import type {CatalogueEdition} from './catalogue-projection.js'
|
||||
@@ -28,6 +29,10 @@ export function approvedDefinition(value:unknown){
|
||||
assert.equal(canonical(v.provenance),canonical(BUILD59_PROVENANCE));assert.equal(canonical(v.template),canonical(FIXED59_ROLE_TEMPLATE))
|
||||
return Object.freeze({edition:59 as const,definitionSha256:BUILD59_PROVENANCE.templateSha256,manifestSha256:BUILD59_PROVENANCE.manifestSha256})
|
||||
}
|
||||
if(v.format==='application-writer-source60-definition-approval-v1'){
|
||||
assert.equal(canonical(v.provenance),canonical(BUILD60_PROVENANCE));assert.equal(canonical(v.template),canonical(FIXED60_ROLE_TEMPLATE))
|
||||
return Object.freeze({edition:60 as const,definitionSha256:BUILD60_PROVENANCE.templateSha256,manifestSha256:BUILD60_PROVENANCE.manifestSha256})
|
||||
}
|
||||
assert.equal(v.format,'application-writer-source56-definition-approval-v1')
|
||||
assert.equal(canonical(v.provenance),canonical(BUILD56_PROVENANCE));assert.equal(canonical(v.template),canonical(FIXED56_ROLE_TEMPLATE))
|
||||
return Object.freeze({edition:56 as const,definitionSha256:BUILD56_PROVENANCE.templateSha256,manifestSha256:BUILD56_PROVENANCE.manifestSha256})
|
||||
@@ -43,6 +48,7 @@ export const collectSource56Catalogue = (s:CatalogueSession, installation:Catalo
|
||||
export const collectSource57Catalogue = (s:CatalogueSession, installation:CatalogueInstallation) => collectCatalogue(s, installation, 57)
|
||||
export const collectSource58Catalogue = (s:CatalogueSession, installation:CatalogueInstallation) => collectCatalogue(s, installation, 58)
|
||||
export const collectSource59Catalogue = (s:CatalogueSession, installation:CatalogueInstallation) => collectCatalogue(s, installation, 59)
|
||||
export const collectSource60Catalogue = (s:CatalogueSession, installation:CatalogueInstallation) => collectCatalogue(s, installation, 60)
|
||||
async function collectCatalogue(s:CatalogueSession,installation:CatalogueInstallation,edition:CatalogueEdition){
|
||||
const settings=(await s.query("SELECT pg_catalog.current_setting('search_path') AS path,pg_catalog.current_setting('TimeZone') AS zone,pg_catalog.current_setting('DateStyle') AS dates")).rows
|
||||
assert.equal(settings.length,1);assert(['path','zone','dates'].every(k=>typeof settings[0][k]==='string'))
|
||||
@@ -52,7 +58,7 @@ async function collectCatalogue(s:CatalogueSession,installation:CatalogueInstall
|
||||
const bindings=installation.roleBindings,values=['operator','runtime','capture','publisher','control'].map(k=>bindings[k as keyof typeof bindings].name)
|
||||
if(edition>=58)await assertRestoreProfileQuarantine(s,bindings.runtime.name,bindings.operator.name,bindings.control.name)
|
||||
const bridge=new Fixed44CatalogueValueBridgeData(bindings,edition)
|
||||
await s.query('DECLARE mm_publisher44 NO SCROLL CURSOR WITHOUT HOLD FOR '+(edition===44?FIXED44_CATALOGUE_BUILD_SQL:edition===59?fixed59Sql:fixed56Sql),values);cursor=true
|
||||
await s.query('DECLARE mm_publisher44 NO SCROLL CURSOR WITHOUT HOLD FOR '+(edition===44?FIXED44_CATALOGUE_BUILD_SQL:edition>=59?fixed59Sql:fixed56Sql),values);cursor=true
|
||||
for(;;){const page=(await s.query('FETCH FORWARD 128 FROM mm_publisher44')).rows;bridge.acceptPage(page);if(page.length===0)break}
|
||||
const result=bridge.finish();await s.query('CLOSE mm_publisher44');cursor=false
|
||||
return {catalogSha256:sha(canonical({values:result.values.snapshotSha256,catalogue:result.catalogue})),definitionSha256:result.catalogue.definitionSha256,manifestSha256:result.catalogue.manifestSha256,leafCount:result.catalogue.leafRelations}
|
||||
|
||||
@@ -4,6 +4,7 @@ import {BUILD56_PROVENANCE,FIXED56_ROLE_TEMPLATE} from './fixed56-build-definiti
|
||||
import {BUILD57_PROVENANCE} from './fixed57-build-definition.js'
|
||||
import {BUILD58_PROVENANCE} from './fixed58-build-definition.js'
|
||||
import {BUILD59_PROVENANCE,FIXED59_ROLE_TEMPLATE} from './fixed59-build-definition.js'
|
||||
import {BUILD60_PROVENANCE,FIXED60_ROLE_TEMPLATE} from './fixed60-build-definition.js'
|
||||
import {fixedCatalogueParentPeriodData} from './application-writer-profile-catalogue-parent-policy.js'
|
||||
import {GROUPS,type CatalogueEdition,type Inventory} from './catalogue-projection.js'
|
||||
export const EXPANDED44_POLICY_VERSION='source44-managed-leaves-3000-data-v1' as const
|
||||
@@ -66,8 +67,19 @@ const EXPANDED59_DATA_POLICY = Object.freeze({
|
||||
maxRows: Object.freeze(Object.fromEntries(GROUPS.map(group => [group,source59BaseRows[group] + LEAVES * leafMax[group]])) as Record<typeof GROUPS[number],number>),
|
||||
definitionSha256: BUILD59_PROVENANCE.templateSha256,
|
||||
})
|
||||
const policies = {44: EXPANDED44_DATA_POLICY, 56: EXPANDED56_DATA_POLICY, 57: EXPANDED57_DATA_POLICY, 58: EXPANDED58_DATA_POLICY, 59: EXPANDED59_DATA_POLICY}
|
||||
const relationCounts = {44: perRelation, 56: source56PerRelation, 57: source57PerRelation, 58: source57PerRelation, 59: source59PerRelation}
|
||||
const source60PerRelation = new Map(source59PerRelation)
|
||||
const storageUsage = source59PerRelation.get('server_poll_storage_usage')!
|
||||
const removed = FIXED59_ROLE_TEMPLATE.constraints.length - FIXED60_ROLE_TEMPLATE.constraints.length
|
||||
source60PerRelation.set('server_poll_storage_usage', {...storageUsage, constraints: storageUsage.constraints - removed})
|
||||
const EXPANDED60_DATA_POLICY = Object.freeze({
|
||||
...EXPANDED59_DATA_POLICY,
|
||||
version: 'source60-managed-leaves-3000-data-v1',
|
||||
baseRows: Object.freeze({...source59BaseRows, constraints: source59BaseRows.constraints - removed}),
|
||||
maxRows: Object.freeze({...EXPANDED59_DATA_POLICY.maxRows, constraints: EXPANDED59_DATA_POLICY.maxRows.constraints - removed}),
|
||||
definitionSha256: BUILD60_PROVENANCE.templateSha256,
|
||||
})
|
||||
const policies = {44: EXPANDED44_DATA_POLICY, 56: EXPANDED56_DATA_POLICY, 57: EXPANDED57_DATA_POLICY, 58: EXPANDED58_DATA_POLICY, 59: EXPANDED59_DATA_POLICY, 60: EXPANDED60_DATA_POLICY}
|
||||
const relationCounts = {44: perRelation, 56: source56PerRelation, 57: source57PerRelation, 58: source57PerRelation, 59: source59PerRelation, 60: source60PerRelation}
|
||||
export const catalogueTopologyPolicy = (edition: CatalogueEdition) => policies[edition]
|
||||
export const expanded44ParentRowCountsData=()=>Object.freeze(Object.fromEntries(parents.map(name=>[name,Object.freeze({...perRelation.get(name)!})])))
|
||||
export interface ManagedLeafData {readonly parent:string;readonly name:string}
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { test } from "node:test"
|
||||
import { migrationManifestDigest } from "../../src/db/migration-manifest.js"
|
||||
import { createHash } from "node:crypto"
|
||||
import { MIGRATION_MANIFEST, migrationManifestDigest } from "../../src/db/migration-manifest.js"
|
||||
import { ixWriterProfileEnrollmentSql } from "../../src/db/internet-exchange-writer-profile.js"
|
||||
import { approvedDefinition } from "./catalogue.mjs"
|
||||
import { FIXED58_ROLE_TEMPLATE } from "./fixed58-build-definition.js"
|
||||
import { BUILD59_PROVENANCE, FIXED59_ROLE_TEMPLATE } from "./fixed59-build-definition.js"
|
||||
import { BUILD60_PROVENANCE, FIXED60_ROLE_TEMPLATE } from "./fixed60-build-definition.js"
|
||||
import { catalogueTopologyPolicy } from "./expanded44-data-policy.js"
|
||||
|
||||
test("source59 pins migration 0058 and alters only the IX catalogue and its existing servers references", () => {
|
||||
assert.equal(BUILD59_PROVENANCE.manifestSha256, migrationManifestDigest())
|
||||
assert.equal(BUILD59_PROVENANCE.manifestSha256, createHash("sha256").update(JSON.stringify(MIGRATION_MANIFEST.slice(0, 58))).digest("hex"))
|
||||
assert.equal(catalogueTopologyPolicy(59).baseRelations, catalogueTopologyPolicy(58).baseRelations + 3)
|
||||
const added = new Set(FIXED59_ROLE_TEMPLATE.tables.filter(row => String(row.relname).startsWith("ix_segment")).map(row => row.relname))
|
||||
assert.deepEqual([...added].sort(), ["ix_segment_devices", "ix_segment_revisions", "ix_segments"])
|
||||
@@ -19,6 +21,15 @@ test("source59 pins migration 0058 and alters only the IX catalogue and its exis
|
||||
assert.equal(FIXED59_ROLE_TEMPLATE.constraints.length - FIXED58_ROLE_TEMPLATE.constraints.length, 24)
|
||||
})
|
||||
|
||||
test("source60 changes poll storage constraints without changing writer grants or table topology", () => {
|
||||
assert.equal(BUILD60_PROVENANCE.manifestSha256, migrationManifestDigest())
|
||||
const approval = { format: "application-writer-source60-definition-approval-v1", provenance: BUILD60_PROVENANCE, template: FIXED60_ROLE_TEMPLATE }
|
||||
assert.equal(approvedDefinition(approval).definitionSha256, BUILD60_PROVENANCE.templateSha256)
|
||||
assert.deepEqual(FIXED60_ROLE_TEMPLATE.tables, FIXED59_ROLE_TEMPLATE.tables)
|
||||
assert.deepEqual(FIXED60_ROLE_TEMPLATE.roleGrants, FIXED59_ROLE_TEMPLATE.roleGrants)
|
||||
assert.equal(catalogueTopologyPolicy(60).baseRows.constraints, catalogueTopologyPolicy(59).baseRows.constraints - 1)
|
||||
})
|
||||
|
||||
test("source59 accepts the exact independently reviewed definition and restricts IX runtime grants", () => {
|
||||
const approval = { format: "application-writer-source59-definition-approval-v1", provenance: BUILD59_PROVENANCE, template: FIXED59_ROLE_TEMPLATE }
|
||||
assert.equal(approvedDefinition(approval).definitionSha256, BUILD59_PROVENANCE.templateSha256)
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { canonical, sha } from "./application-writer-profile-canonical.js"
|
||||
import { sorted, type Inventory } from "./catalogue-projection.js"
|
||||
import { FIXED59_ROLE_TEMPLATE } from "./fixed59-build-definition.js"
|
||||
import { POLL_WRITER_PROFILE_DEFINITION_SHA256, POLL_WRITER_PROFILE_MANIFEST_SHA256 } from "../../src/db/server-poll-writer-profile.js"
|
||||
|
||||
const quotaConstraint = "server_poll_storage_usage_check2"
|
||||
const definitions = new Map([
|
||||
["server_poll_storage_usage_admissions_check", "CHECK ((admissions >= 0))"],
|
||||
["server_poll_storage_rows_charge", "CHECK ((reserved_rows = ((admissions * 4019) + (compacted_admissions * 2))))"],
|
||||
["server_poll_storage_bytes_charge", "CHECK ((reserved_bytes = (((admissions * 8421376) + (compacted_admissions * 32768)) + archive_bytes)))"],
|
||||
])
|
||||
|
||||
export const FIXED60_ROLE_TEMPLATE: Readonly<Inventory> = Object.freeze({
|
||||
...FIXED59_ROLE_TEMPLATE,
|
||||
constraints: sorted(FIXED59_ROLE_TEMPLATE.constraints.filter(row => row.conname !== quotaConstraint || row.relname !== "server_poll_storage_usage").map(row => {
|
||||
const definition = row.relname === "server_poll_storage_usage" ? definitions.get(String(row.conname)) : undefined
|
||||
return definition ? { ...row, definition } : row
|
||||
})),
|
||||
functions: sorted(FIXED59_ROLE_TEMPLATE.functions.map(row => row.proname !== "server_poll_storage_admission_guard" ? row : {
|
||||
...row,
|
||||
definition: String(row.definition)
|
||||
.replace(/^ IF\(SELECT count\(\*\) FROM public\.server_poll_storage_usage WHERE scope IN\('global','owner:'\|\|NEW\.owner_id\)\n[^]*?THEN RAISE EXCEPTION 'poll admission quota exhausted'; END IF;\n/m, "")
|
||||
.replace("poll admission quota unavailable", "poll admission counters unavailable"),
|
||||
})),
|
||||
})
|
||||
|
||||
export const BUILD60_PROVENANCE = Object.freeze({
|
||||
format: "source60-poll-journal-profile-v1",
|
||||
manifestSha256: POLL_WRITER_PROFILE_MANIFEST_SHA256,
|
||||
templateSha256: POLL_WRITER_PROFILE_DEFINITION_SHA256,
|
||||
})
|
||||
|
||||
const digest = sha(canonical(FIXED60_ROLE_TEMPLATE))
|
||||
if (digest !== BUILD60_PROVENANCE.templateSha256) throw new Error("Fixed60 writer catalogue changed: " + digest)
|
||||
@@ -13,8 +13,9 @@ export const UPGRADE_APPROVAL_FORMAT='application-writer-upgrade44-to56-approval
|
||||
export const UPGRADE57_APPROVAL_FORMAT='application-writer-upgrade56-to57-approval-v1'
|
||||
export const UPGRADE58_APPROVAL_FORMAT='application-writer-upgrade57-to58-approval-v1'
|
||||
export const UPGRADE59_APPROVAL_FORMAT='application-writer-upgrade58-to59-approval-v1'
|
||||
export const UPGRADE60_APPROVAL_FORMAT='application-writer-upgrade59-to60-approval-v1'
|
||||
export const REBIND58_APPROVAL_FORMAT='application-writer-rebind58-after-restore-approval-v1'
|
||||
export const isUpgradeApprovalFormat=format=>[UPGRADE_APPROVAL_FORMAT,UPGRADE57_APPROVAL_FORMAT,UPGRADE58_APPROVAL_FORMAT,UPGRADE59_APPROVAL_FORMAT,REBIND58_APPROVAL_FORMAT].includes(format)
|
||||
export const isUpgradeApprovalFormat=format=>[UPGRADE_APPROVAL_FORMAT,UPGRADE57_APPROVAL_FORMAT,UPGRADE58_APPROVAL_FORMAT,UPGRADE59_APPROVAL_FORMAT,UPGRADE60_APPROVAL_FORMAT,REBIND58_APPROVAL_FORMAT].includes(format)
|
||||
function parsedApproval(value,format=publicationFormat){
|
||||
const upgrade=isUpgradeApprovalFormat(format)
|
||||
const keys=['format','manifestSha256','definitionSha256','catalogSha256','expectedHeadSha256','validityMs','expiresAt']
|
||||
|
||||
@@ -3,12 +3,13 @@ import pg from 'pg'
|
||||
import {createPrivateKey,createPublicKey,sign,X509Certificate} from 'node:crypto'
|
||||
import {open,lstat,realpath,unlink} from 'node:fs/promises'
|
||||
import {readProtected,writeFile,withJournalLease} from './operator-files.mjs'
|
||||
import {retainPublisherTlsPeer,upgradeApproval,isUpgradeApprovalFormat,UPGRADE_APPROVAL_FORMAT,UPGRADE57_APPROVAL_FORMAT,UPGRADE58_APPROVAL_FORMAT,UPGRADE59_APPROVAL_FORMAT,REBIND58_APPROVAL_FORMAT} from './operator-contract.mjs'
|
||||
import {retainPublisherTlsPeer,upgradeApproval,isUpgradeApprovalFormat,UPGRADE_APPROVAL_FORMAT,UPGRADE57_APPROVAL_FORMAT,UPGRADE58_APPROVAL_FORMAT,UPGRADE59_APPROVAL_FORMAT,UPGRADE60_APPROVAL_FORMAT,REBIND58_APPROVAL_FORMAT} from './operator-contract.mjs'
|
||||
import {BUILD44_PROVENANCE} from './fixed44-build-definition.js'
|
||||
import {BUILD56_PROVENANCE} from './fixed56-build-definition.js'
|
||||
import {BUILD57_PROVENANCE} from './fixed57-build-definition.js'
|
||||
import {BUILD58_PROVENANCE} from './fixed58-build-definition.js'
|
||||
import {BUILD59_PROVENANCE} from './fixed59-build-definition.js'
|
||||
import {BUILD60_PROVENANCE} from './fixed60-build-definition.js'
|
||||
import path from 'node:path'
|
||||
import {captureDatabaseSourceObservation,assertDatabaseSourceObservationCurrent} from '../../src/db/database-source-observation.js'
|
||||
import {MIGRATION_MANIFEST,migrationManifestDigest} from '../../src/db/migration-manifest.js'
|
||||
@@ -21,6 +22,7 @@ const upgradeTransitions = {
|
||||
[UPGRADE57_APPROVAL_FORMAT]: { predecessor: BUILD56_PROVENANCE, successor: BUILD57_PROVENANCE, oldEdition: 56, newEdition: 57 },
|
||||
[UPGRADE58_APPROVAL_FORMAT]: { predecessor: BUILD57_PROVENANCE, successor: BUILD58_PROVENANCE, oldEdition: 57, newEdition: 58 },
|
||||
[UPGRADE59_APPROVAL_FORMAT]: { predecessor: BUILD58_PROVENANCE, successor: BUILD59_PROVENANCE, oldEdition: 58, newEdition: 59 },
|
||||
[UPGRADE60_APPROVAL_FORMAT]: { predecessor: BUILD59_PROVENANCE, successor: BUILD60_PROVENANCE, oldEdition: 59, newEdition: 60 },
|
||||
[REBIND58_APPROVAL_FORMAT]: { predecessor: BUILD58_PROVENANCE, successor: BUILD58_PROVENANCE, oldEdition: 58, newEdition: 58 },
|
||||
}
|
||||
export function requireCurrentCatalogueDefinition(approval,definition){
|
||||
@@ -253,7 +255,7 @@ async function preflightCurrentProfile(pool,{deadlineAt=Date.now()+120000}={}){
|
||||
}
|
||||
async function inspectCurrentCatalogue(pool,{deadlineAt=Date.now()+120000}={}){
|
||||
const manifestSha256=migrationManifestDigest()
|
||||
const expected=definition?.edition===59?BUILD59_PROVENANCE:definition?.edition===58?BUILD58_PROVENANCE:undefined
|
||||
const expected={58:BUILD58_PROVENANCE,59:BUILD59_PROVENANCE,60:BUILD60_PROVENANCE}[definition?.edition]
|
||||
if(!expected||definition.manifestSha256!==manifestSha256||definition.definitionSha256!==expected.templateSha256)throw Error('Approved current writer definition required')
|
||||
return session(pool,deadlineAt,async s=>{
|
||||
s.phase('source-catalogue-inspection');await s.query('BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY');s.begun(true)
|
||||
@@ -264,7 +266,7 @@ async function inspectCurrentCatalogue(pool,{deadlineAt=Date.now()+120000}={}){
|
||||
const initial=await sourceVerifier.verify(facade,observation,options)
|
||||
const {security,catalogSha256}=await observeCurrentCatalogue(s,manifestSha256)
|
||||
const current=await readCurrent(s,installation,{validNow:false})
|
||||
const allowedHeads=definition.edition===59?[BUILD58_PROVENANCE,BUILD59_PROVENANCE]:[BUILD58_PROVENANCE]
|
||||
const allowedHeads=definition.edition===60?[BUILD59_PROVENANCE,BUILD60_PROVENANCE]:definition.edition===59?[BUILD58_PROVENANCE,BUILD59_PROVENANCE]:[BUILD58_PROVENANCE]
|
||||
if(!current||!allowedHeads.some(head=>head.templateSha256===current.policy.definitionSha256&&head.manifestSha256===current.policy.manifestSha256)||
|
||||
canonical(current.policy.source)!==canonical(sourceCoordinates(first))||canonical(current.policy.roles)!==canonical(security.roles)){
|
||||
throw Error('Approved same-installation writer predecessor required')
|
||||
|
||||
@@ -9,8 +9,9 @@ export const REVIEWED_PREDECESSORS = [
|
||||
{ length: 44, manifestSha256: "fffae3381732e6f276ba276aca7185f6a87587edf8272ba42763b7f49bc59ef5" },
|
||||
{ length: 56, manifestSha256: "b371d8d261f7dd69cf0e2ebc48d4316e3ad804360046bbaaf20e715da8812521" },
|
||||
{ length: 57, manifestSha256: "7dbd678e59740c14a29594180c86b85b3b2dd53fd5aa7a72da6d14a513760dbc" },
|
||||
{ length: 58, manifestSha256: "52c49786b6204dc11577131670cc0098c165ef54d419c25f0c70759e435c99fb" },
|
||||
] as const
|
||||
export const REVIEWED_SUCCESSOR_MANIFEST = "52c49786b6204dc11577131670cc0098c165ef54d419c25f0c70759e435c99fb"
|
||||
export const REVIEWED_SUCCESSOR_MANIFEST = "25913d7ea3e31361c6853084e9eed6f1a1b45806232122097ba2b7e830a315a9"
|
||||
export const canonical = (value: unknown): string => JSON.stringify(value, (_key, item: unknown) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item)
|
||||
export async function observation(intent: DatabaseSchemaIntent, pin: MigrationReview, existingKey = false) {
|
||||
// Fixed, purpose-separated server-keyed ACK issuer. Caller-supplied hashes
|
||||
@@ -56,7 +57,7 @@ export async function exactHistory(rows: Record<string, unknown>[], current: Ret
|
||||
return refuse("Migration release is not the exact internally recorded legacy release")
|
||||
}
|
||||
if (pin ? terminal.observationSha256 !== await observation(terminal.intent, pin, existingKey) :
|
||||
terminal.intent.manifestSha256 !== manifest || terminal.observationSha256 !== await legacy0037AdoptionObservation(terminal.intent)) {
|
||||
terminal.observationSha256 !== await legacy0037AdoptionObservation(terminal.intent)) {
|
||||
return refuse("Migration receipt is not the exact internally recorded file ACK")
|
||||
}
|
||||
pin ??= MIGRATION_MANIFEST[36]
|
||||
|
||||
@@ -200,13 +200,13 @@ test("reviewed 44 migration history keeps its original keyed receipts and resume
|
||||
assert(f.events.every(event => !event.startsWith("file:")))
|
||||
})
|
||||
|
||||
test("complete 56 receipts with or without the inherited 44 prefix dispatch the remaining two files", async () => {
|
||||
test("complete 56 receipts with or without the inherited 44 prefix dispatch the remaining files", async () => {
|
||||
for (const mixed of [false, true]) {
|
||||
const f = fixture()
|
||||
f.seedCompletedHistory(56, index => mixed && index < 44 ? reviewed44 : reviewed56)
|
||||
const previous = structuredClone([...f.history.values()])
|
||||
assert.equal((await f.run()).completedFiles, pins.length)
|
||||
assert.deepEqual(f.events.filter(event => event.startsWith("file:")), ["file:0057_mcp_routing_charge_audit_index.sql", "file:0058_internet_exchange.sql"])
|
||||
assert.deepEqual(f.events.filter(event => event.startsWith("file:")), ["file:0057_mcp_routing_charge_audit_index.sql", "file:0058_internet_exchange.sql", "file:0059_server_poll_journal_limits.sql"])
|
||||
assert.deepEqual([...f.history.values()].slice(0, 56), previous)
|
||||
f.events.length = 0
|
||||
assert.equal((await f.run()).completedFiles, pins.length)
|
||||
@@ -214,15 +214,23 @@ test("complete 56 receipts with or without the inherited 44 prefix dispatch the
|
||||
}
|
||||
})
|
||||
|
||||
test("the source58 migration history needs only the IX migration", async () => {
|
||||
test("the source58 migration history advances through IX and the poll journal migration", async () => {
|
||||
const f = fixture()
|
||||
f.seedCompletedHistory(57, index => index < 44 ? reviewed44 : index < 56 ? reviewed56 : reviewed57)
|
||||
const previous = structuredClone([...f.history.values()])
|
||||
assert.equal((await f.run()).completedFiles, pins.length)
|
||||
assert.deepEqual(f.events.filter(event => event.startsWith("file:")), ["file:0058_internet_exchange.sql"])
|
||||
assert.deepEqual(f.events.filter(event => event.startsWith("file:")), ["file:0058_internet_exchange.sql", "file:0059_server_poll_journal_limits.sql"])
|
||||
assert.deepEqual([...f.history.values()].slice(0, 57), previous)
|
||||
})
|
||||
|
||||
test("the source59 production prefix advances only through the poll journal migration", async () => {
|
||||
const f = fixture()
|
||||
f.seedCompletedHistory(58, index => index < 44 ? reviewed44 : index < 56 ? reviewed56 : index < 57 ? reviewed57 :
|
||||
"52c49786b6204dc11577131670cc0098c165ef54d419c25f0c70759e435c99fb")
|
||||
assert.equal((await f.run()).completedFiles, pins.length)
|
||||
assert.deepEqual(f.events.filter(event => event.startsWith("file:")), ["file:0059_server_poll_journal_limits.sql"])
|
||||
})
|
||||
|
||||
test("history 56 cannot omit a receipt or interleave another manifest", async () => {
|
||||
for (const invalid of ["incomplete", "interleaved"] as const) {
|
||||
const f = fixture()
|
||||
|
||||
@@ -2,10 +2,10 @@ import assert from "node:assert/strict"
|
||||
import { HEAD_DOMAIN, POLICY_DOMAIN, sha } from "./application-writer-profile-format.js"
|
||||
import { stagedModelClient, syntheticFixture } from "./application-writer-profile-registry-read-model.test.js"
|
||||
import { approvedRuntimeWriterProfile } from "./database-runtime-writer-profile.js"
|
||||
import { IX_WRITER_PROFILE_DEFINITION_SHA256, IX_WRITER_PROFILE_MANIFEST_SHA256 } from "./internet-exchange-writer-profile.js"
|
||||
import { POLL_WRITER_PROFILE_DEFINITION_SHA256, POLL_WRITER_PROFILE_MANIFEST_SHA256 } from "./server-poll-writer-profile.js"
|
||||
|
||||
const { subject, policy: basePolicy, state, signBody } = syntheticFixture("1")
|
||||
const policy = { ...basePolicy, definitionSha256: IX_WRITER_PROFILE_DEFINITION_SHA256, manifestSha256: IX_WRITER_PROFILE_MANIFEST_SHA256 }
|
||||
const policy = { ...basePolicy, definitionSha256: POLL_WRITER_PROFILE_DEFINITION_SHA256, manifestSha256: POLL_WRITER_PROFILE_MANIFEST_SHA256 }
|
||||
const expected = { installationId: subject.installationId, source: policy.source, roles: policy.roles }
|
||||
|
||||
function publish(next: typeof policy, previous = state.latest[0]) {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { z } from "zod"
|
||||
import { canonical, epoch, publicKey, type ApplicationWriterPolicy } from "./application-writer-profile-format.js"
|
||||
import { readCurrentApplicationWriterProfile, type ApplicationWriterRegistryReadSql } from "./application-writer-profile-registry-read.js"
|
||||
import { IX_WRITER_PROFILE_DEFINITION_SHA256, IX_WRITER_PROFILE_MANIFEST_SHA256 } from "./internet-exchange-writer-profile.js"
|
||||
import { POLL_WRITER_PROFILE_DEFINITION_SHA256, POLL_WRITER_PROFILE_MANIFEST_SHA256 } from "./server-poll-writer-profile.js"
|
||||
|
||||
const digest = z.string().regex(/^[a-f0-9]{64}$/)
|
||||
const approvalSchema = z.object({
|
||||
@@ -26,8 +26,8 @@ export function approvedRuntimeWriterProfile(
|
||||
async check(client: ApplicationWriterRegistryReadSql) {
|
||||
const current = await readCurrentApplicationWriterProfile(client, subject)
|
||||
const policy = current?.policy
|
||||
if (!current || !policy || policy.definitionSha256 !== IX_WRITER_PROFILE_DEFINITION_SHA256 ||
|
||||
policy.manifestSha256 !== IX_WRITER_PROFILE_MANIFEST_SHA256 ||
|
||||
if (!current || !policy || policy.definitionSha256 !== POLL_WRITER_PROFILE_DEFINITION_SHA256 ||
|
||||
policy.manifestSha256 !== POLL_WRITER_PROFILE_MANIFEST_SHA256 ||
|
||||
canonical(policy.source) !== canonical(expected.source) || canonical(policy.roles) !== canonical(expected.roles)) {
|
||||
throw new Error("Текущий подписанный профиль записи PostgreSQL не подтверждён")
|
||||
}
|
||||
|
||||
@@ -12,10 +12,10 @@ const reviewed = (source: string, extra: Partial<MigrationReview> = {}) => {
|
||||
const bytes = Buffer.from(source), file = "9000_fixture.sql"
|
||||
return () => analyzeMigration(file, bytes, { file, sha256: createHash("sha256").update(bytes).digest("hex"), transaction: "owner-transaction", selfMarker: false, opaqueBodies: 0, bodyReview: [], effects: ["Explicit inert fixture review"], ...extra })
|
||||
}
|
||||
await test("all 58 exact file pins and every top-level schema operation are inventoried", () => {
|
||||
assert.equal(inventory.length, 58); assert.equal(MIGRATION_MANIFEST.length, 58)
|
||||
await test("all 59 exact file pins and every top-level schema operation are inventoried", () => {
|
||||
assert.equal(inventory.length, 59); assert.equal(MIGRATION_MANIFEST.length, 59)
|
||||
assert.equal(inventory.filter(file => file.transaction === "owner-transaction").length, 17)
|
||||
assert.equal(inventory.filter(file => file.transaction === "self-managed-single-transaction").length, 41)
|
||||
assert.equal(inventory.filter(file => file.transaction === "self-managed-single-transaction").length, 42)
|
||||
assert(inventory.every(file => file.operations.length === file.statementCount && file.effects.length > 0))
|
||||
let tables = new Set<string>()
|
||||
for (const file of inventory) {
|
||||
@@ -32,8 +32,8 @@ await test("DO BEGIN and stored function BEGIN are never transaction boundaries"
|
||||
assert.equal(endpoint.topLevelTransactionControls.length, 2); assert.equal(endpoint.opaqueBodies.length, 2)
|
||||
assert.deepEqual(endpoint.opaqueBodies.map(body => body.kind), ["stored-function-body", "executed-do-body"])
|
||||
})
|
||||
await test("0035 through 0058 have exact atomic file-owned terminal markers", () => {
|
||||
assert.deepEqual(inventory.filter(file => file.selfMarker).map(file => file.id), ["0035_server_probe_journal", "0036_diagnostic_cancellations", "0037_server_probe_storage_v2", "0038_server_poll_journal_and_writer_guards", "0039_server_poll_storage", "0040_mcp_routing_reservations", "0041_server_poll_terminal_archives", "0042_server_poll_settings_epoch", "0043_mcp_routing_forward_charges", "0044_mcp_routing_manual_inverse_charges", "0045_mcp_operation_replay_tombstones", "0046_server_poll_operation_retirement", "0047_server_poll_retirement_claims", "0048_mcp_ordinary_retirement_claims", "0049_mcp_ordinary_telemetry_retirement", "0050_server_probe_retired_sources", "0051_server_probe_retirement_claims", "0052_server_probe_retired_gc", "0053_server_probe_terminal_proofs", "0054_mcp_geoip_retirement", "0055_mcp_backup_schedule_retirement", "0056_mcp_manual_inverse_recovery_v8", "0057_mcp_routing_charge_audit_index", "0058_internet_exchange"])
|
||||
await test("0035 through 0059 have exact atomic file-owned terminal markers", () => {
|
||||
assert.deepEqual(inventory.filter(file => file.selfMarker).map(file => file.id), ["0035_server_probe_journal", "0036_diagnostic_cancellations", "0037_server_probe_storage_v2", "0038_server_poll_journal_and_writer_guards", "0039_server_poll_storage", "0040_mcp_routing_reservations", "0041_server_poll_terminal_archives", "0042_server_poll_settings_epoch", "0043_mcp_routing_forward_charges", "0044_mcp_routing_manual_inverse_charges", "0045_mcp_operation_replay_tombstones", "0046_server_poll_operation_retirement", "0047_server_poll_retirement_claims", "0048_mcp_ordinary_retirement_claims", "0049_mcp_ordinary_telemetry_retirement", "0050_server_probe_retired_sources", "0051_server_probe_retirement_claims", "0052_server_probe_retired_gc", "0053_server_probe_terminal_proofs", "0054_mcp_geoip_retirement", "0055_mcp_backup_schedule_retirement", "0056_mcp_manual_inverse_recovery_v8", "0057_mcp_routing_charge_audit_index", "0058_internet_exchange", "0059_server_poll_journal_limits"])
|
||||
for (const file of inventory.filter(file => file.selfMarker)) { assert.equal(file.selfMarker!.atomicWithAllFileEffects, true); assert.equal(file.selfMarker!.statement, file.statementCount - 2); assert.equal(file.currentOuterMarkerGap, false) }
|
||||
assert.equal(inventory.filter(file => file.currentOuterMarkerGap).length, 34)
|
||||
})
|
||||
|
||||
@@ -891,6 +891,19 @@ const classifiedMigrationPins: readonly MigrationReview[] = [
|
||||
"Allows the IX Node server type without changing existing rows.",
|
||||
"Adds versioned IX configuration and device references."
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "0059_server_poll_journal_limits.sql",
|
||||
"sha256": "9b638ed5649ef75359b24ef61c80bf59390372c98c713447ddb6e32e61b6f5be",
|
||||
"transaction": "self-managed-single-transaction",
|
||||
"selfMarker": true,
|
||||
"opaqueBodies": 1,
|
||||
"bodyReview": [
|
||||
"Replaces the existing invoker admission trigger function and removes only the aggregate count, row and byte ceilings from the insertion path. Authority, locking, accounting, compaction and GC checks remain enforced."
|
||||
],
|
||||
"effects": [
|
||||
"Removes the journal quota while preserving exact reconciliation constraints and all previously retained histories."
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
export const POLL_WRITER_PROFILE_MANIFEST_SHA256 = "25913d7ea3e31361c6853084e9eed6f1a1b45806232122097ba2b7e830a315a9"
|
||||
export const POLL_WRITER_PROFILE_DEFINITION_SHA256 = "0bf9596d6fec209959bb00761e1396ad292d50a1e7d4c9f17d1222da75007a49"
|
||||
@@ -27,6 +27,7 @@ import internetPathRoutes from "./routes/internet-path.js"
|
||||
import evobgpRoutes from "./routes/evobgp.js"
|
||||
import { createStorageProbeRoutes } from "./routes/probe-storage-handler.js"
|
||||
import schedulerRoutes from "./routes/scheduler.js"
|
||||
import { ConfigurationBusyError } from "./services/config-mutation-lock.js"
|
||||
import sidebarCountsRoutes from "./routes/sidebar-counts.js"
|
||||
import alertsRoutes from "./routes/alerts.js"
|
||||
import backupsRoutes from "./routes/backups.js"
|
||||
@@ -105,6 +106,7 @@ export async function buildApp(opts?: {
|
||||
return reply.status(status).send({ error: "Внутренняя ошибка сервера" })
|
||||
}
|
||||
const message = error instanceof Error ? error.message : "Ошибка запроса"
|
||||
if (error instanceof ConfigurationBusyError) return reply.code(409).send({ error: message, code: error.code })
|
||||
return reply.status(status).send({ error: message })
|
||||
})
|
||||
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import { registerIpsecServerDeleteActions } from "./ipsec-server-delete-actions.js"
|
||||
import { registerCapabilityActions } from "./capability-actions.js"
|
||||
import { registerIncidentActions } from "./incident-actions.js"
|
||||
import { registerNetworkDiagnosticActions } from "./network-diagnostic-actions.js"
|
||||
import { registerResilienceActions } from "./resilience-actions.js"
|
||||
import { registerIpsecServerInitActions } from "./ipsec-server-init-actions.js"
|
||||
import { registerIpsecRevisionActions } from "./ipsec-revision-actions.js"
|
||||
import { registerWireguardRevisionActions } from "./wireguard-revision-actions.js"
|
||||
@@ -30,7 +34,7 @@ import { gatewayReferencesTable, isDynamicRouteInsideTable } from "../../service
|
||||
import { readLogStream } from "../../services/router-logs-query.js"
|
||||
import { subscribeLogDevice } from "../../services/router-logs-collector.js"
|
||||
import { ospfFilterFields, rosResources, readRosSnapshot, resourceById, routerClient, validateRosStep, splitOspfUnsetUpdate } from "./resources.js"
|
||||
import { registerMcpOperation, listMcpOperations } from "./registry.js"
|
||||
import { registerMcpOperation } from "./registry.js"
|
||||
import { accessGeneration, decryptSecret, encryptSecret, fingerprint, MAX_MCP_PUBLIC_ARRAY_ITEMS, MAX_MCP_PUBLIC_STRING_LENGTH, McpError, redact } from "./security.js"
|
||||
import { hasUnattendedPlanAuthority } from "./policy.js"
|
||||
import { effectiveMcpConnection } from "./store.js"
|
||||
@@ -76,6 +80,8 @@ import { prepareWireguardPeerDeletion, registerWireguardPeerDeleteActions } from
|
||||
import { registerFirewallActions } from "./firewall-actions.js"
|
||||
import { registerBfdMoveActions } from "./bfd-move-actions.js"
|
||||
import { registerGreMutationActions } from "./gre-mutation-actions.js"
|
||||
import { registerGreIpsecPairActions } from "./gre-ipsec-pair-actions.js"
|
||||
import { registerGreIke2PairActions } from "./gre-ikev2-pair-actions.js"
|
||||
import { registerIxActions } from "./internet-exchange-actions.js"
|
||||
import { registerGreRevisionActions } from "./gre-revision-actions.js"
|
||||
import { prepareGreNativeChange, registerGreNativeServices } from "./gre-native-actions.js"
|
||||
@@ -174,7 +180,7 @@ for (const resource of rosResources) {
|
||||
: z.object({ serverId, id: rowId.optional(), fields: publicFields.default({}), ...(resource.id === "vrf" ? { productionAdmission: z.literal(true).optional() } : {}) }).strict()
|
||||
const delegated = resource.id === "wireguard" && action !== "create" || resource.id === "wireguard_peer" || resource.id === "gre" && action !== "create" || resource.id === "ipsec_peer" && action !== "create" || resource.id === "certificate" && action === "delete" || resource.id === "container" && action === "delete"
|
||||
const guardsOspfInterfaceUse = action !== "create" && !delegated && ospfInterfaceResources.includes(resource.id)
|
||||
const previousVersion = action === "create" ? (["ospf_template", "wireguard_peer", "wireguard", "bfd_configuration"].includes(resource.id) ? 3 : 2) : resource.id === "ipsec_peer" || resource.id === "certificate" && action === "delete" ? 2 : resource.id === "wireguard" && action === "update" ? 3 : resource.id === "ospf_template" && action !== "delete" || resource.id === "wireguard_peer" || resource.id === "wireguard" || resource.id === "ip_settings" ? 2 : 1
|
||||
const previousVersion = action === "create" ? (resource.id === "bfd_configuration" ? 4 : ["ospf_template", "wireguard_peer", "wireguard"].includes(resource.id) ? 3 : 2) : resource.id === "ipsec_peer" || resource.id === "certificate" && action === "delete" ? 2 : resource.id === "wireguard" && action === "update" ? 3 : resource.id === "ospf_template" && action !== "delete" || resource.id === "wireguard_peer" || resource.id === "wireguard" || resource.id === "ip_settings" ? 2 : 1
|
||||
add(`ros.${resource.id}.${action}`, `mm_${resource.id}_${action}_plan`, `${resource.title}: ${action}`, resource.permission.split(":")[1], resource.id === "certificate" && action === "update" ? ["mm:certificates:write", "mm:network:write"] : resource.permission + ":write", "write", "servers", schema, {
|
||||
version: resource.id === "ipsec_peer" ? (action === "create" ? 5 : 3) : resource.id === "certificate" ? (action === "update" ? 4 : 3) : previousVersion + (delegated ? 0 : 1) + (resource.id === "bfd_configuration" ? 4 : resource.id === "ospf_template" ? (action === "update" ? 8 : 7) : 0) + (resource.id === "vrf" ? (action === "delete" ? 3 : 2) : 0) + (resource.id === "ospf_instance" ? 2 : 0) + (["bridge", "bridge_port", "bridge_vlan", "ip_settings", "ipv6_settings"].includes(resource.id) ? 1 : 0) + (guardsOspfInterfaceUse ? 1 : 0),
|
||||
prepare: async (input, context) => {
|
||||
@@ -386,9 +392,8 @@ for (const definition of [
|
||||
})
|
||||
}
|
||||
|
||||
add("capabilities.read", "mm_capabilities_get", "Доступные возможности", "mcp", null, "read", "connection", z.object({}).strict(), {
|
||||
read: async (_input, context) => ({ operations: listMcpOperations().filter(operation => operation.implementation === "available" && context.connection.policy.scope.operationIds.includes(operation.id)), schemaVersion: 1 }),
|
||||
})
|
||||
registerCapabilityActions(add)
|
||||
registerIncidentActions(add)
|
||||
add("servers.list", "mm_servers_list", "Серверы", "servers", "mm:servers:read", "read", "servers", z.object({ serverId: serverId.optional(), ...paging }).strict(), {
|
||||
read: async (input, context) => {
|
||||
const ids = typeof input.serverId === "number" ? [input.serverId] : context.connection.policy.scope.serverIds
|
||||
@@ -664,6 +669,8 @@ add("operations.read", "mm_operation_get", "Результат своей опе
|
||||
})
|
||||
|
||||
registerRoutingActions(add)
|
||||
registerNetworkDiagnosticActions(add)
|
||||
registerResilienceActions(add)
|
||||
registerRoutingProfileActions(add)
|
||||
registerRoutingControls(add)
|
||||
registerLifecycleActions(add)
|
||||
@@ -702,6 +709,8 @@ registerWireguardInterfaceDeleteActions(add)
|
||||
registerFirewallActions(add)
|
||||
registerBfdMoveActions(add)
|
||||
registerGreMutationActions(add)
|
||||
registerGreIpsecPairActions(add)
|
||||
registerGreIke2PairActions(add)
|
||||
registerIxActions(add)
|
||||
registerGreRevisionActions(add)
|
||||
registerGreNativeServices()
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { z } from "zod"
|
||||
import { readStaticBgpConnection } from "../../services/bgp-connection-read.js"
|
||||
import { readBgpInstanceContext, readStaticBgpConnection } from "../../services/bgp-connection-read.js"
|
||||
import { bgpExportConnection, bgpExportSources, bgpRedistributionMode, bgpTemplateReferences, nativeBgpExportValue, nativeBgpRows, type BgpExportMode, type NativeBgpRow } from "../../services/bgp-export-model.js"
|
||||
import { readOspfEffectiveDisabled } from "../../services/ospf-effective-disabled.js"
|
||||
import { executeGuardedApplicationWrite } from "../../services/config-mutation-policy.js"
|
||||
@@ -70,9 +70,18 @@ async function readState(input: Record<string, unknown>) {
|
||||
return found[0]
|
||||
}
|
||||
const instance = unique("bgp_instance", connection.instance), vrf = unique("vrf", connection.vrf), table = unique("routing_table", connection["routing-table"])
|
||||
if (instance.vrf !== connection.vrf || instance["routing-table"] !== connection["routing-table"] || vrf.name !== table.name) throw new McpError("STATE_CONFLICT", "Экспорт требует одинаковые явные instance/connection VRF и таблицу", 409)
|
||||
const [v4, v6] = await Promise.all([client.get<unknown>("/ip/route"), client.get<unknown>("/ipv6/route")])
|
||||
const sources = [...parseState("IPv4 source origins/table/prefixes", () => bgpExportSources(v4, String(table.name), sourceModes, 4)), ...parseState("IPv6 source origins/table/prefixes", () => bgpExportSources(v6, String(table.name), sourceModes, 6))]
|
||||
const instanceContext = await readBgpInstanceContext(client, { ...instance, ".id": String(instance[".id"]) })
|
||||
if (unique("vrf", instanceContext.vrf)[".id"] !== vrf[".id"] || unique("routing_table", instanceContext.table)[".id"] !== table[".id"]) throw new McpError("STATE_CONFLICT", "Контекст VRF и таблицы у BGP instance и connection расходится", 409)
|
||||
const tableName = String(table.name)
|
||||
const sourceGroups = await Promise.all(([4, 6] as const).flatMap(family => sourceModes.filter(kind => kind !== "disabled").map(async kind => {
|
||||
const params = new URLSearchParams({ "routing-table": tableName, [kind === "connected" ? "connect" : "static"]: "true" })
|
||||
const rows = nativeBgpRows(await client.get<unknown>(`${family === 4 ? "/ip/route" : "/ipv6/route"}?${params}`))
|
||||
const candidates = parseState(`IPv${family} source origins/table/prefixes`, () => bgpExportSources(rows, tableName, [kind], family))
|
||||
if (candidates.length !== rows.length) throw new McpError("STATE_UNAVAILABLE", "Ответ RouterOS не соответствует запросу источников BGP", 409)
|
||||
return candidates
|
||||
})))
|
||||
const sources = sourceGroups.flat().sort((a, b) => a.family - b.family || a.id.localeCompare(b.id))
|
||||
if (new Set(sources.map(row => `${row.family}:${row.id}`)).size !== sources.length) throw new McpError("STATE_UNAVAILABLE", "Повторяющиеся источники экспорта BGP", 409)
|
||||
if (sources.length > 500) throw new McpError("LIMIT_EXCEEDED", "Экспорт BGP превышает 500 исходных маршрутов", 409)
|
||||
const objects: ChangeEvidence["objects"] = [
|
||||
{ kind: "bgp-export", id, serverId }, { kind: "bgp_connection", id, serverId },
|
||||
@@ -87,7 +96,7 @@ async function readState(input: Record<string, unknown>) {
|
||||
const before = { serverId, serverProof, id, instance: connection.instance, vrf: connection.vrf, table: connection["routing-table"], mode: currentMode, localMode, inheritedMode,
|
||||
templates: templateProof.map(value => ({ id: value.row[".id"], name: value.row.name, mode: value.mode })),
|
||||
sourceModes, sources: sources.map(({ proof: _proof, ...row }) => row),
|
||||
connectionProof: await configurationProof(serverId, id, connection), sourceProof: await privateSecretFingerprint(fingerprint({ serverProof, parentProof, sources, templateProof }), `bgp-export-sources:${serverId}:${id}`) }
|
||||
connectionProof: await configurationProof(serverId, id, connection), sourceProof: await privateSecretFingerprint(fingerprint({ serverProof, parentProof, instanceContext, sources, templateProof }), `bgp-export-sources:${serverId}:${id}`) }
|
||||
return { server, client, connection, before, objects }
|
||||
}
|
||||
async function state(input: Record<string, unknown>) {
|
||||
@@ -117,6 +126,7 @@ export function registerBgpExportActions(register: typeof add) {
|
||||
},
|
||||
})
|
||||
register("routing.bgp.export", "mm_bgp_export_plan", "Человеческий план перераспределения connected/static в BGP с проверкой источников; disabled отключает только перераспределение", "bgp", ["mm:bgp:write", "mm:network:read", "mm:filters:read"], "write", "servers", schema, {
|
||||
version: 2,
|
||||
prepare: async input => {
|
||||
const initial = await state(input), before = initial.before, request = { ...input, sourceModes: before.sourceModes, beforeFingerprint: fingerprint(before), expectedServerProof: before.serverProof }
|
||||
return { target: { scope: "servers", serverIds: [Number(input.serverId)] }, objects: initial.objects, snapshots: [], before,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { z } from "zod"
|
||||
import { pool } from "../../db/index.js"
|
||||
import { readStaticBgpConnection } from "../../services/bgp-connection-read.js"
|
||||
import { readBgpInstanceContext, readStaticBgpConnection } from "../../services/bgp-connection-read.js"
|
||||
import { nativeBgpRows, bgpTemplateReferences, type NativeBgpRow } from "../../services/bgp-export-model.js"
|
||||
import { bgpFilterName, bgpFilterProperty, effectiveBgpFilter, stableBgpPolicyRow, type BgpFilterDirection } from "../../services/bgp-filter-binding-model.js"
|
||||
import { readOspfEffectiveDisabled } from "../../services/ospf-effective-disabled.js"
|
||||
@@ -60,12 +60,14 @@ async function readState(input: Record<string, unknown>) {
|
||||
const [effectiveInstance] = await readOspfEffectiveDisabled<NativeBgpRow & { disabled?: string }>([instance], nativeId => client.post("/routing/bgp/instance/get", { ".id": nativeId, "value-name": "disabled" }))
|
||||
if (!["false", "no"].includes(String(effectiveInstance.disabled))) throw new Error("BGP instance disabled/unknown")
|
||||
Object.assign(instance, effectiveInstance)
|
||||
for (const key of ["vrf", "routing-table"]) if (instance[key] === undefined || instance[key] === "") {
|
||||
const value = bgpFilterName(await client.post("/routing/bgp/instance/get", { ".id": String(instance[".id"]), "value-name": key }))
|
||||
if (!value) throw new Error("BGP instance effective context not confirmed")
|
||||
instance[key] = value
|
||||
const instanceContext = await readBgpInstanceContext(client, instance)
|
||||
if (unique("vrf", instanceContext.vrf)[".id"] !== vrf[".id"]) throw new Error("BGP instance/connection VRFs disagree")
|
||||
const instanceTable = unique("routing_table", instanceContext.table)
|
||||
const separateTables = instanceTable[".id"] !== table[".id"]
|
||||
if (separateTables && snapshots.find(row => row.resource === "vrf")!.rows.some(owner =>
|
||||
owner[".id"] !== vrf[".id"] && (owner.name === table.name || owner.name === instanceTable.name))) {
|
||||
throw new Error("BGP routing table belongs to a different VRF")
|
||||
}
|
||||
if (unique("vrf", instance.vrf)[".id"] !== vrf[".id"] || unique("routing_table", instance["routing-table"])[".id"] !== table[".id"] || vrf.name !== table.name) throw new Error("BGP instance/connection contexts disagree")
|
||||
const filters = nativeBgpRows(await client.get("/routing/filter/rule"))
|
||||
if (filters.length > 1000) throw new McpError("LIMIT_EXCEEDED", "Каталог BGP filters превышает 1000 строк", 409)
|
||||
const selected = filters.filter(row => row.chain === desired)
|
||||
@@ -75,13 +77,14 @@ async function readState(input: Record<string, unknown>) {
|
||||
const protections = (await pool.query("SELECT object_ref FROM mcp_protections WHERE object_ref->>'serverId'=$1 OR (object_ref->>'kind'='server' AND object_ref->>'id'=$1) LIMIT 1001", [String(serverId)])).rows
|
||||
if (protections.length > 1000) throw new Error("BGP protection closure exceeds limit")
|
||||
const objects: ChangeEvidence["objects"] = [{ kind: "bgp-policy", id, serverId }, { kind: "bgp_connection", id, serverId },
|
||||
...[["bgp_instance", instance], ["vrf", vrf], ["routing_table", table]].map(([kind, row]) => ({ kind: String(kind), id: String((row as Record<string, unknown>)[".id"]), serverId })),
|
||||
...[["bgp_instance", instance], ["vrf", vrf], ["routing_table", table], ["routing_table", instanceTable]].map(([kind, row]) => ({ kind: String(kind), id: String((row as Record<string, unknown>)[".id"]), serverId })),
|
||||
...filters.map(row => ({ kind: "routing_filter", id: row[".id"], serverId })), ...[...used.keys()].map(nativeId => ({ kind: "bgp_template", id: nativeId, serverId })),
|
||||
...protections.map(({ object_ref: ref }) => ({ kind: ref.kind, id: ref.id, serverId }))]
|
||||
const uniqueObjects = [...new Map(objects.map(row => [fingerprint(row), row])).values()]
|
||||
if (uniqueObjects.length > 1000) throw new Error("BGP dependency closure exceeds limit")
|
||||
const canonicalConnection = { ...stableBgpPolicyRow(connection), [property]: effectiveChain }
|
||||
const dependencyProof = await proof(serverId, id, "dependencies", { serverProof, otherConnections: connections.filter(row => row[".id"] !== id).map(stableBgpPolicyRow), instance: stableBgpPolicyRow(instance), vrf: { ...stableBgpPolicyRow(vrf), ...(vrf.interfaces !== undefined ? { interfaces: canonicalVrfMembers(vrf.interfaces) } : {}) }, table: stableBgpPolicyRow(table),
|
||||
const dependencyProof = await proof(serverId, id, "dependencies", { serverProof, otherConnections: connections.filter(row => row[".id"] !== id).map(stableBgpPolicyRow), instance: stableBgpPolicyRow(instance), instanceContext, vrf: { ...stableBgpPolicyRow(vrf), ...(vrf.interfaces !== undefined ? { interfaces: canonicalVrfMembers(vrf.interfaces) } : {}) }, table: stableBgpPolicyRow(table),
|
||||
...(separateTables ? { instanceTable: stableBgpPolicyRow(instanceTable) } : {}),
|
||||
filters: filters.map(stableBgpPolicyRow), used: [...used.values()], references, protections })
|
||||
const before = { serverId, id, direction: input.direction, property, instance: instance.name, vrf: vrf.name, table: table.name, localChain, inheritedChain, effectiveChain,
|
||||
selectedRuleCount: selected.length, selectedEnabledRuleCount: effectiveFilters.filter(row => ["false", "no"].includes(String(row.disabled))).length, serverProof, dependencyProof,
|
||||
@@ -112,6 +115,7 @@ export function registerBgpFilterBindingActions(register: typeof add) {
|
||||
},
|
||||
})
|
||||
register("routing.bgp.filter.bind", "mm_bgp_filter_binding_plan", "Человеческий план локальной input/output привязки BGP к существующей цепочке; пустая chain очищает local binding", "bgp", ["mm:bgp:write", "mm:filters:read", "mm:network:read"], "write", "servers", schema, {
|
||||
version: 2,
|
||||
prepare: async input => {
|
||||
const initial = await state(input)
|
||||
return { target: { scope: "servers", serverIds: [initial.server.id] }, objects: initial.objects, snapshots: [], before: initial.before, requiresHuman: true, verificationScope: "configuration", mutationCost: 1,
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { z } from "zod"
|
||||
import { hasPermission } from "../../lib/permissions.js"
|
||||
import { bgpPrefixRows } from "../../services/bgp-prefix-model.js"
|
||||
import { BgpRibChanged, bgpRibSelection, readBgpRib } from "../../services/bgp-rib-observation.js"
|
||||
import { nativeBgpRows } from "../../services/bgp-export-model.js"
|
||||
import { getServerRowById } from "../servers/repository/servers-repository.js"
|
||||
import { routerClient } from "./resources.js"
|
||||
import { effectiveMcpConnection } from "./store.js"
|
||||
import { createRoutingSourceContext, readRoutingEndpoints } from "./routing-observation-source.js"
|
||||
import { fingerprint, McpError } from "./security.js"
|
||||
import type { ActionContext } from "./action-types.js"
|
||||
import type { add } from "./actions.js"
|
||||
@@ -17,6 +19,27 @@ async function access(context: ActionContext) {
|
||||
if (fingerprint(current.policy) !== fingerprint(context.connection.policy)) throw new McpError("RESET_REQUIRED", "Область чтения BGP изменилась", 409)
|
||||
}
|
||||
export function registerBgpPrefixActions(register: typeof add) {
|
||||
const observation = bgpRibSelection.safeExtend({ serverId: z.number().int().positive().safe() })
|
||||
register("routing.bgp.rib.read", "mm_bgp_rib_get", "IPv4 BGP RIB с filtered-путями. Для соседа укажите sessionName или peerCacheId. Для следующих страниц сохраните expectedFingerprint первой страницы", "bgp", permissions, "read", "servers", observation, { read: async (input, context) => {
|
||||
const { serverId, ...selection } = observation.parse(input)
|
||||
await access(context)
|
||||
const source = await createRoutingSourceContext(await readRoutingEndpoints([serverId]))
|
||||
if (source.expected.length !== 1) throw new McpError("DEVICE_UNAVAILABLE", "Источник RIB недоступен", 409)
|
||||
const check = async () => { await access(context); await source.assertCurrent() }
|
||||
try {
|
||||
await check()
|
||||
const { client } = await routerClient(serverId)
|
||||
const startedAt = new Date().toISOString()
|
||||
const result = await readBgpRib(client, selection, check, context.signal)
|
||||
await check()
|
||||
return { serverId, ...result, startedAt, observedAt: new Date().toISOString(), timestampKind: "backend-receipt", forwardingVerified: false }
|
||||
} catch (error) {
|
||||
await check()
|
||||
if (error instanceof McpError) throw error
|
||||
if (error instanceof BgpRibChanged) throw new McpError("STATE_CONFLICT", "Состояние RIB изменилось; повторите чтение с первой страницы", 409)
|
||||
throw new McpError("STATE_UNAVAILABLE", "Полнота нативного чтения IPv4 BGP RIB не подтверждена", 409)
|
||||
}
|
||||
} })
|
||||
register("routing.bgp.prefixes.read", "mm_bgp_prefixes_get", "Наблюдаемые BGP-префиксы IPv4/IPv6 в явной таблице; active nullable, без доказательства forwarding или attribution к peer", "bgp", permissions, "read", "servers", z.object({
|
||||
serverId: z.number().int().positive().safe(), family: z.enum(["ipv4", "ipv6"]).default("ipv4"),
|
||||
table: z.string().trim().min(1).max(100).refine(value => !/[\u0000-\u001f\u007f]/.test(value)).default("main"),
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { z } from "zod"
|
||||
import type { McpPolicyPreviewRequest } from "@mmapp/contracts/mcp"
|
||||
import type { ActionContext } from "./action-types.js"
|
||||
import type { add } from "./actions.js"
|
||||
import { evaluateMcpPolicy } from "./policy.js"
|
||||
import { listMcpOperations } from "./registry.js"
|
||||
|
||||
const identifier = z.string().trim().min(1).max(200).optional()
|
||||
const capabilityInput = z.object({
|
||||
operationId: identifier,
|
||||
toolName: identifier,
|
||||
section: identifier,
|
||||
effect: z.enum(["read", "write", "diagnostic"]).optional(),
|
||||
scope: z.enum(["servers", "global", "connection"]).optional(),
|
||||
serverId: z.number().int().positive().safe().optional(),
|
||||
includeApplicability: z.boolean().optional(),
|
||||
applicable: z.boolean().optional(),
|
||||
}).strict()
|
||||
|
||||
export function readCapabilities(input: z.infer<typeof capabilityInput>, connection: ActionContext["connection"], now = new Date()) {
|
||||
const { policy, owner_permissions: ownerPermissions } = connection
|
||||
const granted = new Set(policy.scope.operationIds)
|
||||
const operations = listMcpOperations().filter(operation =>
|
||||
operation.implementation === "available" && granted.has(operation.id) &&
|
||||
(input.operationId === undefined || operation.id === input.operationId) &&
|
||||
(input.toolName === undefined || operation.toolName === input.toolName) &&
|
||||
(input.section === undefined || operation.section === input.section) &&
|
||||
(input.effect === undefined || operation.effect === input.effect) &&
|
||||
(input.scope === undefined || operation.scope === input.scope) &&
|
||||
(input.serverId === undefined || operation.scope === "servers"))
|
||||
if (!input.includeApplicability && input.serverId === undefined && input.applicable === undefined) return { operations, schemaVersion: 1 }
|
||||
|
||||
const assessed = operations.map(operation => {
|
||||
const serverId = input.serverId ?? policy.scope.serverIds[0]
|
||||
const target: McpPolicyPreviewRequest["target"] | null = operation.scope === "servers"
|
||||
? serverId === undefined ? null : { scope: "servers", serverIds: [serverId] }
|
||||
: { scope: operation.scope }
|
||||
const assessment = target
|
||||
? evaluateMcpPolicy({ operationId: operation.id, policy, ownerPermissions, target, objects: [], protections: [], objectCount: 0,
|
||||
usage: { callsInMinute: 0, concurrentReads: 0, mutationsInHour: 0 }, auditAvailable: true }, now)
|
||||
: { decision: "denied" as const, reasons: [{ code: "SERVER_DENIED", message: "Подключению не выдан доступ к серверам" }] }
|
||||
return { ...operation, applicability: { decision: assessment.decision, reasons: assessment.reasons,
|
||||
serverId: operation.scope === "servers" ? serverId ?? null : null } }
|
||||
})
|
||||
return { operations: assessed.filter(operation => input.applicable === undefined || input.applicable === (operation.applicability.decision !== "denied")),
|
||||
schemaVersion: 1, applicabilityBasis: "effective-policy-before-arguments-and-runtime-checks", observedAt: now.toISOString() }
|
||||
}
|
||||
|
||||
export function registerCapabilityActions(register: typeof add) {
|
||||
register("capabilities.read", "mm_capabilities_get", "Доступные возможности", "mcp", null, "read", "connection", capabilityInput, {
|
||||
read: async (input, context) => readCapabilities(capabilityInput.parse(input), context.connection),
|
||||
})
|
||||
}
|
||||
@@ -9,11 +9,20 @@ assert.equal(new Set(coverage.routes.map(routeKey)).size, coverage.routes.length
|
||||
assert.deepEqual(coverage.routes.map(routeKey).sort(), actual.map(routeKey).sort(), "REST routes changed: update mcp-coverage.json with a typed tool, human-only reason, or explicit pending adapter")
|
||||
const implemented = new Set(listActions().map(action => action.operation.id))
|
||||
const ixInterfaceRoutes = new Set([
|
||||
"POST /api/ix/import",
|
||||
"GET /api/ix/linux-bonds",
|
||||
"POST /api/ix/segments/:id/linux-bonds",
|
||||
"DELETE /api/ix/segments/:id/linux-bonds/:bondId",
|
||||
"POST /api/ix/segments/:id/linux-bonds/:bondId/export",
|
||||
"GET /api/ix/nodes",
|
||||
"GET /api/ix/segments/:id/linux",
|
||||
"GET /api/ix/topology",
|
||||
"POST /api/ix/preview",
|
||||
"POST /api/ix/segments",
|
||||
"POST /api/ix/segments/:id/linux",
|
||||
"POST /api/ix/segments/:id/linux/credential",
|
||||
"POST /api/ix/segments/:id/linux/revoke",
|
||||
"POST /api/ix/segments/:id/transit",
|
||||
])
|
||||
for (const route of coverage.routes) {
|
||||
assert.equal(route.status === "mediated", route.operations.length > 0, routeKey(route))
|
||||
|
||||
@@ -10,6 +10,8 @@ const leases = createPool(limit, true)
|
||||
leases.on("error", () => console.error("MCP database request lease lost on idle connection"))
|
||||
const apiLeases = createPool(limit, true)
|
||||
apiLeases.on("error", () => console.error("REST database request lease lost on idle connection"))
|
||||
const writeReserve = createPool(2, true)
|
||||
writeReserve.on("error", () => console.error("REST write database lease lost on idle connection"))
|
||||
const detachedApiLeases = createPool(2, true)
|
||||
detachedApiLeases.on("error", () => console.error("Detached REST database lease lost on idle connection"))
|
||||
const context = new AsyncLocalStorage<{ accepting: boolean; children: Set<Promise<unknown>>; signal: AbortSignal }>()
|
||||
@@ -28,19 +30,24 @@ export function withActiveDatabaseRequest<T>(run: (signal: AbortSignal) => Promi
|
||||
return child
|
||||
}
|
||||
|
||||
export function withMcpDatabaseRequest<T>(run: () => Promise<T>): Promise<T> { return withDatabaseRequest(run, true) }
|
||||
export function withDatabaseApiRequest<T>(run: () => Promise<T>): Promise<T> { return withDatabaseRequest(run, false) }
|
||||
export function withMcpDatabaseRequest<T>(run: () => Promise<T>): Promise<T> { return withDatabaseRequest(run, leases) }
|
||||
export function withDatabaseApiRequest<T>(run: () => Promise<T>, mutation = false): Promise<T> {
|
||||
// A burst of slow GETs must leave room for a configuration change to reach its lock.
|
||||
const saturated = apiLeases.totalCount >= limit && apiLeases.idleCount === 0
|
||||
return withDatabaseRequest(run, mutation && saturated ? writeReserve : apiLeases)
|
||||
}
|
||||
export function checkDatabaseApiStartup(): Promise<void> {
|
||||
return withDatabaseRequest(async () => {}, false, false, true)
|
||||
return withDatabaseRequest(async () => {}, apiLeases, true)
|
||||
}
|
||||
|
||||
async function withDatabaseRequest<T>(run: () => Promise<T>, mcp: boolean, detached = false, starting = false): Promise<T> {
|
||||
async function withDatabaseRequest<T>(run: () => Promise<T>, pool: typeof apiLeases, starting = false): Promise<T> {
|
||||
const nested = withActiveDatabaseRequest(run)
|
||||
if (nested) return nested
|
||||
const mcp = pool === leases
|
||||
if (mcp && active >= limit) throw new McpError("RATE_LIMITED", "Лимит одновременно выполняемых запросов MCP", 429)
|
||||
if (mcp) active++
|
||||
try {
|
||||
const client = await (detached ? detachedApiLeases : mcp ? leases : apiLeases).connect()
|
||||
const client = await pool.connect()
|
||||
let destroy = true, acquired = false
|
||||
const lifetime = new AbortController()
|
||||
const disconnected = () => lifetime.abort(new McpError("PROTOCOL_STORAGE_BUSY", "Соединение с допуском MCP потеряно", 503))
|
||||
@@ -90,5 +97,5 @@ export function withMcpRunnerDatabaseRequest<T>(run: () => Promise<T>): Promise<
|
||||
|
||||
/** Detached jobs keep their own lease through terminal persistence after the HTTP response. */
|
||||
export function withDetachedDatabaseApiRequest<T>(run: () => Promise<T>): Promise<T> {
|
||||
return context.exit(() => sharedDatabaseGate.request(() => withDatabaseRequest(run, false, true)))
|
||||
return context.exit(() => sharedDatabaseGate.request(() => withDatabaseRequest(run, detachedApiLeases)))
|
||||
}
|
||||
@@ -42,11 +42,21 @@ export function registerLegacyFlowAnalyticsAction(register: typeof add) {
|
||||
})
|
||||
}
|
||||
|
||||
const flowTupleSchema = z.object({
|
||||
srcIp: z.union([z.ipv4(), z.ipv6()]).optional().describe("Точный IP источника в экспортированной записи"),
|
||||
dstIp: z.union([z.ipv4(), z.ipv6()]).optional().describe("Точный IP назначения в экспортированной записи"),
|
||||
srcPort: z.number().int().min(0).max(65535).optional(),
|
||||
dstPort: z.number().int().min(0).max(65535).optional(),
|
||||
protocol: z.number().int().min(0).max(255).optional().describe("Номер IP-протокола IANA"),
|
||||
})
|
||||
const REPORT_ROW_LIMIT = 20000
|
||||
|
||||
export function registerFlowAnalyticsActions(register: typeof add) {
|
||||
register("traffic.flow.analytics.read", "mm_netflow_analytics_report_get", "NetFlow: нагрузка, приложения и разговоры выбранного сервера", "traffic", "mm:traffic:read", "read", "servers", z.object({
|
||||
register("traffic.flow.analytics.read", "mm_netflow_analytics_report_get", "NetFlow: нагрузка, приложения и разговоры выбранного сервера по сохранённым top-N данным", "traffic", "mm:traffic:read", "read", "servers", z.object({
|
||||
serverId: z.number().int().positive().safe(), minutes: z.number().int().min(1).max(1440).default(15),
|
||||
userId: z.string().min(1).max(100).optional(),
|
||||
interface: z.string().trim().min(1).max(200).refine(value => !/[\u0000-\u001f\u007f]/.test(value) && value !== "__all__").optional(),
|
||||
...flowTupleSchema.shape,
|
||||
dedup: z.boolean().default(true), excludeMesh: z.boolean().default(true), excludeOverlay: z.boolean().default(true),
|
||||
offset: z.number().int().min(0).max(100000).default(0), limit: z.number().int().min(1).max(100).default(50),
|
||||
}).strict(), {
|
||||
@@ -57,11 +67,15 @@ export function registerFlowAnalyticsActions(register: typeof add) {
|
||||
const authorize = () => assertTrafficHistorySource(context, server)
|
||||
const startedAt = new Date().toISOString()
|
||||
try {
|
||||
const filters = flowTupleSchema.parse(input)
|
||||
const tuple = Object.values(filters).some(value => value !== undefined) ? filters : undefined
|
||||
const requestedMinutes = Number(input.minutes)
|
||||
const limits = await readFlowSourceLimits()
|
||||
await authorize()
|
||||
const { sourceWindow, ...raw } = await readFlowWindow(Number(input.minutes), minutes => buildFlowAnalytics({ serverId: server.id, minutes, userId: input.userId as string | undefined,
|
||||
iface: input.interface as string | undefined, dedup: input.dedup === true, excludeMesh: input.excludeMesh === true, excludeOverlay: input.excludeOverlay === true },
|
||||
{ serverIds: context.connection.policy.scope.serverIds, maxRows: 20000, authorize }), context.signal)
|
||||
const { sourceWindow: reducedWindow, ...raw } = await readFlowWindow(requestedMinutes, minutes => buildFlowAnalytics({ serverId: server.id, minutes, userId: input.userId as string | undefined,
|
||||
iface: input.interface as string | undefined, tuple, dedup: input.dedup === true, excludeMesh: input.excludeMesh === true, excludeOverlay: input.excludeOverlay === true },
|
||||
{ serverIds: context.connection.policy.scope.serverIds, maxRows: REPORT_ROW_LIMIT, authorize }), context.signal)
|
||||
const sourceWindow = { requestedMinutes, effectiveMinutes: reducedWindow?.effectiveMinutes ?? requestedMinutes, incomplete: reducedWindow !== undefined }
|
||||
const result = flowAnalyticsDtoSchema.parse(raw)
|
||||
const offset = Number(input.offset), limit = Number(input.limit), pages: Record<string, { total: number; nextOffset: number | null }> = {}
|
||||
const analytics: Record<string, unknown> = { ...result }
|
||||
@@ -74,14 +88,16 @@ export function registerFlowAnalyticsActions(register: typeof add) {
|
||||
await authorize()
|
||||
if ((await readFlowSourceLimits()).topN !== limits.topN) throw new McpError("STATE_CONFLICT", "Предел источника NetFlow изменился во время чтения", 409)
|
||||
await authorize()
|
||||
const output = { serverId: server.id, minutes: sourceWindow?.effectiveMinutes ?? Number(input.minutes), sourceWindow, interface: input.interface ?? null, userId: input.userId ?? null,
|
||||
const output = { serverId: server.id, minutes: sourceWindow.effectiveMinutes, sourceWindow, interface: input.interface ?? null, userId: input.userId ?? null, filters,
|
||||
analytics: retained, pages, contextRates: { bpsNowEstimate: _bpsNow, bpsWireEstimate: _bpsWire, bpsOverlayEstimate: _bpsOverlay, bytesWireEstimate: _bytesWire,
|
||||
listenerBound: _live, userAttributionVerified: false, semantics: "REST estimates: filtered or overlay-inclusive rates use the latest complete retained minute with a window-average fallback; wire uses current interface snapshots" },
|
||||
listenerBound: _live, userAttributionVerified: false, semantics: "REST estimates: filtered or overlay-inclusive rates use the latest complete retained minute with a window-average fallback; wire uses unfiltered current interface snapshots" },
|
||||
readStartedAt: startedAt, observedAt: new Date().toISOString(), live: false,
|
||||
source: "retained flow_buckets plus pending; same REST analytics engine with scoped topology",
|
||||
rowLimit: 20000, topRowsPerBucketLimit: Math.max(20, limits.topN), engineTopListLimit: Math.min(50, Math.max(10, limits.topN)),
|
||||
rowLimit: REPORT_ROW_LIMIT, topRowsPerBucketLimit: Math.max(20, limits.topN), engineTopListLimit: Math.min(50, Math.max(10, limits.topN)),
|
||||
historicalDetail: { filtersAppliedTo: "retained rows before aggregation and pagination", rowLimitAppliedBeforeFilters: true,
|
||||
discardedRowsRecoverable: false, exactTupleTotalsVerified: false },
|
||||
incomplete: true, coverageVerified: false, rowSumIsNetworkTotal: false, forwardingVerified: false,
|
||||
inferredPathsVerified: false, historicalOwnershipVerified: false, attribution: "current named whole-interface bindings; users with hidden bindings excluded",
|
||||
inferredPathsVerified: false, historicalOwnershipVerified: false, attribution: "current exclusive interface bindings, including confirmed single-peer WireGuard; users with hidden bindings excluded",
|
||||
backgroundEnrichmentStarted: false, collectorStarted: false }
|
||||
if (Buffer.byteLength(JSON.stringify(output)) > 1048576) throw new McpError("STATE_UNAVAILABLE", "Ответ аналитики превышает 1 МиБ; уменьшите страницу", 409)
|
||||
return withCurrentFlowReadQuality(output,context)
|
||||
|
||||
@@ -72,7 +72,7 @@ export function registerFlowCatalogActions(register: typeof add) {
|
||||
for (const server of selected) await assertTrafficHistorySource(context, server)
|
||||
return withCurrentFlowReadQuality({ ...page, clients, total: data.total, nextOffset: offset + clients.length < data.total ? offset + clients.length : null,
|
||||
incomplete: !!data.sourceWindow || page.incomplete || clients.length < data.total || clients.some(row => !row.completeSourceSet || !row.completeAttribution),
|
||||
source: "retained ingress rows and current named whole-interface bindings", topRowsPerBucketLimit: data.window.topRowsPerBucketLimit,
|
||||
source: "retained ingress rows and current exclusive interface bindings, including confirmed single-peer WireGuard", topRowsPerBucketLimit: data.window.topRowsPerBucketLimit,
|
||||
from: data.window.since, to: data.window.until, sourceWindow: data.sourceWindow, ...sourceSemantics },context)
|
||||
},
|
||||
})
|
||||
|
||||
@@ -59,7 +59,7 @@ export function registerFlowLiveActions(register: typeof add) {
|
||||
historicalOwnershipVerified: false, currentTrafficVerified: false,
|
||||
rateSemantics: "REST live rates: filtered or overlay-inclusive rates use the latest complete retained minute with a window-average fallback",
|
||||
liveMeaning: "events[].data.live means listener bound; it does not prove exporter freshness or forwarding",
|
||||
attribution: "current named whole-interface bindings; users with hidden bindings excluded",
|
||||
attribution: "current exclusive interface bindings, including confirmed single-peer WireGuard; users with hidden bindings excluded",
|
||||
collectorStarted: false, backgroundEnrichmentStarted: false }
|
||||
if (Buffer.byteLength(JSON.stringify(output)) > 1048576) throw new McpError("STATE_UNAVAILABLE", "Ответ live превышает 1 МиБ; уменьшите страницу или число samples", 409)
|
||||
await authorize()
|
||||
|
||||
@@ -49,11 +49,11 @@ export function registerFlowMapActions(register: typeof add) {
|
||||
await authorize()
|
||||
const output = { serverId: server.id, userId: input.userId ?? null, interface: input.interface ?? null, map: projected, pages, sourceWindow,
|
||||
readStartedAt: startedAt, observedAt: new Date().toISOString(), live: false, listenerBound,
|
||||
source: "retained flow_buckets plus pending; same REST map engine with scoped topology",
|
||||
source: "closed minutes for all rates; retained flows for services and user breakdowns; paths use an exit exporter or observed GRE peer/next hop, otherwise identify the observing exporter; interfaceTraffic includes private routed traffic before top-N",
|
||||
topRowsPerBucketLimit: Math.max(20, limits.topN), rowLimit: 20000, incomplete: true, graphComplete: false,
|
||||
referencedNodesMayBeOutsidePage: true, inferredPathsVerified: false, forwardingVerified: false, coverageVerified: false,
|
||||
rowSumIsNetworkTotal: false, historicalOwnershipVerified: false,
|
||||
attribution: "current named whole-interface bindings; users with hidden bindings excluded",
|
||||
attribution: "current exclusive interface bindings, including confirmed single-peer WireGuard; users with hidden bindings excluded",
|
||||
collectorStarted: false, backgroundEnrichmentStarted: false, tracerouteExecuted: false }
|
||||
if (Buffer.byteLength(JSON.stringify(output)) > 1048576) throw new McpError("STATE_UNAVAILABLE", "Ответ карты превышает 1 МиБ; уменьшите страницы", 409)
|
||||
return withCurrentFlowReadQuality(output,context)
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
import assert from "node:assert/strict"
|
||||
import test from "node:test"
|
||||
import { greIpsecPaths } from "../../services/gre-ipsec-transport.js"
|
||||
import { greIke2DefaultProposal, greIke2SideCommands, greIke2StableCatalogues, greIke2StepInput, greIke2StepSchema, planGreIke2Side, validateGreIke2Defaults, verifyGreIke2Create, verifyGreIke2Update } from "./gre-ikev2-pair-actions.js"
|
||||
import { redact } from "./security.js"
|
||||
|
||||
const pair = { endpoints: [
|
||||
{ serverId: 3, greName: "gre-jh-test-home", outerAddress: "192.0.2.3" },
|
||||
{ serverId: 6, greName: "gre-jh-test-nov", outerAddress: "198.51.100.6" },
|
||||
] }
|
||||
const secret = "ab".repeat(32)
|
||||
const empty = () => Object.fromEntries(Object.values(greIpsecPaths).map(path => [path, [] as Record<string, string>[]]))
|
||||
|
||||
test("emits the IX transport suite with a fixed GRE selector and independent identities", () => {
|
||||
const [left, right] = ([0, 1] as const).map(side => greIke2SideCommands(pair, side, secret))
|
||||
assert.equal(left.length, 6)
|
||||
assert.equal(right.length, 6)
|
||||
assert.equal(left.some(command => command.path === greIpsecPaths.proposal), false)
|
||||
assert.deepEqual(left.find(command => command.path === greIpsecPaths.profile), right.find(command => command.path === greIpsecPaths.profile))
|
||||
assert.equal(left.find(command => command.path === greIpsecPaths.peer)?.fields.passive, "true")
|
||||
assert.equal(right.find(command => command.path === greIpsecPaths.peer)?.fields.passive, "false")
|
||||
assert.equal(left.find(command => command.path === greIpsecPaths.identity)?.fields.secret, secret)
|
||||
assert.equal(right.find(command => command.path === greIpsecPaths.identity)?.fields.secret, secret)
|
||||
assert.equal(JSON.stringify(redact({ ipsecSecret: secret, commands: left })).includes(secret), false)
|
||||
const leftPolicy = left.find(command => command.path === greIpsecPaths.policy)!.fields
|
||||
const rightPolicy = right.find(command => command.path === greIpsecPaths.policy)!.fields
|
||||
assert.deepEqual([leftPolicy["src-address"], leftPolicy["dst-address"], leftPolicy.protocol, leftPolicy.level, leftPolicy.tunnel],
|
||||
["192.0.2.3/32", "198.51.100.6/32", "gre", "require", "false"])
|
||||
assert.equal(rightPolicy["src-address"], leftPolicy["dst-address"])
|
||||
assert.equal(leftPolicy.proposal, "default")
|
||||
assert.equal(rightPolicy["dst-address"], leftPolicy["src-address"])
|
||||
assert.deepEqual(left.slice(0, 2).map(command => command.fields["ipsec-policy"]), ["in,none", "out,none"])
|
||||
})
|
||||
|
||||
test("rejects existing objects and opposing IPv4 selectors without touching other peers", () => {
|
||||
const commands = greIke2SideCommands(pair, 0, secret), catalogs = empty()
|
||||
catalogs[greIpsecPaths.policy].push({ ".id": "*A", template: "true", protocol: "all", "src-address": "0.0.0.0/0", "dst-address": "0.0.0.0/0" })
|
||||
catalogs[greIpsecPaths.peer].push({ ".id": "*B", address: "0.0.0.0/0", "exchange-mode": "ike2" })
|
||||
assert.doesNotThrow(() => planGreIke2Side(pair, 0, catalogs, commands))
|
||||
catalogs[greIpsecPaths.policy].push({ ".id": "*C", "src-address": "192.0.2.0/24", "dst-address": "198.51.100.0/24", protocol: "all" })
|
||||
assert.throws(() => planGreIke2Side(pair, 0, catalogs, commands), /перекрывает GRE/)
|
||||
catalogs[greIpsecPaths.policy].pop()
|
||||
catalogs[greIpsecPaths.peer].push({ ".id": "*D", address: "198.51.100.6/32", "exchange-mode": "ike2" })
|
||||
assert.throws(() => planGreIke2Side(pair, 0, catalogs, commands), /Уже настроен IKEv2 peer/)
|
||||
catalogs[greIpsecPaths.peer].pop()
|
||||
catalogs[greIpsecPaths.filter].push({ ".id": "*E", comment: commands[0].fields.comment! })
|
||||
assert.throws(() => planGreIke2Side(pair, 0, catalogs, commands), /изменённый объект/)
|
||||
})
|
||||
|
||||
test("checks the existing defaults for a common encrypted suite and equal PFS", () => {
|
||||
const catalogs = empty()
|
||||
const first = { ".id": "*A", name: "default", "pfs-group": "modp1024", "enc-algorithms": "3des,aes-128-cbc,aes-256-cbc", "auth-algorithms": "sha1,sha256" }
|
||||
catalogs[greIpsecPaths.proposal].push(first)
|
||||
assert.equal(greIke2DefaultProposal(catalogs), first)
|
||||
const second = { ...first, "enc-algorithms": "aes-256-cbc", "auth-algorithms": "sha256" }
|
||||
assert.doesNotThrow(() => validateGreIke2Defaults(first, second))
|
||||
assert.throws(() => validateGreIke2Defaults(first, { ...second, "pfs-group": "modp2048" }), /несовместимы/)
|
||||
assert.throws(() => validateGreIke2Defaults(first, { ...second, "enc-algorithms": "null" }), /несовместимы/)
|
||||
})
|
||||
|
||||
test("resumes a partial side and changes only the verified old test policy's proposal", () => {
|
||||
const commands = greIke2SideCommands(pair, 0, secret), catalogs = empty()
|
||||
const name = commands.find(command => command.path === greIpsecPaths.profile)!.fields.name!
|
||||
for (const [index, command] of commands.entries()) catalogs[command.path].push({ ...command.fields, ".id": `*${index + 1}` })
|
||||
const [policy] = catalogs[greIpsecPaths.policy]
|
||||
policy.proposal = name
|
||||
const [patch] = planGreIke2Side(pair, 0, catalogs, commands)
|
||||
assert.deepEqual(patch, { path: greIpsecPaths.policy, id: policy[".id"], fields: { proposal: "default" } })
|
||||
const after = structuredClone(catalogs)
|
||||
delete after[greIpsecPaths.policy][0].proposal
|
||||
assert.equal(verifyGreIke2Update(catalogs, after, patch), true)
|
||||
assert.deepEqual(planGreIke2Side(pair, 0, after, commands), [])
|
||||
after[greIpsecPaths.policy][0].level = "use"
|
||||
assert.equal(verifyGreIke2Update(catalogs, after, patch), false)
|
||||
})
|
||||
|
||||
test("the runner can parse the prepared plan after its JSON round trip", () => {
|
||||
const planned = greIke2StepInput(pair, 0, secret, "source-proof", [
|
||||
{ path: greIpsecPaths.peer, fields: {} },
|
||||
{ path: greIpsecPaths.policy, id: "*4", fields: { proposal: "default" } },
|
||||
])
|
||||
assert.deepEqual(greIke2StepSchema.parse(JSON.parse(JSON.stringify(planned))), planned)
|
||||
assert.deepEqual(planned.writes, [
|
||||
{ path: greIpsecPaths.peer, action: "create" },
|
||||
{ path: greIpsecPaths.policy, id: "*4", action: "update" },
|
||||
])
|
||||
assert.throws(() => greIke2StepSchema.parse({ ...planned, writes: [{ path: greIpsecPaths.proposal, id: "*4", action: "update" }] }))
|
||||
})
|
||||
|
||||
test("requires the new plaintext drop to precede existing rules and preserve every prior object", () => {
|
||||
const [command] = greIke2SideCommands(pair, 0, secret), before = empty()
|
||||
before[greIpsecPaths.filter] = [{ ".id": "*A", chain: "input", action: "accept", packets: "19" }]
|
||||
const after = structuredClone(before)
|
||||
after[greIpsecPaths.filter][0].packets = "20"
|
||||
after[greIpsecPaths.filter].unshift({ ...command.fields, ".id": "*B", packets: "0" })
|
||||
const verified = () => verifyGreIke2Create(greIke2StableCatalogues(before), greIke2StableCatalogues(after), command, "*B", "*A")
|
||||
assert.equal(verified(), true)
|
||||
after[greIpsecPaths.filter].reverse()
|
||||
assert.equal(verified(), false)
|
||||
after[greIpsecPaths.filter].reverse()
|
||||
after[greIpsecPaths.filter][1].action = "drop"
|
||||
assert.equal(verified(), false)
|
||||
})
|
||||
@@ -0,0 +1,281 @@
|
||||
import { randomBytes } from "node:crypto"
|
||||
import { isIP } from "node:net"
|
||||
import { z } from "zod"
|
||||
import { greMutationProof, greTarget, readGreMutationState } from "../../services/gre-mutation-state.js"
|
||||
import { greIke2TransportFields, greIpsecPaths, greIpsecPlaintextDrops } from "../../services/gre-ipsec-transport.js"
|
||||
import { inIxNetwork } from "../../services/internet-exchange-plan.js"
|
||||
import { ipsecPeerDeleteRows } from "../../services/ipsec-peer-delete.js"
|
||||
import { IpsecServerInitExecutionError } from "../../services/ipsec-server-init.js"
|
||||
import { observedBoolean } from "../../services/ospf-observed-values.js"
|
||||
import { assertVerifiedConfigurationAccess } from "../../services/config-mutation-policy.js"
|
||||
import type { add } from "./actions.js"
|
||||
import type { ChangeEvidence } from "./action-types.js"
|
||||
import { greMutationProtectionObjects } from "./gre-mutation-actions.js"
|
||||
import { routerClient } from "./resources.js"
|
||||
import { fingerprint, McpError, privateFingerprinter } from "./security.js"
|
||||
import { registerMcpService } from "./service-registry.js"
|
||||
|
||||
const operation = "network.gre.ikev2_pair.configure"
|
||||
const endpoint = z.object({
|
||||
serverId: z.number().int().positive().safe(),
|
||||
greName: z.string().trim().min(1).max(100),
|
||||
outerAddress: z.string().refine(value => isIP(value) === 4 && value !== "0.0.0.0", "Требуется фиксированный внешний IPv4"),
|
||||
}).strict()
|
||||
const schema = z.object({ endpoints: z.array(endpoint).length(2) }).strict()
|
||||
const writePath = z.enum([greIpsecPaths.filter, greIpsecPaths.profile, greIpsecPaths.peer, greIpsecPaths.identity, greIpsecPaths.policy])
|
||||
export const greIke2StepSchema = schema.extend({
|
||||
side: z.union([z.literal(0), z.literal(1)]),
|
||||
ipsecSecret: z.string().regex(/^[a-f0-9]{64}$/),
|
||||
beforeFingerprint: z.string(),
|
||||
writes: z.array(z.discriminatedUnion("action", [
|
||||
z.object({ path: writePath, action: z.literal("create") }).strict(),
|
||||
z.object({ path: z.literal(greIpsecPaths.policy), action: z.literal("update"), id: z.string().regex(/^\*[a-z0-9]+$/i) }).strict(),
|
||||
])).max(6),
|
||||
})
|
||||
type Pair = z.infer<typeof schema>
|
||||
type Side = 0 | 1
|
||||
type Fields = Record<string, string>
|
||||
type Catalogue = Record<string, Fields[]>
|
||||
type RouterWrite = { path: string; fields: Fields; id?: string }
|
||||
export function greIke2StepInput(input: Pair, side: Side, ipsecSecret: string, beforeFingerprint: string, commands: RouterWrite[]) {
|
||||
const writes = commands.map(({ path, id }) => id ? { path, id, action: "update" } : { path, action: "create" })
|
||||
return greIke2StepSchema.parse({ endpoints: input.endpoints, side, ipsecSecret, beforeFingerprint, writes })
|
||||
}
|
||||
const sides = [0, 1] as const
|
||||
const paths = Object.values(greIpsecPaths)
|
||||
const runtimeFields: Readonly<Record<string, ReadonlySet<string>>> = {
|
||||
[greIpsecPaths.filter]: new Set(["bytes", "packets"]),
|
||||
[greIpsecPaths.policy]: new Set(["active", "invalid", "ph2-count", "ph2-state"]),
|
||||
}
|
||||
|
||||
function target(input: Pair): ChangeEvidence["target"] {
|
||||
const [first, second] = input.endpoints
|
||||
if (first.serverId === second.serverId || first.outerAddress === second.outerAddress) {
|
||||
throw new McpError("INVALID_INPUT", "Требуются два разных CHR и два разных внешних адреса")
|
||||
}
|
||||
return { scope: "servers", serverIds: [first.serverId, second.serverId] }
|
||||
}
|
||||
|
||||
const nameFor = (input: Pair) => "mm-gre-ike2-" + fingerprint([...input.endpoints].sort((a, b) => a.serverId - b.serverId)).slice(0, 14)
|
||||
export function greIke2SideCommands(input: Pair, side: Side, secret: string) {
|
||||
const name = nameFor(input), local = input.endpoints[side].outerAddress, remote = input.endpoints[side === 0 ? 1 : 0].outerAddress
|
||||
const [inbound, outbound] = greIpsecPlaintextDrops(local, remote)
|
||||
const fields = greIke2TransportFields(name, local, remote, side === 0, secret, false)
|
||||
return [
|
||||
{ path: greIpsecPaths.filter, fields: { ...inbound, comment: `${name}:plain-in` } },
|
||||
{ path: greIpsecPaths.filter, fields: { ...outbound, comment: `${name}:plain-out` } },
|
||||
...(["profile", "peer"] as const).map(kind => ({ path: greIpsecPaths[kind], fields: fields[kind] })),
|
||||
{ path: greIpsecPaths.identity, fields: { ...fields.identity, comment: `${name}:identity` } },
|
||||
{ path: greIpsecPaths.policy, fields: { ...fields.policy, proposal: "default", comment: `${name}:policy` } },
|
||||
] satisfies Array<{ path: string; fields: Fields }>
|
||||
}
|
||||
|
||||
function includesIp(selector: string | undefined, address: string) {
|
||||
if (!selector) return true
|
||||
const [host, length] = selector.split("/")
|
||||
if (isIP(host) === 6) return false
|
||||
if (isIP(host) !== 4 || (length !== undefined && (!/^\d+$/.test(length) || Number(length) > 32))) {
|
||||
throw new McpError("STATE_UNAVAILABLE", "Не подтверждён адресный селектор IPsec", 502)
|
||||
}
|
||||
return inIxNetwork(`${host}/${length ?? "32"}`, address)
|
||||
}
|
||||
|
||||
function ownedRows(catalogs: Catalogue, command: RouterWrite) {
|
||||
return catalogs[command.path].filter(row => command.fields.comment ? row.comment === command.fields.comment : row.name === command.fields.name)
|
||||
}
|
||||
|
||||
export function greIke2DefaultProposal(catalogs: Catalogue) {
|
||||
const rows = catalogs[greIpsecPaths.proposal].filter(row => row.name === "default")
|
||||
const row = rows[0]
|
||||
if (rows.length !== 1 || observedBoolean(row.disabled) === true || !row["pfs-group"] || !row["enc-algorithms"] || row["auth-algorithms"] === undefined) {
|
||||
throw new McpError("STATE_UNAVAILABLE", "Не подтверждены действующие параметры IPsec proposal default", 502)
|
||||
}
|
||||
return row
|
||||
}
|
||||
|
||||
export function validateGreIke2Defaults(first: Fields, second: Fields) {
|
||||
const list = (row: Fields, field: string) => row[field].split(",").map(value => value.trim())
|
||||
const shared = (field: string) => list(first, field).filter(value => list(second, field).includes(value))
|
||||
const encryption = shared("enc-algorithms").filter(value => !!value && value !== "null")
|
||||
const compatible = first["pfs-group"] === second["pfs-group"] && encryption.some(value => value.endsWith("-gcm") || value === "chacha20-poly1305" || shared("auth-algorithms").some(auth => !!auth && auth !== "null"))
|
||||
if (!compatible || (list(first, "enc-algorithms").includes("null") && list(second, "enc-algorithms").includes("null"))) {
|
||||
throw new McpError("DEPENDENCY_CONFLICT", "IPsec proposal default на двух CHR несовместимы или допускают GRE без шифрования", 409)
|
||||
}
|
||||
}
|
||||
|
||||
export function planGreIke2Side(input: Pair, side: Side, catalogs: Catalogue, commands: ReturnType<typeof greIke2SideCommands>): RouterWrite[] {
|
||||
const name = nameFor(input), local = input.endpoints[side].outerAddress, remote = input.endpoints[side === 0 ? 1 : 0].outerAddress
|
||||
if (catalogs[greIpsecPaths.peer].some(row => row.name !== name && row["exchange-mode"] === "ike2" && observedBoolean(row.disabled) !== true &&
|
||||
[remote, `${remote}/32`].includes(row.address) && (!row["local-address"] || ["0.0.0.0", local].includes(row["local-address"])))) {
|
||||
throw new McpError("DEPENDENCY_CONFLICT", "Уже настроен IKEv2 peer для этих внешних адресов", 409)
|
||||
}
|
||||
if (catalogs[greIpsecPaths.policy].some(row => row.comment !== `${name}:policy` && observedBoolean(row.template) !== true && observedBoolean(row.disabled) !== true &&
|
||||
[undefined, "", "all", "0", "255", "gre", "47"].includes(row.protocol) &&
|
||||
((includesIp(row["src-address"], local) && includesIp(row["dst-address"], remote)) ||
|
||||
(includesIp(row["src-address"], remote) && includesIp(row["dst-address"], local))))) {
|
||||
throw new McpError("DEPENDENCY_CONFLICT", "Существующая IPsec policy перекрывает GRE между выбранными адресами", 409)
|
||||
}
|
||||
return commands.flatMap<RouterWrite>(command => {
|
||||
const found = ownedRows(catalogs, command), row = found[0]
|
||||
if (!row) return [command]
|
||||
if (found.length === 1 && observedBoolean(row.dynamic) !== true && observedBoolean(row.builtin) !== true && observedBoolean(row.disabled) !== true) {
|
||||
if (matches(command.fields, row)) {
|
||||
if (command.path === greIpsecPaths.filter && catalogs[command.path].slice(0, catalogs[command.path].indexOf(row)).some(previous =>
|
||||
observedBoolean(previous.dynamic) !== true && observedBoolean(previous.disabled) !== true && previous.chain === row.chain && previous.action !== "drop" &&
|
||||
[undefined, "", "all", "0", "255", "gre", "47"].includes(previous.protocol) && !previous["ipsec-policy"]?.endsWith(",ipsec"))) {
|
||||
throw new McpError("DEPENDENCY_CONFLICT", "Правило против незашифрованного GRE находится после правила, которое может пропустить его", 409)
|
||||
}
|
||||
return []
|
||||
}
|
||||
if (command.path === greIpsecPaths.policy && matches({ ...command.fields, proposal: name }, row)) {
|
||||
return [{ path: command.path, id: row[".id"], fields: { proposal: "default" } }]
|
||||
}
|
||||
}
|
||||
throw new McpError("STATE_CONFLICT", `Пара IKEv2 имеет неоднозначный или изменённый объект в ${command.path}`, 409)
|
||||
})
|
||||
}
|
||||
|
||||
export function greIke2StableCatalogues(catalogs: Catalogue) {
|
||||
return Object.fromEntries(paths.map(path => [path, catalogs[path]
|
||||
.filter(row => observedBoolean(row.dynamic) !== true)
|
||||
.map(row => Object.fromEntries(Object.entries(row).filter(([key]) => !runtimeFields[path]?.has(key))))]))
|
||||
}
|
||||
|
||||
function matches(expected: Fields, observed: Fields) {
|
||||
return Object.entries(expected).every(([key, value]) => {
|
||||
const actual = observed[key]
|
||||
if (["disabled", "tunnel", "passive"].includes(key)) return (observedBoolean(actual) ?? (actual === undefined ? false : null)) === observedBoolean(value)
|
||||
if (["address", "src-address", "dst-address"].includes(key)) return actual?.replace(/\/32$/, "") === value.replace(/\/32$/, "")
|
||||
if (key === "protocol" && value === "gre") return actual === "gre" || actual === "47"
|
||||
if (key === "proposal" && value === "default") return actual === undefined || actual === "default"
|
||||
return actual === value
|
||||
})
|
||||
}
|
||||
|
||||
export function verifyGreIke2Update(before: Catalogue, after: Catalogue, command: RouterWrite) {
|
||||
const source = before[command.path].find(row => row[".id"] === command.id)
|
||||
const observed = after[command.path].find(row => row[".id"] === command.id)
|
||||
if (!source || !observed || !matches(command.fields, observed)) return false
|
||||
const projected = { ...source }
|
||||
for (const key of Object.keys(command.fields)) {
|
||||
if (observed[key] === undefined) delete projected[key]
|
||||
else projected[key] = observed[key]
|
||||
}
|
||||
return fingerprint({ ...before, [command.path]: before[command.path].map(row => row === source ? projected : row) }) === fingerprint(after)
|
||||
}
|
||||
|
||||
function pairSecret(input: Pair, sides: Catalogue[]) {
|
||||
const name = nameFor(input)
|
||||
const identities = sides.flatMap(catalogs => catalogs[greIpsecPaths.identity].filter(row => row.comment === `${name}:identity`))
|
||||
const values = new Set(identities.map(row => row.secret))
|
||||
if (values.size === 0) return randomBytes(32).toString("hex")
|
||||
const [value] = values
|
||||
if (values.size !== 1 || typeof value !== "string" || !/^[a-f0-9]{64}$/.test(value)) throw new McpError("STATE_CONFLICT", "Не подтверждён общий PSK частично настроенной пары", 409)
|
||||
return value
|
||||
}
|
||||
|
||||
function completedPairProof(input: Pair, side: Side, catalogs: Catalogue, commands: ReturnType<typeof greIke2SideCommands>) {
|
||||
if (planGreIke2Side(input, side, catalogs, commands).length !== 0) throw new McpError("VERIFICATION_FAILED", "IKEv2 остался настроен не полностью", 502)
|
||||
return fingerprint({ proposal: greIke2DefaultProposal(catalogs), objects: commands.map(command => ({ path: command.path, id: ownedRows(catalogs, command)[0][".id"] })) })
|
||||
}
|
||||
|
||||
export function verifyGreIke2Create(before: Catalogue, after: Catalogue, command: { path: string; fields: Fields }, nativeId: string | undefined, first: string | undefined) {
|
||||
const created = after[command.path].find(row => row[".id"] === nativeId)
|
||||
return !!created && !before[command.path].some(row => row[".id"] === nativeId) && matches(command.fields, created) &&
|
||||
(first === undefined || after[command.path][0] === created) &&
|
||||
fingerprint({ ...after, [command.path]: after[command.path].filter(row => row !== created) }) === fingerprint(before)
|
||||
}
|
||||
|
||||
async function readSide(input: Pair, side: Side) {
|
||||
const local = input.endpoints[side], remote = input.endpoints[side === 0 ? 1 : 0]
|
||||
const { server, client } = await routerClient(local.serverId)
|
||||
const mutation = { operation: "update" as const, name: local.greName, fields: { ipsecSecret: "" } }
|
||||
const readCatalogues = async () => Object.fromEntries(await Promise.all(paths.map(async path =>
|
||||
[path, ipsecPeerDeleteRows(await client.get<unknown>(path, 10000, undefined, 1048576))] as const)))
|
||||
const [gre, catalogs] = await Promise.all([readGreMutationState(server, mutation), readCatalogues()])
|
||||
const row = greTarget(mutation, gre)
|
||||
if (!row || observedBoolean(row.dynamic) === true || observedBoolean(row.disabled) !== true || observedBoolean(row["allow-fast-path"]) !== false ||
|
||||
row["local-address"] !== local.outerAddress || row["remote-address"] !== remote.outerAddress || row["ipsec-secret"] !== "") {
|
||||
throw new McpError("STATE_CONFLICT", `На сервере ${local.serverId} требуется статический отключённый GRE с указанными адресами, без FastPath и встроенного PSK`, 409)
|
||||
}
|
||||
const seal = await privateFingerprinter("mcp-gre-ikev2-pair-v1")
|
||||
const proof = seal(fingerprint({ gre: greMutationProof(gre), catalogs: greIke2StableCatalogues(catalogs) }))
|
||||
return { server, client, gre, catalogs, readCatalogues, proof }
|
||||
}
|
||||
|
||||
export function registerGreIke2PairActions(register: typeof add) {
|
||||
registerMcpService(operation, {
|
||||
current: async raw => {
|
||||
const input = greIke2StepSchema.parse(raw)
|
||||
return await Promise.all(sides.map(async side => (await readSide(input, side)).proof))
|
||||
},
|
||||
execute: async raw => {
|
||||
const input = greIke2StepSchema.parse(raw), side = input.side, state = await readSide(input, side)
|
||||
if (state.proof !== input.beforeFingerprint) throw new McpError("STATE_CONFLICT", "GRE или IPsec изменился после подготовки", 409)
|
||||
const desired = greIke2SideCommands(input, side, input.ipsecSecret)
|
||||
const commands = planGreIke2Side(input, side, state.catalogs, desired)
|
||||
const reviewed = greIke2StepInput(input, side, input.ipsecSecret, state.proof, commands).writes
|
||||
if (fingerprint(reviewed) !== fingerprint(input.writes)) throw new McpError("STATE_CONFLICT", "Подготовленные команды IKEv2 отличаются от плана", 409)
|
||||
let before = greIke2StableCatalogues(state.catalogs), confirmed = 0, verified = 0
|
||||
for (const command of commands) {
|
||||
let dispatched = false
|
||||
try {
|
||||
const first = command.path === greIpsecPaths.filter ? before[command.path][0]?.[".id"] : undefined
|
||||
const fence = async () => {
|
||||
await assertVerifiedConfigurationAccess()
|
||||
if (fingerprint((await routerClient(Number(state.server.id))).server) !== fingerprint(state.server)) throw new McpError("STATE_CONFLICT", "Источник RouterOS изменился перед записью", 409)
|
||||
if (fingerprint(greIke2StableCatalogues(await state.readCatalogues())) !== fingerprint(before)) throw new McpError("STATE_CONFLICT", "IPsec изменился перед записью", 409)
|
||||
dispatched = true
|
||||
}
|
||||
const ack = command.id
|
||||
? await state.client.patch<Fields>(`${command.path}/${encodeURIComponent(command.id)}`, command.fields, 10000, fence)
|
||||
: await state.client.put<Fields>(command.path, { ...command.fields, ...(first ? { "place-before": first } : {}) }, 10000, fence)
|
||||
confirmed++
|
||||
const after = greIke2StableCatalogues(await state.readCatalogues())
|
||||
const exact = command.id ? verifyGreIke2Update(before, after, command) : verifyGreIke2Create(before, after, command, ack?.[".id"], first)
|
||||
if (!exact) {
|
||||
throw new McpError("VERIFICATION_FAILED", "Ответ RouterOS не подтверждает точное добавление объекта", 502)
|
||||
}
|
||||
before = after
|
||||
verified++
|
||||
} catch (error) {
|
||||
if (!dispatched && !confirmed && error instanceof McpError) throw error
|
||||
throw new IpsecServerInitExecutionError(error instanceof McpError && error.code === "VERIFICATION_FAILED" || !dispatched ? "VERIFICATION_FAILED" : "MUTATION_OUTCOME_UNKNOWN",
|
||||
`Настройка IKEv2 остановлена на ${command.path}. GRE оставлен отключённым, требуется сверка перед повтором.`, confirmed, verified, commands.length)
|
||||
}
|
||||
}
|
||||
const after = await readSide(input, side)
|
||||
const afterFingerprint = completedPairProof(input, side, after.catalogs, desired)
|
||||
return { verified: true, commandCount: commands.length, afterFingerprint, greEnabled: false, forwardingVerified: false }
|
||||
},
|
||||
verify: async (raw, result) => {
|
||||
const input = greIke2StepSchema.parse(raw)
|
||||
const receipt = result as { verified?: boolean; afterFingerprint?: string } | null
|
||||
return receipt?.verified === true && receipt.afterFingerprint === completedPairProof(input, input.side,
|
||||
(await readSide(input, input.side)).catalogs, greIke2SideCommands(input, input.side, input.ipsecSecret))
|
||||
},
|
||||
})
|
||||
register(operation, "mm_gre_ikev2_pair_configure_plan", "План настройки отдельного IKEv2 для двух существующих GRE", "network", "mm:network:write", "write", "servers", schema, {
|
||||
version: 3,
|
||||
target: raw => target(schema.parse(raw)),
|
||||
prepare: async raw => {
|
||||
const input = schema.parse(raw), scope = target(input)
|
||||
const before = await Promise.all(sides.map(side => readSide(input, side)))
|
||||
const catalogs = before.map(state => state.catalogs)
|
||||
validateGreIke2Defaults(greIke2DefaultProposal(catalogs[0]), greIke2DefaultProposal(catalogs[1]))
|
||||
const ipsecSecret = pairSecret(input, catalogs)
|
||||
const changes = sides.map(side => planGreIke2Side(input, side, catalogs[side], greIke2SideCommands(input, side, ipsecSecret)))
|
||||
const steps = sides.map(side => ({ kind: "service" as const, service: operation,
|
||||
input: greIke2StepInput(input, side, ipsecSecret, before[side].proof, changes[side]),
|
||||
}))
|
||||
const objects = (await Promise.all(before.map(state => greMutationProtectionObjects(Number(state.server.id), state.gre)))).flat()
|
||||
return { target: scope, objects, snapshots: [], before: before.map(state => state.proof), steps, mutationCost: Math.max(1, changes.flat().length), requiresHuman: true,
|
||||
warnings: [
|
||||
`На каждом CHR настраиваются выделенные объекты ${nameFor(input)}: profile, peer, identity, транспортная policy GRE с proposal default и два правила против GRE без IPsec. Первая сторона — responder, вторая — инициатор.`,
|
||||
"GRE остаются отключёнными. Proposal default используется после проверки совместимости и не изменяется. Для IKE/ESP требуются разрешения действующего firewall.",
|
||||
"Ранее созданные объекты пары переиспользуются только при совпадении параметров. У старой политики пары разрешена смена proposal на default. IPsec SA проверяется после отдельного включения GRE.",
|
||||
],
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import assert from "node:assert/strict"
|
||||
import test, { mock } from "node:test"
|
||||
import type { add } from "./actions.js"
|
||||
import type { McpAction } from "./action-types.js"
|
||||
import type { GreMutation } from "../../services/gre-mutation-input.js"
|
||||
|
||||
const routerStates = new Map([
|
||||
[3, { ipv4: [{ address: "192.0.2.3/24" }], gre: new Array<Record<string, string>>() }],
|
||||
[6, { ipv4: [{ address: "198.51.100.6/24" }], gre: new Array<Record<string, string>>() }],
|
||||
])
|
||||
const writes: Array<{ id: number; mutation: GreMutation }> = []
|
||||
mock.module("./resources.js", { namedExports: { async routerClient(id: number) { return { server: { id } } } } })
|
||||
mock.module("./gre-mutation-actions.js", { namedExports: { async greMutationProtectionObjects(serverId: number) {
|
||||
return [{ kind: "server", id: String(serverId), serverId }]
|
||||
} } })
|
||||
mock.module("../../services/gre-mutation-state.js", { namedExports: {
|
||||
greMutationProof: (state: unknown) => state,
|
||||
async readGreMutationState(server: { id: number }) { return structuredClone(routerStates.get(server.id)) },
|
||||
} })
|
||||
const { fingerprint, redact } = await import("./security.js")
|
||||
mock.module("../../services/gre-mutation.js", { namedExports: {
|
||||
planGreMutation: () => [{}],
|
||||
async mutateGreTunnel(server: { id: number }, mutation: GreMutation, beforeFingerprint: string) {
|
||||
const state = routerStates.get(server.id)!
|
||||
assert.equal(beforeFingerprint, fingerprint(state))
|
||||
assert.equal(mutation.operation, "create")
|
||||
if (mutation.operation !== "create") throw new Error("expected create")
|
||||
writes.push({ id: server.id, mutation })
|
||||
state.gre.push({ name: mutation.fields.name, "remote-address": mutation.fields.remoteAddress })
|
||||
return { verified: true, afterFingerprint: fingerprint(state), tunnel: { ipsecSecret: mutation.fields.ipsecSecret } }
|
||||
},
|
||||
} })
|
||||
const { registerGreIpsecPairActions } = await import("./gre-ipsec-pair-actions.js")
|
||||
const { findMcpService } = await import("./service-registry.js")
|
||||
let action: Pick<McpAction, "prepare" | "target"> | undefined
|
||||
let definition: { id: string; toolName: string } | undefined
|
||||
const register: typeof add = (id, toolName, _title, _section, _permission, _effect, _scope, _schema, handlers) => {
|
||||
definition = { id, toolName }
|
||||
if (handlers.target) action = { prepare: handlers.prepare, target: handlers.target }
|
||||
}
|
||||
registerGreIpsecPairActions(register)
|
||||
|
||||
const input = { endpoints: [
|
||||
{ serverId: 3, endpoint: "192.0.2.3", name: "gre-test-home", localInnerIp: "10.253.0.1/30" },
|
||||
{ serverId: 6, endpoint: "198.51.100.6", name: "gre-test-nov", localInnerIp: "10.253.0.2/30" },
|
||||
] }
|
||||
const context = {} as Parameters<NonNullable<McpAction["prepare"]>>[1]
|
||||
|
||||
test("GRE/IPsec pair creates two disabled endpoints using one private key", async () => {
|
||||
assert.equal(definition?.toolName, "mm_gre_ipsec_pair_create_plan")
|
||||
const prepare = action!.prepare!, service = findMcpService(definition!.id)!
|
||||
const evidence = await prepare(input, context), another = await prepare(input, context)
|
||||
assert.deepEqual(await action!.target(input, context), { scope: "servers", serverIds: [3, 6] })
|
||||
assert.deepEqual(evidence.objects.map(object => object.serverId), [3, 6])
|
||||
assert.equal(writes.length, 0)
|
||||
const [first, second] = evidence.steps.map(step => { assert.equal(step.kind, "service"); return step.kind === "service" ? step.input : {} })
|
||||
const [other] = another.steps
|
||||
assert.ok(other.kind === "service" && first.ipsecSecret !== other.input.ipsecSecret)
|
||||
assert.match(String(first.ipsecSecret), /^[a-f0-9]{64}$/)
|
||||
assert.equal(first.ipsecSecret, second.ipsecSecret)
|
||||
assert.ok(!JSON.stringify(redact(evidence)).includes(String(first.ipsecSecret)))
|
||||
await assert.rejects(prepare({ ...input, ipsecSecret: "caller-supplied" }, context))
|
||||
await assert.rejects(prepare({ endpoints: input.endpoints.slice(0, 1) }, context))
|
||||
await assert.rejects(prepare({ endpoints: [input.endpoints[0], input.endpoints[0]] }, context), /два разных сервера/)
|
||||
await assert.rejects(prepare({ endpoints: [input.endpoints[0], { ...input.endpoints[1], endpoint: "203.0.113.6" }] }, context), /Внешний адрес GRE не найден/)
|
||||
assert.deepEqual(await service.current(first), evidence.before)
|
||||
for (const step of [first, second]) {
|
||||
const receipt = await service.execute(step)
|
||||
assert.ok(await service.verify!(step, receipt))
|
||||
assert.ok(!JSON.stringify(receipt).includes(String(first.ipsecSecret)))
|
||||
}
|
||||
assert.deepEqual(writes.map(({ id, mutation }) => mutation.operation === "create" ?
|
||||
[id, mutation.fields.localAddress, mutation.fields.remoteAddress, mutation.fields.enabled, mutation.fields.allowFastPath] : []), [
|
||||
[3, "192.0.2.3", "198.51.100.6", false, false],
|
||||
[6, "198.51.100.6", "192.0.2.3", false, false],
|
||||
])
|
||||
await assert.rejects(prepare(input, context), /уже есть GRE/)
|
||||
})
|
||||
@@ -0,0 +1,106 @@
|
||||
import { randomBytes } from "node:crypto"
|
||||
import { z } from "zod"
|
||||
import { greCreateFieldsSchema, type GreMutation } from "../../services/gre-mutation-input.js"
|
||||
import { greMutationProof, readGreMutationState } from "../../services/gre-mutation-state.js"
|
||||
import { mutateGreTunnel, planGreMutation } from "../../services/gre-mutation.js"
|
||||
import { observedBoolean } from "../../services/ospf-observed-values.js"
|
||||
import type { ChangeEvidence } from "./action-types.js"
|
||||
import type { add } from "./actions.js"
|
||||
import { greMutationProtectionObjects } from "./gre-mutation-actions.js"
|
||||
import { routerClient } from "./resources.js"
|
||||
import { fingerprint, McpError } from "./security.js"
|
||||
import { registerMcpService } from "./service-registry.js"
|
||||
|
||||
const operation = "network.gre.ipsec_pair.create"
|
||||
const endpointSchema = greCreateFieldsSchema.pick({ name: true, localInnerIp: true, comment: true }).extend({
|
||||
serverId: z.number().int().positive().safe(), endpoint: greCreateFieldsSchema.shape.remoteAddress,
|
||||
})
|
||||
const schema = z.object({
|
||||
endpoints: z.array(endpointSchema).length(2),
|
||||
mtu: greCreateFieldsSchema.shape.mtu,
|
||||
}).strict()
|
||||
const stepSchema = schema.extend({
|
||||
side: z.union([z.literal(0), z.literal(1)]),
|
||||
ipsecSecret: z.string().regex(/^[a-f0-9]{64}$/),
|
||||
beforeFingerprint: z.string(),
|
||||
})
|
||||
type Pair = z.infer<typeof schema>
|
||||
type Side = 0 | 1
|
||||
const sides = [0, 1] as const
|
||||
|
||||
function target(input: Pair): ChangeEvidence["target"] {
|
||||
const [first, second] = input.endpoints
|
||||
if (first.serverId === second.serverId || first.endpoint === second.endpoint) {
|
||||
throw new McpError("INVALID_INPUT", "Нужны два разных сервера и два разных внешних IPv4")
|
||||
}
|
||||
return { scope: "servers", serverIds: [first.serverId, second.serverId] }
|
||||
}
|
||||
|
||||
function mutationFor(input: Pair, side: Side, ipsecSecret: string): GreMutation {
|
||||
const local = input.endpoints[side], remote = input.endpoints[side === 0 ? 1 : 0]
|
||||
return { operation: "create", fields: {
|
||||
name: local.name, localAddress: local.endpoint, remoteAddress: remote.endpoint,
|
||||
localInnerIp: local.localInnerIp, comment: local.comment, mtu: input.mtu ?? "auto",
|
||||
enabled: false, allowFastPath: false, ipsecSecret,
|
||||
} }
|
||||
}
|
||||
|
||||
async function readSide(input: Pair, side: Side, ipsecSecret: string) {
|
||||
const { server } = await routerClient(input.endpoints[side].serverId)
|
||||
const mutation = mutationFor(input, side, ipsecSecret)
|
||||
const state = await readGreMutationState(server, mutation)
|
||||
return { server, mutation, state, proof: fingerprint(greMutationProof(state)) }
|
||||
}
|
||||
|
||||
export function registerGreIpsecPairActions(register: typeof add) {
|
||||
registerMcpService(operation, {
|
||||
current: async raw => {
|
||||
const input = stepSchema.parse(raw)
|
||||
const before = await Promise.all(sides.map(side => readSide(input, side, input.ipsecSecret)))
|
||||
return before.map(item => item.proof)
|
||||
},
|
||||
execute: async raw => {
|
||||
const input = stepSchema.parse(raw)
|
||||
const { server } = await routerClient(input.endpoints[input.side].serverId)
|
||||
const { tunnel: _tunnel, ...receipt } = await mutateGreTunnel(server, mutationFor(input, input.side, input.ipsecSecret), input.beforeFingerprint)
|
||||
return receipt
|
||||
},
|
||||
verify: async (raw, result) => {
|
||||
const input = stepSchema.parse(raw)
|
||||
const receipt = result as { verified?: boolean; afterFingerprint?: string } | null
|
||||
return receipt?.verified === true && receipt.afterFingerprint === (await readSide(input, input.side, input.ipsecSecret)).proof
|
||||
},
|
||||
})
|
||||
register(operation, "mm_gre_ipsec_pair_create_plan", "План создания пары GRE/IPsec с автоматическим PSK",
|
||||
"network", "mm:network:write", "write", "servers", schema, {
|
||||
target: raw => target(schema.parse(raw)),
|
||||
prepare: async raw => {
|
||||
const input = schema.parse(raw), scope = target(input)
|
||||
const ipsecSecret = randomBytes(32).toString("hex")
|
||||
const before = await Promise.all(sides.map(side => readSide(input, side, ipsecSecret)))
|
||||
const mutationCost = sides.reduce<number>((cost, side) => {
|
||||
const item = before[side]!, local = input.endpoints[side], remote = input.endpoints[side === 0 ? 1 : 0]
|
||||
if (!item.state.ipv4.some(row => row.address.split("/")[0] === local.endpoint &&
|
||||
observedBoolean(row.disabled) !== true && observedBoolean(row.invalid) !== true)) {
|
||||
throw new McpError("STATE_CONFLICT", `Внешний адрес GRE не найден на сервере ${local.serverId}`, 409)
|
||||
}
|
||||
if (item.state.gre.some(row => [row["remote-address"], row["current-remote-address"]].includes(remote.endpoint))) {
|
||||
throw new McpError("STATE_CONFLICT", `На сервере ${local.serverId} уже есть GRE с этим удалённым адресом`, 409)
|
||||
}
|
||||
return cost + planGreMutation(item.server, item.mutation, item.state).length + 1
|
||||
}, 0)
|
||||
return {
|
||||
target: scope, objects: (await Promise.all(before.map(item => greMutationProtectionObjects(Number(item.server.id), item.state)))).flat(),
|
||||
snapshots: [], before: before.map(item => item.proof), mutationCost, requiresHuman: true,
|
||||
steps: sides.map(side => ({ kind: "service" as const, service: operation, input: {
|
||||
...input, side, ipsecSecret, beforeFingerprint: before[side]!.proof,
|
||||
} })),
|
||||
warnings: [
|
||||
"Создаются только два новых отключённых GRE. Стороны получают один автоматически сгенерированный PSK; FastPath отключён.",
|
||||
"Стороны применяются и проверяются последовательно. При отказе второй стороны первая может остаться созданной и отключённой.",
|
||||
"Установка IPsec SA и передача трафика проверяются после отдельного включения обоих интерфейсов.",
|
||||
],
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -36,11 +36,15 @@ export function registerGreMutationActions(register: typeof add) {
|
||||
return receipt?.verified===true && fingerprint(await current(input))===receipt.afterFingerprint
|
||||
}})
|
||||
register(service,"mm_gre_tunnel_"+operation+"_plan","План "+["создания","изменения","удаления"][index]+" GRE и его внутренних адресов", "network","mm:network:write","write","servers",schemas[index],{
|
||||
version: operation === "delete" ? 1 : 2,
|
||||
prepare:async(input,context)=>{
|
||||
const serverId = Number(input.serverId), {server} = await routerClient(serverId)
|
||||
let mutation = greMutationSchema.parse({operation,...(operation==="create"?{fields:input.fields}:{...("rosId" in input?{rosId:input.rosId}:{}),...("name" in input?{name:input.name}:{}),...(operation==="update"?{fields:input.fields}:{})})})
|
||||
const state = await readGreMutationState(server,mutation), target = greTarget(mutation,state)
|
||||
if (input.ipsecSecretRef && input.clearIpsecSecret) throw new McpError("INVALID_INPUT","Выберите новый PSK или явное удаление",400)
|
||||
let mutation = greMutationSchema.parse({operation,...(operation==="create"?{fields:input.fields}:{...("rosId" in input?{rosId:input.rosId}:{}),...("name" in input?{name:input.name}:{}),...(operation==="update"?{fields:input.fields}:{})})})
|
||||
if (mutation.operation === "update" && (input.ipsecSecretRef || input.clearIpsecSecret)) {
|
||||
mutation = { ...mutation, fields: { ...mutation.fields, ipsecSecret: "" } }
|
||||
}
|
||||
const state = await readGreMutationState(server,mutation), target = greTarget(mutation,state)
|
||||
if (mutation.operation!=="delete" && (input.ipsecSecretRef || input.clearIpsecSecret)) {
|
||||
const name = mutation.operation==="create"?mutation.fields.name:target?.name
|
||||
let value = ""
|
||||
|
||||
@@ -69,6 +69,7 @@ export function registerGreRevisionActions(register:typeof add){
|
||||
},
|
||||
})
|
||||
register(service,"mm_gre_revision_restore_plan","Восстановить GRE и все статические адреса из ревизии после подтверждения","network","mm:network:write","write","servers",z.object({serverId:z.number().int().positive().safe(),revisionId:z.string().uuid()}).strict(),{
|
||||
version:2,
|
||||
prepare:async(input,context)=>{
|
||||
const req=request(input,context),source=await read(req,context.signal)
|
||||
const desired=materializeGreRestore(source.revision.desired,source.state),steps=planGreRevisionRestore(desired,source.state)
|
||||
|
||||
@@ -34,14 +34,19 @@ const native=createServer(async(req,res)=>{
|
||||
}
|
||||
assert.ok(base,"Only typed GRE/address writes allowed")
|
||||
writes++
|
||||
if(base==="/interface/gre"&&data["ipsec-secret"]===""&&["yes","true"].includes(data["allow-fast-path"])){
|
||||
res.statusCode=400;res.end(JSON.stringify({error:400,detail:"failure: cannot enable fastpath together with ipsec yet"}));return
|
||||
if(base==="/interface/gre"&&data["ipsec-secret"]===""){
|
||||
res.statusCode=400;res.end(JSON.stringify({error:400,detail:"unexpected empty IPsec secret assignment"}));return
|
||||
}
|
||||
const fields=Object.fromEntries(Object.entries(data).map(([k,v])=>[k,v==="yes"?"true":v==="no"?"false":String(v)]))
|
||||
if(!ignored){
|
||||
if(req.method==="PUT"){
|
||||
const row=base==="/interface/gre"?{".id":"*G"+(++nextId),"local-address":"0.0.0.0",mtu:"1476",keepalive:"10s,10",dscp:"inherit",disabled:"false",dynamic:"false",running:"false","clamp-tcp-mss":"true","allow-fast-path":"true","ipsec-secret":"",comment:"",...fields}:{".id":"*A"+(++nextId),disabled:"false",dynamic:"false",invalid:"false",advertise:"false","no-dad":"false","eui-64":"false","from-pool":"",comment:"",...fields}
|
||||
;(collections[base]??=[]).push(row)
|
||||
}else if(req.method==="POST"&&path==="/interface/gre/unset"){
|
||||
assert.equal(data["value-name"],"ipsec-secret")
|
||||
const row=collections[base].find(r=>r[".id"]===data[".id"])
|
||||
assert.ok(row)
|
||||
row["ipsec-secret"]=""
|
||||
}else if(req.method==="PATCH")Object.assign(collections[base].find(r=>r[".id"]===path.slice(base.length+1))!,fields)
|
||||
else if(req.method==="DELETE")collections[base]=collections[base].filter(r=>r[".id"]!==path.slice(base.length+1))
|
||||
else assert.fail("Unsupported native write")
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { mkdtemp, rm } from "node:fs/promises"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
import { after, mock, test } from "node:test"
|
||||
import { mcpConnectionPolicySchema, mcpOperationDescriptorSchema } from "@mmapp/contracts/mcp"
|
||||
import type { ActionContext } from "./action-types.js"
|
||||
import type { add } from "./actions.js"
|
||||
import { registerMcpOperation } from "./registry.js"
|
||||
|
||||
const queries: Array<{ sql: string; values: unknown[] }> = []
|
||||
const from = "2026-11-27T00:00:00Z"
|
||||
const to = "2026-11-27T01:00:00Z"
|
||||
const observed = new Date("2026-11-27T00:15:00Z")
|
||||
const newer = new Date("2026-11-27T00:30:00Z")
|
||||
const observedPrecise = "2026-11-27T00:15:00.000000Z", newerPrecise = "2026-11-27T00:30:00.000002Z"
|
||||
const fixtures = await mkdtemp(join(tmpdir(), "mcp-incident-test-"))
|
||||
process.env.MCP_STATE_DIR = fixtures
|
||||
after(() => rm(fixtures, { recursive: true, force: true }))
|
||||
let paginate = false
|
||||
mock.module("../../db/index.js", { namedExports: { pool: { async query(sql: string, values: unknown[]) {
|
||||
queries.push({ sql, values })
|
||||
if (sql === "SELECT enabled FROM servers WHERE id=$1") return { rows: [{ enabled: true }] }
|
||||
if (sql.startsWith("SELECT id,enabled FROM servers")) {
|
||||
assert.match(sql, /id=ANY\(\$1::bigint\[\]\) AND id>\$2/)
|
||||
assert.deepEqual(values[0], [7, 9])
|
||||
return { rows: values[1] === 0 ? [{ id: 7, enabled: true }, { id: 9, enabled: false }] : [{ id: 9, enabled: false }] }
|
||||
}
|
||||
if (sql.includes("FROM mcp_requests")) {
|
||||
assert.match(sql, /server_ids=ARRAY\[\$1\]::bigint\[\]/)
|
||||
assert.match(sql, /connection_id=\$5 AND actor_id=\$6 AND tool=ANY\(\$7::text\[\]\)/)
|
||||
assert.deepEqual(values, [7, from, to, 51, "fixture-connection", "fixture-owner", ["mm_fixture_server"]])
|
||||
return { rows: [{ at: newerPrecise, key: "request-id", id: "request-id", status: "completed", timestampKind: "request-created", toolName: "mm_fixture_server" }] }
|
||||
}
|
||||
assert.match(sql, /server_id=\$1/)
|
||||
assert.ok(values[0] === 7 || values[0] === 9)
|
||||
if (sql.includes("servers_rest_ping_samples")) {
|
||||
if (values.length === 3) return { rows: [{ enabled: true, intervalSec: 60, observedAt: null, status: null }] }
|
||||
return { rows: [{ at: observedPrecise, key: "", id: "poll", status: "ok", timestampKind: "backend-sample" }] }
|
||||
}
|
||||
if (sql.includes("router_log_entries")) {
|
||||
const make = (at: string, id: string) => ({ at, id, key: id.padStart(20, "0"), status: "warning", timestampKind: "router", receivedAt: newer })
|
||||
if (!paginate) return { rows: [make(newerPrecise, "41")] }
|
||||
const rows = [make(newerPrecise, "100"), make(newerPrecise, "9"), make("2026-11-27T00:30:00.000001Z", "99")]
|
||||
if (values.length === 4) return { rows: rows.slice(0, Number(values[3])) }
|
||||
assert.match(sql, /\(effective_at,\(lpad\(id::text,20,'0'\)\) COLLATE "C"\) < \(\$5::timestamptz,\$6::text COLLATE "C"\)/)
|
||||
assert.equal(values[4], newerPrecise)
|
||||
return { rows: rows.filter(row => row.at < String(values[4]) || row.at === values[4] && row.key < String(values[5])).slice(0, Number(values[3])) }
|
||||
}
|
||||
if (sql.includes("router_log_collection_state")) throw Error("Sample source unavailable")
|
||||
if (sql.includes("uptime_probe_samples")) {
|
||||
assert.match(sql, /p\.src_server_id=\$1/)
|
||||
assert.match(sql, /sampled_at>=p\.updated_at/)
|
||||
assert.doesNotMatch(sql, /\bp\.(target|name|src_interface)\b/)
|
||||
if (values.length === 3) return { rows: [{ enabled: true, intervalSec: 60, observedAt: observed, status: "warn" }] }
|
||||
return { rows: [{ at: observedPrecise, key: "probe-1", id: "probe-1", status: "warn",
|
||||
timestampKind: "backend-sample", rttMs: 50, lossPct: 25 }] }
|
||||
}
|
||||
if (sql.includes("uptime_resource_samples")) return { rows: [] }
|
||||
throw Error("Unexpected source")
|
||||
} } } })
|
||||
|
||||
const { registerIncidentActions, telemetryFreshness } = await import("./incident-actions.js")
|
||||
const { readCapabilities } = await import("./capability-actions.js")
|
||||
const registered = new Map<string, Parameters<typeof add>>()
|
||||
registerIncidentActions((...args) => registered.set(args[1], args))
|
||||
const connection = {
|
||||
policy: mcpConnectionPolicySchema.parse({
|
||||
id: "fixture", version: 1, status: "active", expiresAt: "2027-01-01T00:00:00Z", mode: "observer",
|
||||
permissions: ["mm:servers:read", "mm:traffic:read"],
|
||||
scope: { serverIds: [7], operationIds: ["catalog.global.read", "catalog.server.read", "catalog.server.write"] },
|
||||
}), owner_permissions: ["mm:servers:read", "mm:uptime:read"],
|
||||
} as ActionContext["connection"]
|
||||
const context = { connection } as ActionContext
|
||||
|
||||
test("timeline limits interval and evidence, keeps order and timestamps, checks both source permission grants", async () => {
|
||||
const registration = registered.get("mm_incident_timeline_get")!
|
||||
const schema = registration[7], read = registration[8].read!
|
||||
const input = { serverId: 7, from, to, limit: 1 }
|
||||
assert.equal(schema.safeParse({ ...input, to: from }).success, false)
|
||||
assert.equal(schema.safeParse({ ...input, to: "2026-11-29T00:00:00Z" }).success, false)
|
||||
assert.equal(schema.safeParse({ ...input, to: "2026-11-27T01:00:00" }).success, false)
|
||||
for (const source of ["uptime", "netflow"]) {
|
||||
await assert.rejects(read(schema.parse({ ...input, sources: [source] }), context),
|
||||
{ code: "PERMISSION_DENIED" })
|
||||
}
|
||||
assert.equal(queries.length, 0)
|
||||
const result = await read(schema.parse(input), context)
|
||||
assert.deepEqual(result, {
|
||||
serverId: 7, from: new Date(from).toISOString(), to: new Date(to).toISOString(),
|
||||
observedAt: (result as { observedAt: string }).observedAt,
|
||||
order: "newest-first", sources: ["routeros-poll", "logs"],
|
||||
items: [{ id: "41", status: "warning", timestampKind: "router", source: "logs", at: newerPrecise, receivedAt: newer.toISOString() }],
|
||||
nextCursor: (result as { nextCursor: string }).nextCursor,
|
||||
truncated: true, coverageVerified: false, managerEventsIncluded: false,
|
||||
})
|
||||
assert.deepEqual(queries.map(query => query.values), [[7], [7, from, to, 2], [7, from, to, 2]])
|
||||
})
|
||||
|
||||
test("health separates disabled, absent, stale and unknown freshness from observed status", async () => {
|
||||
const row = { enabled: true, intervalSec: 30, observedAt: observed, status: "error" }
|
||||
assert.equal(telemetryFreshness(row, observed.getTime() + 90_000, true).freshness, "fresh")
|
||||
assert.equal(telemetryFreshness(row, observed.getTime() + 90_001, true).freshness, "stale")
|
||||
assert.equal(telemetryFreshness(row, observed.getTime(), false).freshness, "disabled")
|
||||
assert.equal(telemetryFreshness({ ...row, intervalSec: null }, observed.getTime(), true).freshness, "unknown")
|
||||
const registration = registered.get("mm_telemetry_health_get")!
|
||||
const result = await registration[8].read!(registration[7].parse({ serverId: 7, sources: ["routeros-poll", "logs"] }), context)
|
||||
assert.deepEqual((result as { observations: unknown[] }).observations, [{
|
||||
source: "routeros-poll", freshness: "unobserved", observedAt: null, ageMs: null,
|
||||
lastStatus: null,
|
||||
}, {
|
||||
source: "logs", freshness: "unavailable", observedAt: null, ageMs: null,
|
||||
lastStatus: null,
|
||||
}])
|
||||
})
|
||||
|
||||
test("capabilities keeps legacy shape and assesses filtered candidates under effective policy", () => {
|
||||
for (const [id, toolName, scope, effect, requiredPermissions] of [
|
||||
["catalog.global.read", "mm_fixture_global", "global", "read", []],
|
||||
["catalog.server.read", "mm_fixture_server", "servers", "read", ["mm:servers:read"]],
|
||||
["catalog.server.write", "mm_fixture_server_plan", "servers", "write", ["mm:traffic:read"]],
|
||||
["catalog.hidden.read", "mm_fixture_hidden", "global", "read", []],
|
||||
]) registerMcpOperation(mcpOperationDescriptorSchema.parse({ id, toolName, scope, effect, requiredPermissions, version: 1,
|
||||
title: "Fixture", section: "fixture", risk: "ordinary", implementation: "available",
|
||||
annotations: { readOnlyHint: effect === "read", destructiveHint: effect === "write", idempotentHint: true, openWorldHint: true } }))
|
||||
const baseline = readCapabilities({}, connection, observed)
|
||||
assert.deepEqual(Object.keys(baseline).sort(), ["operations", "schemaVersion"])
|
||||
assert.equal(baseline.operations.length, 3)
|
||||
assert.ok(baseline.operations.every(operation => !("applicability" in operation)))
|
||||
const applicability = (input: Parameters<typeof readCapabilities>[0]) => readCapabilities({ includeApplicability: true, ...input }, connection, observed)
|
||||
.operations.flatMap(operation => "applicability" in operation ? [operation.applicability] : [])
|
||||
assert.equal(applicability({ toolName: "mm_fixture_global" })[0]?.reasons[0]?.code, "GLOBAL_DENIED")
|
||||
assert.equal(applicability({ serverId: 7, effect: "read" })[0]?.decision, "allowed")
|
||||
assert.equal(applicability({ serverId: 8, effect: "read" })[0]?.reasons[0]?.code, "SERVER_DENIED")
|
||||
assert.deepEqual(applicability({ effect: "write" })[0]?.reasons.map(reason => reason.code), ["OWNER_PERMISSION_MISSING", "OBSERVER_WRITE_DENIED"])
|
||||
assert.equal(applicability({ section: "fixture", applicable: true }).length, 1)
|
||||
})
|
||||
|
||||
test("optional manager evidence requires both audit grants and selects current single-server tool metadata", async () => {
|
||||
const registration = registered.get("mm_incident_timeline_get")!
|
||||
const raw = registration[7].parse({ serverId: 7, from, to, sources: ["routeros-poll"], includeManagerEvents: true })
|
||||
const read = registration[8].read!
|
||||
const before = queries.length
|
||||
const audit = {
|
||||
...connection, id: "fixture-connection", owner_id: "fixture-owner",
|
||||
policy: { ...connection.policy, permissions: [...connection.policy.permissions, "mm:mcp:read"] },
|
||||
}
|
||||
await assert.rejects(read(raw, { ...context, connection: audit }), { code: "PERMISSION_DENIED" })
|
||||
assert.equal(queries.length, before)
|
||||
audit.owner_permissions = [...audit.owner_permissions, "mm:mcp:read"]
|
||||
const result = await read(raw, { ...context, connection: audit })
|
||||
assert.deepEqual((result as { sources: string[] }).sources, ["routeros-poll", "mcp-request"])
|
||||
assert.deepEqual((result as { items: unknown[] }).items[0], {
|
||||
id: "request-id", status: "completed", timestampKind: "request-created", toolName: "mm_fixture_server",
|
||||
source: "mcp-request", at: newerPrecise,
|
||||
})
|
||||
})
|
||||
|
||||
test("timeline paginates equal timestamps and microseconds with a bound opaque cursor", async () => {
|
||||
const registration = registered.get("mm_incident_timeline_get")!
|
||||
const base = { serverId: 7, from, to, sources: ["logs"], limit: 1 }
|
||||
const read = async (raw: typeof base & { cursor?: string }) => await registration[8].read!(registration[7].parse(raw), context) as {
|
||||
nextCursor: string | null; items: Array<{ id: string; at: string }>
|
||||
}
|
||||
paginate = true
|
||||
try {
|
||||
const one = await read(base)
|
||||
assert.ok(one.nextCursor)
|
||||
const two = await read({ ...base, cursor: one.nextCursor })
|
||||
assert.ok(two.nextCursor)
|
||||
const three = await read({ ...base, cursor: two.nextCursor })
|
||||
assert.equal(three.nextCursor, null)
|
||||
assert.deepEqual([one, two, three].flatMap(page => page.items.map(({ id, at }) => [id, at])), [
|
||||
["100", newerPrecise], ["9", newerPrecise], ["99", "2026-11-27T00:30:00.000001Z"],
|
||||
])
|
||||
await assert.rejects(read({ ...base, serverId: 9, cursor: one.nextCursor }), { code: "RESET_REQUIRED" })
|
||||
await assert.rejects(read({ ...base, cursor: "bogus" }), { code: "RESET_REQUIRED" })
|
||||
} finally { paginate = false }
|
||||
})
|
||||
|
||||
test("fleet health pages over the effective server allowlist only", async () => {
|
||||
const registration = registered.get("mm_telemetry_health_get")!
|
||||
const scoped = { ...context, connection: { ...connection, policy: { ...connection.policy,
|
||||
scope: { ...connection.policy.scope, serverIds: [7, 9] } } } }
|
||||
const raw = { sources: ["routeros-poll"], limit: 1 }
|
||||
const read = async (input: typeof raw & { afterServerId?: number }) => await registration[8].read!(registration[7].parse(input), scoped) as {
|
||||
nextAfterServerId: number | null; items: Array<{ serverId: number }>
|
||||
}
|
||||
assert.deepEqual(registration[8].target!(raw, scoped), { scope: "servers", serverIds: [7, 9] })
|
||||
const one = await read(raw), two = await read({ ...raw, afterServerId: 7 })
|
||||
assert.deepEqual([one.nextAfterServerId, two.nextAfterServerId], [7, null])
|
||||
assert.deepEqual([one, two].flatMap(page => page.items.map(item => item.serverId)), [7, 9])
|
||||
})
|
||||
|
||||
test("uptime combines scoped resource and retained probe evidence without target details", async () => {
|
||||
const scoped = { ...context, connection: { ...connection, policy: { ...connection.policy,
|
||||
permissions: [...connection.policy.permissions, "mm:uptime:read"] } } }
|
||||
const health = registered.get("mm_telemetry_health_get")!
|
||||
const sources = ["uptime"]
|
||||
const state = await health[8].read!(health[7].parse({ serverId: 7, sources }), scoped) as {
|
||||
observations: Array<{ source: string; lastStatus: string | null }>
|
||||
}
|
||||
assert.deepEqual(state.observations.map(row => [row.source, row.lastStatus]), [["uptime", null], ["uptime-probe", "warn"]])
|
||||
const timeline = registered.get("mm_incident_timeline_get")!
|
||||
const evidence = await timeline[8].read!(timeline[7].parse({ serverId: 7, from, to, sources }), scoped) as { items: unknown[] }
|
||||
assert.deepEqual(evidence.items, [{ at: observedPrecise, id: "probe-1", status: "warn", source: "uptime-probe",
|
||||
timestampKind: "backend-sample", rttMs: 50, lossPct: 25 }])
|
||||
})
|
||||
@@ -0,0 +1,213 @@
|
||||
import { z } from "zod"
|
||||
import { pool } from "../../db/index.js"
|
||||
import { hasPermission } from "../../lib/permissions.js"
|
||||
import { listMcpOperations } from "./registry.js"
|
||||
import { accessGeneration, decryptSecret, encryptSecret, fingerprint, McpError } from "./security.js"
|
||||
import type { ActionContext } from "./action-types.js"
|
||||
import type { add } from "./actions.js"
|
||||
|
||||
const sources = ["routeros-poll", "uptime", "logs", "netflow"] as const
|
||||
type Source = typeof sources[number]
|
||||
const permissions: Record<Source, string> = {
|
||||
"routeros-poll": "mm:servers:read", uptime: "mm:uptime:read", logs: "mm:servers:read", netflow: "mm:traffic:read",
|
||||
}
|
||||
const selection = {
|
||||
serverId: z.number().int().positive().safe(),
|
||||
sources: z.array(z.enum(sources)).min(1).max(sources.length).optional(),
|
||||
}
|
||||
const healthInput = z.object({ ...selection, serverId: selection.serverId.optional(),
|
||||
afterServerId: selection.serverId.optional(), limit: z.number().int().min(1).max(20).default(10),
|
||||
}).strict().refine(input => input.serverId === undefined || input.afterServerId === undefined, "Курсор доступен для списка серверов")
|
||||
const hourMs = 3_600_000
|
||||
const timelineSourceNames = [...sources, "uptime-probe", "mcp-request"] as const
|
||||
type TimelineSource = typeof timelineSourceNames[number]
|
||||
const cursorSchema = z.object({ scope: z.string(), at: z.iso.datetime({ precision: 6 }),
|
||||
source: z.enum(timelineSourceNames), key: z.string().max(1000),
|
||||
}).strict()
|
||||
const timelineInput = z.object({
|
||||
...selection, from: z.iso.datetime({ offset: true }), to: z.iso.datetime({ offset: true }),
|
||||
limit: z.number().int().min(1).max(200).default(50),
|
||||
includeManagerEvents: z.boolean().default(false),
|
||||
cursor: z.string().min(1).max(3000).optional(),
|
||||
}).strict().refine(({ from, to }) => {
|
||||
const duration = Date.parse(to) - Date.parse(from)
|
||||
return duration > 0 && duration <= 24 * hourMs
|
||||
}, "Требуется положительное окно до 24 часов")
|
||||
|
||||
function permittedSources(context: ActionContext, requested?: Source[]) {
|
||||
const permitted = (source: Source) => [context.connection.policy.permissions, context.connection.owner_permissions]
|
||||
.every(granted => hasPermission(granted, permissions[source]))
|
||||
if (requested?.some(source => !permitted(source))) throw new McpError("PERMISSION_DENIED", "Чтение выбранного источника запрещено", 403)
|
||||
return [...new Set(requested ?? sources.filter(permitted))]
|
||||
}
|
||||
|
||||
type HealthRow = { enabled: boolean | null; intervalSec: number | null; observedAt: Date | null; status: string | null; gapAt?: Date | null }
|
||||
type EvidenceRow = { at: string; key: string; id: string; status: string | null; timestampKind: string; receivedAt?: Date; topics?: string[]; message?: string; toolName?: string }
|
||||
const healthSources: Record<Source, string> = {
|
||||
"routeros-poll": `SELECT cfg.enabled,cfg.interval_sec AS "intervalSec",sample.sampled_at AS "observedAt",
|
||||
CASE sample.ok WHEN true THEN 'ok' WHEN false THEN 'error' END AS status
|
||||
FROM servers_api_ping_settings cfg LEFT JOIN LATERAL (
|
||||
SELECT sampled_at,ok FROM servers_rest_ping_samples WHERE server_id=$1 AND sampled_at BETWEEN $2 AND $3
|
||||
ORDER BY sampled_at DESC LIMIT 1
|
||||
) sample ON true WHERE cfg.id=1`,
|
||||
uptime: `SELECT cfg.enabled AND cfg.resources_enabled AS enabled,cfg.interval_sec AS "intervalSec",
|
||||
sample.sampled_at AS "observedAt",sample.status
|
||||
FROM uptime_settings cfg LEFT JOIN LATERAL (
|
||||
SELECT sampled_at,status FROM uptime_resource_samples WHERE server_id=$1 AND sampled_at BETWEEN $2 AND $3
|
||||
ORDER BY sampled_at DESC LIMIT 1
|
||||
) sample ON true WHERE cfg.id=1`,
|
||||
logs: `SELECT cfg.enabled,cfg.interval_sec AS "intervalSec",
|
||||
CASE WHEN sample.last_collected_at BETWEEN $2 AND $3 THEN sample.last_collected_at END AS "observedAt",
|
||||
CASE WHEN sample.gap_at BETWEEN $2 AND $3 THEN sample.gap_at END AS "gapAt",
|
||||
CASE WHEN sample.last_error IS NOT NULL AND sample.last_error <> '' THEN 'error'
|
||||
WHEN sample.last_collected_at BETWEEN $2 AND $3 THEN 'ok' END AS status
|
||||
FROM router_log_settings cfg LEFT JOIN router_log_collection_state sample ON sample.server_id=$1 WHERE cfg.id=1`,
|
||||
netflow: `SELECT NULL::boolean AS enabled,NULL::integer AS "intervalSec",bucket_at AS "observedAt",'retained-bucket' AS status
|
||||
FROM flow_minute_stats WHERE server_id=$1 AND bucket_at BETWEEN $2 AND $3
|
||||
ORDER BY bucket_at DESC LIMIT 1`,
|
||||
}
|
||||
const uptimeProbeHealth = `SELECT cfg.enabled AND cfg.ping_enabled AS enabled,
|
||||
COALESCE(NULLIF(sample.interval_sec,0),cfg.probe_interval_sec) AS "intervalSec",
|
||||
sample.sampled_at AS "observedAt",sample.status
|
||||
FROM uptime_settings cfg LEFT JOIN LATERAL (
|
||||
SELECT p.interval_sec,s.sampled_at,s.status FROM uptime_probes p CROSS JOIN LATERAL (
|
||||
SELECT sampled_at,status FROM uptime_probe_samples WHERE probe_id=p.id AND sampled_at BETWEEN $2 AND $3 AND sampled_at>=p.updated_at
|
||||
ORDER BY sampled_at DESC LIMIT 1
|
||||
) s WHERE p.src_server_id=$1 AND p.enabled ORDER BY s.sampled_at DESC,p.id LIMIT 1
|
||||
) sample ON true WHERE cfg.id=1`
|
||||
const timelineSources: Record<TimelineSource, { time: string; key: string; evidence: string }> = {
|
||||
"routeros-poll": { time: "sampled_at", key: "''::text", evidence: `sampled_at::text AS id,CASE ok WHEN true THEN 'ok' ELSE 'error' END AS status,
|
||||
'backend-sample' AS "timestampKind" FROM servers_rest_ping_samples WHERE server_id=$1` },
|
||||
uptime: { time: "sampled_at", key: "''::text", evidence: `sampled_at::text AS id,status,'backend-sample' AS "timestampKind"
|
||||
FROM uptime_resource_samples WHERE server_id=$1` },
|
||||
"uptime-probe": { time: "s.sampled_at", key: "p.id", evidence: `p.id,status,'backend-sample' AS "timestampKind",
|
||||
s.rtt_ms AS "rttMs",s.loss_pct AS "lossPct" FROM uptime_probes p
|
||||
JOIN uptime_probe_samples s ON s.probe_id=p.id WHERE p.src_server_id=$1 AND s.sampled_at>=p.updated_at` },
|
||||
logs: { time: "effective_at", key: "lpad(id::text,20,'0')", evidence: `id::text,level AS status,
|
||||
CASE WHEN event_at IS NULL THEN 'receipt' ELSE 'router' END AS "timestampKind",
|
||||
received_at AS "receivedAt",topics[1:20] AS topics,left(message,500) AS message FROM router_log_entries WHERE server_id=$1` },
|
||||
netflow: { time: "bucket_at", key: "''::text", evidence: `bucket_at::text AS id,'retained-bucket' AS status,'bucket' AS "timestampKind"
|
||||
FROM flow_minute_stats WHERE server_id=$1` },
|
||||
"mcp-request": { time: "created_at", key: "id::text", evidence: `id::text,CASE WHEN finished_at <= $3 THEN status END AS status,
|
||||
'request-created' AS "timestampKind",tool AS "toolName" FROM mcp_requests WHERE server_ids=ARRAY[$1]::bigint[]
|
||||
AND connection_id=$5 AND actor_id=$6 AND tool=ANY($7::text[])` },
|
||||
}
|
||||
|
||||
function timelineQuery(source: TimelineSource, parameters: unknown[], cursor?: z.infer<typeof cursorSchema>) {
|
||||
const { time, key, evidence } = timelineSources[source]
|
||||
const tie = `(${key}) COLLATE "C"`
|
||||
let clause = ""
|
||||
if (cursor) {
|
||||
const mark = `$${parameters.push(cursor.at)}::timestamptz`
|
||||
if (source === cursor.source) clause = `AND (${time},${tie}) < (${mark},$${parameters.push(cursor.key)}::text COLLATE "C")`
|
||||
else clause = `AND ${time} ${source > cursor.source ? "<=" : "<"} ${mark}`
|
||||
}
|
||||
return `SELECT to_char(${time} AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS at,
|
||||
${key} AS key,${evidence} AND ${time} BETWEEN $2 AND $3 ${clause}
|
||||
ORDER BY ${time} DESC,${tie} DESC LIMIT $4`
|
||||
}
|
||||
|
||||
function managerEventTools(context: ActionContext) {
|
||||
const { policy, owner_permissions } = context.connection
|
||||
const hasBoth = (permission: string) => hasPermission(policy.permissions, permission) && hasPermission(owner_permissions, permission)
|
||||
if (!hasBoth("mm:mcp:read")) throw new McpError("PERMISSION_DENIED", "Чтение аудита MCP запрещено", 403)
|
||||
const allowed = new Set(policy.scope.operationIds)
|
||||
return listMcpOperations().filter(operation => operation.implementation === "available" && operation.scope === "servers" &&
|
||||
allowed.has(operation.id) && operation.requiredPermissions.every(hasBoth)).map(operation => operation.toolName)
|
||||
}
|
||||
|
||||
async function requireServer(serverId: number) {
|
||||
const { rows } = await pool.query<{ enabled: boolean }>("SELECT enabled FROM servers WHERE id=$1", [serverId])
|
||||
if (!rows.length) throw new McpError("NOT_FOUND", "Сервер не найден", 404)
|
||||
return rows[0].enabled
|
||||
}
|
||||
|
||||
export function telemetryFreshness(row: HealthRow | undefined, asOf: number, serverEnabled: boolean) {
|
||||
const ageMs = row?.observedAt ? asOf - row.observedAt.getTime() : null
|
||||
const staleAfterMs = row?.intervalSec ? row.intervalSec * 3000 : null
|
||||
const freshness = !serverEnabled || row?.enabled === false ? "disabled"
|
||||
: ageMs === null ? "unobserved" : staleAfterMs === null ? "unknown" : ageMs > staleAfterMs ? "stale" : "fresh"
|
||||
return { freshness, observedAt: row?.observedAt?.toISOString() ?? null, ageMs, lastStatus: row?.status ?? null,
|
||||
...(row?.gapAt && { gapAt: row.gapAt.toISOString() }) }
|
||||
}
|
||||
|
||||
export function registerIncidentActions(register: typeof add) {
|
||||
register("telemetry.health.read", "mm_telemetry_health_get", "Здоровье источников телеметрии сервера", "logs",
|
||||
"mm:servers:read", "read", "servers", healthInput, {
|
||||
target: (raw, context) => {
|
||||
const serverIds = typeof raw.serverId === "number" ? [raw.serverId] : context.connection.policy.scope.serverIds
|
||||
if (!serverIds.length) throw new McpError("SERVER_DENIED", "Подключению не выдан доступ к серверам", 403)
|
||||
return { scope: "servers", serverIds }
|
||||
},
|
||||
read: async (raw, context) => {
|
||||
const input = healthInput.parse(raw), selected = permittedSources(context, input.sources)
|
||||
const asOf = Date.now(), from = new Date(asOf - 24 * hourMs), to = new Date(asOf)
|
||||
const healthQueries = selected.map(source => ({ source: source as Source | "uptime-probe", sql: healthSources[source] }))
|
||||
if (selected.includes("uptime")) healthQueries.push({ source: "uptime-probe", sql: uptimeProbeHealth })
|
||||
const readServer = async (serverId: number, serverEnabled: boolean) => ({
|
||||
serverId, serverEnabled, observations: await Promise.all(healthQueries.map(async ({ source, sql }) => {
|
||||
const expectsActiveServer = source === "netflow" || serverEnabled
|
||||
try {
|
||||
const { rows } = await pool.query<HealthRow>(sql, [serverId, from, to])
|
||||
return { source, ...telemetryFreshness(rows[0], asOf, expectsActiveServer) }
|
||||
} catch {
|
||||
context.signal?.throwIfAborted()
|
||||
return { source, ...telemetryFreshness(undefined, asOf, expectsActiveServer), freshness: "unavailable" as const }
|
||||
}
|
||||
})),
|
||||
})
|
||||
const metadata = { observedAt: to.toISOString(), lookbackFrom: from.toISOString(),
|
||||
sourceOmissions: sources.filter(source => !selected.includes(source)).map(source => ({
|
||||
source, reason: input.sources ? "not-requested" : "permission-denied",
|
||||
})),
|
||||
netflowDataQuality: { available: false, reason: "no-server-scoped-collector-quality", exportCoverage: "unverified" } }
|
||||
if (input.serverId !== undefined) return { ...await readServer(input.serverId, await requireServer(input.serverId)), ...metadata }
|
||||
const { rows } = await pool.query<{ id: number; enabled: boolean }>(
|
||||
"SELECT id,enabled FROM servers WHERE id=ANY($1::bigint[]) AND id>$2 ORDER BY id LIMIT $3",
|
||||
[context.connection.policy.scope.serverIds, input.afterServerId ?? 0, input.limit + 1])
|
||||
const page = rows.slice(0, input.limit)
|
||||
const items = await Promise.all(page.map(row => readServer(Number(row.id), row.enabled)))
|
||||
return { ...metadata, items, nextAfterServerId: rows.length > input.limit ? Number(page.at(-1)?.id) : null }
|
||||
},
|
||||
})
|
||||
register("incident.timeline.read", "mm_incident_timeline_get", "Хронология наблюдений по серверу", "logs",
|
||||
"mm:servers:read", "read", "servers", timelineInput, {
|
||||
read: async (raw, context) => {
|
||||
const input = timelineInput.parse(raw), selected = permittedSources(context, input.sources)
|
||||
const managerTools = input.includeManagerEvents ? managerEventTools(context) : null
|
||||
const { cursor: token, limit, ...filters } = input
|
||||
const scope = async () => fingerprint({ purpose: "incident-timeline-v1", filters, generation: await accessGeneration(),
|
||||
connection: context.connection.id, credential: context.principal?.credentialId,
|
||||
policy: context.connection.policy, ownerPermissions: context.connection.owner_permissions })
|
||||
let cursor: z.infer<typeof cursorSchema> | undefined
|
||||
if (token) {
|
||||
try {
|
||||
cursor = cursorSchema.parse(JSON.parse(await decryptSecret(token)))
|
||||
if (cursor.scope !== await scope()) throw Error("scope")
|
||||
} catch { throw new McpError("RESET_REQUIRED", "Курсор устарел или относится к другим фильтрам", 409) }
|
||||
}
|
||||
await requireServer(input.serverId)
|
||||
const parameters = [input.serverId, input.from, input.to, limit + 1]
|
||||
const queries: Array<{ source: TimelineSource; parameters: unknown[] }> =
|
||||
selected.map(source => ({ source, parameters: [...parameters] }))
|
||||
if (selected.includes("uptime")) queries.push({ source: "uptime-probe", parameters: [...parameters] })
|
||||
if (managerTools) queries.push({ source: "mcp-request",
|
||||
parameters: [...parameters, context.connection.id, context.connection.owner_id, managerTools] })
|
||||
const batches = await Promise.all(queries.map(async ({ source, parameters }) => {
|
||||
const { rows } = await pool.query<EvidenceRow>(timelineQuery(source, parameters, cursor), parameters)
|
||||
return rows.map(row => ({ ...row, source }))
|
||||
}))
|
||||
const items = batches.flat().sort((a, b) => a.at < b.at ? 1 : a.at > b.at ? -1 : a.source < b.source ? -1 : a.source > b.source ? 1 : 0)
|
||||
const page = items.slice(0, limit)
|
||||
const last = page.at(-1)
|
||||
const nextCursor = last && items.length > limit
|
||||
? await encryptSecret(JSON.stringify({ at: last.at, key: last.key, source: last.source, scope: cursor?.scope ?? await scope() }))
|
||||
: null
|
||||
return { serverId: input.serverId, from: new Date(input.from).toISOString(), to: new Date(input.to).toISOString(),
|
||||
observedAt: new Date().toISOString(), order: "newest-first", sources: queries.map(query => query.source),
|
||||
items: page.map(({ key: _key, receivedAt, ...row }) => ({
|
||||
...row, ...(receivedAt && { receivedAt: receivedAt.toISOString() }),
|
||||
})), nextCursor, truncated: nextCursor !== null, coverageVerified: false, managerEventsIncluded: input.includeManagerEvents }
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { z } from "zod"
|
||||
import { ixChangeSchema, type IxChange } from "@mmapp/contracts/internet-exchange"
|
||||
import { pool } from "../../db/index.js"
|
||||
import { applyIxChange, currentIxChange, ixTarget, observeIxSegment, prepareIxChange, prepareIxRemoval, reconcileIxChange, removeIxSegment } from "../../services/internet-exchange-execution.js"
|
||||
import { applyIxChange, currentIxChange, ixTarget, observeIxLinuxPath, observeIxSegment, prepareIxChange, prepareIxRemoval, readIxNodeInventory, reconcileIxChange, removeIxSegment } from "../../services/internet-exchange-execution.js"
|
||||
import { IxConflict, ixDeviceIds } from "../../services/internet-exchange-plan.js"
|
||||
import { assertIxRevision, isIxSegmentArchived, listIxSegments, readIxRevision, readIxSegment } from "../../services/internet-exchange-store.js"
|
||||
import type { add } from "./actions.js"
|
||||
@@ -152,6 +152,23 @@ export function registerIxActions(register: typeof add) {
|
||||
return { segment: row, observations: await observeIxSegment(row) }
|
||||
},
|
||||
})
|
||||
const nodeInput = z.object({ serverId: z.number().int().positive().safe() }).strict()
|
||||
register("network.ix.inventory", "mm_ix_inventory_get", "Интерфейсы CHR и кандидат Router ID", "network", "mm:network:read", "read", "servers",
|
||||
nodeInput, {
|
||||
target: async input => ({ scope: "servers", serverIds: [nodeInput.parse(input).serverId] }),
|
||||
read: input => present(() => readIxNodeInventory(nodeInput.parse(input).serverId, undefined, true)),
|
||||
})
|
||||
const pathInput = nodeInput.extend({ id, interfaceName: z.string().regex(/^[A-Za-z0-9_.-]{1,48}$/) })
|
||||
register("network.ix.linux-path", "mm_ix_linux_path_get", "Маршруты Linux-клиента IX", "network", "mm:network:read", "read", "servers",
|
||||
pathInput, {
|
||||
target: async input => ({ scope: "servers", serverIds: [pathInput.parse(input).serverId] }),
|
||||
read: input => present(async () => {
|
||||
const args = pathInput.parse(input)
|
||||
const segment = await readIxSegment(args.id)
|
||||
if (!segment) throw new IxConflict("Сегмент IX не найден", 404)
|
||||
return observeIxLinuxPath(segment, args.serverId, args.interfaceName)
|
||||
}),
|
||||
})
|
||||
register(ixOperation, "mm_ix_change_plan", "План изменения сегмента IX", "network", "mm:network:write", "write", "servers", changeArgs, {
|
||||
target: async input => ({ scope: "servers", serverIds: await ixTarget(changeArgs.parse(input).change) }),
|
||||
prepare: (input, context) => present(() => prepare(changeArgs.parse(input).change, context)),
|
||||
|
||||
@@ -94,6 +94,7 @@ test("actual collector initial settings failures release resource/ping/group bus
|
||||
const modules:Record<string,unknown>={"../db/index.js":{db,dbAll:async()=>[]},"../db/schema.js":tables,"drizzle-orm":Object.fromEntries(["and","asc","eq","gte","lte","inArray","max","sql"].map(name=>[name,()=>null])),
|
||||
"./config-mutation-policy.js":{executeGuardedApplicationWrite:()=>assert.fail("no config mutation")},"./monitoring-server-catalog.js":{listEnabledMonitoringServers:async()=>[]},"./mikrotik.js":{MikrotikClient:class{}},"../types/scheduler-run-snapshot.js":{SCHEDULER_RUN_SNAPSHOT_VERSION:1},"../constants/ping-probe.js":{PING_PROBE_WARN_RTT_MS:100},"./ros-metric-parse.js":{},"./ping-probe-replacement.js":{},"./partition-write-transaction.js":{withPartitionWrite:()=>assert.fail("no targets"),isPartitionWriteOutcomeUnknown:()=>false,PartitionWriteError:class extends Error{}}}
|
||||
const exports:Record<string,(...args:unknown[])=>Record<string,unknown>|Promise<Record<string,unknown>>>={}
|
||||
modules["./config-mutation-lock.js"] = { withApplicationCollectorLock: (collect: () => Promise<unknown>) => collect() }
|
||||
const code=ts.transpileModule(await readFile(new URL("../../services/uptime-collector.ts",import.meta.url),"utf8"),{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022}}).outputText
|
||||
runInNewContext(code,{exports,require:(name:string)=>{assert(name in modules,name);return modules[name]},Date,performance,console,Set,Map,Promise,Number,String,Math,Object,JSON,Error})
|
||||
for(const method of ["collectResourceSamplesOnce","collectPingProbesOnce","collectPingForProbeIds"]){
|
||||
|
||||
@@ -11,7 +11,7 @@ const creates = rosResources.filter(resource => !resource.readOnly && resource.c
|
||||
assert.equal(creates.length, 30)
|
||||
for (const resource of creates) {
|
||||
const action = findAction(`mm_${resource.id}_create_plan`)
|
||||
assert.equal(action.operation.version, resource.id === "bfd_configuration" ? 8 : resource.id === "ospf_template" ? 11 : ["ipsec_peer", "vrf", "ospf_instance"].includes(resource.id) ? 5 : ["wireguard", "bridge", "bridge_port", "bridge_vlan"].includes(resource.id) ? 4 : 3)
|
||||
assert.equal(action.operation.version, resource.id === "bfd_configuration" ? 9 : resource.id === "ospf_template" ? 11 : ["ipsec_peer", "vrf", "ospf_instance"].includes(resource.id) ? 5 : ["wireguard", "bridge", "bridge_port", "bridge_vlan"].includes(resource.id) ? 4 : 3)
|
||||
assert.equal(action.schema.safeParse({ serverId: 1, fields: {} }).success, true)
|
||||
for (const id of ["*OLD", undefined, null, ""]) {
|
||||
const rejected = action.schema.safeParse({ serverId: 1, fields: {}, id })
|
||||
@@ -27,6 +27,7 @@ assert.throws(() => validateRosStep(bfdConfig, "create", { vrf: "main" }), inval
|
||||
assert.deepEqual(validateRosStep(bfdConfig, "create", { interfaces: "bridge1", vrf: "main" }), { interfaces: "bridge1", vrf: "main" })
|
||||
for (const interfaces of ["all", "none", "bridge1,all", "bridge1,"]) assert.throws(() => validateRosStep(bfdConfig, "create", { interfaces, vrf: "main" }), invalid)
|
||||
for (const [addresses, expected] of [["192.0.2.9/24", "192.0.2.0/24"], ["FD00::20/64", "fd00::/64"], ["192.0.2.9/32", "192.0.2.9/32"], ["fd00::20/128", "fd00::20/128"]]) {
|
||||
assert.deepEqual(validateRosStep(bfdConfig, "create", { addresses, vrf: "main" }), { addresses: expected, vrf: "main" })
|
||||
assert.deepEqual(validateRosStep(bfdConfig, "update", { addresses }, "*A"), { addresses: expected })
|
||||
}
|
||||
for (const addresses of ["0.0.0.0/0", "::/0", "192.0.2.1", "fd00::/129", "192.0.2.1/32/extra", "192.0.2.0/24,192.0.3.0/24", "fe80::%ether1/64"]) assert.equal(bfdConfig.fields.safeParse({ addresses }).success, false)
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import assert from "node:assert/strict"
|
||||
import test from "node:test"
|
||||
import { projectDnsState, projectFibTableState, projectRouteLookup } from "./network-diagnostic-actions.js"
|
||||
|
||||
const route = (prefix: string, immediateGateway: string, table = "tenant") => ({
|
||||
"routing-table": table, "dst-address": prefix, active: "true",
|
||||
gateway: immediateGateway, "immediate-gw": immediateGateway,
|
||||
})
|
||||
|
||||
test("requires positive FIB evidence in the explicitly selected table", () => {
|
||||
const main = { name: "main", fib: true, invalid: false }
|
||||
assert.equal(projectFibTableState([main], "main"), "ready")
|
||||
assert.equal(projectFibTableState([main], "tenant"), "table-not-found")
|
||||
assert.equal(projectFibTableState([main, main], "main"), "partial")
|
||||
assert.equal(projectFibTableState([{ ...main, fib: "" }], "main"), "partial")
|
||||
assert.equal(projectFibTableState([{ ...main, fib: "false" }], "main"), "table-not-fib")
|
||||
assert.equal(projectFibTableState([{ ...main, invalid: true }], "main"), "table-inactive")
|
||||
})
|
||||
|
||||
test("looks up IPv4 by longest active prefix and preserves ECMP path multiplicity", () => {
|
||||
const prefix = "203.0.113.0/24"
|
||||
const result = projectRouteLookup([
|
||||
route("0.0.0.0/0", "192.0.2.1%wan"),
|
||||
route("203.0.113.10/32", "192.0.2.2%main", "main"),
|
||||
{ ...route("203.0.113.10/32", "192.0.2.3%disabled"), disabled: "true" },
|
||||
{ ...route("203.0.113.10/32", "192.0.2.4%inactive"), active: "false" },
|
||||
route(prefix, "192.0.2.5%uplink,192.0.2.6%uplink"),
|
||||
route(prefix, "192.0.2.5%uplink"),
|
||||
], "tenant", "203.0.113.10")
|
||||
assert.equal(result.status, "matched")
|
||||
assert.deepEqual(result.routes.map(item => item.prefix), [prefix, prefix])
|
||||
assert.deepEqual(result.nextHops, ["192.0.2.5%uplink", "192.0.2.6%uplink", "192.0.2.5%uplink"])
|
||||
assert.deepEqual(result.nextHopDetails.map(hop => hop.interface), ["uplink", "uplink", "uplink"])
|
||||
})
|
||||
|
||||
test("matches IPv6 blackhole and distinguishes absent and partial observations", () => {
|
||||
const blackhole = { "routing-table": "tenant", "dst-address": "2001:db8:1::/48", active: "true", blackhole: "yes" }
|
||||
const result = projectRouteLookup([route("::/0", "fe80::1%uplink"), blackhole], "tenant", "2001:db8:1:2::15")
|
||||
assert.equal(result.status, "matched")
|
||||
assert.equal(result.routes[0].disposition, "blackhole")
|
||||
assert.deepEqual(result.nextHops, [])
|
||||
assert.equal(projectRouteLookup([blackhole], "tenant", "2001:db8:2::1").status, "no-route")
|
||||
assert.equal(projectRouteLookup([{ ...blackhole, active: undefined }], "tenant", "2001:db8:1::1").status, "partial")
|
||||
assert.equal(projectRouteLookup([route("::/0", "")], "tenant", "2001:db8:1::1").status, "partial")
|
||||
assert.equal(projectRouteLookup([route("::/0", "fe80::1%uplink"), { ...blackhole, "dst-address": "2001:db8:1::/129" }], "tenant", "2001:db8:1::1").status, "partial")
|
||||
assert.equal(projectRouteLookup([{ ...blackhole, blackhole: "" }], "tenant", "2001:db8:1::1").routes[0].disposition, "blackhole")
|
||||
assert.equal(projectRouteLookup([route("::/0", "bridge wan")], "tenant", "2001:db8:1::1").nextHopDetails[0].interface, "bridge wan")
|
||||
})
|
||||
|
||||
test("bounds ECMP output and exposes omissions as partial", () => {
|
||||
const rows = Array.from({ length: 129 }, () => route("0.0.0.0/0", "192.0.2.1%uplink"))
|
||||
const result = projectRouteLookup(rows, "tenant", "203.0.113.10")
|
||||
assert.equal(result.status, "partial")
|
||||
assert.equal(result.nextHops.length, 128)
|
||||
})
|
||||
|
||||
test("retains duplicate native array nexthops across active default rows", () => {
|
||||
const defaults = Array.from({ length: 2 }, () => ({
|
||||
"routing-table": "main", "dst-address": "0.0.0.0/0", active: true,
|
||||
gateway: ["192.0.2.1"], "immediate-gw": ["192.0.2.1%ether1"],
|
||||
}))
|
||||
const result = projectRouteLookup(defaults, "main", "203.0.113.10")
|
||||
assert.equal(result.status, "matched")
|
||||
assert.deepEqual(result.nextHops, ["192.0.2.1%ether1", "192.0.2.1%ether1"])
|
||||
assert.deepEqual(result.routes.map(item => item.gateways), [["192.0.2.1"], ["192.0.2.1"]])
|
||||
assert.equal(projectRouteLookup([{ ...defaults[0], "immediate-gw": ["192.0.2.1%ether1", 1] }], "main", "203.0.113.10").status, "partial")
|
||||
})
|
||||
|
||||
test("DNS reports ordered upstream addresses and projects DoH to a boolean", () => {
|
||||
assert.deepEqual(projectDnsState({
|
||||
"allow-remote-requests": "yes", servers: "192.0.2.53@tenant,2001:db8::53", "dynamic-servers": "",
|
||||
"use-doh-server": "https://example.invalid/dns-query?secret=private", "cache-used": "private",
|
||||
}), {
|
||||
allowRemoteRequests: true, staticServers: ["192.0.2.53@tenant", "2001:db8::53"],
|
||||
dynamicServers: [], dohEnabled: true, incomplete: false,
|
||||
})
|
||||
assert.deepEqual(projectDnsState({ "allow-remote-requests": false, servers: "", "use-doh-server": "" }), {
|
||||
allowRemoteRequests: false, staticServers: [], dynamicServers: null, dohEnabled: false, incomplete: true,
|
||||
})
|
||||
assert.deepEqual(projectDnsState([{ "allow-remote-requests": false, servers: ["192.0.2.53", "2001:db8::53"], "dynamic-servers": [], "use-doh-server": "" }]), {
|
||||
allowRemoteRequests: false, staticServers: ["192.0.2.53", "2001:db8::53"], dynamicServers: [], dohEnabled: false, incomplete: false,
|
||||
})
|
||||
assert.throws(() => projectDnsState([{}, {}]))
|
||||
})
|
||||
@@ -0,0 +1,184 @@
|
||||
import { isIP } from "node:net"
|
||||
import { z } from "zod"
|
||||
import { observedBoolean } from "../../services/ospf-observed-values.js"
|
||||
import { isConfirmedRoutingFibTable } from "../../services/routing-table-fib.js"
|
||||
import { ipv4ToInt, ipv6ToInt, parseCidrV4, parseCidrV6 } from "../../services/traffic-flow-ip.js"
|
||||
import type { add } from "./actions.js"
|
||||
import { readNetworkValue } from "./network-neighbor-actions.js"
|
||||
import { parseRoutingEndpoint } from "./routing-native-endpoint.js"
|
||||
import { McpError } from "./security.js"
|
||||
|
||||
const serverIdSchema = z.number().int().positive().safe()
|
||||
const tableSchema = z.string().min(1).max(200).refine(value => !/[\u0000-\u001f\u007f]/.test(value))
|
||||
const destinationSchema = z.string().max(45).refine(value => !value.includes("%") && isIP(value) !== 0)
|
||||
const rowSchema = z.record(z.string(), z.unknown())
|
||||
const tablePath = "/routing/table?.proplist=name,fib,disabled,invalid"
|
||||
const dnsPath = "/ip/dns?.proplist=allow-remote-requests,servers,dynamic-servers,use-doh-server"
|
||||
const flags = z.union([z.boolean(), z.string()]).transform(value => typeof value === "boolean" ? value : observedBoolean(value))
|
||||
const flag = (value: unknown) => flags.safeParse(value).data ?? null
|
||||
const routeRows = z.array(rowSchema).max(10000)
|
||||
const maxRoutePaths = 128
|
||||
|
||||
export function projectFibTableState(raw: unknown, table: string) {
|
||||
const rows = routeRows.parse(raw)
|
||||
if (rows.some(row => typeof row.name !== "string")) return "partial"
|
||||
const matches = rows.filter(row => row.name === table)
|
||||
if (matches.length > 1) return "partial"
|
||||
if (!matches.length) return "table-not-found"
|
||||
const row = matches[0]
|
||||
if (flag(row.fib) === false) return "table-not-fib"
|
||||
if (flag(row.disabled) === true || flag(row.invalid) === true) return "table-inactive"
|
||||
// This REST catalog has produced an empty fib value for non-FIB tables as well.
|
||||
return row.fib !== "" && isConfirmedRoutingFibTable(row) ? "ready" : "partial"
|
||||
}
|
||||
|
||||
function matchingLength(value: unknown, destination: string): number | null {
|
||||
const family = isIP(destination)
|
||||
if (typeof value !== "string" || value.length > 50 || !/^[^/%]+\/\d+$/.test(value)) return null
|
||||
if (isIP(value.split("/")[0]) !== family) return null
|
||||
if (family === 4) {
|
||||
const prefix = parseCidrV4(value)
|
||||
if (!prefix) return null
|
||||
return ((ipv4ToInt(destination)! & prefix.mask) >>> 0) === prefix.net ? prefix.prefixLen : -1
|
||||
}
|
||||
const prefix = parseCidrV6(value)
|
||||
if (!prefix) return null
|
||||
return (ipv6ToInt(destination)! >> prefix.shift) === prefix.net ? prefix.prefixLen : -1
|
||||
}
|
||||
|
||||
const routePath = z.string().min(1).max(512).refine(value => !/[\u0000-\u001f\u007f]/.test(value))
|
||||
function nativeList(value: unknown, maxCharacters: number, maxItems: number): string[] | null {
|
||||
if (value === "") return []
|
||||
const items = typeof value === "string" && value.length <= maxCharacters ? value.split(",") : value
|
||||
if (!Array.isArray(items) || items.length > maxItems) return null
|
||||
let characters = 0
|
||||
const result = []
|
||||
for (const item of items) {
|
||||
if (typeof item !== "string") return null
|
||||
characters += item.length
|
||||
const entry = item.trim()
|
||||
if (!entry || characters > maxCharacters) return null
|
||||
result.push(entry)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
function splitNexthops(value: unknown) {
|
||||
const paths = nativeList(value, 16384, 1024)
|
||||
return paths?.every(path => !path.includes(",") && routePath.safeParse(path).success) ? paths : []
|
||||
}
|
||||
|
||||
function nexthopDetails(value: string) {
|
||||
try {
|
||||
const hop = parseRoutingEndpoint(value)
|
||||
return { address: hop.address, interface: hop.interface ?? null, vrf: hop.vrf ?? null }
|
||||
} catch {
|
||||
const direct = /^([^%@/]+)(?:@([^%@/]+))?$/.exec(value)
|
||||
return { address: null, interface: direct?.[1] ?? null, vrf: direct?.[2] ?? null }
|
||||
}
|
||||
}
|
||||
|
||||
export function projectRouteLookup(raw: unknown, table: string, destination: string) {
|
||||
const routes: { prefix: string; disposition: "blackhole" | "unreachable" | "prohibit" | "forward"; gateways: string[]; immediateGateways: string[] }[] = []
|
||||
let longest = -1
|
||||
let unknownLongest = -1
|
||||
let limited = false
|
||||
let hopCount = 0
|
||||
for (const row of routeRows.parse(raw)) {
|
||||
if (typeof row["routing-table"] === "string" && row["routing-table"] !== table) continue
|
||||
if (flag(row.active) === false || flag(row.disabled) === true || flag(row.inactive) === true) continue
|
||||
const length = matchingLength(row["dst-address"], destination)
|
||||
if (length === null) {
|
||||
unknownLongest = isIP(destination) === 4 ? 32 : 128
|
||||
continue
|
||||
}
|
||||
if (length < 0) continue
|
||||
if (row["routing-table"] !== table || flag(row.active) !== true) {
|
||||
unknownLongest = Math.max(unknownLongest, length)
|
||||
continue
|
||||
}
|
||||
if (length < longest) continue
|
||||
if (length > longest) {
|
||||
routes.length = 0
|
||||
limited = false
|
||||
hopCount = 0
|
||||
longest = length
|
||||
}
|
||||
if (routes.length === maxRoutePaths) {
|
||||
limited = true
|
||||
continue
|
||||
}
|
||||
const disposition = row.blackhole === "" ? "blackhole" : (["blackhole", "unreachable", "prohibit"] as const)
|
||||
.find(kind => flag(row[kind]) === true || row.type === kind || row.gateway === kind) ?? "forward"
|
||||
const remaining = maxRoutePaths - hopCount
|
||||
const configured = disposition === "forward" ? splitNexthops(row.gateway) : []
|
||||
const resolved = disposition === "forward" ? splitNexthops(row["immediate-gw"]) : []
|
||||
const paths = Math.max(configured.length, resolved.length)
|
||||
limited ||= paths > remaining
|
||||
hopCount += Math.min(paths, remaining)
|
||||
const gateways = configured.slice(0, remaining)
|
||||
const immediateGateways = resolved.slice(0, remaining)
|
||||
routes.push({ prefix: String(row["dst-address"]), disposition, gateways, immediateGateways })
|
||||
}
|
||||
const nextHops = routes.flatMap(route => route.immediateGateways)
|
||||
const nextHopDetails = nextHops.map(nexthopDetails)
|
||||
const incomplete = (unknownLongest >= 0 && unknownLongest >= longest) || limited
|
||||
|| routes.some(route => route.disposition === "forward" && !route.immediateGateways.length)
|
||||
|| nextHopDetails.some(hop => !hop.address && !hop.interface)
|
||||
return { status: incomplete ? "partial" : routes.length ? "matched" : "no-route", incomplete, routes, nextHops, nextHopDetails }
|
||||
}
|
||||
|
||||
function dnsServers(value: unknown) {
|
||||
const items = nativeList(value, 8192, 128)
|
||||
if (!items || items.some(server => {
|
||||
const [address, vrf, extra] = server.split("@")
|
||||
return !isIP(address) || extra !== undefined || (vrf !== undefined && !tableSchema.safeParse(vrf).success)
|
||||
})) return null
|
||||
return items
|
||||
}
|
||||
|
||||
export function projectDnsState(raw: unknown) {
|
||||
const row = Array.isArray(raw) ? z.tuple([rowSchema]).parse(raw)[0] : rowSchema.parse(raw)
|
||||
const allowRemoteRequests = flag(row["allow-remote-requests"])
|
||||
const staticServers = dnsServers(row.servers)
|
||||
const dynamicServers = dnsServers(row["dynamic-servers"])
|
||||
const dohEnabled = typeof row["use-doh-server"] === "string" ? row["use-doh-server"].trim().length > 0 : null
|
||||
return { allowRemoteRequests, staticServers, dynamicServers, dohEnabled,
|
||||
incomplete: [allowRemoteRequests, staticServers, dynamicServers, dohEnabled].includes(null) }
|
||||
}
|
||||
|
||||
export function registerNetworkDiagnosticActions(register: typeof add) {
|
||||
register("network.route.lookup.read", "mm_route_lookup_get",
|
||||
"Поиск самого специфичного активного маршрута IPv4/IPv6 в явно выбранной таблице FIB RouterOS",
|
||||
"network", "mm:network:read", "read", "servers",
|
||||
z.object({ serverId: serverIdSchema, destination: destinationSchema, table: tableSchema }).strict(),
|
||||
{ read: async (input, context) => {
|
||||
const serverId = Number(input.serverId), destination = String(input.destination), table = String(input.table)
|
||||
const family = isIP(destination) === 4 ? "ipv4" : "ipv6"
|
||||
const empty = { routes: [], nextHops: [], nextHopDetails: [] }
|
||||
const observed = { serverId, family, table, destination, forwardingVerified: false, timestampKind: "backend-receipt" }
|
||||
try {
|
||||
const result = await readNetworkValue(serverId, context, tablePath, async (raw, get) => {
|
||||
const state = projectFibTableState(raw, table)
|
||||
if (state !== "ready") return { ...empty, status: state, incomplete: state === "partial" }
|
||||
const resource = family === "ipv4" ? "/ip/route" : "/ipv6/route"
|
||||
const path = `${resource}?.proplist=dst-address,routing-table,active,disabled,inactive,gateway,immediate-gw,blackhole,type&${new URLSearchParams({ "routing-table": table })}`
|
||||
return projectRouteLookup(await get(path), table, destination)
|
||||
})
|
||||
return { ...observed, ...result, observedAt: new Date().toISOString() }
|
||||
} catch (error) {
|
||||
if (!(error instanceof McpError) || error.code !== "STATE_UNAVAILABLE") throw error
|
||||
return { ...observed, ...empty, status: "partial", incomplete: true, reason: "source-unavailable", observedAt: null }
|
||||
}
|
||||
} },
|
||||
)
|
||||
register("network.dns.state.read", "mm_dns_state_get",
|
||||
"Состояние DNS RouterOS: удалённые запросы, статические и динамические серверы и признак настройки DoH",
|
||||
"network", "mm:network:read", "read", "servers", z.object({ serverId: serverIdSchema }).strict(),
|
||||
{ read: async (input, context) => {
|
||||
const serverId = Number(input.serverId)
|
||||
const state = await readNetworkValue(serverId, context, dnsPath, projectDnsState)
|
||||
return { serverId, ...state, observedAt: new Date().toISOString(), timestampKind: "backend-receipt" }
|
||||
} },
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { randomUUID } from "node:crypto"
|
||||
import { createServer } from "node:http"
|
||||
import type { AddressInfo } from "node:net"
|
||||
import { basename, dirname, isAbsolute } from "node:path"
|
||||
import { mcpConnectionCreateSchema } from "@mmapp/contracts/mcp"
|
||||
import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client"
|
||||
|
||||
assert.equal(process.env.MMAPP_OWN_NETWORK_DIAGNOSTICS, "true")
|
||||
assert.equal(process.env.NODE_ENV, "test")
|
||||
const database = new URL(process.env.DATABASE_URL ?? "")
|
||||
assert.equal(database.protocol, "postgresql:")
|
||||
assert.equal(database.hostname, "127.0.0.1")
|
||||
assert.equal(database.username, "mcp_test")
|
||||
assert.equal(database.pathname, "/postgres")
|
||||
assert(database.port && database.password && !database.search && !database.hash)
|
||||
const stateDir = process.env.MCP_STATE_DIR ?? ""
|
||||
assert(isAbsolute(stateDir))
|
||||
assert.equal(basename(stateDir), "state")
|
||||
assert.match(basename(dirname(stateDir)), /^mm-mcp-test-/)
|
||||
|
||||
const { pool, closePool } = await import("../../db/index.js")
|
||||
const { applySqlMigrations } = await import("../../db/migrate.js")
|
||||
const { buildApp } = await import("../../index.js")
|
||||
const { createMcpConnection, updateMcpSettings } = await import("./store.js")
|
||||
const actor = {
|
||||
id: "network-diagnostics-owner", apps: ["mm"],
|
||||
permissions: ["mm:settings:admin", "mm:network:read", "mm:servers:read", "mm:traffic:read", "mm:mcp:read"],
|
||||
expiresAt: Date.now() + 3_600_000,
|
||||
}
|
||||
const operations = {
|
||||
mm_capabilities_get: "capabilities.read",
|
||||
mm_telemetry_health_get: "telemetry.health.read",
|
||||
mm_incident_timeline_get: "incident.timeline.read",
|
||||
mm_route_lookup_get: "network.route.lookup.read",
|
||||
mm_dns_state_get: "network.dns.state.read",
|
||||
mm_resilience_topology_get: "network.resilience.topology.read",
|
||||
mm_resilience_design_preview: "network.resilience.design.read",
|
||||
mm_failover_report_get: "network.resilience.failover.read",
|
||||
}
|
||||
const dnsSecret = "private-doh-url-fixture"
|
||||
const nativeReads: string[] = []
|
||||
const nativeRoutes = new Map<string, unknown>([
|
||||
["/rest/routing/table", [{ name: "main", fib: "true" }]],
|
||||
["/rest/ip/route", [{ "routing-table": "main", "dst-address": "0.0.0.0/0", active: "true",
|
||||
gateway: "192.0.2.1", "immediate-gw": "192.0.2.1%ether1" }]],
|
||||
["/rest/ip/dns", { "allow-remote-requests": "false", servers: "1.1.1.1", "dynamic-servers": "",
|
||||
"use-doh-server": `https://example.invalid/${dnsSecret}` }],
|
||||
])
|
||||
const router = createServer((request, response) => {
|
||||
const path = new URL(request.url ?? "/", "http://127.0.0.1").pathname
|
||||
nativeReads.push(`${request.method} ${path}`)
|
||||
const value = nativeRoutes.get(path)
|
||||
response.writeHead(request.method === "GET" && value !== undefined ? 200 : 404, { "content-type": "application/json" })
|
||||
response.end(JSON.stringify(value ?? {}))
|
||||
})
|
||||
const sdkClient = () => new Client({ name: "owned-network-diagnostics", version: "1.0.0" })
|
||||
let client = sdkClient()
|
||||
const call = (name: keyof typeof operations, args: Record<string, unknown>) => client.callTool({ name, arguments: args })
|
||||
async function read<T>(name: keyof typeof operations, args: Record<string, unknown>) {
|
||||
const response = await call(name, args)
|
||||
assert(!response.isError, `${name}: ${JSON.stringify(response.content)}`)
|
||||
const result = (response.structuredContent as { result?: T } | undefined)?.result
|
||||
assert(result !== undefined, `Missing structured result for ${name}`)
|
||||
return result
|
||||
}
|
||||
async function deny(name: keyof typeof operations, args: Record<string, unknown>, code: string) {
|
||||
const response = await call(name, args)
|
||||
assert.equal(response.isError, true, name)
|
||||
assert(JSON.stringify(response.content).includes(code), `${name}: ${JSON.stringify(response.content)}`)
|
||||
}
|
||||
|
||||
let app: Awaited<ReturnType<typeof buildApp>> | undefined
|
||||
try {
|
||||
await applySqlMigrations(pool)
|
||||
assert.equal((await pool.query("SELECT count(*)::int AS n FROM servers")).rows[0].n, 0)
|
||||
await new Promise<void>(resolve => router.listen(0, "127.0.0.1", resolve))
|
||||
const port = (router.address() as AddressInfo).port
|
||||
await pool.query(`INSERT INTO servers(id,name,host,port,use_ssl,verify_ssl,username,password,enabled)
|
||||
VALUES (1,'scoped-router','127.0.0.1',$1,false,false,'owned','fixture',true),
|
||||
(2,'foreign-router','127.0.0.1',$1,false,false,'owned','fixture',true)`, [port])
|
||||
const now = Date.now()
|
||||
const instant = (offset: number) => new Date(now + offset).toISOString()
|
||||
const [localAt, foreignAt] = [instant(-2_000), instant(-1_000)]
|
||||
await pool.query("UPDATE router_log_settings SET enabled=true,interval_sec=3600 WHERE id=1")
|
||||
for (const [id, eventAt, message] of [[1, localAt, "local-log-fixture"], [2, foreignAt, "foreign-log-fixture"]] as const) {
|
||||
await pool.query(`INSERT INTO router_log_collection_state(server_id,server_name,host,last_collected_at)
|
||||
VALUES ($1,'fixture','127.0.0.1',$2)`, [id, eventAt])
|
||||
await pool.query(`INSERT INTO router_log_entries(server_id,server_name,host,router_id,raw_time,event_at,received_at,effective_at,topics,level,message,generation)
|
||||
VALUES ($1,'fixture','127.0.0.1','fixture','fixture',NULL,$2,$2,ARRAY['system'],'info',$3,1)`, [id, eventAt, message])
|
||||
}
|
||||
const segment = async (name: string, peerServerId?: number) => {
|
||||
const id = randomUUID()
|
||||
const configuration = { name, sites: [{ serverId: 1, autonomousSystem: 64512, routerId: "192.0.2.5",
|
||||
interfaces: [{ name: "ether1", kind: "uplink", peerServerId }],
|
||||
groups: [{ id: "internet", gateway: "192.0.2.1", primary: { interface: "ether1", nextHop: "192.0.2.1", probe: "192.0.2.8" } }],
|
||||
exits: ["internet"],
|
||||
}] }
|
||||
await pool.query(`INSERT INTO ix_segments(id,name,revision,configuration) VALUES ($1,$2,1,$3)`, [id, name, configuration])
|
||||
return { kind: "ix-segment", segmentId: id }
|
||||
}
|
||||
const target = await segment("scoped-segment"), foreignTarget = await segment("foreign-segment", 2)
|
||||
await updateMcpSettings({ enabled: true }, actor)
|
||||
const issue = (audit: boolean) => createMcpConnection(mcpConnectionCreateSchema.parse({
|
||||
name: "Scoped network diagnostics", mode: "observer", expiresAt: instant(600_000),
|
||||
permissions: ["mm:network:read", "mm:servers:read", ...(audit ? ["mm:mcp:read"] : [])],
|
||||
scope: { serverIds: [1], operationIds: Object.values(operations), allowGlobal: false },
|
||||
limits: { callsPerMinute: 120 },
|
||||
}), actor)
|
||||
|
||||
app = await buildApp({ startScheduler: false, logger: false })
|
||||
const address = await app.listen({ host: "127.0.0.1", port: 0 })
|
||||
const connect = (token: string) => client.connect(new StreamableHTTPClientTransport(new URL(`${address}/mcp`),
|
||||
{ requestInit: { headers: { Authorization: `Bearer ${token}` } } }))
|
||||
const access = await issue(false)
|
||||
await connect(access.token)
|
||||
const { tools } = await client.listTools()
|
||||
assert.deepEqual(tools.map(tool => tool.name).sort(), Object.keys(operations).sort())
|
||||
assert(tools.every(tool => tool.annotations?.readOnlyHint === true))
|
||||
const legacy = await read<{ operations: Array<{ id: string; applicability?: unknown }>; schemaVersion: number }>("mm_capabilities_get", {})
|
||||
assert.deepEqual(Object.keys(legacy).sort(), ["operations", "schemaVersion"])
|
||||
assert.equal(legacy.schemaVersion, 1)
|
||||
assert.deepEqual(legacy.operations.map(row => row.id).sort(), Object.values(operations).sort())
|
||||
assert(legacy.operations.every(row => !Object.hasOwn(row, "applicability")))
|
||||
const applicable = await read<{ operations: Array<{ applicability: { decision: string; reasons: Array<{ code: string }> } }> }>(
|
||||
"mm_capabilities_get", { toolName: "mm_route_lookup_get", serverId: 2 })
|
||||
assert.equal(applicable.operations.length, 1)
|
||||
assert.equal(applicable.operations[0].applicability.decision, "denied")
|
||||
assert(applicable.operations[0].applicability.reasons.some(reason => reason.code === "SERVER_DENIED"))
|
||||
|
||||
const health = await read<{ observations: Array<{ source: string; freshness: string; observedAt: string }>; netflowDataQuality: { available: boolean } }>(
|
||||
"mm_telemetry_health_get", { serverId: 1 })
|
||||
assert.deepEqual(health.observations.map(row => row.source).sort(), ["logs", "routeros-poll"])
|
||||
const logs = health.observations.find(row => row.source === "logs")
|
||||
assert.equal(logs?.observedAt, localAt)
|
||||
assert.equal(logs?.freshness, "fresh")
|
||||
assert.equal(health.netflowDataQuality.available, false)
|
||||
assert(!JSON.stringify(health).includes(foreignAt))
|
||||
const fleet = await read<{ items: Array<{ serverId: number }>; nextAfterServerId: number | null }>(
|
||||
"mm_telemetry_health_get", { sources: ["logs"], limit: 1 })
|
||||
assert.deepEqual(fleet.items.map(row => row.serverId), [1])
|
||||
assert.equal(fleet.nextAfterServerId, null)
|
||||
assert(!JSON.stringify(fleet).includes(foreignAt))
|
||||
const window = { from: instant(-60_000), outageAt: instant(-40_000), restoreAt: instant(-20_000), to: instant(0) }
|
||||
const range = { from: window.from, to: window.to, sources: ["logs"] }
|
||||
const timeline = await read<{ items: Array<{ message: string; timestampKind: string }>; coverageVerified: boolean }>(
|
||||
"mm_incident_timeline_get", { serverId: 1, ...range })
|
||||
assert.equal(timeline.items.length, 1)
|
||||
assert.equal(timeline.items[0].message, "local-log-fixture")
|
||||
assert.equal(timeline.items[0].timestampKind, "receipt")
|
||||
assert.equal(timeline.coverageVerified, false)
|
||||
await deny("mm_telemetry_health_get", { serverId: 2 }, "SERVER_DENIED")
|
||||
await deny("mm_incident_timeline_get", { serverId: 2, ...range }, "SERVER_DENIED")
|
||||
await deny("mm_telemetry_health_get", { serverId: 1, sources: ["netflow"] }, "PERMISSION_DENIED")
|
||||
await deny("mm_incident_timeline_get", { serverId: 1, ...range, sources: ["uptime"] }, "PERMISSION_DENIED")
|
||||
await deny("mm_incident_timeline_get", { serverId: 1, ...range, includeManagerEvents: true }, "PERMISSION_DENIED")
|
||||
|
||||
const lookup = { destination: "198.51.100.10", table: "main" }
|
||||
const route = await read<{ status: string; nextHops: string[]; forwardingVerified: boolean }>("mm_route_lookup_get", { serverId: 1, ...lookup })
|
||||
assert.equal(route.status, "matched")
|
||||
assert.deepEqual(route.nextHops, ["192.0.2.1%ether1"])
|
||||
assert.equal(route.forwardingVerified, false)
|
||||
const dns = await read<{ staticServers: string[]; dohEnabled: boolean }>("mm_dns_state_get", { serverId: 1 })
|
||||
assert.deepEqual(dns.staticServers, ["1.1.1.1"])
|
||||
assert.equal(dns.dohEnabled, true)
|
||||
assert(!JSON.stringify(dns).includes(dnsSecret))
|
||||
await deny("mm_route_lookup_get", { serverId: 2, ...lookup }, "SERVER_DENIED")
|
||||
await deny("mm_dns_state_get", { serverId: 2 }, "SERVER_DENIED")
|
||||
|
||||
const topology = await read<{ serverIds: number[]; paths: unknown[]; physicalIndependenceVerified: boolean }>("mm_resilience_topology_get", { target })
|
||||
assert.deepEqual(topology.serverIds, [1])
|
||||
assert.equal(topology.paths.length, 1)
|
||||
assert.equal(topology.physicalIndependenceVerified, false)
|
||||
const design = { scenario: "wan" }
|
||||
const preview = await read<{ suggestedTools: string[] }>("mm_resilience_design_preview", { target, ...design })
|
||||
assert(preview.suggestedTools.includes("mm_ix_segment_get"))
|
||||
const reportArgs = { window, targetFailoverMs: 1000, targetFailbackMs: 1000 }
|
||||
const report = await read<{ status: string; reason: string; managementSsh: string }>("mm_failover_report_get", { target, ...reportArgs })
|
||||
assert.equal(report.status, "inconclusive")
|
||||
assert.equal(report.reason, "NO_SAVED_IX_CONTROL_PROBE_HISTORY")
|
||||
assert.equal(report.managementSsh, "inconclusive")
|
||||
await deny("mm_resilience_topology_get", { target: foreignTarget }, "NOT_FOUND")
|
||||
await deny("mm_resilience_design_preview", { target: foreignTarget, ...design }, "NOT_FOUND")
|
||||
await deny("mm_failover_report_get", { target: foreignTarget, ...reportArgs }, "NOT_FOUND")
|
||||
assert.deepEqual(nativeReads, ["GET /rest/routing/table", "GET /rest/ip/route", "GET /rest/ip/dns"])
|
||||
|
||||
const auditedAccess = await issue(true)
|
||||
const requestId = randomUUID()
|
||||
await pool.query(`INSERT INTO mcp_requests(id,connection_id,actor_id,tool,server_ids,status,input,created_at,finished_at)
|
||||
VALUES ($1,$2,$4,'mm_dns_state_get',ARRAY[1]::bigint[],'succeeded','{"credential":"audit-secret-fixture"}',$5,$5),
|
||||
($6,$3,$4,'mm_dns_state_get',ARRAY[1]::bigint[],'succeeded','{}',$5,$5),
|
||||
($7,$2,$4,'mm_dns_state_get',ARRAY[1,2]::bigint[],'succeeded','{}',$5,$5)`,
|
||||
[requestId, auditedAccess.connection.id, access.connection.id, actor.id, foreignAt, randomUUID(), randomUUID()])
|
||||
await client.close()
|
||||
client = sdkClient()
|
||||
await connect(auditedAccess.token)
|
||||
type TimelinePage = { items: Array<{ id: string; source: string; toolName?: string }>; nextCursor: string | null }
|
||||
const auditArgs = { serverId: 1, ...range, includeManagerEvents: true, limit: 1 }
|
||||
const audited = await read<TimelinePage>("mm_incident_timeline_get", auditArgs)
|
||||
assert.deepEqual(audited.items.map(item => item.source), ["mcp-request"])
|
||||
assert.equal(audited.items[0].id, requestId)
|
||||
assert.equal(audited.items[0].toolName, "mm_dns_state_get")
|
||||
assert(!JSON.stringify(audited).includes("audit-secret-fixture"))
|
||||
assert(audited.nextCursor)
|
||||
const pageArgs = { ...auditArgs, cursor: audited.nextCursor }
|
||||
const next = await read<TimelinePage>("mm_incident_timeline_get", pageArgs)
|
||||
assert.deepEqual(next.items.map(item => item.source), ["logs"])
|
||||
assert.equal(next.nextCursor, null)
|
||||
await deny("mm_incident_timeline_get", { ...pageArgs, includeManagerEvents: false }, "RESET_REQUIRED")
|
||||
|
||||
const { assertSignedResilienceHistory } = await import("../../test/resilience-report-acceptance.js")
|
||||
await assertSignedResilienceHistory({
|
||||
connectionId: auditedAccess.connection.id,
|
||||
foreignConnectionId: access.connection.id,
|
||||
serverId: 1,
|
||||
callReport: input => read("mm_failover_report_get", input),
|
||||
})
|
||||
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_plans")).rows[0].n, 0)
|
||||
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_operations")).rows[0].n, 0)
|
||||
} finally {
|
||||
await client.close()
|
||||
await app?.close()
|
||||
if (router.listening) await new Promise<void>((resolve, reject) => router.close(error => error ? reject(error) : resolve()))
|
||||
await closePool()
|
||||
}
|
||||
@@ -44,7 +44,7 @@ function catalogRows<T>(value: unknown, project: (text: (key: string) => string
|
||||
}).sort((left, right) => left.id.localeCompare(right.id))
|
||||
}
|
||||
|
||||
async function readNetworkValue<T>(serverId: number, context: ActionContext, path: string, project: (raw: unknown) => T) {
|
||||
export async function readNetworkValue<T>(serverId: number, context: ActionContext, path: string, project: (raw: unknown, get: (path: string) => Promise<unknown>) => T | Promise<T>) {
|
||||
const authorize = async () => {
|
||||
if (context.signal?.aborted) throw new McpError("READ_CANCELLED", "Чтение сетевого каталога отменено", 409)
|
||||
const current = await effectiveMcpConnection(context.principal)
|
||||
@@ -57,8 +57,8 @@ async function readNetworkValue<T>(serverId: number, context: ActionContext, pat
|
||||
const check = async () => { await authorize(); await source.assertCurrent(); await authorize() }
|
||||
try {
|
||||
const { client } = await routerClient(serverId)
|
||||
const raw = await client.get<unknown>(path, 10000, context.signal, 1048576, check)
|
||||
const value = project(raw)
|
||||
const get = (resource: string) => client.get<unknown>(resource, 10000, context.signal, 1048576, check)
|
||||
const value = await project(await get(path), get)
|
||||
await check()
|
||||
return value
|
||||
} catch (error) {
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { test } from "node:test"
|
||||
import { routeAiProfileSchema } from "@mmapp/contracts/mcp-routing"
|
||||
import { assessFailover, routePaths, summarizePaths } from "./resilience-actions.js"
|
||||
|
||||
const first = { id: "a", wanInterface: "ether1", jumpHostId: 2, exitNodeId: 3,
|
||||
downstreamInterface: "wg-a", gateway: "192.0.2.1", gatewayRef: { resource: "ipv4_route", id: "*a" } }
|
||||
const second = { ...first, id: "b", jumpHostId: 4, exitNodeId: 5, downstreamInterface: "wg-b" }
|
||||
|
||||
function topology(reserve: typeof second) {
|
||||
const profile = routeAiProfileSchema.parse({ name: "failover", community: "65000:1", family: "ipv4", serverId: 1, candidates: [first, reserve] })
|
||||
return summarizePaths(routePaths(profile))
|
||||
}
|
||||
|
||||
test("different jump and exit nodes still share a WAN on the origin router", () => {
|
||||
const result = topology(second)
|
||||
assert.deepEqual(result.sharedDomains, [
|
||||
{ kind: "source", serverId: 1, pathIds: ["a", "b"] },
|
||||
{ kind: "wan", serverId: 1, interfaceName: "ether1", pathIds: ["a", "b"] },
|
||||
])
|
||||
assert.equal(result.physicalIndependenceVerified, false)
|
||||
})
|
||||
|
||||
test("logically disjoint WAN, jump and exit nodes retain an unknown physical domain", () => {
|
||||
const result = topology({ ...second, wanInterface: "ether2" })
|
||||
assert.deepEqual(result.sharedDomains, [{ kind: "source", serverId: 1, pathIds: ["a", "b"] }])
|
||||
assert.ok(result.unknownDomains.includes("carrier"))
|
||||
assert.equal(result.physicalIndependenceVerified, false)
|
||||
})
|
||||
|
||||
test("pinned profiles retain the other path for inspection and exclude it from eligible reserve", () => {
|
||||
const profile = routeAiProfileSchema.parse({
|
||||
name: "pinned", community: "65000:1", family: "ipv4", serverId: 1, pinnedCandidateId: "a",
|
||||
candidates: [{ ...first, wanRemoteInterface: "wan-up", downstreamRemoteInterface: "wg-remote" }, second],
|
||||
})
|
||||
const result = summarizePaths(routePaths(profile))
|
||||
assert.deepEqual(result.eligiblePathIds, ["a"])
|
||||
assert.deepEqual(result.sharedDomains, [])
|
||||
assert.deepEqual(result.paths[0].dependencies.slice(-2), [
|
||||
{ kind: "wan", serverId: 2, interfaceName: "wan-up" },
|
||||
{ kind: "tunnel", serverId: 3, interfaceName: "wg-remote" },
|
||||
])
|
||||
})
|
||||
|
||||
test("separate IX groups with a single eligible path do not form a reserve pair", () => {
|
||||
const profile = routeAiProfileSchema.parse({ name: "failover", community: "65000:1", family: "ipv4", serverId: 1, candidates: [first, second] })
|
||||
const paths = routePaths(profile).map((path, index) => ({ ...path, groupId: `${index + 2}/exit` }))
|
||||
assert.deepEqual(summarizePaths(paths).alternativeGroups, [
|
||||
{ groupId: "2/exit", eligiblePathIds: ["a"] },
|
||||
{ groupId: "3/exit", eligiblePathIds: ["b"] },
|
||||
])
|
||||
})
|
||||
|
||||
const time = (offset: number) => new Date(Date.UTC(2026, 0, 1, 0, 0, 0, offset)).toISOString()
|
||||
const request = {
|
||||
target: { kind: "route-ai" as const, profileId: "1551445f-7c71-4411-976f-ce30302dcefe" },
|
||||
window: { from: time(0), outageAt: time(3000), restoreAt: time(10000), to: time(20000) },
|
||||
controlProbe: { primaryCandidateId: "a", backupCandidateId: "b" },
|
||||
targetFailoverMs: 1000, targetFailbackMs: 1000,
|
||||
}
|
||||
const probe = (candidateId: string, status: "passed" | "failed" | "unknown", begin: number, end: number) => ({
|
||||
id: candidateId + begin, candidateId, status, startedAt: time(begin), observedAt: time(end),
|
||||
})
|
||||
const baseline = probe("a", "passed", 2500, 2700)
|
||||
const failure = probe("a", "failed", 3100, 3300)
|
||||
const recovered = probe("a", "passed", 10100, 10500)
|
||||
|
||||
test("report passes each probe deadline and leaves HTTPS, SSH and existing connections unverified", () => {
|
||||
const result = assessFailover(request, [baseline, failure, probe("b", "failed", 3100, 3400), probe("b", "passed", 3500, 3800), recovered])
|
||||
assert.equal(result.status, "passed")
|
||||
assert.equal(result.failover.lowerBoundMs, 100)
|
||||
assert.equal(result.failover.upperBoundMs, 800)
|
||||
assert.equal(result.failover.firstGood?.id, "b3500")
|
||||
assert.equal(result.failback.upperBoundMs, 500)
|
||||
assert.equal(result.https, "inconclusive")
|
||||
assert.equal(result.serviceFailover, "inconclusive")
|
||||
assert.equal(result.existingConnections, "inconclusive")
|
||||
assert.equal(result.managementSsh, "inconclusive")
|
||||
assert.equal(result.returnPathVerified, false)
|
||||
})
|
||||
|
||||
test("report fails when the latest definitive failed probe started after the deadline", () => {
|
||||
const result = assessFailover(request, [baseline, failure, probe("b", "failed", 4500, 4700), probe("b", "passed", 4800, 5000), recovered])
|
||||
assert.equal(result.status, "failed")
|
||||
assert.equal(result.failover.lowerBoundMs, 1500)
|
||||
assert.equal(result.failover.upperBoundMs, 2000)
|
||||
assert.equal(result.failover.lastBad?.id, "b4500")
|
||||
})
|
||||
|
||||
test("late first success, unknown evidence, flap, or truncated history cannot establish success", () => {
|
||||
const history = [baseline, failure, recovered]
|
||||
assert.equal(assessFailover(request, [...history, probe("b", "passed", 4500, 4700)]).status, "inconclusive")
|
||||
assert.equal(assessFailover(request, [...history, probe("b", "unknown", 4500, 4700)]).status, "inconclusive")
|
||||
const pass = probe("b", "passed", 3500, 3700)
|
||||
assert.equal(assessFailover(request, [...history, pass, probe("b", "failed", 3800, 4000)]).status, "inconclusive")
|
||||
assert.equal(assessFailover(request, [...history, pass], true).status, "inconclusive")
|
||||
assert.equal(assessFailover(request, [baseline, probe("a", "unknown", 3100, 3300), recovered, pass]).status, "inconclusive")
|
||||
})
|
||||
@@ -0,0 +1,352 @@
|
||||
import { z } from "zod"
|
||||
import { routeAiProfileSchema, type RouteAiProfile } from "@mmapp/contracts/mcp-routing"
|
||||
import type { IxSegment } from "@mmapp/contracts/internet-exchange"
|
||||
import { pool } from "../../db/index.js"
|
||||
import { ixDeviceIds } from "../../services/internet-exchange-plan.js"
|
||||
import { readIxRevision, readIxSegment } from "../../services/internet-exchange-store.js"
|
||||
import type { add } from "./actions.js"
|
||||
import type { ActionContext } from "./action-types.js"
|
||||
import { PATH_PROOF_VERSION, pathProofTag } from "./path-proof-purpose.js"
|
||||
import { constantEqual, fingerprint, McpError, privateFingerprinterExisting } from "./security.js"
|
||||
|
||||
const siteId = z.number().int().positive().safe()
|
||||
const name = z.string().trim().min(1).max(100)
|
||||
const targetSchema = z.discriminatedUnion("kind", [
|
||||
z.object({ kind: z.literal("route-ai"), profileId: z.uuid() }).strict(),
|
||||
z.object({ kind: z.literal("ix-segment"), segmentId: z.uuid() }).strict(),
|
||||
z.object({ kind: z.literal("ix-client"), segmentId: z.uuid(), serverId: siteId, interfaceName: z.string().regex(/^[A-Za-z0-9_.-]{1,48}$/) }).strict(),
|
||||
])
|
||||
const topologyArgs = z.object({ target: targetSchema }).strict()
|
||||
const serviceEndpoint = z.object({
|
||||
serverId: siteId.optional(), interfaceName: z.string().regex(/^[A-Za-z0-9_.-]{1,48}$/).optional(),
|
||||
address: z.union([z.ipv4(), z.ipv6()]).optional(),
|
||||
}).strict().refine(endpoint => endpoint.serverId !== undefined || endpoint.address !== undefined)
|
||||
const designArgs = topologyArgs.extend({
|
||||
scenario: z.enum(["wan", "jump-host", "exit", "tunnel", "return", "flap"]),
|
||||
offset: z.number().int().min(0).max(1000).default(0),
|
||||
limit: z.number().int().min(1).max(25).default(10),
|
||||
protectedService: z.object({
|
||||
name, source: serviceEndpoint.optional(), destination: serviceEndpoint.optional(),
|
||||
maxInterruptionMs: z.number().int().min(1).max(3600000).optional(),
|
||||
}).strict().optional(),
|
||||
})
|
||||
const timestamp = z.iso.datetime({ offset: true })
|
||||
const reportArgs = topologyArgs.extend({
|
||||
controlProbe: z.object({ primaryCandidateId: name, backupCandidateId: name }).strict().optional(),
|
||||
window: z.object({ from: timestamp, outageAt: timestamp, restoreAt: timestamp, to: timestamp }).strict(),
|
||||
targetFailoverMs: z.number().int().min(1).max(3600000),
|
||||
targetFailbackMs: z.number().int().min(1).max(3600000),
|
||||
})
|
||||
|
||||
type Target = z.infer<typeof targetSchema>
|
||||
type ReportArgs = z.infer<typeof reportArgs>
|
||||
type Domain = { kind: "source" | "wan" | "jump-host" | "exit" | "tunnel" | "peer"; serverId: number; interfaceName?: string }
|
||||
type Path = { id: string; groupId: string; eligible: boolean; dependencies: Domain[] }
|
||||
type Source = { target: Target; serverIds: number[] } & (
|
||||
{ kind: "route-ai"; profile: RouteAiProfile; revision: number } |
|
||||
{ kind: "ix"; segment: IxSegment; paths: Path[] }
|
||||
)
|
||||
|
||||
export function routePaths(profile: RouteAiProfile): Path[] {
|
||||
return profile.candidates.map(candidate => ({
|
||||
id: candidate.id,
|
||||
groupId: "route-ai",
|
||||
eligible: !profile.excludedCandidateIds.includes(candidate.id) &&
|
||||
(profile.pinnedCandidateId === null || profile.pinnedCandidateId === candidate.id),
|
||||
dependencies: [
|
||||
{ kind: "source", serverId: profile.serverId },
|
||||
{ kind: "wan", serverId: profile.serverId, interfaceName: candidate.wanInterface },
|
||||
{ kind: "jump-host", serverId: candidate.jumpHostId },
|
||||
{ kind: "exit", serverId: candidate.exitNodeId },
|
||||
{ kind: "tunnel", serverId: candidate.jumpHostId, interfaceName: candidate.downstreamInterface },
|
||||
...(candidate.wanRemoteInterface ? [{ kind: "wan" as const, serverId: candidate.jumpHostId, interfaceName: candidate.wanRemoteInterface }] : []),
|
||||
...(candidate.downstreamRemoteInterface ? [{ kind: "tunnel" as const, serverId: candidate.exitNodeId, interfaceName: candidate.downstreamRemoteInterface }] : []),
|
||||
],
|
||||
}))
|
||||
}
|
||||
|
||||
export function summarizePaths(paths: Path[]) {
|
||||
const domains = new Map<string, { domain: Domain; pathIds: Set<string> }>()
|
||||
const eligibleGroups = new Map<string, string[]>()
|
||||
for (const path of paths.filter(path => path.eligible)) {
|
||||
const alternatives = eligibleGroups.get(path.groupId) ?? []
|
||||
alternatives.push(path.id)
|
||||
eligibleGroups.set(path.groupId, alternatives)
|
||||
for (const domain of path.dependencies) {
|
||||
const key = domain.kind === "wan" || domain.kind === "tunnel"
|
||||
? JSON.stringify([domain.serverId, domain.interfaceName])
|
||||
: JSON.stringify([domain.serverId])
|
||||
const record = domains.get(key) ?? { domain, pathIds: new Set<string>() }
|
||||
record.pathIds.add(path.id)
|
||||
domains.set(key, record)
|
||||
}
|
||||
}
|
||||
return {
|
||||
paths,
|
||||
eligiblePathIds: paths.filter(path => path.eligible).map(path => path.id),
|
||||
alternativeGroups: [...eligibleGroups].map(([groupId, eligiblePathIds]) => ({ groupId, eligiblePathIds })),
|
||||
sharedDomains: [...domains.values()].filter(value => value.pathIds.size > 1).map(value => ({
|
||||
...value.domain, pathIds: [...value.pathIds],
|
||||
})),
|
||||
unknownDomains: ["physical-uplink", "carrier", "power", "facility", "management", "return-path"],
|
||||
physicalIndependenceVerified: false,
|
||||
}
|
||||
}
|
||||
|
||||
function ixPaths(segment: IxSegment, target: Extract<Target, { kind: "ix-segment" | "ix-client" }>): Path[] {
|
||||
const paths: Path[] = []
|
||||
let bindingFound = false
|
||||
for (const site of segment.configuration.sites) {
|
||||
const client = target.kind === "ix-client" && target.serverId === site.serverId
|
||||
? site.interfaces.find(binding => binding.name === target.interfaceName && binding.linux)
|
||||
: undefined
|
||||
if (target.kind === "ix-client" && !client) continue
|
||||
if (client) bindingFound = true
|
||||
const selectedExits = client?.linux?.exit ? [client.linux.exit] : site.exits
|
||||
for (const group of site.groups) {
|
||||
if (client && !selectedExits.includes(group.id)) continue
|
||||
for (const role of ["primary", "backup"] as const) {
|
||||
const path = group[role]
|
||||
if (!path) continue
|
||||
const binding = site.interfaces.find(item => item.name === path.interface)
|
||||
const remote = binding?.peerServerId
|
||||
const dependencies: Domain[] = [
|
||||
{ kind: "source", serverId: site.serverId },
|
||||
{ kind: path.viaMain || binding?.kind === "uplink" ? "wan" : "tunnel", serverId: site.serverId, interfaceName: path.interface },
|
||||
]
|
||||
if (client) dependencies.push({ kind: "tunnel", serverId: site.serverId, interfaceName: client.name })
|
||||
if (remote !== undefined) {
|
||||
dependencies.push({ kind: selectedExits.includes(group.id) ? "exit" : "peer", serverId: remote })
|
||||
const remoteWan = binding?.provisionTransit?.remoteWan.interface
|
||||
if (remoteWan) dependencies.push({ kind: "wan", serverId: remote, interfaceName: remoteWan })
|
||||
}
|
||||
paths.push({
|
||||
id: `${site.serverId}/${group.id}/${role}`,
|
||||
groupId: `${site.serverId}/${group.id}`,
|
||||
eligible: client?.linux?.enabled ?? true,
|
||||
dependencies,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
if (target.kind === "ix-client" && !bindingFound) throw new McpError("NOT_FOUND", "Подключение IX не найдено", 404)
|
||||
return paths
|
||||
}
|
||||
|
||||
async function resolve(target: Target, context: ActionContext): Promise<Source> {
|
||||
const allowed = context.connection.policy.scope.serverIds
|
||||
const inScope = (ids: number[]) => ids.every(id => allowed.includes(id))
|
||||
if (target.kind === "route-ai") {
|
||||
const { rows: [row] } = await (context.transactionClient ?? pool).query(
|
||||
"SELECT version,config FROM mcp_routing_profiles WHERE id=$1 AND connection_id=$2",
|
||||
[target.profileId, context.connection.id],
|
||||
)
|
||||
if (!row) throw new McpError("NOT_FOUND", "Профиль Route AI не найден", 404)
|
||||
const profile = routeAiProfileSchema.parse(row.config)
|
||||
const serverIds = [...new Set([profile.serverId, ...profile.candidates.flatMap(candidate => [candidate.jumpHostId, candidate.exitNodeId])])]
|
||||
if (!inScope(serverIds)) throw new McpError("NOT_FOUND", "Профиль Route AI не найден", 404)
|
||||
return { kind: target.kind, target, profile, serverIds, revision: row.version }
|
||||
}
|
||||
|
||||
const segment = await readIxSegment(target.segmentId, context.transactionClient)
|
||||
if (!segment || !inScope(ixDeviceIds(segment.configuration))) throw new McpError("NOT_FOUND", "Сегмент IX не найден", 404)
|
||||
const applied = segment.appliedRevision !== null && segment.appliedRevision !== segment.revision
|
||||
? await readIxRevision(segment.id, segment.appliedRevision)
|
||||
: null
|
||||
const serverIds = [...new Set([...ixDeviceIds(segment.configuration), ...(applied ? ixDeviceIds(applied) : [])])]
|
||||
if (!inScope(serverIds)) throw new McpError("NOT_FOUND", "Сегмент IX не найден", 404)
|
||||
return { kind: "ix", target, segment, serverIds, paths: ixPaths(segment, target) }
|
||||
}
|
||||
|
||||
function topology(source: Source) {
|
||||
const { target, serverIds } = source
|
||||
const details = source.kind === "route-ai"
|
||||
? { source: "saved-route-ai-profile", revision: source.revision, pinnedCandidateId: source.profile.pinnedCandidateId }
|
||||
: { source: "saved-ix-configuration", revision: source.segment.revision, appliedRevision: source.segment.appliedRevision }
|
||||
return { target, serverIds, ...details, ...summarizePaths(source.kind === "route-ai" ? routePaths(source.profile) : source.paths) }
|
||||
}
|
||||
|
||||
const design = {
|
||||
wan: { tools: ["mm_server_wan_runtime_get", "mm_recursive_routes_get", "mm_recursive_routes_replace_plan"], criteria: "Разные WAN и next hop, с проверкой физической независимости линий." },
|
||||
"jump-host": { tools: ["mm_route_optimizer_analyze", "mm_ospf_application_preview"], criteria: "Разнести транзит по разным узлам и проверить общие зависимости кандидатов." },
|
||||
exit: { tools: ["mm_route_optimizer_analyze", "mm_bgp_sessions_get", "mm_ecmp_plan"], criteria: "Проверить независимость выходов, NAT, анонсы и доступность префиксов со стороны назначения." },
|
||||
tunnel: { tools: ["mm_wireguard_state_get", "mm_ospf_state_get", "mm_recursive_routes_get"], criteria: "Проверить тоннели, выбранный маршрут и детектирование отказа подложки." },
|
||||
return: { tools: ["mm_route_optimizer_analyze", "mm_route_path_verify"], criteria: "Проверить предпочтительный путь после восстановления, обратное направление и сохранение доступа управления вне переключаемого пути." },
|
||||
flap: { tools: ["mm_route_controller_get", "mm_route_profile_save_plan"], criteria: "Сопоставить интервалы наблюдений, подтверждения, гистерезис, cooldown и бюджет переключений с допустимым временем восстановления." },
|
||||
} as const
|
||||
|
||||
function scenarioFailures(paths: Path[], scenario: keyof typeof design) {
|
||||
if (scenario === "return" || scenario === "flap") return []
|
||||
const eligible = paths.filter(path => path.eligible)
|
||||
const failures = new Map<string, { groupId: string; domain: Domain }>()
|
||||
for (const path of eligible) {
|
||||
for (const domain of path.dependencies.filter(domain => domain.kind === scenario)) {
|
||||
failures.set(JSON.stringify([path.groupId, domain.serverId, domain.interfaceName]), { groupId: path.groupId, domain })
|
||||
}
|
||||
}
|
||||
return [...failures.values()].map(({ groupId, domain }) => ({
|
||||
groupId, domain,
|
||||
remainingEligiblePathIds: eligible.filter(path => path.groupId === groupId && !path.dependencies.some(dependency =>
|
||||
dependency.serverId === domain.serverId &&
|
||||
(domain.interfaceName === undefined || dependency.interfaceName === domain.interfaceName),
|
||||
)).map(path => path.id),
|
||||
}))
|
||||
}
|
||||
|
||||
type Observation = { id: string; candidateId: string; status: "passed" | "failed" | "unknown"; startedAt: string; observedAt: string }
|
||||
type PhaseStatus = "passed" | "failed" | "inconclusive"
|
||||
const at = (date: string) => Date.parse(date)
|
||||
|
||||
function phase(observations: Observation[], start: number, end: number, targetMs: number, goodAfter = start) {
|
||||
const samples = observations.filter(row => at(row.startedAt) >= start && at(row.observedAt) <= end)
|
||||
.sort((left, right) => at(left.observedAt) - at(right.observedAt))
|
||||
const firstGood = samples.find(row => row.status === "passed" && at(row.startedAt) >= goodAfter)
|
||||
const lastBad = samples.filter(row => row.status === "failed" && (!firstGood || at(row.observedAt) <= at(firstGood.startedAt))).at(-1)
|
||||
const subsequentFailure = firstGood && samples.find(row => row.status === "failed" && at(row.startedAt) >= at(firstGood.observedAt))
|
||||
const lowerBoundMs = (lastBad ? at(lastBad.startedAt) : start) - start
|
||||
const upperBoundMs = firstGood ? at(firstGood.observedAt) - start : null
|
||||
const ambiguous = firstGood && samples.some(row => row.status === "failed" &&
|
||||
at(row.startedAt) < at(firstGood.observedAt) && at(row.observedAt) > at(firstGood.startedAt))
|
||||
const status: PhaseStatus = ambiguous || subsequentFailure ? "inconclusive"
|
||||
: upperBoundMs !== null && upperBoundMs <= targetMs ? "passed"
|
||||
: lowerBoundMs > targetMs ? "failed" : "inconclusive"
|
||||
return { status, lowerBoundMs, upperBoundMs, targetMs, firstGood: firstGood ?? null, lastBad: lastBad ?? null, subsequentFailure: subsequentFailure ?? null }
|
||||
}
|
||||
|
||||
export function assessFailover(input: ReportArgs, observations: Observation[], truncated = false) {
|
||||
const { window, controlProbe } = input
|
||||
const ordered = [...observations].sort((left, right) => at(left.observedAt) - at(right.observedAt))
|
||||
const primary = ordered.filter(row => row.candidateId === controlProbe?.primaryCandidateId)
|
||||
const backup = ordered.filter(row => row.candidateId === controlProbe?.backupCandidateId)
|
||||
const outage = at(window.outageAt), restore = at(window.restoreAt)
|
||||
const latestBaseline = primary.filter(row => at(row.startedAt) >= at(window.from) && at(row.observedAt) < outage).at(-1)
|
||||
const baseline = latestBaseline?.status === "passed" ? latestBaseline : null
|
||||
const primaryFailure = primary.find(row => row.status === "failed" && at(row.startedAt) >= outage && at(row.observedAt) < restore) ?? null
|
||||
const failover = phase(backup, outage, restore - 1, input.targetFailoverMs, primaryFailure ? at(primaryFailure.observedAt) : restore)
|
||||
const failback = phase(primary, restore, at(window.to), input.targetFailbackMs)
|
||||
const status: PhaseStatus = truncated || !baseline || !primaryFailure ? "inconclusive"
|
||||
: [failover.status, failback.status].includes("failed") ? "failed"
|
||||
: failover.status === "passed" && failback.status === "passed" ? "passed" : "inconclusive"
|
||||
return {
|
||||
status, scope: "configured-control-probe-reachability", baseline, primaryFailure, failover, failback,
|
||||
restoredPath: failback.firstGood ? "control-probe-observed" : "inconclusive",
|
||||
serviceFailover: "inconclusive", https: "inconclusive", existingConnections: "inconclusive", managementSsh: "inconclusive",
|
||||
forwardingSelectionVerified: false, returnPathVerified: false, truncated,
|
||||
}
|
||||
}
|
||||
|
||||
const savedObservation = z.object({
|
||||
id: z.uuid(), connectionId: z.uuid(), profileHash: z.string(), candidateId: name,
|
||||
proofPurpose: z.literal("control-path"), proofVersion: z.literal(PATH_PROOF_VERSION),
|
||||
dependencyProof: z.string().regex(/^[a-f0-9]{64}$/), status: z.enum(["passed", "failed", "unknown"]), startedAt: timestamp, observedAt: timestamp,
|
||||
sourceProofs: z.array(z.object({ serverId: siteId, proof: z.string().regex(/^[a-f0-9]{64}$/) }).strict()).min(1).max(3),
|
||||
})
|
||||
|
||||
async function report(input: ReportArgs, source: Source, context: ActionContext) {
|
||||
const { window, controlProbe } = input
|
||||
const from = at(window.from), outage = at(window.outageAt), restore = at(window.restoreAt), to = at(window.to)
|
||||
if (!(from < outage && outage < restore && restore < to && to <= Date.now() && to - from <= 86400000)) {
|
||||
throw new McpError("INVALID_INPUT", "Окно должно быть завершено, не длиннее 24 часов и включать фазы до отказа, после отказа и после восстановления", 400)
|
||||
}
|
||||
if (source.kind !== "route-ai") return { ...assessFailover(input, []), target: input.target, window, reason: "NO_SAVED_IX_CONTROL_PROBE_HISTORY" }
|
||||
if (!controlProbe || controlProbe.primaryCandidateId === controlProbe.backupCandidateId ||
|
||||
![controlProbe.primaryCandidateId, controlProbe.backupCandidateId].every(id => source.profile.candidates.some(candidate => candidate.id === id && candidate.controlProbe))) {
|
||||
throw new McpError("INVALID_INPUT", "Выберите два разных кандидата с контрольной пробой из сохранённого профиля", 400)
|
||||
}
|
||||
const connectionId = context.connection.id
|
||||
const profileHash = fingerprint(source.profile)
|
||||
const { rows } = await pool.query<{ id: string; candidate_id: string; status: string; evidence: Record<string, unknown> | null }>(
|
||||
`SELECT id,candidate_id,status,CASE WHEN octet_length(evidence::text)<=32768 THEN evidence END AS evidence FROM mcp_path_checks
|
||||
WHERE connection_id=$1 AND profile_hash=$2 AND candidate_id=ANY($3::text[])
|
||||
AND created_at >= $4::timestamptz AND created_at <= $5::timestamptz
|
||||
AND evidence->>'proofPurpose' IS DISTINCT FROM 'community'
|
||||
ORDER BY created_at,id LIMIT 501`,
|
||||
[connectionId, profileHash, [controlProbe.primaryCandidateId, controlProbe.backupCandidateId], window.from, window.to],
|
||||
)
|
||||
const sign = rows.length ? await privateFingerprinterExisting("route-control-path-context-v1").catch(error => {
|
||||
if (error instanceof McpError && error.code === "STATE_UNAVAILABLE") return null
|
||||
throw error
|
||||
}) : null
|
||||
const observations: Observation[] = []
|
||||
const sourceProofs = new Map<number, string>()
|
||||
let evidenceError: "INVALID_CONTROL_PATH_EVIDENCE" | "SOURCE_IDENTITY_CHANGED" | null = null
|
||||
for (const row of rows.slice(0, 500)) {
|
||||
const { proof, ...payload } = row.evidence ?? {}
|
||||
const parsed = savedObservation.safeParse(payload)
|
||||
if (!parsed.success || !sign || typeof proof !== "string") {
|
||||
evidenceError = "INVALID_CONTROL_PATH_EVIDENCE"
|
||||
break
|
||||
}
|
||||
const { id, status, candidateId, startedAt, observedAt, dependencyProof } = parsed.data
|
||||
const candidate = source.profile.candidates.find(candidate => candidate.id === candidateId)
|
||||
const expected = new Set([source.profile.serverId, candidate?.jumpHostId, candidate?.exitNodeId])
|
||||
const observed = new Set(parsed.data.sourceProofs.map(source => source.serverId))
|
||||
if (id !== row.id || status !== row.status || candidateId !== row.candidate_id ||
|
||||
parsed.data.connectionId !== connectionId || parsed.data.profileHash !== profileHash ||
|
||||
at(startedAt) > at(observedAt) || observed.size !== parsed.data.sourceProofs.length ||
|
||||
expected.size !== observed.size || ![...expected].every(id => id !== undefined && observed.has(id)) ||
|
||||
!constantEqual(sign(pathProofTag("control-path") + fingerprint({ dependencyProof, value: payload })), proof)) {
|
||||
evidenceError = "INVALID_CONTROL_PATH_EVIDENCE"
|
||||
break
|
||||
}
|
||||
if (at(startedAt) < from || at(observedAt) > to) continue
|
||||
for (const source of parsed.data.sourceProofs) {
|
||||
if (sourceProofs.has(source.serverId) && sourceProofs.get(source.serverId) !== source.proof) evidenceError = "SOURCE_IDENTITY_CHANGED"
|
||||
sourceProofs.set(source.serverId, source.proof)
|
||||
}
|
||||
observations.push({ id, status, candidateId, startedAt, observedAt })
|
||||
}
|
||||
const result = assessFailover(input, evidenceError ? [] : observations, rows.length > 500)
|
||||
const eligible = routePaths(source.profile).filter(path => path.eligible).map(path => path.id)
|
||||
const reason = rows.length && !sign ? "PROOF_KEY_UNAVAILABLE" : evidenceError ?? (
|
||||
!eligible.includes(controlProbe.primaryCandidateId) || !eligible.includes(controlProbe.backupCandidateId) ? "CANDIDATE_UNAVAILABLE_IN_PROFILE" : null)
|
||||
return { target: input.target, window, controlProbe, ...result,
|
||||
...(reason ? { status: "inconclusive" as const, reason } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export function registerResilienceActions(register: typeof add) {
|
||||
const target = async (input: Record<string, unknown>, context: ActionContext) => ({
|
||||
scope: "servers" as const, serverIds: (await resolve(targetSchema.parse(input.target), context)).serverIds,
|
||||
})
|
||||
register("network.resilience.topology.read", "mm_resilience_topology_get", "Зависимости путей и общие домены отказа", "network", "mm:network:read", "read", "servers", topologyArgs, {
|
||||
target,
|
||||
read: async (input, context) => topology(await resolve(topologyArgs.parse(input).target, context)),
|
||||
})
|
||||
register("network.resilience.design.read", "mm_resilience_design_preview", "Предпросмотр резервирования по сценарию отказа", "network", "mm:network:read", "read", "servers", designArgs, {
|
||||
target,
|
||||
read: async (input, context) => {
|
||||
const args = designArgs.parse(input)
|
||||
const source = await resolve(args.target, context)
|
||||
const serviceServers = [args.protectedService?.source?.serverId, args.protectedService?.destination?.serverId]
|
||||
if (serviceServers.some(id => id !== undefined && !source.serverIds.includes(id))) {
|
||||
throw new McpError("INVALID_INPUT", "Устройство защищаемого сервиса вне выбранной топологии", 400)
|
||||
}
|
||||
const observed = topology(source)
|
||||
const proposal = design[args.scenario]
|
||||
const failures = scenarioFailures(observed.paths, args.scenario)
|
||||
const tools = source.kind === "ix"
|
||||
? ["mm_ix_segment_get", "mm_ix_change_plan", ...(args.target.kind === "ix-client" ? ["mm_ix_linux_path_get"] : []),
|
||||
...proposal.tools.filter(tool => !tool.startsWith("mm_route_") && !tool.endsWith("_plan"))]
|
||||
: [...proposal.tools]
|
||||
return {
|
||||
target: args.target, scenario: args.scenario, protectedService: args.protectedService ?? null,
|
||||
criteria: proposal.criteria, suggestedTools: tools,
|
||||
eligiblePathIds: observed.eligiblePathIds, alternativeGroups: observed.alternativeGroups,
|
||||
configuredReserve: observed.alternativeGroups.some(group => group.eligiblePathIds.length > 1),
|
||||
configuredPathsAfterFailure: failures.slice(args.offset, args.offset + args.limit),
|
||||
nextOffset: args.offset + args.limit < failures.length ? args.offset + args.limit : null,
|
||||
sharedDomains: observed.sharedDomains, unknownDomains: observed.unknownDomains,
|
||||
missingEvidence: ["usable-capacity", "path-mtu", "return-path", "service-interruption", "management-reachability"],
|
||||
requiredChecks: ["Отдельная проверка активного маршрута и обратного направления", "Непрерывность HTTPS, действующих соединений и независимого SSH-управления по отдельным измерениям"],
|
||||
}
|
||||
},
|
||||
})
|
||||
register("network.resilience.failover.read", "mm_failover_report_get", "Оценка failover и failback по сохранённым контрольным пробам", "network", "mm:network:read", "read", "servers", reportArgs, {
|
||||
target,
|
||||
read: async (input, context) => {
|
||||
const args = reportArgs.parse(input)
|
||||
return report(args, await resolve(args.target, context), context)
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -85,6 +85,17 @@ const firewall = {
|
||||
"src-address-list": text.optional(), "dst-address-list": text.optional(), "connection-state": text.optional(),
|
||||
comment: text.optional(), disabled: bool.optional(), log: bool.optional(), "log-prefix": text.optional(),
|
||||
}
|
||||
const ipv4Mangle = {
|
||||
...firewall,
|
||||
"tcp-flags": z.string().regex(/^!?(?:ack|cwr|ece|fin|psh|rst|syn|urg)(?:,!?(?:ack|cwr|ece|fin|psh|rst|syn|urg)){0,7}$/)
|
||||
.refine(value => new Set(value.replaceAll("!", "").split(",")).size === value.split(",").length, "Флаги TCP не должны повторяться").optional(),
|
||||
"tcp-mss": z.string().regex(/^(?:0|[1-9]\d{0,4})(?:-(?:0|[1-9]\d{0,4}))?$/).refine(value => {
|
||||
const [min, max = min] = value.split("-").map(Number)
|
||||
return min <= max && max <= 65535
|
||||
}, "Требуется значение или диапазон TCP MSS от 0 до 65535").optional(),
|
||||
"new-mss": integer(1, 65535).optional(),
|
||||
passthrough: bool.optional(),
|
||||
}
|
||||
const route = {
|
||||
"dst-address": name.optional(), gateway: name.optional(), distance: integer(1, 255).optional(), scope: integer(0, 255).optional(),
|
||||
"target-scope": integer(0, 255).optional(), "routing-table": name.optional(), "check-gateway": z.enum(["none", "ping", "arp", "bfd"]).optional(),
|
||||
@@ -112,7 +123,7 @@ export const rosResources: RosResourceSpec[] = [
|
||||
{ id: "vrf", path: "/ip/vrf", title: "VRF", permission: "mm:network", fields: z.object({ name: name.optional(), interfaces: text.optional(), disabled: bool.optional(), comment: text.optional() }).strict(), create: true, remove: true, requiredOnCreate: ["name", "interfaces"] },
|
||||
{ id: "ip_settings", path: "/ip/settings", title: "RPF и IPv4 hash-policy", permission: "mm:network", fields: z.object({ "rp-filter": z.enum(["no", "loose", "strict"]).optional(), "ipv4-multipath-hash-policy": z.enum(["l3", "l4", "l3-inner"]).optional() }).strict(), create: false, remove: false },
|
||||
{ id: "ipv6_settings", path: "/ipv6/settings", title: "IPv6 hash-policy", permission: "mm:network", fields: z.object({ "multipath-hash-policy": z.enum(["l3", "l4", "l3-inner"]).optional() }).strict(), create: false, remove: false },
|
||||
...(["ip", "ipv6"] as const).flatMap(family => (["filter", "nat", "mangle", "raw"] as const).map(table => ({ id: `${family}_${table}`, path: `/${family}/firewall/${table}`, title: `${family} firewall ${table}`, permission: "mm:network", fields: z.object(firewall).strict(), create: true, remove: true, requiredOnCreate: ["chain", "action"] }))),
|
||||
...(["ip", "ipv6"] as const).flatMap(family => (["filter", "nat", "mangle", "raw"] as const).map(table => ({ id: `${family}_${table}`, path: `/${family}/firewall/${table}`, title: `${family} firewall ${table}`, permission: "mm:network", fields: z.object(family === "ip" && table === "mangle" ? ipv4Mangle : firewall).strict(), create: true, remove: true, requiredOnCreate: ["chain", "action"] }))),
|
||||
{ id: "gre", path: "/interface/gre", title: "GRE", permission: "mm:network", fields: greNativeFieldsSchema, create: true, remove: true, requiredOnCreate: ["name", "remote-address"] },
|
||||
{ id: "wireguard", path: "/interface/wireguard", title: "WireGuard", permission: "mm:network", fields: z.object({ ...common, "listen-port": integer(1, 65535).optional(), mtu: integer(68, 65535).optional() }).strict(), create: true, remove: true, requiredOnCreate: ["name"] },
|
||||
{ id: "wireguard_peer", path: "/interface/wireguard/peers", title: "WireGuard peers", permission: "mm:network", fields: z.object({ interface: name.optional(), "public-key": name.optional(), "allowed-address": text.optional(), "endpoint-address": text.optional(), "endpoint-port": integer(0, 65535).optional(), "persistent-keepalive": text.optional(), disabled: bool.optional(), comment: text.optional() }).strict(), create: true, remove: true, requiredOnCreate: ["interface", "public-key", "allowed-address"] },
|
||||
@@ -154,7 +165,7 @@ export function supportsRosPlacement(step: Pick<RosStep, "resource" | "action" |
|
||||
export const ROS_SNAPSHOT_VERSION = 3
|
||||
// OSPF cost plans and archived inverses issued before prefix-list evidence cannot be reused.
|
||||
export const isSingletonRosResource = (resource: string) => ["ip_settings", "ipv6_settings", "ipv6_nd_settings"].includes(resource)
|
||||
export const rosSnapshotVersion = (resource: string): number => resource === "ospf_template" ? 10 : resource === "bfd_configuration" ? 7 : ["bridge", "bridge_port", "bridge_vlan", "routing_table", "ip_settings", "ipv6_settings", "ospf_instance", "ipv6_nd"].includes(resource) ? 4 : ROS_SNAPSHOT_VERSION
|
||||
export const rosSnapshotVersion = (resource: string): number => resource === "ospf_template" ? 10 : resource === "bfd_configuration" ? 7 : ["bridge", "bridge_port", "bridge_vlan", "routing_table", "ip_settings", "ipv6_settings", "ospf_instance", "ipv6_nd", "ip_mangle"].includes(resource) ? 4 : ROS_SNAPSHOT_VERSION
|
||||
export interface RosSnapshot { serverId: number; resource: string; rows: ConfigurationRow[]; fingerprint: string; projectionVersion?: number; sourceProof?: string }
|
||||
const firewallAddressListResources = ["ip_address_list", "ipv6_address_list"]
|
||||
const routingPolicyResources = new Set(["routing_rule", "routing_filter", "routing_filter_select", "bfd_configuration", ...firewallAddressListResources, "ip_filter", "ip_nat", "ip_mangle", "ip_raw", "ipv6_filter", "ipv6_nat", "ipv6_mangle", "ipv6_raw"])
|
||||
@@ -370,7 +381,7 @@ export function validateRosStep(resource: RosResourceSpec, action: RosStep["acti
|
||||
const parsed = resource.fields.parse(fields ?? {}) as Record<string, unknown>
|
||||
if (action === "create" && resource.requiredOnCreate?.some(field => parsed[field] === undefined)) throw new McpError("INVALID_INPUT", "Не заполнены обязательные поля создания", 400)
|
||||
if (resource.id === "bfd_configuration" && action === "create") {
|
||||
if (!parsed.interfaces && !parsed["address-list"]) throw new McpError("INVALID_INPUT", "Для правила BFD укажите интерфейсы или address-list", 400)
|
||||
if (!parsed.interfaces && !parsed.addresses && !parsed["address-list"]) throw new McpError("INVALID_INPUT", "Для правила BFD укажите interfaces, addresses или address-list", 400)
|
||||
if (parsed.interfaces && parsed.addresses === undefined && String(parsed.interfaces).split(",").some(value => !value.trim() || /^(?:all|none)$/i.test(value.trim()))) {
|
||||
throw new McpError("INVALID_INPUT", "Для правила BFD без адреса укажите конкретные интерфейсы", 400)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { configurationRows, isOrderedRosResource, resourceById, rosSnapshotVersion, splitOspfUnsetUpdate, type ConfigurationRow, type RosSnapshot, type RosStep } from "./resources.js"
|
||||
import { configurationRows, isOrderedRosResource, resourceById, rosSnapshotVersion, splitOspfUnsetUpdate, validateRosStep, type ConfigurationRow, type RosSnapshot, type RosStep } from "./resources.js"
|
||||
import { fingerprint } from "./security.js"
|
||||
import { proveRosDriftExpectation, verifyRosStepSnapshots } from "./ros-step-verification.js"
|
||||
import { readOspfTemplateFlags } from "../../services/ospf-template-flags.js"
|
||||
@@ -24,6 +24,26 @@ assert.equal(check(create, ack, [a, b], [a, b, { ...c, action: "drop" }]), false
|
||||
assert.equal(check(create, undefined, [a], [a, c]), false, "Observed object never substitutes a lost acknowledgement")
|
||||
assert.equal(check({ ...create, id: "*A" }, ack, [a], [a, c]), false)
|
||||
|
||||
const mangle = resourceById("ip_mangle")
|
||||
const mssFields = {
|
||||
chain: "forward", "out-interface": "gre-ix", "dst-address": "192.0.2.2/32", protocol: "tcp",
|
||||
"tcp-flags": "syn,ack", "tcp-mss": "1381-65535", action: "change-mss", "new-mss": 1380, passthrough: true,
|
||||
}
|
||||
const mss = { ...create, resource: mangle.id, fields: validateRosStep(mangle, "create", mssFields) }
|
||||
const liveMss = { ...mss.fields, ".id": "*C", "dst-address": "192.0.2.2", "tcp-flags": "ack,syn", passthrough: "yes", packets: "3" }
|
||||
const mangleRows = (rows: ConfigurationRow[]) => configurationRows(mangle, rows)
|
||||
assert.equal(check(mss, ack, [], mangleRows([liveMss])), true)
|
||||
assert.equal(check(mss, ack, [], mangleRows([{ ...liveMss, "new-mss": "1460" }])), false)
|
||||
assert.equal(check(mss, ack, [], mangleRows([{ ...liveMss, "dst-address": "192.0.2.2/24" }])), false)
|
||||
assert.equal(check(mss, ack, [], mangleRows([{ ...liveMss, "tcp-flags": "syn,!ack" }])), false)
|
||||
const mssUpdate = { ...mss, action: "update" as const, id: "*C", fields: validateRosStep(mangle, "update", { "new-mss": 1360 }, "*C") }
|
||||
assert.equal(check(mssUpdate, {}, mangleRows([liveMss]), mangleRows([{ ...liveMss, "new-mss": "1360" }])), true)
|
||||
assert.equal(check(mssUpdate, {}, mangleRows([liveMss]), mangleRows([{ ...liveMss, "new-mss": "1360", "tcp-mss": "1361-65535" }])), false)
|
||||
for (const bad of [{ "new-mss": 65536 }, { "tcp-mss": "1400-1300" }, { "tcp-mss": "1-65536" }, { "tcp-flags": "syn,!syn" }, { passthrough: "yes" }]) {
|
||||
assert.throws(() => validateRosStep(mangle, "create", { ...mssFields, ...bad }))
|
||||
}
|
||||
assert.equal(resourceById("ip_filter").fields.safeParse(mssFields).success, false)
|
||||
|
||||
const update: RosStep = { ...create, action: "update", id: "*A", fields: { action: "accept" } }
|
||||
const updated = { ...a, action: "accept" }
|
||||
assert.equal(check(update, {}, [a, b], [updated, b]), true)
|
||||
|
||||
@@ -29,6 +29,10 @@ function requested(resource: RosResourceSpec, fields: RosStep["fields"], row: Co
|
||||
if (resource.id === "bridge_vlan" && ["vlan-ids", "tagged", "untagged"].includes(key)) {
|
||||
try { return canonicalBridgeVlanValue(key, row[key]) === canonicalBridgeVlanValue(key, value) } catch { return false }
|
||||
}
|
||||
if (resource.id === "ip_mangle") {
|
||||
if (key === "dst-address" || key === "src-address") return String(row[key]).replace(/\/32$/, "") === value.replace(/\/32$/, "")
|
||||
if (key === "tcp-flags" && schema.safeParse(row[key]).success) return String(row[key]).split(",").sort().join(",") === value.split(",").sort().join(",")
|
||||
}
|
||||
return String(row[key]) === value
|
||||
})
|
||||
}
|
||||
|
||||
@@ -10,9 +10,8 @@ test("registration exposes one actual global write plan and fixed nondiagnostic
|
||||
registerServerPollAction(((...args: Parameters<typeof add>) => { calls.push(args) }) as typeof add)
|
||||
assert.equal(calls.length, 1)
|
||||
const [id, tool, description, section, permission, effect, scope, schema, handlers] = calls[0]
|
||||
assert.match(description, /8 на владельца, 128 на приложение/)
|
||||
assert.match(description, /Архивирование сохраняет аудит/)
|
||||
assert.match(description, /pollStorageCapacity/)
|
||||
assert.doesNotMatch(description, /8 на владельца|128 на приложение/)
|
||||
assert.match(description, /pollStorageUsage/)
|
||||
assert.equal(mcpOperationDescriptorSchema.shape.title.safeParse(description).success, true)
|
||||
assert.equal(id, "servers.poll"); assert.equal(tool, "mm_server_poll_plan"); assert.equal(section, "servers")
|
||||
assert.equal(permission, "mm:servers:write"); assert.equal(effect, "write"); assert.equal(scope, "global"); assert.equal(handlers.version, 1)
|
||||
|
||||
@@ -3,12 +3,11 @@ import { SERVER_POLL_OPERATION } from "../../services/server-poll-authority.js"
|
||||
import { SERVER_POLL_MCP_OPERATION_VERSION } from "./server-poll-actions.js"
|
||||
import { createProductionServerPollMcpAdapter } from "./server-poll-production.js"
|
||||
import { registerMcpService } from "./service-registry.js"
|
||||
import { SERVER_POLL_STORAGE_POLICY } from "../../services/server-poll-storage-model.js"
|
||||
|
||||
/** Normal startup enrolls quota-bound storage before public tools are served. */
|
||||
/** Normal startup enrolls durable storage before public tools are served. */
|
||||
export function registerServerPollAction(register: typeof add) {
|
||||
const adapter = createProductionServerPollMcpAdapter()
|
||||
registerMcpService(SERVER_POLL_OPERATION, adapter.service)
|
||||
register(SERVER_POLL_OPERATION, "mm_server_poll_plan", `Полный опрос и история. Резерв: ${SERVER_POLL_STORAGE_POLICY.ownerAttempts} на владельца, ${SERVER_POLL_STORAGE_POLICY.globalAttempts} на приложение. Архивирование сохраняет аудит; остаток зависит от объёма истории. Статус: pollStorageCapacity в MCP overview.`, "servers", "mm:servers:write", "write", "global", adapter.schema,
|
||||
register(SERVER_POLL_OPERATION, "mm_server_poll_plan", "Полный опрос и история. Число журналов отображается в pollStorageUsage в MCP overview.", "servers", "mm:servers:write", "write", "global", adapter.schema,
|
||||
{ version: SERVER_POLL_MCP_OPERATION_VERSION, target: adapter.target, prepare: adapter.prepare })
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { z } from "zod"
|
||||
import { pool } from "../../db/index.js"
|
||||
import { hasPermission } from "../../lib/permissions.js"
|
||||
import { executeTerminalDiagnostic, terminalDiagnosticSchema, type TerminalDiagnosticClient } from "../../services/terminal-diagnostics.js"
|
||||
import { executeTerminalDiagnostic, readTerminalInterfaceCounters, terminalDiagnosticNames, terminalDiagnosticSchema, terminalInterfaceCountersSchema, type TerminalDiagnosticClient } from "../../services/terminal-diagnostics.js"
|
||||
import { withTerminalDiagnosticClient } from "../../services/terminal-diagnostic-client.js"
|
||||
import { readRoutingEndpoints } from "./routing-observation-source.js"
|
||||
import { effectiveMcpConnection } from "./store.js"
|
||||
@@ -10,11 +10,20 @@ import type { add } from "./actions.js"
|
||||
|
||||
export const TERMINAL_DIAGNOSTIC_MAX_OUTPUT_BYTES = 12000
|
||||
export function registerTerminalDiagnosticActions(register: typeof add) {
|
||||
const schema = terminalDiagnosticSchema.safeExtend({ serverId: z.number().int().positive().safe() })
|
||||
const schema = z.object({
|
||||
...terminalDiagnosticSchema.shape,
|
||||
serverId: z.number().int().positive().safe(),
|
||||
diagnostic: z.enum([...terminalDiagnosticNames, "interface_counters"]),
|
||||
interface: terminalInterfaceCountersSchema.shape.interface,
|
||||
}).strict().superRefine(({ serverId: _id, ...args }, ctx) => {
|
||||
const parsed = args.diagnostic === "interface_counters" ? terminalInterfaceCountersSchema.safeParse(args) : terminalDiagnosticSchema.safeParse(args)
|
||||
if (!parsed.success) for (const issue of parsed.error.issues) ctx.addIssue({ code: "custom", message: issue.message, path: issue.path })
|
||||
})
|
||||
register("servers.terminal.read", "mm_server_terminal_diagnostic", "Разрешённая типизированная диагностика REST-терминала", "servers", "mm:servers:write", "read", "servers", schema, {
|
||||
read: async (input, context) => {
|
||||
const serverId = Number(input.serverId), { serverId: _id, ...args } = input
|
||||
const command = terminalDiagnosticSchema.parse(args), generation = await accessGeneration()
|
||||
const command = args.diagnostic === "interface_counters" ? terminalInterfaceCountersSchema.parse(args) : terminalDiagnosticSchema.parse(args)
|
||||
const generation = await accessGeneration()
|
||||
const initial = (await pool.query("SELECT id,enabled,routing_endpoint_epoch FROM servers WHERE id=$1", [serverId])).rows[0]
|
||||
const authorize = async () => {
|
||||
context.signal?.throwIfAborted()
|
||||
@@ -33,11 +42,20 @@ export function registerTerminalDiagnosticActions(register: typeof add) {
|
||||
await authorize()
|
||||
if (endpoints.length !== 1 || endpoints[0].routingEndpointEpoch !== initial.routing_endpoint_epoch || !endpoints[0].enabled) throw new McpError("STATE_CONFLICT", "Источник диагностики изменился", 409)
|
||||
const endpoint = endpoints[0]
|
||||
try { output = await withTerminalDiagnosticClient(endpoint, { signal: context.signal, authorize }, client => executeTerminalDiagnostic(client, command)) }
|
||||
const secrets = [endpoint.password, Buffer.from(`${endpoint.username}:${endpoint.password}`).toString("base64")].filter(Boolean)
|
||||
try {
|
||||
if (command.diagnostic === "interface_counters") {
|
||||
const protect = (value: string) => secrets.some(secret => value.includes(secret)) ? "[redacted]" : String(redact(value))
|
||||
const interfaceCounters = await withTerminalDiagnosticClient(endpoint, { signal: context.signal, authorize }, client => readTerminalInterfaceCounters(client, command, protect))
|
||||
await authorize()
|
||||
return { serverId, diagnostic: command.diagnostic, interfaceCounters, activity: { kind: "read", configurationApplied: false } }
|
||||
}
|
||||
output = await withTerminalDiagnosticClient(endpoint, { signal: context.signal, authorize }, client => executeTerminalDiagnostic(client, command))
|
||||
}
|
||||
catch (error) { if (error instanceof McpError) throw error; throw new McpError("STATE_UNAVAILABLE", "Терминальная диагностика не вернула подтверждённый результат", 409) }
|
||||
// Free-form comments and log text may echo stored credentials. Mask exact
|
||||
// credentials as well as labelled secrets before returning or auditing.
|
||||
for (const value of [endpoint.password, Buffer.from(`${endpoint.username}:${endpoint.password}`).toString("base64")].filter(Boolean)) output = output.split(value).join("[redacted]")
|
||||
for (const value of secrets) output = output.split(value).join("[redacted]")
|
||||
}
|
||||
await authorize()
|
||||
const redactionTruncated = output.length > MAX_MCP_PUBLIC_STRING_LENGTH
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import { fingerprint, accessGeneration, McpError } from "./security.js"
|
||||
import { pool } from "../../db/index.js"
|
||||
import { wireguardExportRequestSchema } from "../../services/wireguard-export.js"
|
||||
import { effectiveMcpConnection } from "./store.js"
|
||||
import { registerMcpService } from "./service-registry.js"
|
||||
import { wireguardExportAuthority, wireguardExportAuthoritySchema, createWireguardExportArtifact, readWireguardExportSource, verifyWireguardExportArtifact } from "./wireguard-export-artifact.js"
|
||||
import { wireguardExportAuthority, wireguardExportAuthoritySchema, createWireguardExportArtifact, mcpWireguardExportRequestSchema, readWireguardExportSource, verifyWireguardExportArtifact } from "./wireguard-export-artifact.js"
|
||||
import type { add } from "./actions.js"
|
||||
|
||||
export function registerWireguardExportActions(register: typeof add) {
|
||||
@@ -16,10 +15,10 @@ export function registerWireguardExportActions(register: typeof add) {
|
||||
return receipt?.humanDownloadOnly===true && receipt.wireguardContentReturned===false && !!receipt.artifactId && await verifyWireguardExportArtifact(receipt.artifactId,authority(input),String(input.expectedProof))
|
||||
},
|
||||
})
|
||||
register("network.wireguard.export","mm_wireguard_export_plan","Подготовить WireGuard экспорт для скачивания владельцем после человеческого подтверждения","network","mm:network:write","write","servers",wireguardExportRequestSchema,{
|
||||
target:input=>({scope:"servers",serverIds:[wireguardExportRequestSchema.parse(input).serverId]}),
|
||||
register("network.wireguard.export","mm_wireguard_export_plan","Подготовить WireGuard экспорт или готовый .conf для Linux-клиента IX","network","mm:network:write","write","servers",mcpWireguardExportRequestSchema,{
|
||||
target:input=>({scope:"servers",serverIds:[mcpWireguardExportRequestSchema.parse(input).serverId]}),
|
||||
prepare:async(input,context)=>{
|
||||
const request=wireguardExportRequestSchema.parse(input)
|
||||
const request=mcpWireguardExportRequestSchema.parse(input)
|
||||
const authorize=async()=>{
|
||||
if(context.signal?.aborted)throw new McpError("READ_CANCELLED","Экспорт WireGuard отменён",409)
|
||||
const fresh=await effectiveMcpConnection(context.principal)
|
||||
@@ -33,7 +32,10 @@ export function registerWireguardExportActions(register: typeof add) {
|
||||
await authorize()
|
||||
return {target:{scope:"servers",serverIds:[request.serverId]},objects:[{kind:"server",id:String(request.serverId),serverId:request.serverId},{kind:"wireguard-export",id:request.interfaceName,serverId:request.serverId},...protections.map(row=>row.object_ref)],snapshots:[],before:{proof:source.proof},requiresHuman:true,mutationCost:1,
|
||||
steps:[{kind:"service",service:"network.wireguard.export",input:{authority:access,expectedProof:source.proof,beforeFingerprint:fingerprint({proof:source.proof})}}],
|
||||
warnings:[request.includePrivateKey && request.format!=="peer-conf" ? "Этот пакет включает приватный ключ интерфейса WireGuard. Скачивание разрешено только вошедшему владельцу на 15 минут." : "Приватные ключи в этот пакет не включаются. Файл доступен только вошедшему владельцу на 15 минут.","Модель получает только квитанцию и ссылку; содержимое, native ключи и комментарии в MCP не возвращаются. Предел файла — 1 МиБ, чтения — 45 секунд.","Изменение источника, прав, подключений или защит блокирует выдачу. Формат conf не воспроизводит отключённые интерфейсы/пиры; peer-conf не раскрывает ключи клиента.",request.format==="conf"?"Формат conf переносит параметры туннеля; имя интерфейса, имена пиров и клиентские подсказки RouterOS в нём не восстанавливаются.":request.format==="peer-conf"?"peer-conf — шаблон клиента: приватный ключ и AllowedIPs заполняются человеком; готовность клиентского подключения не подтверждается.":"RSC сохраняет поддержанные native поля и отключённые состояния; фактический путь проверяется отдельно."]}
|
||||
warnings: request.ixSegmentId ? [
|
||||
"Готовый конфиг IX содержит приватный ключ Linux-клиента. Скачивание доступно вошедшему владельцу на 15 минут.",
|
||||
"MCP возвращает только квитанцию и ссылку. Изменение применённой ревизии, прав или защит блокирует выдачу.",
|
||||
] : [request.includePrivateKey && request.format!=="peer-conf" ? "Этот пакет включает приватный ключ интерфейса WireGuard. Скачивание разрешено только вошедшему владельцу на 15 минут." : "Приватные ключи в этот пакет не включаются. Файл доступен только вошедшему владельцу на 15 минут.","Модель получает только квитанцию и ссылку; содержимое, native ключи и комментарии в MCP не возвращаются. Предел файла — 1 МиБ, чтения — 45 секунд.","Изменение источника, прав, подключений или защит блокирует выдачу. Формат conf не воспроизводит отключённые интерфейсы/пиры; peer-conf не раскрывает ключи клиента.",request.format==="conf"?"Формат conf переносит параметры туннеля; имя интерфейса, имена пиров и клиентские подсказки RouterOS в нём не восстанавливаются.":request.format==="peer-conf"?"peer-conf — шаблон клиента: приватный ключ и AllowedIPs заполняются человеком; готовность клиентского подключения не подтверждается.":"RSC сохраняет поддержанные native поля и отключённые состояния; фактический путь проверяется отдельно."]}
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -4,6 +4,9 @@ import type { PoolClient } from "pg"
|
||||
import { pool } from "../../db/index.js"
|
||||
import { hasPermission, type AuthUser } from "../../lib/permissions.js"
|
||||
import { readWireguardExport, wireguardExportRequestSchema } from "../../services/wireguard-export.js"
|
||||
import { readIxLinuxClient } from "../../services/internet-exchange-execution.js"
|
||||
import { IxConflict } from "../../services/internet-exchange-plan.js"
|
||||
import { readIxSegment } from "../../services/internet-exchange-store.js"
|
||||
import { assertVerifiedConfigurationAccess, executeGuardedApplicationWrite } from "../../services/config-mutation-policy.js"
|
||||
import { assertLogArtifactBudget } from "./log-artifacts.js"
|
||||
import { assertPortalClaimsCurrent } from "./portal-revocation.js"
|
||||
@@ -13,7 +16,11 @@ import { accessGeneration, decryptSecret, encryptSecret, fingerprint, McpError,
|
||||
const MAX_BYTES = 1048576, MAX_CIPHER = 2 * 1048576
|
||||
const digest = z.string().regex(/^[a-f0-9]{64}$/)
|
||||
const principalSchema = z.object({ connectionId: z.string().uuid(), credentialId: z.string().uuid(), credentialExpiresAt: z.iso.datetime() }).strict()
|
||||
export const wireguardExportAuthoritySchema = z.object({ principal: principalSchema, ownerId: z.string().min(1).max(200), policyProof: digest, generation: digest, request: wireguardExportRequestSchema }).strict()
|
||||
export const mcpWireguardExportRequestSchema = wireguardExportRequestSchema.extend({
|
||||
ixSegmentId: z.string().uuid().optional().describe("Для готового конфига Linux из IX укажите ID сегмента и формат peer-conf"),
|
||||
}).refine(request => !request.ixSegmentId || request.format === "peer-conf" && !request.peerId && !request.includePrivateKey,
|
||||
"Для клиента IX укажите peer-conf и имя интерфейса клиента. Его управляемый ключ будет включён в файл.")
|
||||
export const wireguardExportAuthoritySchema = z.object({ principal: principalSchema, ownerId: z.string().min(1).max(200), policyProof: digest, generation: digest, request: mcpWireguardExportRequestSchema }).strict()
|
||||
export type WireguardExportAuthority = z.infer<typeof wireguardExportAuthoritySchema>
|
||||
const scopeSchema = z.object({ version: z.literal(1), kind: z.literal("wireguard-export"), authority: wireguardExportAuthoritySchema, sourceProof: digest,
|
||||
bytes: z.number().int().min(0).max(MAX_BYTES), sha256: digest, encryptedSha256: digest, proof: digest }).strict()
|
||||
@@ -41,10 +48,25 @@ async function protectionProof(authority: WireguardExportAuthority, client: Pick
|
||||
export async function readWireguardExportSource(authority: WireguardExportAuthority, authorize: () => Promise<unknown> = async()=>{}, signal?: AbortSignal) {
|
||||
await authorize(); await assertWireguardExportAccess(authority)
|
||||
const protections=await protectionProof(authority)
|
||||
const source=await readWireguardExport(authority.request, { signal, authorize: async()=>{
|
||||
const check = async () => {
|
||||
signal?.throwIfAborted()
|
||||
await authorize(); await assertWireguardExportAccess(authority)
|
||||
if (await protectionProof(authority)!==protections) throw fail("Защиты экспорта изменились", "STATE_CONFLICT")
|
||||
} })
|
||||
}
|
||||
const { ixSegmentId, ...request } = authority.request
|
||||
if (ixSegmentId) {
|
||||
await check()
|
||||
const segment = await readIxSegment(ixSegmentId)
|
||||
if (!segment) throw new McpError("NOT_FOUND", "Сегмент IX не найден", 404)
|
||||
const access = await readIxLinuxClient(segment, request.serverId, request.interfaceName, "wireguard").catch(error => {
|
||||
if (error instanceof IxConflict) throw new McpError(error.statusCode === 404 ? "NOT_FOUND" : "STATE_CONFLICT", error.message, error.statusCode)
|
||||
throw error
|
||||
})
|
||||
await check()
|
||||
const proof = await sign({ protections, ixSegmentId, request, access })
|
||||
return { filename: access.filename, content: Buffer.from(access.template), protectionProof: protections, proof }
|
||||
}
|
||||
const source=await readWireguardExport(request, { signal, authorize: check })
|
||||
return {...source,protectionProof:protections,proof:await sign({nativeSource:source.proof,protections})}
|
||||
}
|
||||
|
||||
|
||||
@@ -276,7 +276,8 @@ export async function requireAuth(
|
||||
/** Gate the matched route, including encoded static segments in the raw URL. */
|
||||
export async function requireApiAuth(request: FastifyRequest, reply: FastifyReply): Promise<void> {
|
||||
const pathname = request.routeOptions.url ?? request.url.split("?")[0] ?? request.url
|
||||
if (!pathname.startsWith("/api/") || pathname === "/api/auth/config") return
|
||||
if (!pathname.startsWith("/api/") || pathname === "/api/auth/config" ||
|
||||
request.method === "POST" && pathname === "/api/ix/import") return
|
||||
await requireAuth(request, reply)
|
||||
}
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@ export function installDatabaseRequestGate(app: FastifyInstance, admit = withDat
|
||||
const run = async () => withConfigurationActor(request.authUser?.id ?? "system", async () => await original.call(this, request, reply))
|
||||
// The service owns exclusivity, including calls that do not originate in HTTP.
|
||||
if (operation) return run()
|
||||
if (!stream) return gate.request(() => admit(run))
|
||||
if (!stream) return gate.request(() => admit(run, !["GET", "HEAD", "OPTIONS"].includes(request.method)))
|
||||
const state = { cancelled: false, abort: undefined as (() => void) | undefined }
|
||||
streams.set(request, state)
|
||||
try {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { coalesceCatalogReads, observationIsCurrent, readCatalogWithObservedCache, withCatalogWriteLock } from "../services/routing-catalog-observation.js"
|
||||
import { and, asc, eq, inArray } from "drizzle-orm"
|
||||
import { z } from "zod"
|
||||
import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod"
|
||||
@@ -8,7 +9,6 @@ import { pollGreCatalog } from "../services/gre-catalog-poll.js"
|
||||
import { parseKeepalive } from "../services/gre-live.js"
|
||||
import { parseDbServerId } from "../utils/server-id.js"
|
||||
import { observeBgpFilterRules } from "../services/filter-rules-observed.js"
|
||||
import { withApplicationMutationLock, withConfigMutationLock } from "../services/config-mutation-lock.js"
|
||||
import { appendEvent } from "../modules/events/service/events-service.js"
|
||||
import { managedComment, hasManagedCommentPrefix } from "../managed-markers.js"
|
||||
import { compileManagedFilterRules, filterRuleBranches, filterRuleDescriptions, filterRuleToken, validatedFilterRules } from "../services/filter-rules-write-model.js"
|
||||
@@ -282,6 +282,8 @@ export async function fetchServerFilters(server: ServerRow) {
|
||||
}
|
||||
}
|
||||
|
||||
const readWebFilters = coalesceCatalogReads(fetchServerFilters)
|
||||
|
||||
async function toApiRulesets(serverRows: ServerRow[]) {
|
||||
const dbRules = serverRows.length ? await db.select().from(filterRules).where(inArray(filterRules.serverId, serverRows.map(server => server.id))).orderBy(asc(filterRules.serverId), asc(filterRules.sortOrder), asc(filterRules.id)) : []
|
||||
return serverRows.map(s => ({
|
||||
@@ -381,20 +383,26 @@ export async function readFilterRulesCatalog(selected: ServerRow[], options: { s
|
||||
const rulesets = await toApiRulesets(selected)
|
||||
return rulesets.map(ruleset => ({ ...ruleset, greTunnels: [] as LiveGreTunnel[], nativeRules: null as ReturnType<typeof observeBgpFilterRules> | null, live: false, stale: false, source: "cache" as const, error: null as string | null }))
|
||||
}
|
||||
const readSelected = () => Promise.all(selected.map(async server => {
|
||||
return Promise.all(selected.map(async server => {
|
||||
try {
|
||||
const remote = await fetchServerFilters(server)
|
||||
if (options.persistObserved) {
|
||||
const read = async (fresh: boolean) => {
|
||||
const remote = await (fresh || !options.persistObserved ? fetchServerFilters : readWebFilters)(server)
|
||||
if (!options.persistObserved) return { remote, rules: remote.rules, current: true }
|
||||
const rules = await cacheRulesetsForServer(server.id)
|
||||
const current = await observationIsCurrent(server.id, "filters", canonicalFilterRules(remote.rules), canonicalFilterRules(rules))
|
||||
return { remote, rules, current }
|
||||
}
|
||||
const { remote, rules } = await readCatalogWithObservedCache(server, read, async ({ remote }) => {
|
||||
await replaceDbRules(server.id, remote.rules)
|
||||
await appendRevisionIfChanged({ serverId: server.id, section: "filters", source: "observed", payload: canonicalFilterRules(remote.rules) })
|
||||
}
|
||||
return { serverId: String(server.id), rules: options.persistObserved ? await cacheRulesetsForServer(server.id) : remote.rules, greTunnels: remote.tunnels, nativeRules: remote.nativeRules, live: true, stale: false, source: "device" as const, error: null as string | null }
|
||||
} catch {
|
||||
return { remote, rules: await cacheRulesetsForServer(server.id), current: true }
|
||||
})
|
||||
return { serverId: String(server.id), rules, greTunnels: remote.tunnels, nativeRules: remote.nativeRules, live: true, stale: false, source: "device" as const, error: null as string | null }
|
||||
} catch (error) {
|
||||
if (error instanceof McpError && error.statusCode === 409) throw error
|
||||
return { serverId: String(server.id), rules: await cacheRulesetsForServer(server.id), greTunnels: [] as LiveGreTunnel[], nativeRules: null, live: false, stale: true, source: "cache" as const, error: server.enabled ? "Не подтверждено чтение фильтров выбранного сервера" : "Сервер выключен. Опрос фильтров недоступен." }
|
||||
}
|
||||
}))
|
||||
return options.persistObserved
|
||||
? withApplicationMutationLock(() => withConfigMutationLock(selected.map(server => server.id), readSelected)) : readSelected()
|
||||
}
|
||||
|
||||
export async function applyFiltersToServer(
|
||||
@@ -406,7 +414,7 @@ export async function applyFiltersToServer(
|
||||
if (!server.enabled) throw new McpError("DEVICE_UNAVAILABLE", "Сервер выключен; изменение фильтров запрещено", 409)
|
||||
if (options.managedRuleComment !== undefined && !hasManagedCommentPrefix(options.managedRuleComment)) throw new McpError("PROTECTED_OBJECT", "Сохранённый comment фильтра не принадлежит приложению", 409)
|
||||
rules = validatedFilterRules(rules)
|
||||
return executeGuardedApplicationWrite({ kind: "filters", id: "managed-bgp-in" }, [server.id], () => withConfigMutationLock([server.id], async () => {
|
||||
return withCatalogWriteLock(server, "filters", () => executeGuardedApplicationWrite({ kind: "filters", id: "managed-bgp-in" }, [server.id], async () => {
|
||||
const client = MikrotikClient.fromServer(server)
|
||||
const interfaces = rules.some(rule => rule.action !== "blackhole" && rule.gatewayTunnelId && !rule.gatewayTunnelId.startsWith("rec:")) ? nativeBgpRows(await client.get("/interface/gre")) : []
|
||||
const ruleBody = await toRouterRuleBody(server.id, rules, interfaces)
|
||||
@@ -442,7 +450,7 @@ const filtersRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
const server = enabledServers.find(s => s.id === sid)
|
||||
if (!server) return reply.status(404).send({ error: "Server not found" })
|
||||
try {
|
||||
const remote = await fetchServerFilters(server)
|
||||
const remote = await readWebFilters(server)
|
||||
return reply.send({ tunnels: remote.tunnels })
|
||||
} catch (error) {
|
||||
app.log.warn({ serverId: sid, err: String(error) }, "filters GRE catalog unavailable")
|
||||
@@ -450,7 +458,7 @@ const filtersRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
}
|
||||
}
|
||||
|
||||
return reply.send(await pollGreCatalog(enabledServers, fetchServerFilters))
|
||||
return reply.send(await pollGreCatalog(enabledServers, readWebFilters))
|
||||
})
|
||||
|
||||
/** Без serverId — cache для дашборда. С serverId — live с CHR, cache fallback. */
|
||||
@@ -523,6 +531,7 @@ const filtersRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
rules: cached,
|
||||
})
|
||||
} catch (err) {
|
||||
if (err instanceof McpError && err.statusCode === 409) throw err
|
||||
app.log.error({ serverId, err: String(err) }, "filters apply failed")
|
||||
await appendEvent({
|
||||
level: "critical",
|
||||
@@ -588,6 +597,7 @@ const filtersRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
})
|
||||
return reply.send({ ok: true, rules: cached, pushedRules: result.pushed })
|
||||
} catch (err) {
|
||||
if (err instanceof McpError) throw err
|
||||
app.log.error({ serverId: server.id, err: String(err) }, "filters restore failed")
|
||||
return reply.status(500).send({ error: String(err) })
|
||||
}
|
||||
|
||||
@@ -1,14 +1,19 @@
|
||||
import { randomUUID } from "node:crypto"
|
||||
import type { FastifyPluginAsync } from "fastify"
|
||||
import { z } from "zod"
|
||||
import { ixChangeSchema, 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 { captureVerifiedRestRequest, inspectVerifiedRestRequest, RestRequestProvenanceError } from "../plugins/auth.js"
|
||||
import { withApplicationMutationLock } from "../services/config-mutation-lock.js"
|
||||
import { audit } from "../modules/mcp/store.js"
|
||||
import { pool } from "../db/index.js"
|
||||
import { captureVerifiedRestRequest, inspectVerifiedRestRequest, RestRequestProvenanceError, type VerifiedRestRequestAuthority } from "../plugins/auth.js"
|
||||
import { assertPortalClaimsCurrent } from "../modules/mcp/portal-revocation.js"
|
||||
import { createIxImportLinks } from "../services/ix-import-links.js"
|
||||
import { withApplicationCollectorLock, withApplicationMutationLock } from "../services/config-mutation-lock.js"
|
||||
import { withConfigurationActor } from "../services/config-mutation-policy.js"
|
||||
import { applyIxChange, listIxLinuxClients, observeIxSegment, prepareIxChange, prepareIxRemoval, readIxLinuxClient, removeIxSegment } from "../services/internet-exchange-execution.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, inspectIxBondImports, ixBondCatalog } from "../services/internet-exchange-bonds.js"
|
||||
|
||||
const paging = z.object({
|
||||
limit: z.coerce.number().int().min(1).max(100).default(25),
|
||||
@@ -17,17 +22,19 @@ const paging = z.object({
|
||||
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}$/) })
|
||||
const clientKey = z.object({ serverId: z.number().int().positive().safe(), interfaceName: z.string().regex(/^[A-Za-z0-9_.-]{1,48}$/) })
|
||||
const safeFields = (fields: Record<string, string>) => Object.fromEntries(Object.entries(fields).filter(([key]) => key !== "secret" && key !== "private-key"))
|
||||
|
||||
async function prepareSavedRevision(id: string, revision: number) {
|
||||
async function prepareSavedRevision(id: string, revision: number, resume = false) {
|
||||
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 })
|
||||
return prepareIxChange({ id, revision, configuration: segment.configuration }, resume)
|
||||
}
|
||||
|
||||
function reviewDigest(prepared: Awaited<ReturnType<typeof prepareSavedRevision>>, actorId: string) {
|
||||
return fingerprint({ operation: "ix.web.apply", actorId, change: prepared.change, before: prepared.before, tasks: prepared.native.tasks })
|
||||
function reviewDigest(prepared: Awaited<ReturnType<typeof prepareSavedRevision>>, actorId: string, resume: boolean) {
|
||||
return fingerprint({ operation: "ix.web.apply", actorId, change: prepared.change, before: prepared.before, tasks: prepared.native.tasks, resume })
|
||||
}
|
||||
|
||||
function removalDigest(id: string, revision: number, actorId: string, nativeDigest: string) {
|
||||
@@ -40,15 +47,31 @@ function summarizeTasks(tasks: Awaited<ReturnType<typeof prepareIxChange>>["nati
|
||||
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))),
|
||||
fields: task.fields ? safeFields(task.fields) : Object.fromEntries(Object.entries(task.before ?? {}).filter(([key]) => ["name", "comment", "dst-address", "chain"].includes(key))),
|
||||
}))
|
||||
}
|
||||
|
||||
const importLinkLifetime = 5 * 60_000
|
||||
|
||||
function importLinkOwner(authority: VerifiedRestRequestAuthority) {
|
||||
const { ownerId, issuedAt, authentication, expiresAt } = authority
|
||||
return async () => {
|
||||
if (Date.now() >= expiresAt) throw new IxConflict("Ссылка истекла", 410)
|
||||
if (authentication === "jwt") await assertPortalClaimsCurrent({ id: ownerId, issuedAt })
|
||||
}
|
||||
}
|
||||
|
||||
const ixRoutes: FastifyPluginAsync = async app => {
|
||||
const links = createIxImportLinks()
|
||||
app.post("/ix/import", { bodyLimit: 256 }, async (request, reply) => {
|
||||
reply.header("Cache-Control", "private, no-store")
|
||||
const { code } = z.object({ code: z.string().regex(/^[A-Za-z0-9_-]{32}$/) }).strict().parse(request.body)
|
||||
return links.redeem(code)
|
||||
})
|
||||
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 McpError) return reply.code(error.statusCode).send({ error: error.message, code: error.code })
|
||||
if (error instanceof RestRequestProvenanceError) return reply.code(403).send({ error: "Нет действующего права изменения IX" })
|
||||
request.log.error({ error: error instanceof Error ? error.name : "unknown" }, "IX request failed")
|
||||
const errorMessage = request.method === "DELETE" ? "Удаление сегмента IX не подтверждено. Обновите данные и проверьте план."
|
||||
@@ -61,14 +84,62 @@ 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)
|
||||
await inspectIxBondImports(id, edit)
|
||||
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, importLink } = planRequest.extend({ importLink: z.boolean().optional() }).parse(request.body)
|
||||
const scope = { deadlineAt: Date.now() + (importLink ? importLinkLifetime : 90_000) }
|
||||
const token = await captureVerifiedRestRequest(request, scope)
|
||||
const authorize = () => inspectVerifiedRestRequest(token, scope, "mm:network:write")
|
||||
const authority = await authorize()
|
||||
const { ownerId } = authority
|
||||
if (importLink) {
|
||||
const authorizeOwner = importLinkOwner(authority)
|
||||
await audit(pool, ownerId, "ix.bond.import_link_issued", null, { segmentId: id, bondId, revision })
|
||||
await authorize()
|
||||
reply.header("Cache-Control", "private, no-store")
|
||||
return { code: links.issue(authority.monotonicDeadline, () => withApplicationCollectorLock(async () => {
|
||||
await authorizeOwner()
|
||||
const bond = await exportIxBond(id, bondId, revision, authorizeOwner)
|
||||
await audit(pool, ownerId, "ix.bond.exported", null, { segmentId: id, bondId, revision })
|
||||
await authorizeOwner()
|
||||
return { version: 1, kind: "bond", bond }
|
||||
})) }
|
||||
}
|
||||
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 { pool } = await import("../db/index.js")
|
||||
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"),
|
||||
pool.query("SELECT id,name,site,country,enabled,type FROM servers ORDER BY name,id LIMIT 1000"),
|
||||
])
|
||||
return { items: nodes.rows, peers: peers.rows }
|
||||
})
|
||||
app.get("/ix/nodes/:serverId/inventory", async request => {
|
||||
const { serverId } = z.object({ serverId: z.coerce.number().int().positive().safe() }).parse(request.params)
|
||||
const { segmentId } = z.object({ segmentId: z.string().uuid().optional() }).strict().parse(request.query)
|
||||
const segment = segmentId ? await readIxSegment(segmentId) : null
|
||||
if (segmentId && !segment) throw new IxConflict("Сегмент IX не найден", 404)
|
||||
return readIxNodeInventory(serverId, segment ?? undefined, true)
|
||||
})
|
||||
app.get("/ix/topology", async () => {
|
||||
const segments = await listIxSegments(100, 0)
|
||||
const links = segments.filter(segment => segment.appliedRevision === segment.revision).flatMap(({ configuration }) =>
|
||||
@@ -86,50 +157,143 @@ 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)
|
||||
const input = ixLinuxClientRequest.parse(request.body)
|
||||
return withApplicationMutationLock(async () => {
|
||||
const current = await readIxSegment(id)
|
||||
if (!current) throw new IxConflict("Сегмент IX не найден", 404)
|
||||
assertIxRevision(current, input.revision)
|
||||
const base = input.transit ? { ...current, configuration: await configureIxTransit(current, {
|
||||
...input.transit, revision: input.revision, serverId: input.serverId,
|
||||
}) } : current
|
||||
const { configuration, interfaceName } = await configureIxLinuxClient(base, {
|
||||
...input, exit: input.transit?.name ?? input.exit,
|
||||
})
|
||||
const segment = await writeIxRevision(id, current.revision, configuration, request.authUser?.id ?? "system", false)
|
||||
return { segment, interfaceName }
|
||||
}, { waitMs: 5000 })
|
||||
})
|
||||
app.get("/ix/segments/:id/linux/path", async request => {
|
||||
const { id } = segmentParams.parse(request.params)
|
||||
const { serverId, interfaceName } = clientKey.extend({ serverId: z.coerce.number().int().positive().safe() }).strict().parse(request.query)
|
||||
const segment = await readIxSegment(id)
|
||||
if (!segment) throw new IxConflict("Сегмент IX не найден", 404)
|
||||
return observeIxLinuxPath(segment, serverId, interfaceName)
|
||||
})
|
||||
app.post("/ix/segments/:id/linux/credential", async (request, reply) => {
|
||||
const { id } = segmentParams.parse(request.params)
|
||||
const { serverId, interfaceName, transportOnly, importLink } = clientKey.extend({
|
||||
transportOnly: z.boolean().optional(), importLink: z.boolean().optional(),
|
||||
}).parse(request.body)
|
||||
const scope = { deadlineAt: Date.now() + (importLink ? importLinkLifetime : 60_000) }
|
||||
const token = await captureVerifiedRestRequest(request, scope)
|
||||
const authority = await inspectVerifiedRestRequest(token, scope, "mm:network:write")
|
||||
const { ownerId } = authority
|
||||
const segment = await readIxSegment(id)
|
||||
if (!segment) throw new IxConflict("Сегмент IX не найден", 404)
|
||||
if (importLink) {
|
||||
const revision = segment.appliedRevision
|
||||
if (revision === null) throw new IxConflict("Сначала примените конфигурацию площадки")
|
||||
const authorizeOwner = importLinkOwner(authority)
|
||||
await audit(pool, ownerId, "ix.linux.import_link_issued", null, { segmentId: id, serverId, interfaceName, revision })
|
||||
await inspectVerifiedRestRequest(token, scope, "mm:network:write")
|
||||
reply.header("Cache-Control", "private, no-store")
|
||||
return { code: links.issue(authority.monotonicDeadline, async () => {
|
||||
await authorizeOwner()
|
||||
const current = await readIxSegment(id)
|
||||
if (!current || current.appliedRevision !== revision) throw new IxConflict("Ревизия IX изменилась; получите новую ссылку", 410)
|
||||
const access = await readIxLinuxClient(current, serverId, interfaceName, true, true, true)
|
||||
if ((await readIxSegment(id))?.appliedRevision !== revision) throw new IxConflict("Ревизия IX изменилась; получите новую ссылку", 410)
|
||||
await audit(pool, ownerId, "ix.linux.credential_exported", null, { segmentId: id, serverId, interfaceName, revision })
|
||||
await authorizeOwner()
|
||||
const name = access.filename.replace(/\.conf$/, "")
|
||||
if (access.kind === "wireguard") return { version: 1, kind: "wireguard", name, config: access.template }
|
||||
if (!access.greImport) throw new IxConflict("Нет параметров управляемого GRE/IPsec")
|
||||
return { version: 1, kind: "gre-ipsec", name, gre: access.greImport }
|
||||
}) }
|
||||
}
|
||||
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")
|
||||
return access
|
||||
})
|
||||
app.post("/ix/segments/:id/linux/revoke", async request => {
|
||||
const { id } = segmentParams.parse(request.params)
|
||||
const { serverId, interfaceName, revision } = clientKey.extend(planRequest.shape).strict().parse(request.body)
|
||||
return withApplicationMutationLock(async () => {
|
||||
const current = await readIxSegment(id)
|
||||
if (!current) throw new IxConflict("Сегмент IX не найден", 404)
|
||||
assertIxRevision(current, revision)
|
||||
const site = current.configuration.sites.find(item => item.serverId === serverId)
|
||||
if (!site?.interfaces.some(item => item.name === interfaceName && item.linux)) throw new IxConflict("Управляемый клиент не найден", 404)
|
||||
const configuration = { ...current.configuration, sites: current.configuration.sites.map(item => item !== site ? item : {
|
||||
...item, interfaces: item.interfaces.filter(binding => binding.name !== interfaceName),
|
||||
neighbors: item.neighbors.filter(neighbor => neighbor.binding !== interfaceName),
|
||||
}) }
|
||||
compileIxConfiguration(id, configuration)
|
||||
return { segment: await writeIxRevision(id, revision, configuration, request.authUser?.id ?? "system", false) }
|
||||
}, { waitMs: 5000 })
|
||||
})
|
||||
app.post("/ix/segments/:id/transit", async request => {
|
||||
const { id } = segmentParams.parse(request.params)
|
||||
const input = ixTransitRequest.parse(request.body)
|
||||
return withApplicationMutationLock(async () => {
|
||||
const current = await readIxSegment(id)
|
||||
if (!current) throw new IxConflict("Сегмент IX не найден", 404)
|
||||
assertIxRevision(current, input.revision)
|
||||
const configuration = await configureIxTransit(current, input)
|
||||
return { segment: await writeIxRevision(id, current.revision, configuration, request.authUser?.id ?? "system", false) }
|
||||
}, { waitMs: 5000 })
|
||||
})
|
||||
app.post("/ix/segments", async request => {
|
||||
const input = ixChangeSchema.parse(request.body)
|
||||
const id = input.id ?? randomUUID()
|
||||
compileIxConfiguration(id, input.configuration)
|
||||
return withApplicationMutationLock(async () => {
|
||||
assertIxRevision(input.id ? await readIxSegment(id) : null, input.revision)
|
||||
const segment = await writeIxRevision(id, input.revision, input.configuration, request.authUser?.id ?? "system", false)
|
||||
const current = input.id ? await readIxSegment(id) : null
|
||||
assertIxRevision(current, input.revision)
|
||||
const configuration = await assignIxRouterIds(id, input.configuration, current)
|
||||
compileIxConfiguration(id, configuration)
|
||||
const segment = await writeIxRevision(id, input.revision, configuration, request.authUser?.id ?? "system", false)
|
||||
return { segment }
|
||||
})
|
||||
}, { waitMs: 5000 })
|
||||
})
|
||||
app.post("/ix/preview", async request => {
|
||||
const input = ixChangeSchema.parse(request.body)
|
||||
const id = input.id ?? randomUUID()
|
||||
assertIxRevision(input.id ? await readIxSegment(id) : null, input.revision)
|
||||
return { id, objects: compileIxConfiguration(id, input.configuration) }
|
||||
return { id, objects: compileIxConfiguration(id, input.configuration).map(object => ({ ...object, fields: safeFields(object.fields) })) }
|
||||
})
|
||||
|
||||
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)
|
||||
const { revision, resume = false } = planRequest.extend({ resume: z.boolean().optional() }).parse(request.body)
|
||||
const prepared = await prepareSavedRevision(id, revision, resume)
|
||||
return {
|
||||
revision, digest: reviewDigest(prepared, request.authUser?.id ?? "local-operator"),
|
||||
revision, digest: reviewDigest(prepared, request.authUser?.id ?? "local-operator", resume), ...(resume && { resume }),
|
||||
changes: summarizeTasks(prepared.native.tasks),
|
||||
}
|
||||
})
|
||||
|
||||
app.post("/ix/segments/:id/apply", async request => {
|
||||
const { id } = segmentParams.parse(request.params)
|
||||
const { revision, digest } = applyRequest.parse(request.body)
|
||||
const { revision, digest, resume = false } = applyRequest.extend({ resume: z.boolean().optional() }).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() }))
|
||||
const prepared = await prepareSavedRevision(id, revision, resume)
|
||||
if (digest !== reviewDigest(prepared, ownerId, resume)) throw new IxConflict("План IX устарел. Постройте новый предпросмотр")
|
||||
const result = await withConfigurationActor(ownerId, () => applyIxChange(id, prepared.change, prepared.before, ownerId,
|
||||
async () => { await inspect() }, { resume }))
|
||||
return { segment: await readIxSegment(result.segmentId), result }
|
||||
})
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@ import { humanWireguardExportMetadata, readHumanWireguardExportArtifact } from "
|
||||
import { humanArtifactReceipts } from "../modules/mcp/human-artifact-receipts.js"
|
||||
import { readHumanHostFilesArtifact } from "../modules/mcp/host-files-artifact.js"
|
||||
import { loadLogExportArtifactMetadata } from "../modules/mcp/log-artifacts.js"
|
||||
import { readServerPollCapacity } from "../services/server-poll-capacity.js"
|
||||
import { readServerPollUsage } from "../services/server-poll-capacity.js"
|
||||
import { connectProbeStorage } from "../services/server-probe-storage-connection.js"
|
||||
|
||||
const uuid = z.string().uuid()
|
||||
@@ -56,12 +56,12 @@ export function mcpDevicePlanArguments(serverId: number, input: z.infer<typeof m
|
||||
}
|
||||
const idOf = (params: unknown) => z.object({ id: uuid }).parse(params).id
|
||||
const actorOf = (actor?: AuthUser) => { if (!actor) throw new McpError("UNAUTHORIZED", "Требуется вход", 401); return actor }
|
||||
async function pollCapacityForPortal(ownerId:string,admin:boolean){
|
||||
async function pollUsageForPortal(ownerId:string,admin:boolean){
|
||||
const options={deadlineAt:Date.now()+3000}
|
||||
let connection:Awaited<ReturnType<typeof connectProbeStorage>>|undefined
|
||||
try{
|
||||
connection=await connectProbeStorage(options)
|
||||
return await readServerPollCapacity({query:(text,values)=>connection!.query(text,values,{timeoutMs:Math.max(1,options.deadlineAt-Date.now())})},ownerId,admin)
|
||||
return await readServerPollUsage({query:(text,values)=>connection!.query(text,values,{timeoutMs:Math.max(1,options.deadlineAt-Date.now())})},ownerId,admin)
|
||||
}catch{return {status:"unavailable" as const}}
|
||||
finally{connection?.release()}
|
||||
}
|
||||
@@ -254,7 +254,7 @@ export function createMcpRoutes(checkClaims: typeof assertPortalClaimsCurrent =
|
||||
(SELECT count(*)::int FROM mcp_requests r JOIN mcp_connections c ON c.id=r.connection_id WHERE ($1::boolean OR c.owner_id=$2) AND r.created_at>now()-interval '24 hours' AND r.status IN ('error','denied')) AS errors,
|
||||
(SELECT count(*)::int FROM mcp_plans p JOIN mcp_connections c ON c.id=p.connection_id WHERE ($1::boolean OR c.owner_id=$2) AND p.state='awaiting-approval' AND p.expires_at>now()) AS approvals,
|
||||
(SELECT count(*)::int FROM mcp_operations o JOIN mcp_connections c ON c.id=o.connection_id WHERE ($1::boolean OR c.owner_id=$2) AND o.state IN ('running','pending')) AS running`, [admin, actor.id])
|
||||
return { ...summary, pollStorageCapacity:await pollCapacityForPortal(actor.id,admin), enabled: (await getMcpSettings()).enabled, observedAt: new Date().toISOString() }
|
||||
return { ...summary, pollStorageUsage:await pollUsageForPortal(actor.id,admin), enabled: (await getMcpSettings()).enabled, observedAt: new Date().toISOString() }
|
||||
})
|
||||
for (const table of ["requests", "plans", "operations", "audit", "drift"] as const) {
|
||||
app.get(`/mcp/${table}`, async request => {
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { coalesceCatalogReads, observationIsCurrent, readCatalogWithObservedCache, withCatalogWriteLock } from "../services/routing-catalog-observation.js"
|
||||
import { recursiveApplyBodySchema, recursiveTargetSchema, recursiveInputRowsSchema } from '../services/recursive-route-validation.js'
|
||||
import { parseRecursiveCatalog, parseRecursiveGatewayCatalog, readRecursiveEffectiveProperties, type RecursiveObservedProperty } from "../services/recursive-route-catalog.js"
|
||||
import { executeRecursiveApply, RecursiveApplyError } from "../services/recursive-apply.js"
|
||||
import { storeRecursiveRoutes } from "../services/recursive-route-store.js"
|
||||
import { planRecursiveIdentities } from "../services/recursive-route-identity.js"
|
||||
import { withApplicationMutationLock, withConfigMutationLock } from "../services/config-mutation-lock.js"
|
||||
import { McpError } from "../modules/mcp/security.js"
|
||||
import { asc, eq } from "drizzle-orm"
|
||||
import { z } from "zod"
|
||||
import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod"
|
||||
@@ -100,7 +101,7 @@ export async function applyRecursiveToServer(
|
||||
source: ConfigRevisionSource,
|
||||
validateExisting?: (rows: ReturnType<typeof parseRecursiveCatalog>) => void | Promise<void>,
|
||||
): Promise<{ pushed: number; deleted: number }> {
|
||||
return withApplicationMutationLock(() => withConfigMutationLock([server.id], async () => {
|
||||
return withCatalogWriteLock(server, "recursive-routes", async () => {
|
||||
await storeRecursiveRoutes(server.id, routes, source, true)
|
||||
const client = MikrotikClient.fromServer(server)
|
||||
return executeRecursiveApply(client, routes.map(toRouterPayload), async () => {
|
||||
@@ -116,7 +117,7 @@ export async function applyRecursiveToServer(
|
||||
await validateExisting?.(parseRecursiveCatalog(observed))
|
||||
return observed
|
||||
}, () => readRecursiveNativeRowsForServer(server))
|
||||
}))
|
||||
})
|
||||
}
|
||||
|
||||
const RevisionIdParamSchema = z.object({ id: z.string().min(1) })
|
||||
@@ -158,16 +159,32 @@ const recursiveDefaults: RecursiveRouteDependencies = {
|
||||
|
||||
/** Strict observation shared by both transports. REST can persist metadata;
|
||||
* observers opt out. An unavailable source always fails this catalog read. */
|
||||
export async function readRecursiveCatalogForServer(server: ServerRow, deps: Pick<RecursiveRouteDependencies, "readRaw" | "readProperty" | "getRoutes" | "saveObserved"> = recursiveDefaults, options: { persistObserved?: boolean } = {}) {
|
||||
const read = async () => {
|
||||
type RecursiveReadDependencies = Pick<RecursiveRouteDependencies, "readRaw" | "readProperty" | "getRoutes" | "saveObserved">
|
||||
|
||||
const readWebRecursiveRows = coalesceCatalogReads(readRecursiveNativeRowsForServer)
|
||||
|
||||
async function observeRecursiveRoutes(server: ServerRow, deps: RecursiveReadDependencies, persist: boolean) {
|
||||
const read = async (fresh: boolean) => {
|
||||
if (!server.enabled) throw new Error("Устройство отключено: каталог маршрутов недоступен")
|
||||
const observed = await readRecursiveEffectiveProperties(await deps.readRaw(server), (id, property) => deps.readProperty(server, id, property))
|
||||
const routes = mergeCachedCountry(parseRecursiveCatalog(observed), await deps.getRoutes(server.id))
|
||||
if (options.persistObserved !== false) await deps.saveObserved(server.id, routes)
|
||||
return { serverId: server.id, routes, live: true, stale: false }
|
||||
const observed = !fresh && persist && deps === recursiveDefaults ? await readWebRecursiveRows(server)
|
||||
: await readRecursiveEffectiveProperties(await deps.readRaw(server), (id, property) => deps.readProperty(server, id, property))
|
||||
const cached = await deps.getRoutes(server.id)
|
||||
const routes = mergeCachedCountry(parseRecursiveCatalog(observed), cached)
|
||||
const current = !persist || deps === recursiveDefaults && await observationIsCurrent(server.id, "recursive-routes", canonicalRecursiveRoutes(routes), canonicalRecursiveRoutes(cached))
|
||||
return { routes, cached, current }
|
||||
}
|
||||
return deps === recursiveDefaults && options.persistObserved !== false
|
||||
? withApplicationMutationLock(() => withConfigMutationLock([server.id], read)) : read()
|
||||
const save = async (snapshot: Awaited<ReturnType<typeof read>>) => {
|
||||
await deps.saveObserved(server.id, snapshot.routes)
|
||||
return { ...snapshot, cached: await deps.getRoutes(server.id), current: true }
|
||||
}
|
||||
if (deps === recursiveDefaults) return readCatalogWithObservedCache(server, read, save)
|
||||
const snapshot = await read(true)
|
||||
return snapshot.current ? snapshot : save(snapshot)
|
||||
}
|
||||
|
||||
export async function readRecursiveCatalogForServer(server: ServerRow, deps: RecursiveReadDependencies = recursiveDefaults, options: { persistObserved?: boolean } = {}) {
|
||||
const { routes } = await observeRecursiveRoutes(server, deps, options.persistObserved !== false)
|
||||
return { serverId: server.id, routes, live: true, stale: false }
|
||||
}
|
||||
|
||||
export async function readRecursiveNativeRowsForServer(server: ServerRow) {
|
||||
@@ -187,22 +204,18 @@ export async function readRecursiveGatewaysForServer(server: ServerRow, deps: Pi
|
||||
|
||||
/** Legacy application read, including its explicit stale fallback. MCP observers
|
||||
* share the source/parser while leaving cache and revision history untouched. */
|
||||
export async function readRecursiveRoutesForServer(server: ServerRow, deps: Pick<RecursiveRouteDependencies, "readRaw" | "readProperty" | "getRoutes" | "saveObserved"> = recursiveDefaults, options: { persistObserved?: boolean } = {}) {
|
||||
export async function readRecursiveRoutesForServer(server: ServerRow, deps: RecursiveReadDependencies = recursiveDefaults, options: { persistObserved?: boolean } = {}) {
|
||||
if (!server.enabled) throw new Error("Устройство отключено: опрос маршрутов недоступен")
|
||||
const read = async () => {
|
||||
const cached = await deps.getRoutes(server.id)
|
||||
try {
|
||||
const result = await readRecursiveCatalogForServer(server, deps, options)
|
||||
const routes = options.persistObserved === false
|
||||
? planRecursiveIdentities(cached, result.routes, new Set(), "observed").rows.map((row, index) => ({ ...row, id: row.id || result.routes[index].id }))
|
||||
: await deps.getRoutes(server.id)
|
||||
return { ...result, routes }
|
||||
} catch {
|
||||
return { serverId: server.id, routes: cached, live: false, stale: true, error: "Не удалось подтвердить живой каталог; возвращена сохранённая конфигурация" }
|
||||
}
|
||||
try {
|
||||
const observed = await observeRecursiveRoutes(server, deps, options.persistObserved !== false)
|
||||
const routes = options.persistObserved === false
|
||||
? planRecursiveIdentities(observed.cached, observed.routes, new Set(), "observed").rows.map((row, index) => ({ ...row, id: row.id || observed.routes[index].id }))
|
||||
: observed.cached
|
||||
return { serverId: server.id, routes, live: true, stale: false }
|
||||
} catch (error) {
|
||||
if (error instanceof McpError && (error.code === "CONFIGURATION_BUSY" || error.code === "STATE_CONFLICT")) throw error
|
||||
return { serverId: server.id, routes: await deps.getRoutes(server.id), live: false, stale: true, error: "Не удалось подтвердить живой каталог; возвращена сохранённая конфигурация" }
|
||||
}
|
||||
return deps === recursiveDefaults && options.persistObserved !== false
|
||||
? withApplicationMutationLock(() => withConfigMutationLock([server.id], read)) : read()
|
||||
}
|
||||
|
||||
export function createRecursiveRoutes(overrides: Partial<RecursiveRouteDependencies> = {}): FastifyPluginAsyncZod {
|
||||
@@ -218,6 +231,7 @@ export function createRecursiveRoutes(overrides: Partial<RecursiveRouteDependenc
|
||||
try {
|
||||
return reply.send(await readRecursiveCatalogForServer(server, deps))
|
||||
} catch (error) {
|
||||
if (error instanceof McpError) throw error
|
||||
return reply.status(503).send({ error: error instanceof Error ? error.message : "Не удалось прочитать каталог маршрутов" })
|
||||
}
|
||||
})
|
||||
@@ -276,6 +290,7 @@ export function createRecursiveRoutes(overrides: Partial<RecursiveRouteDependenc
|
||||
return reply.send({ ok: true, serverId, routes: stored, pushedRoutes: result.pushed })
|
||||
} catch (err) {
|
||||
const receipt = recursiveFailureReceipt(err, result)
|
||||
if (!receipt && err instanceof McpError) throw err
|
||||
return reply.status(receipt ? 502 : 500).send({ error: String(err), serverId, ...receipt })
|
||||
}
|
||||
})
|
||||
@@ -313,6 +328,7 @@ export function createRecursiveRoutes(overrides: Partial<RecursiveRouteDependenc
|
||||
return reply.send({ ok: true, serverId: server.id, routes: stored, pushedRoutes: result.pushed })
|
||||
} catch (err) {
|
||||
const receipt = recursiveFailureReceipt(err, result)
|
||||
if (!receipt && err instanceof McpError) throw err
|
||||
return reply.status(receipt ? 502 : 500).send({ error: String(err), serverId: server.id, ...receipt })
|
||||
}
|
||||
})
|
||||
|
||||
@@ -5,6 +5,7 @@ import { createSchedulerRoutes } from "./scheduler.js"
|
||||
import type { SchedulerRunReceipt } from "../services/scheduler-recorded-run.js"
|
||||
import { pauseSchedulerJobsAndWait, resumeSchedulerJobs } from "../services/scheduler-running.js"
|
||||
import { runSchedulerJobNow } from "../services/scheduler.js"
|
||||
import { ConfigurationBusyError } from "../services/config-mutation-lock.js"
|
||||
const receipt: SchedulerRunReceipt = { status: "ok", error: null, result: { v: 1, job: "backups", sampledAt: "2026-10-01T00:00:00Z", due: true, created: 1, failures: 0, pruned: 0 } }
|
||||
async function setup(patch: Partial<Parameters<typeof createSchedulerRoutes>[0]> = {}) {
|
||||
const app = Fastify(); let calls = 0
|
||||
@@ -39,3 +40,13 @@ test("collector or journal rejection remains explicit without a fabricated recei
|
||||
const { app } = await setup({ run: async () => { throw Error("journal not confirmed; retry may repeat operations") } })
|
||||
try { const response = await app.inject({ method: "POST", url: "/scheduler/jobs/backups/run-now" }); assert.equal(response.statusCode, 500); assert.match(response.json().error, /retry may repeat/); assert.equal(response.json().result, undefined) } finally { await app.close() }
|
||||
})
|
||||
|
||||
test("configuration contention is distinguishable from an already running job", async () => {
|
||||
const busy = new ConfigurationBusyError("server")
|
||||
const { app } = await setup({ run: async () => { throw busy } })
|
||||
try {
|
||||
const response = await app.inject({ method: "POST", url: "/scheduler/jobs/uptime_ping/run-now" })
|
||||
assert.equal(response.statusCode, 409)
|
||||
assert.deepEqual(response.json(), { code: "CONFIGURATION_BUSY", error: busy.message })
|
||||
} finally { await app.close() }
|
||||
})
|
||||
@@ -51,11 +51,11 @@ return async (app) => {
|
||||
return reply.send({ ok: result.status === "ok", result, status, ...(statusError ? { statusError } : {}) })
|
||||
} catch (e) {
|
||||
const statusCode = (e as Error & { statusCode?: number }).statusCode
|
||||
if (statusCode === 409) {
|
||||
const paused = (e as Error & { code?: string }).code === "SCHEDULER_PAUSED"
|
||||
return reply.status(409).send({ error: paused ? "Планировщик приостановлен для операции с базой" : "Задача уже выполняется" })
|
||||
}
|
||||
const msg = e instanceof Error ? e.message : String(e)
|
||||
if (statusCode === 409) {
|
||||
const code = (e as Error & { code?: string }).code
|
||||
return reply.status(409).send({ error: msg, ...(code ? { code } : {}) })
|
||||
}
|
||||
return reply.status(500).send({ error: msg })
|
||||
}
|
||||
})
|
||||
|
||||
@@ -210,7 +210,9 @@ const trafficFlowRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
|
||||
app.get("/traffic/flow/map-hops", async (req, reply) => {
|
||||
const query = analyticsQuery(req)
|
||||
return reply.send(await readFlowWindow(query.minutes, minutes => buildFlowMapHops({ ...query, minutes }), mcpDatabaseRequestSignal()))
|
||||
const includeCurrentMinute = (req.query as { range?: string }).range?.toLowerCase() === "1m"
|
||||
const requestedMinutes = includeCurrentMinute ? 1 : query.minutes
|
||||
return reply.send(await readFlowWindow(requestedMinutes, minutes => buildFlowMapHops({ ...query, minutes, includeCurrentMinute }), mcpDatabaseRequestSignal()))
|
||||
})
|
||||
|
||||
app.get("/traffic/flow/monthly", async (req, reply) => {
|
||||
|
||||
@@ -13,12 +13,13 @@ import {
|
||||
} from "../services/traffic-collector.js"
|
||||
import { refreshScheduler } from "../services/scheduler.js"
|
||||
import { collectTrafficManually } from "../services/manual-traffic-collection.js"
|
||||
import { readTrafficLiveSample, TrafficLiveSourceChanged } from "../services/traffic-live.js"
|
||||
import { readTrafficLiveInterfaces, readTrafficLiveSample, TrafficLiveSourceChanged } from "../services/traffic-live.js"
|
||||
import { MikrotikClient, MikrotikError } from "../services/mikrotik.js"
|
||||
import { getEnabledServerById } from "../services/wireguard-live.js"
|
||||
import { readTrafficCollectionContext } from "../services/traffic-collection-state.js"
|
||||
import { readServerTrafficHistory, readServerTrafficHistoryWithSeries, readServerTrafficInterfaces } from "../services/traffic-history-read.js"
|
||||
import { mergeBuiltTraffic } from "../services/traffic-rate.js"
|
||||
import { getUserById } from "../modules/users/service/users-service.js"
|
||||
import {
|
||||
buildBoundInterfaceTraffic,
|
||||
buildUserTrafficList,
|
||||
@@ -106,7 +107,17 @@ const trafficRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
})
|
||||
app.get("/traffic/servers/:id/live", async (req, reply) => {
|
||||
const p = req.params as { id?: string | number }
|
||||
const q = req.query as { iface?: string }
|
||||
const q = req.query as { iface?: string; ifaces?: string; once?: string }
|
||||
const validIface = (name: unknown): name is string => typeof name === "string" && Boolean(name.trim()) &&
|
||||
name.length <= 128 && name !== "__all__" && !/[,\x00-\x1f\x7f]/.test(name)
|
||||
const interfaces = typeof q.ifaces === "string" ? q.ifaces.split(",") : []
|
||||
if (q.ifaces !== undefined && (q.once !== "1" || q.iface !== undefined || !interfaces.length ||
|
||||
interfaces.length > 16 || new Set(interfaces).size !== interfaces.length || !interfaces.every(validIface))) {
|
||||
return reply.code(400).send({ error: "Укажите до 16 разных интерфейсов для live-измерения" })
|
||||
}
|
||||
if (q.once === "1" && !interfaces.length && !validIface(q.iface)) {
|
||||
return reply.code(400).send({ error: "Укажите один интерфейс для live-измерения" })
|
||||
}
|
||||
const readServer = (id: string | number, signal?: AbortSignal) => withDatabaseApiRequest(async () => {
|
||||
signal?.throwIfAborted()
|
||||
const row = await getEnabledServerById(id)
|
||||
@@ -117,11 +128,33 @@ const trafficRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
if (!server || !server.enabled) return reply.status(404).send({ error: "Server not found" })
|
||||
|
||||
const onlyInterface = q.iface && q.iface !== "__all__" ? q.iface : undefined
|
||||
const client = MikrotikClient.fromServer(server)
|
||||
const cache = { names: onlyInterface ? [onlyInterface] : [] as string[], joinedFailed: false }
|
||||
const assertSource = async (signal: AbortSignal) => {
|
||||
const current = await readServer(server.id, signal)
|
||||
if (!current) throw new TrafficLiveSourceChanged("Устройство выключено или удалено. Переподключите live-поток")
|
||||
if (Date.parse(current.updatedAt) !== Date.parse(server.updatedAt)) throw new TrafficLiveSourceChanged("Конфигурация устройства изменилась. Переподключите live-поток")
|
||||
}
|
||||
const readSample = (signal: AbortSignal) => readTrafficLiveSample(client, onlyInterface, cache, signal, () => assertSource(signal))
|
||||
const abort = new AbortController()
|
||||
const onClose = () => abort.abort()
|
||||
registerDatabaseStreamAbort(req, onClose)
|
||||
if (abort.signal.aborted) return reply.code(503).send({ error: "Выполняется операция с базой приложения" })
|
||||
if (reply.raw.destroyed) return
|
||||
if (q.once === "1") {
|
||||
reply.raw.once("close", onClose)
|
||||
try {
|
||||
const sample = interfaces.length
|
||||
? { interfaces: await readTrafficLiveInterfaces(client, interfaces, abort.signal, () => assertSource(abort.signal)) }
|
||||
: await readSample(abort.signal)
|
||||
return reply.header("Cache-Control", "no-store").send(sample)
|
||||
} catch {
|
||||
if (!reply.raw.destroyed) return reply.code(503).send({ error: "Live-измерение интерфейса недоступно" })
|
||||
return
|
||||
} finally {
|
||||
reply.raw.off("close", onClose)
|
||||
}
|
||||
}
|
||||
reply.raw.on("close", onClose)
|
||||
|
||||
reply.hijack()
|
||||
@@ -144,17 +177,10 @@ const trafficRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
reply.raw.writeHead(200, sseHeaders)
|
||||
reply.raw.write(":\n\n")
|
||||
|
||||
const client = MikrotikClient.fromServer(server)
|
||||
const cache = { names: onlyInterface ? [onlyInterface] : [] as string[], joinedFailed: false }
|
||||
|
||||
try {
|
||||
while (!abort.signal.aborted) {
|
||||
try {
|
||||
const sample = await readTrafficLiveSample(client, onlyInterface, cache, abort.signal, async () => {
|
||||
const current = await readServer(server.id, abort.signal)
|
||||
if (!current) throw new TrafficLiveSourceChanged("Устройство выключено или удалено. Live-поток остановлен")
|
||||
if (Date.parse(current.updatedAt) !== Date.parse(server.updatedAt)) throw new TrafficLiveSourceChanged("Конфигурация устройства изменилась. Переподключите live-поток")
|
||||
})
|
||||
const sample = await readSample(abort.signal)
|
||||
if (abort.signal.aborted) break
|
||||
writeSse(reply.raw, "sample", sample)
|
||||
} catch (error) {
|
||||
@@ -211,9 +237,9 @@ const trafficRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
const minutes = rangeToMinutes(q.range)
|
||||
const rangeEndMs = Date.now()
|
||||
const rangeStartMs = rangeEndMs - minutes * 60_000
|
||||
const users = await buildUserTrafficList(rangeStartMs, rangeEndMs)
|
||||
const user = users.find((u) => u.id === id)
|
||||
if (!user) return reply.status(404).send({ error: "Пользователь не найден" })
|
||||
const source = await getUserById(id)
|
||||
if (!source) return reply.status(404).send({ error: "Пользователь не найден" })
|
||||
const [user] = await buildUserTrafficList(rangeStartMs, rangeEndMs, { users: [source] })
|
||||
return reply.send({ user })
|
||||
})
|
||||
|
||||
|
||||
@@ -1,8 +1,24 @@
|
||||
import type { MikrotikClient } from "./mikrotik.js"
|
||||
import { nativeBgpRows, type NativeBgpRow } from "./bgp-export-model.js"
|
||||
import { bgpFilterName } from "./bgp-filter-binding-model.js"
|
||||
import { readOspfEffectiveDisabled } from "./ospf-effective-disabled.js"
|
||||
import { McpError } from "../modules/mcp/security.js"
|
||||
|
||||
export async function readBgpInstanceContext(client: Pick<MikrotikClient, "post">, row: NativeBgpRow) {
|
||||
const read = async (key: "vrf" | "routing-table") => {
|
||||
const value = row[key]
|
||||
return value === undefined || value === ""
|
||||
? bgpFilterName(await client.post("/routing/bgp/instance/get", { ".id": row[".id"], "value-name": key }))
|
||||
: bgpFilterName({ ret: value })
|
||||
}
|
||||
const [observedVrf, observedTable] = await Promise.all([read("vrf"), read("routing-table")])
|
||||
const vrf = observedVrf || "main"
|
||||
// Only infer the routing table when the instance uses the built-in VRF.
|
||||
const table = observedTable || (vrf === "main" ? "main" : null)
|
||||
if (!table) throw new McpError("STATE_UNAVAILABLE", "Не подтверждена таблица BGP instance", 409)
|
||||
return { vrf, table }
|
||||
}
|
||||
|
||||
/** Prove a configured peer, including RouterOS releases that omit the D flag. */
|
||||
export async function readStaticBgpConnection(client: Pick<MikrotikClient, "get" | "post">, id: string) {
|
||||
const connections = nativeBgpRows(await client.get("/routing/bgp/connection")), target = connections.find(row => row[".id"] === id)
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { test } from "node:test"
|
||||
import { readBgpRib } from "./bgp-rib-observation.js"
|
||||
|
||||
const table = "rtab-antiblock"
|
||||
const primary = "*B000001"
|
||||
const standby = "*B000002"
|
||||
const selection = { table, mode: "page" as const, limit: 500, offset: 0 }
|
||||
|
||||
function route(index: number, overrides: Record<string, string> = {}): Record<string, string> {
|
||||
return {
|
||||
".id": "*" + (index + 1).toString(16).toUpperCase(),
|
||||
afi: "ip", bgp: "true", dynamic: "true", "routing-table": table,
|
||||
"dst-address": `198.18.${Math.floor(index / 256)}.${index % 256}/32`,
|
||||
contribution: "active", active: "true", "bgp.peer-cache-id": primary,
|
||||
gateway: "10.255.255.100", "immediate-gw": "10.253.250.1%gre-jh-test-msk",
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function fixture(rows: Record<string, string>[]) {
|
||||
const reads = { routePages: 0, counts: 0, sessionFilters: new Set<string>() }
|
||||
const client = {
|
||||
async get<T>(path: string, _timeout?: number, _signal?: AbortSignal, maxResponseBytes?: number) {
|
||||
assert((maxResponseBytes ?? 8 * 1024 * 1024) <= 8 * 1024 * 1024, "MikrotikClient rejects GET limits above 8 MiB")
|
||||
const { pathname, searchParams } = new URL(path, "http://router.invalid")
|
||||
if (pathname === "/routing/table") return [{ ".id": "*1", name: table }] as T
|
||||
assert.equal(pathname, "/routing/route")
|
||||
assert(!searchParams.has("bgp") && !searchParams.has("afi"), "Independent RIB read must include unclassified rows")
|
||||
assert.equal(searchParams.get("routing-table"), table)
|
||||
reads.routePages++
|
||||
const properties = searchParams.get(".proplist")?.split(",")
|
||||
assert(properties)
|
||||
return rows.filter(row => row["routing-table"] === table)
|
||||
.map(row => Object.fromEntries(Object.entries(row).filter(([key]) => properties.includes(key)))) as T
|
||||
},
|
||||
async post<T>(path: string, body: Record<string, string | string[]>) {
|
||||
assert.equal(path, "/routing/route/print")
|
||||
assert.equal(body["count-only"], "")
|
||||
const query = body[".query"]
|
||||
assert(Array.isArray(query))
|
||||
const peer = query.find(word => word.startsWith("bgp.peer-cache-id="))?.split("=")[1]
|
||||
const session = query.find(word => word.startsWith("bgp.session="))?.slice("bgp.session=".length)
|
||||
assert.deepEqual(query, [
|
||||
"routing-table=" + table, "bgp=true", "afi=ip", "afi=ip4", "#|",
|
||||
...(peer ? ["bgp.peer-cache-id=" + peer] : []),
|
||||
...(session ? ["bgp.session=" + session] : []),
|
||||
])
|
||||
reads.counts++
|
||||
if (session !== undefined) reads.sessionFilters.add(session)
|
||||
const count = rows.filter(row =>
|
||||
row["routing-table"] === table && row.bgp === "true" && (row.afi === "ip" || row.afi === "ip4") &&
|
||||
(!peer || row["bgp.peer-cache-id"] === peer) && (!session || row["bgp.session"] === session),
|
||||
).length
|
||||
return { ret: String(count) } as T
|
||||
},
|
||||
}
|
||||
return { client, reads }
|
||||
}
|
||||
|
||||
test("positive native count is cheap; a verified zero independently reads the target table", async () => {
|
||||
const nonempty = fixture([route(0)])
|
||||
assert.equal((await readBgpRib(nonempty.client, { ...selection, mode: "count" })).total, 1)
|
||||
assert.equal(nonempty.reads.routePages, 0)
|
||||
const { client, reads } = fixture([route(0, { "routing-table": "main" }), route(1, { afi: "ip6", "dst-address": "2001:db8::/32" })])
|
||||
const result = await readBgpRib(client, { ...selection, mode: "count" })
|
||||
assert.equal(result.total, 0)
|
||||
assert(reads.counts > 0)
|
||||
assert.equal(reads.routePages, 1)
|
||||
|
||||
for (const invalid of [[], {}, { ret: "" }, { ret: "0oops" }, { ret: "-1" }]) {
|
||||
const broken = { ...client, post: async <T>() => invalid as T }
|
||||
await assert.rejects(readBgpRib(broken, { ...selection, mode: "count" }))
|
||||
}
|
||||
})
|
||||
|
||||
test("zero fails closed on a missed IPv4 BGP route or ambiguous native BGP evidence", async () => {
|
||||
const staticRow = { ".id": "*70", afi: "ip", static: "true", "routing-table": table, "dst-address": "198.18.250.1/32", contribution: "active", active: "true" }
|
||||
const justStatic = fixture([staticRow])
|
||||
assert.equal((await readBgpRib(justStatic.client, { ...selection, mode: "count" })).total, 0)
|
||||
assert.equal(justStatic.reads.routePages, 1)
|
||||
for (const ambiguous of [route(0), { ...staticRow, "bgp.peer-cache-id": primary }, { ...staticRow, "belongs-to": "BGP IP routes from 192.0.2.1" }]) {
|
||||
const { client } = fixture([ambiguous])
|
||||
const wrongZero = { ...client, post: async <T>() => ({ ret: "0" }) as T }
|
||||
await assert.rejects(readBgpRib(wrongZero, { ...selection, mode: "count" }))
|
||||
}
|
||||
})
|
||||
|
||||
test("matching peer paths include filtered and inactive alternatives with distinct IDs", async () => {
|
||||
const filtered = route(1, { "dst-address": "198.18.0.0/32", contribution: "filtered", filtered: "true", active: "false", "bgp.peer-cache-id": standby })
|
||||
const candidate = route(2, { afi: "ip4", contribution: "candidate", active: "false" })
|
||||
const { client } = fixture([route(0), filtered, candidate, route(3, { afi: "ip6", "dst-address": "2001:db8::/32" })])
|
||||
const result = await readBgpRib(client, selection)
|
||||
assert.equal(result.total, 3)
|
||||
assert(result.items)
|
||||
const samePrefix = result.items.filter(item => item.prefix === "198.18.0.0/32")
|
||||
assert.equal(samePrefix.length, 2)
|
||||
assert.equal(new Set(samePrefix.map(item => item.id)).size, 2)
|
||||
assert.equal(samePrefix.find(item => item.peerCacheId === standby)?.filtered, true)
|
||||
assert.equal(result.items.find(item => item.id === candidate[".id"])?.active, false)
|
||||
const otherPeer = await readBgpRib(client, { ...selection, peerCacheId: standby })
|
||||
assert.equal(otherPeer.total, 1)
|
||||
assert.equal(otherPeer.items?.[0]?.id, filtered[".id"])
|
||||
})
|
||||
|
||||
test("RouterOS static rows without afi coexist with BGP paths identified by session name", async () => {
|
||||
const nativeStatic = {
|
||||
".id": "*800002F2", "dst-address": "5.180.136.242/32", "routing-table": table,
|
||||
contribution: "(unknown)", static: "true",
|
||||
}
|
||||
const sessionName = "ibgp-jh-test-anycast-1"
|
||||
const received = route(0, { "bgp.session": sessionName })
|
||||
delete received["bgp.peer-cache-id"]
|
||||
const { client, reads } = fixture([nativeStatic, received])
|
||||
const mixed = await readBgpRib(client, selection)
|
||||
assert.equal(mixed.total, 1)
|
||||
assert.deepEqual(mixed.items.map(item => [item.id, item.prefix, item.peerCacheId, item.session]), [
|
||||
[received[".id"], received["dst-address"], null, sessionName],
|
||||
])
|
||||
const bySession = await readBgpRib(client, { ...selection, sessionName })
|
||||
assert.equal(bySession.sessionName, sessionName)
|
||||
assert.equal(bySession.total, 1)
|
||||
assert.equal(bySession.items[0].id, received[".id"])
|
||||
assert.equal((await readBgpRib(client, { ...selection, mode: "count", sessionName: "ibgp-other-1" })).total, 0)
|
||||
assert.deepEqual(reads.sessionFilters, new Set([sessionName, "ibgp-other-1"]))
|
||||
assert(bySession.fingerprint)
|
||||
await assert.rejects(readBgpRib(client, { ...selection, expectedFingerprint: bySession.fingerprint }))
|
||||
await assert.rejects(readBgpRib(client, { ...selection, sessionName, peerCacheId: primary }))
|
||||
await assert.rejects(readBgpRib(fixture([received, route(1)]).client, { ...selection, mode: "count", sessionName: "ibgp-other-1" }))
|
||||
for (const invalid of [" ", sessionName + "\r"]) {
|
||||
const malformed = fixture([{ ...received, "bgp.session": invalid }]).client
|
||||
await assert.rejects(readBgpRib(malformed, { ...selection, mode: "count", sessionName }))
|
||||
}
|
||||
const onlyStatic = fixture([nativeStatic])
|
||||
assert.equal((await readBgpRib(onlyStatic.client, { ...selection, mode: "count" })).total, 0)
|
||||
assert.equal(onlyStatic.reads.routePages, 1)
|
||||
|
||||
const noOrigin: Record<string, string> = { ...nativeStatic }
|
||||
delete noOrigin.static
|
||||
for (const ambiguous of [noOrigin, { ...nativeStatic, "bgp.session": "ibgp-to-jh-1" }, { ...noOrigin, bgp: "true" }]) {
|
||||
await assert.rejects(readBgpRib(fixture([ambiguous]).client, { ...selection, mode: "count" }))
|
||||
}
|
||||
})
|
||||
|
||||
test("missing table and missing peer attribution cannot prove a scoped zero", async () => {
|
||||
const { client } = fixture([])
|
||||
const missingTable = { ...client, get: async <T>() => [] as T }
|
||||
await assert.rejects(readBgpRib(missingTable, { ...selection, mode: "count" }), /table/i)
|
||||
const unknownPeer = route(0)
|
||||
delete unknownPeer["bgp.peer-cache-id"]
|
||||
const result = await readBgpRib(fixture([unknownPeer]).client, selection)
|
||||
assert.equal(result.items?.[0].peerCacheId, null)
|
||||
await assert.rejects(readBgpRib(fixture([unknownPeer]).client, { ...selection, mode: "count", peerCacheId: standby }), /peer/i)
|
||||
})
|
||||
|
||||
test("pages beyond 13,000 preserve snapshot identity and reject a changed next page", async () => {
|
||||
const rows = Array.from({ length: 13_705 }, (_, i) => route(i))
|
||||
const { client } = fixture(rows)
|
||||
const first = await readBgpRib(client, selection)
|
||||
assert.equal(first.total, rows.length)
|
||||
assert.equal(first.items?.length, selection.limit)
|
||||
assert.equal(first.nextOffset, selection.limit)
|
||||
assert(first.fingerprint)
|
||||
rows.reverse()
|
||||
const tailSelection = { ...selection, offset: 13_700, expectedFingerprint: first.fingerprint }
|
||||
const tail = await readBgpRib(client, tailSelection)
|
||||
assert.equal(tail.items?.length, 5)
|
||||
assert.equal(tail.nextOffset, null)
|
||||
assert.equal(tail.fingerprint, first.fingerprint)
|
||||
rows[0] = { ...rows[0], gateway: "10.255.255.101" }
|
||||
await assert.rejects(readBgpRib(client, tailSelection))
|
||||
})
|
||||
@@ -0,0 +1,122 @@
|
||||
import { createHash } from "node:crypto"
|
||||
import { isIP } from "node:net"
|
||||
import { z } from "zod"
|
||||
import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js"
|
||||
import type { MikrotikClient } from "./mikrotik.js"
|
||||
|
||||
const rosId = z.string().regex(/^\*[0-9a-z]+$/i).max(64)
|
||||
const exactName = z.string().min(1).refine(name => name.trim() === name && !/[\u0000-\u001f\u007f]/.test(name))
|
||||
const sessionIdentity = exactName.max(512)
|
||||
export const bgpRibSelection = z.object({
|
||||
table: exactName.max(100),
|
||||
peerCacheId: rosId.optional(),
|
||||
sessionName: sessionIdentity.optional(),
|
||||
mode: z.enum(["count", "page"]).default("count"),
|
||||
offset: z.number().int().min(0).max(100_000).default(0),
|
||||
limit: z.number().int().min(1).max(500).default(100),
|
||||
expectedFingerprint: z.string().regex(/^[a-f0-9]{64}$/).optional(),
|
||||
}).strict().refine(input => !(input.peerCacheId && input.sessionName), { message: "Choose only one BGP peer selector" })
|
||||
|
||||
const nativeRow = z.record(z.string(), z.unknown())
|
||||
const otherProtocols = ["static", "connect", "ospf", "dhcp", "rip", "isis", "modem", "slaac", "vpn", "fantasy"]
|
||||
const properties = [".id", "afi", "dst-address", "routing-table", "bgp", "bgp.peer-cache-id", "bgp.session", "belongs-to", "contribution", "active", "filtered", "gateway", "immediate-gw", ...otherProtocols].join(",")
|
||||
const otherFamilies = new Set(["ip6", "ipv6", "link", "vpnv4", "vpnv6", "l2vpn", "l2vpn-cisco", "l2vpn-link", "evpn", "mip4", "mip6"])
|
||||
type Selection = z.infer<typeof bgpRibSelection>
|
||||
const text = z.string().max(512)
|
||||
export class BgpRibChanged extends Error {}
|
||||
const contributions = new Set(["active", "filtered", "candidate", "best-candidate", "unreachable"])
|
||||
|
||||
function optionalFlag(value: unknown) {
|
||||
if (value === undefined) return null
|
||||
if (value === true || value === "true" || value === "yes") return true
|
||||
if (value === false || value === "false" || value === "no") return false
|
||||
throw new Error("Unrecognized RouterOS flag")
|
||||
}
|
||||
|
||||
function ipv4Row(row: Record<string, unknown>, table: string) {
|
||||
if (row["routing-table"] !== table) throw new Error("Unexpected native route table")
|
||||
if (otherFamilies.has(String(row.afi))) return null
|
||||
const bgp = optionalFlag(row.bgp)
|
||||
const other = otherProtocols.some(key => optionalFlag(row[key]) === true)
|
||||
// Disabled static routes on RouterOS can omit afi. Their explicit origin still has to agree with the BGP evidence below.
|
||||
const missingNonBgpAfi = row.afi === undefined && other && bgp !== true
|
||||
if (row.afi !== "ip" && row.afi !== "ip4" && !missingNonBgpAfi) throw new Error("Unrecognized RouterOS address family")
|
||||
if (bgp !== true) {
|
||||
// Missing origin flags occur on some RouterOS REST projections. Do not lose filtered paths or certify a false zero.
|
||||
if (row["bgp.peer-cache-id"] || row["bgp.session"] || /\bbgp\b/i.test(String(row["belongs-to"] ?? "")) || bgp === null && !other) throw new Error("Unconfirmed native route origin")
|
||||
return null
|
||||
}
|
||||
if (other) throw new Error("Conflicting native route origins")
|
||||
const dst = text.parse(row["dst-address"])
|
||||
const prefix = isIP(dst) === 4 ? dst + "/32" : dst
|
||||
if (isIP(prefix.split("/")[0]) !== 4 || canonicalBgpPolicyPrefix(prefix) !== prefix) throw new Error("Invalid IPv4 destination")
|
||||
const id = rosId.parse(row[".id"])
|
||||
const peerCacheId = row["bgp.peer-cache-id"] === undefined ? null : rosId.parse(row["bgp.peer-cache-id"])
|
||||
const contribution = text.nullable().parse(row.contribution ?? null)
|
||||
const activeFlag = optionalFlag(row.active), filteredFlag = optionalFlag(row.filtered)
|
||||
const known = contribution !== null && contributions.has(contribution)
|
||||
if (known && (activeFlag !== null && activeFlag !== (contribution === "active") ||
|
||||
filteredFlag !== null && filteredFlag !== (contribution === "filtered"))) throw new Error("Conflicting native route flags")
|
||||
return {
|
||||
id, prefix, table, peerCacheId, contribution,
|
||||
active: activeFlag ?? (known ? contribution === "active" : null),
|
||||
filtered: filteredFlag ?? (known ? contribution === "filtered" : null),
|
||||
session: sessionIdentity.nullable().parse(row["bgp.session"] ?? null),
|
||||
gateway: text.nullable().parse(row.gateway ?? null), immediateGateway: text.nullable().parse(row["immediate-gw"] ?? null),
|
||||
}
|
||||
}
|
||||
|
||||
/** Counts run on RouterOS. Page offsets use deterministic route IDs and a digest over the full selection. */
|
||||
export async function readBgpRib(client: Pick<MikrotikClient, "get" | "post">, input: Selection,
|
||||
beforeRead: () => Promise<unknown> = async () => {}, signal?: AbortSignal) {
|
||||
const { table, peerCacheId, sessionName, mode, limit, offset, expectedFingerprint } = bgpRibSelection.parse(input)
|
||||
if (offset > 0 && !expectedFingerprint || mode === "count" && (offset || expectedFingerprint)) throw new Error("Invalid RIB page cursor")
|
||||
const query = ["routing-table=" + table, "bgp=true", "afi=ip", "afi=ip4", "#|"]
|
||||
const peer = peerCacheId ? { field: "peerCacheId", native: "bgp.peer-cache-id", value: peerCacheId } as const
|
||||
: sessionName ? { field: "session", native: "bgp.session", value: sessionName } as const : null
|
||||
const tablePath = "/routing/table?.proplist=.id,name,disabled,invalid&name=" + encodeURIComponent(table)
|
||||
const tableIdentity = async () => {
|
||||
const raw = await client.get<unknown>(tablePath, 10_000, signal, 16_384, beforeRead)
|
||||
if (!Array.isArray(raw) || raw.length !== 1) throw new Error("Missing or ambiguous routing table")
|
||||
const row = nativeRow.parse(raw[0])
|
||||
if (row.name !== table || optionalFlag(row.disabled) || optionalFlag(row.invalid)) throw new Error("Routing table unavailable")
|
||||
return rosId.parse(row[".id"])
|
||||
}
|
||||
const nativeCount = async (scoped = false) => {
|
||||
const filter = scoped && peer ? [...query, peer.native + "=" + peer.value] : query
|
||||
const raw = await client.post<unknown>("/routing/route/print", { "count-only": "", ".query": filter }, 15_000, signal, beforeRead)
|
||||
const { ret } = z.object({ ret: z.string().regex(/^(?:0|[1-9]\d{0,14})$/) }).strict().parse(raw)
|
||||
return Number(ret)
|
||||
}
|
||||
const identity = await tableIdentity()
|
||||
const allCount = await nativeCount()
|
||||
type Item = NonNullable<ReturnType<typeof ipv4Row>>
|
||||
let items: Item[] = [], fingerprint: string | null = null, total = allCount, nextOffset: number | null = null
|
||||
if (mode === "page" || peer || allCount === 0) {
|
||||
if (allCount > 100_000) throw new Error("RIB row limit exceeded")
|
||||
const path = "/routing/route?.proplist=" + properties + "&routing-table=" + encodeURIComponent(table)
|
||||
const raw = await client.get<unknown>(path, 30_000, signal, 8 * 1024 * 1024, beforeRead)
|
||||
if (!Array.isArray(raw) || raw.length > 100_000) throw new Error("Invalid or oversized RIB view")
|
||||
const ids = new Set<string>(), selected: Item[] = []
|
||||
for (const rawRow of raw) {
|
||||
const observed = ipv4Row(nativeRow.parse(rawRow), table)
|
||||
if (!observed) continue
|
||||
if (ids.has(observed.id)) throw new Error("Duplicate native RIB identity")
|
||||
ids.add(observed.id)
|
||||
if (peer && !observed[peer.field]) throw new Error("Native peer identity unavailable")
|
||||
if (!peer || observed[peer.field] === peer.value) selected.push(observed)
|
||||
}
|
||||
if (allCount !== ids.size || selected.length !== await nativeCount(true)) throw new BgpRibChanged("Native RIB count changed or view incomplete")
|
||||
total = selected.length
|
||||
if (mode === "page") {
|
||||
selected.sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0)
|
||||
const peerScope = sessionName ? { sessionName } : peerCacheId ?? null
|
||||
fingerprint = createHash("sha256").update(JSON.stringify([table, identity, peerScope, selected])).digest("hex")
|
||||
if (expectedFingerprint && fingerprint !== expectedFingerprint || offset > total) throw new BgpRibChanged("RIB snapshot changed; restart at offset 0")
|
||||
items = selected.slice(offset, offset + limit)
|
||||
nextOffset = offset + items.length < total ? offset + items.length : null
|
||||
}
|
||||
}
|
||||
if (identity !== await tableIdentity()) throw new BgpRibChanged("Routing table changed during observation")
|
||||
return { family: "ipv4", table, peerCacheId: peerCacheId ?? null, sessionName: sessionName ?? null, mode, total, items, nextOffset, fingerprint, source: "/routing/route", atomicSnapshot: false }
|
||||
}
|
||||
@@ -14,10 +14,10 @@ const held = new AsyncLocalStorage<ServerLockCompletion>()
|
||||
const applicationLease = new AsyncLocalStorage<LockCompletion>()
|
||||
const collectorLease = new AsyncLocalStorage<LockCompletion>()
|
||||
const applicationLockKey = "hashtextextended('mm-config:application',0)"
|
||||
/** Another mutation holds the global configuration lock, or collectors hold it shared while they read routers.
|
||||
* Same message and 409 as before; the code lets MCP report it instead of a generic device failure. */
|
||||
export class ConfigurationBusyError extends McpError {
|
||||
constructor() { super("CONFIGURATION_BUSY", "Глобальная конфигурация изменяется другой операцией", 409) }
|
||||
constructor(scope: "application" | "server" = "application") {
|
||||
super("CONFIGURATION_BUSY", scope === "server" ? "Конфигурация сервера временно занята другой операцией" : "Глобальная конфигурация временно занята другой операцией", 409)
|
||||
}
|
||||
}
|
||||
|
||||
export async function acquireApplicationMutationTransactionLock(client: Pick<PoolClient, "query">): Promise<void> {
|
||||
@@ -80,17 +80,36 @@ export async function withApplicationMutationLock<T>(work: () => Promise<T>, opt
|
||||
/** Collectors coexist with each other but exclude configuration mutation for
|
||||
* the complete native/sample/status operation. This lock grants no authority.
|
||||
* Verified operations retain their original exact exclusive client protocol. */
|
||||
export async function withApplicationCollectorLock<T>(work: () => Promise<T>): Promise<T> {
|
||||
export async function withApplicationCollectorLock<T>(work: () => Promise<T>, { waitMs = 5000 }: { waitMs?: number } = {}): Promise<T> {
|
||||
assertOperationConfigurationLockScope()
|
||||
if (applicationLease.getStore()?.active || captureOperationConfigurationLockHandoff()) return withApplicationMutationLock(work)
|
||||
if (collectorLease.getStore()?.active) return work()
|
||||
const deadline = performance.now() + waitMs
|
||||
for (;;) {
|
||||
let admitted = false
|
||||
try {
|
||||
return await tryApplicationCollectorLock(() => {
|
||||
admitted = true
|
||||
return work()
|
||||
})
|
||||
} catch (error) {
|
||||
const remaining = deadline - performance.now()
|
||||
if (admitted || !(error instanceof ConfigurationBusyError) || remaining <= 0) throw error
|
||||
// Release the failed attempt's connection before waiting for the writer.
|
||||
await delay(Math.min(250, remaining))
|
||||
if (performance.now() >= deadline) throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function tryApplicationCollectorLock<T>(work: () => Promise<T>): Promise<T> {
|
||||
let complete!: () => void
|
||||
const completed = new Promise<void>(resolve => { complete = resolve })
|
||||
const client = await pool.connect(), context = { active: true, completed }
|
||||
let acquired = false, unsafe = false
|
||||
try {
|
||||
acquired = (await client.query(`SELECT pg_try_advisory_lock_shared(${applicationLockKey}) AS acquired`)).rows[0].acquired
|
||||
if (!acquired) throw Object.assign(new Error("Глобальная конфигурация изменяется другой операцией"), { statusCode: 409 })
|
||||
if (!acquired) throw new ConfigurationBusyError()
|
||||
return await collectorLease.run(context, work)
|
||||
} finally {
|
||||
context.active = false
|
||||
@@ -159,7 +178,7 @@ async function runConfigMutationLock<T>(serverIds: number[], work: () => Promise
|
||||
}
|
||||
for (const id of requested) {
|
||||
const { rows: [row] } = await client.query<{ acquired: boolean }>("SELECT pg_try_advisory_lock(hashtextextended($1,0)) AS acquired", ["mm-config:" + id])
|
||||
if (!row.acquired) throw Object.assign(new Error("Конфигурация сервера изменяется другой операцией"), { statusCode: 409 })
|
||||
if (!row.acquired) throw new ConfigurationBusyError("server")
|
||||
acquired.push(id)
|
||||
signal.throwIfAborted()
|
||||
}
|
||||
|
||||
@@ -907,7 +907,7 @@ export function greInterfaceBody(t: GreSnapshotTunnel): Record<string, string> {
|
||||
"allow-fast-path": t.allowFastPath ? "yes" : "no",
|
||||
comment: writeGreComment(t.comment, peer),
|
||||
disabled: rosYesNo(t.disabled),
|
||||
"ipsec-secret": isHiddenSecret(t.ipsecSecret) ? undefined : t.ipsecSecret,
|
||||
"ipsec-secret": !t.ipsecSecret || isHiddenSecret(t.ipsecSecret) ? undefined : t.ipsecSecret,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
export const greIpsecPaths = {
|
||||
filter: "/ip/firewall/filter",
|
||||
profile: "/ip/ipsec/profile",
|
||||
proposal: "/ip/ipsec/proposal",
|
||||
peer: "/ip/ipsec/peer",
|
||||
identity: "/ip/ipsec/identity",
|
||||
policy: "/ip/ipsec/policy",
|
||||
} as const
|
||||
|
||||
export function greIpsecPlaintextDrops(local: string, remote: string) {
|
||||
return [
|
||||
{ chain: "input", protocol: "gre", "src-address": `${remote}/32`, "dst-address": `${local}/32`, "ipsec-policy": "in,none", action: "drop" },
|
||||
{ chain: "output", protocol: "gre", "src-address": `${local}/32`, "dst-address": `${remote}/32`, "ipsec-policy": "out,none", action: "drop" },
|
||||
]
|
||||
}
|
||||
|
||||
export function greIke2TransportFields(name: string, local: string, remote: string, passive: boolean, secret: string, disabled: boolean) {
|
||||
return {
|
||||
profile: { name, "enc-algorithm": "aes-256", "hash-algorithm": "sha256", "dh-group": "modp2048" },
|
||||
proposal: { name, "enc-algorithms": "aes-256-cbc", "auth-algorithms": "sha256", "pfs-group": "modp2048" },
|
||||
peer: { name, address: `${remote}/32`, "local-address": local, profile: name, "exchange-mode": "ike2", passive: String(passive) },
|
||||
identity: { peer: name, "auth-method": "pre-shared-key", secret, disabled: String(disabled) },
|
||||
policy: { peer: name, "src-address": `${local}/32`, "dst-address": `${remote}/32`, protocol: "gre", action: "encrypt", level: "require", tunnel: "false", proposal: name },
|
||||
}
|
||||
}
|
||||
@@ -117,9 +117,20 @@ export async function readGreMutationState(server: ServerRow, input: GreMutation
|
||||
try{const value=bounded(raw);await check();return value}catch(error){throw stop(error)}
|
||||
}
|
||||
}
|
||||
// Create and compound edit prove preservation of configured routes. Learned routes
|
||||
// remain necessary for delete, rename and restore dependency checks.
|
||||
const configuredRoutesOnly = input?.operation === "create" || (input?.operation === "update" && !options.identityOnly)
|
||||
const [greRaw, ipv4Raw, ipv6Raw, dependencies, bindings, filters] = await settledGreReads([
|
||||
client.get<unknown>("/interface/gre").then(value=>readGreNativeRows(rows(value,[".id","name"],100))),client.get<unknown>("/ip/address").then(value=>rows(value,[".id","address","interface"])),client.get<unknown>("/ipv6/address").then(value=>rows(value,[".id","address","interface"])),
|
||||
settledGreReads(greDependencyPaths.map(async path => [path, rows(await client.get<unknown>(path), path === "/interface" ? [".id", "name"] : [".id"])] as const),stop),
|
||||
settledGreReads(greDependencyPaths.map(async path => {
|
||||
const configuredRoute = configuredRoutesOnly && (path === "/ip/route" || path === "/ipv6/route")
|
||||
const requestPath = configuredRoute ? path + "?static=true" : path
|
||||
const catalogue = rows(await client.get<unknown>(requestPath), path === "/interface" ? [".id", "name"] : [".id"])
|
||||
if (configuredRoute && catalogue.some(row => observedBoolean(row.dynamic) === true || observedBoolean(row.static) === false)) {
|
||||
throw greMutationProblem("RouterOS вернул маршруты вне запрошенного фильтра GRE")
|
||||
}
|
||||
return [path, catalogue] as const
|
||||
}),stop),
|
||||
pool.query('SELECT id,interface_name AS "interfaceName" FROM user_interface_bindings WHERE server_id=$1 ORDER BY id LIMIT 1001', [server.id]),
|
||||
pool.query('SELECT id,gateway_tunnel_id AS "gatewayTunnelId",gateway FROM filter_rules WHERE server_id=$1 ORDER BY id LIMIT 1001', [server.id]),
|
||||
]as const,stop)
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { greMutationSchema } from "./gre-mutation-input.js"
|
||||
import { planGreMutation, verifyGreMutationOp, executeGreMutationOps } from "./gre-mutation.js"
|
||||
import { assertGreDeleteDependencies, greDependencyPaths, greMutationProof, readGrePskValue, type GreMutationState } from "./gre-mutation-state.js"
|
||||
import { assertGreDeleteDependencies, greDependencyPaths, greMutationProof, readGreMutationState, readGrePskValue, type GreMutationState } from "./gre-mutation-state.js"
|
||||
import { pool } from "../db/index.js"
|
||||
import { MikrotikClient } from "./mikrotik.js"
|
||||
import type { ServerRow } from "../modules/servers/repository/servers-repository.js"
|
||||
import type { RosWriteOp } from "./entity-snapshots.js"
|
||||
|
||||
@@ -25,6 +27,7 @@ function apply(state:GreMutationState,op:RosWriteOp) {
|
||||
next[key].push(row)
|
||||
if (key==="gre") next.dependencies["/interface"].push({".id":"*C",name:row.name,type:"gre"})
|
||||
} else if (op.op === "patch") Object.assign(next[key].find(row=>row[".id"]===id)!,body)
|
||||
else if (op.op === "post" && op.path === "/interface/gre/unset") next.gre.find(row=>row[".id"]===body[".id"])!["ipsec-secret"] = ""
|
||||
else if (op.op === "delete") {
|
||||
next[key]=next[key].filter(row=>row[".id"]!==id)
|
||||
if (key==="gre") next.dependencies["/interface"]=next.dependencies["/interface"].filter(row=>row[".id"]!==id)
|
||||
@@ -38,6 +41,10 @@ let state = empty(), commands = 0
|
||||
const ops = planGreMutation(server,create,state)
|
||||
assert.equal(ops.length,3); assert.equal(ops[0].op,"put"); assert.equal("body" in ops[0]&&ops[0].body.disabled,"yes"); assert.equal(ops[2].path,"/interface/gre/@created")
|
||||
assert.equal("body" in ops[0] && ops[0].body.mtu, "1476")
|
||||
assert.ok("body" in ops[0] && !("ipsec-secret" in ops[0].body))
|
||||
const createWithClear = greMutationSchema.parse({operation:"create",fields:{name:"clear-gre",remoteAddress:"192.0.2.2",ipsecSecret:""}})
|
||||
const createWithClearOp = planGreMutation(server,createWithClear,state)[0]
|
||||
assert.ok("body" in createWithClearOp && !("ipsec-secret" in createWithClearOp.body))
|
||||
const autoCreate = greMutationSchema.parse({operation:"create",fields:{name:"own-gre",remoteAddress:"192.0.2.2",mtu:"auto"}})
|
||||
const autoPut = planGreMutation(server,autoCreate,state)[0]
|
||||
assert.equal("body" in autoPut && autoPut.body.mtu, "auto")
|
||||
@@ -60,7 +67,19 @@ assert.equal(verifyGreMutationOp(autoState, autoAfter, autoPatch), false)
|
||||
const commentPlan = planGreMutation(server,greMutationSchema.parse({operation:"update",rosId:"*G",fields:{mtu:1400}}),preserve)
|
||||
assert.equal(commentPlan[0].op,"patch"); assert.equal("body" in commentPlan[0]&&commentPlan[0].body.keepalive,"1m,3"); assert.equal("body" in commentPlan[0]&&commentPlan[0].body.comment,native.comment); assert.ok(!("body" in commentPlan[0]&&"ipsec-secret" in commentPlan[0].body))
|
||||
const clear = planGreMutation(server,greMutationSchema.parse({operation:"update",rosId:"*G",fields:{comment:"",remoteInnerIp:"",localAddress:"",ipsecSecret:""}}),preserve)
|
||||
assert.equal(clear[0].op,"patch"); assert.equal("body" in clear[0]&&clear[0].body.comment,""); assert.equal("body" in clear[0]&&clear[0].body["ipsec-secret"],"")
|
||||
assert.deepEqual(clear[0],{op:"post",path:"/interface/gre/unset",body:{".id":"*G","value-name":"ipsec-secret"}})
|
||||
assert.equal(clear[1].op,"patch"); assert.equal("body" in clear[1]&&clear[1].body.comment,""); assert.ok("body" in clear[1]&&!("ipsec-secret" in clear[1].body))
|
||||
const runningWithKey = structuredClone(preserve)
|
||||
Object.assign(runningWithKey.gre[0], {disabled:"false","ipsec-secret":"fixture-key","allow-fast-path":"false"})
|
||||
const clearRunning = greMutationSchema.parse({operation:"update",rosId:"*G",fields:{ipsecSecret:"",allowFastPath:true}})
|
||||
const clearRunningOps = planGreMutation(server,clearRunning,runningWithKey)
|
||||
assert.deepEqual(clearRunningOps.map(op=>op.op),["patch","post","patch","patch"])
|
||||
assert.equal(verifyGreMutationOp(runningWithKey,runningWithKey,clearRunningOps[1]),false)
|
||||
let afterClear = runningWithKey
|
||||
const cleared = await executeGreMutationOps(clearRunning,runningWithKey,clearRunningOps,{read:async()=>afterClear,command:async op=>{afterClear=apply(afterClear,op)}})
|
||||
assert.equal(cleared.verified,true)
|
||||
assert.equal(afterClear.gre[0]["ipsec-secret"],"")
|
||||
assert.equal(afterClear.gre[0].disabled,"false")
|
||||
const collision = empty(); collision.dependencies["/interface"]=[{".id":"*E",name:"own-gre",type:"ether"}]
|
||||
assert.throws(()=>planGreMutation(server,create,collision),/используется/)
|
||||
assert.throws(()=>planGreMutation(server,greMutationSchema.parse({operation:"delete",rosId:"*G",name:"different"}),preserve),/разные/)
|
||||
@@ -95,4 +114,37 @@ assert.equal(commands,1); assert.equal(state.gre[0].disabled,"true")
|
||||
const deletion = greMutationSchema.parse({operation:"delete",name:"own-gre"})
|
||||
const deleteOps = planGreMutation(server,deletion,state)
|
||||
assert.equal(deleteOps.at(-1)?.path,"/interface/gre/*C")
|
||||
|
||||
const originalClient = MikrotikClient.fromServer, originalQuery = pool.query
|
||||
const routeRequests: string[] = []
|
||||
const configured = { ".id": "*S", static: "true", dynamic: "false" }
|
||||
const learned = Array.from({ length: 25_626 }, (_, i) => ({ ".id": `*${(i + 100).toString(16)}`, dynamic: "true", bgp: "true" }))
|
||||
let ignoresFilter = false
|
||||
MikrotikClient.fromServer = (() => ({
|
||||
async get(path: string) {
|
||||
if (!/^\/(?:ip|ipv6)\/route(?:\?|$)/.test(path)) return []
|
||||
routeRequests.push(path)
|
||||
if (path.endsWith("?static=true")) return ignoresFilter ? [configured, learned[0]] : [configured]
|
||||
return [configured, ...learned]
|
||||
},
|
||||
async post() { throw new Error("Unexpected native read in route catalogue test") },
|
||||
})) as unknown as typeof MikrotikClient.fromServer
|
||||
pool.query = (async () => ({ rows: [] })) as unknown as typeof pool.query
|
||||
try {
|
||||
const configuredPaths = ["/ip/route?static=true", "/ipv6/route?static=true"]
|
||||
for (const input of [create, greMutationSchema.parse({ operation: "update", name: "test-gre", fields: { enabled: true } })]) {
|
||||
routeRequests.length = 0
|
||||
const snapshot = await readGreMutationState(server, input)
|
||||
assert.deepEqual(routeRequests.sort(), configuredPaths.sort())
|
||||
assert.deepEqual(snapshot.dependencies["/ip/route"], [configured])
|
||||
}
|
||||
ignoresFilter = true
|
||||
await assert.rejects(readGreMutationState(server, create), /вне запрошенного фильтра GRE/)
|
||||
routeRequests.length = 0
|
||||
await assert.rejects(readGreMutationState(server, deletion), /каталог зависимостей GRE/)
|
||||
assert.deepEqual(routeRequests.sort(), ["/ip/route", "/ipv6/route"].sort())
|
||||
} finally {
|
||||
MikrotikClient.fromServer = originalClient
|
||||
pool.query = originalQuery
|
||||
}
|
||||
console.log("GRE mutations: disabled staging, v4→v6 primary replacement, opaque/timer/secret preservation, native identity, parent/application dependencies, link-local exclusion, per-command proof and ignored/lost stop")
|
||||
@@ -12,6 +12,11 @@ import { greMutationSchema, greTunnelFromBody, type GreMutation } from "./gre-mu
|
||||
import { assertGreDeleteDependencies, greMutationProblem, greMutationProof, greNativeValue, greStableRows, greTarget, readGreMutationState, type GreMutationState } from "./gre-mutation-state.js"
|
||||
|
||||
const same = (a: unknown,b: unknown) => fingerprint(a) === fingerprint(b)
|
||||
|
||||
export function greSecretUnsetOp(id: string): RosWriteOp {
|
||||
return { op: "post", path: "/interface/gre/unset", body: { ".id": id, "value-name": "ipsec-secret" } }
|
||||
}
|
||||
|
||||
export async function recordGreMutationRevision(server:ServerRow){
|
||||
try{
|
||||
const revisionRecorded=(await captureAndAppendRevision({serverId:server.id,section:"gre",source:"apply",capture:async()=>{
|
||||
@@ -61,17 +66,29 @@ export function planGreMutation(server: ServerRow, input: GreMutation, before: G
|
||||
const ops = planGreRestore({tunnels:[desired]},selected)
|
||||
if (ops[0]?.op !== "patch") throw greMutationProblem("Не подготовлено изменение GRE")
|
||||
const body = ops[0].body
|
||||
if (fields.ipsecSecret === undefined) delete body["ipsec-secret"]
|
||||
const clearSecret = fields.ipsecSecret === ""
|
||||
if (!fields.ipsecSecret) delete body["ipsec-secret"]
|
||||
else body["ipsec-secret"] = fields.ipsecSecret
|
||||
if (fields.localAddress !== undefined) body["local-address"] = fields.localAddress || "0.0.0.0"
|
||||
body.comment = fields.comment !== undefined || fields.remoteInnerIp !== undefined ? desired.comment : target.comment ?? ""
|
||||
if (ops.length === 1 && Object.entries(body).every(([key,value])=>same(greNativeValue(key,target[key]),greNativeValue(key,value)))) throw greMutationProblem("GRE уже имеет запрошенную конфигурацию")
|
||||
if (!clearSecret && ops.length === 1 && Object.entries(body).every(([key,value])=>same(greNativeValue(key,target[key]),greNativeValue(key,value)))) throw greMutationProblem("GRE уже имеет запрошенную конфигурацию")
|
||||
body.disabled = "yes"
|
||||
if (clearSecret) {
|
||||
// Clear even a configured empty value. RouterOS can create dynamic IKEv1 objects for it.
|
||||
const path = ops[0].path
|
||||
ops.unshift(greSecretUnsetOp(live.rosId))
|
||||
if (!live.disabled) ops.unshift({ op: "patch", path, body: { disabled: "yes" } })
|
||||
}
|
||||
if (!desired.disabled) ops.push({op:"patch",path:"/interface/gre/"+live.rosId,body:{disabled:"no"}})
|
||||
return ops
|
||||
}
|
||||
|
||||
export function verifyGreMutationOp(before: GreMutationState, after: GreMutationState, op: RosWriteOp) {
|
||||
if (op.op === "post" && op.path === "/interface/gre/unset" && op.body["value-name"] === "ipsec-secret") {
|
||||
const id = op.body[".id"]
|
||||
if (after.gre.find(row => row[".id"] === id)?.["ipsec-secret"] !== "") return false
|
||||
return verifyGreMutationOp(before, after, { op: "patch", path: "/interface/gre/" + id, body: { "ipsec-secret": "" } })
|
||||
}
|
||||
const paths = {"/interface/gre":"gre","/ip/address":"ipv4","/ipv6/address":"ipv6"} as const
|
||||
const path = Object.keys(paths).find(path=>op.path===path||op.path.startsWith(path+"/")) as keyof typeof paths|undefined
|
||||
if (!path || !["put","patch","delete"].includes(op.op)) return false
|
||||
@@ -79,8 +96,11 @@ export function verifyGreMutationOp(before: GreMutationState, after: GreMutation
|
||||
const id = op.path === path ? undefined : decodeURIComponent(op.path.slice(path.length+1))
|
||||
if (op.op === "put") {
|
||||
const added = next[key].filter(row=>!prior[key].some(previous=>previous[".id"]===row[".id"]))
|
||||
if (added.length !== 1 || !same(next[key].filter(row=>row!==added[0]),prior[key]) || !Object.entries(op.body).every(([field,value])=>same(greNativeValue(field,after[key].find(row=>row[".id"]===added[0][".id"])?.[field]),greNativeValue(field,value)))) return false
|
||||
if (key!=="gre"&&observedBoolean(after[key].find(row=>row[".id"]===added[0][".id"])?.dynamic)!==false) return false
|
||||
if (added.length !== 1 || !same(next[key].filter(row=>row!==added[0]),prior[key])) return false
|
||||
const created = after[key].find(row => row[".id"] === added[0][".id"])
|
||||
const expected = key === "gre" ? { "ipsec-secret": "", ...op.body } : op.body
|
||||
if (!created || !Object.entries(expected).every(([field,value])=>same(greNativeValue(field,created[field]),greNativeValue(field,value)))) return false
|
||||
if (key!=="gre"&&observedBoolean(created.dynamic)!==false) return false
|
||||
// An address on our deliberately disabled GRE can legitimately be invalid.
|
||||
// This proof confirms configuration, not link/DAD/forwarding readiness.
|
||||
} else {
|
||||
@@ -124,6 +144,7 @@ export async function mutateGreTunnel(server: ServerRow, raw: GreMutation, expec
|
||||
const client = MikrotikClient.fromServer(fresh)
|
||||
const receipt = await executeGreMutationOps(input,before,ops,{read:()=>readGreMutationState(fresh,input),...(input.operation==="delete"?{validate:(state:GreMutationState)=>{planGreMutation(fresh,input,state)}}:{}),command:op=>{
|
||||
if (op.op === "put") return client.put(op.path,op.body)
|
||||
if (op.op === "post") return client.post(op.path,op.body)
|
||||
const slash = op.path.lastIndexOf("/"), path = op.path.slice(0,slash+1)+encodeURIComponent(op.path.slice(slash+1))
|
||||
if (op.op === "delete") return client.delete(path)
|
||||
if (op.op === "patch") return client.patch(path,op.body)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import assert from "node:assert/strict"
|
||||
import {validateGreRestoreSnapshot,materializeGreRestore,planGreRevisionRestore,executeGreRevisionSteps,readGreRestoreState,greRestoreWireOp} from "./gre-revision-restore.js"
|
||||
import {validateGreRestoreSnapshot,materializeGreRestore,planGreRevisionRestore,executeGreRevisionSteps,readGreRestoreState} from "./gre-revision-restore.js"
|
||||
import {canonicalGreSnapshot,type GreSnapshot,type RosWriteOp} from "./entity-snapshots.js"
|
||||
import {greDependencyPaths,type GreMutationState} from "./gre-mutation-state.js"
|
||||
import {mapGreLive} from "./gre-live.js"
|
||||
@@ -12,13 +12,6 @@ assert.equal(expiredAccess,0)
|
||||
const empty=():GreMutationState=>({serverConfiguration:"source",restoreProtectionProof:"protections",gre:[],ipv4:[],ipv6:[],dependencies:Object.fromEntries(greDependencyPaths.map(p=>[p,[]])),bindings:[],filters:[]})
|
||||
const native={".id":"*G",name:"old","local-address":"192.0.2.1","remote-address":"192.0.2.2",mtu:"1476",keepalive:"1m,3",dscp:"inherit",disabled:"false",dynamic:"false",running:"true","clamp-tcp-mss":"true","allow-fast-path":"false","ipsec-secret":" key ",comment:"old-comment","dont-fragment":"yes"}
|
||||
const wanted=(name:string)=>({name,localAddress:"",remoteAddress:"192.0.2.2",localInnerIp:"",remoteInnerIp:"",innerAddresses:[],comment:"",disabled:false,mtu:1400,keepalive:"0",dscp:"inherit",clampTcpMss:true,allowFastPath:false,ipsecSecret:""})
|
||||
const defaultCreate:RosWriteOp={op:"put",path:"/interface/gre",body:{name:"gre","ipsec-secret":"","allow-fast-path":"yes"}}
|
||||
const defaultWire=greRestoreWireOp(defaultCreate,empty())
|
||||
assert.ok("body"in defaultWire&&!("ipsec-secret"in defaultWire.body));assert.equal(defaultCreate.body["ipsec-secret"],"")
|
||||
const keyState=empty();keyState.gre=[{...native}]
|
||||
const clearKey:RosWriteOp={op:"patch",path:"/interface/gre/*G",body:{"ipsec-secret":"","allow-fast-path":"no"}}
|
||||
assert.equal(greRestoreWireOp(clearKey,keyState),clearKey,"A real key removal must not be silently omitted")
|
||||
keyState.gre[0]["ipsec-secret"]="";assert.ok("body"in greRestoreWireOp(clearKey,keyState)&&!("ipsec-secret"in(greRestoreWireOp(clearKey,keyState)as{body:Record<string,string>}).body))
|
||||
const snapshot=(...names:string[])=>canonicalGreSnapshot({tunnels:names.map(wanted)})
|
||||
let sequence=0
|
||||
function apply(state:GreMutationState,op:RosWriteOp){
|
||||
@@ -26,10 +19,11 @@ function apply(state:GreMutationState,op:RosWriteOp){
|
||||
const key=path==="/interface/gre"?"gre":path==="/ip/address"?"ipv4":"ipv6",id=op.path.slice(path.length+1)
|
||||
const body="body"in op?Object.fromEntries(Object.entries(op.body).map(([k,v])=>[k,v==="yes"?"true":v==="no"?"false":v])):{}
|
||||
if(op.op==="put"){
|
||||
const added={...(key==="gre"?native:{dynamic:"false",invalid:"false","no-dad":"false","eui-64":"false","from-pool":""}),...body,".id":"*N"+(++sequence)}
|
||||
const added={...(key==="gre"?{...native,"ipsec-secret":""}:{dynamic:"false",invalid:"false","no-dad":"false","eui-64":"false","from-pool":""}),...body,".id":"*N"+(++sequence)}
|
||||
next[key].push(added)
|
||||
if(key==="gre")next.dependencies["/interface"].push({".id":added[".id"],name:added.name,type:"gre"})
|
||||
}else if(op.op==="patch")Object.assign(next[key].find(r=>r[".id"]===id)!,body)
|
||||
else if(op.op==="post"&&op.path==="/interface/gre/unset")next.gre.find(r=>r[".id"]===body[".id"])!["ipsec-secret"]=""
|
||||
else if(op.op==="delete"){
|
||||
next[key]=next[key].filter(r=>r[".id"]!==id)
|
||||
if(key==="gre")next.dependencies["/interface"]=next.dependencies["/interface"].filter(r=>r[".id"]!==id)
|
||||
@@ -74,6 +68,13 @@ assert.deepEqual(state.ipv6.find(r=>r.interface==="ether1"),original.ipv6[0]);as
|
||||
const firstAddress=commands.findIndex(op=>!op.path.startsWith("/interface/gre")),oldDisable=commands.findIndex(op=>op.path==="/interface/gre/*G"&&"body"in op&&op.body.disabled==="yes")
|
||||
assert.ok(oldDisable>=0&&oldDisable<firstAddress);assert.ok(commands.slice(-2).every(op=>"body"in op&&op.body.disabled==="no"))
|
||||
assert.deepEqual(planGreRevisionRestore(fixed,state),[])
|
||||
assert.ok(commands.every(op=>!("body" in op)||op.body["ipsec-secret"]!==""))
|
||||
const clearRevision=structuredClone(fixed)
|
||||
clearRevision.tunnels.find(row=>row.name==="old")!.ipsecSecret=""
|
||||
commands=[]
|
||||
assert.equal((await execute(clearRevision)).verified,true)
|
||||
assert.deepEqual(commands.find(op=>op.op==="post"),{op:"post",path:"/interface/gre/unset",body:{".id":"*G","value-name":"ipsec-secret"}})
|
||||
assert.ok(commands.every(op=>!("body" in op)||!("ipsec-secret" in op.body)))
|
||||
const deletion=planGreRevisionRestore({tunnels:[]},original)
|
||||
assert.deepEqual(deletion[0],{kind:"native",op:{op:"patch",path:"/interface/gre/*G",body:{disabled:"yes"}}})
|
||||
assert.equal(deletion.at(-1)?.kind,"native");state=structuredClone(original);commands=[]
|
||||
|
||||
@@ -9,7 +9,7 @@ import { canonicalGreSnapshot,greAddressKey,greAddressPath,greInterfaceBody,isHi
|
||||
import { mapGreLive } from "./gre-live.js"
|
||||
import { greMtuSchema } from "./gre-mutation-input.js"
|
||||
import { assertGreDeleteDependencies,greMutationProblem,greMutationProof,greNativeValue,readGreMutationState,type GreMutationState } from "./gre-mutation-state.js"
|
||||
import { verifyGreMutationOp } from "./gre-mutation.js"
|
||||
import { greSecretUnsetOp, verifyGreMutationOp } from "./gre-mutation.js"
|
||||
import { observedBoolean } from "./ospf-observed-values.js"
|
||||
import { MikrotikClient } from "./mikrotik.js"
|
||||
import { withApplicationMutationLock,withConfigMutationLock } from "./config-mutation-lock.js"
|
||||
@@ -69,17 +69,6 @@ export function materializeGreRestore(desired:GreSnapshot,before:GreMutationStat
|
||||
})})
|
||||
}
|
||||
export type GreRestoreStep={kind:"native";op:RosWriteOp}|{kind:"enable";name:string}
|
||||
/** RouterOS treats presence of an empty ipsec-secret as an IPsec write and
|
||||
* rejects it together with FastPath. Omit a redundant empty assignment on the
|
||||
* wire only; per-command verification still uses the original expected body. */
|
||||
export function greRestoreWireOp(op:RosWriteOp,before:GreMutationState):RosWriteOp{
|
||||
if((op.op!=="put"&&op.op!=="patch")||op.body["ipsec-secret"]!=="")return op
|
||||
const creating=op.op==="put"&&op.path==="/interface/gre"
|
||||
const live=op.op==="patch"&&op.path.startsWith("/interface/gre/")?before.gre.find(row=>row[".id"]===decodeURIComponent(op.path.slice("/interface/gre/".length))):undefined
|
||||
if(!creating&&live?.["ipsec-secret"]!=="")return op
|
||||
const body={...op.body};delete body["ipsec-secret"]
|
||||
return{...op,body}
|
||||
}
|
||||
export function planGreRevisionRestore(desired:GreSnapshot,before:GreMutationState):GreRestoreStep[]{
|
||||
const wanted=new Set(desired.tunnels.map(row=>row.name))
|
||||
for(const live of before.gre){
|
||||
@@ -95,10 +84,15 @@ export function planGreRevisionRestore(desired:GreSnapshot,before:GreMutationSta
|
||||
let op=item
|
||||
if((op.op==="put"&&op.path==="/interface/gre")||(op.op==="patch"&&op.path.startsWith("/interface/gre/"))){
|
||||
const want=desired.tunnels.find(row=>row.name===("body"in op?op.body.name:undefined))!
|
||||
const body:Record<string,string>={...op.body,"local-address":want.localAddress||"0.0.0.0",comment:greInterfaceBody(want).comment??"","ipsec-secret":want.ipsecSecret}
|
||||
const body:Record<string,string>={...op.body,"local-address":want.localAddress||"0.0.0.0",comment:greInterfaceBody(want).comment??""}
|
||||
const live=before.gre.find(row=>row.name===want.name)
|
||||
const clearSecret=live&&Boolean(live["ipsec-secret"])&&!want.ipsecSecret
|
||||
const addressChanges=legacy.some(row=>!row.path.startsWith("/interface/gre")&&("body"in row?row.body.interface===want.name:mapped.addrs.some(a=>a.interfaceName===want.name&&row.path===greAddressPath(a.address)+"/"+a.rosId)))
|
||||
if(live&&Object.entries(body).every(([key,value])=>same(greNativeValue(key,live[key]),greNativeValue(key,value)))&&!addressChanges)continue
|
||||
if(live&&!clearSecret&&Object.entries(body).every(([key,value])=>same(greNativeValue(key,live[key]),greNativeValue(key,value)))&&!addressChanges)continue
|
||||
if(live&&clearSecret){
|
||||
if(observedBoolean(live.disabled)===false)staging.push({kind:"native",op:{op:"patch",path:op.path,body:{disabled:"yes"}}})
|
||||
staging.push({kind:"native",op:greSecretUnsetOp(live[".id"])})
|
||||
}
|
||||
body.disabled="yes";op={...op,body};if(!want.disabled)enable.add(want.name)
|
||||
staging.push({kind:"native",op});continue
|
||||
}
|
||||
@@ -132,12 +126,12 @@ export async function restoreGreRevision(server:ServerRow,id:string,options:{bef
|
||||
const desired=options.desired?validateGreRestoreSnapshot(options.desired):materializeGreRestore(revision.desired,before),steps=planGreRevisionRestore(desired,before),client=MikrotikClient.fromServer(server)
|
||||
const checkRevision=async()=>{if((await readGreRestoreRevision(server.id,id,authorize)).revisionProof!==revision.revisionProof)throw problem("Ревизия изменилась во время GRE restore")}
|
||||
const receipt=await executeGreRevisionSteps(before,steps,{read:()=>readGreRestoreState(server,authorize,undefined,deadlineAt),authorizeRevision:checkRevision,validate:state=>{planGreRevisionRestore(desired,state)},command:(op,gate)=>{
|
||||
const wire=greRestoreWireOp(op,before)
|
||||
const slash=op.path.lastIndexOf("/"),path=op.path.slice(0,slash+1)+encodeURIComponent(op.path.slice(slash+1))
|
||||
const timeout=Math.max(1,Math.min(op.op==="delete"?10000:15000,deadlineAt-Date.now()))
|
||||
if(wire.op==="put")return client.put(wire.path,wire.body,timeout,gate)
|
||||
if(op.op==="put")return client.put(op.path,op.body,timeout,gate)
|
||||
if(op.op==="post")return client.post(op.path,op.body,timeout,undefined,gate)
|
||||
if(op.op==="delete")return client.delete(path,timeout,gate)
|
||||
if(wire.op==="patch")return client.patch(path,wire.body,timeout,gate)
|
||||
if(op.op==="patch")return client.patch(path,op.body,timeout,gate)
|
||||
throw problem("Недопустимая команда GRE restore")
|
||||
}})
|
||||
const verified=receipt.verified&&planGreRevisionRestore(desired,receipt.after).length===0
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { test } from "node:test"
|
||||
import type { IxBondCandidate, IxBondEdit, IxSavedBond } from "@mmapp/contracts/internet-exchange"
|
||||
import { ixSegmentConfigurationSchema } from "@mmapp/contracts/internet-exchange"
|
||||
import { bondCandidates, 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), /текущего сегмента/)
|
||||
})
|
||||
|
||||
test("existing static WireGuard exports keep their applied prefixes; external GRE and BGP remain independent", () => {
|
||||
const config = ixSegmentConfigurationSchema.parse({ name: "legacy", sites: [{ serverId: 5, autonomousSystem: 64512,
|
||||
routerId: "192.0.2.1", interfaces: [
|
||||
{ kind: "wireguard", name: "wg-static", provisionWireguard: { listenPort: 31820, hubEndpoint: primary.endpoint,
|
||||
localAddress: primary.probe + "/30", peerAddress: primary.address, peerPublicKey: Buffer.alloc(32, 3).toString("base64") } },
|
||||
{ kind: "gre-ipsec", name: "gre-manual", localEndpoint: primary.endpoint, endpoint: "198.51.100.8", prefixes: ["10.7.0.0/24"] },
|
||||
] }] })
|
||||
const [candidate] = bondCandidates(owner, 7, config)
|
||||
assert.deepEqual(bondCandidates(owner, 7, config).map(c => c.interfaceName), ["wg-static"])
|
||||
assert.deepEqual(candidate.destinations, ["10.7.0.0/24"])
|
||||
assert.equal(candidate.clientId, undefined)
|
||||
config.sites[0].neighbors.push({ id: "bgp", binding: "wg-static", type: "member", remoteAs: 64513,
|
||||
address: primary.address, localAddress: primary.probe, prefixes: [], exportPrefixes: [], rules: [], limit: 10 })
|
||||
assert.deepEqual(bondCandidates(owner, 7, config), [])
|
||||
})
|
||||
@@ -0,0 +1,176 @@
|
||||
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 { ixLegacyWireguardRoutes, ixLinuxBindingKind, ixLinuxInterfaceName } from "./internet-exchange-client.js"
|
||||
import { readIxLinuxClient, verifyIxExistingTransport } from "./internet-exchange-execution.js"
|
||||
import { IxConflict } from "./internet-exchange-plan.js"
|
||||
import { ixReservedTunnelBindings, 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 === false || !tunnel || binding.peerServerId) return []
|
||||
if (!linux && (kind !== "wireguard" || site.neighbors.some(peer => peer.binding === binding.name))) return []
|
||||
const family = isIP(tunnel.peerAddress)
|
||||
const routes = linux ? linux.destinations : ixLegacyWireguardRoutes(config, binding)
|
||||
const destinations = linux?.exit ? [family === 6 ? "::/0" : "0.0.0.0/0"]
|
||||
: [...new Set(routes.map(canonicalBgpPolicyPrefix))].sort()
|
||||
if (!linux && (!destinations.length || destinations.length > 64 || destinations.some(cidr => isIP(cidr.split("/")[0]) !== family))) return []
|
||||
return [{
|
||||
segmentId, appliedRevision, segmentName: config.name, serverId: site.serverId, interfaceName: binding.name,
|
||||
name: linux?.name ?? binding.name, clientId: linux?.clientId, kind, address: tunnel.peerAddress, probe: tunnel.localAddress.split("/")[0],
|
||||
endpoint: (binding.provisionWireguard?.hubEndpoint ?? binding.localEndpoint)!,
|
||||
destinations,
|
||||
}]
|
||||
}))
|
||||
}
|
||||
|
||||
async function candidates(sql: Query, ids?: string[], refs: MemberRef[] = []) {
|
||||
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 => {
|
||||
const config = ixSegmentConfigurationSchema.parse(row.configuration)
|
||||
const result = bondCandidates(row.id, row.applied_revision, config)
|
||||
for (const ref of refs) {
|
||||
const path = ref.existing
|
||||
if (!path || ref.segmentId !== row.id) continue
|
||||
const site = config.sites.find(s => s.serverId === ref.serverId)
|
||||
const binding = site?.interfaces.find(b => b.name === ref.interfaceName)
|
||||
if (!site || binding && (binding.peerServerId || binding.provisionTransit || binding.provisionWireguard || binding.provisionGre || binding.linux ||
|
||||
binding.kind !== path.kind) || result.some(c => key(c) === key(ref)) || site.neighbors.some(p => p.binding === ref.interfaceName)) {
|
||||
throw new IxConflict("Интерфейс занят клиентом, BGP либо принадлежит другому узлу: " + ref.interfaceName)
|
||||
}
|
||||
result.push({ ...ref, ...path, segmentName: config.name, appliedRevision: row.applied_revision, name: path.linuxInterface,
|
||||
destinations: [...new Set(path.destinations.map(canonicalBgpPolicyPrefix))].sort() })
|
||||
}
|
||||
return result
|
||||
})
|
||||
}
|
||||
|
||||
export async function inspectIxBondImports(ownerId: string, edit: IxBondEdit) {
|
||||
if (!edit.members.some(m => m.existing)) return
|
||||
const [available, groups] = await Promise.all([candidates(pool, [...new Set(edit.members.map(m => m.segmentId))], edit.members), savedGroups(pool)])
|
||||
resolveBondMembers(edit, available, groups, ownerId, groups.find(g => g.id === edit.id && g.ownerSegmentId === ownerId))
|
||||
for (const m of edit.members) if (m.existing) await verifyIxExistingTransport(m.segmentId, m.serverId, m.interfaceName, m.existing)
|
||||
}
|
||||
|
||||
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 routerInterface = (m: MemberRef) => m.serverId + "/" + m.interfaceName
|
||||
const occupied = new Set(groups.filter(g => g.id !== previous?.id).flatMap(g => g.members.map(routerInterface)))
|
||||
const owned = new Map(available.map(m => [key(m), m]))
|
||||
const addresses = new Set<string>()
|
||||
const linuxNames = 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(routerInterface(member))) throw new IxConflict("Интерфейс уже входит в группу: " + label)
|
||||
occupied.add(routerInterface(member))
|
||||
const linuxName = found.existing?.linuxInterface ?? ixLinuxInterfaceName(found.kind === "wireguard" ? "ixw" : "ixg", found.serverId, { name: found.interfaceName })
|
||||
if (linuxNames.has(linuxName)) throw new IxConflict("Имя интерфейса на VPS повторяется: " + linuxName)
|
||||
linuxNames.add(linuxName)
|
||||
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))], edit.members)
|
||||
const { clientId } = resolveBondMembers(edit, available, groups, ownerId, previous)
|
||||
for (const m of edit.members) if (m.existing && (await ixReservedTunnelBindings(m.serverId, m.segmentId, sql)).some(b => b.name === m.interfaceName)) {
|
||||
throw new IxConflict("Интерфейс уже закреплён за другим сегментом: " + m.interfaceName)
|
||||
}
|
||||
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, group.members), [], 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 = m.existing ? { filename: m.existing.linuxInterface,
|
||||
hubPublicKey: await verifyIxExistingTransport(m.segmentId, m.serverId, m.interfaceName, m.existing) }
|
||||
: await readIxLinuxClient(segment, m.serverId, m.interfaceName)
|
||||
result.push({ kind: m.kind, interfaceName: m.existing ? m.existing.linuxInterface : 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
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { createHash } from "node:crypto"
|
||||
import { isIP } from "node:net"
|
||||
import type { IxSite } from "@mmapp/contracts/internet-exchange"
|
||||
import type { IxConfiguration, IxSite } from "@mmapp/contracts/internet-exchange"
|
||||
import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js"
|
||||
import { IxConflict } from "./internet-exchange-plan.js"
|
||||
|
||||
@@ -12,11 +12,16 @@ export function ixLinuxBindingKind(binding: Binding) {
|
||||
return null
|
||||
}
|
||||
|
||||
export function ixLinuxInterfaceName(prefix: "ixw" | "ixg", serverId: number, binding: Binding) {
|
||||
export function ixLegacyWireguardRoutes(configuration: IxConfiguration, binding: Binding) {
|
||||
return configuration.sites.flatMap(site => site.interfaces
|
||||
.filter(connection => connection !== binding && connection.kind !== "uplink").flatMap(connection => connection.prefixes))
|
||||
}
|
||||
|
||||
export function ixLinuxInterfaceName(prefix: "ixw" | "ixg", serverId: number, binding: Pick<Binding, "name">) {
|
||||
return prefix + createHash("sha256").update(JSON.stringify([serverId, binding.name])).digest("hex").slice(0, 12)
|
||||
}
|
||||
|
||||
export function ixWireguardClientTemplate(binding: Binding, hubPublicKey: string, routes: string[]) {
|
||||
export function ixWireguardClientTemplate(binding: Binding, hubPublicKey: string, routes: string[], 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")
|
||||
@@ -28,8 +33,12 @@ export function ixWireguardClientTemplate(binding: Binding, hubPublicKey: string
|
||||
return [
|
||||
"[Interface]",
|
||||
"Address = " + address(config.peerAddress),
|
||||
"PrivateKey = <локальный_приватный_ключ>",
|
||||
"Table = off",
|
||||
"PrivateKey = " + privateKey,
|
||||
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",
|
||||
] : []),
|
||||
"",
|
||||
"[Peer]",
|
||||
"PublicKey = " + hubPublicKey,
|
||||
@@ -40,7 +49,7 @@ export function ixWireguardClientTemplate(binding: Binding, hubPublicKey: string
|
||||
].join("\n")
|
||||
}
|
||||
|
||||
export function ixGreClientTemplate(binding: Binding, serverId: number, bgp?: { address: string; localAddress: 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) {
|
||||
@@ -48,10 +57,50 @@ export function ixGreClientTemplate(binding: Binding, serverId: number, bgp?: {
|
||||
}
|
||||
const id = ixLinuxInterfaceName("ixg", serverId, binding)
|
||||
const hostMask = bgp && isIP(bgp.address) === 6 ? "/128" : "/32"
|
||||
const tunnel = binding.provisionGre
|
||||
const family = tunnel ? isIP(tunnel.peerAddress) : 4
|
||||
const protocol = "ip -" + family
|
||||
const table = 30000 + parseInt(id.slice(-4), 16)
|
||||
const management = 12000 + 2 * parseInt(id.slice(-3), 16)
|
||||
const managementRules = [
|
||||
["ip -4", "to " + hub + "/32 lookup main"],
|
||||
["ip -4", "from " + client + "/32 lookup main"],
|
||||
...(family === 6 && binding.linux?.exit ? [["ip -6", "ipproto tcp sport 22 lookup main"]] : []),
|
||||
]
|
||||
const greParameters = id + " mode gre local " + client + " remote " + hub
|
||||
const common = [
|
||||
"swanctl --load-all",
|
||||
"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: [
|
||||
"# Сверьте предложения и идентификаторы IKE с профилем узла IX.",
|
||||
...(tunnel ? [] : ["# Сверьте предложения и идентификаторы IKE с профилем узла IX."]),
|
||||
"connections {",
|
||||
" " + id + " {",
|
||||
" version = 2",
|
||||
@@ -82,19 +131,41 @@ export function ixGreClientTemplate(binding: Binding, serverId: number, bgp?: {
|
||||
" ike-" + id + " {",
|
||||
" id-1 = " + client,
|
||||
" id-2 = " + hub,
|
||||
' secret = "<PSK этого клиента>"',
|
||||
' secret = "' + (credential ?? "<PSK этого клиента>") + '"',
|
||||
" }",
|
||||
"}",
|
||||
"",
|
||||
].join("\n"),
|
||||
setup: [
|
||||
"swanctl --load-all",
|
||||
"swanctl --initiate --child " + id,
|
||||
"# Создайте GRE после успешного установления IPsec.",
|
||||
"ip tunnel add " + id + " mode gre local " + client + " remote " + hub,
|
||||
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',
|
||||
'install -d -m 0700 /etc/swanctl/conf.d',
|
||||
'install -m 0600 "$conf" /etc/swanctl/conf.d/' + id + '.conf',
|
||||
"cleanup() {",
|
||||
" " + protocol + " rule del pref " + (management + 1) + " lookup " + table + " 2>/dev/null || :",
|
||||
" ip link del dev " + id + " 2>/dev/null || :",
|
||||
...managementRules.map(([ip, selector]) => " " + ip + " rule del pref " + management + " " + selector + " 2>/dev/null || :"),
|
||||
" swanctl --terminate --ike " + id + " --timeout 5 >/dev/null 2>&1 || :",
|
||||
"}",
|
||||
"trap cleanup 0",
|
||||
...managementRules.map(([ip, selector]) => ip + " rule add pref " + management + " " + selector),
|
||||
...common,
|
||||
addressCommand!,
|
||||
"ip link set " + id + " up",
|
||||
...[...new Set([
|
||||
tunnel.localAddress.split("/")[0] + (family === 4 ? "/32" : "/128"),
|
||||
...(binding.linux?.destinations ?? []).map(canonicalBgpPolicyPrefix),
|
||||
...(bgp && isIP(bgp.localAddress) === family ? [bgp.localAddress + hostMask] : []),
|
||||
...(binding.linux?.exit ? ["default"] : []),
|
||||
])].map(prefix => protocol + " route replace " + prefix + " dev " + id + " src " + tunnel.peerAddress + " table " + table),
|
||||
protocol + " rule add pref " + (management + 1) + " lookup " + table,
|
||||
"trap - 0",
|
||||
] : [
|
||||
...common,
|
||||
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"),
|
||||
]).join("\n"),
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { test } from "node:test"
|
||||
import type { IxRouterObject } from "@mmapp/contracts/internet-exchange"
|
||||
import { ixSegmentConfigurationSchema, type IxRouterObject } from "@mmapp/contracts/internet-exchange"
|
||||
import { planIxNative } from "./internet-exchange-execution.js"
|
||||
import { ixNamespace } from "./internet-exchange-plan.js"
|
||||
import { compileIxConfiguration, ixNamespace } from "./internet-exchange-plan.js"
|
||||
|
||||
const id = "aaaaaaaa-1111-4222-8333-123456789abc"
|
||||
const name = ixNamespace(id)
|
||||
@@ -14,6 +14,42 @@ const route: IxRouterObject = {
|
||||
}
|
||||
const device = (rows: Record<string, Array<Record<string, string>>>) => [{ serverId: 17, source: "", rows }]
|
||||
|
||||
test("managed MSS rules are backfilled and removed without adopting a hand-written rule", () => {
|
||||
const path = "/ip/firewall/mangle"
|
||||
const from = { serverId: 17, path, fields: { comment: name + ":linux-mss-from-il-wg", action: "change-mss",
|
||||
chain: "forward", "in-interface": name, "new-mss": "1380", "tcp-mss": "1381-65535" } }
|
||||
const to = { serverId: 17, path, fields: { comment: name + ":linux-mss-to-il-wg", action: "change-mss",
|
||||
chain: "postrouting", "out-interface": "il-wg", "new-mss": "1380", "tcp-mss": "1381-65535" } }
|
||||
const manual = { ...to.fields, comment: "manual MSS", ".id": "*A" }
|
||||
const fromRow = { ...from.fields, ".id": "*B" }
|
||||
const toRow = { ...to.fields, ".id": "*C" }
|
||||
const desired = [from, to]
|
||||
const live = (rows: Array<Record<string, string>>) => device({ [path]: rows })
|
||||
assert.deepEqual(planIxNative(id, desired, desired, live([manual])).map(task => [task.fields, task.placeBefore]),
|
||||
[[from.fields, "*A"], [to.fields, "*A"]])
|
||||
assert.deepEqual(planIxNative(id, desired, desired, live([fromRow, manual])).map(task => task.fields), [to.fields])
|
||||
assert.deepEqual(planIxNative(id, desired, desired, live([fromRow, toRow, manual])), [])
|
||||
assert.deepEqual(planIxNative(id, [], desired, live([fromRow, toRow, manual])).map(task => task.rosId), ["*C", "*B"])
|
||||
assert.throws(() => planIxNative(id, desired, [], live([fromRow, manual])), /незавершённой операции/)
|
||||
assert.throws(() => planIxNative(id, desired, desired, live([{ ...fromRow, "new-mss": "1460" }, toRow])), /изменён вне операции/)
|
||||
})
|
||||
|
||||
test("IX migrates an exact disabled legacy ingress MSS rule", () => {
|
||||
const path = "/ip/firewall/mangle"
|
||||
const fields = { comment: name + ":linux-mss-from-il-vps", chain: "forward", "in-interface": name,
|
||||
action: "change-mss", "new-mss": "1380", disabled: "true" }
|
||||
const previous = { serverId: 17, path, fields }
|
||||
const next = { ...previous, fields: { ...fields, disabled: "false" } }
|
||||
const legacy = { ...fields, ".id": "*C", chain: "prerouting", "in-interface": "il-vps" }
|
||||
|
||||
const [update] = planIxNative(id, [next], [previous], device({ [path]: [legacy] }))
|
||||
assert.equal(update.rosId, "*C")
|
||||
assert.deepEqual(update.fields, { chain: "forward", "in-interface": name, disabled: "false" })
|
||||
const [resumed] = planIxNative(id, [previous], [], device({ [path]: [legacy] }), true)
|
||||
assert.deepEqual(resumed.fields, { chain: "forward", "in-interface": name })
|
||||
assert.throws(() => planIxNative(id, [next], [previous], device({ [path]: [{ ...legacy, "new-mss": "1400" }] })), /изменён вне операции/)
|
||||
})
|
||||
|
||||
test("a new VRF is inserted before main and no foreign route is altered", () => {
|
||||
const changes = planIxNative(id, [vrf, route], [], device({
|
||||
"/ip/vrf": [{ ".id": "*A", name: "main", interfaces: "all", builtin: "true" }],
|
||||
@@ -31,6 +67,26 @@ test("managed changes update one exact ID and never adopt unknown objects after
|
||||
assert.deepEqual(task.fields, { gateway: "192.0.2.2@" + name })
|
||||
assert.throws(() => planIxNative(id, [next], [], state), /незавершённой операции/)
|
||||
assert.throws(() => planIxNative(id, [next], [route], device({ "/ip/route": [{ ".id": "*B", ...next.fields }] })), /изменён вне операции/)
|
||||
const resumed = planIxNative(id, [next, vrf], [route], device({
|
||||
"/ip/route": [{ ".id": "*B", ...next.fields }],
|
||||
"/ip/vrf": [{ ".id": "*A", name: "main", interfaces: "all", builtin: "true" }],
|
||||
}), true)
|
||||
assert.deepEqual(resumed.map(task => task.path), ["/ip/vrf"])
|
||||
})
|
||||
|
||||
test("revocation disables the owned client tunnel before withdrawing rules and deleting its native object", () => {
|
||||
const tunnel = { serverId: 17, path: "/interface/gre", fields: {
|
||||
name: "il-client", comment: name + ":gre-il-client", disabled: "false",
|
||||
} }
|
||||
const changes = planIxNative(id, [], [tunnel, route], device({
|
||||
[tunnel.path]: [{ ".id": "*A", ...tunnel.fields }],
|
||||
[route.path]: [{ ".id": "*B", ...route.fields }],
|
||||
}))
|
||||
assert.deepEqual(changes.map(task => [task.rosId, task.fields, task.before?.disabled]), [
|
||||
["*A", { disabled: "true" }, "false"],
|
||||
["*B", undefined, undefined],
|
||||
["*A", undefined, "true"],
|
||||
])
|
||||
})
|
||||
|
||||
test("a foreign route in the IX table and implicit native field removal are refused", () => {
|
||||
@@ -56,6 +112,67 @@ test("RouterOS REST host matches allow only the equivalent explicit host length"
|
||||
}
|
||||
})
|
||||
|
||||
test("another Linux VPS can be planned while a managed GRE/IPsec peer has no SA", () => {
|
||||
const binding = (client: string, endpoint: string, localAddress: string, peerAddress: string) => ({
|
||||
name: "il-gre-" + client, kind: "gre-ipsec", endpoint, localEndpoint: "192.0.2.17",
|
||||
provisionGre: { localAddress, peerAddress, credentialId: id }, linux: { name: client, enabled: true, destinations: [] },
|
||||
})
|
||||
const existing = binding("old", "192.0.2.20", "10.254.0.1/30", "10.254.0.2")
|
||||
const next = binding("new", "192.0.2.21", "10.254.0.5/30", "10.254.0.6")
|
||||
const compile = (...interfaces: ReturnType<typeof binding>[]) => compileIxConfiguration(id, ixSegmentConfigurationSchema.parse({
|
||||
name: "compute", sites: [{ serverId: 17, autonomousSystem: 64512, routerId: "192.0.2.17", interfaces }],
|
||||
}))
|
||||
const previous = compile(existing)
|
||||
const desired = compile(existing, next)
|
||||
const policyPath = "/ip/ipsec/policy", peerPath = "/ip/ipsec/peer"
|
||||
const rows: Record<string, Array<Record<string, string>>> = {}
|
||||
for (const [index, { path, fields }] of previous.entries()) {
|
||||
const catalogue = rows[path] ??= []
|
||||
catalogue.push({ ...fields, ".id": "*" + (index + 1).toString(16) })
|
||||
}
|
||||
const [policy] = rows[policyPath]
|
||||
Object.assign(policy, { "src-address": "::/0", "dst-address": "::/0", invalid: "true" })
|
||||
delete policy.template
|
||||
delete policy["ipsec-protocols"]
|
||||
|
||||
const tasks = planIxNative(id, desired, previous, device(rows))
|
||||
const policyTasks = tasks.filter(task => task.path === policyPath)
|
||||
assert.equal(policyTasks.length, 1)
|
||||
const [create] = policyTasks
|
||||
assert.equal(create.rosId, undefined)
|
||||
assert.equal(create.fields?.peer, name + "-" + next.name)
|
||||
assert.equal(create.fields?.["src-address"], undefined)
|
||||
assert.equal(create.fields?.["dst-address"], undefined)
|
||||
|
||||
policy.level = "use"
|
||||
assert.throws(() => planIxNative(id, desired, previous, device(rows)), /изменён вне операции/)
|
||||
policy.level = "require"
|
||||
policy.template = "true"
|
||||
assert.throws(() => planIxNative(id, desired, previous, device(rows)), /изменён вне операции/)
|
||||
delete policy.template
|
||||
rows[peerPath][0].address = "192.0.2.99/32"
|
||||
assert.throws(() => planIxNative(id, desired, previous, device(rows)), /изменён вне операции/)
|
||||
})
|
||||
|
||||
test("an omitted enabled-by-default flag on a GRE plaintext drop does not block IX", () => {
|
||||
const path = "/ip/firewall/filter"
|
||||
const object = (chain: string, policy: string) => ({ serverId: 17, path, fields: {
|
||||
comment: name + ":gre-" + chain + "-il-vps", chain, action: "drop", protocol: "gre", "ipsec-policy": policy, disabled: "false",
|
||||
} })
|
||||
const inbound = object("input", "in,none"), outbound = object("output", "out,none")
|
||||
const rows = [inbound, outbound].map(({ fields }, index) => {
|
||||
const { disabled: _disabled, ...observed } = fields
|
||||
return { ...observed, ".id": "*" + (index + 1), invalid: "false" }
|
||||
})
|
||||
assert.deepEqual(planIxNative(id, [inbound], [inbound], device({ [path]: [rows[0]] })), [])
|
||||
assert.deepEqual(planIxNative(id, [inbound, outbound], [inbound], device({ [path]: rows }), true), [])
|
||||
const disabled = { ...rows[0], disabled: "true" }
|
||||
assert.throws(() => planIxNative(id, [inbound], [inbound], device({ [path]: [disabled] }), true), /изменён вне операции.*gre-input-il-vps.*disabled/)
|
||||
const otherRule = { ...inbound, fields: { ...inbound.fields, protocol: "tcp" } }
|
||||
const observedOtherRule = { ...rows[0], protocol: "tcp" }
|
||||
assert.throws(() => planIxNative(id, [otherRule], [otherRule], device({ [path]: [observedOtherRule] })), /изменён вне операции.*disabled/)
|
||||
})
|
||||
|
||||
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 }
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
Loaded 100 of 274 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user