Files
MikrotikManager/backend/src/services/network-disabled-server.test.ts
T

97 lines
6.6 KiB
TypeScript

import assert from "node:assert/strict"
import { getEnabledServerById } from "./wireguard-live.js"
import { getServerRowByIdString } from "./certificates-service.js"
import { MikrotikClient } from "./mikrotik.js"
import { pool, closePool } from "../db/index.js"
import { initDatabase } from "../db/bootstrap.js"
import { buildApp } from "../index.js"
try {
const own = process.env.MMAPP_OWN_SQL_DB ?? process.env.MMAPP_OWN_TEST_DB
if (process.env.MMAPP_OWN_SQL_DB && process.env.MMAPP_OWN_TEST_DB) assert.equal(process.env.MMAPP_OWN_SQL_DB, process.env.MMAPP_OWN_TEST_DB)
if (own) {
assert(/^mm_accept_(152|156|166)_\d+$/.test(own))
assert.equal(process.env.NODE_ENV, "test")
const endpoint = new URL(process.env.DATABASE_URL ?? "")
assert(["postgres:", "postgresql:"].includes(endpoint.protocol))
assert.equal(endpoint.hostname, "127.0.0.1"); assert.equal(endpoint.username, "mcp_test"); assert(endpoint.password)
assert.equal(endpoint.pathname, "/" + own); assert.equal(endpoint.search, ""); assert.equal(endpoint.hash, "")
}
const originalQuery = pool.query, originalConnect = pool.connect
let invalidSql = 0
pool.query = (() => { invalidSql++; throw Error("Invalid server ID attempted SQL") }) as typeof pool.query
pool.connect = (() => { invalidSql++; throw Error("Invalid server ID attempted checkout") }) as typeof pool.connect
try {
for (const id of ["srv1", "1abc", "", "0", "-1", "1.5", "9007199254740993", "9007199254740992"]) { assert.equal(await getEnabledServerById(id), null); assert.equal(await getServerRowByIdString(id), null) }
assert.equal(invalidSql, 0)
} finally { pool.query = originalQuery; pool.connect = originalConnect }
if (own) {
assert.equal((await pool.query("SELECT current_database() AS name")).rows[0].name, own)
await initDatabase()
const ownedIds: number[] = []
let app: Awaited<ReturnType<typeof buildApp>> | undefined
const original = MikrotikClient.fromServer
let contacts = 0, checks = 0
try {
const id = Number((await pool.query("INSERT INTO servers (name,host,enabled) VALUES ('disabled-network-fixture','127.0.0.1',false) RETURNING id")).rows[0].id)
ownedIds.push(id)
app = await buildApp({ logger: false, startScheduler: false })
MikrotikClient.fromServer = () => { contacts++; throw new Error("Disabled server was contacted") }
const key = Buffer.alloc(32, 7).toString("base64")
for (const type of ["home-router", "jump-host", "exit-node"]) {
await pool.query("UPDATE servers SET type=$1 WHERE id=$2", [type, id])
assert.equal(await getEnabledServerById(id), null)
assert.equal(await getServerRowByIdString(id), null)
const issue = await app.inject({ method: "POST", url: "/api/certificates/issue", payload: { serverId: String(id), certName: "own-disabled", domainNames: ["disabled.example.test"] } })
assert.equal(issue.statusCode, 404); checks++
const catalog = await app.inject({ method: "GET", url: "/api/certificates/state" }); assert.equal(catalog.statusCode, 200); assert.deepEqual(catalog.json().servers, []); checks++
for (const path of ["/wireguard", "/gre/tunnels"]) {
const r = await app.inject({ method: "GET", url: `/api${path}?serverId=${id}` })
assert.equal(r.statusCode, 200)
assert.deepEqual(r.json().failures, [])
assert.deepEqual(path === "/wireguard" ? r.json().interfaces : r.json().tunnels, [])
checks++
}
const cases = [
{ method: "POST", path: "/wireguard/interfaces", payload: { serverId: id, name: "own", address: "fd00::1/64" } },
{ method: "PATCH", path: `/wireguard/interfaces/${id}/*none`, payload: { address: "fd00::1/64" } },
{ method: "DELETE", path: `/wireguard/interfaces/${id}/*none`, payload: undefined },
{ method: "POST", path: "/wireguard/peers", payload: { serverId: id, interfaceName: "own", publicKey: key, allowedAddresses: ["fd00::2/128"] } },
{ method: "POST", path: "/wireguard/export", payload: { serverId: id, interfaceName: "own", format: "rsc", includePrivateKey: false }, expectedStatus: 409, expectedCode: "DEVICE_UNAVAILABLE" },
{ method: "POST", path: "/wireguard/import", payload: { serverId: id, format: "conf", dryRun: false, content: `[Interface]\nPrivateKey = ${key}\nAddress = fd00::1/64\n` } },
{ method: "POST", path: "/gre/tunnels", payload: { serverId: String(id), name: "own", remoteAddress: "192.0.2.1", localInnerIp: "fd00::1/64" } },
{ method: "PATCH", path: "/gre/tunnels", payload: { serverId: String(id), name: "own", localInnerIp: "fd00::1/64" } },
{ method: "DELETE", path: "/gre/tunnels", payload: { serverId: String(id), name: "own" } },
] as const
for (const item of cases) {
const r = await app.inject({ method: item.method, url: "/api" + item.path, payload: item.payload })
assert.equal(r.statusCode, "expectedStatus" in item ? item.expectedStatus : 404, type + " " + item.path + " " + r.body)
if ("expectedCode" in item) assert.equal(r.json().code, item.expectedCode)
checks++
}
}
assert.equal(checks, 39)
assert.equal(contacts, 0)
await pool.query("UPDATE servers SET enabled=true WHERE id=$1", [id])
assert.equal((await getEnabledServerById(id))?.id, id)
assert.equal((await getServerRowByIdString(id))?.id, id)
for (const largeId of [2147483648, Number.MAX_SAFE_INTEGER]) {
await pool.query("INSERT INTO servers (id,name,host,enabled) VALUES ($1,'large-id-fixture','127.0.0.1',true)", [largeId])
ownedIds.push(largeId)
assert.equal((await getEnabledServerById(String(largeId)))?.id, largeId)
assert.equal((await getServerRowByIdString(String(largeId)))?.id, largeId)
}
assert.equal(contacts, 0)
console.log("network-disabled-server.test.ts: 39 API/SQL checks for three types including certificates, zero RouterOS contacts, enabled positive control passed")
console.log("network-disabled-server.test.ts: real bigint IDs above int32 and MAX_SAFE_INTEGER passed without rounding")
} finally {
MikrotikClient.fromServer = original
try { await app?.close() }
finally { if (ownedIds.length) await pool.query("DELETE FROM servers WHERE id=ANY($1::bigint[])", [ownedIds]) }
}
} else {
assert.notEqual(process.env.REQUIRE_TEST_POSTGRES, "1", "Owned SQL/disabled API checks are mandatory in PostgreSQL regression")
console.log("network-disabled-server.test.ts: invalid IDs passed; optional SQL checks need an explicit owned database")
}
} finally { await closePool() }