The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat: restrict runtime bootstrap peers and bound native pipe I/O
Tekniumd3ccac14e84c
diff --git a/gateway/control_socket.py b/gateway/control_socket.pyindex 0e4dbb8f9d3..5c350c98c43 100644--- a/gateway/control_socket.py+++ b/gateway/control_socket.py@@ -54,7 +54,7 @@ def _fallback_socket_path(home: Path) -> Path:"""Short temp-dir path for homes whose direct socket path exceeds sun_path: ``tempfile.gettempdir()``then ``/tmp`` (POSIX); if nothing fits the tempdir candidate is returned anyway — bind failsnon-fatally and consumers use the scan layer."""- name = f"hermes-gw-{_home_hash(home)}.sock"+ name = f"hermes-gw-{_home_hash(home)}/control.sock"candidates = [Path(tempfile.gettempdir()) / name] + ([] if _IS_WINDOWS else [Path("/tmp") / name])return next((c for c in candidates if _fits_sun_path(c)), candidates[0])@@ -136,6 +136,7 @@ class GatewayControlServer:self._pipe_server: Any = None # Windows proactor pipe serverself._bind_path: Optional[Path] = Noneself._pointer_file: Optional[Path] = None+ self._file_identities = {}self._handlers: dict[str, Callable[[], dict[str, Any]]] = {"identify": build_identify_payload, "status": build_status_payload, **(verb_handlers or {})}@@ -144,16 +145,26 @@ class GatewayControlServer:try:return await (self._start_windows() if _IS_WINDOWS else self._start_posix())except Exception as exc:+ await self.stop()logger.warning("Gateway control socket failed to start (non-fatal): %s", exc)return Falseasync def _start_posix(self) -> bool:bind_path, pointer_file = resolve_server_socket_path(self._home)+ if pointer_file is not None:+ bind_path.parent.mkdir(mode=0o700, exist_ok=True)+ info = bind_path.parent.lstat()+ if (not stat.S_ISDIR(info.st_mode) or info.st_uid != os.getuid() # windows-footgun: ok — POSIX listener+ or info.st_mode & 0o077):+ raise PermissionError("unsafe fallback control directory")+ if bind_path.is_symlink():+ raise PermissionError("control socket cannot be a symlink")# We only get here after winning the PID-file O_EXCL race, so any existing# file is stale or a collision — never a live sibling.- with contextlib.suppress(OSError):- if bind_path.exists():- bind_path.unlink()+ if bind_path.exists():+ if bind_path.lstat().st_uid != os.getuid(): # windows-footgun: ok — POSIX listener+ raise PermissionError("control socket belongs to another user")+ bind_path.unlink()# Restrictive umask so the socket is never world-connectable, even for the instant before chmod.old_umask = os.umask(0o177)try:@@ -163,34 +174,35 @@ class GatewayControlServer:with contextlib.suppress(OSError):os.chmod(bind_path, 0o600)self._bind_path = bind_path+ info = bind_path.lstat()+ self._file_identities[bind_path] = (info.st_dev, info.st_ino)if pointer_file is not None:- pointer_file.write_text(str(bind_path), encoding="utf-8")+ fd = os.open(pointer_file, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)+ with os.fdopen(fd, "w", encoding="utf-8") as pointer:+ pointer.write(str(bind_path))self._pointer_file = pointer_file+ for path in filter(None, (self._bind_path, self._pointer_file)):+ info = path.lstat()+ self._file_identities[path] = (info.st_dev, info.st_ino)logger.info("Gateway control socket listening at %s", bind_path)return Trueasync def _start_windows(self) -> bool:- loop = asyncio.get_running_loop()- start_serving_pipe = getattr(loop, "start_serving_pipe", None)- if start_serving_pipe is None:- logger.debug("Event loop %s has no start_serving_pipe — control socket "- "disabled (selector loop on Windows).", type(loop).__name__)- return False- pipe_name = windows_pipe_name(self._home)- servers = await start_serving_pipe(lambda: _PipeControlProtocol(self), pipe_name)- self._pipe_server = servers[0] if servers else None- logger.info("Gateway control pipe listening at %s", pipe_name)- return self._pipe_server is not None-+ from gateway.runtime_bootstrap_windows import NativeControlServer+ self._pipe_server = NativeControlServer(self._home, self.handle_request_line)+ await asyncio.to_thread(self._pipe_server.start)+ return Trueasync def stop(self) -> None:"""Stop serving and remove the socket/pointer files."""+ if self.ticket_store is not None:+ self.ticket_store.revoke()if self._server is not None:self._server.close()with contextlib.suppress(Exception):await self._server.wait_closed()if self._pipe_server is not None:with contextlib.suppress(Exception):- self._pipe_server.close()+ await asyncio.to_thread(self._pipe_server.close)self._server = self._pipe_server = Noneself.cleanup_files()@@ -198,7 +210,10 @@ class GatewayControlServer:"""Best-effort removal of socket + pointer files (atexit-safe)."""for path in filter(None, (self._bind_path, self._pointer_file)):with contextlib.suppress(OSError):- path.unlink(missing_ok=True)+ info = path.lstat()+ if self._file_identities.get(path) == (info.st_dev, info.st_ino):+ path.unlink()+ self._file_identities.clear()def handle_request_line(self, raw: bytes, peer_subject: Optional[str] = None) -> bytes:"""One JSON request line -> one JSON response line. Never raises (shared by POSIX + pipe)."""@@ -247,20 +262,29 @@ class GatewayControlServer:def _posix_peer_subject(self, writer) -> Optional[str]:# The legacy diagnostic channel may operate without bootstrap-safe metadata.+ if os.name == "nt":+ return Nonetry:home = self._homeinfo = home.lstat()if (home.absolute() != home.resolve() or not stat.S_ISDIR(info.st_mode)- or info.st_uid != os.getuid() or info.st_mode & 0o077):+ or info.st_uid != os.getuid() or info.st_mode & 0o077): # windows-footgun: ok — POSIX-only helperreturn Nonesock = writer.get_extra_info("socket")if hasattr(socket, "SO_PEERCRED"):_, uid, _ = struct.unpack("3i", sock.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12))- elif hasattr(sock, "getpeereid"):- uid, _ = sock.getpeereid()+ elif sys.platform == "darwin":+ import ctypes+ uid_value, gid_value = ctypes.c_uint(), ctypes.c_uint()+ getpeereid = ctypes.CDLL(None, use_errno=True).getpeereid+ getpeereid.argtypes = [ctypes.c_int, ctypes.POINTER(ctypes.c_uint), ctypes.POINTER(ctypes.c_uint)]+ getpeereid.restype = ctypes.c_int+ if getpeereid(sock.fileno(), ctypes.byref(uid_value), ctypes.byref(gid_value)) != 0:+ return None+ uid = uid_value.valueelse:return None- return f"uid:{uid}" if uid == os.getuid() else None+ return f"uid:{uid}" if uid == os.getuid() else None # windows-footgun: ok — POSIX-only helperexcept OSError:return Nonediff --git a/gateway/run.py b/gateway/run.pyindex b1d9319a0c2..d4ba6564fc0 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -4597,6 +4597,8 @@ async def start_gateway(config: Optional[GatewayConfig] = None, replace: bool =release_gateway_runtime_lock()return False+ _control_server = None+ _planned_stop_watcher_stop = Nonetry:_start_gateway_configure_logging(verbosity)@@ -4731,6 +4733,10 @@ async def start_gateway(config: Optional[GatewayConfig] = None, replace: bool =_planned_stop_watcher_stop, _planned_stop_watcher_thread, _signal_initiated_shutdown)finally:+ if _planned_stop_watcher_stop is not None:+ _planned_stop_watcher_stop.set()+ if _control_server is not None:+ await _control_server.stop()remove_pid_file()release_gateway_runtime_lock()diff --git a/gateway/runtime_bootstrap_windows.py b/gateway/runtime_bootstrap_windows.pynew file mode 100644index 00000000000..e63ed46075f--- /dev/null+++ b/gateway/runtime_bootstrap_windows.py@@ -0,0 +1,233 @@+"""Native local-only bootstrap pipes with cancellable overlapped I/O.++The single pipe thread does not own session state. Handlers marshal authority+operations to the gateway loop; the ticket store itself is thread-safe.+"""+from __future__ import annotations++import ctypes+from ctypes import wintypes+import os+from pathlib import Path+import threading+import time+++def _native():+ if os.name != 'nt':+ raise OSError('native Windows bootstrap requires Windows')+ import _winapi+ return _winapi+++def _api(dll, name, result, args):+ fn = getattr(dll, name)+ fn.restype, fn.argtypes = result, args+ return fn+++def _process_sid(pid: int) -> str:+ k = ctypes.WinDLL('kernel32', use_last_error=True)+ a = ctypes.WinDLL('advapi32', use_last_error=True)+ open_process = _api(k, 'OpenProcess', wintypes.HANDLE, [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD])+ close = _api(k, 'CloseHandle', wintypes.BOOL, [wintypes.HANDLE])+ process = open_process(0x1000, False, pid)+ if not process:+ raise PermissionError('cannot verify bootstrap peer process')+ token = wintypes.HANDLE()+ try:+ open_token = _api(a, 'OpenProcessToken', wintypes.BOOL,+ [wintypes.HANDLE, wintypes.DWORD, ctypes.POINTER(wintypes.HANDLE)])+ if not open_token(process, 8, ctypes.byref(token)):+ raise PermissionError('cannot verify bootstrap peer token')+ length = wintypes.DWORD()+ token_info = _api(a, 'GetTokenInformation', wintypes.BOOL,+ [wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(wintypes.DWORD)])+ token_info(token, 1, None, 0, ctypes.byref(length))+ buf = ctypes.create_string_buffer(length.value)+ if not token_info(token, 1, buf, length, ctypes.byref(length)):+ raise PermissionError('cannot read bootstrap peer identity')+ sid = ctypes.cast(buf, ctypes.POINTER(ctypes.c_void_p))[0]+ text = wintypes.LPWSTR()+ convert = _api(a, 'ConvertSidToStringSidW', wintypes.BOOL,+ [ctypes.c_void_p, ctypes.POINTER(wintypes.LPWSTR)])+ if not convert(sid, ctypes.byref(text)):+ raise PermissionError('cannot encode bootstrap peer identity')+ try:+ return text.value+ finally:+ _api(k, 'LocalFree', ctypes.c_void_p, [ctypes.c_void_p])(ctypes.cast(text, ctypes.c_void_p))+ finally:+ if token:+ close(token)+ close(process)+++def _peer_subject(handle, *, server: bool) -> str:+ k = ctypes.WinDLL('kernel32', use_last_error=True)+ name = 'GetNamedPipeServerProcessId' if server else 'GetNamedPipeClientProcessId'+ get_pid = _api(k, name, wintypes.BOOL, [wintypes.HANDLE, ctypes.POINTER(wintypes.ULONG)])+ pid = wintypes.ULONG()+ if not get_pid(handle, ctypes.byref(pid)):+ raise PermissionError('cannot identify named-pipe peer')+ sid = _process_sid(pid.value)+ if sid != _process_sid(os.getpid()):+ raise PermissionError('named-pipe peer belongs to another user')+ return 'sid:' + sid+++def _remaining_ms(deadline):+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ raise TimeoutError('runtime control deadline exceeded')+ return max(1, int(remaining * 1000))+++def _complete(ov, deadline):+ win = _native()+ try:+ if win.WaitForSingleObject(ov.event, _remaining_ms(deadline)) != win.WAIT_OBJECT_0:+ raise TimeoutError('runtime control deadline exceeded')+ transferred, error = ov.GetOverlappedResult(False)+ if error:+ raise OSError(error, 'runtime pipe I/O failed')+ return transferred+ except BaseException:+ # Cancel the native operation, not merely its caller's wait. Completion is+ # reaped before the buffer/OVERLAPPED can be released.+ ov.cancel()+ ov.GetOverlappedResult(True)+ raise+++def _read_line(handle, deadline, maximum):+ win = _native()+ chunks = bytearray()+ while b'\n' not in chunks:+ ov, _ = win.ReadFile(handle, min(4096, maximum + 1 - len(chunks)), overlapped=True)+ count = _complete(ov, deadline)+ if not count:+ raise ConnectionError('runtime pipe closed before response')+ chunks.extend(ov.getbuffer()[:count])+ if len(chunks) > maximum:+ raise PermissionError('runtime control message too large')+ return bytes(chunks).split(b'\n', 1)[0]+++def _write(handle, data, deadline):+ win = _native()+ while data:+ ov, _ = win.WriteFile(handle, data, overlapped=True)+ sent = _complete(ov, deadline)+ if not sent:+ raise ConnectionError('runtime pipe closed during write')+ data = data[sent:]+++def query_runtime_control(home: Path, request: bytes, timeout: float) -> bytes:+ from gateway.control_socket import windows_pipe_name+ win = _native()+ deadline = time.monotonic() + timeout+ name = windows_pipe_name(home)+ _remaining_ms(deadline)+ while True:+ try:+ handle = win.CreateFile(name, 0xC0000000, 0, win.NULL, win.OPEN_EXISTING,+ win.FILE_FLAG_OVERLAPPED | 0x00100000, win.NULL)+ break+ except OSError as exc:+ if exc.winerror == 2:+ raise FileNotFoundError('runtime control pipe absent') from None+ if exc.winerror == 5:+ raise PermissionError('runtime control pipe inaccessible') from None+ if exc.winerror != 231:+ raise+ try:+ win.WaitNamedPipe(name, _remaining_ms(deadline))+ except OSError as wait_error:+ if wait_error.winerror == 121:+ raise TimeoutError('runtime control deadline exceeded') from None+ raise+ try:+ _peer_subject(handle, server=True)+ _write(handle, request.rstrip(b'\n') + b'\n', deadline)+ return _read_line(handle, deadline, 512 * 1024) + b'\n'+ finally:+ win.CloseHandle(handle)+++class NativeControlServer:+ """One bounded native worker, independent of asyncio event-loop policy."""+ def __init__(self, home, handler):+ self.home, self.handler = home, handler+ self._stop = threading.Event()+ self._ready = threading.Event()+ self._error = None+ self._thread = threading.Thread(target=self._run, name='runtime-control-pipe', daemon=True)++ def start(self):+ self._thread.start()+ if not self._ready.wait(5):+ self.close()+ raise TimeoutError('runtime control pipe startup deadline exceeded')+ if self._error:+ raise self._error++ def close(self):+ self._stop.set()+ self._thread.join(timeout=5)+ if self._thread.is_alive():+ raise TimeoutError('runtime control pipe did not stop')++ def _create_pipe(self):+ from gateway.control_socket import windows_pipe_name+ win = _native()+ class SecurityAttributes(ctypes.Structure):+ _fields_ = [('length', wintypes.DWORD), ('descriptor', ctypes.c_void_p), ('inherit', wintypes.BOOL)]+ a = ctypes.WinDLL('advapi32', use_last_error=True)+ descriptor = ctypes.c_void_p()+ convert = _api(a, 'ConvertStringSecurityDescriptorToSecurityDescriptorW', wintypes.BOOL,+ [wintypes.LPCWSTR, wintypes.DWORD, ctypes.POINTER(ctypes.c_void_p), ctypes.c_void_p])+ # Protected DACL: exactly the current user, no inherited Everyone/Users ACEs.+ if not convert('D:P(A;;GA;;;' + _process_sid(os.getpid()) + ')', 1, ctypes.byref(descriptor), None):+ raise PermissionError('cannot create private pipe DACL')+ attrs = SecurityAttributes(ctypes.sizeof(SecurityAttributes), descriptor, False)+ try:+ return win.CreateNamedPipe(windows_pipe_name(self.home),+ 3 | win.FILE_FLAG_OVERLAPPED | 0x00080000,+ 8, 1, 65536, 65536, 2000, ctypes.addressof(attrs))+ finally:+ k = ctypes.WinDLL('kernel32', use_last_error=True)+ _api(k, 'LocalFree', ctypes.c_void_p, [ctypes.c_void_p])(descriptor)++ def _run(self):+ win = _native()+ handle = None+ try:+ handle = self._create_pipe()+ self._ready.set()+ while not self._stop.is_set():+ try:+ ov = win.ConnectNamedPipe(handle, overlapped=True)+ _complete(ov, time.monotonic() + 0.5)+ subject = _peer_subject(handle, server=False)+ deadline = time.monotonic() + 2+ raw = _read_line(handle, deadline, 64 * 1024)+ _write(handle, self.handler(raw, subject), deadline)+ # DisconnectNamedPipe discards unread output. Let the client+ # consume and close, bounded by the same I/O deadline.+ _read_line(handle, deadline, 64 * 1024)+ except (OSError, TimeoutError, ConnectionError):+ pass+ finally:+ try:+ win.DisconnectNamedPipe(handle)+ except OSError as exc:+ if exc.winerror != 233: # ERROR_PIPE_NOT_CONNECTED after a cancelled accept+ raise+ except BaseException as exc:+ self._error = exc+ self._ready.set()+ finally:+ if handle is not None:+ win.CloseHandle(handle)diff --git a/gateway/runtime_ownership.py b/gateway/runtime_ownership.pyindex 71895d85676..67d60d7f263 100644--- a/gateway/runtime_ownership.py+++ b/gateway/runtime_ownership.py@@ -44,7 +44,7 @@ class ProfileOwnership: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()):+ if not stat.S_ISREG(info.st_mode) or (os.name != 'nt' and info.st_uid != os.getuid()): # windows-footgun: ok — guarded UIDraise PermissionError('unsafe gateway lock owner or type')if not _try_acquire_file_lock(handle):raise OwnershipConflict(f'Gateway runtime already owns profile {home}')diff --git a/tests/gateway/test_control_socket.py b/tests/gateway/test_control_socket.pyindex 7dba7588f36..b331ea0e926 100644--- a/tests/gateway/test_control_socket.py+++ b/tests/gateway/test_control_socket.py@@ -183,7 +183,7 @@ def test_stale_socket_file_is_replaced_on_bind(home: Path):# Plant the stale file at wherever the server will actually bind# (in-home OR the temp-dir fallback, depending on path length).bind, _ = resolve_server_socket_path(home)- bind.parent.mkdir(parents=True, exist_ok=True)+ bind.parent.mkdir(parents=True, exist_ok=True, mode=0o700)bind.touch() # crashed predecessor's leftoverasync def scenario():diff --git a/tests/gateway/test_control_socket_windows_live.py b/tests/gateway/test_control_socket_windows_live.pyindex 6a5a25ffa01..d7e0fc8cef4 100644--- a/tests/gateway/test_control_socket_windows_live.py+++ b/tests/gateway/test_control_socket_windows_live.py@@ -2,12 +2,12 @@Runs ONLY on a real Windows host (the on-demand ``windows-venv-e2e.yml``lane). Spawns a REAL child process that binds the REAL named pipe via the-proactor event loop with the DEFAULT verb handlers, then drives the real+dedicated native pipe worker with the DEFAULT verb handlers, then drives the realsync client and the real fleet consumers against it — no mocks anywhere.Proves, on windows-latest:1. `GatewayControlServer` binds ``\\\\.\\pipe\\hermes-gateway-<hash>`` via- ``loop.start_serving_pipe`` and answers ``identify``/``status``.+ same-user local-only native pipe worker and answers ``identify``/``status``.2. The sync client's pipe transport (open/write/read/busy-retry) worksagainst a live server and returns the child's true pid + code identity.3. ``collect_fleet_versions()`` prefers the socket (``source: socket``).@@ -27,9 +27,7 @@ from pathlib import Pathimport pytest-pytestmark = pytest.mark.skipif(- sys.platform != "win32", reason="live Windows named-pipe E2E"-)+pytestmark = pytest.mark.windows_onlyPROJECT_ROOT = Path(__file__).resolve().parents[2]diff --git a/tests/gateway/test_runtime_bootstrap.py b/tests/gateway/test_runtime_bootstrap.pyindex a21715588e0..b2f4a28a2e2 100644--- a/tests/gateway/test_runtime_bootstrap.py+++ b/tests/gateway/test_runtime_bootstrap.py@@ -73,3 +73,49 @@ def test_ticket_atomic_single_use_profile_purpose_expiry_and_capacity(monkeypatcstore.mint(profile_id='a', subject='uid:1', purpose='interactive')with pytest.raises(PermissionError):store.mint(profile_id='a', subject='uid:1', purpose='interactive')++[email protected]_only+async def test_old_socket_cleanup_cannot_unlink_replacement(tmp_path):+ from gateway.control_socket import GatewayControlServer, resolve_client_socket_path+ home = tmp_path / 'private'+ home.mkdir(mode=0o700)+ old = GatewayControlServer(home)+ new = GatewayControlServer(home)+ assert await old.start()+ await old.stop()+ assert await new.start()+ try:+ old.cleanup_files()+ assert resolve_client_socket_path(home) is not None+ reader, writer = await asyncio.open_unix_connection(str(resolve_client_socket_path(home)))+ writer.write(b'{"verb":"identify"}\n')+ await writer.drain()+ assert json.loads(await reader.readline())['ok']+ writer.close()+ await writer.wait_closed()+ finally:+ await new.stop()++[email protected]_only+def test_native_pipe_authenticated_peer_and_deadline(tmp_path):+ import time+ from gateway.runtime_bootstrap_windows import NativeControlServer, query_runtime_control+ def handler(raw, subject):+ assert subject.startswith('sid:S-1-')+ if raw == b'stall':+ time.sleep(1)+ return json.dumps({'subject': subject}).encode() + b'\n'+ server = NativeControlServer(tmp_path, handler)+ server.start()+ try:+ assert json.loads(query_runtime_control(tmp_path, b'hello', 5))['subject'].startswith('sid:')+ started = time.monotonic()+ with pytest.raises(TimeoutError):+ query_runtime_control(tmp_path, b'stall', 0.1)+ assert time.monotonic() - started < 2+ finally:+ server.close()+ assert not server._thread.is_alive()diff --git a/tests/gateway/test_status.py b/tests/gateway/test_status.pyindex d17e47fa86b..933bcac47da 100644--- a/tests/gateway/test_status.py+++ b/tests/gateway/test_status.py@@ -1173,84 +1173,32 @@ class TestLaunchdPlistRespawnGovernance:class TestPermissionErrorOnLockFile:- """Stale root-owned lock files from launchd Background sessions must not- crash the gateway on restart (issue #42685)."""-- def test_permission_error_on_lock_file_returns_false_and_removes(self, tmp_path, monkeypatch):- """When the lock file is not writable (root-owned), the function should- remove the stale file and report the lock as inactive."""+ @pytest.mark.linux_only+ def test_inaccessible_lock_is_not_deleted_or_treated_as_absence(self, tmp_path, monkeypatch):monkeypatch.setenv("HERMES_HOME", str(tmp_path))- lock_path = tmp_path / "gateway.lock"- lock_path.write_text("stale", encoding="utf-8")-- real_open = open-- def deny_write(path, *args, **kwargs):- if str(path) == str(lock_path):- raise PermissionError(13, "Permission denied", str(path))- return real_open(path, *args, **kwargs)-- monkeypatch.setattr("builtins.open", deny_write)-- result = status.is_gateway_runtime_lock_active(lock_path)- assert result is False- assert not lock_path.exists(), "stale root-owned lock file should be removed"-- def test_permission_error_unlink_failure_still_returns_false(self, tmp_path, monkeypatch):- """Even if unlinking the stale lock file fails (e.g. directory not writable),- the function should still return False to allow startup."""- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- lock_path = tmp_path / "gateway.lock"- lock_path.write_text("stale", encoding="utf-8")-- real_open = open-- def deny_write(path, *args, **kwargs):- if str(path) == str(lock_path):- raise PermissionError(13, "Permission denied", str(path))- return real_open(path, *args, **kwargs)-- real_unlink = Path.unlink-- def deny_unlink(self, *args, **kwargs):- if str(self) == str(lock_path):- raise OSError(13, "Permission denied", str(self))- return real_unlink(self, *args, **kwargs)-- monkeypatch.setattr("builtins.open", deny_write)- monkeypatch.setattr(Path, "unlink", deny_unlink)-- result = status.is_gateway_runtime_lock_active(lock_path)- assert result is False-- def test_acquire_gateway_runtime_lock_recovers_from_permission_error(self, tmp_path, monkeypatch):- """acquire_gateway_runtime_lock must survive a stale root-owned lock- file: unlink it and retry with a fresh file instead of crashing."""- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- lock_path = status._get_gateway_lock_path()- lock_path.parent.mkdir(parents=True, exist_ok=True)- lock_path.write_text("stale", encoding="utf-8")-- real_open = open-- def deny_write(path, *args, **kwargs):- # Simulate a root-owned file: opening fails while the ORIGINAL- # stale file is still on disk; after unlink, the fresh file the- # retry creates opens fine.- if (- str(path) == str(lock_path)- and lock_path.exists()- and lock_path.read_text(encoding="utf-8") == "stale"- ):- raise PermissionError(13, "Permission denied", str(path))- return real_open(path, *args, **kwargs)-- monkeypatch.setattr("builtins.open", deny_write)-+ lock = tmp_path / "gateway.lock"+ lock.write_text("existing owner")+ inode = lock.stat().st_ino+ lock.chmod(0)try:- assert status.acquire_gateway_runtime_lock() is True+ assert status.is_gateway_runtime_lock_active(lock) is True+ assert status.acquire_gateway_runtime_lock() is False+ assert lock.stat().st_ino == inodefinally:- status.release_gateway_runtime_lock()+ lock.chmod(0o600)+ assert lock.read_text() == "existing owner"+ assert status.acquire_gateway_runtime_lock() is True+ status.release_gateway_runtime_lock()+ assert lock.stat().st_ino == inode++ @pytest.mark.linux_only+ def test_runtime_lock_does_not_follow_symlink(self, tmp_path, monkeypatch):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ target = tmp_path / "unrelated"+ target.write_text("unchanged")+ (tmp_path / "gateway.lock").symlink_to(target)+ assert status.acquire_gateway_runtime_lock() is False+ assert target.read_text() == "unchanged"class TestNormalizeUpdatedAt: