Skip to content

The agent that grows with you

fix(gateway): a failed host attach never exits 0, and SIGTERM clears the record

teknium1f9b8cf7c42c3
diff --git a/gateway/host_rendezvous.py b/gateway/host_rendezvous.py
index 735280e36f7..55c9e8eb901 100644
--- a/gateway/host_rendezvous.py
+++ b/gateway/host_rendezvous.py
@@ -22,7 +22,7 @@ STALE and is ignored — an attaching client must never dial a recycled PID's po
**Relationship to ``spawn-ledger.json``** (``hermes_cli/process_identity.py``): the ledger stays
the append-only machine roster of every long-lived Hermes process (Desktop's attach ladder reads
it) and is still written unchanged. It cannot be the host record: it has no lock, no
-single-writer semantics, no removal on clean exit, and no place to publish a protocol version or
+single-writer semantics, no removal on exit, and no place to publish a protocol version or
an authentication handle. The record here is authoritative for "who owns this host role"; the
ledger remains authoritative for "what is running". Both are written, and this module reuses the
ledger's ``(pid, create_time)`` liveness proof rather than inventing a second one.
@@ -31,10 +31,12 @@ ledger's ``(pid, create_time)`` liveness proof rather than inventing a second on
from __future__ import annotations
import contextlib
+import enum
import hashlib
import json
import logging
import os
+import sys
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
@@ -48,13 +50,25 @@ logger = logging.getLogger(__name__)
#: does not recognise the version refuses to attach instead of guessing.
HOST_PROTOCOL_VERSION = 1
+#: Token-gated endpoint the owner answers with its own identity. An attaching client dials the
+#: RECORDED port and only attaches when the answer is the recorded owner — a record alone proves
+#: nothing about who holds that port right now.
+HOST_IDENTITY_PATH = "/api/host/identity"
+
+#: Bounded: a closed port, a black-holed one or a foreign listener must cost a second, not a hang.
+PROBE_TIMEOUT_S = 2.0
+
ROLE_GATEWAY = "gateway"
ROLE_SERVE = "serve"
_ROLES = (ROLE_GATEWAY, ROLE_SERVE)
-# Open lock handles, keyed by role: the OS releases the flock when this process dies, which is
-# what makes a crashed owner's host lock re-acquirable without a reaper.
-_lock_handles: dict[str, Any] = {}
+# Open lock handles, keyed by (role, resolved lock path): the OS releases the flock when this
+# process dies, which is what makes a crashed owner's host lock re-acquirable without a reaper.
+# The PATH is part of the key because the lock dir is env-derived (HERMES_GATEWAY_LOCK_DIR):
+# keyed by role alone, a second call after the dir changed returned "already held" without ever
+# creating the new lock file, so owns_host_lock() lied and one pytest process leaked the handle
+# across tests.
+_lock_handles: dict[tuple[str, str], Any] = {}
@dataclass(frozen=True)
@@ -156,9 +170,12 @@ def _pid_incarnation_matches(pid: int, create_time: Optional[float]) -> Optional
def record_is_stale(record: Optional[HostRecord]) -> bool:
"""A record nobody may attach to: absent, unknown protocol, dead PID, or PID reuse.
- ``None`` from the liveness probe (no psutil, permission denied) is NOT stale — refusing to
- attach on an unprovable answer is the safe direction for a *singleton*, but declaring the
- owner dead on one would let a second process bind a second port, which is the bug.
+ ``None`` from the liveness probe (no psutil, permission denied, an unexpected psutil error)
+ means UNPROVABLE, and an unprovable record is a CANDIDATE, never an owner: it survives this
+ predicate only to be handed to :func:`probe_owner`, which dials the recorded port and makes
+ the owner prove itself. Treating unprovable as dead would let a second process bind a second
+ port; treating it as alive *without the probe* made a record for a long-dead PID a permanent
+ silent outage (attach exited 0 forever, with nothing listening).
"""
if record is None:
return True
@@ -167,6 +184,60 @@ def record_is_stale(record: Optional[HostRecord]) -> bool:
return _pid_incarnation_matches(record.pid, record.create_time) is False
+def liveness_is_proven(record: HostRecord) -> bool:
+ """True only when the PID+createTime probe positively matched (never on ``None``)."""
+ return _pid_incarnation_matches(record.pid, record.create_time) is True
+
+
+def dial_host(record: HostRecord) -> str:
+ """Address to dial for ``record``: a wildcard bind is reached over loopback."""
+ host = record.host or "127.0.0.1"
+ return "127.0.0.1" if host in ("0.0.0.0", "::", "*", "") else host
+
+
+def probe_owner(record: HostRecord, *, timeout: float = PROBE_TIMEOUT_S) -> Optional[dict]:
+ """Make the recorded endpoint prove it is this record's owner; ``None`` when it does not.
+
+ Two gates, both required: a bounded TCP connect (nothing listening → the owner is gone, even
+ though its record and PID may still look alive during a graceful-shutdown window) and an
+ identity GET authenticated with the 0600 token (a foreign listener that inherited the port
+ answers the connect but cannot answer as PID N of role R).
+
+ Returns the owner's identity payload (``pid``/``role``/``servesSpa``) on success.
+ """
+ if not record.port:
+ return None
+ import socket
+
+ host = dial_host(record)
+ try:
+ with socket.create_connection((host, record.port), timeout=timeout):
+ pass
+ except OSError:
+ logger.debug("host %s owner does not answer at %s:%s", record.role, host, record.port)
+ return None
+
+ import urllib.request
+
+ token = read_token(record.role)
+ headers = {"X-Hermes-Token": token, "Authorization": f"Bearer {token}"} if token else {}
+ request = urllib.request.Request(
+ f"http://{host}:{record.port}{HOST_IDENTITY_PATH}", headers=headers)
+ try:
+ with urllib.request.urlopen(request, timeout=timeout) as response: # noqa: S310 — fixed http scheme
+ if response.status != 200:
+ return None
+ payload = json.loads(response.read(65536).decode("utf-8", "replace"))
+ except Exception:
+ logger.debug("host %s identity probe failed at %s:%s", record.role, host, record.port, exc_info=True)
+ return None
+ if not isinstance(payload, dict):
+ return None
+ if payload.get("role") != record.role or payload.get("pid") != record.pid:
+ return None
+ return payload
+
+
def read_record(role: str, *, include_stale: bool = False) -> Optional[HostRecord]:
"""Published record for ``role``; ``None`` when absent, corrupt or (by default) stale."""
try:
@@ -185,10 +256,11 @@ def read_record(role: str, *, include_stale: bool = False) -> Optional[HostRecor
def read_token(role: str) -> str:
"""Owner-written session token for ``role`` (``""`` when absent/unreadable).
- The file is 0600, so reading it proves the caller is the same OS user that owns the record —
- which is exactly the authority boundary the host lock is scoped to. This is the handle an
- attaching client uses when the backend is auth-gated and therefore withholds its token from
- an unauthenticated ``GET /``.
+ This is the handle an attaching client uses when the backend is auth-gated and therefore
+ withholds its token from an unauthenticated ``GET /``. Confidentiality is enforced at WRITE
+ time by :func:`_write_private_text` (POSIX ``0o600``; an owner+SYSTEM-only protected DACL on
+ Windows, where mode bits set no ACLs at all). Reading it is therefore evidence of, not proof
+ of, same-OS-user authority — the authority boundary the host lock is scoped to.
"""
try:
return token_path(role).read_text(encoding="utf-8").strip()
@@ -209,7 +281,19 @@ def record_token_is_consistent(record: HostRecord) -> bool:
def _write_private_text(path: Path, text: str) -> None:
- """Create/replace ``path`` with 0600 content (owner-only), atomically via tmp + replace."""
+ """Create/replace ``path`` with owner-only content.
+
+ POSIX: ``0o600`` via tmp + atomic replace. Windows: mode bits set NO ACLs, so the same
+ ``os.open`` would leave a live session token readable by whatever the inherited DACL grants;
+ the SSH runtime's protected owner+SYSTEM DACL writer is the repo's primitive for exactly this
+ credential class and is reused here. It also replaces in place, because ``os.replace`` onto a
+ token file another process still holds open fails on Windows.
+ """
+ if sys.platform == "win32":
+ from hermes_cli.windows_ssh_runtime import write_private_file
+
+ write_private_file(path, text.encode("utf-8"))
+ return
tmp = path.with_name(path.name + ".tmp")
fd = os.open(str(tmp), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
try:
@@ -225,31 +309,55 @@ def _write_private_text(path: Path, text: str) -> None:
os.replace(str(tmp), str(path))
-def acquire_host_lock(role: str) -> bool:
- """Take the host-wide lock for ``role``. Idempotent; False when another process holds it."""
+class HostLockOutcome(enum.Enum):
+ """Why a host-lock claim ended the way it did.
+
+ ``COULD_NOT_OPEN`` is NOT contention: a read-only/undeletable lock dir (EROFS, EACCES,
+ ENOSPC) collapsed into the same \"another owner holds it\" log and sent operators hunting a
+ second gateway that never existed.
+ """
+
+ ACQUIRED = "acquired"
+ HELD_BY_OTHER = "held-by-other"
+ COULD_NOT_OPEN = "could-not-open"
+
+
+def _lock_key(role: str) -> tuple[str, str]:
+ path = lock_path(role)
+ with contextlib.suppress(OSError):
+ return (role, os.path.abspath(str(path)))
+ return (role, str(path))
+
+
+def claim_host_lock(role: str) -> tuple[HostLockOutcome, Optional[OSError]]:
+ """Take the host-wide lock for ``role``. Idempotent per (role, lock path).
+
+ Returns the outcome and, for ``COULD_NOT_OPEN``, the OSError that explains it.
+ """
role = _validated_role(role)
- if _lock_handles.get(role) is not None:
- return True
+ key = _lock_key(role)
+ if _lock_handles.get(key) is not None:
+ return (HostLockOutcome.ACQUIRED, None)
from gateway.status import _try_acquire_file_lock
- path = lock_path(role)
+ path = Path(key[1])
try:
path.parent.mkdir(parents=True, exist_ok=True)
handle = open(path, "a+", encoding="utf-8")
- except OSError:
+ except OSError as exc:
logger.debug("host %s lock could not be opened at %s", role, path, exc_info=True)
- return False
+ return (HostLockOutcome.COULD_NOT_OPEN, exc)
if not _try_acquire_file_lock(handle):
with contextlib.suppress(OSError):
handle.close()
- return False
- _lock_handles[role] = handle
- return True
+ return (HostLockOutcome.HELD_BY_OTHER, None)
+ _lock_handles[key] = handle
+ return (HostLockOutcome.ACQUIRED, None)
def release_host_lock(role: str) -> None:
"""Release the host lock for ``role`` when this process holds it."""
- handle = _lock_handles.pop(_validated_role(role), None)
+ handle = _lock_handles.pop(_lock_key(_validated_role(role)), None)
if handle is None:
return
from gateway.status import _release_file_lock
@@ -261,7 +369,7 @@ def release_host_lock(role: str) -> None:
def owns_host_lock(role: str) -> bool:
"""True when THIS process holds the host lock for ``role`` (re-probing our own flock lies)."""
- return _lock_handles.get(_validated_role(role)) is not None
+ return _lock_handles.get(_lock_key(_validated_role(role))) is not None
def publish_record(
@@ -291,16 +399,18 @@ def publish_record(
try:
record_path(role).parent.mkdir(parents=True, exist_ok=True)
if token:
+ # No record without its token: publishing one an attaching client cannot
+ # authenticate against would degrade to a silent "attach refused forever".
_write_private_text(token_path(role), token)
atomic_json_write(record_path(role), record.to_json(), mode=0o600)
except OSError:
- logger.debug("host %s record publish failed", role, exc_info=True)
+ logger.warning("host %s record could not be published; discovery will not find it", role, exc_info=True)
return None
return record
def clear_record(role: str) -> None:
- """Remove this process's record + token on clean exit (never another owner's)."""
+ """Remove this process's record + token on exit (never another owner's)."""
role = _validated_role(role)
existing = read_record(role, include_stale=True)
if existing is not None and existing.pid != os.getpid():
@@ -310,6 +420,69 @@ def clear_record(role: str) -> None:
path.unlink(missing_ok=True)
+# Roles this process must clean up on the way out, and the signal handlers we prepended.
+_cleanup_roles: list[str] = []
+_prev_signal_handlers: dict[int, Any] = {}
+
+
+def _cleanup_role(role: str) -> None:
+ with contextlib.suppress(Exception):
+ clear_record(role)
+ with contextlib.suppress(Exception):
+ release_host_lock(role)
+
+
+def _handle_terminating_signal(signum, frame) -> None:
+ """Drop the record + token, then hand off to the handler we prepended to."""
+ import signal as _signal
+
+ for role in tuple(_cleanup_roles):
+ _cleanup_role(role)
+ prev = _prev_signal_handlers.get(signum)
+ if callable(prev):
+ prev(signum, frame)
+ return
+ if prev is _signal.SIG_IGN:
+ return
+ with contextlib.suppress(Exception):
+ _signal.signal(signum, _signal.SIG_DFL)
+ os.kill(os.getpid(), signum)
+ raise SystemExit(128 + int(signum))
+
+
+def cleanup_on_exit(role: str) -> None:
+ """Clear ``role``'s record + token and release its lock on exit — SIGTERM included.
+
+ ``atexit`` alone is false advertising for the NORMAL stop: systemd stop, ``docker stop`` and
+ the update relaunch all send SIGTERM, and every terminating SIGTERM path here ends in the
+ default disposition (uvicorn's ``capture_signals`` re-raises it after its graceful shutdown),
+ which kills the process without running ``atexit``. The record then outlived its process and
+ the 0600 token kept a LIVE session token on disk indefinitely.
+
+ The handler only PREPENDS cleanup: whatever handler was installed before (uvicorn's graceful
+ shutdown, the exit-flush chain, a supervisor's) still runs, so the shutdown sequence is
+ unchanged.
+ """
+ import atexit
+ import signal as _signal
+ import threading
+
+ role = _validated_role(role)
+ if role not in _cleanup_roles:
+ _cleanup_roles.append(role)
+ atexit.register(_cleanup_role, role)
+ if threading.current_thread() is not threading.main_thread():
+ return
+ for name in ("SIGTERM", "SIGBREAK"):
+ signum = getattr(_signal, name, None)
+ if signum is None or signum in _prev_signal_handlers:
+ continue
+ with contextlib.suppress(ValueError, OSError, RuntimeError):
+ prev = _signal.getsignal(signum)
+ _signal.signal(signum, _handle_terminating_signal)
+ _prev_signal_handlers[signum] = prev
+
+
def served_profiles() -> tuple[str, ...]:
"""Profiles this process multiplexes; ``()`` when the roster cannot be read."""
try:
diff --git a/gateway/run.py b/gateway/run.py
index 163d9957f7b..06913a21050 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -5181,14 +5181,19 @@ def _claim_host_gateway_role() -> None:
so a host with two gateways (the shape the multiplex-only ruling forbids) starts as it always
did and says so in the log. Flipping this into a refusal is a separate, reviewable change.
"""
- import atexit
from gateway import host_rendezvous as hr
try:
- if hr.acquire_host_lock(hr.ROLE_GATEWAY):
+ outcome, error = hr.claim_host_lock(hr.ROLE_GATEWAY)
+ if outcome is hr.HostLockOutcome.ACQUIRED:
hr.publish_record(hr.ROLE_GATEWAY, profiles=hr.served_profiles())
- atexit.register(hr.clear_record, hr.ROLE_GATEWAY)
- atexit.register(hr.release_host_lock, hr.ROLE_GATEWAY)
+ # SIGTERM (systemd stop, docker stop, the update relaunch) does not run atexit.
+ hr.cleanup_on_exit(hr.ROLE_GATEWAY)
+ return
+ if outcome is hr.HostLockOutcome.COULD_NOT_OPEN:
+ logger.warning(
+ "Host gateway lock could not be opened (%s); this gateway is not discoverable. "
+ "No second gateway is implied — the lock directory itself is unusable.", error)
return
owner = hr.read_record(hr.ROLE_GATEWAY)
logger.warning(
diff --git a/gateway/status.py b/gateway/status.py
index 5e8267020cf..0302da6d419 100644
--- a/gateway/status.py
+++ b/gateway/status.py
@@ -317,7 +317,10 @@ def _get_lock_dir() -> Path:
override = os.getenv("HERMES_GATEWAY_LOCK_DIR")
if override:
return Path(override)
- state_home = Path(os.getenv("XDG_STATE_HOME", Path.home() / ".local" / "state"))
+ # XDG spec: a relative $XDG_STATE_HOME is INVALID and must be ignored. Honouring one made the
+ # lock dir CWD-relative, so two serves started from different directories shared no singleton.
+ state_home_env = os.getenv("XDG_STATE_HOME") or ""
+ state_home = Path(state_home_env) if os.path.isabs(state_home_env) else Path.home() / ".local" / "state"
return state_home / "hermes" / _LOCKS_DIRNAME
diff --git a/hermes_cli/main_dashboard.py b/hermes_cli/main_dashboard.py
index a6067dec79e..fcc927dd887 100644
--- a/hermes_cli/main_dashboard.py
+++ b/hermes_cli/main_dashboard.py
@@ -758,6 +758,7 @@ def _host_backend_attachment():
this port" proved nothing about WHO answers (a foreign service, or a recycled PID's new
owner). The record carries ``(pid, createTime)`` so liveness is proved against the same
incarnation, and its token fingerprint must still match the 0600 token file the owner wrote.
+ The record only nominates a CANDIDATE; :func:`_attach_to_host_backend` makes it prove itself.
"""
try:
from gateway import host_rendezvous as hr
@@ -770,14 +771,60 @@ def _host_backend_attachment():
return None
+def _explicit_endpoint_flags(argv=None) -> set:
+ """Which of ``--host``/``--port`` the operator actually typed.
+
+ argparse defaults are indistinguishable from a typed value in ``args``, and the difference is
+ load-bearing: an unset ``--port`` may attach to whatever port the host owner bound, but a
+ typed ``--port 8899`` or ``--host 0.0.0.0`` (LAN access) must never be silently answered with
+ a loopback attach on some other port.
+ """
+ typed = set()
+ for token in (sys.argv[1:] if argv is None else argv):
+ name = str(token).split("=", 1)[0]
+ if name in ("--host", "--port"):
+ typed.add(name[2:])
+ return typed
+
+
+def _endpoint_conflict(args, record, typed: set) -> str:
+ """Why an explicitly requested endpoint cannot be served by ``record`` ('' when it can)."""
+ if "port" in typed:
+ wanted_port = getattr(args, "port", None)
+ # ``--port 0`` is "any free port", not a demand for a specific one.
+ if isinstance(wanted_port, int) and wanted_port > 0 and wanted_port != record.port:
+ return f"--port {wanted_port} (the host owner is on port {record.port})"
+ if "host" in typed:
+ wanted_host = str(getattr(args, "host", "") or "")
+ owner_host = record.host or "127.0.0.1"
+ loopback = {"127.0.0.1", "localhost", "::1"}
+ wildcard = {"0.0.0.0", "::", "*"}
+ # A wildcard owner already answers on loopback; anything else must match exactly.
+ reachable = wanted_host == owner_host or (owner_host in wildcard and wanted_host in loopback)
+ if not reachable:
+ return f"--host {wanted_host} (the host owner is bound to {owner_host})"
+ return ""
+
+
def _attach_to_host_backend(args, headless_backend: bool) -> None:
"""Multiplex-only: a second `hermes serve`/`dashboard` attaches to the host backend.
Exactly ONE backend runs per host and multiplexes every profile, so a second invocation —
for ANY profile, the default included — reports the live one and exits 0 instead of binding
a second port. ``--isolated`` opts out (Desktop's SSH backend proves ownership with it) and
- Desktop pool backends (HERMES_DESKTOP=1) keep their own lifecycle. Returns normally when no
- live record exists, leaving the re-exec fallback below to run.
+ Desktop pool backends (HERMES_DESKTOP=1) keep their own lifecycle.
+
+ Exit 0 means "the host backend answered and serves what you asked for", and nothing else:
+
+ * the owner must ANSWER on its recorded port and identify itself (a record alone cannot see a
+ graceful-shutdown window or a foreign listener that inherited the port) — a supervisor or
+ `hermes update` relaunch landing in that window would otherwise exit 0 with NOTHING
+ listening, reporting success for a dead service;
+ * an explicitly typed ``--port``/``--host`` the owner cannot serve is a non-zero REFUSAL
+ naming the owner, never a silent redirect;
+ * a `hermes dashboard` user is never handed a headless backend's URL (no SPA behind it).
+
+ Returns normally — leaving the caller to BIND — when no owner answers.
"""
if getattr(args, "isolated", False) or os.environ.get("HERMES_DESKTOP") == "1":
return
@@ -785,13 +832,35 @@ def _attach_to_host_backend(args, headless_backend: bool) -> None:
if record is None:
return
+ from gateway import host_rendezvous as hr
+
+ identity = hr.probe_owner(record)
+ if identity is None:
+ # Unprovable liveness (no psutil), a closed port, a foreign listener: all mean "no owner
+ # answered". Fall through to the bind — never exit 0 on an attach that did not happen.
+ return
+
+ typed = _explicit_endpoint_flags()
+ conflict = _endpoint_conflict(args, record, typed)
+ if conflict:
+ print(f"Refusing to start: this host is already served by {hr.describe(record)}.")
+ print(f" You asked for {conflict}.")
+ print(" Stop that backend, or drop the flag to use the running one.")
+ sys.exit(1)
+
+ if not headless_backend and not identity.get("servesSpa"):
+ print(f"Refusing to start: this host is already served by {hr.describe(record)}, "
+ "which is a headless `hermes serve` backend with no dashboard UI.")
+ print(" Stop it and run `hermes dashboard`, or use --isolated for a dedicated server.")
+ sys.exit(1)
+
try:
from hermes_cli.profiles import get_active_profile_name
profile = get_active_profile_name()
except Exception:
profile = "default"
wanted = getattr(args, "open_profile", "") or profile
- url = f"http://{record.host or '127.0.0.1'}:{record.port}/?profile={wanted}"
+ url = f"http://{hr.dial_host(record)}:{record.port}/?profile={wanted}"
kind = "backend" if headless_backend else "dashboard"
print(f"Hermes {kind} already running on this host: PID {record.pid}, port {record.port}.")
diff --git a/hermes_cli/web_routers/status.py b/hermes_cli/web_routers/status.py
index 86994a6f7cc..0581514a03f 100644
--- a/hermes_cli/web_routers/status.py
+++ b/hermes_cli/web_routers/status.py
@@ -118,6 +118,23 @@ async def get_health():
"auth_required": bool(getattr(app.state, "auth_required", False))}
[email protected]("/api/host/identity")
+async def get_host_identity(request: Request):
+ """Prove to an attaching `hermes serve`/`dashboard` WHO owns this port.
+
+ The host rendezvous record names a (pid, port) owner, but a record cannot say whether that
+ owner still holds the port: a graceful-shutdown window or an unrelated listener that
+ inherited the port both look identical on disk. The attaching side dials this endpoint with
+ the owner's 0600 token and attaches only when pid+role match. ``servesSpa`` is false for
+ headless ``serve``, so a `hermes dashboard` user is never routed to a backend with no UI.
+ """
+ _require_token(request)
+ # ``role`` is the host ROLE this process owns (gateway/host_rendezvous.ROLE_SERVE), not the
+ # launch mode: `hermes serve` and `hermes dashboard` are one host role that differ in SPA.
+ return {"ok": True, "protocolVersion": 1, "pid": os.getpid(), "role": "serve",
+ "servesSpa": bool(getattr(app.state, "serves_spa", False))}
+
+
@router.get("/api/health/idle")
async def get_health_idle(request: Request):
"""Token-gated diagnostic snapshot; never a retirement permit. None means cannot prove idle."""
diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.py
index 6d575eb4293..81859abc0bb 100644
--- a/hermes_cli/web_server.py
+++ b/hermes_cli/web_server.py
@@ -1257,6 +1257,9 @@ def _on_server_started(
actual_port = _read_bound_port(server, fallback=port)
app.state.bound_port = actual_port
+ # Published by /api/host/identity: an attaching `hermes dashboard` must never be routed to a
+ # headless backend (a URL with no UI behind it).
+ app.state.serves_spa = not headless
# Positive process identity in the machine spawn ledger (+ Windows
# kill-on-close job). Registered AFTER the bind so the entry carries the
@@ -1278,11 +1281,15 @@ def _on_server_started(
# after the bind so the record carries the real port, and beside — not instead of — the
# spawn-ledger entry above, which Desktop's attach ladder reads.
def _publish_host_record() -> None:
- import atexit
-
from gateway import host_rendezvous as hr
- if not hr.acquire_host_lock(hr.ROLE_SERVE):
+ outcome, error = hr.claim_host_lock(hr.ROLE_SERVE)
+ if outcome is hr.HostLockOutcome.COULD_NOT_OPEN:
+ _log.warning(
+ "Host backend lock could not be opened (%s); this backend is not discoverable. "
+ "This is NOT another backend holding it.", error)
+ return
+ if outcome is hr.HostLockOutcome.HELD_BY_OTHER:
owner = hr.read_record(hr.ROLE_SERVE)
_log.warning(
"Another backend already owns this host (%s); this one bound anyway "
@@ -1299,8 +1306,8 @@ def _on_server_started(
# authenticate even when the backend is gated and `GET /` withholds it.
token=_SESSION_TOKEN,
)
- atexit.register(hr.clear_record, hr.ROLE_SERVE)
- atexit.register(hr.release_host_lock, hr.ROLE_SERVE)
+ # SIGTERM included: it is the normal stop, and it does not run atexit here.
+ hr.cleanup_on_exit(hr.ROLE_SERVE)
_best_effort("host rendezvous publish", _publish_host_record)
diff --git a/hermes_cli/windows_ssh_runtime.py b/hermes_cli/windows_ssh_runtime.py
index 975c2b9a898..a80099f43b9 100644
--- a/hermes_cli/windows_ssh_runtime.py
+++ b/hermes_cli/windows_ssh_runtime.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import contextlib
import importlib
import json
import os
@@ -180,6 +181,20 @@ def _write_new(path: Path, data: bytes, share: int = 0) -> None:
win32file.CloseHandle(handle)
+def write_private_file(path: Path, data: bytes) -> None:
+ """Create/replace ``path`` with an owner+SYSTEM-only protected DACL (Windows only).
+
+ The repo's writer for any credential landing on a Windows disk: ``os.open(..., 0o600)`` sets
+ no ACLs there at all, so a token written that way inherits whatever the parent directory
+ grants. CreateFile ignores the security descriptor when the file already exists, so an
+ existing file is removed first rather than re-opened — which also avoids ``os.replace``
+ failing against a reader that still holds the old file open.
+ """
+ with contextlib.suppress(FileNotFoundError):
+ os.unlink(str(path))
+ _write_new(path, data)
+
+
def _ensure_directory(path: Path) -> None:
w = _win32()
pywintypes, win32con, win32file = w.pywintypes, w.win32con, w.win32file
diff --git a/tests/gateway/test_host_rendezvous.py b/tests/gateway/test_host_rendezvous.py
index a0265f5d0b7..3cddd99f8dd 100644
--- a/tests/gateway/test_host_rendezvous.py
+++ b/tests/gateway/test_host_rendezvous.py
@@ -2,6 +2,8 @@
import json
import os
+import signal
+import socket
import subprocess
import sys
import time
@@ -18,11 +20,23 @@ from gateway.status import acquire_gateway_runtime_lock
from gateway import host_rendezvous as hr
print(json.dumps({{
"per_home": acquire_gateway_runtime_lock(),
- "host": hr.acquire_host_lock(hr.ROLE_GATEWAY),
+ "host": hr.claim_host_lock(hr.ROLE_GATEWAY)[0] is hr.HostLockOutcome.ACQUIRED,
}}), flush=True)
time.sleep(60)
"""
+# Publishes a serve record + its 0600 token, arms the exit cleanup, then waits to be killed.
+_SIGTERM_CHILD = """
+import sys, time
+sys.path.insert(0, {tree!r})
+from gateway import host_rendezvous as hr
+assert hr.claim_host_lock(hr.ROLE_SERVE)[0] is hr.HostLockOutcome.ACQUIRED
+hr.publish_record(hr.ROLE_SERVE, host="127.0.0.1", port=9119, token="live-session-token")
+hr.cleanup_on_exit(hr.ROLE_SERVE)
+print("published", flush=True)
+time.sleep(120)
+"""
+
@pytest.fixture
def host_dir(tmp_path, monkeypatch):
@@ -32,13 +46,17 @@ def host_dir(tmp_path, monkeypatch):
hr.release_host_lock(hr.ROLE_SERVE)
+def _tree() -> str:
+ return str(Path(__file__).resolve().parents[2])
+
+
def test_two_homes_take_their_own_per_home_lock_but_only_one_host_lock(host_dir, monkeypatch):
"""The per-home lock is per HERMES_HOME (N profiles = N locks); the host lock is not.
This is the whole point of the host layer: before it, a second profile's gateway took its
own ``gateway.lock`` and nothing on the machine noticed.
"""
- tree = str(Path(__file__).resolve().parents[2])
+ tree = _tree()
home_a, home_b = host_dir / "home_a", host_dir / "home_b"
for home in (home_a, home_b):
home.mkdir()
@@ -60,7 +78,8 @@ def test_two_homes_take_their_own_per_home_lock_but_only_one_host_lock(host_dir,
from gateway import status
assert status.acquire_gateway_runtime_lock() is True, "second home must get its OWN lock"
- assert hr.acquire_host_lock(hr.ROLE_GATEWAY) is False, "host lock is not per-home"
+ assert hr.claim_host_lock(hr.ROLE_GATEWAY)[0] is hr.HostLockOutcome.HELD_BY_OTHER, \
+ "host lock is not per-home"
finally:
child.kill()
child.wait(timeout=10)
@@ -87,3 +106,96 @@ def test_stale_record_is_never_attachable(host_dir, pid, create_time):
assert hr.record_is_stale(record) is True
assert hr.read_record(hr.ROLE_SERVE) is None
assert hr.read_record(hr.ROLE_SERVE, include_stale=True) is not None
+
+
[email protected](sys.platform == "win32", reason="POSIX signal disposition")
+def test_sigterm_removes_the_record_and_its_live_session_token(host_dir):
+ """SIGTERM is the NORMAL stop (systemd stop, docker stop, the update relaunch) and it does not
+ run ``atexit``: the record outlived its process and the 0600 token kept a LIVE session token
+ on disk indefinitely, so the next launch attached to something that was gone."""
+ env = {**os.environ, "HERMES_GATEWAY_LOCK_DIR": str(host_dir / "locks")}
+ child = subprocess.Popen(
+ [sys.executable, "-c", _SIGTERM_CHILD.format(tree=_tree())], env=env, cwd=_tree(),
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
+ assert child.stdout is not None
+ try:
+ assert child.stdout.readline().strip() == "published"
+ assert hr.record_path(hr.ROLE_SERVE).exists()
+ assert hr.token_path(hr.ROLE_SERVE).exists()
+
+ child.send_signal(signal.SIGTERM)
+ child.wait(timeout=30)
+ finally:
+ if child.poll() is None:
+ child.kill()
+ child.wait(timeout=10)
+
+ assert not hr.record_path(hr.ROLE_SERVE).exists(), "record outlived its process"
+ assert not hr.token_path(hr.ROLE_SERVE).exists(), "live session token outlived its process"
+ assert hr.claim_host_lock(hr.ROLE_SERVE)[0] is hr.HostLockOutcome.ACQUIRED, "host lock not released"
+
+
+def test_unopenable_lock_dir_is_not_reported_as_another_owner(host_dir, monkeypatch):
+ """EROFS/EACCES/ENOSPC is a THIRD outcome: collapsing it into contention told operators
+ another gateway owned the host and sent them hunting a process that never existed."""
+ blocked = host_dir / "blocked"
+ blocked.write_text("not a directory", encoding="utf-8")
+ monkeypatch.setenv("HERMES_GATEWAY_LOCK_DIR", str(blocked / "locks"))
+
+ outcome, error = hr.claim_host_lock(hr.ROLE_SERVE)
+
+ assert outcome is hr.HostLockOutcome.COULD_NOT_OPEN
+ assert isinstance(error, OSError)
+
+
+def test_lock_cache_follows_the_lock_directory(host_dir, monkeypatch, tmp_path):
+ """The handle cache is keyed by (role, resolved path): keyed by role alone it reported
+ "already held" for a directory it had never created, so ``owns_host_lock()`` lied."""
+ assert hr.claim_host_lock(hr.ROLE_SERVE)[0] is hr.HostLockOutcome.ACQUIRED
+ moved = tmp_path / "other-locks"
+ monkeypatch.setenv("HERMES_GATEWAY_LOCK_DIR", str(moved))
+
+ assert hr.owns_host_lock(hr.ROLE_SERVE) is False
+ assert hr.claim_host_lock(hr.ROLE_SERVE)[0] is hr.HostLockOutcome.ACQUIRED
+ assert (moved / "host-serve.lock").exists()
+ hr.release_host_lock(hr.ROLE_SERVE)
+
+
+def test_probe_owner_refuses_a_closed_port_and_a_foreign_listener(host_dir):
+ """The two shapes the record cannot see: the owner's socket is already closed (the
+ graceful-shutdown window) and an unrelated process holds the port."""
+ import dataclasses
+
+ closed = socket.socket()
+ closed.bind(("127.0.0.1", 0))
+ dead_port = closed.getsockname()[1]
+ closed.close()
+ record = hr.HostRecord(
+ role=hr.ROLE_SERVE, pid=os.getpid(), create_time=hr.process_create_time(),
+ host="127.0.0.1", port=dead_port, protocol_version=hr.HOST_PROTOCOL_VERSION,
+ token_fingerprint="", profiles=(), updated_at="2026-01-01T00:00:00+00:00")
+
+ assert hr.probe_owner(record, timeout=1.0) is None
+
+ foreign = socket.socket()
+ foreign.bind(("127.0.0.1", 0))
+ foreign.listen(1)
+ try:
+ assert hr.probe_owner(
+ dataclasses.replace(record, port=foreign.getsockname()[1]), timeout=1.0) is None
+ finally:
+ foreign.close()
+
+
+def test_relative_xdg_state_home_is_ignored(monkeypatch, tmp_path):
+ """XDG spec: a relative ``$XDG_STATE_HOME`` is invalid and must be ignored. Honouring one made
+ the host lock dir CWD-relative, so two serves started from different directories would each
+ take their own "host" lock."""
+ from gateway import status
+
+ monkeypatch.delenv("HERMES_GATEWAY_LOCK_DIR", raising=False)
+ monkeypatch.setenv("XDG_STATE_HOME", "relative/state")
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path))
+
+ assert status._get_lock_dir().is_absolute()
+ assert status._get_lock_dir() == tmp_path / ".local" / "state" / "hermes" / status._LOCKS_DIRNAME
diff --git a/tests/gateway/test_host_rendezvous_windows.py b/tests/gateway/test_host_rendezvous_windows.py
new file mode 100644
index 00000000000..bfb49ac78f8
--- /dev/null
+++ b/tests/gateway/test_host_rendezvous_windows.py
@@ -0,0 +1,62 @@
+"""Windows confidentiality for the host rendezvous token + lock (``windows_only``).
+
+``os.open(..., 0o600)`` sets NO ACLs on Windows, so the host token — which holds the backend's
+LIVE session token — would inherit whatever the parent directory grants. The SSH runtime's
+protected owner+SYSTEM DACL writer is the repo's primitive for this credential class
+(``tests/hermes_cli/test_ssh_session_token_parser.py`` documents why); this proves the host
+rendezvous actually uses it, and that the host lock still works on that path.
+"""
+
+import pytest
+
+from gateway import host_rendezvous as hr
+
+pytestmark = pytest.mark.windows_only
+
+
+def host_dir(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_GATEWAY_LOCK_DIR", str(tmp_path / "locks"))
+ yield tmp_path
+ hr.release_host_lock(hr.ROLE_SERVE)
+
+
+def _allowed_sids():
+ from hermes_cli import windows_ssh_runtime as wsr
+
+ return wsr._allowed_sids()
+
+
+def test_host_token_is_written_with_a_protected_owner_only_dacl(host_dir):
+ """Owner+SYSTEM only, and the DACL is protected so inheritable parent grants are not merged."""
+ import win32security
+
+ from hermes_cli import windows_ssh_runtime as wsr
+
+ assert hr.claim_host_lock(hr.ROLE_SERVE)[0] is hr.HostLockOutcome.ACQUIRED
+ hr.publish_record(hr.ROLE_SERVE, host="127.0.0.1", port=9119, token="live-session-token")
+
+ path = hr.token_path(hr.ROLE_SERVE)
+ assert path.read_text(encoding="utf-8").strip() == "live-session-token"
+ descriptor = win32security.GetFileSecurity(
+ str(path), win32security.OWNER_SECURITY_INFORMATION | win32security.DACL_SECURITY_INFORMATION)
+ allowed = _allowed_sids()
+ assert wsr._sid_str(descriptor.GetSecurityDescriptorOwner()) in allowed
+ dacl = descriptor.GetSecurityDescriptorDacl()
+ assert dacl is not None, "a null DACL grants everyone"
+ for index in range(dacl.GetAceCount()):
+ ace = dacl.GetAce(index)
+ assert wsr._sid_str(ace[-1]) in allowed
+ assert descriptor.GetSecurityDescriptorControl()[0] & win32security.SE_DACL_PROTECTED
+
+
+def test_rewriting_an_existing_token_keeps_it_private(host_dir):
+ """CreateFile ignores the security descriptor on an existing file, and ``os.replace`` fails
+ against an open reader — the writer replaces in place instead of inheriting either bug."""
+ assert hr.claim_host_lock(hr.ROLE_SERVE)[0] is hr.HostLockOutcome.ACQUIRED
+ hr.publish_record(hr.ROLE_SERVE, host="127.0.0.1", port=9119, token="first")
+ hr.publish_record(hr.ROLE_SERVE, host="127.0.0.1", port=9119, token="second")
+
+ assert hr.read_token(hr.ROLE_SERVE) == "second"
+ record = hr.read_record(hr.ROLE_SERVE, include_stale=True)
+ assert record is not None and hr.record_token_is_consistent(record)
diff --git a/tests/hermes_cli/test_serve_host_attach.py b/tests/hermes_cli/test_serve_host_attach.py
index b7ad64d09f5..eccfca32588 100644
--- a/tests/hermes_cli/test_serve_host_attach.py
+++ b/tests/hermes_cli/test_serve_host_attach.py
@@ -1,7 +1,14 @@
-"""A second `hermes serve` attaches to the host backend instead of binding a second port."""
+"""A second `hermes serve` attaches to the host backend instead of binding a second port.
+
+Attach is a PROOF, not a guess: exit 0 means the recorded owner answered on its recorded port and
+serves what the caller asked for. Every other shape falls through to the bind or refuses loudly.
+"""
import json
import os
+import socket
+import threading
+from http.server import BaseHTTPRequestHandler, HTTPServer
from types import SimpleNamespace
import pytest
@@ -19,13 +26,53 @@ def _args(**over):
def host_dir(tmp_path, monkeypatch):
monkeypatch.setenv("HERMES_GATEWAY_LOCK_DIR", str(tmp_path / "locks"))
monkeypatch.delenv("HERMES_DESKTOP", raising=False)
+ monkeypatch.setattr("sys.argv", ["hermes", "serve"])
return tmp_path
-def _publish(create_time, pid=None):
+def owner(host_dir):
+ """A live backend answering the identity handshake as THIS pid, on a real ephemeral port."""
+ serves_spa = {"value": True}
+
+ class _Handler(BaseHTTPRequestHandler):
+ def do_GET(self): # noqa: N802 — BaseHTTPRequestHandler API
+ if self.path != hr.HOST_IDENTITY_PATH:
+ self.send_error(404)
+ return
+ body = json.dumps({"ok": True, "pid": os.getpid(), "role": hr.ROLE_SERVE,
+ "servesSpa": serves_spa["value"]}).encode()
+ self.send_response(200)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def log_message(self, format, *args): # noqa: A002 — BaseHTTPRequestHandler API
+ pass
+
+ server = HTTPServer(("127.0.0.1", 0), _Handler)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ try:
+ yield SimpleNamespace(port=server.server_port, serves_spa=serves_spa)
+ finally:
+ server.shutdown()
+ server.server_close()
+
+
+def _dead_port() -> int:
+ spare = socket.socket()
+ spare.bind(("127.0.0.1", 0))
+ port = spare.getsockname()[1]
+ spare.close()
+ return port
+
+
+def _publish(create_time, *, pid=None, port=9119, host="127.0.0.1"):
record = hr.HostRecord(
role=hr.ROLE_SERVE, pid=pid if pid is not None else os.getpid(), create_time=create_time,
- host="127.0.0.1", port=9119, protocol_version=hr.HOST_PROTOCOL_VERSION,
+ host=host, port=port, protocol_version=hr.HOST_PROTOCOL_VERSION,
token_fingerprint="", profiles=("default", "alpha"),
updated_at="2026-01-01T00:00:00+00:00")
path = hr.record_path(hr.ROLE_SERVE)
@@ -33,16 +80,15 @@ def _publish(create_time, pid=None):
path.write_text(json.dumps(record.to_json()), encoding="utf-8")
-def test_second_serve_attaches_to_the_live_host_backend(host_dir, capsys):
- """A live record (real pid + its real creation time) ends the second launch at exit 0 —
- it never reaches the bind."""
- _publish(hr.process_create_time())
+def test_second_serve_attaches_to_the_live_host_backend(host_dir, owner, capsys):
+ """A live record whose owner ANSWERS ends the second launch at exit 0 — it never binds."""
+ _publish(hr.process_create_time(), port=owner.port)
with pytest.raises(SystemExit) as exc:
_attach_to_host_backend(_args(), headless_backend=True)
assert exc.value.code == 0
- assert "port 9119" in capsys.readouterr().out
+ assert f"port {owner.port}" in capsys.readouterr().out
def test_stale_record_is_ignored_and_the_launch_proceeds(host_dir):
@@ -53,8 +99,58 @@ def test_stale_record_is_ignored_and_the_launch_proceeds(host_dir):
assert _attach_to_host_backend(_args(), headless_backend=True) is None
-def test_isolated_never_attaches(host_dir):
+def test_isolated_never_attaches(host_dir, owner):
"""`--isolated` is load-bearing for Desktop's SSH backend ownership proof."""
- _publish(hr.process_create_time())
+ _publish(hr.process_create_time(), port=owner.port)
assert _attach_to_host_backend(_args(isolated=True), headless_backend=True) is None
+
+
+def test_a_record_whose_owner_does_not_answer_falls_through_to_the_bind(host_dir):
+ """The graceful-shutdown window: the PID is still alive and the record still on disk, but the
+ socket is already closed. Exiting 0 here reported success with NOTHING listening."""
+ _publish(hr.process_create_time(), port=_dead_port())
+
+ assert _attach_to_host_backend(_args(), headless_backend=True) is None
+
+
+def test_unprovable_liveness_still_has_to_answer(host_dir, monkeypatch):
+ """Without psutil the liveness answer is ``None`` (unprovable). Treating that as "alive" made
+ a record for a long-dead PID a permanent silent outage — every launch exited 0 forever."""
+ monkeypatch.setattr("hermes_cli.process_identity._pid_alive_matches", lambda *_a, **_k: None)
+ _publish(None, pid=2**22 - 1, port=_dead_port())
+
+ assert _attach_to_host_backend(_args(), headless_backend=True) is None
+
+
+ "argv,over",
+ [(["hermes", "serve", "--port", "8899"], {"port": 8899}),
+ (["hermes", "serve", "--host", "0.0.0.0"], {"host": "0.0.0.0"})],
+ ids=["explicit-port", "explicit-host"],
+)
+def test_an_explicit_endpoint_the_owner_cannot_serve_is_refused(host_dir, owner, monkeypatch,
+ argv, over, capsys):
+ """`--port 8899` answered with "use 127.0.0.1:<other>", or `--host 0.0.0.0` (LAN access)
+ silently turned into a loopback attach, are both wrong answers: refuse, naming the owner."""
+ monkeypatch.setattr("sys.argv", argv)
+ _publish(hr.process_create_time(), port=owner.port)
+
+ with pytest.raises(SystemExit) as exc:
+ _attach_to_host_backend(_args(**over), headless_backend=True)
+
+ assert exc.value.code == 1
+ assert f"PID {os.getpid()}" in capsys.readouterr().out
+
+
+def test_dashboard_is_never_routed_to_a_headless_backend(host_dir, owner, capsys):
+ """`hermes serve` and `hermes dashboard` publish the same host role; only one mounts the SPA,
+ so attaching a dashboard user to a headless backend opens a URL with no UI behind it."""
+ owner.serves_spa["value"] = False
+ _publish(hr.process_create_time(), port=owner.port)
+
+ with pytest.raises(SystemExit) as exc:
+ _attach_to_host_backend(_args(), headless_backend=False)
+
+ assert exc.value.code == 1
+ assert "no dashboard UI" in capsys.readouterr().out