diff --git a/server/src/routes/maintenance.ts b/server/src/routes/maintenance.ts index 35ece3b..0f29765 100644 --- a/server/src/routes/maintenance.ts +++ b/server/src/routes/maintenance.ts @@ -90,15 +90,16 @@ maintenanceRouter.post("/import/uptimekuma", requireRole("operator"), asyncHandl const { integrationId, minutes } = parsed.data; const loaded = await loadIntegrationConfig(integrationId); - if (!loaded) return res.status(404).json({ error: "not_found" }); - if (loaded.integration.type !== "uptimekuma") return res.status(400).json({ error: "wrong_type" }); - if (!loaded.integration.enabled) return res.status(400).json({ error: "integration_disabled" }); + if (!loaded) return res.status(404).json({ error: "not_found", message: "That Uptime Kuma integration no longer exists." }); + if (loaded.integration.type !== "uptimekuma") return res.status(400).json({ error: "wrong_type", message: "That integration isn't an Uptime Kuma one." }); + if (!loaded.integration.enabled) return res.status(400).json({ error: "integration_disabled", message: "That integration is disabled. Enable it under Integrations first." }); let monitors; try { monitors = await createUptimeKumaAdapter(loaded.config as any).listMonitors(); } catch (err) { - return res.status(502).json({ error: err instanceof Error ? err.message : String(err) }); + const message = err instanceof Error ? err.message : String(err); + return res.status(502).json({ error: "uptimekuma_unreachable", message: `Couldn't read Uptime Kuma: ${message}` }); } const serverRows = await db.select({ id: servers.id, name: servers.name, hostname: servers.hostname, ips: servers.ipAddresses }).from(servers); @@ -134,7 +135,7 @@ maintenanceRouter.post("/import/uptimekuma", requireRole("operator"), asyncHandl imported.push({ serverId: m.matchedServer.id, serverName: result.target.name, monitorName: m.name, extended: result.extended }); } - res.json({ imported, unmatched, monitorsInMaintenance: inMaintenance.length }); + res.json({ imported, unmatched, monitorsInMaintenance: inMaintenance.length, monitorsChecked: monitors.length }); })); maintenanceRouter.delete("/:id", requireRole("operator"), asyncHandler(async (req, res) => { diff --git a/server/test/kumaImport.test.ts b/server/test/kumaImport.test.ts new file mode 100644 index 0000000..b61c029 --- /dev/null +++ b/server/test/kumaImport.test.ts @@ -0,0 +1,115 @@ +/** + * Importing maintenance windows from Uptime Kuma, end to end through the real route. + * A stand-in Uptime Kuma serves /metrics; the database is a scratch one; only the sign-in is stubbed. + * + * 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 http from "node:http"; +import type { AddressInfo } from "node:net"; + +const dir = mkdtempSync(join(tmpdir(), "hm-kuma-import-")); +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, integrations, maintenanceWindows } = await import("../src/db/schema.js"); +const { runMigrations } = await import("../src/db/migrate.js"); +const { maintenanceRouter } = await import("../src/routes/maintenance.js"); + +await runMigrations(); + +function metric(id: number, name: string, host: string, status: number) { + return `monitor_status{monitor_id="${id}",monitor_name="${name}",monitor_type="ping",monitor_url="",monitor_hostname="${host}",monitor_port=""} ${status}`; +} + +describe("import maintenance from Uptime Kuma", () => { + let kuma: http.Server; + let app: http.Server; + let base = ""; + let metricsBody = ""; + let kumaStatus = 200; + let integrationId = 0; + + before(async () => { + kuma = await new Promise((resolve) => { + const s = http.createServer((req, res) => { + res.statusCode = kumaStatus; + res.end(req.url === "/metrics" ? metricsBody : ""); + }); + s.listen(0, "127.0.0.1", () => resolve(s)); + }); + const kumaUrl = `http://127.0.0.1:${(kuma.address() as AddressInfo).port}`; + + await db.insert(users).values({ oidcSub: "tester", name: "Tester", role: "admin" }); + await db.insert(servers).values({ name: "elsa", hostname: "elsa.lab.example", apiTokenHash: "x", apiTokenPrefix: "x" }); + const [row] = await db + .insert(integrations) + .values({ type: "uptimekuma", name: "Kuma", baseUrl: kumaUrl, config: JSON.stringify({ url: kumaUrl, password: "key" }) }) + .returning(); + integrationId = row.id; + + const a = express(); + a.use(express.json()); + a.use((req, _res, next) => { + (req as unknown as { session: unknown }).session = { user: { sub: "tester" } }; + next(); + }); + a.use("/api/maintenance", maintenanceRouter); + 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/maintenance/import/uptimekuma`; + }); + + after(() => { + kuma.close(); + app.close(); + try { + rmSync(dir, { recursive: true, force: true }); + } catch { + // Windows keeps the database file locked until the process exits. + } + }); + + async function runImport() { + const res = await fetch(base, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ integrationId, minutes: 60 }), + }); + return { status: res.status, body: await res.json() }; + } + + test("a monitor in maintenance on a known server starts a window there", async () => { + kumaStatus = 200; + metricsBody = [metric(1, "elsa ping", "elsa.lab.example", 3), metric(2, "other", "10.9.9.9", 3), metric(3, "up one", "elsa.lab.example", 1)].join("\n"); + const { status, body } = await runImport(); + assert.equal(status, 200); + assert.equal(body.monitorsInMaintenance, 2); + assert.deepEqual(body.imported.map((i: { serverName: string }) => i.serverName), ["elsa"]); + assert.deepEqual(body.unmatched, ["other"]); + assert.equal((await db.select().from(maintenanceWindows)).length, 1); + }); + + test("nothing in maintenance reports zero", async () => { + metricsBody = metric(1, "elsa ping", "elsa.lab.example", 1); + const { body } = await runImport(); + assert.equal(body.monitorsInMaintenance, 0); + assert.equal(body.monitorsChecked, 1); + }); + + test("Uptime Kuma rejecting the credentials comes back with a readable message", async () => { + kumaStatus = 401; + const { status, body } = await runImport(); + assert.equal(status, 502); + assert.equal(typeof body.message, "string", "the page shows body.message; without it the user sees raw JSON"); + assert.match(body.message, /rejected the credentials/); + }); +}); diff --git a/web/src/api/client.ts b/web/src/api/client.ts index 5c079ff..55b6290 100644 --- a/web/src/api/client.ts +++ b/web/src/api/client.ts @@ -777,6 +777,8 @@ export interface UptimeKumaImportResult { imported: { serverId: number; serverName: string; monitorName: string; extended: boolean }[]; unmatched: string[]; monitorsInMaintenance: number; + /** How many monitors Uptime Kuma reported in all, so "nothing in maintenance" can be told apart from "nothing read". */ + monitorsChecked: number; } export interface PbsFailedSnapshot { diff --git a/web/src/pages/Maintenance.tsx b/web/src/pages/Maintenance.tsx index 42a9327..3cad109 100644 --- a/web/src/pages/Maintenance.tsx +++ b/web/src/pages/Maintenance.tsx @@ -256,7 +256,13 @@ export default function Maintenance({ user }: { user: CurrentUser }) { {kumaResult && (
{kumaResult.monitorsInMaintenance === 0 ? ( -
Nothing is currently in maintenance in Uptime Kuma.
+
+ {kumaResult.monitorsChecked === 0 + ? "Uptime Kuma answered, but reported no monitors at all." + : `Read ${kumaResult.monitorsChecked} monitor${kumaResult.monitorsChecked === 1 ? "" : "s"} from Uptime Kuma; none is in maintenance right now.`}{" "} + Only a maintenance window that is active at this moment can be imported — one scheduled for later + shows up here once it starts. +
) : (
{kumaResult.imported.length > 0 ? ( @@ -282,10 +288,13 @@ export default function Maintenance({ user }: { user: CurrentUser }) { )}
)} -
+
+ {kumaIntegrationId === "" && ( + Every Uptime Kuma integration is disabled — enable one under Integrations. + )}