The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(config): preserve opaque .env values
Eugeniusz Gilewski6fba78194564
diff --git a/hermes_cli/config.py b/hermes_cli/config.pyindex 56aee57ddcf..568aafbcafb 100644--- a/hermes_cli/config.py+++ b/hermes_cli/config.py@@ -293,8 +293,8 @@ _EXTRA_ENV_KEYS = frozenset({"IRC_USE_TLS", "IRC_SERVER_PASSWORD", "IRC_NICKSERV_PASSWORD","TERMINAL_ENV", "TERMINAL_SSH_KEY", "TERMINAL_SSH_PORT",# Deprecated tool-progress env vars — replaced by display.tool_progress in- # config.yaml. Kept known here so .env sanitization/reload still handle- # them for existing users (gateway reads them as a back-compat fallback),+ # config.yaml. Kept known here so reload and compatibility paths still+ # handle them for existing users (gateway reads them as a back-compat fallback),# without surfacing them in user-facing OPTIONAL_ENV_VARS listings."HERMES_TOOL_PROGRESS", "HERMES_TOOL_PROGRESS_MODE","WHATSAPP_MODE", "WHATSAPP_ENABLED",@@ -4826,7 +4826,7 @@ OPTIONAL_ENV_VARS = {# HERMES_TOOL_PROGRESS and HERMES_TOOL_PROGRESS_MODE are deprecated —# now configured via display.tool_progress in config.yaml (off|new|all|verbose|log).# The gateway still falls back to these env vars for backward compatibility,- # so they live in _EXTRA_ENV_KEYS (known to .env sanitization/reload) but+ # so they live in _EXTRA_ENV_KEYS (known to reload and compatibility paths) but# are intentionally NOT listed here: OPTIONAL_ENV_VARS feeds user-facing# surfaces (dashboard keys page, setup checklists) and deprecated knobs# shouldn't be offered there.@@ -6007,11 +6007,11 @@ def migrate_config(interactive: bool = True, quiet: bool = False) -> Dict[str, A"""results = {"env_added": [], "config_added": [], "warnings": []}- # ── Always: sanitize .env (split concatenated keys) ──+ # ── Always: normalize safe .env line formatting ──try:fixes = sanitize_env_file()if fixes and not quiet:- print(f" ✓ Repaired .env file ({fixes} corrupted entries fixed)")+ print(f" ✓ Normalized .env line formatting ({fixes} line(s) changed)")except Exception:pass # best-effort; don't block migration on sanitize failure@@ -7890,15 +7890,13 @@ def _parse_env_value(raw_value: str) -> str:def load_env() -> Dict[str, str]:"""Load environment variables from ~/.hermes/.env.- Sanitizes lines before parsing so that corrupted files (e.g.- concatenated KEY=VALUE pairs on a single line) are handled- gracefully instead of producing mangled values such as duplicated- bot tokens. See #8908.+ Normalizes line endings before parsing while treating each assignment's+ value as opaque data for boundary discovery.The parsed dict is memoised keyed on the .env file mtime, because``get_env_value()`` is called dozens-to-hundreds of times perinteractive menu render (`hermes tools`, `hermes setup`, status- panels). Sanitisation is O(lines × known-keys), so re-parsing the+ panels). Sanitisation is O(lines), so re-parsing thesame file on every call was burning ~300ms of CPU per `hermes tools`menu paint on top of the OAuth-refresh slowness. The mtime checkinvalidates the cache when the user edits .env mid-process.@@ -7929,8 +7927,7 @@ def load_env() -> Dict[str, str]:open_kw = {"encoding": "utf-8-sig", "errors": "replace"}with open(env_path, **open_kw) as f:raw_lines = f.readlines()- # Sanitize before parsing: split concatenated lines & drop stale- # placeholders so corrupted .env files don't produce invalid tokens.+ # Normalize line endings without interpreting value contents as syntax.lines = _sanitize_env_lines(raw_lines)for line in lines:line = line.strip()@@ -7969,39 +7966,13 @@ def invalidate_env_cache() -> None:_env_cache = None-_STRUCTURED_VALUE_MARKERS = ("://", "?", "&")---def _looks_like_structured_value(value: str) -> bool:- """True when ``value`` looks like a URL/query string or holds whitespace.-- Such a value is treated as one opaque secret. An embedded- ``KNOWN_KEY=`` substring inside it (e.g. a webhook URL carrying a query- parameter, or a proxy base URL with an embedded key) is part of the value,- not the start of a second .env entry, so the concatenation splitter must- not break on it. Plain token secrets (API keys) never contain these.- """- if any(marker in value for marker in _STRUCTURED_VALUE_MARKERS):- return True- return any(ch.isspace() for ch in value)--def _sanitize_env_lines(lines: list) -> list:- """Fix corrupted .env lines before reading or writing.-- Handles two known corruption patterns:- 1. Concatenated KEY=VALUE pairs on a single line (missing newline between- entries, e.g. ``ANTHROPIC_API_KEY=sk-...OPENAI_BASE_URL=https://...``).- 2. Stale ``KEY=***`` placeholder entries left by incomplete setup runs.+ """Normalize .env line endings without changing assignment semantics.- Uses a known-keys set (OPTIONAL_ENV_VARS + _EXTRA_ENV_KEYS) so we only- split on real Hermes env var names, avoiding false positives from values- that happen to contain uppercase text with ``=``.+ Content after the first ``=`` is opaque value data. A known variable name+ embedded in that value must never be reinterpreted as another assignment;+ concatenated assignments are ambiguous and therefore remain on one line."""- # Build the known keys set lazily from OPTIONAL_ENV_VARS + extras.- # Done inside the function so OPTIONAL_ENV_VARS is guaranteed to be defined.- known_keys = set(OPTIONAL_ENV_VARS.keys()) | _EXTRA_ENV_KEYS-sanitized: list[str] = []for line in lines:raw = line.rstrip("\r\n")@@ -8012,58 +7983,7 @@ def _sanitize_env_lines(lines: list) -> list:sanitized.append(raw + "\n")continue- # Detect concatenated KEY=VALUE pairs on one line.- # Search for known KEY= patterns at any position in the line.- # We collect full needle ranges so we can drop matches that are- # fully contained within a longer overlapping needle. Without this,- # suffix collisions corrupt the file: e.g. LM_API_KEY= inside- # GLM_API_KEY= would otherwise split the line into "G\nLM_API_KEY=...".- match_ranges: list[tuple[int, int]] = []- for key_name in known_keys:- needle = key_name + "="- idx = stripped.find(needle)- while idx >= 0:- match_ranges.append((idx, idx + len(needle)))- idx = stripped.find(needle, idx + len(needle))-- split_positions = sorted({- s for s, e in match_ranges- if not any(- s2 <= s and e2 >= e and (s2, e2) != (s, e)- for s2, e2 in match_ranges- )- })-- # Only treat the line as a concatenation when it actually begins with a- # known KEY= (split_positions[0] == 0). A first match at a non-zero- # offset means the matches sit inside a value, so splitting there would- # silently drop the leading text — keep the line intact instead.- split_into_entries = False- segments: list[str] = []- if len(split_positions) > 1 and split_positions[0] == 0:- segments = [- stripped[pos:(- split_positions[i + 1] if i + 1 < len(split_positions) else len(stripped)- )]- for i, pos in enumerate(split_positions)- ]- # A genuine concatenation has a simple token value in every segment- # that precedes a boundary. If a preceding value looks structured- # (a URL/query string or whitespace), the embedded KNOWN_KEY= is- # part of that value rather than a new entry, so we must not split —- # otherwise we truncate the real secret and fabricate a bogus one.- split_into_entries = all(- not _looks_like_structured_value(seg.split("=", 1)[1])- for seg in segments[:-1]- )-- if split_into_entries:- for seg in segments:- part = seg.strip()- if part:- sanitized.append(part + "\n")- else:- sanitized.append(stripped + "\n")+ sanitized.append(stripped + "\n")return sanitized@@ -8071,8 +7991,8 @@ def _sanitize_env_lines(lines: list) -> list:def sanitize_env_file() -> int:"""Read, sanitize, and rewrite ~/.hermes/.env in place.- Returns the number of lines that were fixed (concatenation splits +- placeholder removals). Returns 0 when no changes are needed.+ Returns the number of lines whose safe formatting was normalized. Returns+ 0 when no changes are needed."""env_path = get_env_path()if not env_path.exists():@@ -8089,10 +8009,9 @@ def sanitize_env_file() -> int:if sanitized == original_lines:return 0- # Count fixes: difference in line count (from splits) + removed lines+ # Count lines whose normalized representation differs.fixes = abs(len(sanitized) - len(original_lines))if fixes == 0:- # Lines changed content (e.g. *** removal) even if count is samefixes = sum(1 for a, b in zip(original_lines, sanitized) if a != b)fixes += abs(len(sanitized) - len(original_lines))@@ -8225,7 +8144,7 @@ def save_env_value(key: str, value: str):if env_path.exists():with open(env_path, **read_kw) as f:lines = f.readlines()- # Sanitize on every read: split concatenated keys, drop stale placeholders+ # Normalize safe line formatting without interpreting values as syntax.lines = _sanitize_env_lines(lines)serialized_value = _quote_env_value(value)diff --git a/hermes_cli/env_loader.py b/hermes_cli/env_loader.pyindex e91c12adf7e..22cb4a45854 100644--- a/hermes_cli/env_loader.py+++ b/hermes_cli/env_loader.py@@ -188,12 +188,7 @@ def _load_dotenv_with_fallback(path: Path, *, override: bool) -> None:def _sanitize_env_file_if_needed(path: Path) -> None:"""Pre-sanitize a .env file before python-dotenv reads it.- python-dotenv does not handle corrupted lines where multiple- KEY=VALUE pairs are concatenated on a single line (missing newline).- This produces mangled values — e.g. a bot token duplicated 8×- (see #8908).-- Also strips embedded null bytes which crash ``os.environ[k] = v``+ Strips embedded null bytes which crash ``os.environ[k] = v``with ``ValueError: embedded null byte`` — typically introduced bycopy-pasting API keys from terminals or rich-text editors.@@ -203,9 +198,8 @@ def _sanitize_env_file_if_needed(path: Path) -> None:to the errors=replace corruption path. Order of BOM checks matters:UTF-32-LE's BOM starts with UTF-16-LE's FF FE.- We delegate to ``hermes_cli.config._sanitize_env_lines`` which- already knows all valid Hermes env-var names and can split- concatenated lines correctly.+ ``hermes_cli.config._sanitize_env_lines`` normalizes line endings while+ treating content after the first ``=`` as opaque for boundary discovery."""if not path.exists():return@@ -317,7 +311,7 @@ def load_hermes_dotenv(user_env = home_path / ".env"project_env_path = Path(project_env) if project_env else None- # Fix corrupted .env files before python-dotenv parses them (#8908).+ # Normalize safe formatting and remove invalid NUL bytes before parsing.if user_env.exists():_sanitize_env_file_if_needed(user_env)if project_env_path and project_env_path.exists():diff --git a/tests/hermes_cli/test_config.py b/tests/hermes_cli/test_config.pyindex 196483f4941..e62fa1a3d79 100644--- a/tests/hermes_cli/test_config.py+++ b/tests/hermes_cli/test_config.py@@ -938,16 +938,13 @@ class TestSaveConfigAtomicity:class TestSanitizeEnvLines:- """Tests for .env file corruption repair."""+ """Tests for semantics-preserving .env line normalization."""- def test_splits_concatenated_keys(self):- """Two KEY=VALUE pairs jammed on one line get split."""+ def test_preserves_known_key_spelling_inside_value(self):+ """Known KEY= text in a value is data, not a second assignment."""lines = ["ANTHROPIC_API_KEY=sk-ant-xxxOPENAI_BASE_URL=https://api.openai.com/v1\n"]result = _sanitize_env_lines(lines)- assert result == [- "ANTHROPIC_API_KEY=sk-ant-xxx\n",- "OPENAI_BASE_URL=https://api.openai.com/v1\n",- ]+ assert result == linesdef test_preserves_clean_file(self):"""A well-formed .env file passes through unchanged (modulo trailing newlines)."""@@ -971,15 +968,30 @@ class TestSanitizeEnvLines:result = _sanitize_env_lines(lines)assert result == ["FOO_BAR=baz\n"]- def test_three_concatenated_keys(self):- """Three known keys on one line all get separated."""+ def test_migrate_reports_normalized_line_formatting(self, capsys):+ latest_version = DEFAULT_CONFIG["_config_version"]+ with (+ patch("hermes_cli.config.sanitize_env_file", return_value=2),+ patch(+ "hermes_cli.config.check_config_version",+ return_value=(latest_version, latest_version),+ ),+ patch("hermes_cli.config.read_raw_config", return_value={}),+ patch("hermes_cli.config.get_missing_env_vars", return_value=[]),+ patch("hermes_cli.config.get_missing_config_fields", return_value=[]),+ patch("hermes_cli.config.get_missing_skill_config_vars", return_value=[]),+ ):+ migrate_config(interactive=False)++ assert capsys.readouterr().out == (+ " ✓ Normalized .env line formatting (2 line(s) changed)\n"+ )++ def test_multiple_known_key_spellings_inside_value_remain_opaque(self):+ """Repeated known KEY= text cannot synthesize assignments."""lines = ["FAL_KEY=111FIRECRAWL_API_KEY=222GITHUB_TOKEN=333\n"]result = _sanitize_env_lines(lines)- assert result == [- "FAL_KEY=111\n",- "FIRECRAWL_API_KEY=222\n",- "GITHUB_TOKEN=333\n",- ]+ assert result == linesdef test_value_with_equals_sign_not_split(self):"""A value containing '=' shouldn't be falsely split (lowercase in value)."""@@ -988,19 +1000,15 @@ class TestSanitizeEnvLines:assert result == linesdef test_unknown_keys_not_split(self):- """Unknown key names on one line are NOT split (avoids false positives)."""+ """Unknown key names on one line remain opaque value data."""lines = ["CUSTOM_VAR=value123OTHER_THING=value456\n"]result = _sanitize_env_lines(lines)- # Unknown keys stay on one line — no false split- assert len(result) == 1+ assert result == lines- def test_value_ending_with_digits_still_splits(self):- """Concatenation is detected even when value ends with digits."""+ def test_value_ending_with_digits_remains_opaque(self):lines = ["OPENROUTER_API_KEY=sk-or-v1-abc123OPENAI_BASE_URL=https://api.openai.com/v1\n"]result = _sanitize_env_lines(lines)- assert len(result) == 2- assert result[0].startswith("OPENROUTER_API_KEY=")- assert result[1].startswith("OPENAI_BASE_URL=")+ assert result == linesdef test_glm_suffix_collision_not_split(self):"""GLM_API_KEY / GLM_BASE_URL must not be mangled by LM_API_KEY / LM_BASE_URL suffixes (#17138)."""@@ -1011,13 +1019,10 @@ class TestSanitizeEnvLines:result = _sanitize_env_lines(lines)assert result == lines, f"GLM_* lines were corrupted by suffix collision: {result}"- def test_suffix_collision_does_not_break_real_concatenation(self):- """A genuine concatenation that happens to start with a suffix-superset key still splits."""+ def test_suffix_superset_value_remains_opaque(self):lines = ["GLM_API_KEY=glmLM_API_KEY=lm-key\n"]result = _sanitize_env_lines(lines)- assert len(result) == 2- assert result[0].startswith("GLM_API_KEY=")- assert result[1].startswith("LM_API_KEY=")+ assert result == linesdef test_value_embedding_known_key_not_split(self):"""A single valid line whose value embeds a known KEY= (e.g. a URL with@@ -1036,8 +1041,18 @@ class TestSanitizeEnvLines:result = _sanitize_env_lines(lines)assert result == lines, f"leading text was dropped: {result}"- def test_save_env_value_fixes_corruption_on_write(self, tmp_path):- """save_env_value sanitizes corrupted lines when writing a new key."""+ def test_load_env_does_not_synthesize_variable_from_value(self, tmp_path):+ """The loader must preserve assignment boundaries from the file."""+ env_file = tmp_path / ".env"+ env_file.write_text("OPENAI_API_KEY=fixtureGITHUB_TOKEN=inert\n")++ with patch.dict(os.environ, {"HERMES_HOME": str(tmp_path)}):+ env = load_env()++ assert env == {"OPENAI_API_KEY": "fixtureGITHUB_TOKEN=inert"}++ def test_save_env_value_preserves_existing_value_semantics(self, tmp_path):+ """Writing another key must not reinterpret an existing value."""env_file = tmp_path / ".env"env_file.write_text("ANTHROPIC_API_KEY=sk-antOPENAI_BASE_URL=https://api.openai.com/v1\n"@@ -1049,13 +1064,11 @@ class TestSanitizeEnvLines:content = env_file.read_text()lines = content.strip().split("\n")- # Corrupted line should be split, new key added- assert "ANTHROPIC_API_KEY=sk-ant" in lines- assert "OPENAI_BASE_URL=https://api.openai.com/v1" in lines+ assert "ANTHROPIC_API_KEY=sk-antOPENAI_BASE_URL=https://api.openai.com/v1" in lines+ assert "OPENAI_BASE_URL=https://api.openai.com/v1" not in linesassert "MESSAGING_CWD=/tmp" in lines- def test_sanitize_env_file_returns_fix_count(self, tmp_path):- """sanitize_env_file reports how many entries were fixed."""+ def test_sanitize_env_file_does_not_rewrite_value_semantics(self, tmp_path):env_file = tmp_path / ".env"env_file.write_text("FAL_KEY=good\n"@@ -1063,12 +1076,13 @@ class TestSanitizeEnvLines:)with patch.dict(os.environ, {"HERMES_HOME": str(tmp_path)}):fixes = sanitize_env_file()- assert fixes > 0+ assert fixes == 0- # Verify file is now cleancontent = env_file.read_text()- assert "OPENROUTER_API_KEY=val\n" in content- assert "FIRECRAWL_API_KEY=val2\n" in content+ assert content == (+ "FAL_KEY=good\n"+ "OPENROUTER_API_KEY=valFIRECRAWL_API_KEY=val2\n"+ )def test_sanitize_env_file_noop_on_clean_file(self, tmp_path):"""No changes when file is already clean."""diff --git a/tests/hermes_cli/test_env_loader.py b/tests/hermes_cli/test_env_loader.pyindex a5a2ee75272..c2aff25cb6b 100644--- a/tests/hermes_cli/test_env_loader.py+++ b/tests/hermes_cli/test_env_loader.py@@ -33,7 +33,7 @@ def test_project_env_overrides_stale_shell_values_when_user_env_missing(tmp_pathassert os.getenv("OPENAI_BASE_URL") == "https://project.example/v1"-def test_project_env_is_sanitized_before_loading(tmp_path, monkeypatch):+def test_project_env_value_cannot_synthesize_an_assignment(tmp_path, monkeypatch):home = tmp_path / "hermes"project_env = tmp_path / ".env"project_env.write_text(@@ -48,8 +48,10 @@ def test_project_env_is_sanitized_before_loading(tmp_path, monkeypatch):loaded = load_hermes_dotenv(hermes_home=home, project_env=project_env)assert loaded == [project_env]- assert os.getenv("TELEGRAM_BOT_TOKEN") == "0123456789:test"- assert os.getenv("ANTHROPIC_API_KEY") == "sk-ant-test123"+ assert os.getenv("TELEGRAM_BOT_TOKEN") == (+ "0123456789:testANTHROPIC_API_KEY=sk-ant-test123"+ )+ assert os.getenv("ANTHROPIC_API_KEY") is Nonedef test_user_env_takes_precedence_over_project_env(tmp_path, monkeypatch):diff --git a/tests/hermes_cli/test_env_sanitize_on_load.py b/tests/hermes_cli/test_env_sanitize_on_load.pyindex f23eadd2a55..9c8c6dadc81 100644--- a/tests/hermes_cli/test_env_sanitize_on_load.py+++ b/tests/hermes_cli/test_env_sanitize_on_load.py@@ -5,12 +5,11 @@ from pathlib import Pathfrom unittest.mock import patch-def test_load_env_sanitizes_concatenated_lines():- """Verify load_env() splits concatenated KEY=VALUE pairs.+def test_load_env_preserves_concatenated_text_as_value_data():+ """Verify load_env() does not infer assignments within a physical line.- Reproduces the scenario from #8908 where a corrupted .env file- contained multiple tokens on a single line, causing the bot token- to be duplicated 8 times.+ A missing newline is ambiguous: text resembling a second assignment may+ instead be part of the first value, so it must remain opaque value data."""from hermes_cli.config import load_env@@ -27,10 +26,10 @@ def test_load_env_sanitizes_concatenated_lines():try:with patch("hermes_cli.config.get_env_path", return_value=env_path):result = load_env()- assert result.get("TELEGRAM_BOT_TOKEN") == token, (- f"Token should be exactly '{token}', got '{result.get('TELEGRAM_BOT_TOKEN')}'"+ assert result.get("TELEGRAM_BOT_TOKEN") == (+ f"{token}ANTHROPIC_API_KEY=sk-ant-test123")- assert result.get("ANTHROPIC_API_KEY") == "sk-ant-test123"+ assert "ANTHROPIC_API_KEY" not in resultfinally:env_path.unlink(missing_ok=True)@@ -63,8 +62,8 @@ def test_load_env_normal_file_unchanged():env_path.unlink(missing_ok=True)-def test_env_loader_sanitizes_before_dotenv():- """Verify env_loader._sanitize_env_file_if_needed fixes corrupted files."""+def test_env_loader_does_not_split_concatenated_text():+ """Verify sanitization preserves one assignment per physical line."""from hermes_cli.env_loader import _sanitize_env_file_if_neededtoken = "0123456789:test"@@ -80,12 +79,8 @@ def test_env_loader_sanitizes_before_dotenv():_sanitize_env_file_if_needed(env_path)with open(env_path, encoding="utf-8") as f:lines = f.readlines()- # Should be split into two separate lines- assert len(lines) == 2, f"Expected 2 lines, got {len(lines)}: {lines}"- assert lines[0].startswith("TELEGRAM_BOT_TOKEN=")- assert lines[1].startswith("ANTHROPIC_API_KEY=")- # Token should not contain the second key+ assert lines == [corrupted]parsed_token = lines[0].strip().split("=", 1)[1]- assert parsed_token == token+ assert parsed_token == f"{token}ANTHROPIC_API_KEY=sk-ant-test"finally:env_path.unlink(missing_ok=True)