Skip to content

The agent that grows with you

fix: reject unbound launch wrappers and nonregular service definitions

Teknium1dd6268bcd53
diff --git a/hermes_cli/gateway_runtime_service.py b/hermes_cli/gateway_runtime_service.py
index b1137b11162..dc1ad571237 100644
--- a/hermes_cli/gateway_runtime_service.py
+++ b/hermes_cli/gateway_runtime_service.py
@@ -56,9 +56,9 @@ def _run(argv: list[str] | tuple[str, ...], deadline: float, *, encoding: str |
creationflags=windows_hide_flags(), timeout=remaining(deadline))
-def _verify_binding(verify, *args) -> None:
+def _verify_binding(verify, *args, **kwargs) -> None:
try:
- verify(*args)
+ verify(*args, **kwargs)
except (ValueError, TypeError, KeyError, AttributeError) as exc:
reason = str(exc)
raise RuntimeStartError(reason if reason in {
@@ -129,9 +129,10 @@ def _launchd(home: Path, deadline: float) -> ExistingService | None:
import pwd
suffix = service_suffix(home)
label = f"ai.hermes.gateway{'-' + suffix if suffix else ''}"
- account_home = Path(pwd.getpwuid(os.getuid()).pw_dir) # windows-footgun: ok — native launchd only
+ account = pwd.getpwuid(os.getuid()) # windows-footgun: ok — native launchd only
+ account_home = Path(account.pw_dir)
plist = account_home / "Library/LaunchAgents" / f"{label}.plist"
- from hermes_cli.gateway_runtime_service_identity import verify_launchd_loaded, verify_launchd_plist
+ from hermes_cli.gateway_runtime_service_identity import verify_launchd_loaded, verify_launchd_plist, read_definition
installed = _exists(plist)
domains = [f"gui/{os.getuid()}", f"user/{os.getuid()}"] # windows-footgun: ok — native launchd only
found = []
@@ -149,11 +150,10 @@ def _launchd(home: Path, deadline: float) -> ExistingService | None:
if len(found) > 1:
raise RuntimeStartError("service_scope_conflict", "conflict")
if found:
- _verify_binding(verify_launchd_loaded, loaded[0], home)
+ _verify_binding(verify_launchd_loaded, loaded[0], home, uid=os.getuid(), username=account.pw_name) # windows-footgun: ok — native launchd only
return found[0]
if installed:
- with plist.open("rb") as stream:
- definition = plistlib.load(stream)
+ definition = plistlib.loads(read_definition(plist))
_verify_binding(verify_launchd_plist, definition, label, home)
# Load ONLY the existing file, never bootout/rewrite or kickstart -k.
return ExistingService("launchd", ("launchctl", "bootstrap", domains[0], str(plist)))
diff --git a/hermes_cli/gateway_runtime_service_identity.py b/hermes_cli/gateway_runtime_service_identity.py
index 3ab6fb9f3db..080ed017161 100644
--- a/hermes_cli/gateway_runtime_service_identity.py
+++ b/hermes_cli/gateway_runtime_service_identity.py
@@ -9,6 +9,7 @@ import os
from pathlib import Path
import re
import shlex
+import stat
from typing import NoReturn
@@ -39,6 +40,8 @@ def verify_gateway_argv(argv: list[str], home: Path) -> None:
# The installer wraps launchd stderr with this fixed, non-shell module.
if len(argv) > 7 and argv[1:4] == ["-m", "hermes_cli.stderr_timestamp", "--error-log"] and argv[5] == "--":
+ if not re.fullmatch(r"python(?:w|\d+(?:\.\d+)*)?(?:\.exe)?", Path(argv[0]).name.lower()):
+ _unverified()
argv = argv[6:]
if not argv or not looks_like_gateway_command_line(subprocess_command(argv)):
_unverified()
@@ -142,7 +145,7 @@ def verify_systemd(props: dict[str, str], manager_env: str, home: Path, *, syste
verify_gateway_argv(argv, home)
-def verify_launchd_loaded(output: str, home: Path) -> None:
+def verify_launchd_loaded(output: str, home: Path, *, uid: int, username: str) -> None:
# Only the job's own blocks, never inherited/default environments or a
# different job embedded in launchctl diagnostic text.
def block(name):
@@ -151,6 +154,10 @@ def verify_launchd_loaded(output: str, home: Path) -> None:
_unverified()
return found[0].splitlines()
+ for key, expected in (("uid", str(uid)), ("username", username)):
+ values = re.findall(r"^\t" + key + r" = (.+)$", output, re.M)
+ if values and values != [expected]:
+ raise ValueError("service_account_mismatch")
env = {}
for line in block("environment"):
if not line.strip():
@@ -160,6 +167,8 @@ def verify_launchd_loaded(output: str, home: Path) -> None:
_unverified()
env[key] = value
verify_home(home, env.get("HERMES_HOME", ""))
+ if home.parent.name != "profiles" and not env.get("HERMES_SUPERVISED_CHILD"):
+ _unverified()
argv = [line.strip() for line in block("arguments")]
programs = re.findall(r"^\tprogram = (.+)$", output, re.M)
if len(programs) != 1 or not argv or programs[0] != argv[0]:
@@ -188,6 +197,20 @@ def verify_launchd_plist(definition: dict, label: str, home: Path) -> None:
_unverified()
+def read_definition(path: Path) -> bytes:
+ # Nonblocking open precedes fstat: a FIFO replacement must not consume the
+ # entire startup deadline waiting for a writer. Symlinked installs work.
+ fd = os.open(path, os.O_RDONLY | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0))
+ with os.fdopen(fd, "rb") as stream:
+ info = os.fstat(stream.fileno())
+ if not stat.S_ISREG(info.st_mode) or info.st_size > 1024 * 1024:
+ _unverified()
+ value = stream.read(1024 * 1024 + 1)
+ if len(value) > 1024 * 1024:
+ _unverified()
+ return value
+
+
def _vbs_identity(script: str) -> tuple[str, list[str]]:
# Recognize the vendor's complete template, not a HERMES_HOME substring
# inside an arbitrary executable script. Doubled quotes are VB literals.
@@ -259,6 +282,6 @@ def verify_windows_task(xml: str | bytes, home: Path, account: str, sid: str) ->
script = _absolute(match[1])
if script.suffix.lower() != '.vbs':
_unverified()
- configured, argv = _vbs_identity(script.read_text(encoding="utf-8"))
+ configured, argv = _vbs_identity(read_definition(script).decode("utf-8"))
verify_home(home, configured)
verify_gateway_argv(argv, home)
diff --git a/tests/hermes_cli/test_gateway_runtime_service.py b/tests/hermes_cli/test_gateway_runtime_service.py
index 7dbc9ab7664..f4148a606a1 100644
--- a/tests/hermes_cli/test_gateway_runtime_service.py
+++ b/tests/hermes_cli/test_gateway_runtime_service.py
@@ -105,6 +105,8 @@ def test_ensure_checks_effective_service_binding_before_start(tmp_path, monkeypa
("requested", "gateway", None), ("other", "gateway", "profile_mismatch"),
("requested", "echo", "service_identity_unverified"),
(None, "gateway", "service_identity_unverified"),
+ ("requested", "unsupervised", "service_identity_unverified"),
+ ("requested", "wrong_account", "service_account_mismatch"),
])
def test_loaded_launchd_identity_is_independent_of_disk(configured, command, reason, tmp_path):
from hermes_cli.gateway_runtime_service_identity import verify_launchd_loaded
@@ -114,11 +116,15 @@ def test_loaded_launchd_identity_is_independent_of_disk(configured, command, rea
argv = ["/bin/echo", "hermes_cli.main", "gateway", "run"]
environment = f"HERMES_HOME => {tmp_path / configured}" if configured else ""
output = "gui/123/ai.hermes.gateway = {\n\tstate = not running\n\tprogram = " + argv[0] + "\n\targuments = {\n" + "\n".join("\t\t" + a for a in argv) + "\n\t}\n\tenvironment = {\n\t\t" + environment + "\n\t}\n}"
+ if command != "unsupervised":
+ output = output.replace("\n\tenvironment = {\n", "\n\tenvironment = {\n\t\tHERMES_SUPERVISED_CHILD => 1\n")
+ if command == "wrong_account":
+ output = output.replace("\n\tstate", "\n\tusername = other\n\tstate")
if reason:
with pytest.raises(ValueError, match=reason):
- verify_launchd_loaded(output, home)
+ verify_launchd_loaded(output, home, uid=123, username="owner")
else:
- verify_launchd_loaded(output, home)
+ verify_launchd_loaded(output, home, uid=123, username="owner")
@pytest.mark.parametrize("case,reason", [
@@ -180,7 +186,7 @@ def test_native_launchd_checks_loaded_job_before_disk(case, reason, tmp_path, mo
home = tmp_path / 'profile'
home.mkdir(mode=0o700)
monkeypatch.setenv('HERMES_HOME', str(home))
- monkeypatch.setattr(pwd, 'getpwuid', lambda uid: SimpleNamespace(pw_dir=str(tmp_path)))
+ monkeypatch.setattr(pwd, 'getpwuid', lambda uid: SimpleNamespace(pw_dir=str(tmp_path), pw_name="owner"))
label = 'ai.hermes.gateway' + ('-' + service.service_suffix(home) if service.service_suffix(home) else '')
plist = tmp_path / 'Library/LaunchAgents' / (label + '.plist')
plist.parent.mkdir(parents=True)
@@ -256,3 +262,26 @@ def test_native_task_query_uses_installed_xml_and_vendor_launcher(wrong, tmp_pat
service.start_existing_gateway_service(found, deadline=time.monotonic()+5)
assert sum('/Run' in a for a in calls) == 1
assert script.read_bytes() == original
+
+
+def test_service_definition_reads_reject_fifo_without_waiting(tmp_path):
+ from hermes_cli.gateway_runtime_service_identity import read_definition
+ regular = tmp_path / 'regular'
+ regular.write_bytes(b'installed definition')
+ assert read_definition(regular) == regular.read_bytes()
+ fifo = tmp_path / 'fifo'
+ os.mkfifo(fifo, 0o600)
+ with pytest.raises(ValueError, match='service_identity_unverified'):
+ read_definition(fifo)
+
+
[email protected]("outer", ["python", "echo"])
+def test_gateway_wrapper_requires_actual_python_entrypoint(outer, tmp_path):
+ from hermes_cli.gateway_runtime_service_identity import verify_gateway_argv
+ argv = [sys.executable if outer == 'python' else '/bin/echo', '-m', 'hermes_cli.stderr_timestamp', '--error-log', str(tmp_path / 'error.log'), '--', sys.executable, '-m', 'hermes_cli.main', 'gateway', 'run']
+ if outer == 'echo':
+ with pytest.raises(ValueError, match='service_identity_unverified'):
+ verify_gateway_argv(argv, tmp_path)
+ else:
+ verify_gateway_argv(argv, tmp_path)