From d446a62975ebbe0794c076bda5ddf6da5e4daaaa Mon Sep 17 00:00:00 2001 From: POWERFULMOVES <142271328+POWERFULMOVES@users.noreply.github.com> Date: Sat, 28 Nov 2026 10:34:48 -0500 Subject: [PATCH] feat(cipher): cipher-token-provision mints and binds a per-agent token, never printed The launchers read CIPHER_TOKEN_ from pmoves/.env.local (#3143, #3449); getting it there was left out of band, i.e. a human copying a bearer through a terminal. The new target runs the real card-gated minter in-process with --emit fd into an os.pipe and upserts exactly one line of .env.local (CRLF kept, atomic replace, 0600). Refuses an existing key unless REPLACE=1, and then says the old row is live until revoked. Includes the register CLAIM row for this lane. Co-Authored-By: Claude Opus 5.5 --- pmoves/Makefile | 6 + pmoves/docs/AGENTS/AGNOTE4482PHI.t1.md | 1 + pmoves/scripts/cipher_token_provision.py | 179 ++++++++++++++++++ .../tools/test_cipher_token_provision.py | 113 +++++++++++ 4 files changed, 299 insertions(+) create mode 100644 pmoves/scripts/cipher_token_provision.py create mode 100644 pmoves/tests/tools/test_cipher_token_provision.py diff --git a/pmoves/Makefile b/pmoves/Makefile index 716b35b71..2295817c1 100644 --- a/pmoves/Makefile +++ b/pmoves/Makefile @@ -6251,6 +6251,12 @@ cipher-mint-token: ## Mint a per-agent cipher token (requires an ACTIVE signing @if [ -z "$(AGENT)" ]; then echo "Usage: make -C pmoves cipher-mint-token AGENT=z890-claude [SCOPES='memory:read,memory:write']"; exit 1; fi @$(PYTHON) $(CURDIR)/scripts/mint_cipher_token.py --agent "$(AGENT)" --scopes "$(or $(SCOPES),$(CIPHER_MINT_DEFAULT_SCOPES))" +cipher-token-provision: ## Mint AND bind a per-agent cipher token into pmoves/.env.local, never printed: AGENT=4090-claude [SCOPES=...] [REPLACE=1] + @if [ -z "$(AGENT)" ]; then echo "Usage: make -C pmoves cipher-token-provision AGENT=4090-claude [REPLACE=1]"; exit 1; fi + @# with-env.sh puts SUPABASE_SERVICE_KEY into THIS child only; the token goes + @# minter -> os.pipe -> .env.local inside one python process (see the script). + @bash -lc '. ./scripts/with-env.sh; exec $(PYTHON) scripts/cipher_token_provision.py --agent "$(AGENT)" --scopes "$(or $(SCOPES),$(CIPHER_MINT_DEFAULT_SCOPES))" $(if $(REPLACE),--replace,)' + cipher-revoke-token: ## Retire an agent's cipher tokens (sets revoked_at; auth.ts already rejects them): AGENT=z890-claude [TOKEN_UUID=... DRY_RUN=1] @if [ -z "$(AGENT)" ]; then echo "Usage: make -C pmoves cipher-revoke-token AGENT=z890-claude [TOKEN_UUID= DRY_RUN=1]"; exit 1; fi @$(PYTHON) $(CURDIR)/scripts/revoke_cipher_token.py --agent "$(AGENT)" $(if $(TOKEN_UUID),--token-uuid "$(TOKEN_UUID)",) $(if $(DRY_RUN),--dry-run,) diff --git a/pmoves/docs/AGENTS/AGNOTE4482PHI.t1.md b/pmoves/docs/AGENTS/AGNOTE4482PHI.t1.md index 668ee2dfe..3d00b9ca1 100644 --- a/pmoves/docs/AGENTS/AGNOTE4482PHI.t1.md +++ b/pmoves/docs/AGENTS/AGNOTE4482PHI.t1.md @@ -3698,3 +3698,4 @@ VILLAGE RULE: delivery delegated to a delivery-agent body; control and memory ar - `2026-11-24T13:36:51Z` RELEASE `5090-CLAUDE` branch: `fix/openroom-root-redirect-2026-11-23` · scope: DELIVERED PR #3527: PMOVES-OpenRoom gitlink 9233894 -> aec292e (fork #19 merged: absolute_redirect off). Root cause: nginx absolute redirects carried the CONTAINER port 3000 through the 5173:3000 publish mapping, so the operator's bare-root URL landed on the wrong host service. Reviewed APPROVE by code-review body with live nginx A/B on the Dockerfile image; two nits taken (topology trimmed from public comment, PR body records the implicit directory-redirect fix); lint-and-build green. 5090 rebuilt via build-svc + recreate-svc: GET / -> 301 Location: /webuiapps/ -> 200, same via the tailnet name. Awaiting checks + Control ACK + closeout merge. - `2026-11-25T07:20:02Z` NOTE `5090-CLAUDE` branch: `fix/httpx-stub-test-pollution` · scope: Scope correction for the 06:23:56Z CLAIM: the 11 semantic-cache entries the Merge Gate reported STALE at bcc2619 are NOT fixed and will NOT be dropped. Measured locally with the ratchet chunking (pytest 9.2.0, 20-file chunks of the pmoves group): the new test file shifts chunk boundaries, moving test_cache.py into chunk [4], and pmoves/tools/test_all_tts_engines.py calls sys.exit(1) at import when gradio_client is absent, so chunk [4] aborts with INTERNALERROR during collection and pytest writes a partial junit (3 sso-auth collection errors, nothing else). The ratchet reads absence as fixed. On main that chunk has never produced a test result (19 files unmeasured every run). Lane now also: guard that script so it skips under pytest, make the ratchet treat pytest exit 3 as a lost chunk (isolate per file, record an finding), and baseline what CI then surfaces, with a header note. The test_cache errors themselves are an alias gap (pmoves.services.semantic_cache is not in the services shim), separate issue to follow. - `2026-11-25T08:21:30Z` RELEASE `5090-CLAUDE` branch: `fix/httpx-stub-test-pollution` · scope: PR #3517 merged 14899a3 (closes #3510). tests (3.11) green on main again, so the standing advisory waivers stop. Also landed: the python-tests ratchet treats pytest exit 3 as a lost chunk (isolate per file, record the aborting file; a session-wide abort is one dead group), pmoves/tools/test_all_tts_engines.py skips under pytest instead of sys.exit, and chunk pmoves [4] was measured for the first time: 17 real semantic-cache failures recorded in the baseline with a header note, stale ERROR|pytest|internal dropped (151 -> 167). Alias gap behind all 28 semantic-cache findings filed as #3529. RELEASE row rides PR #3521 because the lane merged before it was filed. +- `2026-11-28T15:30:46Z` CLAIM `4090-CLAUDE` branch: `feat/cipher-token-provision-2026-11-28` · **TTL 48h (expires `2026-11-30T15:30:46Z`)** · scope: make cipher-token-provision AGENT=: mint a per-agent cipher token with --emit fd and upsert CIPHER_TOKEN_ into pmoves/.env.local without ever printing it (the out-of-band last mile #3143 left open). New script + Make target + tests; no compose, no guard changes. diff --git a/pmoves/scripts/cipher_token_provision.py b/pmoves/scripts/cipher_token_provision.py new file mode 100644 index 000000000..237e95df9 --- /dev/null +++ b/pmoves/scripts/cipher_token_provision.py @@ -0,0 +1,179 @@ +#!/usr/bin/env python3 +"""Mint a per-agent cipher token and bind it into pmoves/.env.local, unseen. + +The last mile #3143 left "out of band". The launchers (pm-cipher-token-bind.sh, +.ps1) read ``CIPHER_TOKEN_`` from ``pmoves/.env.local``; the minter +(mint_cipher_token.py, card-gated) prints the bearer by default. Between the two, +the only route was a human copying a secret through a terminal, the exact +transcript leak the minter's own ``--emit`` help warns about. + +This joins them without the value ever leaving the process: + + mint_cipher_token.main() --emit fd--> os.pipe --> upsert .env.local + +* Nothing about the token reaches stdout, stderr, argv or a temp path. stdout + carries only names: the key written, the file and the agent. +* The minter runs IN PROCESS, loaded by path, so its card gate, scopes and + Supabase insert are the ones that run, not a copy of them. +* The upsert touches exactly one line. Every other line, comment and line + ending is kept byte-for-byte; the file is replaced atomically (temp file in + the same directory, then os.replace) and created 0600 on POSIX. +* A key that already exists is refused unless ``--replace``. A second mint + without that flag would leave two live rows for one agent. With it, the old + row stays VALID in cipher_agent_tokens until ``make cipher-revoke-token``, + and this tool says so. + +Run it through the Make target, which loads the service key with with-env.sh: + + make -C pmoves cipher-token-provision AGENT=4090-claude [REPLACE=1] +""" +from __future__ import annotations + +import argparse +import importlib.util +import os +import re +import sys +from pathlib import Path + +PMOVES_DIR = Path(__file__).resolve().parents[1] +DEFAULT_ENV_FILE = PMOVES_DIR / ".env.local" +MINTER = PMOVES_DIR / "scripts" / "mint_cipher_token.py" +TOKEN_RE = re.compile(r"^cipher_[0-9a-f]{32}$") +AGENT_RE = re.compile(r"^[a-z0-9][a-z0-9-]*$") + + +def env_key(agent: str) -> str: + """The launcher's key spelling: CIPHER_TOKEN_ + agent upper, '-' -> '_'.""" + return "CIPHER_TOKEN_" + agent.upper().replace("-", "_") + + +def _key_line_index(lines: list[str], key: str) -> int | None: + pat = re.compile(rf"^\s*(?:export\s+)?{re.escape(key)}\s*=") + for i, line in enumerate(lines): + if pat.match(line): + return i + return None + + +def _read(path: Path) -> str: + # newline="" keeps CRLF intact: read_text() would fold every CRLF to LF + # and the "one line touched" promise would rewrite the whole file. + with open(path, encoding="utf-8", newline="") as fh: + return fh.read() + + +def has_key(path: Path, key: str) -> bool: + if not path.exists(): + return False + return _key_line_index(_read(path).splitlines(keepends=True), key) is not None + + +def upsert(path: Path, key: str, value: str) -> str: + """Set ``key=value`` in a dotenv file, touching only that line. + + Returns "added" or "replaced". Keeps the file's dominant line ending. + """ + text = _read(path) if path.exists() else "" + lines = text.splitlines(keepends=True) + eol = "\r\n" if "\r\n" in text else "\n" + entry = f"{key}={value}" + idx = _key_line_index(lines, key) + if idx is None: + if lines and not lines[-1].endswith(("\n", "\r")): + lines[-1] += eol + lines.append(entry + eol) + action = "added" + else: + old = lines[idx] + ending = old[len(old.rstrip("\r\n")):] or eol + lines[idx] = entry + ending + action = "replaced" + + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_name(f".{path.name}.provision.tmp") + fd = os.open(str(tmp), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + try: + with os.fdopen(fd, "w", encoding="utf-8", newline="") as fh: + fh.write("".join(lines)) + os.replace(tmp, path) + finally: + if tmp.exists(): + tmp.unlink() + return action + + +def _load_minter(): + spec = importlib.util.spec_from_file_location("_pmoves_mint_cipher_token", MINTER) + if spec is None or spec.loader is None: # pragma: no cover - packaging guard + raise ImportError(f"cannot load {MINTER}") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def mint(agent: str, scopes: str, minter=None) -> tuple[int, str]: + """Run the real minter with --emit fd into a pipe; return (rc, token).""" + minter = minter or _load_minter() + r, w = os.pipe() + argv = sys.argv + try: + sys.argv = [str(MINTER), "--agent", agent, "--scopes", scopes, + "--emit", "fd", "--emit-fd", str(w)] + rc = minter.main() + finally: + sys.argv = argv + os.close(w) # the minter dup()s and closes its copy; this ends the stream + with os.fdopen(r, "r", encoding="utf-8") as fh: + token = fh.read().strip() + return rc, token + + +def main(argv: list[str] | None = None, minter=None) -> int: + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("--agent", required=True, help="signing-card agent_id, e.g. 4090-claude") + ap.add_argument("--scopes", default="memory:read,memory:write") + ap.add_argument("--env-file", default=str(DEFAULT_ENV_FILE)) + ap.add_argument("--replace", action="store_true", + help="overwrite an existing key (the old row stays valid until revoked)") + args = ap.parse_args(argv) + + if not AGENT_RE.match(args.agent): + print(f"error: agent id {args.agent!r} is not a card spelling " + "(lowercase, digits, '-'): pass the signing-card agent_id", file=sys.stderr) + return 2 + key = env_key(args.agent) + env_file = Path(args.env_file) + + existed = has_key(env_file, key) + if existed and not args.replace: + print(f"refused: {key} is already set in {env_file}. Minting again would leave " + "two live tokens for one agent. Bind the existing one (relaunch), or pass " + "REPLACE=1 and then revoke the old row: " + f"make -C pmoves cipher-revoke-token AGENT={args.agent}", file=sys.stderr) + return 2 + + rc, token = mint(args.agent, args.scopes, minter=minter) + if rc != 0: + print(f"error: mint failed (rc={rc}); {env_file} was not touched", file=sys.stderr) + return rc + if not TOKEN_RE.match(token): + # Never echo it: a malformed value may still be a credential. + print(f"error: the minter returned no well-formed cipher_ token " + f"({len(token)} chars); {env_file} was not touched", file=sys.stderr) + return 1 + + action = upsert(env_file, key, token) + del token + print(f"PROVISIONED {key} ({action}) in {env_file} for agent {args.agent}") + print("next: relaunch claude-pmoves so pm-cipher-token-bind exports it as " + "CIPHER_API_TOKEN, then: make -C pmoves cipher-identity AGENT=" + args.agent) + if existed: + print("NOTE: the replaced token is still VALID until revoked: " + f"make -C pmoves cipher-revoke-token AGENT={args.agent} TOKEN_UUID= " + "(DRY_RUN=1 lists rows)") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/pmoves/tests/tools/test_cipher_token_provision.py b/pmoves/tests/tools/test_cipher_token_provision.py new file mode 100644 index 000000000..bd7e4aa75 --- /dev/null +++ b/pmoves/tests/tools/test_cipher_token_provision.py @@ -0,0 +1,113 @@ +"""cipher_token_provision: the token goes minter -> pipe -> .env.local, unseen. + +The minter is replaced by a fake that speaks the real one's contract +(``--emit fd --emit-fd N``: write the bearer to fd N, print names only), so +these tests never touch Supabase and never hold a real credential. +""" +from __future__ import annotations + +import importlib.util +import os +import sys +from pathlib import Path + +import pytest + +REPO_ROOT = Path(__file__).resolve().parents[3] +SCRIPT = REPO_ROOT / "pmoves" / "scripts" / "cipher_token_provision.py" +FAKE = "cipher_" + "ab" * 16 + + +def _load(): + spec = importlib.util.spec_from_file_location("cipher_token_provision", SCRIPT) + mod = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = mod + spec.loader.exec_module(mod) + return mod + + +P = _load() + + +class FakeMinter: + def __init__(self, token=FAKE, rc=0): + self.token, self.rc, self.argv = token, rc, None + + def main(self): + self.argv = list(sys.argv) + fd = int(sys.argv[sys.argv.index("--emit-fd") + 1]) + if self.rc == 0: + with os.fdopen(os.dup(fd), "w", closefd=True) as fh: + fh.write(self.token) + print("AGENT=x\nSCOPES=y\nTOKEN_WRITTEN_TO=fd:%d" % fd) + return self.rc + + +def test_env_key_matches_the_launcher_spelling(): + assert P.env_key("4090-claude") == "CIPHER_TOKEN_4090_CLAUDE" + assert P.env_key("knuckles-kimi") == "CIPHER_TOKEN_KNUCKLES_KIMI" + + +def test_provision_writes_only_its_key_and_never_prints_the_token(tmp_path, capsys): + env = tmp_path / ".env.local" + env.write_bytes(b"# operator file\r\nFOO=bar\r\nCIPHER_DB_SERVICE_KEY=${X}\r\n") + fake = FakeMinter() + assert P.main(["--agent", "4090-claude", "--env-file", str(env)], minter=fake) == 0 + out = capsys.readouterr() + assert FAKE not in out.out and FAKE not in out.err + assert "--emit" in fake.argv and fake.argv[fake.argv.index("--emit") + 1] == "fd" + assert env.read_bytes() == ( + b"# operator file\r\nFOO=bar\r\nCIPHER_DB_SERVICE_KEY=${X}\r\n" + + f"CIPHER_TOKEN_4090_CLAUDE={FAKE}\r\n".encode()) + + +def test_existing_key_is_refused_without_replace_and_minter_never_runs(tmp_path): + env = tmp_path / ".env.local" + env.write_text("CIPHER_TOKEN_4090_CLAUDE=cipher_old\n", encoding="utf-8") + fake = FakeMinter() + assert P.main(["--agent", "4090-claude", "--env-file", str(env)], minter=fake) == 2 + assert fake.argv is None # no second live row was minted + assert env.read_text(encoding="utf-8") == "CIPHER_TOKEN_4090_CLAUDE=cipher_old\n" + + +def test_replace_rewrites_one_line_and_warns_the_old_row_is_live(tmp_path, capsys): + env = tmp_path / ".env.local" + env.write_text("A=1\nCIPHER_TOKEN_4090_CLAUDE=cipher_old\nB=2\n", encoding="utf-8") + rc = P.main(["--agent", "4090-claude", "--env-file", str(env), "--replace"], + minter=FakeMinter()) + assert rc == 0 + assert env.read_text(encoding="utf-8") == f"A=1\nCIPHER_TOKEN_4090_CLAUDE={FAKE}\nB=2\n" + assert "still VALID until revoked" in capsys.readouterr().out + + +@pytest.mark.parametrize("token,rc", [("", 1), ("not-a-token", 0), (FAKE, 1)]) +def test_failed_or_malformed_mint_leaves_the_file_untouched(tmp_path, capsys, token, rc): + env = tmp_path / ".env.local" + env.write_text("A=1\n", encoding="utf-8") + assert P.main(["--agent", "4090-claude", "--env-file", str(env)], + minter=FakeMinter(token=token, rc=rc)) != 0 + assert env.read_text(encoding="utf-8") == "A=1\n" + out = capsys.readouterr() + assert "not-a-token" not in out.out + out.err + + +def test_registry_spelling_is_refused_before_minting(tmp_path): + fake = FakeMinter() + assert P.main(["--agent", "claude_4090", "--env-file", str(tmp_path / "e")], + minter=fake) == 2 + assert fake.argv is None + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX file modes") +def test_new_file_is_created_0600(tmp_path): + env = tmp_path / ".env.local" + P.main(["--agent", "4090-claude", "--env-file", str(env)], minter=FakeMinter()) + assert (env.stat().st_mode & 0o777) == 0o600 + + +def test_make_target_loads_env_and_calls_the_script(): + mk = (REPO_ROOT / "pmoves" / "Makefile").read_text(encoding="utf-8") + start = mk.index("cipher-token-provision:") + recipe = mk[start:mk.index("cipher-revoke-token:", start)] + assert "with-env.sh" in recipe and "scripts/cipher_token_provision.py" in recipe + assert "--emit" not in recipe # the script owns the emit mode, not the caller