Skip to content

The agent that grows with you

fix(gateway): name the unsafe control node in the client's inaccessible verdict

unsupportedpastelsb250fced6c5d
diff --git a/hermes_cli/gateway_runtime.py b/hermes_cli/gateway_runtime.py
index c6eae5236d7..4c0556f608d 100644
--- a/hermes_cli/gateway_runtime.py
+++ b/hermes_cli/gateway_runtime.py
@@ -45,7 +45,8 @@ class GatewayDiscovery:
reason_code: str | None = None
# Human-readable cause behind a bounded ``reason_code`` when the owner published one (the
# multiplexer's park reason), or the redacted output tail of a start this call made that died
- # (``runtime_exited``); never raw peer data.
+ # (``runtime_exited``), or the unsafe local control node a discovery refused (path, owner uid or
+ # mode, and the fix); never raw peer data.
detail: str | None = None
@@ -292,7 +293,8 @@ def discover_gateway_endpoint(profile_home: str | Path, *, timeout: float = 2.0)
except TimeoutError:
return GatewayDiscovery("inaccessible", reason_code="control_timeout")
except DiscoveryError as exc:
- return GatewayDiscovery("inaccessible", reason_code=exc.reason)
+ # The code stays bounded; the detail names the local node, its owner or mode, and the fix.
+ return GatewayDiscovery("inaccessible", reason_code=exc.reason, detail=exc.bounded_detail(500))
except PermissionError:
return _refused(home)
except (OSError, ValueError, TypeError):
diff --git a/hermes_cli/gateway_runtime_discovery.py b/hermes_cli/gateway_runtime_discovery.py
index 688c8a3ed14..db886e0765a 100644
--- a/hermes_cli/gateway_runtime_discovery.py
+++ b/hermes_cli/gateway_runtime_discovery.py
@@ -7,6 +7,7 @@ import errno
import json
import os
from pathlib import Path
+import shlex
import socket
import stat
import sys
@@ -15,9 +16,22 @@ import time
class DiscoveryError(ValueError):
- def __init__(self, reason: str, detail: str | None = None):
- super().__init__(f"{reason}: {detail}" if detail else reason)
- self.reason = reason
+ def __init__(self, reason: str, detail: str | None = None, fix: str | None = None):
+ # The stable code callers match on stays in ``reason``; ``detail`` is what the user reads,
+ # ending in the shell command that repairs the node (``fix``) when there is one.
+ self.reason, self.cause, self.fix = reason, detail, fix
+ self.detail = f"{detail}; {fix}" if detail and fix else detail
+ super().__init__(f"{reason}: {self.detail}" if self.detail else reason)
+
+ def bounded_detail(self, limit: int) -> str | None:
+ """``detail`` within ``limit`` characters, never with a cut-off command: a repair command
+ that does not fit is dropped with a notice, and an overlong description is cut visibly."""
+ if self.detail is None or len(self.detail) <= limit:
+ return self.detail
+ notice = "; repair command omitted (path too long to print)" if self.fix else ""
+ room, marker, cause = limit - len(notice), "… [truncated]", self.cause or ""
+ cause = cause if len(cause) <= room else cause[:room - len(marker)] + marker
+ return cause + notice
def _may_have_access_acl(path: Path) -> bool:
@@ -68,18 +82,27 @@ def _private_node(path: Path, *, kind: str, home: bool = False) -> os.stat_resul
"unsafe_control_path",
f"{path} is {stat.filemode(node.st_mode)}, expected {kind}",
)
- expected_uid = os.getuid()
+ expected_uid = os.getuid() # windows-footgun: ok — POSIX socket path only
if node.st_uid != expected_uid: # windows-footgun: ok — POSIX socket path only
raise DiscoveryError(
"unsafe_control_path",
f"{path} is owned by uid {node.st_uid}, expected uid {expected_uid} (gateway user); "
"chown it to the gateway user",
)
- if home_mode_unsafe(node, path) if home else stat.S_IMODE(node.st_mode) & 0o077:
- raise DiscoveryError("unsafe_control_permissions")
+ mode = stat.S_IMODE(node.st_mode)
+ if home and home_mode_unsafe(node, path):
+ raise DiscoveryError("unsafe_control_permissions", f"{path} has mode {mode:04o}, writable by another user",
+ f"chmod go-w {shlex.quote(str(path))}")
+ if not home and mode & 0o077:
+ raise _open_mode(path, mode, 0o700 if kind == "directory" else 0o600)
return node
+def _open_mode(path: Path, mode: int, expected: int) -> DiscoveryError:
+ return DiscoveryError("unsafe_control_permissions", f"{path} has mode {mode:04o}, expected {expected:04o}",
+ f"chmod {expected:o} {shlex.quote(str(path))}")
+
+
def socket_peer_uid(sock: socket.socket) -> int | None:
"""Kernel-reported uid of the process on the other end of a connected AF_UNIX socket
(SO_PEERCRED on Linux, getpeereid on macOS); None where neither exists."""
@@ -145,7 +168,7 @@ def _socket_path(home: Path) -> Path:
raise DiscoveryError("invalid_control_pointer")
directory = _private_node(target.parent, kind="directory")
if directory.st_mode & 0o077:
- raise DiscoveryError("unsafe_control_permissions")
+ raise _open_mode(target.parent, stat.S_IMODE(directory.st_mode), 0o700)
_private_node(target, kind="socket")
return target
diff --git a/tests/hermes_cli/test_gateway_runtime_discovery.py b/tests/hermes_cli/test_gateway_runtime_discovery.py
index 8f8f885e287..921b4868071 100644
--- a/tests/hermes_cli/test_gateway_runtime_discovery.py
+++ b/tests/hermes_cli/test_gateway_runtime_discovery.py
@@ -154,6 +154,109 @@ def test_private_node_reports_path_kind_and_owner_recovery_hint(tmp_path, monkey
assert owner_error.value.reason == "unsafe_control_path"
[email protected]("linux", "macos")
+def test_the_client_verdict_names_the_unsafe_node_and_its_fix(monkeypatch, request):
+ """``Gateway inaccessible: <code> (<detail>)`` is what a client prints (``connect_gateway``): the
+ detail must survive discovery and ensure, with the code unchanged for callers that match it."""
+ import os
+ import shutil
+ from hermes_cli.gateway_runtime import discover_gateway_endpoint, ensure_gateway_runtime
+ # A short root: the socket path must fit AF_UNIX's limit.
+ root = Path(tempfile.mkdtemp(prefix='h-'))
+ request.addfinalizer(lambda: shutil.rmtree(root, ignore_errors=True))
+ home = root / 'h'
+ home.mkdir(mode=0o700)
+ control = home / 'gateway.sock'
+ # Discovery names the canonical home, the path a chmod/chown must act on: on macOS the temp
+ # root sits under /var, a symlink to /private/var, so the caller's spelling is not what it prints.
+ shown, shown_control = home.resolve(), home.resolve() / 'gateway.sock'
+ control.write_text('not a socket', encoding='utf-8')
+ verdict = ensure_gateway_runtime(home, timeout=2)
+ assert (verdict.state, verdict.reason_code) == ('inaccessible', 'unsafe_control_path')
+ detail = verdict.detail or ''
+ assert f'{shown_control} is -rw' in detail and 'expected socket' in detail, verdict
+
+ control.unlink()
+ with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as server:
+ server.bind(str(control))
+ control.chmod(0o660)
+ verdict = discover_gateway_endpoint(home)
+ assert verdict.reason_code == 'unsafe_control_permissions'
+ assert verdict.detail == f'{shown_control} has mode 0660, expected 0600; chmod 600 {shown_control}', verdict
+ control.unlink()
+
+ home.chmod(0o757)
+ verdict = discover_gateway_endpoint(home)
+ assert verdict.reason_code == 'unsafe_control_permissions'
+ assert verdict.detail == (f'{shown} has mode 0757, writable by another user; chmod go-w {shown}'), verdict
+ home.chmod(0o700)
+
+ owner = home.lstat().st_uid
+ monkeypatch.setattr(os, 'getuid', lambda: owner + 1)
+ verdict = discover_gateway_endpoint(home)
+ assert verdict.reason_code == 'unsafe_control_path'
+ assert f'{shown} is owned by uid {owner}, expected uid {owner + 1}' in (verdict.detail or ''), verdict
+
+
[email protected]("linux", "macos")
+def test_a_long_home_keeps_the_repair_command_whole_or_drops_it(tmp_path):
+ """The detail is bounded to 500 characters; a long profile home (named twice: the node and the
+ command) must not leave the client printing a chmod cut off mid-path or missing its quote."""
+ from hermes_cli.gateway_runtime import discover_gateway_endpoint
+
+ omitted = '; repair command omitted (path too long to print)'
+ home = tmp_path.resolve() / ('p' * 200) / "profile's home"
+ home.mkdir(parents=True, mode=0o700)
+ home.chmod(0o757)
+ verdict = discover_gateway_endpoint(home)
+ assert verdict.reason_code == 'unsafe_control_permissions'
+ assert verdict.detail == f'{home} has mode 0757, writable by another user{omitted}', verdict
+
+ # Too long even without the command: the description is cut with a visible marker.
+ deeper = home / ('q' * 250) / ('r' * 100)
+ deeper.mkdir(parents=True, mode=0o700)
+ deeper.chmod(0o757)
+ detail = discover_gateway_endpoint(deeper).detail or ''
+ assert len(detail) == 500 and detail.endswith(f'… [truncated]{omitted}'), detail
+ assert detail.startswith(str(deeper)[:300]) and 'chmod' not in detail, detail
+
+
[email protected]("linux", "macos")
+def test_a_permission_hint_runs_as_printed_for_a_path_with_spaces(tmp_path):
+ """The hint is a command the user pastes into a shell: a profile home with a space must survive it."""
+ import subprocess
+ from hermes_cli.gateway_runtime_discovery import _private_node
+
+ home = tmp_path / 'profile home'
+ home.mkdir(mode=0o700)
+ control = home / 'control file'
+ control.write_text('', encoding='utf-8')
+ for path, kind, is_home, mode in ((control, 'file', False, 0o660), (home, 'directory', True, 0o702)):
+ path.chmod(mode)
+ with pytest.raises(DiscoveryError, match='unsafe_control_permissions') as error:
+ _private_node(path, kind=kind, home=is_home)
+ hint = str(error.value).split('; ', 1)[1]
+ ran = subprocess.run(['sh', '-c', hint], capture_output=True, text=True, check=False)
+ assert ran.returncode == 0, (hint, ran.stderr)
+ _private_node(path, kind=kind, home=is_home)
+
+
+def test_an_open_control_directory_names_its_path_and_mode(tmp_path):
+ home = tmp_path / 'profile'
+ home.mkdir(mode=0o700)
+ with tempfile.TemporaryDirectory(prefix='h-owner-') as root:
+ directory = Path(root) / f'hermes-gw-{_home_hash(home)}'
+ directory.mkdir(mode=0o755)
+ pointer = home / 'gateway.sock.path'
+ pointer.write_text(str(directory / 'control.sock'), encoding='utf-8')
+ pointer.chmod(0o600)
+ with pytest.raises(DiscoveryError, match='unsafe_control_permissions') as refused:
+ query_identify(home, timeout=2)
+ assert refused.value.reason == 'unsafe_control_permissions'
+ assert getattr(refused.value, 'detail', None) == f'{directory} has mode 0755, expected 0700; chmod 700 {directory}'
+
+
@pytest.mark.platforms("linux", "macos")
def test_home_mode_refuses_only_writes_another_user_can_make(tmp_path, monkeypatch):
import grp