fix: fall back for non-admin Windows task installs (#3437)

## Latest branch refresh

Refreshed cleanly from upstream main to incorporate its Bash
classification fix, which addresses the two inherited failing Bash
tests. All 49 Bash/supervisor tests pass after the refresh. The tested
npm installer pin also addresses the Docker OpenClaw installation crash.
New-head CI is running.

## Description

Keep the current hidden S4U startup and health tasks as the preferred
user-scope behavior, preserving the no-console and logged-off recovery
semantics added for issue #2453, and leave LocalSystem/system-scope
registration unchanged. Extend the Windows task XML/registration path so
production code can request and verify an explicit principal logon type
by querying the registered task XML; a mismatch must not be presented as
full S4U persistence. Treat a user-scope S4U registration failure or
verified downgrade as a compatibility fallback: remove any partially
created preferred tasks, register only the repeating health task with
`TimeTrigger` and `InteractiveToken`, and emit a clear warning that
recovery is session-scoped and will not run while logged off.

On locked-down Windows hosts, user-scope persistent installs always
attempt to create a boot-triggered Task Scheduler job with an S4U
principal, and common corporate policies reject that registration
without elevation. Both `headroom deploy` and the Windows fallback from
`persistent-service` reach this same supervisor code, so the
registration error triggers the existing whole-deployment rollback and
leaves no persistent installation. The reporter verified that a time
trigger with an interactive token is registrable as a standard user,
while the thread notes that Windows may also silently downgrade a
requested S4U principal and make a task look healthy even though it only
runs while the user is logged on. There are no prior or competing PRs in
the supplied issue timeline.

Closes #3418

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- Keep the current hidden S4U startup and health tasks as the preferred
user-scope behavior, preserving the no-console and logged-off recovery
semantics added for issue #2453, and leave LocalSystem/system-scope
registration unchanged. Extend the Windows task XML/registration path so
production code can request and verify an explicit principal logon type
by querying the registered task XML; a mismatch must not be presented as
full S4U persistence. Treat a user-scope S4U registration failure or
verified downgrade as a compatibility fallback: remove any partially
created preferred tasks, register only the repeating health task with
`TimeTrigger` and `InteractiveToken`, and emit a clear warning that
recovery is session-scoped and will not run while logged off.

## Testing

- [ ] Unit tests pass (`pytest`)
  Not run in this workspace, so this is left for CI to confirm.
- [ ] Linting passes (`ruff check .`)
  Not run in this workspace, so this is left for CI to confirm.
- [ ] Type checking passes (`mypy headroom`)
  Not run in this workspace, so this is left for CI to confirm.
- [x] New tests added for new functionality
- [ ] Manual testing performed
Not verified: this needs a person on the named hardware or environment.
- Preferred path: a user-scope install whose two S4U registrations and
read-backs succeed records both startup and health tasks and emits no
degraded-mode warning. - Compatibility path: failure while creating
either preferred task removes any task already created, then registers
one health task whose XML contains `TimeTrigger`, `InteractiveToken`,
`LeastPrivilege`, and the existing five-minute repetition. - Silent
downgrade: a successful create whose queried XML reports
`InteractiveToken` instead of requested `S4U` is detected, cleaned up,
and reported through the same explicit session-scoped fallback warning.

### Test Output

```text

# Paste relevant command output or artifact links here

```

## Real Behavior Proof

Not applicable to this change.

## Runtime Rollout Safety

Not applicable to this change.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [ ] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [ ] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)
  Not run in this workspace, so this is left for CI to confirm.

## Screenshots (if applicable)



## Additional Notes

Nothing beyond what is described above.

