/** * "The internet" as something a server, a service or a network device can need: it is a node of the dependency graph that is always there, can only be needed, and is never * judged down — so it can be drawn and asked "what depends on it?", and it folds no alert. * * Run with: npm test --workspace server */ import { test, describe, before, after } from "node:test"; import assert from "node:assert/strict"; import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import type { AddressInfo } from "node:net"; import type { Server } from "node:http"; const dir = mkdtempSync(join(tmpdir(), "hm-deps-net-")); process.env.DATABASE_PATH = join(dir, "test.sqlite"); process.env.SESSION_DIR = join(dir, "sessions"); process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32); process.env.HEALTH_STARTUP_GRACE_MS = "0"; const express = (await import("express")).default; const { db } = await import("../src/db/client.js"); const { users, servers, integrations, networkDevices } = await import("../src/db/schema.js"); const { runMigrations } = await import("../src/db/migrate.js"); const { dependenciesRouter } = await import("../src/routes/dependencies.js"); const { nodeExists, INTERNET_ID } = await import("../src/services/dependencies.js"); await runMigrations(); describe("the internet as a dependency", () => { let app: Server; let base = ""; let who = "operator"; let box = 0; let hetzner = 0; let gateway = 0; before(async () => { await db.insert(users).values([ { oidcSub: "operator", name: "Olga", role: "operator" }, { oidcSub: "viewer", name: "Vic", role: "viewer" }, ]); box = (await db.insert(servers).values({ name: "vps", apiTokenHash: "v", apiTokenPrefix: "v", lastSeenAt: new Date().toISOString() }).returning({ id: servers.id }))[0].id; const ints = await db.insert(integrations).values([{ type: "hetzner", name: "Hetzner", baseUrl: "https://api.hetzner.cloud", config: "{}" }, { type: "unifi", name: "UniFi", baseUrl: "https://unifi.lab", config: "{}" }]).returning({ id: integrations.id }); hetzner = ints[0].id; gateway = (await db.insert(networkDevices).values({ integrationId: ints[1].id, externalId: "aa:bb:cc:dd:ee:ff", name: "Gateway", kind: "gateway", state: "online", firstSeenAt: new Date().toISOString(), updatedAt: new Date().toISOString() }).returning({ id: networkDevices.id }))[0].id; const a = express(); a.use(express.json()); a.use((req, _res, next) => { (req as unknown as { session: unknown }).session = { user: { sub: who } }; next(); }); a.use("/api/dependencies", dependenciesRouter); app = await new Promise((resolve) => { const s = a.listen(0, "127.0.0.1", () => resolve(s)); }); base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api/dependencies`; }); after(() => { app.close(); try { rmSync(dir, { recursive: true, force: true }); } catch { // Windows keeps the database file locked until the process exits. } }); const send = (method: string, path: string, body?: unknown) => fetch(`${base}${path}`, { method, headers: { "content-type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) }); const need = (fromType: string, fromId: number) => ({ fromType, fromId, toType: "internet", toId: INTERNET_ID }); test("the internet is always there to be picked, whatever else exists", async () => { const list = await (await send("GET", "/")).json(); assert.ok(list.nodes.some((n: { key: string; name: string; type: string }) => n.key === "internet:1" && n.name === "Internet" && n.type === "internet")); assert.equal(await nodeExists("internet", 1), true); assert.equal(await nodeExists("internet", 2), false); }); test("a server, a service and a network device can each need it", async () => { assert.equal((await send("POST", "/", need("server", box))).status, 201); assert.equal((await send("POST", "/", need("integration", hetzner))).status, 201); assert.equal((await send("POST", "/", need("device", gateway))).status, 201); const list = await (await send("GET", "/")).json(); assert.deepEqual(list.dependencies.map((d: { from: { name: string }; to: { name: string } }) => `${d.from.name} > ${d.to.name}`).sort(), ["Gateway > Internet", "Hetzner > Internet", "vps > Internet"]); }); test("it can't be made to need anything, there is only the one, and it isn't added twice", async () => { const reverse = await send("POST", "/", { fromType: "internet", fromId: 1, toType: "server", toId: box }); assert.equal(reverse.status, 400); assert.match((await reverse.json()).message, /can't be made to need/); assert.equal((await send("POST", "/", { fromType: "server", fromId: box, toType: "internet", toId: 2 })).status, 400, "there is no second internet"); assert.equal((await send("POST", "/", need("server", box))).status, 409, "twice"); who = "viewer"; assert.equal((await send("POST", "/", need("integration", hetzner))).status, 403); who = "operator"; }); test("asking what depends on it lists all three; it relies on nothing", async () => { const impact = await (await send("GET", "/impact?type=internet&id=1")).json(); assert.equal(impact.target.name, "Internet"); assert.deepEqual(impact.dependents.map((d: { name: string }) => d.name).sort(), ["Gateway", "Hetzner", "vps"]); assert.deepEqual(impact.needs, []); const server = await (await send("GET", `/impact?type=server&id=${box}`)).json(); assert.deepEqual(server.needs.map((n: { name: string; type: string }) => [n.name, n.type]), [["Internet", "internet"]]); }); test("on the map it is a box that is not watched; it is never down", async () => { const graph = await (await send("GET", "/graph")).json(); const node = graph.nodes.find((n: { key: string }) => n.key === "internet:1"); assert.equal(node.name, "Internet"); assert.equal(node.status, "unknown"); assert.equal(node.type, "internet"); assert.equal(graph.edges.filter((e: { from: string }) => e.from === "internet:1").length, 3, "from what is needed to what needs it"); }); test("removing one works, and the internet stays", async () => { const list = await (await send("GET", "/")).json(); const one = list.dependencies.find((d: { from: { name: string } }) => d.from.name === "Hetzner"); assert.equal((await send("DELETE", `/${one.id}`)).status, 204); const after = await (await send("GET", "/impact?type=internet&id=1")).json(); assert.deepEqual(after.dependents.map((d: { name: string }) => d.name).sort(), ["Gateway", "vps"]); assert.equal(after.target.name, "Internet"); }); });