The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
security: make state databases and snapshots owner-only
Hermes fleet-fix1916cb249d56
diff --git a/hermes_cli/backup.py b/hermes_cli/backup.pyindex 19d7ec9bd2d..ee00de7605a 100644--- a/hermes_cli/backup.py+++ b/hermes_cli/backup.py@@ -322,6 +322,21 @@ def _safe_copy_db(src: Path, dst: Path, *, timeout_seconds: float = 10.0) -> boo"""conn = backup_conn = Nonetry:+ # sqlite3.connect() creates a missing destination with the process+ # umask, which is commonly 0022 (0644). Snapshot databases contain+ # session and tool state, so create the inode owner-only before SQLite+ # writes its first byte. O_NOFOLLOW also refuses a planted symlink on+ # platforms that support it. Tighten an existing internal staging+ # file as well (NamedTemporaryFile callers already create it 0600).+ if os.name != "nt":+ open_flags = os.O_WRONLY | os.O_CREAT+ if hasattr(os, "O_NOFOLLOW"):+ open_flags |= os.O_NOFOLLOW+ secure_fd = os.open(dst, open_flags, 0o600)+ try:+ os.fchmod(secure_fd, 0o600)+ finally:+ os.close(secure_fd)# timeout=0.0 disables sqlite3's implicit busy wait so the progress callback owns the# full locked-source deadline instead of adding the default timeout before each callback.conn = sqlite3.connect(f"file:{src}?mode=ro", uri=True, timeout=0.0)@@ -1182,6 +1197,25 @@ def _copy_quick_snapshot_files(return manifest, failed_dbs, oversized_skipped+def _secure_quick_snapshot_tree(root: Path, snapshot_dir: Path) -> None:+ """Make a staged quick snapshot owner-only before it is published.++ The staging directory is private from creation, so copied source modes can+ be normalized safely before the final atomic rename exposes the snapshot.+ Permission failures are intentionally fatal: publishing a readable+ recovery bundle is worse than reporting a failed snapshot.+ """+ if os.name == "nt":+ return+ os.chmod(root, 0o700)+ os.chmod(snapshot_dir, 0o700)+ for path in snapshot_dir.rglob("*"):+ if path.is_dir():+ os.chmod(path, 0o700)+ elif path.is_file():+ os.chmod(path, 0o600)++def _create_quick_snapshot_locked(label: Optional[str], home: Path, keep: Optional[int], max_file_size: Optional[int]) -> Optional[str]:@@ -1199,7 +1233,10 @@ def _create_quick_snapshot_locked(suffix += 1staging_dir = root / f".{snap_id}.{os.getpid()}.partial"shutil.rmtree(staging_dir, ignore_errors=True)- staging_dir.mkdir(parents=True, exist_ok=False)+ root.mkdir(parents=True, exist_ok=True, mode=0o700)+ if os.name != "nt":+ os.chmod(root, 0o700)+ staging_dir.mkdir(mode=0o700, exist_ok=False)logger.info("quick snapshot phase=copy status=started id=%s", snap_id)manifest, failed_dbs, oversized_skipped = _copy_quick_snapshot_files(home, staging_dir, max_file_size)if failed_dbs:@@ -1221,6 +1258,7 @@ def _create_quick_snapshot_locked(}with open(staging_dir / "manifest.json", "w", encoding="utf-8") as f:json.dump(meta, f, indent=2)+ _secure_quick_snapshot_tree(root, staging_dir)os.replace(staging_dir, root / snap_id)# Auto-prune (pre-update callers pass a smaller keep so state.db copies don't accumulate).# Skip when a DB failed to capture OR was skipped for size (#68805): the snapshot isdiff --git a/hermes_state.py b/hermes_state.pyindex a079b0d0b38..2f9d621303e 100644--- a/hermes_state.py+++ b/hermes_state.py@@ -218,6 +218,42 @@ def _ensure_test_isolation(db_path: Path) -> None:)+def _secure_state_db_files(db_path: Path, *, create_main: bool = False) -> None:+ """Create/tighten a writable state database and its sidecars to 0600.++ SQLite otherwise creates ``state.db``, ``-wal``, and ``-shm`` according to+ the process umask (commonly 0644 under 0022). Use file descriptors so a+ missing main database is private from its first byte and O_NOFOLLOW can+ refuse a planted symlink. Read-only SessionDB attachments never call this+ helper and remain observational.+ """+ if os.name == "nt":+ return++ for index, path in enumerate(+ (+ db_path,+ db_path.with_name(db_path.name + "-wal"),+ db_path.with_name(db_path.name + "-shm"),+ )+ ):+ flags = os.O_RDONLY+ if index == 0 and create_main:+ flags = os.O_WRONLY | os.O_CREAT+ if hasattr(os, "O_NOFOLLOW"):+ flags |= os.O_NOFOLLOW+ if hasattr(os, "O_CLOEXEC"):+ flags |= os.O_CLOEXEC+ try:+ fd = os.open(path, flags, 0o600)+ except FileNotFoundError:+ continue+ try:+ os.fchmod(fd, 0o600)+ finally:+ os.close(fd)++# Openings of the background-review harness prompts (agent/background_review.py)._REVIEW_HARNESS_PREFIXES = ("Review the conversation above and update the skill library",@@ -625,6 +661,9 @@ class SessionDB(# Unknown -> reads queue on the writer lock (slow but correct) instead of racing SQLITE_BUSY# on a file that may really be in rollback-journal mode.self._wal_active = mode == "wal" and _on_disk_journal_mode(conn) == "wal"+ # Existing WAL/SHM files may predate the main-file hardening;+ # normalize any sidecars that became visible during WAL setup.+ _secure_state_db_files(self.db_path)apply_database_pragmas(conn, db_label="state.db")conn.execute("PRAGMA foreign_keys=ON")self._fts_cjk_loaded = load_fts5_cjk_extension(conn)@@ -637,6 +676,9 @@ class SessionDB(# Refuse before sqlite3.connect (under the startup lock) so we cannot mint# a replacement WAL while a live writer still holds a deleted sidecar inode.refuse_deleted_wal_generation(self.db_path)+ # Create/tighten the main database before sqlite3.connect() so a+ # permissive process umask can never expose a fresh profile store.+ _secure_state_db_files(self.db_path, create_main=True)self._conn = self._open_writer_conn()self._init_schema()diff --git a/tests/hermes_cli/test_backup_stability.py b/tests/hermes_cli/test_backup_stability.pyindex d461d507220..d3cb81c3209 100644--- a/tests/hermes_cli/test_backup_stability.py+++ b/tests/hermes_cli/test_backup_stability.py@@ -1,6 +1,9 @@from __future__ import annotationsimport json+import os+import sqlite3+import statfrom pathlib import Pathimport pytest@@ -82,6 +85,39 @@ def test_quick_snapshot_is_published_with_manifest(tmp_path, monkeypatch) -> Nonassert manifest["files"] == {"config.yaml": 10}[email protected](os.name == "nt", reason="POSIX permission bits")+def test_quick_snapshot_tree_is_owner_only_under_permissive_umask(tmp_path) -> None:+ """Recovery snapshots must never inherit world-readable default modes.++ A normal 0022 umask creates SQLite databases and JSON files as 0644 and+ directories as 0755. Quick snapshots contain session state, credentials,+ pairing records, and cron data, so every published file must be 0600 and+ every directory 0700 regardless of the caller's umask or source modes.+ """+ home = tmp_path / ".hermes"+ home.mkdir()+ (home / "config.yaml").write_text("model: {}\n", encoding="utf-8")+ with sqlite3.connect(home / "state.db") as conn:+ conn.execute("CREATE TABLE sessions (id TEXT PRIMARY KEY)")++ old_umask = os.umask(0o022)+ try:+ snapshot_id = create_quick_snapshot(hermes_home=home)+ finally:+ os.umask(old_umask)++ assert snapshot_id is not None+ root = home / "state-snapshots"+ snapshot = root / snapshot_id+ directories = [root, snapshot, *(p for p in snapshot.rglob("*") if p.is_dir())]+ files = [p for p in snapshot.rglob("*") if p.is_file()]++ assert directories+ assert files+ assert all(stat.S_IMODE(path.stat().st_mode) == 0o700 for path in directories)+ assert all(stat.S_IMODE(path.stat().st_mode) == 0o600 for path in files)++def test_quick_snapshot_listing_ignores_partial_directories(tmp_path) -> None:home = tmp_path / ".hermes"partial = home / "state-snapshots" / ".unfinished.1.partial"diff --git a/tests/test_hermes_state.py b/tests/test_hermes_state.pyindex c0e3abf2015..53849a3904b 100644--- a/tests/test_hermes_state.py+++ b/tests/test_hermes_state.py@@ -5,6 +5,8 @@ import reimport sqlite3import timeimport json+import os+import statimport threadingfrom pathlib import Pathfrom unittest import mock@@ -119,6 +121,49 @@ def _no_fts_rebuild_throttle(monkeypatch):class TestConnectionLifecycle:+ @pytest.mark.skipif(os.name == "nt", reason="POSIX permission bits")+ def test_writable_state_db_is_owner_only_under_permissive_umask(self, tmp_path):+ """state.db and any live SQLite sidecars must not inherit 0644 modes."""+ db_path = tmp_path / "state.db"++ old_umask = os.umask(0o022)+ try:+ session_db = SessionDB(db_path=db_path)+ finally:+ os.umask(old_umask)++ try:+ state_files = [+ path+ for path in (+ db_path,+ db_path.with_name(db_path.name + "-wal"),+ db_path.with_name(db_path.name + "-shm"),+ )+ if path.exists()+ ]+ assert state_files+ assert all(+ stat.S_IMODE(path.stat().st_mode) == 0o600+ for path in state_files+ )+ finally:+ session_db.close()++ @pytest.mark.skipif(os.name == "nt", reason="POSIX permission bits")+ def test_writable_state_db_tightens_existing_loose_mode(self, tmp_path):+ """Opening a legacy 0644 profile store repairs it in place."""+ db_path = tmp_path / "state.db"+ initial = SessionDB(db_path=db_path)+ initial.close()+ os.chmod(db_path, 0o644)++ session_db = SessionDB(db_path=db_path)+ try:+ assert stat.S_IMODE(db_path.stat().st_mode) == 0o600+ finally:+ session_db.close()+def test_failed_writable_open_does_not_leak_tracked_connection(self, tmp_path, monkeypatch):