From ebf961d1325b353c093126f06124f6bdb4e6965e Mon Sep 17 00:00:00 2001 From: Alex Ivantsov Date: Wed, 18 Nov 2026 04:17:35 -0500 Subject: [PATCH] feat(harness): key-safe client, caller-bound waiter, fallback flag Port from the private harness, 2026-11-18 pass: mcp-http-call.py redacts every key form before it clips server text; await-approval gains opt-in terminal refusals and per-kind key connectors; a model-fallback Stop hook; the briefing's effort line follows Claude Code's resolution order; suites that cannot run exit 77; resume text verifies DO NOT and HOLD lines; remote-session pane targets use =NAME:. Second-vendor review applied. --- .claude-config/bin/README.md | 81 +++- .claude-config/bin/await-approval | 355 ++++++++++++-- .claude-config/bin/mcp-http-call.py | 216 ++++++++- .../bin/tests/await-approval-test.py | 442 +++++++++++++++++- .../bin/tests/guard-selftest-test.sh | 5 +- .../bin/tests/mcp-http-call-test.sh | 278 ++++++++++- .../bin/tests/post-compact-resume-test.sh | 15 + .../bin/tests/remote-claude-targets-test.sh | 161 +++++++ .../bin/tests/remote-claude-tmux-test.sh | 115 +++++ .claude-config/bin/tests/safe-pkill-test.sh | 4 +- .../bin/tests/session-briefing-effort-test.sh | 329 +++++++++++++ .../hooks/askuser-cancel-selftest.sh | 5 +- .../hooks/context-watch-selftest.sh | 11 +- .../hooks/model-fallback-watch-selftest.sh | 366 +++++++++++++++ .claude-config/hooks/model-fallback-watch.py | 374 +++++++++++++++ .claude-config/hooks/model-fallback-watch.sh | 37 ++ .claude-config/hooks/post-compact-resume.sh | 9 +- .claude-config/hooks/report-lint-selftest.sh | 5 +- .claude-config/hooks/session-briefing.sh | 99 +++- .claude-config/remote-sessions/README.md | 13 +- .../remote-sessions/lib-remote-claude.sh | 40 +- .../remote-sessions/new-remote-claude.sh | 2 +- CHANGELOG.md | 35 ++ CONTEXT/model-roles.md | 2 +- DEPLOYMENT.md | 2 +- README.md | 2 +- 26 files changed, 2900 insertions(+), 103 deletions(-) create mode 100755 .claude-config/bin/tests/remote-claude-targets-test.sh create mode 100755 .claude-config/bin/tests/remote-claude-tmux-test.sh create mode 100755 .claude-config/bin/tests/session-briefing-effort-test.sh create mode 100755 .claude-config/hooks/model-fallback-watch-selftest.sh create mode 100755 .claude-config/hooks/model-fallback-watch.py create mode 100755 .claude-config/hooks/model-fallback-watch.sh diff --git a/.claude-config/bin/README.md b/.claude-config/bin/README.md index b6198b2..2041343 100644 --- a/.claude-config/bin/README.md +++ b/.claude-config/bin/README.md @@ -529,9 +529,9 @@ which cwds get a pool), `tests/memory-host-key-rule-test.sh` and `tests/memory-hint-test.sh`; `tests/memory-digest-test.sh` also drives `hooks/memory-digest.sh`. -## `memory-hint.sh`, `report-lint.sh`, `askuser-cancel.sh`, `foreman-context.sh`: prompt, stop and boot hooks +## `memory-hint.sh`, `report-lint.sh`, `askuser-cancel.sh`, `model-fallback-watch.sh`, `foreman-context.sh`: prompt, stop and boot hooks -Four fail-open hooks (exit 0 always, nothing printed when there is nothing to +Five fail-open hooks (exit 0 always, nothing printed when there is nothing to say, an interpreter or a crash never reaches the session). The Stage-1 settings register each one behind a `test -x` guard, so it runs once this checkout ships it; `deploy.sh` never writes `~/.claude/settings.json`. Each @@ -566,6 +566,24 @@ header says which event. record it as declined; re-ask once or proceed on the stated default). The common case, nothing cancelled, costs a `grep` over the transcript tail and no Python. `ASKUSER_CANCEL=0` turns it off. Test: `hooks/askuser-cancel-selftest.sh`. +- `hooks/model-fallback-watch.sh` (Stop; the work is in `model-fallback-watch.py`): + when Claude Code answers a refused request on a fallback model, the only trace is a + `type:"system"` record in a transcript. The hook reads the session transcript and + every lane transcript under `//subagents/` (any depth), + records each new event once in `${OPS_STATE_DIR:-~/.local/state/ops}/model-fallbacks.tsv`, + and blocks the stop once so the agent tells the Operator which work ran on the + fallback model and re-verifies it. It never blocks a continuation stop + (`stop_hook_active`). If the ledger lock (5 s) or the write fails it still blocks, + says so, and keeps its read offsets, so the flag repeats until the state directory + is fixed. Read offsets track the file identity and sample bytes at the start + and before the offset, so a replacement or a detected in-place rewrite + starts at byte zero. + The locked writer recovers an unfinished ledger row on retry. State files are + 0600 and the directories it creates 0700. + `model_refusal_fallback` was seen on real installations; `model_fallback` and + `model_consent_fallback` are unverified. Without `fcntl` (Windows) the ledger is + written unlocked; with no Python 3 the hook is silent. `MODEL_FALLBACK_WATCH=0` + turns it off. Test: `hooks/model-fallback-watch-selftest.sh`. - `hooks/foreman-context.sh` (SessionStart): prints `CONTEXT/foreman.md`, the doctrine that binds the main thread only, into a foreman session, so `core.md` carries only what binds everyone (every session and every subagent pays for @@ -654,15 +672,33 @@ body. Tool suffixes match only at the namespace boundary (`invoice_query` finds with an HTTP DELETE in a `finally`, also on SIGTERM and SIGHUP (only SIGKILL skips it): a server counts live sessions per key and reaps an idle one only after a timeout, so a client that opens a session per call and never closes it -leaks one per call until the cap refuses every new session. Server text printed -on an error has the key scrubbed, and every out file is written 0600 (results -can carry secrets). Writes: pass an idempotency key where the tool takes one, -and never re-run a call that timed out; read back instead. Test: -`tests/mcp-http-call-test.sh`. - -`await-approval [--kind NAME] [--timeout SEC]` is the waiter for an approval clicked out of band (a remote session, a write grant, a deploy gate) on a host with no webhook callback: it long-polls a status tool through `mcp-http-call.py` and prints one state line, so run it with `run_in_background` and an explicit Bash timeout of at least 1900000 ms and its exit wakes the idle thread with no typed "Approved". Exit codes, all of them: 0 approved (the request is OPEN, and for a kind with a `usable_field`, usable by this caller); 3 not approved and never will be, with `state=` naming why: `denied` (the approver pressed Deny: status CLOSED with reason denied, or a bare DENIED status), `expired` (the pending window ran out), `closed` (any other close), or `not_usable` (the request is OPEN but another caller made it, so acting on it would be refused); 124 the timeout (default 1860 s, a 1800 s pending window plus margin) passed with the request still PENDING; 2 an error (bad usage or configuration, no caller, no API key, a refused key, an id the server does not know, an unreadable answer, five transient failures in a row); 128+N the waiter was stopped by signal N before an answer (`state=interrupted`: 143 SIGTERM, 130 SIGINT, 129 SIGHUP). The script header carries the same table, the on-exit guidance, the status contract the tool must answer and what a box needs. - -Which server, tool and arguments are configuration, in `$AWAIT_APPROVAL_CONFIG` or `~/.config/ops/await-approval.json` (an explicit path that is missing is an error; the default path may be absent). Each named kind sets `server` (an endpoint name for `--server`, or `null` for `OPS_MCP_URL`), `tool`, `args` (the string `"{id}"` becomes the id and `"{wait}"` the wait in whole seconds), an optional `record` (the answer key that holds the status record) and an optional `usable_field` (the answer key that says whether this caller may use an OPEN request); `default_kind` picks the kind when `--kind` is not given, and `key_connectors` names `mcpServers` entries of `~/.claude.json` whose literal `Bearer ` header is the last-resort key (a `${VAR}` reference is not a key; the key reaches the poll through its environment only, never argv or a file). With no file, the built-in kind `default` calls `approval_status` with `{"id": , "wait_s": }` on `OPS_MCP_URL`. The tool answers `status` PENDING, OPEN, CLOSED or EXPIRED, an optional `close_reason`, and holds the call until the request changes or about 40 s pass, so a click ends the wait at once; a poll that returns early with PENDING is paced to at least 3 s. Each poll is one run of `mcp-http-call.py`, so at most one session per waiter is live, and SIGTERM, SIGINT and SIGHUP reach the poll in flight so its session still closes. A transient failure (a 5xx, a 429, a dropped connection, an `isError` answer) is retried up to 5 times in a row; a refused key, an unknown endpoint or tool, a missing configuration and any in-band `error` answer stop at once, and the HTTP status is read where the client puts it, in the first `ERROR: ` line, never in the quoted response body. The line prints only the first 8 characters of the id, never an approve URL, and every key value and bearer token is scrubbed from server text. Tests: `tests/await-approval-test.py` (against a stub of the caller, 100+ cases including each signal, every exit code and the header and this section agreeing). +leaks one per call until the cap refuses every new session. Server text the +client shows (an error body, a tool answer, the `call` preview, the `list` +output) has every form of the key redacted first, raw and JSON-escaped, then +each line break escaped so it stays on one line, and only then is clipped: +clipping first would leave the start of a key that straddles the cut, and a +line break in a body could start a line that reads as the client's own note. +Every out file is written 0600 and keeps the full result (results can carry +secrets). `OPS_MCP_REFUSAL_CODES` (comma-separated codes; `await-approval` +passes its `terminal_refusals`) makes `call`, and `batch` on the call that stops +it, add exactly one stderr line, `NOTE: the gateway answered : ...`, when +an answer carries one of those codes in a structured field such as `error`, +`code` or `error_code` on the tool wrapper, the answer or its `error` or +`context` object (outer fields first), an `isError` result's structured and +JSON text content, or a JSON-RPC error and its `data`. The note names where the key came from +(`env:`, `dotenv:`, or the label in `OPS_MCP_KEY_SOURCE`), its +last four characters when it has 16 or more, and the connector +(`OPS_MCP_CONNECTOR`, else `unknown`), never the key. The waiter reads the +provenance captured by the client when it loaded the credential, including +when the dotenv file changes during a poll. Free text never makes a +note, exit codes and out files are unchanged, and a malformed value of any of +the three variables is refused before any request. Writes: pass an idempotency +key where the tool takes one, and never re-run a call that timed out; read back +instead. Test: `tests/mcp-http-call-test.sh`. + +`await-approval [--kind NAME] [--timeout SEC]` is the waiter for an approval clicked out of band (a remote session, a write grant, a deploy gate) on a host with no webhook callback: it long-polls a status tool through `mcp-http-call.py` and prints one state line, so run it with `run_in_background` and an explicit Bash timeout of at least 1900000 ms and its exit wakes the idle thread with no typed "Approved". Exit codes, all of them: 0 approved (the request is OPEN, and for a kind with a `usable_field`, usable by this caller); 3 not approved and never will be, with `state=` naming why: `denied` (the approver pressed Deny: status CLOSED with reason denied, or a bare DENIED status), `expired` (the pending window ran out), `closed` (any other close), or `not_usable` (the request is OPEN but another caller made it, so acting on it would be refused); 124 the timeout (default 1860 s, a 1800 s pending window plus margin) passed with the request still PENDING; 2 an error (bad usage or configuration, no caller, no API key, a refused key, an id the server does not know, an unreadable answer, five transient failures in a row), which with `terminal_refusals` configured includes a terminal refusal: an answer that refuses this caller (its key is not the credential that made the request, or the server found no usable identity for it) ends the wait on that first answer with the code as the state (`state=not_requester`, for example) and names `connector=`, `key_source=` (`env:`, `dotenv:` or `claude.json:`) and at most the key's last four characters (`key_tail=`); nothing was decided and the request may still be pending, so re-run the waiter with the key the agent requested with, never another; 128+N the waiter was stopped by signal N before an answer (`state=interrupted`: 143 SIGTERM, 130 SIGINT, 129 SIGHUP). The script header carries the same table, the on-exit guidance, the status contract the tool must answer and what a box needs. + +Which server, tool and arguments are configuration, in `$AWAIT_APPROVAL_CONFIG` or `~/.config/ops/await-approval.json` (an explicit path that is missing is an error; the default path may be absent). Each named kind sets `server` (an endpoint name for `--server`, or `null` for `OPS_MCP_URL`), `tool`, `args` (the string `"{id}"` becomes the id and `"{wait}"` the wait in whole seconds), an optional `record` (the answer key that holds the status record) and an optional `usable_field` (the answer key that says whether this caller may use an OPEN request); an optional `key_connector` names the one `mcpServers` entry of `~/.claude.json` whose literal `Bearer ` header that kind may use as its last-resort key, so one kind never lends its key to another; `default_kind` picks the kind when `--kind` is not given, and `key_connectors` names the entries tried in order for a kind with no `key_connector` (a `${VAR}` reference is not a key; the fallback runs only when the poll reports no key, and the key reaches the poll through its environment only, never argv or a file, with `OPS_MCP_KEY_SOURCE=claude.json:` so the client's note names it). `terminal_refusals` is opt-in: omitted, `null` or `[]` keeps the ordinary classification, and a configured code (lowercase letters, digits and `_`, never one of the waiter's own states) ends the wait at once, read only from structured fields (`error`, `code` or `error_code`, the envelope before its `result`) or the client's one `NOTE:` line on a zero or non-zero exit, never from free text. The header's CONFIGURATION section shows a synthetic opt-in with `not_requester`, `requester_mismatch`, `identity_missing`, `identity_ambiguous` and `identity_invalid`; before turning it on in a copy, check each caller-bound kind's `key_connector` and the codes its server sends, and `"terminal_refusals": []` turns it off again. A malformed file is a usage error. With no file, the built-in kind `default` calls `approval_status` with `{"id": , "wait_s": }` on `OPS_MCP_URL`. The tool answers `status` PENDING, OPEN, CLOSED or EXPIRED, an optional `close_reason`, and holds the call until the request changes or about 40 s pass, so a click ends the wait at once; a poll that returns early with PENDING is paced to at least 3 s. Each poll is one run of `mcp-http-call.py`, so at most one session per waiter is live, and SIGTERM, SIGINT and SIGHUP reach the poll in flight so its session still closes. A transient failure (a 5xx, a 429, a dropped connection, an `isError` answer) is retried up to 5 times in a row; a refused key, an unknown endpoint or tool, a missing configuration and any in-band `error` answer stop at once, and the HTTP status is read where the client puts it, in the first `ERROR: ` line, never in the quoted response body. The line prints only the first 8 characters of the id, never an approve URL, and every key value and bearer token is scrubbed from server text. Tests: `tests/await-approval-test.py` (against a stub of the caller and, for refusals, the real client behind a scripted server; 200+ cases including each signal, every exit code and the header and this section agreeing). ## `t3-api.sh`, `compact-cycle.sh` and `lib/`: T3 Code self-compaction @@ -850,6 +886,10 @@ thread gets the foreman boot. So the rules ride in what fires. `post-compact-resume.sh` prints them most-recently-used first and says to select lazily (one name, just before its first call). `tests/pre-compact-test.sh` pins the snapshot section and `tests/post-compact-resume-test.sh` the block. + The resume text also asks the agent to verify a DO NOT or HOLD line in the + snapshot against the operator message or doctrine it cites (or, when it cites + none, the operator's newest direction) before treating it as settled; standing + instructions and real operator holds still apply. - The lane gate in the hooks that talk: `context-watch.sh` stays silent on Stop and in its readout for a lane, and gives a T3 lane its own 60% and 80% @@ -872,6 +912,15 @@ thread gets the foreman boot. So the rules ride in what fires. one line, control characters stripped, 400 characters at most. This hook has no resume short form, so a resume or compact prints it with the rest of the briefing. The matching ruling for the thread such an ask opens is in `CONTEXT/standing-orders.md`. +- The briefing's `effort` (`session-briefing.sh`) is resolved in Claude Code's own + order (the env `CLAUDE_CODE_EFFORT_LEVEL`, the launch `--effort`, the saved + `modelSettings..effortLevel` in the active profile, the model default) and + labelled with its source. On Linux the launch flag is read from the nearest + ancestor process named `claude` (at most 16 parents; only a short alphanumeric + `--effort` value is kept; nothing else on that command line is stored or printed); + elsewhere, or on any read error, the saved level is shown, labelled an estimate when + SessionStart omitted the model. An invalid value is reported, never echoed. Test + seam: `BRIEFING_PROC_ROOT`. Test: `tests/session-briefing-effort-test.sh`. - Per-thread work keys and the leftover-stamp scan (`hooks/hooklib.sh`): under T3 Code the work key is `t3-`, stable across compaction and resume, so two threads in one directory keep separate stamps and work logs. @@ -886,7 +935,7 @@ thread gets the foreman boot. So the rules ride in what fires. Tests: `tests/lane-class-test.sh`, `tests/await-test.sh`, `tests/safe-pkill-test.sh`, `tests/lane-rules-test.sh`, `tests/session-briefing-lane-test.sh`, `tests/session-briefing-scope-test.sh`, `tests/session-briefing-team-ask-test.sh`, -`tests/work-session-key-test.sh`, +`tests/session-briefing-effort-test.sh`, `tests/work-session-key-test.sh`, `tests/orphan-gate-test.sh`, `hooks/context-watch-selftest.sh`, `hooks/foreman-context-selftest.sh` and `tests/post-compact-resume-test.sh`. @@ -904,6 +953,14 @@ exits non-zero if any fails, is step 2 of "Before you open the PR" in `CONTRIBUTING.md`; CI runs the same loops (`.github/workflows/gate.yml`). One file, one command: no second copy here to drift. +A whole-suite skip for a missing prerequisite (Python 3, jq, procps, tmux) +prints `: did not run: ` and exits 77. CI and the contributing +loop fail on that exit. Skips of single cases inside a suite stay explicit. +`tests/remote-claude-targets-test.sh` pins the tmux targets of the +remote-session scripts offline; `tests/remote-claude-tmux-test.sh` proves a +launch line reaches the exact pane on a real tmux server, on a private `-L` +socket that only it starts and stops. + `tests/ci-gate-test.py` runs the gate's JavaScript check over every tracked `.js` and a set of fixtures. Under `sandbox-run` it skips when `node` lives in your HOME (nvm, fnm), which the sandbox hides, and says so; run it bare then. diff --git a/.claude-config/bin/await-approval b/.claude-config/bin/await-approval index 77c433a..76875da 100755 --- a/.claude-config/bin/await-approval +++ b/.claude-config/bin/await-approval @@ -31,7 +31,12 @@ Every exit code the waiter can return: 124 timeout: --timeout passed with the request still PENDING (state=timeout) 2 error: bad usage or configuration, no caller, no API key, the server refused the key, the id is unknown to the server, an answer this script cannot read, or the - server kept failing + server kept failing. Also a terminal refusal, when the configuration opts in + (terminal_refusals, below): the server answered that it refuses THIS caller (its + credential is not the one that made the request, or it has no usable identity), + which no wait can change. It ends the waiter on that first answer with the code + as the state (state=, e.g. state=not_requester); nothing was decided and the + request may still be PENDING 128+N stopped by signal N before the server answered (state=interrupted): 143 SIGTERM (the host stopping a background task), 130 SIGINT, 129 SIGHUP; nothing was decided @@ -41,6 +46,7 @@ Every exit code the waiter can return: await-approval: grant 8c1d44e0 state=open exit=0 waited=41s usable=yes await-approval: grant 8c1d44e0 state=not_usable exit=3 waited=41s usable=no reason=requested_by_another_caller await-approval: session 3f2a91bc state=error exit=2 waited=1s detail="not_found: No such session..." + await-approval: session 3f2a91bc state=not_requester exit=2 waited=1s connector=approvals key_source=env:OPS_MCP_API_KEY key_tail=ab12 detail="..." HOW to run it from an agent: - request every approval the task needs first, post the approve links as the last @@ -54,9 +60,16 @@ HOW to run it from an agent: session (or check that the waiter's key is this session's key). On exit 124 re-run the waiter only if the server says the request is still PENDING. On exit 128+N the waiter was stopped and nothing was decided: re-run it if the request is still PENDING. On exit 2 - report the line. After exit 0, make the real call the approval was for. + report the line, except for a terminal refusal state (a configured code): the waiter's + key is not the credential that made the request, so re-run it with the key the agent + requested with (see "Which key"), never with another key you pick. After exit 0, make + the real call the approval was for. - the id may itself be the credential for the follow-up call, so the line prints only its - first 8 characters, never an approve URL, and never a key. + first 8 characters, never an approve URL, and never a key. A terminal refusal line names + the connector (connector=, "unknown" when none is configured), where the waiter's key + came from (key_source=env:, dotenv: or claude.json:) and at most + its last four characters (key_tail=, only for a key of 16 characters or more), so it can + be compared with the key behind the agent's connector. THE STATUS CONTRACT the tool must answer (a flat JSON object, or the same object under the kind's "record" key), whatever the server: @@ -69,10 +82,19 @@ An answer with an "error" key is an error (exit 2). The tool should hold the cal request changes state or about wait_s seconds pass, so the call returns the moment the approver clicks; a tool that answers PENDING at once is paced, never hammered. +A terminal refusal (only for the codes terminal_refusals names) is read from structured +fields only: error, code or error_code on the answer or on its "error" or "context" object, +the envelope before its "result" (so a refusal around or beside an OPEN record is still a +refusal), or the one line mcp-http-call.py prints for it, "NOTE: the gateway answered +: ...", on a zero or non-zero exit, read before any status is accepted. Free text (a +message, quoted command output, an HTTP error body) never counts: the client keeps all +server text on one line, so only it can start that line, and two such lines count as none. + CONFIGURATION. A JSON file, $AWAIT_APPROVAL_CONFIG or ~/.config/ops/await-approval.json (an explicit AWAIT_APPROVAL_CONFIG that does not exist is an error; the default file may be absent). Without one the built-in kind "default" applies: tool approval_status, arguments -{"id": , "wait_s": }, a flat record, on the endpoint OPS_MCP_URL names. +{"id": , "wait_s": }, a flat record, on the endpoint OPS_MCP_URL names. A file +that cannot be read or breaks a rule below is a usage error (exit 2, no poll). { "default_kind": "session", @@ -93,8 +115,37 @@ absent). Without one the built-in kind "default" applies: tool approval_status, whole seconds (an integer); every other value is passed as written record the key of the status record inside the answer, or null for the answer itself usable_field the answer key that says whether this caller may use an OPEN request, or null + key_connector the one mcpServers entry of ~/.claude.json whose literal key this kind may + use (the connector the agent requests this kind through), or null. A kind + that sets it reads that entry and no other, so one kind never lends its key + to another; it is also the connector a terminal refusal line names key_connectors names of mcpServers entries in ~/.claude.json whose literal "Bearer " - header is the last-resort key (see below); default none + header is the last-resort key for a kind with no key_connector (see below); + default none. The entry it selects is the connector a refusal line names + terminal_refusals the refusal codes that end the wait at once (exit 2, state=). + Default none: omitted, null or [] keeps the ordinary classification above, + and an in-band one stays an ordinary error. Each code is lowercase letters, + digits and "_" and may not be a state of the waiter's own (open, pending, + expired, closed, denied, not_usable, timeout, interrupted, error). The waiter + passes them to mcp-http-call.py (OPS_MCP_REFUSAL_CODES) so its note follows + the same list. A connector name is one printable line of at most 100 + characters. + +To opt in, a copy that polls a server which binds each request to the credential that made +it adds the codes that server answers and gives each caller-bound kind its connector, e.g.: + + { + "terminal_refusals": ["not_requester", "requester_mismatch", "identity_missing", + "identity_ambiguous", "identity_invalid"], + "kinds": { + "session": {"server": "approvals", "tool": "session_status", "key_connector": "approvals", + "args": {"session_id": "{id}", "wait_s": "{wait}"}} + } + } + + (the five codes are an example: not_requester and requester_mismatch say the credential is + not the requester's, the identity_* codes that the server found no usable identity for it). + "terminal_refusals": [] turns the behavior off again. HOW it polls: one run of mcp-http-call.py per poll (`[--server S] call TOOL args out`), wait_s at most 40 (the usual cap on one held call), shorter on the last poll before the deadline. A @@ -114,13 +165,19 @@ WHAT a box needs: 2. The MCP endpoint: OPS_MCP_URL, or OPS_MCP_URL_TEMPLATE plus a kind's "server" name. 3. The API key, read the way mcp-http-call.py reads it: OPS_MCP_API_KEY in the environment (or the variable OPS_MCP_KEY_VAR names), else that line of $OPS_DIR/.env (default - ~/OPS/.env). When the poll reports no key, this script tries the literal "Bearer " - header of the key_connectors entries in ~/.claude.json and gives the key to the poll - through the poll's environment only (never argv, never a file, never printed). A - ${VAR} reference in the entry is not a key and is skipped. + ~/OPS/.env). When the poll reports no key (and only then), this script tries the + literal "Bearer " header of the kind's key_connector entry in ~/.claude.json, or + for a kind without one the key_connectors entries in order, and gives the key to the + poll through the poll's environment only (never argv, never a file, never printed), + with its source (OPS_MCP_KEY_SOURCE=claude.json:) so the client's note names it. + A ${VAR} reference in the entry is not a key and is skipped. 4. Outbound HTTPS to the endpoint. Nothing listens; no inbound URL is needed. - The key must be the same person's key the agent session uses where the server binds a - request to its requester: usable=no means the waiter's key is not the requester's. + +Which key. Where the server binds a request to the credential that made it, the waiter +must poll with the SAME key the agent requested with, not another key of the same person: +usable=no, or a terminal refusal state, means the waiter's key is not the requester's. A +refused poll is never retried with another key, and an agent whose credential is not an API +key (an OAuth login) reads the status itself through that login. Test-only environment (tests/await-approval-test.py): AWAIT_APPROVAL_MCP_CALL names a stub for mcp-http-call.py; AWAIT_APPROVAL_PACE_S replaces the 3 s pacing and the retry pause @@ -153,15 +210,33 @@ ID_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.:-]{3,127}") KIND_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_-]{0,31}") SERVER_RE = re.compile(r"[a-z0-9][a-z0-9-]{0,40}") -# The kind a copy gets when it configures nothing: a neutral shape, no server name. +# The kind a copy gets when it configures nothing: a neutral shape, no server name, and no +# terminal refusals (they are opt-in: a code means something only to the server that sends it). DEFAULT_CONFIG = { "default_kind": "default", "key_connectors": [], + "terminal_refusals": frozenset(), "kinds": { "default": {"server": None, "tool": "approval_status", "args": {"id": "{id}", "wait_s": "{wait}"}, - "record": None, "usable_field": None}, + "record": None, "usable_field": None, "key_connector": None}, }, } +# A terminal refusal code, as configured and as mcp-http-call.py checks OPS_MCP_REFUSAL_CODES. +CODE_RE = re.compile(r"[a-z][a-z0-9_]{0,63}") +# The waiter's own states. A configured code may not reuse one: state= must never read +# as a result the agent acts on (open) or as any other outcome the guidance treats differently. +RESERVED_STATES = frozenset({"open", "pending", "expired", "closed", "denied", "not_usable", "timeout", + "interrupted", "error"}) +# The line mcp-http-call.py prints, on its own, for a configured refusal code. It keeps every +# piece of server text on one line, so no server text can start this line. +NOTE_RE = re.compile(r"NOTE: the gateway answered ([a-z][a-z0-9_]{0,63}):(?: |$)") +# A key is named by its source and, only when it is long enough that four characters give +# little away, its last four characters. Never more. +MIN_TAIL_KEY_LEN = 16 +REFUSAL_DETAIL_LIMIT = 600 # the refusal guidance is longer than the usual 240-character detail +# A connector name's length limit. WHY 100: the poll gets "claude.json:" as its key-source +# label, and mcp-http-call.py refuses a label longer than 200 characters. +CONNECTOR_MAX = 100 # The caller prints "ERROR: " and the message may carry up to 800 characters of server # text (a response body, a tool answer) that quotes anything at all. So every marker below is @@ -220,12 +295,28 @@ def _on_signal(signum, frame): pass +def key_forms(key): + """Match the client's raw and JSON-escaped forms in its unredacted out file.""" + forms, level = {key}, {key} + for _ in range(2): + escaped = set() + for form in level: + for ascii_only in (True, False): + quoted = json.dumps(form, ensure_ascii=ascii_only)[1:-1] + escaped.update((quoted, quoted.replace("/", "\\/"))) + forms |= escaped + level = escaped + return sorted(forms, key=len, reverse=True) + + def scrub(text, limit=240, ident=""): """One line, with every key value and any bearer token removed, cut to `limit`.""" text = str(text) for secret in _secrets + [ident]: - if secret: - text = text.replace(secret, "") + normalized = (secret or "").strip() + if normalized: + for form in key_forms(normalized): + text = text.replace(form, "") text = re.sub(r"(?i)bearer\s+[A-Za-z0-9._~+/=-]{8,}", "Bearer ", text) # An approval URL can carry a different credential from the request id. # No server-supplied URL belongs in the waiter's result notification. @@ -243,6 +334,7 @@ def finish(code, state, kind, ident, started, **extra): parts = [PROG + ":", kind, short(ident), "state=%s" % state, "exit=%d" % code, "waited=%ds" % round(time.monotonic() - started)] detail = extra.pop("detail", None) + limit = extra.pop("detail_limit", 240) for key, value in extra.items(): if value not in (None, ""): value = scrub(value, ident=ident) @@ -250,7 +342,7 @@ def finish(code, state, kind, ident, started, **extra): value = '"%s"' % value parts.append("%s=%s" % (key, value)) if detail: - parts.append('detail="%s"' % scrub(detail, ident=ident)) + parts.append('detail="%s"' % scrub(detail, limit, ident=ident)) print(" ".join(parts)) sys.stdout.flush() return code @@ -299,8 +391,34 @@ def check_kind(name, kind, where): value = kind.get(field) if value is not None and (not isinstance(value, str) or not value): raise ConfigError("%s: kind %s \"%s\" is not a key name or null" % (where, name, field)) + connector = kind.get("key_connector") + if connector is not None and not is_label(connector, CONNECTOR_MAX): + raise ConfigError("%s: kind %s \"key_connector\" is not a connector name (one printable line of at " + "most %d characters) or null" % (where, name, CONNECTOR_MAX)) return {"server": server, "tool": tool, "args": args, "record": kind.get("record"), - "usable_field": kind.get("usable_field")} + "usable_field": kind.get("usable_field"), "key_connector": connector} + + +def is_label(value, limit=200): + """A connector name or key-source label: one printable line of at most `limit` characters + (mcp-http-call.py applies the same rule, at 200, to OPS_MCP_CONNECTOR and OPS_MCP_KEY_SOURCE).""" + return isinstance(value, str) and 0 < len(value) <= limit and value.isprintable() and value.strip() == value + + +def check_refusals(raw, where): + """The validated terminal_refusals: omitted, null or [] is none (today's classification).""" + codes = raw.get("terminal_refusals") + if codes is None: + return frozenset() + if not isinstance(codes, list): + raise ConfigError("%s: terminal_refusals is not a list of codes" % where) + for code in codes: + if not isinstance(code, str) or not CODE_RE.fullmatch(code): + raise ConfigError("%s: terminal_refusals has %r, which is not a code (lowercase letters, digits " + "and '_', starting with a letter)" % (where, code)) + if code in RESERVED_STATES: + raise ConfigError("%s: terminal_refusals has %r, a state of the waiter's own" % (where, code)) + return frozenset(codes) def load_config(): @@ -327,7 +445,11 @@ def load_config(): connectors = raw.get("key_connectors", []) if not isinstance(connectors, list) or not all(isinstance(c, str) for c in connectors): raise ConfigError("%s: key_connectors is not a list of names" % path) - return {"default_kind": default, "key_connectors": connectors, "kinds": kinds} + if not all(is_label(c, CONNECTOR_MAX) for c in connectors): + raise ConfigError("%s: key_connectors has a name that is not one printable line of at most %d " + "characters" % (path, CONNECTOR_MAX)) + return {"default_kind": default, "key_connectors": connectors, "kinds": kinds, + "terminal_refusals": check_refusals(raw, path)} def find_caller(): @@ -340,21 +462,22 @@ def find_caller(): def claude_json_key(connectors): - """A literal API key from a user-scope mcpServers entry of ~/.claude.json, or None. + """(key, entry name) for the first literal API key among the named user-scope mcpServers + entries of ~/.claude.json, or (None, None). The last resort for a box whose key is in no environment and no .env. Only the entries - the configuration names count, and only a literal "Bearer "; a ${VAR} reference is - not a key. + the caller passes count (a kind's own key_connector, or the legacy key_connectors list), + and only a literal "Bearer "; a ${VAR} reference is not a key. """ if not connectors: - return None + return None, None try: with open(os.path.expanduser("~/.claude.json")) as fh: servers = json.load(fh).get("mcpServers") or {} except (OSError, ValueError, AttributeError): - return None + return None, None if not isinstance(servers, dict): - return None + return None, None for name in connectors: entry = servers.get(name) headers = entry.get("headers") if isinstance(entry, dict) else None @@ -363,8 +486,40 @@ def claude_json_key(connectors): continue match = re.fullmatch(r"Bearer\s+([A-Za-z0-9._~+/=-]{16,})", auth.strip()) if match: - return match.group(1) - return None + return match.group(1), name + return None, None + + +def key_tail(key): + """The last four characters of a key long enough that they give little away, else None.""" + return key[-4:] if len(key) >= MIN_TAIL_KEY_LEN else None + + +def key_origin(env): + """(source, tail) of the key mcp-http-call.py resolves from env, by its own lookup: the + variable ("env:"), else the first matching line of $OPS_DIR/.env or ~/OPS/.env + ("dotenv:"); (None, None) when neither has one. Never the key itself. + + Fallback for an answer with just a structured refusal and no client provenance. + Tests pin this lookup to mcp-http-call.py api_key(). + """ + var = env.get("OPS_MCP_KEY_VAR") or "OPS_MCP_API_KEY" + key = env.get(var) + source = "env:%s" % var + if not key: + path = os.path.join(env.get("OPS_DIR") or os.path.expanduser("~/OPS"), ".env") + source = "dotenv:%s" % path + try: + with open(path) as fh: + for line in fh: + match = re.fullmatch(r"(?:export\s+)?%s=(.*)" % re.escape(var), line.strip()) + if match: + key = match.group(1).strip().strip('"').strip("'") + break + except OSError: + return None, None + key = (key or "").strip() + return (source, key_tail(key)) if key else (None, None) def dotenv_keys(): @@ -394,12 +549,15 @@ def dotenv_keys(): class Poll: """The outcome of one run of the caller: a payload, or why it failed.""" - def __init__(self, payload=None, err="", fatal=False, transient=True, no_key=False): + def __init__(self, payload=None, err="", fatal=False, transient=True, no_key=False, + refusal=None, refusal_origin=None): self.payload = payload self.err = err self.fatal = fatal self.transient = transient self.no_key = no_key + self.refusal = refusal # a configured terminal refusal code, or None + self.refusal_origin = refusal_origin @property def failed(self): @@ -432,6 +590,71 @@ def classify_failure(stderr): return Poll(err=text or "no output from the caller") +def note_refusal(stderr, codes): + """The code and optional key provenance from the caller's one refusal NOTE line. + + Only a whole line counts, and only when exactly one such line is there: the caller prints + one per refusal and keeps all server text on a single line, so a second line, a code that + is not configured or a note inside other text is not the caller speaking. + """ + if not codes: + return None, None + matches = [m for m in (NOTE_RE.match(line) for line in (stderr or "").splitlines()) if m] + if len(matches) != 1 or matches[0][1] not in codes: + return None, None + note = matches[0] + code = note[1] + _, sep, encoded = note.string.rpartition("\t") + if not sep: + return code, None + try: + origin = json.loads(encoded) + except (ValueError, RecursionError): + return code, None + if isinstance(origin, dict): + source, tail = origin.get("key_source"), origin.get("key_tail") + if isinstance(source, str) and (tail is None or isinstance(tail, str) and len(tail) == 4): + return code, (source, tail) + return code, None + + +def refusal_state(payload, codes): + """The configured terminal refusal code a status answer carries, or None. + + Reads only structured fields (error, code and error_code, on the answer and on its "error" + and "context" objects), the envelope first and then its "result", the same rule + mcp-http-call.py applies for its note. Free text is never read, so command output that + quotes a code cannot end the wait. + """ + if not codes: + return None + layers = [payload] + if isinstance(payload.get("result"), dict): + layers.append(payload["result"]) + for layer in layers: + for holder in (layer, layer.get("error"), layer.get("context")): + if not isinstance(holder, dict): + continue + for field in ("error", "code", "error_code"): + value = holder.get(field) + if isinstance(value, str) and value in codes: + return value + return None + + +def refusal_detail(code, connector, source, tail): + """What a terminal refusal means and what to do, value-free: it names the connector and + where the waiter's key came from, at most its last four characters, never a key, and never + offers another key.""" + used = ("the key from %s%s" % (source, " (ends %s)" % tail if tail else "")) if source else "its key" + through = ("the %s connector" % connector) if connector else "the connector the agent requested through" + return ("the server answered %s: it refuses this caller, which waiting cannot change. Nothing was decided " + "and the request may still be pending. This waiter used %s. Poll with the credential that made the " + "request: export %s with the key the agent used through %s and run the waiter again, or read the " + "status through that connector or login yourself. Do not try other keys: another key is another " + "caller." % (code, used, key_var(), through)) + + def fill_args(template, ident, wait): """The kind's args with "{id}" and "{wait}" replaced (the wait stays an integer).""" out = {} @@ -444,8 +667,9 @@ def fill_args(template, ident, wait): return out -def run_poll(runner, kind, spec, ident, wait_s, tmp, env, deadline): - """One long poll through the caller; the answer's JSON lands in tmp/out.json.""" +def run_poll(runner, kind, spec, ident, wait_s, tmp, env, deadline, codes=frozenset()): + """One long poll through the caller; the answer's JSON lands in tmp/out.json. The caller's + note of a terminal refusal is read first, on a zero or non-zero exit alike.""" args_path = os.path.join(tmp, "args.json") out_path = os.path.join(tmp, "out.json") try: @@ -469,10 +693,12 @@ def run_poll(runner, kind, spec, ident, wait_s, tmp, env, deadline): _child[0] = proc if STOP.is_set(): # a signal landed between the spawn and the hand-off above proc.terminate() + timed_out = False try: try: _out, err = proc.communicate(timeout=budget) except subprocess.TimeoutExpired: + timed_out = True # Terminate, not kill: SIGTERM lets the poll send its session DELETE. proc.terminate() try: @@ -480,9 +706,16 @@ def run_poll(runner, kind, spec, ident, wait_s, tmp, env, deadline): except subprocess.TimeoutExpired: proc.kill() _out, err = proc.communicate() - return Poll(err="poll timed out after %ds" % budget) finally: _child[0] = None + refusal, origin = note_refusal(err, codes) + if refusal: + # Before any status: a refused caller's answer says nothing about the request. + # The note can arrive before a stalled session DELETE during child cleanup. + return Poll(err=f"the server refused this caller: {refusal}", fatal=True, + refusal=refusal, refusal_origin=origin) + if timed_out: + return Poll(err=f"poll timed out after {int(budget)}s") if proc.returncode != 0: return classify_failure(err) try: @@ -495,9 +728,15 @@ def run_poll(runner, kind, spec, ident, wait_s, tmp, env, deadline): return Poll(payload=payload) -def interpret(spec, payload): +def interpret(spec, payload, codes=frozenset()): """Map a status answer to (state, info): state is pending, open, expired, closed, - denied, not_usable or error, and info carries the fields the result line prints.""" + denied, not_usable, error or a configured terminal refusal code, and info carries the + fields the result line prints.""" + # A terminal refusal on the envelope or its result outranks everything below, including an + # OPEN record beside or inside it: the answer is about this caller, not the request. + refusal = refusal_state(payload, codes) + if refusal: + return refusal, {} record_key = spec["record"] outer = payload if record_key is None and "status" not in payload and isinstance(payload.get("result"), dict): @@ -567,11 +806,38 @@ def wait_for_approval(args, config): # The poll may read its key from a file instead; know that value too so scrub() can # redact it from any text that reaches us unscrubbed (a traceback, a proxy page). _secrets.extend(dotenv_keys()) + codes = config.get("terminal_refusals") or frozenset() + connector = spec.get("key_connector") # the configured connector, or the entry the fallback selects + injected = None # "claude.json:" once this script hands the poll a key from that entry + # What the poll is told, and nothing inherited from this environment: the codes to note (the + # same validated list), the connector its note names, and (only after the fallback) the key's + # source, so the client's note and this line name the same key. + for name in ("OPS_MCP_REFUSAL_CODES", "OPS_MCP_CONNECTOR", "OPS_MCP_KEY_SOURCE"): + env.pop(name, None) + if codes: + env["OPS_MCP_REFUSAL_CODES"] = ",".join(sorted(codes)) + if connector: + env["OPS_MCP_CONNECTOR"] = connector tmp = tempfile.mkdtemp(prefix="await-approval-") # mode 0700 fails = retries = 0 key_fallback_tried = False last = "pending" pending_left = None + + def refusal_exit(code, origin=None): + """End the wait on a terminal refusal: one line, exit 2, no retry and no other key. The + line names the connector, where the refused key came from and at most its last four + characters.""" + if origin is not None: + source, tail = origin + elif injected: + source, tail = injected, key_tail(env.get(var, "")) + else: + source, tail = key_origin(env) + return finish(EXIT_ERROR, code, kind, ident, started, retries=retries or None, + connector=connector or "unknown", key_source=source, key_tail=tail, + detail=refusal_detail(code, connector, source, tail), detail_limit=REFUSAL_DETAIL_LIMIT) + try: while True: if STOP.is_set(): @@ -584,22 +850,33 @@ def wait_for_approval(args, config): # is an immediate read), so the timeout reports a fresh state, not a stale one. wait_s = int(min(MAX_WAIT_S, remaining)) began = time.monotonic() - poll = run_poll(runner, kind, spec, ident, wait_s, tmp, env, deadline) + poll = run_poll(runner, kind, spec, ident, wait_s, tmp, env, deadline, codes) if STOP.is_set(): return finish(128 + _stop_signal[0], "interrupted", kind, ident, started) + if poll.refusal: + return refusal_exit(poll.refusal, poll.refusal_origin) if poll.failed: if poll.no_key and not key_fallback_tried: key_fallback_tried = True - key = claude_json_key(config["key_connectors"]) + # A kind with its own connector reads that entry and no other: another + # entry's key is another credential, which a caller-bound request refuses. + names = [spec["key_connector"]] if spec.get("key_connector") else config["key_connectors"] + key, entry = claude_json_key(names) if key: env[var] = key _secrets.append(key) + connector, injected = entry, "claude.json:%s" % entry + env["OPS_MCP_CONNECTOR"], env["OPS_MCP_KEY_SOURCE"] = connector, injected continue if poll.no_key: + if spec.get("key_connector"): + where = ("or keep it as a literal Bearer key in the %s entry of ~/.claude.json " + "(this kind reads no other entry)" % spec["key_connector"]) + else: + where = ("(a box can also name a connector in key_connectors whose literal Bearer " + "entry in ~/.claude.json holds it)") return finish(EXIT_ERROR, "error", kind, ident, started, retries=retries or None, - detail="no API key: export %s, or put it in $OPS_DIR/.env (a box can " - "also name a connector in key_connectors whose literal Bearer " - "entry in ~/.claude.json holds it)" % var) + detail="no API key: export %s, or put it in $OPS_DIR/.env %s" % (var, where)) fails += 1 if poll.fatal or fails >= MAX_FAILS: return finish(EXIT_ERROR, "error", kind, ident, started, retries=retries or None, @@ -609,7 +886,9 @@ def wait_for_approval(args, config): STOP.wait(min(pause, max(0.0, deadline - time.monotonic()))) continue fails = 0 - state, info = interpret(spec, poll.payload) + state, info = interpret(spec, poll.payload, codes) + if state in codes: + return refusal_exit(state) if state == "open": return finish(EXIT_OK, "open", kind, ident, started, retries=retries or None, **info) if state in NOT_APPROVED_STATES: diff --git a/.claude-config/bin/mcp-http-call.py b/.claude-config/bin/mcp-http-call.py index 3f5dc77..db1251c 100755 --- a/.claude-config/bin/mcp-http-call.py +++ b/.claude-config/bin/mcp-http-call.py @@ -32,6 +32,30 @@ key, when it is not OPS_MCP_API_KEY. OPS_MCP_CLIENT_NAME clientInfo.name sent at initialize (default mcp-http-call); a server-side audit log groups calls by it. + OPS_MCP_REFUSAL_CODES comma-separated refusal codes ([a-z][a-z0-9_]*) that mean the + server refused THIS caller (bin/await-approval passes its + terminal_refusals here). Unset or empty: no notes, as before. + OPS_MCP_CONNECTOR the connector name a refusal note names (default "unknown"). + OPS_MCP_KEY_SOURCE the label a note gives a key that is in the environment + (default "env:"; bin/await-approval sets + "claude.json:" when it supplied the key). + A malformed value of the last three is refused before any request. + +Refusal notes: when an answer carries one of OPS_MCP_REFUSAL_CODES in a structured +field (error, code or error_code, on the answer or its "error" or "context" object; +the envelope is read before its "result"; for isError, the structured content and +each JSON text block; for a JSON-RPC error, the error and its data), `call` (and +`batch`, on the call that stops it) adds exactly one stderr line, "NOTE: the gateway +answered : ...", on a line of its own after any ERROR line, that +names where the key came from (env:, dotenv:, or the label above), +its last four characters when it is at least 16 long, and the connector; never the +key. Free text is never read for it. Exit codes and out files are unchanged. + +Server text this client shows (an error body, a tool answer, the call preview, the +list output) has every form of the key redacted first (raw and JSON-escaped), then +each line break escaped so it stays on one line, and only then is it clipped. WHY +the order: clipping first leaves the start of a key that straddles the cut, and a +line break in a body could start a line that reads as the client's own NOTE. Exit status: 0 ok, 1 any failure (a message on stderr starting "ERROR: "), 128+N when SIGTERM or SIGHUP stopped it. @@ -70,21 +94,91 @@ # The key, once read, so die() can scrub it from server text it prints (a 401 # body or a proxy error page can echo the Authorization header back). _SECRETS = [] +# Where the key came from (a label such as "env:OPS_MCP_API_KEY" or "dotenv:") +# and its last four characters when it is long enough that four give little away. +# api_key() captures both when it reads the credential. +KEY_ORIGIN = {"source": None, "tail": None} +MIN_TAIL_KEY_LEN = 16 +# The refusal codes that get a note (OPS_MCP_REFUSAL_CODES), set by refusal_settings(). +REFUSAL_CODES = frozenset() +CODE_RE = re.compile(r"[a-z][a-z0-9_]{0,63}") +NOTE_PREFIX = "NOTE: the gateway answered " +# Every character str.splitlines() breaks on. bin/await-approval splits this client's +# stderr into lines and trusts one that starts with NOTE_PREFIX, so server text must +# never contain one raw. +LINE_BREAKS = re.compile("[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]") + + +def _key_forms(secret): + """The secret as it can appear in text: raw, and JSON-escaped once and twice (a key + inside a JSON string, and a JSON text carried inside another JSON string), each also + with "/" escaped as some servers write it. Longest first, so no form is cut short.""" + forms, level = {secret}, {secret} + for _ in range(2): + escaped = set() + for form in level: + for ascii_only in (True, False): + quoted = json.dumps(form, ensure_ascii=ascii_only)[1:-1] + escaped.update((quoted, quoted.replace("/", "\\/"))) + forms |= escaped + level = escaped + return sorted(forms, key=len, reverse=True) def scrub(text): text = str(text) for s in _SECRETS: if s: - text = text.replace(s, "") + for form in _key_forms(s): + text = text.replace(form, "") return text -def die(msg): +def _escape_break(match): + char = match.group(0) + return {"\n": "\\n", "\r": "\\r"}.get(char) or "\\u%04x" % ord(char) + + +def shown(text, limit=None): + """Server text as this client may display it: every form of the key redacted, then + each line break escaped (so it stays on one line), then clipped to limit. + + The one place server text is clipped. WHY this order: clipping before redacting + leaves the start of a key that straddles the cut, and an escaped form of the key + is a different string from the key. The escapes are valid inside a JSON string, + so a JSON text stays valid JSON. + """ + text = LINE_BREAKS.sub(_escape_break, scrub(text)) + return text if limit is None else text[:limit] + + +def die(msg, code=None): print("ERROR: %s" % scrub(msg), file=sys.stderr) + print_refusal_note(code) sys.exit(1) +def is_label(value): + """A connector or key-source label: one printable line of at most 200 characters.""" + return isinstance(value, str) and 0 < len(value) <= 200 and value.isprintable() and value.strip() == value + + +def refusal_settings(): + """Read and check OPS_MCP_REFUSAL_CODES, OPS_MCP_CONNECTOR and OPS_MCP_KEY_SOURCE before + any request; a malformed value is refused (and not printed), never guessed at.""" + global REFUSAL_CODES + raw = os.environ.get("OPS_MCP_REFUSAL_CODES") or "" + codes = [c.strip() for c in raw.split(",") if c.strip()] + if not all(CODE_RE.fullmatch(c) for c in codes): + die("OPS_MCP_REFUSAL_CODES must be comma-separated codes of lowercase letters, digits and '_' " + "(the value is not printed)") + REFUSAL_CODES = frozenset(codes) + for var in ("OPS_MCP_CONNECTOR", "OPS_MCP_KEY_SOURCE"): + value = os.environ.get(var) + if value and not is_label(value): + die("%s must be one printable line of at most 200 characters (the value is not printed)" % var) + + class UnknownOutcome(SystemExit): """A dispatched call returned no trustworthy outcome; read back before retrying.""" @@ -96,7 +190,9 @@ def env_file(): def api_key(): k = os.environ.get(KEY_VAR) path = env_file() + source = os.environ.get("OPS_MCP_KEY_SOURCE") or "env:%s" % KEY_VAR if not k: + source = "dotenv:%s" % path try: with open(path) as fh: for line in fh: @@ -114,9 +210,87 @@ def api_key(): if re.search(r"\s", k): die("%s contains whitespace; fix the value (not printed)" % KEY_VAR) _SECRETS.append(k) + KEY_ORIGIN["source"] = source + KEY_ORIGIN["tail"] = k[-4:] if len(k) >= MIN_TAIL_KEY_LEN else None return k +def refusal_code(obj): + """The configured refusal code a tool answer carries, or None. + + Reads only structured fields: error, code and error_code, on the object and on its + "error" and "context" objects, the envelope first and then its "result" (a refusal + around an OPEN-looking result is still a refusal). Free text is never read, so a + command's output that merely quotes a code is not a refusal. + """ + if not REFUSAL_CODES: + return None + layers = [obj] + if isinstance(obj, dict) and isinstance(obj.get("result"), dict): + layers.append(obj["result"]) + for layer in layers: + if not isinstance(layer, dict): + continue + for holder in (layer, layer.get("error"), layer.get("context")): + if not isinstance(holder, dict): + continue + for field in ("error", "code", "error_code"): + value = holder.get(field) + if isinstance(value, str) and value in REFUSAL_CODES: + return value + return None + + +def first_refusal(candidates): + for obj in candidates: + code = refusal_code(obj) + if code: + return code + return None + + +def iserror_code(res): + """The refusal code in an isError result: the result, its structured content, then each + text block that holds JSON (a block with no text is skipped, not a crash).""" + if not REFUSAL_CODES: + return None + code = first_refusal((res, res.get("structuredContent"))) + if code: + return code + content = res.get("content") + if not isinstance(content, list): + return None + for block in content: + if isinstance(block, dict) and block.get("type") == "text": + try: + payload = json.loads(block.get("text")) + except (TypeError, ValueError, RecursionError): + continue + code = refusal_code(payload) + if code: + return code + return None + + +def print_refusal_note(code): + """Print one NOTE line for a configured refusal code. + + Keep the provenance that api_key() captured in a JSON suffix for await-approval. + The dotenv file can change while a long poll is waiting for its answer. + """ + if not code or code not in REFUSAL_CODES: + return + source = shown(KEY_ORIGIN["source"] or "unknown") + tail = shown(KEY_ORIGIN["tail"]) if KEY_ORIGIN["tail"] else None + connector = shown(os.environ.get("OPS_MCP_CONNECTOR") or "unknown") + used = f"the key from {source}" + if tail: + used += f" (ends {tail})" + origin = json.dumps({"key_source": source, "key_tail": tail}, separators=(",", ":")) + print(f"{NOTE_PREFIX}{shown(code)}: the server refused this caller. This call used {used}, " + f"connector {connector}. Use the key or login that made the request.\t{origin}", file=sys.stderr) + + class Response: """What HttpSession.post and .delete return: status_code, headers, content (bytes).""" @@ -212,14 +386,14 @@ def _parse(self, resp): if isinstance(obj, dict) and ("result" in obj or "error" in obj): out = obj if out is None: - die("no JSON-RPC payload in SSE body: %s" % body[:500]) + die("no JSON-RPC payload in SSE body: %s" % shown(body, 500)) return out if not body.strip(): return None try: return json.loads(body) except json.JSONDecodeError: - die("non-JSON response (HTTP %s, %s): %s" % (resp.status_code, ctype, body[:500])) + die("non-JSON response (HTTP %s, %s): %s" % (resp.status_code, shown(ctype, 200), shown(body, 500))) def rpc(self, method, params=None, notify=False): payload = {"jsonrpc": "2.0", "method": method} @@ -236,7 +410,7 @@ def rpc(self, method, params=None, notify=False): self.mcp_session_id = sid try: if resp.status_code >= 300: - die("HTTP %s on %s: %s" % (resp.status_code, method, resp.content.decode("utf-8", "replace")[:500])) + die("HTTP %s on %s: %s" % (resp.status_code, method, shown(resp.content.decode("utf-8", "replace"), 500))) if notify: return None msg = self._parse(resp) @@ -249,7 +423,10 @@ def rpc(self, method, params=None, notify=False): raise UnknownOutcome(exc.code) from None raise if "error" in msg: - die("JSON-RPC error on %s: %s" % (method, json.dumps(msg["error"])[:800])) + err = msg["error"] + data = err.get("data") if isinstance(err, dict) else None + die(f"JSON-RPC error on {method}: {shown(json.dumps(err), 800)}", + first_refusal((msg, err, data))) return msg["result"] def initialize(self): @@ -309,14 +486,14 @@ def resolve(self, suffix): if len(hits) == 1: return hits[0] if not hits: - die("no tool matching %r; available: %s" % (suffix, names)) - die("ambiguous tool suffix %r: %s" % (suffix, hits)) + die(f"no tool matching {suffix!r}; available: {shown(json.dumps(names))}") + die(f"ambiguous tool suffix {suffix!r}: {shown(json.dumps(hits))}") def call(self, suffix, args): name = self.resolve(suffix) res = self.rpc("tools/call", {"name": name, "arguments": args}) if res.get("isError"): - die("tool %s returned isError: %s" % (name, json.dumps(res)[:800])) + die(f"tool {shown(name)} returned isError: {shown(json.dumps(res), 800)}", iserror_code(res)) return res @@ -466,7 +643,8 @@ def run_batch(c, calls, out_path): with private_open(out_path) as out: for n, tool, args in calls: try: - res = unwrap(c.call(tool, args)) + reply = c.call(tool, args) + res = unwrap(reply) except (Interrupted, UnknownOutcome) as exc: why = "terminated by signal" if isinstance(exc, Interrupted) else "unconfirmed response" out.write(json.dumps({"line": n, "tool": tool, "ok": False, "state": "unknown", @@ -493,7 +671,8 @@ def run_batch(c, calls, out_path): if why: out.write(json.dumps({"line": n, "tool": tool, "ok": False, "refused": why, "result": res}, ensure_ascii=False) + "\n") - die("line %d (%s) refused in-band (%s); stopped after %d ok" % (n, tool, why, done)) + die(f"line {n} ({tool}) refused in-band ({shown(why)}); stopped after {done} ok", + first_refusal((reply, res))) out.write(json.dumps({"line": n, "tool": tool, "ok": True, "result": res}, ensure_ascii=False) + "\n") out.flush() done += 1 @@ -522,6 +701,7 @@ def main(): if len(sys.argv) < 4: die("batch ") calls = load_calls(sys.argv[2], sys.argv[3]) + refusal_settings() # before any session opens: a malformed setting sends nothing # SIGHUP does not exist on Windows; install what the platform has. for name in ("SIGTERM", "SIGHUP"): sig = getattr(signal, name, None) @@ -536,8 +716,8 @@ def main(): if cmd == "list": for t in c.tools(): - print(t["name"]) - print(" inputSchema: %s" % json.dumps(t.get("inputSchema", {}))) + print(shown(t["name"])) + print(" inputSchema: %s" % shown(json.dumps(t.get("inputSchema", {})))) return if cmd == "call": @@ -548,14 +728,18 @@ def main(): args = json.load(fh) except (OSError, ValueError) as exc: die("cannot read the args file %s: %s" % (sys.argv[3], exc)) - res = unwrap(c.call(sys.argv[2], args)) + reply = c.call(sys.argv[2], args) + res = unwrap(reply) out = sys.argv[4] if len(sys.argv) > 4 else None if out: with private_open(out) as fh: json.dump(res, fh, ensure_ascii=False, indent=1) print("wrote %s" % out) else: - print(json.dumps(res, ensure_ascii=False)[:4000]) + print(shown(json.dumps(res, ensure_ascii=False), 4000)) + # Read the tool wrapper first. Unwrap can discard a refusal alongside + # structuredContent, which may contain a status from another caller. + print_refusal_note(first_refusal((reply, res))) return if cmd == "batch": @@ -566,7 +750,7 @@ def main(): except OSError as exc: # A refused, reset or timed-out connection. A batch has already marked # the call in flight "unknown" before this point. - die("network error: %s" % exc) + die("network error: %s" % shown(exc)) finally: c.close() diff --git a/.claude-config/bin/tests/await-approval-test.py b/.claude-config/bin/tests/await-approval-test.py index 694ae72..8340d9b 100755 --- a/.claude-config/bin/tests/await-approval-test.py +++ b/.claude-config/bin/tests/await-approval-test.py @@ -25,7 +25,13 @@ classify_failure reads the HTTP status where the client puts it, and an isError is retried, not fatal; (19) the scrub list is seeded from the key in $OPS_DIR/.env and ~/OPS/.env; (20) every exit code is documented in the header and in bin/README.md; (21) the built-in default -kind and the configuration file's checks. +kind and the configuration file's checks; (22) terminal refusals (opt-in through +terminal_refusals): each code ends the wait on its first answer with exit 2, read from structured +fields (the envelope before its result) or the client's own NOTE line on either exit, never from +quoted text; an empty or missing list keeps today's classification; each kind's key_connector +is the only ~/.claude.json entry it reads; the line names the connector, the key's source and +at most its last four characters, matching the real client's lookup; malformed configuration is +a usage error; and the real client and the waiter together against a scripted server. Exit 0 = all pass. Any failure exits non-zero and names the case. """ @@ -34,6 +40,7 @@ import json import os import re +import shlex import shutil import signal import subprocess @@ -77,8 +84,12 @@ open(cp, "w").write(str(n + 1)) step = scenario[min(n, len(scenario) - 1)] rec = {"argv": sys.argv[1:], "server": server, "tool": tool, "args": json.load(open(args_path)), - "key": os.environ.get("OPS_MCP_API_KEY"), "args_mode": oct(os.stat(args_path).st_mode & 0o777), "n": n} + "key": os.environ.get("OPS_MCP_API_KEY"), "args_mode": oct(os.stat(args_path).st_mode & 0o777), "n": n, + "refusal_codes": os.environ.get("OPS_MCP_REFUSAL_CODES"), "connector": os.environ.get("OPS_MCP_CONNECTOR"), + "key_source": os.environ.get("OPS_MCP_KEY_SOURCE")} open(os.path.join(d, "calls.jsonl"), "a").write(json.dumps(rec) + "\n") +if step.get("stderr"): + sys.stderr.write(step["stderr"]) if step.get("needs_key") and not os.environ.get("OPS_MCP_API_KEY"): sys.stderr.write("ERROR: no API key: set OPS_MCP_API_KEY in the environment or in /nonexistent/OPS/.env\n") sys.exit(1) @@ -106,6 +117,104 @@ def term(sig, frm): print("wrote " + out_path) ''' +# The real bin/mcp-http-call.py with only its HTTP session replaced by a scripted server, so the +# waiter and the real client run together offline. Steps in transport.json answer tools/call with +# {"result": } or {"http_status": N, "body": ""}; the client's stderr +# is copied to child-stderr.txt so a case can count its NOTE lines. +TRANSPORT = r'''#!/usr/bin/env python3 +import importlib.machinery, importlib.util, json, os, sys +d = os.environ["STUB_DIR"] +loader = importlib.machinery.SourceFileLoader("mcp_http_call_under_test", os.environ["REAL_CLIENT"]) +spec = importlib.util.spec_from_loader(loader.name, loader) +client = importlib.util.module_from_spec(spec) +loader.exec_module(client) +steps = json.load(open(os.path.join(d, "transport.json"))) +cp = os.path.join(d, "count") +n = int(open(cp).read()) if os.path.exists(cp) else 0 +open(cp, "w").write(str(n + 1)) +step = steps[min(n, len(steps) - 1)] +rec = {"n": n, "argv": sys.argv[1:], "key_source": os.environ.get("OPS_MCP_KEY_SOURCE"), + "connector": os.environ.get("OPS_MCP_CONNECTOR"), "refusal_codes": os.environ.get("OPS_MCP_REFUSAL_CODES")} +open(os.path.join(d, "calls.jsonl"), "a").write(json.dumps(rec) + "\n") + + +class Tee: + def __init__(self, stream, path): + self.stream, self.copy = stream, open(path, "a") + + def write(self, text): + self.copy.write(text) + self.copy.flush() + return self.stream.write(text) + + def flush(self): + self.stream.flush() + + +class Server: + def __init__(self): + self.headers = {} + + def post(self, url, json=None, headers=None, timeout=None): + import json as J + method, rid = json.get("method"), json.get("id") + + def answer(obj): + return client.Response(200, {"Content-Type": "application/json", "mcp-session-id": "s1"}, + J.dumps(obj).encode()) + if method == "initialize": + return answer({"jsonrpc": "2.0", "id": rid, "result": {}}) + if method == "notifications/initialized": + return client.Response(202, {}, b"") + if method == "tools/list": + return answer({"jsonrpc": "2.0", "id": rid, "result": {"tools": [{"name": "approvals__session_status"}]}}) + if "http_status" in step: + return client.Response(step["http_status"], {"Content-Type": "text/plain"}, step["body"].encode()) + if "rotate_dotenv_to" in step: + path = client.env_file() + with open(path + ".new", "w") as fh: + fh.write(client.KEY_VAR + "=" + step["rotate_dotenv_to"] + "\n") + os.replace(path + ".new", path) + return answer({"jsonrpc": "2.0", "id": rid, "result": step["result"]}) + + def delete(self, url, headers=None, timeout=None): + return client.Response(200, {}, b"") + + +client.HttpSession = Server +sys.stderr = Tee(sys.stderr, os.path.join(d, "child-stderr.txt")) +sys.argv = ["mcp-http-call.py"] + sys.argv[1:] +client.main() +''' + +# Terminal refusals (opt-in): the five example codes the header shows, and one custom code. +CODES = ["not_requester", "requester_mismatch", "identity_missing", "identity_ambiguous", "identity_invalid"] +CUSTOM = "caller_unverified" +def fixture_key(label, length=24): + """A fake credential for a test, built at run time from a label. Built, not written: a + literal in this shape reads as a real key to a secrets scanner (CI runs gitleaks over the + whole history). Deterministic, so a failure reproduces.""" + import hashlib + alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789" + n, out = int(hashlib.sha256(("ops-test-fixture:" + label).encode()).hexdigest(), 16), "" + while len(out) < length: + n, r = divmod(n, len(alphabet)) + out += alphabet[r] + return out + + +RKEY = fixture_key("refused-poll") # the line may show its last four characters, never more +KEY_A = fixture_key("connector-a") +KEY_B = fixture_key("connector-b") +TR_CONFIG = { + "default_kind": "session", + "terminal_refusals": CODES + [CUSTOM], + "kinds": { + "session": dict(CONFIG["kinds"]["session"], key_connector="approvals"), + "grant": dict(CONFIG["kinds"]["grant"], key_connector="grants"), + }, +} + def check(label, cond, detail=""): global PASS, FAIL @@ -642,6 +751,335 @@ def run_cases(root): check("21 fill_args substitutes only the two placeholders, wait as an integer", mod.fill_args({"a": "{id}", "b": "{wait}", "c": "{id}x", "d": 7}, "idid", 12) == {"a": "idid", "b": 12, "c": "{id}x", "d": 7}) + check("20 header documents terminal_refusals, key_connector and the five example codes", + all(x in header for x in ["terminal_refusals", "key_connector"] + CODES), "missing from the header") + section = readme.split("## `mcp-http-call.py` and `await-approval`", 1)[-1].split("\n## ", 1)[0] + check("20 README documents terminal_refusals, key_connector and OPS_MCP_REFUSAL_CODES", + all(x in section for x in ("terminal_refusals", "key_connector", "OPS_MCP_REFUSAL_CODES")), "missing from README") + + run_refusal_cases(root) + + +def longer_than_tail(text, key): + """Whether text holds five or more consecutive characters of the key.""" + return any(key[i:i + 5] in text for i in range(len(key) - 4)) + + +def refused(case, code, kind="session", short="3f2a91bc"): + """The one line of a terminal refusal: state=, exit 2.""" + line = one_line(case) + return bool(line) and line.startswith("await-approval: %s %s state=%s exit=2 " % (kind, short, code)) + + +def note_step(code, rc=1): + """A failed poll as the client reports a refusal: its ERROR line, then its one NOTE line.""" + return fail_step('ERROR: tool approvals__session_status returned isError: {"content": [{"type": "text", ' + '"text": "refused"}], "isError": true}\nNOTE: the gateway answered %s: the server refused ' + 'this caller.' % code, rc=rc) + + +def write_claude_json(case, entries): + with open(os.path.join(case.home, ".claude.json"), "w") as fh: + json.dump({"mcpServers": {name: {"type": "http", "headers": {"Authorization": "Bearer " + key}} + for name, key in entries.items()}}, fh) + + +def load_client(): + """The real bin/mcp-http-call.py as a module (it reads OPS_MCP_KEY_VAR when it loads).""" + loader = importlib.machinery.SourceFileLoader("mcp_http_call_origin", os.path.join(BIN, "mcp-http-call.py")) + spec = importlib.util.spec_from_loader(loader.name, loader) + client = importlib.util.module_from_spec(spec) + loader.exec_module(client) + return client + + +def run_refusal_cases(root): + # (22) Terminal refusals, opted in through terminal_refusals. A refusal of this caller (the + # server says the waiter's credential is not the one that requested, or names no identity for + # it) cannot change by waiting, so it ends the wait on its first answer: exit 2, the code as + # the state, the connector, where the key came from and at most its last four characters. + env = {"OPS_MCP_API_KEY": RKEY} + for code in CODES + [CUSTOM]: + c = Case(root, "tr-inband-" + code, config=TR_CONFIG).run( + [{"out": {"error": code, "message": "refused"}}, session("OPEN")], [ID], env=env) + check("22 in-band %s: exit 2 after one poll with state=%s" % (code, code), + c.rc == 2 and len(c.calls) == 1 and refused(c, code), "rc=%s calls=%d out=%r" % (c.rc, len(c.calls), c.out)) + check("22 in-band %s: the line names the connector, key source and at most the last four characters" % code, + all(x in c.out for x in ("connector=approvals", "key_source=env:OPS_MCP_API_KEY", "key_tail=" + RKEY[-4:])) + and not longer_than_tail(c.out + c.err, RKEY), repr(c.out)) + check("22 in-band %s: says the request may still be pending and to poll with the credential that requested it" + % code, "may still be pending" in c.out and "credential that made the request" in c.out, repr(c.out)) + c = Case(root, "tr-note-" + code, config=TR_CONFIG).run([note_step(code), session("OPEN")], [ID], env=env) + check("22 the client's note for %s on a failed poll: exit 2 after one poll" % code, + c.rc == 2 and len(c.calls) == 1 and refused(c, code), "rc=%s calls=%d out=%r" % (c.rc, len(c.calls), c.out)) + c = Case(root, "tr-note-zero-exit", config=TR_CONFIG).run( + [dict(session("PENDING"), stderr="NOTE: the gateway answered not_requester: refused\n"), session("OPEN")], + [ID], env=env) + check("22 a note on a zero exit is read before the status: exit 2 after one poll", + c.rc == 2 and len(c.calls) == 1 and refused(c, "not_requester"), "rc=%s calls=%d out=%r" % (c.rc, len(c.calls), c.out)) + c = Case(root, "tr-note-before-stalled-close", config=TR_CONFIG).run( + [{"stderr": "NOTE: the gateway answered not_requester: refused\n", "hang": True}], + [ID, "--timeout", "1"], env=env) + check("22 a completed refusal survives the timeout during child cleanup", + c.rc == 2 and len(c.calls) == 1 and refused(c, "not_requester") + and os.path.exists(os.path.join(c.stub_dir, "got-sigterm")), + f"rc={c.rc} calls={len(c.calls)} out={c.out!r}") + c = Case(root, "tr-grant-context", config=TR_CONFIG).run( + [{"out": {"error": True, "code": "refused", "context": {"code": "requester_mismatch"}}}], [GID, "--kind", "grant"], + env=env) + check("22 grant, a code under context: state=requester_mismatch and the grant kind's connector", + c.rc == 2 and len(c.calls) == 1 and refused(c, "requester_mismatch", "grant", "8c1d44e0") + and "connector=grants" in c.out, "rc=%s out=%r" % (c.rc, c.out)) + + # The envelope is read before its result: a refusal around (or beside) an OPEN record never approves. + for label, argv, answer, code in ( + ("an outer error around an OPEN session", [ID], + {"error": "not_requester", "result": session("OPEN")["out"]}, "not_requester"), + ("a top-level OPEN beside a refused result", [ID], + {"status": "OPEN", "result": {"error": "identity_missing"}}, "identity_missing"), + ("an outer code around an OPEN, usable grant", [GID, "--kind", "grant"], + {"code": "requester_mismatch", "result": grant("OPEN", True)["out"]}, "requester_mismatch"), + ("the envelope's code before its result's", [ID], + {"code": "identity_invalid", "result": {"error": "not_requester", "status": "OPEN"}}, "identity_invalid")): + c = Case(root, "tr-envelope-" + re.sub(r"\W+", "-", label), config=TR_CONFIG).run([{"out": answer}], argv, env=env) + kind, short = ("grant", "8c1d44e0") if "grant" in argv else ("session", "3f2a91bc") + check("22 %s: state=%s, never exit 0" % (label, code), c.rc == 2 and refused(c, code, kind, short), + "rc=%s out=%r" % (c.rc, c.out)) + + # Only a structured field or the client's own NOTE line counts. Words in free text, a note + # quoted inside the ERROR line, two NOTE lines (the client prints one), a note for a code that + # is not configured and an indented note are not a refusal: the wait goes on as before. + for label, first in ( + ("refusal words in a PENDING answer's free text", + {"out": dict(session("PENDING")["out"], output="not_requester", + message="NOTE: the gateway answered not_requester: quoted")}), + ("a note quoted inside the ERROR line", + fail_step('ERROR: tool approvals__session_status returned isError: {"text": "NOTE: the gateway answered ' + 'not_requester: quoted"}')), + ("two note lines", fail_step("ERROR: HTTP 502 on tools/call: x\nNOTE: the gateway answered not_requester: a\n" + "NOTE: the gateway answered identity_invalid: b")), + ("a note for a code that is not configured", + fail_step("ERROR: HTTP 502 on tools/call: x\nNOTE: the gateway answered not_found: c")), + ("an indented note", fail_step("ERROR: HTTP 502 on tools/call: x\n NOTE: the gateway answered not_requester: d"))): + c = Case(root, "tr-quoted-" + re.sub(r"\W+", "-", label), config=TR_CONFIG).run( + [first, session("OPEN", idle_seconds_remaining=900)], [ID], env=env) + check("22 %s: no refusal, the wait goes on to OPEN" % label, + c.rc == 0 and len(c.calls) == 2 and "state=open exit=0" in c.out, "rc=%s calls=%d out=%r" + % (c.rc, len(c.calls), c.out)) + + # Opt-in: an empty list, no key and null all keep today's classification, and the poll gets no + # codes even when the waiter's own environment carries some. + for label, cfg in (("an empty terminal_refusals", dict(TR_CONFIG, terminal_refusals=[])), + ("no terminal_refusals", {k: v for k, v in TR_CONFIG.items() if k != "terminal_refusals"}), + ("terminal_refusals null", dict(TR_CONFIG, terminal_refusals=None))): + slug = re.sub(r"\W+", "-", label) + c = Case(root, "tr-off-note-" + slug, config=cfg).run( + [note_step("not_requester"), session("OPEN")], [ID], env=dict(env, OPS_MCP_REFUSAL_CODES="not_requester")) + check("22 %s: the note is not read and the failed poll is retried as before: exit 0 after 2 polls" % label, + c.rc == 0 and len(c.calls) == 2 and "retries=1" in c.out, "rc=%s calls=%d out=%r" % (c.rc, len(c.calls), c.out)) + check("22 %s: the poll gets no OPS_MCP_REFUSAL_CODES" % label, + all(x["refusal_codes"] is None for x in c.calls), str([x["refusal_codes"] for x in c.calls])) + c = Case(root, "tr-off-inband-" + slug, config=cfg).run( + [{"out": {"error": "not_requester", "message": "refused"}}], [ID], env=env) + check("22 %s: an in-band refusal is the ordinary in-band error it was" % label, + c.rc == 2 and len(c.calls) == 1 and "state=error exit=2" in c.out and "not_requester" in c.out, repr(c.out)) + + # A PENDING-to-OPEN control with the codes configured, and what the poll is given. + c = Case(root, "tr-control", config=TR_CONFIG).run( + [session("PENDING"), session("PENDING"), session("OPEN", idle_seconds_remaining=900)], [ID], + env=dict(env, OPS_MCP_KEY_SOURCE="claude.json:elsewhere", OPS_MCP_CONNECTOR="elsewhere")) + check("22 control: PENDING, PENDING, OPEN still exits 0 after three polls with the usual line", + c.rc == 0 and len(c.calls) == 3 and re.fullmatch( + r"await-approval: session 3f2a91bc state=open exit=0 waited=\d+s idle_left=900s", one_line(c) or ""), + "rc=%s out=%r" % (c.rc, c.out)) + check("22 the poll gets the configured codes and the kind's connector, and no inherited key source", + c.calls and all(x["refusal_codes"] == ",".join(sorted(CODES + [CUSTOM])) and x["connector"] == "approvals" + and x["key_source"] is None for x in c.calls), str(c.calls[:1])) + + # key_connector: each kind reads only its own entry of ~/.claude.json, even when the legacy + # list names both, so one kind's key is never lent to another. + two = dict(TR_CONFIG, key_connectors=["approvals", "grants"]) + c = Case(root, "tr-two-connectors-one-entry", config=two) + write_claude_json(c, {"approvals": KEY_A}) + c.run([dict(grant("OPEN", True), needs_key=True)], [GID, "--kind", "grant"]) + check("22 two connectors: the grant kind never borrows the approvals entry: exit 2 after one poll, names grants", + c.rc == 2 and len(c.calls) == 1 and all(x["key"] != KEY_A for x in c.calls) and "grants" in c.out, + "rc=%s calls=%r out=%r" % (c.rc, [x["key"] for x in c.calls], c.out)) + for kind, ident, want, other in (("grant", GID, KEY_B, KEY_A), ("session", ID, KEY_A, KEY_B)): + c = Case(root, "tr-two-connectors-" + kind, config=two) + write_claude_json(c, {"approvals": KEY_A, "grants": KEY_B}) + steps = [dict(grant("OPEN", True) if kind == "grant" else session("OPEN"), needs_key=True)] + c.run(steps, [ident, "--kind", kind]) + check("22 two connectors: --kind %s polls with its own entry's key and no other" % kind, + c.rc == 0 and len(c.calls) == 2 and c.calls[1]["key"] == want and all(x["key"] != other for x in c.calls), + "rc=%s keys=%r" % (c.rc, [x["key"] for x in c.calls])) + + # Legacy kinds (no key_connector) keep the global key_connectors list; the entry the fallback + # selected is the connector the line names, and the refusal ends the wait on that same key. + legacy = {"key_connectors": ["other", "approvals"], "terminal_refusals": CODES, + "kinds": {"session": CONFIG["kinds"]["session"]}} + c = Case(root, "tr-legacy", config=legacy) + write_claude_json(c, {"approvals": RKEY}) + c.run([{"needs_key": True, "out": {"error": "not_requester"}}], [ID]) + check("22 legacy key_connectors: the selected entry's key, its refusal ends the wait (two polls, no third key)", + c.rc == 2 and len(c.calls) == 2 and c.calls[1]["key"] == RKEY and refused(c, "not_requester"), + "rc=%s calls=%d out=%r" % (c.rc, len(c.calls), c.out)) + check("22 legacy key_connectors: the line and the poll name the selected entry as connector and key source", + all(x in c.out for x in ("connector=approvals", "key_source=claude.json:approvals", "key_tail=" + RKEY[-4:])) + and len(c.calls) == 2 and c.calls[1]["key_source"] == "claude.json:approvals" + and c.calls[1]["connector"] == "approvals" and not longer_than_tail(c.out + c.err, RKEY), repr(c.out)) + + # Each key source is named as it is: the variable, the .env file, the ~/.claude.json entry. + for label, extra, envfile, want in ( + ("the environment", {"OPS_MCP_API_KEY": RKEY}, None, "key_source=env:OPS_MCP_API_KEY"), + ("a custom variable", {"OPS_MCP_KEY_VAR": "EXAMPLE_KEY", "EXAMPLE_KEY": RKEY}, None, "key_source=env:EXAMPLE_KEY"), + ("$OPS_DIR/.env", {"OPS_DIR": "@/opsdir"}, ("opsdir/.env", 'OPS_MCP_API_KEY="%s"\n'), "dotenv:@/opsdir/.env"), + ("~/OPS/.env", {}, ("home/OPS/.env", "export OPS_MCP_API_KEY=%s\n"), "dotenv:@/home/OPS/.env")): + c = Case(root, "tr-src-" + re.sub(r"\W+", "-", label), config=TR_CONFIG) + extra = {k: v.replace("@", c.dir) for k, v in extra.items()} + if envfile: + path = os.path.join(c.dir, envfile[0]) + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "w") as fh: + fh.write("OTHER=1\n" + envfile[1] % RKEY) + c.run([{"out": {"error": "not_requester"}}], [ID], env=extra) + check("22 key from %s: the line names it, with at most the last four characters" % label, + c.rc == 2 and want.replace("@", c.dir) in c.out and "key_tail=" + RKEY[-4:] in c.out + and not longer_than_tail(c.out + c.err, RKEY), "rc=%s out=%r" % (c.rc, c.out)) + c = Case(root, "tr-src-claude-json", config=TR_CONFIG) + write_claude_json(c, {"approvals": RKEY, "grants": KEY_B}) + c.run([{"needs_key": True, "out": {"error": "not_requester"}}], [ID]) + check("22 key from the kind's ~/.claude.json entry: named, and the refusal ends the wait on that key", + c.rc == 2 and len(c.calls) == 2 and "key_source=claude.json:approvals" in c.out + and "key_tail=" + RKEY[-4:] in c.out and not longer_than_tail(c.out + c.err, RKEY) + and c.calls[1]["key_source"] == "claude.json:approvals", "rc=%s out=%r" % (c.rc, c.out)) + c = Case(root, "tr-src-short", config=TR_CONFIG).run([{"out": {"error": "not_requester"}}], [ID], + env={"OPS_MCP_API_KEY": "short-key-12"}) + check("22 a short key: the source is named and no tail is shown", + c.rc == 2 and "key_source=env:OPS_MCP_API_KEY" in c.out and "key_tail=" not in c.out, repr(c.out)) + + # The actual out file can carry a remote diagnostic verbatim. The waiter + # must scrub the credential itself before printing that diagnostic. + key = 'Dx6P"w8\\Fs2/Qt7Yn4Bv9' + quoted = json.dumps(key)[1:-1].replace("/", "\\/") + for label, value in (("trimmed", key), ("JSON escaped twice", json.dumps(quoted)[1:-1])): + c = Case(root, "unconfigured-error-" + label, config=TR_CONFIG).run( + [{"out": {"error": "lookup_failed", "message": "request header " + value}}], + [ID], env={"OPS_MCP_API_KEY": " " + key + " "}) + check(f"22 generic in-band error scrubs the {label.lower()} key before display", + c.rc == 2 and "state=error" in c.out and "" in c.out and not longer_than_tail(c.out, key), + f"rc={c.rc} redacted={'' in c.out}") + + # The waiter names the key source by the client's own lookup; pin the two to each other. + mod = load_script() + saved = dict(os.environ) + origin = getattr(mod, "key_origin", None) + try: + for label, extra, envfile in ( + ("env", {"OPS_MCP_API_KEY": RKEY}, None), + ("custom variable", {"OPS_MCP_KEY_VAR": "EXAMPLE_KEY", "EXAMPLE_KEY": RKEY}, None), + ("$OPS_DIR/.env, quoted", {"OPS_DIR": "@/opsdir"}, ("opsdir/.env", 'OPS_MCP_API_KEY="%s"\n')), + ("~/OPS/.env, export form", {}, ("home/OPS/.env", "export OPS_MCP_API_KEY=%s\n")), + ("a short key", {"OPS_MCP_API_KEY": "short-key-12"}, None)): + base = os.path.join(root, "origin-" + re.sub(r"\W+", "-", label)) + os.makedirs(os.path.join(base, "home")) + for name in ("OPS_MCP_API_KEY", "OPS_MCP_KEY_VAR", "EXAMPLE_KEY", "OPS_DIR", "OPS_MCP_KEY_SOURCE"): + os.environ.pop(name, None) + os.environ["HOME"] = os.path.join(base, "home") + os.environ.update({k: v.replace("@", base) for k, v in extra.items()}) + if envfile: + path = os.path.join(base, envfile[0]) + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "w") as fh: + fh.write("OTHER=1\n" + envfile[1] % RKEY) + client = load_client() + client.api_key() + want = (client.KEY_ORIGIN["source"], client.KEY_ORIGIN["tail"]) if hasattr(client, "KEY_ORIGIN") else "none" + got = origin(dict(os.environ)) if origin else "no key_origin" + check("22 key source (%s): the waiter names what the real client used" % label, got == want and want[0], + "waiter=%r client=%r" % (got, want)) + finally: + os.environ.clear() + os.environ.update(saved) + + # Malformed new configuration is a usage error: no call, nothing on stdout. + def with_kind(**fields): + return dict(TR_CONFIG, kinds={"session": dict(TR_CONFIG["kinds"]["session"], **fields)}) + for label, cfg in ( + ("terminal_refusals not a list", dict(TR_CONFIG, terminal_refusals="not_requester")), + ("a code that is not a token", dict(TR_CONFIG, terminal_refusals=["Not-A-Code"])), + ("an empty code", dict(TR_CONFIG, terminal_refusals=[""])), + ("a code that is a number", dict(TR_CONFIG, terminal_refusals=[7])), + ("the reserved state open", dict(TR_CONFIG, terminal_refusals=["open"])), + ("the reserved state error", dict(TR_CONFIG, terminal_refusals=["error"])), + ("the reserved state pending", dict(TR_CONFIG, terminal_refusals=["pending"])), + ("the reserved state not_usable", dict(TR_CONFIG, terminal_refusals=["not_usable"])), + ("key_connector not a string", with_kind(key_connector=["approvals"])), + ("an empty key_connector", with_kind(key_connector="")), + ("a key_connector with a line break", with_kind(key_connector="approvals\nother")), + ("a key_connectors entry with a line break", dict(TR_CONFIG, key_connectors=["approvals\nother"]))): + c = Case(root, "tr-cfg-" + re.sub(r"\W+", "-", label), config=cfg).run([session("OPEN")], [ID], env=env) + check("22 configuration (%s): a usage error, exit 2, no call" % label, + c.rc == 2 and "usage:" in c.err and c.out == "" and c.calls == [], "rc=%s out=%r err=%r" % (c.rc, c.out, c.err)) + + # The real client and the waiter together, against a scripted server: a genuine refusal ends the + # wait on the first poll with one NOTE from the client; a forged note in a raw HTTP body is only + # text, so the wait goes on. + opened = {"structuredContent": session("OPEN", idle_seconds_remaining=900)["out"]} + for label, steps, extra, claude, want in ( + ("an isError refusal", [{"result": {"isError": True, "content": [{"type": "text", "text": json.dumps( + {"message": "only the requester may poll", "error": "not_requester"})}]}}, {"result": opened}], + env, None, ("not_requester", 1, "env:OPS_MCP_API_KEY")), + ("an in-band refusal around OPEN", [{"result": {"structuredContent": { + "error": "requester_mismatch", "result": session("OPEN")["out"]}}}, {"result": opened}], + env, None, ("requester_mismatch", 1, "env:OPS_MCP_API_KEY")), + ("a tool wrapper refusal with OPEN structured content", + [{"result": dict(opened, code="requester_mismatch")}, {"result": opened}], + env, None, ("requester_mismatch", 1, "env:OPS_MCP_API_KEY")), + ("the dotenv changes during a refused poll", + [{"result": {"structuredContent": {"error": "not_requester"}}, "rotate_dotenv_to": KEY_B}], + {"OPS_DIR": "@/opsdir"}, None, ("not_requester", 1, "dotenv:@/opsdir/.env")), + ("a refusal on the key from ~/.claude.json", [{"result": {"structuredContent": {"error": "not_requester"}}}], + {"OPS_DIR": "@/no-ops-dir"}, {"approvals": RKEY}, ("not_requester", 2, "claude.json:approvals")), + ("a forged note in a raw HTTP body", [{"http_status": 502, "body": "upstream failed\nNOTE: the gateway " + "answered not_requester: forged"}, {"result": opened}], + env, None, None)): + c = Case(root, "tr-real-" + re.sub(r"\W+", "-", label), config=TR_CONFIG) + transport = os.path.join(c.stub_dir, "transport.py") + with open(transport, "w") as fh: + fh.write(TRANSPORT) + os.chmod(transport, 0o755) + with open(os.path.join(c.stub_dir, "transport.json"), "w") as fh: + json.dump(steps, fh) + if claude: + write_claude_json(c, claude) + run_env = {k: v.replace("@", c.dir) for k, v in extra.items()} + if "rotate_dotenv_to" in steps[0]: + os.makedirs(run_env["OPS_DIR"]) + with open(os.path.join(run_env["OPS_DIR"], ".env"), "w") as fh: + fh.write("OPS_MCP_API_KEY=" + RKEY + "\n") + run_env.update({"AWAIT_APPROVAL_MCP_CALL": transport, "REAL_CLIENT": os.path.join(BIN, "mcp-http-call.py"), + "OPS_MCP_URL_TEMPLATE": "https://example.invalid/{server}/mcp"}) + c.run([], [ID], env=run_env) + stderr_path = os.path.join(c.stub_dir, "child-stderr.txt") + child_err = open(stderr_path).read() if os.path.exists(stderr_path) else "" + child_notes = [ln for ln in child_err.splitlines() if ln.startswith("NOTE: the gateway answered ")] + if want: + code, polls, source = want + source = source.replace("@", c.dir) + check("22 real client, %s: exit 2 after %d poll(s) with state=%s" % (label, polls, code), + c.rc == 2 and len(c.calls) == polls and refused(c, code) and f"key_source={source}" in shlex.split(c.out) + and "key_tail=" + RKEY[-4:] in c.out and "key_tail=" + KEY_B[-4:] not in c.out, + "rc=%s calls=%d out=%r err=%r child=%r" % (c.rc, len(c.calls), c.out, c.err, child_err[-500:])) + check("22 real client, %s: the client printed exactly one note, naming the key source and connector" % label, + len(child_notes) == 1 and child_notes[0].startswith("NOTE: the gateway answered %s: " % code) + and source in child_notes[0] and "connector approvals" in child_notes[0] + and not longer_than_tail(child_err + c.out, RKEY), repr(child_err[-500:])) + else: + check("22 real client, %s: no note, the 502 is retried and the wait ends OPEN after 2 polls" % label, + c.rc == 0 and len(c.calls) == 2 and "state=open exit=0" in c.out and child_notes == [], + "rc=%s calls=%d out=%r child=%r" % (c.rc, len(c.calls), c.out, child_err[-500:])) + if __name__ == "__main__": sys.exit(main()) diff --git a/.claude-config/bin/tests/guard-selftest-test.sh b/.claude-config/bin/tests/guard-selftest-test.sh index 882fe3a..f6869c8 100755 --- a/.claude-config/bin/tests/guard-selftest-test.sh +++ b/.claude-config/bin/tests/guard-selftest-test.sh @@ -14,13 +14,14 @@ # command in GST_FLIP. One command per probe site that read through the pipe: # a blocked rtk form, an allowed rtk form, and the plain project push (a few # heredoc probes send that command too; they are counted either way). +# Exit 0 = all pass; 1 = a case fails; 77 = did not run (no jq: the suite proved nothing). set -uo pipefail HERE="$(cd "$(dirname "$0")" && pwd)" HOOKS="$(cd "$HERE/../../hooks" && pwd)" BIN="$(cd "$HERE/.." && pwd)" if ! command -v jq >/dev/null 2>&1; then - echo "SKIP: guard-selftest-test (jq not installed; guard-selftest's rtk probes build their JSON with it)" - exit 0 + echo "guard-selftest-test: did not run: no jq (guard-selftest's rtk probes build their JSON with it)" + exit 77 fi T="$(mktemp -d "${TMPDIR:-/tmp}/guard-selftest-test.XXXXXX")"; trap 'rm -rf "$T"' EXIT PASS=0; FAIL=0 diff --git a/.claude-config/bin/tests/mcp-http-call-test.sh b/.claude-config/bin/tests/mcp-http-call-test.sh index f79a49c..fc956e5 100755 --- a/.claude-config/bin/tests/mcp-http-call-test.sh +++ b/.claude-config/bin/tests/mcp-http-call-test.sh @@ -28,6 +28,12 @@ # and never followed (the bearer key must not follow a redirect), a 401 is # reported with its status and the key scrubbed, a dropped connection is a # one-line error, and an SSE body decodes as UTF-8 even without a charset +# (k) server text is redacted before it is clipped: a key echoed across each +# cutoff leaves no prefix, a JSON-escaped key is still found, `list` output +# and the call preview are redacted, and server text never starts a line +# (l) a refusal code named in OPS_MCP_REFUSAL_CODES gets exactly one NOTE line +# (key source, at most the last four characters, connector), read from +# structured fields only; quoted output gets none; exit codes are unchanged # A stub HTTP session or a stubbed opener stands in for the network. # # Exit 0 = all pass. Any failure exits non-zero and names the case. @@ -105,12 +111,16 @@ TOOLS = ["billing__invoice_query", "billing__catalog", "billing__write"] class StubSession: """A fake server. answers maps a tool name to one of: - ("rpc_error",) | ("is_error",) | ("raise", exc) | ("struct", obj) | ("text", str).""" + ("rpc_error",) | ("is_error",) | ("raise", exc) | ("struct", obj) | ("text", str) | + ("http_error", status, bytes) | ("raw", bytes) | ("raw_ctype", content_type, bytes) | + ("rpc_error_obj", error_obj) | ("is_error_text", str) | ("is_error_res", result_obj). + tools, when given, is the tools/list answer (a list of tool objects).""" - def __init__(self, answers=None): + def __init__(self, answers=None, tools=None): self.headers = {} self.posts, self.deletes = [], [] self.answers = answers or {} + self.tools = tools def post(self, url, json=None, headers=None, timeout=None): import json as J @@ -122,7 +132,8 @@ class StubSession: if m == "notifications/initialized": return Resp(None, status=202) if m == "tools/list": - return Resp({"jsonrpc": "2.0", "id": rid, "result": {"tools": [{"name": n} for n in TOOLS]}}) + tools = self.tools if self.tools is not None else [{"name": n} for n in TOOLS] + return Resp({"jsonrpc": "2.0", "id": rid, "result": {"tools": tools}}) if m == "tools/call": name = json["params"]["name"] a = self.answers.get(name, ("text", J.dumps({"ok": True, "tool": name}))) @@ -130,10 +141,21 @@ class StubSession: response = Resp(None, status=a[1] if a[0] == "http_error" else 200) response.content = a[2] if a[0] == "http_error" else a[1] return response + if a[0] == "raw_ctype": + response = Resp(None) + response.headers["Content-Type"] = a[1] + response.content = a[2] + return response if a[0] == "rpc_error": return Resp({"jsonrpc": "2.0", "id": rid, "error": {"code": -32000, "message": "boom"}}) + if a[0] == "rpc_error_obj": + return Resp({"jsonrpc": "2.0", "id": rid, "error": a[1]}) if a[0] == "is_error": return Resp({"jsonrpc": "2.0", "id": rid, "result": {"isError": True, "content": [{"type": "text", "text": "nope"}]}}) + if a[0] == "is_error_text": + return Resp({"jsonrpc": "2.0", "id": rid, "result": {"isError": True, "content": [{"type": "text", "text": a[1]}]}}) + if a[0] == "is_error_res": + return Resp({"jsonrpc": "2.0", "id": rid, "result": a[1]}) if a[0] == "raise": raise a[1] if a[0] == "struct": @@ -566,6 +588,256 @@ cl = mod.Client.__new__(mod.Client) got = cl._parse(resp) check("(j) an SSE body without a charset decodes as UTF-8", got["result"]["v"] == "it\u2019s \u2014 fine", repr(got)) +# (k) Server text is redacted BEFORE it is clipped or shown. A key the server echoes across a +# cutoff (the 500-character SSE, non-JSON and HTTP bodies, the 800-character JSON-RPC error and +# isError diagnostics, the 4000-character call preview) leaves no prefix behind; a key that JSON +# escaping changed (a quote, a backslash, the slash some servers escape) is still found; `list` +# output is redacted too. Server text also stays on one line, so a body cannot start a line of +# its own: bin/await-approval trusts a line that starts "NOTE: the gateway answered". +def fixture_key(label, length=24): + """A fake credential for a test, built at run time from a label. Built, not written: a + literal in this shape reads as a real key to a secrets scanner (CI runs gitleaks over the + whole history). Deterministic, so a failure reproduces.""" + import hashlib + alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789" + n, out = int(hashlib.sha256(("ops-test-fixture:" + label).encode()).hexdigest(), 16), "" + while len(out) < length: + n, r = divmod(n, len(alphabet)) + out += alphabet[r] + return out + + +B1KEY = fixture_key("cutoff", 27) +# A key with the three characters JSON escaping changes: a quote, a backslash and a slash. +_E = fixture_key("escaped", 18) +ESCKEY = _E[:3] + '"' + _E[3:6] + '\\' + _E[6:12] + '/' + _E[12:] + + +def key_forms(key): + """The key raw and JSON-escaped once and twice, with and without an escaped slash.""" + forms, level = {key}, {key} + for _ in range(2): + level = {json.dumps(f)[1:-1] for f in level} | {json.dumps(f)[1:-1].replace("/", "\\/") for f in level} + forms |= level + return forms + + +def leaks(text, key): + """Whether text holds a prefix of four or more characters of the key, in any of its forms.""" + return any(f[:4] in text for f in key_forms(key)) + + +def run_io(mod, argv, stub): + """Like run(), but also return stdout: (exit code, stdout, stderr, exception).""" + real_init = mod.Client.__init__ + + def init(self): + real_init(self) + self.session = stub + mod.Client.__init__ = init + sys.argv = argv + code, exc, out, err = 0, None, io.StringIO(), io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + try: + mod.main() + except SystemExit as e: + code = e.code + except BaseException as e: # noqa: BLE001 - interrupted paths propagate on purpose + exc = e + return code, out.getvalue(), err.getvalue(), exc + + +def with_key(key, answers=None, argv=None, tools=None): + """One run with `key` as the client's key; returns run_io's tuple and the stub.""" + os.environ["OPS_MCP_API_KEY"] = key + try: + mod = load(); stub = StubSession(answers, tools=tools) + return run_io(mod, argv or ["mcp-http-call.py", "--server", "billing", "call", "catalog", args_json], stub) + (stub,) + finally: + os.environ["OPS_MCP_API_KEY"] = KEY + + +def json_pad(build, cutoff, ahead=6, **dumps): + """Padding that puts the text after it `ahead` characters before cutoff in json.dumps(build(text)).""" + return "x" * (cutoff - ahead - json.dumps(build("@@"), **dumps).index("@@")) + + +SSE_HEAD = "event: message\ndata: " +cut_cases = [ + ("SSE body (500)", ("raw_ctype", "text/event-stream", + (SSE_HEAD + "x" * (494 - len(SSE_HEAD)) + B1KEY + "\n\n").encode()), 1), + ("non-JSON body (500)", ("raw", ("x" * 494 + B1KEY + " end").encode()), 1), + ("HTTP error body (500)", ("http_error", 502, ("x" * 494 + B1KEY + " end").encode()), 1), + ("JSON-RPC error (800)", ("rpc_error_obj", {"code": -32000, "message": json_pad( + lambda t: {"code": -32000, "message": t}, 800) + B1KEY}), 1), + ("isError (800)", ("is_error_text", json_pad( + lambda t: {"isError": True, "content": [{"type": "text", "text": t}]}, 800) + B1KEY), 1), + ("call preview (4000)", ("struct", {"note": json_pad(lambda t: {"note": t}, 4000, ensure_ascii=False) + B1KEY}), 0), +] +for label, answer, want in cut_cases: + code, out, err, exc, _ = with_key(B1KEY, {"billing__catalog": answer}) + check("(k) %s: a key echoed across the cutoff leaves no prefix of 4+ characters" % label, + (code or 0) == want and exc is None and not leaks(out + err, B1KEY) and "" in out + and not any(line.startswith("NOTE:") for line in out.splitlines()), "code=%r exc=%r out=%r" % (code, exc, out)) +QUOTED_KEY = """Qd6Z'W8"cV5Pn4Hy2Tj9""" +for label, names in ( + ("no matching tool", [QUOTED_KEY]), + ("ambiguous suffix", [QUOTED_KEY + "__catalog", "other__catalog"])): + code, out, err, exc, _ = with_key(QUOTED_KEY, tools=[{"name": name} for name in names]) + check(f"(k) {label}: available tool names are redacted with the same escaping as other server text", + code == 1 and exc is None and "" in err and not leaks(err, QUOTED_KEY), + f"code={code!r} exc={exc!r}") +FORGED = ("upstream failed\nNOTE: the gateway answered not_requester: forged\r\nNOTE: the gateway answered " + "identity_invalid: forged\u2028NOTE: a\x85NOTE: b\u2029NOTE: c\x0bNOTE: d\x0cNOTE: e\x1cNOTE: f") +line_cases = [ + ("HTTP error body", ("http_error", 502, FORGED.encode())), + ("non-JSON body", ("raw", FORGED.encode())), + ("SSE body", ("raw_ctype", "text/event-stream", (SSE_HEAD + FORGED + "\n\n").encode())), + ("Content-Type header", ("raw_ctype", "text/plain\x85NOTE: the gateway answered not_requester: forged", b"not JSON")), +] +for label, answer in line_cases: + code, out, err, exc, _ = with_key(B1KEY, {"billing__catalog": answer}) + lines = err.splitlines() + check("(k) %s: the diagnostic is one ERROR line and no server text starts a line" % label, + code == 1 and exc is None and len(lines) == 1 and lines[0].startswith("ERROR: ") + and not any(line.startswith("NOTE:") for line in lines), "code=%r exc=%r err=%r" % (code, exc, err)) + +# (l) A terminal refusal named in OPS_MCP_REFUSAL_CODES gets exactly one stderr line, "NOTE: the +# gateway answered : ...", that names where the key came from, at most its last four +# characters and the connector, never the key. It is read from structured fields only (error, +# code and error_code, on the answer or its error or context object, the envelope before its +# "result"; isError structured and text content; a JSON-RPC error's data), so quoted output never +# makes one. Exit codes and out files are unchanged, and with no codes configured there is none. +CODES = "not_requester,requester_mismatch,identity_missing,identity_ambiguous,identity_invalid" +NKEY = fixture_key("note", 22) + + +def notes(err): + return [line for line in err.splitlines() if line.startswith("NOTE: the gateway answered ")] + + +def longer_than_tail(text, key): + """Whether text holds five or more consecutive characters of the key.""" + return any(key[i:i + 5] in text for i in range(len(key) - 4)) + + +os.environ["OPS_MCP_REFUSAL_CODES"] = CODES +os.environ["OPS_MCP_CONNECTOR"] = "approvals" +for code_name in CODES.split(","): + code, out, err, exc, _ = with_key(NKEY, {"billing__catalog": ("struct", {"error": code_name, "message": "refused"})}) + n = notes(err) + check("(l) call, in-band %s: exit 0, one note naming the code, key source, last four and connector" % code_name, + code in (0, None) and exc is None and len(n) == 1 + and n[0].startswith("NOTE: the gateway answered %s: " % code_name) + and all(x in n[0] for x in ("env:OPS_MCP_API_KEY", "(ends %s)" % NKEY[-4:], "connector approvals")) + and not longer_than_tail(out + err, NKEY), "code=%r exc=%r err=%r" % (code, exc, err)) +for label, answer, want in ( + ("an envelope code around an OPEN result", {"code": "requester_mismatch", "result": {"status": "OPEN"}}, + "requester_mismatch"), + ("the envelope before its result", {"code": "identity_invalid", "result": {"error": "not_requester"}}, + "identity_invalid"), + ("a code under context", {"error": True, "code": "refused", "context": {"code": "requester_mismatch"}}, + "requester_mismatch"), + ("a code in an error object", {"error": {"code": "identity_missing", "message": "x"}}, "identity_missing"), + ("error_code", {"result": {"error_code": "identity_ambiguous"}}, "identity_ambiguous")): + code, out, err, exc, _ = with_key(NKEY, {"billing__catalog": ("struct", answer)}) + n = notes(err) + check("(l) call, %s: one note for %s" % (label, want), + code in (0, None) and len(n) == 1 and n[0].startswith("NOTE: the gateway answered %s: " % want), + "code=%r err=%r" % (code, err)) +for label, answer, want in ( + ("isError JSON text, the code past the 800-character excerpt", + ("is_error_text", json.dumps({"message": "m" * 1200, "error": "not_requester"})), "not_requester"), + ("isError structured content (and a text block without text)", + ("is_error_res", {"isError": True, "structuredContent": {"code": "identity_invalid"}, "content": [{"type": "text"}]}), + "identity_invalid"), + ("isError structured content alongside malformed content", + ("is_error_res", {"isError": True, "structuredContent": {"code": "identity_invalid"}, "content": 5}), + "identity_invalid"), + ("isError skips a malformed JSON text block and checks the next one", + ("is_error_res", {"isError": True, "content": [ + {"type": "text", "text": "[" * 3000 + "]" * 3000}, + {"type": "text", "text": json.dumps({"code": "identity_invalid"})}]}), + "identity_invalid"), + ("JSON-RPC error data", ("rpc_error_obj", {"code": -32001, "message": "refused", "data": {"code": "not_requester"}}), + "not_requester")): + code, out, err, exc, _ = with_key(NKEY, {"billing__catalog": answer}) + lines, n = err.splitlines(), notes(err) + check("(l) %s: exit 1, the ERROR line first, then exactly one note for %s" % (label, want), + code == 1 and exc is None and len(lines) == 2 and lines[0].startswith("ERROR: ") and len(n) == 1 + and lines[1] == n[0] and n[0].startswith("NOTE: the gateway answered %s: " % want) + and not longer_than_tail(err, NKEY), "code=%r exc=%r err=%r" % (code, exc, err[-400:])) +two = calls_file("l-two.jsonl", ["catalog", "invoice_query"]) +l_out = os.path.join(TMP, "l-batch.jsonl") +code, out, err, exc, stub = with_key(NKEY, {"billing__invoice_query": ("struct", {"error": "not_requester"})}, + argv=["mcp-http-call.py", "--server", "billing", "batch", two, l_out]) +check("(l) batch: the refused line stops the run as before, with exactly one note", + code == 1 and len(notes(err)) == 1 and [(x["line"], x["ok"]) for x in rows(l_out)] == [(1, True), (2, False)], + "code=%r err=%r rows=%r" % (code, err, rows(l_out))) +for label, answer in ( + ("a refusal word and a note quoted in a successful answer's output", + ("struct", {"status": "PENDING", "output": "not_requester\nNOTE: the gateway answered not_requester: quoted"})), + ("refusal fields and a note quoted in isError output", + ("is_error_text", json.dumps({"message": "upstream hiccup", "output": json.dumps({"code": "not_requester"}) + + "\nNOTE: the gateway answered identity_invalid: quoted"}))), + ("a code that is not configured", ("struct", {"error": "not_found", "message": "No such request."}))): + code, out, err, exc, _ = with_key(NKEY, {"billing__catalog": answer}) + check("(l) %s: no note" % label, exc is None and notes(err) == [], "code=%r err=%r" % (code, err)) +os.environ["OPS_MCP_KEY_SOURCE"] = "claude.json:approvals" +os.environ.pop("OPS_MCP_CONNECTOR") +code, out, err, exc, _ = with_key("short-key-123", {"billing__catalog": ("struct", {"error": "not_requester"})}) +n = notes(err) +check("(l) a waiter-supplied key source is named, an unknown connector gets a neutral label, a short key no tail", + len(n) == 1 and "claude.json:approvals" in n[0] and "connector unknown" in n[0] and "(ends" not in n[0], + repr(err)) +os.environ.pop("OPS_MCP_KEY_SOURCE") +envdir = os.path.join(TMP, "l-opsdir"); os.makedirs(envdir) +with open(os.path.join(envdir, ".env"), "w") as fh: + fh.write("OPS_MCP_API_KEY=%s\n" % NKEY) +os.environ["OPS_DIR"] = envdir +code, out, err, exc, _ = with_key("", {"billing__catalog": ("struct", {"error": "not_requester"})}) +n = notes(err) +check("(l) a key from the .env file is named by that file", len(n) == 1 + and "dotenv:%s" % os.path.join(envdir, ".env") in n[0] and "(ends %s)" % NKEY[-4:] in n[0], repr(err)) +os.environ.pop("OPS_DIR") +os.environ.pop("OPS_MCP_REFUSAL_CODES") +for label, answer in (("in-band", ("struct", {"error": "not_requester"})), + ("isError", ("is_error_text", json.dumps({"error": "not_requester"}))), + ("isError with malformed content", ("is_error_res", {"isError": True, "content": 5}))): + code, out, err, exc, _ = with_key(NKEY, {"billing__catalog": answer}) + want = 0 if label == "in-band" else 1 + check(f"(l) no OPS_MCP_REFUSAL_CODES, {label}: exit {want}, no note", + code == want and exc is None and notes(err) == [], f"code={code!r} exc={exc!r} err={err!r}") +for var, value in (("OPS_MCP_REFUSAL_CODES", "not_requester,Bad-Code"), ("OPS_MCP_REFUSAL_CODES", "has space"), + ("OPS_MCP_CONNECTOR", "approvals\nNOTE: x"), ("OPS_MCP_KEY_SOURCE", "x" * 201)): + os.environ[var] = value + code, out, err, exc, stub = with_key(NKEY, {}) + os.environ.pop(var) + check("(l) a malformed %s is refused before any request" % var, + code == 1 and stub.posts == [] and var in err and value not in err, "code=%r posts=%d err=%r" + % (code, len(stub.posts), err)) +_sig.signal(_sig.SIGTERM, _sig.SIG_DFL); _sig.signal(_sig.SIGHUP, _sig.SIG_DFL) + print("mcp-http-call-test: %d passed, %d failed" % (PASS, FAIL)) sys.exit(1 if FAIL else 0) PY diff --git a/.claude-config/bin/tests/post-compact-resume-test.sh b/.claude-config/bin/tests/post-compact-resume-test.sh index be2f0c6..9ee126f 100755 --- a/.claude-config/bin/tests/post-compact-resume-test.sh +++ b/.claude-config/bin/tests/post-compact-resume-test.sh @@ -148,6 +148,21 @@ run_hook "$(compact_payload "$T/t1.jsonl")" && ok "with no snapshot the no-snapshot notice prints and the block follows it" || bad "no-snapshot case" "$out" printf '# Pre-compact snapshot\n' > "$SNAP" +# --- 5b. the resume text tells the agent to verify a DO NOT / HOLD line before trusting it --- +# A snapshot written before a compaction carries the previous session's DO NOT and HOLD +# lines, and an uncited one can be a guess that the next session would treat as a ruling. +# The text names the check (the cited operator message or doctrine, else the newest +# operator direction) and keeps the exceptions (standing instructions, real holds). +printf '# Pre-compact snapshot\n\nDO NOT touch the config.\n' > "$SNAP" +run_hook "$(compact_payload "$T/t1.jsonl")" +{ [ "$rc" -eq 0 ] && has 'verify a DO NOT' && has 'HOLD line against the operator message or doctrine it cites' \ + && has "the operator's newest direction" && has 'standing instructions and real operator holds'; } \ + && ok "with a snapshot the resume text asks for a DO NOT / HOLD line to be verified, and keeps standing instructions and real holds" \ + || bad "DO NOT / HOLD verification sentence missing" "$out" +run_hook "{\"source\":\"resume\",\"session_id\":\"s\",\"transcript_path\":\"$T/t1.jsonl\"}" +{ [ -z "$out" ] && [ "$rc" -eq 0 ]; } && ok "source=resume stays silent: no resume text, no guidance" || bad "resume source printed" "$out" +printf '# Pre-compact snapshot\n' > "$SNAP" + # --- 6. the cap, name hygiene, garbage lines -------------------------------------- names="$(python3 -I -c 'print(",".join("mcp__bulk__tool_%02d" % i for i in range(45)))')" tx "$T/t6.jsonl" "boundary 2 $names" diff --git a/.claude-config/bin/tests/remote-claude-targets-test.sh b/.claude-config/bin/tests/remote-claude-targets-test.sh new file mode 100755 index 0000000..f31a6fd --- /dev/null +++ b/.claude-config/bin/tests/remote-claude-targets-test.sh @@ -0,0 +1,161 @@ +#!/usr/bin/env bash +# remote-claude-targets-test.sh: the tmux targets the remote-session scripts pass are the +# right form for the command (remote-sessions/lib-remote-claude.sh, new-remote-claude.sh). +# +# Why: tmux resolves targets differently by command. A bare exact-session target "=NAME" +# is fine for has-session and kill-session, but send-keys with it fails ("can't find pane") +# on tmux 3.5a and 3.6, which dropped the launch line and left a bare shell that never became +# a Claude session, and display-message with it prints an empty value. Pane-level commands +# need "=NAME:" (exact session, current window). Both forms stay exact, so a name that is a +# prefix of a sibling's (Dev and Dev2) never reaches the sibling. +# +# Offline: `tmux` and `sleep` are shell functions here, so no tmux binary runs and nothing +# waits; each call's argv is logged and pinned. The real-server proof, with a prefix-sharing +# sibling, is remote-claude-tmux-test.sh. +# +# Pinned: for rc_launch (create and resume), rc_sweep, rc_archive and the already-running +# branch of new-remote-claude.sh, the exact argv of every tmux call; session-level commands +# take "=NAME", pane-level ones "=NAME:", and no -t target is ever bare. +# +# Every path (HOME, the registry, the archive, the env file) is a fixture under a temp dir. +# Usage: remote-claude-targets-test.sh (exit 0 all pass, 1 otherwise) +set -uo pipefail +HERE="$(cd "$(dirname "$0")" && pwd -P)" +RS="$HERE/../../remote-sessions" +[ -f "$RS/lib-remote-claude.sh" ] && [ -f "$RS/new-remote-claude.sh" ] || { echo "FAIL: remote-sessions scripts missing"; exit 1; } + +T="$(mktemp -d)"; export T; trap 'rm -rf "$T"' EXIT +pass=0; fail=0 +ok() { pass=$((pass+1)); echo "PASS: $1"; } +bad() { fail=$((fail+1)); echo "FAIL: $1"; [ $# -gt 1 ] && printf ' %s\n' "$2"; } + +echo "remote-claude-targets-test:" +mkdir -p "$T/home/.claude/projects/p" "$T/work" +unset TMUX +export HOME="$T/home" TMUX_TMPDIR="$T/tmuxtmp" RC_ENVFILE="$T/env.sh" RC_REGISTRY="$T/registry.tsv" \ + RC_ARCHIVE="$T/archive.tsv" RC_DEFAULT_WORKDIR="$T/work" TMUX_LOG="$T/tmux.log" +: > "$RC_ENVFILE" + +# The stub: logs one line per call (arguments joined by a unit separator so a space inside an +# argument stays visible), then answers the way a running tmux would. TMUX_HAS decides +# has-session (0 running, 1 not); TMUX_ATTACHED is what session_attached returns. +tmux() { + ( IFS=$'\037'; printf '%s\n' "$*" >> "$TMUX_LOG" ) + case "$1" in + has-session) return "${TMUX_HAS:-1}" ;; + new-session) [ "${TMUX_FAIL:-}" != create ]; return ;; + list-panes) [ "${TMUX_FAIL:-}" != pane ]; return ;; + send-keys) + if [ "$#" -eq 5 ]; then [ "${TMUX_FAIL:-}" != launch ] + else [ "${TMUX_FAIL:-}" != enter ]; fi + return ;; + display-message) case "$*" in *session_attached*) printf '%s\n' "${TMUX_ATTACHED:-0}" ;; *) printf '%s\n' "$T/work" ;; esac ;; + esac + return 0 +} +export -f tmux +sleep() { :; } # rc_launch waits 12 s for a real claude to start; nothing to wait for here +export -f sleep +# shellcheck source=/dev/null +. "$RS/lib-remote-claude.sh" +# the lib puts the system dirs first on PATH; a function still beats any binary +[ "$(type -t tmux)" = function ] || { echo "FAIL: the tmux stub is not in force; refusing to go on"; exit 1; } + +US=$'\037' +SID="11111111-2222-3333-4444-555555555555" +calls() { cat "$TMUX_LOG" 2>/dev/null; } +reset() { : > "$TMUX_LOG"; TMUX_HAS=1; TMUX_ATTACHED=0; } +line_is() { #