The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(windows): name an elevated or other-session gateway instead of "authorization"
Tekniumeecaa7af9a88
diff --git a/apps/desktop/electron/local-gateway.test.ts b/apps/desktop/electron/local-gateway.test.tsindex f1387b00f9b..49f0f0923ac 100644--- a/apps/desktop/electron/local-gateway.test.ts+++ b/apps/desktop/electron/local-gateway.test.ts@@ -588,6 +588,22 @@ test('an ensure refusal names its remedy instead of only a status pointer', asyn}))).rejects.toThrow(`Gateway incompatible (runtime_protocol). ${detail}. Use hermes gateway status for recovery.`)})+test('an elevated or other-session gateway is named with its remedy, not as authorization (#139845, #140252)', async () => {+ const cases = [+ ['gateway_elevated', 'The running gateway (PID 23460) was started as administrator, so this non-elevated app cannot reach it. Stop it from an administrator prompt (hermes gateway stop), then start Hermes without elevation'],+ ['gateway_other_session', 'The running gateway (PID 23460) runs in another Windows logon session (session 0, e.g. a boot-time scheduled task), so this app cannot reach it. Stop it (hermes gateway stop from an administrator prompt) and let only one auto-start task launch the gateway']+ ]++ for (const [reason_code, detail] of cases) {+ const failure = ensureLocalGateway(async () => ({+ code: 4, stdout: JSON.stringify({ state: 'inaccessible', reason_code, detail, endpoint: null })+ }))++ await expect(failure).rejects.toThrow(`Gateway inaccessible (${reason_code}). ${detail}.`)+ await expect(failure).rejects.not.toThrow('authorization')+ }+})+test('an update-paused ensure refusal points to the restart that completes its tail', async () => {await expect(ensureLocalGateway(async () => ({code: 6, stdout: JSON.stringify({ state: 'draining', reason_code: 'update_paused', endpoint: null })diff --git a/gateway/runtime_bootstrap_windows.py b/gateway/runtime_bootstrap_windows.pyindex df6e4b741a8..86a7288d78d 100644--- a/gateway/runtime_bootstrap_windows.py+++ b/gateway/runtime_bootstrap_windows.py@@ -350,3 +350,81 @@ class NativeControlServer:finally:if handle is not None:win.CloseHandle(handle)+++# Why a same-user gateway's control pipe or process refused this client (#139845, #140252). The+# pipe DACL names the user's SID, so a refusal between two processes of one user means a boundary+# the SID does not cross: an elevated owner (High integrity) seen from a filtered token, or an+# owner in another logon session (a session-0 S4U boot task). ``authorization`` reads as a+# credential problem and names neither.+GATEWAY_ELEVATED = "gateway_elevated"+GATEWAY_OTHER_SESSION = "gateway_other_session"+++def classify_refused_owner(*, own_session: int | None, owner_session: int | None,+ own_elevated: bool, owner_elevated: bool | None) -> str | None:+ """Pure decision over probed facts; ``None`` keeps the generic ``authorization`` code.++ ``owner_elevated`` is None when the owner's token could not be opened; from a non-elevated+ client in the same session that refusal is itself the elevation boundary."""+ if own_session is not None and owner_session is not None and own_session != owner_session:+ return GATEWAY_OTHER_SESSION+ if own_elevated:+ return None+ if owner_elevated or (owner_elevated is None and owner_session is not None):+ return GATEWAY_ELEVATED+ return None+++def refused_owner_remedy(reason: str, pid: int, owner_session: int | None) -> str:+ if reason == GATEWAY_ELEVATED:+ return (f"The running gateway (PID {pid}) was started as administrator, so this non-elevated "+ "app cannot reach it. Stop it from an administrator prompt (hermes gateway stop), then "+ "start Hermes without elevation")+ where = f"session {owner_session}" if owner_session is not None else "another session"+ return (f"The running gateway (PID {pid}) runs in another Windows logon session ({where}, e.g. a "+ "boot-time scheduled task), so this app cannot reach it. Stop it (hermes gateway stop from an "+ "administrator prompt) and let only one auto-start task launch the gateway")+++def _session_of(pid: int) -> int | None:+ k = ctypes.WinDLL('kernel32', use_last_error=True)+ session = wintypes.DWORD()+ to_session = _api(k, 'ProcessIdToSessionId', wintypes.BOOL, [wintypes.DWORD, ctypes.POINTER(wintypes.DWORD)])+ return session.value if to_session(pid, ctypes.byref(session)) else None+++def _elevation_of(pid: int) -> bool | None:+ 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) # PROCESS_QUERY_LIMITED_INFORMATION+ if not process:+ return None+ 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)): # TOKEN_QUERY+ return None+ token_info = _api(a, 'GetTokenInformation', wintypes.BOOL,+ [wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD,+ ctypes.POINTER(wintypes.DWORD)])+ elevated, size = wintypes.DWORD(), wintypes.DWORD()+ if not token_info(token, 20, ctypes.byref(elevated), ctypes.sizeof(elevated), ctypes.byref(size)):+ return None+ return bool(elevated.value)+ finally:+ if token:+ close(token)+ close(process)+++def probe_refused_owner(pid: int) -> tuple[str, str] | None:+ """``(reason_code, remedy)`` naming why *pid*'s gateway refused this client, or None."""+ from hermes_dir_acl import process_is_elevated+ own_session, owner_session = _session_of(os.getpid()), _session_of(pid)+ reason = classify_refused_owner(own_session=own_session, owner_session=owner_session,+ own_elevated=process_is_elevated(), owner_elevated=_elevation_of(pid))+ return (reason, refused_owner_remedy(reason, pid, owner_session)) if reason else Nonediff --git a/hermes_cli/gateway_runtime.py b/hermes_cli/gateway_runtime.pyindex c2b602944ac..fd7e7da0c83 100644--- a/hermes_cli/gateway_runtime.py+++ b/hermes_cli/gateway_runtime.py@@ -217,6 +217,33 @@ def _served_by_multiplexer(home: Path, *, timeout: float) -> GatewayDiscovery |return result+_NATIVE_WINDOWS = os.name == "nt"+++def _owner_pid(home: Path) -> int | None:+ from gateway.status import _pid_from_record, _read_json_file+ 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+ return None+++def _refused(home: Path) -> GatewayDiscovery:+ """The owner's control channel refused this same-user client. On Windows name the boundary+ (an elevated owner, or one in another logon session) with its remedy instead of the generic+ ``authorization`` that reads as a credential failure (#139845, #140252)."""+ if _NATIVE_WINDOWS and (pid := _owner_pid(home)) is not None:+ from gateway.runtime_bootstrap_windows import probe_refused_owner+ try:+ named = probe_refused_owner(pid)+ except OSError:+ named = None+ if named is not None:+ return GatewayDiscovery("inaccessible", reason_code=named[0], detail=named[1])+ return GatewayDiscovery("inaccessible", reason_code="authorization")++def discover_gateway_endpoint(profile_home: str | Path, *, timeout: float = 2.0) -> GatewayDiscovery:"""Read live control identity, preserving uncertainty instead of spawning.@@ -245,7 +272,7 @@ def discover_gateway_endpoint(profile_home: str | Path, *, timeout: float = 2.0)except DiscoveryError as exc:return GatewayDiscovery("inaccessible", reason_code=exc.reason)except PermissionError:- return GatewayDiscovery("inaccessible", reason_code="authorization")+ return _refused(home)except (OSError, ValueError, TypeError):# Raw peer data, paths and URLs may contain secrets; report bounded codes.return GatewayDiscovery("inaccessible", reason_code="invalid_control_peer")@@ -419,6 +446,6 @@ def ensure_gateway_runtime(profile_home: str | Path, *, timeout: float = DEFAULTexcept RuntimeStartError as exc:return GatewayDiscovery(exc.state, reason_code=exc.reason)except PermissionError:- return GatewayDiscovery("inaccessible", reason_code="authorization")+ return _refused(home)except OSError:return GatewayDiscovery("inaccessible", reason_code="runtime_start_failed")diff --git a/hermes_cli/gateway_runtime_cli.py b/hermes_cli/gateway_runtime_cli.pyindex 57e6a7175ef..5d623ff9672 100644--- a/hermes_cli/gateway_runtime_cli.py+++ b/hermes_cli/gateway_runtime_cli.py@@ -8,7 +8,7 @@ from contextlib import redirect_stdoutdef ensure_exit_code(result) -> int:if result.reason_code == "deadline":return 5- if result.reason_code in {"authorization", "profile_mismatch"}:+ if result.reason_code in {"authorization", "profile_mismatch", "gateway_elevated", "gateway_other_session"}:return 4return {"ready": 0, "incompatible": 3, "draining": 6,"inaccessible": 7, "conflict": 7, "starting": 5, "absent": 5}[result.state]diff --git a/tests/gateway/test_refused_owner_windows.py b/tests/gateway/test_refused_owner_windows.pynew file mode 100644index 00000000000..94ca03643c0--- /dev/null+++ b/tests/gateway/test_refused_owner_windows.py@@ -0,0 +1,60 @@+"""#139845 / #140252 real Windows probes behind the named refusal states.++The classifier is unit-tested in ``test_gateway_refused_owner.py``; this proves the native probes+read real tokens and sessions: this process's own session/elevation, a same-token child (nothing to+name), and a session-0 system process seen from an interactive session (``gateway_other_session``,+the #140252 shape). Building an elevated owner seen from a filtered client needs a second logon+token, which a hosted runner cannot mint; that half stays a live retest.+"""+import csv+import io+import subprocess+import sys++import pytest++pytestmark = pytest.mark.platforms("windows")+++def test_own_session_and_elevation_are_read_from_the_real_token():+ from gateway import runtime_bootstrap_windows as native+ from hermes_dir_acl import process_is_elevated+ import os++ assert isinstance(native._session_of(os.getpid()), int)+ assert native._elevation_of(os.getpid()) is process_is_elevated()+++def test_a_same_token_owner_is_not_misnamed():+ from gateway import runtime_bootstrap_windows as native++ child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(30)"])+ try:+ assert native.probe_refused_owner(child.pid) is None+ finally:+ child.kill()+ child.wait(timeout=10)+++def _session_zero_pid() -> int | None:+ rows = subprocess.run(["tasklist", "/fo", "csv", "/nh", "/fi", "SESSION eq 0"], capture_output=True,+ text=True, check=False).stdout+ for row in csv.reader(io.StringIO(rows)):+ if len(row) > 1 and row[1].isdigit() and int(row[1]) > 4:+ return int(row[1])+ return None+++def test_a_session_zero_owner_reads_as_another_logon_session():+ import os++ from gateway import runtime_bootstrap_windows as native++ if native._session_of(os.getpid()) == 0:+ pytest.skip("this runner itself runs in session 0")+ pid = _session_zero_pid()+ if pid is None:+ pytest.skip("no session-0 process visible")+ named = native.probe_refused_owner(pid)+ assert named is not None and named[0] == "gateway_other_session", named+ assert f"PID {pid}" in named[1] and "session 0" in named[1]diff --git a/tests/hermes_cli/test_gateway_refused_owner.py b/tests/hermes_cli/test_gateway_refused_owner.pynew file mode 100644index 00000000000..4db6859a9d4--- /dev/null+++ b/tests/hermes_cli/test_gateway_refused_owner.py@@ -0,0 +1,80 @@+"""#139845 / #140252: a same-user gateway that refuses the client is named, not ``authorization``.++#139845: an elevated gateway's pipe/process refuses the non-elevated Desktop (``OpenProcess`` err=5).+#140252: a session-0 S4U boot-task gateway won the control pipe; the interactive Desktop can never+reach it. Both surfaced as ``Gateway inaccessible (authorization)``, which reads as a credential+problem. The probe facts are injected here (no Windows host); ``test_refused_owner_windows.py``+runs the real probes on Windows CI.+"""+from pathlib import Path++import pytest++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++[email protected](("facts", "expected"), [+ # #140252: owner in session 0, Desktop in the interactive session 1.+ ({"own_session": 1, "owner_session": 0, "own_elevated": False, "owner_elevated": None}, "gateway_other_session"),+ ({"own_session": 1, "owner_session": 0, "own_elevated": True, "owner_elevated": True}, "gateway_other_session"),+ # #139845: same session, owner elevated (or its token unopenable from a filtered client).+ ({"own_session": 1, "owner_session": 1, "own_elevated": False, "owner_elevated": True}, "gateway_elevated"),+ ({"own_session": 1, "owner_session": 1, "own_elevated": False, "owner_elevated": None}, "gateway_elevated"),+ # Nothing to name: keep the generic code.+ ({"own_session": 1, "owner_session": 1, "own_elevated": False, "owner_elevated": False}, None),+ ({"own_session": 1, "owner_session": 1, "own_elevated": True, "owner_elevated": None}, None),+ ({"own_session": 1, "owner_session": None, "own_elevated": False, "owner_elevated": None}, None),+])+def test_classify_refused_owner(facts, expected):+ assert native.classify_refused_owner(**facts) == expected+++def _refusing_owner(monkeypatch, tmp_path: Path, named):+ home = tmp_path / "home"+ home.mkdir()+ (home / "gateway.pid").write_text('{"pid": 23460}', 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)+ result = runtime._refused(home)+ assert seen == [23460]+ 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 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)+ 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)+ 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"+ (home / "gateway.pid").unlink()+ assert runtime._refused(home).reason_code == "authorization"+++def test_discovery_maps_a_refused_pipe_through_the_named_state(monkeypatch, tmp_path):+ """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)+ 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")