---------

Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com>
Co-authored-by: Jerrett Davis <mxjerrett@gmail.com>
This commit is contained in:
Matt Van Horn
2026-09-23 21:02:31 -05:00
committed by GitHub
co-authored by Matt Van Horn Jerrett Davis
parent b2d9275328
commit b958509452
2 changed files with 497 additions and 36 deletions
+151 -32
View File
@@ -12,6 +12,7 @@ import tempfile
import time
from datetime import datetime
from pathlib import Path
from xml.etree import ElementTree
from xml.sax.saxutils import escape as _xml_escape
import click
@@ -254,25 +255,43 @@ def _windows_current_user() -> str:
return f"{domain}\\{user}" if domain else user
def _windows_task_xml(command: str, *, trigger_xml: str, scope: str) -> str:
"""Render Task Scheduler XML that runs ``command`` without a visible window.
class _WindowsTaskRegistrationError(RuntimeError):
"""Task registration or read-back verification failed."""
def __init__(self, message: str, *, task_created: bool = False) -> None:
super().__init__(message)
self.task_created = task_created
def _windows_task_xml(
command: str, *, trigger_xml: str, scope: str, logon_type: str | None = None
) -> str:
"""Render Task Scheduler XML for ``command`` and its requested principal.
User-scope tasks use an S4U principal ("run whether user is logged on or
not", no stored password) so each run happens in a non-interactive session
and never draws a console window (issue #2453). System-scope tasks keep the
LocalSystem service account, which already has no desktop.
and never draws a console window (issue #2453). Callers can explicitly use
InteractiveToken as a session-scoped compatibility mode for locked-down
user accounts.
System-scope tasks keep the LocalSystem service account, which already has
no desktop.
"""
if scope == "system":
if logon_type not in (None, "ServiceAccount"):
raise ValueError("System-scope Windows tasks must use ServiceAccount")
principal = (
" <UserId>S-1-5-18</UserId>\n"
" <LogonType>ServiceAccount</LogonType>\n"
" <RunLevel>HighestAvailable</RunLevel>"
)
else:
logon_type = logon_type or "S4U"
if logon_type not in ("S4U", "InteractiveToken"):
raise ValueError(f"Unsupported user-scope Windows task logon type: {logon_type}")
principal = (
f" <UserId>{_xml_escape(_windows_current_user())}</UserId>\n"
" <LogonType>S4U</LogonType>\n"
f" <LogonType>{logon_type}</LogonType>\n"
" <RunLevel>LeastPrivilege</RunLevel>"
)
return (
@@ -318,18 +337,51 @@ def _windows_health_trigger() -> str:
)
def _register_windows_task(name: str, xml: str) -> None:
"""Register ``xml`` as scheduled task ``name`` via ``schtasks /XML``."""
def _register_windows_task(name: str, xml: str, *, expected_logon_type: str) -> None:
"""Register a task and verify its principal from Task Scheduler's XML."""
# schtasks reads the XML from a file; UTF-16 matches the declared encoding.
tmp = tempfile.NamedTemporaryFile(mode="w", suffix=".xml", encoding="utf-16", delete=False)
try:
tmp.write(xml)
tmp.close()
subprocess.run(
["schtasks", "/Create", "/TN", name, "/XML", tmp.name, "/F"],
check=True,
task_created = False
try:
subprocess.run(
["schtasks", "/Create", "/TN", name, "/XML", tmp.name, "/F"],
check=True,
)
task_created = True
query = subprocess.run(
["schtasks", "/Query", "/TN", name, "/XML"],
check=True,
capture_output=True,
)
except (OSError, subprocess.SubprocessError) as exc:
raise _WindowsTaskRegistrationError(
f"Could not register or verify Windows task {name!r}: {exc}",
task_created=task_created,
) from exc
try:
task = ElementTree.fromstring(query.stdout or "")
except ElementTree.ParseError as exc:
raise _WindowsTaskRegistrationError(
f"Could not parse registered Windows task {name!r}", task_created=True
) from exc
logon_element = task.find(".//{*}LogonType")
actual_logon_type = (
logon_element.text.strip()
if logon_element is not None and logon_element.text is not None
else None
)
if actual_logon_type != expected_logon_type:
raise _WindowsTaskRegistrationError(
f"Windows task {name!r} requested {expected_logon_type} logon type, "
f"but Task Scheduler registered {actual_logon_type or 'no logon type'}",
task_created=True,
)
finally:
try:
os.unlink(tmp.name)
@@ -337,6 +389,46 @@ def _register_windows_task(name: str, xml: str) -> None:
pass
def _delete_windows_task(name: str) -> subprocess.CompletedProcess[str] | None:
"""Best-effort removal of a scheduled task."""
try:
return run(
["schtasks", "/Delete", "/TN", name, "/F"],
capture_output=True,
text=True,
)
except OSError:
return None
def _cleanup_windows_tasks_for_fallback(names: list[str], *, must_delete: set[str]) -> None:
"""Remove preferred tasks and fail if Task Scheduler still reports one."""
for name in names:
deletion = _delete_windows_task(name)
if name in must_delete and (deletion is None or deletion.returncode != 0):
raise _WindowsTaskRegistrationError(
f"Could not clean up Windows task {name!r} before compatibility fallback"
)
try:
query = run(
["schtasks", "/Query", "/TN", name, "/XML"],
capture_output=True,
text=True,
)
except OSError as exc:
raise _WindowsTaskRegistrationError(
f"Could not verify cleanup of Windows task {name!r}: {exc}"
) from exc
if query.returncode == 0:
raise _WindowsTaskRegistrationError(
f"Could not clean up Windows task {name!r}; it remains registered"
)
def install_supervisor(manifest: DeploymentManifest) -> list[ArtifactRecord]:
"""Install service/task artifacts for the deployment."""
@@ -443,18 +535,53 @@ def install_supervisor(manifest: DeploymentManifest) -> list[ArtifactRecord]:
# Register from task XML (not schtasks flags) so the principal is S4U /
# hidden — flag-created tasks use an interactive token and flash a
# focus-stealing console on every run (issue #2453).
_register_windows_task(
startup_name,
_windows_task_xml(
startup_cmd, trigger_xml=_windows_boot_trigger(), scope=manifest.scope
),
)
_register_windows_task(
health_name,
_windows_task_xml(
startup_cmd, trigger_xml=_windows_health_trigger(), scope=manifest.scope
),
)
preferred_logon_type = "ServiceAccount" if manifest.scope == "system" else "S4U"
preferred_tasks = [
(startup_name, _windows_boot_trigger()),
(health_name, _windows_health_trigger()),
]
registered_preferred_tasks: list[str] = []
try:
for name, trigger_xml in preferred_tasks:
_register_windows_task(
name,
_windows_task_xml(
startup_cmd,
trigger_xml=trigger_xml,
scope=manifest.scope,
logon_type=preferred_logon_type,
),
expected_logon_type=preferred_logon_type,
)
registered_preferred_tasks.append(name)
except _WindowsTaskRegistrationError as exc:
if manifest.scope == "system":
raise
must_delete = set(registered_preferred_tasks)
if exc.task_created:
must_delete.add(name)
_cleanup_windows_tasks_for_fallback(
[name for name, _trigger_xml in preferred_tasks], must_delete=must_delete
)
_register_windows_task(
health_name,
_windows_task_xml(
startup_cmd,
trigger_xml=_windows_health_trigger(),
scope=manifest.scope,
logon_type="InteractiveToken",
),
expected_logon_type="InteractiveToken",
)
click.echo(
"Warning: Windows Task Scheduler rejected logged-off recovery; "
"using session-scoped health recovery. The health task runs every "
"five minutes while you are logged on and will not run while you are logged off."
)
records.append(ArtifactRecord(kind="windows-task", path=health_name))
return records
records.extend(
[
ArtifactRecord(kind="windows-task", path=startup_name),
@@ -632,13 +759,5 @@ def remove_supervisor(manifest: DeploymentManifest) -> None:
text=True,
)
return
run(
["schtasks", "/Delete", "/TN", f"{manifest.service_name}-startup", "/F"],
capture_output=True,
text=True,
)
run(
["schtasks", "/Delete", "/TN", f"{manifest.service_name}-health", "/F"],
capture_output=True,
text=True,
)
_delete_windows_task(f"{manifest.service_name}-startup")
_delete_windows_task(f"{manifest.service_name}-health")
+346 -4
View File
@@ -1,5 +1,6 @@
from __future__ import annotations
import subprocess
from pathlib import Path
import click
@@ -11,11 +12,13 @@ from headroom.install.supervisors import (
_linux_service_unit,
_linux_task_spec,
_macos_launchd_plist,
_register_windows_task,
_render_unix_runner,
_render_windows_runner,
_windows_boot_trigger,
_windows_health_trigger,
_windows_task_xml,
_WindowsTaskRegistrationError,
install_supervisor,
remove_supervisor,
render_runner_scripts,
@@ -38,6 +41,20 @@ def test_windows_task_xml_user_scope_is_hidden_s4u() -> None:
assert "<Command>C:\\tmp\\default\\ensure-headroom.cmd</Command>" in xml
def test_windows_task_xml_user_scope_supports_interactive_token() -> None:
xml = _windows_task_xml(
"C:\\tmp\\default\\ensure-headroom.cmd",
trigger_xml=_windows_health_trigger(),
scope="user",
logon_type="InteractiveToken",
)
assert "<TimeTrigger>" in xml
assert "<LogonType>InteractiveToken</LogonType>" in xml
assert "<RunLevel>LeastPrivilege</RunLevel>" in xml
assert "<Interval>PT5M</Interval>" in xml
def test_windows_task_xml_system_scope_uses_localsystem() -> None:
xml = _windows_task_xml(
"C:\\tmp\\default\\ensure-headroom.cmd",
@@ -49,6 +66,88 @@ def test_windows_task_xml_system_scope_uses_localsystem() -> None:
assert "<BootTrigger>" in xml
def test_register_windows_task_verifies_queried_logon_type(monkeypatch) -> None:
calls: list[list[str]] = []
def fake_run(command: list[str], **kwargs):
calls.append(command)
if command[1] == "/Query":
return _LaunchctlResult(
stdout=(
'<Task xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">'
"<Principals><Principal><LogonType>S4U</LogonType></Principal></Principals>"
"</Task>"
)
)
return _LaunchctlResult()
monkeypatch.setattr("headroom.install.supervisors.subprocess.run", fake_run)
_register_windows_task("headroom-default-health", "<Task />", expected_logon_type="S4U")
assert calls[0][:4] == [
"schtasks",
"/Create",
"/TN",
"headroom-default-health",
]
assert calls[1] == ["schtasks", "/Query", "/TN", "headroom-default-health", "/XML"]
def test_register_windows_task_rejects_logon_type_downgrade(monkeypatch) -> None:
def fake_run(command: list[str], **kwargs):
if command[1] == "/Query":
return _LaunchctlResult(
stdout=(
'<Task xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">'
"<Principals><Principal>"
"<LogonType>InteractiveToken</LogonType>"
"</Principal></Principals></Task>"
)
)
return _LaunchctlResult()
monkeypatch.setattr("headroom.install.supervisors.subprocess.run", fake_run)
with pytest.raises(
_WindowsTaskRegistrationError, match="requested S4U.*InteractiveToken"
) as exc_info:
_register_windows_task("headroom-default-health", "<Task />", expected_logon_type="S4U")
assert exc_info.value.task_created is True
@pytest.mark.parametrize("failed_action", ["/Create", "/Query"])
def test_register_windows_task_wraps_schtasks_failures(monkeypatch, failed_action: str) -> None:
calls: list[list[str]] = []
def fake_run(command: list[str], **kwargs):
calls.append(command)
if command[1] == failed_action:
raise subprocess.CalledProcessError(1, command)
return _LaunchctlResult()
monkeypatch.setattr("headroom.install.supervisors.subprocess.run", fake_run)
with pytest.raises(
_WindowsTaskRegistrationError, match="Could not register or verify"
) as exc_info:
_register_windows_task("headroom-default-health", "<Task />", expected_logon_type="S4U")
assert calls[-1][1] == failed_action
assert exc_info.value.task_created is (failed_action == "/Query")
def test_register_windows_task_rejects_malformed_queried_xml(monkeypatch) -> None:
monkeypatch.setattr(
"headroom.install.supervisors.subprocess.run",
lambda command, **kwargs: _LaunchctlResult(stdout="<Task>"),
)
with pytest.raises(_WindowsTaskRegistrationError, match="Could not parse registered"):
_register_windows_task("headroom-default-health", "<Task />", expected_logon_type="S4U")
def _manifest(
*,
profile: str = "default",
@@ -353,6 +452,239 @@ def test_install_supervisor_linux_service_and_tasks(monkeypatch, tmp_path: Path)
assert "@reboot ensure" in calls[-1][1]["input"]
def _stub_windows_task_install(monkeypatch, tmp_path: Path) -> None:
run_script = tmp_path / "run-headroom.cmd"
ensure_script = tmp_path / "ensure-headroom.cmd"
monkeypatch.setattr(
"headroom.install.supervisors.render_runner_scripts",
lambda manifest: [
type("Record", (), {"kind": "script", "path": str(run_script)})(),
type("Record", (), {"kind": "script", "path": str(ensure_script)})(),
],
)
monkeypatch.setattr("headroom.install.supervisors.sys.platform", "win32")
monkeypatch.setattr(
"headroom.install.supervisors.windows_ensure_cmd_path",
lambda profile: ensure_script,
)
def test_install_windows_user_tasks_prefers_verified_s4u(
monkeypatch, tmp_path: Path, capsys
) -> None:
_stub_windows_task_install(monkeypatch, tmp_path)
registrations: list[tuple[str, str, str]] = []
def fake_register(name: str, xml: str, *, expected_logon_type: str) -> None:
registrations.append((name, xml, expected_logon_type))
monkeypatch.setattr("headroom.install.supervisors._register_windows_task", fake_register)
records = install_supervisor(_manifest(supervisor=SupervisorKind.TASK.value))
assert [(name, logon_type) for name, _xml, logon_type in registrations] == [
("headroom-default-startup", "S4U"),
("headroom-default-health", "S4U"),
]
assert "<BootTrigger>" in registrations[0][1]
assert "<TimeTrigger>" in registrations[1][1]
assert [record.path for record in records if record.kind == "windows-task"] == [
"headroom-default-startup",
"headroom-default-health",
]
assert "session-scoped" not in capsys.readouterr().out
@pytest.mark.parametrize("failed_task", ["headroom-default-startup", "headroom-default-health"])
def test_install_windows_user_task_failure_cleans_up_and_falls_back(
monkeypatch, tmp_path: Path, capsys, failed_task: str
) -> None:
_stub_windows_task_install(monkeypatch, tmp_path)
registrations: list[tuple[str, str, str]] = []
deletions: list[str] = []
def fake_register(name: str, xml: str, *, expected_logon_type: str) -> None:
registrations.append((name, xml, expected_logon_type))
if name == failed_task and expected_logon_type == "S4U":
raise _WindowsTaskRegistrationError("registration denied")
monkeypatch.setattr("headroom.install.supervisors._register_windows_task", fake_register)
monkeypatch.setattr(
"headroom.install.supervisors._cleanup_windows_tasks_for_fallback",
lambda names, must_delete: deletions.extend(names),
)
records = install_supervisor(_manifest(supervisor=SupervisorKind.TASK.value))
assert deletions == ["headroom-default-startup", "headroom-default-health"]
fallback_name, fallback_xml, fallback_logon_type = registrations[-1]
assert fallback_name == "headroom-default-health"
assert fallback_logon_type == "InteractiveToken"
assert "<TimeTrigger>" in fallback_xml
assert "<LogonType>InteractiveToken</LogonType>" in fallback_xml
assert "<RunLevel>LeastPrivilege</RunLevel>" in fallback_xml
assert "<Interval>PT5M</Interval>" in fallback_xml
assert [record.path for record in records if record.kind == "windows-task"] == [
"headroom-default-health"
]
warning = capsys.readouterr().out
assert "session-scoped" in warning
assert "will not run while you are logged off" in warning
def test_install_windows_user_task_silent_downgrade_uses_fallback(
monkeypatch, tmp_path: Path, capsys
) -> None:
_stub_windows_task_install(monkeypatch, tmp_path)
registered_xml: dict[str, str] = {}
query_count = 0
calls: list[list[str]] = []
def fake_run(command: list[str], **kwargs):
nonlocal query_count
calls.append(command)
name = command[command.index("/TN") + 1]
if command[1] == "/Create":
registered_xml[name] = Path(command[command.index("/XML") + 1]).read_text(
encoding="utf-16"
)
return _LaunchctlResult()
if command[1] == "/Query":
if name not in registered_xml:
return _LaunchctlResult(
1, stderr="ERROR: The system cannot find the file specified."
)
query_count += 1
xml = registered_xml[name]
if query_count == 1:
xml = xml.replace(
"<LogonType>S4U</LogonType>", "<LogonType>InteractiveToken</LogonType>"
)
return _LaunchctlResult(stdout=xml)
registered_xml.pop(name, None)
return _LaunchctlResult()
monkeypatch.setattr("headroom.install.supervisors.subprocess.run", fake_run)
records = install_supervisor(_manifest(supervisor=SupervisorKind.TASK.value))
deletes = [call for call in calls if call[1] == "/Delete"]
assert [call[call.index("/TN") + 1] for call in deletes] == [
"headroom-default-startup",
"headroom-default-health",
]
assert "headroom-default-startup" not in registered_xml
assert "<LogonType>InteractiveToken</LogonType>" in registered_xml["headroom-default-health"]
assert [record.path for record in records if record.kind == "windows-task"] == [
"headroom-default-health"
]
assert "session-scoped" in capsys.readouterr().out
def test_install_windows_user_task_fallback_failure_propagates(
monkeypatch, tmp_path: Path, capsys
) -> None:
_stub_windows_task_install(monkeypatch, tmp_path)
def fake_register(name: str, xml: str, *, expected_logon_type: str) -> None:
raise _WindowsTaskRegistrationError(f"{expected_logon_type} registration denied")
monkeypatch.setattr("headroom.install.supervisors._register_windows_task", fake_register)
monkeypatch.setattr(
"headroom.install.supervisors._cleanup_windows_tasks_for_fallback",
lambda names, must_delete: None,
)
with pytest.raises(_WindowsTaskRegistrationError, match="InteractiveToken registration denied"):
install_supervisor(_manifest(supervisor=SupervisorKind.TASK.value))
assert "session-scoped" not in capsys.readouterr().out
@pytest.mark.parametrize(
("query_state", "error_match"),
[
("survives", "remains registered"),
("delete_denied", "Could not clean up"),
],
)
def test_install_windows_user_task_cleanup_failure_prevents_fallback(
monkeypatch, tmp_path: Path, capsys, query_state: str, error_match: str
) -> None:
_stub_windows_task_install(monkeypatch, tmp_path)
registrations: list[str] = []
def fake_register(name: str, xml: str, *, expected_logon_type: str) -> None:
registrations.append(expected_logon_type)
raise _WindowsTaskRegistrationError("S4U registration denied", task_created=True)
def fake_run(command: list[str], **kwargs):
if query_state == "survives" and command[1] in ("/Delete", "/Query"):
return _LaunchctlResult(stdout="<Task />")
return _LaunchctlResult(1, stderr="ERROR: Access is denied.")
monkeypatch.setattr("headroom.install.supervisors._register_windows_task", fake_register)
monkeypatch.setattr("headroom.install.supervisors.subprocess.run", fake_run)
with pytest.raises(_WindowsTaskRegistrationError, match=error_match):
install_supervisor(_manifest(supervisor=SupervisorKind.TASK.value))
assert registrations == ["S4U"]
assert "session-scoped" not in capsys.readouterr().out
def test_install_windows_system_tasks_use_verified_service_account(
monkeypatch, tmp_path: Path, capsys
) -> None:
_stub_windows_task_install(monkeypatch, tmp_path)
registrations: list[tuple[str, str, str]] = []
def fake_register(name: str, xml: str, *, expected_logon_type: str) -> None:
registrations.append((name, xml, expected_logon_type))
monkeypatch.setattr("headroom.install.supervisors._register_windows_task", fake_register)
records = install_supervisor(_manifest(scope="system", supervisor=SupervisorKind.TASK.value))
assert [(name, logon_type) for name, _xml, logon_type in registrations] == [
("headroom-default-startup", "ServiceAccount"),
("headroom-default-health", "ServiceAccount"),
]
assert "<BootTrigger>" in registrations[0][1]
assert "<TimeTrigger>" in registrations[1][1]
assert all(
"<LogonType>ServiceAccount</LogonType>" in xml for _name, xml, _type in registrations
)
assert all("<UserId>S-1-5-18</UserId>" in xml for _name, xml, _type in registrations)
assert all(
"<RunLevel>HighestAvailable</RunLevel>" in xml for _name, xml, _type in registrations
)
assert [record.path for record in records if record.kind == "windows-task"] == [
"headroom-default-startup",
"headroom-default-health",
]
assert "session-scoped" not in capsys.readouterr().out
def test_install_windows_system_task_failure_does_not_fall_back(
monkeypatch, tmp_path: Path, capsys
) -> None:
_stub_windows_task_install(monkeypatch, tmp_path)
registrations: list[tuple[str, str]] = []
def fake_register(name: str, xml: str, *, expected_logon_type: str) -> None:
registrations.append((name, expected_logon_type))
raise _WindowsTaskRegistrationError("system registration denied")
monkeypatch.setattr("headroom.install.supervisors._register_windows_task", fake_register)
with pytest.raises(_WindowsTaskRegistrationError, match="system registration denied"):
install_supervisor(_manifest(scope="system", supervisor=SupervisorKind.TASK.value))
assert registrations == [("headroom-default-startup", "ServiceAccount")]
assert "session-scoped" not in capsys.readouterr().out
def test_install_supervisor_darwin_windows_and_unsupported(monkeypatch, tmp_path: Path) -> None:
run_script = tmp_path / "run-headroom.sh"
ensure_script = tmp_path / "ensure-headroom.sh"
@@ -364,10 +696,20 @@ def test_install_supervisor_darwin_windows_and_unsupported(monkeypatch, tmp_path
],
)
calls: list[list[str]] = []
monkeypatch.setattr(
"headroom.install.supervisors.subprocess.run",
lambda command, **kwargs: calls.append(command) or _LaunchctlResult(0),
)
def fake_run(command, **kwargs):
calls.append(command)
if isinstance(command, list) and len(command) > 1 and command[1] == "/Query":
return _LaunchctlResult(
stdout=(
'<Task xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">'
"<Principals><Principal><LogonType>S4U</LogonType></Principal></Principals>"
"</Task>"
)
)
return _LaunchctlResult(0)
monkeypatch.setattr("headroom.install.supervisors.subprocess.run", fake_run)
monkeypatch.setattr("headroom.install.supervisors.os.getuid", lambda: 123, raising=False)
plist_path = tmp_path / "com.headroom.default.plist"