Compare commits

...
2 Commits
Author SHA1 Message Date
Denozordec f9b742b730 fix(ix): учесть включённые правила блокировки открытых туннелей
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 11m35s
Docker images / backend-image (push) Successful in 4m31s
Docker images / frontend-image (push) Successful in 4m57s
Docker images / updater-image (push) Successful in 2m9s
Docker images / netflow-agent-image (push) Successful in 37s
Docker images / notify-webhook (push) Successful in 2s
Docker images / publish-release (push) Successful in 10s
2026-12-04 22:53:04 +07:00
Denozordec b395c06ffb fix(ix): исправить проверку и продолжение настройки туннелей
Docker images / prepare-release (push) Successful in 13s
Docker images / backend-test (push) Successful in 11m9s
Docker images / frontend-image (push) Successful in 5m7s
Docker images / updater-image (push) Successful in 3m58s
Docker images / netflow-agent-image (push) Successful in 36s
Docker images / backend-image (push) Successful in 6m53s
Docker images / publish-release (push) Successful in 13s
Docker images / notify-webhook (push) Successful in 2s
2026-12-04 22:16:10 +07:00
3 changed files with 147 additions and 35 deletions

No files matched your search

@@ -1,8 +1,8 @@
import assert from "node:assert/strict"
import { test } from "node:test"
import type { IxRouterObject } from "@mmapp/contracts/internet-exchange"
import { ixSegmentConfigurationSchema, type IxRouterObject } from "@mmapp/contracts/internet-exchange"
import { planIxNative } from "./internet-exchange-execution.js"
import { ixNamespace } from "./internet-exchange-plan.js"
import { compileIxConfiguration, ixNamespace } from "./internet-exchange-plan.js"
const id = "aaaaaaaa-1111-4222-8333-123456789abc"
const name = ixNamespace(id)
@@ -96,6 +96,67 @@ test("RouterOS REST host matches allow only the equivalent explicit host length"
}
})
test("another Linux VPS can be planned while a managed GRE/IPsec peer has no SA", () => {
const binding = (client: string, endpoint: string, localAddress: string, peerAddress: string) => ({
name: "il-gre-" + client, kind: "gre-ipsec", endpoint, localEndpoint: "192.0.2.17",
provisionGre: { localAddress, peerAddress, credentialId: id }, linux: { name: client, enabled: true, destinations: [] },
})
const existing = binding("old", "192.0.2.20", "10.254.0.1/30", "10.254.0.2")
const next = binding("new", "192.0.2.21", "10.254.0.5/30", "10.254.0.6")
const compile = (...interfaces: ReturnType<typeof binding>[]) => compileIxConfiguration(id, ixSegmentConfigurationSchema.parse({
name: "compute", sites: [{ serverId: 17, autonomousSystem: 64512, routerId: "192.0.2.17", interfaces }],
}))
const previous = compile(existing)
const desired = compile(existing, next)
const policyPath = "/ip/ipsec/policy", peerPath = "/ip/ipsec/peer"
const rows: Record<string, Array<Record<string, string>>> = {}
for (const [index, { path, fields }] of previous.entries()) {
const catalogue = rows[path] ??= []
catalogue.push({ ...fields, ".id": "*" + (index + 1).toString(16) })
}
const [policy] = rows[policyPath]
Object.assign(policy, { "src-address": "::/0", "dst-address": "::/0", invalid: "true" })
delete policy.template
delete policy["ipsec-protocols"]
const tasks = planIxNative(id, desired, previous, device(rows))
const policyTasks = tasks.filter(task => task.path === policyPath)
assert.equal(policyTasks.length, 1)
const [create] = policyTasks
assert.equal(create.rosId, undefined)
assert.equal(create.fields?.peer, name + "-" + next.name)
assert.equal(create.fields?.["src-address"], undefined)
assert.equal(create.fields?.["dst-address"], undefined)
policy.level = "use"
assert.throws(() => planIxNative(id, desired, previous, device(rows)), /изменён вне операции/)
policy.level = "require"
policy.template = "true"
assert.throws(() => planIxNative(id, desired, previous, device(rows)), /изменён вне операции/)
delete policy.template
rows[peerPath][0].address = "192.0.2.99/32"
assert.throws(() => planIxNative(id, desired, previous, device(rows)), /изменён вне операции/)
})
test("an omitted enabled-by-default flag on a GRE plaintext drop does not block IX", () => {
const path = "/ip/firewall/filter"
const object = (chain: string, policy: string) => ({ serverId: 17, path, fields: {
comment: name + ":gre-" + chain + "-il-vps", chain, action: "drop", protocol: "gre", "ipsec-policy": policy, disabled: "false",
} })
const inbound = object("input", "in,none"), outbound = object("output", "out,none")
const rows = [inbound, outbound].map(({ fields }, index) => {
const { disabled: _disabled, ...observed } = fields
return { ...observed, ".id": "*" + (index + 1), invalid: "false" }
})
assert.deepEqual(planIxNative(id, [inbound], [inbound], device({ [path]: [rows[0]] })), [])
assert.deepEqual(planIxNative(id, [inbound, outbound], [inbound], device({ [path]: rows }), true), [])
const disabled = { ...rows[0], disabled: "true" }
assert.throws(() => planIxNative(id, [inbound], [inbound], device({ [path]: [disabled] }), true), /изменён вне операции.*gre-input-il-vps.*disabled/)
const otherRule = { ...inbound, fields: { ...inbound.fields, protocol: "tcp" } }
const observedOtherRule = { ...rows[0], protocol: "tcp" }
assert.throws(() => planIxNative(id, [otherRule], [otherRule], device({ [path]: [observedOtherRule] })), /изменён вне операции.*disabled/)
})
test("RouterOS REST encodes an enabled blackhole route as a present empty flag", () => {
const fields = { comment: name + ":default-discard-4", "routing-table": name, "dst-address": "0.0.0.0/0", blackhole: "yes" }
const discard = { ...route, fields }
@@ -8,7 +8,8 @@ import { audit } from "../modules/mcp/store.js"
import { getServerRowById, type ServerRow } from "../modules/servers/repository/servers-repository.js"
import { withApplicationMutationLock, withConfigMutationLock } from "./config-mutation-lock.js"
import { assertVerifiedConfigurationAccess } from "./config-mutation-policy.js"
import { compileIxConfiguration, inIxNetwork, IxConflict, ixClientRoutingTable, ixDeviceIds, ixDiscardInterface, ixEgressList, ixNamespace } from "./internet-exchange-plan.js"
import { compileIxConfiguration, inIxNetwork, IxConflict, ixClientRoutingTable, ixDeviceIds, ixDiscardInterface, ixEgressList, ixManagedGreFields, ixNamespace } from "./internet-exchange-plan.js"
import { greIpsecPaths } from "./gre-ipsec-transport.js"
import { archiveIxSegment, assertIxBondClientAssignments, assertIxName, assertIxRevision, assertIxRouterIds, assertIxSites, assertIxSegmentWithoutBonds, ixBondClientId, ixKnownVpsClient, ixReservedLinuxPoolBlocks, ixReservedRouterIds, ixReservedTunnelBindings, nextIxRouterId, readIxRevision, readIxSegment, writeIxRevision } from "./internet-exchange-store.js"
import { MikrotikClient } from "./mikrotik.js"
import { ixGreClientTemplate, ixLegacyWireguardRoutes, ixLinuxBindingKind, ixLinuxInterfaceName, ixWireguardClientTemplate } from "./internet-exchange-client.js"
@@ -59,6 +60,8 @@ const ipsecPolicyColumns = [".id", "action", "level", "tunnel", "protocol", "src
function normalize(field: string, value: string | undefined) {
if (["blackhole", "fib"].includes(field) && value === "") return "yes"
if (field === "ipsec-protocols") return value ?? "esp"
if (field === "template") return isTrue(value) ? "yes" : "no"
if (["disabled", "advertise", "blackhole", "multihop", "fib", "passive", "tunnel", "allow-fast-path", "passthrough"].includes(field)) {
return value === undefined ? null : isTrue(value) ? "yes" : "no"
}
@@ -75,8 +78,17 @@ function normalize(field: string, value: string | undefined) {
return value
}
function fieldMatches(row: NativeRow, fields: Record<string, string>, field: string) {
// RouterOS can omit disabled=no on GRE plaintext drops created without an explicit flag.
if (field === "disabled" && row.disabled === undefined && fields.disabled === "false" &&
fields.action === "drop" && fields.protocol === "gre" &&
((fields.chain === "input" && fields["ipsec-policy"] === "in,none") ||
(fields.chain === "output" && fields["ipsec-policy"] === "out,none"))) return true
return normalize(field, row[field]) === normalize(field, fields[field])
}
function matches(row: NativeRow, fields: Record<string, string>) {
return Object.entries(fields).every(([field, value]) => normalize(field, row[field]) === normalize(field, value))
return Object.keys(fields).every(field => fieldMatches(row, fields, field))
}
function rowsFor(device: NativeDevice, path: string) { return device.rows[path] ?? [] }
@@ -135,11 +147,13 @@ export function planIxNative(id: string, desired: IxRouterObject[], previous: Ix
}
if (row) {
const before = previousByKey.get(deviceMarker(object))!
if (!matches(row, before.fields)) throw new IxConflict("Объект IX изменён вне операции")
const differences = Object.keys(before.fields).filter(field => !fieldMatches(row, before.fields, field))
if (differences.length) throw new IxConflict("Объект IX изменён вне операции · узел " + object.serverId + " · " + path +
" · " + (object.fields.comment ?? object.fields.name) + " · " + differences.join(", "))
if (Object.keys(before.fields).some(field => !(field in object.fields))) {
throw new IxConflict("Поле RouterOS нельзя неявно сбросить. Замените объект с новым идентификатором")
}
const fields = Object.fromEntries(Object.entries(object.fields).filter(([field, value]) => normalize(field, row[field]) !== normalize(field, value)))
const fields = Object.fromEntries(Object.entries(object.fields).filter(([field]) => !fieldMatches(row, object.fields, field)))
if (Object.keys(fields).length) result.push({ serverId: object.serverId, path, rosId: verifyNativeId(row), fields, before: row })
continue
}
@@ -448,7 +462,7 @@ export async function configureIxTransit(segment: IxSegment, input: IxTransitReq
return configuration
}
async function readDevice(server: ServerRow, objects: IxRouterObject[], removing = false): Promise<NativeDevice> {
async function readDevice(server: ServerRow, objects: IxRouterObject[], removing = false, verifyExternalGre = false): Promise<NativeDevice> {
const client = MikrotikClient.fromServer(server)
const fieldsByPath = new Map<string, string[]>([["/interface", columns], ["/interface/bridge/port", [".id", "bridge", "interface"]],
["/ip/vrf", columns], ["/ip/route", columns], ["/ipv6/route", columns]])
@@ -461,7 +475,7 @@ async function readDevice(server: ServerRow, objects: IxRouterObject[], removing
...(filterPath(object.path) ? ["invalid"] : []), ...Object.keys(object.fields)])])
}
if (fieldsByPath.has("/interface/list")) fieldsByPath.get("/interface/list")!.push("include", "exclude")
if (objects.some(object => object.fields["ipsec-policy"])) {
if (verifyExternalGre) {
fieldsByPath.set("/interface/gre", [...new Set([...greColumns, ...(fieldsByPath.get("/interface/gre") ?? [])])])
fieldsByPath.set("/ip/ipsec/policy", [...new Set([...ipsecPolicyColumns, ...(fieldsByPath.get("/ip/ipsec/policy") ?? [])])])
}
@@ -474,14 +488,10 @@ async function readDevice(server: ServerRow, objects: IxRouterObject[], removing
return { serverId: server.id, source: fingerprint(server), rows }
}
function verifyGreBinding(binding: IxSite["interfaces"][number], interfaces: NativeRow[], policies: NativeRow[]) {
function verifyGreInterface(binding: IxSite["interfaces"][number], interfaces: NativeRow[]) {
const gre = interfaces.find(row => row.name === binding.name)
const policy = policies.some(row =>
!isTrue(row.disabled) && !isTrue(row.template) && !isTrue(row.tunnel) &&
row.action === "encrypt" && ["require", "unique"].includes(row.level) && ["gre", "47"].includes(row.protocol) &&
row["src-address"] === binding.localEndpoint + "/32" && row["dst-address"] === binding.endpoint + "/32")
if (!gre || gre["local-address"] !== binding.localEndpoint || gre["remote-address"] !== binding.endpoint || !policy) {
throw new IxConflict("Для " + binding.name + " не подтверждены адреса и обязательная политика GRE/IPsec")
if (!gre || gre["local-address"] !== binding.localEndpoint || gre["remote-address"] !== binding.endpoint) {
throw new IxConflict("Для " + binding.name + " не подтверждены внешние адреса GRE")
}
if (!["false", "no"].includes(gre["allow-fast-path"])) {
throw new IxConflict("Отключите FastPath на интерфейсе GRE/IPsec " + binding.name)
@@ -489,6 +499,14 @@ function verifyGreBinding(binding: IxSite["interfaces"][number], interfaces: Nat
return gre
}
function verifyGrePolicy(binding: IxSite["interfaces"][number], policies: NativeRow[]) {
const policy = policies.some(row =>
!isTrue(row.disabled) && !isTrue(row.template) && !isTrue(row.tunnel) &&
row.action === "encrypt" && ["require", "unique"].includes(row.level) && ["gre", "47"].includes(row.protocol) &&
row["src-address"] === binding.localEndpoint + "/32" && row["dst-address"] === binding.endpoint + "/32")
if (!policy) throw new IxConflict("Для " + binding.name + " не подтверждена обязательная политика GRE/IPsec")
}
/** Inspect operator-owned transports without running the provisioning or VRF planner. */
export async function verifyIxExistingTransport(segmentId: string, serverId: number, name: string, path: IxExistingTransport) {
const client = await requiredIxNode(serverId)
@@ -517,7 +535,9 @@ export async function verifyIxExistingTransport(segmentId: string, serverId: num
if (path.kind === "gre-ipsec") {
const [interfaces, policies] = await Promise.all([readRows(client, "/interface/gre", [...greColumns, "disabled"]),
readRows(client, "/ip/ipsec/policy", ipsecPolicyColumns)])
const gre = verifyGreBinding({ name, kind: path.kind, localEndpoint: path.endpoint, endpoint: path.remoteEndpoint, prefixes: [] }, interfaces, policies)
const binding = { name, kind: path.kind, localEndpoint: path.endpoint, endpoint: path.remoteEndpoint, prefixes: [] }
const gre = verifyGreInterface(binding, interfaces)
verifyGrePolicy(binding, policies)
if (isTrue(gre.disabled)) throw new IxConflict("Интерфейс отключён: " + name)
if (!sameIP(local.network, path.address) && !inIxNetwork(local.address, path.address)) {
const routes = await readRows(client, isIP(path.address) === 4 ? "/ip/route" : "/ipv6/route", ["dst-address", "gateway", "immediate-gw", "disabled"])
@@ -582,8 +602,9 @@ function validateBindings(configuration: IxConfiguration, id: string, devices: N
gateway.trim().split("@")[0].split("%").at(-1) === binding.name))) {
throw new IxConflict("Интерфейс " + binding.name + " уже используется другой маршрутизацией")
}
if (binding.kind === "gre-ipsec") {
verifyGreBinding(binding, rowsFor(device, "/interface/gre"), rowsFor(device, "/ip/ipsec/policy"))
if (binding.kind === "gre-ipsec" && !binding.provisionGre) {
verifyGreInterface(binding, rowsFor(device, "/interface/gre"))
verifyGrePolicy(binding, rowsFor(device, "/ip/ipsec/policy"))
}
}
}
@@ -648,7 +669,8 @@ async function prepareNative(id: string, configuration: IxConfiguration | null,
if (site?.autoRouterId && (await observedIxRouterIds(MikrotikClient.fromServer(server), id)).has(site.routerId)) {
throw new IxConflict("Router ID " + site.routerId + " уже используется на CHR")
}
before.push(await readDevice(server, [...objects, ...previous].filter(object => object.serverId === serverId), !configuration))
const verifyExternalGre = site?.interfaces.some(binding => binding.kind === "gre-ipsec" && !binding.provisionGre)
before.push(await readDevice(server, [...objects, ...previous].filter(object => object.serverId === serverId), !configuration, verifyExternalGre))
verifyIxMainGateways(before.at(-1)!, objects.filter(object => object.serverId === serverId))
}
if (configuration) validateBindings(configuration, id, before, resume ? objects.concat(previous) : previous)
@@ -673,10 +695,19 @@ async function prepareNative(id: string, configuration: IxConfiguration | null,
async function assertIxResume(id: string, revision: number, native: IxNativeChange) {
const { rows: [attempt] } = await pool.query<{ sources: unknown }>(`
SELECT payload->'sources' AS sources FROM mcp_audit
WHERE action='ix.web.apply_started' AND payload->>'segmentId'=$1 AND payload->>'revision'=$2
ORDER BY id DESC LIMIT 1
`, [id, String(revision)])
WITH last_attempt AS (
SELECT payload FROM mcp_audit
WHERE action='ix.web.apply_started' AND payload->>'segmentId'=$1::uuid::text
ORDER BY id DESC LIMIT 1
)
SELECT last_attempt.payload->'sources' AS sources
FROM last_attempt
JOIN ix_segments s ON s.id=$1
JOIN ix_segment_revisions draft ON draft.segment_id=s.id AND draft.revision=s.revision
JOIN ix_segment_revisions started ON started.segment_id=s.id AND started.revision::text=last_attempt.payload->>'revision'
WHERE draft.revision=$2 AND started.revision>COALESCE(s.applied_revision,0)
AND started.revision<=draft.revision AND started.configuration=draft.configuration
`, [id, revision])
const sources = native.before.map(device => [device.serverId, device.source])
if (!attempt || fingerprint(attempt.sources) !== fingerprint(sources)) {
throw new IxConflict("Нет подтверждённой попытки применения этой ревизии к этим устройствам")
@@ -889,11 +920,24 @@ export async function readIxLinuxClient(segment: IxSegment, serverId: number, na
}
const client = MikrotikClient.fromServer(server)
if (binding.kind === "gre-ipsec") {
const [interfaces, policies] = await Promise.all([
readRows(client, "/interface/gre", [...greColumns, "disabled"]),
readRows(client, "/ip/ipsec/policy", ipsecPolicyColumns),
])
if (isTrue(verifyGreBinding(binding, interfaces, policies).disabled)) throw new IxConflict("Интерфейс GRE/IPsec отключён")
const interfaces = await readRows(client, "/interface/gre", [...greColumns, "disabled"])
const gre = verifyGreInterface(binding, interfaces)
if (isTrue(gre.disabled)) throw new IxConflict("Интерфейс GRE/IPsec отключён")
if (binding.provisionGre) {
const { peer, policy } = ixManagedGreFields(ixNamespace(segment.id), binding)
const [peers, policies] = await Promise.all([
readRows(client, greIpsecPaths.peer, [".id", "dynamic", ...Object.keys(peer)]),
readRows(client, greIpsecPaths.policy, [".id", "dynamic", ...Object.keys(policy)]),
])
const device = { serverId, source: "", rows: { [greIpsecPaths.peer]: peers, [greIpsecPaths.policy]: policies } }
for (const [path, fields] of [[greIpsecPaths.peer, peer], [greIpsecPaths.policy, policy]] as const) {
const row = managedRow(device, { serverId, path, fields })
if (!row || !matches(row, fields)) throw new IxConflict("Пир или политика GRE/IPsec изменены на узле · " + name)
verifyNativeId(row)
}
} else {
verifyGrePolicy(binding, await readRows(client, greIpsecPaths.policy, ipsecPolicyColumns))
}
if (includeCredential && !binding.provisionGre) throw new IxConflict("IX не выдавал этот IKEv2 PSK", 404)
const credential = includeCredential && binding.provisionGre
? (await privateFingerprinterExisting("ix-gre-client-credential-v1"))(segment.id + ":" + serverId + ":ix-credential:" + binding.provisionGre.credentialId)
@@ -974,7 +1018,7 @@ async function applyNativeTasks(native: IxNativeChange, authorize: () => Promise
if (!returnedId || !routerId.test(returnedId)) throw new IxConflict("RouterOS не подтвердил ID объекта IX")
const row = (await readRows(client, task.path, [".id", ...Object.keys(task.fields)])).find(entry => entry[".id"] === returnedId)
if (!row || !matches(row, task.fields)) {
const fields = row ? Object.keys(task.fields).filter(field => normalize(field, row[field]) !== normalize(field, task.fields![field])) : []
const fields = row ? Object.keys(task.fields).filter(field => !fieldMatches(row, task.fields!, field)) : []
throw new IxConflict("Перечитанный объект IX не совпал с планом · " + task.path + (fields.length ? " · " + fields.join(", ") : ""))
}
const vrfName = task.path === "/ip/vrf" ? task.fields.name : undefined
+13 -6
View File
@@ -28,6 +28,15 @@ const forbiddenPublic = {
}
export function ixNamespace(id: string) { return "ix-" + id.replace(/-/g, "").slice(0, 18) }
export function ixManagedGreFields(namespace: string, binding: IxSite["interfaces"][number]) {
const name = namespace + "-" + binding.name
const fields = greIke2TransportFields(name, binding.localEndpoint!, binding.endpoint!, true,
"ix-credential:" + binding.provisionGre!.credentialId, !binding.linux!.enabled)
// RouterOS derives transport-mode selectors from the active SA.
const { "src-address": _source, "dst-address": _destination, ...policy } = fields.policy
return { ...fields, peer: { ...fields.peer, disabled: "false" },
policy: { ...policy, disabled: "false", template: "false", "ipsec-protocols": "esp", comment: namespace + ":gre-policy-" + binding.name } }
}
// RouterOS accepts unambiguous prefixes for interface names before the VRF interface appears.
export function ixDiscardInterface(id: string) { return "ix-drop-" + ixNamespace(id).slice(3) }
export function ixEgressList(id: string) { return "ix-out-" + ixNamespace(id).slice(3) }
@@ -284,8 +293,8 @@ export function compileIxConfiguration(id: string, configuration: IxConfiguratio
}
const protectGre = (binding: IxSite["interfaces"][number], key: string) => {
const [inbound, outbound] = greIpsecPlaintextDrops(binding.localEndpoint!, binding.endpoint!)
add(greIpsecPaths.filter, "gre-in-" + key, inbound)
add(greIpsecPaths.filter, "gre-out-" + key, outbound)
add(greIpsecPaths.filter, "gre-in-" + key, { ...inbound, disabled: "false" })
add(greIpsecPaths.filter, "gre-out-" + key, { ...outbound, disabled: "false" })
}
const dropInterface = ixDiscardInterface(id)
for (const [index, binding] of site.interfaces.entries()) {
@@ -294,11 +303,9 @@ export function compileIxConfiguration(id: string, configuration: IxConfiguratio
if (binding.provisionTransit) compileIxTransit(namespace, site, binding, object => result.push(object))
if (wireguard) add("/interface/wireguard", "wg-" + key, { name: binding.name, "listen-port": String(wireguard.listenPort),
...(binding.linux && { disabled: String(!binding.linux.enabled) }) })
const gre = binding.provisionGre
if (gre) {
const transport = namespace + "-" + key
if (binding.provisionGre) {
protectGre(binding, key)
const fields = greIke2TransportFields(transport, binding.localEndpoint!, binding.endpoint!, true, "ix-credential:" + gre.credentialId, !binding.linux!.enabled)
const fields = ixManagedGreFields(namespace, binding)
for (const kind of ["profile", "proposal", "peer"] as const) add(greIpsecPaths[kind], key, fields[kind])
add(greIpsecPaths.identity, "gre-identity-" + key, fields.identity)
add(greIpsecPaths.policy, "gre-policy-" + key, fields.policy)