diff --git a/CATALOG.md b/CATALOG.md index 776310b1..030225d9 100644 --- a/CATALOG.md +++ b/CATALOG.md @@ -552,7 +552,7 @@ Django UI extensions (XUI). Each folder has a README. | Ssm Inventory | [XUI-l43ailkn](extensions/XUI-l43ailkn/README.md) | Adds Inventory and Patching server tabs for EC2 instances managed by AWS Systems Manager. | | StormForge Optimize Live | [XUI-wyauaxbl](extensions/XUI-wyauaxbl/README.md) | Adds Clusters, Namespaces and Workloads tabs, marked with the StormForge icon, to Kubernetes clusters running the StormForge agent, with StormForge's optimization score, recommendation impact, namespace and workload tables, a live node snapshot, cluster configuration, and each workload's summary, recommendation, patches and optimization settings, the level (cluster, namespace or workload) every setting is set at, drilling down from cluster to namespace to workload, and adds an Optimization tab to each EKS, AKS and GKE namespace on those clusters that shows only that namespace's workloads and applies their recommendations. | | Technology Reference | [XUI-vwrd15py](extensions/XUI-vwrd15py/README.md) | Adds a read-only Technology Reference tab to Resource Handler and Environment pages listing the technology's custom fields, actions, and field dependencies, discovered live from the instance and exportable as one .xlsx. | -| Vulnerabilities | [XUI-wqrj0e3p](extensions/XUI-wqrj0e3p/README.md) | Finds known CVEs on Linux servers (from a software list) and Windows Server 2022 and 2025 servers (from the Windows build and installed updates) by matching them against vulnerability data on the appliance, with a tab on servers and on resources, a search across all servers, and a nightly re-match. | +| Vulnerabilities | [XUI-wqrj0e3p](extensions/XUI-wqrj0e3p/README.md) | Finds known CVEs on Linux servers (from a software list) and Windows Server 2022 and 2025 servers (from the Windows build and installed updates) by matching them against vulnerability data on the appliance, with a tab on servers and on resources, a search across all servers, a nightly re-match, and an optional action that installs updates, restarts if needed and rescans. | ## Parameters diff --git a/catalog.json b/catalog.json index 45f978bd..ed9319a3 100644 --- a/catalog.json +++ b/catalog.json @@ -853,7 +853,7 @@ "id": "XUI-wqrj0e3p", "type": "extensions", "name": "Vulnerabilities", - "description": "Finds known CVEs on Linux servers (from a software list) and Windows Server 2022 and 2025 servers (from the Windows build and installed updates) by matching them against vulnerability data on the appliance, with a tab on servers and on resources, a search across all servers, and a nightly re-match.", + "description": "Finds known CVEs on Linux servers (from a software list) and Windows Server 2022 and 2025 servers (from the Windows build and installed updates) by matching them against vulnerability data on the appliance, with a tab on servers and on resources, a search across all servers, a nightly re-match, and an optional action that installs updates, restarts if needed and rescans.", "path": "extensions/XUI-wqrj0e3p", "readme": "extensions/XUI-wqrj0e3p/README.md", "uses": [], diff --git a/extensions/README.md b/extensions/README.md index fb8b181c..9bde0f39 100644 --- a/extensions/README.md +++ b/extensions/README.md @@ -23,4 +23,4 @@ Django UI extensions (XUI). Each folder has a README. | Ssm Inventory | [XUI-l43ailkn](XUI-l43ailkn/README.md) | Adds Inventory and Patching server tabs for EC2 instances managed by AWS Systems Manager. | | StormForge Optimize Live | [XUI-wyauaxbl](XUI-wyauaxbl/README.md) | Adds Clusters, Namespaces and Workloads tabs, marked with the StormForge icon, to Kubernetes clusters running the StormForge agent, with StormForge's optimization score, recommendation impact, namespace and workload tables, a live node snapshot, cluster configuration, and each workload's summary, recommendation, patches and optimization settings, the level (cluster, namespace or workload) every setting is set at, drilling down from cluster to namespace to workload, and adds an Optimization tab to each EKS, AKS and GKE namespace on those clusters that shows only that namespace's workloads and applies their recommendations. | | Technology Reference | [XUI-vwrd15py](XUI-vwrd15py/README.md) | Adds a read-only Technology Reference tab to Resource Handler and Environment pages listing the technology's custom fields, actions, and field dependencies, discovered live from the instance and exportable as one .xlsx. | -| Vulnerabilities | [XUI-wqrj0e3p](XUI-wqrj0e3p/README.md) | Finds known CVEs on Linux servers (from a software list) and Windows Server 2022 and 2025 servers (from the Windows build and installed updates) by matching them against vulnerability data on the appliance, with a tab on servers and on resources, a search across all servers, and a nightly re-match. | +| Vulnerabilities | [XUI-wqrj0e3p](XUI-wqrj0e3p/README.md) | Finds known CVEs on Linux servers (from a software list) and Windows Server 2022 and 2025 servers (from the Windows build and installed updates) by matching them against vulnerability data on the appliance, with a tab on servers and on resources, a search across all servers, a nightly re-match, and an optional action that installs updates, restarts if needed and rescans. | diff --git a/extensions/XUI-wqrj0e3p/README.md b/extensions/XUI-wqrj0e3p/README.md index 6705eace..395f1b51 100644 --- a/extensions/XUI-wqrj0e3p/README.md +++ b/extensions/XUI-wqrj0e3p/README.md @@ -2,7 +2,7 @@ Adds a **Vulnerabilities** tab to Linux and Windows servers, and to any server labelled `Vulnerabilities`. On Linux the tab collects a list of the software installed on the server, matches it against a database of known vulnerabilities, and shows the findings: how many are critical, high, medium and low, how many are on the CISA known-exploited list, and for each package the installed version, the version that fixes it and the advisory. Users can switch between a Packages view (what to update) and a CVEs view (one row per CVE), search, filter by severity and show only exploited findings or only those with a fix. The Known vulnerabilities card also says how many vulnerabilities have a fix; a vulnerability has one when any package it affects has a fixed version, and a Windows finding always has one. -Nothing is changed on the server. The tab does not contact the server when it opens; it shows the last result. Windows servers are covered in [Windows servers](#windows-servers). +Scanning changes nothing on the server (installing updates is a separate action, see [Install updates](#install-updates)). The tab does not contact the server when it opens; it shows the last result. Windows servers are covered in [Windows servers](#windows-servers). ## How it works @@ -64,6 +64,25 @@ Two recurring jobs are created the first time the Vulnerability Settings page op Turn on **Scan new servers after they are built** on the settings page. The extension then adds an action to the post-provisioning hook point. After a successful build, each new server that can be scanned is scanned as its own job: the build never waits for it and never fails because of it. Turning the setting off switches the action off; it is never created while the setting is off. +## Install updates + +Turn on **Install updates** on the settings page and the extension creates a server action, **Install Updates**, which installs every available update on one Linux or Windows server from the repositories or update source it is already configured with. The button of the same name then shows on the server's Vulnerabilities tab next to the scan button, and the action also appears in the server's Actions menu. Turning the setting off disables the action; its role grants and its Requires approval choice are kept. The action is offered on Linux servers and on Windows Server 2022 and 2025. A server in an Unassigned group is never offered it. + +- **Who can run it.** CB Admins, and users whose role has `server.all_actions` on the server. For any other role, an admin adds **Install Updates** to the role's server actions. A new action is granted to no role. +- **Requires approval.** The action is created without it. An admin can switch it on in the action's settings; the run then waits for an approval like any other server action, and the setting is never changed again by the extension. +- **What it runs.** Red Hat Enterprise Linux and Oracle Linux 8 to 10: `dnf -y --refresh upgrade`. Amazon Linux 2023: `dnf -y --refresh upgrade --releasever=latest`. Ubuntu 22.04 and 24.04: `apt-get update`, then a non-interactive `apt-get -y dist-upgrade` that keeps the existing configuration files. Any other distribution is refused with a message and nothing is installed. The server needs its repositories reachable. +- **Restart.** The dialog has a **Restart if needed** option, on by default; a CloudBolt global preference decides whether it shows as a checkbox or as a True/False list. When an update needs a restart and the option is on, the server is restarted and the job waits for it to come back (up to the restart wait in the settings, 5 to 120 minutes, default 60); a server that is not back by then fails the job. With the option off the updates are installed, the panel says a restart is pending, and the scan afterwards still runs. The update itself is limited by the update timeout in the settings (10 to 240 minutes, default 90). +- **Windows.** Windows Server 2022 and 2025 only. The updates come from the server's configured source: WSUS when group policy sets one, otherwise Windows Update, so on WSUS only approved updates install. The work runs as a scheduled task under SYSTEM, so the credentials CloudBolt uses must be able to create one; a non-administrator WinRM credential cannot. A server with the Configuration Manager client is refused with a message and nothing is installed. A cumulative update finishes during the restart, so the server can take a long time to answer again; raise the restart wait if it fails. If more updates are offered afterwards, the job says how many; run the action again to install them. +- **Old kernels.** Only after a restart that was confirmed, old kernels are removed: on the Red Hat family `dnf -y remove --oldinstallonly` (dnf keeps the number of kernels set by `installonly_limit`, 3 by default); on Ubuntu, which keeps the previous kernel as a boot fallback that its own cleanup never removes, the action removes the older kernel's packages by name, only when the server is running its newest kernel and nothing else would be removed. The setting **Remove old kernels after a restart** (on by default) turns this off; the scan then keeps listing the old kernel's vulnerabilities for as long as it stays installed. +- **What updating cannot fix.** Findings in software the package manager does not own, such as libraries bundled inside agents and tools (Go binaries, Python packages installed outside the distribution's packages). They stay listed with a fix version after the run. +- **Nothing to install.** A server whose image is already current reports "No updates were available". +- **After the update** the server is scanned again and the panel shows the vulnerabilities before and after, and a link to the job. If the scan fails the updates stay installed and the line shows the missing number as a dash. +- **Cancelling.** Cancelling the job does not stop the update on the server: a package transaction is never stopped halfway, so it runs to its end there. Run the action again to see the result. +- **After the dialog** CloudBolt returns to the server's default tab, not to Vulnerabilities, because the browser drops the tab from the address. Open the tab to follow the run; it refreshes every 5 seconds. +- **Not covered.** Windows versions other than 2022 and 2025, and any Linux distribution other than those above. + +**Install updates on all servers of a resource.** The same setting also adds a resource action, **Install Updates on All Servers**, to every resource that has a Linux or Windows server. It installs the updates on the resource's servers one server at a time, in hostname order, and stops at the first server whose update fails; the servers after it are listed as not attempted. A server that needs a restart it was not allowed to do (restart-pending) is not a failure, and the run goes on. A server that cannot be updated now (historical, in an Unassigned group, unsupported, or one the person may not update) is skipped with its reason, and the skipped servers are listed in the job output. To run it a person needs permission to run the resource action on the resource (CB Admins, a role with `resource.all_actions`, or a role that has the action added) and, for every server, the same permission as for the server action; a server that fails the second check is skipped. Requires approval is set separately on the resource action in its settings and is never changed by the extension. A failed server ends the job as a failure and the remaining servers are not attempted. Servers the requester may not act on, or that are not eligible, are skipped and the run continues. A resource runs one install at a time. + ## Setup 1. Sync the repository, then restart the web service (`httpd`) so the new routes load, and confirm the extension is enabled under Admin > Extensions. diff --git a/extensions/XUI-wqrj0e3p/XUI-wqrj0e3p_metadata.json b/extensions/XUI-wqrj0e3p/XUI-wqrj0e3p_metadata.json index 77ebe5d3..fa3d04f4 100644 --- a/extensions/XUI-wqrj0e3p/XUI-wqrj0e3p_metadata.json +++ b/extensions/XUI-wqrj0e3p/XUI-wqrj0e3p_metadata.json @@ -1,10 +1,10 @@ { - "description": "Finds known CVEs on Linux servers (from a software list) and Windows Server 2022 and 2025 servers (from the Windows build and installed updates) by matching them against vulnerability data on the appliance, with a tab on servers and on resources, a search across all servers, and a nightly re-match.", + "description": "Finds known CVEs on Linux servers (from a software list) and Windows Server 2022 and 2025 servers (from the Windows build and installed updates) by matching them against vulnerability data on the appliance, with a tab on servers and on resources, a search across all servers, a nightly re-match, and an optional action that installs updates, restarts if needed and rescans.", "enabled": true, "icon_url": "", "id": "XUI-wqrj0e3p", "label": "Vulnerabilities", - "last_updated": "2026-11-23", + "last_updated": "2026-11-24", "maximum_version_required": "", "minimum_version_required": "8.6", "name": "io_cloudbolt_vulnerabilities", @@ -25,10 +25,20 @@ "vuln_rematch_job.py", "vuln_inventory_job.py", "vuln_provision_job.py", + "vuln_patch.py", + "vuln_patch.sh", + "vuln_patch_job.py", + "vuln_patch_condition.py", + "vuln_patch_resource.py", + "vuln_resource_patch_job.py", + "vuln_resource_patch_condition.py", + "vuln_api.py", "vuln_resource_job.py", "vuln_scan.sh", "vuln_msrc.py", "vuln_scan_windows.ps1", + "vuln_wintask.py", + "vuln_patch_windows.ps1", "templates/vuln_styles.html", "templates/vuln_assets.html", "templates/vuln_tab.html", diff --git a/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/templates/vuln_fleet_assets.html b/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/templates/vuln_fleet_assets.html index 1af08163..82e89d69 100644 --- a/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/templates/vuln_fleet_assets.html +++ b/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/templates/vuln_fleet_assets.html @@ -22,6 +22,15 @@ summary.servers_total > 0 with summary.servers = 0 (a resource whose servers are all unscanned) keeps the explanation and shows the Servers list instead of the cards, the view switch ([data-vuln-switch]) and the Vulnerabilities view. + [data-vuln-patch-all] the "Install updates on all servers" link (resource mode only: the admin page + has neither the link nor [data-vuln-patch-last]). It is a plain anchor that + opens CloudBolt's own dialog (class open-dialog), so it has no data-vuln-act and + this script never handles its click; it is un-hidden when the summary's patch + says offer and no run is live, and its href is used only when it starts with "/". + A run whose kind is "patch" is drawn as "Installing updates", with the server it + is on and the run's message; a change of message alone redraws the banner without + reloading the panes. [data-vuln-patch-last] shows the summary's patch_last, the + result of the last update run, and is hidden while a run is live. A root is initialised once (data-vuln-init), at once when the document has already loaded (the tab HTML is injected after the page), and its timers stop when it leaves the document. {% endcomment %} @@ -285,6 +294,8 @@ var listOnly = false; // resource mode, servers visible but none scanned: the explanation and the Servers list var refreshOnPoll = false; // a run just became live: the next light poll reloads the visible pane once var canScan = null; // true shows the scan button, false hides it; null (a run is live) leaves it as it is + var patch = null; // the summary's patch: the Install updates on all servers link (resource mode only) + var patchLast = null; // the summary's patch_last: the result of the last update run of the resource function alive() { return document.body.contains(rootEl); } function one(sel) { return rootEl.querySelector(sel); } @@ -624,7 +635,9 @@ function drawRun() { var box = one("[data-vuln-run]"); if (!box) { return; } - var key = run ? [run.job_id, run.done, run.total, run.started].join("|") : ""; + var isPatch = !!run && run.kind === "patch"; + var key = run ? [run.job_id, run.done, run.total, run.started, isPatch ? "patch" : "scan", + isPatch ? (run.message || "") : ""].join("|") : ""; if (key === runKey && (run ? !box.hidden : true)) { return; } // unchanged: do not redraw a live region runKey = key; while (box.firstChild) { box.removeChild(box.firstChild); } @@ -632,11 +645,16 @@ var banner = el("div", "vuln-banner vuln-banner-info"); banner.setAttribute("role", "status"); var body = el("div", "vuln-banner-body"); - body.appendChild(el("div", "vuln-banner-t", "Scan in progress")); + body.appendChild(el("div", "vuln-banner-t", isPatch ? "Installing updates" : "Scan in progress")); var total = Number(run.total) || 0; var done = Math.min(Number(run.done) || 0, total); var parts = []; - if (total > 0) { parts.push(done + " of " + total + " servers done"); } + if (isPatch) { + // "Server n of m" and what the job is doing now; the message may already begin with the server count. + var said = run.message ? String(run.message) : ""; + if (total > 0 && !/^Server \d+ of \d+/.test(said)) { parts.push("Server " + Math.min(done + 1, total) + " of " + total); } + if (said) { parts.push(said); } + } else if (total > 0) { parts.push(done + " of " + total + " servers done"); } if (run.started) { parts.push("started " + fmtTime(run.started, "when")); } body.appendChild(el("div", "vuln-banner-s", parts.join(" · "))); banner.appendChild(body); @@ -659,14 +677,67 @@ } } + // The "Install updates on all servers" link: shown only when the summary offers it and no run (scan or + // update) is live. Its href comes from the server and is used only when it is a path on this site. + function syncPatch() { + var link = one("[data-vuln-patch-all]"); + if (!link) { return; } + var url = patch && patch.offer && typeof patch.url === "string" && patch.url.charAt(0) === "/" ? patch.url : ""; + if (url) { link.setAttribute("href", url); } + link.hidden = !url || !!run; + } + + function plural(n, one_, many) { return n + " " + (n === 1 ? one_ : many); } + + // The result line of the last update run of the resource, from the stored record, with textContent only. + function drawPatchLast() { + var box = one("[data-vuln-patch-last]"); + if (!box) { return; } + while (box.firstChild) { box.removeChild(box.firstChild); } + if (!patchLast || run) { box.hidden = true; return; } + var updated = Number(patchLast.updated) || 0; + var pending = Number(patchLast.restart_pending) || 0; + var failed = Number(patchLast.failed) || 0; + var skipped = Number(patchLast.skipped) || 0; + var unchanged = Number(patchLast.no_updates) || 0; + var text; + if (!updated && !pending && !failed && unchanged) { + text = "No updates were available on " + plural(unchanged, "server", "servers") + "."; + } else { + text = (patchLast.at ? "Updated " + fmtTime(patchLast.at, "when") : "Updated") + + (patchLast.by ? " by " + patchLast.by : "") + ": " + plural(updated, "server", "servers") + " updated"; + if (pending) { text += ", " + pending + " pending a restart"; } + if (failed) { text += ", " + failed + " failed"; } + if (skipped) { text += ", " + skipped + " skipped"; } + text += "."; + } + var banner = el("div", "vuln-banner " + (failed > 0 ? "vuln-banner-bad" : "vuln-banner-info")); + banner.setAttribute("role", "status"); + var body = el("div", "vuln-banner-body"); + body.appendChild(el("div", "vuln-banner-s", text)); + banner.appendChild(body); + if (patchLast.job_url && String(patchLast.job_url).charAt(0) === "/") { + var link = el("a", "btn btn-sm btn-outline-secondary vuln-banner-btn", "View job"); + link.setAttribute("href", patchLast.job_url); + banner.appendChild(link); + } + box.appendChild(banner); + box.hidden = false; + } + function applyRun(data) { var was = run; run = (data && data.run) || null; // Resource mode only (scanUrl): the admin page never has a run, and its behaviour is unchanged. refreshOnPoll = !!scanUrl && !!run && (!was || refreshOnPoll); canScan = data && data.can_scan === true ? true : (data && data.can_scan === false ? false : null); + // Resource mode only: the admin page's summary has no patch or patch_last. + patch = scanUrl && data && data.patch ? data.patch : null; + patchLast = scanUrl && data && data.patch_last ? data.patch_last : null; drawRun(); syncScan(); + syncPatch(); + drawPatchLast(); } // While a run is in progress a light request (summary?run=1, only the run) is made every 5 @@ -695,6 +766,10 @@ if (!next || !run || next.job_id !== run.job_id || next.done !== run.done || refreshOnPoll) { refreshOnPoll = false; loadSummary({ quiet: true }); + } else if (next.message !== run.message || next.kind !== run.kind) { + // Only what the job says it is doing changed: redraw the banner, the panes need no reload. + run = next; + drawRun(); } }).always(function () { if (runXhr === req) { runXhr = null; scheduleRun(); } }); } diff --git a/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/templates/vuln_panel.html b/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/templates/vuln_panel.html index e8ca02bb..4d70dfb9 100644 --- a/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/templates/vuln_panel.html +++ b/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/templates/vuln_panel.html @@ -48,7 +48,7 @@
-
{% if vuln.windows %}{% trans "Check running" %}{% else %}{% trans "Scan running" %}{% endif %}
+
{% if vuln.active.kind == "patch" %}{% trans "Installing updates" %}{% elif vuln.windows %}{% trans "Check running" %}{% else %}{% trans "Scan running" %}{% endif %}
{% if vuln.active.started %}{% trans "Started" %} {{ vuln.active.started }}{% endif %}{% if vuln.active.message %}{% if vuln.active.started %} · {% endif %}{{ vuln.active.message }}{% endif %}
{% if vuln.active.job_url %}{% trans "View job" %}{% endif %} @@ -65,6 +65,17 @@
{% endif %} + {% if vuln.patch_last and not vuln.summary %} + {% with p=vuln.patch_last %} +
+ {% if p.status == "failed" %}{% trans "Updating failed" %} {{ p.at }}.{% if p.message %} {{ p.message }}{% endif %} + {% else %}{% if p.status == "restart_pending" %}{% trans "Updates installed" %}{% elif p.status == "no_updates" %}{% trans "Checked" %}{% else %}{% trans "Updated" %}{% endif %} {{ p.at }}{% if p.by %} {% trans "by" %} {{ p.by }}{% endif %}.{% if p.status == "restart_pending" %} {% trans "A restart is pending." %}{% elif p.status == "no_updates" %} {% trans "No updates were available." %}{% elif p.status == "updated" %}{% if p.restarted %} {% trans "The server was restarted." %}{% endif %}{% if p.kernels_removed and p.kernels_removed > 0 %} {{ p.kernels_removed }} {% if p.kernels_removed == 1 %}{% trans "old kernel package was removed." %}{% else %}{% trans "old kernel packages were removed." %}{% endif %}{% endif %}{% endif %} + {% trans "Known vulnerabilities" %} {% if p.before.vulns is not None %}{{ p.before.vulns }}{% else %}–{% endif %} → {% if p.after.vulns is not None %}{{ p.after.vulns }}{% else %}–{% endif %}. {% trans "With a fix" %} {% if p.before.vuln_fixable is not None %}{{ p.before.vuln_fixable }}{% else %}–{% endif %} → {% if p.after.vuln_fixable is not None %}{{ p.after.vuln_fixable }}{% else %}–{% endif %}.{% endif %} + {% if p.job_url %}{% trans "View job" %}{% endif %} +
+ {% endwith %} + {% endif %} + {# No results and nothing running: always offer the scan button, so a failed first scan can be repeated. #} {% if not vuln.summary and not vuln.active %}
@@ -80,6 +91,9 @@ {% elif vuln.can_scan %} {% endif %} + {% if vuln.patch.offer and not vuln.active %} + {% trans "Install updates" %} + {% endif %}
{% endif %} @@ -131,6 +145,17 @@ + {% if vuln.patch_last %} + {% with p=vuln.patch_last %} +
+ {% if p.status == "failed" %}{% trans "Updating failed" %} {{ p.at }}.{% if p.message %} {{ p.message }}{% endif %} + {% else %}{% if p.status == "restart_pending" %}{% trans "Updates installed" %}{% elif p.status == "no_updates" %}{% trans "Checked" %}{% else %}{% trans "Updated" %}{% endif %} {{ p.at }}{% if p.by %} {% trans "by" %} {{ p.by }}{% endif %}.{% if p.status == "restart_pending" %} {% trans "A restart is pending." %}{% elif p.status == "no_updates" %} {% trans "No updates were available." %}{% elif p.status == "updated" %}{% if p.restarted %} {% trans "The server was restarted." %}{% endif %}{% if p.kernels_removed and p.kernels_removed > 0 %} {{ p.kernels_removed }} {% if p.kernels_removed == 1 %}{% trans "old kernel package was removed." %}{% else %}{% trans "old kernel packages were removed." %}{% endif %}{% endif %}{% endif %} + {% trans "Known vulnerabilities" %} {% if p.before.vulns is not None %}{{ p.before.vulns }}{% else %}–{% endif %} → {% if p.after.vulns is not None %}{{ p.after.vulns }}{% else %}–{% endif %}. {% trans "With a fix" %} {% if p.before.vuln_fixable is not None %}{{ p.before.vuln_fixable }}{% else %}–{% endif %} → {% if p.after.vuln_fixable is not None %}{{ p.after.vuln_fixable }}{% else %}–{% endif %}.{% endif %} + {% if p.job_url %}{% trans "View job" %}{% endif %} +
+ {% endwith %} + {% endif %} +
@@ -159,6 +184,9 @@ {% if vuln.can_scan %} {% endif %} + {% if vuln.patch.offer and not vuln.active %} + {% trans "Install updates" %} + {% endif %}
diff --git a/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/templates/vuln_resource_tab.html b/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/templates/vuln_resource_tab.html index 2ea75142..f208e2e1 100644 --- a/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/templates/vuln_resource_tab.html +++ b/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/templates/vuln_resource_tab.html @@ -11,6 +11,10 @@ second style block, built from the same variables. The "Scan all servers" button is always rendered, hidden: the summary answer's can_scan shows it, so this view never works out which servers may be scanned. + The "Install updates on all servers" link is rendered the same way: it has no data-vuln-act (the shared + click handler would cancel the click), it opens CloudBolt's own dialog for the resource action, and the + script un-hides it from the summary answer's patch. [data-vuln-patch-last] holds the result line of the + last update run. Context: resource, no_servers, urls (summary, cves, cve_servers, servers, scan), shell (is_admin, settings_url, fleet_url). {% endcomment %} @@ -43,6 +47,7 @@

{{ resource.name }}

{% if not no_servers %} + {% endif %} {% if shell.fleet_url %}{% trans "All servers" %}{% endif %} {% if shell.settings_url %}{% trans "Settings" %}{% endif %} @@ -62,6 +67,8 @@

{{ resource.name }}

+ +
{% trans "Loading from CloudBolt…" %}
+
+

Installing updates

+
+
+ + +
+
Turning this on creates the Install Updates server action and the Install Updates on All Servers resource action, and turning it off hides both. CB admins and roles with all server actions can run the server action at once; CB admins and roles with all resource actions can run the resource action at once. Other roles must be granted each action. Requires approval is set on each action separately. The resource action appears on every resource that has a Linux or Windows server and updates its servers one at a time, only those the person may update with the server action. It works on Linux servers and on Windows Server 2022 and 2025. Servers in an Unassigned group are never updated.
+ {% if field_errors.patching %}
{{ field_errors.patching }}
{% endif %} + {% if settings.patching and patch_action %}{% if not patch_action.exists %}
The Install Updates action is missing. Save the settings to create it again.
{% elif not patch_action.enabled %}
The Install Updates action is switched off in CloudBolt's actions. Enable it there to offer it again.
{% endif %}{% endif %} + {% if settings.patching and resource_patch_action %}{% if not resource_patch_action.exists %}
The Install Updates on All Servers action is missing. Save the settings to create it again.
{% elif not resource_patch_action.enabled %}
The Install Updates on All Servers action is switched off in CloudBolt's actions. Enable it there to offer it again.
{% endif %}{% endif %} +
+
+
+ + +
+
After a Linux server restarts onto a new kernel, remove the older kernel's packages. A scan keeps reporting an old kernel's vulnerabilities for as long as it stays installed. Turn this off to keep the previous kernel as a boot fallback.
+
+
+ + +
How long an update waits for a restarted server to answer again before it reports a failure, from 5 to 120 (default 60). A Windows cumulative update finishes during the restart, so the server can take a long time to answer.
+ {% if field_errors.restart_wait_min %}
{{ field_errors.restart_wait_min }}
{% endif %} +
+
+ + +
How long the install itself may run on one server before it is reported as failed, from 10 to 240.
+ {% if field_errors.patch_timeout_min %}
{{ field_errors.patch_timeout_min }}
{% endif %} +
+
+
diff --git a/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/views.py b/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/views.py index 5aea3ba8..ae801e52 100644 --- a/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/views.py +++ b/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/views.py @@ -42,6 +42,8 @@ Search script (vuln_fleet_assets.html). Neither the tab dispatcher nor the delegate checks permissions, so every route starts with _viewable_resource and works only on the viewer's servers of that resource, the scan included. + The summary also offers "Install updates on all servers" (a link to CloudBolt's own dialog for the resource + action) and the result of the last update run; a run of kind patch is drawn as progress by the same script. Viewing needs the view permission on the server (Server.objects_for_profile), and for the resource tab on the resource (Resource.objects_for_profile) and on @@ -56,7 +58,6 @@ from django.core.exceptions import PermissionDenied from django.core.paginator import Paginator -from django.db.models import Q from django.http import Http404, JsonResponse from django.shortcuts import render from django.urls import reverse @@ -69,8 +70,8 @@ from utilities.middleware import login_not_required from utilities.permissions import cbadmin_required -from . import (vuln_db, vuln_fleet, vuln_hooks, vuln_jobs, vuln_match, vuln_msrc, vuln_repo, vuln_store as store, - vuln_tools) +from . import (vuln_db, vuln_fleet, vuln_hooks, vuln_jobs, vuln_match, vuln_msrc, vuln_patch, vuln_repo, + vuln_store as store, vuln_tools) logger = ThreadLogger(__name__) @@ -237,13 +238,45 @@ def vulnerabilities_tab(request, obj_id): # --------------------------------------------------------------------------- # Panel (HTML fragment loaded asynchronously by the tab) # --------------------------------------------------------------------------- -def _panel_context(server, profile): +def _patch_offer(server, profile, request): + """The Install updates button for this server as {"offer", "url", "label"}. Any failure, a missing patch module + included, means no button: the panel never breaks because of it.""" + none = {"offer": False, "url": "", "label": ""} + try: + if vuln_patch.eligibility(server): + return none + button = vuln_hooks.patch_button(server, profile, request) + except Exception: + logger.exception("Vulnerabilities: cannot work out the Install updates button for server %s", + getattr(server, "id", "")) + return none + if not button or not button.get("url"): + return none + return {"offer": True, "url": button["url"], "label": button.get("label") or ""} + + +def _patch_last(state): + """The stored record of the last update run, with the link to its job; None when there is none.""" + record = state.get("patch") + if not isinstance(record, dict) or not record.get("status"): + return None + record = dict(record, job_url="") + try: + if record.get("job_id"): + record["job_url"] = reverse("job_detail", args=[record["job_id"]]) + except Exception: + logger.exception("Vulnerabilities: cannot build the job link of an update run") + return record + + +def _panel_context(server, profile, request=None): _upgrade_store() # readers never upgrade, and the summary selects the newest columns summary = vuln_db.server_summary(server.id) state = store.read_state(server.id) active = vuln_jobs.panel_active(server.id) last = state.get("last") or None last_failed = last if last and last.get("status") == "failed" else None + patch_last = _patch_last(state) # The script re-fetches the table only when this changes, so it holds everything that # changes what the table shows: the match time, a scan starting or ending, the newest scan. key = "|".join([ @@ -251,6 +284,7 @@ def _panel_context(server, profile): "1" if active else "0", str((last or {}).get("scan_id") or ""), str((last or {}).get("status") or ""), + str((patch_last or {}).get("job_id") or ""), ]) tools = vuln_tools.status() windows = _is_windows(server) @@ -260,6 +294,10 @@ def _panel_context(server, profile): # The Windows "software list" is the build and the installed updates; its OS name ends in "build ". found = re.search(r"build\s+(\S+)\s*$", str(summary.get("os_name") or "")) summary = dict(summary, windows_build=found.group(1) if found else (summary.get("os_name") or "")) + if active: + patch = {"offer": False, "url": "", "label": ""} + else: + patch = _patch_offer(server, profile, request) vuln = { "denied": False, "windows": windows, @@ -274,6 +312,8 @@ def _panel_context(server, profile): "last_failed": last_failed, "ever_scanned": bool(summary or last), "active": active, + "patch": patch, + "patch_last": patch_last, "key": key, } if vuln["is_admin"]: @@ -292,7 +332,7 @@ def vuln_panel(request, server_id): return render(request, TEMPLATES + "vuln_panel.html", context) profile = request.get_user_profile() try: - context = _panel_context(server, profile) + context = _panel_context(server, profile, request) except store.StoreError: logger.exception("Vulnerabilities: the state of server %s cannot be read", server.id) context = {"vuln": {"denied": False}, "error": STORE_ERROR} @@ -470,6 +510,30 @@ def _msrc_tile(tools): PROVISION_ERROR = ("The settings were saved, but the scan after provisioning could not be switched. " "The CloudBolt application log has the details.") # shown as a warning, not as a save error +def _resource_patch_action_state(): + """{"exists", "enabled", "action_id"} of the resource action that installs updates on all servers of a + resource, or None when it cannot be read (the patch hooks may not be there yet): unknown is never an error.""" + try: + state = vuln_hooks.resource_patch_action_state() + except Exception: + logger.exception("Vulnerabilities: cannot read the Install Updates on All Servers action") + return None + return state if isinstance(state, dict) else None + + +def _patch_action_state(): + """The Install Updates action's state for the settings page; never raises.""" + try: + return vuln_hooks.patch_action_state() + except Exception: + logger.exception("Vulnerabilities: cannot read the Install Updates action") + return {"exists": False, "enabled": False, "action_id": None} + + +PATCHING_ERROR = ("The settings were saved, but the Install Updates action could not be switched. " + "The CloudBolt application log has the details.") # shown as a warning, not as a save error +RESOURCE_PATCHING_ERROR = ("The settings were saved, but the Install Updates on All Servers action could not be " + "switched. The CloudBolt application log has the details.") SCHEDULES_ERROR = "The schedules cannot be read. The CloudBolt application log has the details." # What each schedule does, in one sentence, by the key ensure_schedules returns. @@ -557,6 +621,7 @@ def settings(request): if key in request.POST: current[key] = request.POST.get(key) else: + was_patching = bool(current.get("patching")) store.save_settings(clean) current = store.get_settings() saved = True @@ -566,7 +631,29 @@ def settings(request): except Exception: logger.exception("Vulnerabilities: cannot update the scan after provisioning action") post_warnings.append(PROVISION_ERROR) + try: + patching = bool(clean["patching"]) + # An unchanged setting must not re-enable an action the admin switched off in the action editor; + # only a missing action (an appliance set up before the resource action existed) is created. + resource_state = _resource_patch_action_state() + missing = (not _patch_action_state()["exists"]) or (resource_state is not None + and not resource_state.get("exists")) + if patching != was_patching or (patching and missing): + # create_only: an unchanged setting creates what is missing and never re-enables an action. + vuln_hooks.apply_patching_setting(patching, create_only=(patching == was_patching)) + except Exception: + logger.exception("Vulnerabilities: cannot update the Install Updates action") + # The wrapper raises when either action could not be switched: name the one that did not follow. + server_state, resource_state = _patch_action_state(), _resource_patch_action_state() + server_off = bool(server_state.get("enabled")) != patching + resource_off = resource_state is not None and bool(resource_state.get("enabled")) != patching + if server_off or not resource_off: + post_warnings.append(PATCHING_ERROR) + if resource_off: + post_warnings.append(RESOURCE_PATCHING_ERROR) context = { + "patch_action": _patch_action_state(), + "resource_patch_action": _resource_patch_action_state() or {"exists": False, "enabled": False, "action_id": None}, "settings": current, "saved": saved, "errors": list(errors.values()), @@ -767,15 +854,6 @@ def vuln_fleet_servers(request): # --------------------------------------------------------------------------- # Resource tab (the findings of one resource's own servers) # --------------------------------------------------------------------------- -# Linux or Windows at the server's own OS family or one or two levels up: the same meaning as -# vuln_jobs.is_linux and vuln_jobs.is_windows (the root families are named Linux and Windows), written -# as a filter so should_display costs one query and no Python loop over the servers. -_SUPPORTED = (Q(os_family__name=vuln_jobs.LINUX_FAMILY) - | Q(os_family__parent__name=vuln_jobs.LINUX_FAMILY) - | Q(os_family__parent__parent__name=vuln_jobs.LINUX_FAMILY) - | Q(os_family__name=WINDOWS_FAMILY) - | Q(os_family__parent__name=WINDOWS_FAMILY) - | Q(os_family__parent__parent__name=WINDOWS_FAMILY)) RESOURCE_NOT_FOUND = "This resource was not found." NOTHING_TO_SCAN = ("None of the servers of this resource can be scanned right now. They may be powered off or in an " "Unassigned group, or you may not have permission to scan them.") @@ -788,7 +866,9 @@ class VulnerabilitiesResourceTabDelegate(TabExtensionDelegate): def should_display(self): try: - servers = self.instance.server_set.exclude(status="HISTORICAL").filter(_SUPPORTED) + # vuln_fleet.supported_q: Linux or Windows at the server's own OS family or one or two levels up, as a + # filter so should_display costs one query and no Python loop over the servers. + servers = self.instance.server_set.exclude(status="HISTORICAL").filter(vuln_fleet.supported_q()) if store.get_settings()["visibility"] == "label": servers = servers.filter(tags__name=vuln_jobs.LABEL) return servers.exists() @@ -853,15 +933,69 @@ def _severity(request): return severity if severity in vuln_match.SEVERITIES else "" +def _resource_patch_offer(resource, profile, request, visibility): + """The Install updates on all servers button of the resource as {"offer", "url", "label"}, or None. + The caller has checked that no run is live and that the viewer sees servers. The action must be enabled and + listed for this resource and permitted to the viewer (vuln_hooks.resource_patch_button) and at least one + server must be patchable by the viewer (any_patchable stops at the first one). Any failure, a missing patch module included, means no button.""" + try: + # Imported here, not at the top: the tab and every other view work whatever happens to this module. + from . import vuln_patch_resource + button = vuln_hooks.resource_patch_button(resource, profile, request) + url = (button or {}).get("url") or "" + if not url or not str(url).startswith("/"): + return None + if not vuln_patch_resource.any_patchable(profile, resource, visibility): + return None + return {"offer": True, "url": url, "label": button.get("label") or ""} + except Exception: + logger.exception("Vulnerabilities: cannot work out the Install updates on all servers button of resource %s", + getattr(resource, "id", "")) + return None + + +def _resource_patch_last(resource_id): + """The record of the last update run of the resource as {at, by, status, updated, restart_pending, failed, + skipped, job_url}, or None; no_updates, the number of servers that had nothing to install, is added when the + record counts it. Any failure means no line.""" + try: + record = store.read_resource_patch(resource_id) + if not isinstance(record, dict) or not record.get("status"): + return None + counts = record.get("counts") if isinstance(record.get("counts"), dict) else {} + + def count(name): + try: + return max(int(counts.get(name) or 0), 0) + except (TypeError, ValueError): + return 0 + + job_url = "" + if record.get("job_id"): + job_url = reverse("job_detail", args=[record["job_id"]]) + return {"at": record.get("at") or "", "by": record.get("by") or "", "status": record["status"], + "updated": count("updated"), "restart_pending": count("restart_pending"), + "failed": count("failed"), "skipped": count("skipped"), "no_updates": count("no_updates"), + "job_url": job_url} + except Exception: + logger.exception("Vulnerabilities: cannot read the update record of resource %s", resource_id) + return None + + @_api def vuln_resource_summary(request, resource_id): - """GET: {state, summary, db_built, run, can_scan} for the viewer's servers of the resource. + """GET: {state, summary, db_built, run, can_scan, patch, patch_last} for the viewer's servers of the resource. summary is vuln_db.set_summary with servers (the same number as scanned, the name the shared script reads) and servers_total (the viewer's servers) added. state is "ready" (at least one server has a software list), "empty" or "unavailable" (a store exists but cannot be read now; the page retries). run is the scan in progress, or null (always null for a viewer who can see none of the resource's servers). can_scan is whether the viewer may scan at least one server (vuln_fleet.any_scannable); it is null while a run is in progress. + patch is the "Install updates on all servers" button, {offer, url, label}, or null: it is set only + when no run is live, the viewer sees servers, the setting is on, the action is enabled, listed for the + resource and permitted to the viewer, and at least one server is patchable by the viewer. patch_last is the + record of the last update run, {at, by, status, updated, restart_pending, failed, skipped, job_url}, or null + (null while a run is live). run.kind is "scan" or "patch". GET ?run=1: only {run}, without touching the findings store: the page polls this every 5 seconds while a scan runs and asks for the full answer when it changes.""" if request.method != "GET": @@ -901,8 +1035,18 @@ def vuln_resource_summary(request, resource_id): can_scan = bool(vuln_fleet.any_scannable(profile, resource, store.get_settings()["visibility"])) except Exception: logger.exception("Vulnerabilities: cannot tell whether the viewer may scan servers of resource %s", resource.id) + patch, patch_last = None, None + if run is None and ids: + patch_last = _resource_patch_last(resource.id) + try: + visibility = store.get_settings()["visibility"] + except Exception: + logger.exception("Vulnerabilities: cannot read the settings") + visibility = None + if visibility is not None: + patch = _resource_patch_offer(resource, profile, request, visibility) return JsonResponse({"state": state, "summary": summary, "db_built": _display_built(db_built), "run": run, - "can_scan": can_scan}) + "can_scan": can_scan, "patch": patch, "patch_last": patch_last}) @_api diff --git a/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_api.py b/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_api.py new file mode 100644 index 00000000..25f2cce2 --- /dev/null +++ b/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_api.py @@ -0,0 +1,217 @@ +""" +Vulnerability scans and updates for other content: start them from a plug-in, and wait for the result or not. + + from xui.io_cloudbolt_vulnerabilities import vuln_api + + result = vuln_api.scan_and_wait(server, job.owner) + result = vuln_api.install_updates(server, job.owner, restart_if_needed=True) + result["status"] "completed", "restart_pending" (updates installed, restart still needed), "failed", + "refused" or "timeout" + result["message"] one sentence for the job output + result["job"] the scan's or the update's own Job, or None + result["scan"] the server's last scan entry (scan_and_wait), or None + result["patch"] the server's last update record (install_updates), or None + + result = vuln_api.install_updates_on_resource(resource, job.owner, restart_if_needed=True) + result["counts"] {"updated", "restart_pending", "failed", "skipped"} servers (install_updates_on_resource) + +Both start the same jobs the Vulnerabilities tab starts, so they take the same lock and land in the server's +history. install_updates installs the updates the server's package manager (Linux) or Windows Update (Windows Server +2022 and 2025) offers, restarts it +when that is needed and restart_if_needed is true, and scans it again. + + result = vuln_api.start_scan(server, job.owner, parent_job=job) + result["status"] "started" or "refused" + +start_scan returns at once. With parent_job the scan is a sub-job of that job: shown under it and cancelled with it. + + ok, reason = eligible(server) (True, "") or (False, one sentence why not) + +install_updates_on_resource installs the updates on every server of one resource, one server at a time, and stops at the +first server that fails. Its status is "completed", "restart_pending" (nothing failed, at least one server still needs a +restart), "failed", "refused" or "timeout". + +eligible says whether content may scan a server now: it is not historical, is not in an Unassigned group, has a +script channel, gets the tab under the "Show the tab on" setting, and the scanner is set up. + +Nothing here checks a permission: the caller is content an administrator put in place, running as a job. Do not call +it from a web request. +""" +from utilities.logger import ThreadLogger + +from . import vuln_fleet, vuln_jobs, vuln_patch, vuln_patch_resource, vuln_store as store + +logger = ThreadLogger(__name__) + +# Added to the time limits of a job when waiting for it: queueing and the upload of the software list. +WAIT_MARGIN_SECONDS = 600 +# The longest install_updates_on_resource waits by default: 7.5 hours. +MAX_RESOURCE_WAIT_SECONDS = 27000 + + +def site_url(): + """The default portal's configured site URL, or "" when it has none.""" + return vuln_fleet.default_base_url() + + +def _result(status, message, job=None, scan=None, patch=None): + return {"status": status, "message": message, "job": job, "scan": scan, "patch": patch} + + +def eligible(server): + """(True, "") when content may scan this server now, else (False, one sentence why not).""" + code = vuln_fleet.eligibility(server, store.get_settings()["visibility"]) + if not code: + code = vuln_fleet.prerequisite_for(server, vuln_fleet.prerequisites(site_url())) + if code: + return False, "the server is {}.".format(vuln_fleet.REASONS.get(code, code)) + return True, "" + + +def start_scan(server, owner, parent_job=None): + """Start a scan of one server and return without waiting for it. owner is the UserProfile the scan job belongs to + (a plug-in passes job.owner).""" + started = vuln_jobs.start(owner, server, site_url(), parent_job=parent_job) + if vuln_fleet._started_id(started) is None: + return _result("refused", started.message) + return _result("started", "The scan of {} started as job {}.".format(server.hostname, started.id), job=started) + + +def _wait(started, timeout): + """The ended Job, or None when it did not end within timeout seconds (Job.wait_for_completion cancels it).""" + from utilities.exceptions import TimeoutException + try: + return started.wait_for_completion(timeout=timeout) + except TimeoutException: + return None + + +def scan_and_wait(server, owner, timeout=None, parent_job=None): + """Scan one server and wait for the scan's job to end. timeout is in seconds; the default is the scan time + limit setting plus ten minutes.""" + started = vuln_jobs.start(owner, server, site_url(), parent_job=parent_job) + if vuln_fleet._started_id(started) is None: + return _result("refused", started.message) + wait = timeout or store.job_settings()["timeout_min"] * 60 + WAIT_MARGIN_SECONDS + job = _wait(started, wait) + if job is None: + return _result("timeout", "The scan of {} did not finish within {} minutes (job {}).".format( + server.hostname, wait // 60, started.id), job=started) + last = _state(server.id).get("last") + scan = last if isinstance(last, dict) and last.get("scan_id") and job.status in ("SUCCESS", "WARNING") else None + if scan is None or scan.get("status") != "completed": + detail = scan.get("error") if scan else vuln_jobs.clean(job.errors or "", vuln_jobs.MESSAGE_LEN) + return _result("failed", "The scan of {} failed (job {}). {}".format(server.hostname, job.id, detail or "").strip(), + job=job, scan=scan) + return _result("completed", "{} scanned: {} known vulnerabilities.".format( + server.hostname, _count(server.id)), job=job, scan=scan) + + +def _state(server_id): + try: + return store.read_state(server_id) + except Exception: + logger.exception("Vulnerabilities: could not read the state of server %s", server_id) + return {} + + +def _count(server_id): + summary = vuln_patch._summary(server_id) + return summary["vulns"] if summary and summary.get("vulns") is not None else "no" + + +def install_updates(server, owner, restart_if_needed=True, timeout=None, parent_job=None): + """Install the updates a Linux or Windows Server 2022/2025 server offers, restart it when needed (restart_if_needed), scan it again, and + wait for the job to end. timeout is in seconds; the default covers the update, the restart wait and the rescan + time limits of the settings.""" + started = vuln_patch.start_job(owner, server=server, restart_if_needed=restart_if_needed, parent_job=parent_job) + if vuln_fleet._started_id(started) is None: + return _result("refused", started.message) + cfg = store.get_settings() + wait = timeout or (vuln_patch._minutes(cfg, "patch_timeout_min", vuln_patch.DEFAULT_PATCH_TIMEOUT_MIN) + + vuln_patch._minutes(cfg, "restart_wait_min", vuln_patch.DEFAULT_RESTART_WAIT_MIN) + + cfg["scan_timeout_min"]) * 60 + WAIT_MARGIN_SECONDS + job = _wait(started, wait) + if job is None: + return _result("timeout", "The update of {} did not finish within {} minutes (job {}).".format( + server.hostname, wait // 60, started.id), job=started) + patch = _state(server.id).get("patch") + if not isinstance(patch, dict) or patch.get("job_id") != job.id: + detail = vuln_jobs.clean(job.errors or "", vuln_jobs.MESSAGE_LEN) + return _result("failed", "The update of {} recorded no result (job {} ended as {}). {}".format( + server.hostname, job.id, job.status, detail).strip(), job=job) + status = patch.get("status") + if status == "failed": + return _result("failed", "The update of {} failed: {}".format(server.hostname, patch.get("message") or + "no reason given"), job=job, patch=patch) + if status == "restart_pending": + return _result("restart_pending", "Updates were installed on {}; a restart is still needed.".format( + server.hostname), job=job, patch=patch) + if status == "no_updates": + return _result("completed", "No updates were available on {}.".format(server.hostname), job=job, patch=patch) + return _result("completed", "Updates were installed on {}{}.".format( + server.hostname, "; it restarted" if patch.get("restarted") else ""), job=job, patch=patch) + + +def install_updates_on_resource(resource, owner, restart_if_needed=True, timeout=None, parent_job=None): + """Install the updates on every server of one resource, one server at a time, and wait for the job to end. + owner is the UserProfile the job belongs to (a plug-in passes job.owner). timeout is in seconds; the default is + the worst case of one server (update, restart wait and rescan limits of the settings) times the servers the + owner may update now, at most 7.5 hours. + + This does no permission check of its own before it starts: the caller is content an administrator put in + place. The job still checks every server as owner (the Install Updates server action must be permitted for + that user on it, and the server must be eligible), skips what fails the checks with a reason, and stops at + the first server whose update fails. The patching setting is enforced by the job. The result is the usual + dict plus counts, from the resource's last update record: {"updated", "restart_pending", "failed", "skipped"}. + Status "completed" does not mean every server was updated: the caller must read counts (updated, no_updates, + restart_pending, failed, skipped) to see what happened to each server. + The status is "restart_pending" when nothing failed and at least one server still needs a restart.""" + started = vuln_patch_resource.start_job(owner, resource, restart_if_needed=restart_if_needed, parent_job=parent_job) + if vuln_fleet._started_id(started) is None: + return dict(_result("refused", started.message), counts=None) + cfg = store.get_settings() + if timeout: + wait = timeout + else: + try: + servers = max(1, len(vuln_patch_resource.patchable_ids(owner, resource, cfg["visibility"]))) + except Exception: + logger.exception("Vulnerabilities: could not count the servers of resource %s", getattr(resource, "id", "")) + servers = 1 + worst = (vuln_patch._minutes(cfg, "patch_timeout_min", vuln_patch.DEFAULT_PATCH_TIMEOUT_MIN) + + vuln_patch._minutes(cfg, "restart_wait_min", vuln_patch.DEFAULT_RESTART_WAIT_MIN) + + cfg["scan_timeout_min"]) * 60 + wait = min(servers * worst + WAIT_MARGIN_SECONDS, MAX_RESOURCE_WAIT_SECONDS) + name = getattr(resource, "name", "") or "the resource" + job = _wait(started, wait) + if job is None: + return dict(_result("timeout", "The update of {} did not finish within {} minutes (job {}).".format( + name, wait // 60, started.id), job=started), counts=None) + record = _resource_patch(resource.id) + if not isinstance(record, dict) or record.get("job_id") != job.id: + detail = vuln_jobs.clean(job.errors or "", vuln_jobs.MESSAGE_LEN) + return dict(_result("failed", "The update of {} recorded no result (job {} ended as {}). {}".format( + name, job.id, job.status, detail).strip(), job=job), counts=None) + counts = record.get("counts") if isinstance(record.get("counts"), dict) else {} + counts = {key: _whole(counts.get(key)) for key in ("updated", "no_updates", "restart_pending", "failed", "skipped")} + note = record.get("message") or "no reason given" + if record.get("status") == "failure" or counts["failed"] > 0: + return dict(_result("failed", "The update of {} failed: {}".format(name, note), job=job), counts=counts) + if counts["restart_pending"] > 0: + return dict(_result("restart_pending", "Updates were installed on the servers of {}; {} still need a " + "restart.".format(name, counts["restart_pending"]), job=job), counts=counts) + return dict(_result("completed", "Updates were installed on the servers of {}: {}".format(name, note), job=job), + counts=counts) + + +def _resource_patch(resource_id): + try: + return store.read_resource_patch(resource_id) + except Exception: + logger.exception("Vulnerabilities: could not read the update record of resource %s", resource_id) + return None + + +def _whole(value): + return value if isinstance(value, int) and not isinstance(value, bool) and value > 0 else 0 diff --git a/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_fleet.py b/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_fleet.py index cbf3c626..86115002 100644 --- a/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_fleet.py +++ b/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_fleet.py @@ -845,6 +845,17 @@ def check(server): "the Vulnerabilities folder.") +def supported_q(): + """The Q that keeps servers of a Linux or Windows OS family (the family itself or one of its two parents + up), the same test the Vulnerabilities views use. Q is imported here so this module still imports + without Django's query layer.""" + from django.db.models import Q + linux, windows = vuln_jobs.LINUX_FAMILY, "Windows" + return (Q(os_family__name=linux) | Q(os_family__parent__name=linux) + | Q(os_family__parent__parent__name=linux) | Q(os_family__name=windows) + | Q(os_family__parent__name=windows) | Q(os_family__parent__parent__name=windows)) + + def resource_servers(resource): """The resource's own servers that are not historical (sub-resources are not included), with what eligibility() reads loaded ahead, ordered by hostname then id.""" @@ -890,8 +901,10 @@ def _live_run(resource_id): def resource_run(resource_id): - """The scan run in progress on the resource: {"job_id", "job_url", "started", "done", "total"}, or None - when there is none (a stale marker, or one that cannot be read, is no run). Never raises.""" + """The run in progress on the resource: {"job_id", "job_url", "started", "done", "total", "kind", "message"} + (kind "scan", or "patch" for the install-updates run of vuln_patch_resource.py; message is the job's + progress text), or None when there is none (a stale marker, or one that cannot be read, is no run). + Never raises.""" try: found = _live_run(resource_id) if found is None: @@ -901,7 +914,8 @@ def resource_run(resource_id): # Job.get_absolute_url (line 1679). total = job.total_tasks or len(marker.get("server_ids") or []) return {"job_id": job.id, "job_url": job.get_absolute_url(), "started": marker.get("started") or "", - "done": job.tasks_done or 0, "total": total} + "done": job.tasks_done or 0, "total": total, "kind": marker.get("kind") or "scan", + "message": vuln_jobs._progress_text(job)} except Exception: logger.exception("Vulnerabilities: could not read the scan run of resource %s", resource_id) return None @@ -934,8 +948,9 @@ def start_resource_scan(profile, resource, server_ids, base_url): with store.resource_lock(resource.id): running = _live_run(resource.id) if running is not None: + doing = "installing updates on" if running[0].get("kind") == "patch" else "scanning" return vuln_jobs.Refusal( - "Job {} is already scanning the servers of this resource.".format(running[1].id), 409) + "Job {} is already {} the servers of this resource.".format(running[1].id, doing), 409) problems = prerequisites(base_url) if nothing_can_run(problems): return vuln_jobs.Refusal(not_ready_message(problems), 409) diff --git a/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_hooks.py b/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_hooks.py index 7be83157..2078a010 100644 --- a/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_hooks.py +++ b/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_hooks.py @@ -78,6 +78,58 @@ "the Vulnerability Settings page." ) +PATCH_NAME = "Vulnerability Install Updates" +PATCH_DESCRIPTION = ( + "Installs the available updates on a Linux or Windows Server 2022 or 2025 server and scans it again, for the Vulnerabilities UI " + "extension. Created by the extension when the setting Offer Install updates is turned on; its code is the " + "extension's vuln_patch_job.py, so do not edit or delete it here." +) +PATCH_FILE = "vuln_patch_job.py" + +CONDITION_NAME = "Vulnerability Install Updates Display Condition" +CONDITION_DESCRIPTION = ( + "Decides which servers show the Install Updates action: Linux and Windows servers that are not in an " + "Unassigned group. Created by the extension; its code is the extension's vuln_patch_condition.py, so do " + "not edit or delete it here." +) +CONDITION_FILE = "vuln_patch_condition.py" + +PATCH_ACTION_LABEL = "Install Updates" +# The spelling of the server actions exported from CloudBolt (server_actions/*/*_metadata.json): Font Awesome +# 5 style and name, as in "fas fa-redo". +PATCH_ACTION_ICON = "fas fa-download" +PATCH_DIALOG_MESSAGE = ( + "Installs all available updates on this server from its configured repositories. The server may restart." +) +PATCH_SUBMIT_LABEL = "Install updates" +# The input is the token in vuln_patch_job.py; core names the HookInput _a. +RESTART_INPUT = "restart_if_needed" +RESTART_LABEL = "Restart if needed" +RESTART_DESCRIPTION = "Restart the server when an update needs it." + +RESOURCE_PATCH_NAME = "Vulnerability Install Updates on All Servers" +RESOURCE_PATCH_DESCRIPTION = ( + "Installs the available updates, one server at a time, on the Linux and Windows servers of one resource, for " + "the Vulnerabilities UI extension. Created by the extension when the setting Offer Install updates is turned " + "on; its code is the extension's vuln_resource_patch_job.py, so do not edit or delete it here." +) +RESOURCE_PATCH_FILE = "vuln_resource_patch_job.py" + +RESOURCE_CONDITION_NAME = "Vulnerability Install Updates on All Servers Display Condition" +RESOURCE_CONDITION_DESCRIPTION = ( + "Decides which resources show the Install Updates on All Servers action: resources with at least one Linux " + "or Windows server that is not in an Unassigned group. Created by the extension; its code is the " + "extension's vuln_resource_patch_condition.py, so do not edit or delete it here." +) +RESOURCE_CONDITION_FILE = "vuln_resource_patch_condition.py" + +RESOURCE_ACTION_LABEL = "Install Updates on All Servers" +RESOURCE_DIALOG_MESSAGE = ( + "Installs all available updates on the servers of this resource, one server at a time. The run stops at the " + "first server that fails. Servers may restart." +) +RESOURCE_SUBMIT_LABEL = "Install updates" + # key, name (the job's and its plugin's), cron text, what the job does in one sentence. SCHEDULES = ( ("rematch", REMATCH_NAME, "0 3 * * *", @@ -138,6 +190,29 @@ def provision_hook(): return _hook(PROVISION_NAME, PROVISION_DESCRIPTION, PROVISION_FILE) +def patch_hook(): + """The install updates plugin, created on first use and kept pointing at vuln_patch_job.py.""" + return _hook(PATCH_NAME, PATCH_DESCRIPTION, PATCH_FILE) + + +def condition_hook(): + """The Display Condition plugin of the Install Updates action, created on first use and kept pointing at + vuln_patch_condition.py.""" + return _hook(CONDITION_NAME, CONDITION_DESCRIPTION, CONDITION_FILE) + + +def resource_patch_hook(): + """The install updates on all servers plugin, created on first use and kept pointing at + vuln_resource_patch_job.py.""" + return _hook(RESOURCE_PATCH_NAME, RESOURCE_PATCH_DESCRIPTION, RESOURCE_PATCH_FILE) + + +def resource_condition_hook(): + """The Display Condition plugin of the Install Updates on All Servers action, created on first use and kept + pointing at vuln_resource_patch_condition.py.""" + return _hook(RESOURCE_CONDITION_NAME, RESOURCE_CONDITION_DESCRIPTION, RESOURCE_CONDITION_FILE) + + # ---------------------------------------------------------------- recurring jobs def _ensure_schedule(key, name, cron, description): """The RecurringActionJob called name, made off when it does not exist. An existing row keeps @@ -261,3 +336,311 @@ def provision_action_state(): except Exception: logger.exception("Vulnerabilities: could not read the Post-Provision action") return {"exists": False, "enabled": False} + + +# ---------------------------------------------------------------- install updates (server action) +def ensure_restart_input(hook): + """The Restart if needed input of the install plugin, as a checkbox. hook.save() already made it as a + text input from the token in vuln_patch_job.py (cbhooks/models.py lines 525-544 and 1836-1854); this + turns it into what core's own actions use (c2_wrapper.py update_or_create_hook_input, lines 1985-2050): + type BOOL, not required, and hide_if_default_value off, because a default would otherwise hide the + control (cbhooks/forms.py lines 1565-1571). It makes the input itself when the token pass did not + (update_action_inputs failures on a first save are only logged, cbhooks/models.py lines 1051-1058). An input + that is already a BOOL is left alone, so a label an admin edited stays.""" + from cbhooks.models import HookInput + + name = "{}_a{}".format(RESTART_INPUT, hook.id) + field = hook.input_fields.filter(name=name).first() + if field is None: + return HookInput.objects.create( + hook=hook, name=name, label=RESTART_LABEL, description=RESTART_DESCRIPTION, type="BOOL", + required=False, hide_if_default_value=False, allow_multiple=False, + ) + if field.type != "BOOL": + field.label = RESTART_LABEL + field.description = RESTART_DESCRIPTION + field.type = "BOOL" + field.required = False + field.hide_if_default_value = False + field.save() + return field + + +def _default_restart_on(action, field): + """Give a newly made action the mapping of the input with the default True (the way c2_wrapper.py + get_or_create_hook_input_mapping, line 1962, does: a default is written only on a mapping that did not + exist, so one an admin changed is never reset). update_input_mappings (cbhooks/models.py line 2107) makes + the mapping; the value is a CustomFieldValue of the input (c2_wrapper.py line 1140).""" + from orders.models import CustomFieldValue + + had = action.input_mappings.filter(hook_input=field).exists() + action.update_input_mappings() + if had: + return + mapping = action.input_mappings.filter(hook_input=field).first() + if mapping is not None and mapping.default_value is None: + mapping.default_value = CustomFieldValue.objects.get_or_create(field=field, value=True)[0] + mapping.save() + + +def patch_actions(hook): + """The server actions that run the install plugin (normally one).""" + from cbhooks.models import ServerAction + + return list(ServerAction.objects.filter(hook=hook)) + + +def _apply_server_action(enabled, create_only=False): + """Make the Install Updates server action match the patching setting. On: make the plugin, its Restart + if needed input with the default True, the Display Condition and the action when the action does not + exist; an existing one is only switched on. Off: switch an existing action off and nothing else. + + The caller decides when to call it (the settings view calls it on a change to on, or when the action is + missing); calling it with an existing, switched-off action switches it on, unless create_only is true: then + an existing action is left exactly as it is and only a missing one is made. + + Everything an admin owns on the action is written only when it is first made and never again: label, + Requires approval, Auto submit order, the condition, the role grants and the default of the input. + The OS families of the plugin are never touched either: the condition hides the action, and step 3 + (Windows) must need no database change. Raises RuntimeError when the action could not be made or changed.""" + from cbhooks.models import ServerAction + + try: + if not enabled: + hook = CloudBoltHook.objects.filter(name=PATCH_NAME).first() + if hook is None: + return + for action in patch_actions(hook): + if action.enabled: + action.enabled = False + action.save() + return + + hook = patch_hook() + actions = patch_actions(hook) + if not actions: + field = ensure_restart_input(hook) + condition = condition_hook() + with transaction.atomic(): + # ServerAction.hook is not unique, so two first enables could each make an action. A row lock + # on the plugin (select_for_update, valid inside this atomic block) makes the second one wait, + # and it looks again before making one. + CloudBoltHook.objects.select_for_update().filter(pk=hook.pk).first() + if patch_actions(hook): + return + # The fields core sets when it makes a server action (c2_wrapper.py line 1878, ServerAction in + # cbhooks/models.py line 2970): the plugin, a label, enabled and the dialog texts. A button for + # every server needs no targets (infrastructure/models.py lines 3736-3741). is_synchronous stays + # False because synchronous plus approval is refused (cbhooks/views.py line 3114). + action = ServerAction.objects.create( + hook=hook, label=PATCH_ACTION_LABEL, enabled=True, extra_classes=PATCH_ACTION_ICON, + submit_button_label=PATCH_SUBMIT_LABEL, dialog_message=PATCH_DIALOG_MESSAGE, + is_synchronous=False, condition=condition, + ) + _default_restart_on(action, field) + return + if create_only: + return + for action in actions: + if not action.enabled: + action.enabled = True + action.save() + except Exception as exc: + logger.exception("Vulnerabilities: could not switch the Install Updates action") + raise RuntimeError("The Install Updates action could not be switched.") from exc + + +def patch_action_state(): + """{"exists": bool, "enabled": bool, "action_id": int or None} for the Install Updates action. Reads only; + never makes it and never raises.""" + try: + hook = CloudBoltHook.objects.filter(name=PATCH_NAME).first() + if hook is None: + return {"exists": False, "enabled": False, "action_id": None} + actions = patch_actions(hook) + if not actions: + return {"exists": False, "enabled": False, "action_id": None} + chosen = next((a for a in actions if a.enabled), actions[0]) + return {"exists": True, "enabled": bool(chosen.enabled), "action_id": chosen.pk} + except Exception: + logger.exception("Vulnerabilities: could not read the Install Updates action") + return {"exists": False, "enabled": False, "action_id": None} + + +def patch_button(server, profile, request=None): + """{"url", "label", "action_id"} of the Install Updates button for this server and user, or None. Only + when the setting is on, the action is enabled, its Display Condition accepts the server (server_action_dict + returns None otherwise, cbhooks/models.py line 3257) and the user may run it (server_action_permitted, + utilities/permissions.py line 437). Never raises.""" + try: + from utilities.permissions import server_action_permitted + from . import vuln_store + + if not vuln_store.get_settings().get("patching"): + return None + hook = CloudBoltHook.objects.filter(name=PATCH_NAME).first() + if hook is None: + return None + for action in patch_actions(hook): + if not action.enabled: + continue + shown = action.server_action_dict(server, request) + if not shown or not shown.get("url"): + continue + if not server_action_permitted(profile, server, action): + continue + return {"url": shown["url"], "label": action.label or PATCH_ACTION_LABEL, "action_id": action.pk} + return None + except Exception: + logger.exception("Vulnerabilities: could not work out the Install Updates button for server %s", + getattr(server, "id", "")) + return None + + +# ---------------------------------------------------------------- install updates on all servers (resource action) +def resource_patch_actions(hook): + """The resource actions that run the install on all servers plugin (normally one).""" + from cbhooks.models import ResourceAction + + return list(ResourceAction.objects.filter(hook=hook)) + + +def _apply_resource_action(enabled, create_only=False): + """Make the Install Updates on All Servers resource action match the patching setting, under the rules of + _apply_server_action: made once, then only switched on and off through enabled. Its plugin, its Restart if + needed input with the default True and its Display Condition are made with it. + + ResourceAction has no resource type field and blueprints stays empty (cbhooks/models.py line 2683: none + selected means every resource), so the action is offered to every resource and the condition decides + (resources/models.py available_actions, lines 525-535). list_view_visible is False so it is not offered + for a bulk run from a list (cbhooks/models.py line 2721); an admin may change that. Label, Requires approval, + Auto submit order, the condition, list_view_visible, the role grants and the default of the input are written + only when the action is made. Raises RuntimeError when it could not be made or changed.""" + from cbhooks.models import ResourceAction + + try: + if not enabled: + hook = CloudBoltHook.objects.filter(name=RESOURCE_PATCH_NAME).first() + if hook is None: + return + for action in resource_patch_actions(hook): + if action.enabled: + action.enabled = False + action.save() + return + + hook = resource_patch_hook() + actions = resource_patch_actions(hook) + if not actions: + field = ensure_restart_input(hook) + condition = resource_condition_hook() + with transaction.atomic(): + # ResourceAction.hook is not unique either: the row lock on the plugin makes a second first + # enable wait and look again before it makes one. + CloudBoltHook.objects.select_for_update().filter(pk=hook.pk).first() + if resource_patch_actions(hook): + return + # The idiom of cbhooks/views.py line 4039 (hook, enabled, label) plus the dialog texts and the + # icon, as the server action. is_synchronous stays False because synchronous plus approval is + # refused for resource actions (cbhooks/views.py line 4119). + action = ResourceAction.objects.create( + hook=hook, label=RESOURCE_ACTION_LABEL, enabled=True, extra_classes=PATCH_ACTION_ICON, + submit_button_label=RESOURCE_SUBMIT_LABEL, dialog_message=RESOURCE_DIALOG_MESSAGE, + is_synchronous=False, list_view_visible=False, condition=condition, + ) + _default_restart_on(action, field) + return + if create_only: + return + for action in actions: + if not action.enabled: + action.enabled = True + action.save() + except Exception as exc: + logger.exception("Vulnerabilities: could not switch the Install Updates on All Servers action") + raise RuntimeError("The Install Updates on All Servers action could not be switched.") from exc + + +def apply_patching_setting(enabled, create_only=False): + """Make both Install Updates actions match the patching setting: the server action and the resource action + Install Updates on All Servers. Each half runs in its own try, so one failing does not hide the other; a + RuntimeError is raised afterwards when either failed. create_only leaves existing actions as they are and + only makes missing ones: the settings view passes it when the setting did not change, so an action an admin + switched off in the action editor stays off while a missing one (an appliance that had the server action + before the resource action existed) is made.""" + failed = [] + for name, apply in (("server", _apply_server_action), ("resource", _apply_resource_action)): + try: + apply(enabled, create_only=create_only) + except Exception: + failed.append(name) + if failed: + raise RuntimeError("The Install Updates {} action could not be switched.".format(" and ".join(failed))) + + +def resource_patch_action_state(): + """{"exists": bool, "enabled": bool, "action_id": int or None} for the Install Updates on All Servers action. + Reads only; never makes it and never raises.""" + try: + hook = CloudBoltHook.objects.filter(name=RESOURCE_PATCH_NAME).first() + if hook is None: + return {"exists": False, "enabled": False, "action_id": None} + actions = resource_patch_actions(hook) + if not actions: + return {"exists": False, "enabled": False, "action_id": None} + chosen = next((a for a in actions if a.enabled), actions[0]) + return {"exists": True, "enabled": bool(chosen.enabled), "action_id": chosen.pk} + except Exception: + logger.exception("Vulnerabilities: could not read the Install Updates on All Servers action") + return {"exists": False, "enabled": False, "action_id": None} + + +def resource_patch_button(resource, profile, request=None): + """{"url", "label", "action_id"} of the Install Updates on All Servers dialog for this resource and user, or + None. Only when the setting is on, the action is enabled, core lists it for this resource + (Resource.available_actions, resources/models.py line 443, which applies the blueprint, plug-in and Display + Condition rules and builds the dialog URL with reverse("run_resource_action", ...)) and the user may run it + (resource_action_permitted, utilities/permissions.py line 527). An action an admin turned into a new-tab + link has no dialog and gives None. Never raises.""" + try: + from utilities.permissions import resource_action_permitted + from . import vuln_store + + if not vuln_store.get_settings().get("patching"): + return None + hook = CloudBoltHook.objects.filter(name=RESOURCE_PATCH_NAME).first() + if hook is None: + return None + mine = {action.pk: action for action in resource_patch_actions(hook) if action.enabled} + if not mine: + return None + for shown in resource.available_actions(request): + action = mine.get(getattr(shown.get("action"), "pk", None)) + if action is None or shown.get("not_dialog") or not shown.get("url"): + continue + if not resource_action_permitted(profile, resource, action): + continue + return {"url": shown["url"], "label": action.label or RESOURCE_ACTION_LABEL, "action_id": action.pk} + return None + except Exception: + logger.exception("Vulnerabilities: could not work out the Install Updates on All Servers button for " + "resource %s", getattr(resource, "id", "")) + return None + + +def server_patch_permitted(profile, server): + """True when the enabled Install Updates server action is permitted for this user on this server + (server_action_permitted, utilities/permissions.py line 437). The resource action's job asks this for every + server, because core's check for a resource action says nothing about the servers inside it. Never raises.""" + try: + from utilities.permissions import server_action_permitted + + hook = CloudBoltHook.objects.filter(name=PATCH_NAME).first() + if hook is None: + return False + return any(server_action_permitted(profile, server, action) + for action in patch_actions(hook) if action.enabled) + except Exception: + logger.exception("Vulnerabilities: could not check the Install Updates permission for server %s", + getattr(server, "id", "")) + return False diff --git a/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_jobs.py b/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_jobs.py index a15606e3..70ef1f97 100644 --- a/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_jobs.py +++ b/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_jobs.py @@ -68,6 +68,8 @@ LINUX_FAMILY = "Linux" LABEL = "Vulnerabilities" SCAN_PERMISSION = "server.all_actions" +# The "kind" of the active marker the update job (vuln_patch.py) writes; a scan's marker has none. +PATCH_KIND = "patch" # Bounds on everything parsed from the server's output. MAX_OUTPUT = 256 * 1024 @@ -597,11 +599,15 @@ def panel_active(server_id): if found is None: return None marker, job = found + # A marker without a kind is a scan; the update job (vuln_patch.py) writes kind "patch". + patching = marker.get("kind") == PATCH_KIND return { "job_id": job.id, "job_url": job.get_absolute_url(), "message": _progress_text(job), "started": marker.get("started") or "", + "kind": PATCH_KIND if patching else "scan", + "title": "Installing updates" if patching else "Scan running", } @@ -624,11 +630,10 @@ def _in_cooldown(last): return age is not None and age < COOLDOWN_S -def start(profile, server, base_url, parent_job=None): - """Validate and start the scan. base_url is the default portal's configured - site URL (never a request's Host). profile is the requesting UserProfile, or - None for a scan started by a recurring job (the job's owner is empty then). Returns - the Job, or a Refusal.""" +def precheck(server, base_url): + """The Refusal for a server that cannot be scanned (or updated and then scanned) right now, or None. The + checks that need no lock and no state: the server's status, group, OS, power, and what its kind needs + (the scanner and the site URL, or the Microsoft security data). start() and the update job call it.""" if server.status == "HISTORICAL": return Refusal("This server is historical.") if server.status != "ACTIVE": @@ -650,6 +655,27 @@ def start(profile, server, base_url, parent_job=None): return Refusal(NOT_SET_UP, 409) if not base_url: return Refusal(NO_SITE_URL, 409) + return None + + +def _is_handover(marker, handover_from): + """True when the running marker is the update job named by handover_from (a Job id).""" + return bool(handover_from) and marker.get("kind") == PATCH_KIND and marker.get("job_id") == handover_from + + +def start(profile, server, base_url, parent_job=None, handover_from=None): + """Validate and start the scan. base_url is the default portal's configured + site URL (never a request's Host). profile is the requesting UserProfile, or + None for a scan started by a recurring job (the job's owner is empty then). Returns + the Job, or a Refusal. + + handover_from is the id of the update job (vuln_patch.py) that holds the server's active marker and + starts this scan as its last step. Then the running marker is accepted only when it is that job's, the + cooldown does not apply, and the marker stays: the tab keeps showing the update's progress until the + update job ends and clears it. Any other running job refuses the start, as it always did.""" + refusal = precheck(server, base_url) + if refusal is not None: + return refusal cfg = store.job_settings() try: # One start at a time per server: the active check, the queueing and @@ -657,6 +683,10 @@ def start(profile, server, base_url, parent_job=None): with store.start_lock(server.id): state = store.read_state(server.id) running = active_job(server.id, state) + if handover_from: + if running is None or not _is_handover(running[0], handover_from): + return Refusal("The update job no longer holds this server, so the scan was not started.", 409) + return _queue(profile, server, cfg, base_url, parent_job, keep_active=True) if running is not None: return Refusal( "Job {} is still running on this server; wait for it to finish.".format(running[1].id), 409 @@ -694,8 +724,8 @@ def _requested_by(profile): return str(profile.user.username) if getattr(profile, "user", None) else str(profile) -def _queue(profile, server, cfg, base_url, parent_job): - """The queued Job, or a Refusal.""" +def _queue(profile, server, cfg, base_url, parent_job, keep_active=False): + """The queued Job, or a Refusal. keep_active leaves the server's active marker as it is (the update job's).""" scan_id = store.new_scan_id() windows = is_windows(server) pull = _is_openshift_vm(server) @@ -742,12 +772,13 @@ def _queue(profile, server, cfg, base_url, parent_job): server.jobs.add(job) except Exception: logger.exception("Vulnerabilities: could not label or link job %s", job.id) - try: - store.set_active(server.id, { - "job_id": job.id, "scan_id": scan_id, "started": started, "requested_by": requested_by, - }) - except Exception: - logger.exception("Vulnerabilities: could not record job %s as active on server %s", job.id, server.id) + if not keep_active: + try: + store.set_active(server.id, { + "job_id": job.id, "scan_id": scan_id, "started": started, "requested_by": requested_by, + }) + except Exception: + logger.exception("Vulnerabilities: could not record job %s as active on server %s", job.id, server.id) return job diff --git a/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_patch.py b/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_patch.py new file mode 100644 index 00000000..9ab83725 --- /dev/null +++ b/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_patch.py @@ -0,0 +1,1160 @@ +""" +Installing updates on a server, then scanning it again. + +start_job() runs in the web request or in another job. It checks every server and starts the plugin from +vuln_hooks.py (vuln_patch_job.py) with OrchestrationHook.run_as_job. CloudBolt itself starts the same plugin when a +person chooses the Install Updates server action; the dialog's "Restart if needed" input reaches run_patch as the +keyword restart_if_needed. + +run_patch() runs inside that job. Servers go one at a time. For each one, _patch_one: + 1. takes the server's start lock and refuses when a scan or another update holds the server (the active + marker, kind "patch"), then writes its own marker, so the tab shows the update's progress; + 2. remembers the vulnerability counts of the last scan (None when the server was never scanned) and the + server's boot id; + 3. starts the update on the server as a background worker (vuln_patch.sh, or vuln_patch_windows.ps1 as a + SYSTEM scheduled task through vuln_wintask.py) and polls it every POLL_S (WIN_POLL_S) seconds; + 4. when the server needs a restart and the person allowed it, restarts it and waits until the boot id + changes, then (Linux) removes old kernels; without permission the run ends "restart_pending"; + 5. scans the server again as a child job (vuln_jobs.start with handover_from: the update's marker stays and + the scan is let in), then writes the result to the server's state file under "patch". +A step that fails ends that server only; the next server still runs. A server that the update finished but whose +rescan failed is "updated" with a warning, never a failure. + +All the Linux-specific work (the guest script, the calls, the parsing) is in the functions whose names start +with _linux_, all the Windows-specific work in those that start with _windows_; _patch_one only dispatches on the +server's family. Windows Server 2022 and 2025 are supported (the builds of vuln_msrc.PRODUCTS, because the rescan +cannot match any other), and only when no Configuration Manager client (the CcmExec service) manages the server. + +A cancel of the job leaves the update running on the server: a package transaction is never stopped midway. +Nothing user-controlled reaches a shell: the Linux script gets a header of shlex-quoted values (a run id checked +against a pattern, a UUID boot id, whole numbers), never string-formatted input; the Windows scripts get only a +validated run id and whole numbers. +""" +import os +import re +import shlex +import time +from datetime import datetime + +from utilities.events import add_server_event +from utilities.logger import ThreadLogger + +from . import vuln_db, vuln_fleet, vuln_hooks, vuln_jobs, vuln_msrc, vuln_store as store, vuln_wintask + +logger = ThreadLogger(__name__) + +SCRIPT_FILE = "vuln_patch.sh" +WIN_SCRIPT_FILE = "vuln_patch_windows.ps1" +PATCH_KIND = vuln_jobs.PATCH_KIND + +# Seconds between two looks at a running update, and how many looks in a row may fail (a server restarting +# for the update itself, a network blip) before the update counts as lost. +POLL_S = 15 +LOST_POLLS = 20 +# Seconds between two looks at a server that is restarting. +PROBE_S = 15 +# Seconds the server waits before it restarts itself, on both systems: AWS Systems Manager reads a command's result +# a fixed 5 seconds after it is sent, so a shorter delay can take the server down before the reply is read. +REBOOT_DELAY_S = 20 +# The Windows engine: seconds between two polls of the status file and between two probes of a restarting server +# (a call through Systems Manager or Run Command adds 5 to 60 seconds), the restart delay, and how far apart two +# boot times may be and still be the same boot (the value is derived from the clock and can move by seconds). +WIN_POLL_S = 20 +WIN_PROBE_S = 20 +WIN_REBOOT_DELAY_S = 20 +BOOT_TOLERANCE_S = 10 +# A moved boot id counts as a restart only when the server also reports an uptime shorter than the time since the +# job read the old boot id plus this many seconds: a clock step moves the boot id but not the uptime. +UPTIME_SLACK_S = 120 +# Successful probes in a row that still show the old boot id before a reboot call that raised is sent again, and +# before the restart is given up as not started. +RESTART_UNCHANGED_PROBES = 3 +# The most a start, poll, probe or reboot call may take, and the removal of old kernels. +CALL_TIMEOUT = 60 +OLD_KERNELS_TIMEOUT = 15 * 60 +# Added to the scan time limit when a job waits for the rescan: queueing and the upload. +WAIT_MARGIN_S = 600 +DEFAULT_PATCH_TIMEOUT_MIN = 90 +DEFAULT_RESTART_WAIT_MIN = 60 +MESSAGE_LEN = 300 +# CloudBolt cancels any job that runs 8 hours (vuln_fleet.JOB_BUDGET_S); a server is started only when its +# worst case (the update time limit, the restart wait and this margin for the rescan) still ends before 7.5 hours. +JOB_LIMIT_S = int(7.5 * 3600) +RESCAN_MARGIN_MIN = 30 + +MODES = ("start", "poll", "probe", "reboot", "oldkernels", "cleanup") +KNOWN_KEYS = ("os", "distro", "state", "phase", "updated", "failed", "exit", "removed", "failure", "detail", "reason", + "note", + "restart", "restart_reason", "boot_id", "kernel_running", "kernel_newest", "done") +STATES = ("running", "done", "died", "missing") +DISTROS = ("rhel", "ol", "amzn2023", "ubuntu") +MAX_NOTES = 5 +# The guest sends up to this many "detail" lines after a failure; the job output and errors carry at most +# DETAIL_TOTAL characters of them. +MAX_DETAIL = 12 +DETAIL_TOTAL = 2000 +MAX_COUNT = 10 ** 6 +RUN_ID_RE = re.compile(r"[A-Za-z0-9-]{8,64}") +BOOT_ID_RE = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") +# A Windows boot id: the last boot time in UTC, yyyyMMddHHmmss. +BOOT_RE = re.compile(r"[0-9]{14}") +BOOT_FORMAT = "%Y%m%d%H%M%S" +WIN_KEYS = ("phase", "found", "skipped", "item", "updated", "failed", "result", "hresult", "restart", + "restart_before", "more", "failure", "reason", "note", "done") +HRESULT_RE = re.compile(r"0x[0-9A-Fa-f]{8}") +KB_RE = re.compile(r"KB[0-9]{4,9}") +MAX_ITEMS = 50 +MAX_FAILED_LISTED = 5 + +ONLY_SUPPORTED = "only Linux and Windows Server 2022 and 2025 servers are supported" +ONLY_SERVER = "Only Windows Server 2022 and 2025 are supported." +RESTART_NOT_STARTED = "The restart could not be started." +OLD_KERNELS_KEPT = "Old kernels were kept." +GUEST_KEEPS_RUNNING = "The job was canceled. An update already started on a server keeps running there until it ends." +CALL_FAILED = "The server could not be reached" +PATCHING_OFF = "Installing updates is turned off in Vulnerability Settings." +OLDER_KERNEL = "Restarted, but the server is still running the older kernel." +CHECK_PACKAGE_MANAGER = ("Check the package manager on the server (dnf history, or dpkg --configure -a) before " + "trying again.") +STOPPED = "The update stopped before it finished. " + CHECK_PACKAGE_MANAGER +CHECK_WINDOWS_UPDATE = "Check Windows Update on the server before trying again." +STOPPED_WINDOWS = "The update stopped before it finished. " + CHECK_WINDOWS_UPDATE +RESTARTED_WINDOWS = "The server restarted during the update and the update reported no result." +CCM_REFUSED = "This server is patched by Configuration Manager." + + +class PatchFailed(Exception): + """A step of an update failed; the message is safe to store and show. facts carries what was learned before + the failure (the install's counts), for the record.""" + + def __init__(self, message="", facts=None): + super().__init__(message) + self.facts = facts or {} + + +class CallFailed(Exception): + """A call to the server did not go through (the transport, a timeout, the script could not run); the message + says why and is safe to store.""" + + +# ---------------------------------------------------------------- small helpers +def parse_restart_flag(value, default=True): + """The "Restart if needed" input as a bool. It arrives as a bool from the dialog and as text from a default + set through the API or MCP, or from a dropdown ("True", "false", "0"); anything else is the default.""" + if isinstance(value, bool): + return value + if value is None: + return default + text = str(value).strip().lower() + if text in ("true", "1", "yes", "y", "on", "t"): + return True + if text in ("false", "0", "no", "n", "off", "f"): + return False + return default + + +def _sleep(seconds): + time.sleep(seconds) + + +def _clock(): + """Seconds on a clock that only moves forward; the job measures its time limits with it.""" + return time.monotonic() + + +def _progress(job, message): + vuln_fleet._progress(job, message) + + +def _why(code): + """One phrase for an eligibility code.""" + return vuln_fleet.REASONS.get(code, code) + + +def _minutes(cfg, key, default): + try: + return max(1, int(cfg.get(key) or default)) + except (TypeError, ValueError): + return default + + +def eligibility(server, problems=None): + """"" when updates may be installed on the server now, else a reason code (vuln_fleet.REASONS): the codes + of vuln_fleet.eligibility, unsupported_os for anything but Linux or Windows, and what a rescan of this kind of + server needs (not_set_up, no_site_url, no_windows_data), because a rescan that cannot run is not allowed to + follow an install. problems is vuln_fleet.prerequisites(), when the caller has it. No remote call: the Windows + build and the Configuration Manager check are made on the server, when the update starts.""" + try: + if not (vuln_jobs.is_linux(server) or vuln_jobs.is_windows(server)): + return "unsupported_os" + code = vuln_fleet.eligibility(server, store.get_settings()["visibility"]) + if code: + return code + if problems is None: + problems = vuln_fleet.prerequisites(vuln_fleet.default_base_url()) + return vuln_fleet.prerequisite_for(server, problems) + except Exception: + logger.exception("Vulnerabilities: could not check whether server %s may be updated", getattr(server, "id", "")) + return "unknown" + + +def patching_enabled(): + """True when the "patching" setting is on. An unreadable setting counts as off.""" + try: + return bool(store.get_settings().get("patching")) + except Exception: + logger.exception("Vulnerabilities: could not read the patching setting") + return False + + +def record_patch(server_id, record): + """Write the server's last update (the shape in the module docstring) to its state file, next to the last + scan. vuln_store keeps keys it does not know.""" + store._update(server_id, lambda state: state.__setitem__("patch", record)) + + +def _summary(server_id): + """{"vulns", "vuln_fixable"} from the findings store, or None when the server has no scan.""" + try: + row = vuln_db.server_summary(server_id) + except Exception: + logger.exception("Vulnerabilities: could not read the summary of server %s", server_id) + return None + if not isinstance(row, dict): + return None + return {"vulns": row.get("vulns"), "vuln_fixable": row.get("vuln_fixable")} + + +# ---------------------------------------------------------------- start +def start_job(owner, server=None, restart_if_needed=True, parent_job=None, servers=None): + """Check the server (or the list given as servers) and start the update job. owner is the requesting + UserProfile. Returns the Job, or a vuln_jobs.Refusal for the first server that cannot be updated. No permission + check: the caller has made it.""" + if not patching_enabled(): + return vuln_jobs.Refusal(PATCHING_OFF, 403) + targets = list(servers) if servers is not None else ([server] if server is not None else []) + if not targets: + return vuln_jobs.Refusal("No server was given.") + base_url = vuln_fleet.default_base_url() + problems = vuln_fleet.prerequisites(base_url) + for target in targets: + code = eligibility(target, problems) + if code: + return vuln_jobs.Refusal("{} cannot be updated: {}.".format(target.hostname, _why(code)), 409) + refusal = vuln_jobs.precheck(target, base_url) + if refusal is not None: + return refusal + created = vuln_hooks.patch_hook().run_as_job( + owner=owner, + servers=targets, + parent_job=parent_job, + context={"restart_if_needed": bool(parse_restart_flag(restart_if_needed))}, + ) + if not created: + return vuln_jobs.Refusal("CloudBolt did not start the job; see the application log.", 500) + job = created[0] + # From here the job is queued: nothing below may turn into an error. + try: + job.label = "Install updates: {}".format(targets[0].hostname if len(targets) == 1 + else "{} servers".format(len(targets))) + job.save(update_fields=["label"]) + for target in targets: + target.jobs.add(job) + except Exception: + logger.exception("Vulnerabilities: could not label or link job %s", job.id) + return job + + +# ---------------------------------------------------------------- the guest script +def _linux_build_script(mode, run_id, boot_id=""): + """The script to run: the sh launcher around a header of quoted assignments and vuln_patch.sh. The run id + and the boot id are checked here; the script checks them again.""" + if mode not in MODES: + raise PatchFailed("The update script has no mode {}.".format(mode)) + if not RUN_ID_RE.fullmatch(str(run_id or "")): + raise PatchFailed("The run id has characters that are not allowed.") + if boot_id and not BOOT_ID_RE.fullmatch(str(boot_id)): + raise PatchFailed("The boot id has characters that are not allowed.") + values = [("MODE", mode), ("RUN_ID", run_id), ("BOOT_ID", boot_id or ""), ("REBOOT_DELAY_S", str(REBOOT_DELAY_S))] + header = "".join("{}={}\n".format(name, shlex.quote(str(value))) for name, value in values) + path = os.path.join(os.path.dirname(os.path.abspath(__file__)), SCRIPT_FILE) + with open(path, encoding="utf-8", newline="") as handle: + body = handle.read().replace("\r\n", "\n") + return vuln_jobs._launcher("#!/bin/bash\n" + header + body) + + +def _linux_parse(text): + """The CBVULN|key|value lines of the script's output as one dict. Only known keys are read; a later line + wins; text is cleaned and capped, counts are whole numbers within bounds (else None), state, distro and + restart must be one of their listed values, the boot id a UUID.""" + result = { + "os": "", "distro": "", "state": "", "phase": "", "updated": None, "failed": None, "exit": None, + "removed": None, "failure": "", "details": [], "reason": "", "notes": [], "restart": "", "restart_reason": "", + "boot_id": "", "kernel_running": "", "kernel_newest": "", "done": False, + } + for raw in vuln_jobs._bounded(text).splitlines(): + line = raw.strip() + if not line.startswith("CBVULN|"): + continue + parts = line.split("|", 2) + if len(parts) < 3 or parts[1] not in KNOWN_KEYS: + continue + key, value = parts[1], parts[2].strip() + if key in ("updated", "failed", "removed"): + result[key] = vuln_jobs._int(value, MAX_COUNT) + elif key == "exit": + result[key] = vuln_jobs._int(value, 1000) + elif key == "state": + result[key] = value if value in STATES else "" + elif key == "distro": + result[key] = value if value in DISTROS else "" + elif key == "restart": + result[key] = value if value in ("0", "1", "unknown") else "" + elif key == "boot_id": + result[key] = value if BOOT_ID_RE.fullmatch(value) else "" + elif key == "note": + if len(result["notes"]) < MAX_NOTES: + result["notes"].append(vuln_jobs.clean(value, MESSAGE_LEN)) + elif key == "detail": + if len(result["details"]) < MAX_DETAIL: + result["details"].append(vuln_jobs.clean(value, MESSAGE_LEN)) + elif key == "done": + result["done"] = True + elif key in ("failure", "reason"): + result[key] = vuln_jobs.clean(value, MESSAGE_LEN) + else: + result[key] = vuln_jobs.clean(value, 120) + # A detail line that repeats the failure line or an earlier detail line says nothing new. + seen = {result["failure"]} + unique = [] + for line in result["details"]: + if line and line not in seen: + seen.add(line) + unique.append(line) + result["details"] = unique + return result + + +parse_patch_output = _linux_parse + + +def _minutes_text(minutes): + """"1 minute", "20 minutes": a count and its noun for plain-text job output.""" + minutes = int(minutes) + return "{} minute{}".format(minutes, "" if minutes == 1 else "s") + + +def _cap(text, limit): + """text cut to at most limit characters at a word boundary, with ... (ASCII) when it was cut.""" + if len(text) <= limit: + return text + cut = text[:max(0, limit - 3)] + space = cut.rfind(" ") + if space > 0: + cut = cut[:space] + return cut.rstrip(" ,;:") + "..." + + +def _failure_message(prefix, failure, details): + """The record message of a failed install: the failure line followed by the first detail line that adds + something (details are already free of repeats), cleaned and at most MESSAGE_LEN characters in all.""" + text = "{} {}".format(prefix, failure or "no reason was reported.") + if details: + text += " " + details[0] + return _cap(vuln_jobs.clean(text, 10 * MESSAGE_LEN), MESSAGE_LEN) + + +def _detail_text(lines): + """The guest's detail lines as one text for the job output and errors, at most DETAIL_TOTAL characters.""" + return "\n".join(line for line in (lines or []) if line)[:DETAIL_TOTAL] + + +def _linux_call(server, mode, run_id, boot_id="", timeout=CALL_TIMEOUT, job=None): + """Run one mode of the script on the server and return the parsed output. Raises CallFailed when the call + does not go through or the output is cut off before the script's last line.""" + script = _linux_build_script(mode, run_id, boot_id) + try: + output = vuln_jobs._execute(server, script, timeout, job) + except vuln_jobs.TransportError as exc: + raise CallFailed(vuln_jobs.clean(str(exc), MESSAGE_LEN)) + except NotImplementedError: + raise CallFailed("This server's resource handler cannot run scripts on servers.") + except Exception as exc: + # A script that exits non-zero or times out raises, with its output on the exception. + if hasattr(exc, "output"): + raise CallFailed(vuln_jobs.clean(str(exc), MESSAGE_LEN) or CALL_FAILED) + logger.exception("Vulnerabilities: calling the update script on server %s failed", server.id) + raise CallFailed("The script could not be run on the server. The CloudBolt job log has the details.") + if isinstance(output, bytes): + output = output.decode("utf-8", errors="replace") + parsed = _linux_parse(str(output or "")) + if not parsed["done"] and not parsed["reason"]: + raise CallFailed("The server's answer was cut off.") + return parsed + + +def _linux_cleanup(server, run_id): + """Remove the run folder on the server. Best effort: a server that cannot be reached keeps it, and the next + update removes folders older than three days.""" + try: + _linux_call(server, "cleanup", run_id) + except Exception: + logger.info("Vulnerabilities: the run folder of the update on server %s was not removed", server.id) + + +# ---------------------------------------------------------------- the update on one server +def _linux_wait_for_install(job, server, run_id, limit_s): + """Poll the update until the worker is done. Returns the last poll's parsed output. Raises PatchFailed when + the worker died or is gone, when CloudBolt lost contact for LOST_POLLS looks in a row, or at the limit.""" + began = _clock() + lost = 0 + while True: + _sleep(POLL_S) + if _clock() - began > limit_s: + raise PatchFailed("The update did not finish within {} and may still be running on the server; " + "another update there is refused until it ends. {}".format( + _minutes_text(limit_s // 60), CHECK_PACKAGE_MANAGER)) + try: + polled = _linux_call(server, "poll", run_id, job=job) + except CallFailed as exc: + polled, problem = None, str(exc) + else: + problem = "" + if polled["state"] not in STATES: + polled, problem = None, "the server's answer had no state" + if polled is None: + lost += 1 + if lost >= LOST_POLLS: + raise PatchFailed("CloudBolt lost contact with the server for {} checks in a row ({}). {}".format( + LOST_POLLS, problem, CHECK_PACKAGE_MANAGER)) + continue + lost = 0 + if polled["phase"]: + _progress(job, "{}: {}".format(server.hostname, polled["phase"])) + if polled["state"] == "done": + return polled + if polled["state"] in ("died", "missing"): + raise PatchFailed(STOPPED, _facts_of(polled)) + + +def _facts_of(polled): + return {"updated": polled["updated"], "failed": polled["failed"]} + + +def _linux_restart(job, server, run_id, old_boot_id, wait_s): + """Restart the server and wait until it is back on a new boot id. Returns the probe that showed the new boot + id (it carries the running and the newest kernel). Raises PatchFailed when the restart cannot be scheduled or + the server is not back within wait_s seconds. Any error while probing means not back yet.""" + _progress(job, "{}: restarting".format(server.hostname)) + try: + answer = _linux_call(server, "reboot", run_id, boot_id=old_boot_id, job=job) + except CallFailed as exc: + raise PatchFailed("The restart could not be scheduled: {}".format(exc)) + if answer["reason"]: + raise PatchFailed("The restart could not be scheduled: {}".format(answer["reason"])) + if answer["boot_id"] and answer["boot_id"] != old_boot_id: + # Already restarted: one more look for the kernels. + try: + return _linux_call(server, "probe", run_id, job=job) + except CallFailed: + return answer + began = _clock() + while True: + _sleep(PROBE_S) + if _clock() - began > wait_s: + raise PatchFailed("The server did not come back within {} of the restart.".format(_minutes_text(wait_s // 60))) + try: + probed = _linux_call(server, "probe", run_id, job=job) + except Exception: + continue + if probed["boot_id"] and probed["boot_id"] != old_boot_id: + return probed + + +def _linux_patch(job, server, run_id, restart, cfg): + """Steps 2 to 4 on a Linux server: the boot id, the install, the restart, the old kernels. Returns the facts + {"updated", "failed", "restart_needed", "restarted", "kernels_removed", "notes" (warnings), "info" (plain + sentences for the message), "no_updates"}; raises PatchFailed.""" + notes = [] + probed = _linux_call(server, "probe", run_id, job=job) + old_boot_id = probed["boot_id"] + if not old_boot_id: + raise PatchFailed("The server's boot id could not be read, so nothing was changed.") + _progress(job, "{}: starting the update".format(server.hostname)) + started = _linux_call(server, "start", run_id, job=job) + if started["reason"]: + raise PatchFailed("The update did not start: {}".format(started["reason"])) + if started["state"] != "running": + raise PatchFailed("The update did not start on the server.") + limit = _minutes(cfg, "patch_timeout_min", DEFAULT_PATCH_TIMEOUT_MIN) * 60 + polled = _linux_wait_for_install(job, server, run_id, limit) + facts = {"updated": polled["updated"], "failed": polled["failed"], "restart_needed": False, + "restarted": False, "kernels_removed": None, "notes": notes, "info": [], "no_updates": False} + if polled["exit"]: + facts["detail"] = polled["details"] + raise PatchFailed(_failure_message("The update failed on the server (exit code {}):".format(polled["exit"]), + polled["failure"], polled["details"]), facts) + needed = polled["restart"] == "1" + facts["restart_needed"] = needed + if polled["restart"] == "unknown": + notes.append("Whether a restart is needed could not be told.") + back = None + if needed: + if not restart: + # A restart is pending: old kernels stay until it is done. + return facts + try: + back = _linux_restart(job, server, run_id, old_boot_id, + _minutes(cfg, "restart_wait_min", DEFAULT_RESTART_WAIT_MIN) * 60) + except PatchFailed as exc: + raise PatchFailed(str(exc), facts) + facts["restarted"] = True + if back is not None and _older_kernel(back): + # Old kernels may still go: the package manager never removes the running kernel. + notes.append(OLDER_KERNEL) + # Old kernels go whenever the setting is on and no restart is pending (none was needed, or it is done and + # confirmed); the script itself refuses unless the server runs its newest kernel. A failure here never fails + # the update. + if not _flag(cfg, "remove_old_kernels", True): + if facts["restarted"]: + facts["info"].append(OLD_KERNELS_KEPT) + else: + _linux_old_kernels(job, server, run_id, facts) + facts["no_updates"] = bool(polled["updated"] == 0 and not polled["failed"] and not needed + and not facts["kernels_removed"]) + return facts + + +def _flag(cfg, key, default): + """A boolean setting; a missing or unreadable one is default.""" + try: + return parse_restart_flag(cfg.get(key), default) + except Exception: + return default + + +def _older_kernel(probed): + return bool(probed.get("kernel_running") and probed.get("kernel_newest") + and probed["kernel_running"] != probed["kernel_newest"]) + + +def _linux_old_kernels(job, server, run_id, facts): + """The old-kernel step. kernels_removed is the guest's own count; a note the guest returns when it skipped the + cleanup goes into the message (a warning only when the server is not running its newest kernel).""" + notes, info = facts["notes"], facts["info"] + _progress(job, "{}: removing old kernels".format(server.hostname)) + try: + cleaned = _linux_call(server, "oldkernels", run_id, timeout=OLD_KERNELS_TIMEOUT, job=job) + except CallFailed as exc: + notes.append("Old kernels were not removed: {}".format(exc)) + return + if cleaned["exit"] or cleaned["reason"]: + notes.append("Old kernels were not removed: {}".format(cleaned["failure"] or cleaned["reason"] + or "the package manager failed.")) + return + facts["kernels_removed"] = cleaned["removed"] + if _older_kernel(cleaned): + if OLDER_KERNEL not in notes: + notes.append(OLDER_KERNEL) + else: + info.extend(cleaned["notes"]) + + +# ---------------------------------------------------------------- Windows: the scripts and the calls +# Two small scripts run in the remote session itself (the update runs in a SYSTEM scheduled task, +# vuln_patch_windows.ps1, through vuln_wintask.py). They hold no comments: every character counts against the +# WinRM command-line limit (vuln_wintask.script_fits). Nothing user-controlled goes into either of them. +# PROBE reads the build (the registry value CurrentBuild, as vuln_scan_windows.ps1 does), the last boot time of the +# operating system, its product type and its uptime in seconds (now minus the boot time, both UTC), and whether the +# Configuration Manager client service CcmExec exists. The product type, the uptime and the build travel in one +# value, "build;producttype;uptime", because vuln_wintask only passes on the transport keys it knows. The boot time is +# Win32_OperatingSystem.LastBootUpTime, "Date and time the operating system was last restarted" +# (https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/win32-operatingsystem), printed in UTC as +# yyyyMMddHHmmss: the boot id. It is derived from the clock, so two reads of one boot can differ by seconds +# (BOOT_TOLERANCE_S); a real restart moves it by the uptime. Whether the platform ever moves it by more than a few +# seconds without a restart is not documented: a first live run has to confirm it. +# REBOOT runs shutdown.exe /r /t and waits for shutdown.exe itself, which returns at once +# (https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/shutdown: /r restarts the +# computer after shutdown, /t is the time-out in seconds, and a time-out above 0 implies /f). Start-Process with +# -Wait -PassThru -WindowStyle Hidden writes nothing to stderr, which VMware Tools would count as a failure. +PROBE = ( + vuln_wintask.PRELUDE + + "try{\n" + + "$o=Get-ItemProperty 'HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion'\n" + + "$w=Get-CimInstance Win32_OperatingSystem\n" + + "$b=$w.LastBootUpTime.ToUniversalTime()\n" + + "'CBWT|build|'+$o.CurrentBuild+';'+$w.ProductType+';'+[int]([DateTime]::UtcNow-$b).TotalSeconds\n" + + "'CBWT|boot|'+$b.ToString('yyyyMMddHHmmss',[Globalization.CultureInfo]::InvariantCulture)\n" + + "'CBWT|ccm|'+[int][bool](Get-Service -Name CcmExec -ErrorAction SilentlyContinue)\n" + + "}catch{'CBWT|terr|probe: '+$_.Exception.Message}\n" + + "exit 0\n" +) +REBOOT = ( + vuln_wintask.PRELUDE + + "try{\n" + + "$p=Start-Process -FilePath \"$env:SystemRoot\\System32\\shutdown.exe\" -ArgumentList '/r','/t','@@DELAY@@' " + + "-Wait -PassThru -WindowStyle Hidden\n" + + "'CBWT|reboot|'+$p.ExitCode\n" + + "}catch{'CBWT|terr|reboot: '+$_.Exception.Message}\n" + + "exit 0\n" +) + + +def _reboot_script(): + return REBOOT.replace("@@DELAY@@", str(int(WIN_REBOOT_DELAY_S))) + + +def boot_changed(old, new): + """True when two Windows boot ids (UTC yyyyMMddHHmmss) are more than BOOT_TOLERANCE_S seconds apart. A value + that is not a boot id counts as unchanged.""" + try: + before = datetime.strptime(str(old), BOOT_FORMAT) + after = datetime.strptime(str(new), BOOT_FORMAT) + except (TypeError, ValueError): + return False + return abs((after - before).total_seconds()) > BOOT_TOLERANCE_S + + +def _windows_call(function, *args): + """Call one of vuln_wintask's functions, turning its errors into CallFailed (message safe to store).""" + try: + return function(*args) + except vuln_wintask.WinTaskError as exc: + raise CallFailed(vuln_jobs.clean(str(exc), MESSAGE_LEN) or CALL_FAILED) + except NotImplementedError: + raise CallFailed("This server's resource handler cannot run scripts on servers.") + + +def _windows_probe(server, job=None): + """{"boot", "build", "ccm"} read from the server: boot is the boot id ("" when unreadable), build the Windows + build number, ccm "1" when the Configuration Manager client service exists. Raises CallFailed.""" + reply = _windows_call(vuln_wintask.inline, server, PROBE) + if reply.get("terr"): + raise CallFailed(vuln_jobs.clean(reply["terr"], MESSAGE_LEN)) + return _windows_probe_reply(reply) + + +def _windows_probe_reply(reply): + """The probe's transport values as {"boot", "build", "ccm", "product", "uptime"}. Raises CallFailed when the + answer is empty.""" + boot = str(reply.get("boot", "")).strip() + packed = [part.strip() for part in str(reply.get("build", "")).split(";")] + ["", ""] + build, product, uptime = packed[0], packed[1], packed[2] + if not (boot or build or reply.get("ccm")): + raise CallFailed("The server's answer was cut off.") + return { + "boot": boot if BOOT_RE.fullmatch(boot) else "", + "build": build if vuln_jobs.BUILD_RE.fullmatch(build) else "", + "ccm": "1" if str(reply.get("ccm", "")).strip() == "1" else "0", + "product": product if product in ("1", "2", "3") else "", + "uptime": vuln_jobs._int(uptime, 10 ** 9) if uptime.isdigit() else None, + } + + +def _restarted(old_boot, probed, since): + """True when the probe shows the server restarted since the job read old_boot at clock time since: the boot id + moved by more than BOOT_TOLERANCE_S and the reported uptime is shorter than the time since then plus + UPTIME_SLACK_S. A clock step moves the boot id but not the uptime; an uptime that is missing proves nothing.""" + if not boot_changed(old_boot, probed.get("boot")): + return False + uptime = probed.get("uptime") + return uptime is not None and uptime < (_clock() - since) + UPTIME_SLACK_S + + +def _windows_blank(): + return {"phase": "", "found": None, "skipped": None, "items": [], "updated": None, "failed": None, + "result": None, "hresult": "", "restart": "", "restart_before": "", "more": None, "failure": "", + "reason": "", "notes": [], "done": False} + + +def _windows_parse(lines, into=None): + """The worker's CBVULN|key|value lines as one dict, added to into when it is given (each poll brings the + lines after the last). Only known keys are read; a later line wins; text is cleaned and capped, counts are whole + numbers within bounds (else None), restart is 0 or 1, the result a code from 0 to 5, the HRESULT 0x and eight + hexadecimal digits, and at most MAX_ITEMS items and MAX_NOTES notes are kept.""" + result = into if into is not None else _windows_blank() + if isinstance(lines, (str, bytes)): + text = lines.decode("utf-8", errors="replace") if isinstance(lines, bytes) else lines + lines = vuln_jobs._bounded(text).splitlines() + for raw in lines: + line = str(raw).strip() + if not line.startswith("CBVULN|"): + continue + parts = line.split("|", 2) + if len(parts) < 3 or parts[1] not in WIN_KEYS: + continue + key, value = parts[1], parts[2].strip() + if key in ("found", "skipped", "updated", "failed", "more"): + result[key] = vuln_jobs._int(value, MAX_COUNT) + elif key == "result": + result[key] = vuln_jobs._int(value, 5) + elif key == "hresult": + result[key] = value if HRESULT_RE.fullmatch(value) else "" + elif key in ("restart", "restart_before"): + result[key] = value if value in ("0", "1") else "" + elif key == "item": + bits = value.split(";", 2) + code = vuln_jobs._int(bits[0], 5) if len(bits) == 3 else None + if code is not None and len(result["items"]) < MAX_ITEMS: + kb = bits[1].strip() + result["items"].append({"result": code, "kb": kb if KB_RE.fullmatch(kb) else "", + "title": vuln_jobs.clean(bits[2], 120)}) + elif key == "note": + if len(result["notes"]) < MAX_NOTES: + result["notes"].append(vuln_jobs.clean(value, MESSAGE_LEN)) + elif key == "done": + result["done"] = True + elif key in ("failure", "reason"): + result[key] = vuln_jobs.clean(value, MESSAGE_LEN) + else: + result[key] = vuln_jobs.clean(value, 120) + return result + + +def _windows_cleanup(server, run_id): + """Unregister the task and remove the run folder on the server. Best effort, and only when the task is not + running: vuln_wintask.cleanup stops the task, and an update must never be stopped midway, so a task that is + still running (a canceled job, a timeout) keeps its folder, and the next update removes folders older than two + days. A server that cannot be reached keeps it too.""" + try: + state = vuln_wintask.poll(server, run_id, 0, 200) + except Exception: + logger.info("Vulnerabilities: the update on server %s was not checked, so its run folder stays", server.id) + return + if state.get("alive"): + logger.info("Vulnerabilities: the update on server %s is still running, so its run folder stays", server.id) + return + vuln_wintask.cleanup(server, run_id) + + +def _windows_wait_for_install(job, server, run_id, limit_s, old_boot="", since=None): + """Poll the worker's status file until it logs done. Returns the parsed lines (_windows_parse). Raises + PatchFailed at the limit, when CloudBolt lost contact for LOST_POLLS polls in a row, or when the task is gone + without a done line (two polls in a row: it is not running and brought no new line); then one probe tells a + restart (_restarted, against old_boot read at clock time since) from a task that stopped.""" + began = _clock() + since = began if since is None else since + lost = idle = offset = 0 + parsed = _windows_blank() + shown = "" + more = False + while True: + if not more: + _sleep(WIN_POLL_S) + if _clock() - began > limit_s: + raise PatchFailed("The update did not finish within {} and may still be running on the server. " + "{}".format(_minutes_text(limit_s // 60), CHECK_WINDOWS_UPDATE), _facts_of(parsed)) + try: + polled = _windows_call(vuln_wintask.poll, server, run_id, offset) + except CallFailed as exc: + lost += 1 + more = False + if lost >= LOST_POLLS: + raise PatchFailed("CloudBolt lost contact with the server for {} checks in a row ({}). {}".format( + LOST_POLLS, exc, CHECK_WINDOWS_UPDATE), _facts_of(parsed)) + continue + lost = 0 + _windows_parse(polled["lines"], parsed) + offset = polled["next"] + more = bool(polled["more"]) + if parsed["phase"] and parsed["phase"] != shown: + shown = parsed["phase"] + _progress(job, "{}: {}".format(server.hostname, shown)) + if parsed["done"]: + return parsed + idle = idle + 1 if (not polled["alive"] and not polled["lines"] and not more) else 0 + if idle >= 2: + try: + probed = _windows_probe(server, job) + except CallFailed: + probed = {} + if old_boot and _restarted(old_boot, probed, since): + raise PatchFailed(RESTARTED_WINDOWS, _facts_of(parsed)) + raise PatchFailed(STOPPED_WINDOWS, _facts_of(parsed)) + + +def _windows_reboot(server): + """Send the restart. Returns True when the call went through, False when it raised (ambiguous: the server may + be going down). Raises PatchFailed when the reply says the restart was not scheduled.""" + try: + reply = _windows_call(vuln_wintask.inline, server, _reboot_script()) + except CallFailed: + return False + if reply.get("terr"): + raise PatchFailed("The restart could not be scheduled: {}".format(vuln_jobs.clean(reply["terr"], MESSAGE_LEN))) + code = reply.get("reboot") + if code is not None and str(code).strip() != "0": + raise PatchFailed("The restart could not be scheduled (exit code {}).".format(vuln_jobs.clean(code, 20))) + return True + + +def _windows_restart(job, server, old_boot, wait_s, since=None): + """Restart the server and wait until it has restarted (_restarted). Returns the new boot id. A server that + already shows a restart (it restarted on its own after the install) is not restarted again. Raises PatchFailed + when the restart cannot be scheduled (a reply with a non-zero exit code or an error), when the server is not + back within wait_s seconds, or when a reboot call that raised was not followed by a restart: after + RESTART_UNCHANGED_PROBES successful probes in a row with the old boot id the reboot is sent once more, and after + as many again the restart is given up as not started. Any error while probing means not back yet.""" + since = _clock() if since is None else since + _progress(job, "{}: restarting".format(server.hostname)) + try: + now = _windows_probe(server, job) + except CallFailed: + now = {} + if now.get("boot") and _restarted(old_boot, now, since): + return now["boot"] + ambiguous = not _windows_reboot(server) + resent = False + unchanged = 0 + began = _clock() + while True: + _sleep(WIN_PROBE_S) + if _clock() - began > wait_s: + raise PatchFailed("The server did not come back within {} of the restart.".format(_minutes_text(wait_s // 60))) + try: + probed = _windows_probe(server, job) + except CallFailed: + unchanged = 0 + continue + if probed["boot"] and _restarted(old_boot, probed, since): + return probed["boot"] + if not ambiguous: + continue + unchanged += 1 + if unchanged >= RESTART_UNCHANGED_PROBES: + if resent: + raise PatchFailed(RESTART_NOT_STARTED) + resent = True + unchanged = 0 + _windows_reboot(server) + + +def _failed_note(items): + """"These updates failed: KB1, KB2." for the items whose result is 3, 4 or 5 (at most MAX_FAILED_LISTED), or "".""" + bad = [item for item in items if item["result"] in (3, 4, 5)] + if not bad: + return "" + names = [item["kb"] or item["title"] or "an update" for item in bad[:MAX_FAILED_LISTED]] + more = len(bad) - len(names) + return "{} failed: {}{}.".format("This update" if len(bad) == 1 else "These updates", ", ".join(names), + " and {} more".format(more) if more > 0 else "") + + +def _windows_patch(job, server, run_id, restart, cfg): + """Steps 2 to 4 on a Windows server: the probe (Configuration Manager, build, boot id), the update as a SYSTEM + task, the restart. Returns the same facts as _linux_patch (kernels_removed is None); raises PatchFailed.""" + notes = [] + probed = _windows_probe(server, job) + if probed["ccm"] == "1": + raise PatchFailed(CCM_REFUSED) + if probed["product"] not in ("2", "3"): + # Windows 11 24H2 has build 26100 too; only a server product type is updated here. Unreadable refuses. + raise PatchFailed(ONLY_SERVER) + if not probed["build"]: + raise PatchFailed("The Windows build could not be read, so nothing was changed.") + if probed["build"] not in vuln_msrc.PRODUCTS: + raise PatchFailed("Windows build {} is not one this extension updates (Windows Server 2022 and 2025), so " + "nothing was changed.".format(probed["build"])) + old_boot = probed["boot"] + if not old_boot: + raise PatchFailed("The server's boot time could not be read, so nothing was changed.") + since = _clock() + path = os.path.join(os.path.dirname(os.path.abspath(__file__)), WIN_SCRIPT_FILE) + worker = _windows_call(vuln_wintask.build_worker, path, {}) + limit = _minutes(cfg, "patch_timeout_min", DEFAULT_PATCH_TIMEOUT_MIN) * 60 + _progress(job, "{}: starting the update".format(server.hostname)) + try: + _windows_call(vuln_wintask.start, server, run_id, worker, limit) + except CallFailed as exc: + raise PatchFailed("The update did not start: {}".format(exc)) + polled = _windows_wait_for_install(job, server, run_id, limit, old_boot, since) + needed = polled["restart"] == "1" + facts = {"updated": polled["updated"], "failed": polled["failed"], "restart_needed": needed, + "restarted": False, "kernels_removed": None, "notes": notes, "info": [], "no_updates": False} + if polled["reason"]: + raise PatchFailed(polled["reason"], facts) + if polled["failure"]: + raise PatchFailed("The update failed: {}{}".format( + polled["failure"], " ({})".format(polled["hresult"]) if polled["hresult"] else ""), facts) + if polled["restart_before"] == "1": + notes.append("A restart was already pending before the update started.") + if polled["updated"] is None: + # Nothing was installed: no updates, or none that can be installed without a person. + facts["updated"], facts["failed"] = 0, 0 + # Nothing was offered: the outcome says so. Updates that were offered but skipped are in the skipped note. + facts["no_updates"] = not polled["found"] + failed_note = _failed_note(polled["items"]) + if polled["result"] in (4, 5): + raise PatchFailed("Windows Update could not install the updates (result {}{}). {}".format( + polled["result"], ", " + polled["hresult"] if polled["hresult"] else "", failed_note).strip(), facts) + if failed_note: + notes.append(failed_note) + if polled["skipped"]: + notes.append("{} update{} skipped because {} user input or a license agreement.".format( + polled["skipped"], " was" if polled["skipped"] == 1 else "s were", + "it needs" if polled["skipped"] == 1 else "they need")) + if polled["more"]: + notes.append("{} more update{} available; run the update again.".format( + polled["more"], " is" if polled["more"] == 1 else "s are")) + if not needed or not restart: + return facts + try: + _windows_restart(job, server, old_boot, _minutes(cfg, "restart_wait_min", DEFAULT_RESTART_WAIT_MIN) * 60, + since) + except PatchFailed as exc: + raise PatchFailed(str(exc), facts) + facts["restarted"] = True + return facts + + +def _rescan(job, server): + """Scan the server again as a child of the update job, which holds the active marker. Returns (summary, note): + the vulnerability counts after the scan, or None and a sentence on why there are none.""" + base_url = vuln_fleet.default_base_url() + _progress(job, "{}: scanning again".format(server.hostname)) + try: + started = vuln_jobs.start(getattr(job, "owner", None), server, base_url, parent_job=job, handover_from=job.id) + except Exception: + logger.exception("Vulnerabilities: the rescan of server %s could not start", server.id) + return None, "The rescan could not start." + if vuln_fleet._started_id(started) is None: + return None, "The rescan did not start: {}".format(vuln_jobs.clean(getattr(started, "message", ""), 200)) + wait = _int_setting("scan_timeout_min", 20) * 60 + WAIT_MARGIN_S + # Imported here, not at the top: views.py imports this module for the tab, and a page load needs no job code. + from utilities.exceptions import TimeoutException + try: + # Polls the job every five seconds; cancels it and raises when the time is up (jobs/models.py). + ended = started.wait_for_completion(timeout=wait) + except TimeoutException: + return None, "The rescan did not finish within {}.".format(_minutes_text(wait // 60)) + if getattr(ended, "status", "") not in ("SUCCESS", "WARNING"): + return None, "The rescan failed (job {}).".format(started.id) + summary = _summary(server.id) + if summary is None: + return None, "The rescan finished but its result could not be read." + return summary, "" + + +def _int_setting(key, default): + try: + return max(1, int(store.get_settings().get(key) or default)) + except Exception: + return default + + +def _sentence(host, record): + """The one line a server gets in the job output: the facts, leaving out what did not happen.""" + if record["status"] == "failed": + return "{}: failed. {}".format(host, record["message"]) + if record["status"] == "no_updates": + text = "{}: no updates were available.".format(host) + return text + (" " + record["message"] if record["message"] else "") + windows = record.get("family") == "windows" + if record["updated"] is None: + parts = ["updates installed"] + else: + parts = ["{} {}{} {}".format(record["updated"], "update" if windows else "package", + "" if record["updated"] == 1 else "s", "installed" if windows else "updated")] + if record["restarted"]: + parts.append("restarted") + elif record["restart_needed"]: + parts.append("a restart is still needed") + if record["kernels_removed"]: + parts.append("{} old kernel package{} removed".format( + record["kernels_removed"], "" if record["kernels_removed"] == 1 else "s")) + before, after = record["before"], record["after"] + if before is not None and after is not None: + counts = "known vulnerabilities {} to {}".format(before["vulns"], after["vulns"]) + if before.get("vuln_fixable") is not None and after.get("vuln_fixable") is not None: + counts += ", with a fix {} to {}".format(before["vuln_fixable"], after["vuln_fixable"]) + parts.append(counts) + text = "{}: {}.".format(host, ", ".join(parts)) + if record["message"]: + text += " " + record["message"] + return text + + +def _record(job, server, status, facts, before, after, began, message, family="linux"): + owner = getattr(job, "owner", None) + return { + "family": family, + "at": store.stamp(), + "by": vuln_jobs._requested_by(owner), + "job_id": job.id, + "status": status, + "before": before, + "after": after, + "updated": facts.get("updated"), + "failed": facts.get("failed"), + "restarted": bool(facts.get("restarted")), + "restart_needed": bool(facts.get("restart_needed")), + "kernels_removed": facts.get("kernels_removed"), + "duration_s": max(0, int(_clock() - began)), + "message": vuln_jobs.clean(message, MESSAGE_LEN), + } + + +def _patch_one(job, server, restart, cfg): + """Update one server and scan it again. Returns the record written to the server's state ("patch") plus + "hostname" and "warning" (the run should end with a warning). Raises PatchFailed only when the server was not + touched (neither Linux nor Windows, held by another job, no longer eligible); a failure after that is a + record with status "failed".""" + if vuln_jobs.is_windows(server): + family = "windows" + elif vuln_jobs.is_linux(server): + family = "linux" + else: + raise PatchFailed(ONLY_SUPPORTED) + patcher, cleaner = (_windows_patch, _windows_cleanup) if family == "windows" else (_linux_patch, _linux_cleanup) + began = _clock() + marker = { + "job_id": job.id, "scan_id": "patch-" + store.new_scan_id(), "started": store.stamp(), + "requested_by": vuln_jobs._requested_by(getattr(job, "owner", None)), "kind": PATCH_KIND, + } + run_id = marker["scan_id"] + try: + with store.start_lock(server.id): + running = vuln_jobs.active_job(server.id) + if running is not None: + raise PatchFailed("Job {} is still running on this server; wait for it to finish.".format(running[1].id)) + code = eligibility(server) + if code: + raise PatchFailed("The server cannot be updated: {}.".format(_why(code))) + store.set_active(server.id, marker) + except store.StoreError: + logger.exception("Vulnerabilities: state problem starting an update on server %s", server.id) + raise PatchFailed(vuln_jobs.STATE_ERROR) + try: + before = _summary(server.id) + warning = False + facts = {} + after = None + try: + facts = patcher(job, server, run_id, restart, cfg) + except (PatchFailed, CallFailed) as exc: + facts = getattr(exc, "facts", None) or {} + record = _record(job, server, "failed", facts, before, None, began, str(exc), family) + _finish(job, server, record) + # The detail lines go to the job output and errors only, not into the stored record. + return dict(record, hostname=server.hostname, warning=True, detail=_detail_text(facts.get("detail"))) + notes = list(facts.get("notes") or []) + info = list(facts.get("info") or []) + after, problem = _rescan(job, server) + if after is None: + warning = True + notes.append("The updates were installed and the rescan failed: {}".format(problem)) + status = "updated" + if facts["restart_needed"] and not facts["restarted"]: + status = "restart_pending" + warning = True + notes.append("A restart is needed to finish; the server was not restarted.") + elif facts.get("no_updates") and not facts["restarted"] and not facts.get("kernels_removed"): + status = "no_updates" + warning = warning or bool(notes) + record = _record(job, server, status, facts, before, after, began, " ".join(notes + info), family) + _finish(job, server, record) + return dict(record, hostname=server.hostname, warning=warning) + finally: + try: + store.clear_active(server.id, marker["scan_id"]) + except Exception: + logger.exception("Vulnerabilities: could not clear the active marker for server %s", server.id) + cleaner(server, run_id) + + +def _finish(job, server, record): + """Write the record and the server's history event. Neither may end the run.""" + try: + record_patch(server.id, record) + except Exception: + logger.exception("Vulnerabilities: could not record the update of server %s", server.id) + try: + # INFO, not MODIFICATION: add_server_event drops a MODIFICATION for a server with no creation event. + if record["status"] == "no_updates": + text = "Vulnerability update: no updates were available. {}".format(record["message"]).strip() + else: + text = "Vulnerability update {}: {}".format(record["status"].replace("_", " "), + record["message"] or "no problems.") + add_server_event("INFO", server, text, job=job) + except Exception: + logger.exception("Vulnerabilities: could not add the server event") + + +# ---------------------------------------------------------------- the job +def run_patch(job, servers=None, server=None, restart_if_needed=None, profile=None, **kwargs): + """Plugin entry point (via vuln_patch_job.py). Returns the 4-tuple CloudBolt plugins use: status, output, + errors, outputs. The servers come from the job (one or more). A server that fails does not stop the others; + no server is started whose worst case would not end before JOB_LIMIT_S, or once the job was asked to stop.""" + if not patching_enabled(): + return "FAILURE", "", PATCHING_OFF, {} + targets = list(servers) if servers else ([server] if server is not None else []) + if not targets: + return "FAILURE", "", "No server was given.", {} + restart = parse_restart_flag(restart_if_needed) + try: + cfg = store.get_settings() + except Exception: + cfg = {} + counts = {"updated": 0, "no_updates": 0, "restart_pending": 0, "failed": 0, "skipped": 0} + results = {} + details = {} + lines = [] + warned = False + began = _clock() + stopped = out_of_time = False + worst_s = (_minutes(cfg, "patch_timeout_min", DEFAULT_PATCH_TIMEOUT_MIN) + + _minutes(cfg, "restart_wait_min", DEFAULT_RESTART_WAIT_MIN) + RESCAN_MARGIN_MIN) * 60 + try: + for position, target in enumerate(targets): + if vuln_fleet._cancelled(job): + stopped = True + elif _clock() - began + worst_s > JOB_LIMIT_S: + out_of_time = True + if stopped or out_of_time: + counts["skipped"] += len(targets) - position + break + try: + done = _patch_one(job, target, restart, cfg) + except PatchFailed as exc: + done = {"status": "failed", "message": vuln_jobs.clean(str(exc), MESSAGE_LEN), "hostname": target.hostname, + "warning": True, "updated": None, "failed": None, "restarted": False, "restart_needed": False, + "kernels_removed": None, "before": None, "after": None} + except Exception as exc: + logger.exception("Vulnerabilities: the update of server %s failed", getattr(target, "id", "")) + done = {"status": "failed", "message": "The update failed: {}".format(vuln_jobs.clean(str(exc), 200)), + "hostname": target.hostname, "warning": True, "updated": None, "failed": None, + "restarted": False, "restart_needed": False, "kernels_removed": None, "before": None, + "after": None} + warned = warned or bool(done.pop("warning", False)) + detail = done.pop("detail", "") + counts[done["status"]] += 1 + lines.append(_sentence(target.hostname, done) + ("\n" + detail if detail else "")) + results[str(target.id)] = done + details[str(target.id)] = detail + except BaseException: + # A cancel (CancelJobException) ends the loop here; the marker was cleared by _patch_one's own finally. + _progress(job, GUEST_KEEPS_RUNNING) + raise + if stopped: + lines.append("Stopped early because the job was canceled. {} not started. {}".format( + counts["skipped"], GUEST_KEEPS_RUNNING)) + if out_of_time: + lines.append("{} server{} not started: one more update could take up to {}, and the job has to end " + "before CloudBolt's 8 hour limit. Run the update again for them.".format( + counts["skipped"], " was" if counts["skipped"] == 1 else "s were", + _minutes_text(worst_s // 60))) + outputs = {"servers": results, "counts": counts} + output = "\n".join(lines) + problem = "" + if counts["failed"]: + first_id = next(key for key, item in results.items() if item["status"] == "failed") + first = results[first_id] + problem = first["message"] if len(targets) == 1 else "{} of {} servers failed. First failure ({}): {}".format( + counts["failed"], len(targets), first["hostname"], first["message"]) + if details.get(first_id): + problem += "\n" + details[first_id] + if counts["failed"]: + return "FAILURE", output, problem, outputs + if warned or counts["failed"] or counts["skipped"]: + return "WARNING", output, problem, outputs + return "SUCCESS", output, "", outputs diff --git a/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_patch.sh b/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_patch.sh new file mode 100644 index 00000000..fbe807b5 --- /dev/null +++ b/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_patch.sh @@ -0,0 +1,706 @@ +# Linux updates, run as root on the target by the Vulnerabilities UI extension (vuln_patch.py). +# +# vuln_patch.py wraps this file in the same small POSIX sh launcher the scan uses (vuln_jobs._launcher), +# after a header of VAR= lines: +# MODE start | poll | probe | reboot | oldkernels | cleanup (the worker is started by "start") +# RUN_ID the run's id: letters, digits and dashes, 8 to 64 of them; it names the run folder +# BOOT_ID reboot mode only: the boot id the server had before the update (a UUID) +# REBOOT_DELAY_S reboot mode only: seconds to wait before the restart (a whole number) +# Nothing below is formatted with user input. Every mode exits 0 and reports through lines +# "CBVULN||" on stdout; "CBVULN|done|1" is the last line of every call. +# +# One update is three calls from CloudBolt, because an update can outlive any one connection and can restart +# the server: +# start checks the distribution, copies this file to the run folder and starts it there in the +# background (mode "worker"), so the update goes on if the connection drops. +# worker runs the package manager and keeps its state in $RUN/status, written to a temp file and moved +# into place, so a poll never reads half a file. The status file survives a restart. +# poll prints that file and whether the worker is still alive. It is cheap: one cat and one kill -0. +# A restart is a separate call (reboot) and so is the removal of old kernels (oldkernels), which CloudBolt +# only asks for after the new boot id shows the server really restarted. +# +# Vendor documentation for every command used: +# dnf command reference (upgrade, remove --oldinstallonly, --refresh, -y): +# https://dnf.readthedocs.io/en/latest/command_ref.html +# installonly_limit (how many kernels dnf keeps): https://dnf.readthedocs.io/en/latest/conf_ref.html +# dnf needs-restarting -r (exit status 1 means a restart is required): +# https://dnf-plugins-core.readthedocs.io/en/latest/needs_restarting.html +# Amazon Linux 2023 and --releasever=latest: +# https://docs.aws.amazon.com/linux/al2023/ug/deterministic-upgrades.html +# https://docs.aws.amazon.com/linux/al2023/ug/managing-repos-os-updates.html +# apt-get (update, dist-upgrade, autoremove, purge, -s simulate): +# https://manpages.ubuntu.com/manpages/noble/man8/apt-get.8.html +# systemd-run (transient service and timer units): +# https://www.freedesktop.org/software/systemd/man/latest/systemd-run.html + +umask 077 +set -u +export LC_ALL=C + +MODE_REQ=${MODE-} +if [ -n "${1-}" ]; then + MODE_REQ=$1 +fi +RUN_ID=${RUN_ID-} +BOOT_ID=${BOOT_ID-} +REBOOT_DELAY_S=${REBOOT_DELAY_S-5} + +emit() { + local value=${2-} + value=${value//$'\n'/ } + value=${value//$'\r'/ } + printf 'CBVULN|%s|%s\n' "$1" "$value" +} + +# A value made safe for one status line: no separators or control characters, cut short. +san() { + printf '%s' "$1" | tr '\n\r\t|' ' ' | cut -c1-"${2:-200}" +} + +finish() { + emit done 1 + exit 0 +} + +stop_with() { + emit reason "$1" + finish +} + +valid_id() { + case "$1" in + ''|*[!A-Za-z0-9-]*) return 1 ;; + esac + [ "${#1}" -ge 8 ] && [ "${#1}" -le 64 ] +} + +case "$MODE_REQ" in + start|worker|poll|probe|reboot|oldkernels|cleanup) ;; + *) stop_with "unknown mode" ;; +esac +if [ "$MODE_REQ" != probe ] && ! valid_id "$RUN_ID"; then + stop_with "the run id has characters that are not allowed" +fi +RUN="/var/tmp/cbvuln-patch.$RUN_ID" +UNIT="cbvuln-patch-$RUN_ID" +BOOT_FILE=/proc/sys/kernel/random/boot_id + +current_boot_id() { + cat "$BOOT_FILE" 2>/dev/null | tr -d ' \n\r' +} + +# ---- which distribution -------------------------------------------------- +# DISTRO is rhel, ol, amzn2023 or ubuntu on the versions below; anything else is refused. +DISTRO="" +OS_NAME="" +detect() { + local id ver major + [ -r /etc/os-release ] || return 1 + id=$( . /etc/os-release; printf '%s' "${ID-}") + ver=$( . /etc/os-release; printf '%s' "${VERSION_ID-}") + OS_NAME=$( . /etc/os-release; printf '%s' "${PRETTY_NAME-}") + case "$id" in + rhel|ol) + major=${ver%%.*} + case "$major" in + 8|9|10) DISTRO=$id ;; + esac ;; + amzn) + [ "$ver" = "2023" ] && DISTRO=amzn2023 ;; + ubuntu) + case "$ver" in + 22.04|24.04) DISTRO=ubuntu ;; + esac ;; + esac + [ -n "$DISTRO" ] +} + +is_rpm() { + case "$DISTRO" in + rhel|ol|amzn2023) return 0 ;; + esac + return 1 +} + +need_distro() { + detect || stop_with "updates are not supported on this distribution (${OS_NAME:-unknown}); supported: RHEL and Oracle Linux 8-10, Amazon Linux 2023, Ubuntu 22.04 and 24.04" + emit os "$OS_NAME" + emit distro "$DISTRO" + if [ "$(id -u)" != "0" ]; then + stop_with "the update must run as root" + fi + if is_rpm; then + command -v dnf >/dev/null 2>&1 || stop_with "dnf is not installed on the server" + else + command -v apt-get >/dev/null 2>&1 || stop_with "apt-get is not installed on the server" + fi +} + +# Names of the installed kernel packages on the dnf family, with their version in the form uname -r prints +# (version-release.arch), one "name version" pair per line. The names: kernel and kernel-core (Red Hat, Oracle +# Linux RHCK), kernel-uek and kernel-uek-core (Oracle Linux UEK), and kernel. (Amazon Linux 2023 +# names its kernel package after the series: kernel6.18 was observed on mb-dev, where `rpm -q kernel` finds +# nothing). The subpackages (-modules, -devel, ...) have longer names and are not listed. +rpm_kernels() { + rpm -qa --qf '%{NAME} %{VERSION}-%{RELEASE}.%{ARCH}\n' 2>/dev/null \ + | awk '$1 ~ /^(kernel|kernel-core|kernel-uek|kernel-uek-core|kernel[0-9]+(\.[0-9]+)*)$/ {print $1, $2}' +} + +# Names of the installed packages (state ii) on Ubuntu, one per line. +installed_debs() { + dpkg-query -W -f='${db:Status-Abbrev} ${Package}\n' 2>/dev/null | awk '$1 == "ii" {print $2}' +} + +# The ABI versions (6.8.0-1070-aws) of the kernel images in a package list on stdin, one per line. +deb_abis() { + sed -nE 's/^linux-image-(unsigned-)?([0-9][A-Za-z0-9.+-]*)$/\2/p' | sort -u +} + +# The newest installed kernel, in the form uname -r prints, or empty when it cannot be told (never a guess). +# The newest is the highest version of any kernel package; with two flavours installed (RHCK and UEK) it may +# not be the running flavour, which only makes the callers do less. +newest_kernel() { + if is_rpm; then + rpm_kernels | awk '{print $2}' | sort -V | tail -n 1 + else + installed_debs | deb_abis | sort -V | tail -n 1 + fi +} + +# Every installed package and its version, sorted, into the file $1 (a snapshot to count changes against). +# The dnf family: rpm name and epoch:version-release.arch; Ubuntu: dpkg binary package and version. +snapshot() { + if is_rpm; then + rpm -qa --qf '%{NAME} %{EPOCHNUM}:%{VERSION}-%{RELEASE}.%{ARCH}\n' 2>/dev/null | LC_ALL=C sort >"$1" + else + dpkg-query -W -f='${binary:Package} ${Version}\n' 2>/dev/null | LC_ALL=C sort >"$1" + fi +} + +# Lines only in the second snapshot (new or changed packages), and lines only in the first (gone ones). +count_new() { LC_ALL=C comm -13 "$1" "$2" | wc -l | tr -d ' '; } +count_gone() { LC_ALL=C comm -23 "$1" "$2" | wc -l | tr -d ' '; } + +# ---- the run folder -------------------------------------------------------- +# /var/tmp is writable by every local user, so a folder is trusted only when it is a real directory (not a +# symlink), owned by the user this script runs as, with mode 700. Every mode that reads, writes, lists or removes +# a run folder checks it first, and none creates one with mkdir -p or removes one through a link. +safe_dir() { + [ -d "$1" ] && [ ! -L "$1" ] && [ "$(stat -c '%u %a' "$1" 2>/dev/null)" = "$(id -u) 700" ] +} + +# Stop with a reason when the run folder exists but cannot be trusted. +need_safe_run() { + if { [ -e "$RUN" ] || [ -L "$RUN" ]; } && ! safe_dir "$RUN"; then + stop_with "the run folder on the server is not safe to use (not a real directory owned by root with mode 700)" + fi +} + +# ---- a worker that is alive ---------------------------------------------- +# pid_alive : the pid in the folder belongs to a running worker.sh (a reused pid does not). +pid_alive() { + local pid + safe_dir "$1" || return 1 + [ -f "$1/pid" ] && [ ! -L "$1/pid" ] || return 1 + pid=$(cat "$1/pid" 2>/dev/null | tr -d ' \n\r') + case "$pid" in + ''|*[!0-9]*) return 1 ;; + esac + kill -0 "$pid" 2>/dev/null && grep -qa 'worker\.sh' "/proc/$pid/cmdline" 2>/dev/null +} + +# Another update on this server: a cbvuln-patch unit that is active, or a run folder with a live worker. +other_worker_running() { + local dir + if command -v systemctl >/dev/null 2>&1 && [ -d /run/systemd/system ]; then + if systemctl list-units --all --no-legend --plain 'cbvuln-patch-*' 2>/dev/null \ + | awk '{print $3}' | grep -Eqx 'active|activating|reloading'; then + return 0 + fi + fi + for dir in /var/tmp/cbvuln-patch.*; do + safe_dir "$dir" || continue + pid_alive "$dir" && return 0 + done + return 1 +} + +# ---- status file ---------------------------------------------------------- +STATE=running; PHASE=""; UPDATED=""; FAILED=""; EXITCODE=""; FAILURE=""; DETAIL="" +RESTART=""; RESTART_REASON=""; KERNEL_RUNNING=""; KERNEL_NEWEST="" + +flush() { + local tmp="$RUN/.status.$$" line + { + emit state "$STATE" + emit os "$OS_NAME" + emit distro "$DISTRO" + [ -z "$PHASE" ] || emit phase "$PHASE" + [ -z "$UPDATED" ] || emit updated "$UPDATED" + [ -z "$FAILED" ] || emit failed "$FAILED" + [ -z "$EXITCODE" ] || emit exit "$EXITCODE" + [ -z "$FAILURE" ] || emit failure "$(san "$FAILURE" 300)" + if [ -n "$DETAIL" ]; then + while IFS= read -r line; do + emit detail "$(san "$line" 300)" + done <<<"$DETAIL" + fi + [ -z "$RESTART" ] || emit restart "$RESTART" + [ -z "$RESTART_REASON" ] || emit restart_reason "$(san "$RESTART_REASON" 200)" + [ -z "$KERNEL_RUNNING" ] || emit kernel_running "$(san "$KERNEL_RUNNING" 100)" + [ -z "$KERNEL_NEWEST" ] || emit kernel_newest "$(san "$KERNEL_NEWEST" 100)" + } >"$tmp" 2>/dev/null && mv -f "$tmp" "$RUN/status" 2>/dev/null + rm -f "$tmp" 2>/dev/null +} + +# ---- mode: probe ---------------------------------------------------------- +# One cheap read, before the update (the boot id to compare against) and while waiting for a restart. +mode_probe() { + detect || true + emit boot_id "$(current_boot_id)" + emit kernel_running "$(san "$(uname -r)" 100)" + emit kernel_newest "$(san "$(newest_kernel)" 100)" + finish +} + +# ---- mode: start ---------------------------------------------------------- +mode_start() { + local launched=0 tries + need_distro + if other_worker_running; then + stop_with "another update is already running on this server" + fi + # Run folders an earlier job left behind (root-owned, older than three days) are removed first. + find /var/tmp -maxdepth 1 -type d -name 'cbvuln-patch.*' -user root -perm 700 -mtime +3 -exec rm -rf {} + 2>/dev/null + if [ -e "$RUN" ] || [ -L "$RUN" ]; then + stop_with "this run folder already exists" + fi + # No -p: mkdir fails when the name is taken, by a link too, and never follows one. + mkdir -m 700 "$RUN" 2>/dev/null || stop_with "the run folder could not be made in /var/tmp" + safe_dir "$RUN" || stop_with "the run folder on the server is not safe to use" + # The launcher deletes its own file when this call ends, so the worker runs from a copy. The copy has the + # same header; the worker takes its mode from the first argument. + if ! cp "$0" "$RUN/worker.sh" 2>/dev/null; then + rm -rf "$RUN" + stop_with "the update script could not be copied to the server" + fi + chmod 700 "$RUN/worker.sh" + # A transient systemd service: not tied to this connection or its session, and listed by name. + # https://www.freedesktop.org/software/systemd/man/latest/systemd-run.html + if command -v systemd-run >/dev/null 2>&1 && [ -d /run/systemd/system ]; then + # RefuseManualStop=yes: needrestart skips a unit whose RefuseManualStop property is yes + # (systemd_refuse_restart, https://github.com/liske/needrestart/blob/v3.5/needrestart), a second guard next + # to the conf.d exclusion in run_update. https://www.freedesktop.org/software/systemd/man/latest/systemd.unit.html + # If this systemd does not take the property on a transient unit, the unit is started without it. + if systemd-run --quiet --unit="$UNIT" --collect -p RefuseManualStop=yes bash "$RUN/worker.sh" worker >"$RUN/launch.out" 2>&1 \ + || systemd-run --quiet --unit="$UNIT" --collect bash "$RUN/worker.sh" worker >"$RUN/launch.out" 2>&1; then + launched=1 + fi + fi + if [ "$launched" = 0 ]; then + setsid nohup bash "$RUN/worker.sh" worker >"$RUN/launch.out" 2>&1 "; the unit name is taken from the process's cgroup (/.service), and nothing in +# the code skips transient units, so cbvuln-patch-.service would be a candidate (our bash uses libc). +# https://github.com/liske/needrestart/blob/v3.5/needrestart +# https://manpages.ubuntu.com/manpages/jammy/man1/needrestart.1.html +# https://manpages.ubuntu.com/manpages/noble/man1/needrestart.1.html +# * A service matching a regex in $nrconf{blacklist_rc} "will be ignored completely"; the list starts empty. The +# stock needrestart.conf ends by reading every /etc/needrestart/conf.d/*.conf in sorted order (a Perl eval), +# in v3.5 and v3.6. +# https://github.com/liske/needrestart/blob/v3.5/ex/needrestart.conf +# https://github.com/liske/needrestart/blob/v3.6/ex/needrestart.conf +# * So a snippet that sorts last adds our unit-name prefix to that list for the length of the update; every +# other service is still restarted automatically. It is written before apt runs and removed on every exit path +# and, if a killed run left one, at the start of the next run and by the cleanup mode. +# NEEDRESTART_SUSPEND (documented in the same manual pages: the apt hook does not run needrestart at all) is not +# used, because the other services would then keep their old libraries until a restart. +NR_CONF_DIR=/etc/needrestart/conf.d +NR_CONF_FILE=zz-cloudbolt-updates.conf + +needrestart_exclude_off() { + rm -f "$NR_CONF_DIR/$NR_CONF_FILE" 2>/dev/null +} + +# Only when needrestart is installed and reads a conf.d folder; otherwise nothing is written. +needrestart_exclude_on() { + local tmp="$NR_CONF_DIR/.$NR_CONF_FILE.$$" + command -v needrestart >/dev/null 2>&1 || return 0 + [ -d "$NR_CONF_DIR" ] || return 0 + needrestart_exclude_off + { + printf '%s\n' '# Written by the CloudBolt Vulnerabilities extension while an update runs; removed when it ends.' + printf '%s\n' 'push(@{ $nrconf{blacklist_rc} }, qr(^cbvuln-patch-));' + } >"$tmp" 2>/dev/null && chmod 644 "$tmp" 2>/dev/null && mv -f "$tmp" "$NR_CONF_DIR/$NR_CONF_FILE" 2>/dev/null + rm -f "$tmp" 2>/dev/null + return 0 +} + +run_update() { + # The count of what changed is taken from package lists before and after, not from the console text. The + # "before" list is written once: if this worker runs again (a service restart in the middle of the upgrade, for + # one) the second run must still count against the list from before the first, not from after it. + [ -s "$RUN/before.pkgs" ] || snapshot "$RUN/before.pkgs" + if is_rpm; then + if [ "$DISTRO" = amzn2023 ]; then + # Amazon Linux 2023 moves to the newest release with --releasever=latest: + # https://docs.aws.amazon.com/linux/al2023/ug/deterministic-upgrades.html + # https://docs.aws.amazon.com/linux/al2023/ug/managing-repos-os-updates.html + # https://dnf.readthedocs.io/en/latest/command_ref.html + dnf -y --refresh upgrade --releasever=latest >"$LOG" 2>&1 + else + # https://dnf.readthedocs.io/en/latest/command_ref.html + dnf -y --refresh upgrade >"$LOG" 2>&1 + fi + EXITCODE=$? + else + # Non-interactive: no prompts about configuration files (keep the server's own), and services that + # need a restart are restarted automatically. DPkg::Lock::Timeout waits for another package tool. + # https://manpages.ubuntu.com/manpages/noble/man8/apt-get.8.html + export DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a + trap needrestart_exclude_off EXIT + trap 'exit 143' TERM HUP INT + needrestart_exclude_on + apt-get -o DPkg::Lock::Timeout=600 update >"$LOG" 2>&1 + EXITCODE=$? + if [ "$EXITCODE" -eq 0 ]; then + PHASE="Installing updates" + flush + apt-get -y -o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold \ + -o DPkg::Lock::Timeout=600 dist-upgrade >>"$LOG" 2>&1 + EXITCODE=$? + fi + needrestart_exclude_off + fi + snapshot "$RUN/after.pkgs" + UPDATED=$(count_new "$RUN/before.pkgs" "$RUN/after.pkgs") + [ -n "$UPDATED" ] || UPDATED=0 +} + +# Whether the server must restart to run what was installed. +check_restart() { + local out rc newest + KERNEL_RUNNING=$(uname -r) + KERNEL_NEWEST=$(newest_kernel) + if is_rpm; then + # Exit status 1 means a restart is required, 0 that it is not. dnf also exits 1 for a command it does not + # know, so the exit status is trusted only after the command is shown to exist (its help works). + # https://dnf-plugins-core.readthedocs.io/en/latest/needs_restarting.html + rc=99 + if dnf needs-restarting -h >/dev/null 2>&1; then + out=$(dnf needs-restarting -r 2>&1) + rc=$? + fi + case "$rc" in + 0) RESTART=0 ;; + 1) RESTART=1; RESTART_REASON=$(printf '%s\n' "$out" | grep -v '^[[:space:]]*$' | head -n 2 | tr '\n' ' ') ;; + *) + # The command is missing or failed: compare the newest installed kernel with the running one. + newest=$KERNEL_NEWEST + if [ -z "$newest" ]; then + RESTART=unknown; RESTART_REASON="dnf needs-restarting is not available and the kernel could not be compared" + elif [ "$newest" != "$KERNEL_RUNNING" ]; then + RESTART=1; RESTART_REASON="a newer kernel is installed than the one running" + else + RESTART=0 + fi ;; + esac + else + if [ -f /var/run/reboot-required ]; then + RESTART=1 + RESTART_REASON=$(head -n 3 /var/run/reboot-required.pkgs 2>/dev/null | tr '\n' ' ') + [ -n "$RESTART_REASON" ] || RESTART_REASON="/var/run/reboot-required is present" + else + RESTART=0 + fi + fi +} + +# Up to 12 lines of the update log for a failure: from the first line that starts with Error (dnf) or E: (apt) to +# the end, or the whole log when there is none; the last 12 non-empty lines, each cut to 300 characters. +failure_detail() { + local first + first=$(grep -n -m 1 -E '^(Error|E:)' "$LOG" 2>/dev/null | cut -d: -f1) + if [ -n "$first" ]; then + tail -n +"$first" "$LOG" + else + cat "$LOG" 2>/dev/null + fi | grep -v '^[[:space:]]*$' | tail -n 12 | cut -c1-300 +} + +# A worker started a second time for the same run (a service restart, a duplicate start). A run that is done is left +# exactly as it is. A run whose status says it is still going but whose worker is gone was interrupted: it is +# reported as a failure, with the count of what changed so far, and no second upgrade is started. +second_start_guard() { + local prior + [ -f "$RUN/status" ] && [ ! -L "$RUN/status" ] || return 0 + prior=$(cat "$RUN/status" 2>/dev/null) + if printf '%s\n' "$prior" | grep -qx 'CBVULN|state|done'; then + exit 0 + fi + printf '%s\n' "$prior" | grep -qx 'CBVULN|state|running' || return 0 + pid_alive "$RUN" && exit 0 + detect || true + if [ -s "$RUN/before.pkgs" ]; then + snapshot "$RUN/after.pkgs" + UPDATED=$(count_new "$RUN/before.pkgs" "$RUN/after.pkgs") + fi + PHASE="Interrupted" + EXITCODE=1 + FAILED=1 + FAILURE="the update was interrupted" + STATE=done + flush + exit 0 +} + +mode_worker() { + safe_dir "$RUN" || exit 0 + second_start_guard + LOG="$RUN/update.log" + echo $$ >"$RUN/pid" + detect || true + PHASE="Updating packages" + flush + run_update + if [ "$EXITCODE" -ne 0 ]; then + FAILED=$(grep -c -E '^(Error|E:)' "$LOG" 2>/dev/null) + [ -n "$FAILED" ] && [ "$FAILED" -gt 0 ] 2>/dev/null || FAILED=1 + FAILURE=$(grep -E '^(Error|E:|Failed)' "$LOG" 2>/dev/null | tail -n 3 | tr '\n' ' ') + [ -n "$FAILURE" ] || FAILURE=$(grep -v '^[[:space:]]*$' "$LOG" 2>/dev/null | tail -n 2 | tr '\n' ' ') + DETAIL=$(failure_detail) + else + FAILED=0 + fi + PHASE="Checking whether a restart is needed" + flush + check_restart + PHASE="Finished" + STATE=done + flush + exit 0 +} + +# ---- mode: poll ----------------------------------------------------------- +mode_poll() { + local first second + emit boot_id "$(current_boot_id)" + need_safe_run + if [ ! -f "$RUN/status" ] || [ -L "$RUN/status" ]; then + emit state missing + finish + fi + first=$(cat "$RUN/status" 2>/dev/null) + if printf '%s\n' "$first" | grep -qx 'CBVULN|state|running' && ! pid_alive "$RUN"; then + # The worker may have finished between the read and the check: read again before calling it dead. + second=$(cat "$RUN/status" 2>/dev/null) + if printf '%s\n' "$second" | grep -qx 'CBVULN|state|running'; then + printf '%s\n' "$second" | grep '^CBVULN|' | head -n 40 + emit state died + finish + fi + first=$second + fi + printf '%s\n' "$first" | grep '^CBVULN|' | head -n 40 + finish +} + +# ---- mode: reboot --------------------------------------------------------- +mode_reboot() { + local cur + printf '%s' "$BOOT_ID" | grep -Eq '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' \ + || stop_with "the boot id is not valid" + case "$REBOOT_DELAY_S" in + ''|*[!0-9]*) stop_with "the restart delay is not valid" ;; + esac + [ "$REBOOT_DELAY_S" -le 60 ] || stop_with "the restart delay is not valid" + cur=$(current_boot_id) + emit boot_id "$cur" + if [ "$cur" != "$BOOT_ID" ]; then + # The server already restarted since the update began: a second restart would be for nothing. + emit note "the server restarted before the restart was requested" + finish + fi + # Detached with a delay, so this call can return before the connection goes away. + # https://www.freedesktop.org/software/systemd/man/latest/systemd-run.html + if command -v systemd-run >/dev/null 2>&1 && [ -d /run/systemd/system ] \ + && systemd-run --quiet --unit="cbvuln-reboot-$RUN_ID" --on-active="$REBOOT_DELAY_S" --collect systemctl reboot >/dev/null 2>&1; then + emit note "restart scheduled" + finish + fi + setsid nohup sh -c 'sleep "$1"; systemctl reboot || reboot || shutdown -r now' sh "$REBOOT_DELAY_S" >/dev/null 2>&1 6.8.0-1035. +kernel_base() { + printf '%s' "$1" | sed -nE 's/^([0-9]+\.[0-9]+\.[0-9]+-[0-9]+).*/\1/p' +} + +# The packages of the old kernels, one per line. $1 is the running kernel, stdin the installed package names. +# An old kernel is an installed linux-image (or linux-image-unsigned) whose ABI differs from the running one. Its +# packages are the installed ones whose name starts with linux- and holds - followed by the end of the name +# or a dash (image, modules, modules-extra, headers, tools, cloud-tools, and the flavour-prefixed forms such as +# linux-aws-6.8-tools-6.8.0-1035). A name that holds the running kernel's base is never selected, and a +# metapackage (linux-image-aws, no version in its name) never matches. +select_old_debs() { + local names abi base runbase bases="" + names=$(cat) + runbase=$(kernel_base "$1") + [ -n "$runbase" ] || return 0 + for abi in $(printf '%s\n' "$names" | deb_abis); do + [ "$abi" = "$1" ] && continue + base=$(kernel_base "$abi") + # The same release in another flavour is left alone. + [ -n "$base" ] && [ "$base" != "$runbase" ] && bases="$bases $base" + done + [ -n "$bases" ] || return 0 + printf '%s\n' "$names" | awk -v bases="$bases" -v run="$runbase" ' + function has(name, base, pat, rest, pos, nxt) { + pat = "-" base + rest = name + while ((pos = index(rest, pat)) > 0) { + nxt = substr(rest, pos + length(pat), 1) + if (nxt == "" || nxt == "-") return 1 + rest = substr(rest, pos + 1) + } + return 0 + } + BEGIN { n = split(bases, list, " ") } + index($0, "linux-") == 1 && !has($0, run) { + for (i = 1; i <= n; i++) if (has($0, list[i])) { print $0; break } + }' | sort -u +} + +# Ubuntu: purge the packages of the old kernels, after the checks. Sets OLD_COUNT and OLD_RC. +old_kernels_deb() { + local names extra + local -a list + names=$(installed_debs | select_old_debs "$(uname -r)") + if [ -z "$names" ]; then + : + return 0 + fi + mapfile -t list <<<"$names" + # apt-get -s only simulates. Anything it would remove besides the selected packages stops the cleanup. + # https://manpages.ubuntu.com/manpages/noble/man8/apt-get.8.html + extra=$(comm -13 <(printf '%s\n' "${list[@]}" | sort -u) <(apt-get -s purge "${list[@]}" 2>/dev/null | removals) | head -n 1) + if [ -n "$extra" ]; then + emit note "old kernels were left in place: purging them would also remove $(san "$extra" 100)" + return 0 + fi + snapshot "$RUN/kernels-before.pkgs" + export DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a + apt-get -y -o DPkg::Lock::Timeout=600 purge "${list[@]}" >"$RUN/kernels.log" 2>&1 + OLD_RC=$? + snapshot "$RUN/kernels-after.pkgs" + OLD_COUNT=$(count_gone "$RUN/kernels-before.pkgs" "$RUN/kernels-after.pkgs") +} + +# The dnf family. remove --oldinstallonly removes old installonly packages (kernels), keeping only the latest +# versions and the running kernel, whatever installonly_limit says; with nothing old it stops with "No old +# installonly packages found for removal" and a non-zero status. Sets OLD_COUNT and OLD_RC. +# https://dnf.readthedocs.io/en/latest/command_ref.html (remove --oldinstallonly) +old_kernels_rpm() { + snapshot "$RUN/kernels-before.pkgs" + dnf -y remove --oldinstallonly >"$RUN/kernels.log" 2>&1 + OLD_RC=$? + snapshot "$RUN/kernels-after.pkgs" + OLD_COUNT=$(count_gone "$RUN/kernels-before.pkgs" "$RUN/kernels-after.pkgs") + if [ "$OLD_RC" -ne 0 ] && [ "$OLD_COUNT" = 0 ] \ + && grep -qiE 'No old installonly packages|No packages marked for removal|Nothing to do' "$RUN/kernels.log" 2>/dev/null; then + # Nothing old to remove is not a failure, whatever status dnf gives it. + OLD_RC=0 + : + elif [ "$OLD_RC" -ne 0 ]; then + emit note "dnf could not remove the old kernels (exit code $OLD_RC)" + OLD_RC=0 + fi +} + +mode_oldkernels() { + local running newest + need_distro + need_safe_run + if [ ! -e "$RUN" ]; then + mkdir -m 700 "$RUN" 2>/dev/null || stop_with "the run folder could not be made in /var/tmp" + safe_dir "$RUN" || stop_with "the run folder on the server is not safe to use" + fi + OLD_COUNT=0 + OLD_RC=0 + running=$(uname -r) + newest=$(newest_kernel) + # Only a server running its newest kernel is cleaned: the running kernel and the one before it are what + # a failed boot would fall back to. + if [ -z "$newest" ]; then + emit note "old kernels were left in place: the newest installed kernel could not be told" + elif [ "$running" != "$newest" ]; then + emit note "old kernels were left in place: the server is not running its newest kernel" + elif is_rpm; then + old_kernels_rpm + else + old_kernels_deb + fi + emit removed "$OLD_COUNT" + emit exit "$OLD_RC" + if [ "$OLD_RC" -ne 0 ]; then + emit failure "$(san "$(grep -E '^(Error|E:|Failed)' "$RUN/kernels.log" 2>/dev/null | tail -n 2 | tr '\n' ' ')" 300)" + fi + emit kernel_running "$(san "$running" 100)" + emit kernel_newest "$(san "$(newest_kernel)" 100)" + finish +} + +# ---- mode: cleanup -------------------------------------------------------- +mode_cleanup() { + # A stale needrestart exclusion from a killed run goes too, unless an update is running. + other_worker_running || needrestart_exclude_off + if [ ! -e "$RUN" ] && [ ! -L "$RUN" ]; then + finish + fi + need_safe_run + if pid_alive "$RUN"; then + emit note "the update is still running, so its folder was left in place" + finish + fi + rm -rf "$RUN" 2>/dev/null + finish +} + +# ---- dispatch --------------------------------------------------------------- +case "$MODE_REQ" in + probe) mode_probe ;; + start) mode_start ;; + worker) mode_worker ;; + poll) mode_poll ;; + reboot) mode_reboot ;; + oldkernels) mode_oldkernels ;; + cleanup) mode_cleanup ;; +esac +finish diff --git a/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_patch_condition.py b/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_patch_condition.py new file mode 100644 index 00000000..25f9276c --- /dev/null +++ b/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_patch_condition.py @@ -0,0 +1,17 @@ +""" +Display Condition of the Install Updates server action (Vulnerabilities UI extension). + +Core renders this file through its template engine and runs it every time a server's Actions menu is built, +so it stays small. It shows the action only for Linux and Windows servers outside an Unassigned group; +anything else, and any error, hides it. +""" + + +def should_display(server, request=None): + try: + from xui.io_cloudbolt_vulnerabilities import vuln_jobs + + return bool((vuln_jobs.is_linux(server) or vuln_jobs.is_windows(server)) + and not vuln_jobs.in_unassigned_group(server)) + except Exception: + return False diff --git a/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_patch_job.py b/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_patch_job.py new file mode 100644 index 00000000..3f4078f1 --- /dev/null +++ b/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_patch_job.py @@ -0,0 +1,38 @@ +""" +Vulnerability Install Updates + +The Vulnerabilities UI extension registers this file as a CloudBolt plugin and shows it as the Install Updates +server action when an administrator turns on the patching setting. It installs the updates a Linux server's package +manager or Windows Update offers (Linux, and Windows Server 2022 and 2025), restarts the server when that is needed and allowed, and scans it again. The work itself lives in the +extension (vuln_patch.py). This file reloads the extension's modules, so a job picks up an extension update without a +job engine restart, and hands over. Syncing the extension replaces this file; do not edit it on the appliance. + +The line below declares the action's one input, "Restart if needed". CloudBolt reads it when the plugin is saved and +creates the input from it; the value reaches run() as the keyword restart_if_needed, so the line itself is never read. +""" +import importlib + +# Triple quotes, so a line break in the value cannot end the string. +RESTART_TOKEN = """{{ restart_if_needed }}""" + +# Reloaded in dependency order: each module imports the ones before it. +MODULES = ( + "xui.io_cloudbolt_vulnerabilities.vuln_store", + "xui.io_cloudbolt_vulnerabilities.vuln_match", + "xui.io_cloudbolt_vulnerabilities.vuln_db", + "xui.io_cloudbolt_vulnerabilities.vuln_msrc", + "xui.io_cloudbolt_vulnerabilities.vuln_tools", + "xui.io_cloudbolt_vulnerabilities.vuln_repo", + "xui.io_cloudbolt_vulnerabilities.vuln_hooks", + "xui.io_cloudbolt_vulnerabilities.vuln_jobs", + "xui.io_cloudbolt_vulnerabilities.vuln_fleet", + "xui.io_cloudbolt_vulnerabilities.vuln_wintask", + "xui.io_cloudbolt_vulnerabilities.vuln_patch", +) + + +def run(job, *args, **kwargs): + for name in MODULES: + importlib.reload(importlib.import_module(name)) + patch = importlib.import_module("xui.io_cloudbolt_vulnerabilities.vuln_patch") + return patch.run_patch(job, **kwargs) diff --git a/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_patch_resource.py b/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_patch_resource.py new file mode 100644 index 00000000..69c7888e --- /dev/null +++ b/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_patch_resource.py @@ -0,0 +1,436 @@ +""" +Installing updates on all servers of a resource. + +start_job() runs in the web request or in another job. It checks that patching is on and that no run is live on the +resource, then starts the plugin from vuln_hooks.py (vuln_resource_patch_job.py) with OrchestrationHook.run_as_job. +CloudBolt itself starts the same plugin when a person chooses the Install Updates on All Servers resource action; the +dialog's "Restart if needed" input reaches run_resource_patch as the keyword restart_if_needed. + +run_resource_patch() runs inside that job, as the job's owner. It handles the resource's own servers one at a time, +in the order of the resource scan (hostname, then id), and sends each one through vuln_patch._patch_one, so every +rule of the server action holds here too: the per-server start lock, the Unassigned rule, the time limits. On top of +that it: + 1. refuses to start while another run holds the resource (the same marker file as the resource scan, kind + "patch"), writes that marker, and always clears it at the end; + 2. checks every server again, just before it starts, as the job's owner read fresh: still in the resource, not + in an Unassigned group, the owner may view it and may run the Install Updates server action on it, and + vuln_patch.eligibility() passes. A server that fails a check is skipped with a reason and the run goes on; + 3. stops at the first server whose update fails: the servers after it are not attempted and are reported as + skipped. A server that needs a restart, one with no updates to install and a warning are not failures; + 4. starts no server whose worst case would not end before CloudBolt's 8 hour cancel (vuln_patch.JOB_LIMIT_S), and + none once the job was asked to stop; + 5. writes the last-run record of the resource (store.set_resource_patch) at the end, also on a cancel. +The resource action's own permission says nothing about the servers, so step 2 is what keeps this action from +granting more than the server action does. +""" +from accounts.models import Group, UserProfile +from infrastructure.models import Server +from utilities.logger import ThreadLogger + +from . import vuln_fleet, vuln_hooks, vuln_jobs, vuln_patch, vuln_store as store + +logger = ThreadLogger(__name__) + +MESSAGE_LEN = 300 +ALREADY_RUNNING = "Job {} is already running on this resource." +ACTION_OFF = "The Install Updates on All Servers action is switched off." +IN_FLIGHT = ("The job was canceled while this server was updating. The update on the server may still finish.") +NO_RESOURCE = "This job needs exactly one resource." +NO_OWNER = ("This job has no owner, so nothing was updated. Start it again from the resource's Actions menu.") +NOTHING_UPDATED = "No server could be updated." +# What a skipped server is told, by reason code. The codes that are not here use vuln_fleet.REASONS. +SKIP_TEXT = { + "no_permission": "the person who started the job may not install updates on this server", + "left_resource": "no longer in this resource", +} + + +# ---------------------------------------------------------------- the condition and the offer +def has_candidates(resource): + """True when the resource has at least one live Linux or Windows server outside an Unassigned group: the + Display Condition of the resource action, which core runs for every resource page, so it is one query. No + eligibility and no permission. False on any error.""" + try: + servers = resource.server_set.exclude(status="HISTORICAL").filter(vuln_fleet.supported_q()) + unassigned = list(Group.unassigned.ids()) + if unassigned: + servers = servers.exclude(group__in=unassigned) + return servers.exists() + except Exception: + logger.exception("Vulnerabilities: cannot tell whether resource %s has servers to update", + getattr(resource, "id", "")) + return False + + +def _viewable(profile, resource): + # infrastructure/models.py Server.objects_for_profile returns a plain queryset: never .distinct() on it. + return set(Server.objects_for_profile(profile).filter(resource=resource).values_list("id", flat=True)) + + +def _may_patch(profile, server, viewable): + return server.id in viewable and bool(vuln_hooks.server_patch_permitted(profile, server)) + + +def patchable_ids(profile, resource, visibility, problems=None): + """The ids, in resource_servers() order, of the resource's servers that profile may view and update (the + Install Updates server action is permitted on them) and that pass vuln_patch.eligibility(). problems is + vuln_fleet.prerequisites(), when the caller has it. visibility is the setting, which eligibility reads itself; + the argument keeps this call shaped like vuln_fleet.scannable_ids.""" + viewable = _viewable(profile, resource) + if not viewable: + return [] + if problems is None: + problems = vuln_fleet.prerequisites(vuln_fleet.default_base_url()) + found = [] + for server in vuln_fleet.resource_servers(resource): + if _may_patch(profile, server, viewable) and not vuln_patch.eligibility(server, problems): + found.append(server.id) + return found + + +def any_patchable(profile, resource, visibility): + """True as soon as ONE server passes patchable_ids()'s rules; False when none, and on any error.""" + try: + viewable = _viewable(profile, resource) + if not viewable: + return False + problems = vuln_fleet.prerequisites(vuln_fleet.default_base_url()) + for server in vuln_fleet.resource_servers(resource): + if _may_patch(profile, server, viewable) and not vuln_patch.eligibility(server, problems): + return True + except Exception: + logger.exception("Vulnerabilities: could not tell whether resource %s has a server to update", + getattr(resource, "id", None)) + return False + + +# ---------------------------------------------------------------- start +def start_job(owner, resource, restart_if_needed=True, parent_job=None): + """Start the install job of the resource, run as owner. Returns the Job, or a vuln_jobs.Refusal: 403 when + patching is off, 409 when a run is live on the resource, 500 when the state cannot be read or CloudBolt did + not start the job. No permission check, and no server check: the caller has made the first, and the job makes + both for each server, as owner, when the server's turn comes.""" + if not vuln_patch.patching_enabled(): + return vuln_jobs.Refusal(vuln_patch.PATCHING_OFF, 403) + try: + with store.resource_lock(resource.id): + running = vuln_fleet._live_run(resource.id) + if running is not None: + return vuln_jobs.Refusal(ALREADY_RUNNING.format(running[1].id), 409) + created = vuln_hooks.resource_patch_hook().run_as_job( + owner=owner, + resources=[resource], + parent_job=parent_job, + context={"restart_if_needed": bool(vuln_patch.parse_restart_flag(restart_if_needed))}, + ) + if not created: + return vuln_jobs.Refusal("CloudBolt did not start the job; see the application log.", 500) + job = created[0] + # From here the job is queued: nothing below may turn into an error. + try: + job.label = "Install updates: {}".format(resource.name) + job.save(update_fields=["label"]) + # resources/models.py Resource.jobs: the job shows on the resource's own Jobs tab. + resource.jobs.add(job) + except Exception: + logger.exception("Vulnerabilities: could not label or link job %s", job.id) + return job + except store.StoreError: + logger.exception("Vulnerabilities: state problem starting an update of resource %s", resource.id) + return vuln_jobs.Refusal(vuln_fleet.RESOURCE_STATE_ERROR, 500) + + +# ---------------------------------------------------------------- the job +class _Run: + """What one job knows about its run: the servers in order, what each one got, and the verdict.""" + + def __init__(self, job, resource_id, restart, owner): + self.job = job + self.resource_id = resource_id + self.restart = restart + self.owner = owner + self.requested_by = vuln_jobs._requested_by(owner) + self.order = [] + self.hosts = {} + self.current = None + self.results = {} + self.lines = [] + self.stopped_at = None + self.status = "warning" + self.message = "The job was canceled before it finished." + self.done = False + + def counts(self): + counts = {"updated": 0, "no_updates": 0, "restart_pending": 0, "failed": 0, "skipped": 0} + for item in self.results.values(): + counts[item["status"]] += 1 + return counts + + def name(self, server_id): + """The hostname of a server the owner may view, else "Server ".""" + return self.hosts.get(server_id) or "Server {}".format(server_id) + + def add(self, server_id, status, message): + self.results[server_id] = {"hostname": self.name(server_id), "status": status, + "message": vuln_jobs.clean(message, vuln_patch.MESSAGE_LEN)} + + def skip(self, server_id, why): + self.add(server_id, "skipped", "Skipped: {}.".format(why)) + self.lines.append("{}: skipped, {}.".format(self.results[server_id]["hostname"], why)) + + def close(self): + """Every server that got no result is reported as not attempted (a cancel ended the loop).""" + for server_id in self.order: + if server_id not in self.results: + self.skip(server_id, "not attempted, the job was canceled") + + def outputs(self): + results = {str(server_id): self.results[server_id] for server_id in self.order if server_id in self.results} + return {"resource_id": self.resource_id, "order": list(self.order), "servers": results, + "counts": self.counts(), "stopped_at": self.stopped_at} + + def record(self): + return { + "at": store.stamp(), + "by": self.requested_by, + "job_id": self.job.id, + "status": self.status, + "counts": self.counts(), + "restart_if_needed": bool(self.restart), + "message": vuln_jobs.clean(self.message, MESSAGE_LEN), + } + + +def _one_resource(resources, resource): + """The one resource the job runs on, or None.""" + if resource is not None: + return resource + try: + found = list(resources) if resources is not None else [] + except Exception: + logger.exception("Vulnerabilities: could not read the job's resources") + return None + return found[0] if len(found) == 1 else None + + +def run_resource_patch(job, resources=None, resource=None, restart_if_needed=None, profile=None, **kwargs): + """Plugin entry point (via vuln_resource_patch_job.py). Returns the 4-tuple CloudBolt plugins use: status, + output, errors, outputs. The resource marker is written first and always cleared at the end, for this job + only, whatever way it ends; the last-run record is written at the end too, a cancel included. An action an + admin switched off does not run. When the action does not exist (an API caller on an appliance without it), + the run goes on: the setting gate and the per-server permission checks still apply.""" + if not vuln_patch.patching_enabled(): + return "FAILURE", "", vuln_patch.PATCHING_OFF, {} + try: + state = vuln_hooks.resource_patch_action_state() + except Exception: + state = {} + if state.get("exists") and not state.get("enabled"): + return "FAILURE", "", ACTION_OFF, {} + owner = getattr(job, "owner", None) + if owner is None: + # A job that is rerun or cloned can lose its owner. Nobody's permissions can be checked then, so + # nothing may be updated. + return "FAILURE", NO_OWNER, NO_OWNER, {} + target = _one_resource(resources, resource) + if target is None: + return "FAILURE", "", NO_RESOURCE, {} + run = _Run(job, target.id, vuln_patch.parse_restart_flag(restart_if_needed), owner) + try: + refusal = _take_marker(job, target, run) + except Exception as exc: + logger.exception("Vulnerabilities: could not record job %s as the run on resource %s", job.id, target.id) + message = vuln_fleet.RESOURCE_STATE_ERROR if isinstance(exc, store.StoreError) else ( + "The run could not be recorded: {}".format(vuln_jobs.clean(str(exc), 200))) + return "FAILURE", "", message, {} + if refusal: + return "FAILURE", "", refusal, {} + try: + return _execute(job, target, owner, run) + except Exception as exc: + logger.exception("Vulnerabilities: the update of resource %s failed", target.id) + run.close() + run.status = "failure" + run.message = "The update of the resource's servers failed: {}".format(vuln_jobs.clean(str(exc), 200)) + run.done = True + return "FAILURE", "\n".join(run.lines), run.message, run.outputs() + finally: + # Runs for a cancel too (a BaseException passes the except above untouched). + if not run.done: + run.close() + try: + store.set_resource_patch(target.id, run.record()) + except Exception: + logger.exception("Vulnerabilities: could not record the update of resource %s", target.id) + try: + store.clear_resource_run(target.id, job_id=job.id) + except Exception: + logger.exception("Vulnerabilities: could not clear the run of resource %s", target.id) + + +def _take_marker(job, resource, run): + """Write the marker. Returns a sentence when another job that is still active holds the resource (nothing is + written then), else "". Raises when the state cannot be read or written: the run's exclusivity is not + certain, so it does not start.""" + with store.resource_lock(resource.id): + found = vuln_fleet._live_run(resource.id) + if found is not None and found[1].id != job.id: + return ALREADY_RUNNING.format(found[1].id) + servers = list(vuln_fleet.resource_servers(resource)) + run.order = [server.id for server in servers] + # Only the servers the owner may view are named anywhere in the job's output, the record or its progress. + viewable = _viewable(run.owner, resource) + run.hosts = {server.id: server.hostname for server in servers if server.id in viewable} + store.set_resource_run(resource.id, {"job_id": job.id, "started": store.stamp(), + "requested_by": run.requested_by, "server_ids": list(run.order), + "kind": vuln_patch.PATCH_KIND}) + return "" + + +def _execute(job, resource, owner, run): + try: + cfg = store.get_settings() + except Exception: + cfg = {} + problems = vuln_fleet.prerequisites(vuln_fleet.default_base_url()) + worst_s = (vuln_patch._minutes(cfg, "patch_timeout_min", vuln_patch.DEFAULT_PATCH_TIMEOUT_MIN) + + vuln_patch._minutes(cfg, "restart_wait_min", vuln_patch.DEFAULT_RESTART_WAIT_MIN) + + vuln_patch.RESCAN_MARGIN_MIN) * 60 + began = vuln_patch._clock() + state = {"profile": owner, "revoked": False} + total = len(run.order) + why_not = "" + + def check(server): + """"" when the server may be updated now, else a reason code. Read fresh just now: the request that + started the job may be hours old.""" + if getattr(server, "resource_id", None) != resource.id: + return "left_resource" + if server.status == "HISTORICAL": + return "historical" + if vuln_jobs.in_unassigned_group(server): + return "unassigned" + # The owner's roles are read off the loaded profile, and User.is_active is never consulted by them, so + # read both again here. A profile that is gone or a user that is no longer active has no permission, for + # this and every remaining server. + if state["revoked"]: + return "no_permission" + fresh = UserProfile.objects.select_related("user").filter(id=owner.id).first() + user = getattr(fresh, "user", None) + if fresh is None or user is None or not user.is_active: + state["revoked"] = True + return "no_permission" + state["profile"] = fresh + if not (vuln_jobs.can_view(fresh, server) and vuln_hooks.server_patch_permitted(fresh, server)): + return "no_permission" + return vuln_patch.eligibility(server, problems) + + try: + for position, server_id in enumerate(run.order): + if not why_not: + if vuln_fleet._cancelled(job): + why_not = "not started, the job was canceled" + elif vuln_patch._clock() - began + worst_s > vuln_patch.JOB_LIMIT_S: + why_not = ("not started, one more update could take up to {} and the job has to end " + "before CloudBolt's 8 hour limit".format(vuln_patch._minutes_text(worst_s // 60))) + if why_not: + run.skip(server_id, why_not) + continue + try: + server = vuln_fleet._fetch_for_scan(server_id) + if server is None: + run.skip(server_id, vuln_fleet.REASONS["gone"]) + continue + code = check(server) + except Exception as exc: + logger.exception("Vulnerabilities: could not check server %s", server_id) + run.skip(server_id, "it could not be checked: {}".format(vuln_jobs.clean(str(exc), 200))) + continue + name = run.name(server_id) + if code: + run.skip(server_id, SKIP_TEXT.get(code) or vuln_fleet.REASONS.get(code, code)) + continue + vuln_fleet._progress(job, "Server {} of {}: {}".format(position + 1, total, name), position, total) + run.current = server_id + try: + done = vuln_patch._patch_one(job, server, run.restart, cfg) + except vuln_patch.PatchFailed as exc: + # The server was not touched: skipped, and the run goes on. + run.current = None + run.skip(server_id, "the update could not start: {}".format(vuln_jobs.clean(str(exc), 200))) + continue + except Exception as exc: + logger.exception("Vulnerabilities: the update of server %s failed", server_id) + done = {"status": "failed", "message": "The update failed: {}".format(vuln_jobs.clean(str(exc), 200)), + "warning": True} + run.current = None + status = done["status"] + message = vuln_patch._sentence(name, done) if status != "failed" else done["message"] + if status == "failed": + run.add(server_id, "failed", done["message"]) + run.lines.append("{}: failed. {}".format(name, done["message"])) + run.stopped_at = server_id + why_not = "not attempted, {} failed".format(name) + elif status == "restart_pending": + run.add(server_id, "restart_pending", message) + run.lines.append(message) + else: + # "updated" and "no_updates": neither is a failure or a skip. + run.add(server_id, "no_updates" if status == "no_updates" else "updated", message) + run.lines.append(message) + if done.get("warning") and status != "failed": + state["warned"] = True + except BaseException: + # A cancel (CancelJobException) ends the loop here; _patch_one's own finally cleared the server's marker. + # The server being updated is neither done nor untouched: its update may still finish on the server. + if run.current is not None and run.current not in run.results: + run.add(run.current, "failed", IN_FLIGHT) + run.lines.append("{}: {}".format(run.name(run.current), IN_FLIGHT)) + vuln_fleet._progress(job, vuln_patch.GUEST_KEEPS_RUNNING) + raise + return _finish(run, state.get("warned", False)) + + +def _finish(run, warned): + """The verdict, as run_patch ends: FAILURE when a server failed and nothing was updated, or when nothing was + attempted; WARNING for a failure after other servers were updated, a restart pending, a warning or a skip.""" + counts = run.counts() + ok = counts["updated"] + counts["no_updates"] + counts["restart_pending"] + attempted = ok + counts["failed"] + parts = [] + if counts["updated"]: + parts.append("updated {}".format(_servers(counts["updated"]))) + if counts["no_updates"]: + parts.append("no updates were available on {}".format(_servers(counts["no_updates"]))) + if counts["restart_pending"]: + parts.append("{} waiting for a restart".format(_servers(counts["restart_pending"]))) + if counts["failed"]: + parts.append("{} failed".format(_servers(counts["failed"]))) + if counts["skipped"]: + parts.append("skipped {}".format(_servers(counts["skipped"]))) + message = ("; ".join(parts) or "nothing was updated").capitalize() + "." + problem = "" + if counts["failed"]: + item = run.results[run.stopped_at] + problem = "{} failed: {}".format(item["hostname"], item["message"]) + if counts["skipped"]: + problem += " The run stopped there; the servers after it were not attempted." + if not attempted: + problem = NOTHING_UPDATED + if counts["failed"]: + status = "FAILURE" + elif not attempted: + status = "FAILURE" + elif warned or counts["failed"] or counts["skipped"] or counts["restart_pending"]: + status = "WARNING" + else: + status = "SUCCESS" + run.status = status.lower() + run.message = problem if problem and status == "FAILURE" else message + run.done = True + lines = list(run.lines) + [message] + return status, "\n".join(lines), problem if status != "SUCCESS" else "", run.outputs() + + +def _servers(count): + return "{} server{}".format(count, "" if count == 1 else "s") diff --git a/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_patch_windows.ps1 b/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_patch_windows.ps1 new file mode 100644 index 00000000..ef65e3c4 --- /dev/null +++ b/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_patch_windows.ps1 @@ -0,0 +1,102 @@ +# Installs the software updates the server's own Windows Update Agent offers. It runs as a detached SYSTEM scheduled +# task that vuln_wintask.py stages and starts (the Agent refuses a remote session, so it cannot run in the WinRM or +# Run Command session itself). vuln_wintask.build_worker drops these comment lines, the blank lines and the +# indentation before the file is staged, so only the code counts toward the size limit. +# Windows PowerShell 5.1, ASCII only, always exit 0, nothing on stderr. The update source is never changed: no +# ServerSelection, no AddService, nothing downloaded from anywhere but what the Agent itself is pointed at. +# +# Vendor documentation, one page per member used below (Microsoft Learn, Windows Update Agent API): +# https://learn.microsoft.com/en-us/windows/win32/api/wuapi/nn-wuapi-iupdatesession +# Microsoft.Update.Session; CreateUpdateSearcher, CreateUpdateDownloader, CreateUpdateInstaller. +# https://learn.microsoft.com/en-us/windows/win32/api/wuapi/nf-wuapi-iupdatesearcher-search +# Search(criteria): IsInstalled, Type, IsHidden are criteria; the returned ISearchResult has ResultCode and Updates +# https://learn.microsoft.com/en-us/windows/win32/api/wuapi/nn-wuapi-isearchresult +# https://learn.microsoft.com/en-us/windows/win32/api/wuapi/nn-wuapi-iupdate +# Title, KBArticleIDs, EulaAccepted, AcceptEula(), IsDownloaded, InstallationBehavior. +# https://learn.microsoft.com/en-us/windows/win32/api/wuapi/nn-wuapi-iinstallationbehavior +# InstallationBehavior.CanRequestUserInput. +# https://learn.microsoft.com/en-us/windows/win32/api/wuapi/nf-wuapi-iupdate-accepteula +# AcceptEula() returns E_ACCESSDENIED when called from a remote computer; local as SYSTEM it is allowed. +# https://learn.microsoft.com/en-us/windows/win32/api/wuapi/nn-wuapi-iupdatecollection +# Microsoft.Update.UpdateColl; Add, Count, Item. +# https://learn.microsoft.com/en-us/windows/win32/api/wuapi/nf-wuapi-iupdatedownloader-download +# The downloader's Updates property is set first; Download() is synchronous and returns an IDownloadResult. +# https://learn.microsoft.com/en-us/windows/win32/api/wuapi/nn-wuapi-iupdateinstaller +# Updates, AllowSourcePrompts, Install() (synchronous, returns IInstallationResult). +# https://learn.microsoft.com/en-us/windows/win32/api/wuapi/nn-wuapi-iupdateinstaller2 +# ForceQuiet (Windows Installer without user interaction). +# https://learn.microsoft.com/en-us/windows/win32/api/wuapi/nn-wuapi-iinstallationresult +# ResultCode, HResult, RebootRequired, GetUpdateResult(updateIndex): the index is the update's position in the +# collection given to the installer. https://learn.microsoft.com/en-us/windows/win32/api/wuapi/nn-wuapi-iupdateinstallationresult +# (per update: ResultCode, HResult, RebootRequired). +# https://learn.microsoft.com/en-us/windows/win32/api/wuapi/ne-wuapi-operationresultcode +# orcNotStarted 0, orcInProgress 1, orcSucceeded 2, orcSucceededWithErrors 3, orcFailed 4, orcAborted 5. +# https://learn.microsoft.com/en-us/windows/win32/api/wuapi/nn-wuapi-isysteminformation +# Microsoft.Update.SystemInfo; RebootRequired. +$ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue' +$LogF=Join-Path $PSScriptRoot 'status.log' +$U8=New-Object Text.UTF8Encoding($false) +# Cb appends one CBVULN line to status.log, which the poll script reads. One write per line. Characters outside +# printable ASCII (line breaks too) become spaces and a pipe becomes a slash, so a value never breaks a line. +function Cb($k,$v){$v=([string]$v) -replace '[^\x20-\x7e]',' ' -replace '\|','/';$v=$v.Trim();if($v.Length -gt 900){$v=$v.Substring(0,900)};[IO.File]::AppendAllText($LogF,'CBVULN|'+$k+'|'+$v+"`n",$U8)} +# Rc turns an OperationResultCode into a whole number 0 to 5; anything else counts as 4 (failed). +function Rc($v){try{$n=[int]$v}catch{return 4};if($n -lt 0 -or $n -gt 5){return 4};return $n} +# Hx writes an HRESULT as 0x and eight hexadecimal digits. A failure reports the innermost exception's HResult: +# the outer exception is PowerShell's wrapper around the COM error. +function Hx($v){try{return '0x'+([int]$v).ToString('X8')}catch{return '0x00000000'} } +function Kb($u){$a=@($u.KBArticleIDs);if($a.Count -gt 0){return 'KB'+$a[0]};return '-'} +function Run{ +if(Get-Service -Name 'CcmExec' -ErrorAction SilentlyContinue){Cb reason 'This server is patched by Configuration Manager.';return} +$si=New-Object -ComObject Microsoft.Update.SystemInfo +Cb restart_before ([int][bool]$si.RebootRequired) +$ss=New-Object -ComObject Microsoft.Update.Session +Cb phase 'Searching for updates' +$sr=$ss.CreateUpdateSearcher().Search("IsInstalled=0 and Type='Software' and IsHidden=0") +if((Rc $sr.ResultCode) -ge 4){throw 'The search for updates did not complete.'} +$c=New-Object -ComObject Microsoft.Update.UpdateColl +$sk=0 +Cb found $sr.Updates.Count +foreach($u in $sr.Updates){ +if($u.InstallationBehavior.CanRequestUserInput){$sk++;continue} +if(-not $u.EulaAccepted){try{$u.AcceptEula()}catch{} } +if(-not $u.EulaAccepted){$sk++;continue} +$null=$c.Add($u) +} +Cb skipped $sk +if($c.Count -eq 0){return} +Cb phase 'Downloading updates' +try{$d=$ss.CreateUpdateDownloader();$d.Updates=$c;$null=$d.Download()}catch{Cb note ('The download reported: '+$_.Exception.Message)} +$ins=New-Object -ComObject Microsoft.Update.UpdateColl +$items=@();$nd=0 +foreach($u in $c){if($u.IsDownloaded){$null=$ins.Add($u)}else{$nd++;$items+=('4;'+(Kb $u)+';'+$u.Title)} } +if($ins.Count -eq 0){throw 'None of the updates could be downloaded.'} +Cb phase 'Installing updates' +$i=$ss.CreateUpdateInstaller() +$i.Updates=$ins +$i.ForceQuiet=$true +$i.AllowSourcePrompts=$false +$ir=$i.Install() +$up=0;$fl=$nd +for($k=0;$k -lt $ins.Count;$k++){ +$q=Rc ($ir.GetUpdateResult($k).ResultCode) +if($q -eq 2){$up++}elseif($q -ge 3){$fl++} +$items+=([string]$q+';'+(Kb $ins.Item($k))+';'+$ins.Item($k).Title) +} +foreach($t in ($items|Select-Object -First 50)){Cb item $t} +$rs=Rc $ir.ResultCode +$rb=[int]([bool]$ir.RebootRequired -or [bool]$si.RebootRequired) +Cb updated $up +Cb failed $fl +Cb result $rs +Cb hresult (Hx $ir.HResult) +Cb restart $rb +if($rs -eq 2 -and $rb -eq 0){ +Cb phase 'Checking for more updates' +$m=0 +foreach($u in $ss.CreateUpdateSearcher().Search("IsInstalled=0 and Type='Software' and IsHidden=0").Updates){if(-not $u.InstallationBehavior.CanRequestUserInput){$m++} } +Cb more $m +} +} +try{Run}catch{$x=$_.Exception;while($x.InnerException){$x=$x.InnerException};Cb failure ('Windows Update failed: '+$_.Exception.Message);Cb hresult (Hx $x.HResult)} +try{Cb done 1}catch{} +exit 0 diff --git a/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_resource_patch_condition.py b/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_resource_patch_condition.py new file mode 100644 index 00000000..d23bc011 --- /dev/null +++ b/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_resource_patch_condition.py @@ -0,0 +1,16 @@ +""" +Display Condition of the Install Updates on All Servers resource action (Vulnerabilities UI extension). + +Core renders this file through its template engine and runs it every time a resource's Actions menu is built, so it +stays small. It shows the action only for a resource with a Linux or Windows server outside an Unassigned group; +anything else, and any error, hides it. +""" + + +def should_display(resource, request=None): + try: + from xui.io_cloudbolt_vulnerabilities import vuln_patch_resource + + return bool(vuln_patch_resource.has_candidates(resource)) + except Exception: + return False diff --git a/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_resource_patch_job.py b/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_resource_patch_job.py new file mode 100644 index 00000000..f5354c94 --- /dev/null +++ b/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_resource_patch_job.py @@ -0,0 +1,40 @@ +""" +Vulnerability Install Updates on All Servers + +The Vulnerabilities UI extension registers this file as a CloudBolt plugin and shows it as the Install Updates on All +Servers resource action when an administrator turns on the patching setting. It installs the updates on each of the +resource's own servers, one at a time, as the person who chose the action, and stops at the first server whose update +fails. The work itself lives in the extension (vuln_patch_resource.py). This file reloads the extension's modules, so +a job picks up an extension update without a job engine restart, and hands over. Syncing the extension replaces this +file; do not edit it on the appliance. + +The line below declares the action's one input, "Restart if needed". CloudBolt reads it when the plugin is saved and +creates the input from it; the value reaches run() as the keyword restart_if_needed, so the line itself is never read. +""" +import importlib + +# Triple quotes, so a line break in the value cannot end the string. +RESTART_TOKEN = """{{ restart_if_needed }}""" + +# Reloaded in dependency order: each module imports the ones before it. +MODULES = ( + "xui.io_cloudbolt_vulnerabilities.vuln_store", + "xui.io_cloudbolt_vulnerabilities.vuln_match", + "xui.io_cloudbolt_vulnerabilities.vuln_db", + "xui.io_cloudbolt_vulnerabilities.vuln_msrc", + "xui.io_cloudbolt_vulnerabilities.vuln_tools", + "xui.io_cloudbolt_vulnerabilities.vuln_repo", + "xui.io_cloudbolt_vulnerabilities.vuln_hooks", + "xui.io_cloudbolt_vulnerabilities.vuln_jobs", + "xui.io_cloudbolt_vulnerabilities.vuln_fleet", + "xui.io_cloudbolt_vulnerabilities.vuln_wintask", + "xui.io_cloudbolt_vulnerabilities.vuln_patch", + "xui.io_cloudbolt_vulnerabilities.vuln_patch_resource", +) + + +def run(job, *args, **kwargs): + for name in MODULES: + importlib.reload(importlib.import_module(name)) + patch = importlib.import_module("xui.io_cloudbolt_vulnerabilities.vuln_patch_resource") + return patch.run_resource_patch(job, **kwargs) diff --git a/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_store.py b/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_store.py index 8e33f35c..d40da087 100644 --- a/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_store.py +++ b/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_store.py @@ -81,9 +81,18 @@ # and scans the weekly inventory keeps running at once. "rematch_workers": 1, "inventory_parallel": 4, + # Offer the Install Updates server action (vuln_hooks.apply_patching_setting), and how long one server + # may take: minutes to wait for it to come back after a restart, minutes allowed for the install itself. + "patching": False, + "restart_wait_min": 60, + "patch_timeout_min": 90, + # After a Linux server restarts onto a new kernel, remove the older kernel packages. + "remove_old_kernels": True, } REMATCH_WORKERS_RANGE = (1, 4) INVENTORY_PARALLEL_RANGE = (1, 10) +RESTART_WAIT_RANGE = (5, 120) +PATCH_TIMEOUT_RANGE = (10, 240) class StoreError(Exception): @@ -394,8 +403,13 @@ def get_settings(): result["scan_timeout_min"] = _clamp(result["scan_timeout_min"], 5, 120, DEFAULT_SETTINGS["scan_timeout_min"]) if result["visibility"] not in VISIBILITIES: result["visibility"] = "linux" - for key in ("insecure_upload", "guest_internet_download", "scan_on_provision"): + for key in ("insecure_upload", "guest_internet_download", "scan_on_provision", "patching", + "remove_old_kernels"): result[key] = bool(result[key]) + result["restart_wait_min"] = _clamp( + result["restart_wait_min"], *RESTART_WAIT_RANGE, DEFAULT_SETTINGS["restart_wait_min"]) + result["patch_timeout_min"] = _clamp( + result["patch_timeout_min"], *PATCH_TIMEOUT_RANGE, DEFAULT_SETTINGS["patch_timeout_min"]) result["rematch_workers"] = _clamp( result["rematch_workers"], *REMATCH_WORKERS_RANGE, DEFAULT_SETTINGS["rematch_workers"]) result["inventory_parallel"] = _clamp( @@ -426,10 +440,14 @@ def validate_settings(data): clean["visibility"] = visibility clean["scan_on_provision"] = _flag(data.get("scan_on_provision", "")) + clean["patching"] = _flag(data.get("patching", "")) + clean["remove_old_kernels"] = _flag(data.get("remove_old_kernels", "")) for key, (low, high), label in ( ("rematch_workers", REMATCH_WORKERS_RANGE, "Vulnerability matches at once"), ("inventory_parallel", INVENTORY_PARALLEL_RANGE, "Servers scanned at once by the weekly inventory"), + ("restart_wait_min", RESTART_WAIT_RANGE, "Minutes to wait for a server to come back after a restart"), + ("patch_timeout_min", PATCH_TIMEOUT_RANGE, "Minutes allowed for installing updates"), ): raw = str(data.get(key, DEFAULT_SETTINGS[key])).strip() if _whole(raw, low, high) is None: @@ -572,9 +590,13 @@ def _resource_path(resource_id): return contained(RESOURCES_DIR, "{}.json".format(int(resource_id))) +def _resource_patch_path(resource_id): + return contained(RESOURCES_DIR, "{}.patch.json".format(int(resource_id))) + + def read_resource_run(resource_id): - """The marker {"job_id","started","requested_by","server_ids"} or None when there is none or it is - damaged. A file that exists but cannot be read raises StoreError.""" + """The marker {"job_id","started","requested_by","server_ids"} (plus "kind": "patch" for an install-updates + run; a marker without a kind is a scan) or None when there is none or it is damaged. A file that exists but cannot be read raises StoreError.""" found = _read_json(_resource_path(resource_id), None) return found if isinstance(found, dict) else None @@ -585,6 +607,34 @@ def set_resource_run(resource_id, marker): _write_json(_resource_path(resource_id), marker) +def read_resource_patch(resource_id): + """The record of the last install-updates run on the resource, or None when there is none or it is + damaged. A file that exists but cannot be read raises StoreError. It is not the run marker: it stays + after the run and the marker never holds it.""" + found = _read_json(_resource_patch_path(resource_id), None) + return found if isinstance(found, dict) else None + + +def set_resource_patch(resource_id, record): + """Replace the last-run record (atomic write, the lock of the marker's data).""" + with _resource_data_lock(resource_id): + _write_json(_resource_patch_path(resource_id), record) + + +def clear_resource_patch(resource_id): + """Remove the last-run record. Returns True when one was removed.""" + path = _resource_patch_path(resource_id) + with _resource_data_lock(resource_id): + try: + os.unlink(path) + return True + except FileNotFoundError: + return False + except OSError as exc: + raise StoreError("The install-updates record of resource {} cannot be cleared: {}".format( + int(resource_id), exc.strerror or exc)) + + def clear_resource_run(resource_id, job_id=None): """Remove the marker. With job_id, only when the marker is that job's: a rerun of an old job must not clear the marker of a newer run. Returns True when a marker was removed.""" diff --git a/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_wintask.py b/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_wintask.py new file mode 100644 index 00000000..661de6d7 --- /dev/null +++ b/extensions/XUI-wqrj0e3p/io_cloudbolt_vulnerabilities/vuln_wintask.py @@ -0,0 +1,353 @@ +""" +A generic runner for a long Windows job: stages a PowerShell worker on the guest, runs it as a detached SYSTEM +scheduled task, and reads the marker lines it appends to status.log. The patch engine (vuln_patch.py) uses it to run +Windows Update; nothing here knows what the worker does. + +Transport limits this module is built around (CloudBolt's Server.execute_script on Windows always runs PowerShell): + - WinRM sends the script as "powershell -encodedcommand " on one command line, so base64 + length + 27 must stay within 8000 (about 2,900 characters) and a call gives up after about 120 s. On a non-zero + exit only stderr comes back. + - AWS SSM returns about 24,000 characters of stdout, Azure Run Command about 4 KB, and VMware Tools treats any + stderr output as failure. +So every script sent here is short, finishes in seconds, always exits 0, writes nothing to stderr and reports a failure +as a CBWT|terr|... line. The real work runs detached; its lines are CBVULN|key|value in status.log, which poll reads. + +Flow: start (prepare the run directory, stage the gzipped base64 worker in chunks, launch the task) -> poll -> cleanup. +Everything lives under Program Files (writable by administrators only), never ProgramData, which any user can write to: +SYSTEM runs the worker from there. The run directory is readable by SYSTEM and Administrators only. + +Only a validated run id and integers are ever placed in a script; the worker's own settings travel inside the staged +payload (build_worker), single-quoted. +""" +import base64 +import gzip +import re + +# Resolved on the guest in every script (ProgramW6432 keeps a 32-bit PowerShell on the 64-bit Program Files). +BASEDEF = "$base=Join-Path $(if($env:ProgramW6432){$env:ProgramW6432}else{$env:ProgramFiles}) 'CloudBolt\\Patching'\n" +RUN_ID_RE = re.compile(r"[A-Za-z0-9-]{8,64}") +KEY_RE = re.compile(r"[A-Za-z][A-Za-z0-9]{0,15}") +# C0 and C1 controls plus the Unicode line and paragraph separators (built from code points: this file is ASCII). +CONTROL_RE = re.compile("[\\x00-\\x1f\\x7f-\\x9f" + chr(0x2028) + chr(0x2029) + "]") +URL_RE = re.compile(r"[A-Za-z][A-Za-z0-9+.-]*://\S+") +# PowerShell reads these as single quotes too (U+2018, U+2019, U+201A, U+201B); inside a single-quoted string any of +# them is escaped by doubling. +PS_QUOTES = "'" + "".join(chr(code) for code in (0x2018, 0x2019, 0x201A, 0x201B)) +# The UTF-8 byte order mark that makes PowerShell 5.1 read a script file as UTF-8. +BOM = chr(0xFEFF) + +TRANSPORT_PREFIX = "CBWT|" +WORKER_PREFIX = "CBVULN|" +TRANSPORT_KEYS = ("prepared", "chunk", "launched", "next", "more", "alive", "cleaned", "boot", "build", "ccm", + "reboot", "terr") + +# WinRM: len(b64(utf-16-le(script))) + 27 <= 8000. 2,900 ASCII characters gives 7,763. +MAX_SCRIPT_CHARS = 2900 +# The stripped worker (comments, blank lines and indentation removed) and the stage calls it may need. +MAX_WORKER_CHARS = 12000 +MAX_CHUNKS = 8 +EXEC_TIMEOUT = 110 +LINE_CAP = 400 +BUDGET_AZURE = 3000 +BUDGET_DEFAULT = 20000 +GRACE_MINUTES = 10 + + +class WinTaskError(RuntimeError): + """A script could not be delivered, or a call failed. .output is any text that came back.""" + + def __init__(self, message, output=""): + super().__init__(message) + self.output = output + + +# ---------------------------------------------------------------- quoting and building +def ps_quote(value): + """A PowerShell single-quoted string literal for value: quotes doubled, control characters refused.""" + text = "" if value is None else str(value) + if CONTROL_RE.search(text): + raise WinTaskError("A setting contains a control character.") + for quote in PS_QUOTES: + text = text.replace(quote, quote * 2) + return "'" + text + "'" + + +def build_worker(script_path, values): + """The worker text: a $Cfg hashtable header from values (keys match KEY_RE, values single-quoted), then the file + without comment lines, blank lines and indentation. Raises WinTaskError for a bad key, a control character, + non-ASCII text, a double brace (CloudBolt's template engine) or a worker longer than MAX_WORKER_CHARS.""" + rows = [] + for key, value in (values or {}).items(): + if not KEY_RE.fullmatch(str(key)): + raise WinTaskError("A setting name is not valid.") + rows.append("{}={}\n".format(key, ps_quote(value))) + header = "$Cfg=@{\n" + "".join(rows) + "}\n" + with open(script_path, encoding="utf-8", newline="") as handle: + body = handle.read().replace("\r\n", "\n") + lines = [line.strip() for line in body.split("\n")] + text = header + "\n".join(line for line in lines if line and not line.startswith("#")) + "\n" + if not text.isascii(): + raise WinTaskError("The worker has characters that are not allowed.") + if "{" + "{" in text: + raise WinTaskError("The worker has a template marker in it.") + if len(text) > MAX_WORKER_CHARS: + raise WinTaskError("The worker is too long to send ({} of {} characters allowed).".format(len(text), MAX_WORKER_CHARS)) + return text + + +def encode_worker(text): + """gzip then base64. The UTF-8 BOM makes PowerShell 5.1 read the file as UTF-8.""" + return base64.b64encode(gzip.compress((BOM + text).encode("utf-8"), 9, mtime=0)).decode("ascii") + + +def decode_worker(b64): + """The inverse of encode_worker (used by tests).""" + return gzip.decompress(base64.b64decode(b64)).decode("utf-8-sig") + + +# ---------------------------------------------------------------- scripts +PRELUDE = "$ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue'\n" + +# Always run first, every run: creates the run directory, refuses a reparse point, (re)applies the ACL (SYSTEM and +# Administrators only), prunes run directories older than two days and unregisters tasks whose run directory is gone. +PREP = ( + PRELUDE + + "try{\n" + + BASEDEF + + "$r=\"$base\\run\";$d=\"$r\\@@ID@@\"\n" + + "New-Item -ItemType Directory -Force -Path $d|Out-Null\n" + + "if((Get-Item $d -Force).Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'the work directory is a reparse point'}\n" + + "$null=icacls $d /inheritance:r /grant:r '*S-1-5-18:(OI)(CI)F' '*S-1-5-32-544:(OI)(CI)F'\n" + + "if($LASTEXITCODE -ne 0){throw 'icacls failed'}\n" + + "Remove-Item \"$d\\p.b64\" -Force -EA 0\n" + + "Get-ChildItem $r -Directory|?{$_.LastWriteTime -lt (Get-Date).AddDays(-2)}|Remove-Item -Recurse -Force -EA 0\n" + + "Get-ScheduledTask -TaskName 'CloudBolt-Patch-*' -EA 0|?{$i=$_.TaskName.Substring(16);$i -ne '@@ID@@' -and !(Test-Path \"$r\\$i\")}|Unregister-ScheduledTask -Confirm:$false -EA 0\n" + + "'CBWT|prepared|1'\n" + + "}catch{'CBWT|terr|prepare: '+$_.Exception.Message}\n" + + "exit 0\n" +) + +# Idempotent: the chunk is appended only when the file holds exactly the characters before it, and the reply is the +# current length, so a repeated call after a lost reply changes nothing. +STAGE = ( + PRELUDE + + "try{\n" + + BASEDEF + + "$f=\"$base\\run\\@@ID@@\\p.b64\"\n" + + "$c=0;if(Test-Path $f){$c=(Get-Item $f).Length}\n" + + "if($c -eq @@START@@){[IO.File]::AppendAllText($f,'@@CHUNK@@');$c+=@@LEN@@}\n" + + "'CBWT|chunk|'+$c\n" + + "}catch{'CBWT|terr|stage: '+$_.Exception.Message}\n" + + "exit 0\n" +) + +LAUNCH = ( + PRELUDE + + "try{\n" + + BASEDEF + + "$d=\"$base\\run\\@@ID@@\"\n" + + "if(Test-Path \"$d\\p.b64\"){\n" + + "$b=[Convert]::FromBase64String([IO.File]::ReadAllText(\"$d\\p.b64\"))\n" + + "$g=New-Object IO.Compression.GZipStream((New-Object IO.MemoryStream(,$b)),[IO.Compression.CompressionMode]::Decompress)\n" + + "$o=New-Object IO.MemoryStream\n" + + "$g.CopyTo($o)\n" + + "[IO.File]::WriteAllBytes(\"$d\\worker.ps1\",$o.ToArray())\n" + + "Remove-Item \"$d\\p.b64\" -Force}\n" + + "$n='CloudBolt-Patch-@@ID@@'\n" + + "$a=New-ScheduledTaskAction -Execute 'powershell.exe' -Argument \"-NoProfile -NonInteractive -ExecutionPolicy Bypass -File `\"$d\\worker.ps1`\"\"\n" + + "$p=New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest\n" + + "$s=New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Minutes @@MIN@@) -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries\n" + + "$null=Register-ScheduledTask -TaskName $n -Action $a -Principal $p -Settings $s -Force\n" + + "Start-ScheduledTask -TaskName $n\n" + + "'CBWT|launched|1'\n" + + "}catch{'CBWT|terr|launch: '+$_.Exception.Message}\n" + + "exit 0\n" +) + +POLL = ( + PRELUDE + + "try{\n" + + BASEDEF + + "$f=\"$base\\run\\@@ID@@\\status.log\"\n" + + "$n=@@OFFSET@@;$c=@@CAP@@;$b=@@BUDGET@@;$t=0;$k=0;$m=0\n" + + "$a=@();if(Test-Path $f){$a=@(Get-Content -LiteralPath $f -Encoding UTF8)}\n" + + "for($i=$n;$i -lt $a.Count;$i++){\n" + + "$l=[string]$a[$i];if($l.Length -gt $b){$l=$l.Substring(0,$b)}\n" + + "if($k -ge $c -or ($k -gt 0 -and $t+$l.Length+1 -gt $b)){$m=1;break}\n" + + "$l;$t+=$l.Length+1;$k++}\n" + + "'CBWT|next|'+($n+$k)\n" + + "'CBWT|more|'+$m\n" + + "$s=(Get-ScheduledTask -TaskName 'CloudBolt-Patch-@@ID@@' -EA 0).State\n" + + "'CBWT|alive|'+$(if($s -eq 'Running' -or $s -eq 'Queued'){1}else{0})\n" + + "}catch{'CBWT|terr|poll: '+$_.Exception.Message}\n" + + "exit 0\n" +) + +CLEANUP = ( + PRELUDE + + BASEDEF + + "$n='CloudBolt-Patch-@@ID@@'\n" + + "try{Stop-ScheduledTask -TaskName $n -EA 0}catch{}\n" + + "try{Unregister-ScheduledTask -TaskName $n -Confirm:$false -EA 0}catch{}\n" + + "try{Remove-Item -LiteralPath \"$base\\run\\@@ID@@\" -Recurse -Force -EA 0}catch{}\n" + + "'CBWT|cleaned|1'\n" + + "exit 0\n" +) + + +def _fill(template, **values): + for key, value in values.items(): + template = template.replace("@@" + key.upper() + "@@", str(value)) + return template + + +def _check_id(run_id): + text = str(run_id or "") + if not RUN_ID_RE.fullmatch(text): + raise WinTaskError("The run id has characters that are not allowed.") + return text + + +def script_fits(script): + """The WinRM command-line limit (CloudBolt: len(b64(utf-16-le)) + 27 <= 8000).""" + return len(base64.b64encode(script.encode("utf-16-le"))) + 27 <= 8000 + + +def chunk_size(): + """Characters of base64 per stage call: what the worst-case stage script (64-character id, 8-digit offsets) + leaves under MAX_SCRIPT_CHARS.""" + overhead = len(_fill(STAGE, id="x" * 64, start="99999999", chunk="", len="9999")) + return MAX_SCRIPT_CHARS - overhead + + +def prep_script(run_id): + return _fill(PREP, id=_check_id(run_id)) + + +def stage_scripts(run_id, b64): + """The scripts that append b64 to p.b64, one chunk each. Returns [(script, expected acknowledgement)]; the + acknowledgement is the file length after the chunk.""" + run_id = _check_id(run_id) + size = chunk_size() + chunks = [b64[i:i + size] for i in range(0, len(b64), size)] or [""] + return [ + (_fill(STAGE, id=run_id, start=index * size, chunk=chunk, len=len(chunk)), index * size + len(chunk)) + for index, chunk in enumerate(chunks) + ] + + +def launch_script(run_id, limit_s): + minutes = int(limit_s) // 60 + GRACE_MINUTES + return _fill(LAUNCH, id=_check_id(run_id), min=minutes) + + +def poll_script(run_id, offset, budget): + return _fill(POLL, id=_check_id(run_id), offset=int(offset), cap=LINE_CAP, budget=int(budget)) + + +def cleanup_script(run_id): + return _fill(CLEANUP, id=_check_id(run_id)) + + +# ---------------------------------------------------------------- running +def _budget(server): + """Characters of status lines per poll: Azure Run Command returns about 4 KB, the others far more.""" + try: + handler = server.resource_handler.cast() + if "azure" in (type(handler).__module__ + type(handler).__name__).lower(): + return BUDGET_AZURE + except Exception: + pass + return BUDGET_DEFAULT + + +def _text(value): + if isinstance(value, bytes): + value = value.decode("utf-8", errors="replace") + return str(value or "").replace("\r\n", "\n").replace("\r", "\n") + + +def _short(exc): + return URL_RE.sub("", CONTROL_RE.sub(" ", str(exc))).strip()[:200] or type(exc).__name__ + + +def exec_script(server, script): + """Run one PowerShell script on the server and return its output as text.""" + return _text(server.execute_script(script_contents=script, timeout=EXEC_TIMEOUT, show_streaming_output=False)) + + +def _split(text): + """(worker lines, transport values) of one call's output.""" + lines, transport = [], {} + for raw in _text(text).split("\n"): + line = raw.strip() + if line.startswith(TRANSPORT_PREFIX): + parts = line.split("|", 2) + if len(parts) == 3 and parts[1] in TRANSPORT_KEYS: + transport[parts[1]] = parts[2] + elif line.startswith(WORKER_PREFIX): + lines.append(line) + return lines, transport + + +def _call(server, script): + try: + return _split(exec_script(server, script)) + except Exception as exc: + raise WinTaskError(_short(exc)) + + +def inline(server, script): + """Run a script and return its CBWT transport values as a dict. Raises WinTaskError when the call raises.""" + return _call(server, script)[1] + + +def _step(server, script, key, expected, what): + """One script, tried twice: its reply must carry transport key == expected.""" + reason = "" + for _attempt in range(2): + try: + transport = inline(server, script) + except WinTaskError as exc: + reason = str(exc) + continue + if transport.get(key) == str(expected): + return + reason = (transport.get("terr") or "no reply")[:200] + raise WinTaskError("{}: {}".format(what, reason)) + + +def start(server, run_id, worker_text, limit_s): + """Prepare the run directory, stage worker_text and launch it as a SYSTEM task that may run limit_s seconds + (plus a grace period). Each call is tried twice. Raises WinTaskError; the caller runs cleanup.""" + run_id = _check_id(run_id) + scripts = stage_scripts(run_id, encode_worker(worker_text)) + if len(scripts) > MAX_CHUNKS: + raise WinTaskError("The worker is too long to send.") + _step(server, prep_script(run_id), "prepared", 1, "Could not prepare the server") + for script, expected in scripts: + _step(server, script, "chunk", expected, "Could not send the update script to the server") + _step(server, launch_script(run_id, limit_s), "launched", 1, "Could not start the update on the server") + + +def poll(server, run_id, offset, budget=None): + """One read of status.log from line offset: {"lines": [CBVULN lines], "next": int, "more": bool, "alive": bool}. + One try; raises WinTaskError when the call fails or its reply is not a valid answer.""" + script = poll_script(run_id, offset, _budget(server) if budget is None else budget) + lines, transport = _call(server, script) + if "terr" in transport or not str(transport.get("next", "")).isdigit(): + raise WinTaskError((transport.get("terr") or "no reply")[:200]) + return { + "lines": lines, + "next": int(transport["next"]), + "more": transport.get("more") == "1", + "alive": transport.get("alive") != "0", + } + + +def cleanup(server, run_id): + """Stop and unregister the task and delete the run directory. Never raises.""" + try: + exec_script(server, cleanup_script(run_id)) + except Exception: + pass diff --git a/extensions/XUI-wqrj0e3p/tests/test_vuln_fleet.py b/extensions/XUI-wqrj0e3p/tests/test_vuln_fleet.py index 53a616dd..214b740b 100644 --- a/extensions/XUI-wqrj0e3p/tests/test_vuln_fleet.py +++ b/extensions/XUI-wqrj0e3p/tests/test_vuln_fleet.py @@ -1733,7 +1733,8 @@ def test_a_live_run_reports_the_jobs_progress(self): store.set_resource_run(5, {"job_id": 40, "started": "2026-11-23T10:00:00Z", "server_ids": [1, 2, 3]}) self.table.add(40, done=2, total=3) self.assertEqual(fleet.resource_run(5), {"job_id": 40, "job_url": "/jobs/40/", - "started": "2026-11-23T10:00:00Z", "done": 2, "total": 3}) + "started": "2026-11-23T10:00:00Z", "done": 2, "total": 3, + "kind": "scan", "message": ""}) def test_before_the_job_reports_anything_the_total_comes_from_the_marker(self): store.set_resource_run(5, {"job_id": 40, "started": "t", "server_ids": [1, 2, 3]}) @@ -2385,6 +2386,11 @@ def test_no_double_braces_in_any_python_file(self): if filename.endswith(".py"): with open(os.path.join(package, filename), encoding="utf-8") as handle: text = handle.read() + if filename in ("vuln_patch_job.py", "vuln_resource_patch_job.py"): + # The one declared plugin input: CloudBolt creates the action's input from this line. + token = 'RESTART_TOKEN = """' + "{" * 2 + " restart_if_needed " + "}" * 2 + '"""' + self.assertEqual(text.count(token), 1, filename) + text = text.replace(token, "") self.assertNotIn("{" + "{", text, filename) self.assertNotIn("}" + "}", text, filename) diff --git a/extensions/XUI-wqrj0e3p/tests/test_vuln_patch.py b/extensions/XUI-wqrj0e3p/tests/test_vuln_patch.py new file mode 100644 index 00000000..f260d8cf --- /dev/null +++ b/extensions/XUI-wqrj0e3p/tests/test_vuln_patch.py @@ -0,0 +1,1562 @@ +""" +Checks for the update job of the Vulnerabilities XUI (vuln_patch.py, vuln_patch.sh, vuln_patch_job.py, vuln_api.py +and the handover edits to vuln_jobs.py) without CloudBolt: CloudBolt's modules are stubs, the findings store and the +server's state are in memory, and the guest is a scripted fake that answers each mode of the script. + + python -B -m unittest discover -s extensions/XUI-wqrj0e3p/tests -p "test_vuln_patch.py" + +The stubs are in place only while this file imports the extension's modules (the same swap test_vuln_fleet.py makes, +with the modules this file needs), so another test file's stubs are not disturbed. +""" +import contextlib +import importlib +import os +import re +import shutil +import subprocess +import sys +import tempfile +import types +import unittest +from unittest import mock + +HERE = os.path.dirname(os.path.abspath(__file__)) +EXT = os.path.dirname(HERE) +PACKAGE = "xui.io_cloudbolt_vulnerabilities" +PKG_DIR = os.path.join(EXT, "io_cloudbolt_vulnerabilities") + + +class IntegrityError(Exception): + pass + + +class CancelJob(BaseException): + """Stands in for CloudBolt's CancelJobException, which is a BaseException.""" + + +class Http404(Exception): + pass + + +class TimeoutException(Exception): + """Stands in for utilities.exceptions.TimeoutException.""" + + +class FakeLogger: + def __init__(self, *a): + pass + + def __getattr__(self, name): + return lambda *a, **k: None + + +def _module(name, **attrs): + module = types.ModuleType(name) + module.__dict__.update(attrs) + return module + + +TMP = tempfile.mkdtemp(prefix="vuln-patch-test-") +STUBS = {} +EVENTS = [] + + +def _stub(name, **attrs): + STUBS[name] = _module(name, **attrs) + return STUBS[name] + + +_stub("django") +_stub("django.conf", settings=types.SimpleNamespace(PROSERV_DIR=TMP, CLOUDBOLT_OS_USER="u", CLOUDBOLT_OS_GROUP="g")) +_stub("django.http", FileResponse=object, Http404=Http404, HttpResponse=object) +_stub("django.urls", reverse=lambda *a, **k: "/x/") +_stub("django.db", IntegrityError=IntegrityError, + transaction=types.SimpleNamespace(atomic=lambda: contextlib.nullcontext())) +_stub("cbhooks") +_stub("cbhooks.models", CloudBoltHook=object) +_stub("accounts") +_stub("accounts.models", Group=object, UserProfile=object) +_stub("infrastructure") +_stub("infrastructure.models", Server=object) +_stub("jobs") +_stub("jobs.models", Job=object) +_stub("portals") +_stub("portals.models") +_stub("utilities") +_stub("utilities.events", add_server_event=lambda *a, **k: EVENTS.append((a, k))) +_stub("utilities.exceptions", TimeoutException=TimeoutException) +_stub("utilities.logger", ThreadLogger=FakeLogger) +_xui = _stub("xui") +_xui.__path__ = [EXT] + + +def _import_extension(): + """Import the extension's modules against the stubs, leaving sys.modules as it was found.""" + touched = [k for k in sys.modules if k == "xui" or k.startswith(PACKAGE) or k in STUBS] + saved = {k: sys.modules[k] for k in touched} + for key in touched: + del sys.modules[key] + sys.modules.update(STUBS) + try: + names = ("vuln_store", "vuln_match", "vuln_db", "vuln_tools", "vuln_repo", "vuln_hooks", "vuln_jobs", + "vuln_fleet", "vuln_patch", "vuln_api") + return {name: importlib.import_module(PACKAGE + "." + name) for name in names} + finally: + for key in [k for k in sys.modules if k == "xui" or k.startswith(PACKAGE) or k in STUBS]: + del sys.modules[key] + sys.modules.update(saved) + + +MODS = _import_extension() +store, db, tools, repo, hooks, jobs, fleet, patch, api = (MODS[n] for n in ( + "vuln_store", "vuln_db", "vuln_tools", "vuln_repo", "vuln_hooks", "vuln_jobs", "vuln_fleet", "vuln_patch", + "vuln_api")) + +# The template engine's markers, built here so this file has none of its own. +OPEN, CLOSE = b"{" * 2, b"}" * 2 +BOOT_1 = "11111111-2222-3333-4444-555555555555" +BOOT_2 = "66666666-7777-8888-9999-000000000000" +RUN = "patch-20261124T101500Z-abc123" + + +# ---------------------------------------------------------------- fakes +def make_server(**over): + data = dict( + id=7, hostname="web-01", status="ACTIVE", power_status="POWERON", + group=types.SimpleNamespace(is_unassigned=False, name="Dev"), + environment=types.SimpleNamespace(name="Env"), + os_family=types.SimpleNamespace(get_base_name=lambda: "Linux", name="Linux"), + tags=types.SimpleNamespace(all=lambda: []), + resource_handler=types.SimpleNamespace(cast=lambda: types.SimpleNamespace(can_run_scripts_on_servers=True)), + use_tech_specific_script_execution=lambda: False, + get_preferred_ip=lambda: "10.0.0.5", + get_credentials=lambda **kw: {"username": "root", "password": "secret"}, + jobs=types.SimpleNamespace(add=lambda job: None), + ) + data.update(over) + return types.SimpleNamespace(**data) + + +def windows_server(**over): + data = dict(os_family=types.SimpleNamespace(get_base_name=lambda: "Windows", name="Windows"), + is_windows=lambda: True) + data.update(over) + return make_server(**data) + + +def solaris_server(**over): + return make_server(os_family=types.SimpleNamespace(get_base_name=lambda: "Solaris", name="Solaris"), **over) + + +def out(**fields): + """Script output: a CBVULN line per field, then the final done line.""" + lines = ["CBVULN|{}|{}".format(key, value) for key, value in fields.items()] + return "\n".join(lines + ["CBVULN|done|1"]) + "\n" + + +class Guest: + """The server: answers each call of the script by its MODE. A mode's answers are used in turn and the last one + repeats; an exception in the list is raised.""" + + def __init__(self): + self.calls = [] + self.scripts = [] + self.queues = {} + self.on_call = None + + def answers(self, mode, *items): + self.queues[mode] = list(items) + + def __call__(self, server, script, timeout, job=None): + mode = re.search(r"^MODE=(\w+)", script, re.M).group(1) + self.calls.append(mode) + self.scripts.append(script) + if self.on_call: + self.on_call(mode) + queue = self.queues.get(mode) + if not queue: + raise AssertionError("no answer for mode " + mode) + item = queue.pop(0) if len(queue) > 1 else queue[0] + if isinstance(item, BaseException): + raise item + return item + + +def happy_guest(): + guest = Guest() + guest.answers("probe", out(boot_id=BOOT_1)) + guest.answers("start", out(state="running", os="Rocky", distro="rhel")) + guest.answers("poll", out(state="running", phase="Updating packages"), + out(state="done", updated=7, failed=0, exit=0, restart=0, kernel_running="k1", kernel_newest="k1")) + guest.answers("oldkernels", out(removed=0, exit=0, kernel_running="k1", kernel_newest="k1")) + guest.answers("cleanup", out()) + return guest + + +class Clock: + def __init__(self): + self.now = 0.0 + + def sleep(self, seconds): + self.now += seconds + + def clock(self): + return self.now + + +class FakeHook: + def __init__(self, job_id=11): + self.calls = [] + self.job = types.SimpleNamespace(id=job_id, label="", save=lambda **k: None) + + def run_as_job(self, **kw): + self.calls.append(kw) + return [self.job] + + +def make_job(job_id=11, username="alice"): + progress = [] + return types.SimpleNamespace( + id=job_id, owner=types.SimpleNamespace(user=types.SimpleNamespace(username=username)), + set_progress=lambda message, **k: progress.append(message), progress=progress, + ) + + +class Refused: + def __init__(self, message="no", status=409): + self.message, self.status = message, status + + +class Base(unittest.TestCase): + """In-memory state of one server, a guest, a clock, and the settings the job reads.""" + + def setUp(self): + del EVENTS[:] + self.state = {"active": None, "last": None, "history": []} + self.settings = {"visibility": "linux", "scan_timeout_min": 20, "patch_timeout_min": 90, + "restart_wait_min": 30, "patching": True} + self.guest = happy_guest() + self.clock = Clock() + self.markers = [] + self.cancelled = False + self.active_jobs = {} + self.patches = [ + mock.patch.dict(sys.modules, STUBS), + mock.patch.object(store, "get_settings", side_effect=lambda: dict(self.settings)), + mock.patch.object(store, "job_settings", return_value={"timeout_min": 20}), + mock.patch.object(store, "start_lock", lambda server_id: contextlib.nullcontext()), + mock.patch.object(store, "read_state", side_effect=lambda server_id: self.state), + mock.patch.object(store, "_update", side_effect=lambda server_id, change: change(self.state)), + mock.patch.object(store, "set_active", side_effect=self._set_active), + mock.patch.object(store, "clear_active", side_effect=self._clear_active), + mock.patch.object(tools, "status", return_value={"ready": True, "db": {"built": "b"}}), + mock.patch.object(fleet, "default_base_url", return_value="https://cb.example.com"), + mock.patch.object(fleet, "_cancelled", side_effect=lambda job: self.cancelled), + mock.patch.object(jobs, "_execute", self.guest), + mock.patch.object(jobs, "Job", self._job_model()), + mock.patch.object(patch, "_sleep", self.clock.sleep), + mock.patch.object(patch, "_clock", self.clock.clock), + mock.patch.object(db, "server_summary", side_effect=self._summary), + ] + for patcher in self.patches: + patcher.start() + self.addCleanup(patcher.stop) + self.summaries = [{"vulns": 10, "vuln_fixable": 8}, {"vulns": 2, "vuln_fixable": 0}] + self.rescan_job = types.SimpleNamespace(id=99, status="SUCCESS") + self.rescan_started = types.SimpleNamespace(id=99, wait_for_completion=lambda timeout: self.rescan_job) + self.rescan_calls = [] + self.start_result = self.rescan_started + + def _set_active(self, server_id, marker): + self.state["active"] = marker + self.markers.append(dict(marker)) + + def _clear_active(self, server_id, scan_id=None): + active = self.state.get("active") + if scan_id is None or (isinstance(active, dict) and active.get("scan_id") == scan_id): + self.state["active"] = None + + def _summary(self, server_id): + return self.summaries.pop(0) if self.summaries else None + + def _job_model(self): + outer = self + + class Manager: + def filter(self, **kw): + job = outer.active_jobs.get(kw.get("id")) + return types.SimpleNamespace(first=lambda: job) + + return types.SimpleNamespace(objects=Manager()) + + def rescan(self): + """Make jobs.start a spy answering with the scan job.""" + def start(profile, server, base_url, parent_job=None, handover_from=None): + self.rescan_calls.append({"parent_job": parent_job, "handover_from": handover_from, + "active": self.state.get("active")}) + return self.start_result + + patcher = mock.patch.object(jobs, "start", side_effect=start) + patcher.start() + self.addCleanup(patcher.stop) + + def go(self, servers=None, restart=True, job=None): + job = job or make_job() + self.rescan() + return job, patch.run_patch(job, servers=servers or [make_server()], restart_if_needed=restart) + + +# ---------------------------------------------------------------- the restart flag +class RestartFlagTests(unittest.TestCase): + def test_values(self): + for value in (True, "True", "true", "1", "yes", "on"): + self.assertIs(patch.parse_restart_flag(value, default=False), True, value) + for value in (False, "false", "False", "0", "no", "off"): + self.assertIs(patch.parse_restart_flag(value), False, value) + + def test_nothing_or_unreadable_is_the_default(self): + self.assertIs(patch.parse_restart_flag(None), True) + self.assertIs(patch.parse_restart_flag(None, default=False), False) + self.assertIs(patch.parse_restart_flag("maybe"), True) + self.assertIs(patch.parse_restart_flag("", default=False), False) + + +# ---------------------------------------------------------------- the guest script +class ScriptTests(unittest.TestCase): + def path(self): + return os.path.join(PKG_DIR, "vuln_patch.sh") + + def test_header_quotes_every_value(self): + script = patch._linux_build_script("reboot", RUN, BOOT_1) + for line in ("MODE=reboot\n", "RUN_ID=" + RUN + "\n", "BOOT_ID=" + BOOT_1 + "\n", "REBOOT_DELAY_S=20\n"): + self.assertIn("\n" + line, script) + self.assertIn("BOOT_ID=''\n", patch._linux_build_script("poll", RUN)) + + def test_a_bad_run_id_or_boot_id_is_refused(self): + for bad in ("x; rm -rf /", "short", "has space in it", "a" * 65, "id$(touch x)", "", None, "abc\nMODE=poll"): + with self.assertRaises(patch.PatchFailed, msg=repr(bad)): + patch._linux_build_script("poll", bad) + for bad in ("; reboot", BOOT_1 + "x", "not-a-uuid", "AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE"): + with self.assertRaises(patch.PatchFailed, msg=repr(bad)): + patch._linux_build_script("reboot", RUN, bad) + with self.assertRaises(patch.PatchFailed): + patch._linux_build_script("rm", RUN) + + def test_the_file_is_small_ascii_lf_and_has_no_template_marker(self): + with open(self.path(), "rb") as handle: + raw = handle.read() + self.assertLess(len(raw), 32 * 1024) + raw.decode("ascii") + self.assertNotIn(b"\r", raw) + self.assertNotIn(OPEN, raw) + self.assertNotIn(CLOSE, raw) + script = patch._linux_build_script("start", RUN) + self.assertNotIn(OPEN.decode(), script) + self.assertLess(len(script), 32 * 1024) + + def test_no_other_double_brace_in_the_new_files(self): + for name in ("vuln_patch.py", "vuln_api.py", "vuln_patch.sh"): + with open(os.path.join(PKG_DIR, name), "rb") as handle: + raw = handle.read() + raw.decode("ascii") + self.assertNotIn(OPEN, raw, name) + with open(os.path.join(PKG_DIR, "vuln_patch_job.py"), "rb") as handle: + lines = [line for line in handle.read().decode("ascii").splitlines() if OPEN.decode() in line] + self.assertEqual(lines, ['RESTART_TOKEN = """' + OPEN.decode() + ' restart_if_needed ' + CLOSE.decode() + '"""']) + + def test_the_job_file_reloads_the_patch_module(self): + with open(os.path.join(PKG_DIR, "vuln_patch_job.py"), encoding="ascii") as handle: + text = handle.read() + self.assertIn('"xui.io_cloudbolt_vulnerabilities.vuln_patch"', text) + self.assertIn("run_patch(job, **kwargs)", text) + + def test_the_script_passes_bash_n(self): + bash = shutil.which("bash") + if not bash: + self.skipTest("bash is not installed") + with open(self.path(), "rb") as handle: + raw = handle.read() + for script in (raw, patch._linux_build_script("poll", RUN).encode("ascii")): + done = subprocess.run([bash, "-n"], input=script, capture_output=True, timeout=60) + self.assertEqual(done.returncode, 0, done.stderr.decode(errors="replace")) + + def test_every_vendor_command_is_documented_where_it_is_used(self): + with open(self.path(), encoding="ascii") as handle: + text = handle.read() + for url in ("https://dnf.readthedocs.io/en/latest/command_ref.html", + "https://dnf.readthedocs.io/en/latest/conf_ref.html", + "https://dnf-plugins-core.readthedocs.io/en/latest/needs_restarting.html", + "https://docs.aws.amazon.com/linux/al2023/ug/deterministic-upgrades.html", + "https://docs.aws.amazon.com/linux/al2023/ug/managing-repos-os-updates.html", + "https://manpages.ubuntu.com/manpages/noble/man8/apt-get.8.html", + "https://www.freedesktop.org/software/systemd/man/latest/systemd-run.html"): + self.assertIn(url, text) + self.assertIn("--oldinstallonly", text) + self.assertIn("Remv", text) + self.assertIn("Purg", text) + + +# ---------------------------------------------------------------- the output +class ParseTests(unittest.TestCase): + def test_unknown_keys_and_other_lines_are_ignored(self): + parsed = patch.parse_patch_output( + "noise\nCBVULN|evil|x\nCBVULN|state|running\nCBVULN|phase|Updating packages\nCBVULN|done|1\n") + self.assertEqual((parsed["state"], parsed["phase"], parsed["done"]), ("running", "Updating packages", True)) + self.assertNotIn("evil", parsed) + self.assertIs(patch.parse_patch_output, patch._linux_parse) + + def test_ints_are_capped_and_a_later_line_wins(self): + parsed = patch._linux_parse("CBVULN|updated|99999999999\nCBVULN|failed|-1\nCBVULN|exit|5000\n" + "CBVULN|removed|abc\nCBVULN|updated|12\nCBVULN|updated|7\n") + self.assertEqual((parsed["updated"], parsed["failed"], parsed["exit"], parsed["removed"]), (7, None, None, None)) + + def test_values_outside_their_list_are_dropped(self): + parsed = patch._linux_parse("CBVULN|state|sleeping\nCBVULN|distro|plan9\nCBVULN|restart|maybe\n" + "CBVULN|boot_id|not-a-uuid\n") + self.assertEqual((parsed["state"], parsed["distro"], parsed["restart"], parsed["boot_id"]), ("", "", "", "")) + parsed = patch._linux_parse(out(state="died", distro="amzn2023", restart="unknown", boot_id=BOOT_1)) + self.assertEqual((parsed["state"], parsed["distro"], parsed["restart"], parsed["boot_id"]), + ("died", "amzn2023", "unknown", BOOT_1)) + + def test_text_is_cleaned_and_notes_are_limited(self): + parsed = patch._linux_parse("CBVULN|failure|see https://evil.example/x?t=1 now\n" + + "".join("CBVULN|note|n{}\n".format(i) for i in range(9))) + self.assertNotIn("evil.example", parsed["failure"]) + self.assertEqual(len(parsed["notes"]), patch.MAX_NOTES) + parsed = patch._linux_parse("CBVULN|reason|" + "x" * 5000) + self.assertLessEqual(len(parsed["reason"]), patch.MESSAGE_LEN) + + @unittest.skipUnless(shutil.which("bash"), "bash is not installed") + def test_the_real_script_reports_a_missing_run(self): + script = patch._linux_build_script("poll", "patch-nothing-here-0001") + # Run the built launcher (an sh script) the way the guest does, from stdin. + done = subprocess.run(["sh"], input=script.encode("ascii"), capture_output=True, timeout=60) + parsed = patch._linux_parse(done.stdout.decode(errors="replace")) + self.assertTrue(parsed["done"], done.stderr.decode(errors="replace")) + self.assertEqual(parsed["state"], "missing") + + +# ---------------------------------------------------------------- eligibility +class EligibilityTests(Base): + def test_a_linux_server_is_eligible(self): + self.assertEqual(patch.eligibility(make_server()), "") + + def test_windows_needs_the_microsoft_data_for_the_rescan(self): + with mock.patch.object(jobs, "msrc_ready", return_value=True): + self.assertEqual(patch.eligibility(windows_server()), "") + with mock.patch.object(jobs, "msrc_ready", return_value=False): + self.assertEqual(patch.eligibility(windows_server()), "no_windows_data") + + def test_another_operating_system_is_unsupported(self): + self.assertEqual(patch.eligibility(solaris_server()), "unsupported_os") + + def test_unassigned_and_powered_off(self): + unassigned = make_server(group=types.SimpleNamespace(is_unassigned=True, name="Unassigned")) + self.assertEqual(patch.eligibility(unassigned), "unassigned") + self.assertEqual(patch.eligibility(make_server(power_status="POWEROFF")), "powered_off") + self.assertEqual(patch.eligibility(make_server(status="HISTORICAL")), "historical") + + def test_the_scanner_must_be_ready_for_the_rescan(self): + with mock.patch.object(tools, "status", return_value={"ready": False, "db": {"built": ""}}): + self.assertEqual(patch.eligibility(make_server()), "not_set_up") + with mock.patch.object(fleet, "default_base_url", return_value=""): + self.assertEqual(patch.eligibility(make_server()), "no_site_url") + + def test_an_error_while_checking_is_unknown(self): + with mock.patch.object(store, "get_settings", side_effect=RuntimeError("disk")): + self.assertEqual(patch.eligibility(make_server()), "unknown") + + +# ---------------------------------------------------------------- start_job +class StartJobTests(Base): + def setUp(self): + super().setUp() + self.hook = FakeHook() + for patcher in (mock.patch.object(hooks, "patch_hook", create=True, return_value=self.hook), + mock.patch.object(jobs, "precheck", return_value=None)): + patcher.start() + self.addCleanup(patcher.stop) + + def test_one_server(self): + added = [] + server = make_server(jobs=types.SimpleNamespace(add=added.append)) + job = patch.start_job("owner", server=server, restart_if_needed="false") + self.assertIs(job, self.hook.job) + call = self.hook.calls[0] + self.assertEqual((call["owner"], call["servers"], call["parent_job"]), ("owner", [server], None)) + self.assertEqual(call["context"], {"restart_if_needed": False}) + self.assertEqual(job.label, "Install updates: web-01") + self.assertEqual(added, [job]) + + def test_a_list_of_servers(self): + added = [] + servers = [make_server(id=i, hostname="h{}".format(i), jobs=types.SimpleNamespace(add=added.append)) + for i in (1, 2, 3)] + job = patch.start_job("owner", servers=servers, parent_job="parent") + self.assertEqual(self.hook.calls[0]["servers"], servers) + self.assertEqual(self.hook.calls[0]["parent_job"], "parent") + self.assertEqual(self.hook.calls[0]["context"], {"restart_if_needed": True}) + self.assertEqual(job.label, "Install updates: 3 servers") + self.assertEqual(added, [job, job, job]) + + def test_the_first_server_that_cannot_be_updated_refuses_the_whole_start(self): + servers = [make_server(id=1), windows_server(id=2, hostname="win-01")] + with mock.patch.object(jobs, "msrc_ready", return_value=False): + refusal = patch.start_job("owner", servers=servers) + self.assertEqual(refusal.status, 409) + self.assertIn("win-01", refusal.message) + self.assertEqual(self.hook.calls, []) + + def test_the_scan_prechecks_are_applied_per_server(self): + with mock.patch.object(jobs, "precheck", return_value=jobs.Refusal("not ready", 409)): + refusal = patch.start_job("owner", server=make_server()) + self.assertEqual(refusal.message, "not ready") + self.assertEqual(self.hook.calls, []) + + def test_no_server_and_a_job_that_did_not_start(self): + self.assertEqual(patch.start_job("owner").status, 400) + self.hook.run_as_job = lambda **kw: [] + self.assertEqual(patch.start_job("owner", server=make_server()).status, 500) + + +# ---------------------------------------------------------------- one server, end to end +class FlowTests(Base): + def test_success_with_no_restart_needed(self): + job, result = self.go() + status, output, errors, outputs = result + self.assertEqual((status, errors), ("SUCCESS", "")) + # No restart was needed, so none is pending: the old kernels go, without a restart. + self.assertEqual(self.guest.calls, ["probe", "start", "poll", "poll", "oldkernels", "cleanup"]) + self.assertEqual(outputs["counts"], {"updated": 1, "no_updates": 0, "restart_pending": 0, "failed": 0, "skipped": 0}) + record = self.state["patch"] + self.assertEqual(set(record), {"at", "by", "job_id", "status", "before", "after", "updated", "failed", + "restarted", "restart_needed", "kernels_removed", "duration_s", "message", "family"}) + self.assertEqual((record["status"], record["by"], record["job_id"]), ("updated", "alice", 11)) + self.assertEqual((record["before"], record["after"]), ({"vulns": 10, "vuln_fixable": 8}, + {"vulns": 2, "vuln_fixable": 0})) + self.assertEqual((record["updated"], record["failed"], record["restarted"], record["restart_needed"], + record["kernels_removed"]), (7, 0, False, False, 0)) + self.assertEqual(record["duration_s"], 30) + self.assertEqual(outputs["servers"]["7"]["hostname"], "web-01") + self.assertEqual(outputs["servers"]["7"]["status"], "updated") + self.assertEqual(output, "web-01: 7 packages updated, known vulnerabilities 10 to 2, with a fix 8 to 0.") + + def test_the_marker_is_written_with_kind_patch_and_cleared(self): + seen = [] + self.guest.on_call = lambda mode: seen.append((mode, dict(self.state["active"] or {}))) + self.go() + marker = self.markers[0] + self.assertEqual(set(marker), {"job_id", "scan_id", "started", "requested_by", "kind"}) + self.assertEqual((marker["job_id"], marker["kind"], marker["requested_by"]), (11, "patch", "alice")) + self.assertTrue(marker["scan_id"].startswith("patch-")) + self.assertTrue(store.SCAN_ID_RE.fullmatch(marker["scan_id"])) + self.assertTrue(all(active["kind"] == "patch" for mode, active in seen if mode != "cleanup")) + self.assertIsNone(self.state["active"]) + self.assertIn(marker["scan_id"], self.guest.scripts[0]) + + def test_the_rescan_is_a_handover_child_of_the_job(self): + job, result = self.go() + call = self.rescan_calls[0] + self.assertIs(call["parent_job"], job) + self.assertEqual(call["handover_from"], 11) + self.assertEqual(call["active"]["kind"], "patch") + + def test_the_server_event_is_an_info_event(self): + job, result = self.go() + self.assertEqual(len(EVENTS), 1) + args, kwargs = EVENTS[0] + self.assertEqual(args[0], "INFO") + self.assertEqual(kwargs["job"], job) + + def test_restart_needed_but_not_allowed_is_restart_pending_and_still_rescans(self): + self.guest.answers("poll", out(state="done", updated=3, failed=0, exit=0, restart=1, restart_reason="kernel")) + job, (status, output, errors, outputs) = self.go(restart=False) + self.assertEqual(status, "WARNING") + self.assertNotIn("reboot", self.guest.calls) + self.assertEqual(self.state["patch"]["status"], "restart_pending") + self.assertTrue(self.state["patch"]["restart_needed"]) + self.assertFalse(self.state["patch"]["restarted"]) + self.assertEqual(len(self.rescan_calls), 1) + self.assertEqual(outputs["counts"]["restart_pending"], 1) + self.assertIn("restart is needed", self.state["patch"]["message"]) + + def restart_guest(self): + self.guest.answers("poll", out(state="done", updated=3, failed=0, exit=0, restart=1)) + self.guest.answers("reboot", out(boot_id=BOOT_1, note="restart scheduled")) + self.guest.answers("probe", out(boot_id=BOOT_1), RuntimeError("connection refused"), out(boot_id=BOOT_1), + RuntimeError("timed out"), out(boot_id=BOOT_2)) + self.guest.answers("oldkernels", out(removed=4, exit=0)) + + def test_restart_waits_for_a_new_boot_id_tolerating_probe_errors(self): + self.restart_guest() + job, (status, output, errors, outputs) = self.go() + self.assertEqual(status, "SUCCESS") + calls = self.guest.calls + self.assertEqual(calls[:4], ["probe", "start", "poll", "reboot"]) + self.assertEqual(calls.count("probe"), 5) + self.assertEqual(calls[-2:], ["oldkernels", "cleanup"]) + record = self.state["patch"] + self.assertEqual((record["status"], record["restarted"], record["kernels_removed"]), ("updated", True, 4)) + self.assertEqual(len(self.rescan_calls), 1) + # The reboot call carries the boot id the server had before the update. + reboot = self.guest.scripts[calls.index("reboot")] + self.assertIn("BOOT_ID=" + BOOT_1 + "\n", reboot) + + def test_a_boot_id_that_never_changes_fails_at_the_deadline(self): + self.restart_guest() + self.guest.answers("probe", out(boot_id=BOOT_1)) + job, (status, output, errors, outputs) = self.go() + self.assertEqual(status, "FAILURE") + self.assertEqual(self.state["patch"]["status"], "failed") + self.assertIn("did not come back within 30 minutes", self.state["patch"]["message"]) + self.assertNotIn("oldkernels", self.guest.calls) + self.assertEqual(self.rescan_calls, []) + self.assertIsNone(self.state["active"]) + self.assertGreater(self.clock.now, 30 * 60) + self.assertEqual(self.state["patch"]["updated"], 3) + + def test_old_kernels_failing_does_not_fail_the_update(self): + self.restart_guest() + self.guest.answers("oldkernels", out(exit=1, failure="Error: nothing")) + job, (status, output, errors, outputs) = self.go() + self.assertEqual(status, "WARNING") + self.assertEqual(self.state["patch"]["status"], "updated") + self.assertIsNone(self.state["patch"]["kernels_removed"]) + self.assertIn("Old kernels were not removed", self.state["patch"]["message"]) + + def test_twenty_lost_polls_fail_the_update(self): + self.guest.answers("poll", RuntimeError("no route")) + job, (status, output, errors, outputs) = self.go() + self.assertEqual(status, "FAILURE") + self.assertEqual(self.guest.calls.count("poll"), patch.LOST_POLLS) + self.assertIn("lost contact", self.state["patch"]["message"]) + self.assertEqual(self.rescan_calls, []) + + def test_lost_polls_in_a_row_are_counted_not_in_total(self): + answers = ([RuntimeError("blip")] * (patch.LOST_POLLS - 1) + [out(state="running")] + + [RuntimeError("blip")] * (patch.LOST_POLLS - 1) + + [out(state="done", updated=1, failed=0, exit=0, restart=0)]) + self.guest.answers("poll", *answers) + job, (status, output, errors, outputs) = self.go() + self.assertEqual(status, "SUCCESS") + + def test_a_poll_with_no_state_counts_as_lost(self): + self.guest.answers("poll", out()) + job, (status, output, errors, outputs) = self.go() + self.assertEqual(self.guest.calls.count("poll"), patch.LOST_POLLS) + self.assertEqual(status, "FAILURE") + + def test_the_patch_time_limit(self): + self.settings["patch_timeout_min"] = 10 + self.guest.answers("poll", out(state="running")) + job, (status, output, errors, outputs) = self.go() + self.assertEqual(status, "FAILURE") + self.assertIn("did not finish within 10 minutes", self.state["patch"]["message"]) + self.assertIn("may still be running", self.state["patch"]["message"]) + self.assertIn("dnf history, or dpkg --configure -a", self.state["patch"]["message"]) + + def test_a_worker_that_died_fails_the_update(self): + self.guest.answers("poll", out(state="died", updated=2)) + job, (status, output, errors, outputs) = self.go() + self.assertEqual(status, "FAILURE") + record = self.state["patch"] + self.assertEqual(record["status"], "failed") + self.assertEqual(record["message"], patch.STOPPED) + self.assertIn("dnf history, or dpkg --configure -a", record["message"]) + self.assertEqual(record["updated"], 2) + self.assertEqual(errors, patch.STOPPED) + self.assertIsNone(self.state["active"]) + + def test_the_package_manager_failing_is_a_failure_with_its_reason(self): + self.guest.answers("poll", out(state="done", updated=0, failed=2, exit=1, failure="Error: Failed to download")) + job, (status, output, errors, outputs) = self.go() + self.assertEqual(status, "FAILURE") + self.assertIn("Failed to download", self.state["patch"]["message"]) + self.assertEqual(self.state["patch"]["failed"], 2) + + def test_start_is_refused_while_another_worker_runs(self): + self.guest.answers("start", out(reason="another update is already running on this server")) + job, (status, output, errors, outputs) = self.go() + self.assertEqual(status, "FAILURE") + self.assertNotIn("poll", self.guest.calls) + self.assertIn("another update is already running", self.state["patch"]["message"]) + self.assertIsNone(self.state["active"]) + + def test_an_unreadable_boot_id_changes_nothing(self): + self.guest.answers("probe", out(boot_id="")) + job, (status, output, errors, outputs) = self.go() + self.assertEqual(status, "FAILURE") + self.assertNotIn("start", self.guest.calls) + + def test_a_rescan_that_cannot_start_leaves_the_update_as_updated_with_a_warning(self): + self.start_result = Refused("The scanner is busy.") + job, (status, output, errors, outputs) = self.go() + self.assertEqual(status, "WARNING") + record = self.state["patch"] + self.assertEqual((record["status"], record["after"]), ("updated", None)) + self.assertEqual(record["before"], {"vulns": 10, "vuln_fixable": 8}) + self.assertIn("installed and the rescan failed", record["message"]) + self.assertEqual(outputs["counts"], {"updated": 1, "no_updates": 0, "restart_pending": 0, "failed": 0, "skipped": 0}) + self.assertIsNone(self.state["active"]) + + def test_a_rescan_that_fails_or_times_out_is_a_warning_too(self): + self.rescan_job = types.SimpleNamespace(id=99, status="FAILURE") + job, (status, output, errors, outputs) = self.go() + self.assertEqual((status, self.state["patch"]["status"], self.state["patch"]["after"]), ("WARNING", "updated", None)) + + def never(timeout): + raise TimeoutException("too slow") + + self.rescan_started.wait_for_completion = never + self.state.pop("patch") + self.summaries[:] = [{"vulns": 1, "vuln_fixable": 1}] + job, (status, output, errors, outputs) = self.go() + self.assertEqual((status, self.state["patch"]["after"]), ("WARNING", None)) + self.assertIn("did not finish", self.state["patch"]["message"]) + + def test_a_server_never_scanned_has_no_before_and_proceeds(self): + self.summaries[:] = [None, {"vulns": 3, "vuln_fixable": 1}] + job, (status, output, errors, outputs) = self.go() + self.assertEqual(status, "SUCCESS") + self.assertIsNone(self.state["patch"]["before"]) + self.assertEqual(self.state["patch"]["after"], {"vulns": 3, "vuln_fixable": 1}) + self.assertNotIn("known vulnerabilities", output) + + def test_the_marker_is_cleared_after_a_failure_and_after_a_cancel(self): + self.guest.answers("poll", CancelJob()) + job = make_job() + self.rescan() + with self.assertRaises(CancelJob): + patch.run_patch(job, servers=[make_server()], restart_if_needed=True) + self.assertIsNone(self.state["active"]) + self.assertTrue(any("keeps running" in message for message in job.progress)) + self.assertEqual(self.guest.calls[-1], "cleanup") + + def test_a_server_that_is_held_by_another_job_is_refused_untouched(self): + self.state["active"] = {"job_id": 5, "scan_id": "20261124T101500Z-aaaaaa", "started": "x", "requested_by": "bob"} + self.active_jobs[5] = types.SimpleNamespace(id=5, is_active=lambda: True) + job, (status, output, errors, outputs) = self.go() + self.assertEqual(status, "FAILURE") + self.assertEqual(self.guest.calls, []) + self.assertEqual(self.state["active"]["job_id"], 5) + self.assertIn("Job 5 is still running", output) + self.assertNotIn("patch", self.state) + + def test_a_second_update_job_on_the_same_server_is_refused(self): + job_a, (status, output, errors, outputs) = self.go() + self.state["active"] = {"job_id": 11, "scan_id": "patch-x1234567", "started": "x", "requested_by": "alice", + "kind": "patch"} + self.active_jobs[11] = types.SimpleNamespace(id=11, is_active=lambda: True) + with self.assertRaises(patch.PatchFailed): + patch._patch_one(make_job(12), make_server(), True, {}) + self.assertEqual(self.state["active"]["job_id"], 11) + + def test_a_server_of_another_family_raises_before_anything_is_touched(self): + with self.assertRaises(patch.PatchFailed) as caught: + patch._patch_one(make_job(), solaris_server(), True, {}) + self.assertEqual(str(caught.exception), patch.ONLY_SUPPORTED) + self.assertEqual((self.guest.calls, self.markers), ([], [])) + + def test_a_linux_server_is_dispatched_to_the_linux_runner(self): + facts = {"updated": 1, "failed": 0, "restart_needed": False, "restarted": False, "kernels_removed": None, + "notes": []} + self.rescan() + with mock.patch.object(patch, "_linux_patch", return_value=facts) as linux, \ + mock.patch.object(patch, "_linux_cleanup") as cleanup: + record = patch._patch_one(make_job(), make_server(), True, {}) + self.assertEqual(linux.call_count, 1) + self.assertEqual(cleanup.call_count, 1) + self.assertEqual((record["status"], record["hostname"]), ("updated", "web-01")) + + def test_the_progress_text_names_the_phase(self): + job, result = self.go() + self.assertTrue(any("Updating packages" in message for message in job.progress)) + + +# ---------------------------------------------------------------- several servers +class BulkTests(Base): + def servers(self): + return [make_server(id=i, hostname="h{}".format(i)) for i in (1, 2, 3)] + + def test_the_next_server_runs_after_a_failure(self): + polls = {"n": 0} + original = self.guest.__call__ + + def failing_second(server, script, timeout, job=None): + if re.search(r"^MODE=probe", script, re.M): + polls["n"] += 1 + if polls["n"] == 2 and re.search(r"^MODE=start", script, re.M): + return out(reason="dnf is not installed on the server") + return original(server, script, timeout, job) + + with mock.patch.object(jobs, "_execute", failing_second): + self.summaries[:] = [{"vulns": 5, "vuln_fixable": 5}] * 6 + job, (status, output, errors, outputs) = self.go(servers=self.servers()) + self.assertEqual(status, "FAILURE") + self.assertEqual(outputs["counts"], {"updated": 2, "no_updates": 0, "restart_pending": 0, "failed": 1, "skipped": 0}) + self.assertEqual(sorted(outputs["servers"]), ["1", "2", "3"]) + self.assertEqual(outputs["servers"]["2"]["status"], "failed") + self.assertEqual(len(self.rescan_calls), 2) + self.assertIn("h2: failed", output) + + def test_every_server_failing_is_a_failure(self): + self.guest.answers("start", out(reason="no")) + job, (status, output, errors, outputs) = self.go(servers=self.servers()) + self.assertEqual(status, "FAILURE") + self.assertEqual(outputs["counts"]["failed"], 3) + + def test_the_budget_stops_new_servers(self): + self.summaries[:] = [{"vulns": 5, "vuln_fixable": 5}] * 6 + # One server's worst case is (90 + 30 + 30) minutes = 9000 s; the first server takes 30 s. + with mock.patch.object(patch, "JOB_LIMIT_S", 9020): + job, (status, output, errors, outputs) = self.go(servers=self.servers()) + self.assertEqual(status, "WARNING") + self.assertEqual(outputs["counts"], {"updated": 1, "no_updates": 0, "restart_pending": 0, "failed": 0, "skipped": 2}) + self.assertEqual(list(outputs["servers"]), ["1"]) + self.assertIn("2 servers were not started", output) + self.assertIn("8 hour limit", output) + + def test_a_cancel_between_servers_stops_and_says_the_guest_keeps_running(self): + self.summaries[:] = [{"vulns": 5, "vuln_fixable": 5}] * 6 + servers = self.servers() + results = [] + + def after_first(mode): + if mode == "cleanup": + self.cancelled = True + + self.guest.on_call = after_first + job, (status, output, errors, outputs) = self.go(servers=servers) + self.assertEqual(status, "WARNING") + self.assertEqual(outputs["counts"], {"updated": 1, "no_updates": 0, "restart_pending": 0, "failed": 0, "skipped": 2}) + self.assertIn("keeps running", output) + self.assertEqual(results, []) + + def test_a_restart_pending_server_is_counted(self): + self.guest.answers("poll", out(state="done", updated=1, failed=0, exit=0, restart=1)) + self.summaries[:] = [{"vulns": 5, "vuln_fixable": 5}] * 4 + job, (status, output, errors, outputs) = self.go(servers=self.servers()[:2], restart=False) + self.assertEqual(outputs["counts"], {"updated": 0, "no_updates": 0, "restart_pending": 2, "failed": 0, "skipped": 0}) + self.assertEqual(status, "WARNING") + + def test_no_server_is_a_failure(self): + self.assertEqual(patch.run_patch(make_job())[0], "FAILURE") + + def test_the_servers_and_the_restart_flag_arrive_as_the_job_gives_them(self): + self.rescan() + server = make_server() + status = patch.run_patch(make_job(), server=server, restart_if_needed="False")[0] + self.assertEqual(status, "SUCCESS") + + +# ---------------------------------------------------------------- the handover in vuln_jobs.start +class HandoverTests(Base): + def setUp(self): + super().setUp() + self.queued = [] + self.set_active_calls = [] + + class Hook: + def run_as_job(hook, **kw): + self.queued.append(kw) + return [types.SimpleNamespace(id=42, save=lambda **k: None)] + + for patcher in ( + mock.patch.object(repo, "targets", return_value={"upload_url": "u", "tools": {}, "token": "t"}), + mock.patch.object(repo, "prepare"), + mock.patch.object(hooks, "scan_hook", return_value=Hook()), + mock.patch.object(store, "set_active", side_effect=lambda sid, marker: self.set_active_calls.append(marker)), + ): + patcher.start() + self.addCleanup(patcher.stop) + self.server = make_server() + self.server.jobs = types.SimpleNamespace(add=lambda job: None) + + def hold(self, kind="patch", job_id=11): + marker = {"job_id": job_id, "scan_id": "patch-20261124T101500Z-abc123", "started": "2026-11-24T10:15:00Z", + "requested_by": "alice"} + if kind: + marker["kind"] = kind + self.state["active"] = marker + self.active_jobs[job_id] = types.SimpleNamespace(id=job_id, is_active=lambda: True) + + def start(self, **kw): + return jobs.start(None, self.server, "https://cb.example.com", **kw) + + def test_a_handover_from_the_holding_patch_job_is_accepted_and_keeps_the_marker(self): + self.hold() + created = self.start(handover_from=11, parent_job="parent") + self.assertEqual(created.id, 42) + self.assertEqual(self.set_active_calls, []) + self.assertEqual(self.state["active"]["kind"], "patch") + self.assertEqual(self.queued[0]["parent_job"], "parent") + + def test_a_handover_skips_the_cooldown(self): + self.hold() + self.state["last"] = {"status": "completed", "finished": store.stamp()} + self.assertEqual(self.start(handover_from=11).id, 42) + + def test_without_a_handover_the_same_marker_refuses(self): + self.hold() + refused = self.start() + self.assertIsInstance(refused, jobs.Refusal) + self.assertEqual(refused.status, 409) + self.assertEqual(self.queued, []) + + def test_a_different_job_id_is_refused(self): + self.hold() + refused = self.start(handover_from=12) + self.assertIsInstance(refused, jobs.Refusal) + self.assertEqual((refused.status, self.queued), (409, [])) + + def test_a_scan_marker_cannot_be_taken_over(self): + self.hold(kind=None, job_id=11) + self.assertEqual(self.start(handover_from=11).status, 409) + self.assertEqual(self.queued, []) + + def test_a_handover_with_no_marker_is_refused(self): + self.assertEqual(self.start(handover_from=11).status, 409) + self.assertEqual(self.queued, []) + + def test_a_plain_start_still_sets_the_marker_and_keeps_the_cooldown(self): + created = self.start() + self.assertEqual(created.id, 42) + self.assertEqual(len(self.set_active_calls), 1) + self.assertNotIn("kind", self.set_active_calls[0]) + self.state["last"] = {"status": "completed", "finished": store.stamp()} + refused = self.start() + self.assertEqual(refused.status, 429) + + def test_precheck_is_what_start_refuses_with(self): + self.assertIsNone(jobs.precheck(self.server, "https://cb")) + self.assertEqual(jobs.precheck(self.server, "").message, jobs.NO_SITE_URL) + self.assertEqual(jobs.precheck(make_server(status="PROVFAILED"), "https://cb").message, jobs.NOT_ACTIVE) + refusal = self.start() + self.assertEqual(refusal.id if hasattr(refusal, "id") else None, 42) + bad = jobs.start(None, make_server(power_status="POWEROFF"), "https://cb") + self.assertEqual((bad.message, bad.status), ("The server is not powered on.", 409)) + + +# ---------------------------------------------------------------- the panel's active dict +class PanelActiveTests(Base): + def job(self): + return types.SimpleNamespace(id=11, is_active=lambda: True, get_absolute_url=lambda: "/jobs/11/", + get_progress=lambda: (0, 0, types.SimpleNamespace(message="Updating"))) + + def test_kind_and_title_for_an_update_and_for_a_scan(self): + self.active_jobs[11] = self.job() + self.state["active"] = {"job_id": 11, "scan_id": "patch-x1234567", "started": "t", "requested_by": "a", + "kind": "patch"} + active = jobs.panel_active(7) + self.assertEqual((active["kind"], active["title"], active["job_id"], active["message"]), + ("patch", "Installing updates", 11, "Updating")) + self.assertEqual(active["job_url"], "/jobs/11/") + self.state["active"] = {"job_id": 11, "scan_id": "20261124T101500Z-aaaaaa", "started": "t", "requested_by": "a"} + active = jobs.panel_active(7) + self.assertEqual((active["kind"], active["title"]), ("scan", "Scan running")) + self.assertEqual(set(active), {"job_id", "job_url", "message", "started", "kind", "title"}) + + +# ---------------------------------------------------------------- vuln_api +class ApiTests(Base): + def setUp(self): + super().setUp() + self.hook = FakeHook() + for patcher in (mock.patch.object(hooks, "patch_hook", create=True, return_value=self.hook), + mock.patch.object(jobs, "precheck", return_value=None)): + patcher.start() + self.addCleanup(patcher.stop) + self.ended = types.SimpleNamespace(id=11, status="SUCCESS", errors="") + self.hook.job.wait_for_completion = lambda timeout: self.ended + self.waited = [] + + def test_refused(self): + with mock.patch.object(jobs, "msrc_ready", return_value=False): + result = api.install_updates(windows_server(hostname="win-01"), "owner") + self.assertEqual(result["status"], "refused") + self.assertIn("win-01", result["message"]) + self.assertIsNone(result["job"]) + + def test_no_updates_is_completed_with_that_message(self): + self.state["patch"] = {"job_id": 11, "status": "no_updates", "restarted": False, "message": ""} + result = api.install_updates(make_server(hostname="web-01"), "owner") + self.assertEqual(result["status"], "completed") + self.assertEqual(result["message"], "No updates were available on web-01.") + + def test_timeout(self): + def never(timeout): + self.waited.append(timeout) + raise TimeoutException("slow") + + self.hook.job.wait_for_completion = never + result = api.install_updates(make_server(), "owner") + self.assertEqual(result["status"], "timeout") + self.assertIs(result["job"], self.hook.job) + self.assertEqual(self.waited, [(90 + 30 + 20) * 60 + api.WAIT_MARGIN_SECONDS]) + result = api.install_updates(make_server(), "owner", timeout=120) + self.assertEqual(self.waited[-1], 120) + + def test_completed_restart_pending_and_failed(self): + record = {"job_id": 11, "status": "updated", "restarted": True, "message": ""} + self.state["patch"] = record + result = api.install_updates(make_server(), "owner", restart_if_needed=False) + self.assertEqual(self.hook.calls[0]["context"], {"restart_if_needed": False}) + self.assertEqual((result["status"], result["patch"]), ("completed", record)) + self.assertIn("restarted", result["message"]) + record["status"] = "restart_pending" + self.assertEqual(api.install_updates(make_server(), "owner")["status"], "restart_pending") + record.update(status="failed", message="the server did not come back") + result = api.install_updates(make_server(), "owner") + self.assertEqual(result["status"], "failed") + self.assertIn("did not come back", result["message"]) + + def test_a_job_with_no_record_of_its_own_is_failed(self): + self.state["patch"] = {"job_id": 3, "status": "updated"} + self.ended = types.SimpleNamespace(id=11, status="FAILURE", errors="boom") + result = api.install_updates(make_server(), "owner") + self.assertEqual(result["status"], "failed") + self.assertIn("boom", result["message"]) + + def test_scan_and_wait_and_eligible(self): + started = types.SimpleNamespace(id=55, wait_for_completion=lambda timeout: types.SimpleNamespace( + id=55, status="SUCCESS", errors="")) + with mock.patch.object(jobs, "start", return_value=started): + self.state["last"] = {"scan_id": "20261124T101500Z-aaaaaa", "status": "completed"} + result = api.scan_and_wait(make_server(), "owner") + self.assertEqual((result["status"], result["scan"]["status"]), ("completed", "completed")) + self.state["last"] = {"scan_id": "x", "status": "failed", "error": "no list"} + self.assertEqual(api.scan_and_wait(make_server(), "owner")["status"], "failed") + with mock.patch.object(jobs, "start", return_value=Refused("busy")): + self.assertEqual(api.scan_and_wait(make_server(), "owner")["status"], "refused") + self.assertEqual(api.start_scan(make_server(), "owner")["status"], "refused") + with mock.patch.object(jobs, "start", return_value=started): + self.assertEqual(api.start_scan(make_server(), "owner", parent_job="p")["status"], "started") + self.assertEqual(api.eligible(make_server()), (True, "")) + self.assertEqual(api.eligible(make_server(power_status="POWEROFF")), (False, "the server is powered off.")) + with mock.patch.object(fleet, "default_base_url", return_value=""): + self.assertFalse(api.eligible(make_server())[0]) + + +# ---------------------------------------------------------------- review fixes +class SettingGateTests(Base): + def test_start_job_is_refused_when_patching_is_off(self): + self.settings["patching"] = False + hook = FakeHook() + with mock.patch.object(hooks, "patch_hook", create=True, return_value=hook): + refusal = patch.start_job("owner", server=make_server()) + self.assertEqual((refusal.message, refusal.status), (patch.PATCHING_OFF, 403)) + self.assertEqual(patch.PATCHING_OFF, "Installing updates is turned off in Vulnerability Settings.") + self.assertEqual(hook.calls, []) + + def test_an_unreadable_setting_counts_as_off(self): + with mock.patch.object(store, "get_settings", side_effect=RuntimeError("disk")): + self.assertFalse(patch.patching_enabled()) + + def test_run_patch_ends_in_failure_without_touching_a_server(self): + self.settings["patching"] = False + job, (status, output, errors, outputs) = self.go() + self.assertEqual((status, errors, outputs), ("FAILURE", patch.PATCHING_OFF, {})) + self.assertEqual((self.guest.calls, self.markers, self.rescan_calls), ([], [], [])) + self.assertNotIn("patch", self.state) + + def test_the_api_is_refused_too(self): + self.settings["patching"] = False + with mock.patch.object(hooks, "patch_hook", create=True, return_value=FakeHook()): + result = api.install_updates(make_server(), "owner") + self.assertEqual(result["status"], "refused") + self.assertEqual(result["message"], patch.PATCHING_OFF) + + +class OutcomeTests(Base): + def restart_guest(self, running, newest): + self.guest.answers("poll", out(state="done", updated=3, failed=0, exit=0, restart=1)) + self.guest.answers("reboot", out(boot_id=BOOT_1)) + self.guest.answers("probe", out(boot_id=BOOT_1), out(boot_id=BOOT_2, kernel_running=running, + kernel_newest=newest)) + self.guest.answers("oldkernels", out(removed=2, exit=0)) + + def test_a_restart_into_an_older_kernel_is_a_warning_and_cleanup_still_runs(self): + self.restart_guest("5.14.0-1", "5.14.0-2") + job, (status, output, errors, outputs) = self.go() + self.assertEqual(status, "WARNING") + record = self.state["patch"] + self.assertEqual((record["status"], record["restarted"], record["kernels_removed"]), ("updated", True, 2)) + self.assertIn("Restarted, but the server is still running the older kernel.", record["message"]) + self.assertIn("oldkernels", self.guest.calls) + + def test_a_restart_into_the_newest_kernel_is_clean(self): + self.restart_guest("5.14.0-2", "5.14.0-2") + job, (status, output, errors, outputs) = self.go() + self.assertEqual(status, "SUCCESS") + self.assertEqual(self.state["patch"]["message"], "") + + def test_a_single_failure_puts_its_reason_in_errors(self): + self.guest.answers("poll", out(state="done", updated=0, failed=1, exit=1, failure="Error: no space left")) + job, (status, output, errors, outputs) = self.go() + self.assertEqual(status, "FAILURE") + self.assertIn("no space left", errors) + self.assertNotEqual(errors, "No server was updated.") + self.assertEqual(errors, self.state["patch"]["message"]) + + def test_a_bulk_failure_has_a_count_and_the_first_reason(self): + self.guest.answers("start", out(reason="dnf is not installed on the server")) + servers = [make_server(id=i, hostname="h{}".format(i)) for i in (1, 2)] + job, (status, output, errors, outputs) = self.go(servers=servers) + self.assertEqual(status, "FAILURE") + self.assertTrue(errors.startswith("2 of 2 servers failed. First failure (h1): "), errors) + self.assertIn("dnf is not installed", errors) + + def test_a_partly_failed_bulk_run_still_reports_the_reason(self): + original = self.guest.__call__ + starts = {"n": 0} + + def second_start_refused(server, script, timeout, job=None): + if re.search(r"^MODE=start", script, re.M): + starts["n"] += 1 + if starts["n"] == 2: + return out(reason="the disk is read-only") + return original(server, script, timeout, job) + + self.summaries[:] = [{"vulns": 5, "vuln_fixable": 5}] * 6 + servers = [make_server(id=i, hostname="h{}".format(i)) for i in (1, 2)] + with mock.patch.object(jobs, "_execute", second_start_refused): + job, (status, output, errors, outputs) = self.go(servers=servers) + self.assertEqual(status, "FAILURE") + self.assertIn("1 of 2 servers failed", errors) + self.assertIn("read-only", errors) + + def test_a_server_that_does_not_fit_in_the_time_left_is_skipped_with_a_message(self): + self.settings.update(patch_timeout_min=240, restart_wait_min=120) + # 240 + 120 + 30 minutes = 23400 s of worst case; the limit patched in below is 20000 s. + servers = [make_server(id=i, hostname="h{}".format(i)) for i in (1, 2)] + self.summaries[:] = [{"vulns": 5, "vuln_fixable": 5}] * 6 + with mock.patch.object(patch, "JOB_LIMIT_S", 20000): + self.clock.now = 4000.0 + job, (status, output, errors, outputs) = self.go(servers=servers) + self.assertEqual(outputs["counts"]["skipped"], 2) + self.assertEqual(self.guest.calls, []) + self.assertIn("390 minutes", output) + self.assertEqual(status, "WARNING") + + +# ---------------------------------------------------------------- the shell's decision functions +SH_PATH = os.path.join(PKG_DIR, "vuln_patch.sh") + + +def shell(snippet): + """Run snippet in bash after the script's functions are defined (everything before its dispatch), with stub + commands defined as shell functions in the snippet. Nothing of the script's modes runs. Returns stdout.""" + with open(SH_PATH, encoding="ascii") as handle: + text = handle.read() + head = text[:text.index("# ---- dispatch")] + program = "MODE=poll\nRUN_ID=patch-shell-test-0001\n" + head + "\n" + snippet + "\n" + done = subprocess.run([shutil.which("bash")], input=program.encode("ascii"), capture_output=True, timeout=60) + return done.stdout.decode(errors="replace") + + +@unittest.skipUnless(shutil.which("bash"), "bash is not installed") +# ---------------------------------------------------------------- the fix round +class OutcomeWordingTests(Base): + def test_the_line_gives_every_fact_that_happened(self): + self.guest.answers("poll", out(state="done", updated=1, failed=0, exit=0, restart=1)) + self.guest.answers("reboot", out(boot_id=BOOT_1)) + self.guest.answers("probe", out(boot_id=BOOT_1), out(boot_id=BOOT_2)) + self.guest.answers("oldkernels", out(removed=2, exit=0, kernel_running="k2", kernel_newest="k2")) + job, (status, output, errors, outputs) = self.go() + self.assertEqual(output, "web-01: 1 package updated, restarted, 2 old kernel packages removed, known " + "vulnerabilities 10 to 2, with a fix 8 to 0.") + + def test_parts_that_did_not_happen_are_left_out(self): + self.summaries[:] = [{"vulns": 4, "vuln_fixable": None}, {"vulns": 1, "vuln_fixable": None}] + job, (status, output, errors, outputs) = self.go() + self.assertEqual(output, "web-01: 7 packages updated, known vulnerabilities 4 to 1.") + + def test_a_pending_restart_is_said(self): + self.guest.answers("poll", out(state="done", updated=3, failed=0, exit=0, restart=1)) + job, (status, output, errors, outputs) = self.go(restart=False) + self.assertTrue(output.startswith("web-01: 3 packages updated, a restart is still needed, known ")) + + +class NoUpdatesTests(Base): + def test_nothing_installed_nothing_pending_is_no_updates_and_still_rescans(self): + self.guest.answers("poll", out(state="done", updated=0, failed=0, exit=0, restart=0)) + job, (status, output, errors, outputs) = self.go() + self.assertEqual((status, errors), ("SUCCESS", "")) + self.assertEqual(output, "web-01: no updates were available.") + record = self.state["patch"] + self.assertEqual((record["status"], record["updated"], record["restarted"], record["message"]), + ("no_updates", 0, False, "")) + self.assertEqual(len(self.rescan_calls), 1) + self.assertEqual(record["after"], {"vulns": 2, "vuln_fixable": 0}) + self.assertEqual(outputs["counts"]["no_updates"], 1) + self.assertEqual(outputs["counts"]["updated"], 0) + self.assertIn("no updates were available", EVENTS[0][0][2]) + + def test_a_failed_rescan_is_still_a_warning(self): + self.guest.answers("poll", out(state="done", updated=0, failed=0, exit=0, restart=0)) + self.start_result = Refused("busy") + job, (status, output, errors, outputs) = self.go() + self.assertEqual(status, "WARNING") + self.assertEqual(self.state["patch"]["status"], "no_updates") + + def test_a_run_that_only_removed_old_kernels_is_updated(self): + self.guest.answers("poll", out(state="done", updated=0, failed=0, exit=0, restart=0)) + self.guest.answers("oldkernels", out(removed=3, exit=0, kernel_running="k1", kernel_newest="k1")) + job, (status, output, errors, outputs) = self.go() + self.assertEqual(self.state["patch"]["status"], "updated") + self.assertEqual(self.state["patch"]["kernels_removed"], 3) + self.assertEqual(output, "web-01: 0 packages updated, 3 old kernel packages removed, known vulnerabilities " + "10 to 2, with a fix 8 to 0.") + + def test_a_run_that_only_restarted_is_updated(self): + self.guest.answers("poll", out(state="done", updated=0, failed=0, exit=0, restart=1)) + self.guest.answers("reboot", out(boot_id=BOOT_1)) + self.guest.answers("probe", out(boot_id=BOOT_1), out(boot_id=BOOT_2)) + job, (status, output, errors, outputs) = self.go() + self.assertEqual((status, self.state["patch"]["status"], self.state["patch"]["restarted"]), + ("SUCCESS", "updated", True)) + + def test_a_pending_restart_is_not_no_updates(self): + self.guest.answers("poll", out(state="done", updated=0, failed=0, exit=0, restart=1)) + job, (status, output, errors, outputs) = self.go(restart=False) + self.assertEqual(self.state["patch"]["status"], "restart_pending") + + def test_failures_are_not_no_updates(self): + self.guest.answers("poll", out(state="done", updated=0, failed=2, exit=0, restart=0)) + job, (status, output, errors, outputs) = self.go() + self.assertEqual(self.state["patch"]["status"], "updated") + + def test_every_server_without_updates_keeps_the_job_successful(self): + self.guest.answers("poll", out(state="done", updated=0, failed=0, exit=0, restart=0)) + self.summaries[:] = [{"vulns": 1, "vuln_fixable": 0}] * 4 + job, (status, output, errors, outputs) = self.go(servers=[make_server(id=1, hostname="a"), + make_server(id=2, hostname="b")]) + self.assertEqual(status, "SUCCESS") + self.assertEqual(output, "a: no updates were available.\nb: no updates were available.") + + def test_a_failed_server_next_to_one_without_updates_is_a_failure(self): + self.guest.answers("poll", out(state="done", updated=0, failed=0, exit=0, restart=0)) + self.guest.answers("start", out(state="running"), out(reason="no")) + job, (status, output, errors, outputs) = self.go(servers=[make_server(id=1, hostname="a"), + make_server(id=2, hostname="b")]) + self.assertEqual(status, "FAILURE") + + +class OldKernelStepTests(Base): + def test_it_runs_without_a_restart_when_none_was_needed(self): + self.guest.answers("oldkernels", out(removed=2, exit=0, kernel_running="k1", kernel_newest="k1")) + self.go() + self.assertIn("oldkernels", self.guest.calls) + self.assertNotIn("reboot", self.guest.calls) + self.assertEqual(self.state["patch"]["kernels_removed"], 2) + self.assertLess(self.guest.calls.index("poll"), self.guest.calls.index("oldkernels")) + + def test_it_never_runs_while_a_restart_is_pending(self): + self.guest.answers("poll", out(state="done", updated=3, failed=0, exit=0, restart=1)) + self.go(restart=False) + self.assertNotIn("oldkernels", self.guest.calls) + + def test_it_runs_after_a_confirmed_restart(self): + self.guest.answers("poll", out(state="done", updated=3, failed=0, exit=0, restart=1)) + self.guest.answers("reboot", out(boot_id=BOOT_1)) + self.guest.answers("probe", out(boot_id=BOOT_1), out(boot_id=BOOT_2)) + self.go() + self.assertGreater(self.guest.calls.index("oldkernels"), self.guest.calls.index("reboot")) + + def test_the_setting_turns_the_step_off(self): + self.settings["remove_old_kernels"] = False + job, (status, output, errors, outputs) = self.go() + self.assertNotIn("oldkernels", self.guest.calls) + self.assertEqual(status, "SUCCESS") + self.assertIsNone(self.state["patch"]["kernels_removed"]) + + def test_the_setting_off_is_said_after_a_restart_and_is_not_a_warning(self): + self.settings["remove_old_kernels"] = False + self.guest.answers("poll", out(state="done", updated=3, failed=0, exit=0, restart=1)) + self.guest.answers("reboot", out(boot_id=BOOT_1)) + self.guest.answers("probe", out(boot_id=BOOT_1), out(boot_id=BOOT_2)) + job, (status, output, errors, outputs) = self.go() + self.assertNotIn("oldkernels", self.guest.calls) + self.assertEqual(status, "SUCCESS") + self.assertIn("Old kernels were kept.", self.state["patch"]["message"]) + + def test_the_setting_defaults_to_on_when_it_is_missing_or_unreadable(self): + for value in (None, "", "maybe"): + self.settings["remove_old_kernels"] = value + self.guest.calls[:] = [] + self.state["patch"] = None + self.guest.queues["probe"] = [out(boot_id=BOOT_1)] + self.guest.queues["poll"] = [out(state="done", updated=1, failed=0, exit=0, restart=0)] + self.go() + self.assertIn("oldkernels", self.guest.calls, repr(value)) + del self.settings["remove_old_kernels"] + self.guest.calls[:] = [] + self.guest.queues["poll"] = [out(state="done", updated=1, failed=0, exit=0, restart=0)] + self.go() + self.assertIn("oldkernels", self.guest.calls) + self.assertTrue(patch._flag({}, "remove_old_kernels", True)) + self.assertFalse(patch._flag({"remove_old_kernels": "false"}, "remove_old_kernels", True)) + + def test_a_guest_note_about_a_skipped_cleanup_is_a_note_not_a_warning(self): + self.guest.answers("oldkernels", out(removed=0, exit=0, kernel_running="k1", kernel_newest="k1", + note="purging them would also remove other packages")) + job, (status, output, errors, outputs) = self.go() + self.assertEqual(status, "SUCCESS") + self.assertIn("purging them would also remove other packages", self.state["patch"]["message"]) + self.assertEqual(self.state["patch"]["kernels_removed"], 0) + + def test_not_running_the_newest_kernel_is_a_warning(self): + self.guest.answers("oldkernels", out(removed=0, exit=0, kernel_running="k1", kernel_newest="k2", + note="the server is not running its newest kernel")) + job, (status, output, errors, outputs) = self.go() + self.assertEqual(status, "WARNING") + message = self.state["patch"]["message"] + self.assertIn(patch.OLDER_KERNEL, message) + self.assertNotIn("the server is not running its newest kernel", message) + + def test_the_removed_count_is_the_guests(self): + self.guest.answers("oldkernels", out(removed=5, exit=0, kernel_running="k1", kernel_newest="k1")) + self.go() + self.assertEqual(self.state["patch"]["kernels_removed"], 5) + + +class FailureMessageTests(Base): + CAUSE = ("file /usr/lib64/ossl-modules/fips.so from install of openssl-fips-provider-1:3.5.9-1.el9.x86_64 conflicts " + "with file from package openssl-fips-provider-so-3.0.7-11.el9_8.x86_64") + + def failing(self, *details, failure="Error: Transaction test error:"): + lines = ["CBVULN|state|done", "CBVULN|updated|0", "CBVULN|failed|1", "CBVULN|exit|1", "CBVULN|failure|" + failure] + lines += ["CBVULN|detail|" + detail for detail in details] + self.guest.answers("poll", "\n".join(lines + ["CBVULN|done|1"]) + "\n") + + def test_details_that_repeat_are_dropped(self): + parsed = patch._linux_parse("CBVULN|failure|Error: x\nCBVULN|detail|Error: x\nCBVULN|detail|a\n" + "CBVULN|detail|a\nCBVULN|detail|b\nCBVULN|done|1\n") + self.assertEqual(parsed["details"], ["a", "b"]) + parsed = patch._linux_parse("CBVULN|detail|Error: x\nCBVULN|failure|Error: x\nCBVULN|done|1\n") + self.assertEqual(parsed["details"], []) + + def test_the_record_message_carries_the_cause(self): + error = "Error: Transaction test error:" + self.failing(error, self.CAUSE, self.CAUSE) + job, (status, output, errors, outputs) = self.go() + message = self.state["patch"]["message"] + self.assertEqual(status, "FAILURE") + self.assertEqual(message, "The update failed on the server (exit code 1): " + error + " " + self.CAUSE) + self.assertLessEqual(len(message), 300) + # The job's errors keep the details, and the repeated line is there once. + self.assertEqual(errors.count(error), 1) + self.assertIn(self.CAUSE, errors) + + def test_without_a_detail_the_message_is_the_failure_line(self): + self.failing() + self.go() + self.assertEqual(self.state["patch"]["message"], + "The update failed on the server (exit code 1): Error: Transaction test error:") + + def test_a_long_message_is_cut_at_a_word_with_three_dots(self): + self.failing("word " * 100) + self.go() + message = self.state["patch"]["message"] + self.assertLessEqual(len(message), 300) + self.assertTrue(message.endswith("word..."), message[-20:]) + message.encode("ascii") + self.assertEqual(patch._cap("short", 300), "short") + self.assertEqual(patch._cap("alpha beta gamma", 12), "alpha...") + + def test_the_job_output_keeps_the_details_up_to_the_cap(self): + self.failing(*["detail line {}".format(i) for i in range(12)]) + job, (status, output, errors, outputs) = self.go() + self.assertIn("detail line 11", errors) + self.assertLessEqual(len(patch._detail_text(["x" * 300] * 12)), patch.DETAIL_TOTAL) + + +class SingularTests(unittest.TestCase): + def record(self, **over): + record = {"status": "updated", "message": "", "updated": 1, "restarted": False, "restart_needed": False, + "kernels_removed": 1, "before": None, "after": None, "family": "linux"} + record.update(over) + return record + + def test_one_is_singular(self): + self.assertEqual(patch._sentence("h", self.record()), "h: 1 package updated, 1 old kernel package removed.") + self.assertEqual(patch._sentence("h", self.record(family="windows", kernels_removed=None)), + "h: 1 update installed.") + + def test_zero_and_many_are_plural(self): + self.assertEqual(patch._sentence("h", self.record(updated=0, kernels_removed=2)), + "h: 0 packages updated, 2 old kernel packages removed.") + self.assertEqual(patch._sentence("h", self.record(family="windows", updated=2, kernels_removed=None)), + "h: 2 updates installed.") + self.assertEqual(patch._sentence("h", self.record(family="windows", updated=0, kernels_removed=None)), + "h: 0 updates installed.") + + def test_minutes(self): + self.assertEqual(patch._minutes_text(1), "1 minute") + self.assertEqual(patch._minutes_text(0), "0 minutes") + self.assertEqual(patch._minutes_text(90), "90 minutes") + + def test_failed_updates_note(self): + one = [{"result": 4, "kb": "KB1234567", "title": ""}] + self.assertEqual(patch._failed_note(one), "This update failed: KB1234567.") + two = one + [{"result": 3, "kb": "KB1234568", "title": ""}] + self.assertEqual(patch._failed_note(two), "These updates failed: KB1234567, KB1234568.") + + +class OneMinuteTests(Base): + def test_a_one_minute_limit_is_singular(self): + self.settings["patch_timeout_min"] = 1 + self.guest.answers("poll", out(state="running")) + job, (status, output, errors, outputs) = self.go() + self.assertIn("did not finish within 1 minute and may", errors) + self.assertNotIn("1 minutes", errors) + + +class ShellTests(unittest.TestCase): + RPM = "rpm() { printf '%s\\n' 'kernel 5.14.0-2.x86_64' 'kernel 5.14.0-1.x86_64'; }\n" + + def restart(self, dnf_body, kernel="5.14.0-1.x86_64", rpm=None): + snippet = ("DISTRO=rhel\ndnf() { " + dnf_body + " }\n" + (rpm or self.RPM) + + "uname() { echo " + kernel + "; }\ncheck_restart\necho \"RESULT|$RESTART|$RESTART_REASON\"\n") + for line in shell(snippet).splitlines(): + if line.startswith("RESULT|"): + return line.split("|", 2)[1:] + self.fail("no result") + + def test_a_missing_needs_restarting_plugin_is_not_read_as_restart_required(self): + # dnf exits 1 for a command it does not know; that must not mean "restart". + missing = "return 1;" + self.assertEqual(self.restart(missing, kernel="5.14.0-2.x86_64")[0], "0") + self.assertEqual(self.restart(missing, kernel="5.14.0-1.x86_64")[0], "1") + self.assertEqual(self.restart(missing, rpm="rpm() { return 1; }\n")[0], "unknown") + + def test_a_working_plugin_is_trusted(self): + plugin = ('case "$*" in "needs-restarting -h") return 0;; "needs-restarting -r") echo "Reboot is required"; ' + 'return %d;; esac;') + self.assertEqual(self.restart(plugin % 1, kernel="5.14.0-2.x86_64")[0], "1") + self.assertEqual(self.restart(plugin % 0, kernel="5.14.0-1.x86_64")[0], "0") + # Any other exit status falls through to the kernel comparison. + self.assertEqual(self.restart(plugin % 2, kernel="5.14.0-2.x86_64")[0], "0") + self.assertEqual(self.restart(plugin % 2, kernel="5.14.0-1.x86_64")[0], "1") + + def test_the_run_folder_must_be_owned_by_the_running_user_with_mode_700(self): + # stat and id are stubbed, so the answer does not depend on the file system the test runs on. + with tempfile.TemporaryDirectory() as root: + root = root.replace("\\", "/") + results = {} + for label, owner_mode in (("good", "0 700"), ("open", "0 755"), ("other_owner", "1000 700"), + ("group", "0 770")): + snippet = ("id() { echo 0; }\nstat() { echo '" + owner_mode + "'; }\n" + "if safe_dir " + root + "; then echo SAFE; else echo UNSAFE; fi\n" + "if safe_dir " + root + "/missing; then echo SAFE; else echo UNSAFE; fi\n") + results[label] = shell(snippet).split() + self.assertEqual(results["good"], ["SAFE", "UNSAFE"]) + for label in ("open", "other_owner", "group"): + self.assertEqual(results[label], ["UNSAFE", "UNSAFE"], label) + + def test_a_link_is_never_a_safe_run_folder(self): + with tempfile.TemporaryDirectory() as root: + root = root.replace("\\", "/") + snippet = ("id() { echo 0; }\nstat() { echo '0 700'; }\nmkdir {r}/target; ln -s {r}/target {r}/link 2>/dev/null\n" + "[ -L {r}/link ] || { echo NOLINK; exit 0; }\n" + "if safe_dir {r}/link; then echo SAFE; else echo UNSAFE; fi\n").replace("{r}", root) + text = shell(snippet) + if "NOLINK" in text: + self.skipTest("symbolic links are not available") + self.assertEqual(text.split(), ["UNSAFE"]) + + def test_a_cleanup_refuses_through_a_link_and_removes_nothing(self): + with tempfile.TemporaryDirectory() as root: + root = root.replace("\\", "/") + snippet = ("mkdir -m 700 {r}/target; touch {r}/target/keep; ln -s {r}/target {r}/link 2>/dev/null\n" + "[ -L {r}/link ] || { echo NOLINK; exit 0; }\n" + "RUN={r}/link\nmode_cleanup\n").replace("{r}", root) + text = shell(snippet) + if "NOLINK" in text: + self.skipTest("symbolic links are not available") + self.assertIn("CBVULN|reason|the run folder on the server is not safe to use", text) + self.assertTrue(os.path.exists(os.path.join(root, "target", "keep"))) + + def test_the_other_modes_refuse_an_unsafe_run_folder(self): + with tempfile.TemporaryDirectory() as root: + root = root.replace("\\", "/") + for mode in ("mode_poll", "mode_oldkernels", "mode_cleanup"): + snippet = ("id() { echo 0; }\nstat() { echo '0 755'; }\nneed_distro() { :; }\n" + "mkdir {r}/open; RUN={r}/open\ntouch {r}/open/keep\n{m}\n").replace( + "{r}", root).replace("{m}", mode) + text = shell(snippet) + self.assertIn("CBVULN|reason|the run folder on the server is not safe to use", text, mode) + self.assertTrue(os.path.exists(os.path.join(root, "open", "keep")), mode) + shutil.rmtree(os.path.join(root, "open")) + + def test_a_missing_run_folder_is_not_an_error_for_poll_and_cleanup(self): + with tempfile.TemporaryDirectory() as root: + root = root.replace("\\", "/") + for mode, expect in (("mode_poll", "CBVULN|state|missing"), ("mode_cleanup", "CBVULN|done|1")): + text = shell(("RUN={r}/none\n{m}\n").replace("{r}", root).replace("{m}", mode)) + self.assertIn(expect, text) + self.assertNotIn("reason", text) + + +# ---------------------------------------------------------------- failure detail lines +def failed_poll(details, failure="Error: Transaction test error:"): + """A poll answer for a package manager that failed, with detail lines (a key that may repeat).""" + lines = ["CBVULN|state|done", "CBVULN|updated|0", "CBVULN|failed|1", "CBVULN|exit|1", "CBVULN|failure|" + failure] + lines += ["CBVULN|detail|" + text for text in details] + return "\n".join(lines + ["CBVULN|done|1"]) + "\n" + + +class DetailTests(Base): + CONFLICTS = ["Error: Transaction test error:", " file /usr/a conflicts with b-1", " file /usr/c conflicts with d-2"] + + def test_the_parser_collects_detail_lines_cleaned_capped_and_limited(self): + text = failed_poll(["see https://evil.example/x now"] + ["line {}".format(i) for i in range(20)] + ["x" * 500]) + parsed = patch._linux_parse(text) + self.assertEqual(len(parsed["details"]), patch.MAX_DETAIL) + self.assertNotIn("evil.example", parsed["details"][0]) + self.assertIn("detail", patch.KNOWN_KEYS) + parsed = patch._linux_parse(failed_poll(["y" * 500])) + self.assertLessEqual(len(parsed["details"][0]), patch.MESSAGE_LEN) + self.assertEqual(patch._linux_parse(out(state="done"))["details"], []) + + def test_the_record_carries_the_cause_and_the_output_and_errors_the_full_detail(self): + self.guest.answers("poll", failed_poll(self.CONFLICTS)) + job, (status, output, errors, outputs) = self.go() + self.assertEqual(status, "FAILURE") + first = "The update failed on the server (exit code 1): Error: Transaction test error: file /usr/a conflicts with b-1" + self.assertEqual(self.state["patch"]["message"], first) + self.assertIn("file /usr/a conflicts with b-1", output) + self.assertIn("file /usr/c conflicts with d-2", output) + self.assertTrue(errors.startswith(first + "\n"), errors) + self.assertIn("file /usr/c conflicts with d-2", errors) + self.assertNotIn("detail", outputs["servers"]["7"]) + # The repeated line is said once in the output. + self.assertEqual(output.count("Error: Transaction test error:"), 1) + + def test_the_detail_text_is_capped_at_two_thousand_characters(self): + self.guest.answers("poll", failed_poll(["z" * 290 + str(i) for i in range(12)])) + job, (status, output, errors, outputs) = self.go() + detail = errors.split("\n", 1)[1] + self.assertLessEqual(len(detail), patch.DETAIL_TOTAL) + self.assertGreater(len(detail), 1500) + self.assertEqual(patch._detail_text(["a" * 3000]), "a" * patch.DETAIL_TOTAL) + self.assertEqual(patch._detail_text(None), "") + + def test_a_bulk_failure_errors_carry_the_first_failures_detail(self): + self.guest.answers("poll", failed_poll(self.CONFLICTS)) + servers = [make_server(id=i, hostname="h{}".format(i)) for i in (1, 2)] + job, (status, output, errors, outputs) = self.go(servers=servers) + self.assertTrue(errors.startswith("2 of 2 servers failed. First failure (h1): "), errors) + # Once in the first failure's message (the cause), once in its full detail. + self.assertEqual(errors.count("file /usr/a conflicts with b-1"), 2) + self.assertEqual(errors.count("file /usr/c conflicts with d-2"), 1) + self.assertEqual(errors.count("Error: Transaction test error:"), 1) + + def test_a_failure_without_detail_lines_is_as_before(self): + self.guest.answers("poll", out(state="done", updated=0, failed=1, exit=1, failure="Error: boom")) + job, (status, output, errors, outputs) = self.go() + self.assertEqual(errors, "The update failed on the server (exit code 1): Error: boom") + + +if __name__ == "__main__": + unittest.main() diff --git a/extensions/XUI-wqrj0e3p/tests/test_vuln_patch_hooks.py b/extensions/XUI-wqrj0e3p/tests/test_vuln_patch_hooks.py new file mode 100644 index 00000000..7c9ce07d --- /dev/null +++ b/extensions/XUI-wqrj0e3p/tests/test_vuln_patch_hooks.py @@ -0,0 +1,621 @@ +""" +Checks for the Install Updates wiring of the Vulnerabilities XUI (vuln_hooks.py apply_patching_setting, +patch_button and patch_action_state; the patching settings in vuln_store.py; vuln_patch_condition.py) +without CloudBolt: CloudBolt's modules are stubs and the ORM is a small in-memory fake that records every +write, so a test can say exactly what was created and what was left alone. + + python -B -m unittest extensions/XUI-wqrj0e3p/tests/test_vuln_patch_hooks.py + +The stubs are in place only while this file imports the extension's modules, so another test file's stubs +are not disturbed. The ORM fakes are put in place per test. +""" +import contextlib +import importlib +import itertools +import os +import sys +import tempfile +import types +import unittest +from unittest import mock + +HERE = os.path.dirname(os.path.abspath(__file__)) +EXT = os.path.dirname(HERE) +PACKAGE = "xui.io_cloudbolt_vulnerabilities" +SOURCE = os.path.join(EXT, "io_cloudbolt_vulnerabilities") + + +class IntegrityError(Exception): + pass + + +class FakeLogger: + def __init__(self, *a): + pass + + def __getattr__(self, name): + return lambda *a, **k: None + + +def _module(name, **attrs): + module = types.ModuleType(name) + module.__dict__.update(attrs) + return module + + +TMP = tempfile.mkdtemp(prefix="vuln-patch-hooks-test-") +STUBS = {} + + +def _stub(name, **attrs): + STUBS[name] = _module(name, **attrs) + return STUBS[name] + + +_stub("django") +_stub("django.conf", settings=types.SimpleNamespace(PROSERV_DIR=TMP, CLOUDBOLT_OS_USER="u", CLOUDBOLT_OS_GROUP="g")) +_stub("django.http", FileResponse=object, Http404=Exception, HttpResponse=object) +_stub("django.urls", reverse=lambda *a, **k: "/x/") +_stub("django.db", IntegrityError=IntegrityError, + transaction=types.SimpleNamespace(atomic=lambda: contextlib.nullcontext())) +_stub("cbhooks") +_stub("cbhooks.models", CloudBoltHook=object) +_stub("accounts") +_stub("accounts.models", Group=object, UserProfile=object) +_stub("infrastructure") +_stub("infrastructure.models", Server=object) +_stub("jobs") +_stub("jobs.models", Job=object) +_stub("portals") +_stub("portals.models") +_stub("utilities") +_stub("utilities.events", add_server_event=lambda *a, **k: None) +_stub("utilities.logger", ThreadLogger=FakeLogger) +_xui = _stub("xui") +_xui.__path__ = [EXT] + + +def _import_extension(): + """Import the extension's modules against the stubs, leaving sys.modules as it was found.""" + touched = [k for k in sys.modules if k == "xui" or k.startswith(PACKAGE) or k in STUBS] + saved = {k: sys.modules[k] for k in touched} + for key in touched: + del sys.modules[key] + sys.modules.update(STUBS) + try: + names = ("vuln_store", "vuln_match", "vuln_db", "vuln_tools", "vuln_repo", "vuln_hooks", "vuln_jobs") + return {name: importlib.import_module(PACKAGE + "." + name) for name in names} + finally: + for key in [k for k in sys.modules if k == "xui" or k.startswith(PACKAGE) or k in STUBS]: + del sys.modules[key] + sys.modules.update(saved) + + +MODS = _import_extension() +store, hooks, jobs = MODS["vuln_store"], MODS["vuln_hooks"], MODS["vuln_jobs"] + + +# ---------------------------------------------------------------- an in-memory ORM +class Rows(list): + def first(self): + return self[0] if self else None + + def exists(self): + return bool(self) + + def all(self): + return self + + +class Manager: + def __init__(self, rows): + self.rows = rows + + def filter(self, **kw): + return Rows(r for r in self.rows if all(getattr(r, k, None) == v for k, v in kw.items())) + + def all(self): + return Rows(self.rows) + + def select_for_update(self): + return self + + +class World: + """The fake database of one test and the log of every write made to it.""" + + def __init__(self, make_token_input=True): + self.calls = [] + self.hooks = [] + self.actions = [] + self.values = [] + self.ids = itertools.count(1) + self.make_token_input = make_token_input + world = self + + class Hook: + objects = Manager(world.hooks) + + def __init__(self, **kw): + self.id = None + self.__dict__.update(kw) + self.input_rows = [] + self.input_fields = Manager(self.input_rows) + + @property + def pk(self): + return self.id + + def save(self): + first = self.id is None + if first: + self.id = next(world.ids) + world.hooks.append(self) + world.calls.append(("hook.save", self.name)) + # hook.save() makes a text input from the token in the plugin file. + if first and self.name == hooks.PATCH_NAME and world.make_token_input: + HookInput.objects.create(hook=self, name="restart_if_needed_a{}".format(self.id), + label="restart_if_needed", type="STR", required=True, + hide_if_default_value=True, _from_token=True) + + class HookInput: + objects = types.SimpleNamespace() + + def __init__(self, **kw): + self.__dict__.update(kw) + + def save(self): + world.calls.append(("input.save", self.name)) + + def make_input(**kw): + row = HookInput(**kw) + kw["hook"].input_rows.append(row) + if not kw.get("_from_token"): + world.calls.append(("input.create", kw["name"])) + return row + + HookInput.objects.create = make_input + + class Mapping: + def __init__(self, hook_input): + self.hook_input = hook_input + self.default_value = None + + def save(self): + world.calls.append(("mapping.save", self.default_value.value if self.default_value else None)) + + class Action: + def __init__(self, **kw): + self.requires_approval = False + self.auto_submit_order = False + self.roles = [] + self.pk = next(world.ids) + self.mapping_rows = [] + self.input_mappings = Manager(self.mapping_rows) + self.__dict__.update(kw) + + def update_input_mappings(self): + world.calls.append(("action.update_input_mappings",)) + for row in self.hook.input_rows: + if not self.input_mappings.filter(hook_input=row): + self.mapping_rows.append(Mapping(row)) + + def save(self): + world.calls.append(("action.save", self.enabled)) + + def server_action_dict(self, server, request=None): + return world.action_dict + + class ServerAction: + objects = types.SimpleNamespace( + filter=lambda **kw: Rows(a for a in world.actions if all(getattr(a, k) == v for k, v in kw.items()))) + + def create_action(**kw): + row = Action(**kw) + world.actions.append(row) + world.calls.append(("action.create", dict(kw))) + return row + + ServerAction.objects.create = create_action + + class CustomFieldValue: + objects = types.SimpleNamespace() + + def get_or_create(field, value): + row = types.SimpleNamespace(field=field, value=value) + world.values.append(row) + world.calls.append(("value.get_or_create", field.name, value)) + return row, True + + CustomFieldValue.objects.get_or_create = get_or_create + self.action_dict = {"url": "/server_actions/1/", "label": "Install Updates"} + self.permitted = True + self.Hook, self.HookInput, self.ServerAction, self.CustomFieldValue = Hook, HookInput, ServerAction, CustomFieldValue + + @contextlib.contextmanager + def installed(self): + cb = _module("cbhooks.models", CloudBoltHook=self.Hook, HookInput=self.HookInput, + ServerAction=self.ServerAction) + orders = _module("orders.models", CustomFieldValue=self.CustomFieldValue) + perms = _module("utilities.permissions", server_action_permitted=lambda profile, server, action: self.permitted) + package = _module(PACKAGE, vuln_store=store) + patches = {"cbhooks.models": cb, "orders.models": orders, "utilities.permissions": perms, + PACKAGE: package, PACKAGE + ".vuln_store": store} + with mock.patch.dict(sys.modules, patches), mock.patch.object(hooks, "CloudBoltHook", self.Hook): + yield self + + def count(self, kind): + return len([c for c in self.calls if c[0] == kind]) + + def actions_calls(self, kind): + return [c for c in self.calls if c[0] == kind] + + +def server(**over): + data = dict(id=7, hostname="web-01", group=types.SimpleNamespace(is_unassigned=False, name="Dev"), + os_family=types.SimpleNamespace(get_base_name=lambda: "Linux", name="Linux")) + data.update(over) + return types.SimpleNamespace(**data) + + +# ---------------------------------------------------------------- the action +class ApplyPatchingTests(unittest.TestCase): + def test_off_with_no_hook_is_a_no_op(self): + world = World() + with world.installed(): + hooks._apply_server_action(False) + self.assertEqual(world.calls, []) + + def test_first_enable_makes_everything_once(self): + world = World() + with world.installed(): + hooks._apply_server_action(True) + self.assertEqual([h.name for h in world.hooks], [hooks.PATCH_NAME, hooks.CONDITION_NAME]) + self.assertEqual(len(world.actions), 1) + action = world.actions[0] + patch = world.hooks[0] + self.assertIs(action.hook, patch) + self.assertIs(action.condition, world.hooks[1]) + self.assertEqual(action.label, "Install Updates") + self.assertIs(action.enabled, True) + self.assertIs(action.is_synchronous, False) + self.assertTrue(world.hooks[0].module_file.endswith("vuln_patch_job.py")) + self.assertTrue(world.hooks[1].module_file.endswith("vuln_patch_condition.py")) + # One input: the token's text input turned into a checkbox, not a second one. + self.assertEqual(len(patch.input_rows), 1) + field = patch.input_rows[0] + self.assertEqual(field.name, "restart_if_needed_a{}".format(patch.id)) + self.assertEqual(field.type, "BOOL") + self.assertIs(field.required, False) + self.assertIs(field.hide_if_default_value, False) + # One mapping with the default True. + self.assertEqual(len(action.mapping_rows), 1) + self.assertIs(action.mapping_rows[0].hook_input, field) + self.assertIs(action.mapping_rows[0].default_value.value, True) + self.assertIs(action.mapping_rows[0].default_value.field, field) + + def test_the_input_is_made_when_the_token_pass_did_not(self): + world = World(make_token_input=False) + with world.installed(): + hooks._apply_server_action(True) + patch = world.hooks[0] + self.assertEqual(len(patch.input_rows), 1) + self.assertEqual(world.count("input.create"), 1) + field = patch.input_rows[0] + self.assertEqual((field.type, field.required, field.hide_if_default_value), ("BOOL", False, False)) + self.assertIs(world.actions[0].mapping_rows[0].default_value.value, True) + + def test_no_os_families_call_is_made(self): + world = World() + with world.installed(): + hooks._apply_server_action(True) + hooks._apply_server_action(False) + hooks._apply_server_action(True) + for hook in world.hooks: + self.assertFalse(hasattr(hook, "os_families")) + text = " ".join(str(c) for c in world.calls) + self.assertNotIn("os_famil", text) + import ast + + with open(os.path.join(SOURCE, "vuln_hooks.py"), encoding="ascii") as handle: + tree = ast.parse(handle.read()) + for node in ast.walk(tree): + self.assertNotEqual(getattr(node, "attr", None), "os_families") + self.assertNotEqual(getattr(node, "arg", None), "os_families") + self.assertNotEqual(getattr(node, "id", None), "os_families") + + def test_second_enable_creates_nothing_and_off_only_sets_enabled(self): + world = World() + with world.installed(): + hooks._apply_server_action(True) + world.calls.clear() + hooks._apply_server_action(True) + self.assertEqual(world.calls, []) + hooks._apply_server_action(False) + self.assertEqual(world.calls, [("action.save", False)]) + self.assertIs(world.actions[0].enabled, False) + world.calls.clear() + hooks._apply_server_action(False) + self.assertEqual(world.calls, []) + hooks._apply_server_action(True) + self.assertEqual(world.calls, [("action.save", True)]) + self.assertEqual(len(world.actions), 1) + self.assertEqual(len(world.hooks), 2) + + def test_admin_owned_flags_survive_off_and_on(self): + world = World() + with world.installed(): + hooks._apply_server_action(True) + action = world.actions[0] + action.requires_approval = True + action.auto_submit_order = True + action.label = "Patch it" + action.roles = ["ops"] + condition = action.condition + action.condition = "admin's own" + action.mapping_rows[0].default_value.value = False + hooks._apply_server_action(False) + hooks._apply_server_action(True) + self.assertIs(action.requires_approval, True) + self.assertIs(action.auto_submit_order, True) + self.assertEqual(action.label, "Patch it") + self.assertEqual(action.roles, ["ops"]) + self.assertEqual(action.condition, "admin's own") + self.assertIsNot(action.condition, condition) + # The admin's default is not re-set, and no mapping is written on re-enable. + self.assertIs(action.mapping_rows[0].default_value.value, False) + self.assertEqual(world.count("mapping.save"), 1) + self.assertEqual(world.count("value.get_or_create"), 1) + + def test_extra_classes_follow_the_exported_actions(self): + self.assertEqual(hooks.PATCH_ACTION_ICON, "fas fa-download") + root = os.path.abspath(os.path.join(EXT, "..", "..", "server_actions")) + spellings = set() + for folder in os.listdir(root): + path = os.path.join(root, folder, folder + "_metadata.json") + if os.path.exists(path): + import json + + with open(path, encoding="utf-8") as handle: + spellings.add(json.load(handle).get("extra_classes", "")) + spellings.discard("") + self.assertTrue(spellings, "no exported server action carries extra_classes") + for spelling in spellings: + self.assertTrue(spelling.startswith(("fas ", "far ", "fab ")), spelling) + self.assertTrue(hooks.PATCH_ACTION_ICON.startswith("fas fa-")) + world = World() + with world.installed(): + hooks._apply_server_action(True) + self.assertEqual(world.actions[0].extra_classes, hooks.PATCH_ACTION_ICON) + + def test_a_failure_is_a_runtime_error(self): + world = World() + with world.installed(): + world.ServerAction.objects.create = mock.Mock(side_effect=ValueError("boom")) + with self.assertRaises(RuntimeError): + hooks._apply_server_action(True) + + def test_an_action_made_meanwhile_is_not_doubled(self): + world = World() + with world.installed(): + hooks._apply_server_action(True) + rival = world.actions[0] + world.actions.clear() + real = hooks.patch_actions + seen = [] + + def racing(hook): + seen.append(1) + if len(seen) == 2: + world.actions.append(rival) # the other request made it after our first look + return real(hook) + + world.actions.clear() + with mock.patch.object(hooks, "patch_actions", racing): + world.calls.clear() + hooks._apply_server_action(True) + self.assertEqual(len(world.actions), 1) + self.assertEqual(world.count("action.create"), 0) + + def test_state_reads_only(self): + world = World() + with world.installed(): + self.assertEqual(hooks.patch_action_state(), {"exists": False, "enabled": False, "action_id": None}) + self.assertEqual(world.calls, []) + hooks._apply_server_action(True) + state = hooks.patch_action_state() + self.assertEqual(state, {"exists": True, "enabled": True, "action_id": world.actions[0].pk}) + hooks._apply_server_action(False) + self.assertEqual(hooks.patch_action_state()["enabled"], False) + with mock.patch.object(hooks, "CloudBoltHook", mock.Mock(objects=mock.Mock(filter=mock.Mock( + side_effect=RuntimeError("db"))))): + self.assertEqual(hooks.patch_action_state(), {"exists": False, "enabled": False, "action_id": None}) + + +class PatchButtonTests(unittest.TestCase): + def setUp(self): + self.world = World() + with self.world.installed(): + hooks._apply_server_action(True) + self.settings = {"patching": True} + self.patcher = mock.patch.object(store, "get_settings", lambda: self.settings) + self.patcher.start() + self.addCleanup(self.patcher.stop) + + def button(self): + with self.world.installed(): + return hooks.patch_button(server(), object(), None) + + def test_shows_when_everything_allows_it(self): + self.assertEqual(self.button(), {"url": "/server_actions/1/", "label": "Install Updates", + "action_id": self.world.actions[0].pk}) + + def test_setting_off(self): + self.settings = {"patching": False} + self.assertIsNone(self.button()) + + def test_action_disabled(self): + self.world.actions[0].enabled = False + self.assertIsNone(self.button()) + + def test_condition_hides_it(self): + self.world.action_dict = None + self.assertIsNone(self.button()) + + def test_permission_denied(self): + self.world.permitted = False + self.assertIsNone(self.button()) + + def test_never_raises(self): + self.world.action_dict = "not a dict" + self.assertIsNone(self.button()) + with mock.patch.object(hooks, "CloudBoltHook", None): + self.assertIsNone(hooks.patch_button(server(), object())) + + +# ---------------------------------------------------------------- settings +class PatchSettingsTests(unittest.TestCase): + def test_defaults(self): + self.assertIs(store.DEFAULT_SETTINGS["patching"], False) + self.assertEqual(store.DEFAULT_SETTINGS["restart_wait_min"], 60) + self.assertEqual(store.DEFAULT_SETTINGS["patch_timeout_min"], 90) + clean, errors = store.validate_settings({}) + self.assertEqual(errors, {}) + self.assertEqual((clean["patching"], clean["restart_wait_min"], clean["patch_timeout_min"]), + (False, 60, 90)) + with mock.patch.object(store, "_read_json", return_value={}): + result = store.get_settings() + self.assertEqual((result["patching"], result["restart_wait_min"], result["patch_timeout_min"]), + (False, 60, 90)) + + def test_remove_old_kernels_setting(self): + self.assertIs(store.DEFAULT_SETTINGS["remove_old_kernels"], True) + with mock.patch.object(store, "_read_json", return_value={"patching": True}): + self.assertIs(store.get_settings()["remove_old_kernels"], True) + with mock.patch.object(store, "_read_json", return_value={"remove_old_kernels": False}): + self.assertIs(store.get_settings()["remove_old_kernels"], False) + self.assertIs(store.validate_settings({"remove_old_kernels": "1"})[0]["remove_old_kernels"], True) + self.assertIs(store.validate_settings({})[0]["remove_old_kernels"], False) + self.assertIs(store.validate_settings({"remove_old_kernels": "0"})[0]["remove_old_kernels"], False) + + def test_the_settings_page_has_the_checkbox(self): + path = os.path.join(SOURCE, "templates", "vuln_settings.html") + with open(path, encoding="ascii") as handle: + html = handle.read() + self.assertIn('name="remove_old_kernels"', html) + self.assertIn("Remove old kernels after a restart", html) + + def test_patching_flag_parsing(self): + for value, expect in (("1", True), ("on", True), ("true", True), ("", False), ("0", False), ("off", False)): + clean, errors = store.validate_settings({"patching": value}) + self.assertIs(clean["patching"], expect, value) + self.assertNotIn("patching", errors) + + def test_valid_values(self): + clean, errors = store.validate_settings({"patching": "1", "restart_wait_min": "120", "patch_timeout_min": "10"}) + self.assertEqual(errors, {}) + self.assertEqual((clean["patching"], clean["restart_wait_min"], clean["patch_timeout_min"]), + (True, 120, 10)) + + def test_bad_ints_are_errors_and_clamped(self): + for key, bad, expect in (("restart_wait_min", "4", 5), ("restart_wait_min", "121", 120), + ("restart_wait_min", "soon", 60), ("restart_wait_min", "", 60), + ("patch_timeout_min", "9", 10), ("patch_timeout_min", "241", 240), + ("patch_timeout_min", "-1", 10), ("patch_timeout_min", "\u00b2", 90)): + clean, errors = store.validate_settings({key: bad}) + self.assertIn(key, errors, (key, bad)) + self.assertEqual(clean[key], expect, (key, bad)) + self.assertEqual(store.validate_settings({"restart_wait_min": "4"})[1]["restart_wait_min"], + "Minutes to wait for a server to come back after a restart must be a whole number " + "from 5 to 120.") + + def test_get_settings_clamps(self): + saved = {"patching": 1, "restart_wait_min": 999, "patch_timeout_min": "x"} + with mock.patch.object(store, "_read_json", return_value=saved): + result = store.get_settings() + self.assertIs(result["patching"], True) + self.assertEqual(result["restart_wait_min"], 120) + self.assertEqual(result["patch_timeout_min"], 90) + with mock.patch.object(store, "_read_json", return_value={"patch_timeout_min": 1}): + self.assertEqual(store.get_settings()["patch_timeout_min"], 10) + + +# ---------------------------------------------------------------- the display condition +def _load_condition(): + path = os.path.join(SOURCE, "vuln_patch_condition.py") + namespace = {} + with open(path, encoding="ascii") as handle: + source = handle.read() + exec(compile(source, path, "exec"), namespace) + return source, namespace["should_display"] + + +class ConditionTests(unittest.TestCase): + def setUp(self): + self.source, self.should_display = _load_condition() + fake = _module(PACKAGE + ".vuln_jobs", in_unassigned_group=jobs.in_unassigned_group, + is_linux=jobs.is_linux, is_windows=jobs.is_windows) + patcher = mock.patch.dict(sys.modules, {PACKAGE: _module(PACKAGE), PACKAGE + ".vuln_jobs": fake, + "xui": _module("xui"), + "xui.io_cloudbolt_vulnerabilities": _module( + "xui.io_cloudbolt_vulnerabilities", vuln_jobs=fake)}) + patcher.start() + self.addCleanup(patcher.stop) + + def test_linux_is_shown(self): + self.assertIs(self.should_display(server()), True) + self.assertIs(self.should_display(server(), None), True) + + def test_windows_is_shown(self): + windows = types.SimpleNamespace(get_base_name=lambda: "Windows", name="Windows") + self.assertIs(self.should_display(server(os_family=windows, is_windows=lambda: True)), True) + + def test_windows_in_an_unassigned_group_is_hidden(self): + windows = types.SimpleNamespace(get_base_name=lambda: "Windows", name="Windows") + self.assertIs(self.should_display(server(os_family=windows, is_windows=lambda: True, + group=types.SimpleNamespace(is_unassigned=True))), False) + + def test_an_error_in_the_windows_check_hides_it(self): + def boom(server): + raise RuntimeError("no family") + fake = _module(PACKAGE + ".vuln_jobs", in_unassigned_group=jobs.in_unassigned_group, + is_linux=lambda s: False, is_windows=boom) + with mock.patch.dict(sys.modules, {"xui.io_cloudbolt_vulnerabilities": _module( + "xui.io_cloudbolt_vulnerabilities", vuln_jobs=fake)}): + self.assertIs(self.should_display(server()), False) + + def test_the_texts_say_linux_and_windows(self): + self.assertIn("Windows Server 2022 or 2025", hooks.PATCH_DESCRIPTION) + self.assertNotIn("not Windows", hooks.CONDITION_DESCRIPTION) + self.assertIn("Linux and Windows", hooks.CONDITION_DESCRIPTION) + + def test_no_or_other_os_family_is_hidden(self): + self.assertIs(self.should_display(server(os_family=None)), False) + other = types.SimpleNamespace(get_base_name=lambda: "Solaris", name="Solaris") + self.assertIs(self.should_display(server(os_family=other)), False) + + def test_unassigned_group_is_hidden(self): + self.assertIs(self.should_display(server(group=types.SimpleNamespace(is_unassigned=True))), False) + + def test_an_error_hides_it(self): + broken = types.SimpleNamespace(id=1) # no group at all: in_unassigned_group fails closed + self.assertIs(self.should_display(broken), False) + with mock.patch.dict(sys.modules, {"xui.io_cloudbolt_vulnerabilities": None}): + self.assertIs(self.should_display(server()), False) + + def test_the_file_is_small_ascii_and_has_no_double_braces(self): + self.assertLess(len(self.source), 1400) + self.assertTrue(self.source.isascii()) + self.assertNotIn("{{", self.source) + self.assertNotIn("}}", self.source) + + +class NoTokenTests(unittest.TestCase): + def test_no_double_braces_in_the_files_of_this_package(self): + for name in ("vuln_hooks.py", "vuln_patch_condition.py"): + with open(os.path.join(SOURCE, name), encoding="ascii") as handle: + self.assertNotIn("{{", handle.read(), name) + + +if __name__ == "__main__": + unittest.main() diff --git a/extensions/XUI-wqrj0e3p/tests/test_vuln_patch_panel.py b/extensions/XUI-wqrj0e3p/tests/test_vuln_patch_panel.py new file mode 100644 index 00000000..8a76061c --- /dev/null +++ b/extensions/XUI-wqrj0e3p/tests/test_vuln_patch_panel.py @@ -0,0 +1,373 @@ +""" +Checks for the Install updates part of the Vulnerabilities panel (views._panel_context, vuln_panel.html and the +settings view) without CloudBolt. The patch module and the two vuln_hooks functions the panel calls are stubbed +here, so these tests do not depend on the patch engine. The template tests need Django itself and are skipped +when it is not installed. + + python -B -m unittest discover -s extensions/XUI-wqrj0e3p/tests -p "test_*.py" +""" +import contextlib +import importlib +import os +import sys +import types +import unittest +from unittest import mock + +HERE = os.path.dirname(os.path.abspath(__file__)) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +try: # the real Django, imported before the stubs of test_vuln_fleet.py are put in and taken out again + import django.conf + import django.template + HAVE_DJANGO = True +except ImportError: + HAVE_DJANGO = False + +import test_vuln_fleet as base # noqa: E402 (builds the stubs and imports the extension) + +PATCH_KEY = base.PACKAGE + ".vuln_patch" +VIEW_STUBS = {} + + +def _import_views(): + """views.py against stubs of Django, CloudBolt's extension decorators and the patch module.""" + def stub(name, **attrs): + module = types.ModuleType(name) + module.__dict__.update(attrs) + VIEW_STUBS[name] = module + return module + + def identity(*a, **k): + if len(a) == 1 and callable(a[0]) and not k: + return a[0] + return lambda view: view + + class Q: + def __init__(self, **kw): + pass + + def __or__(self, other): + return self + + stub("django.core") + stub("django.core.exceptions", PermissionDenied=type("PermissionDenied", (Exception,), {})) + stub("django.core.paginator", Paginator=object) + stub("django.db.models", Q=Q) + stub("django.http", Http404=base.Http404, FileResponse=object, HttpResponse=object, + JsonResponse=lambda data, status=200: types.SimpleNamespace(data=data, status=status)) + stub("django.shortcuts", render=lambda request, template, context=None: (template, context)) + stub("django.views") + stub("django.views.decorators") + stub("django.views.decorators.csrf", csrf_exempt=identity) + stub("extensions") + stub("extensions.views", admin_extension=identity, tab_extension=identity, + TabExtensionDelegate=type("Delegate", (), {})) + stub("resources") + stub("resources.models", Resource=object) + stub("utilities.middleware", login_not_required=identity) + stub("utilities.permissions", cbadmin_required=identity) + stub(PATCH_KEY, eligibility=lambda server: "") + names = set(base.STUBS) | set(VIEW_STUBS) + + def ours(key): + return key == "xui" or key.startswith(base.PACKAGE) or key in names + + saved = {k: sys.modules[k] for k in list(sys.modules) if ours(k)} + for key in saved: + del sys.modules[key] + sys.modules.update(base.STUBS) + sys.modules.update(VIEW_STUBS) + try: + return importlib.import_module(base.PACKAGE + ".views") + finally: + for key in [k for k in sys.modules if ours(k)]: + del sys.modules[key] + sys.modules.update(saved) + + +views = _import_views() +TEMPLATES = os.path.join(base.EXT, "io_cloudbolt_vulnerabilities", "templates") +AT = "2026-11-24T10:00:00Z" +BUTTON = {"url": "/actions/9/dialog/7/", "label": "Install Updates", "action_id": 9} +SUMMARY = {"vulns": 12, "vuln_fixable": 9, "vuln_critical": 1, "vuln_high": 2, "vuln_medium": 3, "vuln_low": 6, + "kev": 0, "packages": 300, "os_name": "Amazon Linux 2023"} + + +def record(**over): + data = {"at": AT, "by": "alice", "job_id": 41, "status": "updated", "before": {"vulns": 12, "vuln_fixable": 9}, + "after": {"vulns": 3, "vuln_fixable": 0}, "updated": 20, "failed": 0, "restarted": True, + "restart_needed": True, "kernels_removed": 1, "duration_s": 600, "message": ""} + data.update(over) + return data + + +def context(state=None, active=None, windows=False, eligibility="", button=BUTTON, summary=SUMMARY, denied=False): + """_panel_context with everything outside it replaced; returns (context, the patch_button mock).""" + patch_button = mock.Mock(return_value=None if denied else button) + server = base.make_server() + profile = types.SimpleNamespace(is_cbadmin=False) + with contextlib.ExitStack() as stack: + enter = stack.enter_context + enter(mock.patch.object(views, "_upgrade_store")) + enter(mock.patch.object(views.vuln_db, "server_summary", return_value=dict(summary) if summary else None)) + enter(mock.patch.object(views.store, "read_state", return_value=state or {})) + enter(mock.patch.object(views.vuln_jobs, "panel_active", return_value=active)) + enter(mock.patch.object(views.vuln_jobs, "can_scan", return_value=True)) + enter(mock.patch.object(views.vuln_jobs, "in_unassigned_group", return_value=False)) + enter(mock.patch.object(views.vuln_jobs, "is_windows", return_value=windows)) + enter(mock.patch.object(views.vuln_tools, "status", return_value={"ready": True, "ready_windows": True})) + enter(mock.patch.object(views, "reverse", lambda name, args=None, **k: "/%s/%s/" % (name, (args or [""])[0]))) + enter(mock.patch.object(views.vuln_patch, "eligibility", return_value=eligibility)) + enter(mock.patch.object(views.vuln_hooks, "patch_button", patch_button, create=True)) + ctx = views._panel_context(server, profile, "REQ") + return ctx, patch_button + + +def render(vuln, error=None): + from django.template import Context, Engine + if not django.conf.settings.configured: + django.conf.settings.configure(USE_I18N=False) + engine = Engine(dirs=[TEMPLATES], libraries={"i18n": "django.templatetags.i18n"}) + base_vuln = {"denied": False, "windows": False, "can_scan": True, "ready": True, "summary": SUMMARY, + "active": None, "patch": {"offer": False, "url": "", "label": ""}, "patch_last": None, "key": "k"} + base_vuln.update(vuln) + return engine.get_template("vuln_panel.html").render(Context({"vuln": base_vuln, "error": error})) + + +class PanelContextTests(unittest.TestCase): + def test_offer_is_built_from_the_button_and_the_request_is_passed_on(self): + ctx, button = context() + self.assertEqual(ctx["vuln"]["patch"], {"offer": True, "url": BUTTON["url"], "label": "Install Updates"}) + self.assertEqual(button.call_args.args[2], "REQ") + + def test_no_offer_while_a_job_is_active_and_the_button_is_not_asked(self): + ctx, button = context(active={"job_id": 5, "kind": "patch", "title": "Installing updates"}) + self.assertFalse(ctx["vuln"]["patch"]["offer"]) + button.assert_not_called() + + def test_offer_for_an_eligible_windows_server(self): + ctx, button = context(windows=True) + self.assertEqual(ctx["vuln"]["patch"], {"offer": True, "url": BUTTON["url"], "label": "Install Updates"}) + button.assert_called_once() + + def test_no_offer_for_a_windows_server_that_is_not_eligible(self): + ctx, button = context(windows=True, eligibility="unsupported_windows") + self.assertFalse(ctx["vuln"]["patch"]["offer"]) + button.assert_not_called() + + def test_no_offer_for_windows_while_a_job_is_active(self): + ctx, button = context(windows=True, active={"job_id": 5, "kind": "patch", "title": "Installing updates"}) + self.assertFalse(ctx["vuln"]["patch"]["offer"]) + button.assert_not_called() + + def test_no_offer_when_the_server_is_not_eligible(self): + ctx, button = context(eligibility="unsupported_os") + self.assertFalse(ctx["vuln"]["patch"]["offer"]) + button.assert_not_called() + + def test_no_offer_when_the_user_may_not_run_the_action(self): + ctx, _ = context(denied=True) + self.assertFalse(ctx["vuln"]["patch"]["offer"]) + + def test_a_failing_patch_module_means_no_button_not_a_broken_panel(self): + none = {"offer": False, "url": "", "label": ""} + server, profile = base.make_server(), types.SimpleNamespace() + with mock.patch.object(views.vuln_patch, "eligibility", side_effect=RuntimeError("boom")): + self.assertEqual(views._patch_offer(server, profile, None), none) + with mock.patch.object(views.vuln_patch, "eligibility", return_value=""), \ + mock.patch.object(views.vuln_hooks, "patch_button", side_effect=RuntimeError("boom"), create=True): + self.assertEqual(views._patch_offer(server, profile, None), none) + + def test_patch_last_carries_the_record_and_the_job_link(self): + ctx, _ = context(state={"patch": record()}) + last = ctx["vuln"]["patch_last"] + self.assertEqual(last["status"], "updated") + self.assertEqual(last["before"], {"vulns": 12, "vuln_fixable": 9}) + self.assertEqual(last["job_url"], "/job_detail/41/") + + def test_no_patch_record_gives_none(self): + ctx, _ = context(state={}) + self.assertIsNone(ctx["vuln"]["patch_last"]) + + def test_the_key_changes_with_the_patch_job_id(self): + first, _ = context(state={"patch": record(job_id=41)}) + second, _ = context(state={"patch": record(job_id=42)}) + none, _ = context(state={}) + self.assertNotEqual(first["vuln"]["key"], second["vuln"]["key"]) + self.assertNotEqual(first["vuln"]["key"], none["vuln"]["key"]) + + +@unittest.skipUnless(HAVE_DJANGO, "Django is not installed") +class TemplateTests(unittest.TestCase): + ANCHOR = 'class="btn btn-sm btn-outline-primary open-dialog" href="/actions/9/dialog/7/"' + + def offer(self, **over): + return dict({"patch": {"offer": True, "url": BUTTON["url"], "label": "Install Updates"}}, **over) + + def note(self, html): + return html.split("data-vuln-patch")[1].split('class="vuln-bar"')[0] + + def test_the_anchor_opens_the_dialog_in_the_toolbar(self): + html = render(self.offer()) + self.assertEqual(html.count(self.ANCHOR), 1) + self.assertGreater(html.index(self.ANCHOR), html.index('class="vuln-bar"')) + + def test_the_anchor_is_in_the_first_scan_section_too(self): + html = render(self.offer(summary=None)) + self.assertEqual(html.count(self.ANCHOR), 1) + self.assertIn("No scan yet", html) + + def test_no_anchor_when_not_offered_or_when_active(self): + self.assertNotIn("open-dialog", render({})) + self.assertNotIn("open-dialog", render(self.offer(active={"job_id": 5, "kind": "scan"}))) + self.assertNotIn("open-dialog", render(self.offer(summary=None, active={"job_id": 5, "kind": "scan"}))) + + def test_the_banner_title_follows_the_kind(self): + patch = render({"active": {"job_id": 5, "kind": "patch", "started": AT, "message": "Installing"}}) + scan = render({"active": {"job_id": 5, "kind": "scan", "started": AT}}) + check = render({"active": {"job_id": 5, "kind": "scan"}, "windows": True}) + self.assertIn("Installing updates", patch) + self.assertNotIn("Scan running", patch) + self.assertIn("Scan running", scan) + self.assertIn("Check running", check) + + def test_updated_line(self): + html = render({"patch_last": dict(record(), job_url="/job_detail/41/")}) + self.assertIn('Updated ' % AT, html) + self.assertIn("by alice.", html) + self.assertIn("Known vulnerabilities 12 → 3.", html) + self.assertIn("With a fix 9 → 0.", html) + self.assertIn('View job', html) + self.assertNotIn("A restart is pending", html) + + def test_null_numbers_are_dashes(self): + html = render({"patch_last": dict(record(before=None, after=None), job_url="")}) + self.assertIn("Known vulnerabilities – → –.", html) + self.assertIn("With a fix – → –.", html) + self.assertNotIn("View job", self.note(html)) + html = render({"patch_last": dict(record(after=None), job_url="")}) + self.assertIn("Known vulnerabilities 12 → –.", html) + + def test_no_updates_line_in_both_copies(self): + for extra in ({}, {"summary": None}): + html = render(dict({"patch_last": dict(record(status="no_updates"), job_url="/job_detail/41/")}, **extra)) + self.assertIn('Checked ' % AT, html) + self.assertIn("by alice.", html) + self.assertIn("No updates were available.", html) + self.assertIn("Known vulnerabilities 12 → 3.", html) + self.assertIn('View job', html) + self.assertNotIn("Updated alert(1)", html) + self.assertNotIn("Known vulnerabilities 12", self.note(html)) + + def test_the_note_shows_without_a_scan_summary(self): + html = render({"summary": None, "patch_last": dict(record(status="failed", message="repo unreachable"), + job_url="")}) + self.assertEqual(html.count("data-vuln-patch"), 1) + self.assertIn("Updating failed x", html) + + +class SettingsViewTests(unittest.TestCase): + STATE = {"exists": True, "enabled": True, "action_id": 9} + MISSING = {"exists": False, "enabled": False, "action_id": None} + + def post(self, apply_patching=None, patching=True, was=False, state=None, state_error=False, resource_state=None): + request = types.SimpleNamespace(method="POST", POST={"x": "1"}) + clean = {"patching": patching, "scan_on_provision": False} + if state_error: + get_state = mock.Mock(side_effect=RuntimeError("boom")) + else: + get_state = mock.Mock(return_value=state or self.STATE) + get_resource = mock.Mock(return_value=resource_state or self.STATE) + with mock.patch.object(views.store, "validate_settings", return_value=(clean, {})), mock.patch.object(views.store, "save_settings"), mock.patch.object(views.store, "get_settings", return_value={"patching": was}), mock.patch.object(views.vuln_hooks, "apply_provision_setting", create=True), mock.patch.object(views.vuln_hooks, "apply_patching_setting", apply_patching or mock.Mock(), + create=True), mock.patch.object(views.vuln_hooks, "patch_action_state", get_state, create=True), mock.patch.object(views.vuln_hooks, "resource_patch_action_state", get_resource, create=True), mock.patch.object(views.vuln_hooks, "ensure_schedules", return_value=[], create=True), mock.patch.object(views, "_schedule_rows", return_value=[]), mock.patch.object(views, "_scanner_context", return_value={}), mock.patch.object(views, "_fleet_url", return_value=""), mock.patch.object(views, "reverse", return_value="/setup/"): + return views.settings(request)[1] + + def test_off_to_on_applies_it(self): + apply = mock.Mock() + ctx = self.post(apply, patching=True, was=False) + apply.assert_called_once_with(True, create_only=False) + self.assertEqual(ctx["warnings"], []) + + def test_on_to_on_with_both_actions_present_leaves_them_alone(self): + apply = mock.Mock() + self.post(apply, patching=True, was=True) + apply.assert_not_called() + + def test_on_to_on_with_the_action_missing_applies_it_create_only(self): + apply = mock.Mock() + self.post(apply, patching=True, was=True, state=self.MISSING) + apply.assert_called_once_with(True, create_only=True) + + def test_on_to_on_with_only_the_resource_action_missing_applies_it_create_only(self): + apply = mock.Mock() + self.post(apply, patching=True, was=True, resource_state=self.MISSING) + apply.assert_called_once_with(True, create_only=True) + + def test_on_to_off_applies_false(self): + apply = mock.Mock() + self.post(apply, patching=False, was=True) + apply.assert_called_once_with(False, create_only=False) + + def test_off_to_off_leaves_it_alone(self): + apply = mock.Mock() + self.post(apply, patching=False, was=False) + apply.assert_not_called() + + def test_a_failure_is_a_warning_and_the_save_stands(self): + # The server action did not follow (it does not exist after the failed apply); the resource action did. + ctx = self.post(mock.Mock(side_effect=RuntimeError("no hook")), state=self.MISSING) + self.assertEqual(ctx["warnings"], [views.PATCHING_ERROR]) + self.assertTrue(ctx["saved"]) + + def test_the_action_state_is_in_the_context(self): + self.assertEqual(self.post()["patch_action"], self.STATE) + self.assertEqual(self.post(state_error=True, patching=False, was=False)["patch_action"], self.MISSING) + + +if __name__ == "__main__": + unittest.main() diff --git a/extensions/XUI-wqrj0e3p/tests/test_vuln_patch_resource.py b/extensions/XUI-wqrj0e3p/tests/test_vuln_patch_resource.py new file mode 100644 index 00000000..ad2c949a --- /dev/null +++ b/extensions/XUI-wqrj0e3p/tests/test_vuln_patch_resource.py @@ -0,0 +1,1000 @@ +""" +Checks for installing updates on all servers of a resource (vuln_patch_resource.py, vuln_resource_patch_job.py and +vuln_resource_patch_condition.py) without CloudBolt: CloudBolt's modules are stubs, the resource marker and the last-run +record are in memory, the per-server engine (vuln_patch._patch_one) is a scripted fake, and the permission and +eligibility checks are fakes the tests turn on and off. + + python -B -m unittest discover -s extensions/XUI-wqrj0e3p/tests -p "test_vuln_patch_resource.py" + +The stubs are in place only while this file imports the extension's modules (the same swap test_vuln_patch.py makes), +so another test file's stubs are not disturbed. +""" +import contextlib +import importlib +import json +import os +import re +import sys +import tempfile +import types +import unittest +from unittest import mock + +HERE = os.path.dirname(os.path.abspath(__file__)) +EXT = os.path.dirname(HERE) +PACKAGE = "xui.io_cloudbolt_vulnerabilities" +PKG_DIR = os.path.join(EXT, "io_cloudbolt_vulnerabilities") + + +class IntegrityError(Exception): + pass + + +class CancelJob(BaseException): + """Stands in for CloudBolt's CancelJobException, which is a BaseException.""" + + +class Http404(Exception): + pass + + +class TimeoutException(Exception): + pass + + +class FakeLogger: + def __init__(self, *a): + pass + + def __getattr__(self, name): + return lambda *a, **k: None + + +def _module(name, **attrs): + module = types.ModuleType(name) + module.__dict__.update(attrs) + return module + + +TMP = tempfile.mkdtemp(prefix="vuln-patch-resource-test-") +STUBS = {} + + +def _stub(name, **attrs): + STUBS[name] = _module(name, **attrs) + return STUBS[name] + + +_stub("django") +_stub("django.conf", settings=types.SimpleNamespace(PROSERV_DIR=TMP, CLOUDBOLT_OS_USER="u", CLOUDBOLT_OS_GROUP="g")) +_stub("django.http", FileResponse=object, Http404=Http404, HttpResponse=object) +_stub("django.urls", reverse=lambda *a, **k: "/x/") +_stub("django.db", IntegrityError=IntegrityError, + transaction=types.SimpleNamespace(atomic=lambda: contextlib.nullcontext())) +_stub("cbhooks") +_stub("cbhooks.models", CloudBoltHook=object) +_stub("accounts") +_stub("accounts.models", Group=object, UserProfile=object) +_stub("infrastructure") +_stub("infrastructure.models", Server=object) +_stub("jobs") +_stub("jobs.models", Job=object) +_stub("portals") +_stub("portals.models") +_stub("utilities") +_stub("utilities.events", add_server_event=lambda *a, **k: None) +_stub("utilities.exceptions", TimeoutException=TimeoutException) +_stub("utilities.logger", ThreadLogger=FakeLogger) +_stub("utilities.permissions", server_action_permitted=lambda *a, **k: False) +_xui = _stub("xui") +_xui.__path__ = [EXT] + + +def _import_extension(): + """Import the extension's modules against the stubs, leaving sys.modules as it was found.""" + touched = [k for k in sys.modules if k == "xui" or k.startswith(PACKAGE) or k in STUBS] + saved = {k: sys.modules[k] for k in touched} + for key in touched: + del sys.modules[key] + sys.modules.update(STUBS) + try: + names = ("vuln_store", "vuln_match", "vuln_db", "vuln_tools", "vuln_repo", "vuln_hooks", "vuln_jobs", + "vuln_fleet", "vuln_patch", "vuln_patch_resource") + return {name: importlib.import_module(PACKAGE + "." + name) for name in names} + finally: + for key in [k for k in sys.modules if k == "xui" or k.startswith(PACKAGE) or k in STUBS]: + del sys.modules[key] + sys.modules.update(saved) + + +MODS = _import_extension() +store, hooks, jobs, fleet, patch, rsrc = (MODS[n] for n in ( + "vuln_store", "vuln_hooks", "vuln_jobs", "vuln_fleet", "vuln_patch", "vuln_patch_resource")) + +RESOURCE_ID = 50 +OWNER_ID = 3 +# The template engine's markers, built here so this file has none of its own. +OPEN, CLOSE = "{" * 2, "}" * 2 + + +# ---------------------------------------------------------------- fakes +def make_server(server_id, hostname=None, **over): + data = dict(id=server_id, hostname=hostname or "web-{:02d}".format(server_id), status="ACTIVE", + resource_id=RESOURCE_ID, group=types.SimpleNamespace(is_unassigned=False, name="Dev")) + data.update(over) + return types.SimpleNamespace(**data) + + +def record(status="updated", **over): + """What vuln_patch._patch_one returns.""" + data = {"family": "linux", "status": status, "updated": 4, "failed": 0, "restarted": False, + "restart_needed": status == "restart_pending", "kernels_removed": 0, "before": None, "after": None, + "message": "", "warning": status in ("failed", "restart_pending"), "hostname": "x"} + data.update(over) + return data + + +def make_job(job_id=11, owner="default", username="alice"): + progress = [] + if owner == "default": + owner = types.SimpleNamespace(id=OWNER_ID, user=types.SimpleNamespace(username=username, is_active=True)) + return types.SimpleNamespace(id=job_id, owner=owner, progress=progress, + set_progress=lambda message, **k: progress.append((message, k))) + + +class FakeQuerySet: + def __init__(self, items=None): + self.items = items or [] + self.calls = [] + + def exclude(self, *a, **k): + self.calls.append(("exclude", a, k)) + return self + + def filter(self, *a, **k): + self.calls.append(("filter", a, k)) + return self + + def exists(self): + return bool(self.items) + + +class Base(unittest.TestCase): + """In-memory resource marker and record, a fake engine, fake checks, a clock.""" + + def setUp(self): + self.servers = [make_server(1), make_server(2), make_server(3)] + self.settings = {"visibility": "linux", "patch_timeout_min": 90, "restart_wait_min": 30, "patching": True} + self.marker = None + self.marker_writes = [] + self.last = None + self.record_writes = [] + self.clock_now = 0.0 + self.cancelled = False + self.live_jobs = {} + self.engine = {} + self.engine_calls = [] + self.codes = {} + self.no_view = set() + self.no_patch = set() + self.active_user = True + self.profile_gone = False + self.progress_calls = [] + self.permission_profiles = [] + self.action_state = {"exists": True, "enabled": True, "action_id": 9} + self.patches = [ + mock.patch.dict(sys.modules, STUBS), + mock.patch.object(store, "get_settings", side_effect=lambda: dict(self.settings)), + mock.patch.object(store, "resource_lock", lambda resource_id: contextlib.nullcontext()), + mock.patch.object(store, "read_resource_run", side_effect=lambda rid: self.marker), + mock.patch.object(store, "set_resource_run", side_effect=self._set_marker), + mock.patch.object(store, "clear_resource_run", side_effect=self._clear_marker), + mock.patch.object(store, "set_resource_patch", side_effect=self._set_record), + mock.patch.object(fleet, "default_base_url", return_value="https://cb.example.com"), + mock.patch.object(fleet, "prerequisites", return_value={}), + mock.patch.object(fleet, "resource_servers", side_effect=lambda resource: list(self.servers)), + mock.patch.object(fleet, "_fetch_for_scan", side_effect=self._fetch), + mock.patch.object(fleet, "_cancelled", side_effect=lambda job: self.cancelled), + mock.patch.object(fleet, "_progress", side_effect=self._progress), + mock.patch.object(jobs, "Job", self._job_model()), + mock.patch.object(jobs, "can_view", side_effect=self._can_view), + mock.patch.object(hooks, "server_patch_permitted", side_effect=self._permitted), + mock.patch.object(patch, "eligibility", + side_effect=lambda server, problems=None: self.codes.get(server.id, "")), + mock.patch.object(patch, "_clock", side_effect=lambda: self.clock_now), + mock.patch.object(patch, "_patch_one", side_effect=self._patch_one), + mock.patch.object(rsrc, "UserProfile", self._profile_model()), + mock.patch.object(rsrc, "Server", self._server_model()), + mock.patch.object(hooks, "resource_patch_action_state", side_effect=lambda: dict(self.action_state)), + ] + for patcher in self.patches: + patcher.start() + self.addCleanup(patcher.stop) + + # -- the marker and the record + def _set_marker(self, resource_id, marker): + self.marker = dict(marker) + self.marker_writes.append(dict(marker)) + + def _clear_marker(self, resource_id, job_id=None): + if job_id is not None and (not isinstance(self.marker, dict) or self.marker.get("job_id") != job_id): + return False + self.marker = None + return True + + def _set_record(self, resource_id, rec): + self.last = rec + self.record_writes.append(rec) + + # -- the world + def _job_model(self): + outer = self + + class Manager: + def filter(self, **kw): + job = outer.live_jobs.get(kw.get("id")) + return types.SimpleNamespace(first=lambda: job) + + return types.SimpleNamespace(objects=Manager()) + + def _profile_model(self): + outer = self + + class Manager: + def select_related(self, *a): + return self + + def filter(self, **kw): + fresh = None if outer.profile_gone else types.SimpleNamespace( + id=kw.get("id"), user=types.SimpleNamespace(is_active=outer.active_user, username="alice")) + return types.SimpleNamespace(first=lambda: fresh) + + return types.SimpleNamespace(objects=Manager()) + + def _server_model(self): + outer = self + + class Server: + @staticmethod + def objects_for_profile(profile): + return types.SimpleNamespace(filter=lambda **kw: types.SimpleNamespace( + values_list=lambda *a, **k: [s.id for s in outer.servers if s.id not in outer.no_view])) + + return Server + + def _fetch(self, server_id): + for server in self.servers: + if server.id == server_id: + return server + return None + + def _can_view(self, profile, server): + return server.id not in self.no_view + + def _permitted(self, profile, server): + self.permission_profiles.append(profile) + return server.id not in self.no_patch + + def _progress(self, job, message, done=None, total=None): + self.progress_calls.append((message, done, total)) + + def _patch_one(self, job, server, restart, cfg): + self.engine_calls.append({"id": server.id, "restart": restart, "marker": dict(self.marker or {}), + "clock": self.clock_now}) + item = self.engine.get(server.id, record()) + if callable(item): + item = item(server) + if isinstance(item, BaseException): + raise item + return dict(item, hostname=server.hostname) + + def live(self, job_id, kind="patch"): + """A marker of another job that is still active.""" + self.marker = {"job_id": job_id, "started": "2026-11-24T10:00:00Z", "requested_by": "bob", "server_ids": [1], + "kind": kind} + self.live_jobs[job_id] = types.SimpleNamespace(id=job_id, is_active=lambda: True) + + def go(self, job=None, restart=True, resource=None, **kw): + job = job or make_job() + resource = resource or types.SimpleNamespace(id=RESOURCE_ID, name="Web tier") + return job, rsrc.run_resource_patch(job, resource=resource, restart_if_needed=restart, **kw) + + def ids_by_status(self, outputs, status): + return [int(key) for key, value in outputs["servers"].items() if value["status"] == status] + + +# ---------------------------------------------------------------- the run +class FlowTests(Base): + def test_servers_go_one_at_a_time_in_the_resource_order(self): + job, (status, output, errors, outputs) = self.go() + self.assertEqual((status, errors), ("SUCCESS", "")) + self.assertEqual([call["id"] for call in self.engine_calls], [1, 2, 3]) + self.assertEqual(outputs["order"], [1, 2, 3]) + self.assertEqual(outputs["counts"], {"updated": 3, "no_updates": 0, "restart_pending": 0, "failed": 0, "skipped": 0}) + self.assertEqual(outputs["resource_id"], RESOURCE_ID) + self.assertIsNone(outputs["stopped_at"]) + self.assertEqual(list(outputs["servers"]), ["1", "2", "3"]) + self.assertEqual(outputs["servers"]["1"]["hostname"], "web-01") + self.assertIn("web-02: 4 packages updated.", output) + + def test_progress_names_the_server_before_it_starts(self): + self.go() + self.assertEqual(self.progress_calls, [("Server 1 of 3: web-01", 0, 3), ("Server 2 of 3: web-02", 1, 3), + ("Server 3 of 3: web-03", 2, 3)]) + + def test_the_restart_flag_reaches_every_server(self): + self.go(restart="false") + self.assertEqual([call["restart"] for call in self.engine_calls], [False, False, False]) + self.assertIs(self.last["restart_if_needed"], False) + self.engine_calls[:] = [] + self.go() + self.assertEqual([call["restart"] for call in self.engine_calls], [True, True, True]) + + def test_the_marker_is_set_while_it_runs_and_cleared_after(self): + self.go() + self.assertEqual(len(self.marker_writes), 1) + first = self.marker_writes[0] + self.assertEqual((first["job_id"], first["kind"], first["server_ids"], first["requested_by"]), + (11, "patch", [1, 2, 3], "alice")) + self.assertTrue(first["started"]) + self.assertEqual(self.engine_calls[1]["marker"]["job_id"], 11) + self.assertIsNone(self.marker) + + def test_a_no_updates_server_is_not_a_failure(self): + self.engine[2] = record("no_updates", warning=False, message="") + _, (status, output, errors, outputs) = self.go() + self.assertEqual(status, "SUCCESS") + self.assertEqual(outputs["servers"]["2"]["status"], "no_updates") + self.assertIn("web-02: no updates were available.", output) + self.assertEqual(outputs["counts"]["updated"], 2) + self.assertEqual(outputs["counts"]["no_updates"], 1) + self.assertEqual(self.last["counts"]["no_updates"], 1) + + def test_a_restart_pending_server_does_not_stop_the_run(self): + self.engine[1] = record("restart_pending") + _, (status, output, errors, outputs) = self.go() + self.assertEqual(status, "WARNING") + self.assertEqual([call["id"] for call in self.engine_calls], [1, 2, 3]) + self.assertEqual(outputs["counts"], {"updated": 2, "no_updates": 0, "restart_pending": 1, "failed": 0, "skipped": 0}) + self.assertEqual(self.last["status"], "warning") + + def test_a_warning_makes_the_run_a_warning(self): + self.engine[3] = record("updated", warning=True, message="The rescan failed.") + _, (status, output, errors, outputs) = self.go() + self.assertEqual(status, "WARNING") + self.assertEqual(outputs["counts"]["updated"], 3) + + def test_the_run_stops_at_the_first_failure_and_reports_the_rest_as_skipped(self): + self.engine[2] = record("failed", message="The update stopped before it finished.") + _, (status, output, errors, outputs) = self.go() + self.assertEqual([call["id"] for call in self.engine_calls], [1, 2]) + self.assertEqual(outputs["stopped_at"], 2) + self.assertEqual(outputs["counts"], {"updated": 1, "no_updates": 0, "restart_pending": 0, "failed": 1, "skipped": 1}) + self.assertEqual(outputs["servers"]["3"]["status"], "skipped") + self.assertIn("not attempted, web-02 failed", outputs["servers"]["3"]["message"]) + self.assertIn("web-02 failed", errors) + self.assertEqual(status, "FAILURE") + + def test_a_first_server_failure_with_nothing_updated_is_a_failure(self): + self.engine[1] = record("failed", message="Could not be reached.") + _, (status, output, errors, outputs) = self.go() + self.assertEqual(status, "FAILURE") + self.assertEqual(len(self.engine_calls), 1) + self.assertEqual(outputs["counts"], {"updated": 0, "no_updates": 0, "restart_pending": 0, "failed": 1, "skipped": 2}) + self.assertEqual(self.last["status"], "failure") + + def test_an_unexpected_error_in_the_engine_is_a_failure_of_that_server(self): + self.engine[1] = RuntimeError("boom") + _, (status, output, errors, outputs) = self.go() + self.assertEqual(outputs["servers"]["1"]["status"], "failed") + self.assertEqual(len(self.engine_calls), 1) + self.assertEqual(status, "FAILURE") + + def test_a_server_the_engine_did_not_touch_is_skipped_and_the_run_goes_on(self): + self.engine[1] = patch.PatchFailed("Job 5 is still running on this server; wait for it to finish.") + _, (status, output, errors, outputs) = self.go() + self.assertEqual(outputs["servers"]["1"]["status"], "skipped") + self.assertIn("still running", outputs["servers"]["1"]["message"]) + self.assertEqual([call["id"] for call in self.engine_calls], [1, 2, 3]) + self.assertEqual(outputs["counts"], {"updated": 2, "no_updates": 0, "restart_pending": 0, "failed": 0, "skipped": 1}) + self.assertEqual(status, "WARNING") + self.assertIsNone(outputs["stopped_at"]) + + def test_an_ineligible_server_is_skipped_with_its_reason(self): + self.codes[2] = "powered_off" + _, (status, output, errors, outputs) = self.go() + self.assertEqual([call["id"] for call in self.engine_calls], [1, 3]) + self.assertEqual(outputs["servers"]["2"], {"hostname": "web-02", "status": "skipped", + "message": "Skipped: powered off."}) + self.assertEqual(status, "WARNING") + + def test_nothing_eligible_is_a_failure(self): + for server in self.servers: + self.codes[server.id] = "powered_off" + _, (status, output, errors, outputs) = self.go() + self.assertEqual(status, "FAILURE") + self.assertEqual(errors, rsrc.NOTHING_UPDATED) + self.assertEqual(self.engine_calls, []) + self.assertEqual(outputs["counts"]["skipped"], 3) + self.assertEqual(self.last["status"], "failure") + + def test_a_resource_with_no_servers_is_a_failure(self): + self.servers = [] + _, (status, output, errors, outputs) = self.go() + self.assertEqual(status, "FAILURE") + self.assertEqual(outputs["order"], []) + + +# ---------------------------------------------------------------- permissions +class PermissionTests(Base): + def test_a_server_the_owner_may_not_patch_is_skipped_and_not_named(self): + self.no_patch.add(2) + _, (status, output, errors, outputs) = self.go() + self.assertEqual([call["id"] for call in self.engine_calls], [1, 3]) + item = outputs["servers"]["2"] + self.assertEqual(item["status"], "skipped") + self.assertEqual(item["hostname"], "web-02") + self.assertIn("may not install updates", item["message"]) + self.assertEqual(status, "WARNING") + + def test_a_server_the_owner_may_not_view_is_skipped(self): + self.no_view.add(1) + _, (status, output, errors, outputs) = self.go() + self.assertEqual(self.ids_by_status(outputs, "skipped"), [1]) + self.assertEqual(outputs["servers"]["1"]["hostname"], "Server 1") + self.assertNotIn("web-01", json.dumps(outputs) + output + json.dumps(self.last)) + + def test_the_permission_is_checked_as_the_owner_read_fresh(self): + self.go() + self.assertEqual(len(self.permission_profiles), 3) + self.assertTrue(all(profile.id == OWNER_ID and profile.user.is_active for profile in self.permission_profiles)) + + def test_an_owner_who_is_deactivated_mid_run_gets_no_more_servers(self): + def deactivate(server): + self.active_user = False + return record() + + self.engine[1] = deactivate + _, (status, output, errors, outputs) = self.go() + self.assertEqual([call["id"] for call in self.engine_calls], [1]) + self.assertEqual(self.ids_by_status(outputs, "skipped"), [2, 3]) + self.assertEqual(outputs["servers"]["2"]["hostname"], "web-02") + self.assertEqual(status, "WARNING") + + def test_an_owner_whose_profile_is_gone_updates_nothing(self): + self.profile_gone = True + _, (status, output, errors, outputs) = self.go() + self.assertEqual(self.engine_calls, []) + self.assertEqual(status, "FAILURE") + + def test_a_server_in_an_unassigned_group_is_never_touched(self): + self.servers[1].group = types.SimpleNamespace(is_unassigned=True, name="Unassigned") + _, (status, output, errors, outputs) = self.go() + self.assertEqual([call["id"] for call in self.engine_calls], [1, 3]) + self.assertEqual(outputs["servers"]["2"]["message"], "Skipped: in an Unassigned group.") + # Not even asked about permission: an Unassigned server is out before the permission check. + self.assertEqual(len(self.permission_profiles), 2) + + def test_a_server_that_left_the_resource_or_became_historical_is_skipped(self): + self.servers[0].resource_id = 99 + self.servers[1].status = "HISTORICAL" + _, (status, output, errors, outputs) = self.go() + self.assertEqual([call["id"] for call in self.engine_calls], [3]) + self.assertEqual(outputs["servers"]["1"]["message"], "Skipped: no longer in this resource.") + self.assertEqual(outputs["servers"]["2"]["message"], "Skipped: historical.") + + def test_a_server_that_is_gone_is_skipped(self): + fetch = self._fetch + with mock.patch.object(fleet, "_fetch_for_scan", side_effect=lambda i: None if i == 2 else fetch(i)): + _, (status, output, errors, outputs) = self.go() + self.assertEqual(outputs["servers"]["2"]["message"], "Skipped: no longer in CloudBolt.") + self.assertEqual([call["id"] for call in self.engine_calls], [1, 3]) + + +class InFlightAndNamesTests(Base): + def spy_close(self): + runs = [] + original = rsrc._Run.close + + def close(run): + runs.append(run) + return original(run) + + return runs, mock.patch.object(rsrc._Run, "close", close) + + def test_a_cancel_during_an_update_marks_that_server_and_skips_the_rest(self): + self.engine[2] = CancelJob() + runs, spy = self.spy_close() + with spy, self.assertRaises(CancelJob): + self.go() + run = runs[0] + self.assertEqual(run.results[1]["status"], "updated") + self.assertEqual(run.results[2]["status"], "failed") + self.assertEqual(run.results[2]["message"], rsrc.IN_FLIGHT) + self.assertIn("may still finish", rsrc.IN_FLIGHT) + self.assertEqual(run.results[3]["status"], "skipped") + self.assertIn("web-02: The job was canceled while this server was updating.", "\n".join(run.lines)) + self.assertEqual(self.last["status"], "warning") + self.assertEqual(self.last["counts"]["failed"], 1) + self.assertEqual(self.last["counts"]["skipped"], 1) + self.assertTrue(any(patch.GUEST_KEEPS_RUNNING in m for m, d, t in self.progress_calls)) + + def test_a_cancel_in_the_first_server_skips_the_two_after_it(self): + self.engine[1] = CancelJob() + runs, spy = self.spy_close() + with spy, self.assertRaises(CancelJob): + self.go() + self.assertEqual(runs[0].results[1]["message"], rsrc.IN_FLIGHT) + self.assertEqual(self.last["counts"]["skipped"], 2) + + def test_an_error_in_the_fetch_of_one_server_skips_it_and_goes_on(self): + def broken(server_id): + if server_id == 2: + raise RuntimeError("db down") + return self._fetch(server_id) + + with mock.patch.object(fleet, "_fetch_for_scan", side_effect=broken): + _, (status, output, errors, outputs) = self.go() + self.assertEqual([call["id"] for call in self.engine_calls], [1, 3]) + self.assertEqual(outputs["servers"]["2"]["status"], "skipped") + self.assertIn("db down", outputs["servers"]["2"]["message"]) + self.assertFalse(any(patch.GUEST_KEEPS_RUNNING in m for m, d, t in self.progress_calls)) + self.assertEqual(status, "WARNING") + + def test_the_error_text_is_cleaned_like_the_engine_cleans_it(self): + def broken(server_id): + raise RuntimeError("x" * 500) + + with mock.patch.object(fleet, "_fetch_for_scan", side_effect=broken): + _, (status, output, errors, outputs) = self.go() + self.assertLessEqual(len(outputs["servers"]["1"]["message"]), 300) + self.assertEqual(self.engine_calls, []) + + def test_an_error_in_a_permission_check_skips_that_server_only(self): + def boom(profile, server): + if server.id == 1: + raise RuntimeError("perm down") + return True + + with mock.patch.object(hooks, "server_patch_permitted", side_effect=boom): + _, (status, output, errors, outputs) = self.go() + self.assertEqual([call["id"] for call in self.engine_calls], [2, 3]) + self.assertIn("perm down", outputs["servers"]["1"]["message"]) + + def test_servers_the_owner_cannot_view_are_never_named(self): + self.no_view.add(2) + _, (status, output, errors, outputs) = self.go() + text = json.dumps(outputs) + output + json.dumps(self.last) + self.assertNotIn("web-02", text) + self.assertEqual(outputs["servers"]["2"]["hostname"], "Server 2") + self.assertEqual(outputs["servers"]["1"]["hostname"], "web-01") + self.assertNotIn("web-02", " ".join(m for m, d, t in self.progress_calls)) + + def test_the_not_attempted_lines_do_not_name_an_unviewable_server(self): + self.no_view.add(3) + self.engine[2] = record("failed", message="stopped") + _, (status, output, errors, outputs) = self.go() + self.assertNotIn("web-03", output + json.dumps(outputs)) + self.assertIn("Server 3: skipped", output) + + def test_the_not_attempted_lines_written_at_close_do_not_name_one_either(self): + self.no_view.add(3) + self.engine[2] = CancelJob() + runs, spy = self.spy_close() + with spy, self.assertRaises(CancelJob): + self.go() + self.assertEqual(runs[0].results[3]["hostname"], "Server 3") + self.assertNotIn("web-03", "\n".join(runs[0].lines)) + + +# ---------------------------------------------------------------- gates, budget, cancel, marker +class GateTests(Base): + def test_patching_off_is_a_failure_that_touches_nothing(self): + self.settings["patching"] = False + _, (status, output, errors, outputs) = self.go() + self.assertEqual((status, errors), ("FAILURE", patch.PATCHING_OFF)) + self.assertEqual(self.engine_calls, []) + self.assertEqual(self.marker_writes, []) + self.assertEqual(self.record_writes, []) + + def test_an_action_an_admin_switched_off_does_not_run(self): + self.action_state = {"exists": True, "enabled": False, "action_id": 9} + _, (status, output, errors, outputs) = self.go() + self.assertEqual((status, errors), ("FAILURE", rsrc.ACTION_OFF)) + self.assertEqual(self.engine_calls, []) + self.assertEqual(self.marker_writes, []) + self.assertEqual(self.record_writes, []) + + def test_a_missing_action_or_an_unreadable_state_does_not_stop_the_run(self): + self.action_state = {"exists": False, "enabled": False, "action_id": None} + self.assertEqual(self.go()[1][0], "SUCCESS") + with mock.patch.object(hooks, "resource_patch_action_state", side_effect=RuntimeError("x")): + self.assertEqual(self.go(job=make_job(12))[1][0], "SUCCESS") + + def test_patching_off_is_reported_before_the_action_state(self): + self.settings["patching"] = False + self.action_state = {"exists": True, "enabled": False, "action_id": 9} + self.assertEqual(self.go()[1][2], patch.PATCHING_OFF) + + def test_a_job_without_an_owner_updates_nothing(self): + job = make_job(owner=None) + _, (status, output, errors, outputs) = self.go(job=job) + self.assertEqual(status, "FAILURE") + self.assertIn("no owner", errors) + self.assertEqual(self.engine_calls, []) + self.assertEqual(self.marker_writes, []) + + def test_exactly_one_resource_is_needed(self): + job = make_job() + for found in ([], [types.SimpleNamespace(id=1), types.SimpleNamespace(id=2)]): + status, output, errors, outputs = rsrc.run_resource_patch(job, resources=found) + self.assertEqual((status, errors), ("FAILURE", rsrc.NO_RESOURCE)) + status, output, errors, outputs = rsrc.run_resource_patch(job) + self.assertEqual(status, "FAILURE") + self.assertEqual(self.engine_calls, []) + + def test_the_resources_keyword_works_like_the_resource_keyword(self): + job = make_job() + status, output, errors, outputs = rsrc.run_resource_patch( + job, resources=[types.SimpleNamespace(id=RESOURCE_ID, name="Web tier")], restart_if_needed=True) + self.assertEqual(status, "SUCCESS") + + def test_a_second_run_is_refused_and_leaves_the_first_alone(self): + self.live(77) + before = dict(self.marker) + _, (status, output, errors, outputs) = self.go() + self.assertEqual(status, "FAILURE") + self.assertEqual(errors, "Job 77 is already running on this resource.") + self.assertEqual(self.engine_calls, []) + self.assertEqual(self.marker, before) + self.assertEqual(self.record_writes, []) + + def test_a_scan_of_the_resource_also_refuses_it(self): + self.live(78, kind="scan") + _, (status, output, errors, outputs) = self.go() + self.assertEqual((status, errors), ("FAILURE", "Job 78 is already running on this resource.")) + + def test_a_stale_marker_does_not_refuse_it(self): + self.marker = {"job_id": 5, "started": "x", "requested_by": "bob", "server_ids": [], "kind": "patch"} + _, (status, output, errors, outputs) = self.go() + self.assertEqual(status, "SUCCESS") + self.assertEqual(self.marker_writes[0]["job_id"], 11) + + def test_a_rerun_of_the_same_job_is_let_in(self): + self.live(11) + _, (status, output, errors, outputs) = self.go() + self.assertEqual(status, "SUCCESS") + + def test_an_unreadable_marker_means_no_run(self): + with mock.patch.object(store, "read_resource_run", side_effect=store.StoreError("bad")): + _, (status, output, errors, outputs) = self.go() + self.assertEqual(status, "FAILURE") + self.assertEqual(errors, fleet.RESOURCE_STATE_ERROR) + self.assertEqual(self.engine_calls, []) + + +class BudgetTests(Base): + def test_no_server_starts_when_its_worst_case_would_pass_the_job_limit(self): + def slow(server): + self.clock_now += 10000 + return record() + + for server in self.servers: + self.engine[server.id] = slow + _, (status, output, errors, outputs) = self.go() + # Worst case 150 minutes: servers start at 0 and 10000 seconds, not at 20000 (20000 + 9000 > 27000). + self.assertEqual([call["id"] for call in self.engine_calls], [1, 2]) + self.assertEqual(outputs["servers"]["3"]["status"], "skipped") + self.assertIn("8 hour limit", outputs["servers"]["3"]["message"]) + self.assertIn("150 minutes", outputs["servers"]["3"]["message"]) + self.assertEqual(status, "WARNING") + + def test_the_worst_case_follows_the_settings(self): + self.settings.update(patch_timeout_min=300, restart_wait_min=120) + + def slow(server): + self.clock_now += 1 + return record() + + self.engine[1] = slow + self.go() + # 300 + 120 + 30 minutes is exactly 27000 seconds: server 1 fits at time 0, server 2 not a second later. + self.assertEqual([call["id"] for call in self.engine_calls], [1]) + + def test_a_cancel_between_servers_skips_the_rest(self): + def cancel(server): + self.cancelled = True + return record() + + self.engine[1] = cancel + _, (status, output, errors, outputs) = self.go() + self.assertEqual([call["id"] for call in self.engine_calls], [1]) + self.assertEqual(self.ids_by_status(outputs, "skipped"), [2, 3]) + self.assertIn("canceled", outputs["servers"]["2"]["message"]) + self.assertEqual(status, "WARNING") + self.assertIsNone(self.marker) + + def test_a_cancel_that_raises_clears_the_marker_writes_the_record_and_goes_on_raising(self): + self.engine[2] = CancelJob() + with self.assertRaises(CancelJob): + self.go() + self.assertIsNone(self.marker) + self.assertEqual(len(self.record_writes), 1) + self.assertEqual(self.last["status"], "warning") + self.assertEqual(self.last["counts"], {"updated": 1, "no_updates": 0, "restart_pending": 0, "failed": 1, "skipped": 1}) + self.assertTrue(any(patch.GUEST_KEEPS_RUNNING in message for message, done, total in self.progress_calls)) + + def test_the_marker_is_cleared_when_the_run_ends_in_an_error(self): + with mock.patch.object(rsrc, "_execute", side_effect=RuntimeError("boom")): + _, (status, output, errors, outputs) = self.go() + self.assertEqual(status, "FAILURE") + self.assertIn("boom", errors) + self.assertIsNone(self.marker) + self.assertEqual(self.last["status"], "failure") + + def test_the_marker_of_a_newer_run_is_not_cleared(self): + def newer(server): + self.marker = {"job_id": 99, "kind": "patch"} + return record() + + self.engine[3] = newer + self.go() + self.assertEqual(self.marker, {"job_id": 99, "kind": "patch"}) + + +class RecordTests(Base): + def test_the_record_has_the_contracted_shape(self): + self.engine[2] = record("restart_pending") + self.go(restart=False) + rec = self.last + self.assertEqual(sorted(rec), ["at", "by", "counts", "job_id", "message", "restart_if_needed", "status"]) + self.assertEqual((rec["by"], rec["job_id"], rec["status"], rec["restart_if_needed"]), + ("alice", 11, "warning", False)) + self.assertEqual(rec["counts"], {"updated": 2, "no_updates": 0, "restart_pending": 1, "failed": 0, "skipped": 0}) + self.assertRegex(rec["at"], r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$") + self.assertLessEqual(len(rec["message"]), 300) + self.assertEqual(len(self.record_writes), 1) + + def test_a_success_is_recorded_as_success(self): + self.go() + self.assertEqual(self.last["status"], "success") + self.assertEqual(self.last["counts"]["updated"], 3) + + def test_a_record_that_cannot_be_written_does_not_end_the_run(self): + with mock.patch.object(store, "set_resource_patch", side_effect=store.StoreError("disk")): + _, (status, output, errors, outputs) = self.go() + self.assertEqual(status, "SUCCESS") + self.assertIsNone(self.marker) + + def test_the_output_dict_is_json_ready(self): + _, (status, output, errors, outputs) = self.go() + json.dumps(outputs) + + +# ---------------------------------------------------------------- start_job +class StartJobTests(Base): + def setUp(self): + super().setUp() + self.hook_calls = [] + self.created = types.SimpleNamespace(id=21, label="", save=lambda **k: None) + self.linked = [] + outer = self + + class FakeHook: + def run_as_job(self, **kw): + outer.hook_calls.append(kw) + return [outer.created] + + patcher = mock.patch.object(hooks, "resource_patch_hook", lambda: FakeHook()) + patcher.start() + self.addCleanup(patcher.stop) + self.resource = types.SimpleNamespace(id=RESOURCE_ID, name="Web tier", + jobs=types.SimpleNamespace(add=self.linked.append)) + self.owner = types.SimpleNamespace(id=OWNER_ID) + + def test_it_starts_the_hook_and_labels_and_links_the_job(self): + job = rsrc.start_job(self.owner, self.resource, restart_if_needed="false", parent_job="p") + self.assertIs(job, self.created) + self.assertEqual(self.hook_calls, [{"owner": self.owner, "resources": [self.resource], "parent_job": "p", + "context": {"restart_if_needed": False}}]) + self.assertEqual(job.label, "Install updates: Web tier") + self.assertEqual(self.linked, [job]) + + def test_the_restart_flag_defaults_to_true(self): + rsrc.start_job(self.owner, self.resource) + self.assertIs(self.hook_calls[0]["context"]["restart_if_needed"], True) + + def test_patching_off_refuses(self): + self.settings["patching"] = False + refusal = rsrc.start_job(self.owner, self.resource) + self.assertIsInstance(refusal, jobs.Refusal) + self.assertEqual((refusal.message, refusal.status), (patch.PATCHING_OFF, 403)) + self.assertEqual(self.hook_calls, []) + + def test_a_live_run_refuses_with_409(self): + self.live(77, kind="scan") + refusal = rsrc.start_job(self.owner, self.resource) + self.assertEqual((refusal.message, refusal.status), ("Job 77 is already running on this resource.", 409)) + self.assertEqual(self.hook_calls, []) + + def test_a_stale_marker_does_not_refuse(self): + self.marker = {"job_id": 5, "kind": "patch"} + self.assertIs(rsrc.start_job(self.owner, self.resource), self.created) + + def test_a_hook_that_creates_nothing_is_a_500(self): + hook = types.SimpleNamespace(run_as_job=lambda **k: []) + with mock.patch.object(hooks, "resource_patch_hook", lambda: hook): + refusal = rsrc.start_job(self.owner, self.resource) + self.assertEqual(refusal.status, 500) + + def test_an_unreadable_marker_is_a_500(self): + with mock.patch.object(store, "read_resource_run", side_effect=store.StoreError("bad")): + refusal = rsrc.start_job(self.owner, self.resource) + self.assertEqual((refusal.message, refusal.status), (fleet.RESOURCE_STATE_ERROR, 500)) + + def test_a_label_that_cannot_be_saved_still_returns_the_job(self): + def broken(**kw): + raise RuntimeError("db") + + self.created.save = broken + self.assertIs(rsrc.start_job(self.owner, self.resource), self.created) + + +# ---------------------------------------------------------------- the offer and the condition +class OfferTests(Base): + def setUp(self): + super().setUp() + self.resource = types.SimpleNamespace(id=RESOURCE_ID) + self.profile = types.SimpleNamespace(id=OWNER_ID) + + def test_patchable_ids_keeps_the_order_and_the_rules(self): + self.no_view.add(1) + self.no_patch.add(3) + self.servers.append(make_server(4)) + self.codes[4] = "powered_off" + self.assertEqual(rsrc.patchable_ids(self.profile, self.resource, "linux"), [2]) + + def test_patchable_ids_lists_every_server_that_passes(self): + self.assertEqual(rsrc.patchable_ids(self.profile, self.resource, "linux", problems={}), [1, 2, 3]) + + def test_nothing_viewable_is_nothing(self): + self.no_view.update({1, 2, 3}) + self.assertEqual(rsrc.patchable_ids(self.profile, self.resource, "linux"), []) + self.assertIs(rsrc.any_patchable(self.profile, self.resource, "linux"), False) + + def test_any_patchable_is_true_with_one_and_never_raises(self): + self.assertIs(rsrc.any_patchable(self.profile, self.resource, "linux"), True) + with mock.patch.object(fleet, "resource_servers", side_effect=RuntimeError("db")): + self.assertIs(rsrc.any_patchable(self.profile, self.resource, "linux"), False) + + def test_any_patchable_is_false_when_no_server_passes(self): + for server in self.servers: + self.codes[server.id] = "unassigned" + self.assertIs(rsrc.any_patchable(self.profile, self.resource, "linux"), False) + + +class ConditionTests(Base): + def resource(self, items): + queryset = FakeQuerySet(items) + return types.SimpleNamespace(id=1, server_set=queryset), queryset + + def test_one_exists_query_over_live_supported_servers_outside_unassigned_groups(self): + resource, queryset = self.resource([1]) + group = types.SimpleNamespace(unassigned=types.SimpleNamespace(ids=lambda: [5, 6])) + with mock.patch.object(rsrc, "Group", group), \ + mock.patch.object(fleet, "supported_q", return_value="SUPPORTED"): + self.assertIs(rsrc.has_candidates(resource), True) + self.assertEqual(queryset.calls, [("exclude", (), {"status": "HISTORICAL"}), ("filter", ("SUPPORTED",), {}), + ("exclude", (), {"group__in": [5, 6]})]) + + def test_no_server_is_no_candidate(self): + resource, queryset = self.resource([]) + group = types.SimpleNamespace(unassigned=types.SimpleNamespace(ids=lambda: [])) + with mock.patch.object(rsrc, "Group", group), \ + mock.patch.object(fleet, "supported_q", return_value="SUPPORTED"): + self.assertIs(rsrc.has_candidates(resource), False) + self.assertEqual(len(queryset.calls), 2) + + def test_an_error_is_false(self): + resource = types.SimpleNamespace(id=1, server_set=None) + self.assertIs(rsrc.has_candidates(resource), False) + + def should_display(self): + namespace = {} + path = os.path.join(PKG_DIR, "vuln_resource_patch_condition.py") + with open(path, encoding="utf-8") as handle: + exec(compile(handle.read(), path, "exec"), namespace) + return namespace["should_display"] + + def modules(self, has_candidates): + package = types.ModuleType(PACKAGE) + if has_candidates is not None: + package.vuln_patch_resource = types.SimpleNamespace(has_candidates=has_candidates) + return {"xui": types.ModuleType("xui"), PACKAGE: package} + + def test_the_condition_file_asks_has_candidates(self): + seen = [] + should_display = self.should_display() + resource = object() + with mock.patch.dict(sys.modules, self.modules(lambda r: seen.append(r) or True)): + self.assertIs(should_display(resource), True) + self.assertIs(should_display(resource, request=None), True) + self.assertEqual(seen, [resource, resource]) + with mock.patch.dict(sys.modules, self.modules(lambda r: False)): + self.assertIs(should_display(resource), False) + + def test_the_condition_file_fails_closed(self): + should_display = self.should_display() + + def boom(resource): + raise RuntimeError("db") + + with mock.patch.dict(sys.modules, self.modules(boom)): + self.assertIs(should_display(object()), False) + with mock.patch.dict(sys.modules, self.modules(None)): + self.assertIs(should_display(object()), False) + + +# ---------------------------------------------------------------- the files +class ShimTests(unittest.TestCase): + def read(self, name): + with open(os.path.join(PKG_DIR, name), "rb") as handle: + raw = handle.read() + raw.decode("ascii") + self.assertNotIn(b"\n", raw.replace(b"\r\n", b""), name) + return raw.decode("ascii") + + def test_the_shim_has_exactly_the_one_token_line_the_patch_shim_has(self): + token = 'RESTART_TOKEN = """' + OPEN + " restart_if_needed " + CLOSE + '"""' + text = self.read("vuln_resource_patch_job.py") + self.assertEqual(text.count(token), 1) + self.assertEqual(self.read("vuln_patch_job.py").count(token), 1) + rest = text.replace(token, "") + self.assertNotIn(OPEN, rest) + self.assertNotIn(CLOSE, rest) + + def test_the_other_new_files_have_no_double_braces(self): + for name in ("vuln_resource_patch_condition.py", "vuln_patch_resource.py"): + text = self.read(name) + self.assertNotIn(OPEN, text, name) + self.assertNotIn(CLOSE, text, name) + + def test_the_shim_lists_its_modules_in_dependency_order(self): + text = self.read("vuln_resource_patch_job.py") + namespace = {} + exec(compile(text, "shim", "exec"), namespace) + modules = [name.rsplit(".", 1)[1] for name in namespace["MODULES"]] + self.assertEqual(modules[-3:], ["vuln_wintask", "vuln_patch", "vuln_patch_resource"]) + for earlier, later in (("vuln_store", "vuln_hooks"), ("vuln_jobs", "vuln_fleet"), ("vuln_fleet", "vuln_patch")): + self.assertLess(modules.index(earlier), modules.index(later)) + patch_shim = {} + exec(compile(self.read("vuln_patch_job.py"), "shim", "exec"), patch_shim) + self.assertEqual(list(namespace["MODULES"][:-1]), list(patch_shim["MODULES"])) + + def test_run_reloads_the_modules_and_hands_over(self): + namespace = {} + exec(compile(self.read("vuln_resource_patch_job.py"), "shim", "exec"), namespace) + reloaded = [] + handed = [] + + def run_resource_patch(job, **kw): + handed.append((job, kw)) + return "SUCCESS", "", "", {} + + fake = types.SimpleNamespace(run_resource_patch=run_resource_patch) + importer = namespace["importlib"] + with mock.patch.object(importer, "import_module", side_effect=lambda name: fake), \ + mock.patch.object(importer, "reload", side_effect=lambda module: reloaded.append(module)): + result = namespace["run"]("JOB", restart_if_needed=True, resources=["r"]) + self.assertEqual(result, ("SUCCESS", "", "", {})) + self.assertEqual(len(reloaded), len(namespace["MODULES"])) + self.assertEqual(handed, [("JOB", {"restart_if_needed": True, "resources": ["r"]})]) + + def test_the_new_python_files_are_ascii_with_crlf(self): + for name in ("vuln_patch_resource.py", "vuln_resource_patch_job.py", "vuln_resource_patch_condition.py"): + self.assertTrue(self.read(name).endswith("\r\n"), name) + self.assertTrue(re.search(r"\r\n", self.read(name))) + + +if __name__ == "__main__": + unittest.main() diff --git a/extensions/XUI-wqrj0e3p/tests/test_vuln_patch_resource_hooks.py b/extensions/XUI-wqrj0e3p/tests/test_vuln_patch_resource_hooks.py new file mode 100644 index 00000000..0a6f7a8f --- /dev/null +++ b/extensions/XUI-wqrj0e3p/tests/test_vuln_patch_resource_hooks.py @@ -0,0 +1,538 @@ +""" +Checks for the Install Updates on All Servers wiring of the Vulnerabilities XUI (vuln_hooks.py +apply_patching_setting, _apply_resource_action, resource_patch_button, resource_patch_action_state, +server_patch_permitted; vuln_api.install_updates_on_resource) without CloudBolt. It reuses the stubs and the +in-memory ORM of test_vuln_patch_hooks.py and adds a fake ResourceAction. + + python -B -m unittest extensions/XUI-wqrj0e3p/tests/test_vuln_patch_resource_hooks.py +""" +import contextlib +import importlib.util +import itertools +import os +import sys +import types +import unittest +from unittest import mock + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import test_vuln_patch_hooks as base # noqa: E402 + +hooks, store, PACKAGE, SOURCE = base.hooks, base.store, base.PACKAGE, base.SOURCE +_module = base._module + + +class World(base.World): + """The fake database of test_vuln_patch_hooks.py plus ResourceAction.""" + + def __init__(self, make_token_input=True): + super().__init__(make_token_input) + self.resource_actions = [] + self.resource_permitted = True + self.listed = [] + world = self + + class RAction: + def __init__(self, **kw): + self.requires_approval = False + self.auto_submit_order = False + self.roles = [] + self.blueprints = [] + self.list_view_visible = True + self.pk = next(world.ids) + self.mapping_rows = [] + self.input_mappings = base.Manager(self.mapping_rows) + self.__dict__.update(kw) + + def update_input_mappings(self): + world.calls.append(("raction.update_input_mappings",)) + for row in self.hook.input_rows: + if not self.input_mappings.filter(hook_input=row): + self.mapping_rows.append(_Mapping(row, world)) + + def save(self): + world.calls.append(("raction.save", self.enabled)) + + class ResourceAction: + objects = types.SimpleNamespace( + filter=lambda **kw: base.Rows(a for a in world.resource_actions + if all(getattr(a, k) == v for k, v in kw.items()))) + + def create_action(**kw): + row = RAction(**kw) + world.resource_actions.append(row) + world.calls.append(("raction.create", dict(kw))) + return row + + ResourceAction.objects.create = create_action + self.ResourceAction = ResourceAction + + @contextlib.contextmanager + def installed(self): + cb = _module("cbhooks.models", CloudBoltHook=self.Hook, HookInput=self.HookInput, + ServerAction=self.ServerAction, ResourceAction=self.ResourceAction) + orders = _module("orders.models", CustomFieldValue=self.CustomFieldValue) + perms = _module("utilities.permissions", + server_action_permitted=lambda profile, server, action: self.permitted, + resource_action_permitted=lambda profile, resource, action: self.resource_permitted) + package = _module(PACKAGE, vuln_store=store) + patches = {"cbhooks.models": cb, "orders.models": orders, "utilities.permissions": perms, + PACKAGE: package, PACKAGE + ".vuln_store": store} + with mock.patch.dict(sys.modules, patches), mock.patch.object(hooks, "CloudBoltHook", self.Hook): + yield self + + +class _Mapping: + def __init__(self, hook_input, world): + self.hook_input = hook_input + self.default_value = None + self.world = world + + def save(self): + self.world.calls.append(("mapping.save", self.default_value.value if self.default_value else None)) + + +def resource(actions=None): + """A fake resource whose available_actions returns what the test set.""" + holder = types.SimpleNamespace(id=5, name="web tier", group=object(), owner=None) + holder.available_actions = lambda request=None: list(holder.listed) + holder.listed = actions or [] + return holder + + +class ApplyResourceActionTests(unittest.TestCase): + def test_off_with_no_hook_is_a_no_op(self): + world = World() + with world.installed(): + hooks.apply_patching_setting(False) + self.assertEqual(world.calls, []) + + def test_first_enable_makes_the_resource_half_once(self): + world = World() + with world.installed(): + hooks.apply_patching_setting(True) + names = [h.name for h in world.hooks] + self.assertEqual(names, [hooks.PATCH_NAME, hooks.CONDITION_NAME, hooks.RESOURCE_PATCH_NAME, + hooks.RESOURCE_CONDITION_NAME]) + self.assertEqual(len(world.actions), 1) + self.assertEqual(len(world.resource_actions), 1) + action = world.resource_actions[0] + plugin, condition = world.hooks[2], world.hooks[3] + self.assertIs(action.hook, plugin) + self.assertIs(action.condition, condition) + self.assertTrue(plugin.module_file.endswith("vuln_resource_patch_job.py")) + self.assertTrue(condition.module_file.endswith("vuln_resource_patch_condition.py")) + self.assertEqual(action.label, "Install Updates on All Servers") + self.assertIs(action.enabled, True) + self.assertIs(action.list_view_visible, False) + self.assertIs(action.is_synchronous, False) + self.assertEqual(action.extra_classes, "fas fa-download") + self.assertEqual(action.blueprints, []) + self.assertNotIn("blueprints", [c for c in world.calls if c[0] == "raction.create"][0][1]) + # One input only, turned into a checkbox, and one mapping with the default True. + self.assertEqual(len(plugin.input_rows), 1) + field = plugin.input_rows[0] + self.assertEqual(field.name, "restart_if_needed_a{}".format(plugin.id)) + self.assertEqual((field.type, field.required, field.hide_if_default_value), ("BOOL", False, False)) + self.assertEqual(len(action.mapping_rows), 1) + self.assertIs(action.mapping_rows[0].default_value.value, True) + self.assertIs(action.mapping_rows[0].default_value.field, field) + self.assertEqual(world.count("mapping.save"), 2) # one per action, none on re-enable + + def test_second_enable_only_sets_enabled(self): + world = World() + with world.installed(): + hooks.apply_patching_setting(True) + world.calls.clear() + hooks.apply_patching_setting(True) + self.assertEqual(world.calls, []) + hooks.apply_patching_setting(False) + self.assertEqual(sorted(world.calls), [("action.save", False), ("raction.save", False)]) + world.calls.clear() + hooks.apply_patching_setting(False) + self.assertEqual(world.calls, []) + hooks.apply_patching_setting(True) + self.assertEqual(sorted(world.calls), [("action.save", True), ("raction.save", True)]) + self.assertEqual((len(world.actions), len(world.resource_actions), len(world.hooks)), (1, 1, 4)) + + def test_admin_owned_flags_survive_off_and_on(self): + world = World() + with world.installed(): + hooks.apply_patching_setting(True) + action = world.resource_actions[0] + action.requires_approval = True + action.auto_submit_order = True + action.label = "Patch tier" + action.roles = ["ops"] + action.list_view_visible = True + action.condition = "admin's own" + action.mapping_rows[0].default_value.value = False + hooks.apply_patching_setting(False) + hooks.apply_patching_setting(True) + self.assertIs(action.requires_approval, True) + self.assertIs(action.auto_submit_order, True) + self.assertEqual(action.label, "Patch tier") + self.assertEqual(action.roles, ["ops"]) + self.assertIs(action.list_view_visible, True) + self.assertEqual(action.condition, "admin's own") + self.assertIs(action.mapping_rows[0].default_value.value, False) + self.assertEqual(world.count("mapping.save"), 2) # one per action, none on re-enable + self.assertEqual(world.count("raction.create"), 1) + + def test_appliance_with_the_server_action_gets_only_the_resource_action(self): + world = World() + with world.installed(): + hooks._apply_server_action(True) + server_action = world.actions[0] + world.calls.clear() + hooks.apply_patching_setting(True) + self.assertEqual(world.count("action.create"), 0) + self.assertEqual(world.count("raction.create"), 1) + self.assertEqual(world.count("action.save"), 0) + self.assertIs(server_action.enabled, True) + self.assertEqual(len(world.actions), 1) + + def test_create_only_keeps_a_switched_off_action_off_and_makes_the_missing_one(self): + world = World() + with world.installed(): + hooks._apply_server_action(True) + world.actions[0].enabled = False + world.calls.clear() + hooks.apply_patching_setting(True, create_only=True) + self.assertIs(world.actions[0].enabled, False) + self.assertEqual(world.count("action.save"), 0) + self.assertEqual(len(world.resource_actions), 1) + world.resource_actions[0].enabled = False + world.calls.clear() + hooks.apply_patching_setting(True, create_only=True) + self.assertEqual(world.calls, []) + self.assertIs(world.resource_actions[0].enabled, False) + hooks.apply_patching_setting(True) + self.assertIs(world.resource_actions[0].enabled, True) + self.assertIs(world.actions[0].enabled, True) + + def test_a_failing_half_does_not_hide_the_other(self): + world = World() + with world.installed(): + world.ResourceAction.objects.create = mock.Mock(side_effect=ValueError("boom")) + with self.assertRaises(RuntimeError) as caught: + hooks.apply_patching_setting(True) + self.assertIn("resource", str(caught.exception)) + self.assertNotIn("server and", str(caught.exception)) + self.assertEqual(len(world.actions), 1) + self.assertEqual(world.resource_actions, []) + + world = World() + with world.installed(): + world.ServerAction.objects.create = mock.Mock(side_effect=ValueError("boom")) + with self.assertRaises(RuntimeError) as caught: + hooks.apply_patching_setting(True) + self.assertIn("server", str(caught.exception)) + self.assertEqual(world.actions, []) + self.assertEqual(len(world.resource_actions), 1) + + def test_both_failing_says_both(self): + world = World() + with world.installed(): + world.ServerAction.objects.create = mock.Mock(side_effect=ValueError("boom")) + world.ResourceAction.objects.create = mock.Mock(side_effect=ValueError("boom")) + with self.assertRaises(RuntimeError) as caught: + hooks.apply_patching_setting(True) + self.assertIn("server and resource", str(caught.exception)) + + def test_an_action_made_meanwhile_is_not_doubled(self): + world = World() + with world.installed(): + hooks.apply_patching_setting(True) + rival = world.resource_actions[0] + world.resource_actions.clear() + real = hooks.resource_patch_actions + seen = [] + + def racing(hook): + seen.append(1) + if len(seen) == 2: + world.resource_actions.append(rival) + return real(hook) + + world.calls.clear() + with mock.patch.object(hooks, "resource_patch_actions", racing): + hooks.apply_patching_setting(True, create_only=True) + self.assertEqual(len(world.resource_actions), 1) + self.assertEqual(world.count("raction.create"), 0) + + def test_no_os_families_and_no_blueprints_are_touched(self): + world = World() + with world.installed(): + hooks.apply_patching_setting(True) + hooks.apply_patching_setting(False) + hooks.apply_patching_setting(True) + text = " ".join(str(c) for c in world.calls) + self.assertNotIn("os_famil", text) + self.assertNotIn("blueprints", text) + + def test_state_reads_only(self): + world = World() + empty = {"exists": False, "enabled": False, "action_id": None} + with world.installed(): + self.assertEqual(hooks.resource_patch_action_state(), empty) + self.assertEqual(world.calls, []) + hooks.apply_patching_setting(True) + self.assertEqual(hooks.resource_patch_action_state(), + {"exists": True, "enabled": True, "action_id": world.resource_actions[0].pk}) + hooks.apply_patching_setting(False) + self.assertIs(hooks.resource_patch_action_state()["enabled"], False) + with mock.patch.object(hooks, "CloudBoltHook", mock.Mock(objects=mock.Mock(filter=mock.Mock( + side_effect=RuntimeError("db"))))): + self.assertEqual(hooks.resource_patch_action_state(), empty) + + def test_names_fit_core_and_files_exist(self): + for name in (hooks.RESOURCE_PATCH_NAME, hooks.RESOURCE_CONDITION_NAME): + self.assertLessEqual(len(name), 255) + self.assertEqual(hooks.RESOURCE_ACTION_LABEL, "Install Updates on All Servers") + self.assertEqual(len({hooks.PATCH_NAME, hooks.CONDITION_NAME, hooks.RESOURCE_PATCH_NAME, + hooks.RESOURCE_CONDITION_NAME}), 4) + for name in (hooks.RESOURCE_PATCH_FILE, hooks.RESOURCE_CONDITION_FILE): + self.assertTrue(name.startswith("vuln_") and name.endswith(".py")) + + +class ResourceButtonTests(unittest.TestCase): + def setUp(self): + self.world = World() + with self.world.installed(): + hooks.apply_patching_setting(True) + self.action = self.world.resource_actions[0] + self.settings = {"patching": True} + patcher = mock.patch.object(store, "get_settings", lambda: self.settings) + patcher.start() + self.addCleanup(patcher.stop) + self.listed = [{"action": self.action, "url": "/resource_actions/5/run_action/{}/".format(self.action.pk), + "label": "x", "extra_classes": ""}] + + def button(self): + with self.world.installed(): + return hooks.resource_patch_button(resource(self.listed), object(), None) + + def test_shows_when_everything_allows_it(self): + self.assertEqual(self.button(), {"url": "/resource_actions/5/run_action/{}/".format(self.action.pk), + "label": "Install Updates on All Servers", "action_id": self.action.pk}) + + def test_setting_off(self): + self.settings = {"patching": False} + self.assertIsNone(self.button()) + + def test_action_disabled(self): + self.action.enabled = False + self.assertIsNone(self.button()) + + def test_core_does_not_list_it(self): + self.listed = [{"action": types.SimpleNamespace(pk=99), "url": "/x/"}] + self.assertIsNone(self.button()) + self.listed = [] + self.assertIsNone(self.button()) + + def test_permission_denied(self): + self.world.resource_permitted = False + self.assertIsNone(self.button()) + + def test_a_new_tab_action_has_no_dialog(self): + self.listed[0]["not_dialog"] = True + self.assertIsNone(self.button()) + + def test_never_raises(self): + self.listed = "not a list" + self.assertIsNone(self.button()) + with mock.patch.object(hooks, "CloudBoltHook", None): + self.assertIsNone(hooks.resource_patch_button(resource(), object())) + + +class ServerPatchPermittedTests(unittest.TestCase): + def test_follows_the_enabled_server_action(self): + world = World() + with world.installed(): + self.assertIs(hooks.server_patch_permitted(object(), base.server()), False) + hooks.apply_patching_setting(True) + self.assertIs(hooks.server_patch_permitted(object(), base.server()), True) + world.permitted = False + self.assertIs(hooks.server_patch_permitted(object(), base.server()), False) + world.permitted = True + hooks.apply_patching_setting(False) + self.assertIs(hooks.server_patch_permitted(object(), base.server()), False) + + def test_never_raises(self): + with mock.patch.object(hooks, "CloudBoltHook", None): + self.assertIs(hooks.server_patch_permitted(object(), base.server()), False) + + +# ---------------------------------------------------------------- vuln_api.install_updates_on_resource +class FakeJob: + def __init__(self, id=11, status="SUCCESS", errors=""): + self.id, self.status, self.errors = id, status, errors + self.waited = None + self.ends = True + + def wait_for_completion(self, timeout=None): + self.waited = timeout + if not self.ends: + from utilities.exceptions import TimeoutException + raise TimeoutException() + return self + + +class Refusal: + id = None + + def __init__(self, message): + self.message = message + + +def _load_api(started, record, ids, calls): + class Timeout(Exception): + pass + + fleet = _module(PACKAGE + ".vuln_fleet", _started_id=lambda s: getattr(s, "id", None), + default_base_url=lambda: "") + jobs = _module(PACKAGE + ".vuln_jobs", MESSAGE_LEN=300, clean=lambda text, limit: text[:limit]) + patch = _module(PACKAGE + ".vuln_patch", DEFAULT_PATCH_TIMEOUT_MIN=90, DEFAULT_RESTART_WAIT_MIN=60, + _minutes=lambda cfg, key, default: cfg.get(key, default), _summary=lambda i: None) + + def start_job(owner, res, restart_if_needed=True, parent_job=None): + calls.append(("start_job", owner, res, restart_if_needed, parent_job)) + return started + + def patchable_ids(profile, res, visibility, problems=None): + calls.append(("patchable_ids", visibility)) + if isinstance(ids, Exception): + raise ids + return ids + + patch_resource = _module(PACKAGE + ".vuln_patch_resource", start_job=start_job, patchable_ids=patchable_ids) + fake_store = _module(PACKAGE + ".vuln_store", + get_settings=lambda: {"visibility": "all", "scan_timeout_min": 30, "patch_timeout_min": 90, + "restart_wait_min": 60}, + read_resource_patch=lambda rid: record, read_state=lambda i: {}, + job_settings=lambda: {"timeout_min": 30}) + package = _module(PACKAGE, __path__=[SOURCE], vuln_fleet=fleet, vuln_jobs=jobs, vuln_patch=patch, + vuln_patch_resource=patch_resource, vuln_store=fake_store) + patches = {PACKAGE: package, PACKAGE + ".vuln_fleet": fleet, PACKAGE + ".vuln_jobs": jobs, + PACKAGE + ".vuln_patch": patch, PACKAGE + ".vuln_patch_resource": patch_resource, + PACKAGE + ".vuln_store": fake_store, + "utilities.logger": _module("utilities.logger", ThreadLogger=base.FakeLogger), + "utilities.exceptions": _module("utilities.exceptions", TimeoutException=Timeout)} + patcher = mock.patch.dict(sys.modules, patches) + patcher.start() + path = os.path.join(SOURCE, "vuln_api.py") + spec = importlib.util.spec_from_file_location(PACKAGE + ".vuln_api", path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module, patcher + + +class InstallOnResourceTests(unittest.TestCase): + def run_api(self, started=None, record=None, ids=(1, 2), **kw): + calls = [] + started = started or FakeJob() + api, patcher = _load_api(started, record, list(ids) if not isinstance(ids, Exception) else ids, calls) + self.addCleanup(patcher.stop) + self.calls = calls + return api.install_updates_on_resource(resource(), "owner", **kw), started + + def record(self, job_id=11, status="success", **counts): + full = {"updated": 0, "restart_pending": 0, "failed": 0, "skipped": 0} + full.update(counts) + return {"at": "x", "by": "u", "job_id": job_id, "status": status, "counts": full, + "restart_if_needed": True, "message": "2 updated."} + + def test_completed(self): + result, job = self.run_api(record=self.record(updated=2)) + self.assertEqual(result["status"], "completed") + self.assertEqual(result["counts"], {"updated": 2, "no_updates": 0, "restart_pending": 0, "failed": 0, "skipped": 0}) + self.assertIs(result["job"], job) + self.assertIn("web tier", result["message"]) + self.assertEqual(self.calls[0], ("start_job", "owner", self.calls[0][2], True, None)) + + def test_restart_pending_when_none_failed(self): + result, _ = self.run_api(record=self.record(status="warning", updated=1, restart_pending=1)) + self.assertEqual(result["status"], "restart_pending") + self.assertEqual(result["counts"]["restart_pending"], 1) + + def test_failed_wins_over_restart_pending(self): + result, _ = self.run_api(record=self.record(status="warning", updated=1, restart_pending=1, failed=1)) + self.assertEqual(result["status"], "failed") + result, _ = self.run_api(record=self.record(status="failure")) + self.assertEqual(result["status"], "failed") + self.assertIn("2 updated.", result["message"]) + + def test_refused(self): + result, job = self.run_api(started=Refusal("Job 4 is already installing updates on the servers of this " + "resource.")) + self.assertEqual(result["status"], "refused") + self.assertIsNone(result["counts"]) + self.assertIsNone(result["job"]) + self.assertIn("already installing", result["message"]) + + def test_timeout(self): + job = FakeJob() + job.ends = False + result, _ = self.run_api(started=job, record=None) + self.assertEqual(result["status"], "timeout") + self.assertIs(result["job"], job) + + def test_no_record_or_another_jobs_record_is_a_failure(self): + result, _ = self.run_api(record=None) + self.assertEqual(result["status"], "failed") + self.assertIn("recorded no result", result["message"]) + result, _ = self.run_api(record=self.record(job_id=3, updated=2)) + self.assertEqual(result["status"], "failed") + self.assertIsNone(result["counts"]) + + def test_default_wait_is_servers_times_worst_case_capped(self): + _, job = self.run_api(record=self.record(updated=2), ids=(1, 2)) + self.assertEqual(job.waited, 2 * (90 + 60 + 30) * 60 + 600) + _, job = self.run_api(record=self.record(updated=2), ids=range(50)) + self.assertEqual(job.waited, 27000) + _, job = self.run_api(record=self.record(updated=2), ids=()) + self.assertEqual(job.waited, (90 + 60 + 30) * 60 + 600) + _, job = self.run_api(record=self.record(updated=2), ids=RuntimeError("db")) + self.assertEqual(job.waited, (90 + 60 + 30) * 60 + 600) + _, job = self.run_api(record=self.record(updated=2), timeout=100) + self.assertEqual(job.waited, 100) + + def test_restart_flag_and_parent_job_pass_through(self): + self.run_api(record=self.record(updated=2), restart_if_needed=False, parent_job="parent") + self.assertEqual(self.calls[0][3:], (False, "parent")) + + def test_the_docstring_says_there_is_no_permission_check(self): + api, patcher = _load_api(FakeJob(), None, [], []) + self.addCleanup(patcher.stop) + self.assertIn("no permission check of its own", api.install_updates_on_resource.__doc__) + + +class NoTokenTests(unittest.TestCase): + def test_no_double_braces_in_the_files_this_package_writes(self): + for name in ("vuln_hooks.py", "vuln_api.py"): + with open(os.path.join(SOURCE, name), encoding="ascii") as handle: + text = handle.read() + self.assertNotIn(chr(123) * 2, text, name) + + def test_the_settings_page_names_the_resource_action(self): + path = os.path.join(SOURCE, "templates", "vuln_settings.html") + with open(path, encoding="ascii") as handle: + html = handle.read() + self.assertIn("Install Updates on All Servers", html) + self.assertIn("resource_patch_action.exists", html) + self.assertIn("resource_patch_action.enabled", html) + + def test_the_new_files_are_in_the_package(self): + import json + + path = os.path.join(os.path.dirname(HERE), "XUI-wqrj0e3p_metadata.json") + with open(path, encoding="utf-8") as handle: + contents = json.load(handle)["package_contents"] + for name in ("vuln_patch_resource.py", "vuln_resource_patch_job.py", "vuln_resource_patch_condition.py"): + self.assertEqual(contents.count(name), 1, name) + + +if __name__ == "__main__": + unittest.main() diff --git a/extensions/XUI-wqrj0e3p/tests/test_vuln_patch_resource_store.py b/extensions/XUI-wqrj0e3p/tests/test_vuln_patch_resource_store.py new file mode 100644 index 00000000..075f8a96 --- /dev/null +++ b/extensions/XUI-wqrj0e3p/tests/test_vuln_patch_resource_store.py @@ -0,0 +1,294 @@ +""" +Checks for the storage and run-marker side of Install updates on all servers (vuln_store.py and +vuln_fleet.py) without CloudBolt: CloudBolt's modules are stubs. + + python -B -m unittest discover -s extensions/XUI-wqrj0e3p/tests -p "test_vuln_patch_resource_store.py" + +The stubs are in place only while this file imports the extension's modules, so another test file's +stubs are not disturbed. +""" +import contextlib +import importlib +import os +import sys +import tempfile +import types +import unittest +from unittest import mock + +HERE = os.path.dirname(os.path.abspath(__file__)) +EXT = os.path.dirname(HERE) +PACKAGE = "xui.io_cloudbolt_vulnerabilities" + + +class IntegrityError(Exception): + pass + + +class Http404(Exception): + pass + + +class FakeLogger: + def __init__(self, *a): + pass + + def __getattr__(self, name): + return lambda *a, **k: None + + +class FakeQ: + """Records the keyword of each Q and how they are joined.""" + + def __init__(self, **kw): + self.keys = sorted(kw) + + def __or__(self, other): + joined = FakeQ() + joined.keys = self.keys + other.keys + return joined + + +def _module(name, **attrs): + module = types.ModuleType(name) + module.__dict__.update(attrs) + return module + + +TMP = tempfile.mkdtemp(prefix="vuln-patch-store-test-") +STUBS = {} + + +def _stub(name, **attrs): + STUBS[name] = _module(name, **attrs) + return STUBS[name] + + +_stub("django") +_stub("django.conf", settings=types.SimpleNamespace(PROSERV_DIR=TMP, CLOUDBOLT_OS_USER="u", CLOUDBOLT_OS_GROUP="g")) +_stub("django.http", FileResponse=object, Http404=Http404, HttpResponse=object) +_stub("django.urls", reverse=lambda *a, **k: "/x/") +_stub("django.db", IntegrityError=IntegrityError, + transaction=types.SimpleNamespace(atomic=lambda: contextlib.nullcontext())) +_stub("django.db.models", Q=FakeQ) +_stub("cbhooks") +_stub("cbhooks.models", CloudBoltHook=object) +_stub("accounts") +_stub("accounts.models", Group=object, UserProfile=object) +_stub("infrastructure") +_stub("infrastructure.models", Server=object) +_stub("jobs") +_stub("jobs.models", Job=object) +_stub("portals") +_stub("portals.models") +_stub("utilities") +_stub("utilities.events", add_server_event=lambda *a, **k: None) +_stub("utilities.logger", ThreadLogger=FakeLogger) +_xui = _stub("xui") +_xui.__path__ = [EXT] + + +def _import_extension(): + """Import the extension's modules against the stubs, leaving sys.modules as it was found.""" + touched = [k for k in sys.modules if k == "xui" or k.startswith(PACKAGE) or k in STUBS] + saved = {k: sys.modules[k] for k in touched} + for key in touched: + del sys.modules[key] + sys.modules.update(STUBS) + try: + names = ("vuln_store", "vuln_match", "vuln_db", "vuln_tools", "vuln_repo", "vuln_hooks", "vuln_jobs", + "vuln_fleet") + return {name: importlib.import_module(PACKAGE + "." + name) for name in names} + finally: + for key in [k for k in sys.modules if k == "xui" or k.startswith(PACKAGE) or k in STUBS]: + del sys.modules[key] + sys.modules.update(saved) + + +MODS = _import_extension() +store, tools, hooks, jobs, fleet = (MODS[n] for n in ("vuln_store", "vuln_tools", "vuln_hooks", "vuln_jobs", + "vuln_fleet")) + + +class FakeQuery: + def __init__(self, rows): + self.rows = list(rows) + + def first(self): + return self.rows[0] if self.rows else None + + def __iter__(self): + return iter(self.rows) + + +class FakeJobTable: + """vuln_jobs.Job: the jobs the markers can name. A job that is not in the table is gone.""" + + def __init__(self): + self.live = {} + + def add(self, job_id, active=True, done=None, total=None, message=None): + progress = types.SimpleNamespace(message=message) + self.live[job_id] = types.SimpleNamespace( + id=job_id, is_active=lambda: active, tasks_done=done, total_tasks=total, + get_progress=lambda: (0, 0, progress), get_absolute_url=lambda: "/jobs/{}/".format(job_id)) + + def model(self): + table = self + + class Manager: + def filter(self, **kw): + found = table.live.get(kw.get("id")) + return FakeQuery([found] if found else []) + + return types.SimpleNamespace(objects=Manager()) + + +class Base(unittest.TestCase): + RESOURCE_ID = 5 + + def setUp(self): + self.root = tempfile.mkdtemp(prefix="vuln-patch-resource-") + self.table = FakeJobTable() + self.queued = [] + self.owner = types.SimpleNamespace(id=77, user=types.SimpleNamespace(is_active=True, username="alice")) + for patcher in (mock.patch.object(store, "RESOURCES_DIR", os.path.join(self.root, "resources")), + mock.patch.object(store, "own", lambda *a, **k: None), + mock.patch.object(jobs, "Job", self.table.model()), + mock.patch.object(tools, "status", return_value={"ready": True, "db": {"built": "b"}})): + patcher.start() + self.addCleanup(patcher.stop) + + def resource(self): + return types.SimpleNamespace(id=self.RESOURCE_ID, name="Web tier", + jobs=types.SimpleNamespace(add=lambda job: None)) + + def start_scan(self): + created = types.SimpleNamespace(id=90, label="", save=lambda **k: None) + hook = types.SimpleNamespace(run_as_job=lambda **kw: self.queued.append(kw) or [created]) + with mock.patch.object(hooks, "resource_scan_hook", lambda: hook): + return fleet.start_resource_scan(self.owner, self.resource(), [1, 2], "https://cb.example") + + +class MarkerKindTests(Base): + def test_a_patch_marker_round_trips_with_its_kind(self): + marker = {"job_id": 40, "started": "t", "requested_by": "alice", "server_ids": [1, 2], "kind": "patch"} + store.set_resource_run(5, marker) + self.assertEqual(store.read_resource_run(5), marker) + self.assertTrue(store.clear_resource_run(5, job_id=40)) + self.assertIsNone(store.read_resource_run(5)) + + def test_the_run_reports_kind_and_message(self): + store.set_resource_run(5, {"job_id": 40, "started": "t", "server_ids": [1, 2, 3], "kind": "patch"}) + self.table.add(40, done=1, total=3, message="Server 2 of 3: web-02: installing") + self.assertEqual(fleet.resource_run(5), {"job_id": 40, "job_url": "/jobs/40/", "started": "t", "done": 1, + "total": 3, "kind": "patch", + "message": "Server 2 of 3: web-02: installing"}) + + def test_a_marker_without_a_kind_is_a_scan(self): + store.set_resource_run(5, {"job_id": 40, "started": "t", "server_ids": [1]}) + self.table.add(40) + run = fleet.resource_run(5) + self.assertEqual((run["kind"], run["message"]), ("scan", "")) + + def test_a_stale_patch_marker_is_no_run(self): + store.set_resource_run(5, {"job_id": 40, "kind": "patch"}) + self.assertIsNone(fleet.resource_run(5)) # its job is gone + self.table.add(40, active=False) + self.assertIsNone(fleet.resource_run(5)) # its job has finished + + def test_another_resource_is_not_blocked(self): + store.set_resource_run(6, {"job_id": 40, "kind": "patch"}) + self.table.add(40) + self.assertIsNone(fleet.resource_run(5)) + self.assertIsNotNone(fleet.resource_run(6)) + + +class RefusalWordingTests(Base): + def test_a_scan_is_refused_while_a_scan_runs(self): + store.set_resource_run(5, {"job_id": 40}) + self.table.add(40) + refusal = self.start_scan() + self.assertEqual((refusal.status, refusal.message), ( + 409, "Job 40 is already scanning the servers of this resource.")) + self.assertEqual(self.queued, []) + + def test_a_scan_is_refused_while_updates_install(self): + store.set_resource_run(5, {"job_id": 40, "kind": "patch"}) + self.table.add(40) + refusal = self.start_scan() + self.assertEqual((refusal.status, refusal.message), ( + 409, "Job 40 is already installing updates on the servers of this resource.")) + self.assertEqual(self.queued, []) + + def test_a_scan_starts_when_the_patch_marker_is_stale(self): + store.set_resource_run(5, {"job_id": 40, "kind": "patch"}) + self.table.add(40, active=False) + self.assertEqual(self.start_scan().id, 90) + self.assertEqual(len(self.queued), 1) + + +class PatchRecordTests(Base): + RECORD = {"at": "t", "by": "alice", "job_id": 40, "status": "warning", + "counts": {"updated": 1, "restart_pending": 0, "failed": 1, "skipped": 2}, + "restart_if_needed": True, "message": "x"} + + def test_round_trip_and_replace(self): + self.assertIsNone(store.read_resource_patch(5)) + store.set_resource_patch("5", self.RECORD) + self.assertEqual(store.read_resource_patch(5), self.RECORD) + store.set_resource_patch(5, dict(self.RECORD, job_id=41)) + self.assertEqual(store.read_resource_patch(5)["job_id"], 41) + + def test_clear(self): + store.set_resource_patch(5, self.RECORD) + self.assertTrue(store.clear_resource_patch(5)) + self.assertIsNone(store.read_resource_patch(5)) + self.assertFalse(store.clear_resource_patch(5)) + + def test_the_record_and_the_marker_are_independent_files(self): + store.set_resource_patch(5, self.RECORD) + self.assertIsNone(store.read_resource_run(5)) + store.set_resource_run(5, {"job_id": 40, "kind": "patch"}) + store.clear_resource_run(5) + self.assertEqual(store.read_resource_patch(5), self.RECORD) + store.set_resource_run(5, {"job_id": 41}) + store.clear_resource_patch(5) + self.assertEqual(store.read_resource_run(5), {"job_id": 41}) + + def test_resources_are_independent(self): + store.set_resource_patch(5, self.RECORD) + self.assertIsNone(store.read_resource_patch(6)) + store.set_resource_patch(6, dict(self.RECORD, job_id=2)) + store.clear_resource_patch(5) + self.assertEqual(store.read_resource_patch(6)["job_id"], 2) + + def test_damaged_file_reads_as_none(self): + store.set_resource_patch(5, self.RECORD) + with open(store._resource_patch_path(5), "w") as handle: + handle.write("[1, 2") + self.assertIsNone(store.read_resource_patch(5)) + with open(store._resource_patch_path(5), "w") as handle: + handle.write("[1, 2]") + self.assertIsNone(store.read_resource_patch(5)) + + def test_ids_cannot_leave_the_resources_folder(self): + for call in (lambda: store.read_resource_patch("../5"), lambda: store.set_resource_patch("5/../../x", {}), + lambda: store.clear_resource_patch("x")): + with self.assertRaises(ValueError): + call() + path = store._resource_patch_path(5) + self.assertEqual(os.path.dirname(path), store.RESOURCES_DIR) + self.assertTrue(path.endswith("5.patch.json")) + + +class SupportedQTests(unittest.TestCase): + def test_linux_and_windows_at_three_levels(self): + with mock.patch.dict(sys.modules, STUBS): + q = fleet.supported_q() + self.assertEqual(sorted(q.keys), sorted([ + "os_family__name", "os_family__parent__name", "os_family__parent__parent__name"] * 2)) + + +if __name__ == "__main__": + unittest.main() diff --git a/extensions/XUI-wqrj0e3p/tests/test_vuln_patch_resource_views.py b/extensions/XUI-wqrj0e3p/tests/test_vuln_patch_resource_views.py new file mode 100644 index 00000000..e4b41e11 --- /dev/null +++ b/extensions/XUI-wqrj0e3p/tests/test_vuln_patch_resource_views.py @@ -0,0 +1,291 @@ +""" +Checks for the resource-wide Install updates part of the Vulnerabilities resource tab (views.vuln_resource_summary, +the settings view, vuln_resource_tab.html and the script in vuln_fleet_assets.html) without CloudBolt. The patch +pieces the views call (vuln_hooks.resource_patch_button, vuln_patch_resource, store.read_resource_patch) are +stubbed here. The template tests need Django itself and are skipped when it is not installed. + + python -B -m unittest discover -s extensions/XUI-wqrj0e3p/tests -p "test_*.py" +""" +import contextlib +import os +import re +import sys +import types +import unittest +from unittest import mock + +HERE = os.path.dirname(os.path.abspath(__file__)) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +import test_vuln_patch_panel as panel # noqa: E402 (imports views against stubs) + +views = panel.views +base = panel.base +HAVE_DJANGO = panel.HAVE_DJANGO +TEMPLATES = panel.TEMPLATES +AT = "2026-11-24T10:00:00Z" +URL = "/resource_actions/5/run_action/9/" +BUTTON = {"url": URL, "label": "Install Updates on All Servers", "action_id": 9} +RESOURCE = types.SimpleNamespace(id=5, name="web") +PROFILE = types.SimpleNamespace(is_cbadmin=False) +RUN = {"job_id": 3, "job_url": "/jobs/3/", "started": AT, "done": 1, "total": 4, "kind": "patch", + "message": "Server 2 of 4: web-02"} + + +def patch_record(**over): + data = {"at": AT, "by": "alice", "job_id": 41, "status": "success", + "counts": {"updated": 3, "restart_pending": 1, "failed": 0, "skipped": 2}, + "restart_if_needed": True, "message": ""} + data.update(over) + return data + + +def summary(run=None, ids=(1, 2), button=BUTTON, patchable=(1, 2), record=None, button_error=None, + patchable_error=None, method="GET", query=None): + """views.vuln_resource_summary with everything outside it replaced; returns (data, button mock, patchable mock).""" + button_mock = mock.Mock(return_value=button, side_effect=button_error) + module = types.ModuleType(base.PACKAGE + ".vuln_patch_resource") + module.any_patchable = mock.Mock(return_value=bool(patchable), side_effect=patchable_error) + package = types.ModuleType(base.PACKAGE) + package.__path__ = [] + package.vuln_patch_resource = module + request = types.SimpleNamespace(method=method, GET=query or {}) + with contextlib.ExitStack() as stack: + enter = stack.enter_context + enter(mock.patch.dict(sys.modules, {base.PACKAGE: package, base.PACKAGE + ".vuln_patch_resource": module})) + enter(mock.patch.object(views, "_resource_gate", return_value=(RESOURCE, PROFILE, list(ids)))) + enter(mock.patch.object(views, "_upgrade_store")) + enter(mock.patch.object(views.vuln_fleet, "resource_run", return_value=run)) + enter(mock.patch.object(views.vuln_fleet, "any_scannable", return_value=True)) + enter(mock.patch.object(views.vuln_db, "set_summary", return_value=None)) + enter(mock.patch.object(views.vuln_tools, "status", return_value={})) + enter(mock.patch.object(views.store, "get_settings", return_value={"visibility": "all"})) + enter(mock.patch.object(views.store, "read_resource_patch", return_value=record, create=True)) + enter(mock.patch.object(views, "reverse", lambda name, args=None, **k: "/%s/%s/" % (name, (args or [""])[0]))) + enter(mock.patch.object(views.vuln_hooks, "resource_patch_button", button_mock, create=True)) + response = views.vuln_resource_summary(request, 5) + return response.data, button_mock, module.any_patchable + + +class SummaryTests(unittest.TestCase): + def test_patch_offer(self): + data, button, patchable = summary() + self.assertEqual(data["patch"], {"offer": True, "url": URL, "label": BUTTON["label"]}) + self.assertEqual(button.call_args.args[0], RESOURCE) + patchable.assert_called_once() + self.assertEqual(patchable.call_args.args[:2], (PROFILE, RESOURCE)) + + def test_patch_is_null_while_a_run_is_live_and_nothing_is_asked(self): + data, button, patchable = summary(run=RUN, record=patch_record()) + self.assertIsNone(data["patch"]) + self.assertIsNone(data["patch_last"]) + self.assertEqual(data["run"], RUN) + button.assert_not_called() + patchable.assert_not_called() + + def test_patch_is_null_without_permission_or_with_the_setting_off(self): + data, _, patchable = summary(button=None) + self.assertIsNone(data["patch"]) + patchable.assert_not_called() + + def test_patch_is_null_when_the_button_has_no_site_path(self): + for url in ("", "https://evil.example/x"): + data, _, _ = summary(button={"url": url, "label": "x", "action_id": 1}) + self.assertIsNone(data["patch"]) + + def test_patch_is_null_without_patchable_servers(self): + data, _, _ = summary(patchable=()) + self.assertIsNone(data["patch"]) + + def test_patch_is_null_when_the_viewer_sees_no_servers(self): + data, button, _ = summary(ids=(), record=patch_record()) + self.assertIsNone(data["patch"]) + self.assertIsNone(data["patch_last"]) + button.assert_not_called() + + def test_a_failing_patch_piece_means_no_button_and_an_intact_answer(self): + for kwargs in ({"button_error": RuntimeError("boom")}, {"patchable_error": RuntimeError("boom")}): + data, _, _ = summary(**kwargs) + self.assertIsNone(data["patch"]) + self.assertIn("state", data) + self.assertIn("can_scan", data) + + def test_a_missing_patch_module_means_no_button(self): + request = types.SimpleNamespace(method="GET", GET={}) + with mock.patch.object(views.vuln_hooks, "resource_patch_button", return_value=BUTTON, create=True), \ + mock.patch.dict(sys.modules): + for key in [k for k in sys.modules if k.startswith(base.PACKAGE)]: + del sys.modules[key] + self.assertIsNone(views._resource_patch_offer(RESOURCE, PROFILE, request, "all")) + + def test_patch_last_shape_and_job_link(self): + data, _, _ = summary(record=patch_record()) + self.assertEqual(data["patch_last"], {"at": AT, "by": "alice", "status": "success", "updated": 3, + "restart_pending": 1, "failed": 0, "skipped": 2, "no_updates": 0, + "job_url": "/job_detail/41/"}) + + def test_patch_last_is_null_without_a_record_or_status_and_survives_bad_counts(self): + self.assertIsNone(summary(record=None)[0]["patch_last"]) + self.assertIsNone(summary(record={"at": AT})[0]["patch_last"]) + last = summary(record=patch_record(counts={"updated": "x", "failed": -2}, job_id=None))[0]["patch_last"] + self.assertEqual((last["updated"], last["failed"], last["job_url"]), (0, 0, "")) + + def test_run_one_stays_only_the_run(self): + data, button, patchable = summary(run=RUN, query={"run": "1"}) + self.assertEqual(data, {"run": RUN}) + button.assert_not_called() + patchable.assert_not_called() + + def test_run_kind_and_message_pass_through(self): + data, _, _ = summary(run=dict(RUN, kind="scan", message="x")) + self.assertEqual(data["run"]["kind"], "scan") + self.assertEqual(data["run"]["message"], "x") + + def test_only_get_is_allowed(self): + data, _, _ = summary(method="POST") + self.assertEqual(data, {"error": "Use GET."}) + + +class SettingsTests(unittest.TestCase): + OK = {"exists": True, "enabled": True, "action_id": 9} + MISSING = {"exists": False, "enabled": False, "action_id": None} + + def post(self, patching=True, was=True, server=OK, resource=OK, apply=None): + request = types.SimpleNamespace(method="POST", POST={"x": "1"}) + clean = {"patching": patching, "scan_on_provision": False} + if isinstance(resource, Exception): + resource_state = mock.Mock(side_effect=resource) + else: + resource_state = mock.Mock(return_value=resource) + apply = apply or mock.Mock() + with mock.patch.object(views.store, "validate_settings", return_value=(clean, {})), \ + mock.patch.object(views.store, "save_settings"), \ + mock.patch.object(views.store, "get_settings", return_value={"patching": was}), \ + mock.patch.object(views.vuln_hooks, "apply_provision_setting", create=True), \ + mock.patch.object(views.vuln_hooks, "apply_patching_setting", apply, create=True), \ + mock.patch.object(views.vuln_hooks, "patch_action_state", return_value=server, create=True), \ + mock.patch.object(views.vuln_hooks, "resource_patch_action_state", resource_state, create=True), \ + mock.patch.object(views.vuln_hooks, "ensure_schedules", return_value=[], create=True), \ + mock.patch.object(views, "_schedule_rows", return_value=[]), \ + mock.patch.object(views, "_scanner_context", return_value={}), \ + mock.patch.object(views, "_fleet_url", return_value=""), \ + mock.patch.object(views, "reverse", return_value="/setup/"): + return views.settings(request)[1], apply + + def test_a_missing_resource_action_is_created_when_the_setting_is_unchanged(self): + ctx, apply = self.post(resource=self.MISSING) + apply.assert_called_once_with(True, create_only=True) + self.assertEqual(ctx["warnings"], []) + + def test_a_changed_setting_applies_without_create_only(self): + _, apply = self.post(was=False) + apply.assert_called_once_with(True, create_only=False) + _, apply = self.post(patching=False, was=True) + apply.assert_called_once_with(False, create_only=False) + + def test_everything_present_leaves_it_alone(self): + _, apply = self.post() + apply.assert_not_called() + + def test_an_unreadable_resource_state_does_not_trigger_an_apply(self): + _, apply = self.post(resource=RuntimeError("boom")) + apply.assert_not_called() + + def test_off_never_creates(self): + _, apply = self.post(patching=False, was=False, resource=self.MISSING) + apply.assert_not_called() + + def test_the_resource_action_state_is_in_the_context(self): + ctx, _ = self.post() + self.assertEqual(ctx["resource_patch_action"], self.OK) + ctx, _ = self.post(resource=RuntimeError("boom"), was=False, patching=False) + self.assertEqual(ctx["resource_patch_action"], self.MISSING) + + def test_a_failure_names_the_action_that_did_not_follow(self): + boom = mock.Mock(side_effect=RuntimeError("one half failed")) + ctx, _ = self.post(was=False, resource=self.MISSING, apply=boom) + self.assertEqual(ctx["warnings"], [views.RESOURCE_PATCHING_ERROR]) + ctx, _ = self.post(was=False, server=self.MISSING, resource=self.OK, apply=boom) + self.assertEqual(ctx["warnings"], [views.PATCHING_ERROR]) + ctx, _ = self.post(was=False, server=self.MISSING, resource=self.MISSING, apply=boom) + self.assertEqual(ctx["warnings"], [views.PATCHING_ERROR, views.RESOURCE_PATCHING_ERROR]) + ctx, _ = self.post(was=False, apply=boom) + self.assertEqual(ctx["warnings"], [views.PATCHING_ERROR]) + self.assertTrue(ctx["saved"]) + + +def read(name): + with open(os.path.join(TEMPLATES, name), encoding="utf-8") as handle: + return handle.read() + + +class SourceTests(unittest.TestCase): + def test_the_tab_anchor_opens_the_dialog_and_has_no_act(self): + html = read("vuln_resource_tab.html") + anchors = re.findall(r"]*data-vuln-patch-all[^>]*>", html) + self.assertEqual(len(anchors), 1) + self.assertIn("open-dialog", anchors[0]) + self.assertIn("hidden", anchors[0]) + self.assertNotIn("data-vuln-act", anchors[0]) + self.assertLess(html.index('data-vuln-act="scan-all"'), html.index("