Skip to content

The agent that grows with you

fix(gateway): publish the control-socket pointer atomically

Tekniumf1d62772923e
diff --git a/gateway/control_socket.py b/gateway/control_socket.py
index 9a229844df7..f5a8122f18c 100644
--- a/gateway/control_socket.py
+++ b/gateway/control_socket.py
@@ -91,6 +91,23 @@ def _squat_proof_fallback(bind_path: Path) -> Path:
return path
+def _publish_pointer(pointer_file: Path, bind_path: Path) -> None:
+ """Replace ``pointer_file`` with one naming ``bind_path``, atomically: the listener is already
+ accepting, so a client polling for it may read the pointer at any instant, and an empty or
+ partial pointer is ``invalid_control_pointer`` to it, a refusal rather than "still starting".
+ The fresh mkstemp inode is 0600 and the rename replaces a symlink rather than following it,
+ which also heals an older gateway's leftover 0644 pointer."""
+ fd, tmp = tempfile.mkstemp(prefix=f".{pointer_file.name}.", dir=pointer_file.parent)
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8") as pointer:
+ pointer.write(str(bind_path))
+ os.replace(tmp, pointer_file)
+ except BaseException:
+ with contextlib.suppress(OSError):
+ os.unlink(tmp)
+ raise
+
+
def resolve_server_socket_path(home: Path) -> tuple[Path, Optional[Path]]:
"""Return ``(bind_path, pointer_file)``; pointer_file is set only for the temp-dir fallback."""
direct = Path(home) / _SOCKET_FILENAME
@@ -240,12 +257,7 @@ class GatewayControlServer:
info = bind_path.lstat()
self._file_identities[bind_path] = (info.st_dev, info.st_ino)
if pointer_file is not None:
- fd = os.open(pointer_file, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
- # O_CREAT's mode only applies to a NEW file; an older gateway's leftover pointer is 0644
- # and clients refuse it, so restarting must heal the mode.
- os.fchmod(fd, 0o600)
- with os.fdopen(fd, "w", encoding="utf-8") as pointer:
- pointer.write(str(bind_path))
+ _publish_pointer(pointer_file, bind_path)
self._pointer_file = pointer_file
for path in filter(None, (self._bind_path, self._pointer_file)):
info = path.lstat()
diff --git a/tests/gateway/test_control_socket_peer_security.py b/tests/gateway/test_control_socket_peer_security.py
index 718eeb61a83..fbbc9bf5719 100644
--- a/tests/gateway/test_control_socket_peer_security.py
+++ b/tests/gateway/test_control_socket_peer_security.py
@@ -41,6 +41,44 @@ def test_restart_heals_a_world_readable_pointer_left_by_an_older_gateway(tmp_pat
asyncio.run(run())
+def test_a_client_polling_during_pointer_publication_never_sees_an_invalid_pointer(tmp_path):
+ # A starting client polls discovery while the gateway publishes; the listener already
+ # accepts, so the pointer must go from absent to complete with no readable empty state
+ # (an empty one is ``invalid_control_pointer``, which a client reports as fatal).
+ import asyncio
+ import sys
+ from gateway.control_socket import GatewayControlServer
+ from hermes_cli.gateway_runtime_discovery import DiscoveryError, _socket_path
+ home = tmp_path / ("p" * 90) / ".hermes"
+ home.mkdir(parents=True, mode=0o700)
+ seen, state = [], {"armed": False}
+
+ def poll_at_every_syscall(event, _args):
+ if not state["armed"] or not event.startswith(("open", "os.")):
+ return
+ state["armed"] = False # discovery's own syscalls must not recurse
+ try:
+ seen.append(_socket_path(home).name)
+ except FileNotFoundError:
+ seen.append("absent")
+ except DiscoveryError as exc:
+ seen.append(exc.reason)
+ finally:
+ state["armed"] = True
+ sys.addaudithook(poll_at_every_syscall) # cannot be removed; disarmed outside start()
+
+ async def run():
+ server = GatewayControlServer(home)
+ state["armed"] = True
+ try:
+ assert await server.start()
+ finally:
+ state["armed"] = False
+ await server.stop()
+ asyncio.run(run())
+ assert "absent" in seen and set(seen) <= {"absent", "control.sock"}, seen
+
+
def test_group_bits_that_are_an_acl_mask_never_count_as_a_private_group(tmp_path, monkeypatch):
# With a POSIX ACL (setfacl u:nobody:rwx) the stat group bits are the mask: a 0770 home whose
# group is the owner's private one may still grant another named user write.