feat(rotation): 90-day policy, due runs wait for owner approval (CLI 0.16.0) (#270)

Every automatic secret older than the team's max age (90 days default) is
queued as one run in awaiting-approval. An owner/admin approves it on the
Rotation page or with `teams rotation-approve`; machine keys can queue but
never approve. logicsrc-rotate --queue (*/5 cron) runs approved runs with
propagate + health checks + rollback. rotation_auto_approve per team is the
paid automatic rotation add-on (off by default).

Co-authored-by: Anthony Ettinger <anthony@profullstack.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
sh1pt-actions-fleet[bot] 2026-10-29 04:36:26 +00:00 • committed by GitHub
parent 87bbc50423
commit 0f237cb6e0
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
11 changed files with 407 additions and 24 deletions

View file

@ -11,6 +11,18 @@ import { planRotations, isoTime } from "@logicsrc/cli/dist/rotation-catalog.js";
import { DESKTOP_RECIPES } from "@logicsrc/cli/dist/desktop-recipes.js";
const ROTATE_PREFIX = "__ROTATE__";
const DAY = 24 * 60 * 60 * 1000;
/** Default rotation policy: an automatic secret is due once its value is this many days old. */
export const DEFAULT_MAX_AGE_DAYS = 90;
/** One due run carries at most this many keys (the oldest first); the rest wait for the next. */
export const DUE_RUN_MAX_KEYS = 200;
/** A team's max age in days: its own setting, else the default. */
export function maxAgeDays(team) {
const n = Number(team?.rotation_max_age_days);
return Number.isInteger(n) && n > 0 ? n : DEFAULT_MAX_AGE_DAYS;
}
/** Vault names split the way the CLI does: <project>--<env>. */
export function splitVaultName(name) {
@ -23,7 +35,7 @@ export function splitVaultName(name) {
* `logicsrc teams rotation`. `vaultFilter(name)` limits it to vaults the caller
* may see (a machine key's scope).
*/
export async function rotationPlan(teamId, { project, env, keys, vaultFilter = () => true } = {}) {
export async function rotationPlan(teamId, { project, env, keys, vaultFilter = () => true, maxAge = DEFAULT_MAX_AGE_DAYS, now = Date.now() } = {}) {
const rows = (await all(
`SELECT v.name AS vault, s.name AS key, s.fingerprint, s.updated_at
FROM credshare_secrets s JOIN credshare_vaults v ON v.id = s.vault_id
@ -50,6 +62,8 @@ export async function rotationPlan(teamId, { project, env, keys, vaultFilter = (
const spec = p.spec ?? {};
const recipe = spec.method === "desktop" ? DESKTOP_RECIPES[spec.recipe] : null;
const everywhere = byFp.get(p.fingerprint) ?? [];
const rotatedAt = Date.parse(isoTime(p.oldestUpdate));
const ageDays = Number.isFinite(rotatedAt) ? Math.floor((now - rotatedAt) / DAY) : null;
return {
key: p.key,
method: p.method,
@ -68,6 +82,9 @@ export async function rotationPlan(teamId, { project, env, keys, vaultFilter = (
vaultCount: everywhere.length || p.vaults.length,
alsoIn: everywhere.filter((vk) => !p.vaults.some((v) => vk === `${v}:${p.key}`)),
lastRotated: isoTime(p.oldestUpdate),
ageDays,
// Past the team's max age: the next due run picks it up (automatic keys only).
due: Boolean(p.automatic && !spec.never && ageDays !== null && ageDays >= maxAge),
// The key's own encrypted instructions override the catalog; only the CLI can read them.
hasEntry: p.vaults.some((v) => entries.has(`${v}\u0000${p.key}`))
};
@ -78,6 +95,8 @@ export async function rotationPlan(teamId, { project, env, keys, vaultFilter = (
const KEY_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
const HOST = /^[A-Za-z0-9._@-]{1,100}$/;
/** A run still open: a due run is not queued again while one of these exists. */
export const OPEN_RUN_STATUSES = ["awaiting-approval", "queued", "running"];
const RESULT_STATUSES = new Set(["rotated", "would-rotate", "todo", "failed", "rolled-back", "skipped", "covered", "needs-login", "busy"]);
export class RotationRunError extends Error {}
@ -139,6 +158,9 @@ export function runRow(r) {
approve: Boolean(Number(r.approve)),
options: parse(r.options, {}),
status: r.status,
due: Boolean(parse(r.options, {}).due),
approvedBy: r.approved_by_email ?? r.approved_by ?? null,
approvedAt: r.approved_at ? Number(r.approved_at) : null,
requestedBy: r.requested_by_email ?? r.requested_by,
claimedBy: r.claimed_by ?? null,
claimedAt: r.claimed_at ? Number(r.claimed_at) : null,

View file

@ -0,0 +1,7 @@
-- Postgres copy of migrations/011_rotation_policy.sql (INTEGER -> bigint). Additive only.
-- 90-day rotation policy: due automatic secrets are queued as one run awaiting
-- owner/admin approval; rotation_auto_approve (paid add-on) skips the click.
ALTER TABLE credshare_teams ADD COLUMN IF NOT EXISTS rotation_max_age_days integer;
ALTER TABLE credshare_teams ADD COLUMN IF NOT EXISTS rotation_auto_approve integer NOT NULL DEFAULT 0;
ALTER TABLE credshare_rotation_runs ADD COLUMN IF NOT EXISTS approved_by text;
ALTER TABLE credshare_rotation_runs ADD COLUMN IF NOT EXISTS approved_at bigint;

View file

@ -0,0 +1,11 @@
-- 90-day rotation policy (Anthony, 2026-10-29).
--
-- Every automatic secret older than the team's max age (NULL = 90 days) is
-- queued as one run that waits for an owner or admin to approve it
-- (status 'awaiting-approval'). rotation_auto_approve is the paid add-on:
-- when 1, due runs are queued already approved and rotate without a click.
-- approved_by / approved_at record who said yes. Additive only.
ALTER TABLE credshare_teams ADD COLUMN rotation_max_age_days INTEGER;
ALTER TABLE credshare_teams ADD COLUMN rotation_auto_approve INTEGER NOT NULL DEFAULT 0;
ALTER TABLE credshare_rotation_runs ADD COLUMN approved_by TEXT;
ALTER TABLE credshare_rotation_runs ADD COLUMN approved_at INTEGER;

View file

@ -6,6 +6,8 @@
// POST /api/credshare/teams/:slug/rotation/runs/:id/claim a runner takes a queued run
// POST /api/credshare/teams/:slug/rotation/runs/:id/result the runner reports per-key outcomes
// POST /api/credshare/teams/:slug/rotation/runs/:id/cancel
// POST /api/credshare/teams/:slug/rotation/due queue every automatic key past the max age (90 days) as ONE run
// POST /api/credshare/teams/:slug/rotation/runs/:id/approve an owner/admin approves an awaiting-approval run
// GET /teams/:slug/rotation the Rotation page
//
// The server only ever holds ciphertext, so it cannot rotate anything itself: a
@ -13,6 +15,12 @@
// `logicsrc teams rotate-keys <team> --from-queue` (the CLI decrypts, mints,
// writes the vaults and redeploys), then reports outcomes, never values.
// Queueing an APPROVED run takes an owner or admin; any member may queue a dry run.
//
// The 90-day policy: /rotation/due (the weekly job calls it) queues the overdue
// automatic keys as a run in 'awaiting-approval'. Nothing rotates until an owner
// or admin approves it here (a person, never a machine key); then the queue
// runner picks it up. A team with rotation_auto_approve (the paid automatic
// rotation add-on) gets its due runs queued already approved.
import { Router } from "express";
import { get, all, run } from "../db.mjs";
import { id } from "../lib/crypto.mjs";
@ -20,7 +28,7 @@ import { page, footer, appBar, esc } from "../lib/html.mjs";
import { requireAuth, csrfInput } from "../lib/session.mjs";
import { keyCoversVault } from "../lib/apikey.mjs";
import { api, requireMember, audit } from "./credshare.mjs";
import { rotationPlan, parseRunRequest, sanitizeResults, runRow, summarize, RotationRunError } from "../lib/rotation.mjs";
import { rotationPlan, parseRunRequest, sanitizeResults, runRow, summarize, RotationRunError, maxAgeDays, DUE_RUN_MAX_KEYS, OPEN_RUN_STATUSES } from "../lib/rotation.mjs";
export const rotationRouter = Router();
@ -29,13 +37,23 @@ const canApprove = (member) => member.role === "owner" || member.role === "admin
async function listRuns(teamId, { status, limit = 50 } = {}) {
const rows = await all(
`SELECT r.*, u.email AS requested_by_email FROM credshare_rotation_runs r LEFT JOIN users u ON u.id = r.requested_by
`SELECT r.*, u.email AS requested_by_email, a.email AS approved_by_email FROM credshare_rotation_runs r
LEFT JOIN users u ON u.id = r.requested_by LEFT JOIN users a ON a.id = r.approved_by
WHERE r.team_id = ?${status ? " AND r.status = ?" : ""} ORDER BY r.created_at DESC LIMIT ?`,
status ? [teamId, status, limit] : [teamId, limit]
);
return rows.map(runRow);
}
/** One run, with the requester's and approver's emails. */
async function runWithEmails(runId) {
return runRow(await get(
`SELECT r.*, u.email AS requested_by_email, a.email AS approved_by_email FROM credshare_rotation_runs r
LEFT JOIN users u ON u.id = r.requested_by LEFT JOIN users a ON a.id = r.approved_by WHERE r.id = ?`,
[runId]
));
}
async function queueRun(team, member, user, body, req) {
const r = parseRunRequest(body);
if (r.approve && !canApprove(member)) throw new RotationRunError("Only a team owner or admin can queue an approved rotation. Queue a dry run instead.");
@ -48,6 +66,61 @@ async function queueRun(team, member, user, body, req) {
return runRow(await get(`SELECT * FROM credshare_rotation_runs WHERE id = ?`, [runId]));
}
/**
* Queue every automatic key past the team's max age as one run. Idempotent: while
* a due run is still open (awaiting approval, queued or running) it is returned
* instead of a second one. Returns { run, created, due } (run null when nothing is due).
*/
export async function queueDueRun(team, user, req, { now = Date.now(), vaultFilter } = {}) {
const maxAge = maxAgeDays(team);
const due = (await rotationPlan(team.id, { maxAge, now, vaultFilter })).filter((p) => p.due);
const open = (await all(
`SELECT * FROM credshare_rotation_runs WHERE team_id = ? AND status IN (${OPEN_RUN_STATUSES.map(() => "?").join(",")}) ORDER BY created_at DESC`,
[team.id, ...OPEN_RUN_STATUSES]
)).map(runRow).find((r) => r.due);
if (open) return { run: open, created: false, due: due.length, maxAgeDays: maxAge };
if (!due.length) return { run: null, created: false, due: 0, maxAgeDays: maxAge };
const keys = [...new Set(due.sort((a, b) => String(a.lastRotated).localeCompare(String(b.lastRotated))).map((p) => p.key))].slice(0, DUE_RUN_MAX_KEYS);
const auto = Boolean(Number(team.rotation_auto_approve));
const runId = id();
await run(
`INSERT INTO credshare_rotation_runs (id, team_id, requested_by, keys, project, env, approve, options, status, approved_at, created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?)`,
[runId, team.id, user.id, JSON.stringify(keys), null, null, 1, JSON.stringify({ propagate: true, due: true, maxAgeDays: maxAge }), auto ? "queued" : "awaiting-approval", auto ? now : null, now]
);
await audit({ req, teamId: team.id, actorUserId: user.id, action: auto ? "rotation.due.auto-approved" : "rotation.due.awaiting-approval", keyName: `${keys.length} keys` });
return { run: runRow(await get(`SELECT * FROM credshare_rotation_runs WHERE id = ?`, [runId])), created: true, due: due.length, maxAgeDays: maxAge };
}
/** Approve an awaiting-approval run: it becomes a queued, approved run. */
async function approveRun(team, member, user, runId, req) {
if (!canApprove(member)) throw new RotationRunError("Only a team owner or admin can approve a rotation.");
const upd = await run(
`UPDATE credshare_rotation_runs SET status = 'queued', approve = 1, approved_by = ?, approved_at = ? WHERE id = ? AND team_id = ? AND status = 'awaiting-approval'`,
[user.id, Date.now(), runId, team.id]
);
if (!Number(upd.rowsAffected)) throw new RotationRunError("That run is not waiting for approval.");
await audit({ req, teamId: team.id, actorUserId: user.id, action: "rotation.approve", keyName: runId });
return runWithEmails(runId);
}
rotationRouter.post("/api/credshare/teams/:slug/rotation/due", api(async (req, res, user, key) => {
const ctx = await requireMember(res, req.params.slug, user.id, key); if (!ctx) return;
// A machine key may ask (the weekly job does); approval stays with a person.
if (!isMachine(key) && !canApprove(ctx.member)) return res.status(403).json({ error: "Only a team owner or admin (or a machine key) can queue the due rotations." });
const out = await queueDueRun(ctx.team, user, req, { vaultFilter: isMachine(key) ? (name) => keyCoversVault(key, name) : undefined });
res.status(out.created ? 201 : 200).json({ ...out, approveUrl: `/teams/${ctx.team.slug}/rotation` });
}, { machine: "write" }));
rotationRouter.post("/api/credshare/teams/:slug/rotation/runs/:id/approve", api(async (req, res, user, key) => {
const ctx = await requireMember(res, req.params.slug, user.id, key); if (!ctx) return;
try {
res.json({ run: await approveRun(ctx.team, ctx.member, user, req.params.id, req) });
} catch (e) {
if (e instanceof RotationRunError) return res.status(409).json({ error: e.message });
throw e;
}
}));
rotationRouter.get("/api/credshare/teams/:slug/rotation", api(async (req, res, user, key) => {
const ctx = await requireMember(res, req.params.slug, user.id, key); if (!ctx) return;
const keys = req.query.key ? String(req.query.key).split(",").filter(Boolean) : undefined;
@ -55,9 +128,10 @@ rotationRouter.get("/api/credshare/teams/:slug/rotation", api(async (req, res, u
project: req.query.project ? String(req.query.project) : undefined,
env: req.query.env ? String(req.query.env) : undefined,
keys,
vaultFilter: isMachine(key) ? (name) => keyCoversVault(key, name) : undefined
vaultFilter: isMachine(key) ? (name) => keyCoversVault(key, name) : undefined,
maxAge: maxAgeDays(ctx.team)
});
res.json({ team: ctx.team.slug, plan, source: "catalog", note: "Computed from key names and fingerprints with the built-in catalog. Encrypted __ROTATE__ entries (hasEntry) can override it: logicsrc teams rotation shows the decrypted spec." });
res.json({ team: ctx.team.slug, maxAgeDays: maxAgeDays(ctx.team), autoApprove: Boolean(Number(ctx.team.rotation_auto_approve)), plan, source: "catalog", note: "Computed from key names and fingerprints with the built-in catalog. Encrypted __ROTATE__ entries (hasEntry) can override it: logicsrc teams rotation shows the decrypted spec." });
}, { machine: "read" }));
rotationRouter.get("/api/credshare/teams/:slug/rotation/runs", api(async (req, res, user, key) => {
@ -111,8 +185,8 @@ rotationRouter.post("/api/credshare/teams/:slug/rotation/runs/:id/cancel", api(a
const ctx = await requireMember(res, req.params.slug, user.id, key); if (!ctx) return;
const r = await teamRun(res, ctx.team.id, req.params.id); if (!r) return;
if (r.requested_by !== user.id && !canApprove(ctx.member)) return res.status(403).json({ error: "Only who queued it, or an owner/admin, can cancel it." });
const upd = await run(`UPDATE credshare_rotation_runs SET status = 'cancelled', finished_at = ? WHERE id = ? AND status = 'queued'`, [Date.now(), r.id]);
if (!Number(upd.rowsAffected)) return res.status(409).json({ error: `Run is ${r.status}: only a queued run can be cancelled.` });
const upd = await run(`UPDATE credshare_rotation_runs SET status = 'cancelled', finished_at = ? WHERE id = ? AND status IN ('queued', 'awaiting-approval')`, [Date.now(), r.id]);
if (!Number(upd.rowsAffected)) return res.status(409).json({ error: `Run is ${r.status}: only a queued or awaiting-approval run can be cancelled.` });
res.json({ ok: true });
}));
@ -147,21 +221,21 @@ function planTable(plan, selectable) {
<td>${pill}</td>
<td class="mono" style="font-size:.78rem">${esc(p.owner ?? "")}</td>
<td>${p.vaultCount}</td>
<td class="mono" style="font-size:.76rem;white-space:nowrap">${esc(String(p.lastRotated).slice(0, 10))}</td>
<td class="mono" style="font-size:.76rem;white-space:nowrap">${esc(String(p.lastRotated).slice(0, 10))}${p.ageDays !== null ? `<div class="faint">${p.ageDays}d${p.due ? ` <span class="pill warn">due</span>` : ""}</div>` : ""}</td>
</tr>`;
};
return `<div class="table-scroll"><table><thead><tr>${selectable ? "<th></th>" : ""}<th>Key</th><th>Method</th><th></th><th>Owner</th><th>Vaults</th><th>Last rotated</th></tr></thead><tbody>${plan.map(row).join("")}</tbody></table></div>`;
}
function runsTable(runs, csrf, slug) {
function runsTable(runs, csrf, slug, approver) {
if (!runs.length) return `<p class="faint mono" style="font-size:.82rem">No runs yet.</p>`;
return `<div class="table-scroll"><table><thead><tr><th>Queued (UTC)</th><th>Keys</th><th>Mode</th><th>Status</th><th>Outcome</th><th></th></tr></thead><tbody>${runs.map((r) => `<tr>
<td class="mono" style="font-size:.76rem;white-space:nowrap">${esc(when(r.createdAt))}<div class="faint">${esc(r.requestedBy ?? "")}</div></td>
<td class="mono" style="font-size:.76rem">${r.keys.slice(0, 6).map(esc).join(", ")}${r.keys.length > 6 ? ` +${r.keys.length - 6}` : ""}</td>
<td class="mono" style="font-size:.76rem">${r.approve ? "approved" : "dry run"}${r.options.desktop ? `, desktop ${esc(r.options.desktop)}` : ""}${r.options.propagate ? ", propagate" : ""}${r.options.allowRoll ? ", allow-roll" : ""}</td>
<td><span class="pill ${r.status === "done" ? "on" : r.status === "failed" ? "warn" : ""}">${esc(r.status)}</span></td>
<td><span class="pill ${r.status === "done" ? "on" : r.status === "failed" || r.status === "awaiting-approval" ? "warn" : ""}">${esc(r.status)}</span>${r.due ? `<div class="faint" style="font-size:.72rem">${esc(String(r.options.maxAgeDays ?? 90))}-day policy</div>` : ""}${r.approvedBy ? `<div class="faint" style="font-size:.72rem">approved by ${esc(r.approvedBy)}</div>` : ""}</td>
<td style="font-size:.8rem">${esc(r.summary ?? "")}${r.results?.length ? `<details><summary class="faint">per key</summary><ul>${r.results.map((x) => `<li><code>${esc(x.key)}</code> ${esc(x.status)}${x.error ? `: ${esc(x.error)}` : x.note ? `: ${esc(x.note)}` : ""}</li>`).join("")}</ul></details>` : ""}</td>
<td>${r.status === "queued" ? `<form method="post" action="/teams/${esc(slug)}/rotation/runs/${esc(r.id)}/cancel" style="margin:0">${csrf}<button class="btn compact">Cancel</button></form>` : ""}</td>
<td>${r.status === "awaiting-approval" && approver ? `<form method="post" action="/teams/${esc(slug)}/rotation/runs/${esc(r.id)}/approve" style="margin:0 0 4px">${csrf}<button class="btn acid compact">Approve</button></form>` : ""}${r.status === "queued" || r.status === "awaiting-approval" ? `<form method="post" action="/teams/${esc(slug)}/rotation/runs/${esc(r.id)}/cancel" style="margin:0">${csrf}<button class="btn compact">${r.status === "awaiting-approval" ? "Decline" : "Cancel"}</button></form>` : ""}</td>
</tr>`).join("")}</tbody></table></div>`;
}
@ -170,11 +244,14 @@ rotationRouter.get("/teams/:slug/rotation", requireAuth, async (req, res, next)
if (!ctx) return next();
const project = req.query.project ? String(req.query.project) : undefined;
const env = req.query.env ? String(req.query.env) : undefined;
const plan = await rotationPlan(ctx.team.id, { project, env });
const maxAge = maxAgeDays(ctx.team);
const autoApprove = Boolean(Number(ctx.team.rotation_auto_approve));
const plan = await rotationPlan(ctx.team.id, { project, env, maxAge });
const due = plan.filter((p) => p.due);
const runs = await listRuns(ctx.team.id, { limit: 25 });
const approver = canApprove(ctx.member);
const slug = ctx.team.slug;
const msg = { queued: "Rotation run queued. A runner picks it up with the command below.", cancelled: "Run cancelled." }[String(req.query.ok || "")];
const msg = { queued: "Rotation run queued. A runner picks it up with the command below.", cancelled: "Run cancelled.", approved: "Approved. The runner rotates it within a few minutes.", due: "Due keys queued as one run.", "none-due": `Nothing is older than ${maxAge} days.` }[String(req.query.ok || "")];
const err = req.query.err ? String(req.query.err).slice(0, 200) : "";
const auto = plan.filter((p) => p.automatic).length;
const body = `${appBar(req)}
@ -183,6 +260,13 @@ rotationRouter.get("/teams/:slug/rotation", requireAuth, async (req, res, next)
${msg ? `<div class="notice ok">${esc(msg)}</div>` : ""}${err ? `<div class="notice err">${esc(err)}</div>` : ""}
<p class="dim" style="font-size:.9rem">How each secret in this team is rotated: ${auto} automatic, ${plan.length - auto} by hand or report-only. Values never reach this server, so a queued run is executed by the CLI or an agent:
<code>logicsrc teams rotate-keys ${esc(slug)} --from-queue [--approve] [--propagate] [--desktop &lt;ssh-host&gt;]</code>. The runner's own <code>--approve</code> is needed for approved runs to write anything. Runbook: <a href="https://logicsrc.com/docs/rotation">logicsrc.com/docs/rotation</a>.</p>
<div class="card" style="margin:12px 0"><div class="card-body" style="font-size:.88rem">
<b>${maxAge}-day policy.</b> ${due.length ? `${due.length} automatic secret${due.length === 1 ? " is" : "s are"} older than ${maxAge} days${due.some((p) => p.disruptive) ? ` (${due.filter((p) => p.disruptive).length} of them: ${esc("rotating signs users out")})` : ""}.` : `Every automatic secret is younger than ${maxAge} days.`}
${autoApprove
? `Automatic rotation is on for this team: due keys rotate without a click.`
: `Due keys are queued as one run that waits for an owner or admin to approve it; nothing rotates before that. <span class="faint">Automatic rotation without the approval step is a paid add-on.</span>`}
${due.length && approver ? `<form method="post" action="/teams/${esc(slug)}/rotation/due" style="margin:8px 0 0">${csrfInput(req)}<button class="btn compact">Queue the ${due.length} due key${due.length === 1 ? "" : "s"} now</button></form>` : ""}
</div></div>
<form method="get" style="display:flex;gap:8px;margin:10px 0"><input name="project" placeholder="project" value="${esc(project ?? "")}"><input name="env" placeholder="env" value="${esc(env ?? "")}"><button class="btn compact">Filter</button></form>
<form method="post" action="/teams/${esc(slug)}/rotation/runs">${csrfInput(req)}
${project ? `<input type="hidden" name="project" value="${esc(project)}">` : ""}${env ? `<input type="hidden" name="env" value="${esc(env)}">` : ""}
@ -196,7 +280,7 @@ rotationRouter.get("/teams/:slug/rotation", requireAuth, async (req, res, next)
</div></div></div>
</form>
<div class="label" style="margin:22px 0 6px">Runs</div>
${runsTable(runs, csrfInput(req), slug)}
${runsTable(runs, csrfInput(req), slug, approver)}
</main>${footer}`;
res.set("Cache-Control", "no-store");
res.type("html").send(page({ title: `LogicSRC ▸ ${slug} rotation`, body }));
@ -221,6 +305,28 @@ rotationRouter.post("/teams/:slug/rotation/runs/:id/cancel", requireAuth, async
const back = `/teams/${encodeURIComponent(ctx.team.slug)}/rotation`;
const r = await get(`SELECT * FROM credshare_rotation_runs WHERE id = ? AND team_id = ?`, [req.params.id, ctx.team.id]);
if (!r || (r.requested_by !== req.user.id && !canApprove(ctx.member))) return res.redirect(`${back}?err=${encodeURIComponent("Not allowed.")}`);
await run(`UPDATE credshare_rotation_runs SET status = 'cancelled', finished_at = ? WHERE id = ? AND status = 'queued'`, [Date.now(), r.id]);
await run(`UPDATE credshare_rotation_runs SET status = 'cancelled', finished_at = ? WHERE id = ? AND status IN ('queued', 'awaiting-approval')`, [Date.now(), r.id]);
res.redirect(`${back}?ok=cancelled`);
});
rotationRouter.post("/teams/:slug/rotation/runs/:id/approve", requireAuth, async (req, res, next) => {
const ctx = await pageContext(req);
if (!ctx) return next();
const back = `/teams/${encodeURIComponent(ctx.team.slug)}/rotation`;
try {
await approveRun(ctx.team, ctx.member, req.user, req.params.id, req);
res.redirect(`${back}?ok=approved`);
} catch (e) {
if (e instanceof RotationRunError) return res.redirect(`${back}?err=${encodeURIComponent(e.message)}`);
throw e;
}
});
rotationRouter.post("/teams/:slug/rotation/due", requireAuth, async (req, res, next) => {
const ctx = await pageContext(req);
if (!ctx) return next();
const back = `/teams/${encodeURIComponent(ctx.team.slug)}/rotation`;
if (!canApprove(ctx.member)) return res.redirect(`${back}?err=${encodeURIComponent("Only a team owner or admin can queue the due rotations.")}`);
const out = await queueDueRun(ctx.team, req.user, req);
res.redirect(`${back}?ok=${out.run ? "due" : "none-due"}`);
});

View file

@ -20,7 +20,7 @@ async function migrate() {
await db.execute("DROP SCHEMA public CASCADE");
await db.execute("CREATE SCHEMA public");
}
for (const file of ["001_auth.sql", "002_credshare.sql", "005_machine_keys.sql", "007_hardening.sql", "010_rotation_runs.sql"]) {
for (const file of ["001_auth.sql", "002_credshare.sql", "005_machine_keys.sql", "007_hardening.sql", "010_rotation_runs.sql", "011_rotation_policy.sql"]) {
const sql = readFileSync(join(here, "..", "src", isPostgres ? "migrations-pg" : "migrations", file), "utf8");
for (const statement of sql.split(/;\s*$/m).map((s) => s.trim()).filter(Boolean)) await db.execute(statement);
}
@ -161,3 +161,99 @@ test("the Rotation page lists the plan with checkboxes, no values, and the runne
assert.ok(!body.includes("CIPHERTEXT"));
assert.ok(!/<script>/.test(body));
});
// ---- 90-day policy ----------------------------------------------------------------------
const DAY = 24 * 60 * 60 * 1000;
async function policyTeam(teamId, slug, { auto = false, maxAge = null } = {}) {
await run(`INSERT INTO credshare_teams (id, slug, name, created_by, created_at, rotation_auto_approve, rotation_max_age_days) VALUES (?,?,?,?,?,?,?)`, [teamId, slug, slug, "u_owner", now, auto ? 1 : 0, maxAge]);
await run(`INSERT INTO credshare_members (id, team_id, user_id, email, role, status, created_at) VALUES (?,?,?,?,?,?,?)`, [`${teamId}-o`, teamId, "u_owner", "owner@example.com", "owner", "active", now]);
await run(`INSERT INTO credshare_members (id, team_id, user_id, email, role, status, created_at) VALUES (?,?,?,?,?,?,?)`, [`${teamId}-m`, teamId, "u_member", "member@example.com", "member", "active", now]);
const vault = `${slug}--prod`;
await run(`INSERT INTO credshare_vaults (id, team_id, name, created_by, created_at) VALUES (?,?,?,?,?)`, [vault, teamId, vault, "u_owner", now]);
const put = (name, fp, ageDays) =>
run(`INSERT INTO credshare_secrets (vault_id, name, nonce, ciphertext, fingerprint, version, updated_by, updated_at) VALUES (?,?,?,?,?,?,?,?)`, [vault, name, "n", "CIPHERTEXT", fp, 1, "u_owner", now - ageDays * DAY]);
await put("CRON_SECRET", `${slug}-cron`, 120); // automatic, overdue
await put("ADMIN_TOKEN", `${slug}-admin`, 91); // automatic, overdue
await put("INTERNAL_API_KEY", `${slug}-int`, 10); // automatic, fresh
await put("STRIPE_SECRET_KEY", `${slug}-stripe`, 400); // never automated, never due
}
await policyTeam("t2", "policy");
await policyTeam("t3", "premium", { auto: true });
await policyTeam("t4", "strict", { maxAge: 5 });
test("policy: keys older than 90 days are due; never-auto keys never are", async (t) => {
const app = await serve("u_member");
t.after(app.close);
const { body } = await app.call("GET", "/api/credshare/teams/policy/rotation");
assert.equal(body.maxAgeDays, 90);
assert.equal(body.autoApprove, false);
const by = Object.fromEntries(body.plan.map((p) => [p.key, p]));
assert.equal(by.CRON_SECRET.due, true);
assert.equal(by.CRON_SECRET.ageDays, 120);
assert.equal(by.ADMIN_TOKEN.due, true);
assert.equal(by.INTERNAL_API_KEY.due, false);
assert.equal(by.STRIPE_SECRET_KEY.due, false);
});
test("policy: due run waits for approval, is not queued twice, and only an owner/admin approves it", async (t) => {
const member = await serve("u_member");
const owner = await serve("u_owner");
t.after(member.close);
t.after(owner.close);
assert.equal((await member.call("POST", "/api/credshare/teams/policy/rotation/due")).status, 403);
const d = await owner.call("POST", "/api/credshare/teams/policy/rotation/due");
assert.equal(d.status, 201);
assert.equal(d.body.run.status, "awaiting-approval");
assert.equal(d.body.run.due, true);
assert.deepEqual(d.body.run.keys, ["CRON_SECRET", "ADMIN_TOKEN"]); // oldest first
assert.deepEqual(d.body.run.options, { propagate: true, due: true, maxAgeDays: 90 });
// Idempotent while it is open.
const again = await owner.call("POST", "/api/credshare/teams/policy/rotation/due");
assert.equal(again.status, 200);
assert.equal(again.body.run.id, d.body.run.id);
// The runner only sees queued runs: nothing to claim before approval.
const queued = await owner.call("GET", "/api/credshare/teams/policy/rotation/runs?status=queued");
assert.equal(queued.body.runs.length, 0);
assert.equal((await owner.call("POST", `/api/credshare/teams/policy/rotation/runs/${d.body.run.id}/claim`)).status, 409);
assert.equal((await member.call("POST", `/api/credshare/teams/policy/rotation/runs/${d.body.run.id}/approve`)).status, 409);
const ok = await owner.call("POST", `/api/credshare/teams/policy/rotation/runs/${d.body.run.id}/approve`);
assert.equal(ok.status, 200);
assert.equal(ok.body.run.status, "queued");
assert.equal(ok.body.run.approve, true);
assert.equal(ok.body.run.approvedBy, "owner@example.com");
assert.equal((await owner.call("POST", `/api/credshare/teams/policy/rotation/runs/${d.body.run.id}/approve`)).status, 409);
});
test("policy: a declined due run can be cancelled", async (t) => {
const owner = await serve("u_owner");
t.after(owner.close);
const d = await owner.call("POST", "/api/credshare/teams/strict/rotation/due");
assert.equal(d.body.maxAgeDays, 5);
assert.deepEqual(d.body.run.keys.sort(), ["ADMIN_TOKEN", "CRON_SECRET", "INTERNAL_API_KEY"]);
assert.equal((await owner.call("POST", `/api/credshare/teams/strict/rotation/runs/${d.body.run.id}/cancel`)).status, 200);
});
test("policy: the paid auto-approve add-on queues due runs already approved", async (t) => {
const owner = await serve("u_owner");
t.after(owner.close);
const d = await owner.call("POST", "/api/credshare/teams/premium/rotation/due");
assert.equal(d.status, 201);
assert.equal(d.body.run.status, "queued");
assert.equal(d.body.run.approve, true);
});
test("policy: the Rotation page shows the 90-day policy, due pills and an Approve button", async (t) => {
const owner = await serve("u_owner");
t.after(owner.close);
await owner.call("POST", "/api/credshare/teams/policy/rotation/due"); // already approved above, so a new one is not created
const { body } = await owner.call("GET", "/teams/policy/rotation");
assert.match(body, /90-day policy/);
assert.match(body, /pill warn">due/);
assert.match(body, /paid add-on/);
const { body: premium } = await owner.call("GET", "/teams/premium/rotation");
assert.match(premium, /Automatic rotation is on/);
const s = await owner.call("POST", "/api/credshare/teams/strict/rotation/due");
const { body: strict } = await owner.call("GET", "/teams/strict/rotation");
assert.match(strict, new RegExp(`/rotation/runs/${s.body.run.id}/approve`));
});