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 <noreply@anthropic.com>
This commit is contained in:
Anthony Ettinger 2026-10-29 04:36:02 +00:00
parent 87bbc50423
commit 15cd8bb3c9
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`));
});

View file

@ -107,6 +107,42 @@ Session signers (`SESSION_SECRET`, `AUTH_SECRET`, `NEXTAUTH_SECRET`,
`*_JWT_SECRET`, `SECRET_KEY_BASE`) are `random` but `disruptive`: rotating one
signs every user out, so they rotate on purpose, not weekly.
## The 90-day policy: approve, then it rotates
Every automatic secret has a maximum age, 90 days by default (a team can set
its own). The plan shows each key's age and a `due` flag once it is past it.
1. **Queue.** The weekly job runs `logicsrc teams rotate-keys <team> --queue-due`
(or an owner clicks "Queue the due keys now" on the Rotation page). Every
due key goes into ONE run, oldest first, at most 200 keys, in status
`awaiting-approval`. While that run is open, asking again returns the same run.
2. **Approve.** Nothing rotates until an owner or admin approves it: the
Approve button on `app.logicsrc.com/teams/<team>/rotation`, or
`logicsrc teams rotation-approve <team> <run-id>`. A machine key can queue
the due run but can never approve it. Decline cancels it.
3. **Rotate.** `logicsrc-rotate --queue` runs every 5 minutes on the box. It
picks up approved runs with `--from-queue --propagate --approve`: mint,
write every vault, rewrite and restart consumers 3 at a time, health-check,
revoke the old value, and roll back on any failure. Then it mails what
happened. A typical run finishes a few minutes after the click.
Only automatic keys are ever due. `never` keys (wallets, Stripe, signing) and
manual keys stay on the manual list in the weekly mail.
**Automatic rotation (paid add-on).** A team with `rotation_auto_approve` on
skips step 2: its due runs are queued already approved and rotate on the next
runner tick. It is off for every team by default. It is switched on per team by
us when the add-on is bought; there is no self-serve toggle yet.
```sh
logicsrc teams rotate-keys profullstack --queue-due
logicsrc teams rotation-approve profullstack <run-id>
crontab: */5 * * * * $HOME/.local/bin/logicsrc-rotate --queue
```
API: `POST /api/credshare/teams/:slug/rotation/due` and
`POST /api/credshare/teams/:slug/rotation/runs/:id/approve`.
## Built-in provider rotators
Every rotator is two-phase: create the new credential, switch everything over,

View file

@ -1,6 +1,6 @@
{
"name": "@logicsrc/cli",
"version": "0.15.0",
"version": "0.16.0",
"description": "LogicSRC CLI: every LogicSRC standard and tool as one command.",
"type": "module",
"main": "./dist/index.js",

View file

@ -39,7 +39,7 @@ import { registerKeysCommands } from "./keys.js";
import { registerKeyringCommands } from "./keyring-cmd.js";
import { sshAgentAction, sshListAction, sshPullAction, sshPushAction } from "./ssh.js";
import { credentialsRotateAction } from "./rotate.js";
import { teamsRotateFromQueue, teamsRotateKeysAction, teamsRotationAction, teamsRotationSetAction } from "./rotate-keys.js";
import { teamsQueueDueAction, teamsRotateFromQueue, teamsRotateKeysAction, teamsRotationAction, teamsRotationApproveAction, teamsRotationSetAction } from "./rotate-keys.js";
import { teamsAuditAction, teamsKeyImportAction, teamsRekeyAction, teamsRotateIdentityAction } from "./hardening.js";
import { teamsCleanAction } from "./vault-clean.js";
import { boards, tasks } from "./fixtures.js";
@ -961,6 +961,7 @@ teams
.option("--allow-roll", "let desktop roll recipes run (Cloudflare Global API Key: the old key dies at once; a capture self-test runs first)")
.option("--from-queue", "run the rotations queued on app.logicsrc.com (Rotation page / API / MCP) and report back; approved runs write only with --approve here too")
.option("--max-runs <n>", "with --from-queue: stop after n runs")
.option("--queue-due", "90-day policy: queue every automatic key older than the team's max age as one run awaiting approval")
.option("--format <format>", "table, json, or markdown", "table")
.description("Rotate secret values: automatic ones are minted and written to every vault holding the old value; manual ones come back as steps.")
.addHelpText(
@ -974,6 +975,11 @@ Dry run first, then apply:
logicsrc teams rotate-keys profullstack wx93 prod --key CRON_SECRET --propagate --approve
logicsrc teams rotate-keys profullstack --scheduled --propagate --approve --report r.json (the weekly job)
90-day policy (default max age 90 days): due keys wait for an owner/admin to approve
logicsrc teams rotate-keys profullstack --queue-due queue the overdue keys as one run
logicsrc teams rotation-approve profullstack <run-id> approve it (or the Rotation page)
logicsrc teams rotate-keys profullstack --from-queue --propagate --approve the runner rotates it
Provider rotators (method provider): resend, cloudflare-token, coinpay-api-key,
coinpay-webhook-secret, vapid, postgres-role. Each mints the new credential,
writes the vaults, redeploys consumers, health-checks them, and only then
@ -1007,6 +1013,11 @@ After rotating: redeploy the consumers, install new SSH public keys, revoke the
desktop: options.desktop,
allowRoll: Boolean(options.allowRoll)
};
if (options.queueDue) {
if (project || env || options.key || options.fromQueue) throw new Error("--queue-due covers the whole team; run it alone.");
await teamsQueueDueAction(slug, { format: options.format as OutputFormat });
return;
}
if (options.fromQueue) {
if (project || env || options.key || options.setFromStdin) throw new Error("--from-queue takes its keys, project and env from each queued run.");
const reports = await teamsRotateFromQueue(slug, { ...common, maxRuns: options.maxRuns === undefined ? undefined : Number(options.maxRuns) }, {}, join(homedir(), "www"));
@ -1029,6 +1040,14 @@ After rotating: redeploy the consumers, install new SSH public keys, revoke the
});
});
teams
.command("rotation-approve")
.argument("<slug>", "Team slug")
.argument("<run-id>", "The awaiting-approval run (rotate-keys --queue-due prints it)")
.option("--format <format>", "table, json, or markdown", "table")
.description("Approve a due rotation run (90-day policy): owner or admin only. The queue runner then rotates it.")
.action(async (slug, runId, options) => { await teamsRotationApproveAction(slug, runId, { format: options.format as OutputFormat }); });
teams
.command("clean")
.argument("<slug>", "Team slug")

View file

@ -824,3 +824,31 @@ export async function teamsRotateFromQueue(slug: string, options: FromQueueOptio
}
return reports;
}
/**
* The 90-day policy: ask the app to queue every automatic key older than the
* team's max age as one run. It waits for an owner or admin to approve it on the
* Rotation page (or `teams rotation-approve`), unless the team has the paid
* automatic rotation add-on; then `--from-queue --approve` rotates it.
*/
export async function teamsQueueDueAction(slug: string, options: { format?: OutputFormat } = {}) {
const { client } = authedClient();
const out = await client.queueDueRotation(slug);
if (options.format && options.format !== "table") return print(out, options.format), out;
if (!out.run) console.log(`Nothing in ${slug} is older than ${out.maxAgeDays} days.`);
else {
const verb = out.created ? "Queued" : "Already open";
console.log(`${verb}: run ${out.run.id}, ${out.run.keys.length} key(s) older than ${out.maxAgeDays} days, status ${out.run.status}.`);
if (out.run.status === "awaiting-approval") console.log(`Approve: https://app.logicsrc.com${out.approveUrl} or logicsrc teams rotation-approve ${slug} ${out.run.id}`);
}
return out;
}
/** An owner or admin approves a due run; the queue runner then rotates it. */
export async function teamsRotationApproveAction(slug: string, runId: string, options: { format?: OutputFormat } = {}) {
const { client } = authedClient();
const { run } = await client.approveRotationRun(slug, runId);
if (options.format && options.format !== "table") return print(run, options.format), run;
console.log(`Approved run ${run.id} (${run.keys.length} key(s)): status ${run.status}. The queue runner rotates it next.`);
return run;
}

