/** * A server's hostname set by hand: what a hostname is, that the agent's reports no longer replace one that was set by hand (and are still remembered), that giving it up goes back to what the * agent reports, who may, what is refused and what is written in the audit log. * * 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-hostname-")); process.env.DATABASE_PATH = join(dir, "test.sqlite"); process.env.SESSION_DIR = join(dir, "sessions"); process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32); const express = (await import("express")).default; const { db } = await import("../src/db/client.js"); const { users, servers, auditLog } = await import("../src/db/schema.js"); const { runMigrations } = await import("../src/db/migrate.js"); const { normaliseHostname } = await import("../src/utils/hostnames.js"); const { serversRouter } = await import("../src/routes/servers.js"); const { agentReportRouter } = await import("../src/routes/agentReport.js"); const { hashToken } = await import("../src/services/tokens.js"); const { eq } = await import("drizzle-orm"); await runMigrations(); describe("what a hostname is", () => { test("a host name in labels, or an address, in lower case without the dot at the end", () => { assert.equal(normaliseHostname("NAS.Home.LAN."), "nas.home.lan"); assert.equal(normaliseHostname(" pve1 "), "pve1"); assert.equal(normaliseHostname("web_01.lab"), "web_01.lab"); assert.equal(normaliseHostname("xn--bcher-kva.example"), "xn--bcher-kva.example"); assert.equal(normaliseHostname("192.168.1.20"), "192.168.1.20"); assert.equal(normaliseHostname("FD00::20"), "fd00::20"); }); test("anything else is not: empty, spaces, a leading or doubled dot, a dash at the end of a label, other letters, a path, a port, a label or a name that is too long", () => { for (const bad of ["", " ", "a b", ".lan", "a..lan", "-a.lan", "a-.lan", "bücher.lan", "a/b", "../x", "host:22", "http://host", "a;b", `${"a".repeat(64)}.lan`, `${"a.".repeat(130)}lan`]) { assert.equal(normaliseHostname(bad), null, JSON.stringify(bad)); } }); }); describe("the hostname of a server", () => { let app: Server; let base = ""; let id = 0; let neverReported = 0; let sub = "admin"; before(async () => { await db.insert(users).values([ { oidcSub: "admin", name: "Ada", role: "admin" }, { oidcSub: "operator", name: "Olle", role: "operator" }, { oidcSub: "viewer", name: "Vic", role: "viewer" }, ]); id = (await db.insert(servers).values({ name: "elsa", hostname: "elsa-old", apiTokenHash: hashToken("tok"), apiTokenPrefix: "t" }).returning({ id: servers.id }))[0].id; neverReported = (await db.insert(servers).values({ name: "quiet", hostname: "quiet.lan", apiTokenHash: hashToken("tok2"), apiTokenPrefix: "q" }).returning({ id: servers.id }))[0].id; const a = express(); a.use("/api/agent/report", agentReportRouter); a.use(express.json()); a.use((req, _res, next) => { (req as unknown as { session: unknown }).session = { user: { sub } }; next(); }); a.use("/api/servers", serversRouter); app = await new Promise((resolve) => { const x = a.listen(0, "127.0.0.1", () => resolve(x)); }); base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api`; }); after(() => { app.close(); try { rmSync(dir, { recursive: true, force: true }); } catch { // Windows keeps the database file locked until the process exits. } }); const report = (hostname: string | undefined) => fetch(`${base}/agent/report`, { method: "POST", headers: { "content-type": "application/json", authorization: "Bearer tok" }, body: JSON.stringify({ ...(hostname ? { hostname } : {}), os_type: "linux", tasks: [] }) }); const put = (serverId: number | string, hostname: unknown) => fetch(`${base}/servers/${serverId}/hostname`, { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify({ hostname }) }); const give = (serverId: number | string) => fetch(`${base}/servers/${serverId}/hostname`, { method: "DELETE" }); const row = async (serverId = id) => (await db.select().from(servers).where(eq(servers.id, serverId)))[0]; const audit = async (action: string) => (await db.select().from(auditLog)).filter((e) => e.action === action); test("an agent's hostname is the server's hostname, and is kept as what the agent reports", async () => { assert.equal((await report("elsa-agent")).status, 202); const s = await row(); assert.deepEqual([s.hostname, s.reportedHostname, s.hostnamePinned], ["elsa-agent", "elsa-agent", false]); assert.equal((await report("elsa-agent-2")).status, 202); assert.deepEqual([(await row()).hostname, (await row()).reportedHostname], ["elsa-agent-2", "elsa-agent-2"]); }); test("only an administrator sets a hostname or gives it up", async () => { for (const who of ["viewer", "operator"]) { sub = who; assert.equal((await put(id, "x.lan")).status, 403, who); assert.equal((await give(id)).status, 403, who); } sub = "admin"; assert.equal((await row()).hostname, "elsa-agent-2"); }); test("a hostname set by hand is kept in the form names are compared, pinned, and written in the audit log with what it was", async () => { const res = await put(id, " NAS.Home.LAN. "); assert.equal(res.status, 200); const body = (await res.json()) as { server: { hostname: string; hostnamePinned: boolean; reportedHostname: string | null } }; assert.deepEqual([body.server.hostname, body.server.hostnamePinned, body.server.reportedHostname], ["nas.home.lan", true, "elsa-agent-2"]); const [entry] = await audit("set_hostname"); assert.deepEqual([entry.category, entry.targetType, entry.targetId], ["server", "server", String(id)]); assert.deepEqual(JSON.parse(entry.detail ?? "{}"), { name: "elsa", from: "elsa-agent-2", to: "nas.home.lan" }); }); test("while it is pinned a report does not replace it, but what the agent says is still remembered", async () => { assert.equal((await report("elsa-renamed")).status, 202); const s = await row(); assert.deepEqual([s.hostname, s.reportedHostname, s.hostnamePinned], ["nas.home.lan", "elsa-renamed", true]); assert.equal((await report(undefined)).status, 202, "a report that says no hostname costs nothing"); assert.deepEqual([(await row()).hostname, (await row()).reportedHostname], ["nas.home.lan", "elsa-renamed"]); }); test("the detail and the list say it is set by hand and what the agent reports", async () => { const detail = (await (await fetch(`${base}/servers/${id}/detail`)).json()) as { server: { hostname: string; hostnamePinned: boolean; reportedHostname: string } }; assert.deepEqual([detail.server.hostname, detail.server.hostnamePinned, detail.server.reportedHostname], ["nas.home.lan", true, "elsa-renamed"]); const list = (await (await fetch(`${base}/servers`)).json()) as { servers: { id: number; hostnamePinned: boolean }[] }; assert.equal(list.servers.find((s) => s.id === id)!.hostnamePinned, true); }); test("setting the same thing again changes nothing and is not written down twice", async () => { const before = (await audit("set_hostname")).length; assert.equal((await put(id, "nas.home.lan")).status, 200); assert.equal((await audit("set_hostname")).length, before); }); test("giving it up goes back to what the agent reports, at once, and is written in the audit log; and the reports replace it again", async () => { const res = await give(id); assert.equal(res.status, 200); const body = (await res.json()) as { server: { hostname: string; hostnamePinned: boolean } }; assert.deepEqual([body.server.hostname, body.server.hostnamePinned], ["elsa-renamed", false]); const [entry] = await audit("reset_hostname"); assert.deepEqual(JSON.parse(entry.detail ?? "{}"), { name: "elsa", from: "nas.home.lan", to: "elsa-renamed" }); assert.equal((await report("elsa-third")).status, 202); assert.equal((await row()).hostname, "elsa-third"); }); test("giving up what was not set by hand changes nothing and writes nothing", async () => { const before = (await audit("reset_hostname")).length; assert.equal((await give(id)).status, 200); assert.equal((await audit("reset_hostname")).length, before); assert.equal((await row()).hostname, "elsa-third"); }); test("a server that never reported keeps its hostname when the one set by hand is given up", async () => { assert.equal((await put(neverReported, "quiet-new.lan")).status, 200); const res = await give(neverReported); assert.equal(((await res.json()) as { server: { hostname: string; hostnamePinned: boolean } }).server.hostname, "quiet-new.lan"); assert.equal((await row(neverReported)).hostnamePinned, false); }); test("what is not a hostname, a body that is not one, a server that is not there and an id that is no id are refused", async () => { const before = (await row()).hostname; for (const bad of ["", "a b", "-x", "http://nas", "host:22", "x".repeat(300), 5, null, undefined]) { const res = await put(id, bad); assert.equal(res.status, 400, JSON.stringify(bad)); assert.equal(typeof ((await res.json()) as { message?: string }).message, "string"); } assert.equal((await row()).hostname, before); assert.equal((await put(999999, "x.lan")).status, 404); assert.equal((await give(999999)).status, 404); assert.equal((await put("abc", "x.lan")).status, 400); assert.equal((await give("abc")).status, 400); }); });