Repository navigation
feat(cipher): cipher-token-provision — mint and bind a per-agent token, never printed #3540
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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_<AGENT>`` 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 | ||
|
Comment on lines
+141
to
+144
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When provisioning the active Useful? React with 👍 / 👎. |
||
| 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) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
If Useful? React with 👍 / 👎. |
||
| 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=<old> " | ||
| "(DRY_RUN=1 lists rows)") | ||
| return 0 | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| sys.exit(main()) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
During every successful provision, this writes the bearer to the predictable path
pmoves/..env.local.provision.tmp; because its basename begins with two dots, it does not match the damage-control patterns.env.*or.env*.local. A concurrent agent running under the operator's OS account can therefore poll/read this unprotected path while it contains the token, despite.env.localitself being zero-access. Use a unique temporary name such as.env.local.tmp-*that remains covered by the zero-access patterns.AGENTS.md reference: AGENTS.md:L38-L38
Useful? React with 👍 / 👎.