The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): verify the osascript-wrapped launchd job the installer writes
Paulo Nascimento047a0f75cde0
diff --git a/hermes_cli/gateway_runtime_service_identity.py b/hermes_cli/gateway_runtime_service_identity.pyindex 7a9746f9c33..d58a044b090 100644--- a/hermes_cli/gateway_runtime_service_identity.py+++ b/hermes_cli/gateway_runtime_service_identity.py@@ -5,6 +5,8 @@ programs. Manager-loaded values take precedence over filenames and disk copies."""from __future__ import annotations+import ast+import jsonimport osfrom pathlib import Pathimport re@@ -54,21 +56,51 @@ def verify_home(home: Path, configured: str) -> None:raise ValueError("profile_mismatch")+def _runtime_module(python: str, source: str) -> str | None:+ """The module an inline ``-I -c`` source runs when it is ``_launchers.runtime_command``'s bootstrap+ byte for byte (``installation_command`` persists it when there is no store Python); else None."""+ from hermes_cli._launchers import runtime_command+ literal = re.search(r"""sys\.path\.insert\(0, ('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*")\); """, source)+ try:+ root = Path(ast.literal_eval(literal[1])) if literal else None+ return next((module for module in ("hermes_cli.stderr_timestamp", "hermes_cli.main")+ if root and runtime_command(root, module=module, python=python)[3] == source), None)+ except (ValueError, SyntaxError, OSError, RuntimeError):+ return None+++def _launch_module(argv: list[str]) -> tuple[str, list[str]] | None:+ """``(module, its argv)`` for the module launches the installer persists: ``python -m``, the source+ launcher's ``--run-module``, or the inline bootstrap. None for anything else."""+ executable = Path(argv[0]).name.lower() if argv else ""+ if re.fullmatch(r"python(?:w|\d+(?:\.\d+)*)?(?:\.exe)?", executable):+ if argv[1:2] == ["-m"] and len(argv) > 2:+ return argv[2], argv[3:]+ if argv[1:3] == ["-I", "-c"] and len(argv) > 3 and (module := _runtime_module(argv[0], argv[3])):+ return module, argv[4:]+ elif executable in {"hermes", "hermes.exe"} and argv[1:2] == ["--run-module"] and len(argv) > 2:+ return argv[2], argv[3:]+ return None++def verify_gateway_argv(argv: list[str], home: Path) -> None:from gateway.status import looks_like_gateway_command_line# 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()):+ wrapper = _launch_module(argv)+ if wrapper is not None and wrapper[0] == "hermes_cli.stderr_timestamp":+ args = wrapper[1]+ if len(args) < 4 or args[0] != "--error-log" or args[2] != "--":_unverified()- argv = argv[6:]+ argv = args[3:]if not argv or not looks_like_gateway_command_line(subprocess_command(argv)):_unverified()executable = Path(argv[0]).name.lower()if re.fullmatch(r"python(?:w|\d+(?:\.\d+)*)?(?:\.exe)?", executable):- if argv[1:3] != ["-m", "hermes_cli.main"]:+ entry = _launch_module(argv)+ if entry is None or entry[0] != "hermes_cli.main":_unverified()- args = argv[3:]+ args = entry[1]elif executable in {"hermes", "hermes.exe"}:args = argv[1:]else:@@ -168,6 +200,33 @@ def verify_systemd(props: dict[str, str], manager_env: str, home: Path, *, systeverify_gateway_argv(argv, home)+# The launchd job's Local Network wrapper (gateway_launchd.launchd_program_arguments, #71206) runs ONE shell+# string through JXA's $.system(). Only that exact template is unwrapped, and only when the shell string+# re-serializes byte for byte from its own tokens: no operator, substitution or second command rides along.+_LAUNCHD_JXA = re.compile(+ r'ObjC\.import\("stdlib"\); const status=\$\.system\(("(?:[^"\\]|\\.)*")\); const signal=status & 127; '+ r'\$\.exit\(status === -1 \? 1 : signal === 0 \? \(status >> 8\) & 255 : 128 \+ signal\);')+++def _launchd_command(argv: list[str]) -> list[str]:+ if argv[:1] != ["/usr/bin/osascript"]:+ return argv+ match = _LAUNCHD_JXA.fullmatch(argv[4]) if len(argv) == 5 and argv[1:4] == ["-l", "JavaScript", "-e"] else None+ if match is None:+ _unverified()+ try:+ shell = json.loads(match[1])+ tokens = shlex.split(shell)+ except ValueError:+ _unverified()+ if len(tokens) < 6 or tokens[0] != "exec" or tokens[-4] != ">>" or tokens[-2] != "2>>":+ _unverified()+ command = tokens[1:-4]+ if shell != f"exec {shlex.join(command)} >> {shlex.quote(tokens[-3])} 2>> {shlex.quote(tokens[-1])}":+ _unverified()+ return command++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.@@ -196,7 +255,7 @@ def verify_launchd_loaded(output: str, home: Path, *, uid: int, username: str) -programs = re.findall(r"^\tprogram = (.+)$", output, re.MULTILINE)if len(programs) != 1 or not argv or programs[0] != argv[0]:_unverified()- verify_gateway_argv(argv, home)+ verify_gateway_argv(_launchd_command(argv), home)def verify_launchd_plist(definition: dict, label: str, home: Path) -> None:@@ -215,7 +274,7 @@ def verify_launchd_plist(definition: dict, label: str, home: Path) -> None:_unverified()if definition.get("Program", argv[0] if argv else None) != (argv[0] if argv else None):_unverified()- verify_gateway_argv(argv, home)+ verify_gateway_argv(_launchd_command(argv), home)if home.parent.name != "profiles" and not env.get("HERMES_SUPERVISED_CHILD"):_unverified()diff --git a/tests/hermes_cli/test_gateway_runtime_service.py b/tests/hermes_cli/test_gateway_runtime_service.pyindex 94c66e379cf..9588d4ab915 100644--- a/tests/hermes_cli/test_gateway_runtime_service.py+++ b/tests/hermes_cli/test_gateway_runtime_service.py@@ -136,6 +136,66 @@ def test_loaded_launchd_identity_is_independent_of_disk(configured, command, reaverify_launchd_loaded(output, home, uid=123, username="owner")+def _launchd_gateway_command(tmp_path, monkeypatch, *, store, profile=""):+ """The gateway command generate_launchd_plist persists, from a store Python or an external one."""+ from hermes_cli import _launchers, gateway as gw+ from hermes_cli.gateway_launchd import _timestamped_stderr_gateway_command+ monkeypatch.setattr(gw, "PROJECT_ROOT", tmp_path / "hermes-agent")+ monkeypatch.setattr(gw, "get_python_path", lambda: sys.executable)+ monkeypatch.setattr(gw, "_profile_arg", lambda *a, **k: profile)+ monkeypatch.setattr(_launchers, "resolve_store_python", lambda *a, **k: Path(sys.executable) if store else None)+ return _timestamped_stderr_gateway_command(tmp_path / "logs" / "gateway.error.log", external_supervisor=True)++[email protected]("linux", "macos") # launchd ProgramArguments are POSIX shell-quoted[email protected]("case,reason", [+ ("store", None), ("inline", None), ("store_profile", "profile_mismatch"),+ ("chained_shell", "service_identity_unverified"), ("substituted_shell", "service_identity_unverified"),+ ("extra_jxa", "service_identity_unverified"), ("foreign_osascript", "service_identity_unverified"),+ ("tampered_bootstrap", "service_identity_unverified"), ("arbitrary_inline", "service_identity_unverified"),+ ("other_run_module", "service_identity_unverified"),+])+def test_launchd_verifies_the_osascript_wrapped_command_the_installer_writes(case, reason, tmp_path, monkeypatch):+ """The Local Network wrapper (#71206) is unwrapped only as its exact template, and the command inside+ is held to the same gateway identity as a bare ProgramArguments, on disk and as launchd loaded it."""+ import plistlib+ from hermes_cli.gateway_launchd import launchd_program_arguments+ from hermes_cli.gateway_runtime_service_identity import verify_launchd_loaded, verify_launchd_plist+ home = tmp_path / ".hermes"+ command = _launchd_gateway_command(tmp_path, monkeypatch, store=case not in {"inline", "tampered_bootstrap"},+ profile="--profile stranger" if case == "store_profile" else "")+ if case == "tampered_bootstrap":+ tampered = command[3].replace("import hermes_bootstrap; ", "import hermes_bootstrap; print('injected'); ")+ assert tampered != command[3]+ command[3] = tampered+ if case == "arbitrary_inline":+ command = [sys.executable, "-I", "-c", "print('injected')", *command[3:]]+ if case == "other_run_module":+ command[2] = "other_module"+ argv = launchd_program_arguments(command, tmp_path / "logs" / "gateway.log", tmp_path / "logs" / "gateway.error.log")+ shell_edits = {"chained_shell": (" >> ", "; id >> "), "substituted_shell": (" gateway run", " $(id) gateway run")}+ if case in shell_edits:+ edited = argv[4].replace(*shell_edits[case], 1)+ assert edited != argv[4]+ argv[4] = edited+ if case == "extra_jxa":+ argv[4] += ' $.system("id");'+ if case == "foreign_osascript":+ argv[0] = str(tmp_path / "osascript")+ env = dict(HERMES_HOME=str(home), HERMES_SUPERVISED_CHILD="1")+ definition = plistlib.loads(plistlib.dumps(dict(Label="ai.hermes.gateway", ProgramArguments=argv, EnvironmentVariables=env)))+ output = ("gui/123/ai.hermes.gateway = {\n\tstate = not running\n\tprogram = " + argv[0] + "\n\targuments = {\n"+ + "\n".join("\t\t" + arg for arg in argv) + "\n\t}\n\tenvironment = {\n"+ + "".join(f"\t\t{key} => {value}\n" for key, value in env.items()) + "\t}\n}")+ for verify in (lambda: verify_launchd_plist(definition, "ai.hermes.gateway", home),+ lambda: verify_launchd_loaded(output, home, uid=123, username="owner")):+ if reason:+ with pytest.raises(ValueError, match=reason):+ verify()+ else:+ verify()++def _installed_vbs(home, configured):"""The current installed launcher grammar; no script is executed."""script = home / 'gateway.vbs'