/** * Closing an osTicket ticket from here: what is written (a status, a note, an event — all or none), that it is refused rather than guessed at when osTicket's tables are not * what it was written for, that an open ticket only is closed and nobody else's change is overwritten, "Test closing" that tries it all and rolls back, and how it hangs on an alert. * * There is no osTicket database to try it on, so the database here is a pretend one that answers the exact statements the code sends (it understands transactions, missing * columns and a login that may not write). What it cannot tell is whether osTicket's real tables are as published: the docs say that too. * * 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-osclose-")); 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, heartbeats, integrations, alertTickets, auditLog } = await import("../src/db/schema.js"); const { runMigrations } = await import("../src/db/migrate.js"); const closer = await import("../src/integrations/osticket/closeTicket.js"); const svc = await import("../src/services/alertTickets.js"); const { alertsRouter } = await import("../src/routes/alerts.js"); const { alertTicketsRouter } = await import("../src/routes/alertTickets.js"); const { getAlerts, invalidateAlertsCache } = await import("../src/services/alerts.js"); const { getIncident, openIncidentIds } = await import("../src/services/incidents.js"); const { getChangeLog } = await import("../src/services/changeLog.js"); const { eq } = await import("drizzle-orm"); await runMigrations(); type Conn = import("../src/integrations/osticket/closeTicket.js").SqlConn; /** A pretend osTicket database that answers what closing asks, with transactions. */ function pretend(opts: { missing?: Record; noThread?: boolean; noEvent?: boolean; noClosedStatus?: boolean; denyWrite?: RegExp; tickets?: { id: number; number: string; statusId: number }[]; raceOnUpdate?: boolean; prefix?: string } = {}) { const p = opts.prefix ?? "ost_"; const statuses = opts.noClosedStatus ? [{ id: 1, name: "Open", state: "open" }] : [{ id: 1, name: "Open", state: "open" }, { id: 2, name: "Resolved", state: "closed" }, { id: 3, name: "Closed", state: "closed" }, { id: 4, name: "Archived", state: "archived" }]; const state = { tickets: (opts.tickets ?? [{ id: 10, number: "100001", statusId: 1 }]).map((t) => ({ ...t, deptId: 1, topicId: 2, closed: null as string | null, isanswered: 1, isoverdue: 1 })), entries: [] as Record[], events: [] as Record[], }; let snapshot: string | null = null; const log: { sql: string; params: unknown[] }[] = []; const columns = Object.fromEntries(Object.entries(closer.REQUIRED_COLUMNS).map(([t, cols]) => [`${p}${t}`, (cols as string[]).filter((c) => !(opts.missing?.[t] ?? []).includes(c))])); const conn: Conn & { ended: boolean } = { ended: false, async query(sql: string, params: unknown[] = []) { log.push({ sql, params }); const s = sql.replace(/\s+/g, " ").trim(); if (/information_schema\.columns/.test(s)) { const wanted = new Set(params.map(String)); return [Object.entries(columns).filter(([t]) => wanted.has(t)).flatMap(([t, cols]) => cols.map((c) => ({ t, c })))]; } if (/^SELECT t\.ticket_id AS id/.test(s)) { const t = state.tickets.find((x) => x.number === params[0]); return [t ? [{ id: t.id, statusId: t.statusId, deptId: t.deptId, topicId: t.topicId, state: statuses.find((x) => x.id === t.statusId)!.state }] : []]; } if (/FROM \S*thread WHERE object_id/.test(s)) return [opts.noThread ? [] : [{ id: 900 + Number(params[0]) }]]; if (/FROM \S*ticket_status WHERE state = 'closed'/.test(s)) { const closed = statuses.filter((x) => x.state === "closed").sort((a, b) => Number(b.name === "Closed") - Number(a.name === "Closed") || a.id - b.id); return [closed.length ? [closed[0]] : []]; } if (/FROM \S*event WHERE name = 'closed'/.test(s)) return [opts.noEvent ? [] : [{ id: 7 }]]; if (/FROM \S*thread th JOIN/.test(s)) return [state.tickets.length ? [{ threadId: 900 + state.tickets[0].id, deptId: 1, topicId: 2 }] : []]; if (opts.denyWrite && opts.denyWrite.test(s)) throw new Error("INSERT command denied to user 'hm_close'@'%' for table"); if (/^UPDATE \S*ticket SET status_id = status_id/.test(s)) return [{ affectedRows: 0 }]; if (/^UPDATE \S*ticket SET status_id = \?/.test(s)) { const t = state.tickets.find((x) => x.id === params[1] && x.statusId === params[2]); if (!t || opts.raceOnUpdate) return [{ affectedRows: 0 }]; t.statusId = Number(params[0]); t.closed = "now"; t.isanswered = 0; t.isoverdue = 0; return [{ affectedRows: 1 }]; } if (/^INSERT INTO \S*thread_entry/.test(s)) { state.entries.push({ threadId: params[0], poster: params[1], title: params[2], body: params[3] }); return [{ affectedRows: 1 }]; } if (/^INSERT INTO \S*thread_event/.test(s)) { state.events.push({ threadId: params[0], eventId: params[1], deptId: params[2], topicId: params[3], data: params[4], username: params[5] }); return [{ affectedRows: 1 }]; } throw new Error(`pretend osTicket does not know: ${s.slice(0, 80)}`); }, async beginTransaction() { snapshot = JSON.stringify(state); }, async commit() { snapshot = null; }, async rollback() { if (snapshot !== null) Object.assign(state, JSON.parse(snapshot)); snapshot = null; }, async end() { conn.ended = true; }, }; return { conn, state, log, deps: { connect: async () => conn } }; } const CONFIG = { host: "db.lan", database: "osticket", closeUsername: "hm_close", closePassword: "pw" }; const writes = (log: { sql: string }[]) => log.filter((l) => /^\s*(UPDATE|INSERT)/i.test(l.sql)); describe("what closing writes", () => { test("an open ticket is set to Closed, a note says who closed it and why, and the event is recorded — and the connection is let go", async () => { const o = pretend(); const r = await closer.closeTicket(CONFIG, { number: "100001", closedBy: "Olga", reason: "Fixed outside the app" }, o.deps); assert.deepEqual(r, { result: "closed", statusName: "Closed" }); const t = o.state.tickets[0]; assert.deepEqual([t.statusId, t.closed, t.isanswered, t.isoverdue], [3, "now", 0, 0], "'Closed', not 'Resolved' (which has the lower id)"); assert.deepEqual(o.state.entries, [{ threadId: 910, poster: "Homelab Manager", title: "Closed from Homelab Manager", body: "Fixed outside the app\n\nClosed from Homelab Manager by Olga." }]); assert.deepEqual(o.state.events, [{ threadId: 910, eventId: 7, deptId: 1, topicId: 2, data: JSON.stringify({ status: [3, "Closed"] }), username: "Homelab Manager" }]); assert.equal(o.conn.ended, true); }); test("without a reason the note still says who; with no status called Closed the first closed one is used", async () => { const o = pretend(); await closer.closeTicket(CONFIG, { number: "100001", closedBy: "Olga", reason: null }, o.deps); assert.equal(o.state.entries[0].body, "Closed from Homelab Manager by Olga."); }); test("a ticket that is not open is left alone, with nothing written", async () => { const o = pretend({ tickets: [{ id: 10, number: "100001", statusId: 3 }] }); assert.deepEqual(await closer.closeTicket(CONFIG, { number: "100001", closedBy: "Olga", reason: null }, o.deps), { result: "already_closed", statusName: null }); assert.equal(writes(o.log).length, 0); }); test("a ticket somebody closes at the same moment is not overwritten: the update changes nothing, the transaction is undone and nothing is added to it", async () => { const o = pretend({ raceOnUpdate: true }); const r = await closer.closeTicket(CONFIG, { number: "100001", closedBy: "Olga", reason: null }, o.deps); assert.equal(r.result, "already_closed"); assert.deepEqual([o.state.entries.length, o.state.events.length], [0, 0]); }); test("if the note or the event cannot be written, nothing was changed: the status is put back", async () => { const o = pretend({ denyWrite: /^INSERT INTO \S*thread_event/ }); await assert.rejects( () => closer.closeTicket(CONFIG, { number: "100001", closedBy: "Olga", reason: null }, o.deps), (err: unknown) => err instanceof closer.CloseError && err.code === "failed" && /denied/.test(err.message), ); assert.deepEqual([o.state.tickets[0].statusId, o.state.tickets[0].closed, o.state.entries.length], [1, null, 0], "still open, no note"); assert.equal(o.conn.ended, true); }); test("a table prefix other than ost_ is used, and one that could carry SQL is refused", async () => { const o = pretend({ prefix: "helpdesk_" }); assert.equal((await closer.closeTicket({ ...CONFIG, tablePrefix: "helpdesk_" }, { number: "100001", closedBy: "Olga", reason: null }, o.deps)).result, "closed"); assert.ok(o.log.some((l) => /UPDATE helpdesk_ticket SET/.test(l.sql))); await assert.rejects(() => closer.closeTicket({ ...CONFIG, tablePrefix: "ost_; DROP TABLE x" }, { number: "1", closedBy: "x", reason: null }, pretend().deps), /letters, numbers, and underscores/); }); }); describe("what it refuses to do", () => { const closeIt = (o: ReturnType, number = "100001") => closer.closeTicket(CONFIG, { number, closedBy: "Olga", reason: null }, o.deps); const code = (c: string) => (err: unknown) => err instanceof closer.CloseError && err.code === c; test("an osTicket whose tables are not the ones it was written for is refused, saying what is missing, before anything is written", async () => { const o = pretend({ missing: { thread_event: ["annulled"], ticket: ["isoverdue", "closed"] } }); await assert.rejects( () => closeIt(o), (err: unknown) => err instanceof closer.CloseError && err.code === "schema_mismatch" && /ost_thread_event has no annulled/.test(err.message) && /ost_ticket has no closed, isoverdue/.test(err.message) && /Nothing was changed/.test(err.message), ); assert.equal(writes(o.log).length, 0); assert.equal(o.conn.ended, true); }); test("a ticket number that is not there, a ticket with no thread, no closed status and no 'closed' event are each said plainly", async () => { await assert.rejects(() => closeIt(pretend(), "999999"), code("ticket_not_found")); await assert.rejects(() => closeIt(pretend({ noThread: true })), code("no_thread")); await assert.rejects(() => closeIt(pretend({ noClosedStatus: true })), code("no_closed_status")); await assert.rejects(() => closeIt(pretend({ noEvent: true })), code("schema_mismatch")); }); test("without a login for it, nothing is attempted", async () => { assert.equal(closer.hasCloseAccess({ host: "h", database: "d", closeUsername: "u", closePassword: "" }), false); assert.equal(closer.hasCloseAccess(CONFIG), true); await assert.rejects(() => closer.closeTicket({ host: "h", database: "d" }, { number: "1", closedBy: "x", reason: null }), code("not_configured")); }); }); describe("Test closing", () => { test("everything in order: the writes are tried and every one of them rolled back", async () => { const o = pretend(); const r = await closer.testCloseAccess(CONFIG, o.deps); assert.deepEqual([r.ok, r.problems], [true, []]); assert.deepEqual([o.state.entries.length, o.state.events.length, o.state.tickets[0].statusId], [0, 0, 1], "nothing stayed"); assert.equal(writes(o.log).length, 3, "an update, a note and an event were tried"); assert.equal(o.conn.ended, true); }); test("a login that may not write is found here, with what it needs", async () => { const o = pretend({ denyWrite: /^INSERT INTO \S*thread_entry/ }); const r = await closer.testCloseAccess(CONFIG, o.deps); assert.equal(r.ok, false); assert.match(r.problems[0], /refused/); assert.match(r.problems[0], /UPDATE on ost_ticket/); assert.match(r.problems[0], /INSERT on ost_thread_entry and ost_thread_event/); }); test("a different osTicket is reported as such; an osTicket with no ticket yet says what could not be tried; a login that cannot sign in is said", async () => { const bad = await closer.testCloseAccess(CONFIG, pretend({ missing: { event: ["name"] } }).deps); assert.equal(bad.ok, false); assert.match(bad.problems[0], /not the osTicket the closing was written for/); const empty = await closer.testCloseAccess(CONFIG, pretend({ tickets: [] }).deps); assert.deepEqual([empty.ok, empty.notes.length], [true, 1]); const refused = await closer.testCloseAccess(CONFIG, { connect: async () => Promise.reject(new Error("Access denied for user")) }); assert.equal(refused.ok, false); assert.match(refused.problems[0], /Could not sign in to osTicket's database with that login: Access denied/); assert.equal((await closer.testCloseAccess({ host: "h", database: "d" })).ok, false); }); }); describe("closing the ticket of an alert", () => { let app: Server; let base = ""; let who = "operator"; let integrationId = 0; let readOnlyId = 0; const call = async (method: string, path: string, body?: unknown) => { const res = await fetch(`${base}${path}`, { method, headers: { "content-type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) }); return { status: res.status, body: (await res.json().catch(() => null)) as any }; }; const alertOf = async (name: string) => { invalidateAlertsCache(); return (await getAlerts(true)).alerts.find((a) => a.message.startsWith(name))!; }; const ticketFor = (alertKey: string, extra: Partial = {}) => db.insert(alertTickets).values({ alertKey, status: "open", severity: "warning", message: "m", firstSeenAt: new Date().toISOString(), lastSeenAt: new Date().toISOString(), ticketedAt: new Date().toISOString(), ticketNumber: "100001", integrationId, ...extra }); let fake: ReturnType; before(async () => { await db.insert(users).values([ { oidcSub: "operator", name: "Olga", role: "operator" }, { oidcSub: "admin", name: "Ada", role: "admin" }, { oidcSub: "viewer", name: "Vic", role: "viewer" }, ]); integrationId = (await db.insert(integrations).values({ type: "osticket", name: "osTicket", baseUrl: "", config: JSON.stringify({ host: "db.lan", database: "osticket", username: "ro", password: "x", apiUrl: "https://os.lan/", closeUsername: "hm_close", closePassword: "pw" }) }).returning({ id: integrations.id }))[0].id; readOnlyId = (await db.insert(integrations).values({ type: "osticket", name: "osTicket (read only)", baseUrl: "", config: JSON.stringify({ host: "db2.lan", database: "osticket", username: "ro", password: "x", apiUrl: "https://os2.lan/" }) }).returning({ id: integrations.id }))[0].id; const old = "2026-01-01 00:00:00"; for (const name of ["tkA", "tkB", "tkC", "tkD"]) await db.insert(heartbeats).values({ name, token: `hb_${name}`.padEnd(24, "x"), periodMinutes: 60, graceMinutes: 5, serverId: null, createdAt: old }); 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/alerts", alertsRouter); a.use("/api/alert-tickets", alertTicketsRouter); 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`; fake = pretend(); svc.setTicketCloserForTests((config, input) => closer.closeTicket(config, input, fake.deps)); }); after(() => { svc.setTicketCloserForTests(null); app.close(); try { rmSync(dir, { recursive: true, force: true }); } catch { // Windows keeps the database file locked until the process exits. } }); test("the alert says whether its ticket can be closed from here: only with a login for it, not a summary ticket, not one already closed", async () => { const a = await alertOf("tkA"); const b = await alertOf("tkB"); const c = await alertOf("tkC"); await ticketFor(a.id); await ticketFor(b.id, { integrationId: readOnlyId }); await ticketFor(c.id, { grouped: true }); const info = await svc.ticketsForAlerts([a.id, b.id, c.id]); assert.deepEqual([info.get(a.id)?.canClose, info.get(b.id)?.canClose, info.get(c.id)?.canClose], [true, false, false]); assert.equal(info.get(a.id)?.closedAt, null); }); test("closing the alert with the tick closes its ticket, writes it on the incident and in the logs, and the page no longer offers it", async () => { fake = pretend(); const a = await alertOf("tkA"); const r = await call("PUT", "/alerts/close", { alertId: a.id, note: "Replaced the job", closeTicket: true }); assert.equal(r.status, 200); assert.deepEqual(r.body.ticket, { number: "100001", result: "closed", message: null }); assert.equal(fake.state.tickets[0].statusId, 3); assert.match(String(fake.state.entries[0].body), /Replaced the job\n\nClosed from Homelab Manager by Olga\./); const incidentId = (await openIncidentIds([a.id])).get(a.id)!; assert.deepEqual((await getIncident(incidentId))!.notes.map((n) => n.body), ["Closed: Replaced the job", "osTicket ticket 100001 closed."]); const info = (await svc.ticketsForAlerts([a.id])).get(a.id)!; assert.deepEqual([info.canClose, info.closedAt === null], [false, false]); const actions = (await db.select().from(auditLog)).map((e) => `${e.category}/${e.action}`); assert.ok(actions.includes("alert_ticket/close_ticket")); assert.ok((await getChangeLog({ days: 1, limit: 300 })).entries.some((e) => /^osTicket ticket 100001 closed from here$/.test(e.title))); }); test("closing the alert without the tick leaves its ticket alone", async () => { fake = pretend(); const b = await alertOf("tkD"); await ticketFor(b.id); const r = await call("PUT", "/alerts/close", { alertId: b.id }); assert.equal(r.body.ticket, null); assert.equal(fake.state.tickets[0].statusId, 1); }); test("when the ticket cannot be closed the alert is closed all the same, and the reason is said and written down", async () => { fake = pretend({ missing: { thread_event: ["annulled"] } }); const b = await alertOf("tkB"); const r = await call("PUT", "/alerts/close", { alertId: b.id, closeTicket: true }); assert.equal(r.status, 200); assert.equal(r.body.ticket.result, "failed"); assert.match(r.body.ticket.message, /no login for closing tickets|not the osTicket/); invalidateAlertsCache(); assert.equal((await alertOf("tkB")).closed?.by, "Olga", "the alert is closed"); const actions = (await db.select().from(auditLog)).map((e) => `${e.category}/${e.action}`); assert.ok(actions.includes("alert_ticket/close_ticket_failed")); }); test("a ticket that cannot be closed from here, asked for anyway, is said and the alert is still closed", async () => { const c = await alertOf("tkC"); const r = await call("PUT", "/alerts/close", { alertId: c.id, closeTicket: true }); assert.equal(r.body.ticket.result, "failed"); assert.match(r.body.ticket.message, /summary ticket/); }); test("an alert with no ticket, asked to close one, closes only the alert", async () => { const d = await alertOf("tkD"); await call("DELETE", `/alerts/close?alertId=${encodeURIComponent(d.id)}`); await db.delete(alertTickets).where(eq(alertTickets.alertKey, d.id)); const r = await call("PUT", "/alerts/close", { alertId: d.id, closeTicket: true }); assert.equal(r.status, 200); assert.equal(r.body.ticket.result, "failed"); assert.match(r.body.ticket.message, /No ticket was opened/); }); test("a ticket is closed once from here: asking again says so", async () => { const a = await alertOf("tkA"); await assert.rejects(() => svc.closeTicketForAlert(a.id, { closedBy: "Olga", reason: null }), /already been closed/); }); test("an administrator can test closing for an integration; others cannot; a viewer cannot close an alert at all", async () => { who = "operator"; assert.equal((await call("POST", "/alert-tickets/test-close", { integrationId })).status, 403); who = "admin"; const noLogin = await call("POST", "/alert-tickets/test-close", { integrationId: readOnlyId }); assert.deepEqual([noLogin.body.ok, /no login for closing tickets/.test(noLogin.body.problems[0])], [false, true]); const overview = await call("GET", "/alert-tickets"); assert.deepEqual(overview.body.integrations.map((i: { id: number; closeReady: boolean }) => [i.id, i.closeReady]), [[integrationId, true], [readOnlyId, false]]); assert.equal((await call("POST", "/alert-tickets/test-close", { integrationId: "x" })).status, 400); who = "viewer"; const a = await alertOf("tkA"); assert.equal((await call("PUT", "/alerts/close", { alertId: a.id, closeTicket: true })).status, 403); who = "operator"; }); });