import { Router } from "express"; import { eq, sql } from "drizzle-orm"; import { z } from "zod"; import { db } from "../db/client.js"; import { secrets, secretTypes } from "../db/schema.js"; import { requireAuth, requireRole } from "../auth/middleware.js"; import { recordAudit } from "../services/audit.js"; import { computeSecretStatus } from "../services/secretStatus.js"; import { fetchCertExpiry, refreshTlsSecret } from "../services/tlsCheck.js"; import { asyncHandler } from "../utils/asyncHandler.js"; export const secretsRouter = Router(); secretsRouter.use(requireAuth); secretsRouter.get("/", asyncHandler(async (_req, res) => { const rows = await db.select().from(secrets).orderBy(sql`${secrets.expiryDate} IS NULL`, secrets.expiryDate); res.json({ secrets: rows.map((s) => ({ ...s, ...computeSecretStatus(s.expiryDate, s.warnDays) })), }); })); const secretInput = z.object({ name: z.string().min(1).max(200), type: z.enum(secretTypes), description: z.string().max(2000).optional(), // Optional only because a monitored certificate gets its date from the live cert; validated below. null means the secret never expires. expiryDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "Expected YYYY-MM-DD").nullable().optional(), warnDays: z.number().int().min(0).max(3650).default(30), notes: z.string().max(4000).optional(), checkHost: z.string().min(1).max(253).regex(/^[A-Za-z0-9._:-]+$/, "Invalid host").nullable().optional(), checkPort: z.number().int().min(1).max(65535).nullable().optional(), }); secretsRouter.post("/", requireRole("operator"), asyncHandler(async (req, res) => { const parsed = secretInput.safeParse(req.body); if (!parsed.success) { return res.status(400).json({ error: "invalid_body", details: parsed.error.flatten() }); } const { checkHost, checkPort, expiryDate: manualExpiry, ...rest } = parsed.data; if (checkHost && rest.type !== "ssl_certificate") { return res.status(400).json({ error: "invalid_body", message: "Only SSL certificates can be checked against a host." }); } if (checkHost && manualExpiry === null) { return res.status(400).json({ error: "invalid_body", message: "A certificate that is checked against a host has the expiry of the live certificate; it can't be set to never expire." }); } let expiryDate: string | null | undefined = manualExpiry; let lastCheckedAt: string | null = null; let lastCheckError: string | null = null; if (checkHost) { lastCheckedAt = new Date().toISOString(); try { expiryDate = await fetchCertExpiry(checkHost, checkPort ?? 443); } catch (err) { lastCheckError = err instanceof Error ? err.message : String(err); if (!manualExpiry) { return res.status(400).json({ error: "tls_check_failed", message: `Couldn't read the certificate from ${checkHost}:${checkPort ?? 443} (${lastCheckError}). Fix the host, or enter an expiry date manually.`, }); } } } if (expiryDate === undefined) { return res.status(400).json({ error: "invalid_body", message: "An expiry date is required unless the secret never expires or a host to check is given." }); } const [created] = await db .insert(secrets) .values({ ...rest, expiryDate, checkHost: checkHost ?? null, checkPort: checkHost ? (checkPort ?? 443) : null, lastCheckedAt, lastCheckError }) .returning(); await recordAudit({ actor: req.currentUser!, category: "secret", action: "create", targetType: "secret", targetId: created.id, detail: { name: created.name }, }); res.status(201).json({ secret: { ...created, ...computeSecretStatus(created.expiryDate, created.warnDays) } }); })); secretsRouter.patch("/:id", requireRole("operator"), asyncHandler(async (req, res) => { const id = Number(req.params.id); const parsed = secretInput.partial().safeParse(req.body); if (!parsed.success) { return res.status(400).json({ error: "invalid_body", details: parsed.error.flatten() }); } const [existing] = await db.select().from(secrets).where(eq(secrets.id, id)).limit(1); if (!existing) { return res.status(404).json({ error: "not_found" }); } const { checkHost, checkPort, ...rest } = parsed.data; const nextType = rest.type ?? existing.type; if (checkHost && nextType !== "ssl_certificate") { return res.status(400).json({ error: "invalid_body", message: "Only SSL certificates can be checked against a host." }); } // Changing a monitored secret to a non-certificate type quietly ends the monitoring rather than leaving a stale check behind. const nextHost = nextType !== "ssl_certificate" ? null : checkHost !== undefined ? checkHost : existing.checkHost; const nextPort = checkPort !== undefined ? checkPort : existing.checkPort; if (nextHost && rest.expiryDate === null) { return res.status(400).json({ error: "invalid_body", message: "A certificate that is checked against a host has the expiry of the live certificate; it can't be set to never expire." }); } const now = new Date().toISOString(); const changes: Partial = { ...rest, updatedAt: now }; if (!nextHost) { Object.assign(changes, { checkHost: null, checkPort: null, lastCheckedAt: null, lastCheckError: null }); } else { const port = nextPort ?? 443; Object.assign(changes, { checkHost: nextHost, checkPort: port }); if (nextHost !== existing.checkHost || port !== (existing.checkPort ?? 443)) { changes.lastCheckedAt = now; try { changes.expiryDate = await fetchCertExpiry(nextHost, port); changes.lastCheckError = null; } catch (err) { // Keep whatever date we already have (a manually supplied one, else the existing one) and record why the check failed. changes.lastCheckError = err instanceof Error ? err.message : String(err); if (!changes.expiryDate && !existing.expiryDate) { return res.status(400).json({ error: "tls_check_failed", message: `Couldn't read the certificate from ${nextHost}:${port} (${changes.lastCheckError}), and this secret has no expiry date to fall back on. Fix the host, or enter an expiry date first.`, }); } } } else { // Same host as before: the live certificate stays the source of truth, so ignore a hand-typed date. delete changes.expiryDate; } } const [updated] = await db.update(secrets).set(changes).where(eq(secrets.id, id)).returning(); await recordAudit({ actor: req.currentUser!, category: "secret", action: "update", targetType: "secret", targetId: id, detail: { name: updated.name }, }); res.json({ secret: { ...updated, ...computeSecretStatus(updated.expiryDate, updated.warnDays) } }); })); secretsRouter.post("/:id/check-tls", requireRole("operator"), asyncHandler(async (req, res) => { const id = Number(req.params.id); const result = await refreshTlsSecret(id); if (!result) { return res.status(400).json({ error: "not_monitored", message: "This secret has no host to check." }); } const [updated] = await db.select().from(secrets).where(eq(secrets.id, id)).limit(1); await recordAudit({ actor: req.currentUser!, category: "secret", action: "check_tls", targetType: "secret", targetId: id, detail: { name: result.name, host: result.host, port: result.port, ok: result.ok, error: result.error }, }); res.json({ secret: { ...updated, ...computeSecretStatus(updated.expiryDate, updated.warnDays) }, result }); })); secretsRouter.delete("/:id", requireRole("operator"), asyncHandler(async (req, res) => { const id = Number(req.params.id); const [existing] = await db.select().from(secrets).where(eq(secrets.id, id)).limit(1); if (!existing) { return res.status(404).json({ error: "not_found" }); } await db.delete(secrets).where(eq(secrets.id, id)); await recordAudit({ actor: req.currentUser!, category: "secret", action: "delete", targetType: "secret", targetId: id, detail: { name: existing.name }, }); res.status(204).end(); }));