Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Failing after 4m0s
Docker images / backend-image (push) Skipped
Docker images / frontend-image (push) Successful in 5m0s
Docker images / updater-image (push) Successful in 1m56s
Docker images / netflow-agent-image (push) Successful in 33s
Docker images / publish-release (push) Skipped
Docker images / notify-webhook (push) Skipped
265 lines
16 KiB
TypeScript
265 lines
16 KiB
TypeScript
import assert from "node:assert/strict"
|
|
import { randomBytes, randomUUID, X509Certificate } from "node:crypto"
|
|
import { mkdtemp } from "node:fs/promises"
|
|
import { createServer, isIPv4 } from "node:net"
|
|
import { tmpdir } from "node:os"
|
|
import { join } from "node:path"
|
|
import { setTimeout as delay } from "node:timers/promises"
|
|
import { getCACertificates, setDefaultCACertificates } from "node:tls"
|
|
import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client"
|
|
import EmbeddedPostgres from "embedded-postgres"
|
|
import { SignJWT } from "jose"
|
|
import { ixNamespace } from "../../src/services/internet-exchange-plan.js"
|
|
import { cli, hosts, quote } from "./ix-chr-ssh.mjs"
|
|
|
|
assert.deepEqual(process.argv.slice(2), ["--owned-test-pair"])
|
|
for (const name of Object.keys(process.env)) {
|
|
if (/^(DATABASE_|MCP_|AUTH_|PG|MMAPP_)/.test(name)) delete process.env[name]
|
|
}
|
|
process.env.DOTENV_CONFIG_PATH = join(tmpdir(), "mmapp-ix-no-env-" + randomUUID())
|
|
|
|
const id = randomUUID(), ns = ixNamespace(id), short = ns.slice(0, 12)
|
|
const segment = short + "-gre", gre = short + "-gre", pin = (side: number) => "10.245.0." + (1 + side)
|
|
const psk = randomBytes(32).toString("hex"), password = randomBytes(24).toString("hex")
|
|
const roots = getCACertificates("default")
|
|
const certificates: string[] = []
|
|
const entered = new Map<number, string>()
|
|
const result: Record<string, unknown> = {}
|
|
let appliedNamespace: string | undefined
|
|
const ipsecPaths = ["/ip/ipsec/policy", "/ip/ipsec/identity", "/ip/ipsec/peer", "/ip/ipsec/proposal", "/ip/ipsec/profile"]
|
|
const ixPaths = ["/ip/route", "/ip/address", "/ip/firewall/filter", "/ipv6/firewall/filter", "/ip/vrf", "/interface/bridge"]
|
|
const sides = [0, 1]
|
|
|
|
function baseline(side: number) {
|
|
return cli(side, `:put [/system resource get version]; :put [/system resource get board-name];
|
|
:put [/ip/service/print as-value proplist=disabled,port,certificate,address where name=www-ssl and dynamic=no];
|
|
:put [:len [/interface/gre/find]]; :put [:len [/ip/vrf/find]];
|
|
:put [:len [/ip/ipsec/peer/find]]; :put [:len [/ip/ipsec/installed-sa/find]];
|
|
:put [:len [/ip/firewall/filter/find]]; :put [:len [/ipv6/firewall/filter/find]];
|
|
:put [:len [/ip/address/find where address~${quote("^" + hosts[side] + "/")}]]`)
|
|
}
|
|
|
|
async function port() {
|
|
const socket = createServer()
|
|
await new Promise<void>((ok, fail) => socket.listen(0, "127.0.0.1", ok).on("error", fail))
|
|
const value = (socket.address() as { port: number }).port
|
|
await new Promise<void>((ok, fail) => socket.close(error => error ? fail(error) : ok()))
|
|
return value
|
|
}
|
|
|
|
async function until<T>(label: string, check: () => T | Promise<T>, timeout = 45000) {
|
|
const end = Date.now() + timeout
|
|
do {
|
|
const value = await check()
|
|
if (value) return value
|
|
await delay(900)
|
|
} while (Date.now() < end)
|
|
throw Error(label + " timed out")
|
|
}
|
|
|
|
function prepareGre(side: number) {
|
|
const local = hosts[side], remote = hosts[1 - side]
|
|
const p = quote(short)
|
|
cli(side, `:put "profile"; /ip/ipsec/profile/add name=${p} enc-algorithm=aes-256 hash-algorithm=sha256 dh-group=modp2048;
|
|
:put "proposal"; /ip/ipsec/proposal/add name=${p} enc-algorithms=aes-256-cbc auth-algorithms=sha256 pfs-group=modp2048;
|
|
:put "peer"; /ip/ipsec/peer/add name=${p} address=${remote}/32 local-address=${local} profile=${p} exchange-mode=ike2 passive=${side ? "yes" : "no"};
|
|
:put "identity"; /ip/ipsec/identity/add peer=${p} auth-method=pre-shared-key secret=${quote(psk)} comment=${p};
|
|
:put "policy"; /ip/ipsec/policy/add peer=${p} src-address=${local}/32 dst-address=${remote}/32 protocol=gre action=encrypt level=require tunnel=no proposal=${p} comment=${p};
|
|
:put "GRE"; /interface/gre/add name=${quote(gre)} local-address=${local} remote-address=${remote} allow-fast-path=no comment=${quote("IX:" + segment)};
|
|
/ip/address/add address=${pin(side)}/30 interface=${quote(gre)} comment=${quote(ns + ":lab:gre")}`, "isolated IKEv2/GRE setup")
|
|
}
|
|
|
|
async function openRest(side: number) {
|
|
const sessions = cli(side, ':put [/user/active/print as-value proplist=address where name=claude and via=ssh]')
|
|
const sources = [...new Set([...sessions.matchAll(/address=([\d.]+)/g)].map(match => match[1]))]
|
|
assert(sources.length === 1 && isIPv4(sources[0]), "Cannot pin HTTPS to a single observed management address")
|
|
const source = sources[0] + "/32", host = hosts[side], ca = short + "-ca", leaf = short + "-tls"
|
|
cli(side, `/certificate/add name=${quote(ca)} common-name=${quote(ca)} key-usage=key-cert-sign,crl-sign days-valid=1;
|
|
/certificate/sign [find where name=${quote(ca)}];
|
|
/certificate/add name=${quote(leaf)} common-name=${quote(host)} subject-alt-name=IP:${host} key-usage=tls-server days-valid=1;
|
|
/certificate/sign [find where name=${quote(leaf)}] ca=${quote(ca)};
|
|
/certificate/export-certificate [find where name=${quote(ca)}] file-name=${quote(ca)}`)
|
|
const certificate = cli(side, `:put [/file/get [find where name=${quote(ca + ".crt")}] contents]`)
|
|
assert.equal(new X509Certificate(certificate).ca, true)
|
|
certificates.push(certificate)
|
|
setDefaultCACertificates([...roots, ...certificates])
|
|
cli(side, `/ip/firewall/filter/add chain=input action=drop protocol=tcp dst-port=443 dst-address=${host}/32 src-address=!${source} comment=${quote(ns + ":lab:tls")};
|
|
/user/group/add name=${quote(short)} policy=read,write,api,rest-api;
|
|
/user/add name=${quote(short)} address=${source} group=${quote(short)} password=${quote(password)};
|
|
/ip/service/set [find where name=www-ssl and dynamic=no] address=${source} certificate=${quote(leaf)} disabled=no`, "restricted HTTPS REST setup")
|
|
let lastError = ""
|
|
await until("router REST on verified HTTPS", async () => {
|
|
const response = await fetch(`https://${host}/rest/system/resource`, {
|
|
headers: { authorization: "Basic " + Buffer.from(short + ":" + password).toString("base64") }, signal: AbortSignal.timeout(5000),
|
|
}).catch(error => { lastError = String(error.cause ?? error); return undefined })
|
|
if (!response) return false
|
|
assert.equal(response.status, 200, "REST test user was refused")
|
|
assert.equal((await response.json()).version, "7.24.5 (stable)")
|
|
return true
|
|
}, 18000).catch(error => { throw Error(`CHR ${side + 1}: ${error.message} · ${lastError}`) })
|
|
}
|
|
|
|
function clean(side: number, before: string) {
|
|
const own = `where comment~${quote(appliedNamespace ? `^(${ns}|${appliedNamespace}):` : "^" + ns + ":")}`
|
|
const checks = ixPaths.map(path => `[:len [${path}/find ${own}]]`)
|
|
cli(side, `/ip/service/set [find where name=www-ssl and dynamic=no] disabled=yes address="" certificate=none;
|
|
/user/remove [/user/find where name=${quote(short)}]; /user/group/remove [/user/group/find where name=${quote(short)}];
|
|
/file/remove [/file/find where name=${quote(short + "-ca.crt")}];
|
|
/certificate/remove [/certificate/find where name=${quote(short + "-tls")}];
|
|
/certificate/remove [/certificate/find where name=${quote(short + "-ca")}];
|
|
${ixPaths.map(path => `${path}/remove [${path}/find ${own}]`).join("; ")};
|
|
/interface/gre/remove [/interface/gre/find where name=${quote(gre)} and comment=${quote("IX:" + segment)}];
|
|
${ipsecPaths.map((path, i) => `${path}/remove [${path}/find where ${i < 2 ? "comment" : "name"}=${quote(short)}]`).join("; ")}`)
|
|
checks.push(...ipsecPaths.map((path, i) => `[:len [${path}/find where ${i < 2 ? "comment" : "name"}=${quote(short)}]]`),
|
|
`[:len [/user/find where name=${quote(short)}]]`, `[:len [/user/group/find where name=${quote(short)}]]`,
|
|
`[:len [/certificate/find where name~${quote("^" + short + "-(ca|tls)$")}]]`, `[:len [/file/find where name=${quote(short + "-ca.crt")}]]`)
|
|
assert.equal(cli(side, ":put (" + checks.join("+") + ")"), "0")
|
|
assert.equal(baseline(side), before)
|
|
}
|
|
|
|
async function useManager() {
|
|
const root = await mkdtemp(join(tmpdir(), "mmapp-ix-mcp-"))
|
|
process.chdir(root)
|
|
const pgPort = await port(), httpPort = await port()
|
|
const origin = `http://127.0.0.1:${httpPort}`, endpoint = new URL("/mcp", origin)
|
|
const pgPassword = randomBytes(24).toString("hex"), jwtSecret = randomBytes(32).toString("hex")
|
|
Object.assign(process.env, { DATABASE_URL: `postgresql://ixlab:${pgPassword}@127.0.0.1:${pgPort}/postgres`,
|
|
NODE_ENV: "test", AUTH_REQUIRED: "true", AUTH_JWT_SECRET: jwtSecret, AUTH_ISSUER: origin,
|
|
AUTH_PORTAL_URL: origin, MCP_STATE_DIR: join(root, "state"), MCP_PUBLIC_URL: endpoint.href, MCP_UI_URL: origin, CORS_ORIGIN: origin })
|
|
const pg = new EmbeddedPostgres({ databaseDir: join(root, "db"), user: "ixlab", password: pgPassword, port: pgPort,
|
|
persistent: false, createPostgresUser: false, initdbFlags: ["--encoding=UTF8", "--no-locale"], postgresFlags: ["-h", "127.0.0.1"],
|
|
onLog: () => {}, onError: () => {} })
|
|
await pg.initialise()
|
|
await pg.start()
|
|
const { pool, closePool } = await import("../../src/db/index.js")
|
|
const { applySqlMigrations } = await import("../../src/db/migrate.js")
|
|
const { buildApp } = await import("../../src/index.js")
|
|
const { updateMcpSettings } = await import("../../src/modules/mcp/store.js")
|
|
let app: Awaited<ReturnType<typeof buildApp>> | undefined
|
|
const client = new Client({ name: "owned-ix-gre", version: "1.0.0" })
|
|
try {
|
|
await applySqlMigrations(pool)
|
|
const serverIds: number[] = []
|
|
for (const [side, host] of hosts.entries()) {
|
|
const { rows } = await pool.query(`INSERT INTO servers(name,host,port,username,password,use_ssl,verify_ssl,enabled,type)
|
|
VALUES($1,$2,443,$3,$4,true,true,true,'ix-node') RETURNING id`, [`ix-chr-${side + 1}`, host, short, password])
|
|
serverIds.push(Number(rows[0].id))
|
|
}
|
|
const permissions = ["mm:network:read", "mm:network:write", "mm:mcp:admin", "mm:mcp:approve"]
|
|
const actor = { id: "ix-fixture", email: "[email protected]", name: "IX fixture", apps: ["mm"], permissions,
|
|
expiresAt: Date.now() + 1800000, issuedAt: Date.now() }
|
|
await updateMcpSettings({ enabled: true }, actor)
|
|
app = await buildApp({ startScheduler: false, logger: false })
|
|
await app.listen({ port: httpPort, host: "127.0.0.1" })
|
|
const jwt = await new SignJWT({ sub: actor.id, apps: actor.apps, permissions }).setProtectedHeader({ alg: "HS256" })
|
|
.setIssuer(origin).setIssuedAt().setExpirationTime("15m").sign(new TextEncoder().encode(jwtSecret))
|
|
async function rest(path: string, data?: object) {
|
|
const response = await fetch(origin + "/api" + path, { method: data ? "POST" : "GET",
|
|
headers: { authorization: "Bearer " + jwt, "content-type": "application/json" },
|
|
...(data ? { body: JSON.stringify(data) } : {}), signal: AbortSignal.timeout(15000) })
|
|
const body = await response.json()
|
|
assert(response.ok, `${path}: ${response.status} ${JSON.stringify(body).slice(0, 600)}`)
|
|
return body
|
|
}
|
|
const configuration = { name: segment, sites: serverIds.map((serverId, side) => ({
|
|
serverId, routerId: pin(side), autonomousSystem: 64512 + side,
|
|
interfaces: [{ name: gre, kind: "gre-ipsec", localEndpoint: hosts[side], endpoint: hosts[1 - side], peerServerId: serverIds[1 - side] }],
|
|
})) }
|
|
const draft = await rest("/ix/segments", { revision: 0, configuration })
|
|
const segmentId: string = draft.segment.id
|
|
assert.match(segmentId, /^[0-9a-f-]{36}$/)
|
|
appliedNamespace = ixNamespace(segmentId)
|
|
assert.equal(draft.segment.revision, 1)
|
|
assert.equal(draft.segment.appliedRevision, null)
|
|
result.managerRestDraft = true
|
|
const { token } = await rest("/mcp/connections", { name: "Owned IX approval", mode: "approval", permissions: ["mm:network:read", "mm:network:write"],
|
|
limits: { mutationsPerHour: 40, callsPerMinute: 120 },
|
|
expiresAt: new Date(Date.now() + 600000).toISOString(), scope: { serverIds, allowGlobal: false,
|
|
operationIds: ["network.ix.configure", "network.ix.read", "changes.apply", "operations.read"] } })
|
|
await client.connect(new StreamableHTTPClientTransport(endpoint, {
|
|
requestInit: { headers: { authorization: "Bearer " + token } },
|
|
}), { timeout: 10000 })
|
|
async function call(name: string, args: object, expectedError = false) {
|
|
const reply = await client.callTool({ name, arguments: args }, undefined, { timeout: 120000 })
|
|
assert.equal(Boolean(reply.isError), expectedError, name + " " + JSON.stringify(reply.structuredContent ?? reply.content).slice(0, 1200))
|
|
return (reply.structuredContent as { result: any })?.result
|
|
}
|
|
const plan = await call("mm_ix_change_plan", { change: { id: segmentId, revision: 1, configuration } })
|
|
assert.equal(plan.state, "awaiting-approval")
|
|
const apply = { planId: plan.planId, idempotencyKey: randomUUID() }
|
|
await call("mm_change_apply", apply, true)
|
|
await rest("/mcp/plans/" + plan.planId + "/decision", { approve: true })
|
|
const op = await call("mm_change_apply", apply)
|
|
const terminal = await until("MCP terminal operation", async () => {
|
|
const value = await call("mm_operation_get", { operationId: op.id })
|
|
return !["pending", "running"].includes(value.state) && value
|
|
}, 90000)
|
|
assert.equal(terminal.state, "applied", JSON.stringify({ state: terminal.state, error: terminal.error_code }))
|
|
assert.equal(terminal.verification, "passed")
|
|
assert.equal((await call("mm_change_apply", apply)).id, op.id)
|
|
const verified = await call("mm_ix_segment_get", { id: segmentId })
|
|
assert.equal(verified.segment.appliedRevision, 2)
|
|
const status = await rest("/ix/segments/" + segmentId + "/status")
|
|
assert.deepEqual(status.sites.map(({ serverId, available }: { serverId: number; available: boolean }) => [serverId, available]),
|
|
serverIds.map(serverId => [serverId, true]))
|
|
result.mcpAppliedAndVerified = true
|
|
result.routerRestSites = status.sites.length
|
|
} finally {
|
|
await client.close()
|
|
await app?.close()
|
|
await closePool()
|
|
await pg.stop()
|
|
}
|
|
}
|
|
|
|
function packets(side: number) {
|
|
assert(appliedNamespace)
|
|
return Number(cli(side, `:put [/ping address=${pin(1 - side)} src-address=${pin(side)} vrf=${appliedNamespace} count=3 interval=250ms]`).split(/\r?\n/).at(-1))
|
|
}
|
|
|
|
let failure: unknown
|
|
try {
|
|
const original = sides.map(baseline)
|
|
for (const value of original) {
|
|
const [version, board, ...expected] = value.split(/\r?\n/)
|
|
assert.equal(version, "7.24.5 (stable)")
|
|
assert.match(board, /^CHR/)
|
|
const [https, ...inventory] = expected
|
|
assert.match(https, /(?:^|;)certificate=none;disabled=true;port=443$/)
|
|
assert.deepEqual(inventory, ["0", "1", "0", "0", "0", "0", "1"])
|
|
}
|
|
for (const side of sides) {
|
|
entered.set(side, original[side])
|
|
prepareGre(side)
|
|
}
|
|
for (const side of sides) await openRest(side)
|
|
console.log("Both RouterOS REST endpoints authenticated with temporary trusted HTTPS certificates")
|
|
await useManager()
|
|
console.log("MCP applied the reviewed configuration to both routers")
|
|
await until("encrypted GRE forwarding", () => packets(0) === 3 && packets(1) === 3)
|
|
const sas = sides.map(side => Number(cli(side, ":put [:len [/ip/ipsec/installed-sa/find where state=mature]]")))
|
|
assert(sas.every(count => count === 2))
|
|
result.greReplies = [3, 3]
|
|
result.matureIpsecSAs = sas
|
|
// Turn off both matching policies during the plaintext negative test.
|
|
for (const side of sides) cli(side, `/ip/ipsec/policy/disable [/ip/ipsec/policy/find where comment=${quote(short)}]`)
|
|
for (const side of sides) assert.equal(packets(side), 0)
|
|
result.plaintextGreBlocked = true
|
|
for (const side of sides) cli(side, `/ip/ipsec/policy/enable [/ip/ipsec/policy/find where comment=${quote(short)}]`)
|
|
await until("GRE recovery with required IPsec", () => packets(0) === 3 && packets(1) === 3)
|
|
result.greRecovered = true
|
|
} catch (error) {
|
|
failure = error
|
|
}
|
|
setDefaultCACertificates(roots)
|
|
let testStandRestored = true
|
|
for (const [side, original] of entered) {
|
|
try { clean(side, original) } catch (error) {
|
|
console.error(`Cleanup unconfirmed on CHR ${side + 1} · ${ns} ${appliedNamespace ?? ""}`)
|
|
testStandRestored = false
|
|
failure ??= error
|
|
}
|
|
}
|
|
console.log(JSON.stringify({ ...result, testStandRestored }))
|
|
if (failure) throw failure
|