import assert from "node:assert/strict" import { randomInt, randomUUID } from "node:crypto" import { setTimeout as delay } from "node:timers/promises" import { ixSegmentConfigurationSchema } from "@mmapp/contracts/internet-exchange" import { compileIxConfiguration, ixDiscardInterface, ixNamespace } from "../../src/services/internet-exchange-plan.js" import { cli, hosts, quote } from "./ix-chr-ssh.mjs" assert.equal(process.argv[2], "--owned-test-pair") assert(process.argv.length === 3 || (process.argv.length === 4 && process.argv[3] === "--ipv6")) const ipv6 = process.argv[3] === "--ipv6" const id = randomUUID(), ns = ixNamespace(id), short = ns.slice(0, 10) const discard = ixDiscardInterface(id) const marker = ns + ":lab", primary = short + "-p", backup = short + "-b" const port = randomInt(45000, 55000) const net = "10.247." + randomInt(32, 224) const [aP, bP, aB, bB] = ipv6 ? ["fd00:247:1::1", "fd00:247:1::2", "fd00:247:2::1", "fd00:247:2::2"] : [1, 2, 5, 6].map(n => net + "." + n) const [target, pProbe, bProbe, trafficSource] = ipv6 ? ["2001:db8:3::200", "2001:db8:3::201", "2001:db8:3::202", "2001:db8:3::203"] : ["192.0.2.200", "192.0.2.201", "192.0.2.202", "192.0.2.203"] const afi = ipv6 ? "ipv6" : "ip", length = ipv6 ? "/128" : "/32", gateway = ipv6 ? "fd00:198:18::101" : "198.18.0.101" const addressPath = "/" + afi + "/address", routePath = "/" + afi + "/route", filterPath = "/" + afi + "/firewall/filter", listPath = "/" + afi + "/firewall/address-list" const advertise: Record = ipv6 ? { advertise: "no" } : {} const community = "65000:120" const entered = new Set() const results: Record = {} const pending: string[][] = [[], []] const fields = (values: Record) => Object.entries(values).map(([name, value]) => name === "blackhole" && value === "yes" ? name : name + "=" + quote(value)).join(" ") function add(side: number, path: string, values: Record, beforeMain = false) { pending[side].push(path + " add " + fields(values) + (beforeMain ? " place-before=[/ip/vrf/find where name=main]" : "")) } function flush(side: number) { while (pending[side].length) { const commands = pending[side].splice(0, 10) cli(side, commands.map((command, index) => `:put "IX_STAGE_${index}"; ${command}`).join("; ")) } } function owned(side: number, path: string, values: Record, tag: string) { add(side, path, { ...values, comment: marker + ":" + tag }) } function preflight(side: number) { const data = cli(side, `:put [/system resource get version]; :put [/system resource get board-name]; :put ([:len [/ip/vrf/find]]=1 && [:len [/interface/wireguard/find]]=0 && [:len [/routing/bgp/connection/find]]=0 && [:len [/ip/firewall/filter/find]]=0 && [:len [/ipv6/firewall/filter/find]]=0); :put [:len [/ip/address/find where address~${quote("^" + hosts[side] + "/")}]]`) const [version, board, empty, address] = data.split(/\r?\n/) assert.equal(version, "7.24.5 (stable)") assert.match(board, /^CHR/) assert.equal(empty, "true", "Stand changed, refusing a modified baseline") assert.equal(address, "1", "Expected test WAN address missing") } const config = ixSegmentConfigurationSchema.parse({ name: "ix-acceptance", sites: [ { serverId: 501, autonomousSystem: 64512, routerId: net + ".5", interfaces: [{ name: primary, kind: "wireguard", peerServerId: 502 }, { name: backup, kind: "wireguard", peerServerId: 502 }], groups: [{ id: "far", gateway, primary: { interface: primary, nextHop: bP, probe: pProbe }, backup: { interface: backup, nextHop: bB, probe: bProbe } }], neighbors: [{ id: "feed", type: "public-feed", address: bB, localAddress: aB, remoteAs: 64513, binding: backup, rules: [{ community, group: "far" }] }], }, { serverId: 502, autonomousSystem: 64513, routerId: net + ".6", interfaces: [{ name: primary, kind: "wireguard", peerServerId: 501 }, { name: backup, kind: "wireguard", peerServerId: 501 }] }, ], }) const compiled = compileIxConfiguration(id, config) const deferred = new Set([routePath, "/routing/bgp/instance", "/routing/filter/rule", "/routing/bgp/connection"]) const cleanupPaths = [...deferred].reverse().concat(listPath, "/interface/wireguard/peers", addressPath, "/ip/firewall/filter", "/ipv6/firewall/filter", "/ip/vrf", "/interface/bridge", "/interface/wireguard") function clean(side: number) { const where = `where comment~${quote("^" + ns + ":")}` cli(side, cleanupPaths.map(path => `${path} remove [${path}/find ${where}]`).join("; ")) assert.equal(cli(side, `:put (${cleanupPaths.map(path => `[:len [${path}/find ${where}]]`).join("+")})`), "0") preflight(side) } function observe() { return cli(0, `:put [/routing/route/print as-value where dst-address=${quote(target + length)} and routing-table=${quote(ns)}]`) } async function until(label: string, check: () => boolean, timeout = 75000) { const start = Date.now() while (!check()) { if (Date.now() - start > timeout) throw new Error(label + " timeout: " + observe()) await delay(900) } return Date.now() - start } function hasPath(name: string) { const fields = observe().split(";") return fields.includes("bgp=true") && fields.includes("active=true") && fields.some(field => field.startsWith("immediate-gw=") && field.endsWith("%" + name)) } function establishedSession() { const session = cli(0, `:put [/routing/bgp/session/print as-value where name~${quote(ns + "-feed")}]`).split(";") assert.ok(session.includes("established=true")) assert.ok(session.includes("prefix-count=1")) const started = session.find(field => field.startsWith("last-started=")) assert.ok(started) return started } function packetProbe(destination: string, source?: string, side = 0, routingTable = ns) { return Number(cli(side, `:put [/ping address=${destination} vrf=${routingTable} count=3 interval=250ms${source ? " src-address=" + source : ""}]`).split(/\r?\n/).at(-1)) } async function run() { preflight(0); preflight(1) for (let side = 0; side < 2; side++) { entered.add(side) for (const [index, name] of [primary, backup].entries()) owned(side, "/interface/wireguard", { name, "listen-port": String(port + index), vrf: "main" }, "wg" + index) for (const object of compiled.filter(object => object.serverId === 501 + side && !deferred.has(object.path))) { add(side, object.path, object.fields, object.path === "/ip/vrf") if (object.path === "/ip/vrf") { flush(side) await until("VRF interface", () => cli(side, `:put [:len [/interface/find where name=${quote(ns)}]]`) === "1", 9000) } } for (const [index, name] of [primary, backup].entries()) { owned(side, "/ip/firewall/filter", { chain: "input", action: "accept", protocol: "udp", "src-address": hosts[1 - side] + "/32", "dst-port": String(port + index) }, "allow-wg" + index) const inner = (side ? [bP, bB] : [aP, aB])[index] owned(side, addressPath, { address: inner + (ipv6 ? "/64" : "/30"), interface: name, ...advertise }, "address" + index) } flush(side) } for (const [index, name] of [primary, backup].entries()) { const keys = [0, 1].map(side => cli(side, `:put [/interface/wireguard/get [/interface/wireguard/find where name=${quote(name)}] public-key]`)) keys.forEach(value => assert.match(value, /^[A-Za-z0-9+/]{43}=$/)) for (const side of [0, 1]) owned(side, "/interface/wireguard/peers", { interface: name, "public-key": keys[1 - side], "endpoint-address": hosts[1 - side], "endpoint-port": String(port + index), "allowed-address": (side ? [index ? aB : aP, trafficSource] : [index ? bB : bP, target, index ? bProbe : pProbe]).map(address => address + length).join(","), "persistent-keepalive": "5" }, "peer" + index) } for (const [index, address] of [target, pProbe, bProbe].entries()) { owned(1, addressPath, { address: address + length, interface: discard, ...advertise }, "destination" + index) } owned(0, addressPath, { address: trafficSource + length, interface: discard, ...advertise }, "source") // Keep the same source and return path across both forward paths. owned(1, routePath, { "dst-address": trafficSource + length, "routing-table": ns, gateway: aB + "%" + backup + "@" + ns, "target-scope": "10" }, "return") const control = { chain: "input", "in-interface": ns, protocol: "tcp", "src-address": aB + length, action: "accept" } const beforeDeny = " place-before=[" + filterPath + "/find where comment=" + quote(ns + ":deny-input-" + (ipv6 ? "6" : "4")) + "]" cli(1, [fields({ ...control, "dst-port": "179", comment: marker + ":bgp-accept" }), fields({ ...control, "src-port": "179", "connection-state": "established", comment: marker + ":bgp-reply" })] .map(rule => filterPath + " add " + rule + beforeDeny).join("; ")) owned(1, listPath, { list: short + "-net", address: target + length }, "network") owned(1, "/routing/bgp/instance", { name: ns, as: "64513", "router-id": net + ".6", vrf: ns, "routing-table": ns }, "instance") owned(1, "/routing/filter/rule", { chain: short + "-out", rule: `if (dst == ${target}${length}) { set bgp-communities ${community}; accept; } reject;` }, "export") owned(1, "/routing/bgp/connection", { name: short + "-export", instance: ns, afi, "local.role": "ebgp", "local.address": bB, "remote.address": aB + length, "remote.as": "64512", vrf: ns, "routing-table": ns, "output.network": short + "-net", "output.filter-chain": short + "-out" }, "connection") for (const object of compiled.filter(object => object.serverId === 501 && deferred.has(object.path))) add(0, object.path, object.fields) flush(1); flush(0) await until("primary WireGuard transport", () => packetProbe(bP, aP) === 3, 40000) await until("backup WireGuard transport", () => packetProbe(bB, aB) === 3, 40000) await until("BGP primary route", () => hasPath(primary)) const session = establishedSession() results.bgpEstablished = true results.primaryRoute = observe() results.primaryReplies = packetProbe(target, trafficSource) assert.equal(results.primaryReplies, 3) assert.equal(cli(0, `:put [:len [/routing/route/find where dst-address=${quote(target + length)} and routing-table=main]]`), "0", "BGP prefix must not leak to main") results.mainIsolated = true // Drop only A's test UDP flow on the remote end. Interfaces remain enabled, // so this exercises probe-driven failover rather than administrative down. cli(1, "/ip/firewall/filter add " + fields({ chain: "input", action: "drop", protocol: "udp", "src-address": hosts[0] + "/32", "dst-port": String(port), comment: marker + ":cut" }) + " place-before=[/ip/firewall/filter/find where comment=" + quote(marker + ":allow-wg0") + "]") results.failoverMs = await until("primary underlay loss", () => hasPath(backup)) results.backupRoute = observe() results.backupReplies = packetProbe(target, trafficSource) assert.equal(results.backupReplies, 3) assert.equal(establishedSession(), session) cli(1, "/ip/firewall/filter remove [/ip/firewall/filter/find where comment=" + quote(marker + ":cut") + "]") results.failbackMs = await until("primary recovery", () => hasPath(primary)) results.recoveredReplies = packetProbe(target, trafficSource) assert.equal(results.recoveredReplies, 3) assert.equal(establishedSession(), session) results.bgpSessionKept = true } let failure: unknown try { await run() } catch (error) { failure = error for (const side of entered) try { console.error(`Test CHR ${side + 1} ยท ${cli(side, `:put [/routing/bgp/session/print as-value]; :put [/interface/wireguard/peers/print as-value proplist=interface,rx,tx,last-handshake,current-endpoint-address where comment~${quote("^" + ns + ":")}]; ${filterPath}/print stats where comment~${quote("^" + ns + ":")}; :put [${addressPath}/print as-value proplist=address,interface,invalid where comment~${quote("^" + ns + ":")}]; :put [/routing/route/print as-value where routing-table=${quote(ns)}]; :put [/routing/nexthop/print as-value where address~${quote(gateway)}]`).slice(0, 8500)}`) } catch { /* Preserve the original failure and continue cleanup. */ } } for (const side of entered) { try { clean(side) } catch (error) { console.error(`Cleanup unconfirmed on test CHR ${side + 1} for ${ns}: ${error}`) failure ??= error } } if (failure) { console.error(JSON.stringify(results)) throw failure } console.log(JSON.stringify({ ...results, testStandRestored: true }))