diff --git a/mempalace/mcp_server.py b/mempalace/mcp_server.py index 1a9e770..6a52928 100644 --- a/mempalace/mcp_server.py +++ b/mempalace/mcp_server.py @@ -414,21 +414,51 @@ def _refresh_vector_disabled_flag() -> None: # This provides an audit trail for detecting memory poisoning and # enables review/rollback of writes from external or untrusted sources. -_WAL_DIR = Path(os.path.expanduser("~/.mempalace/wal")) -_WAL_DIR.mkdir(parents=True, exist_ok=True) -try: - _WAL_DIR.chmod(0o700) -except (OSError, NotImplementedError): - pass -_WAL_FILE = _WAL_DIR / "write_log.jsonl" -# Atomically create WAL file with restricted permissions (no TOCTOU race). -# os.open with O_CREAT|O_WRONLY and mode 0o600 creates the file if absent -# or opens it if present, both in a single syscall. -try: - _fd = os.open(str(_WAL_FILE), os.O_CREAT | os.O_WRONLY, 0o600) - os.close(_fd) -except (OSError, NotImplementedError): - pass +_WAL_FILE = Path(os.path.expanduser("~/.mempalace/wal")) / "write_log.jsonl" +_WAL_INITIALIZED_DIR = None + + +def _ensure_wal() -> None: + """Create (and re-harden) the WAL directory lazily, on the first write. + + This must NOT run at import time: a user who removed ``~/.mempalace`` has + engaged the documented kill-switch (``hooks_cli._palace_root_exists()``, + #1305), and recreating the directory just by importing this module would + silently re-arm the autosave/mining hooks they disabled (#1676). Creating + it on the first real write keeps the kill-switch contract intact. + + It is deliberately not gated on ``_palace_root_exists()``: by the time a + write reaches here the palace is already being recreated by the ChromaDB/KG + layer regardless, so gating would only drop audit records, not prevent + recreation. Runtime kill-switch enforcement for MCP writes is the broader + question tracked in #504. + + Hardening is attempted once per directory and the path cached in + ``_WAL_INITIALIZED_DIR`` regardless of outcome (keyed on the path, so a + test repointing ``_WAL_FILE`` re-initialises), so a persistent failure on a + restricted filesystem does not retry on every write. ``mkdir`` runs only + when the initial ``chmod`` raises ``FileNotFoundError`` (EAFP). The parent + ``~/.mempalace`` keeps its umask mode, like the other palace directories; + the WAL file is created atomically with mode 0o600 by ``_wal_log``. + """ + global _WAL_INITIALIZED_DIR + wal_dir = _WAL_FILE.parent + if _WAL_INITIALIZED_DIR == wal_dir: + return + try: + wal_dir.chmod(0o700) + except FileNotFoundError: + try: + wal_dir.mkdir(parents=True, exist_ok=True) + wal_dir.chmod(0o700) + except (OSError, NotImplementedError): + pass + except (OSError, NotImplementedError): + pass + # Cache regardless of outcome: one attempt per directory, so a persistent + # chmod/mkdir failure (restricted FS) is not retried on every write. + _WAL_INITIALIZED_DIR = wal_dir + # Keys whose values should be redacted in WAL entries to avoid logging sensitive content _WAL_REDACT_KEYS = frozenset( @@ -452,6 +482,9 @@ def _wal_log(operation: str, params: dict, result: dict = None): "result": result, } try: + # Dir setup shares the append's exception handler below: any WAL + # failure is logged and non-fatal, never crashing the tool call. + _ensure_wal() fd = os.open(str(_WAL_FILE), os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600) with os.fdopen(fd, "a", encoding="utf-8") as f: f.write(json.dumps(entry, default=str) + "\n") diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index 75de8fe..e1f2bd4 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -2590,6 +2590,66 @@ class TestCacheInvalidation: assert col is None +class TestImportKillSwitchSafety: + """Importing mcp_server must not recreate ~/.mempalace (#1676). + + The module-level WAL setup used to ``mkdir(parents=True)`` at import, + recreating ``~/.mempalace`` even after the user removed it as the + documented kill-switch gesture (``_palace_root_exists()``, #1305), + silently re-arming the autosave/mining hooks. WAL creation is now + deferred to the first actual write. + """ + + def test_import_does_not_recreate_palace_root(self, tmp_path): + """import mempalace.mcp_server must not create ~/.mempalace. + + Runs in a fresh subprocess with HOME pointed at tmp_path so the + assertion targets a clean filesystem, independent of conftest's + session-level HOME patch. + """ + palace_root = tmp_path / ".mempalace" + env = {k: v for k, v in os.environ.items() if not k.startswith("MEMPAL")} + env["HOME"] = str(tmp_path) + env["USERPROFILE"] = str(tmp_path) + result = subprocess.run( + [sys.executable, "-c", "import mempalace.mcp_server"], + env=env, + capture_output=True, + text=True, + timeout=30, + ) + assert result.returncode == 0, f"import failed: {result.stderr}" + assert not palace_root.exists(), ( + f"importing mcp_server recreated {palace_root} as a side effect, " + "defeating the _palace_root_exists() kill-switch (#1676)" + ) + + def test_wal_log_creates_dir_lazily_on_first_write(self, tmp_path, monkeypatch): + """_wal_log creates its directory on first use. + + Proves the deferred setup still works (defers WAL creation to write + time, does not disable it) and preserves the WAL permission bits. + """ + from mempalace import mcp_server + + wal_file = tmp_path / "fresh" / "wal" / "write_log.jsonl" + assert not wal_file.parent.exists() + monkeypatch.setattr(mcp_server, "_WAL_FILE", wal_file) + + mcp_server._wal_log("test_op", {"safe": "ok"}) + + assert wal_file.exists(), "lazy WAL init did not create the log on first write" + entry = json.loads(wal_file.read_text().strip()) + assert entry["operation"] == "test_op" + assert entry["params"]["safe"] == "ok" + + # Permission bits the refactor must preserve (POSIX only; Windows + # ignores chmod and the code swallows NotImplementedError). + if sys.platform != "win32": + assert wal_file.stat().st_mode & 0o777 == 0o600 + assert wal_file.parent.stat().st_mode & 0o777 == 0o700 + + class TestKGLazyCache: """Lazy per-path KnowledgeGraph cache (issue #1136)."""