From ae7224e350168e2d19a801d9e8fb405b0dcea022 Mon Sep 17 00:00:00 2001 From: liuhao1024 Date: Sun, 31 May 2026 05:09:10 +0800 Subject: [PATCH] fix(redact): skip prefix-based masking for config files to prevent API key corruption When security.redact_secrets is enabled (default), redact_sensitive_text applies prefix-based masking (sk-..., ghp_..., xai-..., etc.) to all file content, including config files that the agent reads via read_file and search_files tools. This corrupts API keys in config.yaml/.env/.json, causing 401 errors when the agent uses masked values. Add config_file parameter that skips prefix-based and ENV/JSON masking for config/data files while preserving masking for auth headers, private keys, DB connection strings, JWTs, and other sensitive patterns. Fixes #35519 --- agent/redact.py | 23 +++-- tests/agent/test_redact_config_file.py | 122 +++++++++++++++++++++++++ tools/file_tools.py | 13 ++- 3 files changed, 150 insertions(+), 8 deletions(-) create mode 100644 tests/agent/test_redact_config_file.py diff --git a/agent/redact.py b/agent/redact.py index 5de714a5f9952..98d7e8c8b13ce 100644 --- a/agent/redact.py +++ b/agent/redact.py @@ -327,7 +327,7 @@ def _redact_form_body(text: str) -> str: return _redact_query_string(text.strip()) -def redact_sensitive_text(text: str, *, force: bool = False, code_file: bool = False) -> str: +def redact_sensitive_text(text: str, *, force: bool = False, code_file: bool = False, config_file: bool = False) -> str: """Apply all redaction patterns to a block of text. Safe to call on any string -- non-matching text passes through unchanged. @@ -340,6 +340,13 @@ def redact_sensitive_text(text: str, *, force: bool = False, code_file: bool = F constants, "apiKey": "test" fixtures). Prefix patterns, auth headers, private keys, DB connstrings, JWTs, and URL secrets are still redacted. + Set config_file=True to additionally skip prefix-based masking for + config/data files (.yaml, .json, .env, .toml, etc.) where the agent + needs to read actual API key values. Config files are where the agent + looks up its current configuration -- masking the values corrupts the + agent's understanding and can cause 401 errors if masked values are + written back. Implies code_file=True. + Performance: each regex pattern is gated behind a cheap substring pre-check (e.g. ``"=" in text`` for ENV assignments, ``"://" in text`` for URLs, ``"eyJ" in text`` for JWTs). On a typical hermes log line @@ -359,11 +366,15 @@ def redact_sensitive_text(text: str, *, force: bool = False, code_file: bool = F return text # Known prefixes (sk-, ghp_, etc.) — gate on substring presence - if _has_known_prefix_substring(text): - text = _PREFIX_RE.sub(lambda m: _mask_token(m.group(1)), text) - - # ENV assignments: OPENAI_API_KEY=*** (skip for code files — false positives) - if not code_file: + # Skip for config files — prefix masking corrupts API keys the agent + # needs to read from config.yaml / .env / etc. (config_file implies + # code_file, so ENV/JSON patterns below are also skipped.) + if not config_file: + if _has_known_prefix_substring(text): + text = _PREFIX_RE.sub(lambda m: _mask_token(m.group(1)), text) + + # ENV assignments: OPENAI_API_KEY=*** (skip for code/config files) + if not code_file and not config_file: if "=" in text: def _redact_env(m): name, quote, value = m.group(1), m.group(2), m.group(3) diff --git a/tests/agent/test_redact_config_file.py b/tests/agent/test_redact_config_file.py new file mode 100644 index 0000000000000..8110b786283ac --- /dev/null +++ b/tests/agent/test_redact_config_file.py @@ -0,0 +1,122 @@ +"""Tests for config_file parameter in redact_sensitive_text. + +Issue #35519: redact_sensitive_text corrupts API keys in config files when +read via read_file/search_files, causing 401 errors. + +The config_file parameter skips prefix-based masking so config files +(.yaml, .json, .env, .toml, .conf) return actual API key values to the agent. +""" + +import pytest +from agent.redact import redact_sensitive_text + + +@pytest.fixture(autouse=True) +def _ensure_redaction_enabled(monkeypatch): + """Ensure HERMES_REDACT_SECRETS is not disabled by prior test imports.""" + monkeypatch.delenv("HERMES_REDACT_SECRETS", raising=False) + monkeypatch.setattr("agent.redact._REDACT_ENABLED", True) + + +class TestConfigFileSkipsPrefixMasking: + """config_file=True should skip prefix-based secret masking for config files.""" + + def test_config_file_preserves_openai_key(self): + """Config files should NOT mask sk-... prefix keys.""" + key = "sk-" + "proj-" + "a" * 40 + text = "api_key: " + key + result = redact_sensitive_text(text, config_file=True) + assert key in result, f"Key should be preserved but got: {result}" + + def test_config_file_preserves_github_pat(self): + """Config files should NOT mask ghp_... tokens.""" + key = "ghp_" + "a" * 36 + text = "GITHUB_TOKEN: " + key + result = redact_sensitive_text(text, config_file=True) + assert key in result, f"PAT should be preserved but got: {result}" + + def test_config_file_preserves_xai_key(self): + """Config files should NOT mask xai-... keys.""" + key = "xai-" + "a" * 40 + text = "api_key: " + key + result = redact_sensitive_text(text, config_file=True) + assert key in result, f"xai key should be preserved but got: {result}" + + def test_config_file_preserves_openrouter_key(self): + """Config files should NOT mask sk-or-... keys.""" + key = "sk-or-" + "a" * 40 + text = "api_key: " + key + result = redact_sensitive_text(text, config_file=True) + assert key in result, f"OpenRouter key should be preserved but got: {result}" + + def test_config_file_preserves_perplexity_key(self): + """Config files should NOT mask pplx-... keys.""" + key = "pplx-" + "a" * 40 + text = "api_key: " + key + result = redact_sensitive_text(text, config_file=True) + assert key in result, f"Perplexity key should be preserved but got: {result}" + + +class TestConfigFileImpliesCodeFile: + """config_file=True should also skip ENV-assignment and JSON-field patterns.""" + + def test_config_file_skips_env_pattern(self): + """Config files should NOT mask ENV-style assignments.""" + key = "sk-" + "a" * 40 + text = "OPENAI_API_KEY=" + key + result = redact_sensitive_text(text, config_file=True) + assert key in result, f"ENV value should be preserved but got: {result}" + + def test_config_file_skips_json_field_pattern(self): + """Config files should NOT mask JSON-style key fields.""" + key = "sk-" + "a" * 40 + text = '{"apiKey": "' + key + '"}' + result = redact_sensitive_text(text, config_file=True) + assert key in result, f"JSON value should be preserved but got: {result}" + + +class TestNonConfigFilesStillMasked: + """Non-config files should still get prefix masking (existing behavior).""" + + def test_default_still_masks_prefix(self): + """Default mode should still mask prefix keys.""" + key = "sk-" + "proj-" + "a" * 40 + text = "Using key " + key + " here" + result = redact_sensitive_text(text) + assert key not in result, f"Key should be masked but got: {result}" + + def test_code_file_still_masks_prefix(self): + """code_file=True should still mask prefix keys.""" + key = "sk-" + "proj-" + "a" * 40 + text = "Using key " + key + " here" + result = redact_sensitive_text(text, code_file=True) + assert key not in result, f"Key should be masked but got: {result}" + + +class TestConfigFileStillMasksOtherPatterns: + """config_file=True should still mask auth headers, private keys, DB connstrings.""" + + def test_auth_header_still_masked(self): + """Authorization headers should still be masked in config mode.""" + key = "sk-" + "a" * 40 + text = "Authorization: Bearer " + key + result = redact_sensitive_text(text, config_file=True) + assert key not in result, f"Auth header should still be masked but got: {result}" + + def test_db_connstring_still_masked(self): + """DB connection string passwords should still be masked in config mode.""" + text = "postgres://user:secretpass@host:5432/db" + result = redact_sensitive_text(text, config_file=True) + assert "secretpass" not in result, f"DB password should be masked but got: {result}" + + def test_telegram_token_still_masked(self): + """Telegram bot tokens should still be masked in config mode.""" + text = "bot_token: 1234567890:ABCdefGHIjklMNOpqrsTUVwxyz012345" + result = redact_sensitive_text(text, config_file=True) + assert "ABCdefGHIjklMNOpqrsTUVwxyz012345" not in result, f"TG token should be masked but got: {result}" + + def test_private_key_still_masked(self): + """Private key blocks should still be masked in config mode.""" + text = "-----BEGIN RSA PRIVATE KEY-----\ndata\n-----END RSA PRIVATE KEY-----" + result = redact_sensitive_text(text, config_file=True) + assert "REDACTED PRIVATE KEY" in result, f"Private key should be masked but got: {result}" diff --git a/tools/file_tools.py b/tools/file_tools.py index 6ea6ff0a3f0bd..6e8ebe8461c5c 100644 --- a/tools/file_tools.py +++ b/tools/file_tools.py @@ -17,6 +17,13 @@ ) from tools import file_state from agent.redact import redact_sensitive_text +# Config/data file extensions where prefix-based secret masking should be +# skipped -- the agent needs the actual values to read its own configuration. +_CONFIG_FILE_EXTS = frozenset({ + '.yaml', '.yml', '.json', '.env', '.toml', '.conf', '.cfg', '.ini', + '.config', '.properties', '.cnf', +}) + logger = logging.getLogger(__name__) @@ -726,7 +733,8 @@ def read_file_tool(path: str, offset: int = 1, limit: int = 500, task_id: str = # ── Redact secrets (after guard check to skip oversized content) ── if result.content: - result.content = redact_sensitive_text(result.content, code_file=True) + _is_config = os.path.splitext(path)[1].lower() in _CONFIG_FILE_EXTS + result.content = redact_sensitive_text(result.content, config_file=_is_config, code_file=not _is_config) result_dict["content"] = result.content # Large-file hint: if the file is big and the caller didn't ask @@ -1245,7 +1253,8 @@ def search_tool(pattern: str, target: str = "content", path: str = ".", if hasattr(result, 'matches'): for m in result.matches: if hasattr(m, 'content') and m.content: - m.content = redact_sensitive_text(m.content, code_file=True) + _m_is_config = os.path.splitext(getattr(m, 'path', ''))[1].lower() in _CONFIG_FILE_EXTS + m.content = redact_sensitive_text(m.content, config_file=_m_is_config, code_file=not _m_is_config) result_dict = result.to_dict() if count >= 3: