Compare commits

...
2 Commits
Author SHA1 Message Date
Denozordec 1337325697 fix(ix): исправить цепочку ограничения размера сегмента
Docker images / prepare-release (push) Successful in 12s
Docker images / backend-test (push) Successful in 10m57s
Docker images / frontend-image (push) Successful in 2m58s
Docker images / updater-image (push) Successful in 1m26s
Docker images / netflow-agent-image (push) Successful in 33s
Docker images / backend-image (push) Successful in 3m33s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
2026-12-04 23:31:36 +07:00
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
4 changed files with 69 additions and 16 deletions

No files matched your search

@@ -17,7 +17,7 @@ const device = (rows: Record<string, Array<Record<string, string>>>) => [{ serve
test("managed MSS rules are backfilled and removed without adopting a hand-written rule", () => {
const path = "/ip/firewall/mangle"
const from = { serverId: 17, path, fields: { comment: name + ":linux-mss-from-il-wg", action: "change-mss",
chain: "prerouting", "in-interface": "il-wg", "new-mss": "1380", "tcp-mss": "1381-65535" } }
chain: "forward", "in-interface": name, "new-mss": "1380", "tcp-mss": "1381-65535" } }
const to = { serverId: 17, path, fields: { comment: name + ":linux-mss-to-il-wg", action: "change-mss",
chain: "postrouting", "out-interface": "il-wg", "new-mss": "1380", "tcp-mss": "1381-65535" } }
const manual = { ...to.fields, comment: "manual MSS", ".id": "*A" }
@@ -34,6 +34,22 @@ test("managed MSS rules are backfilled and removed without adopting a hand-writt
assert.throws(() => planIxNative(id, desired, desired, live([{ ...fromRow, "new-mss": "1460" }, toRow])), /изменён вне операции/)
})
test("IX migrates an exact disabled legacy ingress MSS rule", () => {
const path = "/ip/firewall/mangle"
const fields = { comment: name + ":linux-mss-from-il-vps", chain: "forward", "in-interface": name,
action: "change-mss", "new-mss": "1380", disabled: "true" }
const previous = { serverId: 17, path, fields }
const next = { ...previous, fields: { ...fields, disabled: "false" } }
const legacy = { ...fields, ".id": "*C", chain: "prerouting", "in-interface": "il-vps" }
const [update] = planIxNative(id, [next], [previous], device({ [path]: [legacy] }))
assert.equal(update.rosId, "*C")
assert.deepEqual(update.fields, { chain: "forward", "in-interface": name, disabled: "false" })
const [resumed] = planIxNative(id, [previous], [], device({ [path]: [legacy] }), true)
assert.deepEqual(resumed.fields, { chain: "forward", "in-interface": name })
assert.throws(() => planIxNative(id, [next], [previous], device({ [path]: [{ ...legacy, "new-mss": "1400" }] })), /изменён вне операции/)
})
test("a new VRF is inserted before main and no foreign route is altered", () => {
const changes = planIxNative(id, [vrf, route], [], device({
"/ip/vrf": [{ ".id": "*A", name: "main", interfaces: "all", builtin: "true" }],
@@ -138,6 +154,25 @@ test("another Linux VPS can be planned while a managed GRE/IPsec peer has no SA"
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 }
@@ -78,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] ?? [] }
@@ -97,6 +106,11 @@ function verifyNativeId(row: NativeRow) {
export function planIxNative(id: string, desired: IxRouterObject[], previous: IxRouterObject[], devices: NativeDevice[], resume = false): Task[] {
const namespace = ixNamespace(id)
const egressObject = (comment = "") => comment.startsWith(namespace + ":egress-")
const legacyMssIngress = (row: NativeRow, fields: Record<string, string>) => {
const prefix = namespace + ":linux-mss-from-"
return fields.disabled === "true" && fields.action === "change-mss" && fields.comment?.startsWith(prefix) &&
matches(row, { ...fields, chain: "prerouting", "in-interface": fields.comment.slice(prefix.length) })
}
const withEgressList = new Set(devices.filter(device => Object.values(device.rows).some(rows =>
rows.some(row => egressObject(row.comment)))).map(device => device.serverId))
// An older applied revision had no egress list. A partial set still needs reconciliation.
@@ -118,7 +132,9 @@ export function planIxNative(id: string, desired: IxRouterObject[], previous: Ix
const tunnel = ["/interface/wireguard", "/interface/gre"].includes(object.path)
const managedTunnel = tunnel && [":wg-il-", ":gre-il-", ":transit-it-"].some(sign => object.fields.comment?.includes(sign))
const alreadyStopped = managedTunnel && resume && row && matches(row, { ...object.fields, disabled: "true" })
if (!row || !alreadyStopped && !matches(row, object.fields)) throw new IxConflict("Объект предыдущей ревизии IX изменён вне операции")
if (!row || !alreadyStopped && !matches(row, object.fields) && !legacyMssIngress(row, object.fields)) {
throw new IxConflict("Объект предыдущей ревизии IX изменён вне операции")
}
const task = { serverId: object.serverId, path: object.path, rosId: verifyNativeId(row), before: row }
if (managedTunnel && !isTrue(row.disabled)) shutdown.push({ ...task, fields: { disabled: "true" } })
const steps = tunnel ? interfaceCleanup : result
@@ -132,21 +148,24 @@ export function planIxNative(id: string, desired: IxRouterObject[], previous: Ix
throw new IxConflict("Служебный next hop BGP уже занят в таблице main")
}
if (resume && row && !isTrue(row.invalid) && matches(row, object.fields)) { verifyNativeId(row); continue }
if (row && !previousByKey.has(deviceMarker(object))) {
const before = previousByKey.get(deviceMarker(object)) ??
(resume && row && legacyMssIngress(row, object.fields) ? object : undefined)
if (row && !before) {
throw new IxConflict(object.fields.comment ? "Найден объект незавершённой операции IX. Сначала выполните сверку" :
"Имя объекта IX уже занято. Сначала выполните сверку")
}
if (row) {
const before = previousByKey.get(deviceMarker(object))!
if (!matches(row, before.fields)) throw new IxConflict("Объект IX изменён вне операции")
if (row && before) {
const differences = Object.keys(before.fields).filter(field => !fieldMatches(row, before.fields, field))
if (differences.length && !legacyMssIngress(row, before.fields)) 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
}
if (previousByKey.has(deviceMarker(object))) throw new IxConflict("Объект предыдущей ревизии IX исчез. Сначала выполните сверку")
if (before) throw new IxConflict("Объект предыдущей ревизии IX исчез. Сначала выполните сверку")
const foreign = rowsFor(device, path).some(entry => !entry.comment?.startsWith(namespace + ":") &&
(object.fields.name && entry.name === object.fields.name || object.fields.chain && entry.chain === object.fields.chain && path === "/routing/filter/rule" ||
object.fields["routing-table"] && entry["routing-table"] === namespace && !isTrue(entry.dynamic)))
@@ -1007,7 +1026,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
@@ -32,8 +32,7 @@ test("managed clients get their own return path and fail closed if both exit pro
provisionWireguard: { peerPublicKey: "A".repeat(43) + "=", listenPort: 51900,
localAddress: "10.254.1.1/30", peerAddress: "10.254.1.2", hubEndpoint: "192.0.2.10" } })
const objects = compileIxConfiguration(id, value)
const clamp = objects.findIndex(object => object.fields.comment === table + ":linux-mss-from-linux-wg")
assert.ok(clamp >= 0 && clamp < objects.findIndex(object => object.fields.comment === table + ":linux-linux-wg-route"))
assert.equal(objects.find(object => object.fields.comment === table + ":linux-linux-wg-route")?.fields.chain, "prerouting")
const clientTable = ixClientRoutingTable(table, "linux-wg")
const defaults = objects.filter(object => object.fields["routing-table"] === clientTable)
assert.deepEqual(defaults.map(object => object.fields.distance), ["10", "11", "254"])
@@ -47,7 +46,7 @@ test("managed clients get their own return path and fail closed if both exit pro
assert.ok(objects.every(object => object.path !== "/ip/vrf" || !object.fields.interfaces.includes("ether1")))
})
test("managed Linux tunnels clamp TCP SYN in both directions before routing marks can end prerouting", () => {
test("managed Linux tunnels clamp TCP SYN in forward from IX and postrouting to the tunnel", () => {
const value = fixture(), site = value.sites[0]
site.interfaces.push(
{ name: "linux-wg", kind: "wireguard", prefixes: [], linux: { name: "vps", enabled: true, destinations: [] },
@@ -69,7 +68,7 @@ test("managed Linux tunnels clamp TCP SYN in both directions before routing mark
action: "change-mss", "new-mss": String(mss), passthrough: "true", disabled }
assert.deepEqual(rules.filter(object => object.fields.comment.endsWith("-" + binding)), [
{ serverId: site.serverId, path: "/" + family + "/firewall/mangle",
fields: { ...shared, chain: "prerouting", "in-interface": binding, "src-address-list": list, comment: table + ":linux-mss-from-" + binding } },
fields: { ...shared, chain: "forward", "in-interface": table, "src-address-list": list, comment: table + ":linux-mss-from-" + binding } },
{ serverId: site.serverId, path: "/" + family + "/firewall/mangle",
fields: { ...shared, chain: "postrouting", "out-interface": binding, "dst-address-list": list, comment: table + ":linux-mss-to-" + binding } },
])
@@ -129,9 +129,9 @@ function compileLinuxPolicy(namespace: string, site: IxSite, binding: IxSite["in
add(filter, key + "-allow-inbound", { ...inbound, "src-address-list": permitted, "in-interface": namespace,
action: "accept", disabled: String(!policy.enabled) })
add(filter, key + "-deny-inbound", { ...inbound, action: "drop" })
// The real VRF member is visible before routing and after routing, respectively.
// RouterOS allows MSS changes in forward, where ingress is the virtual VRF interface.
add(mangle, "linux-mss-from-" + binding.name, {
...clamp, ...ingress, "src-address-list": sources,
...clamp, chain: "forward", "in-interface": namespace, "src-address-list": sources,
})
add(mangle, "linux-mss-to-" + binding.name, {
...clamp, chain: "postrouting", "out-interface": binding.name, "dst-address-list": sources,