fix(gre): сохранять и восстанавливать статические IPv6 адреса
This commit is contained in:
1 parent
655ea9727f
commit
f3cbc32720
21 files changed
+1643
-60
No files matched your search
@@ -24,7 +24,7 @@
|
||||
"test:users": "tsx src/modules/users/iface-type.test.ts && tsx src/modules/users/bindings.test.ts && tsx src/modules/users/interface-inventory.test.ts && tsx src/routes/users-catalog.test.ts",
|
||||
"test:pg": "tsx src/db/sql-bind.test.ts && tsx src/db/sqlite-json.test.ts && tsx src/db/traffic-flags.test.ts && tsx src/db/pg-schema.test.ts && tsx src/services/config-revisions.test.ts",
|
||||
"test:recursive-routes": "tsx src/routes/recursive-routes.test.ts && tsx src/services/recursive-route-catalog.test.ts && tsx src/services/recursive-apply.test.ts",
|
||||
"test:config-sync": "tsx src/services/config-apply-plan.test.ts && tsx src/services/entity-snapshots.test.ts",
|
||||
"test:config-sync": "tsx src/services/config-apply-plan.test.ts && tsx src/services/entity-snapshots.test.ts && tsx src/services/gre-ipv6.test.ts && tsx src/routes/gre-ipv6-validation.test.ts",
|
||||
"test:ros-file": "tsx src/services/ros-file-contents.test.ts && tsx src/services/mikrotik-response.test.ts",
|
||||
"test:scheduler": "tsx src/services/scheduler-running.test.ts && tsx src/services/scheduler-recorded-run.test.ts && tsx src/routes/scheduler.test.ts",
|
||||
"test:backups": "tsx src/services/backup-scheduler-run.test.ts && tsx src/services/backup-restore.test.ts && tsx src/services/backup-deletion.test.ts && tsx src/services/backup-dto.test.ts && tsx src/services/backup-storage-update.test.ts && tsx src/services/backup-job-execution.test.ts && tsx src/routes/backups-operations.test.ts && tsx src/services/s3-backup-client.test.ts",
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import assert from "node:assert/strict"
|
||||
import Fastify from "fastify"
|
||||
import { validatorCompiler, serializerCompiler } from "@fastify/type-provider-zod"
|
||||
import greRoutes from "./gre.js"
|
||||
|
||||
const app = Fastify()
|
||||
app.setValidatorCompiler(validatorCompiler)
|
||||
app.setSerializerCompiler(serializerCompiler)
|
||||
await app.register(greRoutes, { prefix: "/api" })
|
||||
for (const localInnerIp of ["fd00::1", "fd00::1/129", "fd00::1%ether1/64", "10.0.0.1/33", "bad/64", "10.0.0.1/24/x", " "]) {
|
||||
for (const method of ["POST", "PATCH"] as const) {
|
||||
const r = await app.inject({ method, url: "/api/gre/tunnels", payload: { serverId: "1", name: "own", remoteAddress: "192.0.2.1", localInnerIp } })
|
||||
assert.equal(r.statusCode, 400)
|
||||
assert.equal(r.json().error, "Некорректное тело запроса")
|
||||
}
|
||||
}
|
||||
await app.close()
|
||||
console.log("GRE IPv6: 14 invalid POST/PATCH requests rejected before DB/RouterOS access")
|
||||
@@ -15,6 +15,8 @@ import {
|
||||
planGreCreate,
|
||||
planGreDelete,
|
||||
planGreRestore,
|
||||
greAddressPath,
|
||||
GreRestoreConflict,
|
||||
} from "../services/entity-snapshots.js"
|
||||
import { executeRosOps } from "../services/ros-ops.js"
|
||||
import {
|
||||
@@ -32,7 +34,10 @@ const TunnelWriteSchema = z.object({
|
||||
rosId: z.string().optional(),
|
||||
localAddress: z.string().optional(),
|
||||
remoteAddress: z.string().min(1),
|
||||
localInnerIp: z.string().optional(),
|
||||
localInnerIp: z.string().refine(value => {
|
||||
if (!value) return true
|
||||
try { greAddressPath(value); return true } catch { return false }
|
||||
}, "Требуется IPv4/IPv6 с префиксом").optional(),
|
||||
remoteInnerIp: z.string().optional(),
|
||||
comment: z.string().optional(),
|
||||
enabled: z.boolean().optional(),
|
||||
@@ -126,7 +131,7 @@ const greRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
const created = state.tunnels.find((t) => t.name === tunnel.name)
|
||||
return reply.status(201).send(created ?? { ok: true, name: tunnel.name })
|
||||
} catch (e) {
|
||||
return reply.status(502).send({ error: `RouterOS: ${rosErr(e)}` })
|
||||
return reply.status(e instanceof GreRestoreConflict ? 409 : 502).send({ error: `RouterOS: ${rosErr(e)}` })
|
||||
}
|
||||
})
|
||||
|
||||
@@ -144,12 +149,15 @@ const greRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
(body.rosId && g.rosId === body.rosId) || (body.name && g.name === body.name),
|
||||
)
|
||||
if (!live) return reply.status(404).send({ error: "Туннель не найден" })
|
||||
if (body.rosId && body.rosId !== live.rosId) return reply.status(409).send({ error: "ID и имя GRE указывают на разные объекты" })
|
||||
if (body.name && body.name !== live.name) return reply.status(409).send({ error: "Переименование GRE требует отдельной операции" })
|
||||
const original = state.snapshot.tunnels.find(t => t.name === live.name)!
|
||||
const merged = tunnelFromBody({
|
||||
serverId: body.serverId,
|
||||
name: body.name || live.name,
|
||||
localAddress: body.localAddress ?? live.localAddress,
|
||||
remoteAddress: body.remoteAddress || live.remoteAddress,
|
||||
localInnerIp: body.localInnerIp ?? state.addrs.find((a) => a.interfaceName === live.name)?.address ?? "",
|
||||
localInnerIp: body.localInnerIp ?? original.localInnerIp,
|
||||
remoteInnerIp: body.remoteInnerIp ?? state.tunnels.find(t => t.name === live.name)?.remoteInnerIp ?? "",
|
||||
comment: body.comment ?? live.comment,
|
||||
enabled: body.enabled ?? !live.disabled,
|
||||
@@ -161,15 +169,22 @@ const greRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
allowFastPath: body.allowFastPath ?? live.allowFastPath,
|
||||
ipsecSecret: body.ipsecSecret ?? live.ipsecSecret,
|
||||
})
|
||||
merged.innerAddresses = original.innerAddresses?.map(a => ({ ...a }))
|
||||
if (body.localInnerIp !== undefined && body.localInnerIp !== original.localInnerIp) {
|
||||
merged.innerAddresses = (merged.innerAddresses ?? []).filter(a => a.address !== original.localInnerIp)
|
||||
if (body.localInnerIp && !merged.innerAddresses.some(a => a.address === body.localInnerIp)) {
|
||||
merged.innerAddresses.push({ address: body.localInnerIp, disabled: false, ...(greAddressPath(body.localInnerIp) === "/ipv6/address" ? { advertise: false } : {}) })
|
||||
}
|
||||
}
|
||||
const ops = planGreRestore(
|
||||
{ tunnels: state.snapshot.tunnels.map((t) => t.name === live.name ? merged : t) },
|
||||
{ gre: state.gre, addrs: state.addrs },
|
||||
{ tunnels: [merged] },
|
||||
{ gre: [live], addrs: state.addrs.filter(a => a.interfaceName === live.name) },
|
||||
)
|
||||
await executeRosOps(state.client, ops)
|
||||
await recordGre(server, "apply")
|
||||
return reply.send({ ok: true })
|
||||
} catch (e) {
|
||||
return reply.status(502).send({ error: `RouterOS: ${rosErr(e)}` })
|
||||
return reply.status(e instanceof GreRestoreConflict ? 409 : 502).send({ error: `RouterOS: ${rosErr(e)}` })
|
||||
}
|
||||
})
|
||||
|
||||
@@ -187,11 +202,12 @@ const greRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
(body.rosId && g.rosId === body.rosId) || (body.name && g.name === body.name),
|
||||
)
|
||||
if (!live) return reply.status(404).send({ error: "Туннель не найден" })
|
||||
if ((body.rosId && body.rosId !== live.rosId) || (body.name && body.name !== live.name)) return reply.status(409).send({ error: "ID и имя GRE указывают на разные объекты" })
|
||||
await executeRosOps(state.client, planGreDelete(live.name, { gre: state.gre, addrs: state.addrs }))
|
||||
await recordGre(server, "apply")
|
||||
return reply.send({ ok: true })
|
||||
} catch (e) {
|
||||
return reply.status(502).send({ error: `RouterOS: ${rosErr(e)}` })
|
||||
return reply.status(e instanceof GreRestoreConflict ? 409 : 502).send({ error: `RouterOS: ${rosErr(e)}` })
|
||||
}
|
||||
})
|
||||
|
||||
@@ -223,7 +239,7 @@ const greRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
const next = await fetchGreState(loaded.server)
|
||||
return reply.send({ ok: true, tunnels: next.tunnels })
|
||||
} catch (e) {
|
||||
return reply.status(502).send({ error: `RouterOS: ${rosErr(e)}` })
|
||||
return reply.status(e instanceof GreRestoreConflict ? 409 : 502).send({ error: `RouterOS: ${rosErr(e)}` })
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/** Канонические снапшоты и планы restore для firewall / WireGuard / GRE / IPsec. */
|
||||
import { isIpsecManagedComment, isManagedIpsecModeConfig } from "./ipsec-config.js"
|
||||
import { readGreComment, writeGreComment } from "./gre-comment.js"
|
||||
import { isIP } from "node:net"
|
||||
|
||||
export type FirewallFamily = "ip" | "ip6"
|
||||
export type FirewallTable = "filter" | "nat" | "mangle" | "raw"
|
||||
@@ -129,6 +130,7 @@ export interface GreSnapshotTunnel {
|
||||
localAddress: string
|
||||
remoteAddress: string
|
||||
localInnerIp: string
|
||||
innerAddresses?: GreSnapshotAddress[]
|
||||
remoteInnerIp: string
|
||||
comment: string
|
||||
disabled: boolean
|
||||
@@ -163,6 +165,40 @@ export interface GreLiveAddr {
|
||||
rosId: string
|
||||
interfaceName: string
|
||||
address: string
|
||||
disabled?: boolean
|
||||
advertise?: boolean
|
||||
dynamic?: boolean
|
||||
comment?: string
|
||||
noDad?: boolean
|
||||
fromPool?: string
|
||||
eui64?: boolean
|
||||
}
|
||||
|
||||
export interface GreSnapshotAddress {
|
||||
address: string
|
||||
disabled: boolean
|
||||
advertise?: boolean
|
||||
comment?: string
|
||||
noDad?: boolean
|
||||
fromPool?: string
|
||||
eui64?: boolean
|
||||
}
|
||||
|
||||
export class GreRestoreConflict extends Error {}
|
||||
|
||||
export function greAddressPath(address: string): "/ip/address" | "/ipv6/address" {
|
||||
const parts = address.split("/")
|
||||
const family = isIP(parts[0] ?? "")
|
||||
if (!family || address.includes("%") || parts.length !== 2 || !/^\d+$/.test(parts[1] ?? "") || Number(parts[1]) > (family === 6 ? 128 : 32)) {
|
||||
throw new GreRestoreConflict("Некорректный внутренний адрес GRE: требуется IPv4/IPv6 с префиксом")
|
||||
}
|
||||
return family === 6 ? "/ipv6/address" : "/ip/address"
|
||||
}
|
||||
|
||||
export function greAddressKey(address: string): string {
|
||||
const path = greAddressPath(address)
|
||||
const [ip, prefix] = address.split("/")
|
||||
return `${path === "/ipv6/address" ? new URL(`http://[${ip}]`).hostname : ip}/${Number(prefix)}`
|
||||
}
|
||||
|
||||
// ── IPsec / IKEv2 (managed-объекты, маркер MikrotikManager:ipsec) ────────────
|
||||
@@ -864,6 +900,17 @@ export function canonicalGreSnapshot(input: {
|
||||
localAddress: str(t.localAddress),
|
||||
remoteAddress: str(t.remoteAddress),
|
||||
localInnerIp: str(t.localInnerIp),
|
||||
...(t.innerAddresses === undefined ? {} : {
|
||||
innerAddresses: t.innerAddresses.map(a => ({
|
||||
address: str(a.address), disabled: bool(a.disabled),
|
||||
...(a.comment === undefined ? {} : { comment: str(a.comment) }),
|
||||
...(greAddressPath(str(a.address)) === "/ipv6/address" ? { advertise: a.advertise === true,
|
||||
...(a.noDad === undefined ? {} : { noDad: a.noDad === true }),
|
||||
...(a.fromPool ? { fromPool: str(a.fromPool) } : {}),
|
||||
...(a.eui64 ? { eui64: true } : {}),
|
||||
} : {}),
|
||||
})).sort((a, b) => a.address.localeCompare(b.address)),
|
||||
}),
|
||||
remoteInnerIp: str(t.remoteInnerIp),
|
||||
comment: str(t.comment),
|
||||
disabled: Boolean(t.disabled),
|
||||
@@ -913,11 +960,13 @@ export function planGreCreate(tunnel: GreSnapshotTunnel): RosWriteOp[] {
|
||||
const ops: RosWriteOp[] = [
|
||||
{ op: "put", path: "/interface/gre", body: greInterfaceBody(t) },
|
||||
]
|
||||
if (t.localInnerIp) {
|
||||
const addresses = t.innerAddresses ?? (t.localInnerIp ? [{ address: t.localInnerIp, disabled: false }] : [])
|
||||
if (new Set(addresses.map(a => greAddressKey(a.address))).size !== addresses.length) throw new GreRestoreConflict("В ревизии GRE повторяются внутренние адреса")
|
||||
for (const a of addresses) {
|
||||
ops.push({
|
||||
op: "put",
|
||||
path: "/ip/address",
|
||||
body: { address: t.localInnerIp, interface: t.name },
|
||||
path: greAddressPath(a.address),
|
||||
body: greAddressBody(a, t.name),
|
||||
})
|
||||
}
|
||||
return ops
|
||||
@@ -930,8 +979,8 @@ export function planGreDelete(
|
||||
const want = str(name)
|
||||
const ops: RosWriteOp[] = []
|
||||
for (const addr of current.addrs) {
|
||||
if (addr.interfaceName === want) {
|
||||
ops.push({ op: "delete", path: `/ip/address/${addr.rosId}` })
|
||||
if (addr.interfaceName === want && !addr.dynamic) {
|
||||
ops.push({ op: "delete", path: `${greAddressPath(addr.address)}/${addr.rosId}` })
|
||||
}
|
||||
}
|
||||
for (const gre of current.gre) {
|
||||
@@ -965,30 +1014,40 @@ export function planGreRestore(
|
||||
ops.push({ op: "patch", path: `/interface/gre/${live.rosId}`, body })
|
||||
}
|
||||
|
||||
const liveAddr = current.addrs.find((a) => a.interfaceName === want.name)
|
||||
if (want.localInnerIp) {
|
||||
if (!liveAddr) {
|
||||
ops.push({
|
||||
op: "put",
|
||||
path: "/ip/address",
|
||||
body: { address: want.localInnerIp, interface: want.name },
|
||||
})
|
||||
} else if (liveAddr.address !== want.localInnerIp) {
|
||||
ops.push({ op: "delete", path: `/ip/address/${liveAddr.rosId}` })
|
||||
ops.push({
|
||||
op: "put",
|
||||
path: "/ip/address",
|
||||
body: { address: want.localInnerIp, interface: want.name },
|
||||
})
|
||||
const liveAddrs = current.addrs.filter(a => a.interfaceName === want.name && !a.dynamic)
|
||||
if (liveAddrs.some(a => a.fromPool || a.eui64)) throw new GreRestoreConflict("GRE содержит адрес из IPv6-пула или EUI-64. Измените его отдельно в RouterOS")
|
||||
if (want.innerAddresses === undefined && liveAddrs.length > 1) {
|
||||
throw new GreRestoreConflict("Старая ревизия GRE не описывает все адреса интерфейса. Восстановление остановлено")
|
||||
}
|
||||
const addresses = want.innerAddresses ?? (want.localInnerIp ? [{ address: want.localInnerIp, disabled: false }] : [])
|
||||
const keys = new Set(addresses.map(a => greAddressKey(a.address)))
|
||||
if (keys.size !== addresses.length) throw new GreRestoreConflict("В ревизии GRE повторяются внутренние адреса")
|
||||
for (const addr of liveAddrs) {
|
||||
if (!keys.has(greAddressKey(addr.address))) ops.push({ op: "delete", path: `${greAddressPath(addr.address)}/${addr.rosId}` })
|
||||
}
|
||||
for (const addr of addresses) {
|
||||
const existing = liveAddrs.find(a => greAddressKey(a.address) === greAddressKey(addr.address))
|
||||
if (!existing) ops.push({ op: "put", path: greAddressPath(addr.address), body: greAddressBody(addr, want.name) })
|
||||
else if (Boolean(existing.disabled) !== addr.disabled || (addr.comment !== undefined && str(existing.comment) !== addr.comment) || (greAddressPath(addr.address) === "/ipv6/address" && (Boolean(existing.advertise) !== Boolean(addr.advertise) || (addr.noDad !== undefined && Boolean(existing.noDad) !== addr.noDad)))) {
|
||||
ops.push({ op: "patch", path: `${greAddressPath(addr.address)}/${existing.rosId}`, body: greAddressBody(addr, want.name) })
|
||||
}
|
||||
} else if (liveAddr) {
|
||||
ops.push({ op: "delete", path: `/ip/address/${liveAddr.rosId}` })
|
||||
}
|
||||
}
|
||||
|
||||
return ops
|
||||
}
|
||||
|
||||
function greAddressBody(a: GreSnapshotAddress, name: string): Record<string, string> {
|
||||
if (a.fromPool || a.eui64) throw new GreRestoreConflict("Восстановление IPv6-пула/EUI-64 требует отдельной настройки RouterOS")
|
||||
return {
|
||||
address: a.address, interface: name,
|
||||
...(a.comment === undefined ? {} : { comment: a.comment }),
|
||||
...(a.disabled ? { disabled: "yes" } : { disabled: "no" }),
|
||||
...(greAddressPath(a.address) === "/ipv6/address" ? { advertise: a.advertise ? "yes" : "no" } : {}),
|
||||
...(a.noDad === undefined ? {} : { "no-dad": a.noDad ? "yes" : "no" }),
|
||||
}
|
||||
}
|
||||
|
||||
export function opsPaths(ops: RosWriteOp[]): string[] {
|
||||
return ops.map((op) => op.path)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { canonicalGreSnapshot, greAddressPath, GreRestoreConflict, planGreCreate, planGreDelete, planGreRestore, parseGreSnapshot } from "./entity-snapshots.js"
|
||||
import { fetchGreState, mapGreLive } from "./gre-live.js"
|
||||
import { MikrotikClient } from "./mikrotik.js"
|
||||
import type { servers } from "../db/schema.js"
|
||||
|
||||
const server = { id: 1, name: "CHR", enabled: true } as typeof servers.$inferSelect
|
||||
const raw = [{ ".id": "*g", name: "own-gre", "remote-address": "192.0.2.1", running: "true" }]
|
||||
const rows = [
|
||||
{ ".id": "*1", interface: "own-gre", address: "10.1.0.1/30" },
|
||||
{ ".id": "*1", interface: "own-gre", address: "fd00:151::1/64", advertise: "yes" },
|
||||
{ ".id": "*2", interface: "own-gre", address: "fd00:151::2/64", disabled: "true", advertise: "no" },
|
||||
{ ".id": "*3", interface: "own-gre", address: "fe80::1/64", dynamic: "true" },
|
||||
{ ".id": "*4", interface: "public", address: "192.0.2.2/24" },
|
||||
]
|
||||
const state = mapGreLive(server, raw, rows)
|
||||
assert.equal(state.addrs.length, 3)
|
||||
assert.equal(state.tunnels[0]?.localInnerIp, "10.1.0.1/30")
|
||||
assert.equal(state.snapshot.tunnels[0]?.innerAddresses?.length, 3)
|
||||
assert.deepEqual(mapGreLive(server, raw, [...rows].reverse()).snapshot, state.snapshot)
|
||||
assert.equal(mapGreLive(server, raw, rows.slice(1)).tunnels[0]?.localInnerIp, "fd00:151::1/64")
|
||||
const del = planGreDelete("own-gre", state)
|
||||
assert.deepEqual(del.map(op => op.path), ["/ip/address/*1", "/ipv6/address/*1", "/ipv6/address/*2", "/interface/gre/*g"])
|
||||
assert(!del.some(op => op.path.includes("*3") || op.path.includes("*4")))
|
||||
const noChanges = planGreRestore(state.snapshot, state)
|
||||
assert.equal(noChanges.filter(op => op.path.includes("/address")).length, 0)
|
||||
const expanded = structuredClone(state.snapshot)
|
||||
expanded.tunnels[0]!.innerAddresses![1]!.address = "fd00:0151:0000:0000:0000:0000:0000:0001/64"
|
||||
assert.equal(planGreRestore(expanded, state).filter(op => op.path.includes("/address")).length, 0)
|
||||
const legacy = canonicalGreSnapshot({ tunnels: [{ name: "own-gre", localInnerIp: "fd00:151::1/64" }] })
|
||||
assert.equal(parseGreSnapshot(legacy).tunnels[0]?.innerAddresses, undefined)
|
||||
assert.throws(() => planGreRestore(legacy, state), GreRestoreConflict)
|
||||
for (const address of ["fd00::1/64", "10.0.0.1/30"]) {
|
||||
const t = canonicalGreSnapshot({ tunnels: [{ name: "own-gre", localInnerIp: address }] }).tunnels[0]!
|
||||
const create = planGreCreate(t)
|
||||
assert.equal(create[1]?.path, greAddressPath(address))
|
||||
if (create[1]?.op === "put" && address.includes(":")) assert.equal(create[1].body.advertise, "no")
|
||||
const only = { gre: state.gre, addrs: [{ rosId: "*x", interfaceName: "own-gre", address: address.includes(":") ? "10.0.0.1/30" : "fd00::1/64" }] }
|
||||
const restore = planGreRestore({ tunnels: [t] }, only)
|
||||
assert(restore.some(op => op.op === "delete" && op.path === `${greAddressPath(only.addrs[0]!.address)}/*x`))
|
||||
assert(restore.some(op => op.op === "put" && op.path === greAddressPath(address)))
|
||||
}
|
||||
const flags = structuredClone(state.snapshot)
|
||||
flags.tunnels[0]!.innerAddresses![1]!.advertise = false
|
||||
assert(planGreRestore(flags, state).some(op => op.op === "patch" && op.path === "/ipv6/address/*1" && op.body.advertise === "no"))
|
||||
for (const address of ["fd00::1", "fd00::1/129", "fd00::1/-1", "bad/64", "10.0.0.1/33", "10.0.0.1/", "10.0.0.1/24/x"]) assert.throws(() => greAddressPath(address), GreRestoreConflict)
|
||||
const duplicate = structuredClone(state.snapshot)
|
||||
duplicate.tunnels[0]!.innerAddresses!.push({ address: "fd00:0151:0:0:0:0:0:1/64", disabled: false })
|
||||
assert.throws(() => planGreRestore(duplicate, state), GreRestoreConflict)
|
||||
assert.throws(() => planGreRestore(state.snapshot, { ...state, addrs: state.addrs.map(a => ({ ...a, fromPool: "pool6" })) }), GreRestoreConflict)
|
||||
assert.throws(() => planGreCreate(canonicalGreSnapshot({ tunnels: [{ name: "pooled", innerAddresses: [{ address: "fd00::1/64", disabled: false, eui64: true }] }] }).tunnels[0]!), GreRestoreConflict)
|
||||
const original = MikrotikClient.fromServer
|
||||
try {
|
||||
const calls: string[] = []
|
||||
MikrotikClient.fromServer = () => ({ get: async (path: string) => {
|
||||
calls.push(path)
|
||||
if (path === "/interface/gre") return raw
|
||||
if (path === "/ip/address") return [rows[0]]
|
||||
if (path === "/ipv6/address") return rows.slice(1)
|
||||
throw new Error("Unexpected path")
|
||||
} }) as unknown as MikrotikClient
|
||||
assert.equal((await fetchGreState(server)).addrs.length, 3)
|
||||
assert.deepEqual(calls.sort(), ["/interface/gre", "/ip/address", "/ipv6/address"])
|
||||
MikrotikClient.fromServer = () => ({ get: async (path: string) => {
|
||||
if (path === "/ipv6/address") throw new Error("Unauthorized")
|
||||
return []
|
||||
} }) as unknown as MikrotikClient
|
||||
await assert.rejects(fetchGreState(server), /Unauthorized/)
|
||||
MikrotikClient.fromServer = () => ({ get: async () => ({}) }) as unknown as MikrotikClient
|
||||
await assert.rejects(fetchGreState(server), /неполный каталог/)
|
||||
} finally { MikrotikClient.fromServer = original }
|
||||
console.log("GRE IPv6: static catalog, disabled/advertise, family IDs, legacy conflict, normalization, create/restore/delete and failed reads passed")
|
||||
@@ -1,10 +1,11 @@
|
||||
import { eq } from "drizzle-orm"
|
||||
import { and, eq } from "drizzle-orm"
|
||||
import { db } from "../db/index.js"
|
||||
import { servers } from "../db/schema.js"
|
||||
import { MikrotikClient } from "./mikrotik.js"
|
||||
import { readGreComment } from "./gre-comment.js"
|
||||
import {
|
||||
canonicalGreSnapshot,
|
||||
greAddressPath,
|
||||
type GreLiveAddr,
|
||||
type GreLiveIface,
|
||||
type GreSnapshot,
|
||||
@@ -35,6 +36,12 @@ interface RosIpAddress {
|
||||
interface?: string
|
||||
disabled?: string
|
||||
network?: string
|
||||
dynamic?: string
|
||||
advertise?: string
|
||||
comment?: string
|
||||
"no-dad"?: string
|
||||
"from-pool"?: string
|
||||
"eui-64"?: string
|
||||
}
|
||||
|
||||
export interface LiveGreTunnel {
|
||||
@@ -83,7 +90,7 @@ function parseDscp(value: string | undefined): "inherit" | number {
|
||||
|
||||
function parseInnerFromComment(comment: string | undefined): { localInnerIp: string; remoteInnerIp: string } {
|
||||
if (!comment) return { localInnerIp: "", remoteInnerIp: "" }
|
||||
const local = comment.match(/address\s*=\s*([0-9.]+\/\d+)/)?.[1] ?? ""
|
||||
const local = comment.match(/address\s*=\s*([0-9a-fA-F:.]+\/\d+)/)?.[1] ?? ""
|
||||
const remote = readGreComment(comment).remoteInnerIp
|
||||
return { localInnerIp: local, remoteInnerIp: remote }
|
||||
}
|
||||
@@ -102,15 +109,19 @@ export function mapGreLive(
|
||||
gre: GreLiveIface[]
|
||||
addrs: GreLiveAddr[]
|
||||
} {
|
||||
const addrsByIface = new Map<string, { address: string; rosId: string }[]>()
|
||||
const addrsByIface = new Map<string, GreLiveAddr[]>()
|
||||
const greNames = new Set(greRaw.map(g => (g.name ?? "").trim()))
|
||||
for (const a of addrsRaw) {
|
||||
if (rosDisabled(a.disabled)) continue
|
||||
if (rosDisabled(a.dynamic)) continue
|
||||
const iface = (a.interface ?? "").trim()
|
||||
const address = (a.address ?? "").trim()
|
||||
const rosId = String(a[".id"] ?? "")
|
||||
if (!iface || !address || !rosId) continue
|
||||
if (!iface || !address || !rosId || !greNames.has(iface)) continue
|
||||
const list = addrsByIface.get(iface) ?? []
|
||||
list.push({ address, rosId })
|
||||
const family = greAddressPath(address)
|
||||
list.push({ address, rosId, interfaceName: iface, disabled: rosDisabled(a.disabled), comment: a.comment ?? "",
|
||||
...(family === "/ipv6/address" ? { advertise: rosDisabled(a.advertise), noDad: rosDisabled(a["no-dad"]), fromPool: a["from-pool"] ?? "", eui64: rosDisabled(a["eui-64"]) } : {}),
|
||||
})
|
||||
addrsByIface.set(iface, list)
|
||||
}
|
||||
|
||||
@@ -124,6 +135,7 @@ export function mapGreLive(
|
||||
const keepalive = parseKeepalive(g.keepalive)
|
||||
const fromComment = parseInnerFromComment(g.comment)
|
||||
const ifaceAddrs = addrsByIface.get(name) ?? []
|
||||
ifaceAddrs.sort((a, b) => Number(Boolean(a.disabled)) - Number(Boolean(b.disabled)) || a.address.localeCompare(b.address))
|
||||
const localInnerIp = ifaceAddrs[0]?.address || fromComment.localInnerIp
|
||||
const secret = (g["ipsec-secret"] ?? "").trim()
|
||||
const disabled = rosDisabled(g.disabled)
|
||||
@@ -145,7 +157,7 @@ export function mapGreLive(
|
||||
})
|
||||
|
||||
for (const a of ifaceAddrs) {
|
||||
addrs.push({ rosId: a.rosId, interfaceName: name, address: a.address })
|
||||
addrs.push(a)
|
||||
}
|
||||
|
||||
tunnels.push({
|
||||
@@ -178,7 +190,10 @@ export function mapGreLive(
|
||||
name: g.name,
|
||||
localAddress: g.localAddress,
|
||||
remoteAddress: g.remoteAddress,
|
||||
localInnerIp: addrs.find((a) => a.interfaceName === g.name)?.address ?? "",
|
||||
localInnerIp: tunnels.find(t => t.name === g.name)?.localInnerIp ?? "",
|
||||
innerAddresses: addrs.filter(a => a.interfaceName === g.name).map(a => ({ address: a.address, disabled: Boolean(a.disabled), comment: a.comment,
|
||||
...(a.advertise === undefined ? {} : { advertise: a.advertise, noDad: a.noDad, fromPool: a.fromPool, eui64: a.eui64 }),
|
||||
})),
|
||||
remoteInnerIp: tunnels.find(t => t.name === g.name)?.remoteInnerIp ?? "",
|
||||
comment: g.comment,
|
||||
disabled: g.disabled,
|
||||
@@ -197,13 +212,15 @@ export function mapGreLive(
|
||||
|
||||
export async function fetchGreState(server: ServerRow) {
|
||||
const client = MikrotikClient.fromServer(server)
|
||||
const [greRaw, addrsRaw] = await Promise.all([
|
||||
const [greRaw, addrsRaw, ipv6Raw] = await Promise.all([
|
||||
client.get<RosGre[]>("/interface/gre"),
|
||||
client.get<RosIpAddress[]>("/ip/address").catch(() => [] as RosIpAddress[]),
|
||||
client.get<RosIpAddress[]>("/ip/address"),
|
||||
client.get<RosIpAddress[]>("/ipv6/address"),
|
||||
])
|
||||
if (![greRaw, addrsRaw, ipv6Raw].every(Array.isArray)) throw new Error("RouterOS: неполный каталог GRE/адресов")
|
||||
return {
|
||||
client,
|
||||
...mapGreLive(server, Array.isArray(greRaw) ? greRaw : [], Array.isArray(addrsRaw) ? addrsRaw : []),
|
||||
...mapGreLive(server, Array.isArray(greRaw) ? greRaw : [], [...(Array.isArray(addrsRaw) ? addrsRaw : []), ...(Array.isArray(ipv6Raw) ? ipv6Raw : [])]),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -222,7 +239,7 @@ export async function listGreTunnels(opts?: { serverId?: string }): Promise<{
|
||||
if (!Number.isFinite(id)) {
|
||||
return { tunnels: [], failures: [{ serverId: String(opts.serverId), error: "Некорректный serverId" }] }
|
||||
}
|
||||
const row = (await db.select().from(servers).where(eq(servers.id, id)).limit(1))[0]
|
||||
const row = (await db.select().from(servers).where(and(eq(servers.id, id), eq(servers.enabled, true))).limit(1))[0]
|
||||
serverRows = row ? [row] : []
|
||||
} else {
|
||||
serverRows = await db.select().from(servers).where(eq(servers.enabled, true))
|
||||
|
||||
Reference in new issue
Block a user