From 13fd9d920c382cb4d99c1885c92e5bfdf48b9365 Mon Sep 17 00:00:00 2001 From: Anthony Ettinger Date: Thu, 29 Oct 2026 00:32:21 +0000 Subject: [PATCH] feat(rotation): provider rotators, consumer propagation, weekly job, runbook (CLI 0.14.0) - Catalog covers every key in the team plan (unknown 275 -> 0): new methods `provider` and `not-secret`, plus family/owner/never/disruptive on every spec. Wallets, treasury, Lightning, exchanges, Stripe, npm, GitHub App keys, signing identities and the personal vault are `never` and owner-only; an __ROTATE__ entry cannot make them automatic. - Two-phase provider rotators (rotators.ts): resend, cloudflare-token, coinpay-api-key, coinpay-webhook-secret, vapid, postgres-role (SCRAM verifier over stdin, refuses self-hosted Supabase). - rotate-keys --propagate [root]: finds consumer env files by value, backs up (.bak-rotate-, 600), rewrites, restarts with the site's deploy.env through deploy-gate 3 at a time, health-checks local + public URL, revokes the old credential only after; any failure restores vaults, files and the provider. --scheduled, --max, --max-sites, --exclude-site, --report. - scripts/logicsrc-rotate: weekly job, dry run unless LOGICSRC_ROTATE_LIVE=1, mails rotated / skipped / manual-by-owner report (never values). - docs/rotation.md (logicsrc.com/docs/rotation) + docs/ROTATION.md pointer, including the wallets and signing keys section. Co-Authored-By: Claude Opus 5.5 --- apps/logicsrc-web/src/lib/docs.ts | 1 + apps/logicsrc-web/src/lib/specs.ts | 1 + bun.lock | 2 +- docs/ROTATION.md | 5 + docs/rotation.md | 335 +++++++++++++++ packages/cli/package.json | 2 +- packages/cli/src/index.ts | 32 +- packages/cli/src/propagate.test.ts | 74 ++++ packages/cli/src/propagate.ts | 268 ++++++++++++ packages/cli/src/rotate-flow.test.ts | 214 ++++++++++ packages/cli/src/rotate-keys.test.ts | 6 +- packages/cli/src/rotate-keys.ts | 337 ++++++++++++++- packages/cli/src/rotation-catalog.test.ts | 136 +++++++ packages/cli/src/rotation-catalog.ts | 370 ++++++++++++++--- packages/cli/src/rotators.test.ts | 260 ++++++++++++ packages/cli/src/rotators.ts | 476 ++++++++++++++++++++++ scripts/logicsrc-rotate | 181 ++++++++ 17 files changed, 2609 insertions(+), 91 deletions(-) create mode 100644 docs/ROTATION.md create mode 100644 docs/rotation.md create mode 100644 packages/cli/src/propagate.test.ts create mode 100644 packages/cli/src/propagate.ts create mode 100644 packages/cli/src/rotate-flow.test.ts create mode 100644 packages/cli/src/rotation-catalog.test.ts create mode 100644 packages/cli/src/rotators.test.ts create mode 100644 packages/cli/src/rotators.ts create mode 100755 scripts/logicsrc-rotate diff --git a/apps/logicsrc-web/src/lib/docs.ts b/apps/logicsrc-web/src/lib/docs.ts index 80b09a62..00a89971 100644 --- a/apps/logicsrc-web/src/lib/docs.ts +++ b/apps/logicsrc-web/src/lib/docs.ts @@ -42,6 +42,7 @@ const GUIDE_SUBTITLES: Record = { config: "Where config lives, and what each key does", permissions: "Explicit, scoped, auditable permission grants", keyring: "SSH keys and key pairs, end-to-end encrypted, with optional cloud sync", + rotation: "Rotate every key, password and token in your vaults: plan, rotate, redeploy, verify, revoke", plugins: "The plugin system, and the plugins that ship with it", "openontology-governance": "An agent proposes, a human applies", "openontology-interoperability": "Mapping to RDF, SHACL and PROV-O, and where it stops", diff --git a/apps/logicsrc-web/src/lib/specs.ts b/apps/logicsrc-web/src/lib/specs.ts index 6b15336d..98a44c6e 100644 --- a/apps/logicsrc-web/src/lib/specs.ts +++ b/apps/logicsrc-web/src/lib/specs.ts @@ -149,6 +149,7 @@ export const GUIDES: Array<{ slug: string; name: string }> = [ { slug: "config", name: "Config" }, { slug: "permissions", name: "Permissions" }, { slug: "keyring", name: "Keyring" }, + { slug: "rotation", name: "Rotating secrets" }, { slug: "plugins", name: "Plugins" }, { slug: "openontology-governance", name: "OpenOntology governance" }, { slug: "openontology-interoperability", name: "OpenOntology interoperability" } diff --git a/bun.lock b/bun.lock index afeccb2f..0fbac1b4 100644 --- a/bun.lock +++ b/bun.lock @@ -147,7 +147,7 @@ }, "packages/cli": { "name": "@logicsrc/cli", - "version": "0.12.0", + "version": "0.14.0", "bin": { "logicsrc": "./dist/index.js", }, diff --git a/docs/ROTATION.md b/docs/ROTATION.md new file mode 100644 index 00000000..cd889dad --- /dev/null +++ b/docs/ROTATION.md @@ -0,0 +1,5 @@ +# Rotation runbook + +The runbook for rotating every key, password and token in LogicSRC team vaults +is [rotation.md](rotation.md), published at https://logicsrc.com/docs/rotation. +It lives under that lowercase name because the site serves `docs/.md`. diff --git a/docs/rotation.md b/docs/rotation.md new file mode 100644 index 00000000..5892e653 --- /dev/null +++ b/docs/rotation.md @@ -0,0 +1,335 @@ +# Rotating secrets + +This is the runbook for rotating every key, password and token kept in LogicSRC +team vaults. It covers the whole loop: plan, rotate, propagate to every vault, +redeploy the consumers, verify, and only then revoke the old value. Most of it +is automated. What is not automated is listed here with the exact steps, and +the reason it is left to a person. + +No command in this runbook prints a secret value. Plans and reports name keys, +vaults, sites and files, never values. + +## The loop + +``` +plan -> mint new -> write every vault -> rewrite consumers -> restart -> health check -> revoke old + \___________________ any failure: put the old value back everywhere ____/ +``` + +1. **Plan.** `logicsrc teams rotation --format json` lists every distinct + secret value once, with how it rotates (`method`), who has to do it + (`owner`), which vaults hold it, and the steps. A value stored in fourteen + vaults under three different names is one row: rotation is matched by value + fingerprint, not by key name. +2. **Dry run.** `logicsrc teams rotate-keys [project] [env] [--key K]` + shows what would happen. Nothing is written without `--approve`. +3. **Rotate.** `--approve` mints the new value. For a provider key the new + credential is created at the provider first, while the old one still works. +4. **Propagate to vaults.** The new value is written to every vault holding the + old fingerprint, whatever the key is called there. Companion values move with + it: a VAPID public key beside its private key, a `DATABASE_URL` that embeds a + rotated password. +5. **Redeploy consumers.** With `--propagate [root]` (default `~/www`) the CLI + finds every site whose env files hold the old value, by value, so a renamed + copy is found too. It backs each file up to `.bak-rotate-` + (mode 600), rewrites it in place with the same mode, and restarts the site + with its own `deploy.env` (`docker compose --env-file deploy.env up -d + --no-build --force-recreate`, or `deploy-app.sh ` when a + build-time `NEXT_PUBLIC_*` value changed, or the site's own + `rotate-restart.sh`). Restarts run three at a time through `deploy-gate`. +6. **Verify.** Each site must answer below 500 on its local port and on its + public URL within three minutes. A site that was already unhealthy before the + rotation makes the CLI skip that value, so a rotation is never blamed for an + outage it did not cause. +7. **Revoke.** Only after every consumer is healthy does the CLI revoke the old + credential at the provider. If anything failed before that point, it writes + the old value back to every vault, restores every env file from its backup, + restarts those sites, and deletes the new credential at the provider. The + result is `rolled-back`, and the old value keeps working. + +Rotations that are not automatic come back as `todo` with steps. When you have +rotated one by hand, store it everywhere at once: + +```sh +new-value-command | logicsrc teams rotate-keys --key NAME --set-from-stdin --approve +``` + +## Methods + +| method | who makes the new value | automatic | +| --- | --- | --- | +| `random` | the CLI, matching the old value's alphabet and length (min 32) | yes | +| `provider` | a built-in rotator calls the provider's API (below) | yes | +| `ssh-keygen` | the CLI makes an ed25519 pair; you install the public half | value yes, install no | +| `command` | your command prints the new value on stdout | yes, with `--approve` | +| `manual` | a person or agent follows the steps | no | +| `not-secret` | nothing: public config, dropped from the plan | n/a | + +Each value can carry its own instructions in an encrypted companion entry, +`__ROTATE__`, set with `logicsrc teams rotation-set`. Entries override the +built-in catalog, with one exception: an entry can never make a wallet, +signing or banned-provider key automatic. + +Specs can also say `disruptive` (what users notice, such as everyone being +signed out), `never` (never automated), `owner` (`agent` or the account +owner), and `family` (the grouping used below). + +## The weekly job + +A weekly cron runs: + +```sh +logicsrc teams rotate-keys --scheduled --propagate --approve --report +``` + +`--scheduled` rotates only what is safe to do unattended: + +- `random` secrets that are not `disruptive` (cron tokens, internal API keys, + admin tokens, webhook signing secrets we invented), and +- `provider` rotators whose old and new credentials overlap (Resend, + Cloudflare tokens, CoinPay API keys), + +and only when at least one consumer was found on the box, no more than five +sites read it (`--max-sites`), none of them is excluded (`--exclude-site`; +client sites are never part of a fleet sweep), every consumer was healthy +before, and the value does not also appear in the crontab or a script (those +copies are not rewritten, so they would break). + +The job only sees consumers on its own box. A value also used by an app on +another host would break there, which is why the job starts as a dry run and +goes live only when the owner sets `LOGICSRC_ROTATE_LIVE=1`. Read a dry-run +report first: every value it would rotate is listed with the sites it found. Everything else is +listed in the emailed report: what rotated, what was skipped and why, and the +manual list with steps, grouped by who has to do it. + +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. + +## Built-in provider rotators + +Every rotator is two-phase: create the new credential, switch everything over, +health-check, then revoke the old one. + +### Resend (`resend`) + +- Keys: `RESEND_API_KEY`, `RESEND_*_API_KEY`, `RESEND_*_ADMIN_KEY`. +- Mint: `POST https://api.resend.com/api-keys` with the same permission level + (full access if the old key has it, otherwise sending only). Needs a + full-access key: the old key itself, or `RESEND_ADMIN_API_KEY`. +- Revoke: `DELETE /api-keys/`. Resend never says which id a token is, so + the rotator saves the new key's id in `__ROTATE__` and revokes by that id + next time. The first rotation asks you to delete the previous key in the + dashboard (resend.com/api-keys) and names the one to keep. +- Breaks: nothing, both keys work until the old one is deleted. + +### Cloudflare API tokens (`cloudflare-token`) + +- Keys: `CLOUDFLARE_API_TOKEN`, `CF_API_TOKEN`, `CLOUDFLARE_*_TOKEN`. +- Mint: `GET /user/tokens/verify` names the old token's id, `GET + /user/tokens/` reads its policies, `POST /user/tokens` creates a copy + named ` (rotated )` with the same policies, condition and expiry. + Reading and creating tokens needs "API Tokens Write": set + `CLOUDFLARE_ADMIN_API_TOKEN`, or give the token that permission. +- Revoke: `DELETE /user/tokens/`. +- Not covered: account-owned tokens and the Global API Key. Rotate those in the + dashboard (dash.cloudflare.com/profile/api-tokens). + +### CoinPay business API keys (`coinpay-api-key`) + +- Keys: `COINPAY_API_KEY`, `COINPAYPORTAL_API_KEY`, `COINPAY_*_API_KEY`, + `COINPAY_X402_KEY`. +- Needs a merchant session for the business owner: `COINPAY_ROTATE_TOKEN`, or + `COINPAY_ROTATE_EMAIL` + `COINPAY_ROTATE_PASSWORD`. +- Mint: the old key finds its business (`GET /api/businesses`), then `POST + /api/businesses//api-keys` creates a scoped key with the old key's scopes + (`*` for the legacy key). Old and new both work. +- Revoke: a scoped key is deleted (`DELETE /api/businesses//api-keys/`); the legacy key is killed by regenerating the legacy slot, and that new + value is thrown away unread. + +### CoinPay webhook secrets (`coinpay-webhook-secret`) + +- Keys: `COINPAY_WEBHOOK_SECRET`, `COINPAYPORTAL_WEBHOOK_SECRET`, + `COINPAY_*_WEBHOOK_SECRET`. +- Mint: `POST /api/businesses//webhook-secret` (the business is found by + the secret, using the CoinPay API key in the same vault). +- Breaks: a business has one webhook secret, so there is no overlap. Deliveries + fail signature checks until the consumer restarts; CoinPay retries them. Not in + the weekly job. + +### Web Push VAPID keys (`vapid`) + +- Keys: `VAPID_PRIVATE_KEY`, `VAPID_PRIVATE`. The new public half is written to + every `*VAPID*PUB*` key beside it. +- Mint: a new P-256 pair, made locally. +- Breaks: every existing push subscription. Browsers must subscribe again, so + the app has to re-prompt. Not in the weekly job. + +### Postgres role passwords (`postgres-role`) + +- Keys: `POSTGRES_PASSWORD`, `DB_PASS`, `*_DB_PASSWORD`, when the vault also + holds a `postgres://` URL with that password (it names the host and role). +- Mint: `ALTER ROLE CURRENT_USER PASSWORD ''` through `psql` + over stdin. Only a SCRAM-SHA-256 verifier reaches the server, so the plaintext + never lands in a server log, and no secret is ever on a command line. +- Every connection string holding the old password is rewritten in the vaults + and in the env files. +- Breaks: Postgres has one password per role, so consumers fail until they + restart. Rollback sets the old password back. Not in the weekly job. +- Refused: self-hosted Supabase. Its `POSTGRES_PASSWORD` is shared by six + service roles (`postgres`, `authenticator`, `pgbouncer`, + `supabase_auth_admin`, `supabase_functions_admin`, `supabase_storage_admin`) + and by the stack's own `.env`. See the Supabase section. + +## Manual rotations, by family + +Every family below is in the catalog, so every key gets steps in the plan. The +`owner` column says who has to do it: `agent` means an agent with dashboard or +CLI access can do it; `owner` means the account owner (money, a signing +ceremony, a personal login behind 2FA). + +| family | owner | how | +| --- | --- | --- | +| supabase (JWT secret, anon, service role) | agent | see below | +| turso | agent | `turso db tokens create `; store; redeploy; then `turso db tokens invalidate ` (kills every token for that db, so only after all consumers moved) | +| github tokens, OAuth apps | agent | github.com/settings/tokens: new fine-grained token with the same repos and permissions. OAuth app secrets: Generate a new client secret (two can be live), switch, delete the old | +| google | agent | console.cloud.google.com/apis/credentials: new key with the same API restrictions, or Add secret on the OAuth client, then disable the old | +| ai providers | agent | each provider's API keys page (Anthropic console, OpenAI project keys, and so on): create, store, redeploy, delete the old | +| twilio | agent | Console > API keys & tokens: create a secondary auth token, switch, promote it | +| telnyx, porkbun, storage, social, browser stores | agent | the provider's key page named in the plan | +| coinpay OAuth client secrets | agent | our own CoinPay: Developer > OAuth apps > regenerate secret | +| fleet apps (listing keys, agent keys, admin keys) | agent | the issuing app's admin page or API: mint for the same account, store, redeploy, revoke | +| scraped sessions (cookies) | agent | sign in again in the scraping profile, copy the fresh cookie | +| email (SMTP/IMAP) | agent | mailbox host: generate a new alias password | +| data at rest (encryption keys, hashing salts) | agent | dual-read: add the new key next to the old one, re-encrypt or re-hash every row, remove the old key only when every row reads with the new one | +| ssh | agent | the plan mints the pair; install the new public key everywhere the old one was authorized, remove the old one, restore the private key with `logicsrc keyring restore` | +| wallets, treasury, Lightning | owner | never automated: see the wallet section | +| exchanges, ramps, bank links | owner | can move money: new key with the least permissions, 2FA by the owner | +| stripe | owner | not used for new work, never rotated by automation: dashboard Roll key / Roll secret | +| package registries (npm, PyPI) | owner | a person creates a granular automation token | +| github app private keys | owner | App settings > Generate a private key; delete the old one there | +| signing identities (DID, TUF, PLC, CA, GPG) | owner | key ceremony: publish the new public half where verifiers look before switching signers | +| account logins | owner | change the password on the site (2FA), save it in the personal vault | +| personal vault master password, recovery key | owner | `logicsrc vault passwd` at a terminal | + +### Supabase + +The JWT secret signs every key and every session. Rotating it signs every user +out and re-issues the anon and service_role keys, so it is never weekly. + +Self-hosted: + +1. Generate a new `JWT_SECRET` (40 or more characters) and mint new anon and + service_role JWTs from it (Supabase's self-hosting guide has the generator). +2. Write all three to the stack's `.env`, restart the stack with its own env + file. +3. Store each new value with `--set-from-stdin`: every vault sharing the old + fingerprint is updated, including copies under other names. +4. Redeploy every app (`--propagate` does the env files for you when you store + with the CLI). +5. Verify the old anon key now gets 401. + +For the database password of a self-hosted stack, change all six service roles +in one transaction (`ALTER ROLE PASSWORD ...` for each), update the +stack's `.env` and every app `DATABASE_URL`, then restart the stack and the +apps. Hosted Supabase: Project settings > Database > Reset password, and +Project settings > API for new keys. + +## Wallets and signing keys: why they never auto-rotate, and where they live + +A wallet key cannot be rotated the way an API key can. There is no provider to +issue a new one and revoke the old one: "rotating" a wallet means making a new +wallet and moving every balance to it, which is a payment. The catalog marks +every seed, mnemonic, wallet private key, treasury key and Lightning node secret +`never`, and no `__ROTATE__` entry can override that. The plan lists them for +the owner with these steps: + +1. Generate a new wallet on a trusted machine, never on a server. +2. Move every balance, tokens and native gas, from the old address to the new + one. A person signs this. +3. Store the new seed in the place it belongs (below) and update anything that + pays to or watches the old address. +4. Never reuse the old seed. Assume it is public. + +Signing keys (DID keys, TUF roots, certificate authorities, package publisher +keys) are the same: verifiers pin the public half, so a new key has to be +published where they look before the signer switches. That is a key ceremony, +done by a person. + +### What went wrong + +We learned this the hard way. Plaintext private keys and seed phrases were kept +in a dotfiles repository, and the servers that used encrypted keys also held +the encryption key next to the data. So anyone who got root on one box could +read every key on it. Encryption at rest did not help, because the key to undo +it sat beside the ciphertext. + +### What exists now + +- **The LogicSRC keyring** (`logicsrc keyring`, see [Keyring](/docs/keyring)) + keeps SSH keys and key pairs end-to-end encrypted. Sync is optional and sends + only ciphertext: the server refuses anything that looks like private key + material. +- **The personal vault** (`logicsrc vault`, built on OpenCreds) holds seeds, + recovery phrases and logins, encrypted on the owner's device and synced as + ciphertext. Plaintext files with secrets were imported into it and destroyed. +- **The CoinPay operator vault** seals the platform's system keys and deposit + keys under a passphrase that is derived in the owner's browser. The unlocked + keys live only in the running process's memory. Root on the box no longer + opens deposit keys: the files on disk hold ciphertext and placeholders. +- **Team vaults withhold signing keys from scripts.** A pull without a terminal + does not get mnemonics or wallet keys, and a push refuses a file that holds + them unless you say so. Sweeping a wallet therefore needs a person at a + terminal, by design. +- **Wallet keys are never auto-rotated.** Rotation is a new wallet plus a sweep + by a person, as above. + +### What we are building next + +This part is a roadmap, not shipped. + +- **One intuitive place for wallet and signing keys,** with a plain unlock + flow, instead of keys spread across the keyring, the personal vault and app + vaults. +- **A small in-memory keyholder service,** so redeploys stop re-locking vaults. + Today a restart of a service that holds an unlocked vault (CoinPay, for + example) locks it again and the owner has to unlock it by hand. A keyholder + that survives app restarts, and never writes keys to disk, removes that step. +- **Reminders before a vault locks.** A watcher already emails, texts and calls + the owner before an unlock expires and when a restart has locked it; the + keyholder will make the "a restart locked it" case go away. + +## Never automated + +- Wallet keys, seeds, treasury keys, Lightning secrets, exchange and bank-link + keys: they move money. +- Stripe: not used for new work, rotated only by the account owner. +- npm and other package registry tokens: a person creates them. +- GitHub App private keys and secrets: made in the App settings UI. +- The personal vault's master password and recovery key. +- Signing identities: a key ceremony. + +## Safety rules the CLI follows + +- Dry run unless `--approve`. `--max ` stops after n live rotations. +- Values are never printed, logged or written to a plaintext file. Reports + (`--report`) are JSON with key names, vaults, sites and outcomes, mode 600. +- Every env file is backed up before it is rewritten. +- A restart never runs `docker compose up` without the site's `deploy.env`. +- At most three restarts at a time. +- A failure after the switch rolls everything back, and the old credential is + revoked only after every consumer is healthy. + +## First run + +Start small: + +```sh +logicsrc teams rotation --format json > plan.json # what there is +logicsrc teams rotate-keys prod --key CRON_SECRET --propagate # dry run +logicsrc teams rotate-keys prod --key CRON_SECRET --propagate --approve +``` + +Check the site, then widen to `--scheduled` once a couple of single rotations +have gone through cleanly. diff --git a/packages/cli/package.json b/packages/cli/package.json index 38cfbe40..59fe7035 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "@logicsrc/cli", - "version": "0.13.0", + "version": "0.14.0", "description": "LogicSRC CLI: every LogicSRC standard and tool as one command.", "type": "module", "main": "./dist/index.js", diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 369728e1..1e27e838 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -1,6 +1,8 @@ #!/usr/bin/env node import { spawnSync } from "node:child_process"; import { readFileSync } from "node:fs"; +import { homedir } from "node:os"; +import { join } from "node:path"; import { evaluateAccountPolicy, scoreAccountActionRisk } from "@logicsrc/account-core"; import { Command } from "commander"; import { createCredentialEngine, listCredentialProviders, logicsrcHome, type CredentialEndpoint } from "@logicsrc/plugin-credential-sharing"; @@ -949,6 +951,12 @@ teams .option("-k, --key ", "only these keys (comma-separated or repeated)", collectList) .option("--approve", "write the new values (dry run by default)") .option("--set-from-stdin", "store a value you rotated by hand (exactly one --key), everywhere the old value lives") + .option("--propagate [root]", "also rewrite, restart and health-check the sites holding the old value (default root ~/www); rolls back on failure") + .option("--scheduled", "unattended mode: only non-disruptive random secrets and two-phase provider rotators with known consumers") + .option("--max ", "stop after n live rotations") + .option("--exclude-site ", "never rewrite or restart these sites; a value they hold is skipped (comma-separated or repeated)", collectList) + .option("--max-sites ", "with --scheduled: skip values read by more than n sites (default 5)") + .option("--report ", "also write the JSON results (never values) to this file, mode 600") .option("--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( @@ -959,19 +967,33 @@ Dry run first, then apply: logicsrc teams rotate-keys profullstack b1dz prod --approve rotate one vault's automatic keys logicsrc teams rotate-keys profullstack --key SSH_ID_ED25519 --approve new-key | logicsrc teams rotate-keys profullstack b1dz prod --key RESEND_API_KEY --set-from-stdin --approve + 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) + +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 +revokes the old one; any failure restores the old value everywhere. +Runbook: https://logicsrc.com/docs/rotation Values never print. The same value stored in other vaults (same fingerprint) is rotated there too. Vaults you cannot decrypt are named and keep the OLD value. After rotating: redeploy the consumers, install new SSH public keys, revoke the old values. ` ) - .action((slug, project, env, options) => - teamsRotateKeysAction(slug, { project, env, keys: options.key }, { + .action(async (slug, project, env, options) => { + await teamsRotateKeysAction(slug, { project, env, keys: options.key }, { approve: Boolean(options.approve), setFromStdin: Boolean(options.setFromStdin), - format: options.format as OutputFormat - }) - ); + format: options.format as OutputFormat, + propagate: options.propagate === undefined ? undefined : options.propagate === true ? join(homedir(), "www") : String(options.propagate), + scheduled: Boolean(options.scheduled), + max: options.max === undefined ? undefined : Number(options.max), + report: options.report, + excludeSites: options.excludeSite, + maxSites: options.maxSites === undefined ? undefined : Number(options.maxSites) + }); + }); teams .command("clean") diff --git a/packages/cli/src/propagate.test.ts b/packages/cli/src/propagate.test.ts new file mode 100644 index 00000000..90b3b586 --- /dev/null +++ b/packages/cli/src/propagate.test.ts @@ -0,0 +1,74 @@ +import { mkdtempSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync, readdirSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; +import { envFilesIn, findConsumers, inBatches, replaceInValue, restoreBackup, rewriteEnvFile, strayCopies } from "./propagate.js"; + +const dirs: string[] = []; +function www(): string { + const d = mkdtempSync(join(tmpdir(), "logicsrc-propagate-")); + dirs.push(d); + return d; +} +afterEach(() => { + for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }); +}); + +const OLD = "old-secret-0123456789"; +const NEW = "new-secret-abcdefghij"; + +describe("propagate", () => { + it("finds consumers by value, skipping backups, and flags build-time keys", () => { + const root = www(); + mkdirSync(join(root, "a.com")); + mkdirSync(join(root, "b.com")); + writeFileSync(join(root, "a.com", "app.env"), `X=1\nCRON_SECRET=${OLD}\nRENAMED="${OLD}"\n`); + writeFileSync(join(root, "a.com", "app.env.bak-001"), `CRON_SECRET=${OLD}\n`); + writeFileSync(join(root, "a.com", "app.bak-002.env"), `CRON_SECRET=${OLD}\n`); + writeFileSync(join(root, "b.com", "deploy.env"), `NEXT_PUBLIC_THING=${OLD}\n`); + expect(envFilesIn(join(root, "a.com")).map((f) => f.split("/").pop())).toEqual(["app.env"]); + const hits = findConsumers(root, [{ oldValue: OLD, newValue: NEW }]); + expect(hits.map((h) => [h.site, h.keys, h.needsBuild])).toEqual([ + ["a.com", ["CRON_SECRET", "RENAMED"], false], + ["b.com", ["NEXT_PUBLIC_THING"], true] + ]); + }); + + it("rewrites in place with a 600 backup, keeps mode and quotes, and restores", () => { + const root = www(); + const f = join(root, "app.env"); + writeFileSync(f, `A=${OLD}\nB='${OLD}'\nDATABASE_URL=postgres://u:${OLD}@h:5432/d\nC=keep\n`, { mode: 0o600 }); + const { backup, keys } = rewriteEnvFile(f, [{ oldValue: OLD, newValue: NEW }], "20261029"); + expect(keys).toEqual(["A", "B", "DATABASE_URL"]); + expect(readFileSync(f, "utf8")).toBe(`A=${NEW}\nB='${NEW}'\nDATABASE_URL=postgres://u:${NEW}@h:5432/d\nC=keep\n`); + expect(statSync(f).mode & 0o777).toBe(0o600); + expect(statSync(backup).mode & 0o777).toBe(0o600); + expect(backup).toMatch(/app\.env\.bak-rotate-20261029$/); + restoreBackup(f, backup); + expect(readFileSync(f, "utf8")).toContain(`A=${OLD}`); + const second = rewriteEnvFile(f, [{ oldValue: OLD, newValue: NEW }], "20261029"); + expect(second.backup).toMatch(/-2$/); + expect(readdirSync(root).filter((n) => n.includes("rotate-tmp"))).toEqual([]); + }); + + it("ignores short values that could collide with unrelated text", () => { + expect(replaceInValue("abc", [{ oldValue: "abc", newValue: "x" }])).toBeNull(); + }); + + it("finds stray copies (crontab, scripts)", () => { + const root = www(); + writeFileSync(join(root, "s"), `curl -H "x: ${OLD}"`); + expect(strayCopies([join(root, "s"), join(root, "missing")], [{ oldValue: OLD, newValue: NEW }])).toEqual([join(root, "s")]); + }); + + it("runs at most 3 at a time", async () => { + let running = 0; + let peak = 0; + await inBatches([1, 2, 3, 4, 5, 6, 7], 3, async () => { + peak = Math.max(peak, ++running); + await new Promise((r) => setTimeout(r, 5)); + running--; + }); + expect(peak).toBe(3); + }); +}); diff --git a/packages/cli/src/propagate.ts b/packages/cli/src/propagate.ts new file mode 100644 index 00000000..985f3c87 --- /dev/null +++ b/packages/cli/src/propagate.ts @@ -0,0 +1,268 @@ +import { spawn } from "node:child_process"; +import { chmodSync, copyFileSync, existsSync, readFileSync, readdirSync, statSync, writeFileSync, renameSync } from "node:fs"; +import { join } from "node:path"; + +/** + * After a rotation is written to the vaults, the running sites still hold the + * old value in their env files. This finds them by VALUE (not key name, so a + * renamed copy is found too), rewrites them with a backup, restarts each site + * with its own deploy.env, and health-checks it. + * + * Layout (dev2): //{app.env,deploy.env,docker-compose.app.yml, + * deploy-app.sh,.deploy-state}. A site may ship `rotate-restart.sh` to restart + * itself differently. Values are never printed; reports name files and keys. + */ + +export interface Replacement { + oldValue: string; + newValue: string; +} + +export interface EnvHit { + site: string; + dir: string; + file: string; + keys: string[]; + /** A NEXT_PUBLIC_* value changed: the image has to be rebuilt, not just recreated. */ + needsBuild: boolean; +} + +const ENV_FILE = /^(app|deploy|prober|worker|web|api)?\.?env$|^[a-z0-9_-]+\.env$/i; +const BACKUP = /bak|orig|\.old$|\.example$|\.sample$|\.tmp$/i; +/** Shorter values could collide with unrelated text. */ +const MIN_MATCH = 12; + +export function envFilesIn(dir: string): string[] { + let names: string[]; + try { + names = readdirSync(dir); + } catch { + return []; + } + return names.filter((n) => ENV_FILE.test(n) && !BACKUP.test(n)).map((n) => join(dir, n)).filter((f) => { + try { + return statSync(f).isFile(); + } catch { + return false; + } + }); +} + +function splitLine(line: string): { key: string; value: string; quote: string } | null { + const m = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line); + if (!m) return null; + let value = m[2]!; + let quote = ""; + if ((value.startsWith('"') && value.endsWith('"') && value.length >= 2) || (value.startsWith("'") && value.endsWith("'") && value.length >= 2)) { + quote = value[0]!; + value = value.slice(1, -1); + } + return { key: m[1]!, value, quote }; +} + +/** The new value for a line, or null when the line does not hold an old value. Connection strings match on the embedded password. */ +export function replaceInValue(value: string, reps: Replacement[]): string | null { + for (const r of reps) { + if (r.oldValue.length < MIN_MATCH) continue; + if (value === r.oldValue) return r.newValue; + } + for (const r of reps) { + if (r.oldValue.length < MIN_MATCH) continue; + const enc = encodeURIComponent(r.oldValue); + for (const old of new Set([r.oldValue, enc])) { + const at = value.indexOf(`:${old}@`); + if (at !== -1) return value.slice(0, at + 1) + (old === enc ? encodeURIComponent(r.newValue) : r.newValue) + value.slice(at + 1 + old.length); + } + } + return null; +} + +/** Every env file under root// holding one of the old values. */ +export function findConsumers(root: string, reps: Replacement[]): EnvHit[] { + const hits: EnvHit[] = []; + let sites: string[]; + try { + sites = readdirSync(root); + } catch { + return []; + } + for (const site of sites.sort()) { + const dir = join(root, site); + for (const file of envFilesIn(dir)) { + let text: string; + try { + text = readFileSync(file, "utf8"); + } catch { + continue; + } + if (!reps.some((r) => r.oldValue.length >= MIN_MATCH && (text.includes(r.oldValue) || text.includes(encodeURIComponent(r.oldValue))))) continue; + const keys: string[] = []; + for (const line of text.split("\n")) { + const kv = splitLine(line); + if (kv && replaceInValue(kv.value, reps) !== null) keys.push(kv.key); + } + if (keys.length) hits.push({ site, dir, file, keys, needsBuild: keys.some((k) => /^NEXT_PUBLIC_|^VITE_|^EXPO_PUBLIC_/.test(k)) }); + } + } + return hits; +} + +/** Other places a value can hide that we do not rewrite: crontab, scripts. A hit there blocks unattended rotation. */ +export function strayCopies(paths: string[], reps: Replacement[]): string[] { + const out: string[] = []; + for (const p of paths) { + let text = ""; + try { + text = readFileSync(p, "utf8"); + } catch { + continue; + } + if (reps.some((r) => r.oldValue.length >= MIN_MATCH && text.includes(r.oldValue))) out.push(p); + } + return out; +} + +/** Rewrite one env file in place (same mode), after copying it to .bak-rotate-. */ +export function rewriteEnvFile(file: string, reps: Replacement[], stamp: string): { backup: string; keys: string[] } { + const text = readFileSync(file, "utf8"); + const keys: string[] = []; + const out = text + .split("\n") + .map((line) => { + const kv = splitLine(line); + if (!kv) return line; + const next = replaceInValue(kv.value, reps); + if (next === null) return line; + keys.push(kv.key); + const eq = line.indexOf("="); + return `${line.slice(0, eq + 1)}${kv.quote}${next}${kv.quote}`; + }) + .join("\n"); + const mode = statSync(file).mode & 0o777; + let backup = `${file}.bak-rotate-${stamp}`; + for (let i = 2; existsSync(backup); i++) backup = `${file}.bak-rotate-${stamp}-${i}`; + copyFileSync(file, backup); + chmodSync(backup, 0o600); + const tmp = `${file}.rotate-tmp`; + writeFileSync(tmp, out, { mode }); + chmodSync(tmp, mode); + renameSync(tmp, file); + return { backup, keys }; +} + +export function restoreBackup(file: string, backup: string): void { + const mode = statSync(file).mode & 0o777; + copyFileSync(backup, file); + chmodSync(file, mode); +} + +export function readEnv(file: string): Record { + const out: Record = {}; + try { + for (const line of readFileSync(file, "utf8").split("\n")) { + const kv = splitLine(line); + if (kv) out[kv.key] = kv.value; + } + } catch { + /* missing */ + } + return out; +} + +export interface RestartResult { + site: string; + ok: boolean; + detail: string; +} + +export interface SiteOps { + /** Restart a site so it reads its env files again. */ + restart(dir: string, site: string, needsBuild: boolean): Promise; + /** Healthy = local port and public URL answer below 500. */ + health(dir: string, site: string): Promise; +} + +function sh(cmd: string, args: string[], cwd: string, timeoutMs: number): Promise<{ code: number | null; tail: string }> { + return new Promise((resolve) => { + const child = spawn(cmd, args, { cwd, stdio: ["ignore", "pipe", "pipe"], env: process.env }); + let tail = ""; + const keep = (b: Buffer) => { + tail = (tail + b.toString()).slice(-600); + }; + child.stdout.on("data", keep); + child.stderr.on("data", keep); + const t = setTimeout(() => child.kill("SIGTERM"), timeoutMs); + child.on("close", (code) => { + clearTimeout(t); + resolve({ code, tail }); + }); + child.on("error", (e) => { + clearTimeout(t); + resolve({ code: -1, tail: String(e.message) }); + }); + }); +} + +async function status(url: string): Promise { + try { + const r = await fetch(url, { redirect: "manual", signal: AbortSignal.timeout(10_000) }); + return r.status; + } catch { + return 0; + } +} + +/** dev2: recreate with the site's own deploy.env through deploy-gate (3 slots); rebuild via deploy-app.sh when a build-time value changed. */ +export const dev2Ops: SiteOps = { + async restart(dir, site, needsBuild) { + const gate = [join(process.env.HOME ?? "", ".local/bin/deploy-gate"), "/usr/local/bin/deploy-gate"].find((g) => existsSync(g)); + if (existsSync(join(dir, "rotate-restart.sh"))) { + const r = await sh(join(dir, "rotate-restart.sh"), [], dir, 900_000); + return { site, ok: r.code === 0, detail: r.code === 0 ? "rotate-restart.sh" : `rotate-restart.sh exit ${r.code}: ${r.tail}` }; + } + if (needsBuild) { + const sha = readEnv(join(dir, ".deploy-state")).DEPLOYED_SHA; + if (!sha || !existsSync(join(dir, "deploy-app.sh"))) return { site, ok: false, detail: "build-time value changed and there is no deploy-app.sh/.deploy-state to rebuild with" }; + const r = await sh(join(dir, "deploy-app.sh"), [sha], dir, 1_800_000); + return { site, ok: r.code === 0, detail: r.code === 0 ? `rebuilt ${sha.slice(0, 8)}` : `deploy-app.sh exit ${r.code}: ${r.tail}` }; + } + const compose = ["docker-compose.app.yml", "docker-compose.yml", "compose.yml"].find((f) => existsSync(join(dir, f))); + if (!compose) return { site, ok: false, detail: "no compose file: restart it by hand" }; + // Never without the site's deploy.env: compose would drop APP_PORT and friends. + if (!existsSync(join(dir, "deploy.env"))) return { site, ok: false, detail: "no deploy.env: refusing a bare docker compose up" }; + const args = ["compose", "-f", compose, "--env-file", "deploy.env", "up", "-d", "--no-build", "--force-recreate"]; + const r = gate ? await sh(gate, ["--name", site, "--", "docker", ...args], dir, 900_000) : await sh("docker", args, dir, 900_000); + return { site, ok: r.code === 0, detail: r.code === 0 ? "recreated" : `compose exit ${r.code}: ${r.tail}` }; + }, + async health(dir, site) { + const port = readEnv(join(dir, "deploy.env")).APP_PORT; + const deadline = Date.now() + 180_000; + let local = 0; + if (port) { + while (Date.now() < deadline) { + local = await status(`http://127.0.0.1:${port}/`); + if (local > 0 && local < 500) break; + await new Promise((r) => setTimeout(r, 5000)); + } + if (!(local > 0 && local < 500)) return { site, ok: false, detail: `127.0.0.1:${port} answered ${local || "nothing"}` }; + } + if (/^[a-z0-9.-]+\.[a-z]{2,}$/i.test(site)) { + let pub = 0; + while (Date.now() < deadline) { + pub = await status(`https://${site}/`); + if (pub > 0 && pub < 500) break; + await new Promise((r) => setTimeout(r, 5000)); + } + if (!(pub > 0 && pub < 500)) return { site, ok: false, detail: `https://${site}/ answered ${pub || "nothing"}` }; + return { site, ok: true, detail: `local ${local || "-"}, public ${pub}` }; + } + return { site, ok: Boolean(port), detail: port ? `local ${local}` : "no APP_PORT and not a hostname: health unknown" }; + } +}; + +/** Run fn over items, at most `limit` at a time (the fleet rule is 3). */ +export async function inBatches(items: T[], limit: number, fn: (t: T) => Promise): Promise { + const out: R[] = []; + for (let i = 0; i < items.length; i += limit) out.push(...(await Promise.all(items.slice(i, i + limit).map(fn)))); + return out; +} diff --git a/packages/cli/src/rotate-flow.test.ts b/packages/cli/src/rotate-flow.test.ts new file mode 100644 index 00000000..f637d48d --- /dev/null +++ b/packages/cli/src/rotate-flow.test.ts @@ -0,0 +1,214 @@ +import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync, readdirSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { + decryptValue, + encryptValue, + fingerprintValue, + generateIdentityKeyPair, + generateVaultKey, + wrapVaultKey +} from "@logicsrc/plugin-credential-sharing"; +import type { SiteOps } from "./propagate.js"; + +/** An in-memory team server: vaults of sealed values, exactly what the real API returns. */ +const server = vi.hoisted(() => ({ client: null as any, identity: null as any })); +vi.mock("./teams.js", async (orig) => ({ ...(await orig()), authedClient: () => ({ client: server.client, identity: server.identity }) })); + +const { teamsRotateKeysAction } = await import("./rotate-keys.js"); + +interface Row { + name: string; + nonce: string; + ciphertext: string; + fingerprint: string; + updatedAt: string; +} + +async function makeTeam(vaults: Record>) { + const keys = await generateIdentityKeyPair(); + const dek = await generateVaultKey(); + const wrapped = await wrapVaultKey(dek, keys.publicKey); + const store = new Map(); + for (const [name, values] of Object.entries(vaults)) { + const rows: Row[] = []; + for (const [k, v] of Object.entries(values)) rows.push({ name: k, ...(await encryptValue(v, dek)), fingerprint: fingerprintValue(v), updatedAt: "2026-01-01T00:00:00Z" }); + store.set(name, rows); + } + const puts: string[][] = []; + server.identity = { keys, apiToken: "t" }; + server.client = { + listVaults: async () => ({ vaults: [...store.keys()].map((n) => ({ id: n, name: n, hasAccess: true })) }), + listSecrets: async (id: string) => ({ secrets: store.get(id)!.map((r) => ({ ...r })) }), + getMyGrant: async () => ({ wrappedDek: wrapped }), + putSecrets: async (id: string, upserts: Row[]) => { + const rows = store.get(id)!; + for (const u of upserts) { + const i = rows.findIndex((r) => r.name === u.name); + const row = { ...u, updatedAt: "2026-10-29T00:00:00Z" }; + if (i === -1) rows.push(row); + else rows[i] = row; + } + puts.push(upserts.map((u) => `${id}:${u.name}`)); + return { ok: true, applied: upserts.map((u) => u.name) }; + } + }; + const read = async (vault: string, key: string) => { + const r = store.get(vault)!.find((x) => x.name === key); + return r ? decryptValue(r, dek) : undefined; + }; + return { read, puts }; +} + +const OLD = "0123456789abcdef0123456789abcdef"; +let root: string; +beforeEach(() => { + root = mkdtempSync(join(tmpdir(), "logicsrc-flow-")); + for (const s of ["a.com", "b.com"]) mkdirSync(join(root, s)); + writeFileSync(join(root, "a.com", "app.env"), `CRON_SECRET=${OLD}\nOTHER=1\n`, { mode: 0o600 }); + writeFileSync(join(root, "b.com", "app.env"), `CALLER_TOKEN=${OLD}\n`, { mode: 0o600 }); +}); +afterEach(() => rmSync(root, { recursive: true, force: true })); + +function ops(fail: string[] = []): SiteOps & { restarts: string[] } { + const restarts: string[] = []; + return { + restarts, + async restart(_dir, site) { + restarts.push(site); + return { site, ok: true, detail: "recreated" }; + }, + async health(_dir, site) { + const bad = fail.includes(site) && restarts.includes(site); + return { site, ok: !bad, detail: bad ? "503" : "200" }; + } + }; +} + +const quiet = { format: "json" as const }; + +describe("rotate-keys two-phase flow", () => { + beforeEach(() => { + vi.spyOn(console, "log").mockImplementation(() => {}); + vi.spyOn(console, "error").mockImplementation(() => {}); + }); + + it("random: writes every vault and every consumer file, restarts both sites, health-checks", async () => { + const team = await makeTeam({ "a--prod": { CRON_SECRET: OLD }, "a--local": { CRON_SECRET: OLD } }); + const o = ops(); + const [r] = await teamsRotateKeysAction("t", { keys: ["CRON_SECRET"] }, { ...quiet, approve: true, propagate: root }, { ops: o, strayText: () => [] }); + expect(r!.status).toBe("rotated"); + const now = (await team.read("a--prod", "CRON_SECRET"))!; + expect(now).not.toBe(OLD); + expect(await team.read("a--local", "CRON_SECRET")).toBe(now); + expect(readFileSync(join(root, "a.com", "app.env"), "utf8")).toBe(`CRON_SECRET=${now}\nOTHER=1\n`); + expect(readFileSync(join(root, "b.com", "app.env"), "utf8")).toBe(`CALLER_TOKEN=${now}\n`); + expect(readdirSync(join(root, "a.com")).some((n) => n.startsWith("app.env.bak-rotate-"))).toBe(true); + expect(o.restarts.sort()).toEqual(["a.com", "b.com"]); + expect(JSON.stringify(r)).not.toContain(now); + expect(JSON.stringify(r)).not.toContain(OLD); + }); + + it("rolls back vaults and files when a consumer fails health after the switch", async () => { + const team = await makeTeam({ "a--prod": { CRON_SECRET: OLD } }); + const o = ops(["b.com"]); + const [r] = await teamsRotateKeysAction("t", { keys: ["CRON_SECRET"] }, { ...quiet, approve: true, propagate: root }, { ops: o, strayText: () => [] }); + expect(r!.status).toBe("rolled-back"); + expect(await team.read("a--prod", "CRON_SECRET")).toBe(OLD); + expect(readFileSync(join(root, "a.com", "app.env"), "utf8")).toContain(`CRON_SECRET=${OLD}`); + expect(readFileSync(join(root, "b.com", "app.env"), "utf8")).toBe(`CALLER_TOKEN=${OLD}\n`); + process.exitCode = 0; + }); + + it("dry run writes nothing, but reports the consumers it found", async () => { + const team = await makeTeam({ "a--prod": { CRON_SECRET: OLD, SSH_ID_ED25519: "-----BEGIN OPENSSH PRIVATE KEY-----xxxxxxxx" } }); + const o = ops(); + const results = await teamsRotateKeysAction("t", {}, { ...quiet, approve: false, propagate: root }, { ops: o, strayText: () => [] }); + const cron = results.find((r) => r.key === "CRON_SECRET")!; + expect(cron.status).toBe("would-rotate"); + expect(cron.sites!.map((s) => s.site).sort()).toEqual(["a.com", "b.com"]); + expect(results.find((r) => r.key === "SSH_ID_ED25519")!.status).toBe("would-rotate"); + expect(team.puts).toEqual([]); + expect(o.restarts).toEqual([]); + expect(readFileSync(join(root, "a.com", "app.env"), "utf8")).toContain(OLD); + }); + + it("scheduled dry run applies the same checks as a live run", async () => { + await makeTeam({ "a--prod": { CRON_SECRET: OLD, PIT_ADMIN_TOKEN: "f".repeat(40) } }); + const results = await teamsRotateKeysAction("t", {}, { ...quiet, approve: false, scheduled: true, propagate: root }, { ops: ops(), strayText: () => [] }); + expect(results.find((r) => r.key === "CRON_SECRET")!.status).toBe("would-rotate"); + expect(results.find((r) => r.key === "PIT_ADMIN_TOKEN")!.status).toBe("skipped"); + }); + + it("scheduled mode skips values with no consumer, values in the crontab, disruptive and manual ones", async () => { + await makeTeam({ + "a--prod": { CRON_SECRET: OLD, SESSION_SECRET: "s".repeat(40), STRIPE_SECRET_KEY: "sk_live_xxxxxxxxxxxxxxxx", PIT_ADMIN_TOKEN: "f".repeat(40) } + }); + const results = await teamsRotateKeysAction("t", {}, { ...quiet, approve: true, scheduled: true, propagate: root }, { ops: ops(), strayText: () => [`0 * * * * curl -H 'x: ${OLD}'`] }); + const by = Object.fromEntries(results.map((r) => [r.key, r])); + expect(by.CRON_SECRET!.status).toBe("skipped"); + expect(by.CRON_SECRET!.error).toMatch(/crontab/); + expect(by.SESSION_SECRET!.error).toMatch(/disruptive/); + expect(by.STRIPE_SECRET_KEY!.status).toBe("todo"); + expect(by.STRIPE_SECRET_KEY!.never).toBe(true); + expect(by.PIT_ADMIN_TOKEN!.error).toMatch(/no consumer/); + }); + + it("never touches an excluded site, and caps consumers in unattended mode", async () => { + const team = await makeTeam({ "a--prod": { CRON_SECRET: OLD } }); + const [r] = await teamsRotateKeysAction("t", { keys: ["CRON_SECRET"] }, { ...quiet, approve: true, propagate: root, excludeSites: ["b.com"] }, { ops: ops(), strayText: () => [] }); + expect(r!.status).toBe("skipped"); + expect(r!.error).toMatch(/excluded site holds it: b\.com/); + const [s] = await teamsRotateKeysAction("t", { keys: ["CRON_SECRET"] }, { ...quiet, approve: true, scheduled: true, propagate: root, maxSites: 1 }, { ops: ops(), strayText: () => [] }); + expect(s!.error).toMatch(/too many consumers/); + expect(await team.read("a--prod", "CRON_SECRET")).toBe(OLD); + }); + + it("skips when a consumer is already unhealthy, so the rotation is never blamed", async () => { + const team = await makeTeam({ "a--prod": { CRON_SECRET: OLD } }); + const sick: SiteOps = { restart: async (_d, site) => ({ site, ok: true, detail: "" }), health: async (_d, site) => ({ site, ok: site !== "a.com", detail: "502" }) }; + const [r] = await teamsRotateKeysAction("t", { keys: ["CRON_SECRET"] }, { ...quiet, approve: true, propagate: root }, { ops: sick, strayText: () => [] }); + expect(r!.status).toBe("skipped"); + expect(await team.read("a--prod", "CRON_SECRET")).toBe(OLD); + }); + + it("provider: mints via the rotator, revokes the old key only after health, saves the new id", async () => { + const team = await makeTeam({ "a--prod": { RESEND_API_KEY: "re_old_xxxxxxxxxxxxxxxx" } }); + writeFileSync(join(root, "a.com", "app.env"), "RESEND_API_KEY=re_old_xxxxxxxxxxxxxxxx\n"); + writeFileSync(join(root, "b.com", "app.env"), "X=1\n"); + const order: string[] = []; + const fetch = (async (url: any, init: any = {}) => { + const m = init.method ?? "GET"; + order.push(`${m} ${new URL(String(url)).pathname}`); + if (m === "POST") return new Response(JSON.stringify({ id: "new-id", token: "re_new_yyyyyyyyyyyyyyyy" }), { status: 201 }); + return new Response(JSON.stringify({ data: [] }), { status: 200 }); + }) as typeof globalThis.fetch; + const o = ops(); + const wrapped: SiteOps = { restart: async (d, s, b) => (order.push(`restart ${s}`), o.restart(d, s, b)), health: (d, s) => o.health(d, s) }; + const [r] = await teamsRotateKeysAction("t", { keys: ["RESEND_API_KEY"] }, { ...quiet, approve: true, propagate: root }, { ops: wrapped, fetch, strayText: () => [], env: {} }); + expect(r!.status).toBe("rotated"); + expect(await team.read("a--prod", "RESEND_API_KEY")).toBe("re_new_yyyyyyyyyyyyyyyy"); + expect(order.indexOf("restart a.com")).toBeGreaterThan(order.indexOf("POST /api-keys")); + expect(r!.note).toMatch(/delete the previous key/); // first rotation: old id unknown + expect(JSON.parse((await team.read("a--prod", "__ROTATE__RESEND_API_KEY"))!).state).toEqual({ keyId: "new-id" }); + }); + + it("provider rollback deletes the new credential and restores the old value", async () => { + const team = await makeTeam({ "a--prod": { RESEND_API_KEY: "re_old_xxxxxxxxxxxxxxxx" } }); + writeFileSync(join(root, "a.com", "app.env"), "RESEND_API_KEY=re_old_xxxxxxxxxxxxxxxx\n"); + const deletes: string[] = []; + const fetch = (async (url: any, init: any = {}) => { + const m = init.method ?? "GET"; + if (m === "DELETE") deletes.push(new URL(String(url)).pathname); + if (m === "POST") return new Response(JSON.stringify({ id: "new-id", token: "re_new_yyyyyyyyyyyyyyyy" }), { status: 201 }); + return new Response(JSON.stringify({ data: [] }), { status: 200 }); + }) as typeof globalThis.fetch; + const [r] = await teamsRotateKeysAction("t", { keys: ["RESEND_API_KEY"] }, { ...quiet, approve: true, propagate: root }, { ops: ops(["a.com"]), fetch, strayText: () => [], env: {} }); + expect(r!.status).toBe("rolled-back"); + expect(deletes).toEqual(["/api-keys/new-id"]); + expect(await team.read("a--prod", "RESEND_API_KEY")).toBe("re_old_xxxxxxxxxxxxxxxx"); + expect(readFileSync(join(root, "a.com", "app.env"), "utf8")).toBe("RESEND_API_KEY=re_old_xxxxxxxxxxxxxxxx\n"); + process.exitCode = 0; + }); +}); diff --git a/packages/cli/src/rotate-keys.test.ts b/packages/cli/src/rotate-keys.test.ts index 927fcd2b..40e3108e 100644 --- a/packages/cli/src/rotate-keys.test.ts +++ b/packages/cli/src/rotate-keys.test.ts @@ -38,8 +38,8 @@ describe("catalog", () => { expect(catalogSpec("SSH_ID_ED25519")?.method).toBe("ssh-keygen"); expect(catalogSpec("SSH_ID_ED25519_DEPLOY")?.method).toBe("ssh-keygen"); expect(catalogSpec("DEPLOY_KEY")?.method).toBe("ssh-keygen"); - expect(catalogSpec("SSH_ID_ED25519_PUB")).toBeNull(); - expect(catalogSpec("SSH_CONFIG")).toBeNull(); + expect(catalogSpec("SSH_ID_ED25519_PUB")?.method).toBe("not-secret"); + expect(catalogSpec("SSH_CONFIG")?.method).toBe("not-secret"); expect(isNotSecret("SSH_KNOWN_HOSTS")).toBe(true); }); @@ -52,7 +52,7 @@ describe("catalog", () => { }); it("knows nothing about plain config", () => { - expect(catalogSpec("SOLANA_RPC_URL")).toBeNull(); + expect(catalogSpec("SOLANA_RPC_URL")?.method).toBe("not-secret"); expect(catalogSpec("NODE_ENV")).toBeNull(); }); }); diff --git a/packages/cli/src/rotate-keys.ts b/packages/cli/src/rotate-keys.ts index 486c94c1..d894bcf6 100644 --- a/packages/cli/src/rotate-keys.ts +++ b/packages/cli/src/rotate-keys.ts @@ -1,6 +1,6 @@ import { spawnSync } from "node:child_process"; -import { mkdtempSync, readFileSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { chmodSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { homedir, tmpdir } from "node:os"; import { join } from "node:path"; import { decodeSshFile, @@ -25,6 +25,8 @@ import { type PlannedRotation, type RotationSpec } from "./rotation-catalog.js"; +import { ROTATORS, defaultRun, rewriteUrls, type Minted, type ProviderRotator, type RotatorContext } from "./rotators.js"; +import { dev2Ops, findConsumers, inBatches, restoreBackup, rewriteEnvFile, type SiteOps } from "./propagate.js"; /** * `logicsrc teams rotation` what rotating each secret takes (never values) @@ -146,6 +148,8 @@ export async function teamsRotationAction(slug: string, filter: RotationFilter, key: p.key, method: p.method, auto: p.automatic ? "yes" : "no", + family: p.spec?.family ?? "", + owner: p.spec?.owner ?? "", source: p.source, vaults: p.vaults.length + ((p as { alsoIn?: string[] }).alsoIn?.length ?? 0), since: String(p.oldestUpdate).slice(0, 10), @@ -153,7 +157,9 @@ export async function teamsRotationAction(slug: string, filter: RotationFilter, })) ); const auto = plan.filter((p) => p.automatic).length; - console.error(`\n${plan.length} value(s): ${auto} automatic, ${plan.length - auto} need a person or agent. Steps per key: --format json.`); + const unknown = plan.filter((p) => p.method === "unknown").length; + const never = plan.filter((p) => p.spec?.never).length; + console.error(`\n${plan.length} value(s): ${auto} automatic, ${plan.length - auto - unknown} manual (${never} never automated), ${unknown} without instructions. Steps per key: --format json.`); console.error(`Rotate: logicsrc teams rotate-keys ${slug}${filter.project ? ` ${filter.project}` : ""}${filter.env ? ` ${filter.env}` : ""} [--key NAME] --approve`); } else { print(plan.map(({ fingerprint: _fp, ...p }) => p), options.format); @@ -215,6 +221,18 @@ export interface RotateKeysOptions { approve: boolean; setFromStdin?: boolean; format: OutputFormat; + /** Rewrite + restart + health-check consumer sites under this root (dev2: ~/www). */ + propagate?: string; + /** Unattended mode: only methods that are automatic, non-disruptive, and two-phase (or a plain random secret with known consumers). */ + scheduled?: boolean; + /** Stop after this many live rotations. */ + max?: number; + /** Write the JSON results (never values) to this file as well. */ + report?: string; + /** Sites never rewritten or restarted: a value they hold is skipped. */ + excludeSites?: string[]; + /** Unattended mode: skip values read by more sites than this (default 5). */ + maxSites?: number; } interface KeyPair { @@ -286,10 +304,20 @@ async function makeReplacement(p: PlannedRotation, oldValue: string, stdinValue? } } +export interface ConsumerReport { + site: string; + file: string; + keys: string[]; + backup?: string; + restart?: string; + health?: string; + ok?: boolean; +} + export interface RotationResult { key: string; method: string; - status: "rotated" | "would-rotate" | "todo" | "failed" | "covered"; + status: "rotated" | "would-rotate" | "todo" | "failed" | "rolled-back" | "skipped" | "covered"; /** Every vault:key holding the old value. */ vaults?: string[]; written: string[]; @@ -297,6 +325,13 @@ export interface RotationResult { steps?: string[]; url?: string; consumers?: string[]; + /** Sites found holding the value (with --propagate) and what happened to each. */ + sites?: ConsumerReport[]; + family?: string; + owner?: string; + never?: boolean; + disruptive?: string; + note?: string; error?: string; } @@ -306,9 +341,230 @@ async function readStdin(): Promise { return Buffer.concat(chunks).toString("utf8").replace(/\r?\n$/, ""); } -export async function teamsRotateKeysAction(slug: string, filter: RotationFilter, options: RotateKeysOptions): Promise { +/** Why the unattended job leaves this one to a person, or null when it may rotate it. */ +export function scheduledBlock(p: PlannedRotation): string | null { + const spec = p.spec; + if (!spec || !p.automatic) return "needs a person"; + if (spec.never) return "never automated"; + if (spec.disruptive) return `disruptive: ${spec.disruptive}`; + if (spec.method === "random") return null; + if (spec.method === "provider") { + const r = ROTATORS[spec.provider ?? ""]; + if (!r) return `unknown rotator ${spec.provider}`; + return r.overlap ? null : `${r.title} has no overlap window`; + } + return `${spec.method} needs a person (public key install / command review)`; +} + +const STRAY_PLACES = (): string[] => { + const home = homedir(); + const dirs = [join(home, ".local/bin"), join(home, "scripts/bin")]; + const files: string[] = []; + for (const d of dirs) { + try { + for (const n of readdirSync(d)) files.push(join(d, n)); + } catch { + /* missing */ + } + } + return files; +}; + +/** The crontab and small scripts under ~/.local/bin and ~/scripts/bin: places a secret hides outside env files. */ +function defaultStrayText(): string[] { + const out = [crontabText()]; + for (const f of STRAY_PLACES()) { + try { + if (statSync(f).isFile() && statSync(f).size < 1 << 20) out.push(readFileSync(f, "utf8")); + } catch { + /* unreadable */ + } + } + return out; +} + +function crontabText(): string { + const r = spawnSync("crontab", ["-l"], { encoding: "utf8" }); + return r.status === 0 ? r.stdout : ""; +} + +export interface RotateDeps { + ops?: SiteOps; + fetch?: typeof fetch; + now?: Date; + env?: Record; + /** Extra text to search for stray copies (tests). */ + strayText?: () => string[]; +} + +interface VaultWrite { + vault: VaultState; + name: string; + oldValue: string; + newValue: string; +} + +async function writeValues(team: Loaded, writes: VaultWrite[], which: "newValue" | "oldValue"): Promise { + const written: string[] = []; + for (const vault of [...new Set(writes.map((w) => w.vault))]) { + const upserts = []; + for (const w of writes.filter((x) => x.vault === vault)) { + const value = w[which]; + upserts.push({ name: w.name, ...(await encryptValue(value, await team.dek(vault))), fingerprint: fingerprintValue(value) }); + } + const { applied } = await team.client.putSecrets(vault.id, upserts, []); + for (const name of applied) written.push(`${vault.name}:${name}`); + } + return written; +} + +async function vaultValues(team: Loaded, v: VaultState): Promise> { + const out: Record = {}; + for (const s of v.secrets) { + if (isRotationEntry(s.name) || s.fingerprint === EMPTY_FINGERPRINT) continue; + out[s.name] = await readValue(team, v, s.name); + } + return out; +} + +/** + * Rotate one value with a new one we can make ourselves (random, provider): + * mint -> vaults -> consumers -> health -> revoke, with a full rollback when + * any step after mint fails. + */ +async function rotateTwoPhase( + team: Loaded, + p: PlannedRotation, + targets: Array<{ vault: VaultState; key: string }>, + base: RotationResult, + options: RotateKeysOptions, + deps: Required> & { strayText: () => string[] } +): Promise { + const spec = p.spec!; + const first = targets[0]!; + const oldValue = await readValue(team, first.vault, first.key); + const firstValues = await vaultValues(team, first.vault); + const stamp = deps.now.toISOString().slice(0, 10).replace(/-/g, ""); + + // Who reads it today. Found by value, so renamed copies count too. + const probe = [{ oldValue, newValue: oldValue }]; + const hits = options.propagate ? findConsumers(options.propagate, probe) : []; + const sites: ConsumerReport[] = hits.map((h) => ({ site: h.site, file: h.file, keys: h.keys })); + const strays = deps.strayText().some((t) => oldValue.length >= 12 && t.includes(oldValue)); + const excluded = hits.filter((h) => options.excludeSites?.includes(h.site)); + if (excluded.length) return { ...base, status: "skipped", sites, error: `excluded site holds it: ${[...new Set(excluded.map((h) => h.site))].join(", ")}` }; + if (options.scheduled) { + const n = new Set(hits.map((h) => h.site)).size; + if (n > (options.maxSites ?? 5)) return { ...base, status: "skipped", sites, error: `too many consumers for unattended rotation: ${n} sites (run it by hand with --propagate)` }; + if (!options.propagate) return { ...base, status: "skipped", sites, error: "unattended rotation needs --propagate" }; + if (!hits.length) return { ...base, status: "skipped", sites, error: "no consumer found on this box: rotate by hand where it is used" }; + if (strays) return { ...base, status: "skipped", sites, error: "also in the crontab or a script under ~/.local/bin or ~/scripts/bin: update those by hand" }; + } + if (spec.method === "provider") { + const r = ROTATORS[spec.provider ?? ""]; + if (!r) return { ...base, status: "todo", sites, error: `unknown rotator ${spec.provider}` }; + const why = await r.preflight({ key: p.key, oldValue, vaultValues: firstValues, state: spec.state ?? {}, env: deps.env, fetch: deps.fetch, run: defaultRun, now: deps.now }); + if (why) return { ...base, status: "todo", sites, error: why }; + } + if (!options.approve) return { ...base, status: "would-rotate", sites }; + // A site that is already down would make the rotation look guilty. + const siteDirs = [...new Map(hits.map((h) => [h.dir, h])).values()]; + const before = await inBatches(siteDirs, 3, (h) => deps.ops.health(h.dir, h.site)); + const sick = before.filter((b) => !b.ok); + if (sick.length) return { ...base, status: "skipped", sites, error: `unhealthy before rotation: ${sick.map((s) => `${s.site} (${s.detail})`).join(", ")}` }; + + let rotator: ProviderRotator | undefined; + let minted: Minted; + if (spec.method === "provider") { + rotator = ROTATORS[spec.provider ?? ""]; + if (!rotator) return { ...base, status: "todo", error: `unknown rotator ${spec.provider}` }; + const ctx: RotatorContext = { key: p.key, oldValue, vaultValues: firstValues, state: spec.state ?? {}, env: deps.env, fetch: deps.fetch, run: defaultRun, now: deps.now }; + minted = await rotator.mint(ctx); + } else { + const replacement = await makeReplacement(p, oldValue); + const value = replacement.valueFor(first.key, oldValue); + minted = { value, revokeOld: async () => undefined, rollback: async () => undefined }; + } + + // Vault writes: the value itself everywhere, plus companions (public halves, connection strings) where they live. + const writes: VaultWrite[] = []; + const companionReps: Array<{ oldValue: string; newValue: string }> = []; + for (const vault of [...new Set(targets.map((t) => t.vault))]) { + const values = vault === first.vault ? firstValues : await vaultValues(team, vault); + for (const t of targets.filter((x) => x.vault === vault)) writes.push({ vault, name: t.key, oldValue: values[t.key] ?? oldValue, newValue: minted.value }); + const extra: Record = { ...rewriteUrls(values, oldValue, minted.value) }; + for (const [name, v] of Object.entries(minted.companions ?? {})) if (name in values && !rewriteUrls({ [name]: values[name]! }, oldValue, minted.value)[name]) extra[name] = v; + for (const [name, v] of Object.entries(extra)) { + if (writes.some((w) => w.vault === vault && w.name === name)) continue; + writes.push({ vault, name, oldValue: values[name]!, newValue: v }); + if (values[name] !== v && values[name]!.length >= 12 && !values[name]!.includes(oldValue)) companionReps.push({ oldValue: values[name]!, newValue: v }); + } + } + + const undo = async (why: string, rewritten: Array<{ file: string; backup: string; dir: string; site: string }>): Promise => { + const notes: string[] = [why]; + try { + await writeValues(team, writes, "oldValue"); + } catch (err) { + notes.push(`VAULTS NOT RESTORED: ${(err as Error).message}`); + } + for (const r of rewritten) restoreBackup(r.file, r.backup); + const restarted = await inBatches([...new Map(rewritten.map((r) => [r.dir, r])).values()], 3, (r) => deps.ops.restart(r.dir, r.site, false)); + for (const r of restarted.filter((x) => !x.ok)) notes.push(`${r.site} did not come back on the old value: ${r.detail}`); + const rb = await minted.rollback().catch((e: Error) => e.message); + if (rb) notes.push(rb); + return { ...base, status: "rolled-back", sites, error: notes.join("; ") }; + }; + + let written: string[]; + try { + written = await writeValues(team, writes, "newValue"); + } catch (err) { + return undo(`vault write failed: ${(err as Error).message}`, []); + } + + // Consumers: rewrite env files (with backups), restart 3 at a time, health-check. + const reps = [{ oldValue, newValue: minted.value }, ...companionReps]; + const rewritten: Array<{ file: string; backup: string; dir: string; site: string }> = []; + if (options.propagate) { + const now = findConsumers(options.propagate, reps); + for (const h of now) { + const { backup } = rewriteEnvFile(h.file, reps, stamp); + rewritten.push({ file: h.file, backup, dir: h.dir, site: h.site }); + const rep = sites.find((s) => s.file === h.file); + if (rep) rep.backup = backup; + else sites.push({ site: h.site, file: h.file, keys: h.keys, backup }); + } + const dirs = [...new Map(now.map((h) => [h.dir, { ...h, needsBuild: now.some((x) => x.dir === h.dir && x.needsBuild) }])).values()]; + const results = await inBatches(dirs, 3, async (h) => { + const r = await deps.ops.restart(h.dir, h.site, h.needsBuild); + const hl = r.ok ? await deps.ops.health(h.dir, h.site) : { site: h.site, ok: false, detail: "not restarted" }; + for (const s of sites.filter((x) => x.site === h.site)) Object.assign(s, { restart: r.detail, health: hl.detail, ok: r.ok && hl.ok }); + return r.ok && hl.ok; + }); + if (results.some((ok) => !ok)) return undo("a consumer failed after the switch; rolled back", rewritten); + } + + const revokeNote = await minted.revokeOld().catch((e: Error) => `revoking the old credential failed (it is still live): ${e.message}`); + // Remember provider ids for next time (the old key's id is what revokeOld needs). + if (minted.state && Object.keys(minted.state).length) { + const entry = rotationEntryName(first.key); + const value = JSON.stringify({ ...spec, state: minted.state }); + await team.client.putSecrets(first.vault.id, [{ name: entry, ...(await encryptValue(value, await team.dek(first.vault))), fingerprint: fingerprintValue(value) }], []); + } + return { ...base, status: "rotated", written, sites, ...(revokeNote ? { note: revokeNote } : {}) }; +} + +export async function teamsRotateKeysAction(slug: string, filter: RotationFilter, options: RotateKeysOptions, depsIn: RotateDeps = {}): Promise { const { team, plan, invalid } = await buildPlan(slug, filter); if (plan.length === 0) throw new Error("Nothing to rotate: no matching keys. See: logicsrc teams rotation " + slug); + const deps = { + ops: depsIn.ops ?? dev2Ops, + fetch: depsIn.fetch ?? fetch, + now: depsIn.now ?? new Date(), + env: depsIn.env ?? process.env, + strayText: depsIn.strayText ?? defaultStrayText + }; let stdinValue: string | undefined; if (options.setFromStdin) { @@ -320,6 +576,7 @@ export async function teamsRotateKeysAction(slug: string, filter: RotationFilter const results: RotationResult[] = []; // One value stored under two names is one rotation, not two. const handled = new Map(); + let live = 0; for (const p of plan) { const earlier = handled.get(p.fingerprint); if (earlier && (p.automatic || stdinValue !== undefined)) { @@ -327,18 +584,56 @@ export async function teamsRotateKeysAction(slug: string, filter: RotationFilter continue; } handled.set(p.fingerprint, p.key); - const base = { key: p.key, method: stdinValue !== undefined ? "set" : p.method, steps: p.spec?.steps, url: p.spec?.url, consumers: p.spec?.consumers }; + const spec = p.spec; + const base: RotationResult = { + key: p.key, + method: stdinValue !== undefined ? "set" : spec?.method === "provider" ? `provider:${spec.provider}` : p.method, + status: "todo", + written: [], + steps: spec?.steps, + url: spec?.url, + consumers: spec?.consumers, + family: spec?.family, + owner: spec?.owner ?? (spec?.method === "manual" ? "agent" : undefined), + never: spec?.never, + disruptive: spec?.disruptive, + note: spec?.note + }; const targets = siblings(team, p.fingerprint); - const where = targets.map((t) => `${t.vault.name}:${t.key}`); + base.vaults = targets.map((t) => `${t.vault.name}:${t.key}`); if (stdinValue === undefined && !p.automatic) { - results.push({ ...base, status: "todo", vaults: where, written: [], steps: p.spec?.steps ?? ["No instructions: add some with logicsrc teams rotation-set."] }); + results.push({ ...base, status: "todo", steps: spec?.steps ?? ["No instructions: add some with logicsrc teams rotation-set."] }); continue; } - if (!options.approve) { - results.push({ ...base, status: "would-rotate", vaults: where, written: [] }); + if (options.scheduled && stdinValue === undefined) { + const why = scheduledBlock(p); + if (why) { + results.push({ ...base, status: "skipped", error: why }); + continue; + } + } + // A plain dry run only plans; with --propagate or --scheduled it also runs the read-only checks. + if (!options.approve && !options.propagate && !options.scheduled) { + results.push({ ...base, status: "would-rotate" }); + continue; + } + if (options.approve && options.max !== undefined && live >= options.max) { + results.push({ ...base, status: "skipped", error: `--max ${options.max} reached` }); continue; } try { + if (stdinValue === undefined && (spec?.method === "random" || spec?.method === "provider")) { + const r = await rotateTwoPhase(team, p, targets, base, options, deps); + if (r.status === "rotated" || r.status === "rolled-back") live++; + results.push(r); + continue; + } + // ssh-keygen, command and --set-from-stdin: vault write only, consumers by hand. + if (!options.approve) { + results.push({ ...base, status: "would-rotate" }); + continue; + } + live++; const first = targets[0]!; const oldValue = await readValue(team, first.vault, first.key); const replacement = await makeReplacement(p, oldValue, stdinValue); @@ -368,22 +663,36 @@ export async function teamsRotateKeysAction(slug: string, filter: RotationFilter const { applied } = await team.client.putSecrets(vault.id, upserts, []); for (const name of applied) written.push(`${vault.name}:${name}`); } - results.push({ ...base, status: "rotated", vaults: where, written, publicKey: replacement.publicKey }); + results.push({ ...base, status: "rotated", written, publicKey: replacement.publicKey }); } catch (err) { results.push({ ...base, status: "failed", written: [], error: (err as Error).message }); } } + if (options.report) { + writeFileSync(options.report, JSON.stringify({ team: slug, at: deps.now.toISOString(), approve: options.approve, scheduled: Boolean(options.scheduled), results, locked: team.locked }, null, 2), { mode: 0o600 }); + chmodSync(options.report, 0o600); + } if (options.format === "table") { - printColumns(results.map((r) => ({ key: r.key, method: r.method, status: r.status, vaults: (r.status === "rotated" ? r.written : r.vaults ?? []).length, next: r.status === "todo" ? (r.url ?? "see --format json") : r.error ?? "" }))); + printColumns( + results.map((r) => ({ + key: r.key, + method: r.method, + status: r.status, + vaults: (r.status === "rotated" ? r.written : r.vaults ?? []).length, + sites: r.sites?.length ?? "", + next: r.status === "todo" ? (r.error ?? r.url ?? "see --format json") : r.error ?? r.note ?? "" + })) + ); for (const r of results.filter((x) => x.publicKey)) console.error(`\n${r.key} new public key (install it, remove the old one):\n${r.publicKey}`); const todo = results.filter((r) => r.status === "todo").length; if (!options.approve) console.error(`\nDry run. Apply with --approve.${todo ? ` ${todo} key(s) need a person or agent: --format json lists the steps.` : ""}`); - else console.error(`\nRestart or redeploy whatever reads the rotated values, then revoke the old ones where they were issued.`); + else if (!options.propagate) console.error(`\nRestart or redeploy whatever reads the rotated values (or pass --propagate ~/www), then revoke the old ones where they were issued.`); } else { print(results, options.format); } if (invalid.length) console.error(`Unreadable rotation entries (ignored): ${invalid.join("; ")}`); if (team.locked.length) console.error(`Not covered (no access): ${team.locked.join(", ")}. Copies of these values there stay OLD.`); - if (results.some((r) => r.status === "failed")) process.exitCode = 1; + if (results.some((r) => r.status === "failed" || r.status === "rolled-back")) process.exitCode = 1; + return results; } diff --git a/packages/cli/src/rotation-catalog.test.ts b/packages/cli/src/rotation-catalog.test.ts new file mode 100644 index 00000000..30060ddb --- /dev/null +++ b/packages/cli/src/rotation-catalog.test.ts @@ -0,0 +1,136 @@ +import { describe, expect, it } from "vitest"; +import { catalogSpec, isAutomatic, isNotSecret, planRotations, baseKeyName, EMPTY_FINGERPRINT } from "./rotation-catalog.js"; +import { scheduledBlock } from "./rotate-keys.js"; + +const method = (k: string) => catalogSpec(k)?.method; + +describe("catalog coverage (2026-10-29 plan)", () => { + it("never automates money, signing, the personal vault, Stripe, npm or GitHub App keys", () => { + for (const k of [ + "SYSTEM_MNEMONIC_SOL__1", + "TREASURY_MNEMONIC_ETH", + "PRIVATE_KEY", + "LN_HSM_SECRET_HEX", + "LNBITS_ADMIN_KEY", + "KRAKEN_API_SECRET", + "COINBASE_API_PRIVATE_KEY_B64", + "STRIPE_SECRET_KEY", + "STRIPE_WEBHOOK_SECRET", + "NPM_TOKEN", + "GITHUB_APP_PRIVATE_KEY", + "OPENCREDS_MASTER_PASSWORD", + "OPENCREDS_RECOVERY_KEY", + "W3BS_TUF_ROOT_KEY_PK8_B64", + "DID_PRIVATE_KEY_BASE64", + "MOSHPIT_CA_ROOT_KEY", + "FTB_BUSINESS_PASSWORD" + ]) { + const s = catalogSpec(k); + expect(s?.never, k).toBe(true); + expect(s?.owner, k).toBe("anthony"); + expect(isAutomatic(s), k).toBe(false); + } + }); + + it("never mints random bytes for provider secrets that look like ours", () => { + for (const k of ["SLACK_SIGNING_SECRET", "JWT_SECRET", "SUPABASE_JWT_SECRET", "FIREFOX_JWT_SECRET", "META_APP_SECRET", "GITHUB_WEBHOOK_SECRET"]) { + expect(method(k), k).not.toBe("random"); + } + }); + + it("routes keys with clean APIs to provider rotators", () => { + expect(catalogSpec("RESEND_API_KEY")?.provider).toBe("resend"); + expect(catalogSpec("RESEND_PITWORLD_ADMIN_KEY")?.provider).toBe("resend"); + expect(catalogSpec("CLOUDFLARE_API_TOKEN")?.provider).toBe("cloudflare-token"); + expect(catalogSpec("COINPAY_API_KEY")?.provider).toBe("coinpay-api-key"); + expect(catalogSpec("COINPAYPORTAL_WEBHOOK_SECRET")?.provider).toBe("coinpay-webhook-secret"); + expect(catalogSpec("VAPID_PRIVATE_KEY")?.provider).toBe("vapid"); + expect(catalogSpec("VAPID_PRIVATE")?.provider).toBe("vapid"); + expect(catalogSpec("SUPABASE_DB_PASSWORD")?.provider).toBe("postgres-role"); + }); + + it("classifies public config as not-secret", () => { + for (const k of [ + "COINPAY_OAUTH_CLIENT_ID", + "COINPAY_OAUTH_REDIRECT_URI", + "COINPAY_OAUTH_SCOPES", + "COINPAY_OAUTH_ISSUER", + "STRIPE_PUBLISHABLE_KEY", + "SUPABASE_PUBLISHABLE_KEY", + "HCAPTCHA_SITE_KEY", + "SENTRY_DSN", + "EXPO_PUBLIC_SENTRY_DSN", + "WEBAUTHN_RP_ID", + "SESSION_COOKIE_SECURE", + "TURSO_DATABASE_URL", + "AUTHOR_BATCH_SIZE", + "SYSTEM_KEY_GENERATION", + "JWT_PUBLIC_KEY_JWK", + "R2_ACCESS_KEY_ID", + "__ARCHIVE__SUPABASE_SERVICE_ROLE_KEY" + ]) { + expect(isNotSecret(k), k).toBe(true); + } + // ...but a connection string can hold a password. + expect(isNotSecret("DATABASE_URL")).toBe(false); + expect(catalogSpec("DATABASE_URL")?.family).toBe("postgres"); + expect(isNotSecret("NEXT_PUBLIC_SUPABASE_ANON_KEY")).toBe(false); + }); + + it("gives every secret-looking name from the 2026-10-29 unknown list some instructions", () => { + const unknownBefore = [ + "ADMIN_KEY", "ADNETWORK_KEY", "ANON_KEY", "API_KEY_SALT", "BITTORRENTED_SUPABASE_KEY", "BUILTINDIE_KEY", "CRAWLPROOF_ACTOR_TOKEN_ANTHONY", + "CRYPTO_APIS_KEY", "DB_PASS", "DEALDASH_COOKIE", "FAL_KEY", "GROUPCALL_AGENT_WORKER_KEY", "IMAP_PASS", "IP_HASH_SALT", "OPENACCESS_KEY_UGIG_NET", + "PAYAGENT_KEY", "PG_META_CRYPTO_KEY", "SALAD_AI_GATEWAY_KEY", "SECRET_KEY_BASE", "SEEDBOX_HTTP_AUTH", "SERVICE_ROLE_KEY", "SMTP_PASS", + "SOCIAL_VAULT_KEY", "SUPABASE_SECRETMAT_KEY", "TOKEN_ENC_KEY", "TURN_SERVER_CREDENTIAL", "VOTE_SALT", "SP_TOKEN_PEPPER", "AUR_SSH_KEY__1" + ]; + for (const k of unknownBefore) expect(catalogSpec(k), k).not.toBeNull(); + }); + + it("strips __n duplicate suffixes before matching", () => { + expect(baseKeyName("SYSTEM_MNEMONIC_BTC__2")).toBe("SYSTEM_MNEMONIC_BTC"); + expect(method("CRON_SECRET__1")).toBe("random"); + }); + + it("marks session signers disruptive so the weekly job leaves them", () => { + expect(catalogSpec("SESSION_SECRET")?.disruptive).toBeTruthy(); + expect(catalogSpec("CRON_SECRET")?.disruptive).toBeUndefined(); + }); +}); + +describe("planRotations", () => { + const row = (vault: string, key: string, fingerprint: string) => ({ vault, key, fingerprint, updatedAt: "2026-10-01T00:00:00Z" }); + it("drops not-secret, archive and empty values; an entry can declare not-secret", () => { + const plan = planRotations( + [row("a--prod", "COINPAY_OAUTH_CLIENT_ID", "f1"), row("a--prod", "__ARCHIVE__X", "f2"), row("a--prod", "CRON_SECRET", EMPTY_FINGERPRINT), row("a--prod", "WEIRD_TOKEN", "f3"), row("a--prod", "CRON_SECRET", "f4")], + new Map([["a--prod\u0000WEIRD_TOKEN", { method: "not-secret" as const }]]) + ); + expect(plan.map((p) => p.key)).toEqual(["CRON_SECRET"]); + }); +}); + +describe("entry specs", () => { + it("cannot make a wallet key automatic", () => { + const plan = planRotations([{ vault: "c--prod", key: "TREASURY_MNEMONIC_SOL", fingerprint: "f", updatedAt: "" }], new Map([["c--prod\u0000TREASURY_MNEMONIC_SOL", { method: "random" as const }]])); + expect(plan[0]!.automatic).toBe(false); + expect(plan[0]!.spec?.never).toBe(true); + }); + it("TURN secrets are manual (coturn config holds a copy)", () => { + expect(catalogSpec("TURN_SERVER_CREDENTIAL")?.method).toBe("manual"); + }); +}); + +describe("scheduledBlock", () => { + const p = (spec: any) => ({ key: "K", vaults: ["a--prod"], fingerprint: "f", oldestUpdate: "", method: spec.method, source: "catalog" as const, automatic: isAutomatic(spec), spec }); + it("lets plain random secrets and overlapping provider rotators through, nothing else", () => { + expect(scheduledBlock(p(catalogSpec("CRON_SECRET")))).toBeNull(); + expect(scheduledBlock(p(catalogSpec("RESEND_API_KEY")))).toBeNull(); + expect(scheduledBlock(p(catalogSpec("CLOUDFLARE_API_TOKEN")))).toBeNull(); + expect(scheduledBlock(p(catalogSpec("COINPAY_API_KEY")))).toBeNull(); + expect(scheduledBlock(p(catalogSpec("SESSION_SECRET")))).toMatch(/disruptive/); + expect(scheduledBlock(p(catalogSpec("COINPAY_WEBHOOK_SECRET")))).toMatch(/disruptive/); + expect(scheduledBlock(p(catalogSpec("SUPABASE_DB_PASSWORD")))).toMatch(/disruptive/); + expect(scheduledBlock(p(catalogSpec("SSH_ID_ED25519")))).toMatch(/person/); + expect(scheduledBlock(p(catalogSpec("SYSTEM_MNEMONIC_SOL")))).toMatch(/person|never/); + }); +}); diff --git a/packages/cli/src/rotation-catalog.ts b/packages/cli/src/rotation-catalog.ts index a44957c5..0b7de058 100644 --- a/packages/cli/src/rotation-catalog.ts +++ b/packages/cli/src/rotation-catalog.ts @@ -25,12 +25,19 @@ export function isoTime(value: unknown): string { * public key has to be installed where the old one was. * command a shell command that prints the new value on stdout (a * provider CLI that can mint keys). Runs only with --approve. + * provider a built-in rotator (rotators.ts) that creates the new + * credential by API, and revokes the old one only after every + * consumer is healthy on the new one. * manual a person or agent follows `steps` at `url`. Never automatic: - * provider-issued keys, wallet seeds, encryption keys that - * protect stored data. + * provider-issued keys without a rotator, wallet seeds, + * encryption keys that protect stored data. + * not-secret public config that happens to look like a secret (URLs, + * client ids, publishable keys). Dropped from the plan. */ -export type RotationMethod = "random" | "ssh-keygen" | "command" | "manual"; +export type RotationMethod = "random" | "ssh-keygen" | "command" | "provider" | "manual" | "not-secret"; export type RandomFormat = "hex" | "base64" | "base64url" | "alnum"; +/** Who has to do a manual rotation: an agent with dashboard/CLI access, or Anthony (money, signing ceremonies, his logins). */ +export type RotationOwner = "agent" | "anthony"; export interface RotationSpec { method: RotationMethod; @@ -40,6 +47,8 @@ export interface RotationSpec { length?: number; /** command: prints the new value on stdout. */ command?: string; + /** provider: the rotator id (see rotators.ts). */ + provider?: string; /** Where to do it (provider dashboard, docs). */ url?: string; /** What to do, in order. For manual rotations this is the whole job. */ @@ -48,9 +57,21 @@ export interface RotationSpec { consumers?: string[]; /** Why this method; shown in the plan. */ note?: string; + /** Grouping for reports and the runbook (stripe, supabase, wallet, ...). */ + family?: string; + /** Manual rotations: who must do it. */ + owner?: RotationOwner; + /** Never automated, whatever the method says (moves money, signing ceremony, banned provider). */ + never?: boolean; + /** What a rotation breaks for users (sessions end, push subscriptions die). The weekly job skips these. */ + disruptive?: string; + /** Rotator bookkeeping (e.g. the provider's id for the current key), written back after a rotation. */ + state?: Record; } export const ROTATE_PREFIX = ROTATION_ENTRY_PREFIX; +/** `teams clean` archive records: metadata about an archived value, never consumed. */ +export const ARCHIVE_PREFIX = "__ARCHIVE__"; export function isRotationEntry(name: string): boolean { return name.startsWith(ROTATE_PREFIX); @@ -60,7 +81,7 @@ export function rotationEntryName(key: string): string { return `${ROTATE_PREFIX}${key}`; } -const METHODS: readonly RotationMethod[] = ["random", "ssh-keygen", "command", "manual"]; +const METHODS: readonly RotationMethod[] = ["random", "ssh-keygen", "command", "provider", "manual", "not-secret"]; const FORMATS: readonly RandomFormat[] = ["hex", "base64", "base64url", "alnum"]; /** Parse and validate a stored spec. Throws with a message naming the problem. */ @@ -79,139 +100,349 @@ export function parseRotationSpec(raw: string): RotationSpec { throw new Error("length must be an integer between 16 and 512"); } if (v.method === "command" && (typeof v.command !== "string" || !v.command.trim())) throw new Error("method command needs a command"); + if (v.method === "provider" && (typeof v.provider !== "string" || !v.provider.trim())) throw new Error("method provider needs a provider"); + if (v.owner !== undefined && v.owner !== "agent" && v.owner !== "anthony") throw new Error("owner must be agent or anthony"); const strings = (x: unknown): string[] | undefined => Array.isArray(x) ? x.filter((s): s is string => typeof s === "string" && s.trim() !== "") : undefined; + const state = + v.state && typeof v.state === "object" && !Array.isArray(v.state) + ? Object.fromEntries(Object.entries(v.state as Record).filter((e): e is [string, string] => typeof e[1] === "string")) + : undefined; return { method: v.method as RotationMethod, ...(v.format ? { format: v.format as RandomFormat } : {}), ...(v.length ? { length: v.length as number } : {}), ...(typeof v.command === "string" ? { command: v.command } : {}), + ...(typeof v.provider === "string" ? { provider: v.provider } : {}), ...(typeof v.url === "string" ? { url: v.url } : {}), ...(strings(v.steps) ? { steps: strings(v.steps) } : {}), ...(strings(v.consumers) ? { consumers: strings(v.consumers) } : {}), - ...(typeof v.note === "string" ? { note: v.note } : {}) + ...(typeof v.note === "string" ? { note: v.note } : {}), + ...(typeof v.family === "string" ? { family: v.family } : {}), + ...(v.owner ? { owner: v.owner as RotationOwner } : {}), + ...(v.never === true ? { never: true } : {}), + ...(typeof v.disruptive === "string" ? { disruptive: v.disruptive } : {}), + ...(state && Object.keys(state).length ? { state } : {}) }; } +const STORE = "Store it: logicsrc teams rotate-keys --key --set-from-stdin --approve (writes every vault holding the old value)."; +const REDEPLOY = "Redeploy every consumer the plan lists, check each health URL."; const REVOKE = "Revoke the old key once every consumer runs on the new one."; -function provider(name: string, url: string, extra: string[] = []): RotationSpec { +function provider(name: string, url: string, extra: string[] = [], more: Partial = {}): RotationSpec { return { method: "manual", + owner: "agent", url, - steps: [`Create a new key in ${name} (${url}).`, ...extra, "Store it: logicsrc teams rotate-keys --key --set-from-stdin", REVOKE] + steps: [`Create a new key in ${name}${url ? ` (${url})` : ""}.`, ...extra, STORE, REDEPLOY, REVOKE], + ...more }; } +/** Anthony has to do it: his login/2FA, a signing ceremony, or money. */ +function anthony(family: string, note: string, steps: string[], url?: string): RotationSpec { + return { method: "manual", owner: "anthony", never: true, family, note, steps, ...(url ? { url } : {}) }; +} + +function auto(provider: string, family: string, extra: Partial = {}): RotationSpec { + return { method: "provider", provider, family, ...extra }; +} + interface CatalogRule { test: RegExp; spec: RotationSpec; } +const WALLET_STEPS = [ + "Generate a new wallet on a trusted machine (never on a server).", + "Move every balance (tokens and native gas) from the old address to the new one. A person signs this: it moves money.", + "Store the new key/seed under the same name (CoinPay system keys go in the CoinPay operator vault, not app.env), then update anything that pays to or watches the old address.", + "Never reuse the old seed: assume it is public." +]; + +const SIGNING_STEPS = [ + "Generate the new key pair on a trusted machine.", + "Publish the new public half where verifiers look for it (DID document, TUF root, PLC directory, keyserver, MCP registry) BEFORE switching signers.", + "Store the new private key, redeploy the signer, keep the old public key trusted until everything signed with it has expired.", + "Revoke the old key in the same place you published the new one." +]; + /** * Order matters: the first match wins, so specific names come before the broad - * suffix rules at the bottom. + * suffix rules at the bottom. Names are matched upper-cased with any `__` + * duplicate suffix removed (KEY__1 is the second copy of KEY). */ const CATALOG: CatalogRule[] = [ - // Things whose "rotation" moves money or re-encrypts data: never automatic. + // ---- never automated: personal vault, money, signing ceremonies, banned providers -------- { - test: /(MNEMONIC|SEED_PHRASE|WALLET_PRIVATE_KEY|^(EVM|SOLANA|SOL|ETH|BTC|TRON)_PRIVATE_KEY$|X402_.*PRIVATE_KEY)/, + test: /^OPENCREDS_(MASTER_PASSWORD|RECOVERY_KEY)$/, + spec: anthony("personal-vault", "unlocks Anthony's personal vault", [ + "Anthony only: logicsrc vault passwd (new master password), then save the new recovery key it prints.", + "Update the copy in the anthony-personal vault by hand at a terminal." + ]) + }, + { + test: /(MNEMONIC|SEED_PHRASE|^TREASURY_|WALLET_PRIVATE_KEY|^(EVM|SOLANA|SOL|ETH|BTC|TRON|XRP|PRIVATE)_?(PRIVATE_)?KEY$|^PRIVATE_KEY$|X402_.*PRIVATE_KEY|TREASURY|LN_HSM_SECRET|HSM_SECRET|^LNBITS_.*(ADMIN|INVOICE|PAYLINK)_KEY$|^LNBITS_SUPERUSER_PASSWORD$|RELAYER.*KEY|^QRYPT_WEB_ISSUER_SEED$)/, + spec: anthony("wallet", "a wallet or Lightning key: rotating it means moving funds", WALLET_STEPS) + }, + { + test: /^(KRAKEN|BINANCE(_US)?|COINBASE|ALPACA|APCA|CHANGENOW|SIDESHIFT|ZEROX|MOONPAY|PLAID|PAYPAL(_PLATFORM|_SANDBOX)?|WATCHWALLET)_.*(KEY|SECRET|PASSWORD|B64)$/, + spec: anthony("exchange", "an exchange, ramp or bank-link credential: it can move money", [ + "Anthony: create a new key in the provider dashboard with the same (least) permissions; 2FA is his.", + STORE, + REDEPLOY, + "Delete the old key in the dashboard." + ]) + }, + { + test: /^STRIPE_/, + spec: anthony("stripe", "Stripe is banned for new work: never rotated by automation", [ + "Anthony: Stripe dashboard > Developers > API keys > Roll key (or the webhook endpoint > Roll secret).", + STORE, + REDEPLOY + ], "https://dashboard.stripe.com/apikeys") + }, + { + test: /^NPM_TOKEN$|^PYPI_API_TOKEN$|^CHOCOLATEY_API_KEY$/, + spec: anthony("package-registry", "publishes packages: a person creates it", [ + "Anthony: create a granular automation token on the registry (npmjs.com > Access Tokens), scoped to the packages it publishes.", + STORE, + "Delete the old token on the registry." + ], "https://www.npmjs.com/settings/~/tokens") + }, + { + test: /^GITHUB_APP_(PRIVATE_KEY|CLIENT_SECRET|WEBHOOK_SECRET)$|^GITHUB_MARKETPLACE_WEBHOOK_SECRET$/, + spec: anthony("github-app", "GitHub App credentials are made in the App settings UI", [ + "Anthony: github.com/settings/apps/ (or the org's) > Generate a private key / new client secret / webhook secret.", + STORE, + REDEPLOY, + "Delete the old private key in the App settings." + ], "https://github.com/settings/apps") + }, + { + test: /(^|_)(DID_PRIVATE_KEY|MCP_(REGISTRY|PUBLISHER)_PRIVATE_KEY|PLC_ROTATION_KEY|TUF_.*_KEY|PUBLISHER_KEY|POWER_KEY_PRIVATE_KEY|GPG_PRIVATE_KEY|CA_(ROOT_)?KEY|NOSTR_PRIVATE_KEY|CLIENT_JWT_PRIVATE_KEY|JWT_KEYS|FIREBASE_PRIVATE_KEY)/, + spec: anthony("signing", "a signing identity: verifiers pin the public half", SIGNING_STEPS) + }, + { + test: /^(FTB|IRS|EFTPS|MAIL|CAL|NVIDIA|REDDIT|BLUESKY|MASTODON|BRAVE|APPLE|RIOTCODER|CHA0SPUNK|SEED\d*|OUTREACHGRAPH|THREATCRUSH|MOSHPIT|COINPAY|W3BS_SOCIAL|GIT_CHOVY|MYNA_CLOUD|EPIC|EXTELLA|PDL|HUNTER|CONTACTOUT|FULLENRICH|ROCKETREACH|SERPAPI|SERPER|DATAFORSEO|STOPFORUMSPAM|ABUSEIPDB|PROXIWARE|SALAD|OPENSUBTITLES|WEBSHARE|[A-Z0-9]+_AFFILIATE)(_[A-Z0-9]+)*_(PASSWORD|APP_SPECIFIC_PASSWORD|SUDO_PASSWORD)$/, + spec: anthony("account-login", "a human account login (often behind 2FA or email confirmation)", [ + "Sign in to the account and change the password there (2FA/email confirmation goes to Anthony).", + "Save it in the personal vault (logicsrc vault) and, if an app logs in with it, store it: " + STORE.slice(10) + ]) + }, + + // ---- data at rest: a new value makes stored data unreadable ------------------------------ + { + test: /(^|_)(ENCRYPTION_KEY|MASTER_KEY|DB_ENCRYPTION_KEY|SETTINGS_ENCRYPTION_KEY|LN_KEY_ENCRYPTION_KEY|TOKEN_ENC_KEY|CRYPTO_KEY|VAULT_KEY|KEYS_SECRET|API_KEY_SALT|TOKEN_PEPPER|SUPPRESSION_HASH_SALT|VOTE_SALT|SUBMISSION_SALT|OTR_SALT|DHT_API_KEY_SALT)$/, spec: { method: "manual", - note: "a wallet key: rotating it means moving funds", + owner: "agent", + family: "data-at-rest", + note: "protects or indexes stored data: a new value makes old ciphertext or hashes unreadable", steps: [ - "Generate a new wallet on a trusted machine.", - "Move every balance (tokens and native gas) from the old address to the new one.", - "Store the new key/seed under the same name, then update anything that pays to or watches the old address.", - "Never reuse the old seed: assume it is public." + "Add the new key next to the old one (dual-read), or run the app's re-encryption / re-hash migration.", + "Re-encrypt (or re-hash) stored data under the new key.", + "Remove the old key only after every row decrypts or matches with the new one." ] } }, { - test: /(^|_)(ENCRYPTION_KEY|MASTER_KEY|DB_ENCRYPTION_KEY|SETTINGS_ENCRYPTION_KEY|LN_KEY_ENCRYPTION_KEY|NEXT_SERVER_ACTIONS_ENCRYPTION_KEY)$/, - spec: { - method: "manual", - note: "protects data at rest: a new value makes old ciphertext unreadable", - steps: [ - "Add the new key next to the old one (dual-read), or run the app's re-encryption migration.", - "Re-encrypt stored data under the new key.", - "Remove the old key only after every row decrypts with the new one." - ] - } + // Next's server-actions key encrypts closures in flight only: a redeploy is all it needs. + test: /^NEXT_SERVER_ACTIONS_ENCRYPTION_KEY$/, + spec: { method: "random", family: "internal", format: "base64", length: 44, note: "Next server actions key: in-flight only", disruptive: "open tabs lose pending server actions until reload" } }, + + // ---- SSH ----------------------------------------------------------------------------------- { // Raw keys (DEPLOY_KEY=...) and the ssh provider's file envelopes (SSH_ID_ED25519). test: /(^|_)(SSH_PRIVATE_KEY|DEPLOY_KEY|SSH_KEY)$|^SSH_(.*_)?ID_(RSA|ED25519|ECDSA|DSA)(_[A-Z0-9_]+)?$|^SSH_.*_(KEY|PEM)$/, spec: { method: "ssh-keygen", + family: "ssh", steps: [ "Install the new public key everywhere the old one was authorized (authorized_keys on every host, GitHub deploy/user keys, CI secrets).", "Remove the old public key from all of those places.", - "Pull the new private key onto the machines that use it: logicsrc teams pull / logicsrc ssh pull." + "Pull the new private key onto the machines that use it: logicsrc teams pull / logicsrc ssh pull / logicsrc keyring." ] } }, - // Secrets we invent and only we check: mint a new random value. + + // ---- built-in API rotators -------------------------------------------------------------- + { test: /^RESEND(_[A-Z0-9]+)*_(API|ADMIN)_KEY$/, spec: auto("resend", "resend", { url: "https://resend.com/api-keys" }) }, + { + test: /^(CLOUDFLARE|CF)(_[A-Z0-9]+)*_(API_TOKEN|TOKEN)$/, + spec: auto("cloudflare-token", "cloudflare", { url: "https://dash.cloudflare.com/profile/api-tokens" }) + }, + { + test: /^(COINPAY|COINPAYPORTAL|CHOVY_COINPAY)(_[A-Z0-9]+)*_API_KEY$|^COINPAY_X402_KEY$/, + spec: auto("coinpay-api-key", "coinpay", { url: "https://coinpayportal.com/dashboard" }) + }, + { + test: /^(COINPAY|COINPAYPORTAL|CHOVY_COINPAY)(_[A-Z0-9]+)*_WEBHOOK_SECRET$/, + spec: auto("coinpay-webhook-secret", "coinpay", { + url: "https://coinpayportal.com/dashboard", + disruptive: "CoinPay has one webhook secret per business: webhooks fail signature checks until the consumer restarts (CoinPay retries them)" + }) + }, + { + test: /^VAPID_PRIVATE(_KEY)?$/, + spec: auto("vapid", "vapid", { disruptive: "every existing push subscription stops working; browsers must subscribe again" }) + }, + { + test: /^(POSTGRES_PASSWORD|DB_PASS(WORD)?|PG_?PASSWORD|[A-Z0-9_]*_DB_PASSWORD)$/, + spec: auto("postgres-role", "postgres", { + disruptive: "Postgres keeps one password per role: consumers that are not restarted fail to connect", + note: "self-hosted Supabase shares this password across its service roles: see the runbook" + }) + }, + + // ---- provider-issued keys without a rotator (yet) ---------------------------------------- + { test: /^(GITHUB|GH)(_[A-Z0-9]+)*_(TOKEN|PAT)$/, spec: provider("GitHub (fine-grained token, same repos and permissions)", "https://github.com/settings/tokens", [], { family: "github" }) }, + { test: /^GITHUB(_[A-Z0-9]+)*_(CLIENT_SECRET|WEBHOOK_SECRET)$|^GL_WEBHOOK_SECRET$/, spec: provider("the GitHub OAuth app / webhook settings (Generate a new client secret; GitHub keeps two live)", "https://github.com/settings/developers", [], { family: "github" }) }, + { test: /^ANTHROPIC_API_KEY$/, spec: provider("the Anthropic console", "https://console.anthropic.com/settings/keys", [], { family: "ai" }) }, + { test: /^OPENAI_API_KEY$/, spec: provider("the OpenAI dashboard (same project)", "https://platform.openai.com/api-keys", [], { family: "ai" }) }, + { test: /^(GEMINI|GOOGLE)_API_(KEY|SECRET)$|^EXPO_PUBLIC_GOOGLE_API_KEY$/, spec: provider("Google Cloud credentials (same API restrictions)", "https://console.cloud.google.com/apis/credentials", [], { family: "google" }) }, + { test: /^GOOGLE(_OAUTH)?_CLIENT_SECRET$|^CHROME_(CLIENT_SECRET|REFRESH_TOKEN)$/, spec: provider("Google Cloud OAuth client (Add secret, then disable the old one)", "https://console.cloud.google.com/apis/credentials", [], { family: "google" }) }, + { + test: /^SUPABASE_ACCESS_TOKEN$/, + spec: provider("Supabase account tokens", "https://supabase.com/dashboard/account/tokens", [], { family: "supabase" }) + }, + { + test: /^(SUPABASE_SERVICE_ROLE_KEY|SUPABASE_SERVICE_KEY|SUPABASE_SECRET_KEY|SUPABASE_SECRETMAT_KEY|SERVICE_ROLE_KEY(_ASYMMETRIC)?|SUPABASE_JWT_SECRET|JWT_SECRET|NEXT_PUBLIC_SUPABASE_ANON_KEY|VITE_SUPABASE_ANON_KEY|PUBLIC_SUPABASE_ANON_KEY|SUPABASE_ANON_KEY|ANON_KEY(_ASYMMETRIC)?|[A-Z0-9]+_SUPABASE_KEY|SUPABASE_S3_(ACCESS|SECRET)_KEY|S3_PROTOCOL_ACCESS_KEY_SECRET|SUPABASE_SMS_HOOK_SECRET|SEND_SMS_HOOK_SECRET|LOGFLARE_.*(KEY|TOKEN))$/, + spec: { + method: "manual", + owner: "agent", + family: "supabase", + note: "the Supabase JWT secret signs every key and session", + disruptive: "a new JWT secret signs everyone out and re-issues the anon and service_role keys", + url: "https://supabase.com/docs/guides/self-hosting/docker#securing-your-services", + steps: [ + "Self-hosted: generate a new JWT_SECRET (40+ chars), mint new anon + service_role JWTs from it, write all three to the stack's .env.", + "Restart the stack (docker compose up -d with the stack's own env file); every session ends.", + "Hosted: Project settings > API > generate new JWT secret / new API keys.", + "Store each new value with --set-from-stdin (every vault sharing the old fingerprint is updated), redeploy the apps, then confirm the old anon key gets 401." + ] + } + }, + { + test: /^(TURSO|DATABASE|[A-Z0-9]+_DB|[A-Z0-9]+_DATABASE)_AUTH_TOKEN$|^TURSO_AUTH_TOKEN$/, + spec: provider("Turso: turso db tokens create (old tokens keep working)", "https://docs.turso.tech/cli/db/tokens/create", [ + "turso db tokens invalidate kills EVERY token for that database: run it only after all consumers use the new one." + ], { family: "turso" }) + }, + { test: /^TWILIO_(AUTH_TOKEN|SECRET)$/, spec: provider("Twilio (Console > Account > API keys & tokens > secondary auth token, then promote)", "https://console.twilio.com/us1/account/keys-credentials/api-keys", [], { family: "twilio" }) }, + { test: /^TELNYX_(API_KEY|.*SECRET)$/, spec: provider("Telnyx", "https://portal.telnyx.com/#/app/api-keys", [], { family: "telnyx" }) }, + { test: /^PORKBUN_(API|SECRET)(_API)?_KEY$|^PORKBUN_API_SECRET$/, spec: provider("Porkbun (create a new API key pair)", "https://porkbun.com/account/api", [], { family: "porkbun" }) }, + { test: /^ELEVENLABS_API_KEY$/, spec: provider("ElevenLabs", "https://elevenlabs.io/app/settings/api-keys", [], { family: "ai" }) }, + { test: /^(DEEPSEEK|MOONSHOT|QWEN|DASHSCOPE|ZAI|PERPLEXITY|OLLAMA|GLAMA|FAL|HUGGINGFACE|NGC|NVIDIA_NIM|ABLITERATION|SALAD_AI_GATEWAY|EXA|LINKUP|BRAVE)(_API)?_(KEY|TOKEN)$/, spec: provider("the model/search provider's API keys page", "", [], { family: "ai" }) }, + { test: /^(COINPAY|[A-Z0-9]+_COINPAY|ADNETWORK_COINPAY)(_OAUTH)?_CLIENT_SECRET$/, spec: provider("CoinPay OAuth apps (our own: coinpayportal.com > Developer > OAuth apps > regenerate secret)", "https://coinpayportal.com/dashboard", [], { family: "coinpay" }) }, + { test: /^FIREFOX_JWT_(SECRET|ISSUER)$/, spec: provider("addons.mozilla.org API credentials (Developer Hub > Manage API Keys > Generate new credentials)", "https://addons.mozilla.org/developers/addon/api/key/", [], { family: "browser-store" }) }, + { test: /^EDGE_(API_KEY|CLIENT_SECRET)$/, spec: provider("Microsoft Partner Center (Edge Add-ons API)", "https://partner.microsoft.com/dashboard/microsoftedge/publishapi", [], { family: "browser-store" }) }, + { test: /^SLACK_|^META_APP_SECRET$|^THREADS_APP_SECRET$|^LINKEDIN_|^MASTODON_(ACCESS_TOKEN|CLIENT_SECRET)$|^DEVTO_API_KEY$|^BLUESKY_APP_PASSWORD$/, spec: provider("the social platform's developer settings", "", [], { family: "social" }) }, + { test: /^(R2|S3|AWS|MINIO)_(SECRET_ACCESS_KEY|ROOT_PASSWORD)$/, spec: provider("the object store (Cloudflare R2 > Manage API tokens, or MinIO admin)", "https://dash.cloudflare.com/?to=/:account/r2/api-tokens", [], { family: "storage" }) }, + { + test: /^TURN_(SECRET|SERVER_CREDENTIAL)$/, + spec: { + method: "manual", + owner: "agent", + family: "internal", + note: "the coturn static-auth-secret lives in turnserver.conf as well as the app env", + steps: ["Generate a new value (openssl rand -hex 32).", "Set static-auth-secret in turnserver.conf and the app's env together, restart coturn and the app.", STORE] + } + }, + { + test: /^OPENACCESS_KEY_[A-Z0-9_]+$/, + spec: provider("the OpenAccess hub (logicsrc.com/app, site keys): mint a new key for that site", "https://logicsrc.com/docs/openaccess", [], { family: "fleet-app" }) + }, + { + test: /(DEALDASH_COOKIE|SESSION_COOKIES|AUTO_COOKIE|SEEDBOX_.*_(AUTH|TOKEN)|SIRIUSXM_TOKEN|TUNEIN_TOKEN)$/, + spec: { method: "manual", owner: "agent", family: "scraped-session", note: "a logged-in browser session for a third-party site", steps: ["Sign in to the site again in the scraping browser profile and copy the fresh cookie/token.", STORE, REDEPLOY] } + }, + // ---- secrets we invent: mint a random value -------------------------------------------- + { + // Session signers: rotating signs everybody out. + test: /^(AUTH_SECRET|BETTER_AUTH_SECRET|NEXTAUTH_SECRET|SESSION_SECRET|COOKIE_SECRET|JWT_SIGNING_SECRET|SECRET_KEY_BASE|([A-Z0-9]+_)*(SESSION_SECRET|JWT_SECRET|OIDC_SIGNING_SECRET|CLI_SESSION_SECRET))$/, + spec: { method: "random", family: "internal", disruptive: "signs sessions or tokens: everyone signs in again", steps: ["Redeploy every consumer so both sides use the new value."] } + }, { // Exact names, or our own *_CRON_SECRET / *_ADMIN_TOKEN style suffixes. A // provider prefix (META_APP_SECRET, GOOGLE_AUTH_SECRET) is THEIR secret and // must never be replaced with random bytes. - test: /^(APP_SECRET|AUTH_SECRET|BETTER_AUTH_SECRET|NEXTAUTH_SECRET|SESSION_SECRET|COOKIE_SECRET|JWT_SIGNING_SECRET|([A-Z0-9]+_)*(CRON_SECRET|INTERNAL_API_KEY|ADMIN_TOKEN|CLI_SESSION_SECRET|WEBHOOK_SIGNING_SECRET|REPUTATION_SIGNING_SECRET|OIDC_SIGNING_SECRET))$/, - spec: { method: "random", steps: ["Redeploy every consumer so both sides use the new value."] } + test: /^(APP_SECRET|IP_HASH_SALT|RATE_LIMIT_SALT|([A-Z0-9]+_)*(CRON_SECRET|CRON_TOKEN|INTERNAL_API_KEY|ADMIN_TOKEN|WEBHOOK_SIGNING_SECRET|REPUTATION_SIGNING_SECRET|SHARED_SECRET|HMAC_SECRET|TICKET_SECRET|BRIDGE_SECRET|HOOKS_SECRET|FORM_SECRET|PARTNER_VERIFY_SECRET|SIGN_SECRET|SIGNING_SECRET|BOOTSTRAP_SECRET|HOST_TOOL_SECRET|IP_HASH_SALT))$/, + spec: { method: "random", family: "internal", steps: ["Redeploy every consumer so both sides use the new value."] } }, - // Provider-issued keys. - { test: /^STRIPE_(SECRET|RESTRICTED)_KEY$/, spec: provider("the Stripe dashboard (Developers > API keys > Roll key)", "https://dashboard.stripe.com/apikeys") }, - { test: /^STRIPE.*WEBHOOK_SECRET$/, spec: provider("the Stripe webhook endpoint (Roll secret)", "https://dashboard.stripe.com/webhooks") }, - { test: /^(GITHUB|GH)_(TOKEN|PAT)$|^GITHUB_APP_PRIVATE_KEY$/, spec: provider("GitHub", "https://github.com/settings/tokens") }, - { test: /^ANTHROPIC_API_KEY$/, spec: provider("the Anthropic console", "https://console.anthropic.com/settings/keys") }, - { test: /^OPENAI_API_KEY$/, spec: provider("the OpenAI dashboard", "https://platform.openai.com/api-keys") }, - { test: /^GEMINI_API_KEY$|^GOOGLE_API_KEY$/, spec: provider("Google AI Studio", "https://aistudio.google.com/app/apikey") }, - { test: /^RESEND_API_KEY$/, spec: provider("Resend", "https://resend.com/api-keys") }, - { test: /^TELNYX_API_KEY$/, spec: provider("Telnyx", "https://portal.telnyx.com/#/app/api-keys") }, - { test: /^ELEVENLABS_API_KEY$/, spec: provider("ElevenLabs", "https://elevenlabs.io/app/settings/api-keys") }, - { test: /^(COINPAY|COINPAYPORTAL)_API_KEY$|^COINPAY_X402_KEY$/, spec: provider("CoinPay (business > API keys)", "https://coinpayportal.com/dashboard") }, - { test: /^COINPAY.*WEBHOOK_SECRET$/, spec: provider("CoinPay (business > webhook secret > regenerate)", "https://coinpayportal.com/dashboard") }, - { test: /^CLOUDFLARE_API_TOKEN$|^CF_API_TOKEN$/, spec: provider("Cloudflare", "https://dash.cloudflare.com/profile/api-tokens") }, - { test: /^PORKBUN_(API|SECRET)_KEY$/, spec: provider("Porkbun", "https://porkbun.com/account/api") }, + { - test: /^(SUPABASE_SERVICE_ROLE_KEY|SUPABASE_SECRET_KEY|SUPABASE_JWT_SECRET|NEXT_PUBLIC_SUPABASE_ANON_KEY|SUPABASE_ANON_KEY|JWT_SECRET)$/, - spec: { - method: "manual", - note: "the Supabase JWT secret signs every key and session", - steps: [ - "Self-hosted: set a new JWT secret, mint new anon + service_role keys from it, restart the stack (all sessions end).", - "Hosted: Project settings > API > generate new JWT secret / new API keys.", - "Update every vault holding the old keys (they share a fingerprint), redeploy, then revoke the old ones." - ] - } + // Our own apps issue these (listing keys, agent keys, bridge keys, admin keys). + test: /^([A-Z0-9]+_)*(LISTING_KEY|AGENT_KEY|AGENT_WORKER_KEY|PARTNER_KEY|PROJECT_KEY|ACTOR_TOKEN(_[A-Z0-9]+)?|BRIDGE_KEY|PAYAGENT_KEY|LIBRARY_KEY|LYRICS_KEY|OWNER_KEY|ADMIN_KEY|HOUSE_API_KEY|PUBLISHER_TOKEN|ADVERTISER_TOKEN|POST_TOKEN|DEV_BOX_TOKEN|SUBMIT_TOKEN|GATEWAY_TOKEN|NOBODY_KEY|HEALTH_TOKEN_KEY|COMP_KEYS|API_KEYS|ALERT_API_KEY)$|^(ADNETWORK|BUILTINDIE|GROUPCALL|MEDIAANALYZER|UGIG_API_KEY_[A-Z0-9_]+|RSSAMPLIFIER_API|SMSHUB_API|WX93_API|SEORANK_API|BUFFEROVERRIDE|CRAWLPROOF(_API)?|MOSHPIT_API|SUBMITFLEET_SECRET)_?(KEY|TOKEN)?$/, + spec: provider("our own app that issues it (its admin page or API: mint a new key for the same account, then revoke the old one there)", "", [], { family: "fleet-app" }) + }, + { test: /(^|_)WEBHOOK_SECRET$/, spec: provider("the service that signs the webhook (its webhook settings: regenerate/roll the signing secret)", "", [], { family: "webhook" }) }, + { + test: /^(SMTP|IMAP)_PASS(WORD)?$|_EMAIL_PASSWORD$/, + spec: provider("the mailbox (Forward Email > Domains > Aliases > Generate password)", "https://forwardemail.net/my-account/domains", [], { family: "email" }) }, - { test: /(^|_)WEBHOOK_SECRET$/, spec: provider("the service that signs the webhook", "") }, // Broad fallbacks for anything provider-issued. - { test: /(_API_KEY|_API_SECRET|_SECRET_KEY|_ACCESS_KEY|_TOKEN|_PRIVATE_KEY|_PASSWORD|_SECRET)$/, spec: provider("the issuing provider's dashboard", "") } + { + test: /(_API_KEY|_API_SECRET|_SECRET_KEY|_ACCESS_KEY|_TOKEN|_PRIVATE_KEY|_PASSWORD|_SECRET|_KEY|_PASS|_AUTH|_CREDENTIAL|_COOKIE|_SALT|_PEPPER)$|^(API_TOKEN|ADMIN_PASSWORD|ACCESS_PASSWORD|DASHBOARD_PASSWORD)$/, + spec: provider("the issuing provider's dashboard (the key name's prefix names it)", "", [], { family: "other" }) + } ]; +/** KEY__1 is the second copy of KEY (keyring/pull dedupe); match on KEY. */ +export function baseKeyName(key: string): string { + return key.toUpperCase().replace(/__\d+$/, ""); +} + /** Names that read like credentials. Plain config (MODE, URL, *_USD) is not planned at all. */ export function looksSecret(key: string): boolean { - return /(KEY|SECRET|TOKEN(?!S)|PASSWORD|PASSWD|_PASS$|PRIVATE|MNEMONIC|SEED_PHRASE|_SEED$|CREDENTIAL|AUTH|SALT|SIGNING|COOKIE|SESSION|DSN|CONNECTION_STRING|DATABASE_URL|_PEM|_P12|CERT)/i.test(key); + return /(KEY|SECRET|TOKEN(?!S)|PASSWORD|PASSWD|_PASS$|PRIVATE|MNEMONIC|SEED_PHRASE|_SEED$|CREDENTIAL|AUTH|SALT|PEPPER|SIGNING|COOKIE|SESSION|DSN|CONNECTION_STRING|DATABASE_URL|_PEM|_P12|CERT)/i.test(key); } -/** Built-in instructions for a key name, or null when we know nothing. */ -/** Public halves, ssh config and browser-public values: nothing to rotate. */ +/** URLs that can carry a password in their userinfo. Turso/libsql URLs carry none. */ +const CREDENTIAL_URL = /(^|_)(DATABASE|DB|POSTGRES|PG|REDIS|MONGO|MONGODB|AMQP|RABBITMQ|CONNECTION)(_URL|_URI|_STRING|_DSN)$/; + +/** + * Public halves, ssh config, browser-public values and plain config whose name + * merely contains KEY/TOKEN/AUTH: nothing to rotate. + */ export function isNotSecret(key: string): boolean { - const name = key.toUpperCase(); - return /^SSH_.*(_PUB|CONFIG|KNOWN_HOSTS|AUTHORIZED_KEYS|_CONF)$/.test(name) || /_PUBLIC_KEY$|^NEXT_PUBLIC_(?!SUPABASE_ANON_KEY)/.test(name); + const name = baseKeyName(key); + if (name.startsWith(ARCHIVE_PREFIX)) return true; + if (/^SSH_.*(_PUB|CONFIG|KNOWN_HOSTS|AUTHORIZED_KEYS|_CONF)$/.test(name)) return true; + if (/_PUBLIC_KEY(_JWK)?$|_PUBLIC$|^NEXT_PUBLIC_(?!SUPABASE_ANON_KEY)|^EXPO_PUBLIC_(?!GOOGLE_API_KEY)/.test(name)) return true; + if (/^TURSO_|^[A-Z0-9]+_TURSO_/.test(name) && /_URL$/.test(name)) return true; + if (CREDENTIAL_URL.test(name) && !/^TURSO_/.test(name)) return false; + return /(_URL|_URI|_ISSUER|_SCOPES?|_CLIENT_ID|_KEY_ID|_KEY_NAME|_ACCESS_KEY_ID|_BATCH_SIZE|_CONCURRENCY|_INTERVAL_SECONDS|_ENRICH|_EMAIL|_LIFETIME|_TTL|_PER_HOUR|_DAILY_LIMIT|_SITE_KEY|_PUBLISHABLE_KEY|_KID|_CONNECTION_ID|_RP_ID|_ORIGIN|_COOKIE_SECURE|_KEY_GENERATION|_AUTH_USER|_USER|_USERNAME|_CA_CERT|_CERT|_DSN|_VERIFICATION_KEY|_GPG_KEY_ID|_KEY_CONCURRENCY|_KEY_DAILY_LIMIT)$|^(AUTH_EMAIL|CERTBOT_EMAIL|SESSION_LIFETIME|GPG_KEY_ID|AUTHOR_[A-Z_]+|SYSTEM_KEY_GENERATION)$/.test(name); } export function catalogSpec(key: string): RotationSpec | null { - const name = key.toUpperCase(); - if (isNotSecret(name)) return null; + const name = baseKeyName(key); + if (isNotSecret(name)) return { method: "not-secret", note: "public or plain config" }; + if (CREDENTIAL_URL.test(name)) { + return { + method: "manual", + owner: "agent", + family: "postgres", + note: "a connection string: it changes when the password inside it rotates", + steps: ["Rotate the role password (postgres-role rotator or the runbook); the rotator rewrites every connection string holding the old password."] + }; + } const rule = CATALOG.find((r) => r.test.test(name)); if (!rule) return null; const spec = { ...rule.spec, steps: rule.spec.steps ? [...rule.spec.steps] : undefined }; if (spec.url === "") delete spec.url; + if (!spec.steps) delete spec.steps; return spec; } +/** Automatic = we can produce the new value without a person. */ +export function isAutomatic(spec: RotationSpec | null): boolean { + if (!spec || spec.never) return false; + return spec.method === "random" || spec.method === "ssh-keygen" || spec.method === "command" || spec.method === "provider"; +} + /** The alphabet an existing value looks like it was drawn from. */ export function detectFormat(value: string): RandomFormat { if (/^[0-9a-f]+$/i.test(value)) return "hex"; @@ -263,14 +494,17 @@ export interface PlannedRotation { /** * One row per distinct (key name, value): the same value stored under the same * name in several vaults rotates once and is written to all of them. Rotation - * entries themselves are never rotated. + * entries, archive records and not-secret config are never planned. */ export function planRotations(rows: PlanInput[], entrySpecs: Map): PlannedRotation[] { const groups = new Map(); for (const r of rows) { - if (isRotationEntry(r.key) || isNotSecret(r.key) || r.fingerprint === EMPTY_FINGERPRINT) continue; + if (isRotationEntry(r.key) || r.key.startsWith(ARCHIVE_PREFIX) || r.fingerprint === EMPTY_FINGERPRINT) continue; + const entry = entrySpecs.get(`${r.vault}\u0000${r.key}`); + if (entry?.method === "not-secret") continue; + if (!entry && isNotSecret(r.key)) continue; // Config with no instructions is not a secret to rotate; an explicit entry overrides. - if (!looksSecret(r.key) && !catalogSpec(r.key) && !entrySpecs.has(`${r.vault}\u0000${r.key}`)) continue; + if (!entry && !looksSecret(r.key) && !catalogSpec(r.key)) continue; const id = `${r.key}\u0000${r.fingerprint}`; groups.set(id, [...(groups.get(id) ?? []), r]); } @@ -279,7 +513,9 @@ export function planRotations(rows: PlanInput[], entrySpecs: Map entrySpecs.get(`${m.vault}\u0000${m.key}`)).find(Boolean) ?? null; - const spec = fromEntry ?? catalogSpec(first.key); + const fromCatalog = catalogSpec(first.key); + // An entry can add steps, but it cannot make a never-automated key (wallet, signing, Stripe) automatic. + const spec = fromEntry && fromCatalog?.never ? { ...fromEntry, never: true, owner: fromCatalog.owner, family: fromEntry.family ?? fromCatalog.family } : fromEntry ?? fromCatalog; out.push({ key: first.key, vaults: members.map((m) => m.vault).sort(), @@ -287,7 +523,7 @@ export function planRotations(rows: PlanInput[], entrySpecs: Map isoTime(m.updatedAt)).sort()[0]!, method: spec?.method ?? "unknown", source: fromEntry ? "entry" : spec ? "catalog" : "none", - automatic: spec?.method === "random" || spec?.method === "ssh-keygen" || spec?.method === "command", + automatic: isAutomatic(spec), spec }); } diff --git a/packages/cli/src/rotators.test.ts b/packages/cli/src/rotators.test.ts new file mode 100644 index 00000000..a74263ab --- /dev/null +++ b/packages/cli/src/rotators.test.ts @@ -0,0 +1,260 @@ +import { createHash, createHmac, pbkdf2Sync } from "node:crypto"; +import { describe, expect, it } from "vitest"; +import { + cloudflareTokenRotator, + coinpayApiKeyRotator, + coinpayWebhookSecretRotator, + newVapidPair, + postgresRoleRotator, + resendRotator, + rewriteUrls, + scramVerifier, + vapidRotator, + type RotatorContext +} from "./rotators.js"; + +type Handler = (method: string, url: URL, auth: string, body: any) => { status: number; body?: any }; + +function fakeFetch(handler: Handler): { fetch: typeof fetch; calls: Array<{ method: string; path: string; auth: string }> } { + const calls: Array<{ method: string; path: string; auth: string }> = []; + const f = (async (input: any, init: any = {}) => { + const url = new URL(String(input)); + const method = (init.method ?? "GET").toUpperCase(); + const auth = String(init.headers?.authorization ?? "").replace(/^Bearer /, ""); + calls.push({ method, path: url.pathname, auth }); + const r = handler(method, url, auth, init.body ? JSON.parse(init.body) : null); + return new Response(r.body === undefined ? "" : JSON.stringify(r.body), { status: r.status }); + }) as typeof fetch; + return { fetch: f, calls }; +} + +const ctx = (over: Partial): RotatorContext => ({ + key: "K", + oldValue: "old-value-xxxxxxxxxxxx", + vaultValues: {}, + state: {}, + env: {}, + fetch: fetch, + now: new Date("2026-10-29T00:00:00Z"), + ...over +}); + +describe("resend", () => { + it("mints with the old full-access key, revokes the old id from state only after revokeOld, rolls back the new one", async () => { + const keys = new Map([["old-id", "re_old_xxxxxxxxxxxxxxxx"]]); + const { fetch, calls } = fakeFetch((m, url, auth, body) => { + const live = [...keys.values()].includes(auth); + if (!live) return { status: 401, body: { message: "API key is invalid" } }; + if (m === "GET" && url.pathname === "/api-keys") return { status: 200, body: { data: [...keys.keys()].map((id) => ({ id })) } }; + if (m === "POST" && url.pathname === "/api-keys") { + keys.set("new-id", "re_new_yyyyyyyyyyyyyyyy"); + expect(body.permission).toBe("full_access"); + return { status: 201, body: { id: "new-id", token: "re_new_yyyyyyyyyyyyyyyy" } }; + } + if (m === "DELETE") { + keys.delete(url.pathname.split("/").pop()!); + return { status: 200, body: {} }; + } + return { status: 404 }; + }); + const c = ctx({ key: "RESEND_API_KEY", oldValue: "re_old_xxxxxxxxxxxxxxxx", state: { keyId: "old-id" }, fetch }); + expect(await resendRotator.preflight(c)).toBeNull(); + const minted = await resendRotator.mint(c); + expect(minted.value).toBe("re_new_yyyyyyyyyyyyyyyy"); + expect(minted.state).toEqual({ keyId: "new-id" }); + expect(keys.has("old-id")).toBe(true); // both live until revokeOld + expect(await minted.revokeOld()).toBeUndefined(); + expect(keys.has("old-id")).toBe(false); + expect(calls.some((x) => x.auth.includes("yyyy"))).toBe(true); + }); + + it("asks for a manual revoke when the old key's id was never recorded, and rollback deletes the new key", async () => { + const deleted: string[] = []; + const { fetch } = fakeFetch((m, url) => { + if (m === "GET") return { status: 200, body: { data: [] } }; + if (m === "POST") return { status: 201, body: { id: "n1", token: "re_n1_zzzzzzzzzzzzzz" } }; + if (m === "DELETE") deleted.push(url.pathname); + return { status: 200, body: {} }; + }); + const minted = await resendRotator.mint(ctx({ key: "RESEND_API_KEY", fetch })); + expect(await minted.revokeOld()).toMatch(/delete the previous key/); + await minted.rollback(); + expect(deleted).toEqual(["/api-keys/n1"]); + }); + + it("preflight fails for a sending-only key without an admin key", async () => { + const { fetch } = fakeFetch(() => ({ status: 401, body: { message: "restricted" } })); + expect(await resendRotator.preflight(ctx({ fetch }))).toMatch(/RESEND_ADMIN_API_KEY/); + }); +}); + +describe("cloudflare-token", () => { + it("clones the old token's policies, deletes the old token only on revokeOld", async () => { + const tokens = new Map([["t-old", { id: "t-old", name: "dns edit", value: "cf_old_xxxxxxxxxxxxxx", policies: [{ id: "p", effect: "allow", resources: { "com.cloudflare.api.account.zone.*": "*" }, permission_groups: [{ id: "g1", name: "DNS Write" }] }] }]]); + let created: any = null; + const { fetch } = fakeFetch((m, url, auth, body) => { + const me = [...tokens.values()].find((t) => t.value === auth); + if (!me) return { status: 401, body: { errors: [{ message: "Invalid API Token" }] } }; + if (url.pathname.endsWith("/user/tokens/verify")) return { status: 200, body: { result: { id: me.id, status: "active" } } }; + const id = url.pathname.split("/").pop()!; + if (m === "GET") return tokens.has(id) ? { status: 200, body: { result: tokens.get(id) } } : { status: 404 }; + if (m === "POST") { + created = body; + tokens.set("t-new", { id: "t-new", value: "cf_new_yyyyyyyyyyyyyy", ...body }); + return { status: 200, body: { result: { id: "t-new", value: "cf_new_yyyyyyyyyyyyyy" } } }; + } + if (m === "DELETE") { + tokens.delete(id); + return { status: 200, body: { result: { id } } }; + } + return { status: 404 }; + }); + const c = ctx({ key: "CLOUDFLARE_API_TOKEN", oldValue: "cf_old_xxxxxxxxxxxxxx", fetch }); + expect(await cloudflareTokenRotator.preflight(c)).toBeNull(); + const minted = await cloudflareTokenRotator.mint(c); + expect(created.policies[0].permission_groups).toEqual([{ id: "g1" }]); + expect(created.name).toBe("dns edit (rotated 2026-10-29)"); + expect(tokens.has("t-old")).toBe(true); + await minted.revokeOld(); + expect(tokens.has("t-old")).toBe(false); + expect(tokens.has("t-new")).toBe(true); + }); + + it("refuses a token it cannot verify", async () => { + const { fetch } = fakeFetch(() => ({ status: 401, body: {} })); + expect(await cloudflareTokenRotator.preflight(ctx({ fetch }))).toMatch(/not a live user API token/); + }); +}); + +describe("coinpay", () => { + const legacy = "cp_live_legacyAAAAAAAAAAAAAAAA"; + function coinpay() { + const state = { legacy, scoped: new Map(), regenerated: 0, webhook: "whsec_old_xxxxxxxxxxxx" }; + const { fetch, calls } = fakeFetch((m, url, auth, body) => { + const p = url.pathname; + if (p === "/api/auth/login") return body.password === "pw" ? { status: 200, body: { success: true, token: "session-jwt" } } : { status: 401 }; + if (p === "/api/businesses" && m === "GET") { + const ok = auth === state.legacy || [...state.scoped.values()].some((k) => k.raw === auth && !k.revoked_at) || auth === "session-jwt"; + return ok ? { status: 200, body: { success: true, businesses: [{ id: "b1", api_key: state.legacy, webhook_secret: state.webhook }] } } : { status: 401 }; + } + if (auth !== "session-jwt") return { status: 401 }; + if (p === "/api/businesses/b1/api-keys" && m === "POST") { + const id = `k${state.scoped.size + 1}`; + state.scoped.set(id, { id, raw: `cp_live_scoped${id}BBBBBBBBBB`, scopes: body.scopes, prefix: `cp_live_scoped${id}`.slice(0, 16) }); + return { status: 201, body: { success: true, apiKey: state.scoped.get(id).raw, key: { id } } }; + } + if (p === "/api/businesses/b1/api-keys" && m === "GET") return { status: 200, body: { keys: [...state.scoped.values()].map(({ raw: _r, ...k }) => k) } }; + if (p.startsWith("/api/businesses/b1/api-keys/") && m === "DELETE") { + const k = state.scoped.get(p.split("/").pop()!); + if (!k) return { status: 404 }; + k.revoked_at = "now"; + return { status: 200, body: { success: true } }; + } + if (p === "/api/businesses/b1/api-key" && m === "POST") { + state.legacy = `cp_live_regen${++state.regenerated}`; + return { status: 200, body: { success: true, apiKey: state.legacy } }; + } + if (p === "/api/businesses/b1/webhook-secret" && m === "POST") { + state.webhook = "whsec_new_yyyyyyyyyyyy"; + return { status: 200, body: { success: true, secret: state.webhook } }; + } + return { status: 404 }; + }); + return { state, fetch, calls }; + } + const env = { COINPAY_ROTATE_URL: "https://coinpay.test", COINPAY_ROTATE_EMAIL: "o@x", COINPAY_ROTATE_PASSWORD: "pw" }; + + it("legacy key: mints a wildcard scoped key, old key still works until revokeOld regenerates the legacy slot", async () => { + const { state, fetch } = coinpay(); + const c = ctx({ key: "COINPAY_API_KEY", oldValue: legacy, fetch, env }); + expect(await coinpayApiKeyRotator.preflight(c)).toBeNull(); + const minted = await coinpayApiKeyRotator.mint(c); + expect(minted.value).toBe("cp_live_scopedk1BBBBBBBBBB"); + expect(state.scoped.get("k1").scopes).toEqual(["*"]); + expect(state.legacy).toBe(legacy); + await minted.revokeOld(); + expect(state.legacy).not.toBe(legacy); + expect(minted.state).toEqual({ businessId: "b1", keyId: "k1" }); + }); + + it("scoped key: the next rotation keeps its scopes and deletes it; rollback revokes the new key", async () => { + const { state, fetch } = coinpay(); + const first = await coinpayApiKeyRotator.mint(ctx({ key: "COINPAY_API_KEY", oldValue: legacy, fetch, env })); + const second = await coinpayApiKeyRotator.mint(ctx({ key: "COINPAY_API_KEY", oldValue: first.value, fetch, env })); + expect(state.scoped.get("k2").scopes).toEqual(["*"]); + await second.revokeOld(); + expect(state.scoped.get("k1").revoked_at).toBe("now"); + await second.rollback(); + expect(state.scoped.get("k2").revoked_at).toBe("now"); + }); + + it("refuses to run without a merchant session", async () => { + expect(await coinpayApiKeyRotator.preflight(ctx({ env: {} }))).toMatch(/COINPAY_ROTATE_TOKEN/); + }); + + it("webhook secret: finds the business by its secret and regenerates it (no overlap)", async () => { + const { state, fetch } = coinpay(); + expect(coinpayWebhookSecretRotator.overlap).toBe(false); + const c = ctx({ key: "COINPAY_WEBHOOK_SECRET", oldValue: "whsec_old_xxxxxxxxxxxx", vaultValues: { COINPAY_API_KEY: legacy }, fetch, env }); + expect(await coinpayWebhookSecretRotator.preflight(c)).toBeNull(); + const minted = await coinpayWebhookSecretRotator.mint(c); + expect(minted.value).toBe("whsec_new_yyyyyyyyyyyy"); + expect(state.webhook).toBe(minted.value); + expect(await minted.rollback()).toMatch(/cannot restore/); + }); +}); + +describe("vapid", () => { + it("makes a valid P-256 pair and writes the public half to every VAPID public companion", async () => { + const pair = newVapidPair(); + expect(Buffer.from(pair.publicKey, "base64url")).toHaveLength(65); + expect(Buffer.from(pair.privateKey, "base64url")).toHaveLength(32); + const c = ctx({ key: "VAPID_PRIVATE_KEY", vaultValues: { VAPID_PRIVATE_KEY: "x", VAPID_PUBLIC_KEY: "y", NEXT_PUBLIC_VAPID_PUBLIC_KEY: "y" } }); + expect(await vapidRotator.preflight(c)).toBeNull(); + const minted = await vapidRotator.mint(c); + expect(Object.keys(minted.companions!)).toEqual(["VAPID_PUBLIC_KEY", "NEXT_PUBLIC_VAPID_PUBLIC_KEY"]); + expect(await vapidRotator.preflight(ctx({ vaultValues: { VAPID_PRIVATE_KEY: "x" } }))).toMatch(/no VAPID public key/); + }); +}); + +describe("postgres-role", () => { + it("SCRAM verifier matches the RFC 7677 construction", () => { + const salt = Buffer.from("0123456789abcdef"); + const v = scramVerifier("pencil", salt, 4096); + const salted = pbkdf2Sync("pencil", salt, 4096, 32, "sha256"); + const stored = createHash("sha256").update(createHmac("sha256", salted).update("Client Key").digest()).digest("base64"); + expect(v).toBe(`SCRAM-SHA-256$4096:${salt.toString("base64")}$${stored}:${createHmac("sha256", salted).update("Server Key").digest("base64")}`); + }); + + it("alters its own role over stdin (never argv), rewrites URLs, rolls back to the old password", async () => { + const runs: Array<{ args: string[]; input?: string; env?: Record }> = []; + const old = "oldpassword123456"; + const c = ctx({ + key: "POSTGRES_PASSWORD", + oldValue: old, + vaultValues: { POSTGRES_PASSWORD: old, DATABASE_URL: `postgres://app:${old}@db.local:5432/app` }, + run: (_cmd, args, opts) => { + runs.push({ args, ...opts }); + return { status: 0, stdout: "", stderr: "" }; + } + }); + expect(await postgresRoleRotator.preflight(c)).toBeNull(); + const minted = await postgresRoleRotator.mint(c); + expect(runs[0]!.args.join(" ")).not.toContain(old); + expect(runs[0]!.args.join(" ")).not.toContain(minted.value); + expect(runs[0]!.input).toMatch(/^ALTER ROLE CURRENT_USER PASSWORD 'SCRAM-SHA-256\$/); + expect(runs[0]!.input).not.toContain(minted.value); + expect(runs[0]!.env!.PGPASSWORD).toBe(old); + expect(minted.companions!.DATABASE_URL).toBe(`postgres://app:${minted.value}@db.local:5432/app`); + await minted.rollback(); + expect(runs[1]!.env!.PGPASSWORD).toBe(minted.value); + }); + + it("refuses self-hosted Supabase passwords", async () => { + expect(await postgresRoleRotator.preflight(ctx({ key: "SUPABASE_DB_PASSWORD" }))).toMatch(/Supabase/); + }); + + it("rewriteUrls only touches URLs holding the old password", () => { + expect(rewriteUrls({ A: "postgres://u:old@h/d", B: "postgres://u:other@h/d", C: "plain" }, "old", "n w")).toEqual({ A: "postgres://u:n%20w@h/d" }); + }); +}); diff --git a/packages/cli/src/rotators.ts b/packages/cli/src/rotators.ts new file mode 100644 index 00000000..f71bb26b --- /dev/null +++ b/packages/cli/src/rotators.ts @@ -0,0 +1,476 @@ +import { createHash, createHmac, generateKeyPairSync, pbkdf2Sync, randomBytes } from "node:crypto"; +import { spawnSync } from "node:child_process"; +import { generateRandomSecret } from "./rotation-catalog.js"; + +/** + * Built-in rotators for `method: "provider"`. Each one is two-phase: + * + * mint() create the new credential at the provider; the old one stays live + * (caller) write it to every vault holding the old value, redeploy the + * consumers, health-check them + * revokeOld() only now kill the old credential + * rollback() on any failure before revokeOld: undo mint, so the old value + * (still in the vaults' history and in the consumers) keeps working + * + * `overlap` says whether old and new really are valid at the same time. When + * the provider has a single slot (a CoinPay webhook secret, a Postgres role + * password) it is false: the caller still rolls back, but consumers see a short + * window of failures, so the weekly job leaves those to a person. + * + * Nothing here prints or logs a secret value; errors carry provider status + * codes and messages only. + */ + +export interface RotatorContext { + key: string; + oldValue: string; + /** Decrypted values of the first vault holding the key, by name (companions: public halves, DB URLs). */ + vaultValues: Record; + /** Rotator bookkeeping saved after the last rotation (provider key ids). */ + state: Record; + /** Admin credentials for rotators that need them (CLOUDFLARE_ADMIN_API_TOKEN, ...). */ + env: Record; + fetch: typeof fetch; + /** Runs a process with stdin; secrets travel on stdin or env, never argv. */ + run?: (cmd: string, args: string[], opts: { input?: string; env?: Record }) => { status: number | null; stdout: string; stderr: string }; + now: Date; +} + +export interface Minted { + value: string; + /** Extra values written beside it in the same vaults (by key name): the VAPID public key, rewritten DB URLs. */ + companions?: Record; + /** Saved to the key's __ROTATE__ entry so the next rotation can revoke this credential by id. */ + state?: Record; + /** Kill the old credential. Returns a note when it has to be done by hand. */ + revokeOld(): Promise; + /** Undo mint (delete the new credential / restore the old password). */ + rollback(): Promise; +} + +export interface ProviderRotator { + id: string; + title: string; + overlap: boolean; + /** null when it can run; otherwise why not (missing admin credential, wrong key type). */ + preflight(ctx: RotatorContext): Promise; + mint(ctx: RotatorContext): Promise; +} + +export class RotatorError extends Error {} + +const day = (d: Date) => d.toISOString().slice(0, 10); + +async function call(ctx: RotatorContext, url: string, init: RequestInit & { token: string }): Promise<{ status: number; body: any }> { + const { token, headers, ...rest } = init; + const res = await ctx.fetch(url, { + ...rest, + headers: { authorization: `Bearer ${token}`, "content-type": "application/json", accept: "application/json", ...(headers as Record | undefined) } + }); + const text = await res.text(); + let body: any = null; + try { + body = text ? JSON.parse(text) : null; + } catch { + body = { raw: text.slice(0, 200) }; + } + return { status: res.status, body }; +} + +function fail(what: string, r: { status: number; body: any }): never { + const msg = r.body?.message ?? r.body?.error ?? r.body?.errors?.[0]?.message ?? r.body?.raw ?? ""; + throw new RotatorError(`${what}: HTTP ${r.status}${msg ? ` ${String(msg).slice(0, 160)}` : ""}`); +} + +// ---- Resend ------------------------------------------------------------------------------- + +const RESEND = "https://api.resend.com"; + +/** + * Resend: POST /api-keys mints, DELETE /api-keys/:id revokes; both need a + * full-access key. The old key itself is used when it has full access, + * otherwise RESEND_ADMIN_API_KEY. Resend never shows which id a token is, so + * the old key is revoked by the id saved at the previous rotation; the first + * time round that id is unknown and revoking is a one-line manual step. + */ +export const resendRotator: ProviderRotator = { + id: "resend", + title: "Resend API key", + overlap: true, + async preflight(ctx) { + const token = adminFor(ctx); + const r = await call(ctx, `${RESEND}/api-keys`, { method: "GET", token }); + if (r.status === 200) return null; + if (!ctx.env.RESEND_ADMIN_API_KEY) return `this key cannot manage API keys (HTTP ${r.status}); set RESEND_ADMIN_API_KEY to a full-access key`; + return `RESEND_ADMIN_API_KEY cannot manage API keys (HTTP ${r.status})`; + }, + async mint(ctx) { + const token = adminFor(ctx); + // A full-access old key gets a full-access successor; anything else gets sending only. + const own = await call(ctx, `${RESEND}/api-keys`, { method: "GET", token: ctx.oldValue }); + const permission = own.status === 200 ? "full_access" : "sending_access"; + const name = `logicsrc ${ctx.key.toLowerCase()} ${day(ctx.now)}`; + const r = await call(ctx, `${RESEND}/api-keys`, { method: "POST", token, body: JSON.stringify({ name, permission }) }); + if (r.status !== 200 && r.status !== 201) fail("Resend create key", r); + const id = String(r.body?.id ?? ""); + const value = String(r.body?.token ?? ""); + if (!id || !value) throw new RotatorError("Resend create key: response had no id/token"); + const oldId = ctx.state.keyId; + return { + value, + state: { keyId: id }, + async revokeOld() { + if (!oldId) return `Resend does not say which key id the old token is: delete the previous key in ${"https://resend.com/api-keys"} (keep "${name}").`; + const d = await call(ctx, `${RESEND}/api-keys/${oldId}`, { method: "DELETE", token: value }); + if (d.status !== 200 && d.status !== 204 && d.status !== 404) fail("Resend delete old key", d); + return undefined; + }, + async rollback() { + const d = await call(ctx, `${RESEND}/api-keys/${id}`, { method: "DELETE", token }); + return d.status < 300 || d.status === 404 ? undefined : `delete the new Resend key "${name}" by hand (HTTP ${d.status})`; + } + }; + } +}; + +function adminFor(ctx: RotatorContext): string { + return ctx.env.RESEND_ADMIN_API_KEY || ctx.oldValue; +} + +// ---- Cloudflare --------------------------------------------------------------------------- + +const CF = "https://api.cloudflare.com/client/v4"; + +/** + * Cloudflare user API tokens: /user/tokens/verify names the token id, the + * token's policies are copied into a new token, and the old one is deleted + * after the consumers are healthy. Reading and creating tokens needs "API + * Tokens Write": CLOUDFLARE_ADMIN_API_TOKEN, or the token itself if it has it. + */ +export const cloudflareTokenRotator: ProviderRotator = { + id: "cloudflare-token", + title: "Cloudflare API token", + overlap: true, + async preflight(ctx) { + const v = await call(ctx, `${CF}/user/tokens/verify`, { method: "GET", token: ctx.oldValue }); + if (v.status !== 200 || !v.body?.result?.id) return `not a live user API token (verify HTTP ${v.status}); account tokens and Global API keys rotate by hand`; + const admin = ctx.env.CLOUDFLARE_ADMIN_API_TOKEN || ctx.oldValue; + const r = await call(ctx, `${CF}/user/tokens/${v.body.result.id}`, { method: "GET", token: admin }); + if (r.status !== 200) return `cannot read token policies (HTTP ${r.status}); set CLOUDFLARE_ADMIN_API_TOKEN to a token with "API Tokens Write"`; + return null; + }, + async mint(ctx) { + const admin = ctx.env.CLOUDFLARE_ADMIN_API_TOKEN || ctx.oldValue; + const v = await call(ctx, `${CF}/user/tokens/verify`, { method: "GET", token: ctx.oldValue }); + const oldId = String(v.body?.result?.id ?? ""); + if (!oldId) fail("Cloudflare verify", v); + const cur = await call(ctx, `${CF}/user/tokens/${oldId}`, { method: "GET", token: admin }); + if (cur.status !== 200) fail("Cloudflare read token", cur); + const t = cur.body.result; + const policies = (t.policies ?? []).map((p: any) => ({ + effect: p.effect, + resources: p.resources, + permission_groups: (p.permission_groups ?? []).map((g: any) => ({ id: g.id })) + })); + const baseName = String(t.name ?? ctx.key).replace(/ \(rotated \d{4}-\d{2}-\d{2}\)$/, ""); + const body: Record = { name: `${baseName} (rotated ${day(ctx.now)})`, policies }; + if (t.condition) body.condition = t.condition; + if (t.expires_on) body.expires_on = t.expires_on; + if (t.not_before) body.not_before = t.not_before; + const r = await call(ctx, `${CF}/user/tokens`, { method: "POST", token: admin, body: JSON.stringify(body) }); + if (r.status !== 200) fail("Cloudflare create token", r); + const id = String(r.body?.result?.id ?? ""); + const value = String(r.body?.result?.value ?? ""); + if (!id || !value) throw new RotatorError("Cloudflare create token: no id/value in the response"); + return { + value, + state: { tokenId: id }, + async revokeOld() { + const d = await call(ctx, `${CF}/user/tokens/${oldId}`, { method: "DELETE", token: admin === ctx.oldValue ? value : admin }); + if (d.status !== 200 && d.status !== 404) fail("Cloudflare delete old token", d); + return undefined; + }, + async rollback() { + const d = await call(ctx, `${CF}/user/tokens/${id}`, { method: "DELETE", token: admin }); + return d.status === 200 || d.status === 404 ? undefined : `delete the new Cloudflare token "${body.name}" by hand (HTTP ${d.status})`; + } + }; + } +}; + +// ---- CoinPay (our own API) ---------------------------------------------------------------- + +function coinpayBase(ctx: RotatorContext): string { + // COINPAY_API_URL elsewhere in the fleet carries an /api suffix; accept both. + return (ctx.env.COINPAY_ROTATE_URL || ctx.env.COINPAY_API_URL || "https://coinpayportal.com").replace(/\/+$/, "").replace(/\/api$/, ""); +} + +/** A merchant session: COINPAY_ROTATE_TOKEN, or log in with COINPAY_ROTATE_EMAIL + COINPAY_ROTATE_PASSWORD. */ +async function coinpaySession(ctx: RotatorContext): Promise { + if (ctx.env.COINPAY_ROTATE_TOKEN) return ctx.env.COINPAY_ROTATE_TOKEN; + if (!ctx.env.COINPAY_ROTATE_EMAIL || !ctx.env.COINPAY_ROTATE_PASSWORD) return null; + const res = await ctx.fetch(`${coinpayBase(ctx)}/api/auth/login`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ email: ctx.env.COINPAY_ROTATE_EMAIL, password: ctx.env.COINPAY_ROTATE_PASSWORD }) + }); + const body = (await res.json().catch(() => null)) as any; + return res.ok && body?.token ? String(body.token) : null; +} + +/** The business that owns a key: GET /api/businesses accepts the key itself and lists the owner's businesses. */ +async function coinpayBusiness(ctx: RotatorContext, match: (b: any) => boolean): Promise { + const r = await call(ctx, `${coinpayBase(ctx)}/api/businesses`, { method: "GET", token: ctx.oldValue }); + if (r.status !== 200) return null; + return (r.body?.businesses ?? []).find(match) ?? null; +} + +/** + * CoinPay business API keys. A business has one legacy key (businesses.api_key) + * and any number of scoped keys (business_api_keys, cp_live_ + 8 char prefix). + * Rotation always mints a scoped key with the old key's scopes ("*" for the + * legacy key) so old and new work side by side; revoking the old one means + * DELETE for a scoped key, or regenerating the legacy slot (its new value is + * thrown away unread) for the legacy key. + */ +export const coinpayApiKeyRotator: ProviderRotator = { + id: "coinpay-api-key", + title: "CoinPay business API key", + overlap: true, + async preflight(ctx) { + if (!(await coinpaySession(ctx))) return "needs a CoinPay merchant session: set COINPAY_ROTATE_TOKEN, or COINPAY_ROTATE_EMAIL + COINPAY_ROTATE_PASSWORD (owner of the business)"; + return null; + }, + async mint(ctx) { + const session = await coinpaySession(ctx); + if (!session) throw new RotatorError("no CoinPay merchant session"); + const base = coinpayBase(ctx); + const r = await call(ctx, `${base}/api/businesses`, { method: "GET", token: ctx.oldValue }); + if (r.status !== 200) fail("CoinPay: the old key does not authenticate", r); + const businesses: any[] = r.body?.businesses ?? []; + let business = businesses.find((b) => b.api_key === ctx.oldValue) ?? null; + let scoped: any = null; + if (!business) { + const prefix = ctx.oldValue.startsWith("cp_live_") ? ctx.oldValue.slice(0, 16) : ""; + for (const b of businesses) { + const k = await call(ctx, `${base}/api/businesses/${b.id}/api-keys`, { method: "GET", token: session }); + const hit = (k.body?.keys ?? []).find((x: any) => !x.revoked_at && prefix && x.prefix === prefix); + if (hit) { + business = b; + scoped = hit; + break; + } + } + } + if (!business) throw new RotatorError("CoinPay: no business of this merchant owns the key (wrong COINPAY_ROTATE_* account?)"); + const name = `logicsrc ${ctx.key.toLowerCase()} ${day(ctx.now)}`; + const created = await call(ctx, `${base}/api/businesses/${business.id}/api-keys`, { + method: "POST", + token: session, + body: JSON.stringify({ name, scopes: scoped?.scopes?.length ? scoped.scopes : ["*"] }) + }); + if (created.status !== 201 && created.status !== 200) fail("CoinPay create scoped key", created); + const value = String(created.body?.apiKey ?? ""); + const newId = String(created.body?.key?.id ?? ""); + if (!value || !newId) throw new RotatorError("CoinPay create scoped key: no key in the response"); + return { + value, + state: { businessId: String(business.id), keyId: newId }, + async revokeOld() { + const d = scoped + ? await call(ctx, `${base}/api/businesses/${business.id}/api-keys/${scoped.id}`, { method: "DELETE", token: session }) + : await call(ctx, `${base}/api/businesses/${business.id}/api-key`, { method: "POST", token: session }); + if (d.status >= 300 && d.status !== 404) fail("CoinPay revoke old key", d); + return undefined; + }, + async rollback() { + const d = await call(ctx, `${base}/api/businesses/${business.id}/api-keys/${newId}`, { method: "DELETE", token: session }); + return d.status < 300 || d.status === 404 ? undefined : `revoke the new CoinPay key "${name}" by hand (HTTP ${d.status})`; + } + }; + } +}; + +/** + * CoinPay webhook secret: one per business, regenerated in place, so there is + * no overlap and no way back to the old value. Consumers fail signature + * checks until they restart; CoinPay retries failed deliveries. + */ +export const coinpayWebhookSecretRotator: ProviderRotator = { + id: "coinpay-webhook-secret", + title: "CoinPay webhook secret", + overlap: false, + async preflight(ctx) { + if (!(await coinpaySession(ctx))) return "needs a CoinPay merchant session: set COINPAY_ROTATE_TOKEN, or COINPAY_ROTATE_EMAIL + COINPAY_ROTATE_PASSWORD"; + if (!findApiKey(ctx)) return "no CoinPay API key in the same vault to find the business with"; + return null; + }, + async mint(ctx) { + const session = await coinpaySession(ctx); + const apiKey = findApiKey(ctx); + if (!session || !apiKey) throw new RotatorError("needs a CoinPay merchant session and the vault's CoinPay API key"); + const base = coinpayBase(ctx); + const r = await call(ctx, `${base}/api/businesses`, { method: "GET", token: apiKey }); + const business = (r.body?.businesses ?? []).find((b: any) => b.webhook_secret === ctx.oldValue); + if (!business) throw new RotatorError("CoinPay: no business has this webhook secret"); + const g = await call(ctx, `${base}/api/businesses/${business.id}/webhook-secret`, { method: "POST", token: session }); + if (g.status !== 200) fail("CoinPay regenerate webhook secret", g); + const value = String(g.body?.secret ?? ""); + if (!value) throw new RotatorError("CoinPay regenerate webhook secret: no secret in the response"); + return { + value, + async revokeOld() { + return undefined; // regenerating already killed it + }, + async rollback() { + return "CoinPay cannot restore an old webhook secret: the new one is live, so keep it and finish redeploying the consumers"; + } + }; + } +}; + +function findApiKey(ctx: RotatorContext): string | undefined { + const name = Object.keys(ctx.vaultValues).find((k) => /^(COINPAY|COINPAYPORTAL)(_[A-Z0-9]+)*_API_KEY$/.test(k) && ctx.vaultValues[k]); + return name ? ctx.vaultValues[name] : undefined; +} + +// ---- VAPID (local) ------------------------------------------------------------------------ + +/** A Web Push VAPID pair: P-256, public as uncompressed point, both base64url. */ +export function newVapidPair(): { publicKey: string; privateKey: string } { + const { publicKey, privateKey } = generateKeyPairSync("ec", { namedCurve: "prime256v1" }); + const pub = publicKey.export({ format: "jwk" }); + const priv = privateKey.export({ format: "jwk" }); + const raw = Buffer.concat([Buffer.from([4]), Buffer.from(pub.x!, "base64url"), Buffer.from(pub.y!, "base64url")]); + return { publicKey: raw.toString("base64url"), privateKey: String(priv.d) }; +} + +export const vapidRotator: ProviderRotator = { + id: "vapid", + title: "Web Push VAPID key pair", + overlap: false, + async preflight(ctx) { + return vapidPublicNames(ctx).length ? null : "no VAPID public key beside the private one: the browser side would not get the new key"; + }, + async mint(ctx) { + const pair = newVapidPair(); + const companions = Object.fromEntries(vapidPublicNames(ctx).map((n) => [n, pair.publicKey])); + return { + value: pair.privateKey, + companions, + async revokeOld() { + return undefined; // nothing to revoke: subscriptions made with the old public key just stop + }, + async rollback() { + return undefined; // the caller restores the old pair from the vaults + } + }; + } +}; + +function vapidPublicNames(ctx: RotatorContext): string[] { + return Object.keys(ctx.vaultValues).filter((k) => /VAPID/.test(k) && /PUB/.test(k)); +} + +// ---- Postgres role password --------------------------------------------------------------- + +/** A SCRAM-SHA-256 verifier, so the plaintext password never reaches the server log. */ +export function scramVerifier(password: string, salt = randomBytes(16), iterations = 4096): string { + const salted = pbkdf2Sync(password.normalize("NFKC"), salt, iterations, 32, "sha256"); + const clientKey = createHmac("sha256", salted).update("Client Key").digest(); + const storedKey = createHash("sha256").update(clientKey).digest(); + const serverKey = createHmac("sha256", salted).update("Server Key").digest(); + return `SCRAM-SHA-256$${iterations}:${salt.toString("base64")}$${storedKey.toString("base64")}:${serverKey.toString("base64")}`; +} + +interface PgTarget { + urlKey: string; + url: URL; +} + +function pgTargets(ctx: RotatorContext): PgTarget[] { + const out: PgTarget[] = []; + for (const [k, v] of Object.entries(ctx.vaultValues)) { + if (!/^postgres(ql)?:\/\//.test(v)) continue; + try { + const url = new URL(v); + if (decodeURIComponent(url.password) === ctx.oldValue) out.push({ urlKey: k, url }); + } catch { + /* not a URL */ + } + } + return out; +} + +/** Every connection string in the vault holding the old password, rewritten to the new one. */ +export function rewriteUrls(values: Record, oldPassword: string, newPassword: string): Record { + const out: Record = {}; + for (const [k, v] of Object.entries(values)) { + if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(v)) continue; + try { + const url = new URL(v); + if (url.password && decodeURIComponent(url.password) === oldPassword) { + url.password = encodeURIComponent(newPassword); + out[k] = url.toString(); + } + } catch { + /* not a URL */ + } + } + return out; +} + +/** + * ALTER ROLE CURRENT_USER for the role in the vault's connection string (a + * role may always change its own password). Sends a SCRAM verifier on stdin of + * psql, never the plaintext. Rollback sets the old password back. Self-hosted + * Supabase stacks are refused: the same password is shared by six service roles + * and the stack's own .env, which this rotator does not restart. + */ +export const postgresRoleRotator: ProviderRotator = { + id: "postgres-role", + title: "Postgres role password", + overlap: false, + async preflight(ctx) { + if (/^SUPABASE_/.test(ctx.key) || Object.keys(ctx.vaultValues).some((k) => k === "POSTGRES_PASSWORD" && "JWT_SECRET" in ctx.vaultValues)) + return "self-hosted Supabase shares this password with its service roles: follow the runbook (Postgres / Supabase section)"; + if (!pgTargets(ctx).length) return "no postgres:// URL with this password in the vault, so the host and role are unknown"; + if (!ctx.run) return "no process runner (psql) available"; + return null; + }, + async mint(ctx) { + const target = pgTargets(ctx)[0]; + if (!target || !ctx.run) throw new RotatorError("no postgres target"); + const value = generateRandomSecret({ format: "alnum", length: 40 }); + const apply = (password: string, current: string): string | undefined => { + const url = new URL(target.url.toString()); + url.password = ""; + const r = ctx.run!("psql", ["-X", "-q", "-v", "ON_ERROR_STOP=1", url.toString()], { + env: { PGPASSWORD: current, PGCONNECT_TIMEOUT: "10" }, + input: `ALTER ROLE CURRENT_USER PASSWORD '${scramVerifier(password)}';\n` + }); + return r.status === 0 ? undefined : `psql exited ${r.status}: ${r.stderr.trim().slice(0, 200)}`; + }; + const err = apply(value, ctx.oldValue); + if (err) throw new RotatorError(`ALTER ROLE failed: ${err}`); + return { + value, + companions: rewriteUrls(ctx.vaultValues, ctx.oldValue, value), + async revokeOld() { + return undefined; // the old password died with ALTER ROLE + }, + async rollback() { + return apply(ctx.oldValue, value); + } + }; + } +}; + +export const ROTATORS: Record = Object.fromEntries( + [resendRotator, cloudflareTokenRotator, coinpayApiKeyRotator, coinpayWebhookSecretRotator, vapidRotator, postgresRoleRotator].map((r) => [r.id, r]) +); + +export function defaultRun(cmd: string, args: string[], opts: { input?: string; env?: Record }) { + const r = spawnSync(cmd, args, { input: opts.input, env: { ...process.env, ...opts.env }, encoding: "utf8", timeout: 60_000 }); + return { status: r.status, stdout: r.stdout ?? "", stderr: r.stderr ?? (r.error ? String(r.error.message) : "") }; +} diff --git a/scripts/logicsrc-rotate b/scripts/logicsrc-rotate new file mode 100755 index 00000000..c75e033e --- /dev/null +++ b/scripts/logicsrc-rotate @@ -0,0 +1,181 @@ +#!/usr/bin/env bash +# +# logicsrc-rotate: the weekly secret rotation job (runbook: logicsrc.com/docs/rotation). +# +# 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 +# +# Rotates only what `rotate-keys --scheduled` allows unattended (non-disruptive +# random secrets and overlapping provider rotators with known, healthy +# consumers), rewrites + restarts + health-checks the consumers under ~/www, +# and mails a report: rotated, rolled back, skipped (why), and the manual list +# with steps grouped by who has to do it. No secret value is ever printed, +# logged or mailed: the CLI's report holds key names, vaults, sites, outcomes. +# +# Config (optional, mode 600): ~/.config/logicsrc-rotate.env +# LOGICSRC_ROTATE_LIVE=1 actually rotate (default: dry run) +# LOGICSRC_ROTATE_TEAM=profullstack +# LOGICSRC_ROTATE_MAX=10 live rotations per run +# LOGICSRC_ROTATE_TO=a@x,b@y report recipients +# LOGICSRC_ROTATE_ROOT=~/www where consumer sites live +# LOGICSRC_ROTATE_MAX_SITES=5 skip values read by more sites than this +# LOGICSRC_ROTATE_EXCLUDE=a.com,b.com never touch these sites (default: the client site) +# RESEND_ADMIN_API_KEY, CLOUDFLARE_ADMIN_API_TOKEN, +# COINPAY_ROTATE_TOKEN | COINPAY_ROTATE_EMAIL + COINPAY_ROTATE_PASSWORD +# admin creds for the provider rotators +set -euo pipefail +umask 077 + +CONF="${LOGICSRC_ROTATE_CONF:-$HOME/.config/logicsrc-rotate.env}" +if [ -f "$CONF" ]; then + [ "$(stat -c %a "$CONF")" = 600 ] || { echo "refusing $CONF: mode must be 600" >&2; exit 2; } + set -a + # shellcheck disable=SC1090 + . "$CONF" + set +a +fi + +TEAM="${LOGICSRC_ROTATE_TEAM:-profullstack}" +MAX="${LOGICSRC_ROTATE_MAX:-10}" +TO="${LOGICSRC_ROTATE_TO:-ettinger@gmail.com}" +ROOT="${LOGICSRC_ROTATE_ROOT:-$HOME/www}" +LIVE="${LOGICSRC_ROTATE_LIVE:-0}" +MAX_SITES="${LOGICSRC_ROTATE_MAX_SITES:-5}" +# Client sites are never part of a fleet sweep. +EXCLUDE="${LOGICSRC_ROTATE_EXCLUDE:-tomahawkedison.com}" +MAIL=1 +for a in "$@"; do + case "$a" in + --dry-run) LIVE=0 ;; + --no-mail) MAIL=0 ;; + -h|--help) sed -n 2,25p "$0"; exit 0 ;; + *) echo "unknown option $a" >&2; exit 2 ;; + esac +done + +STATE="${XDG_STATE_HOME:-$HOME/.local/state}/logicsrc-rotate" +mkdir -p "$STATE" +chmod 700 "$STATE" +STAMP="$(date -u +%Y%m%dT%H%M%SZ)" +REPORT="$STATE/report-$STAMP.json" +exec 9>"$STATE/lock" +flock -n 9 || { echo "another logicsrc-rotate is running" >&2; exit 0; } + +# Leave room on the box: restarts rebuild nothing, but compose recreates still cost memory. +avail_gb=$(awk '/MemAvailable/ {print int($2/1048576)}' /proc/meminfo) +if [ "$LIVE" = 1 ] && [ "$avail_gb" -lt 6 ]; then + echo "only ${avail_gb} GB available: running as a dry run" >&2 + LIVE=0 +fi + +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 +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' +const fs = require("fs"); +const [file, live, status, errFile] = process.argv.slice(2); +let report; +try { + report = JSON.parse(fs.readFileSync(file, "utf8")); +} catch { + const err = fs.existsSync(errFile) ? fs.readFileSync(errFile, "utf8").slice(-1500) : ""; + console.log(`logicsrc-rotate could not produce a report (exit ${status}).\n\n${err}`); + process.exit(0); +} +const R = report.results; +const by = (s) => R.filter((r) => r.status === s); +const out = []; +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}`); +line(`Runbook: https://logicsrc.com/docs/rotation`); +line(); +const rotated = by("rotated"); +const would = by("would-rotate"); +line(`Rotated: ${rotated.length} Would rotate: ${would.length} Rolled back: ${by("rolled-back").length} Failed: ${by("failed").length} Skipped: ${by("skipped").length} Manual: ${by("todo").length}`); +for (const [title, list] of [["ROTATED (verified healthy, old value revoked)", rotated], ["WOULD ROTATE (set LOGICSRC_ROTATE_LIVE=1 to do it)", would], ["ROLLED BACK (old value restored everywhere)", by("rolled-back")], ["FAILED", by("failed")]]) { + if (!list.length) continue; + line(); + line(title); + // Dry runs list one line per key name; live results list every value. + if (title.startsWith("WOULD")) { + const g = new Map(); + for (const r of list) { + const k = `${r.key} [${r.method}]`; + const e = g.get(k) || { n: 0, sites: new Set() }; + e.n++; + for (const s of r.sites || []) e.sites.add(s.site); + g.set(k, e); + } + for (const [k, e] of g) line(` ${k} x${e.n} sites: ${[...e.sites].join(" ") || "-"}`); + continue; + } + for (const r of list) { + line(` ${r.key} [${r.method}] ${where(r)}`); + for (const s of r.sites || []) line(` ${s.site}: ${s.restart || "-"} / ${s.health || "-"}${s.backup ? ` (backup ${s.backup.split("/").pop()})` : ""}`); + if (r.note) line(` note: ${r.note}`); + if (r.error) line(` ${r.error}`); + } +} +const skipped = by("skipped"); +if (skipped.length) { + line(); + line("SKIPPED (left for a person, with the reason)"); + const reasons = new Map(); + for (const r of skipped) { + const why = (r.error || "").replace(/: .*/, ""); + reasons.set(why, [...(reasons.get(why) || []), r]); + } + for (const [why, list] of reasons) { + const n = new Map(); + for (const r of list) n.set(r.key, (n.get(r.key) || 0) + 1); + line(` ${why} (${list.length}): ${[...n].map(([k, c]) => (c > 1 ? `${k} x${c}` : k)).join(", ")}`); + } +} +const todo = by("todo"); +if (todo.length) { + line(); + line("MANUAL TO-DO (grouped by who does it, then family; steps once per family)"); + const owners = [["anthony", "Anthony (money, signing, his logins: never automated)"], ["agent", "An agent with dashboard / CLI access"]]; + for (const [owner, label] of owners) { + const mine = todo.filter((r) => (r.owner || "agent") === owner); + if (!mine.length) continue; + line(); + line(`== ${label}: ${mine.length} value(s)`); + const fam = new Map(); + for (const r of mine) fam.set(r.family || "other", [...(fam.get(r.family || "other") || []), r]); + for (const [f, list] of [...fam].sort((a, b) => b[1].length - a[1].length)) { + line(); + line(` -- ${f} (${list.length})${list[0].url ? ` ${list[0].url}` : ""}`); + if (list[0].note) line(` ${list[0].note}`); + for (const s of list[0].steps || []) line(` - ${s}`); + const keys = new Map(); + for (const r of list) keys.set(r.key, (keys.get(r.key) || 0) + (r.vaults || []).length); + line(` keys: ${[...keys].map(([k, n]) => `${k} (${n})`).join(", ")}`); + const why = [...new Set(list.map((r) => r.error).filter(Boolean))]; + if (why.length) line(` blocked: ${why.join("; ")}`); + } + } +} +if (report.locked && report.locked.length) { + line(); + line(`Vaults this identity cannot decrypt (not covered): ${report.locked.length}`); +} +console.log(out.join("\n")); +NODE + +SUBJECT="logicsrc rotation $( [ "$LIVE" = 1 ] && echo live || echo dry-run ): $(node -e 'try{const r=require(process.argv[1]).results;const c=s=>r.filter(x=>x.status===s).length;console.log(`${c("rotated")} rotated, ${c("rolled-back")+c("failed")} failed, ${c("todo")} manual`)}catch{console.log("no report")}' "$REPORT")" +if [ "$MAIL" = 1 ]; then + # The shell's RESEND_API_KEY can be stale; mail's own resend account is the house path. + env -u RESEND_API_KEY mail send --via resend --to "$TO" --subject "$SUBJECT" --file "$BODY" +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 +exit "$status"