From d205cef41886b490a569e817d9a8a8f49181af58 Mon Sep 17 00:00:00 2001 From: shehjaddev Date: Mon, 14 Sep 2026 11:34:56 +0600 Subject: [PATCH] fix(redact): mask assignments in secret-bearing file reads MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit read_file/search_files passed file_read=True, which folded into code_file=True and skipped the ENV/JSON/YAML assignment passes, so an opaque prefix-less credential under a credential-shaped key reached the model in cleartext from a secret-bearing file — the file-read half of the #110228 gate (#110567). Two defects on that path, both fixed here: - The rendered line-number gutter ("5| ADS_API_TOKEN: ..." from read_file, "6: ADS_API_TOKEN: ..." from grep -n / cat -n) defeated the line-anchored patterns, so the real rendered read leaked exactly what the raw text masked. A gutter-free fixture cannot see this, which is why the tool-level tests carry the real render shape. - _is_secret_file_arg() could not see the RESOLVED Hermes home: the default home's basename is an installation detail (".hermes" on POSIX, "hermes" under AppData/Local on Windows) and a resolved path never spells $HERMES_HOME, so the managed Windows home's config.yaml was classified as ordinary YAML on both the file-read and the terminal surface. Changes: - redact_sensitive_text(): secret_file= re-enables the assignment passes for content the caller classified with _is_secret_file_arg, keeping code_file behaviour everywhere else. It is authoritative over code_file, so a caller cannot be fail-open on the security flag by setting both. - _redact_assignments(): mask_nonreusable selects the non-reusable sentinel for file reads, so the #35519 write-back hazard stays closed. - _should_redact_assignment(): no longer re-masks an already-masked value, which was erasing the vendor label the sentinel deliberately keeps. - _is_secret_file_arg(): consult the resolved Hermes home for the config.yaml arm. - _CFG_ANCHORED_RE / _YAML_ASSIGN_RE: tolerate a rendered line-number gutter. - file_tools.py: classify the resolved path at all three file-read call sites. Closes #110567 --- agent/redact.py | 91 ++++++++++++++++---- contributors/emails/hello@shehjad.dev | 2 + tests/agent/test_redact.py | 118 ++++++++++++++++++++++++++ tests/tools/test_file_tools.py | 89 +++++++++++++++++++ tools/file_tools.py | 32 +++++-- 5 files changed, 307 insertions(+), 25 deletions(-) create mode 100644 contributors/emails/hello@shehjad.dev diff --git a/agent/redact.py b/agent/redact.py index 0479640e0b..ea29cfc039 100644 --- a/agent/redact.py +++ b/agent/redact.py @@ -230,6 +230,8 @@ _ENV_ASSIGN_LOWER_RE = re.compile( # bare secret-word key only at line start (optionally after ``export``), so conversational ``I have # password=foo`` mid-sentence is left alone. _SECRET_CFG_NAMES = r"(?:api[ _.\-]?key|token|secret|passwd|password|credential|auth)" +# Rendered line-number prefix (``5|line`` from read_file, ``6:line`` from grep -n / cat -n). +_LINE_NUMBER_GUTTER = r"[0-9]+[|:][ \t]*" _CFG_VALUE = r"(['\"]?)([^\s&]+?)\2(?=[\s&]|$)" # Linear pre-gate for the _CFG_*_RE subs: no secret keyword => neither can match. _CFG_SECRET_WORD_RE = re.compile(_SECRET_CFG_NAMES, re.IGNORECASE) @@ -250,8 +252,12 @@ _CFG_DOTTED_RE = re.compile( re.IGNORECASE, ) # Line-anchored bare key: ``password=…`` / ``export api_key=…`` at start of line. +# ``{_LINE_NUMBER_GUTTER}``: line-numbered dumps put the key behind a rendered gutter — +# ``read_file`` emits ``5| ADS_API_TOKEN: …`` and ``grep -n`` / ``cat -n`` emit +# ``6: ADS_API_TOKEN: …``. Anchored at ``^`` without it, none of those matched, so the +# rendered read of a secret-bearing file leaked what the raw text masked. _CFG_ANCHORED_RE = re.compile( - rf"(^[ \t]*(?:export[ \t]+)?[A-Za-z0-9_\-]*{_SECRET_CFG_NAMES}[A-Za-z0-9_\-]*)={_CFG_VALUE}", + rf"(^(?:[ \t]*{_LINE_NUMBER_GUTTER})?[ \t]*(?:export[ \t]+)?[A-Za-z0-9_\-]*{_SECRET_CFG_NAMES}[A-Za-z0-9_\-]*)={_CFG_VALUE}", re.IGNORECASE | re.MULTILINE, ) @@ -264,7 +270,7 @@ _CFG_ANCHORED_RE = re.compile( # stays backtrackable (see _CFG_DOTTED_RE). _YAML_CFG_NAMES = r"(?:api[ _.\-]?key|token|secret|passwd|password|credential)" _YAML_ASSIGN_RE = re.compile( - rf"(^[ \t]*+[A-Za-z0-9_.\-]*{_YAML_CFG_NAMES}[A-Za-z0-9_.\-]*+)(:[ \t]*+)(?!['\"])([^\s&]++)", + rf"(^(?:[ \t]*+{_LINE_NUMBER_GUTTER})?[ \t]*+[A-Za-z0-9_.\-]*{_YAML_CFG_NAMES}[A-Za-z0-9_.\-]*+)(:[ \t]*+)(?!['\"])([^\s&]++)", re.IGNORECASE | re.MULTILINE, ) @@ -357,6 +363,11 @@ def _should_redact_assignment(key: str, value: str, *, check_keyword: bool) -> b # a code snippet, not a leaked secret value. if _ENV_LOOKUP_VALUE_RE.match(value): return False + # An earlier pass already masked this value (``***`` or the ``«redacted:…»`` sentinel). Masking it + # again only erases what the sentinel deliberately kept — the vendor label (``Digest ***`` → + # ``***``, ``«redacted:ghp_…»`` → ``«redacted-secret»``). Same guard _redact_python_repr_fields uses. + if value == "***" or value.startswith("«redacted"): + return False if check_keyword and not _key_has_secret_keyword(key): return False return (_has_word_bounded_keyword(key, _STRONG_KEY_KEYWORD_RE) @@ -733,12 +744,18 @@ def _assignment_sub(render, *, check_keyword: bool): return _sub -def _redact_assignments(text: str) -> str: +def _redact_assignments(text: str, *, mask_nonreusable: bool = False) -> str: """ENV / config / JSON / YAML assignment passes (skipped for code files). Passes that would match ``token=``/``key=`` URL params skip ``://`` text (web-URL query - params are intentionally passed through, see redact_sensitive_text).""" + params are intentionally passed through, see redact_sensitive_text). + + ``mask_nonreusable`` masks the assignments with the ``«redacted:…»`` sentinel that + ``file_read=True`` already uses for prefix-matched credentials. Without it an agent + that read a secret-bearing file would hold a head/tail mask shaped like a real but + truncated key and could write it back as a dead credential (#35519).""" + mask = _mask_token_nonreusable if mask_nonreusable else _mask_token if "=" in text: - _redact_env = _assignment_sub(lambda g: f"{g[0]}={g[1]}{_mask_token(g[2])}{g[1]}", check_keyword=True) + _redact_env = _assignment_sub(lambda g: f"{g[0]}={g[1]}{mask(g[2])}{g[1]}", check_keyword=True) text = _ENV_ASSIGN_RE.sub(_redact_env, text) if "://" not in text: # lowercase names would match URL params # Skip URLs — the query string may contain ``token=``/``key=`` params that are intentionally @@ -761,7 +778,7 @@ def _redact_assignments(text: str) -> str: if ":" in text and '"' in text: text = _JSON_FIELD_RE.sub( - _assignment_sub(lambda g: f'{g[0]}: "{_mask_token(g[1])}"', check_keyword=False), text) + _assignment_sub(lambda g: f'{g[0]}: "{mask(g[1])}"', check_keyword=False), text) # Python mapping repr fields ({'API_KEY': '…'}): single-quoted, so the JSON rule # above never sees them — the traceback / pytest-introspection leak shape. @@ -771,7 +788,7 @@ def _redact_assignments(text: str) -> str: # YAML after JSON: quoted values are handled there (_YAML_ASSIGN_RE skips quotes). if ":" in text and "://" not in text: text = _YAML_ASSIGN_RE.sub( - _assignment_sub(lambda g: f"{g[0]}{g[1]}{_mask_token(g[2])}", check_keyword=True), text) + _assignment_sub(lambda g: f"{g[0]}{g[1]}{mask(g[2])}", check_keyword=True), text) return text @@ -795,7 +812,8 @@ def _redact_phone(m): def redact_sensitive_text(text: str, *, force: bool = False, code_file: bool = False, - file_read: bool = False, redact_url_credentials: bool = False) -> str: + file_read: bool = False, secret_file: bool = False, + redact_url_credentials: bool = False) -> str: """Apply all redaction patterns to a block of text. Safe on any string. Enabled by default (``security.redact_secrets: false`` @@ -807,10 +825,9 @@ def redact_sensitive_text(text: str, *, force: bool = False, code_file: bool = F magic-link / pre-signed URLs must survive ordinary tool flows unchanged. ``code_file=True``: skip the ENV/JSON assignment passes for known source code (``MAX_TOKENS=***``, ``"apiKey": "test"`` fixtures). ``file_read=True`` - (implies code_file): prefix-matched credentials become a non-reusable - sentinel (``«redacted:ghp_…»``) instead of a head/tail mask an agent could - write back into config.yaml as a dead credential. - + (implies code_file unless ``secret_file``): prefix-matched credentials become a + non-reusable sentinel (``«redacted:ghp_…»``) instead of a head/tail mask an agent + could write back into config.yaml as a dead credential. Every regex sits behind a cheap substring gate that its pattern requires, so the gates are never false-negative. @@ -822,6 +839,17 @@ def redact_sensitive_text(text: str, *, force: bool = False, code_file: bool = F mask looked like a real-but-truncated key, so an agent reading it from config.yaml and writing it back silently corrupted the stored credential into a dead 13-char value → 401 (issue #35519). The sentinel is syntactically invalid as a token, so it can't be mistaken for a usable key or written back as one. + + Set ``secret_file=True`` when the caller has already classified the SOURCE as secret-bearing + (``_is_secret_file_arg``: command reads on the terminal side, resolved tool paths on the + file side). It re-enables the ENV/JSON/YAML assignment passes that ``file_read`` would + otherwise skip, so an opaque prefix-less credential assigned to a credential-shaped key is + masked instead of passed through in cleartext (issue #110567). With ``file_read=True`` those + assignments are masked with the non-reusable sentinel, so the #35519 write-back hazard stays + closed. ``secret_file`` is authoritative: it wins over ``code_file``, so a caller cannot be + fail-open by setting both. Files that are not secret-bearing (any source file, a project's own + ``config.yaml``) keep the code_file behaviour: ``MAX_TOKENS: 100`` and ``"apiKey": "test"`` + fixtures are untouched. """ if text is None: return None @@ -832,7 +860,9 @@ def redact_sensitive_text(text: str, *, force: bool = False, code_file: bool = F text = redact_registered_vault_values(text) if not (force or _redact_enabled()): return text - code_file = code_file or file_read + # ``secret_file`` is authoritative: a caller that classified the source as secret-bearing must not + # be silently fail-open because another flag (code_file, or file_read implying it) was also set. + code_file = (code_file or file_read) and not secret_file # Control/zero-width chars can split a token body so _PREFIX_RE alone misses it. if _has_known_prefix_substring(text): @@ -845,7 +875,7 @@ def redact_sensitive_text(text: str, *, force: bool = False, code_file: bool = F text = _PREFIX_RE.sub(lambda m: _prefix_sub(m.group(1)), text) if not code_file: - text = _redact_assignments(text) + text = _redact_assignments(text, mask_nonreusable=file_read) if "uthorization" in text or "UTHORIZATION" in text: # cheapest gate over every casing text = _AUTH_HEADER_RE.sub(lambda m: m.group(1) + (m.group(2) or "") + _mask_token(m.group(3)), text) @@ -950,9 +980,36 @@ def _command_segments(command: str) -> list[str]: return segments +def _is_under_hermes_home(path: str) -> bool: + """True when an absolute ``config.yaml`` path sits under the active Hermes home or root. + + The default home's basename is an installation detail — ``.hermes`` on POSIX, ``hermes`` + under ``AppData/Local`` on Windows — and a resolved path never spells ``$HERMES_HOME``, + so the literal-segment test in ``_is_secret_file_arg`` cannot see a native Windows path. + Compare against the resolved homes instead. Only reached for a ``config.yaml`` basename, + so the resolve cost stays off the per-token command scan. + """ + from agent.file_safety import _hermes_dirs + + try: + target = os.path.normcase(os.path.realpath(os.path.expanduser(path))) + except (OSError, ValueError): + return False + for home in _hermes_dirs(): + try: + base = os.path.normcase(os.path.realpath(str(home))) + except (OSError, ValueError): + continue + if target == base or target.startswith(base + os.sep): + return True + return False + + def _is_secret_file_arg(arg: str) -> bool: """``.env``-style or shell rc basename anywhere; ``config.yaml`` only under a - ``.hermes`` directory or ``$HERMES_HOME`` (never arbitrary YAML).""" + ``.hermes`` directory, ``$HERMES_HOME``, or the resolved Hermes home (never arbitrary + YAML). The resolved-home arm is what covers native Windows, where the home directory + is ``%LOCALAPPDATA%\\hermes`` and carries no ``.hermes`` segment.""" path = arg.strip("\"'").replace("\\", "/") hermes_home = False for prefix in _HERMES_HOME_PREFIXES: @@ -971,7 +1028,9 @@ def _is_secret_file_arg(arg: str) -> bool: return False if parts[-1] in _ENV_FILE_BASENAMES or parts[-1] in _SHELL_RC_BASENAMES: return True - return parts[-1] == "config.yaml" and (hermes_home or ".hermes" in parts[:-1]) + if parts[-1] != "config.yaml": + return False + return hermes_home or ".hermes" in parts[:-1] or _is_under_hermes_home(path) def _command_reads_secret_file(command: str | None) -> bool: diff --git a/contributors/emails/hello@shehjad.dev b/contributors/emails/hello@shehjad.dev new file mode 100644 index 0000000000..dbf41f6333 --- /dev/null +++ b/contributors/emails/hello@shehjad.dev @@ -0,0 +1,2 @@ +shehjaddev +# redact: file-read half of #110228 (#110567) diff --git a/tests/agent/test_redact.py b/tests/agent/test_redact.py index 3df2b82879..693f43cb78 100644 --- a/tests/agent/test_redact.py +++ b/tests/agent/test_redact.py @@ -1245,6 +1245,124 @@ class TestFileReadNonReusableRedaction: +class TestSecretFileAssignmentRedaction: + """#110567: the file-read half of the #110228 gate. + + ``read_file`` / ``search_files`` pass ``file_read=True``, which folded into ``code_file=True`` + and skipped the ENV/JSON/YAML assignment passes — so an opaque, prefix-less credential under a + credential-shaped key reached the model in cleartext from a secret-bearing file, while the + terminal read of the same file masked it. Callers now classify the resolved path with + ``_is_secret_file_arg`` and pass ``secret_file=True``. + """ + + SYNTH = "3JcQ1UqZ8mNp4Rt6vWx2Yb9Ad0Ef7Gh5Ij2kS" # 40-char opaque, no vendor prefix + + @pytest.mark.parametrize("template", [ + "ADS_API_TOKEN: {tok}", # YAML assignment + "export FOO_TOKEN='{tok}'", # shell rc / profile + "FOO_API_KEY={tok}", # dotenv + '{{"api_key": "{tok}"}}', # JSON field + ]) + def test_opaque_assignment_masked_in_secret_file(self, template): + out = redact_sensitive_text( + template.format(tok=self.SYNTH), force=True, file_read=True, secret_file=True) + assert self.SYNTH not in out + assert "«redacted" in out + + def test_opaque_mask_is_non_reusable(self): + """No head/tail characters: the value must not look like a truncated-but-real key (#35519).""" + out = redact_sensitive_text( + f"ADS_API_TOKEN: {self.SYNTH}", force=True, file_read=True, secret_file=True) + assert out.split(": ", 1)[1].strip() == "«redacted-secret»" + + def test_vendor_prefix_label_survives(self): + """The assignment pass must not re-mask what the prefix pass already masked; re-masking + erases the vendor label the sentinel deliberately keeps.""" + token = "ghp_S1abcdefghijklmnopqrstuvwxyz0Pn2T" + out = redact_sensitive_text( + f"GITHUB_TOKEN: {token}", force=True, file_read=True, secret_file=True) + assert token not in out + assert "«redacted:ghp_…»" in out + + def test_unclassified_read_keeps_code_file_behaviour(self): + """``secret_file`` defaults off: a read the classifier did not flag is byte-identical to + the pre-fix behaviour, so source dumps and fixtures are never mangled.""" + for text in ("MAX_TOKENS: 100", '{"apiKey": "test"}', "api_key: test", + f"5|ADS_API_TOKEN: {self.SYNTH}"): + assert redact_sensitive_text(text, force=True, file_read=True) == text + + @pytest.mark.parametrize("gutter", ["5|", "108:", " 7| ", "12: "]) + def test_rendered_line_number_gutter_does_not_block_masking(self, gutter): + """read_file renders ``5|line`` and grep -n / cat -n render ``6:line``. The assignment + passes anchor at line start, so without gutter tolerance the rendered read of a + secret-bearing file leaked exactly what the raw text masked.""" + text = f"{gutter} ADS_API_TOKEN: {self.SYNTH}" + out = redact_sensitive_text(text, force=True, file_read=True, secret_file=True) + assert self.SYNTH not in out + assert out.startswith(gutter), "the rendered gutter must survive redaction" + + def test_rendered_gutter_keeps_non_secret_scalars(self): + text = "5|MAX_TOKENS: 100" + assert redact_sensitive_text(text, force=True, file_read=True, secret_file=True) == text + + def test_secret_file_is_authoritative_over_code_file(self): + """A caller that sets both must not be silently fail-open on a security flag.""" + text = f"ADS_API_TOKEN: {self.SYNTH}" + assert self.SYNTH not in redact_sensitive_text( + text, force=True, code_file=True, secret_file=True) + assert self.SYNTH not in redact_sensitive_text( + text, force=True, code_file=True, file_read=True, secret_file=True) + + def test_secret_file_keeps_non_secret_scalars(self): + text = f"ADS_API_TOKEN: {self.SYNTH}\nMAX_TOKENS: 100\n" + out = redact_sensitive_text(text, force=True, file_read=True, secret_file=True) + assert self.SYNTH not in out + assert "MAX_TOKENS: 100" in out + + +class TestHermesHomePathClassification: + """#110567: ``_is_secret_file_arg`` must see the RESOLVED Hermes home. + + The default home's basename is an installation detail — ``.hermes`` on POSIX, ``hermes`` + under ``AppData/Local`` on Windows — and a resolved path never spells ``$HERMES_HOME``, so + the literal-segment test alone classified the managed Windows home's ``config.yaml`` as + ordinary YAML (the file-read half AND the terminal half were both blind there). + """ + + @pytest.fixture + def hermes_home(self, tmp_path, monkeypatch): + import agent.file_safety as file_safety + + home = tmp_path / "hermes" # no ".hermes" segment, like %LOCALAPPDATA%\hermes + monkeypatch.setattr(file_safety, "_hermes_home_path", lambda: home) + monkeypatch.setattr(file_safety, "_hermes_root_path", lambda: home) + return home + + def test_resolved_home_config_is_secret_bearing(self, hermes_home): + from agent.redact import _is_secret_file_arg + + assert _is_secret_file_arg(str(hermes_home / "config.yaml")) + assert _is_secret_file_arg(str(hermes_home / "profiles" / "coder" / "config.yaml")) + assert _is_secret_file_arg(str(hermes_home / ".env")) + + def test_ordinary_files_are_not_secret_bearing(self, hermes_home, tmp_path): + from agent.redact import _is_secret_file_arg + + assert not _is_secret_file_arg(str(tmp_path / "proj" / "config.yaml")) + assert not _is_secret_file_arg(str(tmp_path / "proj" / "src" / "app.py")) + assert not _is_secret_file_arg("config.yaml") # relative, not resolvable to the home + + def test_terminal_read_of_resolved_home_masks_opaque_token(self, hermes_home): + from agent.redact import _command_reads_secret_file, redact_terminal_output + + config = hermes_home / "config.yaml" + if " " in str(config): + pytest.skip("paths with spaces are not tokenizable by the command scanner") + syn = "3JcQ1UqZ8mNp4Rt6vWx2Yb9Ad0Ef7Gh5Ij2kS" + assert _command_reads_secret_file(f"type {config}") + assert syn not in redact_terminal_output(f"ADS_API_TOKEN: {syn}", f"type {config}") + + class TestFireworksToken: KEY = "fw_" + "A" * 40 diff --git a/tests/tools/test_file_tools.py b/tests/tools/test_file_tools.py index 22bac53374..fffdf75608 100644 --- a/tests/tools/test_file_tools.py +++ b/tests/tools/test_file_tools.py @@ -1055,3 +1055,92 @@ class TestSSHConfigWriteGateSingleQuery: f"required kwargs {missing}; it would raise TypeError instead " f"of showing an approval prompt" ) + + +class TestSecretFileReadRedaction: + """#110567: read_file / search_files must classify the RESOLVED path and run the + assignment passes for a secret-bearing file, instead of returning an opaque + prefix-less credential in cleartext. Same classifier the terminal side uses + (``_is_secret_file_arg``), so the two surfaces cannot drift.""" + + SYNTH = "3JcQ1UqZ8mNp4Rt6vWx2Yb9Ad0Ef7Gh5Ij2kS" # 40-char opaque, no vendor prefix + + class _Match: + def __init__(self, path, content): + self.path = path + self.content = content + + class _SearchResult: + def __init__(self, matches): + self.matches = matches + self.files = [] + self.counts = {} + + def to_dict(self, densify=False): + return { + "total_count": len(self.matches), + "matches": [{"path": m.path, "content": m.content} for m in self.matches], + } + + @pytest.fixture + def hermes_home(self, tmp_path, monkeypatch): + """A Hermes home with no ``.hermes`` segment, like ``%LOCALAPPDATA%\\hermes``.""" + import agent.file_safety as file_safety + + home = tmp_path / "hermes" + home.mkdir() + monkeypatch.setattr(file_safety, "_hermes_home_path", lambda: home) + monkeypatch.setattr(file_safety, "_hermes_root_path", lambda: home) + return home + + @staticmethod + def _read_ops(body): + ops = MagicMock() + result_obj = MagicMock() + result_obj.content = body + result_obj.to_dict.return_value = {"content": body, "total_lines": body.count("\n")} + ops.read_file.return_value = result_obj + return ops + + @patch("tools.file_tools._get_file_ops") + def test_read_file_of_hermes_config_masks_opaque_token(self, mock_get, hermes_home): + # read_file renders line-numbered content ("5| ADS_API_TOKEN: …"); the gutter is + # part of the text the redactor sees, so the fixture must carry it (a gutter-free + # fixture would pass even though the real read leaks). + body = (f"1|mcp_servers:\n2| nasa_ads:\n3| env:\n" + f"4| ADS_API_TOKEN: {self.SYNTH}\n5|MAX_TOKENS: 100\n") + mock_get.return_value = self._read_ops(body) + + from tools.file_tools import read_file_tool + out = json.loads(read_file_tool(str(hermes_home / "config.yaml"), task_id="secret-read")) + + assert self.SYNTH not in out["content"] + assert "«redacted" in out["content"] + assert "MAX_TOKENS: 100" in out["content"] + assert "5|MAX_TOKENS" in out["content"] # the rendered gutter survives + + @patch("tools.file_tools._get_file_ops") + def test_project_config_read_stays_raw(self, mock_get, tmp_path): + """A project's own config.yaml is NOT secret-bearing: source dumps are never mangled.""" + body = f"4| ADS_API_TOKEN: {self.SYNTH}\n" + mock_get.return_value = self._read_ops(body) + + from tools.file_tools import read_file_tool + out = json.loads(read_file_tool(str(tmp_path / "proj-config.yaml"), task_id="plain-read")) + + assert self.SYNTH in out["content"] + + @patch("tools.file_tools._get_file_ops") + def test_search_in_hermes_home_masks_opaque_token(self, mock_get, hermes_home): + config = hermes_home / "config.yaml" + ops = MagicMock() + ops.search.return_value = self._SearchResult( + [self._Match(str(config), f" ADS_API_TOKEN: {self.SYNTH}")]) + mock_get.return_value = ops + + from tools.file_tools import search_tool + raw = search_tool(pattern="ADS_API_TOKEN", path=str(hermes_home), + task_id="secret-search") + + assert self.SYNTH not in raw + assert "«redacted" in raw diff --git a/tools/file_tools.py b/tools/file_tools.py index 4839723f37..ce8d1d4f7b 100644 --- a/tools/file_tools.py +++ b/tools/file_tools.py @@ -24,7 +24,7 @@ from tools.file_operations import ( ShellFileOperations, normalize_read_pagination, normalize_search_pagination) from tools.file_operations_common import DEFAULT_READ_LIMIT from tools import file_state -from agent.redact import redact_sensitive_text +from agent.redact import _is_secret_file_arg, redact_sensitive_text from tools.file_tools_paths import ( _expand_tilde, _path_resolution_warning, _resolve_base_dir, _resolve_path_for_task) from tools.file_tools_write_guards import ( @@ -209,6 +209,19 @@ def _is_blocked_device(filepath: str, base_dir: str | Path | None = None) -> boo return _is_blocked_device_path(resolved) +def _resolved_match_path(path: str, task_id: str) -> str: + """Best-effort task-cwd resolution of a search hit's path. + + Search backends may return cwd-relative paths while the process cwd differs, so both the + read-block filter and the redaction classifier must resolve against the task cwd. An + unresolvable path is used as-is (the raw path is still worth classifying). + """ + try: + return str(_resolve_path_for_task(path, task_id)) + except (OSError, ValueError, RuntimeError): + return path + + def _filter_read_blocked_search_results(result, task_id: str = "default") -> int: """Remove credential/cache/env paths from a SearchResult in-place; return the omitted count. @@ -219,11 +232,7 @@ def _filter_read_blocked_search_results(result, task_id: str = "default") -> int def _allowed(path: str) -> bool: nonlocal omitted - try: - target = str(_resolve_path_for_task(path, task_id)) - except (OSError, ValueError, RuntimeError): - target = path - if get_read_block_error(target): + if get_read_block_error(_resolved_match_path(path, task_id)): omitted += 1 return False return True @@ -459,7 +468,9 @@ def _read_extracted_document(path: str, _resolved, offset: int, limit: int, task _apply_char_budget(result_dict, result_dict["content"], offset, total_lines, max_chars) if result_dict["content"]: rendered = result_dict["content"] - result_dict["content"] = redact_sensitive_text(rendered, file_read=True) + result_dict["content"] = redact_sensitive_text( + rendered, file_read=True, + secret_file=_is_secret_file_arg(str(_resolved))) redacted = result_dict["content"] != rendered else: redacted = False @@ -656,7 +667,8 @@ def read_file_tool(path: str, offset: int = 1, limit: int = DEFAULT_READ_LIMIT, redacted = False if result.content: unredacted = result.content - result.content = redact_sensitive_text(unredacted, file_read=True) + result.content = redact_sensitive_text( + unredacted, file_read=True, secret_file=_is_secret_file_arg(resolved_str)) redacted = result.content != unredacted result_dict["content"] = result.content @@ -1029,7 +1041,9 @@ def search_tool(pattern: str, target: str = "content", path: str = ".", omitted = _filter_read_blocked_search_results(result, task_id) for m in getattr(result, "matches", None) or (): if getattr(m, "content", None): - m.content = redact_sensitive_text(m.content, file_read=True) + m.content = redact_sensitive_text( + m.content, file_read=True, + secret_file=_is_secret_file_arg(_resolved_match_path(m.path, task_id))) result_dict = result.to_dict(densify=True) if omitted: