Skip to content

The agent that grows with you

fix: bind loaded launchd jobs and scheduled task XML before start

Teknium1ce0d11ef3fe
diff --git a/hermes_cli/gateway_runtime_service.py b/hermes_cli/gateway_runtime_service.py
index 05fc5a1a62e..f785d5873d7 100644
--- a/hermes_cli/gateway_runtime_service.py
+++ b/hermes_cli/gateway_runtime_service.py
@@ -56,6 +56,16 @@ def _run(argv: list[str] | tuple[str, ...], deadline: float):
creationflags=windows_hide_flags(), timeout=remaining(deadline))
+def _verify_binding(verify, *args) -> None:
+ try:
+ verify(*args)
+ except (ValueError, TypeError, KeyError, AttributeError) as exc:
+ reason = str(exc)
+ raise RuntimeStartError(reason if reason in {
+ "profile_mismatch", "service_account_mismatch", "service_disabled"
+ } else "service_identity_unverified") from None
+
+
def _exists(path: Path) -> bool:
try:
path.lstat()
@@ -121,20 +131,15 @@ def _launchd(home: Path, deadline: float) -> ExistingService | None:
label = f"ai.hermes.gateway{'-' + suffix if suffix else ''}"
account_home = Path(pwd.getpwuid(os.getuid()).pw_dir) # windows-footgun: ok — native launchd only
plist = account_home / "Library/LaunchAgents" / f"{label}.plist"
+ from hermes_cli.gateway_runtime_service_identity import verify_launchd_loaded, verify_launchd_plist
installed = _exists(plist)
- if installed:
- with plist.open("rb") as stream:
- definition = plistlib.load(stream)
- configured = definition.get("EnvironmentVariables", {}).get("HERMES_HOME")
- if not configured or Path(configured).resolve() != home or definition.get("Label") != label:
- raise RuntimeStartError("profile_mismatch")
- if definition.get("Disabled"):
- raise RuntimeStartError("service_disabled")
domains = [f"gui/{os.getuid()}", f"user/{os.getuid()}"] # windows-footgun: ok — native launchd only
found = []
+ loaded = []
for domain in domains:
result = _run(["launchctl", "print", f"{domain}/{label}"], deadline)
if result.returncode == 0:
+ loaded.append(result.stdout)
found.append(ExistingService("launchd", ("launchctl", "kickstart", f"{domain}/{label}"),
"state = running" in result.stdout))
continue
@@ -144,8 +149,12 @@ 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)
return found[0]
if installed:
+ with plist.open("rb") as stream:
+ definition = plistlib.load(stream)
+ _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)))
return None
@@ -162,6 +171,15 @@ def _windows(home: Path, deadline: float) -> ExistingService | None:
if any(len(row) != 3 for row in rows if row):
raise RuntimeStartError("service_state_unknown")
if any(row and row[0].lstrip("\\") == name for row in rows):
+ from hermes_cli.gateway_runtime_service_identity import verify_windows_task
+ definition = _run(["schtasks.exe", "/Query", "/TN", name, "/XML"], deadline)
+ identity = _run(["whoami.exe", "/USER", "/FO", "CSV", "/NH"], deadline)
+ if definition.returncode or identity.returncode:
+ raise RuntimeStartError("service_identity_unverified")
+ accounts = list(csv.reader(io.StringIO(identity.stdout)))
+ if len(accounts) != 1 or len(accounts[0]) != 2:
+ raise RuntimeStartError("service_identity_unverified")
+ _verify_binding(verify_windows_task, definition.stdout, home, *accounts[0])
return ExistingService("windows", ("schtasks.exe", "/Run", "/TN", name))
# Startup-folder entries are installed persistence too, but have no independent
# start supervisor. Do not bypass them with a job-bound unmanaged child.
diff --git a/hermes_cli/gateway_runtime_service_identity.py b/hermes_cli/gateway_runtime_service_identity.py
index 1cd545cd677..ec3d0f3d205 100644
--- a/hermes_cli/gateway_runtime_service_identity.py
+++ b/hermes_cli/gateway_runtime_service_identity.py
@@ -140,3 +140,122 @@ def verify_systemd(props: dict[str, str], manager_env: str, home: Path, *, syste
if not argv or match[1] != argv[0]:
_unverified()
verify_gateway_argv(argv, home)
+
+
+def verify_launchd_loaded(output: str, home: Path) -> None:
+ # Only the job's own blocks, never inherited/default environments or a
+ # different job embedded in launchctl diagnostic text.
+ def block(name):
+ found = re.findall(r"^\t" + name + r" = \{\n(.*?)^\t\}", output, re.M | re.S)
+ if len(found) != 1:
+ _unverified()
+ return found[0].splitlines()
+
+ env = {}
+ for line in block("environment"):
+ if not line.strip():
+ continue
+ key, sep, value = line.strip().partition(" => ")
+ if not sep or key in env:
+ _unverified()
+ env[key] = value
+ verify_home(home, env.get("HERMES_HOME", ""))
+ 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]:
+ _unverified()
+ verify_gateway_argv(argv, home)
+
+
+def verify_launchd_plist(definition: dict, label: str, home: Path) -> None:
+ if definition.get("Label") != label:
+ _unverified()
+ if definition.get("Disabled"):
+ raise ValueError("service_disabled")
+ if definition.get("UserName") or definition.get("GroupName") or definition.get("RootDirectory"):
+ _unverified()
+ env = definition.get("EnvironmentVariables", {})
+ if not isinstance(env, dict):
+ _unverified()
+ verify_home(home, env.get("HERMES_HOME", ""))
+ argv = definition.get("ProgramArguments")
+ if not isinstance(argv, list) or not all(isinstance(arg, str) for arg in argv):
+ _unverified()
+ if definition.get("Program", argv[0] if argv else None) != (argv[0] if argv else None):
+ _unverified()
+ verify_gateway_argv(argv, home)
+ if home.parent.name != "profiles" and not env.get("HERMES_SUPERVISED_CHILD"):
+ _unverified()
+
+
+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.
+ literal = r'"(?:[^"\r\n]|"")*"'
+ lines = script.splitlines()
+ if len(lines) < 16 or not lines[0].startswith("' "):
+ _unverified()
+ fixed = ["Option Explicit", "Dim sh, env, existing_pp",
+ 'Set sh = CreateObject("WScript.Shell")', 'Set env = sh.Environment("PROCESS")']
+ if lines[1:5] != fixed:
+ _unverified()
+ env = {}
+ index = 5
+ while index < len(lines):
+ match = re.fullmatch(r'env.Item\("([A-Z_]+)"\) = (' + literal + ')', lines[index])
+ if not match:
+ break
+ if match[1] not in {"HERMES_HOME", "HERMES_SUPERVISED_CHILD", "HERMES_GATEWAY_DETACHED", "PYTHONIOENCODING", "VIRTUAL_ENV"} or match[1] in env:
+ _unverified()
+ env[match[1]] = match[2][1:-1].replace('""', '"')
+ index += 1
+ tail = lines[index:]
+ if len(tail) != 8 or tail[:2] != ['existing_pp = env.Item("PYTHONPATH")', 'If Len(existing_pp) > 0 Then'] or tail[3] != 'Else' or tail[5] != 'End If':
+ _unverified()
+ if not re.fullmatch(r' env.Item\("PYTHONPATH"\) = ' + literal + r' & existing_pp', tail[2]) or not re.fullmatch(r' env.Item\("PYTHONPATH"\) = ' + literal, tail[4]):
+ _unverified()
+ if not re.fullmatch(r'sh.CurrentDirectory = ' + literal, tail[6]):
+ _unverified()
+ run = re.fullmatch(r'sh.Run (' + literal + r'), 0, False', tail[7])
+ if not run or not env.get("HERMES_SUPERVISED_CHILD"):
+ _unverified()
+ command = run[1][1:-1].replace('""', '"')
+ if "%" in command or "%" in env.get("HERMES_HOME", ""):
+ _unverified()
+ # The template uses list2cmdline, with no embedded executable quote escapes.
+ argv = [part.strip('"') for part in shlex.split(command, posix=False)]
+ return env.get("HERMES_HOME", ""), argv
+
+
+def verify_windows_task(xml: str, home: Path, account: str, sid: str) -> None:
+ import xml.etree.ElementTree as ET
+
+ task = ET.fromstring(xml)
+ ns = {"t": "http://schemas.microsoft.com/windows/2004/02/mit/task"}
+ principals = task.findall("t:Principals/t:Principal", ns)
+ actions = task.find("t:Actions", ns)
+ if len(principals) != 1 or actions is None or len(actions) != 1:
+ _unverified()
+ principal = principals[0]
+ user = principal.findtext("t:UserId", "", ns)
+ if not user or not account or not sid or principal.find("t:GroupId", ns) is not None:
+ _unverified()
+ if user.casefold() not in {account.casefold(), sid.casefold()}:
+ raise ValueError("service_account_mismatch")
+ if principal.findtext("t:RunLevel", "", ns) != "LeastPrivilege" or actions.get("Context") != principal.get("id"):
+ _unverified()
+ if task.findtext("t:Settings/t:Enabled", "", ns) != "true":
+ raise ValueError("service_disabled")
+ action = actions[0]
+ if action.tag != '{' + ns['t'] + '}Exec' or action.findtext('t:Command', '', ns).lower() not in {"wscript.exe", r"c:\windows\system32\wscript.exe"}:
+ _unverified()
+ args = action.findtext("t:Arguments", "", ns)
+ match = re.fullmatch(r'//B //Nologo "([^"\r\n]+)"', args)
+ if not match:
+ _unverified()
+ script = _absolute(match[1])
+ if script.suffix.lower() != '.vbs':
+ _unverified()
+ configured, argv = _vbs_identity(script.read_text(encoding="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 f466e8e12d7..8fd925b5a04 100644
--- a/tests/hermes_cli/test_gateway_runtime_service.py
+++ b/tests/hermes_cli/test_gateway_runtime_service.py
@@ -99,3 +99,68 @@ def test_ensure_checks_effective_service_binding_before_start(tmp_path, monkeypa
if case != 'system':
assert unit.read_bytes() == original
assert not (home / 'logs').exists()
+
+
[email protected]("configured,command,reason", [
+ ("requested", "gateway", None), ("other", "gateway", "profile_mismatch"),
+ ("requested", "echo", "service_identity_unverified"),
+ (None, "gateway", "service_identity_unverified"),
+])
+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
+ home = tmp_path / "requested"
+ argv = [sys.executable, "-m", "hermes_cli.main", "gateway", "run"]
+ if command == "echo":
+ 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 reason:
+ with pytest.raises(ValueError, match=reason):
+ verify_launchd_loaded(output, home)
+ else:
+ verify_launchd_loaded(output, home)
+
+
[email protected]("case,reason", [
+ ("bound", None), ("wrong_home", "profile_mismatch"),
+ ("wrong_user", "service_account_mismatch"), ("missing_user", "service_identity_unverified"),
+ ("extra_action", "service_identity_unverified"), ("disabled", "service_disabled"),
+ ("unknown_script", "service_identity_unverified"),
+])
+def test_task_xml_binds_actual_action_and_principal(case, reason, tmp_path):
+ from hermes_cli.gateway_runtime_service_identity import verify_windows_task
+ from hermes_cli.gateway_windows import _build_scheduled_task_xml
+ home = tmp_path / 'requested'
+ home.mkdir()
+ script = home / 'gateway.vbs'
+ configured = str(home if case != 'wrong_home' else tmp_path / 'other')
+ # The current installed launcher grammar; no script is executed.
+ script.write_text("\n".join([
+ "' Hermes Agent Gateway", "Option Explicit", "Dim sh, env, existing_pp",
+ 'Set sh = CreateObject("WScript.Shell")', 'Set env = sh.Environment("PROCESS")',
+ f'env.Item("HERMES_HOME") = "{configured}"',
+ 'env.Item("HERMES_SUPERVISED_CHILD") = "1"',
+ 'env.Item("VIRTUAL_ENV") = "C:\\Hermes"',
+ 'existing_pp = env.Item("PYTHONPATH")', 'If Len(existing_pp) > 0 Then',
+ ' env.Item("PYTHONPATH") = "C:\\Hermes;" & existing_pp', 'Else',
+ ' env.Item("PYTHONPATH") = "C:\\Hermes"', 'End If',
+ f'sh.CurrentDirectory = "{home}"',
+ f'sh.Run "{sys.executable} -m hermes_cli.main gateway run", 0, False',
+ ]) + "\n", encoding='utf-8')
+ user = 'DOMAIN\\owner'
+ xml = _build_scheduled_task_xml('Hermes_Gateway', script, user)
+ if case == 'wrong_user':
+ xml = xml.replace(user, 'DOMAIN\\other')
+ if case == 'missing_user':
+ xml = xml.replace(f'<UserId>{user}</UserId>', '')
+ if case == 'extra_action':
+ xml = xml.replace('</Actions>', '<Exec><Command>other.exe</Command></Exec></Actions>')
+ if case == 'disabled':
+ xml = xml.replace('<Enabled>true</Enabled>', '<Enabled>false</Enabled>')
+ if case == 'unknown_script':
+ script.write_text('MsgBox "not a gateway"', encoding='utf-8')
+ if reason:
+ with pytest.raises(ValueError, match=reason):
+ verify_windows_task(xml, home, user, 'S-1-5-21-123')
+ else:
+ verify_windows_task(xml, home, user, 'S-1-5-21-123')