diff --git a/README.md b/README.md index dbd5166d1..42c1a3dc3 100644 --- a/README.md +++ b/README.md @@ -66,6 +66,56 @@ Release support dates are bundled with the app (see `build/update-os-support.php`, data from [endoflife.date](https://endoflife.date), MIT License); the app never looks them up online. +### Root helper + +The web server cannot see everything: only root can tell which services still +run code an update replaced, and only root can refresh the package lists. The +optional script `bin/serverinfo-os-report` adds that. Run as root, it writes a +small JSON report that the app reads. It only reads the system; it never +installs, upgrades, restarts or reboots anything. + +Install it outside the Nextcloud directory: the web server can write there, so +a root cron job pointing into it would hand the web server root. + +Take the file from a freshly extracted release archive, not from the +installed app: the Nextcloud server archive, checked against the SHA-256 sum +or signature published next to it on download.nextcloud.com, or the app's own +release archive. A copy taken from `apps/serverinfo/bin` is safe from changes +made after copying, but not from a web server that was already compromised +and changed the file before. `cmp` shows whether the installed app's file +still matches the release. Repeat this when an update ships a newer helper +(the app then reports the installed helper as outdated). The release archive +does not contain this README; the same instructions are at the top of the +script. + +Extract the file into a new directory that only you can enter, which +`mktemp -d` creates, so that no one can swap it before root installs it. +Remove that directory afterwards. + +``` +d=$(mktemp -d) && +tar -xjf nextcloud-.tar.bz2 -C "$d" nextcloud/apps/serverinfo/bin/serverinfo-os-report && +sudo install -o root -g root -m 0755 "$d"/nextcloud/apps/serverinfo/bin/serverinfo-os-report /usr/local/sbin/ && +rm -r "$d" +echo '17 */6 * * * root /usr/local/sbin/serverinfo-os-report --refresh --random-delay' | sudo tee /etc/cron.d/serverinfo-os-report +``` + +`--random-delay` waits up to 30 minutes first, so that servers sharing this +cron line do not all reach the package mirrors at the same minute; leave it +out when running the helper by hand. Where `flock` is available, a run that +finds another one still going exits without doing anything. Package manager +calls are stopped after a time limit where `timeout` is available. + +The report is written to `/var/lib/serverinfo/os-report.json`. Use +`--output` and `occ config:app:set serverinfo os_helper_report_path --value …` +to put it elsewhere. Every directory on the way to the report must be owned +by root, writable by no one else and no symbolic link; the helper refuses to +write anywhere else, such as below /tmp or the Nextcloud directory. The app +ignores a report that anyone but root could have written, on the same rules +as far as open_basedir lets it check, one written before the last reboot or +on another host, one older than 26 hours, and one dated more than five +minutes in the future (a clock problem). + ## API The API provides a lot of information about a running Nextcloud diff --git a/bin/serverinfo-os-report b/bin/serverinfo-os-report new file mode 100755 index 000000000..94fcdca9a --- /dev/null +++ b/bin/serverinfo-os-report @@ -0,0 +1,588 @@ +#!/bin/sh +# SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors +# SPDX-License-Identifier: AGPL-3.0-or-later +# +# serverinfo-os-report: optional root helper for the Nextcloud Monitoring app. +# +# The Monitoring app runs as the web server user, which can see most of the +# operating system status by itself. This helper adds what only root can see: +# +# - services still running code that an upgrade replaced (needrestart, +# dnf needs-restarting, zypper ps, or a scan of /proc as a fallback) +# - fresh package lists (--refresh), so pending updates are current +# - pending dnf updates, which dnf 5 does not tell other users +# - SUSE LTSS registration +# +# It only reads the system and writes one JSON file. It never installs, +# upgrades, restarts or reboots anything. +# +# Install it outside the Nextcloud directory, which the web server can write +# to, so that the web server cannot change what root runs later on. Take the +# file from a freshly extracted release archive, not from the installed +# app: the Nextcloud server archive, checked against the SHA-256 sum or +# signature published next to it on download.nextcloud.com, or the app's +# own release archive. A copy taken from apps/serverinfo/bin is safe from +# changes made after copying, but not from a web server that was already +# compromised and changed the file before. If both copies are at hand, +# `cmp` shows whether the installed app's file still matches the release. +# Repeat this when an update ships a newer helper. Extract the file into a +# new directory that only you can enter, which `mktemp -d` creates, so that +# no one can swap it before root installs it. Remove that directory +# afterwards. +# +# d=$(mktemp -d) && +# tar -xjf nextcloud-.tar.bz2 -C "$d" nextcloud/apps/serverinfo/bin/serverinfo-os-report && +# sudo install -o root -g root -m 0755 "$d"/nextcloud/apps/serverinfo/bin/serverinfo-os-report /usr/local/sbin/ && +# rm -r "$d" +# echo '17 */6 * * * root /usr/local/sbin/serverinfo-os-report --refresh --random-delay' | sudo tee /etc/cron.d/serverinfo-os-report +# +# Report format (schema 1), all fields but the first five optional: +# schema, helperVersion, generatedAt (unix time), hostname, bootTime (unix time), +# distribution, listsRefreshedAt (unix time, after a successful --refresh), +# pendingUpdates (list of {name, installed, candidate, security, origin, +# advisories, severity}, null when not collected), +# restartServices (list of systemd units, null when unknown), +# rebootReasons (list of {kind: kernel|microcode, detail}), +# subscription ({kind, active}), errors (list of strings) + +set -u +# Command output is split into words in places; it must never be expanded as +# a file name pattern. +set -f +umask 022 + +PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin +LC_ALL=C +LANG=C +export PATH LC_ALL LANG + +VERSION=1.0.0 +SCHEMA=1 +OUTPUT=/var/lib/serverinfo/os-report.json +LOCK=/run/serverinfo-os-report.lock +REFRESH=0 +RANDOM_DELAY=0 +DRY_RUN=0 +TEMPORARY= +TIMEOUT_MODE= +ERRORS= +SERVICES= +REBOOT_REASONS= + +usage() { + cat <&2 + exit 1 +} + +# Records a problem for the report. Only printable ASCII is kept, so the +# message can be placed in JSON after escaping quotes and backslashes. +note_error() { + message=$(printf '%s' "$1" | tr -c '\040-\176' ' ' | cut -c1-300) + ERRORS="$ERRORS$message +" +} + +json_text() { + printf '"%s"' "$(printf '%s' "$1" | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g')" +} + +# Package, unit and version tokens are emitted only when they consist of +# characters that need no escaping in JSON; anything else is dropped. +is_token() { + case "$1" in + '' | *[!A-Za-z0-9@._+:~^-]*) return 1 ;; + *) return 0 ;; + esac +} + +# Removes the temporary report, if there is one. +cleanup() { + if [ -n "$TEMPORARY" ]; then + rm -f "$TEMPORARY" + TEMPORARY= + fi +} + +# Cleans up on every exit; a signal ends the run with an error. +set_traps() { + trap cleanup EXIT + trap 'cleanup; exit 1' HUP INT TERM +} + +# How run_limited can stop a command: "kill" when timeout(1) takes -k, +# "term" when it only sends SIGTERM, "none" without timeout(1) or with the +# busybox before 1.30, which has another syntax. +timeout_mode() { + if ! command -v timeout >/dev/null 2>&1; then + echo none + elif timeout -k 1 10 true >/dev/null 2>&1; then + echo kill + elif timeout 10 true >/dev/null 2>&1; then + echo term + else + echo none + fi +} + +# Runs a command ($2 ...) for at most $1 seconds, and kills it 30 seconds +# after that if it ignores SIGTERM. The lock is not passed on, so nothing +# the command leaves running can hold it. +run_limited() { + limit=$1 + shift + [ -n "$TIMEOUT_MODE" ] || TIMEOUT_MODE=$(timeout_mode) + case "$TIMEOUT_MODE" in + kill) timeout -k 30 "$limit" "$@" 9>&- ;; + term) timeout "$limit" "$@" 9>&- ;; + *) "$@" 9>&- ;; + esac +} + +# Exits quietly when another run holds the lock. Without flock(1), as in +# some busybox builds, runs are not locked; each still writes its own +# temporary file and renames it into place. +take_lock() { + command -v flock >/dev/null 2>&1 || return 0 + [ -d "$(dirname "$LOCK")" ] || return 0 + exec 9>>"$LOCK" + if ! flock -n 9; then + [ -t 2 ] && printf 'serverinfo-os-report: another run is still going\n' >&2 + exit 0 + fi +} + +# Waits a random time of up to 30 minutes; does not wait without a source +# of random numbers. +random_delay() { + number=$(od -An -N2 -tu2 /dev/urandom 2>/dev/null | tr -d ' \n') + case "$number" in + '' | *[!0-9]*) return 0 ;; + esac + sleep $((number % 1800)) +} + +os_value() { + sed -n "s/^$1=//p" /etc/os-release 2>/dev/null | head -n 1 | tr -d "\"'" +} + +add_service() { + unit=$1 + case "$unit" in + *.service) ;; + *) unit="$unit.service" ;; + esac + is_token "$unit" || return 0 + case " +$SERVICES" in + *" +$unit +"*) return 0 ;; + esac + SERVICES="$SERVICES$unit +" +} + +# One unit per line. +add_services() { + while IFS= read -r unit; do + unit=$(printf '%s' "$unit" | tr -d ' \t\r') + [ -n "$unit" ] && add_service "$unit" + done </dev/null 2>&1 || return 1 + output=$(printf '%s\n' "$NEEDRESTART_CONFIG" | run_limited 300 needrestart -c /dev/stdin -b -r l 2>/dev/null) || return 1 + parse_needrestart "$output" +} + +# Takes services and reboot reasons from needrestart's batch output ($1). +parse_needrestart() { + printf '%s\n' "$1" | grep -q '^NEEDRESTART-VER:' || return 1 + + add_services "$(printf '%s\n' "$1" | sed -n 's/^NEEDRESTART-SVC: *//p')" + + kernel_status=$(printf '%s\n' "$1" | sed -n 's/^NEEDRESTART-KSTA: *//p') + expected=$(printf '%s\n' "$1" | sed -n 's/^NEEDRESTART-KEXP: *//p') + case "$kernel_status" in + 2 | 3) add_reboot_reason kernel "$expected" ;; + esac + microcode_status=$(printf '%s\n' "$1" | sed -n 's/^NEEDRESTART-UCSTA: *//p') + [ "$microcode_status" = 2 ] && add_reboot_reason microcode '' + return 0 +} + +from_dnf() { + command -v dnf >/dev/null 2>&1 || return 1 + # dnf 5 loads the repositories for needs-restarting; --cacheonly keeps it + # from downloading metadata. dnf 4 accepts the option and loads none. + output=$(run_limited 300 dnf -q --cacheonly needs-restarting -s 2>/dev/null) || return 1 + add_services "$output" + return 0 +} + +from_zypper() { + command -v zypper >/dev/null 2>&1 || return 1 + # Exits 4 without lsof; the /proc scan then answers instead. + output=$(run_limited 300 zypper --non-interactive --quiet ps -sss 2>/dev/null) || return 1 + add_services "$output" + return 0 +} + +# Fallback for any systemd distribution: processes that map a library which +# has been deleted since, attributed to their systemd unit. +from_proc() { + [ -d /proc/1 ] || return 1 + set +f + directories=$(printf '%s\n' /proc/[0-9]*) + set -f + for dir in $directories; do + [ -r "$dir/maps" ] || continue + awk ' + / \(deleted\)$/ && $6 ~ /\.so/ && $6 !~ /^\/(dev|memfd:|tmp|var\/tmp|run|proc|SYSV)/ { found = 1; exit } + END { exit found ? 0 : 1 } + ' "$dir/maps" 2>/dev/null || continue + unit=$(system_unit "$dir/cgroup") + [ -n "$unit" ] && add_service "$unit" + done + return 0 +} + +# Prints the system service a process belongs to, from its cgroup file +# ($1): cgroup v2 (0::/system.slice/...) or the systemd hierarchy of v1. +# Units under user.slice are users' own and are left out. +system_unit() { + sed -n \ + -e 's#^0::/system\.slice/\(.*/\)\{0,1\}\([^/]*\.service\)$#\2#p' \ + -e 's#^[0-9]*:name=systemd:/system\.slice/\(.*/\)\{0,1\}\([^/]*\.service\)$#\2#p' \ + "$1" 2>/dev/null | head -n 1 +} + +# Prints pending dnf updates as a JSON list, from the output of +# `dnf check-update` ($1), the security advisory list of dnf 4 or 5 ($2) and +# `rpm -qa` with name and epoch:version-release ($3). Values that are not +# plain tokens are dropped, so nothing needs escaping. +dnf_updates_json() { + { + printf '%s\n' "$3" | sed 's/^/I /' + printf '%s\n' "$2" | sed 's/^/A /' + printf '%s\n' "$1" | sed 's/^/U /' + } | awk ' + function token(s) { return s ~ /^[A-Za-z0-9@._+:~^-]+$/ } + # The architecture is whatever follows the last dot: x86_64, x86_64_v2, noarch, s390, ... + function strip_arch(s) { sub(/\.[A-Za-z0-9_]+$/, "", s); return s } + function rank(s) { + s = tolower(s) + return s == "critical" ? 4 : s == "important" ? 3 : s == "moderate" ? 2 : s == "low" ? 1 : 0 + } + $1 == "I" && NF == 3 && token($3) { version = $3; sub(/^0:/, "", version); installed[$2] = version; next } + $1 == "A" { + if ($3 ~ /\/Sec\.$/) { severity = $3; sub(/\/Sec\.$/, "", severity); nevra = $4 } + else if ($3 == "security") { severity = $4; nevra = $5 } + else next + if (!token($2) || !token(nevra)) next + name = strip_arch(nevra) + sub(/-[^-]+-[^-]+$/, "", name) + if (!((name, $2) in seen)) { + seen[name, $2] = 1 + ids[name] = ids[name] (ids[name] == "" ? "" : ",") "\"" $2 "\"" + } + if (severity ~ /^[A-Za-z]+$/ && rank(severity) > rank(highest[name])) highest[name] = severity + next + } + $1 == "U" && $2 ~ /^Obsoleting/ { stop = 1 } + # dnf 4 continues a row on the next line, indented to the next column, + # after a name or version too wide for its column. + $1 == "U" && !stop && held != "" { + if ($0 ~ /^U [ \t]/) $0 = "U " held " " substr($0, 3) + held = "" + } + $1 == "U" && !stop && (NF == 2 || NF == 3) && $0 !~ /^U [ \t]/ && $2 ~ /\.[A-Za-z0-9_]+$/ { + held = substr($0, 3) + next + } + $1 == "U" && !stop && NF == 4 && $2 ~ /\.[A-Za-z0-9_]+$/ { + if (!token($2) || !token($3) || !token($4)) next + name = strip_arch($2) + out = out (count++ ? "," : "") sprintf("{\"name\":\"%s\",\"installed\":%s,\"candidate\":\"%s\",\"security\":%s,\"origin\":\"%s\",\"advisories\":[%s],\"severity\":%s}", + name, + (name in installed) ? "\"" installed[name] "\"" : "null", + $3, + (name in ids) ? "true" : "false", + $4, + ids[name], + (name in highest) ? "\"" highest[name] "\"" : "null") + } + END { printf "[%s]", out } + ' +} + +dnf_pending_updates() { + command -v dnf >/dev/null 2>&1 || return 1 + updates=$(run_limited 600 dnf -q --cacheonly check-update 2>/dev/null) + case $? in + 0) printf '[]'; return 0 ;; + 100) ;; + *) return 1 ;; + esac + if command -v dnf5 >/dev/null 2>&1; then + advisories=$(run_limited 600 dnf -q --cacheonly advisory list --security 2>/dev/null) || return 1 + else + advisories=$(run_limited 600 dnf -q --cacheonly updateinfo list --security --available 2>/dev/null) || return 1 + fi + installed=$(rpm -qa --qf '%{NAME} %{EPOCHNUM}:%{VERSION}-%{RELEASE}\n' 2>/dev/null) || return 1 + dnf_updates_json "$updates" "$advisories" "$installed" +} + +main() { + while [ $# -gt 0 ]; do + case "$1" in + --refresh) REFRESH=1 ;; + --random-delay) RANDOM_DELAY=1 ;; + --dry-run) DRY_RUN=1 ;; + --output) + [ $# -ge 2 ] || die '--output needs a file name' + OUTPUT=$2 + shift + ;; + --output=*) OUTPUT=${1#--output=} ;; + --version) echo "$VERSION"; exit 0 ;; + --help | -h) usage; exit 0 ;; + *) usage >&2; exit 1 ;; + esac + shift + done + + case "$OUTPUT" in + /*.json) ;; + *) die 'the output must be an absolute path ending in .json' ;; + esac + case "$OUTPUT" in + */../* | */./* | *[!A-Za-z0-9._/-]*) die 'the output path may only contain letters, digits, dots, dashes, underscores and slashes' ;; + esac + + [ "$(id -u)" -eq 0 ] || die 'must run as root' + cd / || exit 1 + + set_traps + [ "$RANDOM_DELAY" -eq 1 ] && random_delay + take_lock + TIMEOUT_MODE=$(timeout_mode) + + # --- identity ----------------------------------------------------------- + + HOSTNAME_VALUE=$(hostname 2>/dev/null || cat /proc/sys/kernel/hostname 2>/dev/null) + is_token "$HOSTNAME_VALUE" || die 'the host name could not be determined' + + BOOT_TIME=$(awk '/^btime / { print $2 }' /proc/stat 2>/dev/null) + case "$BOOT_TIME" in + '' | *[!0-9]*) BOOT_TIME=null ;; + esac + + DISTRO_ID=$(os_value ID) + DISTRO_LIKE=$(os_value ID_LIKE) + is_token "$DISTRO_ID" || DISTRO_ID=unknown + + case " $DISTRO_ID $DISTRO_LIKE " in + *' debian '* | *' ubuntu '*) FAMILY=apt ;; + *' suse '* | *' opensuse'* | *' sles '*) FAMILY=zypper ;; + *' fedora '* | *' rhel '* | *' centos '* | *' amzn '*) FAMILY=dnf ;; + *' arch '*) FAMILY=pacman ;; + *' alpine '*) FAMILY=apk ;; + *) FAMILY=unknown ;; + esac + + # --- package lists ------------------------------------------------------ + + LISTS_REFRESHED_AT=null + if [ "$REFRESH" -eq 1 ]; then + refreshed=0 + case "$FAMILY" in + apt) run_limited 900 apt-get update -qq -o DPkg::Lock::Timeout=300 >/dev/null 2>&1 && refreshed=1 ;; + dnf) run_limited 900 dnf -q makecache >/dev/null 2>&1 && refreshed=1 ;; + zypper) run_limited 900 zypper --non-interactive --quiet refresh >/dev/null 2>&1 && refreshed=1 ;; + apk) run_limited 900 apk update -q >/dev/null 2>&1 && refreshed=1 ;; + # pacman -Sy without -u leaves Arch half upgraded; checkupdates, which + # the app runs itself, syncs into a private database instead. + *) refreshed=2 ;; + esac + case "$refreshed" in + 1) LISTS_REFRESHED_AT=$(date +%s) ;; + 0) note_error "Refreshing the package lists with $FAMILY failed." ;; + esac + fi + + PENDING=null + if [ "$FAMILY" = dnf ]; then + PENDING=$(dnf_pending_updates) || { + PENDING=null + note_error 'Pending updates could not be listed with dnf.' + } + fi + + # --- services that need a restart --------------------------------------- + + services_known=0 + case "$FAMILY" in + apt) from_needrestart && services_known=1 ;; + dnf) from_dnf && services_known=1 ;; + zypper) from_zypper && services_known=1 ;; + esac + if [ "$services_known" -eq 0 ]; then + from_proc && services_known=1 + fi + [ "$services_known" -eq 1 ] || note_error 'Services that need a restart could not be determined.' + + # --- subscriptions ------------------------------------------------------ + + SUBSCRIPTION=null + if [ "$FAMILY" = zypper ] && command -v SUSEConnect >/dev/null 2>&1; then + status=$(run_limited 120 SUSEConnect --status 2>/dev/null | tr -d ' \n') + case "$status" in + *'"identifier":"SLES-LTSS"'*'"status":"Registered"'*) SUBSCRIPTION='{"kind":"suse-ltss","active":true}' ;; + '['*) SUBSCRIPTION='{"kind":"suse-ltss","active":false}' ;; + esac + fi + + # --- report ------------------------------------------------------------- + + services_json=null + if [ "$services_known" -eq 1 ]; then + services_json=$(printf '%s' "$SERVICES" | awk 'NF { printf "%s\"%s\"", (n++ ? "," : ""), $0 }') + services_json="[$services_json]" + fi + + errors_json= + old_ifs=$IFS + IFS=' +' + for message in $ERRORS; do + errors_json="${errors_json:+$errors_json,}$(json_text "$message")" + done + IFS=$old_ifs + + REPORT=$(cat < "$TEMPORARY" || die "cannot write $TEMPORARY" + chmod 0644 "$TEMPORARY" + # rename(2) replaces a symbolic link to a file instead of following it. + mv -f "$TEMPORARY" "$2" || die "cannot replace $2" + TEMPORARY= +} + +# Tests load the functions above without running anything. +if [ "${SERVERINFO_OS_REPORT_FUNCTIONS_ONLY:-}" != 1 ]; then + main "$@" +fi diff --git a/lib/Commands/ShowOsStatus.php b/lib/Commands/ShowOsStatus.php index 6f37d1540..d73f63bf0 100644 --- a/lib/Commands/ShowOsStatus.php +++ b/lib/Commands/ShowOsStatus.php @@ -84,6 +84,7 @@ public function __invoke( 'updates' => $status->updates === null ? 'unknown' : count($status->updates) + $status->updatesOmitted, 'updatesPendingDays' => is_int($pendingDays) ? $pendingDays : 'none', 'rebootRequired' => $status->rebootReasons === null ? 'unknown' : ($status->rebootReasons !== [] ? 'yes' : 'no'), + 'helper' => $status->helper->state, 'concerns' => $concerns, ]); diff --git a/lib/Config/ConfigLexicon.php b/lib/Config/ConfigLexicon.php index d13de9626..465dee5f6 100644 --- a/lib/Config/ConfigLexicon.php +++ b/lib/Config/ConfigLexicon.php @@ -32,6 +32,7 @@ class ConfigLexicon implements ILexicon { public const CACHED_OS_PHP_PROCESS = 'cached_os_php_process'; public const CACHED_OS_PHP_OUTDATED_SINCE = 'cached_os_php_outdated_since'; public const JOB_INTERVAL_OS_STATUS = 'job_interval_os_status'; + public const OS_HELPER_REPORT_PATH = 'os_helper_report_path'; public const OS_SECURITY_WARNING_DAYS = 'os_security_warning_days'; public const OS_SECURITY_ERROR_DAYS = 'os_security_error_days'; public const OS_REBOOT_WARNING_DAYS = 'os_reboot_warning_days'; @@ -111,6 +112,13 @@ public function getAppConfigs(): array { 60 * 60, 'How often the operating system status is collected, in seconds', ), + new Entry( + self::OS_HELPER_REPORT_PATH, + ValueType::STRING, + '/var/lib/serverinfo/os-report.json', + 'Where the optional root helper bin/serverinfo-os-report writes its report; an absolute path ending in .json', + lazy: true, + ), new Entry(self::OS_SECURITY_WARNING_DAYS, ValueType::INT, 3, 'Days a security update may be pending before a warning', lazy: true), new Entry(self::OS_SECURITY_ERROR_DAYS, ValueType::INT, 14, 'Days a security update may be pending before an error', lazy: true), new Entry(self::OS_REBOOT_WARNING_DAYS, ValueType::INT, 7, 'Days a reboot may be pending before a warning', lazy: true), diff --git a/lib/OsStatus/Helper/HelperReport.php b/lib/OsStatus/Helper/HelperReport.php new file mode 100644 index 000000000..15579c0e9 --- /dev/null +++ b/lib/OsStatus/Helper/HelperReport.php @@ -0,0 +1,150 @@ +|null $pendingUpdates + * @param list|null $restartServices + * @param list $rebootReasons + * @param list $errors + */ + public function __construct( + public readonly int $generatedAt, + public readonly string $helperVersion, + public readonly string $hostname, + public readonly ?int $bootTime, + public readonly ?int $listsRefreshedAt, + public readonly ?array $pendingUpdates, + public readonly ?array $restartServices, + public readonly array $rebootReasons, + /** Whether a paid extended support subscription is active, null when unknown */ + public readonly ?bool $subscriptionActive, + public readonly array $errors, + ) { + } + + /** + * @throws \InvalidArgumentException when required fields are missing or malformed + */ + public static function fromArray(array $data): self { + $generatedAt = $data['generatedAt'] ?? null; + $version = $data['helperVersion'] ?? null; + $hostname = $data['hostname'] ?? null; + if (!is_int($generatedAt) || !is_string($version) || preg_match('/^\d{1,5}\.\d{1,5}\.\d{1,5}$/', $version) !== 1 + || !is_string($hostname) || $hostname === '' || strlen($hostname) > 253) { + throw new \InvalidArgumentException('Required fields are missing'); + } + + $pendingUpdates = null; + if (is_array($data['pendingUpdates'] ?? null)) { + $pendingUpdates = self::mapList($data['pendingUpdates'], static fn (mixed $item): ?PendingUpdate => PendingUpdate::fromArray(self::capped($item))); + } + + $restartServices = null; + if (is_array($data['restartServices'] ?? null)) { + $restartServices = self::mapList( + $data['restartServices'], + static fn (mixed $unit): ?ServiceRestart => is_string($unit) ? ServiceRestart::fromArray(['unit' => $unit]) : null, + ); + } + + $rebootReasons = []; + if (is_array($data['rebootReasons'] ?? null)) { + $rebootReasons = self::mapList($data['rebootReasons'], static fn (mixed $item): ?RebootReason => RebootReason::fromArray(self::capped($item))); + } + + $errors = []; + if (is_array($data['errors'] ?? null)) { + $errors = self::mapList( + $data['errors'], + static fn (mixed $error): ?string => is_string($error) ? mb_substr($error, 0, 300) : null, + ); + $errors = array_slice($errors, 0, 20); + } + + $subscription = $data['subscription'] ?? null; + + return new self( + $generatedAt, + $version, + $hostname, + Values::int($data['bootTime'] ?? null), + Values::int($data['listsRefreshedAt'] ?? null), + $pendingUpdates, + $restartServices, + $rebootReasons, + is_array($subscription) && is_bool($subscription['active'] ?? null) ? $subscription['active'] : null, + $errors, + ); + } + + /** + * Drops strings longer than MAX_STRING from an item, also inside its + * lists, which are cut to MAX_NESTED entries. A required field that is + * dropped makes the item invalid. + */ + private static function capped(mixed $item): mixed { + if (!is_array($item)) { + return $item; + } + + $fits = static fn (mixed $value): bool => !is_string($value) || strlen($value) <= self::MAX_STRING; + foreach ($item as $key => $value) { + if (!$fits($value)) { + unset($item[$key]); + } elseif (is_array($value)) { + $item[$key] = array_slice(array_values(array_filter($value, $fits)), 0, self::MAX_NESTED); + } + } + + return $item; + } + + /** + * @template T + * @param array $items + * @param callable(mixed): (T|null) $map + * @return list + */ + private static function mapList(array $items, callable $map): array { + $mapped = []; + foreach (array_slice(array_values($items), 0, self::MAX_ITEMS) as $item) { + $value = $map($item); + if ($value !== null) { + $mapped[] = $value; + } + } + + return $mapped; + } +} diff --git a/lib/OsStatus/Helper/HelperReportReader.php b/lib/OsStatus/Helper/HelperReportReader.php new file mode 100644 index 000000000..c5a81dd96 --- /dev/null +++ b/lib/OsStatus/Helper/HelperReportReader.php @@ -0,0 +1,178 @@ +host->fileExists($path)) { + $state = $this->isOutsideOpenBasedir($path) || $this->isClosedDirectory(dirname($path)) + ? HelperState::STATE_UNREADABLE + : HelperState::STATE_ABSENT; + + return [new HelperState($state, $path), null]; + } + + $security = $this->securityState($path); + if ($security !== null) { + return [new HelperState($security, $path), null]; + } + + $content = $this->host->readFile($path, self::MAX_BYTES + 1); + if ($content === null) { + return [new HelperState(HelperState::STATE_UNREADABLE, $path), null]; + } + if (strlen($content) > self::MAX_BYTES) { + return [new HelperState(HelperState::STATE_INVALID, $path), null]; + } + + $data = json_decode($content, true, 16); + if (!is_array($data)) { + return [new HelperState(HelperState::STATE_INVALID, $path), null]; + } + if (($data['schema'] ?? null) !== HelperReport::SCHEMA) { + return [new HelperState(HelperState::STATE_UNSUPPORTED, $path), null]; + } + + try { + $report = HelperReport::fromArray($data); + } catch (\InvalidArgumentException) { + return [new HelperState(HelperState::STATE_INVALID, $path), null]; + } + + $state = match (true) { + $report->hostname !== $this->host->hostname() => HelperState::STATE_OTHER_HOST, + $bootTime !== null && $report->bootTime !== null && abs($report->bootTime - $bootTime) > self::BOOT_TIME_TOLERANCE => HelperState::STATE_PREVIOUS_BOOT, + $report->generatedAt > $now + self::FUTURE_TOLERANCE => HelperState::STATE_CLOCK_SKEW, + $now - $report->generatedAt > self::MAX_AGE => HelperState::STATE_STALE, + default => HelperState::STATE_OK, + }; + + $helperState = new HelperState( + $state, + $path, + $report->generatedAt, + $report->helperVersion, + version_compare($report->helperVersion, self::BUNDLED_VERSION, '<'), + $report->errors, + ); + + return [$helperState, $state === HelperState::STATE_OK ? $report : null]; + } + + /** + * The report and every directory above it must be owned by root, + * writable by no one else, sticky world-writable directories included, + * and no symbolic links: the rules bin/serverinfo-os-report checks the + * directories against before writing. Directories outside open_basedir + * cannot be inspected here and are left to the helper's check. + * + * @return HelperState::STATE_INSECURE|HelperState::STATE_UNREADABLE|null null when the path is secure + */ + private function securityState(string $path): ?string { + for ($checked = $path; ; $checked = dirname($checked)) { + if ($this->host->readLink($checked) !== null) { + return HelperState::STATE_INSECURE; + } + $ownership = $this->host->ownership($checked); + if ($ownership === null) { + if ($checked === $path || !$this->isOutsideOpenBasedir($checked)) { + return HelperState::STATE_UNREADABLE; + } + } elseif ($ownership['owner'] !== 0 || ($ownership['mode'] & 0o022) !== 0) { + return HelperState::STATE_INSECURE; + } + if ($checked === '/') { + return null; + } + } + } + + private function isOutsideOpenBasedir(string $path): bool { + $allowed = $this->host->openBasedir(); + if ($allowed === []) { + return false; + } + + // As PHP does: an entry is a directory whether or not it ends in a + // slash, and an entry naming the file itself allows it. + foreach ($allowed as $entry) { + $entry = rtrim($entry, '/'); + if ($path === $entry || str_starts_with($path, $entry . '/')) { + return false; + } + } + + return true; + } + + /** + * A directory of root's that neither group nor others may enter, so the + * web server cannot tell whether the report is in it. + */ + private function isClosedDirectory(string $directory): bool { + $ownership = $this->host->ownership($directory); + + return $ownership !== null + && $ownership['owner'] === 0 + && ($ownership['mode'] & 0o170000) === 0o040000 + && ($ownership['mode'] & 0o011) === 0; + } +} diff --git a/lib/OsStatus/Helper/HelperState.php b/lib/OsStatus/Helper/HelperState.php new file mode 100644 index 000000000..c589f8112 --- /dev/null +++ b/lib/OsStatus/Helper/HelperState.php @@ -0,0 +1,86 @@ + $errors problems the helper itself reported + */ + public function __construct( + public readonly string $state, + public readonly string $path, + public readonly ?int $generatedAt = null, + public readonly ?string $version = null, + /** The installed helper is older than the one bundled with the app */ + public readonly bool $outdated = false, + public readonly array $errors = [], + ) { + } + + /** + * @return array{state: string, path: string, generatedAt: ?int, version: ?string, outdated: bool, errors: list} + */ + public function toArray(): array { + return [ + 'state' => $this->state, + 'path' => $this->path, + 'generatedAt' => $this->generatedAt, + 'version' => $this->version, + 'outdated' => $this->outdated, + 'errors' => $this->errors, + ]; + } + + public static function fromArray(mixed $data, string $defaultPath): self { + if (!is_array($data) || !in_array($data['state'] ?? null, self::STATES, true)) { + return new self(self::STATE_ABSENT, $defaultPath); + } + + return new self( + $data['state'], + is_string($data['path'] ?? null) ? $data['path'] : $defaultPath, + Values::int($data['generatedAt'] ?? null), + Values::string($data['version'] ?? null), + ($data['outdated'] ?? false) === true, + Values::strings($data['errors'] ?? null), + ); + } +} diff --git a/lib/OsStatus/Host/IHost.php b/lib/OsStatus/Host/IHost.php index a8bf9cfde..de4892d65 100644 --- a/lib/OsStatus/Host/IHost.php +++ b/lib/OsStatus/Host/IHost.php @@ -45,6 +45,11 @@ public function modifiedAt(string $path): ?int; */ public function changedAt(string $path): ?int; + /** + * @return array{owner: int, mode: int}|null + */ + public function ownership(string $path): ?array; + public function readLink(string $path): ?string; /** @@ -83,6 +88,8 @@ public function environment(string $name): ?string; */ public function uname(string $mode): string; + public function hostname(): string; + /** * As PHP_OS_FAMILY, e.g. "Linux" or "BSD". */ diff --git a/lib/OsStatus/Host/LocalHost.php b/lib/OsStatus/Host/LocalHost.php index f6a95675a..607257cb6 100644 --- a/lib/OsStatus/Host/LocalHost.php +++ b/lib/OsStatus/Host/LocalHost.php @@ -83,6 +83,18 @@ public function changedAt(string $path): ?int { return $time === false ? null : $time; } + #[\Override] + public function ownership(string $path): ?array { + clearstatcache(true, $path); + $owner = @fileowner($path); + $mode = @fileperms($path); + if ($owner === false || $mode === false) { + return null; + } + + return ['owner' => $owner, 'mode' => $mode]; + } + #[\Override] public function readLink(string $path): ?string { $target = @readlink($path); @@ -129,6 +141,13 @@ public function uname(string $mode): string { return php_uname($mode); } + #[\Override] + public function hostname(): string { + $hostname = gethostname(); + + return is_string($hostname) && $hostname !== '' ? $hostname : php_uname('n'); + } + #[\Override] public function osFamily(): string { return PHP_OS_FAMILY; diff --git a/lib/OsStatus/OsStatus.php b/lib/OsStatus/OsStatus.php index 3e2c2bfbc..64e72149a 100644 --- a/lib/OsStatus/OsStatus.php +++ b/lib/OsStatus/OsStatus.php @@ -9,10 +9,13 @@ namespace OCA\ServerInfo\OsStatus; +use OCA\ServerInfo\OsStatus\Helper\HelperReportReader; +use OCA\ServerInfo\OsStatus\Helper\HelperState; use OCA\ServerInfo\OsStatus\Packages\AutomaticUpdates; use OCA\ServerInfo\OsStatus\Packages\HeldPackage; use OCA\ServerInfo\OsStatus\Packages\PendingUpdate; use OCA\ServerInfo\OsStatus\Reboot\RebootReason; +use OCA\ServerInfo\OsStatus\Restart\ServiceRestart; use OCA\ServerInfo\OsStatus\Support\SupportStatus; /** @@ -32,6 +35,7 @@ final class OsStatus { /** Source of a finding */ public const SOURCE_SYSTEM = 'system'; + public const SOURCE_HELPER = 'helper'; /** * @param self::STATE_* $state @@ -39,6 +43,7 @@ final class OsStatus { * @param self::SOURCE_*|null $updatesSource * @param list|null $held * @param list|null $rebootReasons + * @param list|null $restartServices * @param list|null $livePatches * @param list|null $failedUnits * @param array{all: ?string, security: ?string} $upgradeCommands @@ -64,6 +69,7 @@ public function __construct( public readonly ?int $lastUpgradeAt = null, public readonly AutomaticUpdates $automaticUpdates = new AutomaticUpdates(AutomaticUpdates::STATE_UNKNOWN), public readonly ?array $rebootReasons = null, + public readonly ?array $restartServices = null, public readonly ?array $livePatches = null, public readonly ?array $failedUnits = null, public readonly ?bool $timeSynchronized = null, @@ -72,6 +78,7 @@ public function __construct( public readonly ?string $apparmor = null, public readonly array $upgradeCommands = ['all' => null, 'security' => null], public readonly ?string $packageDatabase = null, + public readonly HelperState $helper = new HelperState(HelperState::STATE_ABSENT, HelperReportReader::DEFAULT_PATH), public readonly ?int $bootTime = null, public readonly array $diagnostics = [], ) { @@ -116,6 +123,7 @@ public function toArray(): array { 'lastUpgradeAt' => $this->lastUpgradeAt, 'automaticUpdates' => $this->automaticUpdates->toArray(), 'rebootReasons' => $this->rebootReasons === null ? null : array_map(static fn (RebootReason $r): array => $r->toArray(), $this->rebootReasons), + 'restartServices' => $this->restartServices === null ? null : array_map(static fn (ServiceRestart $s): array => $s->toArray(), $this->restartServices), 'livePatches' => $this->livePatches, 'failedUnits' => $this->failedUnits, 'timeSynchronized' => $this->timeSynchronized, @@ -124,6 +132,7 @@ public function toArray(): array { 'apparmor' => $this->apparmor, 'upgradeCommands' => $this->upgradeCommands, 'packageDatabase' => $this->packageDatabase, + 'helper' => $this->helper->toArray(), 'bootTime' => $this->bootTime, 'diagnostics' => $this->diagnostics, ]; @@ -140,7 +149,8 @@ public static function fromArray(mixed $data): ?self { $state = in_array($data['state'] ?? null, [self::STATE_OK, self::STATE_RESTRICTED, self::STATE_UNSUPPORTED], true) ? $data['state'] : self::STATE_OK; - $source = ($data['updatesSource'] ?? null) === self::SOURCE_SYSTEM ? self::SOURCE_SYSTEM : null; + $source = in_array($data['updatesSource'] ?? null, [self::SOURCE_SYSTEM, self::SOURCE_HELPER], true) + ? $data['updatesSource'] : null; $commands = is_array($data['upgradeCommands'] ?? null) ? $data['upgradeCommands'] : []; return new self( @@ -161,6 +171,7 @@ public static function fromArray(mixed $data): ?self { Values::int($data['lastUpgradeAt'] ?? null), AutomaticUpdates::fromArray($data['automaticUpdates'] ?? null), self::listOf($data['rebootReasons'] ?? null, static fn (mixed $item): ?RebootReason => RebootReason::fromArray($item)), + self::listOf($data['restartServices'] ?? null, static fn (mixed $item): ?ServiceRestart => ServiceRestart::fromArray($item)), self::stringList($data['livePatches'] ?? null), self::stringList($data['failedUnits'] ?? null), is_bool($data['timeSynchronized'] ?? null) ? $data['timeSynchronized'] : null, @@ -172,6 +183,7 @@ public static function fromArray(mixed $data): ?self { 'security' => is_string($commands['security'] ?? null) ? $commands['security'] : null, ], Values::string($data['packageDatabase'] ?? null), + HelperState::fromArray($data['helper'] ?? null, HelperReportReader::DEFAULT_PATH), Values::int($data['bootTime'] ?? null), self::stringList($data['diagnostics'] ?? null) ?? [], ); diff --git a/lib/OsStatus/OsStatusCollector.php b/lib/OsStatus/OsStatusCollector.php index d4733300a..f062a7bfb 100644 --- a/lib/OsStatus/OsStatusCollector.php +++ b/lib/OsStatus/OsStatusCollector.php @@ -9,10 +9,13 @@ namespace OCA\ServerInfo\OsStatus; +use OCA\ServerInfo\Config\ConfigLexicon; use OCA\ServerInfo\Os; use OCA\ServerInfo\OsStatus\Health\SecurityProbe; use OCA\ServerInfo\OsStatus\Health\SystemdProbe; use OCA\ServerInfo\OsStatus\Health\TimeSyncProbe; +use OCA\ServerInfo\OsStatus\Helper\HelperReport; +use OCA\ServerInfo\OsStatus\Helper\HelperReportReader; use OCA\ServerInfo\OsStatus\Host\IHost; use OCA\ServerInfo\OsStatus\Packages\AutomaticUpdates; use OCA\ServerInfo\OsStatus\Packages\IPackageManager; @@ -22,6 +25,7 @@ use OCA\ServerInfo\OsStatus\Reboot\CoreLibraryProbe; use OCA\ServerInfo\OsStatus\Reboot\KernelProbe; use OCA\ServerInfo\OsStatus\Reboot\RebootReason; +use OCA\ServerInfo\OsStatus\Restart\ServiceRestart; use OCA\ServerInfo\OsStatus\Support\SubscriptionProbe; use OCA\ServerInfo\OsStatus\Support\SupportStatus; use OCA\ServerInfo\OsStatus\Support\SupportTable; @@ -56,6 +60,7 @@ public function __construct( private SystemdProbe $systemd, private TimeSyncProbe $timeSync, private SecurityProbe $security, + private HelperReportReader $helperReader, private OsStatusStore $store, private LoggerInterface $logger, ) { @@ -91,12 +96,15 @@ public function collect(): OsStatus { $uptime = $this->probe('The boot time', fn (): int => $this->os->getUptime(), -1, $diagnostics); $bootTime = $uptime >= 0 ? $now - $uptime : null; + $helperPath = $this->appConfig->getAppValueString(ConfigLexicon::OS_HELPER_REPORT_PATH, HelperReportReader::DEFAULT_PATH); + [$helperState, $report] = $this->helperReader->read($helperPath, $bootTime, $now); + $support = $release !== null ? $this->probe('The support period', fn (): SupportStatus => $this->supportTable->lookup($release), SupportStatus::unknown(), $diagnostics) : SupportStatus::unknown(); if ($support->extended !== null) { $extended = $support->extended; - $support = $support->withExtendedActive($this->probe('The extended support subscription', fn (): ?bool => $this->subscriptions->isActive($extended), null, $diagnostics)); + $support = $support->withExtendedActive($this->probe('The extended support subscription', fn (): ?bool => $this->subscriptions->isActive($extended), null, $diagnostics) ?? $report?->subscriptionActive); } $packageManager = null; @@ -120,26 +128,33 @@ public function collect(): OsStatus { $diagnostics[] = 'Pending updates could not be determined; see the Nextcloud log.'; } } + $reportedUpdates = $report?->pendingUpdates; + if ($updates === null && $reportedUpdates !== null && $environment->managesPackages()) { + $updates = $reportedUpdates; + $updatesSource = OsStatus::SOURCE_HELPER; + } - $listsRefreshedAt = $packageManager !== null - ? $this->probe('The package list age', fn (): ?int => $packageManager->getListsRefreshedAt(), null, $diagnostics) - : null; + $listsRefreshedAt = $this->latest( + $packageManager !== null ? $this->probe('The package list age', fn (): ?int => $packageManager->getListsRefreshedAt(), null, $diagnostics) : null, + $report?->listsRefreshedAt, + ); // Without package lists the package manager knows of no newer versions at all. - if ($updates === [] && $listsRefreshedAt === null && in_array($packageManager?->getId(), OsVerdict::LISTS_AGE_MATTERS, true)) { + if ($updates === [] && $updatesSource === OsStatus::SOURCE_SYSTEM && $listsRefreshedAt === null && in_array($packageManager?->getId(), OsVerdict::LISTS_AGE_MATTERS, true)) { $updates = null; $updatesSource = null; $diagnostics[] = 'The package lists could not be found, so pending updates are unknown until the lists are refreshed.'; } $rebootReasons = $environment->managesPackages() - ? $this->probe('Whether a reboot is needed', fn (): array => $this->rebootReasons($packageManager, $environment, $bootTime), null, $diagnostics) + ? $this->probe('Whether a reboot is needed', fn (): array => $this->rebootReasons($packageManager, $environment, $bootTime, $report), null, $diagnostics) : null; + $restartServices = $environment->managesPackages() ? $report?->restartServices : null; - $classified = $packageManager?->classifiesSecurity() ?? false; - [$updates, $rebootReasons] = $this->probe( + $classified = $packageManager?->classifiesSecurity() ?? ($updatesSource === OsStatus::SOURCE_HELPER); + [$updates, $rebootReasons, $restartServices] = $this->probe( 'How long the findings have been pending', - fn (): array => $this->applyFirstSeen($updates, $classified, $rebootReasons, $now), - [$updates, $rebootReasons], + fn (): array => $this->applyFirstSeen($updates, $classified, $rebootReasons, $restartServices, $now), + [$updates, $rebootReasons, $restartServices], $diagnostics, ); @@ -172,6 +187,7 @@ public function collect(): OsStatus { ? $this->probe('The automatic updates', fn (): AutomaticUpdates => $packageManager->getAutomaticUpdates(), AutomaticUpdates::unknown(), $diagnostics) : AutomaticUpdates::unknown(), $rebootReasons, + $restartServices, $this->probe('The live kernel patches', fn (): ?array => $this->security->getLivePatches(), null, $diagnostics), $this->probe('The failed system services', fn (): ?array => $this->systemd->getFailedUnits(), null, $diagnostics), $timeSync['synchronized'], @@ -180,6 +196,7 @@ public function collect(): OsStatus { $this->probe('The AppArmor state', fn (): ?string => $this->security->getApparmor(), null, $diagnostics), $packageManager?->getUpgradeCommands() ?? ['all' => null, 'security' => null], $packageManager?->getPackageDatabasePath(), + $helperState, $bootTime, $diagnostics, ); @@ -228,7 +245,7 @@ public function collectAndStore(): ?OsStatus { /** * @return list */ - private function rebootReasons(?IPackageManager $packageManager, Environment $environment, ?int $bootTime): array { + private function rebootReasons(?IPackageManager $packageManager, Environment $environment, ?int $bootTime, ?HelperReport $report): array { $reasons = []; $add = static function (RebootReason $reason) use (&$reasons, $environment): void { if (!$environment->ownsKernel() && in_array($reason->kind, [RebootReason::KIND_KERNEL, RebootReason::KIND_KERNEL_REMOVED, RebootReason::KIND_MICROCODE], true)) { @@ -243,6 +260,9 @@ private function rebootReasons(?IPackageManager $packageManager, Environment $en foreach ($this->kernelProbe->getRebootReasons($bootTime) as $reason) { $add($reason); } + foreach ($report?->rebootReasons ?? [] as $reason) { + $add($reason); + } $hasDistributionAnswer = ($packageManager?->hasOwnRebootCheck() ?? false) || array_filter($reasons, static fn (RebootReason $r): bool => $r->kind === RebootReason::KIND_DISTRIBUTION) !== []; @@ -262,9 +282,10 @@ private function rebootReasons(?IPackageManager $packageManager, Environment $en * * @param list|null $updates * @param list|null $reasons - * @return array{0: list|null, 1: list|null} + * @param list|null $services + * @return array{0: list|null, 1: list|null, 2: list|null} */ - private function applyFirstSeen(?array $updates, bool $classified, ?array $reasons, int $now): array { + private function applyFirstSeen(?array $updates, bool $classified, ?array $reasons, ?array $services, int $now): array { $current = []; $scope = []; @@ -282,8 +303,15 @@ private function applyFirstSeen(?array $updates, bool $classified, ?array $reaso $current['reboot:' . $reason->key()] = $reason->since; } } + if ($services !== null) { + $scope[] = 'restart'; + foreach ($services as $service) { + $current['restart:' . $service->unit] = null; + } + } + if ($scope === []) { - return [$updates, $reasons]; + return [$updates, $reasons, $services]; } $seen = $this->store->firstSeen($current, $now, $scope); @@ -297,6 +325,10 @@ private function applyFirstSeen(?array $updates, bool $classified, ?array $reaso static fn (RebootReason $r): RebootReason => $r->withSince($seen['reboot:' . $r->key()] ?? $r->since), $reasons, ), + $services === null ? null : array_map( + static fn (ServiceRestart $s): ServiceRestart => $s->withSince($seen['restart:' . $s->unit] ?? null), + $services, + ), ]; } @@ -312,4 +344,10 @@ private static function sortUpdates(array $updates): array { return $updates; } + + private function latest(?int ...$times): ?int { + $times = array_filter($times, 'is_int'); + + return $times === [] ? null : max($times); + } } diff --git a/lib/OsStatus/Restart/ServiceRestart.php b/lib/OsStatus/Restart/ServiceRestart.php new file mode 100644 index 000000000..bd07dee10 --- /dev/null +++ b/lib/OsStatus/Restart/ServiceRestart.php @@ -0,0 +1,45 @@ + $this->unit, 'since' => $this->since, 'stack' => NextcloudStack::isStackService($this->unit)]; + } + + public static function fromArray(mixed $data): ?self { + if (!is_array($data) || !is_string($data['unit'] ?? null) || preg_match('/^[A-Za-z0-9@._:\\\\-]{1,200}$/', $data['unit']) !== 1) { + return null; + } + + return new self($data['unit'], Values::int($data['since'] ?? null)); + } + + public function withSince(?int $since): self { + return new self($this->unit, $since); + } +} diff --git a/lib/OsStatus/Verdict/Concern.php b/lib/OsStatus/Verdict/Concern.php index 5c30c6ea2..50c556b73 100644 --- a/lib/OsStatus/Verdict/Concern.php +++ b/lib/OsStatus/Verdict/Concern.php @@ -30,6 +30,7 @@ final class Concern { public const TIME_SYNC = 'time-sync'; /** Whether the stored status still describes the system */ public const FRESHNESS = 'freshness'; + public const HELPER = 'helper'; /** * @param self::LEVEL_* $level diff --git a/lib/OsStatus/Verdict/OsVerdict.php b/lib/OsStatus/Verdict/OsVerdict.php index 5acad4661..519a229b1 100644 --- a/lib/OsStatus/Verdict/OsVerdict.php +++ b/lib/OsStatus/Verdict/OsVerdict.php @@ -9,12 +9,14 @@ namespace OCA\ServerInfo\OsStatus\Verdict; +use OCA\ServerInfo\OsStatus\Helper\HelperState; use OCA\ServerInfo\OsStatus\NextcloudStack; use OCA\ServerInfo\OsStatus\OsStatus; use OCA\ServerInfo\OsStatus\Packages\AutomaticUpdates; use OCA\ServerInfo\OsStatus\Packages\PendingUpdate; use OCA\ServerInfo\OsStatus\Reboot\RebootReason; use OCA\ServerInfo\OsStatus\Restart\PhpProcessSample; +use OCA\ServerInfo\OsStatus\Restart\ServiceRestart; use OCA\ServerInfo\OsStatus\Support\SupportStatus; /** @@ -50,7 +52,7 @@ public function evaluate(OsStatus $status, ?PhpProcessSample $php, ?int $phpOutd $concerns[] = $this->updates($status, $thresholds, $now); $concerns[] = $this->reboot($status, $thresholds, $now); } - $concerns[] = $this->restart($php, $phpOutdatedSince, $thresholds, $now); + $concerns[] = $this->restart($status, $php, $phpOutdatedSince, $thresholds, $now); $concerns[] = $this->support($status, $thresholds, $now); if ($managed) { $concerns[] = $this->packageLists($status, $thresholds, $now); @@ -58,6 +60,7 @@ public function evaluate(OsStatus $status, ?PhpProcessSample $php, ?int $phpOutd } $concerns[] = $this->failedUnits($status); $concerns[] = $this->timeSync($status); + $concerns[] = $this->helper($status); $concerns[] = $this->freshness($status, $now, $systemCron, $collectInterval); return new Verdict($concerns); @@ -142,20 +145,36 @@ private function reboot(OsStatus $status, Thresholds $thresholds, int $now): Con ]); } - private function restart(?PhpProcessSample $php, ?int $phpOutdatedSince, Thresholds $thresholds, int $now): Concern { - if ($php === null) { + private function restart(OsStatus $status, ?PhpProcessSample $php, ?int $phpOutdatedSince, Thresholds $thresholds, int $now): Concern { + $services = $status->environment->managesPackages() ? $status->restartServices : null; + if ($php === null && $services === null) { return new Concern(Concern::RESTART, Concern::LEVEL_UNKNOWN); } - if (!$php->isOutdated()) { - return new Concern(Concern::RESTART, Concern::LEVEL_OK, ['php' => false, 'days' => null]); + + $phpOutdated = $php !== null && $php->isOutdated(); + $services ??= []; + $facts = [ + 'php' => $phpOutdated, + 'services' => count($services), + 'stack' => count(array_filter($services, static fn (ServiceRestart $s): bool => NextcloudStack::isStackService($s->unit))), + 'days' => null, + ]; + + if (!$phpOutdated && $services === []) { + return new Concern(Concern::RESTART, Concern::LEVEL_OK, $facts); } - $days = self::days($now - ($phpOutdatedSince ?? $now)); + $since = $now; + foreach ($services as $service) { + $since = min($since, $service->since ?? $now); + } + if ($phpOutdated) { + $since = min($since, $phpOutdatedSince ?? $now); + } + $days = self::days($now - $since); + $facts['days'] = $days; - return new Concern(Concern::RESTART, $days >= $thresholds->restartWarning ? Concern::LEVEL_WARNING : Concern::LEVEL_INFO, [ - 'php' => true, - 'days' => $days, - ]); + return new Concern(Concern::RESTART, $days >= $thresholds->restartWarning ? Concern::LEVEL_WARNING : Concern::LEVEL_INFO, $facts); } private function support(OsStatus $status, Thresholds $thresholds, int $now): Concern { @@ -238,6 +257,21 @@ private function timeSync(OsStatus $status): Concern { return new Concern(Concern::TIME_SYNC, $level, ['source' => $status->timeSource]); } + private function helper(OsStatus $status): Concern { + $helper = $status->helper; + $level = match ($helper->state) { + HelperState::STATE_OK => $helper->outdated || $helper->errors !== [] ? Concern::LEVEL_INFO : Concern::LEVEL_OK, + HelperState::STATE_ABSENT => Concern::LEVEL_OK, + HelperState::STATE_INSECURE => Concern::LEVEL_WARNING, + default => Concern::LEVEL_INFO, + }; + + return new Concern(Concern::HELPER, $level, [ + 'state' => $helper->state, + 'outdated' => $helper->outdated, + ]); + } + /** * Applies a pair of thresholds; below the warning threshold a finding is * worth showing but not worth an alert. diff --git a/tests/data/os/alma-9-dnf-check-update-pending b/tests/data/os/alma-9-dnf-check-update-pending new file mode 100644 index 000000000..69dc42654 --- /dev/null +++ b/tests/data/os/alma-9-dnf-check-update-pending @@ -0,0 +1,10 @@ + +curl-minimal.aarch64 7.76.1-40.el9_8.8 baseos +glibc.aarch64 2.34-283.el9_8 baseos +glibc-common.aarch64 2.34-283.el9_8 baseos +glibc-minimal-langpack.aarch64 2.34-283.el9_8 baseos +libcurl-minimal.aarch64 7.76.1-40.el9_8.8 baseos +openssl.aarch64 1:3.5.8-2.el9_8 baseos +openssl-fips-provider.aarch64 1:3.5.8-2.el9_8 baseos +openssl-libs.aarch64 1:3.5.8-2.el9_8 baseos +tzdata.noarch 2026e-1.el9_8 baseos diff --git a/tests/data/os/alma-9-dnf-updateinfo-security b/tests/data/os/alma-9-dnf-updateinfo-security new file mode 100644 index 000000000..d320318bd --- /dev/null +++ b/tests/data/os/alma-9-dnf-updateinfo-security @@ -0,0 +1,9 @@ +Last metadata expiration check: 0:11:04 ago on Mon Oct 19 18:12:41 2026. +ALSA-2026:80511 Moderate/Sec. curl-minimal-7.76.1-40.el9_8.8.aarch64 +ALSA-2026:79281 Moderate/Sec. glibc-2.34-283.el9_8.aarch64 +ALSA-2026:79281 Moderate/Sec. glibc-common-2.34-283.el9_8.aarch64 +ALSA-2026:79281 Moderate/Sec. glibc-minimal-langpack-2.34-283.el9_8.aarch64 +ALSA-2026:80511 Moderate/Sec. libcurl-minimal-7.76.1-40.el9_8.8.aarch64 +ALSA-2026:77396 Important/Sec. openssl-1:3.5.8-2.el9_8.aarch64 +ALSA-2026:77396 Important/Sec. openssl-libs-1:3.5.8-2.el9_8.aarch64 +ALSA-2026:75571 Important/Sec. sudo-1.9.17p2-3.el9_8.3.aarch64 diff --git a/tests/data/os/fedora-44-dnf-advisory-security b/tests/data/os/fedora-44-dnf-advisory-security new file mode 100644 index 000000000..b53994cf7 --- /dev/null +++ b/tests/data/os/fedora-44-dnf-advisory-security @@ -0,0 +1,5 @@ +Name Type Severity Package Issued +FEDORA-2026-12f3f3d569 security Important openssl-libs-1:3.5.9-1.fc44.aarch64 2026-10-03 01:09:41 +FEDORA-2026-7d4732cbab security Important sudo-1.9.17-10.p2.fc44.aarch64 2026-10-09 01:06:38 +FEDORA-2026-a06b828d65 security Moderate curl-8.18.0-14.fc44.aarch64 2026-10-14 01:20:20 +FEDORA-2026-a06b828d65 security Moderate libcurl-8.18.0-14.fc44.aarch64 2026-10-14 01:20:20 diff --git a/tests/data/os/fedora-44-dnf-check-update-pending b/tests/data/os/fedora-44-dnf-check-update-pending new file mode 100644 index 000000000..4b6bcb3a1 --- /dev/null +++ b/tests/data/os/fedora-44-dnf-check-update-pending @@ -0,0 +1,8 @@ +Upgrades +curl.aarch64 8.18.0-14.fc44 updates +glibc.aarch64 2.43-9.fc44 updates +glibc-common.aarch64 2.43-9.fc44 updates +glibc-minimal-langpack.aarch64 2.43-9.fc44 updates +libcurl.aarch64 8.18.0-14.fc44 updates +openssl-libs.aarch64 1:3.5.9-1.fc44 updates +tzdata.noarch 2026e-1.fc44 updates diff --git a/tests/lib/OsStatus/FakeHost.php b/tests/lib/OsStatus/FakeHost.php index 489d7296e..c0eac92cb 100644 --- a/tests/lib/OsStatus/FakeHost.php +++ b/tests/lib/OsStatus/FakeHost.php @@ -106,6 +106,11 @@ public function changedAt(string $path): ?int { return $this->changed[$path] ?? null; } + #[\Override] + public function ownership(string $path): ?array { + return $this->owners[$path] ?? null; + } + #[\Override] public function readLink(string $path): ?string { return $this->links[$path] ?? null; @@ -162,6 +167,11 @@ public function uname(string $mode): string { }; } + #[\Override] + public function hostname(): string { + return $this->host; + } + #[\Override] public function osFamily(): string { return $this->family; diff --git a/tests/lib/OsStatus/HelperReportReaderTest.php b/tests/lib/OsStatus/HelperReportReaderTest.php new file mode 100644 index 000000000..8aa0ee0cc --- /dev/null +++ b/tests/lib/OsStatus/HelperReportReaderTest.php @@ -0,0 +1,310 @@ +host = new FakeHost(); + $this->reader = new HelperReportReader($this->host); + $this->owned(self::PATH, 0o100644); + foreach (['/var/lib/serverinfo', '/var/lib', '/var', '/'] as $directory) { + $this->owned($directory, 0o40755); + } + } + + private function owned(string $path, int $mode, int $owner = 0): void { + $this->host->owners[$path] = ['owner' => $owner, 'mode' => $mode]; + } + + private function report(array $overrides = []): string { + return (string)json_encode(array_merge([ + 'schema' => 1, + 'helperVersion' => HelperReportReader::BUNDLED_VERSION, + 'generatedAt' => self::NOW - 3600, + 'hostname' => 'cloud.example.org', + 'bootTime' => self::BOOT + 3, + 'listsRefreshedAt' => self::NOW - 3600, + 'restartServices' => ['php8.3-fpm.service', 'bad unit; rm -rf /'], + 'rebootReasons' => [['kind' => 'kernel', 'detail' => '6.8.0-48-generic'], ['kind' => 'bogus']], + 'subscription' => ['kind' => 'suse-ltss', 'active' => true], + 'errors' => ['Refreshing the package lists with apt failed.'], + ], $overrides)); + } + + /** + * @return array{0: HelperState, 1: mixed} + */ + private function read(?string $content = null): array { + $this->host->files[self::PATH] = $content ?? $this->report(); + + return $this->reader->read(self::PATH, self::BOOT, self::NOW); + } + + public function testAValidReport(): void { + [$state, $report] = $this->read(); + + $this->assertSame(HelperState::STATE_OK, $state->state); + $this->assertFalse($state->outdated); + $this->assertSame(['Refreshing the package lists with apt failed.'], $state->errors); + $this->assertSame(['php8.3-fpm.service'], array_map(static fn ($s) => $s->unit, $report->restartServices)); + $this->assertCount(1, $report->rebootReasons); + $this->assertTrue($report->subscriptionActive); + } + + public function testNoReport(): void { + unset($this->host->owners[self::PATH]); + + [$state, $report] = $this->reader->read(self::PATH, self::BOOT, self::NOW); + + $this->assertSame(HelperState::STATE_ABSENT, $state->state); + $this->assertNull($report); + } + + public function testAReportTheWebServerCannotRead(): void { + [$state] = $this->reader->read(self::PATH, self::BOOT, self::NOW); + + $this->assertSame(HelperState::STATE_UNREADABLE, $state->state); + } + + public function testOutsideOpenBasedir(): void { + $this->host->basedir = ['/var/www/', '/tmp/']; + unset($this->host->owners[self::PATH]); + + $this->assertSame(HelperState::STATE_UNREADABLE, $this->reader->read(self::PATH, self::BOOT, self::NOW)[0]->state); + } + + public static function dataDirectories(): array { + return [ + 'only root may enter' => [0o40700, 0, HelperState::STATE_UNREADABLE], + 'only root may list' => [0o40711, 0, HelperState::STATE_ABSENT], + 'the group may enter' => [0o40750, 0, HelperState::STATE_ABSENT], + 'owned by someone else' => [0o40700, 1000, HelperState::STATE_ABSENT], + ]; + } + + /** + * A report that cannot be seen is unreadable rather than absent when the + * web server cannot enter its directory. + */ + #[DataProvider('dataDirectories')] + public function testAReportInADirectoryTheWebServerCannotEnter(int $mode, int $owner, string $expected): void { + unset($this->host->owners[self::PATH]); + $this->owned('/var/lib/serverinfo', $mode, $owner); + + $this->assertSame($expected, $this->reader->read(self::PATH, self::BOOT, self::NOW)[0]->state); + } + + public function testADirectoryThatCannotBeCheckedIsUnreadable(): void { + unset($this->host->owners['/var/lib/serverinfo']); + + [$state, $report] = $this->read(); + + $this->assertSame(HelperState::STATE_UNREADABLE, $state->state); + $this->assertNull($report); + } + + public static function dataOpenBasedir(): array { + return [ + 'the directory' => [['/var/lib/serverinfo'], HelperState::STATE_ABSENT], + 'the directory with a slash' => [['/var/lib/serverinfo/'], HelperState::STATE_ABSENT], + 'the file itself' => [['/var/www', '/var/lib/serverinfo/os-report.json'], HelperState::STATE_ABSENT], + 'everything' => [['/'], HelperState::STATE_ABSENT], + 'a directory whose name starts the same' => [['/var/lib/server'], HelperState::STATE_UNREADABLE], + 'a file whose name starts the same' => [['/var/lib/serverinfo/os-report'], HelperState::STATE_UNREADABLE], + ]; + } + + /** + * @param list $basedir + */ + #[DataProvider('dataOpenBasedir')] + public function testOpenBasedirEntries(array $basedir, string $expected): void { + $this->host->basedir = $basedir; + unset($this->host->owners[self::PATH]); + + $this->assertSame($expected, $this->reader->read(self::PATH, self::BOOT, self::NOW)[0]->state); + } + + public function testASlightlyFastClockIsTolerated(): void { + $this->assertSame(HelperState::STATE_OK, $this->read($this->report(['generatedAt' => self::NOW + 200]))[0]->state); + } + + public function testLongStringsAreNotTaken(): void { + $long = str_repeat('a', 256); + [$state, $report] = $this->read($this->report([ + 'hostname' => 'cloud.example.org', + 'pendingUpdates' => [ + ['name' => $long, 'candidate' => '1-1'], + ['name' => 'openssl', 'candidate' => $long], + [ + 'name' => 'glibc', 'candidate' => '2.39-1', 'installed' => $long, 'origin' => $long, 'severity' => $long, + 'security' => true, 'advisories' => [$long, ...array_map(static fn (int $i): string => 'USN-' . $i, range(1, 150))], + ], + ], + 'rebootReasons' => [['kind' => 'kernel', 'detail' => $long, 'packages' => [$long, 'linux-image']]], + ])); + + $this->assertSame(HelperState::STATE_OK, $state->state); + $this->assertCount(1, $report->pendingUpdates); + $update = $report->pendingUpdates[0]; + $this->assertSame(['glibc', '2.39-1', null, null, null, true], [$update->name, $update->candidateVersion, $update->installedVersion, $update->origin, $update->severity, $update->security]); + $this->assertCount(100, $update->advisories); + $this->assertSame('USN-1', $update->advisories[0]); + $this->assertNull($report->rebootReasons[0]->detail); + $this->assertSame(['linux-image'], $report->rebootReasons[0]->packages); + } + + public function testOverlongHostnamesOrVersionsAreInvalid(): void { + $this->assertSame(HelperState::STATE_INVALID, $this->read($this->report(['hostname' => str_repeat('a', 254)]))[0]->state); + $this->assertSame(HelperState::STATE_INVALID, $this->read($this->report(['helperVersion' => '1.0.' . str_repeat('1', 6)]))[0]->state); + } + + public static function dataInsecure(): array { + return [ + 'owned by the web server' => [self::PATH, 0o100644, 33], + 'group writable' => [self::PATH, 0o100664, 0], + 'world writable' => [self::PATH, 0o100646, 0], + 'directory owned by the web server' => ['/var/lib/serverinfo', 0o40755, 33], + 'directory world writable' => ['/var/lib/serverinfo', 0o41777, 0], + 'an ancestor owned by the web server' => ['/var/lib', 0o40755, 33], + 'an ancestor group writable' => ['/var', 0o40775, 0], + 'an ancestor world writable with the sticky bit' => ['/var', 0o41777, 0], + 'the root directory group writable' => ['/', 0o40775, 0], + ]; + } + + #[DataProvider('dataInsecure')] + public function testReportsOthersCouldForgeAreIgnored(string $path, int $mode, int $owner): void { + $this->owned($path, $mode, $owner); + + [$state, $report] = $this->read(); + + $this->assertSame(HelperState::STATE_INSECURE, $state->state); + $this->assertNull($report); + } + + public static function dataSymlinks(): array { + return [ + 'the report' => [self::PATH], + 'its directory' => ['/var/lib/serverinfo'], + 'an ancestor' => ['/var'], + ]; + } + + /** + * The helper writes a plain file and refuses symlinked directories, so a + * link anywhere on the path was not set up by it. + */ + #[DataProvider('dataSymlinks')] + public function testSymlinksOnThePathAreInsecure(string $link): void { + $this->host->links[$link] = '/srv/elsewhere'; + + [$state, $report] = $this->read(); + + $this->assertSame(HelperState::STATE_INSECURE, $state->state); + $this->assertNull($report); + } + + public function testAnAncestorThatCannotBeCheckedIsUnreadable(): void { + unset($this->host->owners['/var']); + + $this->assertSame(HelperState::STATE_UNREADABLE, $this->read()[0]->state); + } + + public static function dataOpenBasedirAncestors(): array { + return [ + 'only the report directory' => [['/var/lib/serverinfo/'], null, HelperState::STATE_OK], + 'an ancestor within open_basedir is checked' => [['/var/lib'], 33, HelperState::STATE_INSECURE], + 'an ancestor within open_basedir that cannot be checked' => [['/var/lib/'], null, HelperState::STATE_UNREADABLE], + ]; + } + + /** + * Directories open_basedir hides from PHP cannot be inspected; the ones + * it allows are. + * + * @param list $basedir + * @param int|null $libOwner owner of /var/lib, null when it cannot be checked + */ + #[DataProvider('dataOpenBasedirAncestors')] + public function testAncestorsOutsideOpenBasedir(array $basedir, ?int $libOwner, string $expected): void { + $this->host->basedir = $basedir; + foreach (['/var/lib', '/var', '/'] as $directory) { + unset($this->host->owners[$directory]); + } + if ($libOwner !== null) { + $this->owned('/var/lib', 0o40755, $libOwner); + } + + $this->assertSame($expected, $this->read()[0]->state); + } + + public static function dataRejected(): array { + $base = [ + 'schema' => 1, 'helperVersion' => '1.0.0', 'generatedAt' => self::NOW - 60, + 'hostname' => 'cloud.example.org', 'bootTime' => self::BOOT, + ]; + + return [ + 'not json' => ['{"schema": 1,', HelperState::STATE_INVALID], + 'not an object' => ['"report"', HelperState::STATE_INVALID], + 'future schema' => [json_encode(['schema' => 2] + $base), HelperState::STATE_UNSUPPORTED], + 'missing host' => [json_encode(array_diff_key($base, ['hostname' => 1])), HelperState::STATE_INVALID], + 'bad version' => [json_encode(['helperVersion' => 'latest'] + $base), HelperState::STATE_INVALID], + 'other host' => [json_encode(['hostname' => 'elsewhere'] + $base), HelperState::STATE_OTHER_HOST], + 'previous boot' => [json_encode(['bootTime' => self::BOOT - 86400] + $base), HelperState::STATE_PREVIOUS_BOOT], + 'stale' => [json_encode(['generatedAt' => self::NOW - 27 * 3600] + $base), HelperState::STATE_STALE], + 'from the future' => [json_encode(['generatedAt' => self::NOW + 3600] + $base), HelperState::STATE_CLOCK_SKEW], + 'too large' => [json_encode($base + ['padding' => str_repeat('x', 1024 * 1024)]), HelperState::STATE_INVALID], + 'too deep' => [str_repeat('[', 40) . str_repeat(']', 40), HelperState::STATE_INVALID], + ]; + } + + #[DataProvider('dataRejected')] + public function testRejectedReports(string $content, string $expected): void { + [$state, $report] = $this->read($content); + + $this->assertSame($expected, $state->state); + $this->assertNull($report); + } + + public function testAnOlderHelperIsFlagged(): void { + [$state] = $this->read($this->report(['helperVersion' => '0.9.0'])); + + $this->assertSame(HelperState::STATE_OK, $state->state); + $this->assertTrue($state->outdated); + } + + public function testUnsafePathsFallBackToTheDefault(): void { + $this->assertSame(HelperReportReader::DEFAULT_PATH, HelperReportReader::sanitizePath('/etc/shadow')); + $this->assertSame(HelperReportReader::DEFAULT_PATH, HelperReportReader::sanitizePath('/var/lib/../../etc/x.json')); + $this->assertSame(HelperReportReader::DEFAULT_PATH, HelperReportReader::sanitizePath('relative.json')); + $this->assertSame('/srv/reports/os.json', HelperReportReader::sanitizePath('/srv/reports/os.json')); + } + + public function testBundledVersionMatchesTheScript(): void { + $script = (string)file_get_contents(__DIR__ . '/../../../bin/serverinfo-os-report'); + + $this->assertMatchesRegularExpression('/^VERSION=' . preg_quote(HelperReportReader::BUNDLED_VERSION, '/') . '$/m', $script); + $this->assertMatchesRegularExpression('/^OUTPUT=' . preg_quote(HelperReportReader::DEFAULT_PATH, '/') . '$/m', $script); + } +} diff --git a/tests/lib/OsStatus/HelperScriptTest.php b/tests/lib/OsStatus/HelperScriptTest.php new file mode 100644 index 000000000..344805dd7 --- /dev/null +++ b/tests/lib/OsStatus/HelperScriptTest.php @@ -0,0 +1,564 @@ + */ + private array $temporary = []; + + protected function setUp(): void { + parent::setUp(); + $this->runner = new CommandRunner(); + if (!$this->runner->isAvailable() || $this->runner->resolve('sh') === null) { + $this->markTestSkipped('No shell to run'); + } + } + + private function runScript(string ...$arguments): array { + $result = $this->runner->run('sh', [realpath(self::SCRIPT) ?: self::SCRIPT, ...$arguments], 30); + $this->assertNotNull($result); + + return [$result->exitCode, $result->stdout, $result->stderr]; + } + + public function testIsValidPosixShell(): void { + $this->assertSame(0, $this->runner->run('sh', ['-n', realpath(self::SCRIPT) ?: self::SCRIPT], 10)?->exitCode); + } + + public function testVersion(): void { + $this->assertSame([0, HelperReportReader::BUNDLED_VERSION . "\n", ''], $this->runScript('--version')); + } + + public function testHelp(): void { + [$exit, $stdout] = $this->runScript('--help'); + + $this->assertSame(0, $exit); + $this->assertStringContainsString('--refresh', $stdout); + $this->assertStringContainsString('--random-delay', $stdout); + } + + public function testUnknownOptions(): void { + $this->assertSame(1, $this->runScript('--install-everything')[0]); + } + + public function testUnsafeOutputPathsAreRefusedBeforeAnythingElse(): void { + foreach (['relative.json', '/etc/shadow', '/var/lib/../../etc/x.json', '/var/lib/a b.json', '/var/lib/x.json;id'] as $path) { + [$exit, , $stderr] = $this->runScript('--output', $path); + $this->assertSame(1, $exit, $path); + $this->assertStringNotContainsString('must run as root', $stderr, $path); + } + } + + /** + * Runs shell code with the script's functions loaded; the arguments are + * $1, $2, ... to the code. + * + * @return array{0: int, 1: string, 2: string} exit code, stdout and stderr + */ + private function functions(string $code, string ...$arguments): array { + $script = realpath(self::SCRIPT) ?: self::SCRIPT; + $result = $this->runner->run('sh', [ + '-c', + 'SERVERINFO_OS_REPORT_FUNCTIONS_ONLY=1; . "$0"; ' . $code, + $script, ...$arguments, + ], 30); + $this->assertNotNull($result); + + return [$result->exitCode, $result->stdout, $result->stderr]; + } + + /** + * A directory for one test, removed afterwards. + */ + private function temporaryDirectory(): string { + $directory = sys_get_temp_dir() . '/serverinfo-helper-' . bin2hex(random_bytes(6)); + mkdir($directory, 0o700); + $this->temporary[] = $directory; + + return realpath($directory) ?: $directory; + } + + /** + * Writes a shell script standing in for a system command. + * + * @param list $lines + */ + private function fakeCommand(string $directory, string $name, array $lines): void { + file_put_contents($directory . '/' . $name, implode("\n", ['#!/bin/sh', ...$lines]) . "\n"); + chmod($directory . '/' . $name, 0o755); + } + + protected function tearDown(): void { + foreach ($this->temporary as $directory) { + $this->runner->run('rm', ['-rf', $directory], 10); + } + parent::tearDown(); + } + + /** + * Runs dnf_updates_json from the script on captured output. + */ + private function dnfUpdates(string $checkUpdate, string $advisories, string $installed): array { + [$exit, $stdout, $stderr] = $this->functions('dnf_updates_json "$1" "$2" "$3"', $checkUpdate, $advisories, $installed); + $this->assertSame(0, $exit, $stderr); + + $report = HelperReport::fromArray([ + 'generatedAt' => 1, 'helperVersion' => '1.0.0', 'hostname' => 'h', + 'pendingUpdates' => json_decode($stdout, true, 16, JSON_THROW_ON_ERROR), + ]); + + $updates = []; + foreach ($report->pendingUpdates ?? [] as $update) { + $updates[$update->name] = [$update->installedVersion, $update->candidateVersion, $update->security, $update->advisories, $update->severity]; + } + + return $updates; + } + + public function testDnf4PendingUpdatesForTheReport(): void { + $updates = $this->dnfUpdates( + FakeHost::fixture('alma-9-dnf-check-update-pending'), + FakeHost::fixture('alma-9-dnf-updateinfo-security'), + "glibc 0:2.34-275.el9_8\nopenssl-libs 1:3.5.8-1.el9_8\n", + ); + + $this->assertCount(9, $updates); + $this->assertSame(['2.34-275.el9_8', '2.34-283.el9_8', true, ['ALSA-2026:79281'], 'Moderate'], $updates['glibc']); + $this->assertSame(['1:3.5.8-1.el9_8', '1:3.5.8-2.el9_8', true, ['ALSA-2026:77396'], 'Important'], $updates['openssl-libs']); + $this->assertSame([null, '2026e-1.el9_8', false, [], null], $updates['tzdata']); + $this->assertArrayNotHasKey('sudo', $updates, 'An advisory alone does not make an update pending'); + } + + public function testDnf5PendingUpdatesForTheReport(): void { + $updates = $this->dnfUpdates( + FakeHost::fixture('fedora-44-dnf-check-update-pending'), + FakeHost::fixture('fedora-44-dnf-advisory-security'), + '', + ); + + $this->assertSame(['curl', 'glibc', 'glibc-common', 'glibc-minimal-langpack', 'libcurl', 'openssl-libs', 'tzdata'], array_keys($updates)); + $this->assertSame([null, '1:3.5.9-1.fc44', true, ['FEDORA-2026-12f3f3d569'], 'Important'], $updates['openssl-libs']); + $this->assertFalse($updates['glibc'][2]); + } + + public function testDnfOutputThatIsNotPlainIsDropped(): void { + $updates = $this->dnfUpdates( + "evil\",\"x.x86_64 1-1 repo\nfine.noarch 1-2 base\"os\nok.noarch 2-1 base\n", + 'RHSA-1"]} Important/Sec. ok-2-1.noarch', + '', + ); + + $this->assertSame(['ok'], array_keys($updates)); + $this->assertSame([], $updates['ok'][3]); + } + + /** + * dnf 4 wraps a row when a name or version is wider than its column; + * architectures are not limited to a known list. + */ + public function testDnf4WrappedRowsAndAnyArchitecture(): void { + $checkUpdate = <<<'EOT' + Last metadata expiration check: 0:01:02 ago on Mon Oct 19 18:12:41 2026. + + glibc.x86_64_v2 2.39-58.el10_1 baseos + rhel-9-a-very-long-package-name-for-testing.x86_64 + 1.2.3-4.el9 rhel-9-for-x86_64-appstream-rpms + long-version.noarch 1:20261022.0.1234567890-1.el9.something_long + rhel-9-for-x86_64-baseos-rpms + a-package-with-both-columns-too-wide.aarch64 + 1:20261022.0.1234567890-1.el9.something_long + rhel-9-for-aarch64-appstream-rpms + python3.11-libs.ppc64 3.11.9-1.el9 appstream + zlib.s390 1.2.11-41.el9 baseos + orphan-line.noarch + tzdata.noarch 2026e-1.el9 baseos + Obsoleting Packages + obsoleting.noarch 1-1 baseos + EOT; + + $updates = $this->dnfUpdates($checkUpdate, '', ''); + + $this->assertSame([ + 'glibc' => '2.39-58.el10_1', + 'rhel-9-a-very-long-package-name-for-testing' => '1.2.3-4.el9', + 'long-version' => '1:20261022.0.1234567890-1.el9.something_long', + 'a-package-with-both-columns-too-wide' => '1:20261022.0.1234567890-1.el9.something_long', + 'python3.11-libs' => '3.11.9-1.el9', + 'zlib' => '1.2.11-41.el9', + 'tzdata' => '2026e-1.el9', + ], array_map(static fn (array $update): string => $update[1], $updates)); + } + + public function testDnfNeedsRestartingReadsFromTheCache(): void { + $directory = $this->temporaryDirectory(); + $this->fakeCommand($directory, 'dnf', [ + 'printf "%s\n" "$*" > "$CAPTURE/arguments"', + 'echo nginx.service', + ]); + + [$exit, $stdout, $stderr] = $this->functions('CAPTURE=$1; export CAPTURE; PATH="$1:$PATH"; from_dnf; printf "%s" "$SERVICES"', $directory); + + $this->assertSame([0, "nginx.service\n"], [$exit, $stdout], $stderr); + $this->assertSame("-q --cacheonly needs-restarting -s\n", file_get_contents($directory . '/arguments')); + } + + public function testInstalledVersionsThatAreNotPlainAreDropped(): void { + [$exit, $stdout, $stderr] = $this->functions( + 'dnf_updates_json "$1" "" "$2"', + "ok.noarch 2-1 base\nfine.noarch 3-1 base\n", + "ok 0:1-1\\\"]\nfine 0:2-1\n", + ); + + $this->assertSame(0, $exit, $stderr); + $updates = json_decode($stdout, true, 16, JSON_THROW_ON_ERROR); + $this->assertSame([null, '2-1'], array_column($updates, 'installed')); + } + + public function testNeedrestartBatchOutput(): void { + $output = implode("\n", [ + 'NEEDRESTART-VER: 3.6', + 'NEEDRESTART-KCUR: 6.8.0-45-generic', + 'NEEDRESTART-KEXP: 6.8.0-48-generic', + 'NEEDRESTART-KSTA: 3', + 'NEEDRESTART-UCSTA: 2', + 'NEEDRESTART-SVC: php8.3-fpm.service', + 'NEEDRESTART-SVC: ssh', + 'NEEDRESTART-SVC: php8.3-fpm.service', + 'NEEDRESTART-SVC: bad;unit', + 'NEEDRESTART-SESS: frank @ session #3', + ]); + + [$exit, $stdout] = $this->functions('parse_needrestart "$1"; printf "%s|%s" "$SERVICES" "$REBOOT_REASONS"', $output); + + $this->assertSame(0, $exit); + $this->assertSame("php8.3-fpm.service\nssh.service\n|" + . '{"kind":"kernel","detail":"6.8.0-48-generic"},{"kind":"microcode","detail":null}', $stdout); + } + + public function testNeedrestartWithoutKernelOrMicrocodeFindings(): void { + [$exit, $stdout] = $this->functions( + 'parse_needrestart "$1"; printf "%s|%s" "$SERVICES" "$REBOOT_REASONS"', + "NEEDRESTART-VER: 3.11\nNEEDRESTART-KCUR: 7.0.0-38-generic\nNEEDRESTART-KEXP: 7.0.0-38-generic\nNEEDRESTART-KSTA: 1\n", + ); + + $this->assertSame([0, '|'], [$exit, $stdout]); + } + + public function testOutputThatIsNotNeedrestartsIsRejected(): void { + $this->assertSame(1, $this->functions('parse_needrestart "$1"', "Scanning processes...\n")[0]); + } + + /** + * needrestart runs with a configuration that turns off its interpreter + * scan, read from a pipe. + */ + public function testNeedrestartRunsWithoutInterpreterScan(): void { + $directory = $this->temporaryDirectory(); + $this->fakeCommand($directory, 'needrestart', [ + 'printf "%s\n" "$*" > "$CAPTURE/arguments"', + 'cat "$2" > "$CAPTURE/config"', + 'printf "NEEDRESTART-VER: 3.6\nNEEDRESTART-SVC: nginx.service\n"', + ]); + + [$exit, $stdout, $stderr] = $this->functions( + 'CAPTURE=$1; export CAPTURE; PATH="$1:$PATH"; from_needrestart; printf "%s" "$SERVICES"', + $directory, + ); + + $this->assertSame([0, "nginx.service\n"], [$exit, $stdout], $stderr); + $this->assertSame("-c /dev/stdin -b -r l\n", file_get_contents($directory . '/arguments')); + $config = (string)file_get_contents($directory . '/config'); + $this->assertStringContainsString('$nrconf{interpscan} = 0;', $config); + + if ($this->runner->resolve('perl') === null) { + return; + } + // Evaluated the way needrestart evaluates its configuration. + $result = $this->runner->run('perl', ['-e', implode(' ', [ + 'our %nrconf = (interpscan => 1, sendnotify => 1);', + 'eval do { local $/; open my $fh, $ARGV[0] or die "ERROR: $!\n"; my $cfg = <$fh>; close($fh); $cfg; };', + 'die "Error parsing: $@" if $@;', + 'print "$nrconf{interpscan} $nrconf{sendnotify}";', + ]), $directory . '/config'], 10); + $this->assertSame([0, '0 0'], [$result?->exitCode, $result?->stdout], (string)$result?->stderr); + } + + public static function dataCgroups(): array { + return [ + 'cgroup v2' => ["0::/system.slice/php8.3-fpm.service\n", 'php8.3-fpm.service'], + 'nested slice' => ["0::/system.slice/system-getty.slice/getty@tty1.service\n", 'getty@tty1.service'], + 'cgroup v1' => ["12:pids:/system.slice/nginx.service\n1:name=systemd:/system.slice/nginx.service\n", 'nginx.service'], + 'hybrid' => ["1:name=systemd:/system.slice/nginx.service\n0::/system.slice/nginx.service\n", 'nginx.service'], + 'a user unit named like a system one' => ["0::/user.slice/user-1000.slice/user@1000.service/app.slice/php8.3-fpm.service\n", ''], + 'a user unit in cgroup v1' => ["1:name=systemd:/user.slice/user-1000.slice/user@1000.service/php8.3-fpm.service\n", ''], + 'the user manager' => ["0::/user.slice/user-1000.slice/user@1000.service/init.scope\n", ''], + 'a login session' => ["0::/user.slice/user-1000.slice/session-3.scope\n", ''], + 'a delegated subtree' => ["0::/system.slice/docker.service/payload\n", ''], + 'init' => ["0::/init.scope\n", ''], + ]; + } + + #[DataProvider('dataCgroups')] + public function testOnlySystemServicesAreTakenFromCgroups(string $cgroup, string $unit): void { + $file = $this->temporaryDirectory() . '/cgroup'; + file_put_contents($file, $cgroup); + + $this->assertSame([0, $unit === '' ? '' : $unit . "\n"], array_slice($this->functions('system_unit "$1"', $file), 0, 2)); + } + + /** + * Shell code that replaces stat(1) with the owner and mode given as + * $2 and $3 for the directory $1, and as $4 and $5 for anything else. + */ + private const FAKE_STAT = 'stat() { if [ "$3" = "$DIR" ]; then o=$DO m=$DM; else o=$PO m=$PM; fi; case "$2" in %u) echo "$o" ;; *) echo "$m" ;; esac; }; DIR=$1 DO=$2 DM=$3 PO=$4 PM=$5; '; + + public static function dataDirectories(): array { + return [ + 'root only' => ['0', '755', '0', '755', ''], + 'setgid, sticky and closed modes' => ['0', '2750', '0', '1755', ''], + 'directory owned by the web server' => ['33', '755', '0', '755', '/reports must be owned by root'], + 'directory group writable' => ['0', '775', '0', '755', '/reports must not be writable by group or others'], + 'directory world writable' => ['0', '757', '0', '755', '/reports must not be writable by group or others'], + 'parent owned by a user' => ['0', '755', '1000', '755', ' must be owned by root'], + 'parent world writable' => ['0', '755', '0', '1777', ' must not be writable by group or others'], + 'parent group writable, setgid' => ['0', '755', '0', '2775', ' must not be writable by group or others'], + ]; + } + + #[DataProvider('dataDirectories')] + public function testReportDirectoryMustBeRootsAlone(string $owner, string $mode, string $parentOwner, string $parentMode, string $error): void { + $directory = $this->temporaryDirectory() . '/reports'; + + [$exit, $stdout, $stderr] = $this->functions( + self::FAKE_STAT . 'secure_directory "$1" && echo secured', + $directory, $owner, $mode, $parentOwner, $parentMode, + ); + + if ($error === '') { + $this->assertSame([0, "secured\n"], [$exit, $stdout], $stderr); + $this->assertDirectoryExists($directory); + } else { + $this->assertSame(1, $exit); + $this->assertStringContainsString($error, $stderr); + } + } + + /** + * Shell code that replaces stat(1) with owner $2 and mode $3 for the + * path $1, and root and 755 for anything else. + */ + private const FAKE_STAT_ONE = 'stat() { o=0 m=755; if [ "$3" = "$CHECKED" ]; then o=$CO m=$CM; fi; case "$2" in %u) echo "$o" ;; *) echo "$m" ;; esac; }; CHECKED=$1 CO=$2 CM=$3; '; + + public static function dataAncestors(): array { + return [ + 'root only' => ['0', '755', ''], + 'owned by the web server' => ['33', '755', ' must be owned by root'], + 'group writable' => ['0', '775', ' must not be writable by group or others'], + 'world writable with the sticky bit, like /tmp' => ['0', '1777', ' must not be writable by group or others'], + ]; + } + + /** + * Every directory above the report's is checked, and nothing is created + * below one that fails. + */ + #[DataProvider('dataAncestors')] + public function testEveryDirectoryAboveTheReportIsChecked(string $owner, string $mode, string $error): void { + $base = $this->temporaryDirectory(); + mkdir($base . '/a'); + + [$exit, $stdout, $stderr] = $this->functions( + self::FAKE_STAT_ONE . 'secure_directory "$4" && echo secured', + $base . '/a', $owner, $mode, $base . '/a/b/reports', + ); + + if ($error === '') { + $this->assertSame([0, "secured\n"], [$exit, $stdout], $stderr); + $this->assertDirectoryExists($base . '/a/b/reports'); + } else { + $this->assertSame(1, $exit); + $this->assertStringContainsString($base . '/a' . $error, $stderr); + $this->assertDirectoryDoesNotExist($base . '/a/b'); + } + } + + public function testTheWalkReachesTheRootDirectory(): void { + $directory = $this->temporaryDirectory(); + + [$exit, , $stderr] = $this->functions(self::FAKE_STAT_ONE . 'secure_directory "$4"', '/', '0', '775', $directory); + + $this->assertSame(1, $exit); + $this->assertStringContainsString('/ must not be writable by group or others', $stderr); + } + + public function testASymlinkedAncestorIsRefused(): void { + $base = $this->temporaryDirectory(); + mkdir($base . '/real'); + symlink($base . '/real', $base . '/link'); + + [$exit, , $stderr] = $this->functions(self::FAKE_STAT_ONE . 'secure_directory "$4"', '', '0', '755', $base . '/link/sub/reports'); + + $this->assertSame(1, $exit); + $this->assertStringContainsString($base . '/link is a symbolic link', $stderr); + $this->assertSame(['.', '..'], scandir($base . '/real')); + } + + public function testASymlinkedReportDirectoryIsRefused(): void { + $base = $this->temporaryDirectory(); + mkdir($base . '/elsewhere'); + symlink($base . '/elsewhere', $base . '/reports'); + + [$exit, , $stderr] = $this->functions(self::FAKE_STAT . 'write_report "{}" "$1/os-report.json"', $base . '/reports', '0', '755', '0', '755'); + + $this->assertSame(1, $exit); + $this->assertStringContainsString('is a symbolic link', $stderr); + $this->assertSame(['.', '..'], scandir($base . '/elsewhere')); + } + + public function testTheReportReplacesASymlinkInsteadOfFollowingIt(): void { + $directory = $this->temporaryDirectory(); + file_put_contents($directory . '/victim', 'keep'); + symlink($directory . '/victim', $directory . '/os-report.json'); + + [$exit, , $stderr] = $this->functions(self::FAKE_STAT . 'write_report "{\"schema\": 1}" "$1/os-report.json"', $directory, '0', '755', '0', '755'); + + $this->assertSame(0, $exit, $stderr); + $this->assertSame('keep', file_get_contents($directory . '/victim')); + $this->assertFalse(is_link($directory . '/os-report.json')); + $this->assertSame("{\"schema\": 1}\n", file_get_contents($directory . '/os-report.json')); + $this->assertSame(0o644, fileperms($directory . '/os-report.json') & 0o777); + $this->assertSame(['.', '..', 'os-report.json', 'victim'], scandir($directory), 'No temporary file is left'); + } + + public function testTheReportIsNeverMovedIntoADirectory(): void { + $directory = $this->temporaryDirectory(); + mkdir($directory . '/os-report.json'); + mkdir($directory . '/elsewhere'); + symlink($directory . '/elsewhere', $directory . '/linked.json'); + + foreach (['os-report.json', 'linked.json'] as $name) { + [$exit, , $stderr] = $this->functions(self::FAKE_STAT . 'write_report "{}" "$1/' . $name . '"', $directory, '0', '755', '0', '755'); + + $this->assertSame(1, $exit, $name); + $this->assertStringContainsString('is a directory', $stderr, $name); + } + $this->assertSame(['.', '..'], scandir($directory . '/os-report.json')); + $this->assertSame(['.', '..'], scandir($directory . '/elsewhere')); + $this->assertSame(['.', '..', 'elsewhere', 'linked.json', 'os-report.json'], scandir($directory)); + } + + public function testASignalRemovesTheTemporaryReportAndFails(): void { + $directory = $this->temporaryDirectory(); + + [$exit, $stdout] = $this->functions( + 'set_traps; TEMPORARY=$1/.os-report.test; : > "$TEMPORARY"; kill -TERM $$; echo still running', + $directory, + ); + + $this->assertSame([1, ''], [$exit, $stdout]); + $this->assertSame(['.', '..'], scandir($directory)); + } + + public static function dataTimeouts(): array { + return [ + 'coreutils and busybox 1.30 or later' => [':', "-k 30 300 echo run\n"], + 'timeout without -k' => ['[ "$1" = -k ] && exit 125', "300 echo run\n"], + 'busybox before 1.30' => ['exit 1', ''], + ]; + } + + /** + * Commands get a kill timeout where timeout(1) supports one, and run + * without a limit where it does not understand the arguments at all. + */ + #[DataProvider('dataTimeouts')] + public function testCommandsAreTimeLimitedAsFarAsTimeoutAllows(string $behaviour, string $called): void { + $directory = $this->temporaryDirectory(); + $this->fakeCommand($directory, 'timeout', [ + $behaviour, + 'case "$*" in *" true") ;; *) printf "%s\n" "$*" >> "$CAPTURE/calls" ;; esac', + '[ "$1" = -k ] && shift 2', + 'shift', + 'exec "$@"', + ]); + + [$exit, $stdout, $stderr] = $this->functions('CAPTURE=$1; export CAPTURE; PATH="$1:$PATH"; run_limited 300 echo run', $directory); + + $this->assertSame([0, "run\n"], [$exit, $stdout], $stderr); + $this->assertSame($called, (string)@file_get_contents($directory . '/calls')); + } + + public function testCommandsDoNotInheritTheLock(): void { + [$exit] = $this->functions('exec 9>/dev/null; TIMEOUT_MODE=none; run_limited 5 sh -c "echo held >&9"'); + + $this->assertNotSame(0, $exit); + } + + public static function dataLocks(): array { + return [ + 'free' => ['exit 0', [0, "running\n"]], + 'held by another run' => ['exit 1', [0, '']], + ]; + } + + #[DataProvider('dataLocks')] + public function testOnlyOneRunAtATime(string $flock, array $expected): void { + $directory = $this->temporaryDirectory(); + $this->fakeCommand($directory, 'flock', ['[ "$*" = "-n 9" ] || exit 2', $flock]); + + $result = $this->functions('LOCK=$1/os-report.lock; PATH="$1:$PATH"; take_lock; echo running', $directory); + + $this->assertSame($expected, array_slice($result, 0, 2), $result[2]); + $this->assertFileExists($directory . '/os-report.lock'); + } + + public function testRunsUnlockedWithoutFlock(): void { + $directory = $this->temporaryDirectory(); + $dirname = $this->runner->resolve('dirname'); + $this->assertNotNull($dirname); + symlink($dirname, $directory . '/dirname'); + + [$exit, $stdout] = $this->functions('LOCK=$1/os-report.lock; PATH=$1; take_lock; echo running', $directory); + + $this->assertSame([0, "running\n"], [$exit, $stdout]); + } + + public function testTheRandomDelayIsAtMostHalfAnHour(): void { + for ($i = 0; $i < 5; $i++) { + [$exit, $stdout] = $this->functions('sleep() { echo "$1"; }; random_delay'); + + $this->assertSame(0, $exit); + $this->assertMatchesRegularExpression('/^\d+\n$/', $stdout); + $this->assertLessThan(1800, (int)$stdout); + } + } + + public function testRequiresRoot(): void { + if (function_exists('posix_geteuid') && posix_geteuid() === 0) { + $this->markTestSkipped('Running as root'); + } + + [$exit, , $stderr] = $this->runScript('--dry-run'); + + $this->assertSame(1, $exit); + $this->assertStringContainsString('must run as root', $stderr); + } +} diff --git a/tests/lib/OsStatus/OsStatusCollectorTest.php b/tests/lib/OsStatus/OsStatusCollectorTest.php index ac5f91a13..41c4b0f53 100644 --- a/tests/lib/OsStatus/OsStatusCollectorTest.php +++ b/tests/lib/OsStatus/OsStatusCollectorTest.php @@ -15,6 +15,8 @@ use OCA\ServerInfo\OsStatus\Health\SecurityProbe; use OCA\ServerInfo\OsStatus\Health\SystemdProbe; use OCA\ServerInfo\OsStatus\Health\TimeSyncProbe; +use OCA\ServerInfo\OsStatus\Helper\HelperReportReader; +use OCA\ServerInfo\OsStatus\Helper\HelperState; use OCA\ServerInfo\OsStatus\OsStatus; use OCA\ServerInfo\OsStatus\OsStatusCollector; use OCA\ServerInfo\OsStatus\OsStatusStore; @@ -87,6 +89,7 @@ private function collector(int $now = self::NOW): OsStatusCollector { $systemd, $this->timeSync ?? new TimeSyncProbe($host), new SecurityProbe($host), + new HelperReportReader($host), new OsStatusStore($appConfig, $this->appData(), $cacheFactory), $this->createMock(LoggerInterface::class), ); @@ -155,11 +158,13 @@ public function testAnUbuntuHost(): void { $this->assertSame(self::NOW, $status->updates[0]->since); $this->assertSame(RebootReason::KIND_DISTRIBUTION, $status->rebootReasons[0]->kind); $this->assertSame(self::NOW - 2 * 86400, $status->rebootReasons[0]->since); + $this->assertNull($status->restartServices, 'Without the helper other services are unknown'); $this->assertSame(SupportStatus::STATE_SUPPORTED, $status->support->state(self::NOW)); $this->assertFalse($status->support->extendedActive); $this->assertSame(self::NOW - 3600, $status->listsRefreshedAt); $this->assertSame([], $status->failedUnits); $this->assertTrue($status->timeSynchronized); + $this->assertSame(HelperState::STATE_ABSENT, $status->helper->state); $this->assertSame(self::BOOT, $status->bootTime); } @@ -211,6 +216,51 @@ public function testAContainerIsNotAskedAboutPackagesOrReboots(): void { $this->assertNotContains('apt-get -s -o Debug::NoLocking=1 dist-upgrade', $this->host->ran); } + /** + * The helper's report and every directory above it are root's alone. + */ + private function withRootsHelperReportPath(): void { + $this->host->owners[HelperReportReader::DEFAULT_PATH] = ['owner' => 0, 'mode' => 0o100644]; + foreach (['/var/lib/serverinfo', '/var/lib', '/var', '/'] as $directory) { + $this->host->owners[$directory] = ['owner' => 0, 'mode' => 0o40755]; + } + } + + public function testHelperFillsWhatTheWebServerCannotSee(): void { + $this->withPendingUpdates(); + $this->withRootsHelperReportPath(); + $this->host->withFile(HelperReportReader::DEFAULT_PATH, (string)json_encode([ + 'schema' => 1, 'helperVersion' => '1.0.0', 'generatedAt' => self::NOW - 600, 'hostname' => 'cloud.example.org', + 'bootTime' => self::BOOT, 'listsRefreshedAt' => self::NOW - 600, + 'restartServices' => ['php8.3-fpm.service'], + 'rebootReasons' => [['kind' => 'microcode', 'detail' => null]], + ])); + + $status = $this->collector()->collect(); + + $this->assertSame(HelperState::STATE_OK, $status->helper->state); + $this->assertSame('php8.3-fpm.service', $status->restartServices[0]->unit); + $this->assertSame(self::NOW, $status->restartServices[0]->since); + $this->assertSame(self::NOW - 600, $status->listsRefreshedAt); + $this->assertContains(RebootReason::KIND_MICROCODE, array_map(static fn ($r) => $r->kind, $status->rebootReasons ?? [])); + } + + public function testUpdatesFromTheHelperWhenTheWebServerCannotAsk(): void { + $this->withRootsHelperReportPath(); + $this->host->withFile(HelperReportReader::DEFAULT_PATH, (string)json_encode([ + 'schema' => 1, 'helperVersion' => '1.0.0', 'generatedAt' => self::NOW - 600, 'hostname' => 'cloud.example.org', + 'bootTime' => self::BOOT, + 'pendingUpdates' => [['name' => 'openssl', 'installed' => '1', 'candidate' => '2', 'security' => true]], + ])); + + $status = $this->collector()->collect(); + + $this->assertNull($status->packageManager, 'apt-get is not available to the web server here'); + $this->assertSame(OsStatus::SOURCE_HELPER, $status->updatesSource); + $this->assertSame('openssl', $status->updates[0]->name); + $this->assertContains('No supported package manager was found for Ubuntu 24.04.3 LTS.', $status->diagnostics); + } + public function testFailuresBecomeDiagnostics(): void { $this->host->withCommand('apt-get', ['-s', '-o', 'Debug::NoLocking=1', 'dist-upgrade'], '', 100, "E: The package lists are damaged\n"); diff --git a/tests/lib/OsStatus/OsVerdictTest.php b/tests/lib/OsStatus/OsVerdictTest.php index d508beacb..953d1dbc9 100644 --- a/tests/lib/OsStatus/OsVerdictTest.php +++ b/tests/lib/OsStatus/OsVerdictTest.php @@ -10,11 +10,13 @@ namespace OCA\ServerInfo\Tests\OsStatus; use OCA\ServerInfo\OsStatus\Environment; +use OCA\ServerInfo\OsStatus\Helper\HelperState; use OCA\ServerInfo\OsStatus\OsStatus; use OCA\ServerInfo\OsStatus\Packages\AutomaticUpdates; use OCA\ServerInfo\OsStatus\Packages\PendingUpdate; use OCA\ServerInfo\OsStatus\Reboot\RebootReason; use OCA\ServerInfo\OsStatus\Restart\PhpProcessSample; +use OCA\ServerInfo\OsStatus\Restart\ServiceRestart; use OCA\ServerInfo\OsStatus\Support\SupportStatus; use OCA\ServerInfo\OsStatus\Verdict\Concern; use OCA\ServerInfo\OsStatus\Verdict\OsVerdict; @@ -38,6 +40,7 @@ private function osStatus(array $overrides = []): OsStatus { 'listsRefreshedAt' => self::NOW - 3600, 'automaticUpdates' => new AutomaticUpdates(AutomaticUpdates::STATE_ENABLED, 'unattended-upgrades', AutomaticUpdates::SCOPE_SECURITY), 'rebootReasons' => [], + 'restartServices' => [], 'livePatches' => [], 'failedUnits' => [], 'timeSynchronized' => true, @@ -134,19 +137,20 @@ public function testRebootEscalatesAndLivePatchingSoftensKernelReboots(): void { $this->assertSame(Concern::LEVEL_ERROR, $mixed?->level, 'A live patch does not cover the C library'); } - public function testRestartOfPhp(): void { + public function testRestartOfPhpAndServices(): void { $php = new PhpProcessSample(self::NOW, 'fpm-fcgi', ['libssl.so.3'], 'php8.3-fpm', null); $fresh = $this->evaluate($this->osStatus(), $php, self::NOW - 3600)->get(Concern::RESTART); $this->assertSame(Concern::LEVEL_INFO, $fresh?->level); $this->assertTrue($fresh->facts['php']); - $old = $this->evaluate($this->osStatus(), $php, self::NOW - 4 * self::DAY)->get(Concern::RESTART); + $old = $this->evaluate($this->osStatus(['restartServices' => [new ServiceRestart('redis-server.service', self::NOW - 4 * self::DAY)]]))->get(Concern::RESTART); $this->assertSame(Concern::LEVEL_WARNING, $old?->level); + $this->assertSame(1, $old->facts['stack']); } public function testRestartIsUnknownWithoutAnyInformation(): void { - $this->assertSame(Concern::LEVEL_UNKNOWN, $this->evaluate($this->osStatus())->get(Concern::RESTART)?->level); + $this->assertSame(Concern::LEVEL_UNKNOWN, $this->evaluate($this->osStatus(['restartServices' => null]))->get(Concern::RESTART)?->level); } public static function dataSupport(): array { @@ -178,20 +182,32 @@ public function testHealth(): void { 'failedUnits' => ['logrotate.service', 'php8.3-fpm.service'], 'timeSynchronized' => false, 'automaticUpdates' => new AutomaticUpdates(AutomaticUpdates::STATE_DISABLED), + 'helper' => new HelperState(HelperState::STATE_INSECURE, '/var/lib/serverinfo/os-report.json'), ])); $this->assertSame(Concern::LEVEL_WARNING, $verdict->get(Concern::FAILED_UNITS)?->level); $this->assertSame(['php8.3-fpm.service'], $verdict->get(Concern::FAILED_UNITS)?->facts['stack']); $this->assertSame(Concern::LEVEL_WARNING, $verdict->get(Concern::TIME_SYNC)?->level); $this->assertSame(Concern::LEVEL_INFO, $verdict->get(Concern::AUTOMATIC_UPDATES)?->level); + $this->assertSame(Concern::LEVEL_WARNING, $verdict->get(Concern::HELPER)?->level); $this->assertSame(Concern::LEVEL_WARNING, $verdict->level()); } + public function testAHelperReportFromTheFutureIsWorthMentioning(): void { + $verdict = $this->evaluate($this->osStatus([ + 'helper' => new HelperState(HelperState::STATE_CLOCK_SKEW, '/var/lib/serverinfo/os-report.json', self::NOW + 3600, '1.0.0'), + ])); + + $this->assertSame(Concern::LEVEL_INFO, $verdict->get(Concern::HELPER)?->level); + $this->assertSame(HelperState::STATE_CLOCK_SKEW, $verdict->get(Concern::HELPER)?->facts['state']); + } + public function testApplicationContainersSkipWhatIsNotTheirs(): void { $verdict = $this->evaluate($this->osStatus([ 'environment' => new Environment(Environment::KIND_APPLICATION_CONTAINER, 'docker'), 'updates' => null, 'rebootReasons' => null, + 'restartServices' => null, ]), new PhpProcessSample(self::NOW, 'apache2handler', [], 'apache2', null)); $ids = array_map(static fn (Concern $c): string => $c->id, $verdict->concerns); diff --git a/tests/lib/OsStatus/ThresholdsAndStatusTest.php b/tests/lib/OsStatus/ThresholdsAndStatusTest.php index 65039f88d..5c3870484 100644 --- a/tests/lib/OsStatus/ThresholdsAndStatusTest.php +++ b/tests/lib/OsStatus/ThresholdsAndStatusTest.php @@ -11,12 +11,14 @@ use OCA\ServerInfo\Config\ConfigLexicon; use OCA\ServerInfo\OsStatus\Environment; +use OCA\ServerInfo\OsStatus\Helper\HelperState; use OCA\ServerInfo\OsStatus\OsRelease; use OCA\ServerInfo\OsStatus\OsStatus; use OCA\ServerInfo\OsStatus\Packages\AutomaticUpdates; use OCA\ServerInfo\OsStatus\Packages\HeldPackage; use OCA\ServerInfo\OsStatus\Packages\PendingUpdate; use OCA\ServerInfo\OsStatus\Reboot\RebootReason; +use OCA\ServerInfo\OsStatus\Restart\ServiceRestart; use OCA\ServerInfo\OsStatus\Support\SupportStatus; use OCA\ServerInfo\OsStatus\Verdict\Thresholds; use OCP\AppFramework\Services\IAppConfig; @@ -41,6 +43,7 @@ public function testStatusRoundTrip(): void { 1792300000, new AutomaticUpdates(AutomaticUpdates::STATE_ENABLED, 'unattended-upgrades', AutomaticUpdates::SCOPE_SECURITY), [new RebootReason(RebootReason::KIND_KERNEL, '7.0.0-40-generic', [], 1792100000)], + [new ServiceRestart('php8.5-fpm.service', 1792200000)], [], ['logrotate.service'], true, @@ -49,6 +52,7 @@ public function testStatusRoundTrip(): void { 'enabled', ['all' => 'sudo apt update && sudo apt full-upgrade', 'security' => null], '/var/lib/dpkg/status', + new HelperState(HelperState::STATE_OK, '/var/lib/serverinfo/os-report.json', 1792410000, '1.0.0'), 1792000000, ['diagnostic'], ); @@ -95,5 +99,7 @@ public function testStackPackagesAreMarked(): void { $this->assertTrue((new PendingUpdate('libapache2-mod-php8.3', null, '1', false))->toArray()['stack']); $this->assertTrue((new PendingUpdate('openssl-libs', null, '1', false))->toArray()['stack']); $this->assertFalse((new PendingUpdate('vim', null, '1', false))->toArray()['stack']); + $this->assertTrue((new ServiceRestart('mariadb.service'))->toArray()['stack']); + $this->assertFalse((new ServiceRestart('ssh.service'))->toArray()['stack']); } }