diff --git a/api/onboarding.py b/api/onboarding.py index 05cc9b4b8f1..abfa1d27603 100644 --- a/api/onboarding.py +++ b/api/onboarding.py @@ -23,6 +23,7 @@ save_settings, verify_hermes_imports, ) +from api.providers import _write_env_file # shared impl with _ENV_LOCK (#1164) from api.workspace import get_last_workspace, load_workspaces logger = logging.getLogger(__name__) @@ -167,26 +168,6 @@ def _load_env_file(env_path: Path) -> dict[str, str]: return values -def _write_env_file(env_path: Path, updates: dict[str, str]) -> None: - current = _load_env_file(env_path) - for key, value in updates.items(): - if value is None: - current.pop(key, None) - os.environ.pop(key, None) - continue - clean = str(value).strip() - if not clean: - continue - # Reject embedded newlines/carriage returns to prevent .env injection - if "\n" in clean or "\r" in clean: - raise ValueError("API key must not contain newline characters.") - current[key] = clean - os.environ[key] = clean - - env_path.parent.mkdir(parents=True, exist_ok=True) - lines = [f"{key}={current[key]}" for key in sorted(current)] - env_path.write_text("\n".join(lines) + ("\n" if lines else ""), encoding="utf-8") - def _load_yaml_config(config_path: Path) -> dict: try: diff --git a/api/providers.py b/api/providers.py index a9624bf7b7e..cb817c8ea21 100644 --- a/api/providers.py +++ b/api/providers.py @@ -88,6 +88,10 @@ def _write_env_file(env_path: Path, updates: dict[str, str | None]) -> None: """Write key=value pairs to the .env file. Values of ``None`` cause the key to be removed. + + Preserves comments, blank lines, and original key order (#1164). + New keys are appended at the end of the file with a blank-line separator. + Holds ``_ENV_LOCK`` from ``api.streaming`` for the entire load → modify → write cycle to prevent TOCTOU races between concurrent POST /api/providers calls (each reading the same file baseline and overwriting the other's key). @@ -97,11 +101,31 @@ def _write_env_file(env_path: Path, updates: dict[str, str | None]) -> None: import stat as _stat with _ENV_LOCK: - current = _load_env_file(env_path) + # ── Read existing lines (preserving comments and blank lines) ── + existing_lines: list[str] = [] + if env_path.exists(): + try: + existing_lines = env_path.read_text(encoding="utf-8").splitlines() + except Exception: + existing_lines = [] + + # Map each existing key to its line index so we can update in-place. + existing_key_indices: dict[str, int] = {} + for _i, _raw in enumerate(existing_lines): + _stripped = _raw.strip() + if _stripped and not _stripped.startswith("#") and "=" in _stripped: + _existing_key_indices_key = _stripped.split("=", 1)[0].strip() + existing_key_indices[_existing_key_indices_key] = _i + + output_lines = list(existing_lines) + new_keys: list[str] = [] + for key, value in updates.items(): if value is None: - current.pop(key, None) + # Mark the line for removal (None sentinel) and clear env. os.environ.pop(key, None) + if key in existing_key_indices: + output_lines[existing_key_indices[key]] = None # type: ignore[assignment] continue clean = str(value).strip() if not clean: @@ -109,17 +133,49 @@ def _write_env_file(env_path: Path, updates: dict[str, str | None]) -> None: # Reject embedded newlines/carriage returns to prevent .env injection if "\n" in clean or "\r" in clean: raise ValueError("API key must not contain newline characters.") - current[key] = clean os.environ[key] = clean + if key in existing_key_indices: + output_lines[existing_key_indices[key]] = f"{key}={clean}" + else: + new_keys.append(f"{key}={clean}") + + # Remove deleted lines (None sentinels) + output_lines = [l for l in output_lines if l is not None] + + # Append new keys after a blank-line separator + if new_keys: + if output_lines and output_lines[-1].strip() != "": + output_lines.append("") + output_lines.extend(new_keys) + env_path.parent.mkdir(parents=True, exist_ok=True) - lines = [f"{key}={current[key]}" for key in sorted(current)] - # Create at owner-only mode from the first byte (O_CREAT honours the mode - # argument subject to umask). A trailing chmod guards pre-existing files. + content = "\n".join(output_lines) + if content: + content += "\n" + # Atomic write via tempfile + os.replace so cross-process readers + # (Telegram bot, CLI) never see a half-truncated file. The shared + # ``~/.hermes/.env`` is also written by ``hermes_cli.config.save_env_value`` + # using the same atomic pattern; matching it here closes the + # cross-process leg of #1164 (within-process is covered by _ENV_LOCK). _mode = _stat.S_IRUSR | _stat.S_IWUSR # 0o600 - _fd = os.open(str(env_path), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, _mode) - with os.fdopen(_fd, "w", encoding="utf-8") as _f: - _f.write("\n".join(lines) + ("\n" if lines else "")) + import tempfile as _tempfile + _tmp_fd, _tmp_path = _tempfile.mkstemp( + dir=str(env_path.parent), prefix=".env_", suffix=".tmp" + ) + try: + with os.fdopen(_tmp_fd, "w", encoding="utf-8") as _f: + _f.write(content) + _f.flush() + os.fsync(_f.fileno()) + os.chmod(_tmp_path, _mode) # tighten before rename so readers see 0600 + os.replace(_tmp_path, env_path) + except BaseException: + try: + os.unlink(_tmp_path) + except OSError: + pass + raise try: env_path.chmod(_mode) except OSError: diff --git a/tests/test_issue1164_env_file_corruption.py b/tests/test_issue1164_env_file_corruption.py new file mode 100644 index 00000000000..67302b6903c --- /dev/null +++ b/tests/test_issue1164_env_file_corruption.py @@ -0,0 +1,170 @@ +""" +Regression tests for #1164 — .env file corruption by WebUI. + +The WebUI's onboarding flow had a duplicate _write_env_file() without +_ENV_LOCK protection. Concurrent writes (e.g. Telegram bot + WebUI) could +corrupt the shared .env file. Additionally, both _write_env_file copies +rewrote the entire file from a parsed dict, stripping comments and +reordering keys alphabetically. + +Fix: +- onboarding.py now imports _write_env_file from providers.py (which holds + _ENV_LOCK from api.streaming for the entire load→modify→write cycle). +- _write_env_file in providers.py now preserves comments, blank lines, and + original key order instead of rebuilding from a sorted dict. + +Sprint/commit: v0.50.227+ +""" +import os +import tempfile +import textwrap +import unittest +from pathlib import Path + + +class TestEnvFileCommentPreservation(unittest.TestCase): + """Verify _write_env_file preserves comments, blank lines, and key order.""" + + def setUp(self): + self.tmpdir = tempfile.mkdtemp() + self.env_path = Path(self.tmpdir) / ".env" + # Must import AFTER setting up, as the module has top-level code + from api.providers import _write_env_file + self._write_env_file = _write_env_file + + def tearDown(self): + # Clean os.environ entries set during tests + for key in ("OPENROUTER_API_KEY", "OPENAI_API_KEY", "NEW_KEY"): + os.environ.pop(key, None) + import shutil + shutil.rmtree(self.tmpdir, ignore_errors=True) + + def _read(self) -> str: + return self.env_path.read_text(encoding="utf-8") + + # ── Comment preservation ────────────────────────────────────────── + + def test_comments_preserved_on_update(self): + """Comments in .env must survive a key value update.""" + self.env_path.write_text(textwrap.dedent("""\ + # Hermes API keys + OPENROUTER_API_KEY=sk-or-old + # Another comment + OPENAI_API_KEY=sk-oai-old + """).strip() + "\n", encoding="utf-8") + + self._write_env_file(self.env_path, {"OPENROUTER_API_KEY": "sk-or-new"}) + + content = self._read() + self.assertIn("# Hermes API keys", content, + "Leading comment must be preserved") + self.assertIn("# Another comment", content, + "Inline comment must be preserved") + self.assertIn("sk-or-new", content) + + def test_blank_lines_preserved(self): + """Blank lines between key blocks must be preserved.""" + self.env_path.write_text( + "KEY_A=val_a\n\nKEY_B=val_b\n", encoding="utf-8") + + self._write_env_file(self.env_path, {"KEY_A": "updated"}) + + content = self._read() + self.assertEqual(content.count("\n\n"), 1, + "Blank line between keys must be preserved") + + def test_key_order_preserved(self): + """Original key order must not be sorted alphabetically.""" + self.env_path.write_text( + "ZZZ_KEY=last\nAAA_KEY=first\nBBB_KEY=middle\n", + encoding="utf-8") + + self._write_env_file(self.env_path, {"AAA_KEY": "updated"}) + + content = self._read() + zzz_pos = content.find("ZZZ_KEY") + aaa_pos = content.find("AAA_KEY") + bbb_pos = content.find("BBB_KEY") + # Original order: ZZZ, AAA, BBB + self.assertLess(zzz_pos, aaa_pos, + "ZZZ_KEY must still come before AAA_KEY (original order)") + self.assertLess(aaa_pos, bbb_pos, + "AAA_KEY must still come before BBB_KEY (original order)") + + def test_new_key_appended_with_separator(self): + """New keys are appended at the end with a blank-line separator.""" + self.env_path.write_text( + "EXISTING_KEY=value\n", encoding="utf-8") + + self._write_env_file(self.env_path, {"NEW_KEY": "new_value"}) + + content = self._read() + self.assertIn("NEW_KEY=new_value", content) + # New key should appear after the existing one + self.assertGreater(content.find("NEW_KEY"), content.find("EXISTING_KEY")) + + def test_key_removal_preserves_others(self): + """Removing a key leaves other keys and comments intact.""" + self.env_path.write_text(textwrap.dedent("""\ + # Comment A + KEY_A=val_a + # Comment B + KEY_B=val_b + """).strip() + "\n", encoding="utf-8") + + self._write_env_file(self.env_path, {"KEY_B": None}) + + content = self._read() + self.assertIn("KEY_A=val_a", content) + self.assertIn("# Comment A", content) + self.assertNotIn("KEY_B", content) + # Comment B stays (it's just a comment, not tied to KEY_B structurally) + self.assertIn("# Comment B", content) + + def test_empty_file_handled_gracefully(self): + """Writing to a non-existent .env file works.""" + self.assertFalse(self.env_path.exists()) + self._write_env_file(self.env_path, {"NEW_KEY": "value"}) + self.assertTrue(self.env_path.exists()) + self.assertEqual(self._read().strip(), "NEW_KEY=value") + + +class TestOnboardingUsesProviderWriteEnv(unittest.TestCase): + """Verify that onboarding.py delegates to providers._write_env_file + (which holds _ENV_LOCK), eliminating the duplicate unprotected path.""" + + def test_onboarding_imports_write_env_from_providers(self): + """api.onboarding._write_env_file must be the same object as + api.providers._write_env_file (shared implementation with lock).""" + from api import onboarding, providers + self.assertIs( + onboarding._write_env_file, + providers._write_env_file, + "onboarding must use providers._write_env_file for thread safety (#1164)" + ) + + def test_providers_write_env_holds_env_lock(self): + """providers._write_env_file must acquire _ENV_LOCK from api.streaming.""" + import inspect + from api.providers import _write_env_file + source = inspect.getsource(_write_env_file) + self.assertIn("_ENV_LOCK", source, + "_write_env_file must use _ENV_LOCK for concurrency safety") + self.assertIn("from api.streaming import _ENV_LOCK", source, + "_ENV_LOCK must be imported from api.streaming") + + def test_providers_write_env_uses_atomic_rename(self): + """providers._write_env_file must write atomically via tempfile + + os.replace so cross-process readers (Telegram, CLI) never observe + a truncated half-written file (#1164 cross-process leg).""" + import inspect + from api.providers import _write_env_file + source = inspect.getsource(_write_env_file) + self.assertIn("tempfile", source, + "_write_env_file must stage writes through a tempfile") + self.assertIn("os.replace(", source, + "_write_env_file must atomically rename via os.replace") + # The original O_TRUNC pattern must NOT remain — it is the source of + # the cross-process race the PR is closing. + self.assertNotIn("O_TRUNC", source, + "_write_env_file must not truncate-in-place (#1164)")