diff --git a/apps/pwa/package.json b/apps/pwa/package.json index 91ac69ff..c33fa1dd 100644 --- a/apps/pwa/package.json +++ b/apps/pwa/package.json @@ -3,7 +3,7 @@ "version": "0.1.1", "private": true, "type": "module", - "description": "LogicSRC credentials — Express app on Postgres (@profullstack/libsql-pg): auth + end-to-end-encrypted team credential sharing.", + "description": "LogicSRC credentials \u2014 Express app on Postgres (@profullstack/libsql-pg): auth + end-to-end-encrypted team credential sharing.", "scripts": { "start": "bun src/server.mjs", "dev": "bun --watch src/server.mjs", @@ -11,6 +11,7 @@ "test": "node --test" }, "dependencies": { + "@logicsrc/cli": "workspace:*", "@profullstack/footer": "0.5.0", "@profullstack/libsql-pg": "^0.1.4", "@profullstack/profile": "0.1.6", diff --git a/apps/pwa/src/lib/rotation.mjs b/apps/pwa/src/lib/rotation.mjs new file mode 100644 index 00000000..56a9b7c1 --- /dev/null +++ b/apps/pwa/src/lib/rotation.mjs @@ -0,0 +1,157 @@ +// Key rotation: the plan per key and the run queue, for the Rotation page, the +// API and the MCP tools. +// +// The server never sees a value (E2E rule). The plan is computed from what it +// does see: key names, value fingerprints and update times, matched against the +// same built-in catalog the CLI uses (@logicsrc/cli's rotation-catalog). A key's +// own `__ROTATE__` entry is encrypted, so the page can only say that one +// exists; the CLI, which can decrypt it, is the authority on what it says. +import { all } from "../db.mjs"; +import { planRotations, isoTime } from "@logicsrc/cli/dist/rotation-catalog.js"; +import { DESKTOP_RECIPES } from "@logicsrc/cli/dist/desktop-recipes.js"; + +const ROTATE_PREFIX = "__ROTATE__"; + +/** Vault names split the way the CLI does: --. */ +export function splitVaultName(name) { + const i = String(name).lastIndexOf("--"); + return i > 0 ? { project: name.slice(0, i), env: name.slice(i + 2) } : { project: name, env: "" }; +} + +/** + * The rotation plan for a team: one row per distinct (key, value), like + * `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 } = {}) { + 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 + WHERE v.team_id = ?`, + [teamId] + )).filter((r) => vaultFilter(r.vault)); + const entries = new Set(rows.filter((r) => r.key.startsWith(ROTATE_PREFIX)).map((r) => `${r.vault}\u0000${r.key.slice(ROTATE_PREFIX.length)}`)); + // Every vault:key per fingerprint across the team (a value pasted under other names counts). + const byFp = new Map(); + for (const r of rows) { + if (r.key.startsWith(ROTATE_PREFIX)) continue; + byFp.set(r.fingerprint, [...(byFp.get(r.fingerprint) ?? []), `${r.vault}:${r.key}`]); + } + const inFilter = (vault) => { + const p = splitVaultName(vault); + return (!project || p.project === project) && (!env || p.env === env); + }; + const wanted = keys?.length ? new Set(keys.map((k) => String(k).toUpperCase())) : null; + const plan = planRotations( + rows.filter((r) => inFilter(r.vault)).map((r) => ({ vault: r.vault, key: r.key, fingerprint: r.fingerprint, updatedAt: Number(r.updated_at) })), + new Map() + ).filter((p) => !wanted || wanted.has(p.key.toUpperCase())); + return plan.map((p) => { + const spec = p.spec ?? {}; + const recipe = spec.method === "desktop" ? DESKTOP_RECIPES[spec.recipe] : null; + const everywhere = byFp.get(p.fingerprint) ?? []; + return { + key: p.key, + method: p.method, + ...(spec.provider ? { provider: spec.provider } : {}), + ...(recipe ? { recipe: recipe.id, desktopMode: recipe.mode } : {}), + automatic: p.automatic, + owner: spec.owner ?? null, + family: spec.family ?? null, + url: spec.url ?? null, + steps: spec.steps ?? [], + consumers: spec.consumers ?? [], + disruptive: spec.disruptive ?? null, + never: Boolean(spec.never), + note: spec.note ?? null, + vaults: p.vaults, + vaultCount: everywhere.length || p.vaults.length, + alsoIn: everywhere.filter((vk) => !p.vaults.some((v) => vk === `${v}:${p.key}`)), + lastRotated: isoTime(p.oldestUpdate), + // 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}`)) + }; + }); +} + +// ---- runs ------------------------------------------------------------------------------ + +const KEY_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/; +const HOST = /^[A-Za-z0-9._@-]{1,100}$/; +const RESULT_STATUSES = new Set(["rotated", "would-rotate", "todo", "failed", "rolled-back", "skipped", "covered", "needs-login", "busy"]); + +export class RotationRunError extends Error {} + +/** Validate a queue request. Throws RotationRunError with a message for the caller. */ +export function parseRunRequest(body = {}) { + const keys = [...new Set((Array.isArray(body.keys) ? body.keys : String(body.keys ?? "").split(/[\s,]+/)).map((k) => String(k).trim()).filter(Boolean))]; + if (!keys.length) throw new RotationRunError("Pick at least one key to rotate."); + if (keys.length > 200) throw new RotationRunError("At most 200 keys per run."); + const bad = keys.find((k) => !KEY_NAME.test(k)); + if (bad) throw new RotationRunError(`Not a key name: ${bad.slice(0, 60)}`); + const desktop = body.desktop ? String(body.desktop).trim() : ""; + if (desktop && !HOST.test(desktop)) throw new RotationRunError("desktop must be an ssh host alias"); + const name = (v) => (v ? String(v).trim() : "") || null; + const project = name(body.project); + const env = name(body.env); + for (const v of [project, env]) if (v && !/^[a-z0-9][a-z0-9-]{0,62}$/.test(v)) throw new RotationRunError(`Bad project/env name: ${v.slice(0, 60)}`); + const truthy = (v) => v === true || v === "1" || v === "on" || v === "true"; + return { + keys, + project, + env, + approve: truthy(body.approve), + options: { + ...(desktop ? { desktop } : {}), + ...(truthy(body.propagate) ? { propagate: true } : {}), + ...(truthy(body.allowRoll) ? { allowRoll: true } : {}) + } + }; +} + +/** + * Keep only the fields a runner may report, so a buggy or hostile runner cannot + * park arbitrary text (or a value) in the database: statuses, names, short notes. + */ +export function sanitizeResults(results) { + if (!Array.isArray(results)) return []; + const str = (v, n = 300) => (typeof v === "string" ? v.slice(0, n) : undefined); + const names = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === "string").slice(0, 100).map((x) => x.slice(0, 200)) : undefined); + return results.slice(0, 500).map((r) => ({ + key: str(r?.key, 128) ?? "?", + method: str(r?.method, 64), + status: RESULT_STATUSES.has(r?.status) ? r.status : "failed", + vaults: names(r?.vaults), + written: names(r?.written), + sites: Array.isArray(r?.sites) ? r.sites.slice(0, 50).map((s) => ({ site: str(s?.site, 120), ok: typeof s?.ok === "boolean" ? s.ok : undefined, health: str(s?.health, 120) })) : undefined, + note: str(r?.note), + error: str(r?.error) + })); +} + +export function runRow(r) { + const parse = (s, d) => { try { return s ? JSON.parse(s) : d; } catch { return d; } }; + return { + id: r.id, + keys: parse(r.keys, []), + project: r.project ?? null, + env: r.env ?? null, + approve: Boolean(Number(r.approve)), + options: parse(r.options, {}), + status: r.status, + requestedBy: r.requested_by_email ?? r.requested_by, + claimedBy: r.claimed_by ?? null, + claimedAt: r.claimed_at ? Number(r.claimed_at) : null, + finishedAt: r.finished_at ? Number(r.finished_at) : null, + createdAt: Number(r.created_at), + summary: r.summary ?? null, + results: parse(r.results, null) + }; +} + +/** "3 rotated, 1 todo" from a result list. */ +export function summarize(results) { + const counts = {}; + for (const r of results) counts[r.status] = (counts[r.status] ?? 0) + 1; + return Object.entries(counts).map(([k, n]) => `${n} ${k}`).join(", ") || "nothing"; +} diff --git a/apps/pwa/src/migrations-pg/010_rotation_runs.sql b/apps/pwa/src/migrations-pg/010_rotation_runs.sql new file mode 100644 index 00000000..55e8dec2 --- /dev/null +++ b/apps/pwa/src/migrations-pg/010_rotation_runs.sql @@ -0,0 +1,26 @@ +-- Postgres copy of migrations/010_rotation_runs.sql (INTEGER -> bigint). Additive only. +-- Key rotation runs queued from the Rotation page (or the API / MCP) and +-- executed by a CLI or agent with `logicsrc teams rotate-keys --from-queue`. +-- +-- The server never sees a secret value (E2E rule): a run records WHICH keys to +-- rotate and how (dry run or approved, desktop host, propagate), and later the +-- runner's per-key outcome (statuses, vault and site names, errors), never a +-- value. Additive only. +CREATE TABLE IF NOT EXISTS credshare_rotation_runs ( + id TEXT PRIMARY KEY, + team_id TEXT NOT NULL REFERENCES credshare_teams(id) ON DELETE CASCADE, + requested_by TEXT NOT NULL REFERENCES users(id), + keys TEXT NOT NULL, -- JSON array of key names + project TEXT, + env TEXT, + approve bigint NOT NULL DEFAULT 0, -- 0 = dry run + options TEXT, -- JSON: { desktop?, propagate?, allowRoll? } + status TEXT NOT NULL DEFAULT 'queued', -- queued | running | done | failed | cancelled + claimed_by TEXT, -- api key id or user id of the runner + claimed_at bigint, + finished_at bigint, + summary TEXT, + results TEXT, -- JSON array of per-key results (never values) + created_at bigint NOT NULL +); +CREATE INDEX IF NOT EXISTS idx_rotation_runs_team ON credshare_rotation_runs(team_id, status, created_at); diff --git a/apps/pwa/src/migrations/010_rotation_runs.sql b/apps/pwa/src/migrations/010_rotation_runs.sql new file mode 100644 index 00000000..2be6cf95 --- /dev/null +++ b/apps/pwa/src/migrations/010_rotation_runs.sql @@ -0,0 +1,25 @@ +-- Key rotation runs queued from the Rotation page (or the API / MCP) and +-- executed by a CLI or agent with `logicsrc teams rotate-keys --from-queue`. +-- +-- The server never sees a secret value (E2E rule): a run records WHICH keys to +-- rotate and how (dry run or approved, desktop host, propagate), and later the +-- runner's per-key outcome (statuses, vault and site names, errors), never a +-- value. Additive only. +CREATE TABLE IF NOT EXISTS credshare_rotation_runs ( + id TEXT PRIMARY KEY, + team_id TEXT NOT NULL REFERENCES credshare_teams(id) ON DELETE CASCADE, + requested_by TEXT NOT NULL REFERENCES users(id), + keys TEXT NOT NULL, -- JSON array of key names + project TEXT, + env TEXT, + approve INTEGER NOT NULL DEFAULT 0, -- 0 = dry run + options TEXT, -- JSON: { desktop?, propagate?, allowRoll? } + status TEXT NOT NULL DEFAULT 'queued', -- queued | running | done | failed | cancelled + claimed_by TEXT, -- api key id or user id of the runner + claimed_at INTEGER, + finished_at INTEGER, + summary TEXT, + results TEXT, -- JSON array of per-key results (never values) + created_at INTEGER NOT NULL +); +CREATE INDEX IF NOT EXISTS idx_rotation_runs_team ON credshare_rotation_runs(team_id, status, created_at); diff --git a/apps/pwa/src/routes/credshare.mjs b/apps/pwa/src/routes/credshare.mjs index 6e9d4605..74ee2364 100644 --- a/apps/pwa/src/routes/credshare.mjs +++ b/apps/pwa/src/routes/credshare.mjs @@ -50,7 +50,7 @@ async function actor(req) { * "write" allowed unless the key is read-only * "register" allowed even for a read-only key (its own public key) */ -function api(handler, { machine = false } = {}) { +export function api(handler, { machine = false } = {}) { return async (req, res) => { const found = await actor(req); if (!found) return res.status(401).json({ error: "Not authenticated, or the API key is revoked or expired. Run: logicsrc login" }); @@ -73,7 +73,7 @@ function api(handler, { machine = false } = {}) { }; } -async function requireMember(res, slug, userId, key = null) { +export async function requireMember(res, slug, userId, key = null) { const team = await get(`SELECT * FROM credshare_teams WHERE slug = ?`, [slug]); if (!team) { res.status(404).json({ error: `Unknown team: ${slug}` }); return null; } if (isMachine(key) && key.team_id !== team.id) { res.status(403).json({ error: "This API key is scoped to another team." }); return null; } @@ -96,7 +96,7 @@ function auditStatement(ev) { }; } -async function audit(ev) { +export async function audit(ev) { const st = auditStatement(ev); await run(st.sql, st.args); } diff --git a/apps/pwa/src/routes/pages.mjs b/apps/pwa/src/routes/pages.mjs index 4305a819..48142915 100644 --- a/apps/pwa/src/routes/pages.mjs +++ b/apps/pwa/src/routes/pages.mjs @@ -69,7 +69,7 @@ async function teamCard(team, uid) { ${me.role === "owner" ? `` : ``} ` : ""} -
Vaults
+ ${vaults.length ? `${vaultRows.join("")}
VaultSecretsYour access
` : `

No vaults yet — create one from the CLI: logicsrc teams push ${esc(team.slug)} <project> <env>

`}
Recent access (full trail: logicsrc teams audit ${esc(team.slug)})
diff --git a/apps/pwa/src/routes/rotation.mjs b/apps/pwa/src/routes/rotation.mjs new file mode 100644 index 00000000..4f21f39f --- /dev/null +++ b/apps/pwa/src/routes/rotation.mjs @@ -0,0 +1,226 @@ +// Key rotation: the plan per key, and a queue of rotation runs. +// +// GET /api/credshare/teams/:slug/rotation the plan (never values) +// GET /api/credshare/teams/:slug/rotation/runs queued / past runs (?status=queued) +// POST /api/credshare/teams/:slug/rotation/runs queue a run {keys, project?, env?, approve?, desktop?, propagate?, allowRoll?} +// 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 +// GET /teams/:slug/rotation the Rotation page +// +// The server only ever holds ciphertext, so it cannot rotate anything itself: a +// run is a request that a CLI or agent executes with +// `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. +import { Router } from "express"; +import { get, all, run } from "../db.mjs"; +import { id } from "../lib/crypto.mjs"; +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"; + +export const rotationRouter = Router(); + +const isMachine = (key) => key?.kind === "machine"; +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 + 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); +} + +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."); + const runId = id(); + await run( + `INSERT INTO credshare_rotation_runs (id, team_id, requested_by, keys, project, env, approve, options, status, created_at) VALUES (?,?,?,?,?,?,?,?,?,?)`, + [runId, team.id, user.id, JSON.stringify(r.keys), r.project, r.env, r.approve ? 1 : 0, JSON.stringify(r.options), "queued", Date.now()] + ); + await audit({ req, teamId: team.id, actorUserId: user.id, action: r.approve ? "rotation.queue.approve" : "rotation.queue.dry-run", keyName: r.keys.slice(0, 5).join(",") + (r.keys.length > 5 ? ",..." : "") }); + return runRow(await get(`SELECT * FROM credshare_rotation_runs WHERE id = ?`, [runId])); +} + +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; + const plan = await rotationPlan(ctx.team.id, { + 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 + }); + 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." }); +}, { machine: "read" })); + +rotationRouter.get("/api/credshare/teams/:slug/rotation/runs", api(async (req, res, user, key) => { + const ctx = await requireMember(res, req.params.slug, user.id, key); if (!ctx) return; + const status = req.query.status ? String(req.query.status) : undefined; + res.json({ runs: await listRuns(ctx.team.id, { status, limit: Math.min(Number(req.query.limit) || 50, 200) }) }); +}, { machine: "read" })); + +rotationRouter.post("/api/credshare/teams/:slug/rotation/runs", api(async (req, res, user, key) => { + const ctx = await requireMember(res, req.params.slug, user.id, key); if (!ctx) return; + try { + res.status(201).json({ run: await queueRun(ctx.team, ctx.member, user, req.body ?? {}, req) }); + } catch (e) { + if (e instanceof RotationRunError) return res.status(400).json({ error: e.message }); + throw e; + } +})); + +/** Load a run of this team, or answer 404. */ +async function teamRun(res, teamId, runId) { + const r = await get(`SELECT * FROM credshare_rotation_runs WHERE id = ? AND team_id = ?`, [runId, teamId]); + if (!r) res.status(404).json({ error: "No such rotation run." }); + return r; +} + +rotationRouter.post("/api/credshare/teams/:slug/rotation/runs/:id/claim", api(async (req, res, user, key) => { + 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; + // Atomic: only one runner wins a queued run. + const claimer = key?.id ?? user.id; + const upd = await run(`UPDATE credshare_rotation_runs SET status = 'running', claimed_by = ?, claimed_at = ? WHERE id = ? AND status = 'queued'`, [claimer, Date.now(), r.id]); + if (!Number(upd.rowsAffected)) return res.status(409).json({ error: `Run is ${r.status}, not queued.` }); + await audit({ req, teamId: ctx.team.id, actorUserId: user.id, action: "rotation.claim", keyName: r.id }); + res.json({ run: runRow(await get(`SELECT * FROM credshare_rotation_runs WHERE id = ?`, [r.id])) }); +}, { machine: "write" })); + +rotationRouter.post("/api/credshare/teams/:slug/rotation/runs/:id/result", api(async (req, res, user, key) => { + 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; + const claimer = key?.id ?? user.id; + if (r.status !== "running" || r.claimed_by !== claimer) return res.status(409).json({ error: "Only the runner that claimed this run can report it." }); + const results = sanitizeResults(req.body?.results); + const failed = req.body?.status === "failed" || results.some((x) => x.status === "failed" || x.status === "rolled-back"); + const summary = (typeof req.body?.error === "string" ? `${req.body.error.slice(0, 300)}; ` : "") + summarize(results); + await run(`UPDATE credshare_rotation_runs SET status = ?, finished_at = ?, results = ?, summary = ? WHERE id = ?`, [failed ? "failed" : "done", Date.now(), JSON.stringify(results), summary, r.id]); + await audit({ req, teamId: ctx.team.id, actorUserId: user.id, action: "rotation.result", keyName: r.id }); + res.json({ run: runRow(await get(`SELECT * FROM credshare_rotation_runs WHERE id = ?`, [r.id])) }); +}, { machine: "write" })); + +rotationRouter.post("/api/credshare/teams/:slug/rotation/runs/:id/cancel", api(async (req, res, user, key) => { + 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.` }); + res.json({ ok: true }); +})); + +// ---- the page -------------------------------------------------------------------------- + +async function pageContext(req) { + const team = await get(`SELECT * FROM credshare_teams WHERE slug = ?`, [req.params.slug]); + const member = team && await get(`SELECT * FROM credshare_members WHERE team_id = ? AND user_id = ? AND status = 'active'`, [team.id, req.user.id]); + return team && member ? { team, member } : null; +} + +const when = (ms) => (ms ? new Date(Number(ms)).toISOString().slice(0, 16).replace("T", " ") : ""); + +function planTable(plan, selectable) { + if (!plan.length) return `

No secrets to rotate in this filter.

`; + const row = (p) => { + const how = p.method === "desktop" ? `desktop: ${p.recipe}${p.desktopMode && p.desktopMode !== "two-phase" ? ` (${p.desktopMode})` : ""}` : p.method === "provider" ? `provider: ${p.provider}` : p.method; + const pill = p.never ? `never auto` : p.automatic ? `auto` : `manual`; + const details = [ + p.note ? `

${esc(p.note)}

` : "", + p.disruptive ? `

Breaks: ${esc(p.disruptive)}

` : "", + p.url ? `

${esc(p.url)}

` : "", + p.steps.length ? `
    ${p.steps.map((s) => `
  1. ${esc(s)}
  2. `).join("")}
` : "", + p.consumers.length ? `

Consumers: ${p.consumers.map(esc).join(", ")}

` : "", + `

Vaults: ${p.vaults.map(esc).join(", ")}${p.alsoIn.length ? `; same value also in ${p.alsoIn.map(esc).join(", ")}` : ""}

`, + p.hasEntry ? `

Has its own encrypted rotation entry: logicsrc teams rotation shows it.

` : "" + ].join(""); + return ` + ${selectable ? `` : ""} +
${esc(p.key)}
${details}
+ ${esc(how)} + ${pill} + ${esc(p.owner ?? "")} + ${p.vaultCount} + ${esc(String(p.lastRotated).slice(0, 10))} + `; + }; + return `
${selectable ? "" : ""}${plan.map(row).join("")}
KeyMethodOwnerVaultsLast rotated
`; +} + +function runsTable(runs, csrf, slug) { + 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.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}
` : ""}
`; +} + +rotationRouter.get("/teams/:slug/rotation", requireAuth, async (req, res, next) => { + const ctx = await pageContext(req); + 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 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 err = req.query.err ? String(req.query.err).slice(0, 200) : ""; + const auto = plan.filter((p) => p.automatic).length; + const body = `${appBar(req)} +
+

