Skip to content

The agent that grows with you

fix(constants): honor managed/shared-home permission policy in get_scratch_dir

liuhao1024a5605724c21d
diff --git a/hermes_cli/config.py b/hermes_cli/config.py
index 66352cfd514..f604150dedb 100644
--- a/hermes_cli/config.py
+++ b/hermes_cli/config.py
@@ -37,6 +37,7 @@ from hermes_cli.colors import Colors, color
from hermes_cli import managed_scope
from hermes_cli.default_soul import DEFAULT_SOUL_MD, is_legacy_template_soul
from hermes_cli.secret_prompt import masked_secret_prompt
+from hermes_constants import apply_secure_dir_policy
# Re-export from hermes_constants — canonical definition lives there.
from hermes_constants import get_hermes_home, get_process_hermes_home # noqa: F401
from utils import atomic_replace, atomic_yaml_write, fast_safe_load, file_signature
@@ -612,25 +613,11 @@ def _secure_dir(path):
Also applies ``HERMES_UID``/``HERMES_GID``-based ownership when those env vars are set (#34107 — Docker
deployments need this so profile subdirs created at runtime by kanban workers don't land as root:root
and block subsequent uid-mapped workers).
+
+ Delegates to the canonical import-safe primitive ``hermes_constants.apply_secure_dir_policy``
+ so callers outside this package (``get_scratch_dir``) share one implementation (#117347).
"""
- if is_managed():
- return
- explicit_mode = os.environ.get("HERMES_HOME_MODE", "").strip()
- # Same skip as _secure_file: a bind-mounted data dir is often shared with sibling containers
- # running as other UIDs (web UI, permissions fixers); forcing 0700 on it locks them out on every
- # start (#10757). An explicit HERMES_HOME_MODE is the operator's choice and is still applied.
- if _is_container() and not explicit_mode:
- _chown_to_hermes_uid(path)
- return
- try:
- mode = int(explicit_mode or "700", 8)
- except ValueError:
- mode = 0o700
- try:
- os.chmod(path, mode)
- except (OSError, NotImplementedError):
- pass
- _chown_to_hermes_uid(path)
+ return apply_secure_dir_policy(path)
def _is_container() -> bool:
diff --git a/hermes_constants.py b/hermes_constants.py
index d4a4c37db89..8e1920d29af 100644
--- a/hermes_constants.py
+++ b/hermes_constants.py
@@ -1004,6 +1004,92 @@ def socket_safe_tmpdir() -> str:
return "/tmp" # no-tmp: ok — AF_UNIX 108-byte socket path limit on Linux
+def _is_managed_home() -> bool:
+ """Managed-install signal for the active home: the ``HERMES_MANAGED`` env var (set by the
+ systemd service) or a ``.managed`` marker file in the home (NixOS activation script).
+
+ Same values and precedence as ``hermes_cli.config.is_managed`` (an unreadable or empty
+ marker file still counts as managed; brew/homebrew and explicit false values do not) —
+ keep the two in sync. Lives here because constants must stay import-safe from the CLI.
+ """
+ marker = os.getenv("HERMES_MANAGED", "").strip().lower() or None
+ if marker is None:
+ marker_file = get_hermes_home() / ".managed"
+ if marker_file.exists():
+ try:
+ marker = marker_file.read_text(encoding="utf-8", errors="replace").strip().lower()
+ except OSError:
+ marker = ""
+ if marker is None or marker in ("", "brew", "homebrew", "false", "0", "no", "off"):
+ return False
+ return True
+
+
+def _container_or_chmod_skipped() -> bool:
+ """Docker/Podman/LXC detection honoring the ``HERMES_CONTAINER``/``HERMES_SKIP_CHMOD``
+ overrides — the same signals as ``hermes_cli.config._is_container``, deliberately not the
+ cached :func:`is_container` (that one ignores these env overrides)."""
+ if (os.environ.get("HERMES_CONTAINER") or os.environ.get("HERMES_SKIP_CHMOD")
+ or os.path.exists("/.dockerenv")):
+ return True
+ try:
+ with open("/proc/1/cgroup", "r", encoding="utf-8") as f:
+ return any(m in f.read() for m in ("docker", "lxc", "kubepods"))
+ except OSError:
+ return False
+
+
+def _chown_dir_to_hermes_uid(path) -> None:
+ """Chown *path* to ``HERMES_UID:HERMES_GID`` when set; EPERM/ENOENT are non-fatal.
+
+ Same contract as ``hermes_cli.config._chown_to_hermes_uid`` — used by
+ :func:`apply_secure_dir_policy` so Docker deployments keep directory ownership consistent.
+ """
+ def env_int(name: str):
+ try:
+ return int(os.environ.get(name, "").strip() or None)
+ except (TypeError, ValueError):
+ return None
+
+ uid, gid = env_int("HERMES_UID"), env_int("HERMES_GID")
+ if uid is None and gid is None:
+ return
+ try:
+ os.chown(path, uid if uid is not None else -1, gid if gid is not None else -1)
+ except (OSError, AttributeError, NotImplementedError):
+ pass
+
+
+def apply_secure_dir_policy(path) -> None:
+ """Apply the canonical Hermes home-directory permission policy to *path*.
+
+ Owner-only ``0700`` by default, but the operator's explicit and managed sharing choices
+ win (#117347): managed installs are left exactly as the package manager / activation
+ script set them (#77579); in a container only an explicit ``HERMES_HOME_MODE`` is applied
+ (a bind-mounted data dir is often shared with sibling containers, #10757); elsewhere
+ ``HERMES_HOME_MODE`` (e.g. ``0701``, ``2770``) overrides the mode. ``HERMES_UID`` /
+ ``HERMES_GID`` ownership is applied when those env vars are set (#34107).
+
+ Import-safe twin of ``hermes_cli.config._secure_dir`` (which delegates here), so callers
+ outside the CLI package — like :func:`get_scratch_dir` — share one policy implementation.
+ """
+ if _is_managed_home():
+ return
+ explicit_mode = os.environ.get("HERMES_HOME_MODE", "").strip()
+ if _container_or_chmod_skipped() and not explicit_mode:
+ _chown_dir_to_hermes_uid(path)
+ return
+ try:
+ mode = int(explicit_mode or "700", 8)
+ except ValueError:
+ mode = 0o700
+ try:
+ os.chmod(path, mode)
+ except (OSError, NotImplementedError):
+ pass
+ _chown_dir_to_hermes_uid(path)
+
+
def get_scratch_dir(home: str | Path | None = None, *, prune: bool = True) -> Path:
"""``<home>/cache/scratch`` (created, owner-only); *home* defaults to the active Hermes home.
@@ -1011,13 +1097,16 @@ def get_scratch_dir(home: str | Path | None = None, *, prune: bool = True) -> Pa
:func:`export_scratch_tmp_env`), so ``tempfile`` defaults land here without call sites
knowing. Entries older than ``SCRATCH_MAX_AGE_HOURS`` are pruned at most once per process
and once per hour across processes (stamp file), so a fan-out of children stays cheap.
+
+ Permissions follow :func:`apply_secure_dir_policy`, so an explicit ``HERMES_HOME_MODE`` or
+ a managed/shared home is honored instead of a blanket ``0700`` (#117347).
"""
base = Path(home) if home is not None else get_hermes_home()
scratch = base / "cache" / "scratch"
try:
scratch.mkdir(parents=True, exist_ok=True)
if sys.platform != "win32":
- os.chmod(scratch, 0o700)
+ apply_secure_dir_policy(scratch)
except OSError:
pass
if prune:
diff --git a/tests/test_scratch_dir.py b/tests/test_scratch_dir.py
index ee033a8e57d..bb3d2b2dddf 100644
--- a/tests/test_scratch_dir.py
+++ b/tests/test_scratch_dir.py
@@ -1,9 +1,13 @@
"""Scratch dir contract: TMPDIR/TMP/TEMP follow HERMES_HOME/cache/scratch unless the user set them."""
import os
+import stat
import subprocess
import sys
import time
+from unittest.mock import patch
+
+import pytest
from hermes_constants import apply_scratch_tmp_env, get_scratch_dir, prune_scratch_dir
@@ -52,3 +56,74 @@ def test_prune_removes_only_stale_top_level_entries(tmp_path):
os.utime(stale, (ancient, ancient))
assert prune_scratch_dir(scratch) == 1
assert not stale.exists() and fresh.exists()
+
+
[email protected](sys.platform == "win32", reason="POSIX directory modes")
+class TestScratchDirPermissionPolicy:
+ """get_scratch_dir must honor the home permission policy instead of a blanket 0700:
+ an explicit HERMES_HOME_MODE and a managed/shared home win (#117347)."""
+
+ def _isolate_env(self, monkeypatch, tmp_path):
+ # HERMES_HOME must point somewhere without a .managed marker, or a marker file in the
+ # real home would flip every case into "managed" (the marker is read via get_hermes_home).
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))
+ for var in ("HERMES_HOME_MODE", "HERMES_MANAGED", "HERMES_CONTAINER",
+ "HERMES_SKIP_CHMOD", "HERMES_UID", "HERMES_GID"):
+ monkeypatch.delenv(var, raising=False)
+
+ def test_default_is_owner_only(self, tmp_path, monkeypatch):
+ self._isolate_env(monkeypatch, tmp_path)
+ scratch = get_scratch_dir(tmp_path, prune=False)
+ assert stat.S_IMODE(os.stat(scratch).st_mode) == 0o700
+
+ def test_explicit_home_mode_retained_with_setgid(self, tmp_path, monkeypatch):
+ self._isolate_env(monkeypatch, tmp_path)
+ monkeypatch.setenv("HERMES_HOME_MODE", "2770")
+ scratch = get_scratch_dir(tmp_path, prune=False)
+ assert stat.S_IMODE(os.stat(scratch).st_mode) == 0o2770
+
+ def test_managed_env_leaves_preexisting_mode_untouched(self, tmp_path, monkeypatch):
+ self._isolate_env(monkeypatch, tmp_path)
+ monkeypatch.setenv("HERMES_MANAGED", "nixos")
+ pre = tmp_path / "cache" / "scratch"
+ pre.mkdir(parents=True)
+ os.chmod(pre, 0o2770)
+ scratch = get_scratch_dir(tmp_path, prune=False)
+ assert stat.S_IMODE(os.stat(scratch).st_mode) == 0o2770
+
+ def test_managed_marker_file_leaves_preexisting_mode_untouched(self, tmp_path, monkeypatch):
+ home = tmp_path / "home"
+ home.mkdir()
+ self._isolate_env(monkeypatch, tmp_path)
+ (home / ".managed").write_text("nixos", encoding="utf-8")
+ pre = tmp_path / "cache" / "scratch"
+ pre.mkdir(parents=True)
+ os.chmod(pre, 0o2770)
+ scratch = get_scratch_dir(tmp_path, prune=False)
+ assert stat.S_IMODE(os.stat(scratch).st_mode) == 0o2770
+
+ def test_repeated_calls_do_not_strip_setgid(self, tmp_path, monkeypatch):
+ self._isolate_env(monkeypatch, tmp_path)
+ monkeypatch.setenv("HERMES_HOME_MODE", "2770")
+ first = get_scratch_dir(tmp_path, prune=False)
+ second = get_scratch_dir(tmp_path, prune=False)
+ assert first == second
+ assert stat.S_IMODE(os.stat(second).st_mode) == 0o2770
+
+ def test_container_keeps_operator_mode_but_honors_explicit(self, tmp_path, monkeypatch):
+ self._isolate_env(monkeypatch, tmp_path)
+ monkeypatch.setenv("HERMES_CONTAINER", "1")
+ pre = tmp_path / "cache" / "scratch"
+ pre.mkdir(parents=True)
+ os.chmod(pre, 0o750)
+ assert stat.S_IMODE(os.stat(get_scratch_dir(tmp_path, prune=False)).st_mode) == 0o750
+ monkeypatch.setenv("HERMES_HOME_MODE", "2770")
+ assert stat.S_IMODE(os.stat(get_scratch_dir(tmp_path, prune=False)).st_mode) == 0o2770
+
+ def test_hermes_uid_gid_applied_to_scratch(self, tmp_path, monkeypatch):
+ self._isolate_env(monkeypatch, tmp_path)
+ monkeypatch.setenv("HERMES_UID", "1000")
+ monkeypatch.setenv("HERMES_GID", "911")
+ with patch.object(os, "chown") as mock_chown:
+ get_scratch_dir(tmp_path, prune=False)
+ mock_chown.assert_called_once_with(tmp_path / "cache" / "scratch", 1000, 911)