The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: narrow an upgraded same-owner gateway.lock to 0600 instead of refusing it
Teknium7ca2d492f8e1
diff --git a/gateway/runtime_ownership.py b/gateway/runtime_ownership.pyindex ac1103977eb..e08ffafda42 100644--- a/gateway/runtime_ownership.py+++ b/gateway/runtime_ownership.py@@ -20,6 +20,27 @@ def canonical_home(home: Path) -> Path:return Path(os.path.normcase(str(Path(home).expanduser().resolve())))+def tighten_lock_mode(fd: int) -> None:+ """Validate an open ``gateway.lock`` descriptor and narrow an upgraded lock to 0600.++ Main's ``acquire_gateway_runtime_lock`` created the inode with ``open(path, "a+")`` under the+ umask (0644 on most hosts), and lock inodes are never replaced, so an upgraded home keeps that+ mode forever and discovery refuses it. Only a regular, single-link inode this user owns is+ chmodded, through the already-open NOFOLLOW descriptor (no path race); anything else is refused.+ """+ info = os.fstat(fd)+ if os.name == 'nt':+ if not stat.S_ISREG(info.st_mode):+ raise PermissionError('unsafe gateway lock owner or type')+ return+ if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid(): # windows-footgun: ok — POSIX branch+ raise PermissionError('unsafe gateway lock owner or type')+ if stat.S_IMODE(info.st_mode) & 0o077:+ if info.st_nlink != 1:+ raise PermissionError('unsafe gateway lock link count')+ os.fchmod(fd, 0o600) # windows-footgun: ok — POSIX branch++class ProfileOwnership:def __init__(self):self._handles: dict[Path, object] = {}@@ -45,9 +66,7 @@ class ProfileOwnership:fd = os.open(path, flags, 0o600)handle = os.fdopen(fd, 'r+', encoding='utf-8')try:- info = os.fstat(handle.fileno())- if not stat.S_ISREG(info.st_mode) or (os.name != 'nt' and info.st_uid != os.getuid()): # windows-footgun: ok — guarded UID- raise PermissionError('unsafe gateway lock owner or type')+ tighten_lock_mode(handle.fileno())if not _try_acquire_file_lock(handle):raise OwnershipConflict(f'Gateway runtime already owns profile {home}')record = {**_build_pid_record(), 'hermes_home': str(home)}diff --git a/hermes_cli/gateway_runtime_discovery.py b/hermes_cli/gateway_runtime_discovery.pyindex a04bc35165b..0af76eb2519 100644--- a/hermes_cli/gateway_runtime_discovery.py+++ b/hermes_cli/gateway_runtime_discovery.py@@ -1,4 +1,5 @@-"""Bounded local-control discovery without diagnostic fallback or mutation."""+"""Bounded local-control discovery without diagnostic fallback or mutation (the one exception: an+upgraded same-owner ``gateway.lock`` is narrowed to 0600, see :func:`_private_lock`)."""from __future__ import annotations@@ -177,13 +178,34 @@ def _identify_response(data: bytes) -> dict:return response["result"]+def _private_lock(lock: Path) -> None:+ """Validate ``gateway.lock``; narrow an upgraded same-owner lock to 0600 first.++ Main created the inode with ``open(path, "a+")`` under the umask (0644), and lock inodes are+ never replaced, so without this an upgraded home reads ``inaccessible`` forever and nothing+ auto-starts its owner. Only the mode is touched, only on a regular single-link inode this user+ owns, through a NOFOLLOW descriptor; a foreign or non-regular node still raises."""+ try:+ _private_node(lock, kind="file")+ except DiscoveryError as exc:+ if exc.reason != "unsafe_control_permissions":+ raise+ from gateway.runtime_ownership import tighten_lock_mode+ fd = os.open(lock, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) # windows-footgun: ok — POSIX lock only+ try:+ tighten_lock_mode(fd)+ finally:+ os.close(fd)+ _private_node(lock, kind="file")++def missing_owner_state(home: Path) -> Literal["starting", "absent", "inaccessible"]:"""A reservation before PID/control publication already excludes a new owner."""from gateway.status import _is_gateway_runtime_lock_active_strictlock = home / "gateway.lock"try:if os.name != "nt":- _private_node(lock, kind="file")+ _private_lock(lock)return "starting" if _is_gateway_runtime_lock_active_strict(lock) else "absent"except FileNotFoundError:return "absent"diff --git a/tests/hermes_cli/test_gateway_runtime_discovery.py b/tests/hermes_cli/test_gateway_runtime_discovery.pyindex f6826ae28ac..920694dd680 100644--- a/tests/hermes_cli/test_gateway_runtime_discovery.py+++ b/tests/hermes_cli/test_gateway_runtime_discovery.py@@ -95,3 +95,33 @@ def test_group_write_is_private_only_when_no_other_account_has_that_primary_grouraise OSError('passwd database unavailable')monkeypatch.setattr(pwd, 'getpwall', unreadable)assert home_mode_unsafe(home.lstat(), home) is True++[email protected]("linux", "macos")+def test_upgraded_same_owner_0644_lock_is_narrowed_not_inaccessible(tmp_path):+ """Main created gateway.lock with open("a+") under the umask (0644); the inode is never+ replaced, so discovery and reserve must narrow it in place instead of refusing it forever.+ A hardlinked lock (another name shares the inode) is never chmodded."""+ import os+ import stat+ from gateway.runtime_ownership import ProfileOwnership+ from hermes_cli.gateway_runtime_discovery import missing_owner_state+ home = tmp_path / 'profile'+ home.mkdir(mode=0o700)+ lock = home / 'gateway.lock'+ lock.touch()+ lock.chmod(0o644)+ assert missing_owner_state(home) == 'absent'+ assert stat.S_IMODE(lock.stat().st_mode) == 0o600+ lock.chmod(0o644)+ owner = ProfileOwnership()+ owner.reserve([home])+ try:+ assert stat.S_IMODE(lock.stat().st_mode) == 0o600+ assert missing_owner_state(home) == 'starting'+ finally:+ owner.close()+ lock.chmod(0o644)+ os.link(lock, tmp_path / 'alias')+ assert missing_owner_state(home) == 'inaccessible'+ assert stat.S_IMODE(lock.stat().st_mode) == 0o644