The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(security): harden at-rest secrets in browser profiles, media caches, and the in-flight journal
Brooklyn Nicholson6c3aae398ade
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts b/apps/desktop/src/app/session/hooks/use-session-actions/index.tsindex 187d734d843..50bd8ffed54 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts+++ b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts@@ -29,7 +29,7 @@ import {} from '@/lib/chat-messages'import { markReasoningEffortPending } from '@/lib/chat-runtime'import { isMissingRpcMethod } from '@/lib/gateway-rpc'-import { recoverInFlightTurnJournal } from '@/lib/inflight-turn-journal'+import { purgeInFlightTurnJournals, recoverInFlightTurnJournal } from '@/lib/inflight-turn-journal'import { latestSessionTodoSnapshot } from '@/lib/todos'import { setSessionYolo } from '@/lib/yolo-session'import { $clarifyRequests, clearClarifyRequest } from '@/store/clarify'@@ -3252,6 +3252,13 @@ export function useSessionActions({// back, and a rolled-back row must keep its watermark/marker.forgetSessionUnread(removedIds, profile)clearQueuedPrompts(storedSessionId)+ // The journaled in-flight tail holds this session's prompt and tool+ // calls in localStorage; a deleted session must not leave that copy+ // behind to age out on its own. Purge after the RPC lands (same+ // rollback argument as the unread watermark above), passing every id+ // the delete holds: the stored tip, the row id, the lineage root, and+ // the closing runtime id — the journal keys on the stored id.+ purgeInFlightTurnJournals([...removedIds, closingRuntimeId])if (closingRuntimeId) {clearQueuedPrompts(closingRuntimeId)diff --git a/apps/desktop/src/app/settings/sessions-settings.tsx b/apps/desktop/src/app/settings/sessions-settings.tsxindex f10fad821d5..e03f96aa93c 100644--- a/apps/desktop/src/app/settings/sessions-settings.tsx+++ b/apps/desktop/src/app/settings/sessions-settings.tsx@@ -17,6 +17,7 @@ import { useI18n } from '@/i18n'import { sessionTitle } from '@/lib/chat-runtime'import { pathLeaf } from '@/lib/display-path'import { triggerHaptic } from '@/lib/haptics'+import { purgeInFlightTurnJournals } from '@/lib/inflight-turn-journal'import { Archive, ArchiveOff, FolderOpen, Loader2, Trash2 } from '@/lib/icons'import { confirm } from '@/store/confirm'import { notify, notifyError } from '@/store/notifications'@@ -117,6 +118,12 @@ function ArchivedSessionsSettings({ includeDefaultDirectory }: { includeDefaultD// Permanent delete bypasses removeSession, so retire the persisted// unread state here too rather than leaving it to rot.forgetSessionUnread([session.id, session._lineage_root_id], session.profile)+ // Same for the journaled in-flight tail: it holds this session's+ // prompt and tool calls in localStorage, and a deleted session must+ // not leave that copy behind to age out on its own. Both ids — the+ // stored tip and the durable lineage root — the journal keys on the+ // stored id and the row may carry either.+ purgeInFlightTurnJournals([session.id, session._lineage_root_id])setLocalSessions(prev => prev.filter(s => s.id !== session.id))triggerHaptic('warning')} catch (err) {diff --git a/apps/desktop/src/lib/inflight-turn-journal.test.ts b/apps/desktop/src/lib/inflight-turn-journal.test.tsindex a9b079f81b1..79deaa49e05 100644--- a/apps/desktop/src/lib/inflight-turn-journal.test.ts+++ b/apps/desktop/src/lib/inflight-turn-journal.test.ts@@ -6,6 +6,7 @@ import {type JournalableSessionState,mergeInFlightMessages,persistInFlightTurnState,+ purgeInFlightTurnJournals,readInFlightTurnJournal,recoverInFlightTurnJournal,resetInFlightTurnJournalStateForTests@@ -829,3 +830,40 @@ describe('mid-turn redirect corrections', () => {expect(journaled.map(message => message.id)).toEqual(['user-1', 'assistant-stream-1'])})})++describe('purgeInFlightTurnJournals', () => {+ it('clears a busy session\'s journaled tail from localStorage (delete must reach the local copy)', () => {+ persistInFlightTurnState(journalState())+ vi.advanceTimersByTime(400)++ expect(readInFlightTurnJournal('stored-1')?.messages.length).toBeGreaterThan(0)++ purgeInFlightTurnJournals(['stored-1'])++ expect(readInFlightTurnJournal('stored-1')).toBeNull()+ expect(window.localStorage.getItem(sessionStorageKey('stored-1'))).toBeNull()+ })++ it('drains every id it is given, not just the stored tip', () => {+ persistInFlightTurnState(journalState({ storedSessionId: 'stored-tip' }))+ persistInFlightTurnState(journalState({ storedSessionId: 'lineage-root' }))+ vi.advanceTimersByTime(400)++ purgeInFlightTurnJournals(['stored-tip', 'lineage-root', null, undefined])++ expect(readInFlightTurnJournal('stored-tip')).toBeNull()+ expect(readInFlightTurnJournal('lineage-root')).toBeNull()+ })++ it('drops a pending throttled write so the tail cannot land after the purge', () => {+ persistInFlightTurnState(journalState())++ expect(window.localStorage.getItem(sessionStorageKey('stored-1'))).toBeNull()++ purgeInFlightTurnJournals(['stored-1'])+ vi.advanceTimersByTime(400)++ expect(window.localStorage.getItem(sessionStorageKey('stored-1'))).toBeNull()+ expect(readInFlightTurnJournal('stored-1')).toBeNull()+ })+})diff --git a/apps/desktop/src/lib/inflight-turn-journal.ts b/apps/desktop/src/lib/inflight-turn-journal.tsindex 6ca1a364d8d..ab9db4015f8 100644--- a/apps/desktop/src/lib/inflight-turn-journal.ts+++ b/apps/desktop/src/lib/inflight-turn-journal.ts@@ -1087,3 +1087,32 @@ export function clearInFlightTurnJournal(storedSessionId: null | string): void {removeSnapshot(storedSessionId)}++/** Purge journaled in-flight tails for a deleted session.+ *+ * Deleting a session removes its authoritative history, but the journal+ * kept the deleted turn's user prompt and tool calls in localStorage until+ * the entry aged out — the delete gesture did not reach the local copy (the+ * sibling `composer-queue` store was already cleared on delete; this one+ * was missed, which is the #77486 journal requirement).+ *+ * A session has more than one id, so callers pass every id they hold: the+ * stored tip, the durable lineage root, and (the sidebar delete) the+ * closing runtime id. The store keys on the stored id, so each id drains+ * its own key in a single pass; entries written by an older build under a+ * pre-rotation tip the caller no longer holds are NOT reachable this way —+ * those age out under `MAX_AGE_MS`, which is the retention floor this file+ * already documents. */+export function purgeInFlightTurnJournals(sessionIds: readonly (null | string | undefined)[]): void {+ const store = storage()++ if (!store) {+ return+ }++ for (const storedSessionId of sessionIds) {+ if (storedSessionId) {+ clearInFlightTurnJournal(storedSessionId)+ }+ }+}diff --git a/gateway/platforms/base.py b/gateway/platforms/base.pyindex b403617076f..8d7950cc2e8 100644--- a/gateway/platforms/base.py+++ b/gateway/platforms/base.py@@ -596,7 +596,7 @@ def _cache_dir_accessors(kind: str, constant_name: str, new_subpath: str, old_nadefault = _CACHE_DIR_IMPORT_DEFAULTS.get(constant_name)if current is not None and default is not None and current != default:d = Path(current)- d.mkdir(parents=True, exist_ok=True)+ _secure_media_cache_dir(d)return ddef cleanup(max_age_hours: int = 24) -> int:@@ -617,10 +617,60 @@ def _looks_like_image(data: bytes) -> bool:or (data[:4] == b"RIFF" and len(data) >= 12 and data[8:12] == b"WEBP"))+def _secure_media_cache_dir(cache_dir: Path) -> None:+ """Create/reconcile a gateway media-cache dir owner-only (0700), except managed.++ Inbound media (photos, voice notes, documents a user sent through a+ messaging platform) is user content, not regenerable cache: the+ umask-derived 0755 these dirs inherited made them readable by every other+ local account whenever ``HERMES_HOME`` is traversable — the documented+ ``HERMES_HOME_MODE=0701`` web-server hatch. The mode is passed to ``mkdir``+ so it is set at creation, then reconciled by the house policy helper+ ``hermes_cli.config._secure_dir`` (managed/NixOS installs keep their+ group-share design: these lazily-created dirs are not covered by the+ module's ``systemd.tmpfiles`` rules, so the mode is left to the+ configured umask/setgid). Best-effort: never fails a media write.+ """+ try:+ managed = False+ try:+ from hermes_cli.config import is_managed++ managed = bool(is_managed())+ except Exception: # pragma: no cover - defensive+ pass+ if managed:+ cache_dir.mkdir(parents=True, exist_ok=True)+ return+ cache_dir.mkdir(parents=True, exist_ok=True, mode=0o700)+ try:+ from hermes_cli.config import _secure_dir++ _secure_dir(cache_dir)+ except Exception as exc: # pragma: no cover - defensive+ logger.debug("media cache dir chmod skipped: %s", exc)+ except Exception as exc: # pragma: no cover - defensive+ logger.debug("media cache dir creation failed for %s: %s", cache_dir, exc)+ cache_dir.mkdir(parents=True, exist_ok=True)++def _write_cache_file(cache_dir: Path, prefix: str, ext: str, data: bytes) -> str:- """Write ``data`` to ``<cache_dir>/<prefix>_<uuid12><ext>``; return the path string."""+ """Write ``data`` to ``<cache_dir>/<prefix>_<uuid12><ext>``; return the path string.++ The file is written owner-only (0600) — inbound media is private user+ content and the cache dir is hardened to 0700 by ``_secure_media_cache_dir``;+ one directory should not carry two file-mode conventions. Best-effort on+ platforms where POSIX mode bits are advisory (Windows): falls back to a+ plain write rather than failing the media write.+ """filepath = cache_dir / f"{prefix}_{uuid.uuid4().hex[:12]}{ext}"- filepath.write_bytes(data)+ try:+ fd = os.open(str(filepath), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)+ except OSError:+ filepath.write_bytes(data)+ return str(filepath)+ with os.fdopen(fd, "wb") as handle:+ handle.write(data)return str(filepath)diff --git a/hermes_cli/browser_connect.py b/hermes_cli/browser_connect.pyindex ffa72f3ce06..59dc551563a 100644--- a/hermes_cli/browser_connect.py+++ b/hermes_cli/browser_connect.py@@ -761,6 +761,135 @@ def chrome_debug_data_dir() -> str:return str(get_hermes_home() / "chrome-debug")+def _managed_install() -> bool:+ """True when a package manager (NixOS) owns this install's modes.++ Read once per creation so the *creation* mode honours the same carve-out+ ``hermes_cli.config._secure_dir`` applies to reconciliation. Import is+ local and failure means "not managed": an unimportable config module is+ the single-user source-install case, where 0700 is the right default.+ """+ try:+ from hermes_cli.config import is_managed++ return bool(is_managed())+ except Exception: # pragma: no cover - defensive+ return False+++def _ensure_chrome_debug_data_dir(data_dir: str) -> None:+ """Create the Chromium user-data-dir owner-only (0700), except managed.++ ``chrome-debug`` is a real Chromium profile: Cookies, Login Data, and+ Local Storage live here. Created with a bare ``os.makedirs`` it inherits+ the umask and lands 0755, so every other local account could list and+ read those stores. ``HERMES_HOME`` is 0700 by default, which contains the+ damage — but the documented ``HERMES_HOME_MODE=0701`` hatch (so nginx can+ traverse to a served subdirectory) makes a 0755 child genuinely+ world-readable.++ The mode is passed to ``os.makedirs`` so it is set *at creation* — no+ window where the profile sits world-readable before a follow-up chmod.+ Policy is then reconciled by ``hermes_cli.config._secure_dir``, the house+ helper, rather than a hand-rolled chmod: it skips managed/NixOS installs,+ honours ``HERMES_HOME_MODE``, and applies ``HERMES_UID``/``HERMES_GID``+ ownership so a root-created dir does not lock out uid-mapped Docker+ workers (#34107).++ **Managed installs are skipped at creation too, not just at+ reconciliation.** ``_secure_dir`` returns early under ``is_managed()``+ because the NixOS module deliberately shares state group-wise, and+ ``chrome-debug`` is *not* one of the directories its ``systemd.tmpfiles``+ rules pre-create — it is made lazily at runtime, so a hardcoded 0700 here+ would be the only thing setting its mode and would silently override that+ design. On such a host the gateway and a hostUsers CLI share one+ ``$HERMES_HOME`` through the hermes group, so a 0700 profile created by+ whichever ran first locks the other out of the browser entirely.+ Omitting the explicit mode there lets the inherited setgid + umask decide,+ matching ``ensure_hermes_home``'s managed branch.++ Reconciling unconditionally also heals a profile an older Hermes left at+ 0755, which is the whole point — the exposure is on disk already. It is+ safe against a *running* browser: only group/other bits are dropped, the+ owner keeps ``rwx``, and POSIX checks the mode at ``open()`` rather than+ on already-open descriptors, so an attached Chromium keeps reading and+ writing its profile. On Windows POSIX mode bits are advisory (``chmod``+ only toggles the read-only flag), so this is best-effort there.+ """+ if _managed_install():+ # Managed mode: the NixOS-configured umask/setgid owns the mode, and+ # _secure_dir would no-op here anyway.+ os.makedirs(data_dir, exist_ok=True)+ return+ os.makedirs(data_dir, mode=0o700, exist_ok=True)+ try:+ from hermes_cli.config import _secure_dir++ _secure_dir(data_dir)+ except Exception as exc: # pragma: no cover - defensive+ logger.debug("browser debug launch: profile dir chmod skipped: %s", exc)+++def _open_launch_stderr_log(path: str):+ """Open the launch stderr log owner-only (0600), truncating as before.++ Opened with a plain ``open(path, "wb")`` this lands 0644 under a default+ umask — a fixed, guessable name inside the profile dir hardened just+ above. Under ``HERMES_HOME_MODE=0701`` the directory is traversable but+ unlistable, so a predictable filename is exactly the case that stays+ reachable; the uuid-named files elsewhere in the profile do not.++ Two halves, covering different installs:++ * **At creation** the mode is passed to ``os.open``, so the file is never+ briefly group/other-readable. ``O_TRUNC`` keeps the existing+ per-candidate overwrite semantics.+ * **On an already-existing log** ``O_CREAT`` applies ``mode`` only to a+ file it actually creates, so the inode keeps whatever it had. An older+ Hermes left this file at 0644 on disk, so creation-time hardening alone+ would leave every *upgrading* install exposed at the one path in this+ change with a guessable name. ``hermes_cli.config._secure_file``+ reconciles it, for the same reason ``_ensure_chrome_debug_data_dir``+ delegates to ``_secure_dir``: that helper is the single owner of the+ owner-only file policy — it skips managed/NixOS installs and containers+ and is where Windows ACL enforcement lands (#77527). Ordering: the+ reconcile runs *after* the truncating open and *before* any bytes are+ written, so the tighten lands while the file is empty.++ The managed/NixOS carve-out applies at creation here too — the same defect+ the profile directory had. This log is created lazily at runtime and is+ not covered by the module's ``systemd.tmpfiles`` rules; the gateway and an+ interactive ``hostUsers`` CLI share one ``$HERMES_HOME`` at two uids+ through the hermes group, and a 0600 log created by whichever ran first+ makes the other's truncating open fail with ``EACCES`` — and because every+ candidate binary reuses this one path, that fails *the whole launch*.+ There the inherited ``UMask = "0007"`` decides, like the merge base's+ plain ``open()``.+ """+ managed = _managed_install()+ # 0o666 rather than 0o600 on managed installs so the configured umask+ # decides, matching the merge base's plain open() and the carve-out+ # _ensure_chrome_debug_data_dir applies to the directory.+ create_mode = 0o666 if managed else 0o600+ flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC+ try:+ fd = os.open(path, flags, create_mode)+ except OSError:+ # Same fallback the pre-fix code had: let a genuinely unopenable path+ # surface to launch_chrome_debug's per-candidate handler.+ handle = open(path, "wb")+ else:+ handle = os.fdopen(fd, "wb")+ if not managed:+ try:+ from hermes_cli.config import _secure_file++ _secure_file(path)+ except Exception as exc: # pragma: no cover - defensive+ logger.debug("browser debug launch: stderr log chmod skipped: %s", exc)+ return handle++def _chrome_debug_args(port: int) -> list[str]:return [f"--remote-debugging-port={port}", f"--user-data-dir={chrome_debug_data_dir()}","--no-first-run", "--no-default-browser-check"]@@ -931,11 +1060,11 @@ def launch_chrome_debug(return resultdata_dir = chrome_debug_data_dir()- os.makedirs(data_dir, exist_ok=True)+ _ensure_chrome_debug_data_dir(data_dir)stderr_path = os.path.join(data_dir, _LAUNCH_STDERR_LOG)for candidate in candidates:try:- with open(stderr_path, "wb") as stderr_file:+ with _open_launch_stderr_log(stderr_path) as stderr_file:proc = subprocess.Popen([candidate, *_chrome_debug_args(port)],stdout=subprocess.DEVNULL, stderr=stderr_file, **_detach_kwargs(system))diff --git a/tests/hermes_cli/test_browser_connect_media_permissions.py b/tests/hermes_cli/test_browser_connect_media_permissions.pynew file mode 100644index 00000000000..2ff8404652b--- /dev/null+++ b/tests/hermes_cli/test_browser_connect_media_permissions.py@@ -0,0 +1,167 @@+"""The chrome-debug Chromium profile and Hermes media-cache dirs are created owner-only.++``$HERMES_HOME/chrome-debug`` is a real Chromium user-data dir (Cookies, Login Data,+Local Storage). A bare ``os.makedirs`` inherited the umask and landed 0755, so on the+documented ``HERMES_HOME_MODE=0701`` web-server hatch every other local account could+read those stores (#77579 / #77486). The same held for the lazily-created media caches+that hold user content — vision/computer-use captures, downloaded media, gateway inbound+media. These tests pin the creation contract: 0700 dirs at creation time, a 0600 launch+stderr log, and 0600 media files, with managed (NixOS) installs deliberately left to+the configured umask/setgid.+"""+import os+import stat++import pytest++import hermes_cli.browser_connect as bc+import tools.computer_use.tool as cu+import tools.vision_tools as vt+++def _mode(path) -> int:+ return stat.S_IMODE(os.stat(path).st_mode)+++def _no_managed(monkeypatch, home):+ """Force the not-managed branch: no HERMES_MANAGED env, no marker in ``home``."""+ monkeypatch.delenv("HERMES_MANAGED", raising=False)+ monkeypatch.delenv("HERMES_HOME_MODE", raising=False)+ monkeypatch.delenv("HERMES_UID", raising=False)+ monkeypatch.delenv("HERMES_GID", raising=False)+ monkeypatch.setattr("hermes_constants.get_hermes_home", lambda: home)+++def test_chrome_debug_data_dir_created_owner_only(tmp_path, monkeypatch):+ """A fresh chrome-debug profile dir lands 0700, not the umask-derived 0755."""+ home = tmp_path / "hh"+ _no_managed(monkeypatch, home)+ monkeypatch.setattr(bc, "get_hermes_home", lambda: home)+ bc._ensure_chrome_debug_data_dir(bc.chrome_debug_data_dir())+ assert _mode(home / "chrome-debug") == 0o700+++def test_chrome_debug_data_dir_reconciles_legacy_world_readable(tmp_path, monkeypatch):+ """A profile an older Hermes left at 0755 is tightened on the next launch — the+ exposure is already on disk, so creation-time hardening alone is not enough."""+ home = tmp_path / "hh"+ _no_managed(monkeypatch, home)+ monkeypatch.setattr(bc, "get_hermes_home", lambda: home)+ profile = home / "chrome-debug"+ profile.mkdir(parents=True, mode=0o755)+ bc._ensure_chrome_debug_data_dir(str(profile))+ assert _mode(profile) == 0o700+++def test_chrome_debug_data_dir_managed_install_leaves_mode_to_umask(tmp_path, monkeypatch):+ """Managed (NixOS) installs share $HERMES_HOME group-wise by design; the profile+ is not pre-created by tmpfiles rules, so the creation mode must stay with the+ configured umask/setgid rather than a hardcoded 0700."""+ home = tmp_path / "hh"+ monkeypatch.setenv("HERMES_MANAGED", "nixos")+ monkeypatch.delenv("HERMES_HOME_MODE", raising=False)+ monkeypatch.setattr(bc, "get_hermes_home", lambda: home)+ monkeypatch.setattr(bc, "_managed_install", lambda: True)+ profile = home / "chrome-debug"+ bc._ensure_chrome_debug_data_dir(str(profile))+ # mkdir with no explicit mode: umask applies (0o777 & ~umask); the point is that+ # the helper did NOT force 0700 — group bits survive under the service umask.+ assert _mode(profile) == 0o777 & ~_umask()+++def _umask() -> int:+ current = os.umask(0o022)+ os.umask(current)+ return current+++def test_launch_stderr_log_owner_only(tmp_path, monkeypatch):+ """The launch stderr log (fixed, guessable name inside the profile dir) is created+ 0600, and an older 0644 log is reconciled, not left exposed on upgrade."""+ home = tmp_path / "hh"+ _no_managed(monkeypatch, home)+ monkeypatch.setattr(bc, "get_hermes_home", lambda: home)+ log = home / "chrome-debug" / bc._LAUNCH_STDERR_LOG+ log.parent.mkdir(parents=True, mode=0o700)+ with bc._open_launch_stderr_log(str(log)) as handle:+ handle.write(b"stderr tail")+ assert _mode(log) == 0o600+ # Legacy exposure on disk: the reconcile must tighten it after the open.+ os.chmod(log, 0o644)+ with bc._open_launch_stderr_log(str(log)) as handle:+ handle.write(b"again")+ assert _mode(log) == 0o600+ assert log.read_bytes() == b"again" # O_TRUNC overwrite semantics preserved+++def test_vision_media_cache_dirs_created_owner_only(tmp_path, monkeypatch):+ """cache/vision and cache/video land 0700 at creation, and a legacy 0755 dir is+ healed (PR #77579's media-cache half)."""+ home = tmp_path / "hh"+ _no_managed(monkeypatch, home)+ monkeypatch.setattr(vt, "get_hermes_dir", lambda new, old: home / new)+ for sub in ("cache/vision", "cache/video"):+ assert _mode(vt._secure_cache_dir(sub, "legacy")) == 0o700+ legacy = home / "cache" / "vision"+ os.chmod(legacy, 0o755)+ assert _mode(vt._secure_cache_dir("cache/vision", "legacy")) == 0o700+++def test_vision_media_cache_files_owner_only(tmp_path, monkeypatch):+ """Media bytes written into the hardened cache land 0600, not the umask default."""+ home = tmp_path / "hh"+ _no_managed(monkeypatch, home)+ monkeypatch.setattr(vt, "get_hermes_dir", lambda new, old: home / new)+ path = vt._secure_cache_dir("cache/vision", "legacy") / "capture.png"+ vt._write_private_bytes(path, b"screen contents")+ assert path.read_bytes() == b"screen contents"+ assert _mode(path) == 0o600+++def test_computer_use_cache_files_owner_only(tmp_path, monkeypatch):+ """computer_use's capture caches (screenshots, vision temps) are created 0700 and+ the capture bytes land 0600 — a capture is as sensitive as the screen it came+ from."""+ import hermes_constants++ home = tmp_path / "hh"+ _no_managed(monkeypatch, home)+ # computer_use resolves the cache dir through the lazily-imported+ # hermes_constants.get_hermes_dir (see _cache_file), so patch it there —+ # the module attribute the import binds to, not the consumer module.+ monkeypatch.setattr(hermes_constants, "get_hermes_dir", lambda new, old: home / new)+ path = cu._cache_file("cache/vision", "temp_vision_images", "capture.png")+ cu._write_private_bytes(path, b"frame")+ assert path.read_bytes() == b"frame"+ assert _mode(path.parent) == 0o700+ assert _mode(path) == 0o600++[email protected]("getter_name", ["get_image_cache_dir", "get_video_cache_dir",+ "get_audio_cache_dir", "get_document_cache_dir",+ "get_screenshot_cache_dir"])+def test_gateway_media_cache_dirs_created_owner_only(tmp_path, monkeypatch, getter_name):+ """The gateway's inbound-media caches (photos/voice notes/documents users sent)+ land 0700 at creation and heal a legacy 0755 dir."""+ import gateway.platforms.base as gw+ home = tmp_path / "hh"+ _no_managed(monkeypatch, home)+ monkeypatch.setattr(gw, "get_hermes_dir", lambda new, old: home / new)+ for name in gw._CACHE_DIR_IMPORT_DEFAULTS:+ monkeypatch.setattr(gw, name, None, raising=False)+ cache_dir = getattr(gw, getter_name)()+ assert _mode(cache_dir) == 0o700+ os.chmod(cache_dir, 0o755)+ assert _mode(getattr(gw, getter_name)()) == 0o700+++def test_gateway_media_cache_files_owner_only(tmp_path, monkeypatch):+ """Inbound media bytes written into the gateway cache land 0600."""+ import gateway.platforms.base as gw+ home = tmp_path / "hh"+ _no_managed(monkeypatch, home)+ monkeypatch.setattr(gw, "get_hermes_dir", lambda new, old: home / new)+ for name in gw._CACHE_DIR_IMPORT_DEFAULTS:+ monkeypatch.setattr(gw, name, None, raising=False)+ path_str = gw.cache_image_from_bytes(b"\x89PNG\r\n\x1a\n" + b"photo bytes" * 8)+ assert _mode(path_str) == 0o600diff --git a/tools/computer_use/tool.py b/tools/computer_use/tool.pyindex 84cef3d96e8..e3c9d92fce1 100644--- a/tools/computer_use/tool.py+++ b/tools/computer_use/tool.py@@ -741,12 +741,71 @@ def _maybe_follow_capture(backend: ComputerUseBackend, res: ActionResult, do_capreturn json.dumps({**json.loads(resp), **payload}) # text capture: merge the action payload in# ── Cache files (screenshots, element spills, vision temps) ─────────────────+def _secure_dir_policy(cache_dir) -> None:+ """Create/reconcile a Hermes media-cache dir owner-only (0700), except managed.++ A capture is as sensitive as the screen it came from — an open password+ manager, a private chat, a bank tab. The umask-derived 0755 these dirs+ used to get made every local account able to list (and read) those+ frames whenever ``HERMES_HOME`` itself is traversable, which is exactly+ what the documented ``HERMES_HOME_MODE=0701`` web-server escape hatch+ arranges. Delegates to the same house policy as every Hermes secret dir —+ ``hermes_cli.config._secure_dir`` — with the mode passed to ``mkdir`` so+ there is no window between mkdir and chmod; managed/NixOS installs keep+ their group-share design (the mode is left to the configured umask/setgid+ because these lazily-created dirs are not covered by the module's+ ``systemd.tmpfiles`` rules). Best-effort; never breaks a capture.+ """+ try:+ managed = False+ try:+ from hermes_cli.config import is_managed++ managed = bool(is_managed())+ except Exception: # pragma: no cover - defensive+ pass+ if managed:+ cache_dir.mkdir(parents=True, exist_ok=True)+ return+ cache_dir.mkdir(parents=True, exist_ok=True, mode=0o700)+ try:+ from hermes_cli.config import _secure_dir++ _secure_dir(cache_dir)+ except Exception as exc: # pragma: no cover - defensive+ logger.debug("computer_use: cache dir chmod skipped: %s", exc)+ except Exception as exc: # pragma: no cover - defensive+ logger.debug("computer_use: cache dir creation failed for %s: %s", cache_dir, exc)+ cache_dir.mkdir(parents=True, exist_ok=True)+++def _write_private_bytes(path, data: bytes) -> None:+ """Write ``data`` to ``path`` with owner-only (0600) permissions.++ ``Path.write_bytes`` would land 0644 under a default umask. POSIX mode+ bits are advisory on Windows (``os.chmod`` there only toggles the+ read-only flag), so this is a best-effort narrowing that falls back to a+ plain write rather than failing the capture.+ """+ import os as _os_priv++ flags = _os_priv.O_WRONLY | _os_priv.O_CREAT | _os_priv.O_TRUNC+ try:+ fd = _os_priv.open(str(path), flags, 0o600)+ except OSError:+ path.write_bytes(data)+ return+ with _os_priv.fdopen(fd, "wb") as handle:+ handle.write(data)++def _cache_file(subdir: str, legacy: str, name: str, pattern: str = "", cap: int = 0):- """Path for a new file under ``$HERMES_HOME/<subdir>`` (dir created). With ``pattern``/``cap``, first unlinks the- oldest matching files so at most ``cap - 1`` remain (best-effort)."""+ """Path for a new file under ``$HERMES_HOME/<subdir>`` (dir created owner-only, per #77579).+ With ``pattern``/``cap``, first unlinks the oldest matching files so at most ``cap - 1`` remain+ (best-effort)."""from hermes_constants import get_hermes_dir # lazy so tests can patch get_hermes_dircache_dir = get_hermes_dir(subdir, legacy)- cache_dir.mkdir(parents=True, exist_ok=True)+ _secure_dir_policy(cache_dir)with contextlib.suppress(Exception):files = sorted(cache_dir.glob(pattern), key=lambda p: p.stat().st_mtime) if pattern else []for stale in files[: max(0, len(files) - (cap - 1))]:@@ -768,7 +827,8 @@ def _persist_capture_image(cap: CaptureResult) -> Optional[str]:"""Copy of the capture in Hermes' media cache so attachment surfaces can deliver it (None without an image)."""return _write_cache_file("screenshot persistence", "cache/images", "image_cache", f"computer_use_{uuid.uuid4().hex}{_capture_image_format(cap)[1]}",- "computer_use_*.*", _MAX_CAPTURE_FILES, lambda p: p.write_bytes(base64.b64decode(cap.png_b64, validate=False)),+ "computer_use_*.*", _MAX_CAPTURE_FILES,+ lambda p: _write_private_bytes(p, base64.b64decode(cap.png_b64, validate=False)),) if cap.png_b64 else Nonedef _spill_elements_to_file(cap: CaptureResult) -> Optional[str]:@@ -856,7 +916,7 @@ def _route_capture_through_aux_vision(cap: CaptureResult, summary: str, *, visibext = _capture_image_format(cap)[1]temp_image_path = _cache_file("cache/vision", "temp_vision_images", f"computer_use_{uuid.uuid4().hex}{ext}")raw, scale_note = _shrink_capture_for_vision(raw, ext)- temp_image_path.write_bytes(raw)+ _write_private_bytes(temp_image_path, raw)prompt = _VISION_PROMPT + summary + (f"\n\nNote: {scale_note}" if scale_note else "")result_json = _run_async(vision_analyze_tool(str(temp_image_path), prompt))except Exception as exc:diff --git a/tools/vision_tools.py b/tools/vision_tools.pyindex 390968a9ec9..a0f05a5daf2 100644--- a/tools/vision_tools.py+++ b/tools/vision_tools.py@@ -149,6 +149,103 @@ _DOWNLOAD_USER_AGENT = ()+def _managed_install() -> bool:+ """True when a package manager (NixOS) owns this install's modes.++ Mirrors the check ``hermes_cli.config._secure_dir`` makes internally, read+ here so the *creation* mode honours the same carve-out as reconciliation.+ Import is local and failure means "not managed": an unimportable config+ module is the single-user source-install case, where 0700 is correct.+ """+ try:+ from hermes_cli.config import is_managed++ return bool(is_managed())+ except Exception: # pragma: no cover - defensive+ return False+++def _secure_cache_dir(new_subpath: str, old_name: str) -> Path:+ """Resolve a Hermes media-cache dir, creating it owner-only (0700).++ A downloaded image or video is as sensitive as whatever the user pointed+ the agent at — a private attachment, an internal screenshot, a document+ scan. Created with a bare ``mkdir(parents=True, exist_ok=True)`` these+ inherited the umask and landed 0755, readable by every other local+ account. ``HERMES_HOME`` is 0700 by default so default-config exposure is+ narrow; the concrete scenario is the documented ``HERMES_HOME_MODE=0701``+ hatch (letting nginx/caddy traverse to a served subdirectory), where a+ 0755 child really is world-readable.++ The mode is passed to ``mkdir`` so it is set *at creation*, leaving no+ window where the directory sits world-readable before a follow-up chmod.+ Policy is then reconciled through ``hermes_cli.config._secure_dir`` — the+ house helper — rather than a hand-rolled chmod, which is what keeps this+ correct off a single-user desktop: managed/NixOS installs are skipped,+ ``HERMES_HOME_MODE`` stays honoured, and ``HERMES_UID``/``HERMES_GID``+ ownership is applied so a root-created dir does not lock out uid-mapped+ Docker workers (#34107).++ The managed/NixOS carve-out applies to **creation as well as+ reconciliation**. ``cache/vision`` and ``cache/video`` are not among the+ directories the NixOS module's ``systemd.tmpfiles`` rules pre-create, so+ they are made lazily at runtime; a hardcoded 0700 here would be the only+ thing setting their mode and would silently override a design that pins+ ``stateDir/.hermes`` to ``2770`` and runs the gateway with ``UMask =+ "0007"`` so "interactive users in the hermes group can read/write"+ gateway-created state. On such a host the gateway and a hostUsers CLI+ share one ``$HERMES_HOME``, so a 0700 cache created by whichever ran+ first makes vision fail with EACCES for the other. Skipping the explicit+ mode there lets the inherited setgid + umask land 2770, matching+ ``ensure_hermes_home``'s managed branch and its ``logs/curator``+ lazy-mkdir precedent.++ Running it unconditionally also heals a directory an older Hermes left at+ 0755. That retroactive tighten is safe *here* because this is+ Hermes-private scratch that the same user re-reads in the same call —+ there is no user-shared content to strand. Note ``parents=True`` applies+ the mode to the leaf only, so an intermediate ``cache/`` keeps its default+ mode; it is shared with other subsystems and holds only directory names.+ """+ cache_dir = get_hermes_dir(new_subpath, old_name)+ if _managed_install():+ # Managed mode: the NixOS-configured umask/setgid owns the mode, and+ # _secure_dir would no-op here anyway.+ cache_dir.mkdir(parents=True, exist_ok=True)+ return cache_dir+ # mode= is honored only for the leaf and is not further masked by umask+ # for the bits we care about; _secure_dir reconciles anything unusual.+ cache_dir.mkdir(parents=True, exist_ok=True, mode=0o700)+ try:+ from hermes_cli.config import _secure_dir++ _secure_dir(cache_dir)+ except Exception as exc: # pragma: no cover - defensive+ logger.debug("vision: cache dir chmod skipped: %s", exc)+ return cache_dir+++def _write_private_bytes(path: Path, data: bytes) -> None:+ """Write ``data`` to ``path`` with owner-only (0600) permissions.++ ``Path.write_bytes`` lands 0644 under a default umask. The enclosing cache+ dir is 0700, so this matters only under ``HERMES_HOME_MODE=0701`` — but+ ``tools.computer_use.tool`` already writes private captures into this+ very directory, and one directory with two file-mode conventions is the+ kind of inconsistency that rots. POSIX mode bits are advisory on Windows+ (``os.chmod`` there only toggles the read-only flag), so on an ``os.open``+ failure this degrades to a plain write rather than failing the download.+ """+ flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC+ try:+ fd = os.open(str(path), flags, 0o600)+ except OSError:+ path.write_bytes(data)+ return+ with os.fdopen(fd, "wb") as handle:+ handle.write(data)++async def _ssrf_redirect_guard(response):"""Re-validate each redirect target (a public URL 302ing to 169.254.169.254 would otherwisebypass the pre-flight check). Async because httpx.AsyncClient awaits hooks."""@@ -547,10 +644,9 @@ async def _prepare_image(resolved = await resolve_image_source(image_url, ResolveContext(task_id=task_id))except ImageResolutionError as exc:raise _ImagePrepError(str(exc)) from exc- temp_dir = get_hermes_dir("cache/vision", "temp_vision_images")- temp_dir.mkdir(parents=True, exist_ok=True)+ temp_dir = _secure_cache_dir("cache/vision", "temp_vision_images")path = temp_dir / f"temp_image_{uuid.uuid4()}.img"- await asyncio.to_thread(path.write_bytes, resolved.data)+ await asyncio.to_thread(_write_private_bytes, path, resolved.data)mime, size_bytes, crop_offset = resolved.mime, len(resolved.data), {}try:normalized_path, mime, norm_err = await asyncio.to_thread(_normalize_to_supported_image, path, mime)@@ -990,10 +1086,9 @@ async def _materialize_video(video_url: str, task_id: Optional[str], temp_paths:video_url, ResolveContext(task_id=task_id), permitted=("video",))except ImageResolutionError as exc:raise ValueError(f"Could not read video from terminal backend: {exc}") from exc- temp_dir = get_hermes_dir("cache/video", "temp_video_files")- temp_dir.mkdir(parents=True, exist_ok=True)+ temp_dir = _secure_cache_dir("cache/video", "temp_video_files")path = temp_dir / f"terminal_video_{uuid.uuid4()}{suffix}"- path.write_bytes(resolved.data)+ _write_private_bytes(path, resolved.data)temp_paths.append(path)return pathif local_path.is_file():@@ -1005,7 +1100,13 @@ async def _materialize_video(video_url: str, task_id: Optional[str], temp_paths:blocked = check_website_access(video_url)if blocked:raise PermissionError(blocked["message"])- path = get_hermes_dir("cache/video", "temp_video_files") / f"temp_video_{uuid.uuid4()}.mp4"+ # Hardened here rather than inside _download_media: that helper takes+ # a caller-supplied destination (tools/image_source.py hands its+ # sibling a /tmp NamedTemporaryFile it owns the mode of), and+ # chmod-ing an arbitrary caller's parent to 0700 would be a+ # destructive side effect on a path Hermes does not own.+ temp_dir = _secure_cache_dir("cache/video", "temp_video_files")+ path = temp_dir / f"temp_video_{uuid.uuid4()}.mp4"temp_paths.append(path)# Video downloads retry every failure class (legacy behavior).await _download_media(diff --git a/tools/vision_tools_image_prep.py b/tools/vision_tools_image_prep.pyindex 7d5474b2ed8..d9099ebdc3e 100644--- a/tools/vision_tools_image_prep.py+++ b/tools/vision_tools_image_prep.py@@ -166,8 +166,8 @@ def rasterize_svg_data_url(url: str) -> Optional[str]:raw = base64.b64decode(payload) if ";base64" in header.lower() else unquote(payload).encode()except Exception:return None- out_dir = get_hermes_dir("cache/vision", "temp_vision_images")- out_dir.mkdir(parents=True, exist_ok=True)+ from tools.vision_tools import _secure_cache_dir, _write_private_bytes+ out_dir = _secure_cache_dir("cache/vision", "temp_vision_images")stem = out_dir / f"inline_{uuid.uuid4()}"svg_path, png_path = stem.with_suffix(".svg"), stem.with_suffix(".png")try:@@ -189,8 +189,8 @@ def _normalize_to_supported_image(Pillow-readable rasters (BMP, TIFF) re-encode to PNG."""if detected_mime in _supported_media_types():return image_path, detected_mime, None- out_dir = get_hermes_dir("cache/vision", "temp_vision_images")- out_dir.mkdir(parents=True, exist_ok=True)+ from tools.vision_tools import _secure_cache_dir+ out_dir = _secure_cache_dir("cache/vision", "temp_vision_images")out_path = out_dir / f"converted_{uuid.uuid4()}.png"if detected_mime == "image/svg+xml":if _rasterize_svg_to_png(image_path, out_path):