From b9b629781528322a139233a7382bd7e7fc87feae Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Sat, 28 Nov 2026 04:23:17 +0100 Subject: [PATCH] feat(kernel): the live patches the running kernel carries, with the kernel facts (NetOrk/netork#2701) /sys/kernel/livepatch with each patch's enabled and transition, kpatch list, and Canonical Livepatch's status for the running kernel with the CVEs it names. status reads the daemon's last state; refresh is never run. Where the client is installed and its status needs root, a driver that supplies _run_livepatch_status_command reads it again as root. --- README.md | 7 + napalm_device_types/__init__.py | 18 +- napalm_device_types/kernel.py | 49 ++++- napalm_device_types/livepatch.py | 201 +++++++++++++++++++ napalm_device_types/models.py | 3 + tests/test_live_patches.py | 321 +++++++++++++++++++++++++++++++ 6 files changed, 597 insertions(+), 2 deletions(-) create mode 100644 napalm_device_types/livepatch.py create mode 100644 tests/test_live_patches.py diff --git a/README.md b/README.md index e934ff0..5bc22e1 100644 --- a/README.md +++ b/README.md @@ -159,6 +159,13 @@ rather than by a role base: what a Linux kernel has built and loaded is read the everywhere, so the command and its parse are concrete here and a driver supplies only `_run_kernel_facts_command`. `OSDriver` does not carry it — a Windows host is an OS driver too, and `hasattr(driver, "get_kernel_facts")` has to stay truthful. +The kernel facts carry the kernel's live patches too (`live_patches`, from +`napalm_device_types.livepatch`): the patches loaded in `/sys/kernel/livepatch` with whether +each is enabled, `kpatch list`, and Canonical Livepatch's status for the running kernel with +the CVEs it fixes (`canonical-livepatch status --format json`, the daemon's last state; never +`refresh`). Where Canonical's client is installed and its status does not read without root, a +driver that can gain root supplies `_run_livepatch_status_command` and the mixin reads +`LIVEPATCH_STATUS_COMMAND` again through it. `HardeningMixin` (`get_hardening`) is mixed in the same way: how the host is hardened, as its kernel and its own tools say it, in one read-only command. The active security modules diff --git a/napalm_device_types/__init__.py b/napalm_device_types/__init__.py index 623f967..808f7d7 100644 --- a/napalm_device_types/__init__.py +++ b/napalm_device_types/__init__.py @@ -192,7 +192,12 @@ from napalm_device_types.host_shutdown import HostShutdownMixin from napalm_device_types.host_status import HOST_STATUS_COMMAND, HostStatusMixin, parse_host_status from napalm_device_types.hypervisor import HypervisorDriver from napalm_device_types.interface_filter import InterfaceFilterMixin -from napalm_device_types.kernel import KERNEL_FACTS_COMMAND, KernelFactsMixin, parse_kernel_facts +from napalm_device_types.kernel import ( + KERNEL_FACTS_COMMAND, + LIVEPATCH_STATUS_COMMAND, + KernelFactsMixin, + parse_kernel_facts, +) from napalm_device_types.lag import add_lag_interfaces from napalm_device_types.licenses import LicenseMixin from napalm_device_types.listening import ( @@ -201,6 +206,12 @@ from napalm_device_types.listening import ( ListeningSocketsUnavailable, parse_listening_sockets, ) +from napalm_device_types.livepatch import ( + CanonicalLivepatchDict, + LivePatchesDict, + canonical_release, + parse_canonical_status, +) from napalm_device_types.lldp import ( LldpNeighborDict, LldpNeighborRow, @@ -573,6 +584,11 @@ __all__ = [ "KernelFactsMixin", "KERNEL_FACTS_COMMAND", "parse_kernel_facts", + "LIVEPATCH_STATUS_COMMAND", + "CanonicalLivepatchDict", + "LivePatchesDict", + "canonical_release", + "parse_canonical_status", "HARDENING_COMMAND", "HardeningMixin", "HardeningDict", diff --git a/napalm_device_types/kernel.py b/napalm_device_types/kernel.py index 629ddab..1487bf3 100644 --- a/napalm_device_types/kernel.py +++ b/napalm_device_types/kernel.py @@ -16,6 +16,13 @@ What the four lists mean for a module, and why "not loaded" alone is never "absent": a module that is not loaded can still be loaded on demand -- by an attacker too, where autoloading reaches it. Only a module that is neither loaded, nor compiled in, nor shipped for this kernel is one it cannot have. + +**The live patches** the kernel carries come with it (NetOrk/netork#2701, +:mod:`napalm_device_types.livepatch`): the patches loaded in ``/sys/kernel/livepatch``, +``kpatch list``, and Canonical Livepatch's status with the CVEs it fixes. That status +may need root: where the client is installed and its status did not read without, a +driver that supplies ``_run_livepatch_status_command`` reads it again as root, one +fixed, read-only command (:data:`LIVEPATCH_STATUS_COMMAND`). """ from __future__ import annotations @@ -26,6 +33,7 @@ import gzip import zlib from typing import TYPE_CHECKING +from napalm_device_types.livepatch import live_patches, parse_canonical_status from napalm_device_types.models import KernelFactsDict _BEGIN = "KFACTS_BEGIN" @@ -43,11 +51,23 @@ KERNEL_FACTS_COMMAND = ( "if [ -r /boot/config-$r ]; then echo '[config]'; grep '^CONFIG_' /boot/config-$r; " "elif [ -r /proc/config.gz ]; then echo '[config]'; " "zcat /proc/config.gz | grep '^CONFIG_'; fi; " + "if [ -d /sys/kernel/livepatch ]; then echo '[livepatch]'; " + 'for p in /sys/kernel/livepatch/*; do [ -d "$p" ] && ' + 'echo "${p##*/} $(cat "$p/enabled") $(cat "$p/transition")"; done; fi; ' + "if command -v kpatch >/dev/null; then echo '[kpatch]'; kpatch list; fi; " + "c=$(command -v canonical-livepatch || ls /snap/bin/canonical-livepatch); " + "if [ -n \"$c\" ]; then echo '[canonical_livepatch]'; " + "\"$c\" status --format json | tr -d '\\n'; echo; fi; " "} 2>/dev/null | gzip -c | base64; " "printf '%s%s\\n' KFACTS_ END" ) +#: Canonical Livepatch's status, as root: the client lives in ``/snap/bin``, outside the +#: ``PATH`` sudo keeps. Read-only: ``status`` reads what the daemon holds. +LIVEPATCH_STATUS_COMMAND = "/snap/bin/canonical-livepatch status --format json" + + def module_name(raw: str) -> str: """A module as the kernel names it: no path, no ``.ko`` suffix, ``_`` for ``-``. @@ -124,6 +144,7 @@ def parse_kernel_facts(output: str) -> KernelFactsDict: "builtin": names("builtin"), "available": names("available"), "config": _config(sections["config"]) if "config" in sections else None, + "live_patches": live_patches(sections), } @@ -144,6 +165,9 @@ class KernelFactsMixin: """Run *command* on the host with ``sh`` and return what it printed.""" ... + #: Optional: a driver that can gain root supplies + #: ``_run_livepatch_status_command(command) -> str``, which runs *command* as root. + def get_kernel_facts(self) -> KernelFactsDict: """ Returns what the running kernel has built and loaded. @@ -166,6 +190,29 @@ class KernelFactsMixin: "config": {"CONFIG_TIPC": "m", "CONFIG_HZ": "250"}, } + * live_patches (dict) - loaded (``/sys/kernel/livepatch``, None without live + patching), kpatch (``kpatch list``) and canonical (Canonical Livepatch's + status for the running kernel, with the CVEs it fixes); each None when not read + :raises ValueError: if the host's output carried no intact report. """ - return parse_kernel_facts(self._run_kernel_facts_command(KERNEL_FACTS_COMMAND)) + facts = parse_kernel_facts(self._run_kernel_facts_command(KERNEL_FACTS_COMMAND)) + return self._with_canonical_as_root(facts) + + def _with_canonical_as_root(self, facts: KernelFactsDict) -> KernelFactsDict: + """*facts* with Canonical's status read as root where it did not read without. + + Only where the client was found (its section printed) and gave no status, and + only by a driver that can gain root. A refusal leaves it unread. + """ + patches = facts.get("live_patches") + run = getattr(self, "_run_livepatch_status_command", None) + if patches is None or not patches["canonical_installed"] or not callable(run): + return facts + if patches["canonical"] is not None: + return facts + try: + patches["canonical"] = parse_canonical_status(run(LIVEPATCH_STATUS_COMMAND)) + except Exception: # noqa: BLE001 - root refused or the client failed: not read + pass + return facts diff --git a/napalm_device_types/livepatch.py b/napalm_device_types/livepatch.py new file mode 100644 index 0000000..22e04d1 --- /dev/null +++ b/napalm_device_types/livepatch.py @@ -0,0 +1,201 @@ +"""The live patches a running Linux kernel carries, as the kernel and the vendors' tools say it. + +A live patch replaces kernel functions while the kernel runs: it fixes a CVE without a +new release, and without the reboot a new release needs (NetOrk/netork#2701). Three +places say which are in, each read by the kernel facts (:mod:`napalm_device_types.kernel`): + +- **The kernel itself:** ``/sys/kernel/livepatch//enabled`` for every patch + loaded, whoever built it (kpatch, Canonical, SUSE's kGraft successor), and + ``transition`` while it is still being applied. No package needed. +- **kpatch** (the Red Hat family): ``kpatch list`` names the patch modules loaded, with + whether each is enabled, and those installed for each kernel. +- **Canonical Livepatch** (Ubuntu Pro): ``canonical-livepatch status --format json``, + the daemon's last state -- the kernel it is for, whether a patch is applied, and the + CVEs it fixes. ``status`` reads what the daemon holds; netOrk never runs ``refresh``, + which is what calls Canonical. + +Parsing only: what a patch means for a CVE is the consumer's call. **Not read is None**: +a kernel built without live patching has no ``/sys/kernel/livepatch`` and ``loaded`` is +None; a host without kpatch or Canonical's client has ``kpatch`` / ``canonical`` None. +""" + +from __future__ import annotations + +import json +import re +from collections.abc import Iterable, Mapping +from typing import Any + +from typing_extensions import TypedDict + +_CVE = re.compile(r"\bcve-(\d{4})-(\d{4,})\b", re.IGNORECASE) +#: ``5.15.0-91.101-generic`` (Canonical's) is ``5.15.0-91-generic`` (``uname -r``). +_CANONICAL_KERNEL = re.compile(r"^(\d+\.\d+\.\d+-\d+)\.[^-]+(-.+)$") +_KPATCH_LOADED = re.compile(r"^(\S+)\s+\[(enabled|disabled)\]$") +_KPATCH_INSTALLED = re.compile(r"^(\S+)\s+\((\S+)\)$") + + +class LoadedLivePatchDict(TypedDict): + """One directory under ``/sys/kernel/livepatch``.""" + + name: str + enabled: bool | None + #: Still being applied to (or taken off) every task. + transition: bool | None + + +class KpatchModuleDict(TypedDict, total=False): + name: str + enabled: bool # loaded ones + kernel: str # installed ones: the kernel they are built for + + +class KpatchDict(TypedDict): + loaded: list[KpatchModuleDict] + installed: list[KpatchModuleDict] + + +class LivepatchFixDict(TypedDict): + cve: str # upper case, "CVE-2023-1077" + patched: bool + + +class CanonicalLivepatchDict(TypedDict): + """``canonical-livepatch status`` for the running kernel. None in a field: not said.""" + + kernel: str | None # as Canonical writes it: "5.15.0-91.101-generic" + running: bool | None + state: str | None # "applied", "nothing-to-apply", "unapplied", "apply-failed", ... + check_state: str | None # "checked", "needs-check", "check-failed", ... + version: str | None + fixes: list[LivepatchFixDict] + + +class LivePatchesDict(TypedDict): + #: ``/sys/kernel/livepatch``; None: the kernel has no live patching. + loaded: list[LoadedLivePatchDict] | None + #: ``kpatch list``; None: kpatch is not installed. + kpatch: KpatchDict | None + #: ``canonical-livepatch status``; None: not installed, or its status not read. + canonical: CanonicalLivepatchDict | None + #: Canonical's client is on the host (``canonical`` None then: its status unread). + canonical_installed: bool + + +def _flag(word: str | None) -> bool | None: + return {"1": True, "0": False}.get(word or "") + + +def parse_sysfs_livepatches(lines: Iterable[str]) -> list[LoadedLivePatchDict]: + """`` `` per loaded patch, as the command prints them.""" + patches: list[LoadedLivePatchDict] = [] + for line in lines: + words = line.split() + if not words: + continue + patches.append( + { + "name": words[0], + "enabled": _flag(words[1] if len(words) > 1 else None), + "transition": _flag(words[2] if len(words) > 2 else None), + } + ) + return patches + + +def parse_kpatch_list(lines: Iterable[str]) -> KpatchDict: + """``kpatch list``: the loaded modules with their state, the installed ones by kernel.""" + found: KpatchDict = {"loaded": [], "installed": []} + for line in (raw.strip() for raw in lines): + loaded = _KPATCH_LOADED.match(line) + if loaded: + found["loaded"].append({"name": loaded[1], "enabled": loaded[2] == "enabled"}) + continue + installed = _KPATCH_INSTALLED.match(line) + if installed: + found["installed"].append({"name": installed[1], "kernel": installed[2]}) + return found + + +def canonical_release(kernel: str | None) -> str | None: + """Canonical's name of a kernel as ``uname -r`` names it: without the upload number.""" + if kernel is None: + return None + match = _CANONICAL_KERNEL.match(kernel) + return f"{match[1]}{match[2]}" if match else kernel + + +def _get(data: Mapping[str, Any], key: str) -> Any: + """*key* in either case: the client wrote ``Status``, later ``status``.""" + for name, value in data.items(): + if name.lower() == key.lower(): + return value + return None + + +def _text(value: object) -> str | None: + return value if isinstance(value, str) and value else None + + +def _cve(text: str) -> str | None: + match = _CVE.search(text) + return f"CVE-{match[1]}-{match[2]}" if match else None + + +def _fixes(value: object) -> list[LivepatchFixDict]: + """The 10.x client's list of fixes, or the 9.x client's text of ``* cve-...`` lines.""" + if isinstance(value, str): + return [{"cve": cve, "patched": True} for line in value.splitlines() if (cve := _cve(line))] + fixes: list[LivepatchFixDict] = [] + for fix in value if isinstance(value, list) else []: + if not isinstance(fix, Mapping): + continue + cve = _cve(str(_get(fix, "Name") or "")) + if cve: + fixes.append({"cve": cve, "patched": _get(fix, "Patched") is True}) + return fixes + + +def _running_entry(entries: list[Any]) -> Mapping[str, Any] | None: + """The status of the running kernel: the one marked running, else the only one.""" + mappings = [e for e in entries if isinstance(e, Mapping)] + running = [e for e in mappings if _get(e, "Running") is True] + if running: + return running[0] + return mappings[0] if len(mappings) == 1 else None + + +def parse_canonical_status(text: str) -> CanonicalLivepatchDict | None: + """``canonical-livepatch status --format json``; None when it carries no status.""" + try: + data = json.loads(text) + except ValueError: + return None + entries = _get(data, "Status") if isinstance(data, Mapping) else None + entry = _running_entry(entries) if isinstance(entries, list) else None + if entry is None: + return None + patch = _get(entry, "Livepatch") + patch = patch if isinstance(patch, Mapping) else {} + running = _get(entry, "Running") + return { + "kernel": _text(_get(entry, "Kernel")), + "running": running if isinstance(running, bool) else None, + "state": _text(_get(patch, "State")), + "check_state": _text(_get(patch, "CheckState")), + "version": _text(_get(patch, "Version")), + "fixes": _fixes(_get(patch, "Fixes")), + } + + +def live_patches(sections: Mapping[str, list[str]]) -> LivePatchesDict: + """The three readings from the kernel facts' sections.""" + canonical = sections.get("canonical_livepatch") + return { + "loaded": parse_sysfs_livepatches(sections["livepatch"]) + if "livepatch" in sections + else None, + "kpatch": parse_kpatch_list(sections["kpatch"]) if "kpatch" in sections else None, + "canonical": parse_canonical_status("".join(canonical)) if canonical else None, + "canonical_installed": canonical is not None, + } diff --git a/napalm_device_types/models.py b/napalm_device_types/models.py index 18b3bb5..400ee50 100644 --- a/napalm_device_types/models.py +++ b/napalm_device_types/models.py @@ -21,6 +21,7 @@ from napalm_device_types.access_point_models import SSIDBridgeDict as SSIDBridge from napalm_device_types.access_point_models import SSIDDict as SSIDDict from napalm_device_types.access_point_models import WirelessClientDict as WirelessClientDict from napalm_device_types.access_point_models import WirelessConfigDict as WirelessConfigDict +from napalm_device_types.livepatch import LivePatchesDict from napalm_device_types.snmp_health_profile import SnmpHealthProfile as SnmpHealthProfile from napalm_device_types.snmp_health_profile import SnmpInterfacesSpec as SnmpInterfacesSpec from napalm_device_types.snmp_health_profile import SnmpMemorySpec as SnmpMemorySpec @@ -289,6 +290,8 @@ class KernelFactsDict(TypedDict): builtin: list[str] | None # modules.builtin -- compiled into the kernel image available: list[str] | None # modules.dep -- shipped as loadable modules config: dict[str, str] | None # build configuration, set options only; quotes stripped + #: The live patches the kernel carries (NetOrk/netork#2701, ``livepatch``). + live_patches: NotRequired[LivePatchesDict] class ListeningSocketDict(TypedDict): diff --git a/tests/test_live_patches.py b/tests/test_live_patches.py new file mode 100644 index 0000000..66cfef5 --- /dev/null +++ b/tests/test_live_patches.py @@ -0,0 +1,321 @@ +"""get_kernel_facts' live patches: what the running kernel has patched in while it runs. + +A live patch fixes a kernel CVE without a new release, so a consumer that judges the +running release alone reports the CVE open and a reboot as worth it (NetOrk/netork#2701). +The kernel facts read three things, each where it is kept: the loaded patches in +``/sys/kernel/livepatch`` (every distribution), ``kpatch list`` where kpatch is +installed, and ``canonical-livepatch status --format json`` -- the daemon's last state, +which names the CVEs each patch fixes. Canonical's status may need root: a driver that +can gain it supplies ``_run_livepatch_status_command``. +""" + +from __future__ import annotations + +import base64 +import gzip +import json + +import pytest + +from napalm_device_types.kernel import ( + KERNEL_FACTS_COMMAND, + LIVEPATCH_STATUS_COMMAND, + KernelFactsMixin, + parse_kernel_facts, +) +from napalm_device_types.livepatch import ( + canonical_release, + parse_canonical_status, + parse_kpatch_list, + parse_sysfs_livepatches, +) + +#: Ubuntu 22.04 with Livepatch applied: the client of the 10.x series, as the Ubuntu +#: Pro client reads it (``Status`` -> ``Livepatch`` -> ``Fixes``). +CANONICAL = { + "client-version": "10.8.3", + "architecture": "x86_64", + "cpu-model": "Intel(R) Xeon(R) CPU", + "last-check": "2026-11-28T09:12:44Z", + "boot-time": "2026-11-01T07:00:00Z", + "uptime": "2312h12m44s", + "Status": [ + { + "Kernel": "5.15.0-91.101-generic", + "Running": True, + "Livepatch": { + "CheckState": "checked", + "State": "applied", + "Version": "101.1", + "Fixes": [ + { + "Name": "cve-2023-1077", + "Description": "sched: ...", + "Bug": "", + "Patched": True, + }, + { + "Name": "cve-2023-3090", + "Description": "ipvlan: ...", + "Bug": "", + "Patched": True, + }, + { + "Name": "cve-2023-3389", + "Description": "io_uring: ...", + "Bug": "", + "Patched": False, + }, + {"Name": "lp-2023-1", "Description": "not a CVE", "Bug": "", "Patched": True}, + ], + }, + "Supported": "supported", + } + ], + "tier": "updates", +} + +#: The 9.x client wrote its fixes as one text, a ``* cve-...`` line each. +CANONICAL_9 = { + "Status": [ + { + "Kernel": "5.4.0-42.46-generic", + "Running": True, + "Livepatch": { + "CheckState": "checked", + "State": "applied", + "Version": "70.1", + "Fixes": "* cve-2020-11935\n* cve-2020-15780 (bug 1883337)\n", + }, + } + ] +} + +REPORT = """[release] +5.15.0-91-generic +[loaded] +lkp_Ubuntu_5_15_0_91_101_generic_101 +[livepatch] +lkp_Ubuntu_5_15_0_91_101_generic_101 1 0 +[canonical_livepatch] +{json} +""" + + +def _wire(report: str) -> str: + payload = base64.encodebytes(gzip.compress(report.encode())).decode() + return f"KFACTS_BEGIN\n{payload}KFACTS_END\n" + + +class TestSysfs: + def test_each_loaded_patch_enabled_or_not(self): + lines = ["livepatch_cve_2024_1 1 0", "kpatch_5_14_0_427 0 1", ""] + + assert parse_sysfs_livepatches(lines) == [ + {"name": "livepatch_cve_2024_1", "enabled": True, "transition": False}, + {"name": "kpatch_5_14_0_427", "enabled": False, "transition": True}, + ] + + def test_an_unreadable_flag_is_none(self): + assert parse_sysfs_livepatches(["lkp_x"]) == [ + {"name": "lkp_x", "enabled": None, "transition": None} + ] + + +class TestKpatch: + def test_loaded_and_installed_modules(self): + text = [ + "Loaded patch modules:", + "kpatch_5_14_0_427_13_1 [enabled]", + "kpatch_cumulative_old [disabled]", + "", + "Installed patch modules:", + "kpatch_5_14_0_427_13_1 (5.14.0-427.13.1.el9_4.x86_64)", + "kpatch_5_14_0_362 (5.14.0-362.8.1.el9_3.x86_64)", + ] + + assert parse_kpatch_list(text) == { + "loaded": [ + {"name": "kpatch_5_14_0_427_13_1", "enabled": True}, + {"name": "kpatch_cumulative_old", "enabled": False}, + ], + "installed": [ + {"name": "kpatch_5_14_0_427_13_1", "kernel": "5.14.0-427.13.1.el9_4.x86_64"}, + {"name": "kpatch_5_14_0_362", "kernel": "5.14.0-362.8.1.el9_3.x86_64"}, + ], + } + + def test_nothing_loaded(self): + assert parse_kpatch_list(["Loaded patch modules:", "", "Installed patch modules:"]) == { + "loaded": [], + "installed": [], + } + + +class TestCanonical: + def test_the_running_kernels_status_and_its_cves(self): + status = parse_canonical_status(json.dumps(CANONICAL)) + + assert status == { + "kernel": "5.15.0-91.101-generic", + "running": True, + "state": "applied", + "check_state": "checked", + "version": "101.1", + "fixes": [ + {"cve": "CVE-2023-1077", "patched": True}, + {"cve": "CVE-2023-3090", "patched": True}, + {"cve": "CVE-2023-3389", "patched": False}, + ], + } + + def test_the_9_x_clients_text_of_fixes(self): + status = parse_canonical_status(json.dumps(CANONICAL_9)) + + assert status is not None + assert status["fixes"] == [ + {"cve": "CVE-2020-11935", "patched": True}, + {"cve": "CVE-2020-15780", "patched": True}, + ] + + def test_keys_in_either_case(self): + lowered = json.loads( + json.dumps(CANONICAL).replace('"Status"', '"status"').replace('"State"', '"state"') + ) + + assert parse_canonical_status(json.dumps(lowered))["state"] == "applied" + + def test_the_entry_of_the_running_kernel(self): + other = { + "Kernel": "5.15.0-88.98-generic", + "Running": False, + "Livepatch": {"State": "applied", "Fixes": []}, + } + data = {"Status": [other, CANONICAL["Status"][0]]} + + assert parse_canonical_status(json.dumps(data))["kernel"] == "5.15.0-91.101-generic" + + @pytest.mark.parametrize("text", ["", "error: must be root", "{}", '{"Status": []}', "[1, 2]"]) + def test_no_status_is_none(self, text): + assert parse_canonical_status(text) is None + + @pytest.mark.parametrize( + "kernel, release", + [ + ("5.15.0-91.101-generic", "5.15.0-91-generic"), + ("6.8.0-49.49~22.04.1-generic", "6.8.0-49-generic"), + ("5.4.0-1045.47-aws", "5.4.0-1045-aws"), + ("6.8.0-49-generic", "6.8.0-49-generic"), + (None, None), + ], + ) + def test_its_kernel_as_uname_names_it(self, kernel, release): + assert canonical_release(kernel) == release + + +class TestInTheKernelFacts: + def test_read_with_the_kernel_facts(self): + facts = parse_kernel_facts(_wire(REPORT.format(json=json.dumps(CANONICAL)))) + patches = facts["live_patches"] + + assert patches["loaded"] == [ + {"name": "lkp_Ubuntu_5_15_0_91_101_generic_101", "enabled": True, "transition": False} + ] + assert patches["kpatch"] is None + assert patches["canonical"]["state"] == "applied" + + def test_a_kernel_without_live_patching_has_none_loaded(self): + """No ``/sys/kernel/livepatch``: the kernel was built without it, nothing is loaded.""" + facts = parse_kernel_facts(_wire("[release]\n6.1.0-25-amd64\n")) + + assert facts["live_patches"] == { + "loaded": None, + "kpatch": None, + "canonical": None, + "canonical_installed": False, + } + + def test_an_empty_directory_is_none_loaded(self): + facts = parse_kernel_facts(_wire("[release]\n6.1.0-25-amd64\n[livepatch]\n")) + + assert facts["live_patches"]["loaded"] == [] + + +class _Driver(KernelFactsMixin): + def __init__(self, report: str, status: str | None = None): + self.report = report + self.status = status + self.asked: list[str] = [] + + def _run_kernel_facts_command(self, command: str) -> str: + return _wire(self.report) + + +class _RootDriver(_Driver): + def _run_livepatch_status_command(self, command: str) -> str: + self.asked.append(command) + return self.status or "" + + +class TestCanonicalAsRoot: + """``canonical-livepatch status`` may refuse a user who is not root: where the + kernel facts found the client but no status, a driver that can gain root asks again.""" + + UNREAD = "[release]\n5.15.0-91-generic\n[livepatch]\n[canonical_livepatch]\n" + + def test_asked_again_as_root(self): + driver = _RootDriver(self.UNREAD, json.dumps(CANONICAL)) + + facts = driver.get_kernel_facts() + + assert driver.asked == [LIVEPATCH_STATUS_COMMAND] + assert facts["live_patches"]["canonical"]["version"] == "101.1" + + def test_not_asked_when_read_already(self): + driver = _RootDriver(REPORT.format(json=json.dumps(CANONICAL))) + + driver.get_kernel_facts() + + assert driver.asked == [] + + def test_not_asked_without_the_client(self): + driver = _RootDriver("[release]\n6.1.0\n") + + driver.get_kernel_facts() + + assert driver.asked == [] + + def test_a_driver_without_root_leaves_it_unread(self): + facts = _Driver(self.UNREAD).get_kernel_facts() + + assert facts["live_patches"]["canonical"] is None + assert facts["live_patches"]["canonical_installed"] is True + + def test_a_failed_root_read_leaves_it_unread(self): + class Failing(_RootDriver): + def _run_livepatch_status_command(self, command: str) -> str: + raise RuntimeError("sudo: a password is required") + + assert Failing(self.UNREAD).get_kernel_facts()["live_patches"]["canonical"] is None + + +class TestTheCommands: + def test_the_kernel_facts_read_the_live_patches(self): + assert "/sys/kernel/livepatch" in KERNEL_FACTS_COMMAND + assert "kpatch list" in KERNEL_FACTS_COMMAND + assert "status --format json" in KERNEL_FACTS_COMMAND + + def test_they_ask_canonical_nothing(self): + """``status`` reads the daemon's last state; ``refresh`` would call Canonical.""" + for command in (KERNEL_FACTS_COMMAND, LIVEPATCH_STATUS_COMMAND): + for verb in ( + "refresh", + "livepatch enable", + "livepatch disable", + "kpatch load", + "kpatch unload", + "kpatch install", + "kpatch uninstall", + ): + assert verb not in command + assert LIVEPATCH_STATUS_COMMAND.endswith("status --format json")