diff --git a/plugins/memory/hindsight/__init__.py b/plugins/memory/hindsight/__init__.py index 736b255b13496..03666f2c4180a 100644 --- a/plugins/memory/hindsight/__init__.py +++ b/plugins/memory/hindsight/__init__.py @@ -559,15 +559,61 @@ def _embedded_profile_env_path(config: dict[str, Any]): return Path.home() / ".hindsight" / "profiles" / f"{_embedded_profile_name(config)}.env" +def _secure_write_profile_env(profile_env, content: str) -> None: + """Create/overwrite *profile_env* with owner-only (0600) permissions. + + The file carries the embedded daemon's plaintext LLM API key + (``HINDSIGHT_API_LLM_API_KEY``), so it must never be created with the + default umask-derived mode. A pre-existing file is tightened *before* + the new secret bytes are written. + """ + if profile_env.exists(): + try: + os.chmod(profile_env, 0o600) + except OSError: + pass + fd = os.open(str(profile_env), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(fd, "w", encoding="utf-8") as fh: + fh.write(content) + + +def _validate_profile_env_permissions(profile_env) -> None: + """Post-write validation: the secret file must be owner-only on POSIX.""" + if os.name != "posix": + # POSIX mode bits do not model Windows ACLs. + return + import stat + + mode = stat.S_IMODE(profile_env.stat().st_mode) + if mode != 0o600: + try: + os.chmod(profile_env, 0o600) + except OSError: + pass + mode = stat.S_IMODE(profile_env.stat().st_mode) + if mode != 0o600: + raise PermissionError( + f"Embedded Hindsight profile environment is not owner-only: {profile_env}" + ) + + def _materialize_embedded_profile_env(config: dict[str, Any], *, llm_api_key: str | None = None): """Write the profile-scoped env file that standalone hindsight-embed uses.""" profile_env = _embedded_profile_env_path(config) profile_env.parent.mkdir(parents=True, exist_ok=True) env_values = _build_embedded_profile_env(config, llm_api_key=llm_api_key) - profile_env.write_text( - "".join(f"{key}={value}\n" for key, value in env_values.items()), - encoding="utf-8", - ) + content = "".join(f"{key}={value}\n" for key, value in env_values.items()) + try: + _secure_write_profile_env(profile_env, content) + _validate_profile_env_permissions(profile_env) + except BaseException: + # Never leave a plaintext API key behind in a file whose permissions + # could not be verified. + try: + profile_env.unlink() + except OSError: + pass + raise return profile_env def _sanitize_bank_segment(value: str) -> str: diff --git a/tests/plugins/memory/test_hindsight_env_perms.py b/tests/plugins/memory/test_hindsight_env_perms.py new file mode 100644 index 0000000000000..f444d4439bfdc --- /dev/null +++ b/tests/plugins/memory/test_hindsight_env_perms.py @@ -0,0 +1,80 @@ +"""Regression tests: the embedded Hindsight profile env file carries the +plaintext ``HINDSIGHT_API_LLM_API_KEY`` and must be created/kept owner-only +(0600), and must not survive a failed post-write permission validation. +""" + +import os +import stat +from pathlib import Path + +import pytest + +from plugins.memory.hindsight import ( + _embedded_profile_env_path, + _materialize_embedded_profile_env, +) + + +@pytest.fixture(autouse=True) +def _isolated_home(tmp_path, monkeypatch): + isolated_home = tmp_path / "user-home" + monkeypatch.setattr(Path, "home", classmethod(lambda cls: isolated_home)) + return isolated_home + + +_CONFIG = { + "profile": "hermes", + "llm_provider": "openai", + "llm_model": "gpt-4o-mini", +} + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX mode bits are not enforced on Windows") +def test_fresh_profile_env_is_owner_only_despite_permissive_umask(): + old_umask = os.umask(0o022) + try: + profile_env = _materialize_embedded_profile_env( + _CONFIG, llm_api_key="sk-hindsight-secret" + ) + finally: + os.umask(old_umask) + + assert profile_env.exists() + assert stat.S_IMODE(profile_env.stat().st_mode) == 0o600 + assert "HINDSIGHT_API_LLM_API_KEY=sk-hindsight-secret\n" in profile_env.read_text( + encoding="utf-8" + ) + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX mode bits are not enforced on Windows") +def test_rewrite_tightens_existing_world_readable_profile_env(): + profile_env = _embedded_profile_env_path(_CONFIG) + profile_env.parent.mkdir(parents=True) + profile_env.write_text("HINDSIGHT_API_LLM_API_KEY=stale\n", encoding="utf-8") + os.chmod(profile_env, 0o644) + + _materialize_embedded_profile_env(_CONFIG, llm_api_key="sk-current") + + assert stat.S_IMODE(profile_env.stat().st_mode) == 0o600 + assert "HINDSIGHT_API_LLM_API_KEY=sk-current\n" in profile_env.read_text( + encoding="utf-8" + ) + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX mode bits are not enforced on Windows") +def test_secret_file_removed_when_permission_validation_fails(monkeypatch): + """If the post-write permission check cannot verify 0600, the plaintext + key file must not be left behind.""" + import plugins.memory.hindsight as hs + + def _fail_validation(profile_env): + raise PermissionError(f"not owner-only: {profile_env}") + + monkeypatch.setattr(hs, "_validate_profile_env_permissions", _fail_validation) + + with pytest.raises(PermissionError): + _materialize_embedded_profile_env(_CONFIG, llm_api_key="sk-doomed") + + assert not _embedded_profile_env_path(_CONFIG).exists(), ( + "secret env file must be cleaned up when validation fails" + )