-
+
{inDetail &&
}
@@ -341,30 +370,33 @@ export default function IxPage() {
{inDetail && selected &&
}
{inDetail ? (selected &&
- Ревизия {selected.revision}{selected.appliedRevision ? ` · Применена ревизия ${selected.appliedRevision}` : ""}
+ Ревизия {selected.revision}{selected.appliedRevision && selected.appliedRevision !== selected.revision ? ` · Применена ревизия ${selected.appliedRevision}` : ""}
) :
Сегменты IX, площадки и маршрутизация
}
- {inDetail && selected && live && write &&
{ if (open) void perform(prepareRemoval); else setRemovalPlan(null) }}>
- }>
- Удалить сегмент
-
-
-
- Удалить {selected.configuration.name}?
-
- {selected.appliedRevision
- ? "Этот сегмент перестанет передавать трафик. Управляемая конфигурация будет удалена с узлов IX."
- : "Черновик будет удалён из списка сегментов. Конфигурация роутеров останется прежней."}
-
-
- {removalPlan && }
-
- Отмена
- void perform(removeSegment)}>Удалить
-
-
- }
+ {inDetail && live && write &&
+ {(dirty || canPlan) &&
}
+ {selected &&
{ if (open) void perform(prepareRemoval); else setRemovalPlan(null) }}>
+ }>
+ Удалить сегмент
+
+
+
+ Удалить {selected.configuration.name}?
+
+ {selected.appliedRevision
+ ? "Этот сегмент перестанет передавать трафик. Управляемая конфигурация будет удалена с узлов IX."
+ : "Черновик будет удалён из списка сегментов. Конфигурация роутеров останется прежней."}
+
+
+ {removalPlan && }
+
+ Отмена
+ void perform(removeSegment)}>Удалить
+
+
+ }
+
}
{!inDetail &&
@@ -391,17 +423,16 @@ export default function IxPage() {
:
showTab(value as Tab)} className="min-w-0 gap-3">
- Конфигурация
- Linux-клиенты
- Выходы и резерв
- Маршруты и BGP
- План изменений
+ {selected && <>
+ Linux-клиенты
+ Маршрутизация
+ >}
+ Настройки IX
- {advanced === null ? { setDraft(value); invalidateReview() }} /> :
+ {advanced === null ? settingsProps && :
Конфигурация JSONИнтерфейсы, группы шлюзов, маршруты и BGP-политики.
-
- {selected ? perform(() => stageTransit(input))} configure={() => showTab("configuration")} />
- : }
-
-
- {!selected?.appliedRevision ? : <>
+ {selected && !dirty && live && write && perform(() => stageTransit(input))} />}
+ {settingsProps && }
+ {!!selected?.appliedRevision && <>
diff --git a/backend/mcp-coverage.json b/backend/mcp-coverage.json
index aa2dfe02..e1ab8807 100644
--- a/backend/mcp-coverage.json
+++ b/backend/mcp-coverage.json
@@ -1637,14 +1637,14 @@
"path": "/api/ix/segments/:id/linux",
"status": "excluded",
"operations": [],
- "reason": "Мастер WebUI подготавливает черновик подключения Linux. Записи на RouterOS идут после отдельного подтверждения плана."
+ "reason": "WebUI сохраняет одной ревизией клиента Linux и выбранный транзит. Записи на RouterOS идут после подтверждения изменений."
},
{
"method": "POST",
"path": "/api/ix/segments/:id/linux/credential",
"status": "excluded",
"operations": [],
- "reason": "Действующий PSK выдаётся оператору WebUI с правом изменения сети и записью в журнале. Инструменты MCP не получают секрет."
+ "reason": "WebUI выдаёт действующий PSK или ключ WireGuard оператору с правом изменения сети и записью в журнале. Для WireGuard MCP возвращает защищённую ссылку через network.wireguard.export."
},
{
"method": "POST",
diff --git a/backend/scripts/acceptance/ix-web-rest.mts b/backend/scripts/acceptance/ix-web-rest.mts
index efe354c5..c7838924 100644
--- a/backend/scripts/acceptance/ix-web-rest.mts
+++ b/backend/scripts/acceptance/ix-web-rest.mts
@@ -1,5 +1,5 @@
import assert from "node:assert/strict"
-import { randomBytes, randomUUID } from "node:crypto"
+import { createPrivateKey, createPublicKey, randomBytes, randomUUID } from "node:crypto"
import { mkdtemp } from "node:fs/promises"
import { createServer } from "node:http"
import { tmpdir } from "node:os"
@@ -157,6 +157,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\]/)
@@ -250,7 +251,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 } } }))
@@ -275,9 +276,104 @@ 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
+ const clientInput = { serverId: Number(server.id), name: "linux-auto", kind: "wireguard", hubEndpoint: "192.0.2.20",
+ prefixes: [], destinations: ["203.0.113.0/24"], enabled: true }
+ const staged = await post(managedPath + "/linux", { ...clientInput, revision: managed.revision }, 200)
+ 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
("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("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 { 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])
+ 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", "immediate-gw": "192.0.2.1%ether1", active: "true" })
+ const transit = { targetServerId: Number(exit.id), localEndpoint: "192.0.2.20", remoteEndpoint: "192.0.2.30", family: 4, name: "remote-exit" }
+ const remoteClient = { ...clientInput, name: "linux-remote", revision: credential.revision, 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.equal(writes, beforeStage)
+ assert.equal(stagedRemote.segment.revision, credential.revision + 1)
+ assert.equal(stagedRemote.segment.appliedRevision, credential.revision)
+ 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)
+
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 }))
} finally {
await mcp?.close()
await app?.close()
diff --git a/backend/src/modules/mcp/wireguard-export-actions.ts b/backend/src/modules/mcp/wireguard-export-actions.ts
index dcf3b981..941f3778 100644
--- a/backend/src/modules/mcp/wireguard-export-actions.ts
+++ b/backend/src/modules/mcp/wireguard-export-actions.ts
@@ -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 поля и отключённые состояния; фактический путь проверяется отдельно."]}
},
})
}
diff --git a/backend/src/modules/mcp/wireguard-export-artifact.ts b/backend/src/modules/mcp/wireguard-export-artifact.ts
index dea81fdf..239b61d4 100644
--- a/backend/src/modules/mcp/wireguard-export-artifact.ts
+++ b/backend/src/modules/mcp/wireguard-export-artifact.ts
@@ -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
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 = 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})}
}
diff --git a/backend/src/routes/internet-exchange.ts b/backend/src/routes/internet-exchange.ts
index 9797418d..1e1448f2 100644
--- a/backend/src/routes/internet-exchange.ts
+++ b/backend/src/routes/internet-exchange.ts
@@ -110,7 +110,12 @@ const ixRoutes: FastifyPluginAsync = async app => {
const current = await readIxSegment(id)
if (!current) throw new IxConflict("Сегмент IX не найден", 404)
assertIxRevision(current, input.revision)
- const { configuration, interfaceName } = await configureIxLinuxClient(current, input)
+ 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 })
diff --git a/backend/src/services/internet-exchange-client.ts b/backend/src/services/internet-exchange-client.ts
index c97f6c43..51d4fde7 100644
--- a/backend/src/services/internet-exchange-client.ts
+++ b/backend/src/services/internet-exchange-client.ts
@@ -16,7 +16,7 @@ export function ixLinuxInterfaceName(prefix: "ixw" | "ixg", serverId: number, bi
return prefix + createHash("sha256").update(JSON.stringify([serverId, binding.name])).digest("hex").slice(0, 12)
}
-export function ixWireguardClientTemplate(binding: Binding, hubPublicKey: string, routes: string[]) {
+export function ixWireguardClientTemplate(binding: Binding, hubPublicKey: string, routes: string[], privateKey = "<локальный_приватный_ключ>") {
const config = binding.provisionWireguard
if (binding.kind !== "wireguard" || !config?.hubEndpoint || !/^[A-Za-z0-9+/]{43}=$/.test(hubPublicKey)) {
throw new IxConflict("Для Linux нужны публичный ключ узла и заданный внешний адрес IX")
@@ -28,7 +28,7 @@ export function ixWireguardClientTemplate(binding: Binding, hubPublicKey: string
return [
"[Interface]",
"Address = " + address(config.peerAddress),
- "PrivateKey = <локальный_приватный_ключ>",
+ "PrivateKey = " + privateKey,
binding.linux ? "Table = auto" : "Table = off",
...(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",
diff --git a/backend/src/services/internet-exchange-execution.ts b/backend/src/services/internet-exchange-execution.ts
index 584e4cfc..a62ad4e0 100644
--- a/backend/src/services/internet-exchange-execution.ts
+++ b/backend/src/services/internet-exchange-execution.ts
@@ -27,6 +27,23 @@ interface IxNativeChange {
tasks: Task[]
}
+function wireguardKeys(seed: string) {
+ const scalar = Buffer.from(seed, "hex")
+ scalar[0] &= 248
+ scalar[31] = (scalar[31] & 127) | 64
+ const der = Buffer.concat([Buffer.from("302e020100300506032b656e04220420", "hex"), scalar])
+ const key = createPrivateKey({ key: der, format: "der", type: "pkcs8" })
+ return {
+ privateKey: scalar.toString("base64"),
+ publicKey: createPublicKey(key).export({ format: "der", type: "spki" }).subarray(-32).toString("base64"),
+ }
+}
+
+async function ixLinuxWireguardKeys(segmentId: string, serverId: number, name: string, credentialId: string, create = false) {
+ const derive = await (create ? privateFingerprinter : privateFingerprinterExisting)("ix-linux-wireguard-credential-v1")
+ return wireguardKeys(derive([segmentId, serverId, name, credentialId].join(":")))
+}
+
const nativePlanDigest = ({ before, tasks }: IxNativeChange) => fingerprint({ before, tasks })
const routerId = /^\*[a-z\d]+$/i
@@ -256,7 +273,7 @@ export async function configureIxLinuxClient(segment: IxSegment, input: IxLinuxC
let peerAddress = input.peerAddress ?? currentTunnel?.peerAddress
if (!localAddress && !peerAddress) {
const used = inventory.interfaces.flatMap(item => item.addresses).concat(reserved
- .concat(segment.configuration.sites.filter(candidate => candidate !== site).flatMap(candidate => candidate.interfaces))
+ .concat(segment.configuration.sites.flatMap(candidate => candidate.interfaces))
.flatMap(binding => [binding.provisionWireguard?.localAddress, binding.provisionGre?.localAddress,
binding.provisionTransit?.localAddress, ...binding.prefixes].filter(value => value !== undefined)))
for (let index = 0; index < 65536; index += 4) {
@@ -269,7 +286,14 @@ export async function configureIxLinuxClient(segment: IxSegment, input: IxLinuxC
}
}
if (!localAddress || !peerAddress) throw new IxConflict("Укажите оба адреса туннеля или оставьте их для автоматического подбора", 400)
- const ports = new Set([...inventory.wireguardPorts, ...reserved.map(binding => binding.provisionWireguard?.listenPort)])
+ const ports = new Set(inventory.wireguardPorts)
+ for (const binding of [...reserved, ...site.interfaces]) {
+ if (binding.provisionWireguard) ports.add(binding.provisionWireguard.listenPort)
+ if (binding.provisionTransit) {
+ ports.add(binding.provisionTransit.localPort)
+ ports.add(binding.provisionTransit.remotePort)
+ }
+ }
let listenPort = 51820
while (ports.has(listenPort) && listenPort <= 65535) listenPort++
const name = previous?.name ?? "il-" + randomUUID().replace(/-/g, "").slice(0, 12)
@@ -293,9 +317,15 @@ export async function configureIxLinuxClient(segment: IxSegment, input: IxLinuxC
exit: input.exit === "local-wan" ? localExit : input.exit },
}
if (input.kind === "wireguard") {
- const publicKey = input.peerPublicKey ?? previous?.provisionWireguard?.peerPublicKey
- if (!publicKey || !previous?.provisionWireguard && listenPort > 65535) throw new IxConflict("Нужен публичный ключ и свободный порт WireGuard", 400)
- binding.provisionWireguard = { peerPublicKey: publicKey, listenPort: previous?.provisionWireguard?.listenPort ?? listenPort,
+ const existing = previous?.provisionWireguard
+ if (!existing && listenPort > 65535) throw new IxConflict("Нет свободного порта WireGuard", 400)
+ let peerPublicKey = input.peerPublicKey ?? existing?.peerPublicKey
+ let credentialId = peerPublicKey === existing?.peerPublicKey ? existing?.credentialId : undefined
+ if (!peerPublicKey) {
+ credentialId = randomUUID()
+ peerPublicKey = (await ixLinuxWireguardKeys(segment.id, site.serverId, name, credentialId, true)).publicKey
+ }
+ binding.provisionWireguard = { peerPublicKey, credentialId, listenPort: existing?.listenPort ?? listenPort,
localAddress, peerAddress, hubEndpoint: input.hubEndpoint }
} else {
if (isIP(input.peerEndpoint ?? "") !== 4 || isIP(input.hubEndpoint) !== 4) throw new IxConflict("Укажите два внешних IPv4 для GRE/IPsec", 400)
@@ -473,20 +503,22 @@ async function resolveIxCredentials(id: string, objects: IxRouterObject[], exist
if (name === "secret" && psk && value.startsWith("ix-credential:")) return [name, psk(id + ":" + object.serverId + ":" + value)]
if (wg && ["public-key", "private-key"].includes(name) && value.startsWith("ix-transit:")) {
const [, variant, version, side] = value.split(":")
- const raw = Buffer.from(wg([id, version, side].join(":")), "hex")
- const scalar = Buffer.from(raw)
- scalar[0] &= 248
- scalar[31] = (scalar[31] & 127) | 64
- if (variant === "private") return [name, scalar.toString("base64")]
- const der = Buffer.concat([Buffer.from("302e020100300506032b656e04220420", "hex"), scalar])
- const privateKey = createPrivateKey({ key: der, format: "der", type: "pkcs8" })
- return [name, createPublicKey(privateKey).export({ format: "der", type: "spki" }).subarray(-32).toString("base64")]
+ const keys = wireguardKeys(wg([id, version, side].join(":")))
+ return [name, variant === "private" ? keys.privateKey : keys.publicKey]
}
return [name, value]
})) }))
}
async function prepareNative(id: string, configuration: IxConfiguration | null, previousConfiguration: IxConfiguration | null, resume = false): Promise {
+ for (const site of configuration?.sites ?? []) for (const binding of site.interfaces) {
+ const wg = binding.provisionWireguard
+ if (!wg?.credentialId) continue
+ const keys = await ixLinuxWireguardKeys(id, site.serverId, binding.name, wg.credentialId)
+ if (!binding.linux || !constantEqual(keys.publicKey, wg.peerPublicKey)) {
+ throw new IxConflict("Ключ WireGuard не соответствует управляемому клиенту IX")
+ }
+ }
const previous = previousConfiguration ? await resolveIxCredentials(id, compileIxConfiguration(id, previousConfiguration), true) : []
const objects = configuration ? await resolveIxCredentials(id, compileIxConfiguration(id, configuration), false) : []
const before: NativeDevice[] = []
@@ -660,6 +692,7 @@ export async function listIxLinuxClients(segment: IxSegment) {
const bindings = site.interfaces.filter(binding => ixLinuxBindingKind(binding) && !binding.peerServerId)
const items: IxLinuxBinding[] = bindings.map(binding => ({
serverId: site.serverId, interfaceName: binding.name, kind: ixLinuxBindingKind(binding)!,
+ ...(binding.provisionWireguard?.credentialId && { managedWireguard: true }),
...(binding.linux && { name: binding.linux.name, enabled: binding.linux.enabled, policy: binding.linux }),
}))
if (!bindings.some(binding => binding.linux?.enabled)) return items
@@ -715,7 +748,7 @@ export async function observeIxLinuxPath(segment: IxSegment, serverId: number, n
})) }
}
-export async function readIxLinuxClient(segment: IxSegment, serverId: number, name: string, includeCredential = false): Promise {
+export async function readIxLinuxClient(segment: IxSegment, serverId: number, name: string, includeCredential: boolean | "wireguard" = false): Promise {
if (segment.appliedRevision === null) throw new IxConflict("Сначала примените конфигурацию площадки")
const configuration = await readIxRevision(segment.id, segment.appliedRevision)
const site = configuration.sites.find(site => site.serverId === serverId)
@@ -723,6 +756,7 @@ export async function readIxLinuxClient(segment: IxSegment, serverId: number, na
const server = await getServerRowById(serverId)
if (!site || !binding || !server?.enabled || server.type !== "ix-node") throw new IxConflict("Подключение IX не найдено", 404)
if (binding.peerServerId || binding.linux?.enabled === false) throw new IxConflict("Клиентское подключение отключено или недоступно")
+ if (includeCredential === "wireguard" && binding.kind !== "wireguard") throw new IxConflict("Для скачивания выберите клиента WireGuard", 404)
const peer = site.neighbors.find(entry => entry.binding === name && entry.type !== "public-feed")
const clientInfo = {
revision: segment.appliedRevision,
@@ -749,7 +783,7 @@ export async function readIxLinuxClient(segment: IxSegment, serverId: number, na
return { ...clientInfo, kind: "gre-ipsec", ...ixGreClientTemplate(binding, serverId, peer, credential) }
}
if (ixLinuxBindingKind(binding) !== "wireguard") throw new IxConflict("Нет параметров WireGuard для Linux")
- const wireguard = await readRows(client, "/interface/wireguard", ["name", "public-key", "comment", "disabled"])
+ const wireguard = await readRows(client, "/interface/wireguard", ["name", "public-key", "listen-port", "comment", "disabled"])
const iface = wireguard.find(row => row.name === binding.name && row.comment?.startsWith(ixNamespace(segment.id) + ":wg-") && !isTrue(row.disabled))
const peers = await readRows(client, "/interface/wireguard/peers", ["interface", "public-key", "comment", "disabled"])
if (!peers.some(row => row.interface === name && row["public-key"] === binding.provisionWireguard?.peerPublicKey &&
@@ -760,11 +794,22 @@ export async function readIxLinuxClient(segment: IxSegment, serverId: number, na
...(binding.linux.exit ? [isIP(binding.provisionWireguard!.peerAddress) === 4 ? "0.0.0.0/0" : "::/0"] : [])]
: configuration.sites.flatMap(entry => entry.interfaces
.filter(connection => connection !== binding && connection.kind !== "uplink").flatMap(connection => connection.prefixes))
+ let privateKey: string | undefined
+ if (includeCredential) {
+ const wg = binding.provisionWireguard
+ if (!binding.linux || !wg?.credentialId) throw new IxConflict("Этот клиент использует собственный ключ WireGuard", 404)
+ const keys = await ixLinuxWireguardKeys(segment.id, serverId, name, wg.credentialId)
+ if (Number(iface?.["listen-port"]) !== wg.listenPort || !constantEqual(keys.publicKey, wg.peerPublicKey) ||
+ (await readIxSegment(segment.id))?.appliedRevision !== segment.appliedRevision) {
+ throw new IxConflict("Действующие параметры WireGuard не совпали с применённой ревизией. Выполните сверку")
+ }
+ privateKey = keys.privateKey
+ }
return {
...clientInfo,
kind: "wireguard",
filename: ixLinuxInterfaceName("ixw", serverId, binding) + ".conf",
- template: ixWireguardClientTemplate(binding, iface?.["public-key"] ?? "", routes),
+ template: ixWireguardClientTemplate(binding, iface?.["public-key"] ?? "", routes, privateKey),
}
}
diff --git a/backend/src/services/internet-exchange-store.ts b/backend/src/services/internet-exchange-store.ts
index b0e02a4d..40091b3b 100644
--- a/backend/src/services/internet-exchange-store.ts
+++ b/backend/src/services/internet-exchange-store.ts
@@ -88,7 +88,7 @@ export async function ixReservedTunnelBindings(serverId: number) {
WHERE d.server_id=$1 AND (s.configuration->>'deleted') IS DISTINCT FROM 'true'
`, [serverId])
return rows.flatMap(({ configuration }) => ixSegmentConfigurationSchema.parse(configuration).sites
- .filter(site => site.serverId === serverId).flatMap(site => site.interfaces))
+ .flatMap(site => site.interfaces.filter(binding => site.serverId === serverId || binding.peerServerId === serverId)))
}
export function nextIxRouterId(used: ReadonlySet) {
diff --git a/docs/ix.md b/docs/ix.md
index b69eed47..b744eb86 100644
--- a/docs/ix.md
+++ b/docs/ix.md
@@ -55,11 +55,12 @@
### Доступ конечных Linux-серверов
-1. На вкладке **Linux-клиенты** нажмите **Подключить Linux**. Выберите транспорт, права на сети и выход. Адреса IPv4 внутри туннеля и порт WireGuard выделяются автоматически. Для ручного назначения IPv4 или IPv6 откройте параметры адресов туннеля.
-2. Нажмите **Подготовить доступ** и примените план. Скачайте файлы из применённой ревизии по кнопке **Конфиг Linux**.
-3. В карточке **Доступ и выход** можно сменить политику или приостановить подключение. Действие **Отозвать** удаляет управляемые объекты клиента после проверки плана.
+1. Откройте сегмент IX и нажмите **Подключить Linux**. Выберите транспорт и выход VPS. **Только разрешённые сети** направляет в туннель выбранные префиксы, **Интернет с этого IX** выводит трафик через его WAN. Для удалённого выхода выберите конкретный ExitNode или другой IX. Менеджер использует подходящий настроенный выход либо подготовит транзит вместе с клиентом.
+2. Нажмите **Сохранить**. В окне подтверждения проверьте узлы и изменения RouterOS, затем нажмите **Подтвердить**. Кнопка **Конфиг Linux** в строке клиента выдаёт файлы из применённой ревизии. Отмена до подтверждения оставляет изменения в черновике. Его можно открыть той же кнопкой **Сохранить**.
+3. В строке клиента нажмите на название выхода, чтобы сменить маршрут или приостановить доступ. В меню действий **Проверить путь** показывает фактический шлюз, а **Отозвать доступ** удаляет клиентское подключение после подтверждения. Во вкладке **Маршрутизация** можно настроить общие выходы и резерв, интерфейсы CHR, статические маршруты и BGP.
-- **WireGuard.** Создайте пару ключей на Linux и вставьте публичный ключ. Подставьте приватный ключ в скачанный файл и поднимите соединение через `wg-quick`. Указанный внешний IP Linux используется в конфиге для сохранения исходного пути управления при полном туннеле.
+- **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 минут. Ключ находится только в скачиваемом файле.
- **GRE/IPsec.** Укажите два фиксированных внешних IPv4-адреса. Менеджер создаёт на CHR GRE с выключенным FastPath и IKEv2/IPsec в транспортном режиме. Оператор с правами записи скачивает конфиг strongSwan с индивидуальным PSK и команды настройки Linux. Старые вручную подготовленные подключения остаются доступны по прежнему шаблону.
### Выход и резерв
@@ -68,9 +69,9 @@
При выборе **Только разрешённые сети** клиенту открываются согласованные префиксы, которые маршрутизируются внутри IX. **Проверить путь** показывает FIB и активный next hop. Доступность назначения и фактический внешний адрес проверяйте с Linux.
-Если операция оборвалась после записи части объектов, откройте **План изменений** для текущей ревизии и выберите **Сверить и продолжить**. Менеджер проверяет запись о предыдущей попытке и адресатов, перечитывает CHR и предлагает план оставшихся изменений.
+Если операция оборвалась после записи части объектов, нажмите **Сохранить** для текущей ревизии. Если обычное сравнение выявит частично применённые изменения, выберите в окне **Сверить и продолжить**. Менеджер проверяет запись о предыдущей попытке и адресатов, перечитывает CHR и предлагает план оставшихся изменений.
-На изолированном стенде с двумя CHR RouterOS 7.24.5 проверены скачанные конфигурации WireGuard и GRE/IKEv2, IPv4 TCP на локальных выходах и блокировка открытого GRE после снятия IPsec. Для выхода через ExitNode получатель увидел смену WAN второй CHR на WAN первой и обратно после восстановления туннеля. В роли второго IX та же пара передала IPv6 с сохранением адреса Linux. Стендовый BGP-анонс выбран через заданный шлюз, после отзыва активировался защитный маршрут отбрасывания.
+До автоматической выдачи ключей на изолированном стенде с двумя CHR RouterOS 7.24.5 проверены WireGuard и GRE/IKEv2, IPv4 TCP на локальных выходах и блокировка открытого GRE после снятия IPsec. Для выхода через ExitNode получатель увидел смену WAN второй CHR на WAN первой и обратно после восстановления туннеля. В роли второго IX та же пара передала IPv6 с сохранением адреса Linux. Стендовый BGP-анонс выбран через заданный шлюз, после отзыва активировался защитный маршрут отбрасывания. Автоматическая выдача WireGuard проверена через REST и MCP с временной PostgreSQL и имитацией RouterOS.
### Удаление сегмента
diff --git a/packages/contracts/src/internet-exchange.ts b/packages/contracts/src/internet-exchange.ts
index b9101086..d0536342 100644
--- a/packages/contracts/src/internet-exchange.ts
+++ b/packages/contracts/src/internet-exchange.ts
@@ -27,6 +27,7 @@ const group = z.object({
const wireguardProvision = z.object({
peerPublicKey: z.string().regex(/^[A-Za-z0-9+/]{43}=$/),
+ credentialId: z.string().uuid().optional(),
listenPort: z.number().int().min(1).max(65535),
localAddress: prefix,
peerAddress: address,
@@ -122,6 +123,15 @@ export type IxSite = z.infer
export type IxConfiguration = z.infer
export type IxChange = z.infer
+const ixTransitOptions = z.object({
+ targetServerId: serverId,
+ name: key,
+ localEndpoint: z.ipv4(),
+ remoteEndpoint: z.ipv4(),
+ family: z.union([z.literal(4), z.literal(6)]).default(4),
+ probe: address.optional(),
+}).strict()
+
export const ixLinuxClientRequest = z.object({
revision: z.number().int().positive(),
serverId,
@@ -137,21 +147,17 @@ export const ixLinuxClientRequest = z.object({
prefixes: z.array(prefix).max(64).default([]),
destinations: linuxPolicy.shape.destinations.default([]),
exit: key.optional(),
+ transit: ixTransitOptions.optional(),
rotate: z.boolean().optional(),
-}).strict()
+}).strict().refine(input => !input.transit || !input.exit || input.exit === input.transit.name,
+ { path: ["exit"], message: "Выход клиента должен совпадать с выбранным транзитом" })
export type IxLinuxClientRequest = z.infer
-export const ixTransitRequest = z.object({
+export const ixTransitRequest = ixTransitOptions.extend({
revision: z.number().int().positive(),
serverId,
- targetServerId: serverId,
- name: key,
- localEndpoint: z.ipv4(),
- remoteEndpoint: z.ipv4(),
- family: z.union([z.literal(4), z.literal(6)]).default(4),
- probe: address.optional(),
-}).strict()
+})
export type IxTransitRequest = z.infer
@@ -196,6 +202,7 @@ export interface IxLinuxBinding {
interfaceName: string
kind: "wireguard" | "gre-ipsec"
name?: string
+ managedWireguard?: boolean
enabled?: boolean
policy?: IxSite["interfaces"][number]["linux"]
connection?: { state: "connected" | "waiting" | "unknown"; observedAt: string; rx?: string; tx?: string }
diff --git a/tests/e2e/ix-context.spec.ts b/tests/e2e/ix-context.spec.ts
index 507a2326..6452cd02 100644
--- a/tests/e2e/ix-context.spec.ts
+++ b/tests/e2e/ix-context.spec.ts
@@ -1,3 +1,4 @@
+import { readFile } from "node:fs/promises"
import { expect, test } from "@playwright/test"
import { ixChangeSchema, ixSegmentConfigurationSchema } from "@mmapp/contracts/internet-exchange"
@@ -80,24 +81,30 @@ test("IX: редактирование и применение сохранён
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.getByText("Подключения · 1", { exact: true }).click()
+ await page.getByRole("button", { name: "wg-member", exact: true }).click()
await page.getByLabel("Префиксы подключения").fill("2001:db8:120::/48")
- await page.getByText("Группы шлюзов · 0", { exact: true }).first().click()
- await page.getByRole("button", { name: "Добавить группу шлюзов" }).click()
+ await page.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.getByText("Статические маршруты · 0", { exact: true }).first().click()
- await page.getByRole("button", { name: "Добавить маршрут" }).click()
+ await page.getByRole("button", { name: "Добавить маршрут" }).first().click()
await page.getByLabel("Префикс маршрута").fill("2001:db8:120::/48")
- const save = page.getByRole("button", { name: "Сохранить черновик" })
+ const save = page.getByRole("button", { name: "Сохранить", exact: true })
await save.scrollIntoViewIfNeeded()
await expect(save).toBeInViewport()
await save.click()
- await expect(page.getByText("Черновик сохранён")).toBeVisible()
+ 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"] }],
@@ -106,17 +113,12 @@ test("IX: редактирование и применение сохранён
})
expect(segment.configuration.sites[1]).toEqual(configuration.sites[1])
- await page.getByRole("tab", { name: "Маршруты и BGP" }).click()
- await expect(page.getByText("2001:db8:120::/48")).toBeVisible()
await expect(page.getByText("BGP 1 из 1")).toBeVisible()
- await page.getByRole("tab", { name: "План изменений" }).click()
- await page.getByRole("button", { name: "Построить предпросмотр" }).click()
- await expect(page.getByText("Ревизия 2 · операций RouterOS: 1")).toBeVisible()
- await expect(page.getByText("/ipv6/route", { exact: true })).toBeVisible()
- await page.getByRole("button", { name: "Применить план" }).click()
- await expect(page.getByRole("alertdialog")).toBeVisible()
+ await save.click()
+ await expect(dialog.getByText("/ipv6/route", { exact: true })).toBeVisible()
+ expect(segment.revision).toBe(2)
expect(applies).toBe(0)
- await page.getByRole("button", { name: "Применить", exact: true }).click()
+ await dialog.getByRole("button", { name: "Подтвердить", exact: true }).click()
await expect(page.getByText("Конфигурация IX применена")).toBeVisible()
expect(segment.appliedRevision).toBe(3)
expect(applies).toBe(1)
@@ -172,34 +174,93 @@ test("IX: черновик удаляется после подтвержден
expect(deleted).toBe(true)
})
-test("IX: Linux-клиент получает выход и конфигурацию через WebUI", async ({ page }, testInfo) => {
+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 remote = mode !== "WAN IX", 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 } | undefined
+ let client: { name: string; kind: "wireguard"; serverId: number; interfaceName: string; managedWireguard: boolean } | undefined
+ 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 })
+ 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", exit: "local-wan" })
- client = { name: "vps-01", kind: "wireguard", serverId: 1, interfaceName: "il-vps" }
- segment = { ...segment, revision: 2 }
+ 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")
+ 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 } },
+ ...(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")
+ 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`) {
- if (url.searchParams.get("interfaceName") === "il-vps") {
- return json({ kind: "wireguard", revision: 3, filename: "vps.conf", template: "AllowedIPs = 0.0.0.0/0\n" })
- }
return json({ revision: segment.appliedRevision, items: segment.appliedRevision === 3 && client ? [client] : [] })
}
if (path.endsWith("/plan")) return json({ revision: 2, digest, changes: [{ serverId: 1, action: "create", path: "/interface/wireguard", fields: {} }] })
@@ -213,22 +274,34 @@ test("IX: Linux-клиент получает выход и конфигурац
})
await page.goto("/ix")
await page.getByRole("button", { name: "ix-vps", exact: true }).click()
- await expect(page.getByLabel("Router ID", { exact: true })).toHaveValue("10.255.0.1")
- await expect(page.getByText("Интерфейсы CHR · 1")).toBeVisible()
- await page.getByRole("tab", { name: "Linux-клиенты" }).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 page.getByLabel("Публичный ключ Linux").fill("A".repeat(43) + "=")
+ await expect(page.getByLabel("Публичный ключ Linux")).toBeHidden()
await page.getByLabel("Выход трафика").click()
- await page.getByRole("option", { name: "Интернет с этого IX" }).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: "Подготовить доступ" }).click()
- await page.getByRole("button", { name: "Применить план" }).click()
- await page.getByRole("button", { name: "Применить", exact: true }).click()
- await page.getByRole("button", { name: "Получить конфиг vps-01" }).click()
+ 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: "Скачать vps.conf" }).click()
- expect((await download).suggestedFilename()).toBe("vps.conf")
+ await page.getByRole("button", { name: "Получить конфиг vps-01" }).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)
+ 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")
+ }
})