Skip to content

The agent that grows with you

refactor(redact): one secret-file predicate for .env, shell rc and Hermes config.yaml

teknium16e7ea9cbdccd
diff --git a/agent/redact.py b/agent/redact.py
index f18cb31831b..4100b46cde1 100644
--- a/agent/redact.py
+++ b/agent/redact.py
@@ -750,25 +750,26 @@ def redact_sensitive_text(text: str, *, force: bool = False, code_file: bool = F
# ``postgresql://{user}`` f-string templates). See issue #43025.
_ENV_DUMP_COMMANDS = frozenset({"env", "printenv", "set", "export", "declare"})
-# Commands that read file contents to stdout. A ``.env`` target is a credential
-# dump (per AGENTS.md ``.env`` holds only secrets), so the ENV pass must run.
+# Commands that read file contents to stdout, plus the filter readers (``grep``/``awk``/``sed``)
+# the model reaches for on config files. A secret-bearing target (``.env`` per AGENTS.md,
+# a shell rc/profile, Hermes' own ``config.yaml`` where ``hermes mcp add --env`` writes
+# tokens) is a credential dump, so the ENV/YAML assignment pass must run. Arbitrary
+# ``config.yaml`` / source files stay on the code_file path (``MAX_TOKENS: 100``).
_FILE_READ_COMMANDS = frozenset({
"cat", "head", "tail", "type", "bat", "less", "more", "nl",
- "zcat", "tac", "view", "batcat",
+ "zcat", "tac", "view", "batcat", "grep", "awk", "sed",
})
-_SECRET_BEARING_FILE_BASENAMES = frozenset({
+_SHELL_RC_BASENAMES = frozenset({
".bashrc", ".bash_profile", ".bash_login", ".profile",
".zshrc", ".zprofile", ".zlogin", ".zshenv",
})
-_TEXT_FILE_READ_COMMANDS = frozenset({"grep", "awk", "sed"})
+_HERMES_HOME_PREFIXES = ("$HERMES_HOME/", "${HERMES_HOME}/")
def _command_segments(command: str) -> list[str]:
- """Pipeline/sequence segments, split only on unquoted ``| ; &``.
-
- Quote-aware so ``awk '{print $1; print $2}'`` / ``grep 'foo|bar'`` stay
- one segment. Backslash is not an escape (Windows ``C:\\Users\\...``).
- """
+ """Pipeline/sequence segments, split only on unquoted ``| ; &`` so an
+ ``awk '{print $1; print $2}'`` program or ``grep 'foo|bar'`` pattern stays one
+ segment. Backslash is not an escape (Windows ``C:\\Users\\...``)."""
segments: list[str] = []
buf: list[str] = []
quote: str | None = None
@@ -795,30 +796,9 @@ def _command_segments(command: str) -> list[str]:
return segments
-def _command_reads_env_file(command: str | None) -> bool:
- """True if ``command`` reads a ``.env``-style file (by basename) to stdout.
- Defense-in-depth, not a boundary: indirect reads (``sudo cat .env``, ``$(cat
- .env)``, ``sed``/``awk``) are not detected, matching ``is_env_dump_command``."""
- if not command:
- return False
- for seg in _command_segments(command):
- tokens = seg.split() # not shlex: it mangles Windows paths (``C:\Users\...\.env``)
- if not tokens or tokens[0] not in _FILE_READ_COMMANDS:
- continue
- for arg in tokens[1:]:
- if arg.startswith("-"):
- continue
- basename = arg.strip("\"'").rsplit("/", 1)[-1].rsplit("\\", 1)[-1]
- if basename.lower() in _ENV_FILE_BASENAMES:
- return True
- return False
-
-
-_HERMES_HOME_PREFIXES = ("$HERMES_HOME/", "${HERMES_HOME}/")
-
-
-def _is_secret_bearing_file_arg(arg: str) -> bool:
- """Recognize explicit Hermes config and standard shell startup paths."""
+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)."""
path = arg.strip("\"'").replace("\\", "/")
hermes_home = False
for prefix in _HERMES_HOME_PREFIXES:
@@ -831,30 +811,23 @@ def _is_secret_bearing_file_arg(arg: str) -> bool:
parts = [part.lower() for part in path.split("/") if part]
if not parts:
return False
- if parts[-1] in _SECRET_BEARING_FILE_BASENAMES:
+ if parts[-1] in _ENV_FILE_BASENAMES or parts[-1] in _SHELL_RC_BASENAMES:
return True
- if parts[-1] != "config.yaml":
- return False
- return hermes_home or ".hermes" in parts[:-1]
+ return parts[-1] == "config.yaml" and (hermes_home or ".hermes" in parts[:-1])
-def _command_reads_secret_bearing_file(command: str | None) -> bool:
- """True for direct stdout reads of known secret-bearing config files."""
+def _command_reads_secret_file(command: str | None) -> bool:
+ """True if ``command`` reads a secret-bearing file (see ``_is_secret_file_arg``) to
+ stdout. Defense-in-depth, not a boundary: indirect reads (``sudo cat .env``, ``$(cat
+ .env)``, unresolved variable paths) are not detected, matching ``is_env_dump_command``."""
if not command or not isinstance(command, str):
return False
for seg in _command_segments(command):
- tokens = seg.split() # preserve Windows path separators; see _command_reads_env_file
- if not tokens:
- continue
- reader = tokens[0].rsplit("/", 1)[-1].lower()
- if reader in _FILE_READ_COMMANDS:
- if any(_is_secret_bearing_file_arg(arg) for arg in tokens[1:] if not arg.startswith("-")):
- return True
+ tokens = seg.split() # not shlex: it mangles Windows paths (``C:\Users\...\.env``)
+ if not tokens or tokens[0].rsplit("/", 1)[-1].lower() not in _FILE_READ_COMMANDS:
continue
- if reader in _TEXT_FILE_READ_COMMANDS:
- positional = [arg for arg in tokens[1:] if not arg.startswith("-")]
- if any(_is_secret_bearing_file_arg(arg) for arg in positional[1:]):
- return True
+ if any(_is_secret_file_arg(arg) for arg in tokens[1:] if not arg.startswith("-")):
+ return True
return False
@@ -896,16 +869,13 @@ def redact_for_egress(text: str) -> str:
def redact_terminal_output(output: str, command: str | None = None, *, force: bool = False) -> str:
- """Single redaction policy for ALL terminal-output surfaces: the ENV-assignment
- pass runs when ``command`` is an env dump or reads a secret-bearing file
- (otherwise code_file=True avoids false positives on source/config dumps)."""
+ """Single redaction policy for ALL terminal-output surfaces: the ENV/YAML-assignment
+ pass runs only when ``command`` is an env dump or reads a secret-bearing file (``.env``,
+ shell rc, Hermes ``config.yaml``); otherwise code_file=True avoids false positives on
+ source/config dumps."""
if not output:
return output
- code_file = not (
- is_env_dump_command(command)
- or _command_reads_env_file(command)
- or _command_reads_secret_bearing_file(command)
- )
+ code_file = not (is_env_dump_command(command) or _command_reads_secret_file(command))
return redact_sensitive_text(output, force=force, code_file=code_file)
diff --git a/tests/agent/test_redact.py b/tests/agent/test_redact.py
index e86bbe9701d..f8e50859af3 100644
--- a/tests/agent/test_redact.py
+++ b/tests/agent/test_redact.py
@@ -861,53 +861,53 @@ class TestTerminalOutputRedaction:
# ── .env file detection (issue #61352 v2) ──
- def test_command_reads_env_file_detection(self):
- from agent.redact import _command_reads_env_file
+ def test_command_reads_secret_file_detection(self):
+ from agent.redact import _command_reads_secret_file
# Basic detection
- assert _command_reads_env_file("cat .env")
- assert _command_reads_env_file("cat .env.local")
- assert _command_reads_env_file("cat .env.production")
- assert _command_reads_env_file("cat .envrc")
- assert _command_reads_env_file("head .env")
- assert _command_reads_env_file("tail .env")
- assert _command_reads_env_file("type .env")
- assert _command_reads_env_file("nl .env")
- assert _command_reads_env_file("bat .env")
+ assert _command_reads_secret_file("cat .env")
+ assert _command_reads_secret_file("cat .env.local")
+ assert _command_reads_secret_file("cat .env.production")
+ assert _command_reads_secret_file("cat .envrc")
+ assert _command_reads_secret_file("head .env")
+ assert _command_reads_secret_file("tail .env")
+ assert _command_reads_secret_file("type .env")
+ assert _command_reads_secret_file("nl .env")
+ assert _command_reads_secret_file("bat .env")
# With flags
- assert _command_reads_env_file("cat -n .env")
- assert _command_reads_env_file("cat -A .env")
+ assert _command_reads_secret_file("cat -n .env")
+ assert _command_reads_secret_file("cat -A .env")
# With paths
- assert _command_reads_env_file("cat ~/.hermes/.env")
- assert _command_reads_env_file("cat /home/user/project/.env")
- assert _command_reads_env_file("cat ./config/.env.local")
+ assert _command_reads_secret_file("cat ~/.hermes/.env")
+ assert _command_reads_secret_file("cat /home/user/project/.env")
+ assert _command_reads_secret_file("cat ./config/.env.local")
# In a pipeline / sequence
- assert _command_reads_env_file("cat .env | grep KEY")
- assert _command_reads_env_file("echo '---' && cat .env")
+ assert _command_reads_secret_file("cat .env | grep KEY")
+ assert _command_reads_secret_file("echo '---' && cat .env")
# Windows-style backslash paths
- assert _command_reads_env_file("cat C:\\Users\\test\\.env")
+ assert _command_reads_secret_file("cat C:\\Users\\test\\.env")
# Quoted paths (plain split leaves the quotes attached)
- assert _command_reads_env_file('cat ".env"')
- assert _command_reads_env_file("cat '.env'")
+ assert _command_reads_secret_file('cat ".env"')
+ assert _command_reads_secret_file("cat '.env'")
# Case-insensitive basename (macOS/Windows filesystems)
- assert _command_reads_env_file("cat .ENV")
+ assert _command_reads_secret_file("cat .ENV")
- def test_command_reads_env_file_excludes_templates(self):
- from agent.redact import _command_reads_env_file
+ def test_command_reads_secret_file_excludes_templates(self):
+ from agent.redact import _command_reads_secret_file
# Templates/examples should NOT trigger
- assert not _command_reads_env_file("cat .env.example")
- assert not _command_reads_env_file("cat .env.sample")
- assert not _command_reads_env_file("cat .env.template")
- assert not _command_reads_env_file("cat .env.dist")
-
- def test_command_reads_env_file_rejects_non_env_files(self):
- from agent.redact import _command_reads_env_file
- assert not _command_reads_env_file("cat config.py")
- assert not _command_reads_env_file("cat README.md")
- assert not _command_reads_env_file("cat .envrc.bak") # .bak not in list
- assert not _command_reads_env_file("python app.py")
- assert not _command_reads_env_file("echo .env") # echo is not a file-read cmd
- assert not _command_reads_env_file("")
- assert not _command_reads_env_file(None)
+ assert not _command_reads_secret_file("cat .env.example")
+ assert not _command_reads_secret_file("cat .env.sample")
+ assert not _command_reads_secret_file("cat .env.template")
+ assert not _command_reads_secret_file("cat .env.dist")
+
+ def test_command_reads_secret_file_rejects_non_env_files(self):
+ from agent.redact import _command_reads_secret_file
+ assert not _command_reads_secret_file("cat config.py")
+ assert not _command_reads_secret_file("cat README.md")
+ assert not _command_reads_secret_file("cat .envrc.bak") # .bak not in list
+ assert not _command_reads_secret_file("python app.py")
+ assert not _command_reads_secret_file("echo .env") # echo is not a file-read cmd
+ assert not _command_reads_secret_file("")
+ assert not _command_reads_secret_file(None)
def test_cat_env_file_masks_opaque_token(self):
"""cat .env → code_file=False → generic ENV pass redacts opaque keys."""
@@ -1026,15 +1026,15 @@ class TestTerminalOutputRedaction:
"sed -n '1,20p' template.yaml",
],
)
- def test_secret_bearing_file_detection_preserves_fail_open_controls(self, command):
+ def test_arbitrary_yaml_and_source_reads_stay_unredacted(self, command):
+ """Only the known secret-bearing files flip the gate: the same opaque value read
+ from project YAML / source code is left alone (code_file path), while the
+ identical text under ``cat .env`` is masked."""
from agent.redact import redact_terminal_output
- output = "SERVICE_TOKEN=placeholder_value_here"
+ output = "SERVICE_TOKEN=3JcQ1UzX9vQ2mL7pR4tY8wA1sD5fG6hJ2kSbn7Q0"
assert redact_terminal_output(output, command) == output
- assert "realEnvSecret123" not in redact_terminal_output(
- "SERVICE_TOKEN=realEnvSecret123", "cat .env"
- )
-
+ assert "3JcQ1UzX9vQ2mL7pR4tY8wA1sD5fG6hJ2kSbn7Q0" not in redact_terminal_output(output, "cat .env")
def test_disabled_passes_through(self, monkeypatch):