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.
330 lines
13 KiB
Python
330 lines
13 KiB
Python
"""Windows Update: the search, the pending list read from it, and the history (netork#2892).
|
|
|
|
A fake transport answers each script from tests/fixtures/synthetic/wu_*.json, the JSON
|
|
the scripts are written to emit. What a real host emits the fixtures cannot prove --
|
|
see the README there.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
import pytest
|
|
from napalm_device_types import PackageIndexMissing
|
|
|
|
from napalm_windows import WindowsDriver
|
|
from napalm_windows import windows_update as mod
|
|
from napalm_windows.transport import PowerShellError
|
|
|
|
FIXTURES = Path(__file__).parent / "fixtures" / "synthetic"
|
|
|
|
CU = "Cumulative-Update-for-Microsoft-server-operating-system-version-21H2-for-x64-based-Systems"
|
|
DEFENDER = "Security-Intelligence-Update-for-Microsoft-Defender-Antivirus-Current-Channel-Broad"
|
|
DOTNET = (
|
|
"Cumulative-Update-for-.NET-Framework-3.5-4.8-and-4.8.1-for-Microsoft-server-operating-"
|
|
"system-version-21H2-for-x64"
|
|
)
|
|
MSRT = "Windows-Malicious-Software-Removal-Tool-x64"
|
|
|
|
|
|
def _fixture(name: str) -> Any:
|
|
return json.loads((FIXTURES / f"wu_{name}.json").read_text())
|
|
|
|
|
|
class FakeTransport:
|
|
"""Answers each Windows Update script with its canned output; records them all."""
|
|
|
|
def __init__(self, answers: dict[str, Any]):
|
|
self.answers = answers
|
|
self.sent: list[str] = []
|
|
self.is_open = True
|
|
|
|
def run(self, script: str) -> str:
|
|
self.sent.append(script)
|
|
answer = self.answers[script]
|
|
if isinstance(answer, Exception):
|
|
raise answer
|
|
return answer if isinstance(answer, str) else json.dumps(answer)
|
|
|
|
def close(self) -> None:
|
|
self.is_open = False
|
|
|
|
|
|
def _driver(**answers: Any) -> WindowsDriver:
|
|
scripts = {
|
|
"search": mod._PS_WU_SEARCH,
|
|
"pending": mod._PS_WU_PENDING,
|
|
"history": mod._PS_WU_HISTORY,
|
|
}
|
|
d = WindowsDriver("win01", "admin", "secret")
|
|
d._transport = FakeTransport({scripts[k]: v for k, v in answers.items()}) # type: ignore[assignment]
|
|
return d
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Names
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("title", "name"),
|
|
[
|
|
(
|
|
"2026-11 Cumulative Update for Microsoft server operating system version 21H2 "
|
|
"for x64-based Systems (KB5070000)",
|
|
CU,
|
|
),
|
|
(
|
|
"Security Intelligence Update for Microsoft Defender Antivirus - KB2267602 "
|
|
"(Version 1.441.120.0) - Current Channel (Broad)",
|
|
DEFENDER,
|
|
),
|
|
("Windows Malicious Software Removal Tool x64 - v5.141 (KB890830)", MSRT),
|
|
(
|
|
"2026-01 Cumulative Update for Windows 11, version 24H2 for x64-based Systems "
|
|
"(KB5050009) (26100.2894)",
|
|
"Cumulative-Update-for-Windows-11-version-24H2-for-x64-based-Systems",
|
|
),
|
|
(
|
|
"2026-11 Kumulatives Update für Microsoft Server Operating System, Version 21H2 "
|
|
"für x64-basierte Systeme (KB5070000)",
|
|
"Kumulatives-Update-fur-Microsoft-Server-Operating-System-Version-21H2-fur-"
|
|
"x64-basierte-Systeme",
|
|
),
|
|
],
|
|
)
|
|
def test_an_update_is_named_by_what_it_keeps_from_month_to_month(title: str, name: str) -> None:
|
|
"""Next month's cumulative update replaces this one under the same name, so the time
|
|
the host has been waiting for it is not reset each month: the date, the KB article
|
|
and the version are left out of the name."""
|
|
assert mod.update_name(title, ["5070000"], "8f5c0d55-3b0f-4ad0-9a3e-1a8a0d7f6e11") == name
|
|
assert mod.NAME.fullmatch(name)
|
|
|
|
|
|
def test_a_title_with_nothing_left_is_named_by_its_kb_then_by_its_id() -> None:
|
|
assert mod.update_name("(KB5070000)", ["5070000"], "x") == "KB5070000"
|
|
assert mod.update_name("", [], "8f5c0d55-3b0f") == "8f5c0d55-3b0f"
|
|
|
|
|
|
def test_a_long_title_is_cut_to_a_name_a_store_keeps() -> None:
|
|
name = mod.update_name("Update " * 80, [], "x")
|
|
assert len(name) <= mod.NAME_MAX
|
|
assert not name.endswith("-")
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Pending updates: read from the last search, never searching in the poll
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def _pending(**kw: Any) -> dict[str, dict[str, Any]]:
|
|
answers = {"pending": _fixture("pending"), **kw}
|
|
return {u["name"]: dict(u) for u in _driver(**answers).get_available_updates()}
|
|
|
|
|
|
def test_the_pending_list_is_the_last_search_without_what_was_installed_since() -> None:
|
|
"""The Defender update was installed an hour after the search; the cumulative update
|
|
has an install in the history, but from before the search -- it is offered again."""
|
|
pending = _pending()
|
|
assert sorted(pending) == sorted([CU, DOTNET, MSRT])
|
|
|
|
|
|
def test_a_pending_update_says_what_it_fixes() -> None:
|
|
cu = _pending()[CU]
|
|
assert cu == {
|
|
"name": CU,
|
|
"current_version": "",
|
|
"new_version": "KB5070000",
|
|
"origin": "Windows Update",
|
|
"security": True,
|
|
"title": (
|
|
"2026-11 Cumulative Update for Microsoft server operating system version 21H2 "
|
|
"for x64-based Systems (KB5070000)"
|
|
),
|
|
"advisories": ["KB5070000"],
|
|
"cves": ["CVE-2026-21001", "CVE-2026-21002", "CVE-2026-21003"],
|
|
"vendor_severity": "Critical",
|
|
}
|
|
|
|
|
|
def test_security_is_what_windows_classifies_so() -> None:
|
|
pending = _pending()
|
|
assert pending[DOTNET]["security"] is True
|
|
assert pending[DOTNET]["vendor_severity"] == "Important"
|
|
# The removal tool is an update rollup: known, and not a security update.
|
|
assert pending[MSRT]["security"] is False
|
|
assert pending[MSRT]["vendor_severity"] is None
|
|
assert pending[MSRT]["cves"] == []
|
|
|
|
|
|
def test_optional_updates_and_feature_upgrades_are_not_pending() -> None:
|
|
"""A preview Windows does not install by itself, and an in-place upgrade of the OS,
|
|
are no pending updates: this path installs neither."""
|
|
names = set(_pending())
|
|
assert not any("Preview" in n for n in names)
|
|
assert not any("upgrade" in n for n in names)
|
|
|
|
|
|
def test_definition_updates_count_as_security() -> None:
|
|
search = _fixture("search")
|
|
reading = {"search": json.dumps(search), "installed": [], "history_error": None}
|
|
assert _pending(pending=reading)[DEFENDER]["security"] is True
|
|
|
|
|
|
def test_updates_of_the_same_name_are_one_entry() -> None:
|
|
search = _fixture("search")
|
|
twin = dict(search["updates"][0], id="00000000-0000-4000-8000-000000000001")
|
|
twin.update(kb=["5070001"], cves=["CVE-2026-21009"], severity="Moderate")
|
|
search["updates"].append(twin)
|
|
reading = {"search": json.dumps(search), "installed": [], "history_error": None}
|
|
cu = _pending(pending=reading)[CU]
|
|
assert cu["new_version"] == "KB5070000 KB5070001"
|
|
assert cu["advisories"] == ["KB5070000", "KB5070001"]
|
|
assert cu["cves"] == ["CVE-2026-21001", "CVE-2026-21002", "CVE-2026-21003", "CVE-2026-21009"]
|
|
assert cu["vendor_severity"] == "Critical" # the higher of the two
|
|
|
|
|
|
def test_an_update_without_a_kb_shows_its_revision() -> None:
|
|
search = _fixture("search")
|
|
search["updates"][3]["kb"] = []
|
|
reading = {"search": json.dumps(search), "installed": [], "history_error": None}
|
|
assert _pending(pending=reading)[MSRT]["new_version"] == "rev 1"
|
|
|
|
|
|
def test_a_wsus_client_names_its_server() -> None:
|
|
search = dict(_fixture("search"), wsus="https://wsus.example.lan:8531")
|
|
reading = {"search": json.dumps(search), "installed": [], "history_error": None}
|
|
assert _pending(pending=reading)[CU]["origin"] == "WSUS https://wsus.example.lan:8531"
|
|
|
|
|
|
def test_no_search_yet_is_a_missing_index_that_a_refresh_cures() -> None:
|
|
with pytest.raises(PackageIndexMissing, match="refresh"):
|
|
_pending(pending={"search": None, "installed": [], "history_error": None})
|
|
|
|
|
|
def test_a_failed_history_read_keeps_the_search_as_it_was() -> None:
|
|
reading = dict(_fixture("pending"), installed=[], history_error="0x8024000C")
|
|
assert DEFENDER in _pending(pending=reading)
|
|
|
|
|
|
def test_a_reading_that_is_no_search_raises() -> None:
|
|
with pytest.raises(ValueError, match="Windows Update"):
|
|
_pending(pending={"search": "[1, 2]", "installed": [], "history_error": None})
|
|
|
|
|
|
def test_the_poll_does_not_search() -> None:
|
|
"""The search takes minutes: the poll reads what the refresh found."""
|
|
d = _driver(pending=_fixture("pending"))
|
|
d.get_available_updates()
|
|
assert d._transport.sent == [mod._PS_WU_PENDING] # type: ignore[union-attr]
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Refresh: the search itself
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_the_refresh_searches_and_says_what_it_found() -> None:
|
|
result = _driver(search=_fixture("search")).refresh_available_updates()
|
|
assert result["success"] is True
|
|
assert result["output"] == (
|
|
"Windows Update offers 4 updates, 3 of them for security, searched in 94 s."
|
|
)
|
|
|
|
|
|
def test_a_refresh_windows_refuses_is_a_failed_refresh() -> None:
|
|
d = _driver(search=PowerShellError("Exception from HRESULT: 0x8024402C"))
|
|
assert d.refresh_available_updates() == {
|
|
"success": False,
|
|
"output": "Exception from HRESULT: 0x8024402C",
|
|
}
|
|
|
|
|
|
def test_a_search_script_keeps_what_it_found_for_the_poll() -> None:
|
|
"""The search writes its reading where only administrators can write, and the poll's
|
|
script reads it there."""
|
|
assert "Set-ItemProperty" in mod._PS_WU_SEARCH
|
|
assert mod.STORE in mod._PS_WU_SEARCH and mod.STORE in mod._PS_WU_PENDING
|
|
assert mod.STORE.startswith("HKLM:\\SOFTWARE\\napalm-windows\\")
|
|
assert "Type='Software'" in mod._PS_WU_SEARCH # no drivers
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# History
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def _history(since: int | None = None, reading: Any = None) -> list[dict[str, Any]]:
|
|
d = _driver(history=_fixture("history") if reading is None else reading)
|
|
return [dict(t) for t in d.get_update_history(since)]
|
|
|
|
|
|
def test_each_history_entry_is_a_transaction_newest_first() -> None:
|
|
history = _history()
|
|
assert [t["start"] for t in history] == sorted((t["start"] for t in history), reverse=True)
|
|
first = history[0]
|
|
assert first == {
|
|
"id": "d2b5e0a8-6c3e-4c9b-8a55-0f6b5bb2a1c4:200:1:1795603600",
|
|
"start": 1795603600,
|
|
"end": 1795603600,
|
|
"packages": [
|
|
{
|
|
"name": DEFENDER,
|
|
"action": "install",
|
|
"old_version": None,
|
|
"new_version": "KB2267602",
|
|
"title": (
|
|
"Security Intelligence Update for Microsoft Defender Antivirus - KB2267602 "
|
|
"(Version 1.441.120.0) - Current Channel (Broad)"
|
|
),
|
|
}
|
|
],
|
|
"requested_by": "Windows Defender (77BDAF73-B396-481F-9042-AD358843EC24)",
|
|
"command": None,
|
|
"error": None,
|
|
}
|
|
|
|
|
|
def test_a_failed_install_names_its_error() -> None:
|
|
failed = next(t for t in _history() if t["requested_by"] == "napalm-windows")
|
|
assert failed["error"] == "failed (0x80240017)"
|
|
|
|
|
|
def test_an_uninstall_removes_its_kb() -> None:
|
|
removed = next(t for t in _history() if t["packages"][0]["action"] == "remove")
|
|
assert removed["packages"][0]["old_version"] == "KB5007651"
|
|
assert removed["packages"][0]["new_version"] is None
|
|
|
|
|
|
def test_an_install_still_running_has_no_end_and_an_unknown_requester() -> None:
|
|
running = _history()[-1]
|
|
assert running["end"] is None
|
|
assert running["requested_by"] is None
|
|
assert running["error"] is None
|
|
|
|
|
|
def test_the_history_since_a_moment() -> None:
|
|
assert [t["start"] for t in _history(since=1795590000)] == [1795603600, 1795590000]
|
|
|
|
|
|
def test_an_empty_history() -> None:
|
|
assert _history(reading="") == []
|
|
|
|
|
|
def test_other_results_are_named() -> None:
|
|
entry = dict(_fixture("history")[0], result=5, hresult=0)
|
|
assert _history(reading=[entry])[0]["error"] == "aborted"
|
|
entry = dict(entry, result=3, hresult=-2145124329)
|
|
assert _history(reading=[entry])[0]["error"] == "succeeded with errors (0x80240017)"
|
|
|
|
|
|
def test_one_name_is_unknown_security_when_one_of_its_updates_does_not_say() -> None:
|
|
search = _fixture("search")
|
|
twin = dict(search["updates"][3], id="00000000-0000-4000-8000-000000000002")
|
|
twin["classifications"] = []
|
|
search["updates"].append(twin)
|
|
reading = {"search": json.dumps(search), "installed": [], "history_error": None}
|
|
assert _pending(pending=reading)[MSRT]["security"] is None
|