HarnessRouter Community Edition: the self-hosted, Apache-2.0 edition of the unified interface for agent harnesses. Run Codex, Claude Code, Hermes, PI, DSH, and more through one API, with sessions, streaming, files, cancellation, and failure handling. Implements the Unified Harness Protocol (UHP), an open standard. Your keys, your infrastructure.
Python agent-apiagent-frameworkagent-harnessai-agentsai-infrastructurecoding-agentconformance-testingdeepseek-harnessharness-engineeringhermesllmopen-protocolopen-sourceopen-standardpi-coding-agentself-hosteduhpunified-apiunified-harness-protocolunified-interface
A turn's secrets are redacted in every form, and only from what the agent wrote (#422)
github-actions[bot]1835e95e2288
diff --git a/runner/server.py b/runner/server.pyindex 3bca9263..452ccb27 100644--- a/runner/server.py+++ b/runner/server.py@@ -463,19 +463,75 @@ _SCRUB_MIN = 8 # shorter values are not scrubbed: replacing "yes" everywhere wdef _turn_secrets(env: dict, names: list | None) -> list[str]:"""The values of a turn's environment that came through a reference (the gateway names them):- what the agent may read but the record may not carry. Longest first, so a value that contains- another is replaced whole."""- vals = {str(env[n]) for n in (names or []) if isinstance(n, str) and env.get(n) and len(str(env[n])) >= _SCRUB_MIN}+ what the agent may read but the record may not carry. Each also as JSON writes it inside a+ string, since a tool's output is often JSON text and there a quote, a backslash, a newline and+ a non-ASCII character are escaped. Longest first, so a value that contains another is replaced+ whole."""+ vals: set[str] = set()+ for n in names or []:+ v = env.get(n) if isinstance(n, str) else None+ if v and len(str(v)) >= _SCRUB_MIN:+ v = str(v)+ vals.update((v, json.dumps(v)[1:-1], json.dumps(v, ensure_ascii=False)[1:-1]))return sorted(vals, key=len, reverse=True)-def _scrub_secrets(text: str, secrets: list[str] | None) -> str:- """Every occurrence of a turn's secret values replaced in a serialized record. Applied where- the gateway reads the turn, so no event, result or error leaves the sandbox with one."""- for sec in secrets or []:- if sec and sec in text:- text = text.replace(sec, "[redacted]")- return text+# What redaction touches in a turn's answer: what the agent wrote (its text, its thinking, its tools'+# input and output, the result, the error), never the turn's own account of itself. A value that came+# through a $headers reference is chosen by whoever calls the harness, so it is a pattern the caller+# picks: redacted everywhere, it let a caller blank the turn's status, every event's type (which the+# gateway reads the transcript by) or a role, and erase its own transcript from the trace (reported+# privately, GHSA-7pwj-vv9r-rh2m). The turn's own fields are kept by POSITION, not by name anywhere:+# a tool's input is an arbitrary map, and a "type" inside it is the agent's content.+_ANSWER_CONTENT = ("result", "error", "reason", "handoff", "events")+_ANSWER_KEEP = {+ "event": frozenset({"type", "subtype", "session_id", "uuid", "parent_tool_use_id", "model", "usage", "modelUsage",+ "stop_reason"}),+ "message": frozenset({"type", "role", "id", "model", "usage", "stop_reason", "stop_sequence"}),+ "part": frozenset({"type", "id", "tool_use_id", "name"}),+}+_ANSWER_DEPTH = 64 # deeper than this, a structure is shown as a placeholder (see _redact_answer)+++def _redact_answer(out: dict, secrets: list[str] | None) -> dict:+ """A turn's answer as it leaves the runner: every secret value replaced in what the agent wrote,+ and nothing nested deeper than _ANSWER_DEPTH. A copy; the record itself is not changed.++ Walked as values, not as serialized text: the text form escapes a quote, a backslash, a newline+ and every non-ASCII character, so a secret holding one (a PEM key, a passphrase with a quote) was+ not found and went out whole (reported privately, GHSA-rmh9-whjx-gfrc). Walked with a stack, not+ recursion, and capped in depth: the agent chooses how deep its tool input nests, and an answer+ that cannot be serialized is a turn the gateway can never read."""+ secrets = [s for s in secrets or [] if s]+ root = dict(out)+ work = [(root, k, root[k], "events" if k == "events" else "", True, 1) for k in _ANSWER_CONTENT if k in root]+ while work:+ parent, key, val, role, scrub, depth = work.pop()+ if isinstance(val, str):+ if scrub:+ for sec in secrets:+ if sec in val:+ val = val.replace(sec, "[redacted]")+ parent[key] = val+ continue+ if not isinstance(val, (dict, list)):+ continue+ if depth > _ANSWER_DEPTH:+ parent[key] = "[nested too deeply to show]"+ continue+ if isinstance(val, dict):+ keep = _ANSWER_KEEP.get(role, frozenset())+ new = dict(val)+ for k, x in val.items():+ child = "message" if role == "event" and k == "message" else "parts" if role == "message" and k == "content" else ""+ work.append((new, k, x, child, scrub and k not in keep, depth + 1))+ else:+ new = list(val)+ child = "event" if role == "events" else "part" if role == "parts" else ""+ for i, x in enumerate(val):+ work.append((new, i, x, child, scrub, depth + 1))+ parent[key] = new+ return rootdef _child_env() -> dict:@@ -10423,8 +10479,7 @@ def _turn_answer(turn_id: str, rec: dict, since: int, held: bool) -> dict:"events": evs, "n_total": n, "elapsed": round(time.time() - rec["started"], 1)}if held:out["held"] = True- sec = rec.get("secrets")- return json.loads(_scrub_secrets(json.dumps(out, default=str), sec)) if sec else out+ return _redact_answer(out, rec.get("secrets"))@app.get("/turn/{turn_id}")diff --git a/runner/tests/test_answer_redaction.py b/runner/tests/test_answer_redaction.pynew file mode 100644index 00000000..642d5d6f--- /dev/null+++ b/runner/tests/test_answer_redaction.py@@ -0,0 +1,94 @@+"""A turn's answer leaves the runner without the turn's secret values, and with its own account intact.++Two private reports (GHSA-rmh9-whjx-gfrc, GHSA-7pwj-vv9r-rh2m). Redaction ran on the serialized+record: JSON escapes a quote, a backslash, a newline and every non-ASCII character there, so a secret+holding one was not found and went out whole. And it replaced every occurrence anywhere, while a+value from a $headers reference is chosen by the caller: a caller could blank the turn's status and+every event's type. Now the walk is over values, touches only what the agent wrote, and is capped+in depth so an answer can always be serialized.+"""+import asyncio+import json+import pathlib+import sys++import pytest++sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))+import server # noqa: E402++PEM = "-----BEGIN KEY-----\nMIIBVQIBADANBgkqhkiG\n-----END KEY-----"+AWKWARD = ["sk-plain-ABC123", 'sk-"quoted"-XYZ', "sk-back\\slash", PEM, "sk-паролата-42"]+++def _read(monkeypatch, rec: dict) -> dict:+ base = {"status": "completed", "done": True, "backend": "claude", "model": "claude-sonnet-5.5", "started": 0.0,+ "session_id": "sess-1", "events": []}+ monkeypatch.setitem(server._turns, "turn_r", {**base, **rec})+ return asyncio.run(server.get_turn("turn_r"))+++def _event(text: str, tool_input) -> list[dict]:+ return [{"type": "assistant", "session_id": "sess-1", "message": {"role": "assistant", "model": "claude-sonnet-5.5",+ "content": [{"type": "text", "text": text},+ {"type": "tool_use", "id": "tu_1", "name": "Bash", "input": tool_input}]}},+ {"type": "user", "message": {"role": "user", "content": [+ {"type": "tool_result", "tool_use_id": "tu_1", "content": [{"type": "text", "text": text}]}]}},+ {"type": "result", "subtype": "success", "result": text, "usage": {"input_tokens": 10, "output_tokens": 5}}]++[email protected]("secret", AWKWARD)+def test_no_secret_leaves_in_any_form(monkeypatch, secret):+ secrets = server._turn_secrets({"TOKEN": secret}, ["TOKEN"])+ as_json = json.dumps({"key": secret}) # the agent ran `cat config.json`: the secret, escaped+ text = f"env says {secret}; the file says {as_json}"+ out = _read(monkeypatch, {"result": text, "error": text, "reason": text, "handoff": {"note": text},+ "events": _event(text, {"command": f"echo {secret}", "type": secret}), "secrets": secrets})+ wire = json.dumps(out, ensure_ascii=False) + json.dumps(out)+ for form in (secret, json.dumps(secret)[1:-1], json.dumps(secret, ensure_ascii=False)[1:-1]):+ assert form not in wire, form+ assert out["result"].startswith("env says [redacted]; the file says")+ assert out["events"][0]["message"]["content"][1]["input"] == {"command": "echo [redacted]", "type": "[redacted]"}+++def test_a_caller_chosen_value_cannot_rewrite_the_turns_own_account(monkeypatch):+ """A $headers value is the caller's choice: it is redacted from what the agent wrote, and the+ turn's status, event types, roles, model, session, tool names and usage stay what they were."""+ picked = ["assistant", "completed", "input_tokens", "tool_result", "claude-sonnet-5.5", "success", "sess-1", "Bash"]+ secrets = server._turn_secrets({f"V{i}": v for i, v in enumerate(picked)}, [f"V{i}" for i in range(len(picked))])+ out = _read(monkeypatch, {"result": "the assistant completed", "events": _event("the assistant completed", {"c": "x"}),+ "secrets": secrets})+ assert out["status"] == "completed" and out["model"] == "claude-sonnet-5.5" and out["session_id"] == "sess-1"+ ev = out["events"]+ assert [e["type"] for e in ev] == ["assistant", "user", "result"] and ev[2]["subtype"] == "success"+ assert ev[0]["message"]["role"] == "assistant" and ev[0]["message"]["model"] == "claude-sonnet-5.5"+ assert ev[0]["session_id"] == "sess-1" and ev[0]["message"]["content"][1]["name"] == "Bash"+ assert ev[1]["message"]["content"][0]["type"] == "tool_result" and ev[1]["message"]["content"][0]["tool_use_id"] == "tu_1"+ assert ev[2]["usage"] == {"input_tokens": 10, "output_tokens": 5}+ assert out["result"] == "the [redacted] [redacted]" # what the agent wrote is still redacted+ assert ev[0]["message"]["content"][0]["text"] == "the [redacted] [redacted]"+++def test_a_deeply_nested_answer_is_still_readable(monkeypatch):+ deep: dict = {"leaf": "tok_0123456789abcdef"}+ for _ in range(20000):+ deep = {"d": deep}+ out = _read(monkeypatch, {"events": _event("ok", deep), "secrets": ["tok_0123456789abcdef"]})+ wire = json.dumps(out) # serializable: the gateway can read the turn+ assert "[nested too deeply to show]" in wire and "tok_0123456789abcdef" not in wire+ assert out["status"] == "completed" and out["events"][0]["message"]["content"][0]["text"] == "ok"+++def test_reading_a_turn_leaves_its_record_as_it_was(monkeypatch):+ rec = {"result": "x tok_0123456789abcdef", "events": _event("y tok_0123456789abcdef", {"c": 1}),+ "secrets": ["tok_0123456789abcdef"]}+ _read(monkeypatch, rec)+ stored = server._turns["turn_r"]+ assert stored["result"] == "x tok_0123456789abcdef"+ assert stored["events"][0]["message"]["content"][0]["text"] == "y tok_0123456789abcdef"+++def test_a_turn_without_secrets_is_answered_as_written(monkeypatch):+ out = _read(monkeypatch, {"result": 'a "quoted" line\nand ünïcode', "events": _event("plain", {"n": [1, 2.5, None, True]})})+ assert out["result"] == 'a "quoted" line\nand ünïcode'+ assert out["events"][0]["message"]["content"][1]["input"] == {"n": [1, 2.5, None, True]}