Skip to content

The agent that grows with you

test(e2e/windows): inline message gates, AccessCheck-based standard-user probe, strict status check

teknium11e6a3bbeabfc
diff --git a/tests/e2e/core/windows_update/test_fresh_install_update.py b/tests/e2e/core/windows_update/test_fresh_install_update.py
index dd5565db5cb..97156570554 100644
--- a/tests/e2e/core/windows_update/test_fresh_install_update.py
+++ b/tests/e2e/core/windows_update/test_fresh_install_update.py
@@ -13,7 +13,7 @@ import json
import pytest
-from tests.e2e.core._pending_fixes import known_gate
+from tests.e2e.core._pending_fixes import known_failure
from tests.e2e.core.windows_update._machine import (
NEXT_MARKER,
REQUIRES_OPT_IN,
@@ -29,13 +29,6 @@ from tests.fakes.fake_llm_provider import FakeLLMServer
pytestmark = [pytest.mark.platforms("windows"), pytest.mark.integration,
pytest.mark.live_system_guard_bypass, REQUIRES_OPT_IN]
-KNOWN = {
- "update": (
- r"^hermes update exited 1: ✗ Update failed: \[WinError 2\]",
- "gated on #124634: on a machine without system Git, the pinned Git that install.ps1 "
- "staged never reaches `hermes update`'s PATH",
- ),
-}
@pytest.fixture(scope="module")
@@ -82,11 +75,16 @@ def test_first_agent_launch_runs_the_turn(journey: Journey) -> None:
def test_update_moves_checkout_to_next(journey: Journey) -> None:
m, run = journey.machine, journey["update"]
- with known_gate(KNOWN, "update"):
- assert run.returncode == 0, fail_with(m, f"hermes update exited {run.returncode}: {failure_line(run)}", run)
+ with known_failure(r"^hermes update exited 1: ✗ Update failed: \[WinError 2\]",
+ "gated on #124634: on a machine without system Git, the pinned Git install.ps1 "
+ "staged never reaches `hermes update`'s PATH"):
+ assert run.returncode == 0, fail_with(
+ m, f"hermes update exited {run.returncode}: {failure_line(run)}", run)
head = m.installed_head()
- assert head == m.next, fail_with(m, f"after hermes update the checkout is at {head}, expected NEXT {m.next}", run)
- assert (m.install_dir / NEXT_MARKER).is_file(), fail_with(m, "NEXT's marker file is missing from the checkout", run)
+ assert head == m.next, fail_with(
+ m, f"after hermes update the checkout is at {head}, expected NEXT {m.next}", run)
+ assert (m.install_dir / NEXT_MARKER).is_file(), fail_with(
+ m, "NEXT's marker file is missing from the checkout", run)
receipt_path = m.hermes_home / "logs" / "update_receipts" / "latest.json"
receipt = json.loads(receipt_path.read_text(encoding="utf-8")) if receipt_path.is_file() else {}
assert receipt.get("outcome") == "success", fail_with(
diff --git a/tests/e2e/core/windows_update/test_gateway_across_update.py b/tests/e2e/core/windows_update/test_gateway_across_update.py
index d86503669bc..411b91450f6 100644
--- a/tests/e2e/core/windows_update/test_gateway_across_update.py
+++ b/tests/e2e/core/windows_update/test_gateway_across_update.py
@@ -14,7 +14,7 @@ import re
import psutil
import pytest
-from tests.e2e.core._pending_fixes import known_gate
+from tests.e2e.core._pending_fixes import known_failure
from tests.e2e.core.windows._helpers import wait_until
from tests.e2e.core.windows_update._machine import (
REQUIRES_OPT_IN,
@@ -27,15 +27,8 @@ from tests.fakes.fake_llm_provider import FakeLLMServer
pytestmark = [pytest.mark.platforms("windows"), pytest.mark.integration,
pytest.mark.live_system_guard_bypass, REQUIRES_OPT_IN]
-_INVISIBLE = ("gated on #124318 (same root as #123430/#123463/#123490): the updater relaunches the "
- "gateway as `python -I -c ...`, a form Windows gateway discovery rejects, so the live "
- "gateway is invisible")
-KNOWN = {
- "update_restart": (r"^hermes update with a running gateway reported a failed gateway restart", _INVISIBLE),
- "discoverable": (r"^after update the serving gateway \(pid \d+\) is invisible", _INVISIBLE),
- "next_update": (r"^the next hermes update is blocked at the gateway pause step", _INVISIBLE),
- "stop": (r"^after update `hermes gateway stop` left the serving gateway \(pid \d+\) running", _INVISIBLE),
-}
+_INVISIBLE = ("gated on #124318: the gateway the updater relaunches holds its lock without gateway.pid "
+ "metadata, so `hermes gateway status`/`stop` and the next update's pause cannot see it")
_RESTART_FAILURE = re.compile(
r"^.*(recovery failed|restart could not be verified|restart incomplete|not verified alive).*$", re.M)
_STATUS_LINE = re.compile(r"^.*[✓✗].*[Gg]ateway.*$", re.M)
@@ -95,7 +88,8 @@ def journey(tmp_path_factory):
def test_launcher_started_gateway_is_visible_before_update(journey: Journey) -> None:
m, state, status = journey.machine, journey["state_before"], journey["status_before"]
- assert status.returncode == 0 and "running" in _status_line(status.stdout).lower(), fail_with(
+ line = _status_line(status.stdout)
+ assert status.returncode == 0 and line.startswith("✓") and str(state.get("pid")) in line, fail_with(
m, f"the launcher-started gateway (pid {state.get('pid')}) is invisible to `hermes gateway status` "
f"before any update: {_status_line(status.stdout)!r}", status)
@@ -104,7 +98,9 @@ def test_update_with_running_gateway_succeeds(journey: Journey) -> None:
m, run = journey.machine, journey["update"]
journey["state_before"] # the precondition: a gateway was running when the update began
failure = _RESTART_FAILURE.search(run.stdout)
- with known_gate(KNOWN, "update_restart"):
+ with known_failure(r"^hermes update with a running gateway reported a failed gateway restart "
+ r"\(rc=\d+\): ⚠ Windows gateway restart could not be verified",
+ _INVISIBLE):
assert run.returncode == 0 and failure is None, fail_with(
m, f"hermes update with a running gateway reported a failed gateway restart "
f"(rc={run.returncode}): {failure.group(0).strip() if failure else '<no restart message>'}", run)
@@ -121,7 +117,8 @@ def test_gateway_discoverable_after_update(journey: Journey) -> None:
m, state, status = journey.machine, journey["state_after"], journey["status_after"]
pid, pidfile = int(state.get("pid") or 0), journey["pidfile_after"]
line = _status_line(status.stdout)
- with known_gate(KNOWN, "discoverable"):
+ with known_failure(r"^after update the serving gateway \(pid \d+\) is invisible",
+ _INVISIBLE):
assert status.returncode == 0 and str(pid) in line and pidfile, fail_with(
m, f"after update the serving gateway (pid {pid}) is invisible: `hermes gateway status` says "
f"{line!r}; gateway.pid present={pidfile}", status)
@@ -131,7 +128,9 @@ def test_next_update_is_not_blocked(journey: Journey) -> None:
m, run = journey.machine, journey["update_again"]
journey["state_after"] # a gateway was running (the relaunched one)
blocked = "Could not map Windows gateway PIDs" in run.stdout
- with known_gate(KNOWN, "next_update"):
+ with known_failure(r"^the next hermes update is blocked at the gateway pause step \(rc=1, "
+ r"'Could not map Windows gateway PIDs' printed=True\)",
+ _INVISIBLE):
assert run.returncode == 0 and not blocked, fail_with(
m, f"the next hermes update is blocked at the gateway pause step (rc={run.returncode}, "
f"'Could not map Windows gateway PIDs' printed={blocked})", run)
@@ -141,7 +140,8 @@ def test_gateway_stop_after_update(journey: Journey) -> None:
m, stop, state = journey.machine, journey["stop"], journey["state_before_stop"]
pid = int(state.get("pid") or 0)
assert pid, fail_with(m, f"no gateway recorded before stop: {state}")
- with known_gate(KNOWN, "stop"):
+ with known_failure(r"^after update `hermes gateway stop` left the serving gateway \(pid \d+\) running",
+ _INVISIBLE):
assert journey["stopped"], fail_with(
m, f"after update `hermes gateway stop` left the serving gateway (pid {pid}) running", stop)
assert stop.returncode == 0, fail_with(m, f"hermes gateway stop exited {stop.returncode}", stop)
diff --git a/tests/e2e/core/windows_update/test_git_and_holders.py b/tests/e2e/core/windows_update/test_git_and_holders.py
index ec4d57775d5..1f7bd759b0a 100644
--- a/tests/e2e/core/windows_update/test_git_and_holders.py
+++ b/tests/e2e/core/windows_update/test_git_and_holders.py
@@ -19,7 +19,7 @@ import subprocess
import psutil
import pytest
-from tests.e2e.core._pending_fixes import known_gate
+from tests.e2e.core._pending_fixes import known_failure
from tests.e2e.core.windows._helpers import Run, wait_until
from tests.e2e.core.windows_update._machine import (
REQUIRES_OPT_IN,
@@ -34,15 +34,6 @@ from tests.fakes.fake_llm_provider import FakeLLMServer
pytestmark = [pytest.mark.platforms("windows"), pytest.mark.integration,
pytest.mark.live_system_guard_bypass, REQUIRES_OPT_IN]
-KNOWN = {
- "partial_fetch": (r"^hermes update over the installer's partial clone failed: rc=1, .*"
- r"✗ Update failed: \[WinError 2\]",
- "gated on #124634: the pinned Git install.ps1 staged never reaches `hermes update`'s PATH"),
- "holders": (r"^`hermes update --list-venv-holders` did not report the live venv holders .*"
- r"\(rc=0, reported pids \[\]\)",
- "gated on #123050: --list-venv-holders reads the retired hermes_cli.main stub and always "
- "prints []"),
-}
VENV_HOLDERS_EXIT = 3
@@ -112,7 +103,10 @@ def test_update_fetches_into_the_installers_partial_clone(journey: Journey) -> N
"serve.git should allow filters")
fetch_bug = next((ln.strip() for ln in run.stdout.splitlines() if "BUG:" in ln or "fatal:" in ln),
failure_line(run))
- with known_gate(KNOWN, "partial_fetch"):
+ with known_failure(r"^hermes update over the installer's partial clone failed: rc=1, "
+ r".*✗ Update failed: \[WinError 2\]",
+ "gated on #124634: the pinned Git install.ps1 staged never reaches "
+ "`hermes update`'s PATH"):
assert run.returncode == 0 and m.installed_head() == m.next, fail_with(
m, f"hermes update over the installer's partial clone failed: rc={run.returncode}, checkout at "
f"{m.installed_head()} (NEXT {m.next}); {fetch_bug or 'no git error printed'}", run)
@@ -122,7 +116,10 @@ def test_list_venv_holders_reports_live_holders(journey: Journey) -> None:
m, pids, run = journey.machine, journey["holders"], journey["list_live"]
reported = _reported(run)
assert reported is not None, fail_with(m, "--list-venv-holders printed no JSON list", run)
- with known_gate(KNOWN, "holders"):
+ with known_failure(r"^`hermes update --list-venv-holders` did not report the live venv holders "
+ r".*\(rc=0, reported pids \[\]\)",
+ "gated on #123050: --list-venv-holders reads the retired hermes_cli.main stub "
+ "and always prints []"):
assert run.returncode == VENV_HOLDERS_EXIT and set(pids) <= set(reported), fail_with(
m, f"`hermes update --list-venv-holders` did not report the live venv holders {pids} "
f"(rc={run.returncode}, reported pids {reported})", run)
diff --git a/tests/e2e/core/windows_update/test_interpreter.py b/tests/e2e/core/windows_update/test_interpreter.py
index 9bb40b66a48..baa2945ac55 100644
--- a/tests/e2e/core/windows_update/test_interpreter.py
+++ b/tests/e2e/core/windows_update/test_interpreter.py
@@ -23,7 +23,6 @@ from pathlib import Path
import psutil
import pytest
-from tests.e2e.core._pending_fixes import known_gate
from tests.e2e.core.windows_update._machine import (
REQUIRES_OPT_IN,
Journey,
@@ -37,9 +36,6 @@ from tests.fakes.fake_llm_provider import FakeLLMServer
pytestmark = [pytest.mark.platforms("windows"), pytest.mark.integration,
pytest.mark.live_system_guard_bypass, REQUIRES_OPT_IN]
-# Gates cover observed failures only. On main these cells pass: the gateway boots on the
-# managed Python and skips the stale venv (#123185, #123965 and #123972 do not reproduce).
-KNOWN: dict[str, tuple[str, str]] = {}
_WORKER_DEATH = re.compile(r"^.*Supervised task \S+ died.*$", re.M)
@@ -128,10 +124,9 @@ def _inspect(pid: int) -> dict:
def test_gateway_runs_on_managed_python(journey: Journey) -> None:
m, info = journey.machine, journey["gateway_proc"]
system_python = journey["system_python"]
- with known_gate(KNOWN, "path_python"):
- assert _under(info["exe"], m.hermes_home) and not _under(info["exe"], system_python), fail_with(
- m, f"the gateway runs on a Python outside the managed runtime: {info['exe']} "
- f"(PATH starts with {system_python}; managed runtime lives under {m.hermes_home})")
+ assert _under(info["exe"], m.hermes_home) and not _under(info["exe"], system_python), fail_with(
+ m, f"the gateway runs on a Python outside the managed runtime: {info['exe']} "
+ f"(PATH starts with {system_python}; managed runtime lives under {m.hermes_home})")
def test_gateway_does_not_load_stale_in_tree_venv(journey: Journey) -> None:
@@ -144,10 +139,9 @@ def test_gateway_does_not_load_stale_in_tree_venv(journey: Journey) -> None:
loaded = sorted(journey.results["loaded_by_gateway"])
log = m.hermes_home / "logs" / "gateway.log"
deaths = _WORKER_DEATH.findall(log.read_text(encoding="utf-8", errors="replace")) if log.is_file() else []
- with known_gate(KNOWN, "stale_venv"):
- assert not loaded and not published, fail_with(
- m, f"the gateway loaded the stale pre-PM in-tree venv {stale} (site dir added by pids "
- f"{loaded}, gateway pid {info['pid']}; published via {published or 'nothing'}; worker deaths: {deaths[:3]})")
+ assert not loaded and not published, fail_with(
+ m, f"the gateway loaded the stale pre-PM in-tree venv {stale} (site dir added by pids "
+ f"{loaded}, gateway pid {info['pid']}; published via {published or 'nothing'}; worker deaths: {deaths[:3]})")
assert not deaths, fail_with(m, f"gateway supervised workers died: {deaths[:5]}")
diff --git a/tests/e2e/core/windows_update/test_paths_and_acls.py b/tests/e2e/core/windows_update/test_paths_and_acls.py
index 55949cbd75b..6eca818fbe2 100644
--- a/tests/e2e/core/windows_update/test_paths_and_acls.py
+++ b/tests/e2e/core/windows_update/test_paths_and_acls.py
@@ -8,8 +8,9 @@ Failure class: paths and ACLs.
* After ``hermes update`` the managed toolchain under ``%LOCALAPPDATA%\\hermes\\tools``
must still be executable by a non-elevated process: a logon Scheduled Task or Startup
entry runs with a standard-user token even when the updating session was elevated
- (#122935). The runner session is elevated, so each tool is launched with a Basic User
- (SAFER_LEVELID_NORMALUSER) token, the same token ``runas /trustlevel:0x20000`` uses.
+ (#122935). The runner session is elevated, so each tool's DACL is checked (kernel
+ AccessCheck) against a Basic User (SAFER_LEVELID_NORMALUSER) token, the token
+ ``runas /trustlevel:0x20000`` uses.
"""
from __future__ import annotations
@@ -19,7 +20,6 @@ from pathlib import Path
import pytest
-from tests.e2e.core._pending_fixes import known_gate
from tests.e2e.core.windows_update._machine import (
REQUIRES_OPT_IN,
Journey,
@@ -33,93 +33,92 @@ pytestmark = [pytest.mark.platforms("windows"), pytest.mark.integration,
pytest.mark.live_system_guard_bypass, REQUIRES_OPT_IN]
PERSON = "Jörg Ñúñez" # the profile is "Jörg Ñúñez hermes-e2e-<id>"
-KNOWN = {
- "acl": (r"^managed tools are not executable by a non-elevated process after update: .*WinError 5",
- "gated on #122935: tools\\* keep a hardened DACL a standard-user token cannot execute"),
-}
_TOOL_NAMES = {"python.exe", "node.exe", "git.exe", "uv.exe", "rg.exe"}
-def run_as_standard_user(argv: list[str], timeout: float = 120.0) -> tuple[int | None, str]:
- """``(exit code, "")`` or ``(None, launch error)`` for ``argv`` under a Basic User token."""
+_FILE_READ_EXECUTE = 0x1200A9 # FILE_GENERIC_READ | FILE_GENERIC_EXECUTE
+
+
+def standard_user_access(paths: list[Path]) -> dict[Path, str]:
+ """``{path: ""}`` when a Basic User token may read+execute ``path``, else why not.
+
+ The kernel's own decision (AccessCheck) for the SAFER_LEVELID_NORMALUSER token that
+ ``runas /trustlevel:0x20000`` uses: what a logon-time task gets on a UAC machine.
+ """
import ctypes
from ctypes import wintypes
advapi32 = ctypes.WinDLL("advapi32", use_last_error=True)
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
- class STARTUPINFOW(ctypes.Structure):
- _fields_ = [("cb", wintypes.DWORD), ("lpReserved", wintypes.LPWSTR), ("lpDesktop", wintypes.LPWSTR),
- ("lpTitle", wintypes.LPWSTR), ("dwX", wintypes.DWORD), ("dwY", wintypes.DWORD),
- ("dwXSize", wintypes.DWORD), ("dwYSize", wintypes.DWORD), ("dwXCountChars", wintypes.DWORD),
- ("dwYCountChars", wintypes.DWORD), ("dwFillAttribute", wintypes.DWORD),
- ("dwFlags", wintypes.DWORD), ("wShowWindow", wintypes.WORD), ("cbReserved2", wintypes.WORD),
- ("lpReserved2", ctypes.c_void_p), ("hStdInput", wintypes.HANDLE),
- ("hStdOutput", wintypes.HANDLE), ("hStdError", wintypes.HANDLE)]
-
- class PROCESS_INFORMATION(ctypes.Structure):
- _fields_ = [("hProcess", wintypes.HANDLE), ("hThread", wintypes.HANDLE),
- ("dwProcessId", wintypes.DWORD), ("dwThreadId", wintypes.DWORD)]
+ class GENERIC_MAPPING(ctypes.Structure):
+ _fields_ = [("GenericRead", wintypes.DWORD), ("GenericWrite", wintypes.DWORD),
+ ("GenericExecute", wintypes.DWORD), ("GenericAll", wintypes.DWORD)]
+ handle = wintypes.HANDLE
advapi32.SaferCreateLevel.argtypes = [wintypes.DWORD, wintypes.DWORD, wintypes.DWORD,
- ctypes.POINTER(wintypes.HANDLE), ctypes.c_void_p]
- advapi32.SaferComputeTokenFromLevel.argtypes = [wintypes.HANDLE, wintypes.HANDLE,
- ctypes.POINTER(wintypes.HANDLE), wintypes.DWORD,
- ctypes.c_void_p]
- advapi32.SaferCloseLevel.argtypes = [wintypes.HANDLE]
- advapi32.CreateProcessAsUserW.argtypes = [
- wintypes.HANDLE, wintypes.LPCWSTR, wintypes.LPWSTR, ctypes.c_void_p, ctypes.c_void_p, wintypes.BOOL,
- wintypes.DWORD, ctypes.c_void_p, wintypes.LPCWSTR, ctypes.POINTER(STARTUPINFOW),
- ctypes.POINTER(PROCESS_INFORMATION)]
- kernel32.WaitForSingleObject.argtypes = [wintypes.HANDLE, wintypes.DWORD]
- kernel32.GetExitCodeProcess.argtypes = [wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD)]
- kernel32.TerminateProcess.argtypes = [wintypes.HANDLE, wintypes.UINT]
- kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
-
- level, token = wintypes.HANDLE(), wintypes.HANDLE()
+ ctypes.POINTER(handle), ctypes.c_void_p]
+ advapi32.SaferComputeTokenFromLevel.argtypes = [handle, handle, ctypes.POINTER(handle),
+ wintypes.DWORD, ctypes.c_void_p]
+ advapi32.SaferCloseLevel.argtypes = [handle]
+ advapi32.DuplicateToken.argtypes = [handle, ctypes.c_int, ctypes.POINTER(handle)]
+ advapi32.GetFileSecurityW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, ctypes.c_void_p,
+ wintypes.DWORD, ctypes.POINTER(wintypes.DWORD)]
+ advapi32.AccessCheck.argtypes = [ctypes.c_void_p, handle, wintypes.DWORD, ctypes.POINTER(GENERIC_MAPPING),
+ ctypes.c_void_p, ctypes.POINTER(wintypes.DWORD),
+ ctypes.POINTER(wintypes.DWORD), ctypes.POINTER(wintypes.BOOL)]
+ kernel32.CloseHandle.argtypes = [handle]
+
+ def check(ok: int, what: str) -> None:
+ if not ok:
+ err = ctypes.get_last_error()
+ raise OSError(err, f"{what}: WinError {err} {ctypes.FormatError(err).strip()}")
+
+ level, primary, imp = handle(), handle(), handle()
# SAFER_SCOPEID_USER=2, SAFER_LEVELID_NORMALUSER=0x20000, SAFER_LEVEL_OPEN=1
- if not advapi32.SaferCreateLevel(2, 0x20000, 1, ctypes.byref(level), None):
- raise OSError(ctypes.get_last_error(), "SaferCreateLevel failed")
+ check(advapi32.SaferCreateLevel(2, 0x20000, 1, ctypes.byref(level), None), "SaferCreateLevel")
try:
- if not advapi32.SaferComputeTokenFromLevel(level, None, ctypes.byref(token), 0, None):
- raise OSError(ctypes.get_last_error(), "SaferComputeTokenFromLevel failed")
+ check(advapi32.SaferComputeTokenFromLevel(level, None, ctypes.byref(primary), 0, None),
+ "SaferComputeTokenFromLevel")
finally:
advapi32.SaferCloseLevel(level)
- si, pi = STARTUPINFOW(), PROCESS_INFORMATION()
- si.cb = ctypes.sizeof(si)
- cmdline = ctypes.create_unicode_buffer(subprocess.list2cmdline(argv))
try:
- if not advapi32.CreateProcessAsUserW(token, argv[0], cmdline, None, None, False,
- 0x08000000, None, None, ctypes.byref(si), ctypes.byref(pi)):
- err = ctypes.get_last_error()
- return None, f"WinError {err}: {ctypes.FormatError(err).strip()}"
- try:
- if kernel32.WaitForSingleObject(pi.hProcess, int(timeout * 1000)) != 0:
- kernel32.TerminateProcess(pi.hProcess, 1)
- return None, f"timed out after {timeout}s"
- code = wintypes.DWORD()
- kernel32.GetExitCodeProcess(pi.hProcess, ctypes.byref(code))
- return int(code.value), ""
- finally:
- kernel32.CloseHandle(pi.hProcess)
- kernel32.CloseHandle(pi.hThread)
+ check(advapi32.DuplicateToken(primary, 2, ctypes.byref(imp)), "DuplicateToken") # SecurityImpersonation
+ mapping = GENERIC_MAPPING(0x120089, 0x120116, 0x1200A0, 0x1F01FF)
+ verdicts: dict[Path, str] = {}
+ for path in paths:
+ needed = wintypes.DWORD()
+ info = 0x1 | 0x2 | 0x4 # OWNER | GROUP | DACL
+ advapi32.GetFileSecurityW(str(path), info, None, 0, ctypes.byref(needed))
+ sd = ctypes.create_string_buffer(max(needed.value, 1))
+ try:
+ check(advapi32.GetFileSecurityW(str(path), info, sd, needed, ctypes.byref(needed)),
+ "GetFileSecurityW")
+ privs, privs_len = ctypes.create_string_buffer(1024), wintypes.DWORD(1024)
+ granted, status = wintypes.DWORD(), wintypes.BOOL()
+ check(advapi32.AccessCheck(sd, imp, _FILE_READ_EXECUTE, ctypes.byref(mapping), privs,
+ ctypes.byref(privs_len), ctypes.byref(granted), ctypes.byref(status)),
+ "AccessCheck")
+ verdicts[path] = "" if status.value else "access denied to a standard-user token"
+ except OSError as exc:
+ verdicts[path] = str(exc)
+ return verdicts
finally:
- kernel32.CloseHandle(token)
+ for h in (imp, primary):
+ if h:
+ kernel32.CloseHandle(h)
def _standard_user_token_is_really_restricted(scratch: Path) -> str:
- """Harness control: the Basic User token runs system binaries and is not an admin."""
- # A dir the restricted token may write: the machine root is Administrators-owned.
- box = scratch / "basic-user"
- box.mkdir(parents=True, exist_ok=True)
- subprocess.run(["icacls", str(box), "/grant", "*S-1-1-0:(OI)(CI)F"], capture_output=True, check=True, timeout=60)
- out = box / "whoami-groups.txt"
- code, err = run_as_standard_user(
- [r"C:\Windows\System32\cmd.exe", "/d", "/c", f'whoami /groups /fo csv > "{out}"'])
- assert code == 0, f"harness: cannot launch cmd.exe with a Basic User token (code={code}, {err})"
- admins = [ln for ln in out.read_text(encoding="mbcs", errors="replace").splitlines() if "S-1-5-32-544" in ln]
- assert not admins or all("Deny only" in ln or "deny only" in ln.lower() for ln in admins), (
- f"harness: the Basic User token still holds Administrators: {admins}")
+ """Harness control: the token reads System32 but not an Administrators+SYSTEM-only file."""
+ admin_only = scratch / "admin-only.txt"
+ admin_only.write_text("x", encoding="utf-8")
+ subprocess.run(["icacls", str(admin_only), "/inheritance:r", "/grant:r", "*S-1-5-32-544:F", "*S-1-5-18:F"],
+ capture_output=True, check=True, timeout=60)
+ cmd = Path(r"C:\Windows\System32\cmd.exe")
+ verdicts = standard_user_access([cmd, admin_only])
+ assert verdicts[cmd] == "", f"harness: the standard-user token cannot even run cmd.exe: {verdicts[cmd]}"
+ assert verdicts[admin_only], "harness: the standard-user token still reads an Administrators-only file"
return "ok"
@@ -131,8 +130,8 @@ def _managed_tools(hermes_home: Path) -> list[Path]:
return sorted(set(found))
-def _tool_runs(hermes_home: Path) -> list[tuple[Path, int | None, str]]:
- return [(exe, *run_as_standard_user([str(exe), "--version"])) for exe in _managed_tools(hermes_home)]
+def _tool_access(hermes_home: Path) -> dict[Path, str]:
+ return standard_user_access(_managed_tools(hermes_home))
@pytest.fixture(scope="module")
@@ -149,7 +148,7 @@ def journey(tmp_path_factory):
machine.advance()
j.step("update", machine.update)
j.step("control", lambda: _standard_user_token_is_really_restricted(machine.root))
- j.step("tool_runs", lambda: _tool_runs(machine.hermes_home))
+ j.step("tool_access", lambda: _tool_access(machine.hermes_home))
yield j
finally:
machine.teardown()
@@ -158,9 +157,8 @@ def journey(tmp_path_factory):
def test_install_from_non_ascii_profile_with_spaces(journey: Journey) -> None:
m, run = journey.machine, journey["install"]
first_error = next((ln.strip() for ln in run.stdout.splitlines() if "[X]" in ln or "✗" in ln), "<none>")
- with known_gate(KNOWN, "install"):
- assert run.returncode == 0, fail_with(
- m, f"install.ps1 failed for a profile path with non-ASCII characters and spaces: {first_error}", run)
+ assert run.returncode == 0, fail_with(
+ m, f"install.ps1 failed for a profile path with non-ASCII characters and spaces: {first_error}", run)
def test_hermes_works_and_updates_from_that_profile(journey: Journey) -> None:
@@ -177,12 +175,11 @@ def test_hermes_works_and_updates_from_that_profile(journey: Journey) -> None:
def test_managed_tools_stay_executable_for_standard_user(journey: Journey) -> None:
- m, runs = journey.machine, journey["tool_runs"]
+ m, verdicts = journey.machine, journey["tool_access"]
journey["control"]
journey["update"]
- assert any(exe.name.lower() == "python.exe" for exe, _, _ in runs), fail_with(
- m, f"no managed python.exe under {m.hermes_home / 'tools'}: {[str(e) for e, _, _ in runs]}")
- broken = [f"{exe.relative_to(m.hermes_home)}: {err or f'exit {code}'}" for exe, code, err in runs if code != 0]
- with known_gate(KNOWN, "acl"):
- assert not broken, fail_with(
- m, f"managed tools are not executable by a non-elevated process after update: {'; '.join(broken)}")
+ assert any(exe.name.lower() == "python.exe" for exe in verdicts), fail_with(
+ m, f"no managed python.exe under {m.hermes_home / 'tools'}: {[str(e) for e in verdicts]}")
+ broken = [f"{exe.relative_to(m.hermes_home)}: {why}" for exe, why in verdicts.items() if why]
+ assert not broken, fail_with(
+ m, f"managed tools are not executable by a non-elevated process after update: {'; '.join(broken)}")