From 8126f5b261a77f63a6e4f3bccfdc138aedf10861 Mon Sep 17 00:00:00 2001 From: Matthew Stone Date: Wed, 18 Nov 2026 10:13:36 -0600 Subject: [PATCH 1/2] feat(72.3): patchbot fact schema version 2 and an exact security count Closes the module side of G-72.3-5b: class patchbot now delivers the version 2 patchbot fact instead of the v1 fact. - facts.d/patchbot.sh and facts.d/patchbot.ps1 are byte-identical copies of the development copy in the Puppet Stagehand Console repository (lab source commit d6af8a8f), proved with cmp. sha256 patchbot.sh daf7d4fb4ad702f2cbe55cc9d3c8dc58a6cb630dc69403a535389200633431f1 sha256 patchbot.ps1 fd934bbec566b876b93e9adc81c32c556e6e57688b6462ed7da291ecd593f333 - Fact: schema_version 2, a three-state reboot_status with a fixed reboot_status_reason, dnf status/check_error, repos, package_count and truncated, and a security count that is exact (one per pending update, matched by exact package name, never above available). - metadata.json version 0.3.0 (0.2.0 was never tagged); CHANGELOG and the README fact section describe the version 2 fact. The patch task is unchanged. Checked locally: dnf security smoke on a real AlmaLinux 8.9 userland and the EL7 yum smoke, both against this tree's facts.d; shellcheck; tasks/patch_test.sh; tools/supplychain/scan.sh (0 findings); gitleaks, tree and history. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01McuAWfE22TvftB9SGnvzTT --- CHANGELOG.md | 29 ++++ README.md | 63 +++++--- facts.d/patchbot.ps1 | 314 +++++++++++++++++++++++++++++----------- facts.d/patchbot.sh | 332 +++++++++++++++++++++++++++++++++++-------- metadata.json | 2 +- 5 files changed, 578 insertions(+), 162 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 30da3d8..2ccc881 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,34 @@ # Changelog +## [0.3.0] - 2026-11-18 + +0.2.0 was never tagged or released, and 0.3.0 is the first release that carries it: everything under 0.2.0 below ships in 0.3.0 +too. + +- **The `patchbot` fact is now schema version 2, on Linux and Windows.** The fact carries `schema_version: 2`. A reader written + for version 1 keeps working: `available`, `security`, `reboot_required` and `last_checked` mean what they always did, and + everything else is additive. +- **Three-state reboot answer.** `reboot_status` is always present and is `required`, `not_required` or `unknown`. `unknown` + means the node cannot tell, and it is never read as "no". `reboot_status_reason` is a fixed code saying why, never raw command + output. `reboot_required` is kept for version 1 readers and is true only when `reboot_status` is `required`. +- **How each platform decides.** apt reads the `/var/run/reboot-required` marker, and reports `unknown` when no marker exists and + nothing installed would ever write one. dnf runs `needs-restarting -r` and reads its exit code; a missing plugin is reported as + `unknown` (`plugin_missing`), not as "no reboot needed". yum uses the standalone `needs-restarting` the same way. Windows runs + four probes (Component Based Servicing, Windows Update, pending file renames, and System Center Configuration Manager when + present); any yes is `required`, and a probe that failed is never read as a no. +- **dnf reports when the update check could not run.** `status` is `ok`, or `check_failed` with a fixed `check_error` + (`metadata_unavailable` or `package_manager_error`), and the counts are then zero instead of looking like a clean node. +- **Package detail.** The fact lists `repos`, `package_count` and `truncated`. `packages[]` is capped by `PCM_PATCH_MAX_PACKAGES` + (default 500); only the list is capped, and `available`, `security` and `package_count` stay exact. +- **`security` is now an exact count of pending updates.** It used to count advisory rows, so a package named in several + advisories was counted several times and `security` could exceed `available`. It now counts each pending update that has a + security advisory once, matched by exact package name, so one package can no longer be flagged by another package's advisory + that merely starts with the same letters. +- The patch task (`tasks/patch.*`) is unchanged in this release. +- `facts.d/patchbot.sh` and `facts.d/patchbot.ps1` are byte-identical copies of the development copy kept in the Puppet Stagehand + Console repository. sha256: `patchbot.sh` `daf7d4fb4ad702f2cbe55cc9d3c8dc58a6cb630dc69403a535389200633431f1`, `patchbot.ps1` + `fd934bbec566b876b93e9adc81c32c556e6e57688b6462ed7da291ecd593f333`. + ## [0.2.0] - 2026-09-23 - **Breaking (external fact consumers):** `facts.d/patchbot.sh`'s apt, dnf, and yum diff --git a/README.md b/README.md index 25958ff..db8f39b 100644 --- a/README.md +++ b/README.md @@ -55,7 +55,7 @@ metadata; same parameters and same JSON output shape either way. | `console_url` | `Optional[String[1]]` | — | Server-injected; unused by the patch itself (posture reaches the console via the fact, not the task's own output). | | `ingest_token` | `Optional[String[1]]` | — | Server-injected; unused by the patch itself. | | `security_only` | `Boolean` | `false` | Apply only security updates when true; otherwise apply all available updates. Ignored when `patch_ids` is set. | -| `patch_ids` | `Optional[Array[String[1]]]` | — | Install only these specific ids, as reported in the fact's `patches[]` array (KB numbers on Windows, package names on Linux). Takes priority over `security_only`. | +| `patch_ids` | `Optional[Array[String[1]]]` | — | Install only these specific ids, as reported in the fact (KB numbers from `missing[].kbs` on Windows, package names from `packages[].name` on Linux). Takes priority over `security_only`. | | `reboot` | `Boolean` | `false` | Reboot the node afterward if a reboot is required. | On Linux, `patch_ids` requires `jq` on the target (only when actually used — @@ -64,40 +64,65 @@ every other path stays dependency-light). On Windows, no extra dependency: ## The `patchbot` fact schema +This module publishes **schema version 2** of the `patchbot` fact: the same keys, and the same reboot rule, as the fact the +console's own `stagehand` module ships. The full contract (every key and every reboot reason code) is kept with the Puppet Stagehand Console's own documentation, which +this repository does not link to. A fact without `schema_version` is version 1. + +A Linux fact (dnf): + ```json { "patchbot": { - "available": 4, + "schema_version": 2, + "status": "ok", + "available": 3, "security": 1, "reboot_required": false, - "last_checked": "2026-08-18T14:03:00Z", - "patches": [ - { "id": "KB5031354", "severity": "high", "security": true }, - { "id": "openssl", "severity": "high", "security": true }, - { "id": "some-lib.x86_64", "severity": "unknown", "security": false } - ] + "reboot_status": "not_required", + "reboot_status_reason": "needs_restarting", + "last_checked": "2026-11-17T14:03:00Z", + "manager": "dnf", + "repos": ["appstream", "baseos"], + "packages": [ + { "name": "openssl", "arch": "x86_64", "current": "1:3.2.2-2.el9", "available": "1:3.2.2-6.el9_5", "repo": "rhel-9-appstream", "security": true } + ], + "package_count": 3, + "truncated": false } } ``` | Field | Type | Meaning | |---|---|---| -| `available` | integer | Count of packages/updates with an available update. | -| `security` | integer | Subset of `available` that are security updates. | -| `reboot_required` | boolean | Whether a pending reboot has been flagged (`/var/run/reboot-required` or `needs-restarting -r` on Linux; the WUA `SystemInfo.RebootRequired` property on Windows). | +| `schema_version` | integer | Always `2`. | +| `available` | integer | Count of packages/updates with an available update. Exact even when the list is capped. | +| `security` | integer | How many pending updates have a security advisory. An update is counted once even when several advisories or builds name it, and it is matched by exact package name, so `security` is never more than `available`. | +| `reboot_status` | enum | `required`, `not_required` or `unknown`. `unknown` means this node cannot tell (the tool that reports it is missing or failed, or no supported package manager is present). It is never reported as `not_required`. | +| `reboot_status_reason` | string | A fixed code saying why (for example `marker_present`, `needs_restarting`, `plugin_missing`, `no_package_manager`; `pending_reboot_probe`, `probes_clear`, `probes_failed` on Windows). Never raw command output. | +| `reboot_required` | boolean | Kept for readers of version 1: true only when `reboot_status` is `required`. | | `last_checked` | string | ISO 8601 UTC timestamp of the last time this fact ran. | -| `patches[].id` | string | The identifier this entry round-trips into the task's `patch_ids` parameter. KB number (`KB5031354`) on Windows; bare package name (or `name.arch` on RHEL-family) on Linux. | -| `patches[].severity` | enum | `low` \| `medium` \| `high` \| `unknown` — the same severity scale `compliance.v1` uses. On Windows this is MSRC's rating (Critical/Important collapse to `high`, Moderate → `medium`, Low → `low`). On Linux it's an approximation: `high` if the package manager's security channel flags the update, `unknown` otherwise — Linux package managers don't expose per-package severity as cleanly as WUA does. | -| `patches[].security` | boolean | Whether this update is classified as a security update. | +| `manager` | string | `apt`, `dnf`, `yum` or `wua`; empty on a Linux node with no supported package manager. | +| `repos` | array | Linux: the configured suites or repository ids. | +| `packages[]` | array | Linux: `name`, `arch`, `current` (installed version), `available`, `repo`, `security`. Capped (see below). | +| `package_count`, `truncated` | integer, boolean | The full count, and whether the list above was cut at the cap. | +| `status`, `check_error` | string | dnf only: `ok`, or `check_failed` with a fixed `check_error` (`metadata_unavailable`, `package_manager_error`) when the update check could not run. | +| `os_build`, `installed_kbs`, `missing[]`, `source`, `wsus_server`, `cve_ids_populated`, `scan_error` | various | Windows: the build, the installed KBs, the missing updates (`kbs`, `title`, `severity`, `cve_ids`, `reboot`), and where the scan looked. | +| `cache_age_seconds`, `cache_stale` | integer, boolean | Windows: always `0` and `false` here, because this module's Windows fact scans live and has no cache. | + +The package list is capped (`PCM_PATCH_MAX_PACKAGES`, default 500) because the fact is stored in PuppetDB and re-sent every agent +run. Only the detail list is capped; the counts stay exact and `truncated` says so. -**Deliberately no `title` field** — the fact is stored in PuppetDB and -re-sent every agent run, and `patches[]` can run to dozens of entries on a -stale node. The console resolves human-readable display text from `id` -itself rather than paying that cost in every fact upload. +The `patches[]` array of version 1 is no longer emitted. The console still falls back to it for a node that has not yet received +this module's new facts. -Structured JSON output requires Facter 4, which ships with Puppet 8 — +Structured JSON output requires Facter 4, which ships with Puppet 8 -- OpenVox, Puppet Core, and PE all qualify. +## Tests + +The fact is tested together with its development copy in the Puppet Stagehand Console repository. This repository's CI runs the +task tests, rspec-puppet and Pester. + ## Files - `manifests/init.pp` — the `patchbot` class (Linux refresh timer only; the diff --git a/facts.d/patchbot.ps1 b/facts.d/patchbot.ps1 index 749507a..a719296 100644 --- a/facts.d/patchbot.ps1 +++ b/facts.d/patchbot.ps1 @@ -1,104 +1,258 @@ -# patchbot.ps1 — external fact (facts.d, pluginsynced from the patchbot -# module). Windows counterpart to facts.d/patchbot.sh — identical JSON shape: -# {"patchbot": {"available": N, "security": N, "reboot_required": bool, -# "last_checked": "", -# "patches": [{"id","severity","security"}, ...]}} +# patchbot.ps1 -- external fact (facts.d, pluginsynced from the patchbot +# module). Windows counterpart to facts.d/patchbot.sh, schema version 2: the same keys as adapters/stagehand/facts.d/patchbot.ps1 +# (published as docs/schemas/patchbot-fact-v2.schema.json, described in docs/design/patch-fact-schema.md): +# {"patchbot": {"schema_version": 2, "available": N, "security": N, "reboot_required": bool, +# "reboot_status": "required|not_required|unknown", "reboot_status_reason": "", +# "last_checked": "", "manager": "wua", "os_build": "10.0.x.y", +# "installed_kbs": ["KB..."], "missing": [{"kbs","title","severity","cve_ids","reboot"}], +# "source": "...", "wsus_server": "...|null", "package_count": N, "truncated": bool, +# "cache_age_seconds": 0, "cache_stale": false, "cve_ids_populated": bool|null, "scan_error": "...|null"}} # # Facter's facts.d loader runs .ps1 scripts directly on Windows (no wrapping # .bat needed) and, on Linux, simply skips this file (not executable, no -# shebang) — patchbot.sh and patchbot.ps1 coexist in the same facts.d/ and +# shebang) -- patchbot.sh and patchbot.ps1 coexist in the same facts.d/ and # only the platform-appropriate one ever actually runs. # -# Uses the built-in Windows Update Agent (WUA) COM API directly — no -# PSWindowsUpdate module dependency, matching this module's dependency-light -# design (same reasoning as the shell fact needing no jq/python). +# Unlike the adapters fact, which reads a cache written by a scheduled scanner (patchbot_refresh.ps1), this fact scans LIVE with the +# built-in Windows Update Agent (WUA) COM API -- no PSWindowsUpdate module dependency, matching this module's dependency-light design. +# So cache_age_seconds is always 0 and cache_stale is always false: there is no cache. The scan keys (installed_kbs, missing, source, +# wsus_server, cve_ids_populated, scan_error) are built the way patchbot_refresh.ps1 builds them. # -# Severity: MSRC's four-tier rating (Critical/Important/Moderate/Low) maps -# onto the shared low/medium/high/unknown enum used across the whole -# product (compliance.v1's severity field, and the Linux side of this same -# fact). Critical and Important both collapse to "high" — matching -# trivy-report.sh's own CRITICAL/HIGH -> high collapse — so a Windows node -# and a Linux node report severity on the same three-plus-unknown scale. -# Updates with no MsrcSeverity (most non-security updates) are "unknown". +# `reboot_status` is a three-state answer decided by the shared block below, byte-identical to the one in the adapters fact (a Go test +# keeps them the same). Each probe answers yes, no or error and an error is never read as a no, so a host that cannot tell reports +# unknown. `reboot_required` is kept for readers of version 1 and is true only when reboot_status is required. +# +# `security` is the number of missing updates whose MSRC severity is anything but Unspecified, counted over the whole scan; `missing` +# is capped (PCM_PATCH_MAX_PACKAGES, default 500) and `truncated` says so, while `available` and `package_count` stay exact. +# +# A scan that cannot run (WUA unavailable, WSUS unreachable) never breaks a Puppet run: the fact still prints every key, with zero +# counts, an empty missing list, the reboot answer and scan_error naming the failure. $ErrorActionPreference = 'Stop' +$ProgressPreference = 'SilentlyContinue' + +# The detail cap. A value that is not a positive whole number falls back to the default. +$MaxMissing = 500 +$capEnv = 0 +if ([int]::TryParse([string]$env:PCM_PATCH_MAX_PACKAGES, [ref]$capEnv) -and $capEnv -gt 0) { $MaxMissing = $capEnv } + +function Get-OsBuild { + # Four-part build: CurrentMajorVersionNumber.CurrentMinorVersionNumber. + # CurrentBuildNumber.UBR — e.g. 10.0.20348.3328. + # + # UBR is the revision that changes with every cumulative update and is the + # ONLY part that distinguishes a patched host from an unpatched one. It + # lives in the registry and nowhere else convenient: Facter's os.release + # stops at the build number, and [Environment]::OSVersion has been + # shimmed/lying since Windows 8.1. Read the registry. + $key = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' + $cv = Get-ItemProperty -Path $key -ErrorAction SilentlyContinue + if ($null -eq $cv) { return $null } -function ConvertTo-Severity { - param($Msrc) - switch (([string]$Msrc).Trim().ToLowerInvariant()) { - 'critical' { 'high' } - 'important' { 'high' } - 'moderate' { 'medium' } - 'low' { 'low' } - default { 'unknown' } - } + $major = $cv.CurrentMajorVersionNumber + $minor = $cv.CurrentMinorVersionNumber + if ($null -eq $major) { + # Pre-Windows 10 (Server 2012 R2 and older) has no + # CurrentMajorVersionNumber; fall back to the "6.3" style string. + $parts = ("$($cv.CurrentVersion)").Split('.') + if ($parts.Count -ge 2) { $major = $parts[0]; $minor = $parts[1] } + else { return $null } + } + $build = $cv.CurrentBuildNumber + $ubr = $cv.UBR + if ($null -eq $ubr) { $ubr = 0 } # absent on pre-Win10; treat as .0 + return "$major.$minor.$build.$ubr" } -function New-EmptyFact { - [pscustomobject]@{ - patchbot = [pscustomobject]@{ - available = 0 - security = 0 - reboot_required = $false - last_checked = (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ') - patches = @() +# BEGIN reboot_status +# Reboot answer, three states. Each probe answers yes, no or error, and an +# error is never read as a no (D-09). The classification below is D-25: any yes +# is required; the CBS and Windows Update probes both answering a definite no is +# not required (the file-rename and SCCM probes only add a yes); otherwise +# unknown with reason probes_failed. +# +# ASSUMED until a Windows host confirms it (RESEARCH A1): a missing registry key +# raises ItemNotFoundException and a denied key raises another exception type, +# as the filesystem provider does. Verified on the filesystem provider only. +function Test-PatchbotProbe([scriptblock]$Probe) { + try { + if (& $Probe) { 'yes' } else { 'no' } + } catch [System.Management.Automation.ItemNotFoundException] { + 'no' + } catch { + 'error' } - } } -try { - $session = New-Object -ComObject Microsoft.Update.Session - $searcher = $session.CreateUpdateSearcher() - # IsHidden=0: match what a user checking Windows Update manually would - # see — dismissed/postponed updates are excluded, same as the console's - # "double-click Windows Update" framing. - $result = $searcher.Search('IsInstalled=0 and IsHidden=0') - - $patches = @() - $securityCount = 0 - - foreach ($update in $result.Updates) { - $isSecurity = $false - if ($update.MsrcSeverity) { - $isSecurity = $true - } else { - foreach ($cat in $update.Categories) { - if ($cat.Name -eq 'Security Updates') { $isSecurity = $true; break } - } +function Resolve-PatchbotRebootStatus([string]$Cbs, [string]$WindowsUpdate, [string]$FileRename, [string]$Sccm) { + if (($Cbs, $WindowsUpdate, $FileRename, $Sccm) -contains 'yes') { + return [pscustomobject]@{ Status = 'required'; Reason = 'pending_reboot_probe' } } - if ($isSecurity) { $securityCount++ } - - if ($update.KBArticleIDs -and $update.KBArticleIDs.Count -gt 0) { - $id = 'KB' + $update.KBArticleIDs[0] - } else { - # Rare: an update with no KB (e.g. a driver update) falls back to its - # WUA-internal UpdateID GUID so it still has a stable, unique `id`. - $id = $update.Identity.UpdateID + if ($Cbs -eq 'no' -and $WindowsUpdate -eq 'no') { + return [pscustomobject]@{ Status = 'not_required'; Reason = 'probes_clear' } } + return [pscustomobject]@{ Status = 'unknown'; Reason = 'probes_failed' } +} +# END reboot_status - $patches += [pscustomobject]@{ - id = $id - severity = if ($isSecurity) { ConvertTo-Severity $update.MsrcSeverity } else { 'unknown' } - security = $isSecurity +function Get-RebootStatus { + # Four independent signals; each is run through Test-PatchbotProbe with + # -ErrorAction Stop inside its scriptblock, so a probe that could not read + # the registry answers error and not no. + $cbs = Test-PatchbotProbe { + $null = Get-Item -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending' -ErrorAction Stop + $true + } + $wu = Test-PatchbotProbe { + $null = Get-Item -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired' -ErrorAction Stop + $true + } + $fileRename = Test-PatchbotProbe { + # GetValue returns a plain null when the value is absent, so an absent + # value is a no and only a failure to open the key is an error. + $key = Get-Item -LiteralPath 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager' -ErrorAction Stop + $v = $key.GetValue('PendingFileRenameOperations') + ($null -ne $v) -and (@($v).Count -gt 0) } - } - $rebootRequired = [bool](New-Object -ComObject Microsoft.Update.SystemInfo).RebootRequired + # SCCM's own opinion, only when the client is actually installed. A missing + # client is not applicable, not an error. + $sccm = 'absent' + if (Get-CimClass -Namespace 'root\ccm\clientsdk' -ClassName 'CCM_ClientUtilities' -ErrorAction SilentlyContinue) { + $sccm = Test-PatchbotProbe { + $r = Invoke-CimMethod -Namespace 'root\ccm\clientsdk' -ClassName 'CCM_ClientUtilities' ` + -MethodName 'DetermineIfRebootPending' -ErrorAction Stop + ($null -ne $r) -and ($r.RebootPending -eq $true -or $r.IsHardRebootPending -eq $true) + } + } + return Resolve-PatchbotRebootStatus -Cbs $cbs -WindowsUpdate $wu -FileRename $fileRename -Sccm $sccm +} + +function Get-KbList($update) { + $out = @() + try { + foreach ($kb in $update.KBArticleIDs) { + if ($kb) { $out += ("KB" + ($kb -replace '^KB', '')) } + } + } catch { } + return $out +} - $fact = [pscustomobject]@{ - patchbot = [pscustomobject]@{ - available = $result.Updates.Count - security = $securityCount - reboot_required = $rebootRequired - last_checked = (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ') - patches = @($patches) +# ---- fast path: no network, no WUA ------------------------------------------ +# Neither read may break the run: a build that cannot be read is null, and a reboot answer that cannot be read is unknown. +$osBuild = $null +try { $osBuild = Get-OsBuild } catch { } +$reboot = [pscustomobject]@{ Status = 'unknown'; Reason = 'probes_failed' } +try { $reboot = Get-RebootStatus } catch { } + +# ---- live scan -------------------------------------------------------------- +$installedKbs = New-Object System.Collections.Generic.HashSet[string] +$missing = @() +$total = 0 +$securityCount = 0 +$source = 'unknown' +$wsus = $null +$scanError = $null +$cveSeen = $false # did ANY update expose a non-empty CveIDs? +$cveChecked = $false # did we get far enough to look? + +try { + $session = New-Object -ComObject Microsoft.Update.Session + $searcher = $session.CreateUpdateSearcher() + + # Which service are we actually asking? 0=default 1=WSUS 2=Windows Update 3=other. A box pointed at WSUS reports what WSUS has + # approved, not what Microsoft has published. + switch ($searcher.ServerSelection) { + 1 { $source = 'wsus' } + 2 { $source = 'windowsupdate' } + 3 { $source = 'other' } + default { $source = 'default' } + } + $wsusKey = Get-ItemProperty -Path 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate' -Name 'WUServer' -ErrorAction SilentlyContinue + if ($null -ne $wsusKey) { $wsus = [string]$wsusKey.WUServer; if ($source -eq 'default') { $source = 'wsus' } } + + # ---- installed: history first (cheap, local) -------------------------- + try { + $count = $searcher.GetTotalHistoryCount() + if ($count -gt 0) { + foreach ($entry in $searcher.QueryHistory(0, $count)) { + if ($entry.ResultCode -ne 2) { continue } # 2 = succeeded + if ($entry.Title -match 'KB(\d{6,})') { [void]$installedKbs.Add("KB" + $Matches[1]) } + } + } + } catch { } + + # ---- installed: searcher view (catches image-baked updates) ----------- + try { + $inst = $searcher.Search("IsInstalled=1 and Type='Software'") + foreach ($u in $inst.Updates) { foreach ($kb in (Get-KbList $u)) { [void]$installedKbs.Add($kb) } } + } catch { } + + # ---- missing: IsHidden=0 matches what a user checking Windows Update manually would see -- dismissed or postponed updates are + # excluded. + $result = $searcher.Search('IsInstalled=0 and IsHidden=0') + $cveChecked = $true + $total = $result.Updates.Count + $listed = 0 + foreach ($u in $result.Updates) { + $sev = $null + try { if ($u.MsrcSeverity) { $sev = [string]$u.MsrcSeverity } } catch { } + # Counted over every update, not only the listed ones, so the count stays exact when the detail list is capped. + if ($sev -and $sev -ne 'Unspecified') { $securityCount++ } + + if ($listed -ge $MaxMissing) { continue } + $listed++ + + # IUpdate2::CveIDs. Reported as a diagnostic rather than assumed: cve_ids_populated answers, with data, whether WUA fills it. + $cves = @() + try { + if ($null -ne $u.CveIDs) { + foreach ($c in $u.CveIDs) { if ($c) { $cves += [string]$c } } + } + } catch { } + if ($cves.Count -gt 0) { $cveSeen = $true } + + $missing += [ordered]@{ + kbs = (Get-KbList $u) + title = [string]$u.Title + severity = $sev + cve_ids = $cves + reboot = [bool]$u.RebootRequired + } } - } } catch { - # Same contract as the shell fact: never break a Puppet run over a - # patch-posture read failure — report a zeroed, honest "couldn't check" - # state instead of crashing pluginsync'd fact resolution. - $fact = New-EmptyFact + # Same contract as the shell fact: never break a Puppet run over a patch-posture read failure. Report a zeroed, honest "could not + # check" state, with the reason, instead of crashing pluginsync'd fact resolution. Nothing half-collected is kept. + $scanError = $_.Exception.Message + $missing = @() + $total = 0 + $securityCount = 0 + $cveChecked = $false +} + +$payload = [ordered]@{ + schema_version = 2 + available = $total + security = $securityCount + # Kept for version 1 readers: true only when reboot_status is required. + reboot_required = ($reboot.Status -eq 'required') + reboot_status = $reboot.Status + reboot_status_reason = $reboot.Reason + last_checked = (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ') + manager = 'wua' + os_build = $osBuild + installed_kbs = @($installedKbs | Sort-Object) + missing = $missing + source = $source + wsus_server = $wsus + package_count = $total + truncated = ($total -gt $MaxMissing) + # The scan is live, so there is no cache to age or to go stale. + cache_age_seconds = 0 + cache_stale = $false + cve_ids_populated = $(if ($cveChecked) { $cveSeen } else { $null }) + scan_error = $scanError } -$fact | ConvertTo-Json -Depth 6 -Compress +# -Compress keeps it to one line; Depth 6 covers missing[].cve_ids. +@{ patchbot = $payload } | ConvertTo-Json -Compress -Depth 6 diff --git a/facts.d/patchbot.sh b/facts.d/patchbot.sh index 8ec8690..383c44e 100755 --- a/facts.d/patchbot.sh +++ b/facts.d/patchbot.sh @@ -1,13 +1,30 @@ #!/bin/sh # patchbot — external fact (facts.d, pluginsynced from the patchbot module). -# Patch posture the console reads (Patching page + Action Center): -# {"patchbot": {"available": N, "security": N, "reboot_required": bool, -# "last_checked": "", -# "packages": [{"name","arch","current","available","repo","security"}, ...]}} +# Patch posture the console reads (Patching page + Action Center). Schema version 2: the same keys as +# adapters/stagehand/facts.d/patchbot.sh, published as docs/schemas/patchbot-fact-v2.schema.json and described in +# docs/design/patch-fact-schema.md: +# {"patchbot": {"schema_version": 2, "available": N, "security": N, "reboot_required": bool, +# "reboot_status": "required|not_required|unknown", "reboot_status_reason": "", +# "last_checked": "", "manager": "apt|dnf|yum|", +# "repos": ["", ...], +# "packages": [{"name","arch","current","available","repo","security"}, ...], +# "package_count": N, "truncated": bool}} +# dnf also reports "status" (ok | check_failed) and, when the check could not run, "check_error" (a fixed code): dnf is the one +# manager whose check-update exit codes are verified. # (apt, dnf and yum all emit this shape as of 999.47-03. See 999.47-01 for # apt, 999.47-03 for dnf/yum -- the three branches converged onto one # shape via shared add_package/json_escape/rpm_installed_versions helpers # rather than each formatting its own JSON.) +# +# `reboot_status` is a three-state answer decided by the shared block below. That block is byte-identical to the ones in +# adapters/stagehand/facts.d/patchbot.sh and adapters/stagehand/tasks/patch.sh, and a Go test keeps all three the same. Unknown means +# this node cannot tell (the tool that reports it is missing or failed, or no supported package manager is present); it is never +# reported as not_required. `reboot_required` is kept for readers of version 1 and is true only when reboot_status is required. A +# fact without schema_version is version 1. +# +# Cost note: this fact is per-node state in PuppetDB, so the package list is capped (PCM_PATCH_MAX_PACKAGES, default 500) and +# `truncated` reports when it bites. The counts and package_count stay exact; only the detail array is capped. +# # Structured JSON output requires Facter 4 (ships with Puppet 8 — OpenVox, # Puppet Core, and PE all qualify). # @@ -45,10 +62,107 @@ # modulepath, or drop into /etc/puppetlabs/facter/facts.d/ (chmod 755). set -u +# The package cap. A non-numeric value falls back to the default rather than breaking the comparison below. +LIMIT=${PCM_PATCH_MAX_PACKAGES:-500} +case "$LIMIT" in + ''|*[!0-9]*) LIMIT=500 ;; +esac + AVAILABLE=0 SECURITY=0 -REBOOT=false +TOTAL=0 +# REBOOT_STATUS and REBOOT_REASON come from detect_reboot_status (the shared block below); the boolean is derived from the status in +# one place, further down. The defaults are the cannot-tell answer, so a path that forgot to ask never says "no". +REBOOT_STATUS=unknown +REBOOT_REASON=no_package_manager +MANAGER="" PACKAGES="" +PKG_LISTED=0 +REPOS="" +# status: ok = the check ran and the numbers are real (zero included); check_failed = it could not run, so the numbers say nothing +# about the node. check_error names why, from a fixed set, never raw command output. Only dnf claims a status (verified exit codes). +STATUS=ok +CHECK_ERROR="" + +# BEGIN reboot_status +# Reboot-pending detection shared by tasks/patch.sh and facts.d/patchbot.sh. A +# test keeps the two copies byte-identical: change both or neither. +# +# detect_reboot_status MANAGER (MANAGER is apt, dnf, yum or anything else) +# sets REBOOT_STATUS and REBOOT_REASON: +# REBOOT_STATUS required | not_required | unknown (unknown is never "no") +# REBOOT_REASON marker_present | marker_absent | no_marker_writer | +# needs_restarting | plugin_missing | needs_restarting_failed | +# no_package_manager +# PATCHBOT_REBOOT_MARKER and PATCHBOT_MARKER_WRITER override the apt paths and +# exist for tests only. +detect_reboot_status() { + REBOOT_STATUS="unknown" + REBOOT_REASON="no_package_manager" + case "${1:-}" in + apt) + if [ -f "${PATCHBOT_REBOOT_MARKER:-/var/run/reboot-required}" ]; then + REBOOT_STATUS="required" + REBOOT_REASON="marker_present" + elif [ -x "${PATCHBOT_MARKER_WRITER:-/usr/share/update-notifier/notify-reboot-required}" ]; then + # A writer is installed, so the marker's absence is meaningful. + REBOOT_STATUS="not_required" + REBOOT_REASON="marker_absent" + else + # Nothing on this node would ever write the marker: cannot tell. + REBOOT_REASON="no_marker_writer" + fi + ;; + dnf) + # dnf4 plugin / dnf5: exit 0 = no reboot needed; exit 1 WITH output = a + # reboot is required; exit 1 with NO output is dnf4 saying "No such + # command" because the plugin is not installed; any other exit (dnf5 + # reports an unknown argument as 2) means the probe itself failed. The + # text of the output is never parsed: it is locale dependent. + _nr_out=$(dnf -q needs-restarting -r 2>/dev/null) + _nr_rc=$? + case "$_nr_rc" in + 0) + REBOOT_STATUS="not_required" + REBOOT_REASON="needs_restarting" + ;; + 1) + if [ -n "$_nr_out" ]; then + REBOOT_STATUS="required" + REBOOT_REASON="needs_restarting" + else + REBOOT_REASON="plugin_missing" + fi + ;; + *) REBOOT_REASON="needs_restarting_failed" ;; + esac + ;; + yum) + # yum hosts carry no dnf plugin; the standalone needs-restarting (from + # yum-utils) answers with exit 0 (no) or 1 (yes). Absent: cannot tell. + if command -v needs-restarting >/dev/null 2>&1; then + needs-restarting -r >/dev/null 2>&1 + _nr_rc=$? + case "$_nr_rc" in + 0) + REBOOT_STATUS="not_required" + REBOOT_REASON="needs_restarting" + ;; + 1) + REBOOT_STATUS="required" + REBOOT_REASON="needs_restarting" + ;; + *) REBOOT_REASON="needs_restarting_failed" ;; + esac + else + REBOOT_REASON="plugin_missing" + fi + ;; + *) : ;; + esac +} +# END reboot_status + # json_escape backslash-and-quote-escapes a value before it is interpolated # into emitted JSON (T-999.47-01: suite/version/arch strings, unlike the bare @@ -63,6 +177,10 @@ json_escape() { # to $PACKAGES. Used by all three branches (apt: 999.47-01; dnf/yum: # 999.47-03). Every string field is routed through json_escape first. add_package() { + # The detail list is capped (PCM_PATCH_MAX_PACKAGES): past the cap an entry is dropped, never the count, so package_count and the + # top-level counts stay exact and `truncated` says the list is partial. + [ "$PKG_LISTED" -lt "$LIMIT" ] || return 0 + PKG_LISTED=$((PKG_LISTED + 1)) _name=$(json_escape "$1") _arch=$(json_escape "$2") _cur=$(json_escape "$3") @@ -127,6 +245,23 @@ rpm_installed_version_for() { printf '%s\n' "$2" | awk -v name="$1" '$1 == name { print $2; exit }' } +# security_names: reads `updateinfo list security` rows on stdin, prints the exact package names they name, sorted and unique, one per +# line. An advisory row ends with a NEVRA (name-[epoch:]version-release.arch); dropping the .arch and the last two hyphen fields leaves +# the exact name, so an advisory for curl-minimal is never taken for one for curl, and a package under several advisories or builds +# appears once. The awk body is the adapters copy's nevra_name (adapters/stagehand/facts.d/patchbot.sh, SEC_AWK). The rows go in on +# stdin, never through `awk -v`: BSD awk (macOS, where the harness runs) rejects a multi-line -v value. +security_names() { + awk ' + function nevra_name(s, n, parts, i) { + sub(/\.[^.-]+$/, "", s) # drop .arch + n = split(s, parts, "-") + if (n < 3) return s + s = parts[1]; for (i = 2; i <= n - 2; i++) s = s "-" parts[i] + return s + } + NF >= 3 { print nevra_name($NF) }' | sort -u +} + if command -v apt-get >/dev/null 2>&1; then # Simulated dist-upgrade: count Inst lines; security = those from a # -security suite. Uses the package cache only (no network) — the patchbot @@ -138,9 +273,11 @@ if command -v apt-get >/dev/null 2>&1; then # the third field is parsed defensively rather than positionally (ported # from adapters/stagehand/facts.d/patchbot.sh's apt awk block, the proven # reference implementation of this exact parse). + MANAGER="apt" UPGR=$(apt-get -s dist-upgrade 2>/dev/null | grep '^Inst ' || true) if [ -n "$UPGR" ]; then - AVAILABLE=$(printf '%s\n' "$UPGR" | wc -l | tr -d ' ') + TOTAL=$(printf '%s\n' "$UPGR" | wc -l | tr -d ' ') + AVAILABLE=$TOTAL SECURITY=$(printf '%s\n' "$UPGR" | grep -ci 'security' || true) OLDIFS=$IFS IFS=' @@ -195,7 +332,16 @@ PKGFIELDS done IFS=$OLDIFS fi - [ -f /var/run/reboot-required ] && REBOOT=true + + # Configured suites, from the resolved policy rather than sources.list, so pinning and deb822 sources are both accounted for. + REPOS=$(apt-cache policy 2>/dev/null \ + | grep -o 'a=[A-Za-z0-9._-]*' | cut -d= -f2 \ + | grep -v '^now$' | sort -u \ + | awk '{ printf "%s\"%s\"", (NR > 1 ? "," : ""), $0 }') + + # The reboot-required marker, read through the shared block. A node with no marker and nothing installed that would ever write + # one reports unknown rather than "no". + detect_reboot_status apt elif command -v dnf >/dev/null 2>&1; then # `check-update -q` exits 100 with a package list when updates exist: @@ -203,19 +349,37 @@ elif command -v dnf >/dev/null 2>&1; then # Column 2 is the CANDIDATE (available) version, not the installed one -- # check-update never reports what's currently installed, so the batched # rpm_installed_versions lookup below is what makes `current` true - # (D-02, spec S4). NF>=3 and the Obsoleting guard are unchanged from the - # legacy parse -- both already drop the lines that must be dropped (the - # NF>=3 filter also silently drops a wrapped two-line check-update entry, - # a pre-existing limitation this plan does not change). - LIST=$(dnf -q check-update 2>/dev/null | awk 'NF>=3 && $1 !~ /^Obsoleting/ {print}' || true) - # Advisory severity for the security subset (e.g. "Important/Sec." NEVRA); - # cross-referenced below by NEVRA-prefix match against each $LIST entry's - # bare package name — RPM NEVRA always starts "-...", so a - # "name-" prefix match is a reliable (if not bulletproof) correlation. - SECLIST=$(dnf -q updateinfo list security --available 2>/dev/null | awk 'NF>=3 {print $2, $3}' || true) - SECURITY=$(printf '%s\n' "$SECLIST" | grep -c '.' || true) - if [ -n "$LIST" ]; then - AVAILABLE=$(printf '%s\n' "$LIST" | wc -l | tr -d ' ') + # (D-02, spec S4). NF>=3 drops a wrapped two-line check-update entry (a + # pre-existing limitation this plan does not change). The LIST filter is the + # adapters copy's (D-06): it also drops a `Last metadata expiration` line and + # any row whose first field has no dot, so a `replacing` row under + # Obsoleting Packages is never counted as an update. + MANAGER="dnf" + # Capture the exit codes the old pipelines discarded: `check-update` exits 0 with nothing pending, 100 with updates pending, and + # anything else when it could not run (AlmaLinux 8.10 exits 1 when repo metadata is unreachable). Without this a failed check + # printed exactly what a fully patched host prints. Only dnf's exit codes are verified, so only dnf reports a status. + CHECK_OUT=$(dnf -q check-update 2>/dev/null) + CHECK_RC=$? + case "$CHECK_RC" in + 0|100) ;; + *) STATUS=check_failed; CHECK_ERROR=metadata_unavailable ;; + esac + LIST=$(printf '%s\n' "$CHECK_OUT" | awk 'NF>=3 && $1 !~ /^Obsoleting/ && $1 !~ /^Last/ && $1 ~ /\./ {print}' || true) + # Security advisories name their packages as full NEVRA, one row per advisory per package build. If this lookup fails the update + # list is real but every security flag would silently be false, so a failure here fails the whole check too. + SEC_OUT=$(dnf -q updateinfo list security --available 2>/dev/null) + SEC_RC=$? + if [ "$SEC_RC" -ne 0 ] && [ "$STATUS" = ok ]; then + STATUS=check_failed; CHECK_ERROR=package_manager_error + fi + # The exact names the advisories name (see security_names). `security` is NOT a count of these rows: one package can sit under + # several advisories and builds. It is the number of distinct pending updates whose exact name is in this set, counted over the + # WHOLE list in pass 2 below (the detail list may be capped, the count is not), so it can never exceed `available`. + SECNAMES=$(printf '%s\n' "$SEC_OUT" | security_names) + SEC_COUNT=0 + if [ -n "$LIST" ] && [ "$STATUS" = ok ]; then + TOTAL=$(printf '%s\n' "$LIST" | wc -l | tr -d ' ') + AVAILABLE=$TOTAL OLDIFS=$IFS IFS=' ' @@ -224,8 +388,12 @@ elif command -v dnf >/dev/null 2>&1; then # validated by pkgname_is_safe (T-999.47-09) before it can reach rpm's # argv. An invalid name is skipped, not aborted -- see pkgname_is_safe. NAMES="" + NAMES_SEEN=0 for ENTRY in $LIST; do [ -n "$ENTRY" ] || continue + # Only the entries that will be listed are looked up: a capped list does not cost a full rpm lookup. + [ "$NAMES_SEEN" -lt "$LIMIT" ] || break + NAMES_SEEN=$((NAMES_SEEN + 1)) NAMEARCH=$(printf '%s\n' "$ENTRY" | awk '{print $1}') NAME=${NAMEARCH%.*} if pkgname_is_safe "$NAME"; then @@ -238,7 +406,9 @@ elif command -v dnf >/dev/null 2>&1; then # package. RPM_TABLE=$(rpm_installed_versions $NAMES) - # Pass 2: emit one packages[] entry per check-update line. + # Pass 2: one packages[] entry per check-update line. An entry is flagged when its exact name is one an advisory names (whole-line + # fixed-string match: a name is data, never a pattern or an option). The walk covers the WHOLE list; add_package drops entries + # past the cap, SEC_COUNT does not. for ENTRY in $LIST; do [ -n "$ENTRY" ] || continue NAMEARCH=$(printf '%s\n' "$ENTRY" | awk '{print $1}') @@ -247,44 +417,53 @@ elif command -v dnf >/dev/null 2>&1; then NAME=${NAMEARCH%.*} ARCH=${NAMEARCH##*.} CUR=$(rpm_installed_version_for "$NAME" "$RPM_TABLE") - MATCH=$(printf '%s\n' "$SECLIST" | grep -m1 -- "${NAME}-" || true) - if [ -n "$MATCH" ]; then - SEV=$(printf '%s\n' "$MATCH" | awk '{print $1}' | sed -E 's#/Sec\.?$##' | tr '[:upper:]' '[:lower:]') - case "$SEV" in - critical|important) add_package "$NAME" "$ARCH" "$CUR" "$AVAIL" "$REPO" "true" ;; - moderate) add_package "$NAME" "$ARCH" "$CUR" "$AVAIL" "$REPO" "true" ;; - low) add_package "$NAME" "$ARCH" "$CUR" "$AVAIL" "$REPO" "true" ;; - *) add_package "$NAME" "$ARCH" "$CUR" "$AVAIL" "$REPO" "true" ;; - esac + if [ -n "$NAME" ] && printf '%s\n' "$SECNAMES" | grep -qxF -- "$NAME"; then + SEC_COUNT=$((SEC_COUNT + 1)) + add_package "$NAME" "$ARCH" "$CUR" "$AVAIL" "$REPO" "true" else add_package "$NAME" "$ARCH" "$CUR" "$AVAIL" "$REPO" "false" fi done IFS=$OLDIFS + SECURITY=$SEC_COUNT fi - # needs-restarting -r: exit 0 = no reboot, exit 1 = reboot required. - # Only trust an explicit 1 — a missing plugin exits differently. - dnf -q needs-restarting -r >/dev/null 2>&1 - [ $? -eq 1 ] && REBOOT=true + + REPOS=$(dnf -q repolist --enabled 2>/dev/null \ + | awk 'NR>1 && NF>=1 && $1 !~ /^repo[ -]?id/ {print $1}' \ + | sort -u | awk '{ printf "%s\"%s\"", (NR > 1 ? "," : ""), $0 }') + + # The reboot answer comes from the shared block (`dnf needs-restarting -r`). A host without the plugin (dnf4 exits 1 with no + # output) reports unknown, never "no" and never "required". needs-restarting does not depend on repository metadata, so the answer + # is valid even when the update check above failed. + detect_reboot_status dnf elif command -v yum >/dev/null 2>&1; then # Same shape as the dnf branch above, reusing rpm_installed_versions, - # rpm_installed_version_for, pkgname_is_safe, add_package and json_escape - # rather than duplicating any of them. Every yum-specific difference from - # the dnf branch stays intact: no Obsoleting guard, the bare - # needs-restarting reboot probe (not `yum -q needs-restarting`), and its - # own SECLIST invocation. + # rpm_installed_version_for, pkgname_is_safe, add_package, json_escape and + # the shared exact-name rule (security_names, counted once per pending + # update over the whole list) rather than duplicating any of them. Every + # yum-specific difference from the dnf branch stays intact: its own LIST + # filter (no Obsoleting guard), `yum -q updateinfo list security` without + # --available, and the bare needs-restarting reboot probe (not + # `yum -q needs-restarting`). + MANAGER="yum" LIST=$(yum -q check-update 2>/dev/null | awk 'NF>=3 {print}' || true) - SECLIST=$(yum -q updateinfo list security 2>/dev/null | awk 'NF>=3 {print $2, $3}' || true) - SECURITY=$(printf '%s\n' "$SECLIST" | grep -c '.' || true) + # The exact names the advisories name, and the count of pending updates among them: never advisory rows (see the dnf branch). + SECNAMES=$(yum -q updateinfo list security 2>/dev/null | security_names) + SEC_COUNT=0 if [ -n "$LIST" ]; then - AVAILABLE=$(printf '%s\n' "$LIST" | wc -l | tr -d ' ') + TOTAL=$(printf '%s\n' "$LIST" | wc -l | tr -d ' ') + AVAILABLE=$TOTAL OLDIFS=$IFS IFS=' ' NAMES="" + NAMES_SEEN=0 for ENTRY in $LIST; do [ -n "$ENTRY" ] || continue + # Only the entries that will be listed are looked up: a capped list does not cost a full rpm lookup. + [ "$NAMES_SEEN" -lt "$LIMIT" ] || break + NAMES_SEEN=$((NAMES_SEEN + 1)) NAMEARCH=$(printf '%s\n' "$ENTRY" | awk '{print $1}') NAME=${NAMEARCH%.*} if pkgname_is_safe "$NAME"; then @@ -305,32 +484,61 @@ elif command -v yum >/dev/null 2>&1; then NAME=${NAMEARCH%.*} ARCH=${NAMEARCH##*.} CUR=$(rpm_installed_version_for "$NAME" "$RPM_TABLE") - MATCH=$(printf '%s\n' "$SECLIST" | grep -m1 -- "${NAME}-" || true) - if [ -n "$MATCH" ]; then - SEV=$(printf '%s\n' "$MATCH" | awk '{print $1}' | sed -E 's#/Sec\.?$##' | tr '[:upper:]' '[:lower:]') - case "$SEV" in - critical|important) add_package "$NAME" "$ARCH" "$CUR" "$AVAIL" "$REPO" "true" ;; - moderate) add_package "$NAME" "$ARCH" "$CUR" "$AVAIL" "$REPO" "true" ;; - low) add_package "$NAME" "$ARCH" "$CUR" "$AVAIL" "$REPO" "true" ;; - *) add_package "$NAME" "$ARCH" "$CUR" "$AVAIL" "$REPO" "true" ;; - esac + if [ -n "$NAME" ] && printf '%s\n' "$SECNAMES" | grep -qxF -- "$NAME"; then + SEC_COUNT=$((SEC_COUNT + 1)) + add_package "$NAME" "$ARCH" "$CUR" "$AVAIL" "$REPO" "true" else add_package "$NAME" "$ARCH" "$CUR" "$AVAIL" "$REPO" "false" fi done IFS=$OLDIFS + SECURITY=$SEC_COUNT fi - needs-restarting -r >/dev/null 2>&1 - [ $? -eq 1 ] && REBOOT=true + + REPOS=$(yum -q repolist --enabled 2>/dev/null \ + | awk 'NR>1 && NF>=1 && $1 !~ /^repo[ -]?id/ {print $1}' \ + | sort -u | awk '{ printf "%s\"%s\"", (NR > 1 ? "," : ""), $0 }') + + # yum hosts carry no dnf plugin; the standalone needs-restarting (yum-utils) answers, read through the shared block. Absent: + # cannot tell. + detect_reboot_status yum + +# ----------------------------------------------- no supported manager ----- +else + # No apt, dnf or yum on PATH: this node cannot tell, and must not look like a clean one. + detect_reboot_status "" fi +TRUNCATED=false +[ "$TOTAL" -gt "$LIMIT" ] && TRUNCATED=true + +# The one place the boolean is derived: true only when the status is required (unknown and not_required are both false). +REBOOT=false +[ "$REBOOT_STATUS" = required ] && REBOOT=true +# Only a non-empty reason is written; the key is absent, not empty, when there is none. +REASON_FIELD="" +[ -n "$REBOOT_REASON" ] && REASON_FIELD=", \"reboot_status_reason\": \"$REBOOT_REASON\"" + NOW=$(date -u +%Y-%m-%dT%H:%M:%SZ) -# All three branches (apt, dnf, yum) build $PACKAGES now (999.47-03) -- a -# node with no supported package manager on PATH at all also gets this -# shape, with an empty packages[] array. The legacy patches[] shape is no -# longer emitted by this script; patchFactPackages's fallback to "patches" -# (backend/internal/httpapi/patching.go) remains the only thing that still -# knows it, as the degradation path for any node still running a pre-999.47 -# copy of this module during rollout (spec section 7). -printf '{"patchbot": {"available": %s, "security": %s, "reboot_required": %s, "last_checked": "%s", "packages": [%s]}}\n' \ - "${AVAILABLE:-0}" "${SECURITY:-0}" "$REBOOT" "$NOW" "$PACKAGES" + +# A check that did not run knows nothing about the node's updates: report no packages and zero counts, never a partial list. The +# reboot answer is the exception: needs-restarting does not depend on repository metadata, so it is reported truthfully even when the +# update check failed. +if [ "$STATUS" != ok ]; then + printf '{"patchbot": {"schema_version": 2, "status": "%s", "check_error": "%s", "available": 0, "security": 0, "reboot_required": %s, "reboot_status": "%s"%s, "last_checked": "%s", "manager": "%s", "repos": [], "packages": [], "package_count": 0, "truncated": false}}\n' \ + "$STATUS" "$CHECK_ERROR" "$REBOOT" "$REBOOT_STATUS" "$REASON_FIELD" "$NOW" "$MANAGER" + exit 0 +fi + +# status is only claimed where the exit codes are verified: the dnf branch. The apt branch captures no exit codes and real yum's are +# unverified, so their output stays without one rather than asserting a status never measured. +STATUS_FIELD="" +case "$MANAGER" in dnf) STATUS_FIELD='"status": "ok", ' ;; esac + +# All three branches (apt, dnf, yum) build $PACKAGES (999.47-03); a node with no supported package manager on PATH gets this shape +# too, with an empty packages[] array and an empty manager. The legacy patches[] shape is no longer emitted by this script; +# patchFactPackages's fallback to "patches" (backend/internal/httpapi/patching.go) remains the only thing that still knows it, as +# the degradation path for any node still running a pre-999.47 copy of this module during rollout (spec section 7). +printf '{"patchbot": {"schema_version": 2, %s"available": %s, "security": %s, "reboot_required": %s, "reboot_status": "%s"%s, "last_checked": "%s", "manager": "%s", "repos": [%s], "packages": [%s], "package_count": %s, "truncated": %s}}\n' \ + "$STATUS_FIELD" "${AVAILABLE:-0}" "${SECURITY:-0}" "$REBOOT" "$REBOOT_STATUS" "$REASON_FIELD" "$NOW" "$MANAGER" \ + "$REPOS" "$PACKAGES" "${TOTAL:-0}" "$TRUNCATED" diff --git a/metadata.json b/metadata.json index 2fc1f4c..6186b14 100644 --- a/metadata.json +++ b/metadata.json @@ -1,6 +1,6 @@ { "name": "stagehand-patchbot", - "version": "0.2.0", + "version": "0.3.0", "author": "stagehand", "summary": "Patch posture reporting (pull-path fact) and OS package patching (push-path Bolt task) for the Puppet Stagehand Console.", "license": "Apache-2.0", From c57bed968c7d5bd25025bb731981ad35279bc216 Mon Sep 17 00:00:00 2001 From: Matthew Stone Date: Wed, 18 Nov 2026 13:29:48 -0600 Subject: [PATCH 2/2] chore(ci): regenerate REFERENCE.md and waive two dev-only gem advisories REFERENCE.md: puppet-strings 4.1.2 drops trailing spaces and the final blank line; content is unchanged. The lint gate failed on the drift. .bundler-audit.yml waives GHSA-r6vf-943r-2wvw (minitar 0.12.1, held below 1.0 by bolt, r10k and puppet_forge via puppet_litmus) and GHSA-4m5j-jjfc-97gx (mcp 0.25.0, from rubocop). Both are dev/test gems that the module does not ship. The release workflow runs the same audit, so without this a v* tag would publish no Release. Verified in a ruby:3.2 container: rake validate lint metadata_lint exits 0, rake spec 241 examples 0 failures, bundler-audit check clean. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01McuAWfE22TvftB9SGnvzTT --- .bundler-audit.yml | 14 ++++++++++++++ REFERENCE.md | 5 ++--- 2 files changed, 16 insertions(+), 3 deletions(-) create mode 100644 .bundler-audit.yml diff --git a/.bundler-audit.yml b/.bundler-audit.yml new file mode 100644 index 0000000..8419a87 --- /dev/null +++ b/.bundler-audit.yml @@ -0,0 +1,14 @@ +--- +# bundler-audit waivers. Each entry is a dev/test-only gem that is not +# shipped in the module (the module ships shell and PowerShell facts and a +# Bolt task) and that cannot be upgraded while an upstream pin holds it. +# Revisit each entry when the named pin moves; remove it once the +# resolved version clears the advisory. +ignore: + # minitar 0.12.1: path traversal on Windows with a crafted tarball. + # Held below 1.0 by bolt (~> 0.6), r10k (~> 0.9) and puppet_forge (< 1.0), + # all pulled in by puppet_litmus for acceptance tests. Waived 2026-11-18. + - GHSA-r6vf-943r-2wvw + # mcp 0.25.0: OAuth discovery SSRF. Pulled in by rubocop (mcp ~> 0.6) for + # its optional MCP server, which lint never starts. Waived 2026-11-18. + - GHSA-4m5j-jjfc-97gx diff --git a/REFERENCE.md b/REFERENCE.md index 2983b2f..0d602e3 100644 --- a/REFERENCE.md +++ b/REFERENCE.md @@ -10,7 +10,7 @@ ### Tasks -* [`patch`](#patch): Apply available OS updates (all, security-only, or a specific set of patch_ids) on a node, optionally reboot when required, then refresh the +* [`patch`](#patch): Apply available OS updates (all, security-only, or a specific set of patch_ids) on a node, optionally reboot when required, then refresh the ## Classes @@ -38,7 +38,7 @@ refresh, and facts.d/patchbot.ps1 queries WUA live on every fact run. #### Examples -##### +##### ```puppet include patchbot @@ -107,4 +107,3 @@ Install only these specific patch/package ids, as reported in the patchbot fact' Data type: `Boolean` Reboot the node afterward if a reboot is required. -