fix(install): parse Windows Task Scheduler XML output (#3830)

## Description

Closes #3829.

Windows `schtasks /Query /XML` output can contain an XML encoding
declaration that does not match the returned stdout bytes. The installer
passed that output directly to `ElementTree.fromstring`, so
persistent-task installation failed after the tasks had been created and
rolled the deployment back.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [x] New tests added for new functionality

## Changes Made

- Add a focused Windows Task Scheduler XML parser that first preserves
valid byte-level XML parsing, then normalizes a mismatched encoding
declaration after decoding fallback output.
- Use the parser during task principal verification.
- Add a regression test reproducing UTF-16-declared XML returned as
UTF-8 bytes.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .` for changed files)
- [x] New tests added
- [x] Manual testing performed

### Test Output

```text
python -m pytest -q tests/test_install/test_supervisors.py
45 passed, 1 warning in 1.04s

uvx ruff check headroom/install/supervisors.py tests/test_install/test_supervisors.py
All checks passed!
```

## Real Behavior Proof

- Environment: Windows 11, Python 3.12.8, Headroom 0.39.1, German
PowerShell, user-scoped persistent-task deployment.
- Exact command / steps: ran `headroom install apply --preset
persistent-task --scope user --providers auto --port 8787` after
applying the parser fix; then ran `headroom install status` and
requested `http://127.0.0.1:8787/health`.
- Observed result: installation completed with exit code 0, deployment
status was `running` and `Healthy: yes`, and the health endpoint
returned HTTP 200. Windows still rejected logged-off S4U recovery and
Headroom correctly fell back to an interactive health task.
- Not tested: full repository test suite, non-Windows Task Scheduler
behavior, and a logged-off Windows recovery run.

## Runtime Rollout Safety

- Rollout-managed feature(s): None.
- Minimum rollout channel: N/A.
- Stable/default behavior changed: Only Windows Task Scheduler XML
verification becomes tolerant of the known encoding mismatch.
- Kill switch / disable path: N/A.
- Unsafe override required: No.
- Qualification impact: None.
- Rollback path: Revert this commit.

## 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] My changes generate no new warnings in the changed files
- [x] I have added tests that prove my fix is effective
- [x] New and existing focused tests pass locally
- [x] I did **not** edit `CHANGELOG.md`

## Additional Notes

This is related to #3418, #2453, and #2552, but addresses the separate
XML verification failure after task registration.
This commit is contained in:
Ralf Escher
2026-09-28 13:22:43 -05:00
committed by GitHub
parent d13e1966f8
commit c32a4f4131
2 changed files with 48 additions and 1 deletions
+17 -1
View File
@@ -337,6 +337,22 @@ def _windows_health_trigger() -> str:
)
def _parse_windows_task_xml(raw: bytes | str) -> ElementTree.Element:
"""Parse schtasks XML when its declaration does not match stdout bytes."""
if isinstance(raw, bytes):
try:
return ElementTree.fromstring(raw)
except ElementTree.ParseError:
raw = raw.decode(errors="replace")
normalized = re.sub(
r'<\?xml\s+version="1\.0"\s+encoding="[^"]+"\?>',
'<?xml version="1.0"?>',
raw,
count=1,
)
return ElementTree.fromstring(normalized)
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."""
@@ -364,7 +380,7 @@ def _register_windows_task(name: str, xml: str, *, expected_logon_type: str) ->
) from exc
try:
task = ElementTree.fromstring(query.stdout or "")
task = _parse_windows_task_xml(query.stdout or b"")
except ElementTree.ParseError as exc:
raise _WindowsTaskRegistrationError(
f"Could not parse registered Windows task {name!r}", task_created=True
+31
View File
@@ -12,6 +12,7 @@ from headroom.install.supervisors import (
_linux_service_unit,
_linux_task_spec,
_macos_launchd_plist,
_parse_windows_task_xml,
_register_windows_task,
_render_unix_runner,
_render_windows_runner,
@@ -94,6 +95,36 @@ def test_register_windows_task_verifies_queried_logon_type(monkeypatch) -> None:
assert calls[1] == ["schtasks", "/Query", "/TN", "headroom-default-health", "/XML"]
def test_register_windows_task_accepts_mismatched_xml_encoding(monkeypatch) -> None:
task_xml = (
b'<?xml version="1.0" encoding="UTF-16"?>'
b'<Task xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">'
b"<Principals><Principal><LogonType>S4U</LogonType></Principal></Principals>"
b"</Task>"
)
def fake_run(command: list[str], **kwargs):
if command[1] == "/Query":
return _LaunchctlResult(stdout=task_xml)
return _LaunchctlResult()
monkeypatch.setattr("headroom.install.supervisors.subprocess.run", fake_run)
_register_windows_task("headroom-default-health", "<Task />", expected_logon_type="S4U")
def test_parse_windows_task_xml_accepts_valid_bytes() -> None:
task = _parse_windows_task_xml(b"<Task><LogonType>S4U</LogonType></Task>")
assert task.find("LogonType").text == "S4U"
def test_parse_windows_task_xml_accepts_text() -> None:
task = _parse_windows_task_xml("<Task><LogonType>InteractiveToken</LogonType></Task>")
assert task.find("LogonType").text == "InteractiveToken"
def test_register_windows_task_rejects_logon_type_downgrade(monkeypatch) -> None:
def fake_run(command: list[str], **kwargs):
if command[1] == "/Query":