Compare commits

..
1 Commits
Author SHA1 Message Date
Denozordec 676be13251 fix(ix): открыть добавление протокола из формы клиента
Docker images / prepare-release (push) Successful in 12s
Docker images / backend-test (push) Successful in 10m31s
Docker images / frontend-image (push) Successful in 3m20s
Docker images / updater-image (push) Successful in 1m56s
Docker images / netflow-agent-image (push) Successful in 34s
Docker images / backend-image (push) Successful in 3m4s
Docker images / publish-release (push) Successful in 13s
Docker images / notify-webhook (push) Successful in 2s
2026-11-23 21:48:52 +07:00
4 changed files with 100 additions and 43 deletions

No files matched your search

+55 -33
View File
@@ -35,9 +35,20 @@ type FormState = {
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
@@ -45,39 +56,47 @@ function groupLabel(group: IxSite["groups"][number], site: IxSite, nodes: IxNode
return [label, group.backup && "с резервом"].filter(Boolean).join(" · ")
}
function ClientForm({ segment, edit, nodes, backendUrl, busy, save, cancel }: {
function ClientForm({ segment, edit, setAddProtocol, nodes, backendUrl, busy, save, cancel }: {
segment: IxSegment; edit: ClientSelection | null; nodes: IxNode[]; backendUrl: string
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 [form, setForm] = useState<FormState>(() => ({
serverId: edit?.site.serverId ?? segment.configuration.sites[0].serverId,
name: existing?.linux?.name ?? "",
kind: companion ? (companion.kind === "wireguard" ? "gre-ipsec" : "wireguard")
: binding?.kind === "gre-ipsec" ? "gre-ipsec" : "wireguard",
hub: existing?.localEndpoint ?? existing?.provisionWireguard?.hubEndpoint ?? "",
peer: existing?.linux?.peerEndpoint ?? existing?.endpoint ?? "",
key: binding?.provisionWireguard?.credentialId ? "" : binding?.provisionWireguard?.peerPublicKey ?? "",
localAddress: (binding?.provisionWireguard ?? binding?.provisionGre)?.localAddress ?? "",
peerAddress: (binding?.provisionWireguard ?? binding?.provisionGre)?.peerAddress ?? "",
prefixes: binding?.prefixes.join("\n") ?? "", destinations: binding?.linux?.destinations.join("\n") ?? "",
exit: binding?.linux?.exit ?? "isolated", enabled: binding?.linux?.enabled ?? true,
}))
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 origin = useIxNodeInventory(backendUrl, form.serverId, segment.id)
const [transitLocal, setTransitLocal] = useState("")
const [transitRemote, setTransitRemote] = useState("")
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 = transitLocal.trim() || suggested || (form.hub.includes(":") ? "" : form.hub.trim())
const remoteEndpoint = transitRemote.trim() || publicEndpoint(target.inventory)
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) }))
@@ -109,7 +128,7 @@ function ClientForm({ segment, edit, nodes, backendUrl, busy, save, cancel }: {
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,
enabled: form.enabled, rotate: !!binding && rotate,
})
}}>
<div className="grid min-h-0 gap-4 overflow-y-auto px-4 pb-4">
@@ -124,23 +143,26 @@ function ClientForm({ segment, edit, nodes, backendUrl, busy, save, cancel }: {
<Field>
<FieldTitle id="ix-linux-transport">Протоколы подключения</FieldTitle>
<ButtonGroup aria-labelledby="ix-linux-transport" className="max-w-full">
<Button type="button" size="sm" variant={wireguard ? "secondary" : "outline"} aria-pressed={wireguard}
disabled={!!edit || form.kind === "wireguard"}
onClick={() => patch({ kind: wireguard ? "gre-ipsec" : "both" })}>WireGuard</Button>
<Button type="button" size="sm" variant={gre ? "secondary" : "outline"} aria-pressed={gre}
disabled={!!edit || form.kind === "gre-ipsec"}
onClick={() => patch({ kind: gre ? "wireguard" : "both" })}>GRE/IPsec</Button>
{protocols.map(({ kind, label }) => {
const selected = paired || !!companion || form.kind === "both" || form.kind === kind
return <Button key={kind} type="button" size="sm" variant={selected ? "secondary" : "outline"} aria-pressed={selected}
disabled={busy || (existing ? paired || existing.kind === kind : form.kind === kind)}
onClick={() => existing ? setAddProtocol(!companion)
: patch({ kind: form.kind === "both" ? (kind === "wireguard" ? "gre-ipsec" : "wireguard") : "both" })}>{label}</Button>
})}
</ButtonGroup>
{form.kind === "both" ? <FieldDescription>Оба туннеля получат свои адреса в одной VRF сегмента.</FieldDescription>
: companion ? <FieldDescription>Второй туннель добавится в ту же VRF. Выход и сети можно выбрать отдельно.</FieldDescription>
: !edit && <FieldDescription>Можно отметить оба протокола.</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 }); setTransitLocal(""); setTransitRemote("") } }}>
<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>
@@ -148,10 +170,10 @@ function ClientForm({ segment, edit, nodes, backendUrl, busy, save, cancel }: {
</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={transitRemote} onChange={event => setTransitRemote(event.target.value)} />
<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 => setTransitLocal(event.target.value)} /></Field>}
<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}>
@@ -181,7 +203,7 @@ function ClientForm({ segment, edit, nodes, backendUrl, busy, save, cancel }: {
</div>}
</div>
<SheetFooter>{(gre || !form.key) && <p className="text-sm text-muted-foreground">После подтверждения файлы подключения будут доступны в таблице.</p>}
<Button type="submit" disabled={!valid || busy}>Сохранить</Button>
<Button type="submit" disabled={!valid || busy}>{companion ? "Добавить туннель" : "Сохранить"}</Button>
<Button type="button" variant="outline" disabled={busy} onClick={cancel}>Отмена</Button></SheetFooter>
</form>
}
@@ -237,8 +259,7 @@ export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly,
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 = !!saved?.linux?.clientId && site?.interfaces.some(item =>
item.kind !== saved.kind && item.linux?.clientId === saved.linux?.clientId)
const paired = !!site && !!saved && hasCompanion(site, saved)
const live = applied.find(item => item.serverId === binding.serverId && item.interfaceName === binding.interfaceName && item.enabled !== false)
return <div className="flex flex-wrap gap-1">
{live && <Button size="sm" variant="outline" disabled={busy} aria-label={"Получить конфиг " + (binding.name ?? binding.interfaceName) +
@@ -278,6 +299,7 @@ export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly,
{error && <p className="text-sm text-destructive" role="alert">{error}</p>}
</SheetHeader>
{open && <ClientForm segment={segment} edit={edit} nodes={nodes} backendUrl={backendUrl} busy={busy}
setAddProtocol={addProtocol => setEdit(selection => selection && { ...selection, addProtocol })}
save={async input => { if (await save(input)) setOpen(false) }} cancel={() => setOpen(false)} />}
</SheetContent>
</Sheet>
@@ -369,6 +369,8 @@ try {
const bindings = paired.segment.configuration.sites[0].interfaces
const [wireguard, greBinding] = bindings
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",
+1 -1
View File
@@ -61,7 +61,7 @@
- **WireGuard.** IX автоматически создаёт пару ключей Linux. После применения скачайте готовый `.conf` из карточки клиента, сохраните под исходным именем в `/etc/wireguard/` с правами `0600` и запустите `sudo wg-quick up <имя-файла-без-.conf>`. Указанный внешний IP Linux сохраняет исходный путь управления при полном туннеле. Для клиента со своей парой ключей доступен шаблон с полем для его приватного ключа.
- **Получение WireGuard через MCP.** Вызовите `mm_wireguard_export_plan` с полями `serverId`, `interfaceName` клиента, `ixSegmentId` и `format: "peer-conf"`. После подтверждения и выполнения плана ссылка на готовый файл доступна авторизованному владельцу подключения 15 минут. Ключ находится только в скачиваемом файле.
- **Два протокола.** Отметьте WireGuard и GRE/IPsec при создании или выберите **Добавить другой протокол** в действиях клиента. Туннели имеют отдельные адреса и ключи, входят в одну VRF сегмента на выбранном IX, настраиваются и отключаются отдельно. Для второго туннеля по умолчанию предложен доступ к разрешённым сетям. Если на VPS одновременно запущены оба туннеля с маршрутом по умолчанию, сгенерированные правила GRE направляют обычный трафик через GRE.
- **Два протокола.** Отметьте WireGuard и GRE/IPsec при создании. Для существующего клиента откройте **Доступ и выход**, выберите свободный протокол и нажмите **Добавить туннель**. Туннели имеют отдельные адреса и ключи, входят в одну VRF сегмента на выбранном IX, настраиваются и отключаются отдельно. Для второго туннеля по умолчанию предложен доступ к разрешённым сетям. Если на VPS одновременно запущены оба туннеля с маршрутом по умолчанию, сгенерированные правила GRE направляют обычный трафик через GRE.
- **GRE/IPsec.** Укажите два фиксированных внешних IPv4-адреса. После применения скачайте конфиг strongSwan и скрипт GRE в одну папку на VPS. На Ubuntu установите `charon-systemd strongswan-swanctl`, запустите `sudo systemctl start strongswan` и выполните показанную в карточке команду `sudo sh ./…-setup.sh`. Скрипт копирует профиль с правами `0600`, устанавливает IKEv2/IPsec, создаёт GRE и использует отдельную таблицу для туннельных маршрутов. Транспорт до IX и ответы с внешнего IPv4 VPS, включая SSH, идут по основной таблице Linux.
### Выход и резерв
+42 -9
View File
@@ -228,6 +228,7 @@ for (const mode of ["WAN IX", "два протокола", "новый ExitNode"
let segment = { id, revision: 1, appliedRevision: 1, configuration, updatedAt: observedAt }
const digest = "c".repeat(64)
let client: { name: string; kind: "wireguard"; serverId: number; interfaceName: string; managedWireguard: boolean } | undefined
let extended = false
const clientId = "6677cc81-0ac8-48fd-902a-cecd0ce8633a"
const configFile = "[Interface]\nPrivateKey = TEST_PRIVATE_KEY\n[Peer]\nAllowedIPs = 0.0.0.0/0\n"
await page.route("**/health", route => route.fulfill({ json: { ok: true } }))
@@ -243,6 +244,21 @@ for (const mode of ["WAN IX", "два протокола", "новый ExitNode"
defaultRoutes: [{ family: 4, gateway: "192.0.2.1", interface: "ether1" }] })
if (path === "/api/ix/segments") return json({ items: [segment] })
if (path === `/api/ix/segments/${id}/linux` && req.method() === "POST") {
if (req.postDataJSON().companionOf) {
expect(req.postDataJSON()).toMatchObject({ revision: 3, serverId: 1, name: "vps-01", kind: "gre-ipsec",
companionOf: "il-vps", hubEndpoint: "192.0.2.11", peerEndpoint: "123.123.123.123", prefixes: [], destinations: [] })
expect(req.postDataJSON()).not.toHaveProperty("interfaceName")
expect(req.postDataJSON()).not.toHaveProperty("exit")
const site = segment.configuration.sites[0]
segment = { ...segment, revision: 4, configuration: ixSegmentConfigurationSchema.parse({
...segment.configuration, sites: [{ ...site, interfaces: [
{ ...site.interfaces[0], linux: { ...site.interfaces[0].linux, clientId } },
{ name: "il-gre", kind: "gre-ipsec", linux: { name: "vps-01", enabled: true, destinations: [], clientId } },
] }],
}) }
extended = true
return json({ segment, interfaceName: "il-gre" })
}
expect(req.postDataJSON()).toMatchObject({ name: "vps-01", kind: "wireguard", hubEndpoint: "192.0.2.11",
peerEndpoint: "123.123.123.123", ...(remote ? { transit: { targetServerId: 3, localEndpoint: "192.0.2.11", remoteEndpoint: "192.0.2.13", family: 4 } } : { exit: "local-wan" }) })
expect(req.postDataJSON()).not.toHaveProperty("peerPublicKey")
@@ -263,22 +279,24 @@ for (const mode of ["WAN IX", "два протокола", "новый ExitNode"
if (path === `/api/ix/segments/${id}/linux/credential`) {
expect(req.method()).toBe("POST")
if (req.postDataJSON().interfaceName === "il-gre") {
expect(both).toBe(true)
expect(both || extended).toBe(true)
return json({ kind: "gre-ipsec", revision: 3, filename: "vps-gre.conf", template: "secret = TEST_PSK", setup: "ip tunnel add vps-gre mode gre" })
}
expect(req.postDataJSON()).toEqual({ serverId: 1, interfaceName: "il-vps" })
return json({ kind: "wireguard", revision: 3, filename: "vps.conf", template: configFile })
}
if (path === `/api/ix/segments/${id}/linux`) {
return json({ revision: segment.appliedRevision, items: segment.appliedRevision === 3 && client ? [
client, ...(both ? [{ name: "vps-01", kind: "gre-ipsec", serverId: 1, interfaceName: "il-gre",
return json({ revision: segment.appliedRevision, items: segment.appliedRevision >= 3 && client ? [
client, ...(both || segment.appliedRevision === 5 ? [{ name: "vps-01", kind: "gre-ipsec", serverId: 1, interfaceName: "il-gre",
policy: segment.configuration.sites[0].interfaces[1].linux }] : []),
] : [] })
}
if (path.endsWith("/plan")) return json({ revision: 2, digest, changes: [{ serverId: 1, action: "create", path: "/interface/wireguard", fields: {} }] })
if (path.endsWith("/plan")) return json({ revision: segment.revision, digest, changes: [
{ serverId: 1, action: "create", path: extended ? "/interface/gre" : "/interface/wireguard", fields: {} },
] })
if (path.endsWith("/apply")) {
expect(req.postDataJSON()).toEqual({ revision: 2, digest })
segment = { ...segment, revision: 3, appliedRevision: 3 }
expect(req.postDataJSON()).toEqual({ revision: extended ? 4 : 2, digest })
segment = { ...segment, revision: segment.revision + 1, appliedRevision: segment.revision + 1 }
return json({ segment })
}
expect(path.startsWith("/api/mcp/")).toBe(false)
@@ -334,10 +352,25 @@ for (const mode of ["WAN IX", "два протокола", "новый ExitNode"
await expect(page.getByRole("option", { name: /Через exit-arn/ })).toHaveCount(1)
await expect(page.getByRole("option", { name: /Через exit-arn/ })).toHaveAttribute("aria-selected", "true")
} else {
await page.getByRole("button", { name: "Действия клиента vps-01" }).click()
await page.getByRole("menuitem", { name: "Добавить другой протокол" }).click()
await editExit.click()
await page.getByLabel("Имя клиента").fill("Несохранённое имя")
const gre = protocols.getByRole("button", { name: "GRE/IPsec" })
await expect(gre).toBeEnabled()
await gre.click()
await expect(page.getByRole("heading", { name: "Добавить другой протокол" })).toBeVisible()
await expect(page.getByLabel("Имя клиента")).toHaveValue("vps-01")
await expect(page.getByLabel("Внешний адрес Linux")).toHaveValue("123.123.123.123")
await expect(protocols.getByRole("button", { name: "GRE/IPsec" })).toHaveAttribute("aria-pressed", "true")
await expect(gre).toHaveAttribute("aria-pressed", "true")
await expect(protocols.getByRole("button", { name: "WireGuard" })).toHaveAttribute("aria-pressed", "true")
await gre.click()
await expect(page.getByLabel("Имя клиента")).toHaveValue("Несохранённое имя")
await gre.click()
await page.getByRole("button", { name: "Добавить туннель", exact: true }).click()
const dialog = page.getByRole("dialog", { name: "Подтвердите сохранение" })
await expect(dialog.getByText("/interface/gre", { exact: true })).toBeVisible()
await dialog.getByRole("button", { name: "Подтвердить" }).click()
await expect(page.getByRole("button", { name: "Получить конфиг vps-01 · GRE/IPsec", exact: true })).toBeVisible()
await expect(page.getByRole("button", { name: "Получить конфиг vps-01 · WireGuard", exact: true })).toBeVisible()
expect(segment.configuration.sites[0].interfaces[0].linux?.exit).toBe("ix-wan4")
}
})