Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 17 additions & 6 deletions agent/redact.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand All @@ -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)
Expand Down
122 changes: 122 additions & 0 deletions tests/agent/test_redact_config_file.py
Original file line number Diff line number Diff line change
@@ -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}"
13 changes: 11 additions & 2 deletions tools/file_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
Loading