/** * Proxmox snapshots: listing them, taking one (with or without memory), rolling back and deleting, each a Proxmox task that is followed until it stops; what is refused before Proxmox is asked, * who may do which, and that every one is written in the audit log. Against a pretend Proxmox. * * Run with: npm test --workspace server */ import { test, describe, before, after, beforeEach } from "node:test"; import assert from "node:assert/strict"; import { createServer as createHttpServer, type Server } from "node:http"; import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import type { AddressInfo } from "node:net"; const dir = mkdtempSync(join(tmpdir(), "hm-pvesnap-")); 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.PROXMOX_TASK_WAIT_MS = "300"; const express = (await import("express")).default; const { db } = await import("../src/db/client.js"); const { users, integrations, auditLog } = await import("../src/db/schema.js"); const { runMigrations } = await import("../src/db/migrate.js"); const { createProxmoxAdapter } = await import("../src/integrations/proxmox/adapter.js"); const { integrationsRouter, autoSnapshotName } = await import("../src/routes/integrations.js"); const { ID_PATTERNS } = await import("../src/utils/pathSegment.js"); const { subjectOfConditionKey } = await import("../src/services/maintenance.js"); const { snapshotDepths } = await import("../../web/src/utils/proxmoxSnapshots.js"); await runMigrations(); const UPID = "UPID:pve1:00001A2B:0003C4D5:67890ABC:qmsnapshot:100:root@pam:"; let seen: { method: string; path: string; body: string; auth: string }[] = []; /** How the task ends: how many times it answers "running" first, and the exit status once it has stopped (null: it never stops). */ let task: { runningFirst: number; exit: string | null } = { runningFirst: 0, exit: "OK" }; let polls = 0; let listAnswer: unknown[] = []; let apiFailure: number | null = null; let badUpid = false; let pve: Server; let pveUrl = ""; before(async () => { pve = createHttpServer((req, res) => { let body = ""; req.on("data", (c) => (body += c)); req.on("end", () => { const u = new URL(req.url ?? "", "http://x"); seen.push({ method: req.method ?? "", path: u.pathname, body, auth: String(req.headers.authorization ?? "") }); const send = (status: number, json: unknown) => { res.writeHead(status, { "content-type": "application/json" }); res.end(JSON.stringify(json)); }; if (apiFailure !== null) return send(apiFailure, { errors: { snapname: "bad" }, message: "no good" }); if (/\/tasks\/[^/]+\/status$/.test(u.pathname)) { polls++; return send(200, { data: polls <= task.runningFirst || task.exit === null ? { status: "running" } : { status: "stopped", exitstatus: task.exit } }); } if (/\/snapshot$/.test(u.pathname) && req.method === "GET") return send(200, { data: listAnswer }); if (/\/snapshot(\/[^/]+(\/rollback)?)?$/.test(u.pathname)) return send(200, { data: badUpid ? { not: "a task" } : UPID }); send(404, { message: "no such thing" }); }); }); await new Promise((resolve) => pve.listen(0, "127.0.0.1", resolve)); pveUrl = `http://127.0.0.1:${(pve.address() as AddressInfo).port}`; }); beforeEach(() => { seen = []; polls = 0; task = { runningFirst: 0, exit: "OK" }; apiFailure = null; badUpid = false; listAnswer = []; }); after(() => { pve.close(); }); const adapter = () => createProxmoxAdapter({ url: pveUrl, tokenId: "root@pam!lab", tokenSecret: "s3cret", insecure: true }); describe("listing", () => { test("the snapshots of a guest, oldest first, without the line that is the guest as it is now", async () => { listAnswer = [ { name: "after-update", description: " after the update ", snaptime: 1_760_000_100, vmstate: 1, parent: "before-update" }, { name: "current", description: "You are here!", parent: "after-update" }, { name: "before-update", description: "", snaptime: 1_760_000_000, vmstate: 0 }, ]; const list = await adapter().listSnapshots("pve1", "qemu", 100); assert.deepEqual(list.map((s) => [s.name, s.description, s.withRam, s.parent]), [["before-update", "", false, null], ["after-update", "after the update", true, "before-update"]]); assert.equal(list[0].takenAt, new Date(1_760_000_000_000).toISOString()); assert.deepEqual(seen.map((s) => [s.method, s.path, s.auth]), [["GET", "/api2/json/nodes/pve1/qemu/100/snapshot", "PVEAPIToken=root@pam!lab=s3cret"]]); }); test("a guest with none, a time Proxmox did not give, and an answer that is not a list", async () => { assert.deepEqual(await adapter().listSnapshots("pve1", "lxc", 200), []); listAnswer = [{ name: "odd" }]; assert.equal((await adapter().listSnapshots("pve1", "lxc", 200))[0].takenAt, null); listAnswer = {} as never; assert.deepEqual(await adapter().listSnapshots("pve1", "qemu", 1), [], "an answer that is not a list is none"); }); }); describe("taking one", () => { test("the name goes as a form, with the description, and the memory only for a virtual machine that asked for it", async () => { await adapter().createSnapshot("pve1", "qemu", 100, { name: "before-upgrade", description: " before the upgrade ", includeRam: true }); assert.equal(seen[0].method, "POST"); assert.equal(seen[0].path, "/api2/json/nodes/pve1/qemu/100/snapshot"); assert.deepEqual(Object.fromEntries(new URLSearchParams(seen[0].body)), { snapname: "before-upgrade", description: "before the upgrade", vmstate: "1" }); seen = []; await adapter().createSnapshot("pve1", "qemu", 100, { name: "plain" }); assert.deepEqual(Object.fromEntries(new URLSearchParams(seen[0].body)), { snapname: "plain" }); seen = []; await adapter().createSnapshot("pve1", "lxc", 200, { name: "ct", includeRam: true, description: " " }); assert.deepEqual(Object.fromEntries(new URLSearchParams(seen[0].body)), { snapname: "ct" }, "a container has no memory to keep, and a blank description is none"); }); test("with no time to wait it answers with the task and says it has not finished; with time it follows it to the end", async () => { task = { runningFirst: 2, exit: "OK" }; const quick = await adapter().createSnapshot("pve1", "qemu", 100, { name: "a" }); assert.deepEqual([quick.done, quick.ok, quick.upid], [false, null, UPID]); polls = 0; const waited = await adapter().createSnapshot("pve1", "qemu", 100, { name: "b" }, 5000); assert.deepEqual([waited.done, waited.ok, waited.message], [true, true, "OK"]); assert.ok(polls >= 3, "it asked more than once"); }); test("a task that ends badly says what Proxmox said; one that never ends is left running when the wait is over", async () => { task = { runningFirst: 0, exit: "snapshot feature is not available" }; const bad = await adapter().createSnapshot("pve1", "qemu", 100, { name: "c" }, 2000); assert.deepEqual([bad.done, bad.ok, bad.message], [true, false, "snapshot feature is not available"]); task = { runningFirst: 0, exit: null }; const slow = await adapter().createSnapshot("pve1", "qemu", 100, { name: "d" }, 150); assert.deepEqual([slow.done, slow.ok], [false, null]); }); }); describe("rolling back and deleting", () => { test("a rollback is a POST to the snapshot's rollback, a deletion a DELETE of it, each followed as a task", async () => { const back = await adapter().rollbackSnapshot("pve1", "lxc", 200, "before-upgrade", 2000); const gone = await adapter().deleteSnapshot("pve1", "lxc", 200, "before-upgrade", 2000); assert.deepEqual([back.ok, gone.ok], [true, true]); const calls = seen.filter((s) => !/\/tasks\//.test(s.path)).map((s) => [s.method, s.path]); assert.deepEqual(calls, [["POST", "/api2/json/nodes/pve1/lxc/200/snapshot/before-upgrade/rollback"], ["DELETE", "/api2/json/nodes/pve1/lxc/200/snapshot/before-upgrade"]]); assert.ok(seen.some((s) => s.path.includes("/tasks/UPID%3Apve1") && s.path.endsWith("/status")), "and the task was asked after"); }); }); describe("what is refused before Proxmox is asked", () => { test("a snapshot name that Proxmox would not take, or that is a path, never goes out", async () => { for (const bad of ["1starts-with-digit", "../../x", "a b", "a/b", "", "x".repeat(41), "name?x=1", "%2e%2e", "-dash"]) { await assert.rejects(() => adapter().createSnapshot("pve1", "qemu", 100, { name: bad }), /snapshot name/, JSON.stringify(bad)); await assert.rejects(() => adapter().rollbackSnapshot("pve1", "qemu", 100, bad), /snapshot name/); await assert.rejects(() => adapter().deleteSnapshot("pve1", "qemu", 100, bad), /snapshot name/); } assert.deepEqual(seen, []); for (const ok of ["a", "Before_upgrade-2", "x".repeat(40)]) assert.match(ok, ID_PATTERNS.proxmoxSnapshot); }); test("a node, a guest type and a number are checked as for the power actions; an answer with no task is an error", async () => { await assert.rejects(() => adapter().listSnapshots("../etc", "qemu", 1), /node name/); await assert.rejects(() => adapter().listSnapshots("pve1", "vm" as never, 1), /guest type/); await assert.rejects(() => adapter().listSnapshots("pve1", "qemu", 1.5), /VM ID/); assert.deepEqual(seen, []); badUpid = true; await assert.rejects(() => adapter().createSnapshot("pve1", "qemu", 100, { name: "z" }), /did not say which task/); }); test("an error from Proxmox is the error: what it said", async () => { apiFailure = 403; await assert.rejects(() => adapter().listSnapshots("pve1", "qemu", 100), /snapname|no good/); }); }); describe("how the page indents them", () => { const snap = (name: string, parent: string | null) => ({ name, parent }); test("a chain, each taken after the one before, is all at the left edge", () => { assert.deepEqual(snapshotDepths([snap("a", null), snap("b", "a"), snap("c", "b")]), { a: 0, b: 0, c: 0 }); }); test("a branch — two taken after the same one — is indented, and what follows it with it", () => { const d = snapshotDepths([snap("a", null), snap("b", "a"), snap("c", "a"), snap("d", "c")]); assert.deepEqual(d, { a: 0, b: 1, c: 1, d: 1 }); }); test("a parent that is not in the list is the top, and a loop cannot hang it", () => { assert.deepEqual(snapshotDepths([snap("x", "gone")]), { x: 0 }); assert.deepEqual(snapshotDepths([snap("a", "b"), snap("b", "a")]), { a: 0, b: 0 }); assert.deepEqual(snapshotDepths([]), {}); }); }); describe("through the routes", () => { let app: Server; let base = ""; let who = "operator"; let id = 0; const call = (method: string, path: string, body?: unknown) => fetch(`${base}/${id}/proxmox/nodes/pve1/qemu/100/snapshots${path}`, { method, headers: { "content-type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) }); const audits = async (action: string) => (await db.select().from(auditLog)).filter((e) => e.action === action); 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(integrations).values({ type: "proxmox", name: "pve", baseUrl: pveUrl, config: JSON.stringify({ url: pveUrl, tokenId: "root@pam!lab", tokenSecret: "s3cret", insecure: true }) }).returning({ id: integrations.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/integrations", integrationsRouter); 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/integrations`; }); after(() => { app.close(); try { rmSync(dir, { recursive: true, force: true }); } catch { // Windows keeps the database file locked until the process exits. } }); test("anyone signed in can list; the list is what the adapter read", async () => { who = "viewer"; listAnswer = [{ name: "one", snaptime: 1_760_000_000 }]; const res = await call("GET", ""); assert.equal(res.status, 200); assert.deepEqual(((await res.json()) as { snapshots: { name: string }[] }).snapshots.map((s) => s.name), ["one"]); }); test("an operator takes one: it is named from the time when no name is given, checked when it is, done, and written down; a viewer may not", async () => { who = "viewer"; assert.equal((await call("POST", "", {})).status, 403); assert.deepEqual(seen, []); who = "operator"; const res = await call("POST", "", { description: "before the upgrade", includeRam: true }); assert.equal(res.status, 200); const body = (await res.json()) as { snapshot: string; done: boolean; ok: boolean }; assert.match(body.snapshot, /^hlm-\d{8}-\d{6}$/); assert.deepEqual([body.done, body.ok], [true, true]); assert.equal(new URLSearchParams(seen.find((s) => s.method === "POST" && s.path.endsWith("/snapshot"))!.body).get("snapname"), body.snapshot); const [entry] = await audits("create_snapshot"); const detail = JSON.parse(entry.detail ?? "{}"); assert.deepEqual([entry.category, entry.targetType, entry.targetId, detail.snapshot, detail.vmid, detail.node, detail.withRam, detail.ok], ["integration", "proxmox_guest", "100", body.snapshot, 100, "pve1", true, true]); assert.match(autoSnapshotName(new Date("2026-11-10T12:34:56Z")), /^hlm-20261110-123456$/); }); test("a name that is not one is refused with why, and a description that is too long; nothing is asked of Proxmox", async () => { who = "operator"; seen = []; const name = await call("POST", "", { name: "1bad" }); assert.equal(name.status, 400); assert.match(((await name.json()) as { message: string }).message, /starts with a letter/); assert.equal((await call("POST", "", { description: "x".repeat(201) })).status, 400); assert.deepEqual(seen, []); }); test("a task that is slow is said to be still going; one that fails is an error with what Proxmox said", async () => { who = "operator"; task = { runningFirst: 0, exit: null }; const slow = (await (await call("POST", "", { name: "slow" })).json()) as { done: boolean; ok: boolean | null; upid: string }; assert.deepEqual([slow.done, slow.ok, slow.upid], [false, null, UPID]); task = { runningFirst: 0, exit: "VM is locked (backup)" }; const failed = await call("POST", "", { name: "locked" }); assert.equal(failed.status, 502); assert.match(((await failed.json()) as { error: string }).error, /Proxmox: VM is locked \(backup\)/); }); test("rolling back and deleting are an administrator's, each checked, done and written down", async () => { who = "operator"; assert.equal((await call("POST", "/before-upgrade/rollback")).status, 403); assert.equal((await call("DELETE", "/before-upgrade")).status, 403); who = "admin"; seen = []; assert.equal((await call("POST", "/1bad/rollback")).status, 400); assert.equal((await call("DELETE", "/..%2Fx")).status, 400); assert.deepEqual(seen, [], "nothing was asked of Proxmox"); assert.equal((await call("POST", "/before-upgrade/rollback")).status, 200); assert.equal((await call("DELETE", "/before-upgrade")).status, 200); assert.equal((await audits("rollback_snapshot")).length, 1); assert.equal(JSON.parse((await audits("delete_snapshot"))[0].detail ?? "{}").snapshot, "before-upgrade"); }); test("a guest that is not one, and an integration of another kind, are refused", async () => { who = "admin"; seen = []; for (const path of ["/nodes/..%2Fx/qemu/100/snapshots", "/nodes/pve1/vm/100/snapshots", "/nodes/pve1/qemu/abc/snapshots", "/nodes/pve1/qemu/0/snapshots"]) { const res = await fetch(`${base}/${id}/proxmox${path}`); assert.equal(res.status, 400, path); } assert.deepEqual(seen, []); const other = (await db.insert(integrations).values({ type: "gitea", name: "g", baseUrl: "http://g", config: JSON.stringify({}) }).returning({ id: integrations.id }))[0].id; assert.equal((await fetch(`${base}/${other}/proxmox/nodes/pve1/qemu/100/snapshots`)).status, 400); }); test("the change log says what happened in words, and the maintenance key is not involved", async () => { const { describeChange } = await import("../src/services/changeLog.js"); const sentence = (action: string) => describeChange("integration", action, { vmid: 100, node: "pve1", snapshot: "s1", withRam: true }); assert.equal(sentence("create_snapshot").title, "A snapshot was taken of guest 100 on pve1"); assert.match(sentence("create_snapshot").detail ?? "", /s1 \(with memory\)/); assert.equal(sentence("rollback_snapshot").title, "Guest 100 on pve1 was rolled back to a snapshot"); assert.equal(sentence("delete_snapshot").title, "A snapshot was deleted from guest 100 on pve1"); assert.equal(subjectOfConditionKey("not-a-snapshot-key"), null); }); });