From 15cd8bb3c9f70a57a68e466a2fa593b87f07c64a Mon Sep 17 00:00:00 2001 From: Anthony Ettinger Date: Thu, 29 Oct 2026 04:36:02 +0000 Subject: [PATCH] feat(rotation): 90-day policy, due runs wait for owner approval (CLI 0.16.0) 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: Claude Opus 5.5 --- apps/pwa/src/lib/rotation.mjs | 24 +++- .../src/migrations-pg/011_rotation_policy.sql | 7 + .../src/migrations/011_rotation_policy.sql | 11 ++ apps/pwa/src/routes/rotation.mjs | 134 ++++++++++++++++-- apps/pwa/test/rotation.test.mjs | 98 ++++++++++++- docs/rotation.md | 36 +++++ packages/cli/package.json | 2 +- packages/cli/src/index.ts | 21 ++- packages/cli/src/rotate-keys.ts | 28 ++++ plugins/credential-sharing/src/client.ts | 11 +- scripts/logicsrc-rotate | 59 +++++++- 11 files changed, 407 insertions(+), 24 deletions(-) create mode 100644 apps/pwa/src/migrations-pg/011_rotation_policy.sql create mode 100644 apps/pwa/src/migrations/011_rotation_policy.sql diff --git a/apps/pwa/src/lib/rotation.mjs b/apps/pwa/src/lib/rotation.mjs index 56a9b7c1..00603fb3 100644 --- a/apps/pwa/src/lib/rotation.mjs +++ b/apps/pwa/src/lib/rotation.mjs @@ -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: --. */ 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, diff --git a/apps/pwa/src/migrations-pg/011_rotation_policy.sql b/apps/pwa/src/migrations-pg/011_rotation_policy.sql new file mode 100644 index 00000000..1037e12f --- /dev/null +++ b/apps/pwa/src/migrations-pg/011_rotation_policy.sql @@ -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; diff --git a/apps/pwa/src/migrations/011_rotation_policy.sql b/apps/pwa/src/migrations/011_rotation_policy.sql new file mode 100644 index 00000000..66191037 --- /dev/null +++ b/apps/pwa/src/migrations/011_rotation_policy.sql @@ -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; diff --git a/apps/pwa/src/routes/rotation.mjs b/apps/pwa/src/routes/rotation.mjs index 4f21f39f..fa467c03 100644 --- a/apps/pwa/src/routes/rotation.mjs +++ b/apps/pwa/src/routes/rotation.mjs @@ -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 --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) { ${pill} ${esc(p.owner ?? "")} ${p.vaultCount} - ${esc(String(p.lastRotated).slice(0, 10))} + ${esc(String(p.lastRotated).slice(0, 10))}${p.ageDays !== null ? `
${p.ageDays}d${p.due ? ` due` : ""}
` : ""} `; }; return `
${selectable ? "" : ""}${plan.map(row).join("")}
KeyMethodOwnerVaultsLast rotated
`; } -function runsTable(runs, csrf, slug) { +function runsTable(runs, csrf, slug, approver) { if (!runs.length) return `

No runs yet.

`; return `
${runs.map((r) => ` - + - + `).join("")}
Queued (UTC)KeysModeStatusOutcome
${esc(when(r.createdAt))}
${esc(r.requestedBy ?? "")}
${r.keys.slice(0, 6).map(esc).join(", ")}${r.keys.length > 6 ? ` +${r.keys.length - 6}` : ""} ${r.approve ? "approved" : "dry run"}${r.options.desktop ? `, desktop ${esc(r.options.desktop)}` : ""}${r.options.propagate ? ", propagate" : ""}${r.options.allowRoll ? ", allow-roll" : ""}${esc(r.status)}${esc(r.status)}${r.due ? `
${esc(String(r.options.maxAgeDays ?? 90))}-day policy
` : ""}${r.approvedBy ? `
approved by ${esc(r.approvedBy)}
` : ""}
${esc(r.summary ?? "")}${r.results?.length ? `
per key
    ${r.results.map((x) => `
  • ${esc(x.key)} ${esc(x.status)}${x.error ? `: ${esc(x.error)}` : x.note ? `: ${esc(x.note)}` : ""}
  • `).join("")}
` : ""}
${r.status === "queued" ? `
${csrf}
` : ""}
${r.status === "awaiting-approval" && approver ? `
${csrf}
` : ""}${r.status === "queued" || r.status === "awaiting-approval" ? `
${csrf}
` : ""}
`; } @@ -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 ? `
${esc(msg)}
` : ""}${err ? `
${esc(err)}
` : ""}

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: logicsrc teams rotate-keys ${esc(slug)} --from-queue [--approve] [--propagate] [--desktop <ssh-host>]. The runner's own --approve is needed for approved runs to write anything. Runbook: logicsrc.com/docs/rotation.

+
+ ${maxAge}-day policy. ${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. Automatic rotation without the approval step is a paid add-on.`} + ${due.length && approver ? `
${csrfInput(req)}
` : ""} +
${csrfInput(req)} ${project ? `` : ""}${env ? `` : ""} @@ -196,7 +280,7 @@ rotationRouter.get("/teams/:slug/rotation", requireAuth, async (req, res, next)
Runs
- ${runsTable(runs, csrfInput(req), slug)} + ${runsTable(runs, csrfInput(req), slug, approver)} ${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"}`); +}); diff --git a/apps/pwa/test/rotation.test.mjs b/apps/pwa/test/rotation.test.mjs index 6df95ea3..8b3420cc 100644 --- a/apps/pwa/test/rotation.test.mjs +++ b/apps/pwa/test/rotation.test.mjs @@ -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(!/