/** * Filling in the inventory from what an agent says the machine is: only blanks are filled, a refresh overwrites on purpose, and an agent's * report fills the entries of the machine it came from. * * 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-invfill-")); 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, assets, auditLog } = await import("../src/db/schema.js"); const { runMigrations } = await import("../src/db/migrate.js"); const { inventoryRouter } = await import("../src/routes/inventory.js"); const { agentReportRouter } = await import("../src/routes/agentReport.js"); const { hashToken } = await import("../src/services/tokens.js"); const { blanksToFill, differences, hardwareOf } = await import("../src/services/inventoryAutofill.js"); const { eq } = await import("drizzle-orm"); await runMigrations(); describe("what would be filled, and what would change", () => { const hw = { manufacturer: "Dell Inc.", model: "PowerEdge R730", serial: "ABC123" }; test("only blank fields are filled; what a person wrote stays", () => { assert.deepEqual(blanksToFill({ manufacturer: null, model: "R730 (mine)", serial: " " }, hw), { manufacturer: "Dell Inc.", serial: "ABC123" }); assert.deepEqual(blanksToFill({ manufacturer: "x", model: "y", serial: "z" }, hw), {}); assert.deepEqual(blanksToFill({ manufacturer: null, model: null, serial: null }, null), {}); assert.deepEqual(blanksToFill({ manufacturer: null, model: null, serial: null }, { manufacturer: "Dell", model: null, serial: null }), { manufacturer: "Dell" }); }); test("a refresh would change the fields where the agent says something else, and nothing that already matches", () => { assert.deepEqual(differences({ manufacturer: "Dell Inc.", model: "R730", serial: null }, hw), { model: "PowerEdge R730", serial: "ABC123" }); assert.deepEqual(differences(hw, hw), {}); assert.deepEqual(differences({ manufacturer: "Dell Inc. ", model: "PowerEdge R730", serial: "ABC123" }, hw), {}, "stray spaces aren't a difference"); assert.deepEqual(differences({ manufacturer: "x", model: "y", serial: "z" }, { manufacturer: null, model: null, serial: null }), {}, "an agent that says nothing changes nothing"); }); test("a server that has said nothing has no hardware", () => { assert.equal(hardwareOf(null), null); assert.equal(hardwareOf({ hwManufacturer: null, hwModel: null, hwSerial: null }), null); assert.deepEqual(hardwareOf({ hwManufacturer: "A", hwModel: null, hwSerial: null }), { manufacturer: "A", model: null, serial: null }); }); }); describe("through the routes and the agent's report", () => { let app: Server; let base = ""; let id = 0; before(async () => { await db.insert(users).values([{ oidcSub: "operator", name: "Olle", role: "operator" }]); const [s] = await db.insert(servers).values({ name: "elsa", apiTokenHash: hashToken("tok"), apiTokenPrefix: "t" }).returning(); id = s.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: "operator" } }; next(); }); a.use("/api/inventory", inventoryRouter); 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 = (hardware: unknown) => fetch(`${base}/agent/report`, { method: "POST", headers: { "content-type": "application/json", authorization: "Bearer tok" }, body: JSON.stringify({ hostname: "h", os_type: "linux", tasks: [], system: { hardware } }) }); const send = (method: string, path: string, body?: unknown) => fetch(`${base}/inventory${path}`, { method, headers: { "content-type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) }); const entry = async (assetId: number) => (await db.select().from(assets).where(eq(assets.id, assetId)))[0]; let linked = 0; let unlinked = 0; test("an entry made before the agent has said anything stays blank, then an agent's report fills it", async () => { linked = (await (await send("POST", "/", { name: "elsa's box", kind: "server", serverId: id, model: "my own words" })).json()).asset.id; unlinked = (await (await send("POST", "/", { name: "a switch", kind: "network" })).json()).asset.id; assert.deepEqual([(await entry(linked)).manufacturer, (await entry(linked)).serial], [null, null]); assert.equal((await report({ manufacturer: "Dell Inc.", model: "PowerEdge R730", serial: "ABC123" })).status, 202); const row = await entry(linked); assert.deepEqual([row.manufacturer, row.model, row.serial], ["Dell Inc.", "my own words", "ABC123"], "blanks filled, the model a person wrote is kept"); const [s] = await db.select().from(servers).where(eq(servers.id, id)); assert.deepEqual([s.hwManufacturer, s.hwModel, s.hwSerial], ["Dell Inc.", "PowerEdge R730", "ABC123"]); assert.equal((await entry(unlinked)).manufacturer, null, "an entry that isn't this machine is left alone"); }); test("the list shows what the agent says and what a refresh would change", async () => { const list = (await (await send("GET", "/")).json()).assets; const a = list.find((x: { id: number }) => x.id === linked); assert.deepEqual(a.agent, { manufacturer: "Dell Inc.", model: "PowerEdge R730", serial: "ABC123", differs: { model: "PowerEdge R730" } }); assert.equal(list.find((x: { id: number }) => x.id === unlinked).agent, null); }); test("a new entry linked to a machine that has already reported starts out filled in", async () => { const made = (await (await send("POST", "/", { name: "elsa again", kind: "server", serverId: id })).json()).asset; assert.deepEqual([made.manufacturer, made.model, made.serial], ["Dell Inc.", "PowerEdge R730", "ABC123"]); const edited = (await (await send("PUT", `/${unlinked}`, { name: "a switch", kind: "network", serverId: id })).json()).asset; assert.equal(edited.serial, "ABC123", "linking an existing entry fills its blanks too"); }); test("a report with nothing in it, or garbage, changes nothing", async () => { assert.equal((await report({ manufacturer: " " })).status, 202); assert.equal((await report("nonsense")).status, 202); const [s] = await db.select().from(servers).where(eq(servers.id, id)); assert.equal(s.hwSerial, "ABC123"); }); test("refreshing from the agent overwrites on purpose, says what changed, and is in the audit log", async () => { const res = await send("POST", `/${linked}/refresh-from-agent`); assert.equal(res.status, 200); const body = await res.json(); assert.deepEqual(body.changed, ["model"]); assert.equal(body.asset.model, "PowerEdge R730"); const again = await (await send("POST", `/${linked}/refresh-from-agent`)).json(); assert.deepEqual(again.changed, [], "nothing left to change"); const log = (await db.select().from(auditLog)).filter((e) => e.action === "refresh_from_agent"); assert.equal(log.length, 1, "only a refresh that changed something is recorded"); }); test("an entry without a server, or one that isn't there, can't be refreshed", async () => { const lone = (await (await send("POST", "/", { name: "a shelf", kind: "other" })).json()).asset.id; assert.equal((await send("POST", `/${lone}/refresh-from-agent`)).status, 400); assert.equal((await send("POST", "/99999/refresh-from-agent")).status, 404); }); });