Repository navigation
fix(5090): JWT rotation runbook v1 + jwt_rotate.py (backup-first; 13 consumers; cross-fork map) - #3346
fix(5090): JWT rotation runbook v1 + jwt_rotate.py (backup-first; 13 consumers; cross-fork map)#3346POWERFULMOVES wants to merge 6 commits into
Conversation
|
Important Review skippedAuto reviews are limited based on label configuration. 🏷️ Required labels (at least one): 1
Please check the settings in the CodeRabbit UI or the
|
Fleet review: kilocode (zai-coding-plan/glm-5.3)reviewer: tier 2/3
reviewer chain
_ lane: fleet-review chain (self-hosted kvm4) - spark-local (when online) -> kilo-primary -> kilo-alternate _ |
| # SUPABASE_-prefixed alias if it exists in the file. | ||
| replacements: Dict[str, str] = {} | ||
| for key in ROTATION_VARS: | ||
| replacements[key] = new.get(key, "") |
There was a problem hiding this comment.
🔥 The Roast: The comment two lines up promises rotate "also update[s] the SUPABASE_-prefixed alias if it exists in the file" — and then line 453's filter deletes every alias, because keygen() only ever returns three keys. So SUPABASE_JWT_SECRET, SUPABASE_ANON_KEY, SUPABASE_SERVICE_ROLE_KEY, and SUPABASE_SERVICE_KEY survive a "rotation" still carrying the OLD secret. This isn't hypothetical: pmoves/env.shared.example:184 shows SUPABASE_SERVICE_KEY is the var Archon/cipher actually reads, pmoves/scripts/supabase/generate-keys.sh:91-93 materializes these aliases alongside the primaries, and compose env_file: does zero ${...} resolution — whatever stale literal sits in env.tier-supabase is what the consumer gets. Meanwhile the runbook (Phase 3, step 3, runbook lines 86-88) advertises all 7 vars updated. A rotation tool that leaves half the locks keyed to the old secret is a lie with a backup file attached. (Expands the fleet-review P1 onto the exact line that needs it.)
🩹 The Fix: map the aliases explicitly and drop the truthiness filter:
replacements = {
"JWT_SECRET": new["JWT_SECRET"],
"SUPABASE_JWT_SECRET": new["JWT_SECRET"],
"ANON_KEY": new["ANON_KEY"],
"SUPABASE_ANON_KEY": new["ANON_KEY"],
"SERVICE_ROLE_KEY": new["SERVICE_ROLE_KEY"],
"SUPABASE_SERVICE_ROLE_KEY": new["SERVICE_ROLE_KEY"],
"SUPABASE_SERVICE_KEY": new["SERVICE_ROLE_KEY"],
}
write_env_replace(tier_supabase, replacements)(write_env_replace only rewrites keys present in the file, so a file without the aliases is unaffected — missing keys get appended; the next test should pin that: feed rotate a file containing the four aliases and assert none survives with old values.)
📏 Severity: critical
Reply with @kilocode-bot fix it to have Kilo Code address this issue.
| cur_reasons = [] | ||
| continue | ||
| m = SERVICE_TOP.match(stripped) | ||
| if m and indent == 2: |
There was a problem hiding this comment.
🔥 The Roast: A hand-rolled YAML parser whose entire world model is 'services live at exactly two-space indent and env_file: entries end the line'. Any compose file written with 4-space indentation silently contributes zero consumers, and env_file: env.shared # see notes (trailing comment) misses the line-end match. Silent-skip combined with a runbook that treats the enumerate output as full coverage is how v0-vs-v1 déjà vu happens again — except this time the tool confidently reports [] and the operator believes it, because the test suite never parsed a file nobody hand-wrote for it.
🩹 The Fix: derive the service indent from the first service line seen instead of hard-coding == 2, and allow trailing comments in the env_file match. Better: use yaml.safe_load (PyYAML is already the house tool in pmoves/tools/ — see a0_plugins_check.py, agent_registry_check.py) and keep this parser as a fallback.
📏 Severity: suggestion
Reply with @kilocode-bot fix it to have Kilo Code address this issue.
| from typing import Any, Dict, List, Optional, Tuple | ||
|
|
||
| # Default paths; override via env or CLI flags. | ||
| REPO_ROOT_DEFAULT = Path(os.environ.get("PMOVES_REPO_ROOT", Path.cwd())) |
There was a problem hiding this comment.
🔥 The Roast: Path.cwd() frozen at import time means the tool rotates the JWT of whatever directory the interpreter happened to wake up in. The runbook mitigates with a cd "$(git rev-parse --show-toplevel)" pin — i.e. the safety of a destructive, in-place secret rewrite rests entirely on operator discipline; nothing ever verifies the resolved root actually belongs to this repo (an env.tier-supabase in any stray cwd gets rotated just fine). It also leaks into the tests: test_enumerate_finds_canonical_supabase_consumers calls enumerate_consumers() with this frozen default, so 26/26 green is only true when pytest runs from the repo root via python -m pytest — bare pytest from anywhere else imports differently or finds zero compose files. The suite carries an undocumented cwd precondition and calls itself a ratchet.
🩹 The Fix: resolve the fallback repo root relative to this file — Path(__file__).resolve().parents[2] — instead of Path.cwd(), making the tool location-independent; and have the enumerate tests pass an explicit root (the CLI test already does this right).
📏 Severity: suggestion
Reply with @kilocode-bot fix it to have Kilo Code address this issue.
| self.assertIn("JWT_SECRET=old", text) | ||
| self.assertIn("NEW_KEY=new_value", text) | ||
|
|
||
| def test_rotate_takes_backup_before_writing(self): |
There was a problem hiding this comment.
🔥 The Roast: This test is named test_rotate_takes_backup_before_writing, its docstring says rotate must call backup_env BEFORE write_env_replace — and then it invokes the backup subcommand and clocks out. Not one line of rotate is exercised: an author who reorders backup_env and write_env_replace in main() — recreating exactly the P1.1 no-working-rollback bug this PR exists to fix — passes the entire suite green. Bonus: lines 151-152 write a tier fixture into self.tmp that nothing ever reads. Dead code cosplaying as setup. A ratchet that does not engage on the failure mode it is named after is decoration.
🩹 The Fix: actually run rotate: [sys.executable, str(script_path), "--repo-root", str(fake_repo), "rotate"], then assert (a) a .bak.* file exists whose content equals the pre-rotation file, and (b) the live file contains three-segment JWTs. Delete the unused tier writes. Optionally monkeypatch jwt_rotate.generate_jwt_secret to a fixed value so assertions are deterministic.
📏 Severity: warning
Reply with @kilocode-bot fix it to have Kilo Code address this issue.
| # --------------------------------------------------------------------------- | ||
| def read_env(path: Path) -> Dict[str, str]: | ||
| """Parse a tier env file (KEY=VALUE) into a dict. Preserves comments and | ||
| blank lines via a separate index map. Returns a flat dict of keys; the |
There was a problem hiding this comment.
🔥 The Roast: The docstring claims read_env Preserves comments and blank lines via a separate index map — it returns a flat Dict[str, str]. Nothing is preserved. There is no index map. There is not even map-adjacent ambition. It then directs readers to a replace_value function that does not exist anywhere in this file (the writer is write_env_replace). In a repo where docstring coverage is a CI gate, a docstring that is confidently wrong is worse than no docstring — it is misinformation wearing the authority of documentation.
🩹 The Fix: say what actually happens:
| blank lines via a separate index map. Returns a flat dict of keys; the | |
| """Parse a tier env file (KEY=VALUE) into a flat dict. Comments and blank | |
| lines are NOT retained here; the writer, `write_env_replace`, preserves | |
| them by rewriting only the keys in its replacement map.""" |
📏 Severity: nitpick
Reply with @kilocode-bot fix it to have Kilo Code address this issue.
Code Review Roast 🔥Verdict: 9 Issues Found | Recommendation: Address before merge Overview
Issue Details (click to expand)
Also on file (not duplicated here): the two CodeQL clear-text-logging findings at Fix these issues in Kilo Cloud 🏆 Best part: The keygen mirror itself is honest work — 💀 Worst part: The rotation bug at line 451 — the tool's entire reason for existing is to move every consumer onto the new secret, and it leaves the four 📊 Overall: Like a new lock company whose demo is rekeying your house — great hardware, careful backups, meticulous documentation of the process… and they only changed two of the five locks, but the brochure says all five. Files Reviewed (5 files)
Reviewed by glm-5.3-flash · Input: 126.2K · Output: 26.6K · Cached: 1.5M |
…n a worktree is_excluded() substring-matched the ABSOLUTE path for "worktrees". When the repo itself lives in a git worktree - the layout this fleet actually uses, 210 of them on the 4090 alone - every compose file answered True and the survey returned zero consumers. The failure is silent and load-bearing: `jwt_rotate rotate` builds its blast-radius list from that survey. Run from a worktree it would have reported nothing to update and left all 13 Supabase consumers on the old key while `verify` passed against the one endpoint it did probe. Decision is now made on the path RELATIVE to the survey root: a nested .worktrees/ directory is still skipped, but the survey root may itself be one. node_modules, .git and the pmoves-supabase submodule stay excluded. Three regression tests pin the behaviour (29 pass, was 26 passing / 1 failing). Found while rebasing #3346 onto current main: the rebase was textually clean and the suite still failed, because main had moved and nothing asserted the exclusion logic against a worktree root.
f6d2edf to
e99f184
Compare
ORGSIM-MIRROR drift check (advisory, fail-soft)vv3 / 8 files / VERIFIED 124 / DRIFTED 10 / UNDECIDED 29 / digest 2711c2ad83f5 Zero-LLM deterministic audit - unreachable = UNDECIDED, never dead - scripts/runbook_drift.py |
ORGSIM-MIRROR drift check (advisory, fail-soft)vv3 / 8 files / VERIFIED 124 / DRIFTED 10 / UNDECIDED 29 / digest 120e0fc5478c Zero-LLM deterministic audit - unreachable = UNDECIDED, never dead - scripts/runbook_drift.py |
…env.tier-supabase before edit; enumerates 13 canonical Supabase consumers; cross-fork map; backup-first semantics)
…n a worktree is_excluded() substring-matched the ABSOLUTE path for "worktrees". When the repo itself lives in a git worktree - the layout this fleet actually uses, 210 of them on the 4090 alone - every compose file answered True and the survey returned zero consumers. The failure is silent and load-bearing: `jwt_rotate rotate` builds its blast-radius list from that survey. Run from a worktree it would have reported nothing to update and left all 13 Supabase consumers on the old key while `verify` passed against the one endpoint it did probe. Decision is now made on the path RELATIVE to the survey root: a nested .worktrees/ directory is still skipped, but the survey root may itself be one. node_modules, .git and the pmoves-supabase submodule stay excluded. Three regression tests pin the behaviour (29 pass, was 26 passing / 1 failing). Found while rebasing #3346 onto current main: the rebase was textually clean and the suite still failed, because main had moved and nothing asserted the exclusion logic against a worktree root.
… with the manifest?
secrets_manifest.yaml declares JWT_SECRET and SUPABASE_JWT_SECRET as aliases of one
canonical value. Measured on the 4090 on 2026-11-21, the runtime disagreed three ways:
env.shared JWT_SECRET 58 chars
env.shared SUPABASE_JWT_SECRET 55 chars
live Kong container JWT_SECRET 64 chars
Supabase signs tokens with the container's secret. BoTZ (features/mcp_bridge/auth.py,
features/gateway/python-gateway/a2a/server.py) validates against SUPABASE_JWT_SECRET.
Nothing mints in BoTZ -- both are decoders -- so the mismatch rejects every token that
crosses, and it presents as a generic 401 with three plausible causes.
Adds:
check_alias_integrity(env, container_secret) -- pure, returns divergences
read_container_jwt_secret(container) -- docker exec printenv
`jwt_rotate check-aliases [--env PATH] [--container NAME]`
Deliberately a COMMAND, not a test that reads the live machine. Against the real env it
reports:
alias integrity: DIVERGENT
- JWT_SECRET and SUPABASE_JWT_SECRET differ in the env file ...
- JWT_SECRET does not match the live container JWT_SECRET (env len=58, container len=64)
- SUPABASE_JWT_SECRET does not match the live container JWT_SECRET (env len=55, container len=64)
Seven fixture-based tests pin the logic (36 pass total). The live state stays a
diagnostic an operator runs, because a repo check that is red on the day it lands gets
muted -- which is how two Supabase secret alerts here ended up closed as false positives
while a live service_role key stayed in a public file.
Note for the rotation run: `rotate` rotates JWT_SECRET and re-mints anon + service_role,
so it RESOLVES this divergence. Run `check-aliases` before and after to confirm.
2bd59d4 to
da01243
Compare
ORGSIM-MIRROR drift check (advisory, fail-soft)vv3 / 8 files / VERIFIED 124 / DRIFTED 10 / UNDECIDED 29 / digest 3e93c67b1c91 Zero-LLM deterministic audit - unreachable = UNDECIDED, never dead - scripts/runbook_drift.py |
…-text-logging)
CodeQL raised 2 high-severity alerts at jwt_rotate.py:543. Both are real disclosure,
not lint noise:
* `rotate --dry-run` called `json.dumps(new, indent=2)` and printed the full
contents of JWT_SECRET, ANON_KEY and SERVICE_ROLE_KEY to stdout - terminal
scrollback, CI logs, and any transcript of the session.
* the post-rotation summary printed each new key as `first8...last4`. A truncated
credential is still a credential: 12 characters of a signing key is material.
Both now print only the key name and its length. An operator who needs the values
reads them from the file the non-dry-run path writes - which is where they have to
come from anyway, since the whole point of `rotate` is to write them there.
No test asserted on either output, so behaviour is otherwise unchanged: 36 pass.
ORGSIM-MIRROR drift check (advisory, fail-soft)vv3 / 8 files / VERIFIED 124 / DRIFTED 10 / UNDECIDED 29 / digest f7e177903a0e Zero-LLM deterministic audit - unreachable = UNDECIDED, never dead - scripts/runbook_drift.py |
Summary
Inherits the 5090 JWT rotation runbook lane from PR #3213 (operator-owned draft, B850-CLAUDE REQUEST-CHANGES), supersedes it with a full v1 that addresses every P1/P2/P3 in B850's 2026-09-28 review. The slice lands a reusable operator tool (
pmoves/tools/jwt_rotate.py) plus a runbook that references the tool instead of inline bash, plus 26 ratchets and a live end-to-end verification.Operator directive 2026-10-11: "review JWT since it was done on PMOVES-BoTZ and PMOVES-Archon as well as supabase we should map out to one ensure no conflictss and routes correct PMOVES-supabase".
The "map to one" is the PATTERN, not the SECRET. Each PMOVES surface has its own JWT scope; the runbook unifies the BACKUP → ROTATE → ENUMERATE → RECREATE → VERIFY → ROLLBACK sequence across all of them, while keeping the secrets surface-local.
What this PR carries (vs PR #3213)
pmoves/docs/RUNBOOK-5090-JWT-ROTATION.mdpmoves/tools/jwt_rotate.py(NEW)backup+rotateboth write.bak.<UTC-ISO>firstrollback <backup_file>restores from the named filecd "$(git rev-parse --show-toplevel)"What this PR does NOT carry (vs PR #3213)
|| echo 'changeme'(line 91 in v0) that silently falls back to a default dashboard credential. The v1 script raises on missing credentials instead./tmpfiles. The v1 script prints to stdout (operator captures withumask 077+mktemp).Cross-fork map (the "map out to one" piece)
POWERFULMOVES/PMOVES.AIpmoves/env.tier-supabasePOWERFULMOVES/PMOVES-BoTZcore/docker-compose/env.sharedPOWERFULMOVES/PMOVES-ArchonPOWERFULMOVES/PMOVES-supabase(submodule)generate-keys.shlives heregrep -r JWT_SECRETconfirms the BoTZ and Archon distinction:core/docker-compose/env.sharedand docs. BoTZ's JWT is the Mavis-gateway JWT; it does NOT gate PostgREST.Conflict check: rotating this runbook's secret does NOT affect BoTZ or Archon. A BoTZ rotation is a separate operator task in BoTZ's docs.
The 13 canonical Supabase consumers
Enumerated by parsing every
pmoves/docker-compose*.ymlfor<<: *tier-supabase-hardened[-ro]anchors:Pinned as
jwt_rotate.CANONICAL_SUPABASE_CONSUMERS(13-tuple, asserted bytest_canonical_supabase_consumers_pinned).Commits
Tests
pmoves/tools/tests/test_jwt_rotate.py— 26/26 PASS across 6 test classesC:\Users\russe\AppData\Local\Temp\jwt-rotate-live:backup→ wroteenv.tier-supabase.bak.2026-10-11T13-03-10Z(66 bytes, matches source)rotate --dry-run→ JSON with fresh JWT_SECRET (40-char base64), real 3-segment ANON_KEY + SERVICE_ROLE_KEY JWTsrotate→ wrote new keys to active env, took a fresh backup, printed the consumer listrollback→ restored from the named backup, took a pre-rollback snapshotFiles
NEW (4):
pmoves/tools/jwt_rotate.py(~480 lines, 18915 bytes) — the rotation toolpmoves/docs/RUNBOOK-5090-JWT-ROTATION.md(~200 lines) — the new runbook (replaces v0)pmoves/tools/tests/test_jwt_rotate.py(~310 lines, 12057 bytes) — 26 ratchetspmoves/docs/AGENTS/jwt_rotate_v1_LEARNINGS.md(11.4 KB) — 4-bucket × 5-class taxonomyMODIFIED (1):
pmoves/docs/AGENTS/AGNOTE4482PHI.t1.md— RELEASE row at 2026-10-11T13:05:00ZVerification commands
Provenance (DARKXSIDE practice 2026-09-16, no workarounds)
pmoves/tools/jwt_rotate.py:1-480(keygen, backup, write_env_replace, enumerate, verify, CLI)pmoves/docs/RUNBOOK-5090-JWT-ROTATION.md:1-200pmoves/tools/tests/test_jwt_rotate.py:1-310(26 ratchets, all green)pmoves/docs/AGENTS/AGNOTE4482PHI.t1.mdRELEASE row at 2026-10-11T13:05:00Zpmoves/docs/AGENTS/jwt_rotate_v1_LEARNINGS.md(11.4 KB, 4-bucket × 5-class)fix/5090-jwt-rotation-runbook-rollback→ mainFollow-up
After this PR merges, PR #3213 can close with
superseded by #<this>.