Skip to content

The agent that grows with you

fix(windows): a refusal names only a gateway proved by its process identity

Tekniumb8ea5196e4e5
diff --git a/hermes_cli/gateway_runtime.py b/hermes_cli/gateway_runtime.py
index fd7e7da0c83..862cd090e15 100644
--- a/hermes_cli/gateway_runtime.py
+++ b/hermes_cli/gateway_runtime.py
@@ -221,11 +221,33 @@ _NATIVE_WINDOWS = os.name == "nt"
def _owner_pid(home: Path) -> int | None:
- from gateway.status import _pid_from_record, _read_json_file
+ """The PID a refusal may name: one of *home*'s gateway records whose process is provably that
+ gateway, else None (the caller keeps the generic ``authorization``).
+
+ Proof is the shared identity chain: alive, its recorded start time known and equal to the live
+ one (a recycled PID differs), its recorded home not another profile's, and its live command line
+ (or, when that is unreadable across the elevation boundary, its record) a gateway's. A stale
+ ``gateway.pid`` falls through to ``gateway.lock`` instead of masking it."""
+ from gateway.status import (
+ _get_process_start_time,
+ _live_pid_from_record,
+ _read_json_file,
+ _record_matches_live_gateway_pid,
+ recorded_gateway_home_conflicts,
+ )
for name in ("gateway.pid", "gateway.lock"):
- pid = _pid_from_record(_read_json_file(home / name, bare_pid_ok=True))
- if pid and pid != os.getpid():
- return pid
+ record = _read_json_file(home / name, bare_pid_ok=True)
+ pid = _live_pid_from_record(record)
+ if pid is None or pid == os.getpid():
+ continue
+ recorded = record.get("start_time")
+ if recorded is None or recorded != _get_process_start_time(pid):
+ continue # unverifiable or recycled: never name it
+ if recorded_gateway_home_conflicts(record, expected_home=home):
+ continue
+ if not _record_matches_live_gateway_pid(record, pid):
+ continue
+ return pid
return None
diff --git a/tests/hermes_cli/test_gateway_refused_owner.py b/tests/hermes_cli/test_gateway_refused_owner.py
index 4db6859a9d4..44c584127eb 100644
--- a/tests/hermes_cli/test_gateway_refused_owner.py
+++ b/tests/hermes_cli/test_gateway_refused_owner.py
@@ -6,6 +6,9 @@ reach it. Both surfaced as ``Gateway inaccessible (authorization)``, which reads
problem. The probe facts are injected here (no Windows host); ``test_refused_owner_windows.py``
runs the real probes on Windows CI.
"""
+import json
+import subprocess
+import sys
from pathlib import Path
import pytest
@@ -14,6 +17,9 @@ from gateway import runtime_bootstrap_windows as native
from hermes_cli import gateway_runtime as runtime
from hermes_cli.gateway_runtime_cli import ensure_exit_code
+# The owner stand-in is a stub ``hermes gateway run`` child that each test reaps itself.
+pytestmark = pytest.mark.spawns_gateway_lookalike
+
@pytest.mark.parametrize(("facts", "expected"), [
# #140252: owner in session 0, Desktop in the interactive session 1.
@@ -31,36 +37,59 @@ def test_classify_refused_owner(facts, expected):
assert native.classify_refused_owner(**facts) == expected
-def _refusing_owner(monkeypatch, tmp_path: Path, named):
+def _gateway_child(tmp_path: Path):
+ """A real live process whose command line is a gateway's (``.../hermes gateway run``)."""
+ entry = tmp_path / "bin" / "hermes"
+ entry.parent.mkdir(exist_ok=True)
+ entry.write_text("import sys\nsys.stdin.read()\n", encoding="utf-8")
+ return subprocess.Popen([sys.executable, str(entry), "gateway", "run"], stdin=subprocess.PIPE)
+
+
+def _record(home: Path, pid: int, **extra) -> dict:
+ from gateway.status import _get_process_start_time
+ return {"pid": pid, "kind": "hermes-gateway", "argv": ["hermes", "gateway", "run"],
+ "start_time": _get_process_start_time(pid), "hermes_home": str(home), **extra}
+
+
+def gateway_owner(tmp_path):
+ child = _gateway_child(tmp_path)
+ yield child
+ child.stdin.close()
+ child.wait(timeout=10)
+
+
+def _refusing_owner(monkeypatch, tmp_path: Path, named, owner):
home = tmp_path / "home"
- home.mkdir()
- (home / "gateway.pid").write_text('{"pid": 23460}', encoding="utf-8")
+ home.mkdir(exist_ok=True)
+ (home / "gateway.pid").write_text(json.dumps(_record(home, owner.pid)), encoding="utf-8")
monkeypatch.setattr(runtime, "_NATIVE_WINDOWS", True, raising=False)
seen = []
monkeypatch.setattr(native, "probe_refused_owner", lambda pid: seen.append(pid) or named)
return home, seen
-def test_refusal_names_the_other_session_owner_with_its_remedy(monkeypatch, tmp_path):
- named = ("gateway_other_session", native.refused_owner_remedy("gateway_other_session", 23460, 0))
- home, seen = _refusing_owner(monkeypatch, tmp_path, named)
+def test_refusal_names_the_other_session_owner_with_its_remedy(monkeypatch, tmp_path, gateway_owner):
+ pid = gateway_owner.pid
+ named = ("gateway_other_session", native.refused_owner_remedy("gateway_other_session", pid, 0))
+ home, seen = _refusing_owner(monkeypatch, tmp_path, named, gateway_owner)
result = runtime._refused(home)
- assert seen == [23460]
+ assert seen == [pid]
assert (result.state, result.reason_code) == ("inaccessible", "gateway_other_session")
- assert result.detail and "PID 23460" in result.detail and "session 0" in result.detail
+ assert result.detail and f"PID {pid}" in result.detail and "session 0" in result.detail
assert ensure_exit_code(result) == 4
-def test_refusal_names_the_elevated_owner_with_its_remedy(monkeypatch, tmp_path):
- named = ("gateway_elevated", native.refused_owner_remedy("gateway_elevated", 23460, 1))
- home, _ = _refusing_owner(monkeypatch, tmp_path, named)
+def test_refusal_names_the_elevated_owner_with_its_remedy(monkeypatch, tmp_path, gateway_owner):
+ named = ("gateway_elevated", native.refused_owner_remedy("gateway_elevated", gateway_owner.pid, 1))
+ home, _ = _refusing_owner(monkeypatch, tmp_path, named, gateway_owner)
result = runtime._refused(home)
assert result.reason_code == "gateway_elevated"
assert result.detail and "administrator" in result.detail and "hermes gateway stop" in result.detail
-def test_unnamed_or_unprobeable_refusal_keeps_authorization(monkeypatch, tmp_path):
- home, _ = _refusing_owner(monkeypatch, tmp_path, None)
+def test_unnamed_or_unprobeable_refusal_keeps_authorization(monkeypatch, tmp_path, gateway_owner):
+ home, _ = _refusing_owner(monkeypatch, tmp_path, None, gateway_owner)
assert runtime._refused(home).reason_code == "authorization"
monkeypatch.setattr(native, "probe_refused_owner", lambda pid: (_ for _ in ()).throw(OSError("x")))
assert runtime._refused(home).reason_code == "authorization"
@@ -68,13 +97,68 @@ def test_unnamed_or_unprobeable_refusal_keeps_authorization(monkeypatch, tmp_pat
assert runtime._refused(home).reason_code == "authorization"
-def test_discovery_maps_a_refused_pipe_through_the_named_state(monkeypatch, tmp_path):
+def test_discovery_maps_a_refused_pipe_through_the_named_state(monkeypatch, tmp_path, gateway_owner):
"""The real discovery path: ``query_identify`` raising PermissionError is what Windows' pipe
``CreateFile`` err=5 / peer-identity refusal produces."""
from hermes_cli import gateway_runtime_discovery as discovery
- named = ("gateway_elevated", native.refused_owner_remedy("gateway_elevated", 23460, 1))
- home, _ = _refusing_owner(monkeypatch, tmp_path, named)
+ named = ("gateway_elevated", native.refused_owner_remedy("gateway_elevated", gateway_owner.pid, 1))
+ home, _ = _refusing_owner(monkeypatch, tmp_path, named, gateway_owner)
monkeypatch.setattr(discovery, "query_identify",
lambda *_a, **_k: (_ for _ in ()).throw(PermissionError("runtime control pipe inaccessible")))
result = runtime.discover_gateway_endpoint(home, timeout=1)
assert (result.state, result.reason_code) == ("inaccessible", "gateway_elevated")
+
+
+# ── Review-9 (e): never name a PID that is not provably this home's gateway ─────────────────────
+
+
+def _probe_recorder(monkeypatch):
+ monkeypatch.setattr(runtime, "_NATIVE_WINDOWS", True, raising=False)
+ seen = []
+ named = lambda pid: seen.append(pid) or ("gateway_elevated", native.refused_owner_remedy("gateway_elevated", pid, 1))
+ monkeypatch.setattr(native, "probe_refused_owner", named)
+ return seen
+
+
+def test_a_recycled_pid_is_never_named(monkeypatch, tmp_path, gateway_owner):
+ """A live process whose start time differs from the record's (the PID was recycled)."""
+ home = tmp_path / "home"
+ home.mkdir()
+ record = _record(home, gateway_owner.pid)
+ record["start_time"] = (record["start_time"] or 0) + 12345
+ (home / "gateway.pid").write_text(json.dumps(record), encoding="utf-8")
+ seen = _probe_recorder(monkeypatch)
+ assert runtime._refused(home).reason_code == "authorization" and seen == []
+
+
[email protected]("shape", ["no start time", "not a gateway", "another home"])
+def test_an_unverifiable_owner_is_never_named(monkeypatch, tmp_path, shape):
+ home = tmp_path / "home"
+ home.mkdir()
+ if shape == "not a gateway":
+ child = subprocess.Popen([sys.executable, "-c", "import sys; sys.stdin.read()"], stdin=subprocess.PIPE)
+ else:
+ child = _gateway_child(tmp_path)
+ try:
+ record = _record(home, child.pid)
+ if shape == "no start time":
+ del record["start_time"]
+ elif shape == "another home":
+ record["hermes_home"] = str(tmp_path / "other-profile")
+ (home / "gateway.pid").write_text(json.dumps(record), encoding="utf-8")
+ seen = _probe_recorder(monkeypatch)
+ assert runtime._refused(home).reason_code == "authorization" and seen == []
+ finally:
+ child.stdin.close()
+ child.wait(timeout=10)
+
+
+def test_a_stale_pid_file_falls_through_to_the_lock_owner(monkeypatch, tmp_path, gateway_owner):
+ home = tmp_path / "home"
+ home.mkdir()
+ dead = subprocess.Popen([sys.executable, "-c", "pass"])
+ dead.wait()
+ (home / "gateway.pid").write_text(json.dumps({"pid": dead.pid, "start_time": 1}), encoding="utf-8")
+ (home / "gateway.lock").write_text(json.dumps(_record(home, gateway_owner.pid)), encoding="utf-8")
+ seen = _probe_recorder(monkeypatch)
+ assert runtime._refused(home).reason_code == "gateway_elevated" and seen == [gateway_owner.pid]