refresh_available_updates runs the Windows Update Agent's search against the configured source and keeps its reading under HKLM\SOFTWARE\napalm-windows; get_available_updates reads it back without a search, leaving out what the history shows installed since, and raises PackageIndexMissing before the first search. Each update carries its title, KB articles, CveIDs and MsrcSeverity, and is named by its title without month, KB and version, so next month's cumulative update keeps the name. Previews, feature upgrades and drivers are left out. apply_updates installs in a one-shot task running as SYSTEM, since Windows refuses downloads and installs to a network logon. The task's script and the exact UpdateID:revision chosen travel in the run's registry key; it searches again, refuses what no longer matches exactly, what asks for input or has unaccepted licence terms, installs nothing while a restart is pending and never restarts. Its log is followed line by line; the next run sweeps what a dead run left. get_scheduled_jobs shows these tasks as an application's. get_update_history reads QueryHistory, one transaction per entry, with the ClientApplicationID as requested_by.
272 lines
10 KiB
Python
272 lines
10 KiB
Python
"""Installing Windows updates in a one-shot SYSTEM task (netork#2892).
|
|
|
|
The transport is faked: each script the run sends is recognised by what it does and
|
|
answered as the host would. The SYSTEM script itself is read here as text; what Windows
|
|
Update does with it only a real host can show.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
import pytest
|
|
|
|
from napalm_windows import WindowsDriver
|
|
from napalm_windows import windows_update as wu
|
|
from napalm_windows import windows_update_run as mod
|
|
from napalm_windows.transport import PowerShellError
|
|
|
|
FIXTURES = Path(__file__).parent / "fixtures" / "synthetic"
|
|
|
|
CU_ID = "8f5c0d55-3b0f-4ad0-9a3e-1a8a0d7f6e11:1"
|
|
DOTNET_ID = "1c7f9e2a-5b4d-4e0f-9d8c-3a2b1c0d9e8f:3"
|
|
MSRT_ID = "6a0d3c1e-9f8b-4d7a-8e6c-5b4a3f2e1d0c:1"
|
|
CU = "Cumulative-Update-for-Microsoft-server-operating-system-version-21H2-for-x64-based-Systems"
|
|
MSRT = "Windows-Malicious-Software-Removal-Tool-x64"
|
|
|
|
|
|
class Host:
|
|
"""The host's side of a run: what the sweep finds, and what each look shows."""
|
|
|
|
def __init__(
|
|
self,
|
|
looks: list[dict[str, Any]] | None = None,
|
|
busy: list[str] | None = None,
|
|
start_fails: str | None = None,
|
|
):
|
|
self.looks = list(looks or [])
|
|
self.busy = busy or []
|
|
self.start_fails = start_fails
|
|
self.sent: list[str] = []
|
|
self.is_open = True
|
|
|
|
def kind(self, script: str) -> str:
|
|
if script == wu._PS_WU_PENDING:
|
|
return "pending"
|
|
if "busy" in script and "Unregister-ScheduledTask" in script:
|
|
return "sweep"
|
|
if "Register-ScheduledTask" in script:
|
|
return "start"
|
|
if "$state = 'gone'" in script:
|
|
return "follow"
|
|
if "Remove-Item -LiteralPath $key" in script:
|
|
return "cleanup"
|
|
raise AssertionError(f"unexpected script: {script[:80]}")
|
|
|
|
def run(self, script: str) -> str:
|
|
kind = self.kind(script)
|
|
self.sent.append(kind)
|
|
if kind == "pending":
|
|
return (FIXTURES / "wu_pending.json").read_text()
|
|
if kind == "sweep":
|
|
return json.dumps({"busy": self.busy, "swept": ["update-run-0123456789ab"]})
|
|
if kind == "start":
|
|
self.start_script = script
|
|
if self.start_fails:
|
|
raise PowerShellError(self.start_fails)
|
|
return ""
|
|
if kind == "follow":
|
|
return json.dumps(self.looks.pop(0))
|
|
return ""
|
|
|
|
def close(self) -> None:
|
|
self.is_open = False
|
|
|
|
|
|
def _look(state: str, log: list[str], result: dict[str, Any] | None = None) -> dict[str, Any]:
|
|
return {"state": state, "log": "\n".join(log), "result": json.dumps(result) if result else ""}
|
|
|
|
|
|
def _result(**kw: Any) -> dict[str, Any]:
|
|
return {
|
|
"reboot_required": False,
|
|
"installed": [],
|
|
"refused": [],
|
|
"failed": [],
|
|
"error": None,
|
|
**kw,
|
|
}
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def no_waiting(monkeypatch: pytest.MonkeyPatch) -> list[float]:
|
|
slept: list[float] = []
|
|
monkeypatch.setattr(mod.time, "sleep", slept.append)
|
|
return slept
|
|
|
|
|
|
def _driver(host: Host) -> WindowsDriver:
|
|
d = WindowsDriver("win01", "admin", "secret")
|
|
d._transport = host # type: ignore[assignment]
|
|
return d
|
|
|
|
|
|
def test_a_run_installs_in_a_system_task_and_hands_on_each_line() -> None:
|
|
host = Host(
|
|
[
|
|
_look("Running", ["Searching Windows Update again for the chosen updates"]),
|
|
_look(
|
|
"Ready",
|
|
[
|
|
"Searching Windows Update again for the chosen updates",
|
|
"Downloading 1 update(s)",
|
|
"Installing 1 update(s); the host is not restarted",
|
|
"Installed: 2026-11 Cumulative Update ... (KB5070000) (" + CU_ID + ")",
|
|
"A restart finishes the installation.",
|
|
],
|
|
_result(installed=[CU_ID], reboot_required=True),
|
|
),
|
|
]
|
|
)
|
|
seen: list[str] = []
|
|
result = _driver(host).apply_updates([CU], log=seen.append)
|
|
|
|
assert result["success"] is True
|
|
assert "error" not in result
|
|
assert host.sent == ["pending", "sweep", "start", "follow", "follow", "cleanup"]
|
|
assert seen[0].startswith("Chosen: 2026-11 Cumulative Update")
|
|
assert seen[1:] == [
|
|
"Searching Windows Update again for the chosen updates",
|
|
"Downloading 1 update(s)",
|
|
"Installing 1 update(s); the host is not restarted",
|
|
"Installed: 2026-11 Cumulative Update ... (KB5070000) (" + CU_ID + ")",
|
|
"A restart finishes the installation.",
|
|
]
|
|
assert result["output"] == "\n".join(seen)
|
|
|
|
|
|
def test_the_task_gets_exactly_the_updates_chosen_and_runs_as_system() -> None:
|
|
host = Host([_look("Ready", [], _result(installed=[CU_ID]))])
|
|
_driver(host).apply_updates([CU])
|
|
start = host.start_script
|
|
assert f"@('{CU_ID}')" in start
|
|
assert DOTNET_ID not in start
|
|
assert "-UserId 'SYSTEM'" in start and "-RunLevel Highest" in start
|
|
assert "Register-ScheduledTask -TaskPath '\\napalm-windows\\'" in start
|
|
# The script travels in the run's registry key, never as a file.
|
|
assert "-Name Script" in start and ".ps1" not in start
|
|
|
|
|
|
def test_every_pending_update_when_none_is_named() -> None:
|
|
host = Host([_look("Ready", [], _result(installed=[CU_ID, DOTNET_ID, MSRT_ID]))])
|
|
assert _driver(host).apply_updates([])["success"] is True
|
|
for identity in (CU_ID, DOTNET_ID, MSRT_ID):
|
|
assert f"'{identity}'" in host.start_script
|
|
|
|
|
|
def test_a_name_the_last_search_does_not_offer_is_refused_and_the_rest_installed() -> None:
|
|
host = Host([_look("Ready", ["Installed: x"], _result(installed=[MSRT_ID]))])
|
|
seen: list[str] = []
|
|
result = _driver(host).apply_updates([MSRT, "Gone-Update"], log=seen.append)
|
|
assert seen[0] == "Refused Gone-Update: not offered by the last search"
|
|
assert result["success"] is False
|
|
assert result["error"] == "1 update(s) refused, 0 failed."
|
|
|
|
|
|
def test_only_names_the_search_does_not_offer_start_nothing() -> None:
|
|
host = Host()
|
|
result = _driver(host).apply_updates(["Gone-Update"])
|
|
assert result["success"] is False
|
|
assert host.sent == ["pending"]
|
|
|
|
|
|
def test_nothing_pending_is_nothing_to_install() -> None:
|
|
result = mod.install(lambda s: "", {}, [], None)
|
|
assert result == {"success": True, "output": "Nothing to install."}
|
|
|
|
|
|
def test_a_name_that_is_no_package_name_is_refused_before_anything_runs() -> None:
|
|
host = Host()
|
|
with pytest.raises(ValueError, match="Invalid update name"):
|
|
_driver(host).apply_updates(["KB1; Restart-Computer"])
|
|
assert host.sent == []
|
|
|
|
|
|
def test_what_the_task_refused_or_failed_makes_the_run_fail() -> None:
|
|
refused = {"id": CU_ID, "reason": "it asks for input while it installs"}
|
|
failed = {"id": DOTNET_ID, "step": "Install", "result": 4, "hresult": -2145124329}
|
|
host = Host([_look("Ready", [], _result(refused=[refused], failed=[failed]))])
|
|
result = _driver(host).apply_updates([])
|
|
assert result["success"] is False
|
|
assert result["error"] == "1 update(s) refused, 1 failed."
|
|
|
|
|
|
def test_a_pending_restart_installs_nothing_and_says_so() -> None:
|
|
error = "A restart is pending on the host: nothing is installed until it has restarted."
|
|
host = Host([_look("Ready", [error], _result(error=error))])
|
|
result = _driver(host).apply_updates([CU])
|
|
assert result["success"] is False
|
|
assert result["error"] == error
|
|
|
|
|
|
def test_a_task_that_ends_without_a_result_failed_and_is_cleaned_up() -> None:
|
|
host = Host([_look("Ready", ["Downloading 1 update(s)"])])
|
|
result = _driver(host).apply_updates([CU])
|
|
assert result["success"] is False
|
|
assert result["error"] == "The update task ended without a result."
|
|
assert host.sent[-1] == "cleanup"
|
|
|
|
|
|
def test_an_earlier_run_still_installing_refuses_this_one() -> None:
|
|
host = Host(busy=["update-run-0123456789ab"])
|
|
result = _driver(host).apply_updates([CU])
|
|
assert result["success"] is False
|
|
assert "still installing" in result["error"]
|
|
assert host.sent == ["pending", "sweep"]
|
|
|
|
|
|
def test_a_run_followed_too_long_is_left_to_finish_on_the_host(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
clock = iter([0.0, 10.0, mod.FOLLOW_SECONDS + 1.0])
|
|
monkeypatch.setattr(mod.time, "monotonic", lambda: next(clock))
|
|
host = Host([_look("Running", ["Downloading 1 update(s)"]), _look("Running", [])])
|
|
result = _driver(host).apply_updates([CU])
|
|
assert result["success"] is False
|
|
assert "carries on there" in result["error"]
|
|
assert "cleanup" not in host.sent # the next run's sweep deletes it once it ended
|
|
|
|
|
|
def test_a_task_windows_refuses_to_register_raises() -> None:
|
|
host = Host(start_fails="Access is denied.")
|
|
with pytest.raises(PowerShellError, match="Access is denied"):
|
|
_driver(host).apply_updates([CU])
|
|
|
|
|
|
def test_the_follower_waits_between_looks(no_waiting: list[float]) -> None:
|
|
host = Host([_look("Running", []), _look("Ready", [], _result(installed=[CU_ID]))])
|
|
_driver(host).apply_updates([CU])
|
|
assert no_waiting == [mod.POLL_SECONDS, mod.POLL_SECONDS]
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# The SYSTEM script, read as text
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_the_system_script_guards_what_it_installs() -> None:
|
|
script = mod.run_script("0123456789ab")
|
|
assert "HKLM:\\SOFTWARE\\napalm-windows\\WindowsUpdate\\Runs\\0123456789ab" in script
|
|
# A pending restart refuses everything before any download.
|
|
assert script.index("$pending -or $installer.RebootRequiredBeforeInstallation") < (
|
|
script.index("CreateUpdateDownloader")
|
|
)
|
|
# Exactly the ID and revision, offered once, quiet, licence accepted on the host.
|
|
assert "no longer offered" in script
|
|
assert "offered more than once" in script
|
|
assert "CanRequestUserInput" in script
|
|
assert "EulaAccepted" in script
|
|
assert "AcceptEula" not in script
|
|
# Never restarts, and Windows Update's history names the run.
|
|
assert "Restart-Computer" not in script and "shutdown" not in script.lower()
|
|
assert "ClientApplicationID = 'napalm-windows'" in script
|
|
|
|
|
|
def test_the_scripts_quote_what_they_are_given() -> None:
|
|
start = mod._script(mod._PS_START, RUN="'x'", TASK="'t'", REQUESTED="'a'", SCRIPT="'s'")
|
|
assert "__" not in start
|
|
for template in (mod._PS_SWEEP, mod._PS_FOLLOW, mod._PS_CLEANUP):
|
|
assert "__" not in mod._script(template, RUN="'x'", TASK="'t'")
|