import { createLogger } from "@hivegrid/logger"; import { afterEach, describe, expect, it } from "vitest"; import { createControllerHttpRuntime, type ControllerHttpRuntime } from "./http.js"; import { createControllerMetrics } from "./metrics.js"; const METRICS_TOKEN = "metrics-token-that-is-at-least-thirty-two-bytes"; const runtimes: ControllerHttpRuntime[] = []; afterEach(async () => { await Promise.all(runtimes.splice(0).map((runtime) => runtime.close())); }); describe("portal-domain controller HTTP runtime", () => { it("serves liveness, fail-closed readiness and a bearer-protected metrics endpoint", async () => { let ready = false; const runtime = createControllerHttpRuntime({ host: "127.0.0.1", port: 0, revision: "abc123", metricsToken: METRICS_TOKEN, isReady: async () => ready, logger: createLogger({ level: "silent" }), metrics: createControllerMetrics("test", false), }); runtimes.push(runtime); const address = await runtime.listen(); const origin = `http://127.0.0.1:${address.port}`; const health = await fetch(`${origin}/healthz`); expect(health.status).toBe(200); expect(await health.json()).toEqual({ status: "ok", service: "hivegrid-portal-domain-controller", revision: "abc123" }); expect(health.headers.get("x-content-type-options")).toBe("nosniff"); expect((await fetch(`${origin}/readyz`)).status).toBe(503); ready = true; expect((await fetch(`${origin}/readyz`)).status).toBe(200); expect((await fetch(`${origin}/metrics`)).status).toBe(401); expect((await fetch(`${origin}/metrics`, { headers: { authorization: "Bearer wrong" } })).status).toBe(401); const metrics = await fetch(`${origin}/metrics`, { headers: { authorization: `Bearer ${METRICS_TOKEN}` } }); expect(metrics.status).toBe(200); expect(await metrics.text()).toContain("hivegrid_portal_domain_controller_ready"); expect((await fetch(`${origin}/unknown`)).status).toBe(404); expect((await fetch(`${origin}/healthz`, { method: "POST" })).status).toBe(405); }); });