View file

@ -172,8 +172,10 @@ export interface RemoteRotationRun {
project: string | null;
env: string | null;
approve: boolean;
options: { desktop?: string; propagate?: boolean; allowRoll?: boolean };
options: { desktop?: string; propagate?: boolean; allowRoll?: boolean; due?: boolean; maxAgeDays?: number };
status: string;
due?: boolean;
approvedBy?: string | null;
createdAt: number;
summary: string | null;
}
@ -311,6 +313,13 @@ export class TeamClient {
queueRotationRun(slug: string, body: { keys: string[]; project?: string; env?: string; approve?: boolean; desktop?: string; propagate?: boolean; allowRoll?: boolean }) {
return this.request<{ run: RemoteRotationRun }>("POST", `/teams/${encodeURIComponent(slug)}/rotation/runs`, body);
}
/** Queue every automatic key past the team's max age (90 days by default) as one run awaiting approval. */
queueDueRotation(slug: string) {
return this.request<{ run: RemoteRotationRun | null; created: boolean; due: number; maxAgeDays: number; approveUrl: string }>("POST", `/teams/${encodeURIComponent(slug)}/rotation/due`);
}
approveRotationRun(slug: string, id: string) {
return this.request<{ run: RemoteRotationRun }>("POST", `/teams/${encodeURIComponent(slug)}/rotation/runs/${encodeURIComponent(id)}/approve`);
}
claimRotationRun(slug: string, id: string) {
return this.request<{ run: RemoteRotationRun }>("POST", `/teams/${encodeURIComponent(slug)}/rotation/runs/${encodeURIComponent(id)}/claim`);
}

View file

@ -5,6 +5,13 @@
# logicsrc-rotate run per the config (dry run unless LOGICSRC_ROTATE_LIVE=1)
# logicsrc-rotate --dry-run plan + report only, whatever the config says
# logicsrc-rotate --no-mail print the report instead of mailing it
# logicsrc-rotate --queue run the APPROVED queued runs now (a */5 cron), mail only if one ran
#
# 90-day policy: every weekly run first queues the automatic keys older than the
# team's max age (90 days) as one run awaiting approval, and the mail links to
# the Rotation page. An owner/admin clicks Approve; the --queue cron rotates it
# within five minutes (3 sites at a time, health-checked, rolled back on failure).
# Teams with the paid automatic rotation add-on skip the click.
#
# Rotates only what `rotate-keys --scheduled` allows unattended (non-disruptive
# random secrets and overlapping provider rotators with known, healthy
@ -45,11 +52,13 @@ MAX_SITES="${LOGICSRC_ROTATE_MAX_SITES:-5}"
# Client sites are never part of a fleet sweep.
EXCLUDE="${LOGICSRC_ROTATE_EXCLUDE:-tomahawkedison.com}"
MAIL=1
QUEUE=0
for a in "$@"; do
case "$a" in
--dry-run) LIVE=0 ;;
--queue) QUEUE=1 ;;
--no-mail) MAIL=0 ;;
-h|--help) sed -n 2,25p "$0"; exit 0 ;;
-h|--help) sed -n 2,33p "$0"; exit 0 ;;
*) echo "unknown option $a" >&2; exit 2 ;;
esac
done
@ -69,6 +78,36 @@ if [ "$LIVE" = 1 ] && [ "$avail_gb" -lt 6 ]; then
LIVE=0
fi
if [ "$QUEUE" = 1 ]; then
# Low memory: leave approved runs queued for the next tick instead of restarting sites now.
[ "$avail_gb" -lt 6 ] && { echo "only ${avail_gb} GB available: approved runs wait for the next tick" >&2; exit 0; }
# Only runs an owner/admin approved in the app (or the paid auto-approve add-on queued) write anything.
QREPORT="$STATE/queue-$STAMP.json"
logicsrc teams rotate-keys "$TEAM" --from-queue --propagate "$ROOT" --approve --exclude-site "$EXCLUDE" --report "$QREPORT" --format json >/dev/null 2>"$STATE/queue-$STAMP.err" || status=$?
status="${status:-0}"
if [ -f "$QREPORT" ] && node -e 'process.exit(require(process.argv[1]).runs.length ? 0 : 1)' "$QREPORT"; then
QBODY="$STATE/queue-mail-$STAMP.txt"
node - "$QREPORT" >"$QBODY" <<'NODE'
const r = require(process.argv[2]);
const out = [`Approved rotation run(s) for team ${r.team}, ${r.at}`, ""];
for (const run of r.runs) {
out.push(`Run ${run.id}: ${run.status} (${run.ran}), ${run.keys.length} key(s): ${run.summary}`);
for (const x of run.results) out.push(` ${x.key} ${x.status}${x.sites && x.sites.length ? ` sites: ${[...new Set(x.sites.map((s) => s.site))].join(" ")}` : ""}${x.error ? ` ${x.error}` : ""}`);
}
console.log(out.join("\n"));
NODE
QSUBJECT="logicsrc rotation: approved run $(node -e 'const r=require(process.argv[1]);console.log(r.runs.map(x=>x.status).join(", "))' "$QREPORT")"
if [ "$MAIL" = 1 ]; then env -u RESEND_API_KEY mail send --via resend --to "$TO" --subject "$QSUBJECT" --file "$QBODY"; else cat "$QBODY"; fi
else
rm -f "$QREPORT" "$STATE/queue-$STAMP.err"
fi
exit "${status:-0}"
fi
# 90-day policy: queue the overdue automatic keys as one run awaiting approval (never rotates by itself).
DUE="$STATE/due-$STAMP.json"
logicsrc teams rotate-keys "$TEAM" --queue-due --format json >"$DUE" 2>>"$STATE/run-$STAMP.err" || echo '{}' >"$DUE"
args=(teams rotate-keys "$TEAM" --scheduled --propagate "$ROOT" --max "$MAX" --max-sites "$MAX_SITES" --exclude-site "$EXCLUDE" --report "$REPORT" --format json)
[ "$LIVE" = 1 ] && args+=(--approve)
status=0
@ -76,9 +115,19 @@ logicsrc "${args[@]}" >/dev/null 2>"$STATE/run-$STAMP.err" || status=$?
# stderr holds vault names and counts only; keep it for the report.
BODY="$STATE/mail-$STAMP.txt"
node - "$REPORT" "$LIVE" "$status" "$STATE/run-$STAMP.err" >"$BODY" <<'NODE'
node - "$REPORT" "$LIVE" "$status" "$STATE/run-$STAMP.err" "$DUE" "$TEAM" >"$BODY" <<'NODE'
const fs = require("fs");
const [file, live, status, errFile] = process.argv.slice(2);
const [file, live, status, errFile, dueFile, team] = process.argv.slice(2);
let due = {};
try { due = JSON.parse(fs.readFileSync(dueFile, "utf8")); } catch {}
const dueLines = [];
if (due.run) {
dueLines.push(`${due.maxAgeDays}-DAY POLICY: ${due.run.keys.length} automatic key(s) older than ${due.maxAgeDays} days, run ${due.run.id} is ${due.run.status}.`);
if (due.run.status === "awaiting-approval") dueLines.push(` Approve it: https://app.logicsrc.com/teams/${team}/rotation (it rotates within 5 minutes of the click)`);
dueLines.push("");
} else if (due.maxAgeDays) {
dueLines.push(`${due.maxAgeDays}-DAY POLICY: nothing is older than ${due.maxAgeDays} days.`, "");
}
let report;
try {
report = JSON.parse(fs.readFileSync(file, "utf8"));
@ -89,7 +138,7 @@ try {
}
const R = report.results;
const by = (s) => R.filter((r) => r.status === s);
const out = [];
const out = [...dueLines];
const line = (s = "") => out.push(s);
const where = (r) => `${(r.vaults || []).length} vault(s)${r.sites && r.sites.length ? `, sites: ${[...new Set(r.sites.map((s) => s.site))].join(" ")}` : ""}`;
line(`Secret rotation ${live === "1" ? "LIVE run" : "DRY RUN (nothing changed)"} for team ${report.team}, ${report.at}`);
@ -177,5 +226,5 @@ else
cat "$BODY"
fi
# Keep 12 weeks of reports.
find "$STATE" -maxdepth 1 -type f \( -name 'report-*.json' -o -name 'mail-*.txt' -o -name 'run-*.err' \) -mtime +84 -delete
find "$STATE" -maxdepth 1 -type f \( -name 'report-*.json' -o -name 'mail-*.txt' -o -name 'run-*.err' -o -name 'due-*.json' -o -name 'queue-*' \) -mtime +84 -delete
exit "$status"