|
|
|
@@ -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
|
|
|
|
|