Rotation /${esc(slug)}

${plan.length}
+ ${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.

+
+
${csrfInput(req)} + ${project ? `` : ""}${env ? `` : ""} +
${planTable(plan, true)} +
+ + + + + +
+
+
Runs
+ ${runsTable(runs, csrfInput(req), slug)} +
${footer}`; + res.set("Cache-Control", "no-store"); + res.type("html").send(page({ title: `LogicSRC ▸ ${slug} rotation`, body })); +}); + +rotationRouter.post("/teams/:slug/rotation/runs", requireAuth, async (req, res, next) => { + const ctx = await pageContext(req); + if (!ctx) return next(); + const back = `/teams/${encodeURIComponent(ctx.team.slug)}/rotation`; + try { + await queueRun(ctx.team, ctx.member, req.user, req.body ?? {}, req); + res.redirect(`${back}?ok=queued`); + } catch (e) { + if (e instanceof RotationRunError) return res.redirect(`${back}?err=${encodeURIComponent(e.message)}`); + throw e; + } +}); + +rotationRouter.post("/teams/:slug/rotation/runs/:id/cancel", requireAuth, async (req, res, next) => { + const ctx = await pageContext(req); + if (!ctx) return next(); + 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]); + res.redirect(`${back}?ok=cancelled`); +}); diff --git a/apps/pwa/src/server.mjs b/apps/pwa/src/server.mjs index dd8b838d..6ca5b224 100644 --- a/apps/pwa/src/server.mjs +++ b/apps/pwa/src/server.mjs @@ -10,6 +10,7 @@ import { authRouter } from "./routes/auth.mjs"; import { passkeyRouter } from "./routes/passkey.mjs"; import { coinpayRouter } from "./routes/coinpay.mjs"; import { credshareRouter } from "./routes/credshare.mjs"; +import { rotationRouter } from "./routes/rotation.mjs"; import { apiKeysRouter } from "./routes/apikeys.mjs"; import { opencredsRouter } from "./routes/opencreds.mjs"; import { keyringRouter } from "./routes/keyring.mjs"; @@ -79,6 +80,7 @@ app.use(authRouter); // GET / (+ /auth/login|register|logout) app.use(passkeyRouter); app.use(coinpayRouter); app.use(credshareRouter); // /api/credshare/* (session or lsk_ Bearer) +app.use(rotationRouter); // /api/credshare/teams/:slug/rotation* + /teams/:slug/rotation (plan + run queue, never values) app.use(apiKeysRouter); // /api/keys (session or a person's lsk_ key; never a machine key) app.use(opencredsRouter); // /api/opencreds/* — personal vault sync (session or lsk_ Bearer) app.use(keyringShareRouter); // /api/keyring/share: the public-keys share link (session or person key) diff --git a/apps/pwa/test/rotation.test.mjs b/apps/pwa/test/rotation.test.mjs new file mode 100644 index 00000000..6df95ea3 --- /dev/null +++ b/apps/pwa/test/rotation.test.mjs @@ -0,0 +1,163 @@ +// Rotation plan + run queue (routes/rotation.mjs). The server holds only names, +// fingerprints and ciphertext: these tests check the plan comes from those, that +// a run carries no values, and who may queue, claim, report and cancel. +process.env.DATABASE_URL = process.env.PWA_TEST_DATABASE_URL || ":memory:"; + +import test from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import { dirname, join } from "node:path"; +import express from "express"; + +const here = dirname(fileURLToPath(import.meta.url)); +const { db, run, isPostgres } = await import("../src/db.mjs"); +const { rotationRouter } = await import("../src/routes/rotation.mjs"); +const { parseRunRequest, sanitizeResults } = await import("../src/lib/rotation.mjs"); + +async function migrate() { + if (isPostgres) { + 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"]) { + 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); + } +} + +async function serve(userId) { + const app = express(); + app.use(express.json()); + app.use((req, _res, next) => { req.user = { id: userId }; next(); }); + app.use(rotationRouter); + const server = app.listen(0); + await new Promise((r) => server.once("listening", r)); + const base = `http://127.0.0.1:${server.address().port}`; + const call = async (method, path, body) => { + const res = await fetch(`${base}${path}`, { method, headers: body ? { "content-type": "application/json" } : {}, body: body ? JSON.stringify(body) : undefined }); + const text = await res.text(); + return { status: res.status, body: text.startsWith("{") ? JSON.parse(text) : text }; + }; + return { call, close: () => new Promise((r) => server.close(r)) }; +} + +const now = Date.now(); +await migrate(); +for (const [uid, email] of [["u_owner", "owner@example.com"], ["u_member", "member@example.com"], ["u_out", "out@example.com"]]) { + await run(`INSERT INTO users (id, email, created_at) VALUES (?,?,?)`, [uid, email, now]); +} +await run(`INSERT INTO credshare_teams (id, slug, name, created_by, created_at) VALUES (?,?,?,?,?)`, ["t1", "acme", "acme", "u_owner", now]); +await run(`INSERT INTO credshare_members (id, team_id, user_id, email, role, status, created_at) VALUES (?,?,?,?,?,?,?)`, ["m1", "t1", "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 (?,?,?,?,?,?,?)`, ["m2", "t1", "u_member", "member@example.com", "member", "active", now]); +for (const v of ["app--prod", "web--prod"]) await run(`INSERT INTO credshare_vaults (id, team_id, name, created_by, created_at) VALUES (?,?,?,?,?)`, [v, "t1", v, "u_owner", now]); +const secret = (vault, name, fp) => + 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]); +await secret("app--prod", "OPENAI_API_KEY", "fp-openai"); +await secret("web--prod", "OPENAI_KEY_COPY", "fp-openai"); // same value under another name +await secret("app--prod", "CRON_SECRET", "fp-cron"); +await secret("app--prod", "__ROTATE__CRON_SECRET", "fp-entry"); +await secret("app--prod", "STRIPE_SECRET_KEY", "fp-stripe"); +await secret("app--prod", "CLOUDFLARE_GLOBAL_API_KEY", "fp-cfg"); +await secret("app--prod", "PUBLIC_SITE_URL", "fp-url"); + +test("plan: catalog methods by key name, vault counts by fingerprint, never ciphertext", async (t) => { + const app = await serve("u_member"); + t.after(app.close); + const { status, body } = await app.call("GET", "/api/credshare/teams/acme/rotation"); + assert.equal(status, 200); + const by = Object.fromEntries(body.plan.map((p) => [p.key, p])); + assert.equal(by.OPENAI_API_KEY.method, "desktop"); + assert.equal(by.OPENAI_API_KEY.recipe, "openai"); + assert.equal(by.OPENAI_API_KEY.automatic, true); + assert.equal(by.OPENAI_API_KEY.vaultCount, 2); + assert.deepEqual(by.OPENAI_API_KEY.alsoIn, ["web--prod:OPENAI_KEY_COPY"]); + assert.equal(by.CLOUDFLARE_GLOBAL_API_KEY.desktopMode, "roll"); + assert.equal(by.CRON_SECRET.method, "random"); + assert.equal(by.CRON_SECRET.hasEntry, true); + assert.equal(by.STRIPE_SECRET_KEY.never, true); + assert.equal(by.PUBLIC_SITE_URL, undefined); + assert.equal(by.__ROTATE__CRON_SECRET, undefined); + assert.ok(by.OPENAI_API_KEY.steps.length > 3); + assert.ok(!JSON.stringify(body).includes("CIPHERTEXT")); + assert.ok(!JSON.stringify(body).includes("fp-openai")); +}); + +test("plan: outsiders get 403", async (t) => { + const app = await serve("u_out"); + t.after(app.close); + assert.equal((await app.call("GET", "/api/credshare/teams/acme/rotation")).status, 403); +}); + +test("queue: a member may queue a dry run but not an approved run", async (t) => { + const app = await serve("u_member"); + t.after(app.close); + const denied = await app.call("POST", "/api/credshare/teams/acme/rotation/runs", { keys: ["CRON_SECRET"], approve: true }); + assert.equal(denied.status, 400); + assert.match(denied.body.error, /owner or admin/); + const ok = await app.call("POST", "/api/credshare/teams/acme/rotation/runs", { keys: ["CRON_SECRET"], desktop: "bonita" }); + assert.equal(ok.status, 201); + assert.equal(ok.body.run.status, "queued"); + assert.equal(ok.body.run.approve, false); + assert.deepEqual(ok.body.run.options, { desktop: "bonita" }); +}); + +test("queue -> claim (once) -> result (sanitized) -> listed", async (t) => { + const owner = await serve("u_owner"); + t.after(owner.close); + const q = await owner.call("POST", "/api/credshare/teams/acme/rotation/runs", { keys: ["OPENAI_API_KEY", "CRON_SECRET"], approve: true, propagate: true }); + assert.equal(q.status, 201); + const runId = q.body.run.id; + const queued = await owner.call("GET", "/api/credshare/teams/acme/rotation/runs?status=queued"); + assert.ok(queued.body.runs.some((r) => r.id === runId)); + const c1 = await owner.call("POST", `/api/credshare/teams/acme/rotation/runs/${runId}/claim`); + assert.equal(c1.status, 200); + assert.equal(c1.body.run.status, "running"); + assert.equal((await owner.call("POST", `/api/credshare/teams/acme/rotation/runs/${runId}/claim`)).status, 409); + // Another member cannot report a run they did not claim. + const other = await serve("u_member"); + t.after(other.close); + assert.equal((await other.call("POST", `/api/credshare/teams/acme/rotation/runs/${runId}/result`, { results: [] })).status, 409); + const done = await owner.call("POST", `/api/credshare/teams/acme/rotation/runs/${runId}/result`, { + results: [ + { key: "OPENAI_API_KEY", status: "needs-login", error: "login wall", value: "sk-SHOULD-NOT-BE-STORED" }, + { key: "CRON_SECRET", status: "rotated", written: ["app--prod:CRON_SECRET"], secret: "nope" } + ] + }); + assert.equal(done.status, 200); + assert.equal(done.body.run.status, "done"); + assert.match(done.body.run.summary, /1 needs-login, 1 rotated/); + assert.ok(!JSON.stringify(done.body).includes("SHOULD-NOT")); + assert.ok(!JSON.stringify(done.body).includes("nope")); +}); + +test("cancel: only queued runs", async (t) => { + const app = await serve("u_member"); + t.after(app.close); + const q = await app.call("POST", "/api/credshare/teams/acme/rotation/runs", { keys: "CRON_SECRET" }); + assert.equal((await app.call("POST", `/api/credshare/teams/acme/rotation/runs/${q.body.run.id}/cancel`)).status, 200); + assert.equal((await app.call("POST", `/api/credshare/teams/acme/rotation/runs/${q.body.run.id}/cancel`)).status, 409); +}); + +test("parseRunRequest rejects junk", () => { + assert.throws(() => parseRunRequest({ keys: [] }), /at least one/); + assert.throws(() => parseRunRequest({ keys: ["BAD KEY;"] }), /Not a key name/); + assert.throws(() => parseRunRequest({ keys: ["A"], desktop: "bonita; rm -rf /" }), /ssh host/); + assert.deepEqual(parseRunRequest({ keys: "A, B", approve: "1", allowRoll: "on" }).options, { allowRoll: true }); + assert.equal(sanitizeResults([{ key: "A", status: "weird" }])[0].status, "failed"); +}); + +test("the Rotation page lists the plan with checkboxes, no values, and the runner command", async (t) => { + const app = await serve("u_member"); + t.after(app.close); + const { status, body } = await app.call("GET", "/teams/acme/rotation"); + assert.equal(status, 200); + assert.match(body, /OPENAI_API_KEY/); + assert.match(body, /desktop: openai/); + assert.match(body, /name="keys" value="CRON_SECRET"/); + assert.match(body, /value="STRIPE_SECRET_KEY" aria-label="Rotate STRIPE_SECRET_KEY" disabled/); + assert.match(body, /--from-queue/); + assert.match(body, /owner\/admin only/); // a member cannot queue an approved run + assert.ok(!body.includes("CIPHERTEXT")); + assert.ok(!/