Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(redaction): scrub free-text tool results, keep readable payloads (#675)

tyj147454413-cmd9efd9a1581ad
diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.py
index 147e40410..2ae418d21 100644
--- a/agent/src/agent/loop.py
+++ b/agent/src/agent/loop.py
@@ -45,7 +45,7 @@ from src.providers.content_filter import (
)
from src.config.accessor import get_env_config
from src.tools.background_tools import get_background_manager
-from src.tools.redaction import redact_payload
+from src.tools.redaction import redact_payload, redact_tool_result
RUNS_DIR = Path(__file__).resolve().parents[2] / "runs"
SESSIONS_DIR = Path(__file__).resolve().parents[2] / "sessions"
@@ -203,24 +203,6 @@ def _record_llm_usage(
return normalized
-def _redact_trace_result(result: str) -> str:
- """Redact structured sensitive fields before persisting trace/event previews.
-
- Args:
- result: Raw tool result string.
-
- Returns:
- Redacted JSON string when ``result`` is JSON, otherwise the original
- text. Plain text is left unchanged because reliable free-text secret
- scrubbing would be more error-prone than helpful here.
- """
- try:
- payload = json.loads(result)
- except (TypeError, json.JSONDecodeError):
- return result
- return json.dumps(redact_payload(payload), ensure_ascii=False)
-
-
def _format_timeout(seconds: float) -> str:
"""Return a human-readable timeout label."""
if seconds < 1:
@@ -1488,7 +1470,9 @@ class AgentLoop:
truncated = result[:TOOL_RESULT_LIMIT]
messages.append(context.format_tool_result(tc.id, tc.name, truncated))
- trace_result = _redact_trace_result(result)
+ # One redaction feeds every subscriber below: the persisted trace
+ # record, the react trace, and the SSE preview.
+ trace_result = redact_tool_result(result)
trace.write_tool_result(
call_id=tc.id,
result=trace_result,
diff --git a/agent/src/swarm/worker.py b/agent/src/swarm/worker.py
index a7b5bbd31..a32abc33c 100644
--- a/agent/src/swarm/worker.py
+++ b/agent/src/swarm/worker.py
@@ -32,7 +32,7 @@ from src.swarm.models import (
)
from src.tools import build_swarm_registry
from src.tools.mcp import MCPRemoteTool
-from src.tools.redaction import is_sensitive_arg, redact_payload
+from src.tools.redaction import is_sensitive_arg, redact_payload, redact_tool_result
logger = logging.getLogger(__name__)
@@ -800,12 +800,13 @@ def _preview_tool_arguments(arguments: dict) -> dict[str, str]:
def _preview_tool_result(result: str) -> str:
- """Return a short, redacted result preview for streamed events."""
- try:
- parsed = json.loads(result)
- except (TypeError, ValueError):
- return _truncate_preview(result)
- return _truncate_preview(redact_payload(parsed))
+ """Return a short, redacted result preview for streamed events.
+
+ Delegates to the shared :func:`redact_tool_result` choke point so a
+ plain-text result is pattern-scrubbed instead of streamed raw (a JSON
+ result was already scrubbed by key).
+ """
+ return _truncate_preview(redact_tool_result(result))
def _truncate_preview(value: Any, *, limit: int = 200) -> str:
diff --git a/agent/src/tools/redaction.py b/agent/src/tools/redaction.py
index 87a359261..a874b6369 100644
--- a/agent/src/tools/redaction.py
+++ b/agent/src/tools/redaction.py
@@ -1,11 +1,13 @@
"""Shared redaction helpers (CWE-209/497, P10).
-Two independent concerns live here:
+Three independent concerns live here:
1. ``redact_internal_paths`` — replaces internal root prefixes with a
``'<redacted>'`` sentinel, keeping the relative tail. Caller-supplied or
external absolute paths stay intact for diagnosability; only our own
- topology is hidden. Idempotent and regex-free (zero ReDoS surface).
+ topology is hidden. Idempotent, regex-free (zero ReDoS surface), and
+ path-boundary aware: ``/Users/me`` redacts ``/Users/me/x`` and a bare
+ ``/Users/me`` but never the unrelated ``/Users/metest/x``.
2. ``redact_payload`` / ``is_sensitive_arg`` — recursively scrub sensitive
keys from structured tool-call payloads before they reach any event
stream, trace, or live audit ledger. Two key classes are scrubbed:
@@ -17,13 +19,26 @@ Two independent concerns live here:
Promoted from the swarm worker's private copies (#142) so
the swarm worker, the live-action audit, the main agent loop, and the
paper-trading surfaces all consume one shared implementation.
+ Classification is *sink aware*: :data:`ARGUMENTS_SINK` (the fail-closed
+ default, used for tool-call arguments and the audit ledger) and
+ :data:`RESULT_SINK` (tool results, where a ``content`` envelope is the
+ payload the trace exists to explain). See :data:`_RESULT_SAFE_KEYS`.
+3. ``redact_text`` / ``redact_tool_result`` — pattern scrub for free-form
+ text surfaces (plain-text tool results, shell output, error messages, log
+ lines) that :func:`redact_payload` cannot reach because it only walks
+ structured keys. :func:`redact_tool_result` is the single choke point for
+ a tool result: it dispatches JSON to the key walk and everything else to
+ the pattern scrub, so one call covers trace persistence and every event
+ preview.
"""
from __future__ import annotations
+import json
+import re
import sys
import sysconfig
-from functools import cache
+from functools import lru_cache
from pathlib import Path
from typing import Any
@@ -31,6 +46,14 @@ _SENTINEL = "<redacted>"
_REDACTED = "[redacted]"
+#: Sink identifiers for :func:`is_sensitive_arg` / :func:`redact_payload`.
+#: ``ARGUMENTS_SINK`` is both the default and the strict one, so a caller that
+#: forgets to pass a sink gets the strongest key set; only a caller that has
+#: reasoned about its surface opts into ``RESULT_SINK``. An unrecognized value
+#: degrades to the strict behaviour (fail closed).
+ARGUMENTS_SINK = "arguments"
+RESULT_SINK = "result"
+
#: Curated EXACT-MATCH PII / account-identifier field names (SPEC Consent §5 /
#: §8 #2). These are scrubbed in addition to the credential-marker keys below.
#: Matching is exact (normalized) on purpose: a broad ``"account"`` substring
@@ -75,6 +98,21 @@ _SENSITIVE_ARG_KEYS = {
_SENSITIVE_ARG_MARKERS = ("api_key", "authorization", "password", "secret", "token")
+#: Keys that stay sensitive in the ARGUMENTS / audit sink but are released in
+#: the tool-RESULT sink.
+#:
+#: ``content`` is the payload field of the ``read_file`` / ``read_document`` /
+#: ``read_url`` / ``load_skill`` result envelopes, so redacting it by name
+#: blanks out the very text a trace exists to explain — that is the real
+#: over-redaction this relaxation fixes. In the arguments sink the same key
+#: carries tool *input*: ``write_file(content=…)`` is a whole user document, a
+#: generated credential, or a private skill body, so it stays redacted there
+#: and in the live audit ledger.
+#:
+#: ``env`` is deliberately NOT here: its values are secrets in both directions
+#: (an env dump in a result leaks exactly what an env argument would).
+_RESULT_SAFE_KEYS = {"content"}
+
def _fold_key(name: str) -> str:
"""Fold a key to its alphanumeric core (lower-case, separators stripped).
@@ -98,17 +136,28 @@ def _fold_key(name: str) -> str:
#: folded candidate key so camelCase/kebab variants are caught too.
_SENSITIVE_ARG_KEYS_FOLDED = frozenset(_fold_key(k) for k in _SENSITIVE_ARG_KEYS)
_SENSITIVE_ARG_MARKERS_FOLDED = tuple(_fold_key(m) for m in _SENSITIVE_ARG_MARKERS)
+#: Folded form of :data:`_RESULT_SAFE_KEYS`. Exact (folded) match only, so
+#: ``secret_content`` / ``content_token`` keep redacting everywhere.
+_RESULT_SAFE_KEYS_FOLDED = frozenset(_fold_key(k) for k in _RESULT_SAFE_KEYS)
-@cache
-def _internal_roots() -> list[str]:
+@lru_cache(maxsize=8)
+def _internal_roots_for_cwd(cwd: str) -> tuple[str, ...]:
+ """Compute the internal root prefixes for one working directory.
+
+ Args:
+ cwd: Working directory to include among the roots (the cache key).
+
+ Returns:
+ Root prefixes, longest first, in both separator spellings.
+ """
# AGENT_DIR derived like agent/src/providers/llm.py:90
# (Path(__file__).resolve().parents[2]); redaction.py is agent/src/tools/
# so parents[2] == the agent/ dir. Anchor tracks layout, not hardcoded.
agent_dir = Path(__file__).resolve().parents[2]
cands = [
Path.home(),
- Path.cwd(),
+ Path(cwd),
agent_dir,
agent_dir.parent,
Path(sys.prefix),
@@ -123,23 +172,78 @@ def _internal_roots() -> list[str]:
roots.add(s)
roots.add(s.replace("\\", "/"))
roots.add(s.replace("/", "\\"))
- return sorted(roots, key=len, reverse=True)
+ return tuple(sorted(roots, key=len, reverse=True))
+
+
+def _internal_roots() -> list[str]:
+ """Return the internal root prefixes to hide, longest first.
+
+ Memoized per working directory rather than globally: a set cached on first
+ call would capture the then-current ``Path.cwd()`` and silently stop
+ redacting after an ``os.chdir``, while recomputing unconditionally would
+ re-run ``sysconfig.get_paths()`` for every redacted string on a tool-result
+ hot path. Keying the cache on the live cwd keeps both properties.
+
+ Returns:
+ Root prefixes sorted longest-first, so a nested root is replaced before
+ its parent.
+ """
+ return list(_internal_roots_for_cwd(str(Path.cwd())))
def redact_internal_paths(text: object) -> str:
- """Replace internal root prefixes with '<redacted>', keep relative tail."""
+ """Replace internal root prefixes with '<redacted>', keep relative tail.
+
+ Every occurrence of an internal root is replaced when it ends at a real
+ path boundary: a separator (``/Users/me/x`` → ``<redacted>/x``), the end of
+ the string (an exact root match — a bare cwd or home path is just as much
+ of a topology leak), or any other character that cannot continue a path
+ component (quote, comma, whitespace, closing bracket …). A root that is
+ merely a *name* prefix of a longer component (``/Users/metest/x``) is left
+ intact; that over-redaction is what the boundary check fixes.
+
+ Args:
+ text: Value to scrub. ``None`` becomes the empty string; non-strings
+ are coerced via :func:`str`.
+
+ Returns:
+ The scrubbed string. Idempotent — the sentinel contains no root, so
+ re-running never nests replacements.
+ """
if text is None:
return ""
s = text if isinstance(text, str) else str(text)
if not s:
return s
for root in _internal_roots():
- if root in s:
- s = s.replace(root, _SENTINEL)
+ if root not in s:
+ continue
+ out: list[str] = []
+ idx = 0
+ while (pos := s.find(root, idx)) >= 0:
+ end = pos + len(root)
+ nxt = s[end : end + 1]
+ after = s[end + 1 : end + 2]
+ # A path component continues on a word character, or on a
+ # ``.``/``-`` that is itself followed by one (``/Users/me.bak/x``
+ # is a different directory, while a trailing ``/Users/me.`` at the
+ # end of a sentence is still the root and must be redacted).
+ if nxt and (
+ nxt.isalnum()
+ or nxt == "_"
+ or (nxt in "-." and (after.isalnum() or after == "_"))
+ ):
+ out.append(s[idx:end])
+ else:
+ out.append(s[idx:pos])
+ out.append(_SENTINEL)
+ idx = end
+ out.append(s[idx:])
+ s = "".join(out)
return s
-def is_sensitive_arg(name: str) -> bool:
+def is_sensitive_arg(name: str, *, sink: str = ARGUMENTS_SINK) -> bool:
"""Return whether a tool-argument / payload key name should be redacted.
A key is sensitive when its normalized (stripped, lower-cased) form either
@@ -157,6 +261,11 @@ def is_sensitive_arg(name: str) -> bool:
Args:
name: Argument or payload key name to classify.
+ sink: Where the value is headed. :data:`ARGUMENTS_SINK` (the default)
+ is the strict set used for tool-call arguments and the live audit
+ ledger; :data:`RESULT_SINK` additionally releases the
+ :data:`_RESULT_SAFE_KEYS` result envelopes. Any other value is
+ treated as :data:`ARGUMENTS_SINK` (fail closed).
Returns:
``True`` when the key holds a credential, account number, or other PII
@@ -164,6 +273,9 @@ def is_sensitive_arg(name: str) -> bool:
surfacing.
"""
normalized = name.strip().lower()
+ folded = _fold_key(name)
+ if sink == RESULT_SINK and folded in _RESULT_SAFE_KEYS_FOLDED:
+ return False
if normalized in _SENSITIVE_ARG_KEYS or any(
marker in normalized for marker in _SENSITIVE_ARG_MARKERS
):
@@ -171,13 +283,12 @@ def is_sensitive_arg(name: str) -> bool:
# Separator-folded match catches camelCase / kebab / spaced variants
# (accountNumber, account-number, socialSecurityNumber) that the exact
# snake_case set would miss, without a broad substring over-redaction.
- folded = _fold_key(name)
return folded in _SENSITIVE_ARG_KEYS_FOLDED or any(
marker in folded for marker in _SENSITIVE_ARG_MARKERS_FOLDED
)
-def redact_payload(obj: Any) -> Any:
+def redact_payload(obj: Any, *, sink: str = ARGUMENTS_SINK) -> Any:
"""Recursively redact sensitive keys in a structured payload.
Walks dicts and lists; any dict value whose key :func:`is_sensitive_arg`
@@ -194,6 +305,12 @@ def redact_payload(obj: Any) -> Any:
Args:
obj: Arbitrary payload (dict / list / scalar) to scrub.
+ sink: Where the payload is headed; forwarded to
+ :func:`is_sensitive_arg`. In :data:`RESULT_SINK` the surviving
+ string leaves are additionally pattern-scrubbed with
+ :func:`redact_text`, because a JSON tool result routinely carries
+ free text (shell ``stdout``, error bodies) under a benign key that
+ no key-based rule can classify.
Returns:
A new structure of the same shape with sensitive values replaced. The
@@ -201,9 +318,148 @@ def redact_payload(obj: Any) -> Any:
"""
if isinstance(obj, dict):
return {
- key: _REDACTED if is_sensitive_arg(str(key)) else redact_payload(item)
+ key: _REDACTED
+ if is_sensitive_arg(str(key), sink=sink)
+ else redact_payload(item, sink=sink)
for key, item in obj.items()
}
if isinstance(obj, list):
- return [redact_payload(item) for item in obj]
+ return [redact_payload(item, sink=sink) for item in obj]
+ if sink == RESULT_SINK and isinstance(obj, str):
+ return redact_text(obj)
return obj
+
+
+#: Credential-shaped key names recognized in FREE TEXT. Longer alternatives
+#: come first so ``access_token`` is not clipped to ``token`` and
+#: ``secret_key`` is not clipped to ``secret``. The list is deliberately
+#: scoped to credential field names so a benign number in shell output (a
+#: price, a duration, a timestamp) is never mangled.
+#:
+#: All names are SINGULAR and ``\b``-anchored: a plural is a count or a
+#: collection, never a credential, and matching it mangles routine output
+#: (``tokens: 1204 in / 318 out`` from the LLM usage line, ``api_keys: 3``).
+_TEXT_CREDENTIAL_KEYS = (
+ r"api[_-]?key|api[_-]?secret|access[_-]?token|auth[_-]?token"
+ r"|refresh[_-]?token|bearer[_-]?token|id[_-]?token|session[_-]?token"
+ r"|client[_-]?secret|secret[_-]?key|private[_-]?key|app[_-]?secret"
+ r"|passphrase|password|passwd|authorization|secret|token"
+)
+
+#: Value shapes: a double-quoted string, a single-quoted string, or a bare
+#: token. The bare branch stops at whitespace, at list/dict/call punctuation
+#: and at quotes, so it can neither swallow a following JSON key nor — since
+#: ``[`` and ``]`` are excluded — re-match an inserted ``[redacted]``.
+_TEXT_VALUE = r"\"[^\"\n]*\"|'[^'\n]*'|[^\s,;{}\[\]()\"']+"
+
+#: ``key=value`` / ``key: value`` / ``"key": "value"`` credential pairs. The
+#: key may be quoted (JSON) as long as the quoting is symmetric, matched with a
+#: backreference. The negative lookahead keeps the substitution idempotent (an
+#: already-redacted value is skipped) and defers ``Bearer <jwt>`` to
+#: :data:`_TEXT_BEARER_PATTERN`, which would otherwise be consumed as the value
+#: and leave the token body visible.
+#:
+#: Every quantifier applies to a bounded character class, with no nesting and
+#: no overlapping alternatives, so matching stays linear (no ReDoS surface).
+_TEXT_KV_PATTERN = re.compile(
+ r"(?P<q>[\"']?)\b(?P<name>" + _TEXT_CREDENTIAL_KEYS + r")\b(?P=q)"
+ r"(?P<sep>\s*[:=]\s*)"
+ r"(?![\"']?" + re.escape(_REDACTED) + r"[\"']?|bearer\b)"
+ r"(?P<value>" + _TEXT_VALUE + r")",
+ re.IGNORECASE,
+)
+
+#: ``Authorization: Bearer <token>`` and bare ``bearer <token>`` header values.
+#: Applied before :data:`_TEXT_KV_PATTERN`; the value class excludes ``[`` so a
+#: second pass cannot match ``Bearer [redacted]``.
+_TEXT_BEARER_PATTERN = re.compile(
+ r"\b(?P<scheme>bearer)\s+(?P<value>[A-Za-z0-9._~+/-]+=*)",
+ re.IGNORECASE,
+)
+
+
+def _sub_credential_pair(match: re.Match[str]) -> str:
+ """Rebuild one ``key=value`` match with the value redacted.
+
+ Key and value quoting are preserved, so a redacted JSON fragment stays
+ parseable (``{"api_key": "[redacted]"}``) and a second pass produces the
+ identical string.
+
+ Args:
+ match: Match produced by :data:`_TEXT_KV_PATTERN`.
+
+ Returns:
+ The rebuilt ``key``/separator/sentinel fragment.
+ """
+ value = match.group("value")
+ quote = value[0] if value[:1] in ("'", '"') else ""
+ key_quote = match.group("q")
+ return (
+ f"{key_quote}{match.group('name')}{key_quote}{match.group('sep')}"
+ f"{quote}{_REDACTED}{quote}"
+ )
+
+
+def redact_text(text: object) -> str:
+ """Scrub credential-shaped values from a free-form string.
+
+ Used for plain-text tool results, shell output, error messages and log
+ lines where :func:`redact_payload` is a no-op (it only walks structured
+ keys). Bearer header values and ``key=value`` / ``key: value`` /
+ ``"key": "value"`` credential pairs are replaced with ``'[redacted]'``
+ while the surrounding text — labels, paths, error context — stays
+ readable.
+
+ Args:
+ text: Free-form string (or any object coerced via :func:`str`).
+ ``None`` becomes the empty string to match
+ :func:`redact_internal_paths`.
+
+ Returns:
+ The redacted string. Idempotent: redacting an already-redacted string
+ returns it unchanged. Never raises on non-string input.
+ """
+ if text is None:
+ return ""
+ s = text if isinstance(text, str) else str(text)
+ if not s:
+ return s
+ s = _TEXT_BEARER_PATTERN.sub(r"\g<scheme> " + _REDACTED, s)
+ return _TEXT_KV_PATTERN.sub(_sub_credential_pair, s)
+
+
+def redact_tool_result(result: object) -> str:
+ """Redact one tool result for trace persistence and event previews.
+
+ The single choke point for a tool-result string: callers redact once and
+ hand the same value to every subscriber (the persisted trace record, the
+ SSE preview, the react trace) instead of redacting per subscriber.
+
+ A JSON result goes through :func:`redact_payload` in the
+ :data:`RESULT_SINK`: sensitive keys are replaced by name, ``content``
+ envelopes stay readable, and the surviving free-text string leaves are
+ pattern-scrubbed — the common shape is a JSON envelope whose ``stdout`` /
+ ``error`` field holds raw output that no key-based rule can classify. A
+ non-JSON result is pattern-scrubbed directly. Each byte is processed by
+ exactly one of the two mechanisms; nothing is redacted twice.
+
+ Args:
+ result: Raw tool result (string, or any object coerced via
+ :func:`str`). ``None`` becomes the empty string.
+
+ Returns:
+ The redacted result as a string. JSON input comes back re-serialized
+ with ``ensure_ascii=False`` and default separators, so preview
+ consumers that grep the JSON shape (``"audit_id": "la_…"``) keep
+ matching.
+ """
+ if result is None:
+ return ""
+ text = result if isinstance(result, str) else str(result)
+ if not text:
+ return text
+ try:
+ payload = json.loads(text)
+ except (TypeError, ValueError):
+ return redact_text(text)
+ return json.dumps(redact_payload(payload, sink=RESULT_SINK), ensure_ascii=False)
diff --git a/agent/tests/test_redaction.py b/agent/tests/test_redaction.py
index f51955fe8..fd222203b 100644
--- a/agent/tests/test_redaction.py
+++ b/agent/tests/test_redaction.py
@@ -1,10 +1,37 @@
-"""G1 evidence: anchored redaction — no over-redaction, idempotent, None-safe."""
+"""G1 evidence: anchored redaction — no over-redaction, idempotent, None-safe.
+
+Covers ``redact_internal_paths`` (path-boundary aware root scrubbing) and
+``redact_text`` (pattern scrubbing for free-form text surfaces).
+"""
from __future__ import annotations
+import os
+import tempfile
from pathlib import Path
-from src.tools.redaction import _internal_roots, redact_internal_paths
+import pytest
+
+import src.tools.redaction as red_mod
+from src.tools.redaction import _internal_roots, redact_internal_paths, redact_text
+
+#: Short synthetic root used to test boundary behaviour deterministically,
+#: independent of the machine's home / venv layout.
+_SYNTHETIC_ROOT = "/data/internal_users"
+
+
+def _install_synthetic_root(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Add :data:`_SYNTHETIC_ROOT` to the internal root set for one test.
+
+ Args:
+ monkeypatch: pytest patcher (reverted automatically at teardown).
+ """
+ real_roots = _internal_roots()
+ monkeypatch.setattr(
+ red_mod,
+ "_internal_roots",
+ lambda: sorted({*real_roots, _SYNTHETIC_ROOT}, key=len, reverse=True),
+ )
def test_none_and_empty_and_nonstr_safe():
@@ -33,3 +60,137 @@ def test_idempotent():
once = redact_internal_paths(leak)
assert redact_internal_paths(once) == once
assert "<redacted>" in once
+
+
+def test_no_over_redaction_when_root_is_name_prefix_of_unrelated_path(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """``/data/internal_users`` must not redact ``/data/internal_users_test``.
+
+ A root that is only a *name* prefix of a longer path component is not an
+ ancestor, so the naive substring match over-redacted it.
+ """
+ unrelated = f"{_SYNTHETIC_ROOT}_test/data.csv"
+ assert not any(rt in unrelated for rt in _internal_roots())
+ _install_synthetic_root(monkeypatch)
+
+ assert redact_internal_paths(unrelated) == unrelated
+ # A real descendant of the same root still redacts.
+ assert redact_internal_paths(f"{_SYNTHETIC_ROOT}/x.csv") == "<redacted>/x.csv"
+
+
+ ("text", "expected"),
+ [
+ (_SYNTHETIC_ROOT, "<redacted>"), # exact match: the whole string
+ (f"cwd={_SYNTHETIC_ROOT}", "cwd=<redacted>"), # root ends the string
+ (f'"{_SYNTHETIC_ROOT}"', '"<redacted>"'), # quoted
+ (f"{_SYNTHETIC_ROOT}, next", "<redacted>, next"), # comma-terminated
+ (f"{_SYNTHETIC_ROOT}.", "<redacted>."), # sentence-final period
+ (f"{_SYNTHETIC_ROOT}/x.csv", "<redacted>/x.csv"), # descendant
+ (f"{_SYNTHETIC_ROOT}\\x.csv", "<redacted>\\x.csv"), # windows separator
+ (
+ f"a {_SYNTHETIC_ROOT}/x and {_SYNTHETIC_ROOT}/y",
+ "a <redacted>/x and <redacted>/y",
+ ), # every occurrence
+ ],
+)
+def test_root_is_redacted_at_every_real_boundary(
+ monkeypatch: pytest.MonkeyPatch,
+ text: str,
+ expected: str,
+) -> None:
+ """Regression: a root followed by a separator is NOT the only leak.
+
+ An exact root (a bare cwd/home path), a root at end of string, and a root
+ followed by punctuation all disclose internal topology and must redact —
+ matching only ``root + separator`` silently stopped redacting them.
+ """
+ _install_synthetic_root(monkeypatch)
+ assert redact_internal_paths(text) == expected
+
+
+def test_internal_roots_tracks_cwd_changes() -> None:
+ """``_internal_roots`` must reflect the live cwd, not the first one seen.
+
+ The root set is memoized per working directory; a globally cached set went
+ stale after ``os.chdir`` and silently stopped redacting the new cwd.
+ """
+ first_cwd = os.getcwd()
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ real_tmp = os.path.realpath(tmp_dir)
+ os.chdir(tmp_dir)
+ try:
+ with_cwd = _internal_roots()
+ finally:
+ os.chdir(first_cwd)
+ without_cwd = _internal_roots()
+
+ # ``Path.cwd()`` resolves symlinks (macOS /tmp → /private/tmp), so accept
+ # either spelling of the temporary directory.
+ assert real_tmp in with_cwd or tmp_dir in with_cwd
+ assert real_tmp not in without_cwd and tmp_dir not in without_cwd
+
+
+#: ``(raw, expected)`` credential shapes for :func:`redact_text`. Quoted
+#: values, quoted JSON keys and bearer tokens all bypassed the first pattern
+#: revision, so each shape is asserted exactly and re-checked for idempotence.
+_CREDENTIAL_SHAPES = (
+ ("api_key=abc123", "api_key=[redacted]"),
+ ('api_key="abc123"', 'api_key="[redacted]"'),
+ ("api_key='abc123'", "api_key='[redacted]'"),
+ ('{"api_key": "abc123"}', '{"api_key": "[redacted]"}'),
+ ("{'api_key': 'abc123'}", "{'api_key': '[redacted]'}"),
+ ("API_KEY = abc123", "API_KEY = [redacted]"),
+ ("access_token: abc.123-x", "access_token: [redacted]"),
+ ("client_secret=abc123", "client_secret=[redacted]"),
+ ("SECRET_KEY=deadbeef", "SECRET_KEY=[redacted]"),
+ ("passphrase: 'open sesame'", "passphrase: '[redacted]'"),
+ ("password: hunter2, user: bob", "password: [redacted], user: bob"),
+ ("authorization=raw-token-value", "authorization=[redacted]"),
+ ("Authorization: Bearer eyJhbGciOi.J9-_x==", "Authorization: Bearer [redacted]"),
+ ("bearer abc123", "bearer [redacted]"),
+)
+
+
[email protected](("raw", "expected"), _CREDENTIAL_SHAPES)
+def test_redact_text_scrubs_credential_shapes(raw: str, expected: str) -> None:
+ assert redact_text(raw) == expected
+
+
[email protected]("raw", [shape[0] for shape in _CREDENTIAL_SHAPES])
+def test_redact_text_is_idempotent(raw: str) -> None:
+ """Redacting twice must equal redacting once (previews are re-rendered)."""
+ once = redact_text(raw)
+ assert redact_text(once) == once
+ assert "[redacted]" in once
+
+
+ "raw",
+ [
+ "Backtest finished: sharpe=1.82, max_drawdown=-0.12",
+ "fetched 250 bars, timestamp=1699999999",
+ "GET /api/v1/orders 200 in 42ms",
+ "content=Quarterly revenue rose 12%",
+ "no separator after this token",
+ "tokens: 1204 in / 318 out", # plural = a count, not a credential
+ "api_keys: 3 configured",
+ ],
+)
+def test_redact_text_leaves_benign_output_readable(raw: str) -> None:
+ """Only credential-shaped ``key=value`` pairs are touched."""
+ assert redact_text(raw) == raw
+
+
+def test_redact_text_scrubs_every_line_of_multiline_output() -> None:
+ raw = "line1 api_key=one\nline2 clean\nline3 password: two"
+ assert redact_text(raw) == (
+ "line1 api_key=[redacted]\nline2 clean\nline3 password: [redacted]"
+ )
+
+
+def test_redact_text_none_and_empty_and_nonstr_safe() -> None:
+ assert redact_text(None) == ""
+ assert redact_text("") == ""
+ assert redact_text(42) == "42"
diff --git a/agent/tests/test_redaction_shared.py b/agent/tests/test_redaction_shared.py
index d62f2adb9..2394bb613 100644
--- a/agent/tests/test_redaction_shared.py
+++ b/agent/tests/test_redaction_shared.py
@@ -1,15 +1,32 @@
"""Shared redaction helpers promoted from the swarm worker (#142 → public).
-Covers ``redact_payload`` (recursive sensitive-key scrubbing) and
-``is_sensitive_arg`` (key-name classification), now consumed by the swarm
-worker and the live-action audit ledger from one module.
+Covers ``redact_payload`` (recursive sensitive-key scrubbing),
+``is_sensitive_arg`` (sink-aware key-name classification) and
+``redact_tool_result`` (the single tool-result choke point), now consumed by
+the swarm worker, the live-action audit ledger and the agent loop from one
+module. The end-to-end tests at the bottom drive the real ``AgentLoop`` +
+``TraceWriter`` and assert that a planted secret reaches neither the persisted
+trace nor an event preview.
"""
from __future__ import annotations
+import json
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
import pytest
-from src.tools.redaction import is_sensitive_arg, redact_payload
+from src.agent.context import ContextBuilder
+from src.agent.loop import AgentLoop
+from src.agent.trace import TraceWriter
+from src.tools.redaction import (
+ RESULT_SINK,
+ is_sensitive_arg,
+ redact_payload,
+ redact_tool_result,
+)
@pytest.mark.parametrize(
@@ -22,8 +39,8 @@ from src.tools.redaction import is_sensitive_arg, redact_payload
"passphrase",
"secret",
"headers",
- "content",
- "env",
+ "content", # write_file(content=…) — see the sink policy below
+ "env", # never released: env values are secrets in both directions
"api_token", # marker substring
"access_token", # marker substring
"x-authorization", # marker substring
@@ -34,6 +51,61 @@ def test_is_sensitive_arg_matches(key: str) -> None:
assert is_sensitive_arg(key) is True
[email protected]("key", ["content", "Content", "CONTENT", " content "])
+def test_content_is_released_in_the_result_sink_only(key: str) -> None:
+ """``content`` is tool *output* in a result and tool *input* in arguments.
+
+ In a result envelope (``read_file`` / ``read_document`` / ``read_url`` /
+ ``load_skill``) it is the very text the trace exists to explain, so
+ name-based redaction there is pure over-redaction. In the arguments sink
+ the same key is ``write_file(content=…)`` — a whole user document, a
+ generated credential, or a private skill body — so it stays redacted.
+ """
+ assert is_sensitive_arg(key) is True
+ assert is_sensitive_arg(key, sink=RESULT_SINK) is False
+
+
[email protected]("key", ["env", "ENV", "secret_content", "content_token"])
+def test_result_sink_releases_nothing_else(key: str) -> None:
+ """The relaxation is an exact (folded) match on ``content`` and nothing more.
+
+ ``env`` is never released — an env dump in a result leaks exactly what an
+ env argument would — and a compound name that merely contains ``content``
+ keeps its credential classification.
+ """
+ assert is_sensitive_arg(key) is True
+ assert is_sensitive_arg(key, sink=RESULT_SINK) is True
+
+
+def test_unknown_sink_falls_back_to_the_strict_key_set() -> None:
+ """An unrecognized sink must fail closed, never relax."""
+ assert is_sensitive_arg("content", sink="typo_sink") is True
+
+
+def test_redact_payload_arguments_sink_protects_write_file_content() -> None:
+ """The arguments sink is the leak this policy closes: raw ``content``
+ reaching the trace would persist whole documents / credentials."""
+ out = redact_payload({"path": "notes.md", "content": "SECRET DOC BODY"})
+ assert out == {"path": "notes.md", "content": "[redacted]"}
+
+
+def test_redact_payload_result_sink_keeps_content_but_scrubs_inside_it() -> None:
+ """A released ``content`` envelope is still pattern-scrubbed for secrets."""
+ out = redact_payload(
+ {
+ "status": "ok",
+ "content": "# Report\napi_key=leaked-in-doc",
+ "api_key": "raw-key",
+ },
+ sink=RESULT_SINK,
+ )
+ assert out == {
+ "status": "ok",
+ "content": "# Report\napi_key=[redacted]",
+ "api_key": "[redacted]",
+ }
+
+
@pytest.mark.parametrize(
"key",
[
@@ -139,3 +211,212 @@ def test_redact_payload_passes_through_scalars() -> None:
assert redact_payload("plain string") == "plain string"
assert redact_payload(42) == 42
assert redact_payload(None) is None
+
+
+# --------------------------------------------------------------------------- #
+# redact_tool_result — the single choke point for a tool result.
+# --------------------------------------------------------------------------- #
+
+
+def test_redact_tool_result_scrubs_json_keys_and_keeps_valid_json() -> None:
+ out = redact_tool_result(
+ json.dumps({"status": "ok", "api_key": "raw", "nested": {"token": "raw"}})
+ )
+ assert json.loads(out) == {
+ "status": "ok",
+ "api_key": "[redacted]",
+ "nested": {"token": "[redacted]"},
+ }
+
+
+def test_redact_tool_result_scrubs_free_text_inside_a_json_envelope() -> None:
+ """A JSON envelope routinely wraps raw output under a benign key.
+
+ ``bash_tool`` returns ``{"status", "exit_code", "stdout", "stderr"}``, so a
+ secret echoed by a shell command sits in ``stdout`` where no key-based rule
+ can see it. The result sink pattern-scrubs the surviving string leaves.
+ """
+ envelope = json.dumps(
+ {
+ "status": "ok",
+ "exit_code": 0,
+ "stdout": "api_key=shell-leak-1\nAuthorization: Bearer shell-leak-2\n",
+ }
+ )
+ out = redact_tool_result(envelope)
+ assert "shell-leak-1" not in out and "shell-leak-2" not in out
+ assert json.loads(out)["stdout"] == (
+ "api_key=[redacted]\nAuthorization: Bearer [redacted]\n"
+ )
+
+
+def test_redact_tool_result_scrubs_plain_text_results() -> None:
+ out = redact_tool_result("connection failed: api_key=plain-leak")
+ assert out == "connection failed: api_key=[redacted]"
+
+
+def test_redact_tool_result_keeps_document_content_readable() -> None:
+ """The over-redaction the sink policy fixes: a document envelope stays legible."""
+ out = redact_tool_result(
+ json.dumps({"status": "ok", "path": "a.md", "content": "# Q3\nRevenue +12%"})
+ )
+ assert json.loads(out)["content"] == "# Q3\nRevenue +12%"
+
+
+ "raw",
+ [
+ json.dumps({"api_key": "raw", "stdout": "password: raw"}),
+ "plain: client_secret='raw'",
+ json.dumps({"content": "Authorization: Bearer raw"}),
+ ],
+)
+def test_redact_tool_result_is_idempotent(raw: str) -> None:
+ once = redact_tool_result(raw)
+ assert redact_tool_result(once) == once
+
+
+def test_redact_tool_result_none_and_empty_safe() -> None:
+ assert redact_tool_result(None) == ""
+ assert redact_tool_result("") == ""
+
+
+# --------------------------------------------------------------------------- #
+# End-to-end: a planted secret must reach neither the persisted trace nor an
+# event preview, through the real AgentLoop + TraceWriter.
+# --------------------------------------------------------------------------- #
+
+_PLAINTEXT_KEY_SECRET = "pk-live-plaintext-9df3"
+_PLAINTEXT_BEARER_SECRET = "bearer-body-77aa"
+_PLAINTEXT_RESULT = (
+ "connect failed\n"
+ f'api_key="{_PLAINTEXT_KEY_SECRET}"\n'
+ f"Authorization: Bearer {_PLAINTEXT_BEARER_SECRET}\n"
+)
+_WRITE_FILE_DOC_SECRET = "PRIVATE DOC BODY 4b1c-do-not-persist"
+
+
+class _Tool:
+ is_readonly = False
+ repeatable = True
+
+
+class _StubRegistry:
+ """Minimal registry returning a canned result string."""
+
+ _tools: dict[str, Any] = {}
+
+ def __init__(self, result: str) -> None:
+ self._result = result
+
+ def get(self, tool_name: str) -> _Tool:
+ del tool_name
+ return _Tool()
+
+ def execute(self, tool_name: str, args: dict[str, Any]) -> str:
+ del tool_name, args
+ return self._result
+
+
+def _run_one_tool_call(
+ registry: _StubRegistry,
+ tc: SimpleNamespace,
+ run_dir: Path,
+) -> tuple[list[tuple[str, dict]], list[dict], list[dict]]:
+ """Drive one tool call through ``AgentLoop`` with a real ``TraceWriter``.
+
+ Args:
+ registry: Stub registry supplying the tool result.
+ tc: Tool call (``id`` / ``name`` / ``arguments``).
+ run_dir: Existing directory receiving ``trace.jsonl`` and sidecars.
+
+ Returns:
+ ``(events, messages, react_trace)`` — emitted SSE events, the
+ LLM-facing message list, and the react trace.
+ """
+ events: list[tuple[str, dict]] = []
+ agent = AgentLoop(
+ registry=registry, # type: ignore[arg-type]
+ llm=SimpleNamespace(),
+ max_iterations=1,
+ event_callback=lambda event_type, data: events.append((event_type, data)),
+ )
+ agent.memory.run_dir = str(run_dir)
+ trace = TraceWriter(run_dir)
+ messages: list[dict[str, Any]] = []
+ react_trace: list[dict[str, Any]] = []
+
+ agent._execute_single(tc, ContextBuilder, messages, trace, react_trace, 1)
+ trace.close()
+ return events, messages, react_trace
+
+
+def _persisted_text(run_dir: Path) -> str:
+ """Return every byte persisted under ``run_dir`` (trace JSONL + sidecars)."""
+ return "\n".join(
+ path.read_text(encoding="utf-8", errors="replace")
+ for path in sorted(run_dir.rglob("*"))
+ if path.is_file()
+ )
+
+
+def test_plaintext_result_secret_reaches_neither_trace_nor_preview(
+ tmp_path: Path,
+) -> None:
+ """A non-JSON tool result used to be persisted and streamed verbatim."""
+ run_dir = tmp_path / "run"
+ run_dir.mkdir()
+ tc = SimpleNamespace(id="tc_plain", name="fetch_quote", arguments={"symbol": "AAPL"})
+
+ events, messages, react_trace = _run_one_tool_call(
+ _StubRegistry(_PLAINTEXT_RESULT), tc, run_dir
+ )
+
+ persisted = _persisted_text(run_dir)
+ assert _PLAINTEXT_KEY_SECRET not in persisted
+ assert _PLAINTEXT_BEARER_SECRET not in persisted
+ assert "[redacted]" in persisted
+
+ entries = TraceWriter.read(run_dir, resolve_offloads=True)
+ tool_result = next(entry for entry in entries if entry["type"] == "tool_result")
+ assert 'api_key="[redacted]"' in tool_result["result"]
+ assert "Bearer [redacted]" in tool_result["result"]
+ # The failure context survives redaction — the trace stays diagnosable.
+ assert "connect failed" in tool_result["result"]
+
+ previews = [data["preview"] for event_type, data in events if event_type == "tool_result"]
+ assert previews, "expected a tool_result event"
+ for preview in previews + [item["result_preview"] for item in react_trace]:
+ assert _PLAINTEXT_KEY_SECRET not in preview
+ assert _PLAINTEXT_BEARER_SECRET not in preview
+
+ # Deliberate boundary: the LLM still receives the real result, because the
+ # model needs the unredacted text to act on it. Only persisted/streamed
+ # surfaces are scrubbed.
+ assert _PLAINTEXT_KEY_SECRET in messages[0]["content"]
+
+
+def test_write_file_content_argument_never_lands_in_the_trace(tmp_path: Path) -> None:
+ """``write_file(content=…)`` is the arguments-sink leak the policy closes."""
+ run_dir = tmp_path / "run"
+ run_dir.mkdir()
+ tc = SimpleNamespace(
+ id="tc_write",
+ name="write_file",
+ arguments={"path": "notes.md", "content": _WRITE_FILE_DOC_SECRET},
+ )
+
+ events, _, _ = _run_one_tool_call(
+ _StubRegistry(json.dumps({"status": "ok", "bytes_written": 42})), tc, run_dir
+ )
+
+ assert _WRITE_FILE_DOC_SECRET not in _persisted_text(run_dir)
+
+ entries = TraceWriter.read(run_dir, resolve_offloads=True)
+ tool_call = next(entry for entry in entries if entry["type"] == "tool_call")
+ assert tool_call["args"]["content"] == "[redacted]"
+ assert tool_call["args"]["path"] == "notes.md"
+
+ call_events = [data for event_type, data in events if event_type == "tool_call"]
+ assert call_events, "expected a tool_call event"
+ assert _WRITE_FILE_DOC_SECRET not in json.dumps(call_events, default=str)