The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): verify the installed Scheduled Task as schtasks exports it
Teknium4389ed69ce26
diff --git a/hermes_cli/gateway_runtime_service.py b/hermes_cli/gateway_runtime_service.pyindex 6e6c41e672a..03cb4758b7a 100644--- a/hermes_cli/gateway_runtime_service.py+++ b/hermes_cli/gateway_runtime_service.py@@ -185,25 +185,29 @@ def _launchd(home: Path, deadline: float) -> ExistingService | None:def _windows(home: Path, deadline: float) -> ExistingService | None:- from hermes_cli.gateway_windows import _schtasks_encoding+ from hermes_cli.gateway_windows import _decode_schtasks_outputsuffix = service_suffix(home)name = f"Hermes_Gateway{'_' + suffix if suffix else ''}"- result = _run(["schtasks.exe", "/Query", "/FO", "CSV", "/NH"], deadline, encoding=_schtasks_encoding())- if result.returncode:- raise RuntimeStartError("service_manager_unavailable")- rows = list(csv.reader(io.StringIO(result.stdout)))++ def query(refusal: str, *argv: str) -> str:+ # schtasks/whoami write the console code page, and /XML declares UTF-16 over those bytes:+ # decode like the drift check does (#116193) instead of the locale codec or raw bytes (#139083).+ result = _run(list(argv), deadline, encoding=None)+ if result.returncode:+ raise RuntimeStartError(refusal)+ return _decode_schtasks_output(result.stdout or b"")++ rows = list(csv.reader(io.StringIO(query("service_manager_unavailable", "schtasks.exe", "/Query", "/FO", "CSV", "/NH"))))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, encoding=None)- identity = _run(["whoami.exe", "/USER", "/FO", "CSV", "/NH"], deadline, encoding=_schtasks_encoding())- if definition.returncode or identity.returncode:- raise RuntimeStartError("service_identity_unverified")- accounts = list(csv.reader(io.StringIO(identity.stdout)))+ unverified = "service_identity_unverified"+ definition = query(unverified, "schtasks.exe", "/Query", "/TN", name, "/XML")+ accounts = list(csv.reader(io.StringIO(query(unverified, "whoami.exe", "/USER", "/FO", "CSV", "/NH"))))if len(accounts) != 1 or len(accounts[0]) != 2:raise RuntimeStartError("service_identity_unverified")- _verify_binding(verify_windows_task, definition.stdout, home, *accounts[0])+ _verify_binding(verify_windows_task, definition, home, *accounts[0])return ExistingService("windows", ("schtasks.exe", "/Run", "/TN", name))# A Startup-folder entry (the fallback when Scheduled Task install was declined/blocked) is login# persistence only, with no start verb or identity to verify. Starting a stopped owner is thediff --git a/hermes_cli/gateway_runtime_service_identity.py b/hermes_cli/gateway_runtime_service_identity.pyindex cd7334800fa..7a9746f9c33 100644--- a/hermes_cli/gateway_runtime_service_identity.py+++ b/hermes_cli/gateway_runtime_service_identity.py@@ -291,9 +291,11 @@ def verify_windows_task(xml: str | bytes, home: Path, account: str, sid: str) ->_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"):+ # schtasks /Query /XML omits elements that hold the Windows default (#139013): an absent RunLevel+ # is least privilege and an absent Enabled is enabled. An explicit other value is still refused.+ if principal.findtext("t:RunLevel", "LeastPrivilege", ns) != "LeastPrivilege" or actions.get("Context") != principal.get("id"):_unverified()- if task.findtext("t:Settings/t:Enabled", "", ns) != "true":+ if task.findtext("t:Settings/t:Enabled", "true", 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"}:diff --git a/hermes_cli/gateway_windows.py b/hermes_cli/gateway_windows.pyindex f275836be8a..590164ec83c 100644--- a/hermes_cli/gateway_windows.py+++ b/hermes_cli/gateway_windows.py@@ -7,6 +7,7 @@ hidden-console launcher instead of ``schtasks /Run`` so start/restart behavior ifrom __future__ import annotations+import codecsimport ctypesimport jsonimport locale@@ -96,6 +97,8 @@ def _decode_schtasks_output(data: bytes) -> str:Scheduled-Task drift check could never settle (#116193). Strict UTF-8 first (ASCII and genuineUTF-8 output pass; legacy multi-byte text fails loudly), then the native code pages, then a lossyfallback so a reader thread never raises."""+ if data[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):+ return data.decode("utf-16") # a genuine UTF-16 write (BOM) decodes as such, never as a code pagefor encoding in ("utf-8", *_windows_console_encodings()):try:return data.decode(encoding)diff --git a/tests/hermes_cli/test_gateway_runtime_service.py b/tests/hermes_cli/test_gateway_runtime_service.pyindex b84620b0a8d..494c3bd4f86 100644--- a/tests/hermes_cli/test_gateway_runtime_service.py+++ b/tests/hermes_cli/test_gateway_runtime_service.py@@ -136,20 +136,9 @@ def test_loaded_launchd_identity_is_independent_of_disk(configured, command, reaverify_launchd_loaded(output, home, uid=123, username="owner")[email protected]("case,reason", [- ("bound", None), ("utf16", 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"), ("malformed_xml", "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()+def _installed_vbs(home, configured):+ """The current installed launcher grammar; no script is executed."""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")',@@ -162,8 +151,33 @@ def test_task_xml_binds_actual_action_and_principal(case, reason, tmp_path):f'sh.CurrentDirectory = "{home}"',f'sh.Run "{sys.executable} -m hermes_cli.main gateway run", 0, False',]) + "\n", encoding='utf-8')+ return script+++def _as_schtasks_exports(xml):+ """``schtasks /Query /XML`` omits elements holding the Windows default (seen on a real host)."""+ return xml.replace('<RunLevel>LeastPrivilege</RunLevel>', '').replace('<Enabled>true</Enabled>\n <Hidden>', '<Hidden>')++[email protected]("case,reason", [+ ("bound", None), ("utf16", 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"), ("malformed_xml", "service_identity_unverified"),+ ("schtasks_export", None), ("elevated", "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 = _installed_vbs(home, str(home if case != 'wrong_home' else tmp_path / 'other'))user = 'DOMAIN\\owner'xml = _build_scheduled_task_xml('Hermes_Gateway', script, user)+ if case == 'schtasks_export':+ xml = _as_schtasks_exports(xml)+ if case == 'elevated': # an explicit non-default value is still refused+ xml = xml.replace('<RunLevel>LeastPrivilege</RunLevel>', '<RunLevel>HighestAvailable</RunLevel>')if case == 'wrong_user':xml = xml.replace(user, 'DOMAIN\\other')if case == 'missing_user':@@ -330,7 +344,7 @@ def test_windows_startup_folder_entry_still_restarts_a_stopped_owner(tmp_path, m(startup / f"Hermes_Gateway_{service.service_suffix(home)}.vbs").write_text("' fallback\r\n")monkeypatch.setattr(gateway_windows, "_startup_dir", lambda: startup)queries, spawned = [], []- monkeypatch.setattr(service, "_run", lambda argv, *a, **k: queries.append(argv) or SimpleNamespace(returncode=0, stdout=""))+ monkeypatch.setattr(service, "_run", lambda argv, *a, **k: queries.append(argv) or SimpleNamespace(returncode=0, stdout=b""))monkeypatch.setattr(service.sys, "platform", "win32")monkeypatch.setattr(runtime, "discover_gateway_endpoint", lambda *a, **k: runtime.GatewayDiscovery("absent"))monkeypatch.setattr(start, "spawn_unmanaged_gateway", lambda target, **k: spawned.append(Path(target)))@@ -338,3 +352,32 @@ def test_windows_startup_folder_entry_still_restarts_a_stopped_owner(tmp_path, massert result.reason_code != "startup_service_requires_login"assert spawned == [home.resolve()]assert all(argv[:2] == ["schtasks.exe", "/Query"] for argv in queries) # nothing installed or run++[email protected]("linux")+def test_task_discovery_reads_localized_schtasks_output(tmp_path, monkeypatch):+ """A localized host (zh-CN, console cp936) with Python in UTF-8 mode: schtasks and whoami write+ cp936 bytes, and /XML declares UTF-16 over them with the defaults elided (#139083, #139013).+ The installed task must still be verified, not refused as service_identity_unverified."""+ from types import SimpleNamespace+ from hermes_cli import gateway_runtime_service as service, gateway_windows+ from hermes_cli.gateway_windows import _build_scheduled_task_xml++ home = tmp_path / "profile"+ home.mkdir()+ script = _installed_vbs(home, str(home))+ name = "Hermes_Gateway_" + service.service_suffix(home)+ account, sid = "DESKTOP-1\\\u65b9\u821f", "S-1-5-21-123"+ # whoami first: it is queried with /FO CSV too.+ out = {"whoami.exe": f'"{account}","{sid}"\r\n', "/XML": _as_schtasks_exports(+ _build_scheduled_task_xml(name, script, account)), "/FO": f'"\\{name}","N/A","\u5c31\u7eea"\r\n'}+ monkeypatch.setattr(gateway_windows, "_windows_console_encodings", lambda: ["cp936"])+ monkeypatch.setattr(service.sys, "platform", "win32")++ def run(argv, *_args, encoding=None, **_kwargs): # subprocess semantics: bytes, or decoded with encoding+ data = next(text for key, text in out.items() if key in argv).encode("cp936")+ return SimpleNamespace(returncode=0, stdout=data.decode(encoding) if encoding else data)++ monkeypatch.setattr(service, "_run", run)+ found = service.discover_existing_gateway_service(home, deadline=time.monotonic() + 5)+ assert found is not None and found.start_argv == ("schtasks.exe", "/Run", "/TN", name)