Files
MikrotikManager/tests/e2e/ix-context.spec.ts
T
Denozordec ca1bc1ab38
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 10m29s
Docker images / frontend-image (push) Successful in 2m14s
Docker images / updater-image (push) Successful in 39s
Docker images / netflow-agent-image (push) Successful in 32s
Docker images / backend-image (push) Successful in 1m58s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
feat(ix): добавить два протокола для одного клиента
Выдавать профиль и скрипт настройки туннеля с прямым доступом по внешнему адресу. Учитывать собственные маршруты возврата при применении черновика.
2026-11-23 18:48:10 +07:00

344 lines
22 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { readFile } from "node:fs/promises"
import { expect, test } from "@playwright/test"
import { ixChangeSchema, ixSegmentConfigurationSchema } from "@mmapp/contracts/internet-exchange"
const id = "fa58fa40-4bcb-4616-9316-cb69463b3150"
const observedAt = "2026-11-20T00:00:00Z"
const nodes = [
{ id: 1, name: "ix-node-01", site: "TEST-1", country: "DE", enabled: true },
{ id: 2, name: "ix-node-02", site: "TEST-2", country: "FI", enabled: true },
]
test("IX: редактирование и применение сохранённой ревизии из WebUI без MCP", async ({ page }, testInfo) => {
const configuration = ixSegmentConfigurationSchema.parse({ name: "ix-central", sites: [
{ serverId: 1, autonomousSystem: 64512, routerId: "192.0.2.10", interfaces: [{ name: "wg-member", kind: "wireguard" }] },
{ serverId: 2, autonomousSystem: 64512, routerId: "192.0.2.11" },
] })
let segment = { id, revision: 1, appliedRevision: 1, configuration, updatedAt: observedAt }
const digest = "a".repeat(64)
const mcpCalls: string[] = []
let applies = 0
await page.route("**/health", route => route.fulfill({ json: { ok: true } }))
await page.route("**/api/**", async route => {
const request = route.request()
const path = new URL(request.url()).pathname
const json = (body: unknown) => route.fulfill({ json: body })
if (path === "/api/auth/config") return json({ required: false })
if (path === "/api/ix/nodes") return json({ items: nodes, peers: nodes })
if (/\/api\/ix\/nodes\/\d+\/inventory$/.test(path)) return json({ observedAt, routerId: "10.255.0.1", defaultRoutes: [], wireguardPorts: [],
interfaces: [{ name: "wg-member", type: "wg", running: true, disabled: false, addresses: [], restriction: null }] })
if (path.startsWith("/api/mcp/")) {
mcpCalls.push(path)
return route.fulfill({ status: 503, json: { error: "MCP недоступен" } })
}
if (path === "/api/ix/segments" && request.method() === "POST") {
const change = ixChangeSchema.parse(request.postDataJSON())
segment = { ...segment, configuration: change.configuration, revision: change.revision + 1 }
return json({ segment })
}
if (path === "/api/ix/segments") return json({ items: [segment] })
if (path === `/api/ix/segments/${id}/linux`) {
const kind = new URL(request.url()).searchParams.get("interfaceName")
if (kind === "wg-linux") return json({ revision: segment.appliedRevision, kind: "wireguard",
filename: "wg-linux.conf", template: "[Interface]\nTable = off\n" })
if (kind === "gre-linux") return json({ revision: segment.appliedRevision, kind: "gre-ipsec",
filename: "gre-linux.conf", template: "mode = transport\n", setup: "swanctl --initiate --child gre-linux" })
return json({ revision: segment.appliedRevision, items: [
{ serverId: 1, kind: "wireguard", interfaceName: "wg-linux" },
{ serverId: 2, kind: "gre-ipsec", interfaceName: "gre-linux" },
] })
}
if (path === `/api/ix/segments/${id}/status`) return json({ sites: [{
serverId: 1, available: true, observedAt, neighbors: [{ name: "member", established: true }],
routes: [{ prefix: "2001:db8:120::/48", gateway: "2001:db8::1", immediateGateway: "2001:db8::2%wg-member", active: true }],
}] })
if (path === `/api/ix/segments/${id}/plan`) {
expect(request.postDataJSON()).toEqual({ revision: segment.revision })
return json({ revision: segment.revision, digest, changes: [
{ serverId: 1, action: "create", path: "/ipv6/route", fields: { "dst-address": "2001:db8:120::/48" } },
] })
}
if (path === `/api/ix/segments/${id}/apply`) {
expect(request.postDataJSON()).toEqual({ revision: segment.revision, digest })
applies++
segment = { ...segment, revision: segment.revision + 1, appliedRevision: segment.revision + 1 }
return json({ segment })
}
if (path === "/api/servers") return json([])
return json({})
})
await page.goto("/ix")
const row = page.getByRole("button", { name: "ix-central", exact: true })
await expect(row).toBeVisible()
const search = page.getByRole("searchbox", { name: "Поиск сегментов" })
await search.fill("no-match")
await expect(page.getByText("Сегменты не найдены")).toBeVisible()
await search.clear()
await expect(row).toBeVisible()
await page.screenshot({ path: testInfo.outputPath("ix-list-desktop.png"), animations: "disabled" })
await row.click()
await expect(page.getByRole("heading", { name: "ix-central" })).toBeFocused()
await page.screenshot({ path: testInfo.outputPath("ix-detail-desktop.png"), animations: "disabled" })
await expect(page.getByRole("tab", { name: "Linux-клиенты" })).toHaveAttribute("aria-selected", "true")
await expect(page.getByRole("tab", { name: "План изменений" })).toHaveCount(0)
await page.setViewportSize({ width: 390, height: 760 })
await page.getByRole("tab", { name: "Маршрутизация" }).click()
await page.getByLabel("Локальный ASN", { exact: true }).first().fill("64513")
await page.getByRole("button", { name: "wg-member", exact: true }).click()
await page.getByLabel("Префиксы подключения").fill("2001:db8:120::/48")
await page.getByRole("button", { name: "Добавить группу шлюзов" }).first().click()
await page.getByLabel("Имя группы шлюзов").fill("member")
await page.getByLabel("Служебный адрес шлюза").fill("2001:db8:ff::1")
await page.getByLabel("Адрес следующего шлюза").fill("2001:db8::2")
await page.getByLabel("Контрольный адрес").fill("2001:db8::2")
await page.getByRole("button", { name: "Добавить маршрут" }).first().click()
await page.getByLabel("Префикс маршрута").fill("2001:db8:120::/48")
const save = page.getByRole("button", { name: "Сохранить", exact: true })
await save.scrollIntoViewIfNeeded()
await expect(save).toBeInViewport()
await save.click()
const dialog = page.getByRole("dialog", { name: "Подтвердите сохранение" })
await expect(dialog).toBeVisible()
expect(applies).toBe(0)
await dialog.getByRole("button", { name: "Отмена" }).click()
await expect(page.getByText(/Изменения сохранены в черновике/)).toBeVisible()
expect(applies).toBe(0)
expect(segment.configuration.sites[0]).toMatchObject({
autonomousSystem: 64513,
interfaces: [{ name: "wg-member", prefixes: ["2001:db8:120::/48"] }],
groups: [{ id: "member", primary: { interface: "wg-member", nextHop: "2001:db8::2" } }],
routes: [{ prefix: "2001:db8:120::/48", group: "member" }],
})
expect(segment.configuration.sites[1]).toEqual(configuration.sites[1])
await expect(page.getByText("BGP 1 из 1")).toBeVisible()
await save.click()
await expect(dialog.getByText("/ipv6/route", { exact: true })).toBeVisible()
expect(segment.revision).toBe(2)
expect(applies).toBe(0)
await dialog.getByRole("button", { name: "Подтвердить", exact: true }).click()
await expect(page.getByText("Конфигурация IX применена")).toBeVisible()
expect(segment.appliedRevision).toBe(3)
expect(applies).toBe(1)
await page.getByRole("tab", { name: "Linux-клиенты" }).click()
await page.getByRole("button", { name: "Получить конфиг wg-linux" }).click()
await expect(page.getByText(/Table = off/)).toBeVisible()
const download = page.waitForEvent("download")
await page.getByRole("button", { name: "Скачать wg-linux.conf" }).click()
expect((await download).suggestedFilename()).toBe("wg-linux.conf")
await page.getByRole("button", { name: "Получить конфиг gre-linux" }).click()
await expect(page.getByText("mode = transport", { exact: true })).toBeVisible()
await expect(page.getByText("swanctl --initiate --child gre-linux", { exact: true })).toBeVisible()
expect(mcpCalls).toEqual([])
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(390)
})
test("IX: черновик удаляется после подтверждения в карточке", async ({ page }) => {
const draft = { id, revision: 1, appliedRevision: null, updatedAt: observedAt,
configuration: ixSegmentConfigurationSchema.parse({ name: "ix-eu", sites: [{ serverId: 1, autonomousSystem: 64512, routerId: "192.0.2.10" }] }) }
const digest = "b".repeat(64)
let deleted = false
await page.route("**/health", route => route.fulfill({ json: { ok: true } }))
await page.route("**/api/**", async route => {
const request = route.request()
const path = new URL(request.url()).pathname
if (path === "/api/auth/config") return route.fulfill({ json: { required: false } })
if (path === "/api/ix/nodes") return route.fulfill({ json: { items: nodes } })
if (path === "/api/ix/segments") return route.fulfill({ json: { items: deleted ? [] : [draft] } })
if (path === `/api/ix/segments/${id}/removal-plan`) {
expect(request.postDataJSON()).toEqual({ revision: 1 })
return route.fulfill({ json: { revision: 1, digest, changes: [] } })
}
if (path === `/api/ix/segments/${id}`) {
expect(request.method()).toBe("DELETE")
expect(request.postDataJSON()).toEqual({ revision: 1, digest })
deleted = true
return route.fulfill({ status: 204 })
}
return route.fulfill({ json: {} })
})
await page.goto("/ix")
await page.getByRole("button", { name: "ix-eu", exact: true }).click()
const remove = page.getByRole("button", { name: "Удалить сегмент", exact: true })
await remove.click()
await expect(page.getByRole("alertdialog", { name: "Удалить ix-eu?" })).toBeVisible()
await page.getByRole("button", { name: "Отмена", exact: true }).click()
expect(deleted).toBe(false)
await remove.click()
await page.getByRole("button", { name: "Удалить", exact: true }).click()
await expect(page.getByText("Сегмент ix-eu удалён")).toBeVisible()
await expect(page.getByText("Нет сегментов IX")).toBeVisible()
expect(deleted).toBe(true)
})
test("IX: новый сегмент сохраняется одним подтверждением, ошибки сравнения можно исправить", async ({ page }) => {
let stores = 0, applies = 0
const configuration = ixSegmentConfigurationSchema.parse({ name: "ix-new", sites: [
{ serverId: 1, autonomousSystem: 64512, routerId: "10.255.0.5", autoRouterId: true },
] })
const segment = { id, revision: 1, appliedRevision: null, configuration, updatedAt: observedAt }
const digest = "d".repeat(64)
await page.route("**/health", route => route.fulfill({ json: { ok: true } }))
await page.route("**/api/**", async route => {
const req = route.request(), path = new URL(req.url()).pathname
const json = (body: unknown) => route.fulfill({ json: body })
if (path === "/api/auth/config") return json({ required: false })
if (path === "/api/ix/nodes") return json({ items: [nodes[0]] })
if (path === "/api/ix/segments" && req.method() === "POST") {
const change = ixChangeSchema.parse(req.postDataJSON())
expect(change.configuration.sites[0]).toMatchObject({ serverId: 1, autoRouterId: true })
stores++
return json({ segment })
}
if (path === "/api/ix/segments") return json({ items: [] })
if (path.endsWith("/plan")) return req.postDataJSON().resume
? json({ revision: 1, digest, resume: true, changes: [] })
: route.fulfill({ status: 409, json: { error: "Требуется сверка" } })
if (path.endsWith("/apply")) {
expect(req.postDataJSON()).toEqual({ revision: 1, digest, resume: true })
applies++
return json({ segment: { ...segment, revision: 2, appliedRevision: 2 } })
}
return json({ items: [] })
})
await page.goto("/ix")
await page.getByRole("button", { name: "Добавить сегмент" }).click()
await page.getByLabel("Имя сегмента").fill("ix-new")
await page.getByRole("button", { name: "Сохранить", exact: true }).click()
const dialog = page.getByRole("dialog", { name: "Подтвердите сохранение" })
await expect(dialog.getByText("Требуется сверка")).toBeVisible()
await dialog.getByRole("button", { name: "Сверить и продолжить" }).click()
await expect(dialog.getByText(/RouterOS уже настроена/)).toBeVisible()
expect(applies).toBe(0)
await dialog.getByRole("button", { name: "Подтвердить" }).click()
await expect(page.getByRole("button", { name: "Подключить Linux" })).toBeVisible()
expect(stores).toBe(1)
expect(applies).toBe(1)
})
for (const mode of ["WAN IX", "два протокола", "новый ExitNode", "ExitNode с двумя WAN-адресами"]) test("IX: VPS подключается · " + mode, async ({ page }, testInfo) => {
const both = mode === "два протокола"
const remote = mode.includes("ExitNode"), manual = mode === "ExitNode с двумя WAN-адресами"
const configuration = ixSegmentConfigurationSchema.parse({ name: "ix-vps", sites: [
{ serverId: 1, autonomousSystem: 64512, routerId: "10.255.0.1", autoRouterId: true },
] })
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
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 } }))
await page.route("**/api/**", async route => {
const req = route.request(), url = new URL(req.url()), path = url.pathname
const json = (body: unknown) => route.fulfill({ json: body })
if (path === "/api/auth/config") return json({ required: false })
if (path === "/api/ix/nodes") return json({ items: nodes, peers: [...nodes, { id: 3, name: "exit-arn", type: "exit-node", enabled: true }] })
if (path === "/api/ix/nodes/3/inventory") return json({ interfaces: [{ name: "wan", disabled: false, addresses: manual ? ["192.0.2.12/24", "192.0.2.13/24"] : ["192.0.2.13/24"] }],
defaultRoutes: [{ family: 4, interface: "wan" }] })
if (path === "/api/ix/nodes/1/inventory") return json({ observedAt, routerId: "10.255.0.1", wireguardPorts: [],
interfaces: [{ name: "ether1", type: "ether", running: true, disabled: false, addresses: ["192.0.2.11/24"], restriction: "Интерфейс используется в таблице main" }],
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") {
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")
expect(req.postDataJSON().additionalGre).toBe(both ? true : undefined)
client = { name: "vps-01", kind: "wireguard", serverId: 1, interfaceName: "il-vps", managedWireguard: true }
const exit = remote ? req.postDataJSON().transit.name : "ix-wan4"
segment = { ...segment, revision: 2, configuration: ixSegmentConfigurationSchema.parse({
...configuration, sites: [{ ...configuration.sites[0], interfaces: [
{ name: "il-vps", kind: "wireguard", linux: { name: "vps-01", enabled: true, destinations: [], exit, clientId: both ? clientId : undefined,
peerEndpoint: "123.123.123.123" } },
...(both ? [{ name: "il-gre", kind: "gre-ipsec", linux: { name: "vps-01", enabled: true, destinations: [], exit, clientId } }] : []),
...(remote ? [{ name: "it-to-exit", kind: "wireguard", peerServerId: 3 }] : []),
], groups: [{ id: exit, gateway: "198.19.253.5", onFailure: "block",
primary: { interface: remote ? "it-to-exit" : "ether1", nextHop: "192.0.2.1", probe: "192.0.2.1", viaMain: !remote } }] }],
}) }
return json({ segment, interfaceName: client.interfaceName })
}
if (path === `/api/ix/segments/${id}/linux/credential`) {
expect(req.method()).toBe("POST")
if (req.postDataJSON().interfaceName === "il-gre") {
expect(both).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",
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("/apply")) {
expect(req.postDataJSON()).toEqual({ revision: 2, digest })
segment = { ...segment, revision: 3, appliedRevision: 3 }
return json({ segment })
}
expect(path.startsWith("/api/mcp/")).toBe(false)
return json({})
})
await page.goto("/ix")
await page.getByRole("button", { name: "ix-vps", exact: true }).click()
await expect(page.getByRole("tab", { name: "Linux-клиенты" })).toHaveAttribute("aria-selected", "true")
await page.getByRole("button", { name: "Подключить Linux" }).click()
await page.getByLabel("Имя клиента").fill("vps-01")
await page.getByLabel("Внешний адрес Linux").fill("123.123.123.123")
await expect(page.getByLabel("Публичный ключ Linux")).toBeHidden()
const protocols = page.getByRole("group", { name: "Протоколы подключения" })
await expect(protocols.getByRole("button", { name: "WireGuard" })).toHaveAttribute("aria-pressed", "true")
if (both) {
await protocols.getByRole("button", { name: "GRE/IPsec" }).click()
await expect(protocols.getByRole("button", { name: "GRE/IPsec" })).toHaveAttribute("aria-pressed", "true")
await expect(protocols.getByRole("button", { name: "WireGuard" })).toHaveAttribute("aria-pressed", "true")
}
await page.getByLabel("Выход трафика").click()
await page.getByRole("option", { name: remote ? "Через exit-arn · ExitNode" : "Интернет с этого IX" }).click()
await expect(page.getByLabel("Внешний адрес IX")).toHaveValue("192.0.2.11")
if (remote) await expect(page.getByText(/IX создаст туннель до exit-arn/)).toBeVisible()
if (manual) {
await expect(page.getByRole("button", { name: "Сохранить", exact: true })).toBeDisabled()
await page.getByLabel("IPv4 выходного узла").fill("192.0.2.13")
}
await page.screenshot({ path: testInfo.outputPath("ix-connect-linux.png"), animations: "disabled" })
await page.getByRole("button", { name: "Сохранить", exact: true }).click()
await page.getByRole("dialog", { name: "Подтвердите сохранение" }).getByRole("button", { name: "Подтвердить" }).click()
const download = page.waitForEvent("download")
await page.getByRole("button", { name: both ? "Получить конфиг vps-01 · WireGuard" : "Получить конфиг vps-01", exact: true }).click()
const file = await download
expect(file.suggestedFilename()).toBe("vps.conf")
expect(await readFile((await file.path())!, "utf8")).toBe(configFile)
await expect(page.getByText("TEST_PRIVATE_KEY")).toHaveCount(0)
if (both) {
await page.getByRole("button", { name: "Получить конфиг vps-01 · GRE/IPsec", exact: true }).click()
await expect(page.getByText(/sudo sh .\/vps-gre-setup\.sh/)).toBeVisible()
await expect(page.getByText("TEST_PSK")).toHaveCount(0)
const greDownload = page.waitForEvent("download")
await page.getByRole("button", { name: "Скачать скрипт GRE" }).click()
const greFile = await greDownload
expect(greFile.suggestedFilename()).toBe("vps-gre-setup.sh")
expect(await readFile((await greFile.path())!, "utf8")).toContain("ip tunnel add")
return
}
const editExit = page.getByRole("button", { name: "Доступ и выход клиента vps-01" })
await expect(editExit).toContainText(remote ? "Через exit-arn" : "Интернет с этого IX")
if (remote) {
await editExit.click()
await page.getByLabel("Выход трафика").click()
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 expect(page.getByRole("heading", { name: "Добавить другой протокол" })).toBeVisible()
await expect(page.getByLabel("Внешний адрес Linux")).toHaveValue("123.123.123.123")
await expect(protocols.getByRole("button", { name: "GRE/IPsec" })).toHaveAttribute("aria-pressed", "true")
}
})