Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions pmoves/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -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=<one> 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,)
Expand Down
1 change: 1 addition & 0 deletions pmoves/docs/AGENTS/AGNOTE4482PHI.t1.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <internal-error> 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=<card id>: mint a per-agent cipher token with --emit fd and upsert CIPHER_TOKEN_<AGENT> 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.
179 changes: 179 additions & 0 deletions pmoves/scripts/cipher_token_provision.py
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))
Comment on lines +94 to +98

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep the temporary credential under the zero-access glob

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.local itself 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 👍 / 👎.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Accept every valid signing-card identifier

When provisioning the active coder_claw card declared in pmoves/config/signing_identity_cards.yaml, this regex rejects the identifier before the real minter can apply its card gate. The target advertises AGENT=<card id>, so this valid identity can never receive a token and remains on bootstrap authentication; validate against the card roster or permit the underscore already used by card identifiers.

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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Revoke a minted token when the local bind fails

If .env.local cannot be created or replaced—for example because of permissions, a full filesystem, or an os.replace failure—the Supabase insert has already succeeded, but this uncaught upsert exception leaves a live credential with no local binding. Because has_key remains false, retrying provisions another live token, defeating the duplicate-token protection; catch binding failures and revoke the newly minted UUID before returning an error.

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())
113 changes: 113 additions & 0 deletions pmoves/tests/tools/test_cipher_token_provision.py
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
Loading