Let a secret be marked as never expiring
The expiry date is now optional: no date means the secret never expires, gets the status "no expiry" and never raises an alert or reminder. The Secrets form has a "Never expires" checkbox. Certificates checked against a host keep their live expiry and can't be set to never expire. Migration 0016 makes secrets.expiry_date nullable. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
75f0a3d881
commit
3daec601fd
11 files changed
+2069
-36
No files matched your search
@@ -0,0 +1,21 @@
|
||||
PRAGMA foreign_keys=OFF;--> statement-breakpoint
|
||||
CREATE TABLE `__new_secrets` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
`type` text DEFAULT 'generic' NOT NULL,
|
||||
`description` text,
|
||||
`expiry_date` text,
|
||||
`warn_days` integer DEFAULT 30 NOT NULL,
|
||||
`notes` text,
|
||||
`check_host` text,
|
||||
`check_port` integer,
|
||||
`last_checked_at` text,
|
||||
`last_check_error` text,
|
||||
`created_at` text DEFAULT (current_timestamp) NOT NULL,
|
||||
`updated_at` text DEFAULT (current_timestamp) NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `__new_secrets`("id", "name", "type", "description", "expiry_date", "warn_days", "notes", "check_host", "check_port", "last_checked_at", "last_check_error", "created_at", "updated_at") SELECT "id", "name", "type", "description", "expiry_date", "warn_days", "notes", "check_host", "check_port", "last_checked_at", "last_check_error", "created_at", "updated_at" FROM `secrets`;--> statement-breakpoint
|
||||
DROP TABLE `secrets`;--> statement-breakpoint
|
||||
ALTER TABLE `__new_secrets` RENAME TO `secrets`;--> statement-breakpoint
|
||||
PRAGMA foreign_keys=ON;
|
||||
File diff suppressed because it is too large.
Load diff
@@ -113,6 +113,13 @@
|
||||
"when": 1791407868932,
|
||||
"tag": "0015_yellow_scalphunter",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 16,
|
||||
"version": "6",
|
||||
"when": 1791667275424,
|
||||
"tag": "0016_great_glorian",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -94,7 +94,7 @@ export const secrets = sqliteTable("secrets", {
|
||||
name: text("name").notNull(),
|
||||
type: text("type").$type<SecretType>().notNull().default("generic"),
|
||||
description: text("description"),
|
||||
expiryDate: text("expiry_date").notNull(), // ISO date, e.g. 2026-03-01
|
||||
expiryDate: text("expiry_date"), // ISO date, e.g. 2026-03-01. NULL = never expires (no status, no reminders).
|
||||
warnDays: integer("warn_days").notNull().default(30),
|
||||
notes: text("notes"),
|
||||
// ssl_certificate secrets only: when set, expiryDate is read from the live certificate on this host:port instead of typed in.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Router } from "express";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { db } from "../db/client.js";
|
||||
import { secrets, secretTypes } from "../db/schema.js";
|
||||
@@ -14,7 +14,7 @@ export const secretsRouter = Router();
|
||||
secretsRouter.use(requireAuth);
|
||||
|
||||
secretsRouter.get("/", asyncHandler(async (_req, res) => {
|
||||
const rows = await db.select().from(secrets).orderBy(secrets.expiryDate);
|
||||
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) })),
|
||||
});
|
||||
@@ -24,8 +24,8 @@ 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.
|
||||
expiryDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "Expected YYYY-MM-DD").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(),
|
||||
@@ -43,7 +43,11 @@ secretsRouter.post("/", requireRole("operator"), asyncHandler(async (req, res) =
|
||||
return res.status(400).json({ error: "invalid_body", message: "Only SSL certificates can be checked against a host." });
|
||||
}
|
||||
|
||||
let expiryDate = manualExpiry;
|
||||
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) {
|
||||
@@ -60,8 +64,8 @@ secretsRouter.post("/", requireRole("operator"), asyncHandler(async (req, res) =
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!expiryDate) {
|
||||
return res.status(400).json({ error: "invalid_body", message: "An expiry date is required unless a host to check is given." });
|
||||
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
|
||||
@@ -101,6 +105,9 @@ secretsRouter.patch("/:id", requireRole("operator"), asyncHandler(async (req, re
|
||||
// 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<typeof secrets.$inferInsert> = { ...rest, updatedAt: now };
|
||||
@@ -117,6 +124,12 @@ secretsRouter.patch("/:id", requireRole("operator"), asyncHandler(async (req, re
|
||||
} 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.
|
||||
|
||||
@@ -1,19 +1,22 @@
|
||||
export type SecretStatus = "ok" | "expiring" | "expired";
|
||||
export type SecretStatus = "ok" | "expiring" | "expired" | "never";
|
||||
|
||||
/** Computes status + days-left for a secret, matching Sloth Manager's original semantics. */
|
||||
export type SecretStatusResult =
|
||||
| { status: "ok" | "expiring" | "expired"; daysLeft: number }
|
||||
| { status: "never"; daysLeft: null };
|
||||
|
||||
/** Computes status + days-left for a secret, matching Sloth Manager's original semantics. A secret with no expiry date never expires. */
|
||||
export function computeSecretStatus(
|
||||
expiryDate: string,
|
||||
expiryDate: string | null,
|
||||
warnDays: number,
|
||||
now: Date = new Date(),
|
||||
): { status: SecretStatus; daysLeft: number } {
|
||||
): SecretStatusResult {
|
||||
if (!expiryDate) return { status: "never", daysLeft: null };
|
||||
|
||||
const expiry = new Date(`${expiryDate}T00:00:00Z`);
|
||||
const today = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
|
||||
const daysLeft = Math.round((expiry.getTime() - today.getTime()) / (1000 * 60 * 60 * 24));
|
||||
|
||||
let status: SecretStatus;
|
||||
if (daysLeft < 0) status = "expired";
|
||||
else if (daysLeft <= warnDays) status = "expiring";
|
||||
else status = "ok";
|
||||
|
||||
return { status, daysLeft };
|
||||
if (daysLeft < 0) return { status: "expired", daysLeft };
|
||||
if (daysLeft <= warnDays) return { status: "expiring", daysLeft };
|
||||
return { status: "ok", daysLeft };
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
/**
|
||||
* Secrets that never expire: a secret with no expiry date has no status to warn about, and the API accepts and returns it.
|
||||
* The routes run for real against a scratch database; only the sign-in is stubbed (every request is an admin).
|
||||
*
|
||||
* 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-secrets-test-"));
|
||||
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, secrets } = await import("../src/db/schema.js");
|
||||
const { runMigrations } = await import("../src/db/migrate.js");
|
||||
const { secretsRouter } = await import("../src/routes/secrets.js");
|
||||
const { collectAlerts } = await import("../src/services/alerts.js");
|
||||
const { computeSecretStatus } = await import("../src/services/secretStatus.js");
|
||||
|
||||
await runMigrations();
|
||||
|
||||
describe("computeSecretStatus", () => {
|
||||
const now = new Date("2026-10-10T12:00:00Z");
|
||||
|
||||
test("a secret without an expiry date never expires", () => {
|
||||
assert.deepEqual(computeSecretStatus(null, 30, now), { status: "never", daysLeft: null });
|
||||
});
|
||||
|
||||
test("dated secrets keep their ok / expiring / expired meaning", () => {
|
||||
assert.deepEqual(computeSecretStatus("2026-12-31", 30, now), { status: "ok", daysLeft: 82 });
|
||||
assert.deepEqual(computeSecretStatus("2026-10-20", 30, now), { status: "expiring", daysLeft: 10 });
|
||||
assert.deepEqual(computeSecretStatus("2026-10-08", 30, now), { status: "expired", daysLeft: -2 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("secrets API", () => {
|
||||
let server: Server;
|
||||
let base = "";
|
||||
|
||||
before(async () => {
|
||||
await db.insert(users).values({ oidcSub: "tester", name: "Tester", role: "admin" });
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use((req, _res, next) => {
|
||||
(req as unknown as { session: unknown }).session = { user: { sub: "tester" } };
|
||||
next();
|
||||
});
|
||||
app.use("/api/secrets", secretsRouter);
|
||||
server = await new Promise<Server>((resolve) => {
|
||||
const s = app.listen(0, "127.0.0.1", () => resolve(s));
|
||||
});
|
||||
base = `http://127.0.0.1:${(server.address() as AddressInfo).port}/api/secrets`;
|
||||
});
|
||||
|
||||
after(() => {
|
||||
server.close();
|
||||
try {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
} catch {
|
||||
// Windows keeps the database file locked until the process exits; the folder is in the temp directory anyway.
|
||||
}
|
||||
});
|
||||
|
||||
async function send(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: res.status === 204 ? null : await res.json() };
|
||||
}
|
||||
|
||||
test("a secret can be created without an expiry date and is reported as never expiring", async () => {
|
||||
const created = await send("POST", "/", { name: "Break-glass admin", type: "password", expiryDate: null });
|
||||
assert.equal(created.status, 201);
|
||||
assert.equal(created.body.secret.expiryDate, null);
|
||||
assert.equal(created.body.secret.status, "never");
|
||||
assert.equal(created.body.secret.daysLeft, null);
|
||||
});
|
||||
|
||||
test("leaving the date out is still an error — never expiring has to be said explicitly", async () => {
|
||||
const res = await send("POST", "/", { name: "Forgot the date", type: "generic" });
|
||||
assert.equal(res.status, 400);
|
||||
});
|
||||
|
||||
test("a dated secret can be switched to never expire and back", async () => {
|
||||
const created = await send("POST", "/", { name: "API token", type: "api_token", expiryDate: "2030-01-01" });
|
||||
const id = created.body.secret.id;
|
||||
assert.equal(created.body.secret.status, "ok");
|
||||
|
||||
const never = await send("PATCH", `/${id}`, { expiryDate: null });
|
||||
assert.equal(never.status, 200);
|
||||
assert.equal(never.body.secret.expiryDate, null);
|
||||
assert.equal(never.body.secret.status, "never");
|
||||
|
||||
const dated = await send("PATCH", `/${id}`, { expiryDate: "2030-06-01" });
|
||||
assert.equal(dated.body.secret.expiryDate, "2030-06-01");
|
||||
assert.equal(dated.body.secret.status, "ok");
|
||||
});
|
||||
|
||||
test("a certificate checked against a host cannot be set to never expire", async () => {
|
||||
const res = await send("POST", "/", {
|
||||
name: "Monitored cert",
|
||||
type: "ssl_certificate",
|
||||
expiryDate: null,
|
||||
checkHost: "nas.example.lan",
|
||||
});
|
||||
assert.equal(res.status, 400);
|
||||
});
|
||||
|
||||
test("the list puts secrets without a date last, after the dated ones in date order", async () => {
|
||||
await send("POST", "/", { name: "Soonest", type: "generic", expiryDate: "2026-11-01" });
|
||||
const list = await send("GET", "/");
|
||||
const dates = list.body.secrets.map((s: { expiryDate: string | null }) => s.expiryDate);
|
||||
const firstNever = dates.findIndex((d: string | null) => d === null);
|
||||
assert.ok(firstNever > 0);
|
||||
assert.ok(dates.slice(firstNever).every((d: string | null) => d === null), "every undated secret comes after every dated one");
|
||||
const dated = dates.slice(0, firstNever);
|
||||
assert.deepEqual(dated, [...dated].sort());
|
||||
});
|
||||
|
||||
test("a secret that never expires raises no alert, an expired one does", async () => {
|
||||
await db.delete(secrets);
|
||||
await send("POST", "/", { name: "Never", type: "generic", expiryDate: null });
|
||||
await send("POST", "/", { name: "Old", type: "generic", expiryDate: "2020-01-01" });
|
||||
const report = await collectAlerts();
|
||||
const messages = report.alerts.map((a: { message: string }) => a.message).filter((m: string) => m.startsWith("Secret"));
|
||||
assert.equal(messages.length, 1);
|
||||
assert.match(messages[0], /Old/);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user