Skip to content
Merged
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
29 changes: 27 additions & 2 deletions plugins/memory/openviking/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1217,7 +1217,15 @@ def _env_line_safe(value: Any) -> str:
def _write_env_vars(env_path: Path, env_writes: dict, remove_keys: tuple[str, ...] = ()) -> None:
env_path.parent.mkdir(parents=True, exist_ok=True)
remove_set = set(remove_keys) - set(env_writes)
existing_lines = env_path.read_text(encoding="utf-8").splitlines() if env_path.exists() else []
# A Windows editor can leave a UTF-8 BOM, which prevents the first key
# from matching, or save the file as cp1252, which makes a strict UTF-8
# read fail. Strip the BOM and round-trip undecodable bytes unchanged so
# updating one credential cannot corrupt an unrelated value.
existing_lines = (
env_path.read_text(encoding="utf-8-sig", errors="surrogateescape").splitlines()
if env_path.exists()
else []
)
updated_keys = set()
new_lines = []
for line in existing_lines:
Expand All @@ -1234,7 +1242,11 @@ def _write_env_vars(env_path: Path, env_writes: dict, remove_keys: tuple[str, ..
new_lines.append(f"{key}={_env_line_safe(val)}")
# Pre-create with 0600 so secrets are never briefly world-readable.
_precreate_secret_file(env_path)
env_path.write_text("\n".join(new_lines) + ("\n" if new_lines else ""), encoding="utf-8")
env_path.write_text(
"\n".join(new_lines) + ("\n" if new_lines else ""),
encoding="utf-8",
errors="surrogateescape",
)
_restrict_secret_file_permissions(env_path)


Expand Down Expand Up @@ -1536,13 +1548,26 @@ def _start_local_openviking_server(endpoint: str) -> tuple[str, str]:
log_path = _openviking_server_log_path()
try:
log_path.parent.mkdir(parents=True, exist_ok=True)
# Do not let the server child inherit this process's PYTHONPATH.
# The Hermes Desktop backend can include the Hermes venv's
# site-packages in PYTHONPATH. If inherited, openviking-server would
# import aiohttp and friends from the Hermes venv instead of its own
# (its venv's site-packages are shadowed because PYTHONPATH precedes
# them) β€”
# and on Windows the loaded DLLs then lock the Hermes venv,
# aborting `hermes update` with access-denied on .pyd files.
# Strip PYTHONPATH so the server resolves packages from its own
# venv. (#78153)
child_env = os.environ.copy()
child_env.pop("PYTHONPATH", None)
with log_path.open("ab") as log_file:
subprocess.Popen(
[server_cmd, "--host", host, "--port", str(port)],
stdout=log_file,
stderr=log_file,
stdin=subprocess.DEVNULL,
start_new_session=True,
env=child_env,
)
except Exception as e:
return _LOCAL_SERVER_FAILED, f"Could not start openviking-server: {e}"
Expand Down
75 changes: 75 additions & 0 deletions tests/plugins/memory/test_openviking_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -392,6 +392,35 @@ def fake_popen(args, **kwargs):
assert kwargs["start_new_session"] is True


def test_start_local_openviking_server_strips_pythonpath_from_child_env(monkeypatch):
"""The spawned server must not inherit Hermes's PYTHONPATH (#78153).

Inheriting it makes openviking-server import packages from the Hermes
venv instead of its own, and on Windows locks Hermes venv DLLs so the
venv cannot be rebuilt during `hermes update`.
"""
popen_calls = []

def fake_popen(args, **kwargs):
popen_calls.append((args, kwargs))
return object()

monkeypatch.setattr(openviking_module, "_local_openviking_port_is_open", lambda host, port: False)
monkeypatch.setattr(openviking_module.shutil, "which", lambda name: "/usr/local/bin/openviking-server")
monkeypatch.setattr(openviking_module.subprocess, "Popen", fake_popen)
monkeypatch.setenv("PYTHONPATH", "/opt/hermes/.venv/Lib/site-packages")
monkeypatch.setenv("HERMES_PROFILE", "test-profile")

state, _message = openviking_module._start_local_openviking_server("http://127.0.0.1:1934")

assert state == openviking_module._LOCAL_SERVER_STARTED
_, kwargs = popen_calls[0]
child_env = kwargs["env"]
assert child_env is not None
assert "PYTHONPATH" not in child_env
assert child_env.get("HERMES_PROFILE") == "test-profile"


def test_start_local_openviking_server_does_not_spawn_when_port_already_open(monkeypatch):
"""A live listener means a second server would just die on DataDirectoryLocked."""
probed = []
Expand Down Expand Up @@ -1700,3 +1729,49 @@ def test_is_available_false_without_any_endpoint(monkeypatch):
openviking_module, "_load_hermes_openviking_config", lambda: {}
)
assert OpenVikingMemoryProvider().is_available() is False


class TestOpenVikingEnvWriter:
"""``_write_env_vars`` copies existing .env lines through on every update,
so how it *reads* them decides whether a credential update lands.

f1ea4a56c ("cover the remaining setup-time .env reads with utf-8-sig")
swept this class; this writer was missed.
"""

def test_bom_prefixed_env_updates_in_place(self, tmp_path):
from plugins.memory.openviking import _write_env_vars

env = tmp_path / ".env"
env.write_bytes(b"\xef\xbb\xbfOPENAI_API_KEY=old\nOTHER=1\n")

_write_env_vars(env, {"OPENAI_API_KEY": "new"})

lines = [l for l in env.read_text(encoding="utf-8-sig").splitlines() if l]
# The stale value must be gone, not left as a duplicate. Hermes and
# python-dotenv use the last occurrence, but the file must have one value.
assert lines.count("OPENAI_API_KEY=new") == 1
assert not any(l.endswith("=old") for l in lines)
assert "OTHER=1" in lines

def test_non_utf8_env_preserves_unrelated_bytes(self, tmp_path):
from plugins.memory.openviking import _write_env_vars

env = tmp_path / ".env"
env.write_bytes(b"NAME=caf\xe9\nOPENAI_API_KEY=old\n")

_write_env_vars(env, {"OPENAI_API_KEY": "new"})

assert env.read_bytes() == b"NAME=caf\xe9\nOPENAI_API_KEY=new\n"

def test_plain_env_is_unchanged_apart_from_the_write(self, tmp_path):
from plugins.memory.openviking import _write_env_vars

env = tmp_path / ".env"
env.write_text("A=1\nOPENAI_API_KEY=old\nB=2\n", encoding="utf-8")

_write_env_vars(env, {"OPENAI_API_KEY": "new"})

assert env.read_text(encoding="utf-8").splitlines() == [
"A=1", "OPENAI_API_KEY=new", "B=2",
]
Loading