Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Guard auto-update asset staging and migrate stale update units
[email protected]5c1c89a36366
diff --git a/docs/release-control/v6/internal/subsystems/deployment-installability.md b/docs/release-control/v6/internal/subsystems/deployment-installability.mdindex 74e8ae6590..89c9e21672 100644--- a/docs/release-control/v6/internal/subsystems/deployment-installability.md+++ b/docs/release-control/v6/internal/subsystems/deployment-installability.md@@ -483,8 +483,10 @@ TLS floor in the dynamic config.`TestEnsureServiceRestartedHonorsPriorServiceState`) and`scripts/tests/test-pulse-auto-update.sh`. For the same reason, root`install.sh` writes outside the hardened update unit's writable set- (`ProtectSystem=strict` leaves only the install dir, config dir and `/tmp`- writable) must be idempotent and non-fatal warnings rather than errexit+ (`ProtectSystem=strict` with `ReadWritePaths` covering the install dir,+ config dir, `/tmp`, the auto-update helper's directory and the unit+ directory — everything else, including `/bin` and `/etc/profile`, stays+ read-only) must be idempotent and non-fatal warnings rather than errexitaborts: the `/bin/update` helper heredoc, the PATH appends to`/etc/profile` and `/etc/bash.bashrc`, and the `/usr/local/bin/pulse`convenience symlink (`install_binary_symlink`, which must also keep an@@ -1916,17 +1918,60 @@ timer must schedule exactly one update attempt per day — a singleand the unit directory inside `ReadWritePaths`: unattended updates run`install.sh` (and therefore `refresh_auto_updates`) under that very sandbox,and a sandbox that excludes those paths freezes every installed helper and-unit at whatever a manual install last wrote (issue #1637 triage). Because+unit at whatever a manual install last wrote (issue #1637 triage). Those two+`ReadWritePaths` entries are deliberately directory grants rather than the+four individual file paths: every write commits with a rename from a sibling+staging file, and rename needs write access on the containing directory. The+tradeoff — the update unit can write any file under `/etc/systemd/system` —+is accepted because the unit already runs the full installer as root, so the+grant does not widen what a compromised installer could reach; it only means+the sandbox no longer contains a *buggy* installer's unit writes. Becausethe unattended path replaces the helper script that bash is currentlyexecuting, `install_auto_update_assets` must stage the new helper in thedestination directory and swap it in with an atomic same-filesystem renameonly after repo configuration succeeds; no failure path may delete ortruncate a previously working helper (the old `rm -f` on configure failure-left the enabled timer with a dangling `ExecStart`). The generated units are+left the enabled timer with a dangling `ExecStart`). Every step that produces+one of those three files must be status-checked and must fail the function:+the staging copy of the bundled helper (both call sites invoke+`install_auto_update_assets` under `if !`, which suppresses errexit for its+whole body, so an unchecked `cp` fell through and+`configure_auto_update_script_repo`'s awk turned the empty file into a+plausible one-line shebang-less "helper" that silently disabled updates), and+both unit renders, which are staged to `${path}.tmp` and committed by rename+rather than written with a truncating `cat >` — the function's last statement+is `safe_systemctl daemon-reload`, which returns 0 by design, so an unchecked+write reported success over a truncated unit. The staged helper must also be+rejected before the swap unless it is non-empty and begins with `#!`.++Changes to the generated units must be able to reach already-deployed boxes.+A box installed before the sandbox was widened runs the installer from a+`pulse-update.service` whose `ReadWritePaths` excludes the helper and unit+directories, so the very run that would install the corrected unit cannot+write it (EROFS) and auto-update alone would never migrate it — the+corrected unit would reach only manually reinstalled boxes. The in-app Go+update pipeline (`internal/updates` `ApplyUpdate`) cannot carry the migration+either: `pulse.service` runs as `User=pulse` under its own+`ProtectSystem=strict` with `ReadWritePaths` limited to the install and+config dirs. `install_auto_update_assets` therefore probes each destination+directory for writability up front and, when one is blocked, hands off to+`migrate_auto_update_assets_outside_sandbox`, which re-execs this same+already-signature-verified installer under `systemd-run` with the internal+`--repair-auto-update-units` entry point. PID 1 forks the transient unit, so+it starts in the host mount namespace instead of inheriting the update unit's+sandbox; the system bus stays reachable from inside that sandbox because+`ProtectSystem=` only remounts the hierarchy read-only and a read-only mount+does not block `connect()` on an `AF_UNIX` socket. The installer is copied+into the install dir before the escape because the calling unit's+`PrivateTmp=yes` hides the auto-update helper's `/tmp` copy of it from PID 1.+The escape must be inert unless it can work and must not recurse: it requires+root and a `systemd-run` on `PATH`, and the escaped run (marked by+`PULSE_AUTO_UPDATE_ASSET_REPAIR=1`) never escapes again. The generated units arethe only unit source — no checked-in reference copies of`pulse-update.service` / `pulse-update.timer` may exist to drift from theheredocs. The rendered-unit execution, schedule, sandbox-writability,-failure-preservation, refresh-behavior, and call-site wiring tests in+failure-preservation, staging-guard, atomic-unit-write, sandbox-escape+migration, refresh-behavior, and call-site wiring tests in`scripts/installtests/root_install_sh_test.go` are the owned proof surfacefor these invariants.That same server-installer uninstall must also leave no legacy companiondiff --git a/install.sh b/install.shindex 580e4a9567..b04d85e89d 100755--- a/install.sh+++ b/install.sh@@ -4067,6 +4067,112 @@ configure_auto_update_script_repo() {chmod +x "$dest"}+# Probes whether new entries can be created in a directory. This is exactly+# the capability the staged-rename swaps below need (rename creates and+# unlinks entries in the target directory), and unlike `test -w` it gives an+# unambiguous answer for root under a ProtectSystem= sandbox.+auto_update_dir_writable() {+ local dir="$1"+ local probe=""+ [[ -d "$dir" ]] || return 1+ probe=$(mktemp "${dir}/.pulse-write-probe.XXXXXX" 2>/dev/null) || return 1+ rm -f "$probe"+ return 0+}++# Guards the helper swap: a truncated or shebang-less helper would replace a+# working one with a file systemd cannot execute as the update unit's+# ExecStart. This matters because configure_auto_update_script_repo's awk+# happily emits a lone GITHUB_REPO= line from empty input, so a silently+# failed copy would otherwise produce a plausible-looking one-line "helper"+# whose only effect is to return success and never update anything.+auto_update_helper_is_sane() {+ local path="$1"+ [[ -s "$path" ]] || return 1+ local first_line=""+ IFS= read -r first_line < "$path" || true+ [[ "$first_line" == '#!'* ]]+}++# Migration for boxes installed before the update sandbox was widened.+#+# Unattended updates run this installer from pulse-update.service, and on a box+# whose unit predates the widened ReadWritePaths that sandbox covers only the+# install dir, config dir and /tmp. The corrected unit therefore cannot be+# written by the very run that would install it (EROFS), so without an escape+# no deployed box ever receives the single-schedule timer or the widened+# sandbox through auto-update — updater fixes reach only manually reinstalled+# boxes. The in-app Go update pipeline cannot carry the migration either:+# pulse.service runs as User=pulse under its own ProtectSystem=strict with+# ReadWritePaths limited to the install and config dirs, so it cannot write+# /etc/systemd/system or /usr/local/bin.+#+# systemd-run asks PID 1 to fork the repair, so the transient unit starts in+# the host mount namespace rather than inheriting this unit's sandbox. The+# system bus stays reachable from inside the sandbox because ProtectSystem=+# only remounts the hierarchy read-only and a read-only mount does not block+# connect() on an AF_UNIX socket (the same reason the unit's own+# ExecCondition=systemctl call works). The installer is copied into the+# install dir rather than run from its current path because the helper stages+# it under /tmp and PrivateTmp=yes hides that from PID 1; re-execing this+# already-signature-verified file also avoids a second unverified download.+migrate_auto_update_assets_outside_sandbox() {+ local blocked_dir="$1"++ # The escaped run writes with no sandbox; if it still cannot write, a+ # second escape would loop forever.+ if [[ "${PULSE_AUTO_UPDATE_ASSET_REPAIR:-}" == "1" ]]; then+ return 1+ fi+ if [[ "$(id -u)" -ne 0 ]]; then+ return 1+ fi+ # Absent on hosts without systemd (and inside Docker), where there is no+ # timer driving this path in the first place.+ if ! command -v systemd-run >/dev/null 2>&1; then+ return 1+ fi++ local installer_src="${BASH_SOURCE[0]:-}"+ if [[ -z "$installer_src" || ! -r "$installer_src" ]]; then+ # curl | bash leaves no file to re-exec.+ return 1+ fi++ local install_dir="${INSTALL_DIR:-${PULSE_INSTALL_DIR:-/opt/pulse}}"+ local repair_copy="${install_dir}/.pulse-update-asset-repair.sh"+ if ! cp "$installer_src" "$repair_copy" 2>/dev/null; then+ return 1+ fi+ chmod 0700 "$repair_copy" 2>/dev/null || true++ print_info "The auto-update sandbox blocks ${blocked_dir}; refreshing the update assets through a transient systemd unit."++ local status=0+ systemd-run --quiet --collect --wait \+ --unit="pulse-update-asset-repair-$$" \+ --description="Refresh Pulse auto-update helper and units outside the update sandbox" \+ --property=Type=oneshot \+ --setenv=PULSE_AUTO_UPDATE_ASSET_REPAIR=1 \+ --setenv="PULSE_SERVICE_NAME=${SERVICE_NAME:-${PULSE_SERVICE_NAME:-pulse}}" \+ --setenv="PULSE_INSTALL_DIR=${install_dir}" \+ --setenv="PULSE_CONFIG_DIR=${CONFIG_DIR:-${PULSE_CONFIG_DIR:-/etc/pulse}}" \+ --setenv="PULSE_AUTO_UPDATE_DEST=${AUTO_UPDATE_DEST:-${PULSE_AUTO_UPDATE_DEST:-/usr/local/bin/pulse-auto-update.sh}}" \+ --setenv="PULSE_UPDATE_SERVICE_PATH=${UPDATE_SERVICE_PATH:-${PULSE_UPDATE_SERVICE_PATH:-/etc/systemd/system/pulse-update.service}}" \+ --setenv="PULSE_UPDATE_TIMER_PATH=${UPDATE_TIMER_PATH:-${PULSE_UPDATE_TIMER_PATH:-/etc/systemd/system/pulse-update.timer}}" \+ /usr/bin/env bash "$repair_copy" --repair-auto-update-units || status=$?++ rm -f "$repair_copy"++ if [[ "$status" -ne 0 ]]; then+ print_warn "Could not refresh the auto-update assets outside the sandbox (systemd-run exited ${status})."+ return 1+ fi++ print_success "Auto-update helper and units refreshed outside the update sandbox."+ return 0+}+# Installs the auto-update helper script and rewrites the systemd# service/timer units. Shared by setup_auto_updates (first-time enable) and# refresh_auto_updates (updates/reinstalls where the timer already exists).@@ -4089,6 +4195,22 @@ install_auto_update_assets() {unit_write_dirs="$unit_write_dirs $update_timer_dir"fi+ # Everything below stages into these directories and commits with a+ # rename, so check up front that entries can be created in each of them.+ # A box whose update unit predates the widened sandbox fails here, and the+ # migration escapes that sandbox to write the corrected assets instead.+ local asset_dir+ for asset_dir in "$auto_update_bin_dir" $unit_write_dirs; do+ if auto_update_dir_writable "$asset_dir"; then+ continue+ fi+ if migrate_auto_update_assets_outside_sandbox "$asset_dir"; then+ return 0+ fi+ print_warn "Cannot write to ${asset_dir} to refresh the auto-update assets."+ return 1+ done+# Stage the helper next to its destination and only swap it in once it is# fully configured. During unattended updates install.sh runs under the# pulse-update.service sandbox, where the file being replaced is the very@@ -4102,8 +4224,15 @@ install_auto_update_assets() {return 1fiif [[ -f "$install_dir/scripts/pulse-auto-update.sh" ]]; then- # Copy auto-update script if it exists in the release- cp "$install_dir/scripts/pulse-auto-update.sh" "$staged_helper"+ # Copy auto-update script if it exists in the release. Both callers+ # invoke this function under `if !`, which suppresses errexit for the+ # whole body, so an unchecked cp (ENOSPC, EIO) would fall through and+ # swap a zero-byte "helper" over the working one.+ if ! cp "$install_dir/scripts/pulse-auto-update.sh" "$staged_helper"; then+ print_warn "Could not copy the bundled auto-update helper into ${auto_update_bin_dir}."+ rm -f "$staged_helper"+ return 1+ fielseprint_info "Downloading auto-update script..."if ! AUTO_UPDATE_DEST="$staged_helper" download_auto_update_script; then@@ -4118,14 +4247,20 @@ install_auto_update_assets() {rm -f "$staged_helper"return 1fi- chmod +x "$staged_helper"- mv "$staged_helper" "$auto_update_dest"- # Install systemd timer and service. The heredoc is unquoted so the- # installer substitutes paths/names; the rendered unit must contain no- # unexpanded $ (in particular never $$, which bash expands to the- # installer's PID and which broke ExecCondition before v6.0.0).- cat > "$update_service_path" <<EOF+ # Render both units beside their destinations before committing anything.+ # A bare truncating `cat > "$unit"` with no status check could leave a+ # half-written unit behind and still report success, because the only+ # thing left in this function is safe_systemctl daemon-reload, which+ # deliberately returns 0 even when it fails.+ local staged_service="${update_service_path}.tmp"+ local staged_timer="${update_timer_path}.tmp"++ # The heredoc is unquoted so the installer substitutes paths/names; the+ # rendered unit must contain no unexpanded $ (in particular never $$,+ # which bash expands to the installer's PID and which broke ExecCondition+ # before v6.0.0).+ if ! cat > "$staged_service" <<EOF[Unit]Description=Automatic Pulse update check and installDocumentation=$(repo_web_url)@@ -4154,6 +4289,14 @@ ProtectSystem=strict# The helper and unit directories are writable on purpose: the installer this# service runs refreshes the auto-update helper and rewrites these units, and# without write access updater fixes only ever reach boxes via manual installs.+# These are directory grants rather than the four individual file paths+# because every one of those writes commits with a rename from a sibling+# staging file (so the previously working helper survives a failed refresh),+# and rename needs write access on the containing directory. The tradeoff is+# that this unit can write any unit file: it already runs the installer as+# root, so the grant does not widen what a compromised installer could do,+# but it does mean the sandbox no longer contains a buggy installer's writes+# to /etc/systemd/system.ReadWritePaths=$install_dir $config_dir /tmp $auto_update_bin_dir $unit_write_dirsPrivateNetwork=noNice=10@@ -4161,8 +4304,13 @@ Nice=10[Install]WantedBy=multi-user.targetEOF+ then+ print_warn "Could not write ${update_service_path}."+ rm -f "$staged_helper" "$staged_service"+ return 1+ fi- cat > "$update_timer_path" <<EOF+ if ! cat > "$staged_timer" <<EOF[Unit]Description=Daily check for Pulse updatesDocumentation=$(repo_web_url)@@ -4181,6 +4329,44 @@ AccuracySec=1h[Install]WantedBy=timers.targetEOF+ then+ print_warn "Could not write ${update_timer_path}."+ rm -f "$staged_helper" "$staged_service" "$staged_timer"+ return 1+ fi++ if ! auto_update_helper_is_sane "$staged_helper"; then+ print_warn "The staged auto-update helper is empty or has no interpreter line; keeping the previously installed helper."+ rm -f "$staged_helper" "$staged_service" "$staged_timer"+ return 1+ fi++ # Explicit mode, not chmod +x: mktemp creates the staging file 0600, and+ # the installed helper should keep the 0755 a plain copy would have had.+ if ! chmod 0755 "$staged_helper"; then+ print_warn "Could not make the staged auto-update helper executable."+ rm -f "$staged_helper" "$staged_service" "$staged_timer"+ return 1+ fi++ # Commit. Each rename is atomic and same-filesystem, so no consumer ever+ # observes a partial file — including the timer's ExecStart, which on the+ # unattended path is the very helper being replaced.+ if ! mv "$staged_helper" "$auto_update_dest"; then+ print_warn "Could not install the auto-update helper at ${auto_update_dest}."+ rm -f "$staged_helper" "$staged_service" "$staged_timer"+ return 1+ fi+ if ! mv "$staged_service" "$update_service_path"; then+ print_warn "Could not install ${update_service_path}."+ rm -f "$staged_service" "$staged_timer"+ return 1+ fi+ if ! mv "$staged_timer" "$update_timer_path"; then+ print_warn "Could not install ${update_timer_path}."+ rm -f "$staged_timer"+ return 1+ fi# Reload systemd daemonsafe_systemctl daemon-reload@@ -5290,6 +5476,16 @@ while [[ $# -gt 0 ]]; doSKIP_UPGRADE_PREFLIGHT=trueshift;;+ --repair-auto-update-units)+ # Internal re-entry point for migrate_auto_update_assets_outside_sandbox:+ # rewrite the auto-update helper and units, nothing else. Deliberately+ # undocumented in --help; it exists so the transient systemd unit can+ # run this installer outside the update sandbox that blocks those writes.+ if install_auto_update_assets; then+ exit 0+ fi+ exit 1+ ;;--source|--from-source|--branch)BUILD_FROM_SOURCE=true# Optional: specify branchdiff --git a/scripts/installtests/install_sh_test.go b/scripts/installtests/install_sh_test.goindex 766d23bd8b..64071ca58d 100644--- a/scripts/installtests/install_sh_test.go+++ b/scripts/installtests/install_sh_test.go@@ -2185,10 +2185,22 @@ func extractSetupAutoUpdatesShellFunctions(t *testing.T) string {return extractSelectedUpdateChannelShellFunctions(t) + "\n" +extractRootInstallShellFunction(t, "repo_web_url") + "\n" +extractRootInstallShellFunction(t, "configure_auto_update_script_repo") + "\n" +- extractRootInstallShellFunction(t, "install_auto_update_assets") + "\n" ++ extractInstallAutoUpdateAssetsShellFunctions(t) + "\n" +extractRootInstallShellFunction(t, "setup_auto_updates")}+// install_auto_update_assets delegates its writability probe, its staged-helper+// sanity check and the sandbox-escape migration to sibling functions, so every+// harness that executes it has to pull those in alongside it.+func extractInstallAutoUpdateAssetsShellFunctions(t *testing.T) string {+ t.Helper()++ return extractRootInstallShellFunction(t, "auto_update_dir_writable") + "\n" ++ extractRootInstallShellFunction(t, "auto_update_helper_is_sane") + "\n" ++ extractRootInstallShellFunction(t, "migrate_auto_update_assets_outside_sandbox") + "\n" ++ extractRootInstallShellFunction(t, "install_auto_update_assets")+}+func prepareAutoUpdatePaths(t *testing.T, tmpDir string) (string, string, string) {t.Helper()diff --git a/scripts/installtests/root_install_sh_test.go b/scripts/installtests/root_install_sh_test.goindex 523d1a80d4..c0117baffd 100644--- a/scripts/installtests/root_install_sh_test.go+++ b/scripts/installtests/root_install_sh_test.go@@ -1217,7 +1217,7 @@ func TestRefreshAutoUpdatesReplacesStaleHelperWithoutChangingEnablement(t *testisafe_systemctl() { printf '%s\n' "$*" >> "` + callsPath + `"; }` + extractRootInstallShellFunction(t, "repo_web_url") + `` + extractRootInstallShellFunction(t, "configure_auto_update_script_repo") + `-` + extractRootInstallShellFunction(t, "install_auto_update_assets") + `+` + extractInstallAutoUpdateAssetsShellFunctions(t) + `` + extractRootInstallShellFunction(t, "refresh_auto_updates") + `refresh_auto_updates`@@ -1355,10 +1355,12 @@ func TestRootInstallServiceGrantsIcmpProbeCapability(t *testing.T) {// #1630 guarantee: setup_update_command's write of the /bin/update helper// (and its PATH appends) must not abort the installer under errexit when the// destination is unwritable. The stock pulse-update.service runs the-// unattended updater with ProtectSystem=strict, leaving /bin and-// /usr/local/bin read-only; the old behavior killed the installer after the-// new binary was installed and the service stopped, and the auto-update-// rollback then left Pulse down. A regular file as the "parent directory"+// unattended updater with ProtectSystem=strict; its ReadWritePaths covers the+// install dir, config dir, /tmp and the auto-update helper and unit+// directories, so /bin (the default helper path) and /etc/profile stay+// read-only. The old behavior killed the installer after the new binary was+// installed and the service stopped, and the auto-update rollback then left+// Pulse down. A regular file as the "parent directory"// makes writes beneath it fail with ENOTDIR, which also fails when the test// runs as root (unlike chmod 555).func TestRootInstallScriptUpdateHelperWriteIsNonFatalOnReadOnlyPath(t *testing.T) {@@ -1475,7 +1477,7 @@ func renderAutoUpdateUnits(t *testing.T) (string, string, string, string) {safe_systemctl() { :; }` + extractRootInstallShellFunction(t, "repo_web_url") + `` + extractRootInstallShellFunction(t, "configure_auto_update_script_repo") + `-` + extractRootInstallShellFunction(t, "install_auto_update_assets") + `+` + extractInstallAutoUpdateAssetsShellFunctions(t) + `install_auto_update_assets`@@ -1597,7 +1599,7 @@ func TestInstallAutoUpdateAssetsKeepsWorkingHelperWhenConfigureFails(t *testing.print_warn() { :; }safe_systemctl() { :; }` + extractRootInstallShellFunction(t, "repo_web_url") + `-` + extractRootInstallShellFunction(t, "install_auto_update_assets") + `+` + extractInstallAutoUpdateAssetsShellFunctions(t) + `configure_auto_update_script_repo() { return 1; }if install_auto_update_assets; thenecho "UNEXPECTED_SUCCESS"@@ -1634,3 +1636,402 @@ func TestInstallAutoUpdateAssetsKeepsWorkingHelperWhenConfigureFails(t *testing.}}}++// autoUpdateAssetsHarness builds a bash harness that runs the real+// install_auto_update_assets against temp paths, with a seeded release helper+// and a previously installed working helper. extra is appended after the+// extracted functions so it can override them with stubs.+func autoUpdateAssetsHarness(t *testing.T, tmpDir string, autoUpdateDest, servicePath, timerPath, extra string) string {+ t.Helper()++ configDir := filepath.Join(tmpDir, "config")+ installDir := filepath.Join(tmpDir, "install")+ autoUpdateSrc := filepath.Join(installDir, "scripts", "pulse-auto-update.sh")++ if err := os.MkdirAll(configDir, 0755); err != nil {+ t.Fatalf("mkdir config dir: %v", err)+ }+ if err := os.MkdirAll(filepath.Dir(autoUpdateSrc), 0755); err != nil {+ t.Fatalf("mkdir auto-update src dir: %v", err)+ }+ if err := os.WriteFile(autoUpdateSrc, []byte("#!/usr/bin/env bash\necho new-helper\n"), 0755); err != nil {+ t.Fatalf("write auto-update src: %v", err)+ }++ return `+ CONFIG_DIR="` + configDir + `"+ INSTALL_DIR="` + installDir + `"+ PULSE_AUTO_UPDATE_DEST="` + autoUpdateDest + `"+ PULSE_UPDATE_SERVICE_PATH="` + servicePath + `"+ PULSE_UPDATE_TIMER_PATH="` + timerPath + `"+ GITHUB_REPO="rcourtman/Pulse"+ print_info() { :; }+ print_warn() { echo "WARN: $*"; }+ print_success() { :; }+ safe_systemctl() { :; }+` + extractRootInstallShellFunction(t, "repo_web_url") + `+` + extractRootInstallShellFunction(t, "configure_auto_update_script_repo") + `+` + extractInstallAutoUpdateAssetsShellFunctions(t) + `+` + extra + `+ if install_auto_update_assets; then+ echo "UNEXPECTED_SUCCESS"+ else+ echo "FAILED_AS_EXPECTED"+ fi+ `+}++// assertNoAutoUpdateStagingLitter fails when a staged helper or a staged unit+// file survived a run. `.service.tmp` is not a unit suffix systemd loads, but+// leaving one behind still means the function abandoned a partial write.+func assertNoAutoUpdateStagingLitter(t *testing.T, dirs ...string) {+ t.Helper()++ for _, dir := range dirs {+ entries, err := os.ReadDir(dir)+ if err != nil {+ t.Fatalf("read %s: %v", dir, err)+ }+ for _, entry := range entries {+ name := entry.Name()+ if strings.Contains(name, ".staged.") || strings.HasSuffix(name, ".tmp") {+ t.Fatalf("run left staging litter behind in %s: %s", dir, name)+ }+ }+ }+}++// Regression test for the unchecked staging copy in install_auto_update_assets:+// the bundled helper was copied into the staged mktemp file with a bare `cp`,+// and because both call sites invoke the function under `if !` errexit is+// suppressed for its whole body. A cp that failed (ENOSPC) therefore fell+// through to configure_auto_update_script_repo, whose awk happily emits a lone+// GITHUB_REPO= line for empty input, and the resulting one-line shebang-less+// stub replaced the working helper with a "script" whose only behaviour is to+// exit 0 — silently disabling unattended updates on the box. A failed or+// truncated copy must leave the installed helper and the units untouched.+func TestInstallAutoUpdateAssetsKeepsWorkingHelperWhenStagingCopyFails(t *testing.T) {+ workingHelper := "#!/usr/bin/env bash\necho working-helper\n"++ for _, tc := range []struct {+ name string+ stub string+ }{+ {+ name: "copy reports failure",+ stub: `cp() { return 1; }`,+ },+ {+ // cp that "succeeds" having written nothing: the shape the awk+ // rewrite turns into a plausible-looking one-line helper.+ name: "copy silently produces an empty file",+ stub: `cp() { : > "$2"; }`,+ },+ } {+ t.Run(tc.name, func(t *testing.T) {+ tmpDir := t.TempDir()+ autoUpdateDest, servicePath, timerPath := prepareAutoUpdatePaths(t, tmpDir)+ if err := os.WriteFile(autoUpdateDest, []byte(workingHelper), 0755); err != nil {+ t.Fatalf("write installed helper: %v", err)+ }++ script := autoUpdateAssetsHarness(t, tmpDir, autoUpdateDest, servicePath, timerPath, tc.stub)+ out, err := exec.Command("bash", "-c", script).CombinedOutput()+ if err != nil {+ t.Fatalf("bash: %v\n%s", err, out)+ }+ if !strings.Contains(string(out), "FAILED_AS_EXPECTED") {+ t.Fatalf("install_auto_update_assets should report failure when the staging copy fails:\n%s", out)+ }++ helper, err := os.ReadFile(autoUpdateDest)+ if err != nil {+ t.Fatalf("installed helper is gone after a failed staging copy: %v", err)+ }+ if string(helper) != workingHelper {+ t.Fatalf("failed staging copy replaced the working helper:\n%s", helper)+ }+ if _, err := os.Stat(servicePath); !os.IsNotExist(err) {+ t.Fatalf("failed staging copy still rewrote the service unit (stat err %v)", err)+ }+ if _, err := os.Stat(timerPath); !os.IsNotExist(err) {+ t.Fatalf("failed staging copy still rewrote the timer unit (stat err %v)", err)+ }+ assertNoAutoUpdateStagingLitter(t, filepath.Dir(autoUpdateDest), filepath.Dir(servicePath))+ })+ }+}++// Regression test for the unit writes in install_auto_update_assets: both units+// were rendered with a bare truncating `cat > "$unit"` whose status was never+// checked, and the function's last statement is safe_systemctl daemon-reload,+// which returns 0 by design even when systemctl fails. A failing write+// therefore truncated a working unit and still reported success. Each unit is+// now rendered beside its destination and committed with a rename, so a failure+// at either step must be reported and must leave the installed unit intact.+func TestInstallAutoUpdateAssetsWritesUnitsAtomically(t *testing.T) {+ workingHelper := "#!/usr/bin/env bash\necho working-helper\n"+ workingUnit := "[Service]\nExecStart=/usr/local/bin/pulse-auto-update.sh\n"++ for _, tc := range []struct {+ name string+ stub string+ }{+ {+ // The render itself fails (a full disk hitting the heredoc).+ name: "unit render fails",+ stub: `cat() { return 1; }`,+ },+ {+ // The render succeeds but the commit does not; the live unit must+ // still hold its previous contents rather than a truncated file.+ name: "unit commit fails",+ stub: `mv() { if [[ "${2:-}" == "` + "SERVICE_PATH_PLACEHOLDER" + `" ]]; then return 1; fi; command mv "$@"; }`,+ },+ } {+ t.Run(tc.name, func(t *testing.T) {+ tmpDir := t.TempDir()+ autoUpdateDest, servicePath, timerPath := prepareAutoUpdatePaths(t, tmpDir)+ if err := os.WriteFile(autoUpdateDest, []byte(workingHelper), 0755); err != nil {+ t.Fatalf("write installed helper: %v", err)+ }+ if err := os.WriteFile(servicePath, []byte(workingUnit), 0644); err != nil {+ t.Fatalf("write installed service unit: %v", err)+ }++ stub := strings.ReplaceAll(tc.stub, "SERVICE_PATH_PLACEHOLDER", servicePath)+ script := autoUpdateAssetsHarness(t, tmpDir, autoUpdateDest, servicePath, timerPath, stub)+ out, err := exec.Command("bash", "-c", script).CombinedOutput()+ if err != nil {+ t.Fatalf("bash: %v\n%s", err, out)+ }+ if !strings.Contains(string(out), "FAILED_AS_EXPECTED") {+ t.Fatalf("install_auto_update_assets should report failure when a unit write fails:\n%s", out)+ }++ unit, err := os.ReadFile(servicePath)+ if err != nil {+ t.Fatalf("installed service unit is gone after a failed write: %v", err)+ }+ if string(unit) != workingUnit {+ t.Fatalf("failed unit write clobbered the installed unit:\n%s", unit)+ }+ if _, err := os.Stat(timerPath); !os.IsNotExist(err) {+ t.Fatalf("failed service unit write still installed the timer (stat err %v)", err)+ }+ assertNoAutoUpdateStagingLitter(t, filepath.Dir(autoUpdateDest), filepath.Dir(servicePath))+ })+ }+}++// A successful run must commit through renames and leave nothing staged.+func TestInstallAutoUpdateAssetsLeavesNoStagingFilesOnSuccess(t *testing.T) {+ _, _, autoUpdateDest, servicePath := renderAutoUpdateUnits(t)+ assertNoAutoUpdateStagingLitter(t, filepath.Dir(autoUpdateDest), filepath.Dir(servicePath))+}++// Migration coverage for deployed boxes (the EROFS chicken-and-egg): a box+// installed before the sandbox was widened runs this installer from a+// pulse-update.service whose ReadWritePaths excludes /etc/systemd/system and+// /usr/local/bin, so the run that would install the corrected unit cannot write+// it. install_auto_update_assets must detect the unwritable directory up front+// and hand off to the sandbox escape rather than failing the refresh.+func TestInstallAutoUpdateAssetsMigratesWhenSandboxBlocksUnitDir(t *testing.T) {+ tmpDir := t.TempDir()+ autoUpdateDest, _, _ := prepareAutoUpdatePaths(t, tmpDir)++ // A regular file standing in for the unit directory makes it unwritable in+ // a way that also holds when the test runs as root (unlike chmod 555).+ blocker := filepath.Join(tmpDir, "blocker")+ if err := os.WriteFile(blocker, nil, 0644); err != nil {+ t.Fatalf("write blocker: %v", err)+ }+ servicePath := filepath.Join(blocker, "pulse-update.service")+ timerPath := filepath.Join(blocker, "pulse-update.timer")+ recordPath := filepath.Join(tmpDir, "migrated-dir")++ stub := `migrate_auto_update_assets_outside_sandbox() { printf '%s' "$1" > "` + recordPath + `"; return 0; }`+ script := autoUpdateAssetsHarness(t, tmpDir, autoUpdateDest, servicePath, timerPath, stub)++ out, err := exec.Command("bash", "-c", script).CombinedOutput()+ if err != nil {+ t.Fatalf("bash: %v\n%s", err, out)+ }+ if !strings.Contains(string(out), "UNEXPECTED_SUCCESS") {+ t.Fatalf("a successful sandbox escape must be reported as success:\n%s", out)+ }++ recorded, err := os.ReadFile(recordPath)+ if err != nil {+ t.Fatalf("unwritable unit directory did not trigger the sandbox escape: %v\n%s", err, out)+ }+ if string(recorded) != blocker {+ t.Fatalf("sandbox escape was told %q was blocked, want %q", recorded, blocker)+ }+ assertNoAutoUpdateStagingLitter(t, filepath.Dir(autoUpdateDest))+}++// The sandbox escape itself: systemd-run asks PID 1 to fork the repair, so the+// transient unit runs in the host mount namespace instead of inheriting the+// update unit's ProtectSystem=strict. The installer is copied into the install+// dir first because the calling unit's PrivateTmp=yes hides the helper's /tmp+// copy of it from PID 1, and the escaped run must be handed the same service,+// helper and unit paths or it would repair the defaults instead.+func TestMigrateAutoUpdateAssetsOutsideSandboxReExecsInstallerViaSystemdRun(t *testing.T) {+ tmpDir := t.TempDir()+ installDir := filepath.Join(tmpDir, "install")+ if err := os.MkdirAll(installDir, 0755); err != nil {+ t.Fatalf("mkdir install dir: %v", err)+ }+ argsPath := filepath.Join(tmpDir, "systemd-run-args")++ harness := `#!/usr/bin/env bash+set -uo pipefail+INSTALL_DIR="` + installDir + `"+CONFIG_DIR="` + tmpDir + `/config"+SERVICE_NAME="pulse"+AUTO_UPDATE_DEST="` + tmpDir + `/bin/pulse-auto-update.sh"+UPDATE_SERVICE_PATH="` + tmpDir + `/systemd/pulse-update.service"+UPDATE_TIMER_PATH="` + tmpDir + `/systemd/pulse-update.timer"+print_info() { :; }+print_warn() { echo "WARN: $*"; }+print_success() { echo "MIGRATED"; }+id() { echo 0; }+systemd-run() { printf '%s\n' "$@" > "` + argsPath + `"; return 0; }+` + extractRootInstallShellFunction(t, "migrate_auto_update_assets_outside_sandbox") + `+if migrate_auto_update_assets_outside_sandbox /etc/systemd/system; then+ echo "ESCAPED"+else+ echo "DID_NOT_ESCAPE"+fi+# The escape must refuse to recurse: the escaped run has no sandbox, so if it+# still cannot write, escaping again would loop forever.+rm -f "` + argsPath + `.recursion"+systemd-run() { printf '%s\n' "$@" > "` + argsPath + `.recursion"; return 0; }+if PULSE_AUTO_UPDATE_ASSET_REPAIR=1 migrate_auto_update_assets_outside_sandbox /etc/systemd/system; then+ echo "RECURSED"+fi+[[ -e "` + argsPath + `.recursion" ]] && echo "RECURSION_INVOKED_SYSTEMD_RUN"+exit 0+`+ harnessPath := filepath.Join(tmpDir, "installer-harness.sh")+ if err := os.WriteFile(harnessPath, []byte(harness), 0755); err != nil {+ t.Fatalf("write harness: %v", err)+ }++ out, err := exec.Command("bash", harnessPath).CombinedOutput()+ if err != nil {+ t.Fatalf("bash: %v\n%s", err, out)+ }+ got := string(out)+ if !strings.Contains(got, "ESCAPED") || !strings.Contains(got, "MIGRATED") {+ t.Fatalf("sandbox escape did not report success:\n%s", got)+ }+ for _, unwanted := range []string{"RECURSED", "RECURSION_INVOKED_SYSTEMD_RUN"} {+ if strings.Contains(got, unwanted) {+ t.Fatalf("sandbox escape recursed inside the escaped run (%s):\n%s", unwanted, got)+ }+ }++ argsBytes, err := os.ReadFile(argsPath)+ if err != nil {+ t.Fatalf("sandbox escape never invoked systemd-run: %v\n%s", err, got)+ }+ args := strings.Split(strings.TrimRight(string(argsBytes), "\n"), "\n")+ joined := strings.Join(args, " ")+ for _, want := range []string{+ "--wait",+ "--property=Type=oneshot",+ "--setenv=PULSE_AUTO_UPDATE_ASSET_REPAIR=1",+ "--repair-auto-update-units",+ "--setenv=PULSE_UPDATE_SERVICE_PATH=" + tmpDir + "/systemd/pulse-update.service",+ "--setenv=PULSE_UPDATE_TIMER_PATH=" + tmpDir + "/systemd/pulse-update.timer",+ "--setenv=PULSE_AUTO_UPDATE_DEST=" + tmpDir + "/bin/pulse-auto-update.sh",+ "--setenv=PULSE_INSTALL_DIR=" + installDir,+ } {+ if !strings.Contains(joined, want) {+ t.Fatalf("systemd-run invocation missing %q:\n%s", want, joined)+ }+ }++ // The re-exec target must be the copy inside the install dir: PrivateTmp+ // hides the helper's /tmp copy of the installer from PID 1.+ repairCopy := filepath.Join(installDir, ".pulse-update-asset-repair.sh")+ if !strings.Contains(joined, repairCopy) {+ t.Fatalf("systemd-run was not pointed at the install-dir copy %q:\n%s", repairCopy, joined)+ }+ if _, err := os.Stat(repairCopy); !os.IsNotExist(err) {+ t.Fatalf("sandbox escape left the installer copy behind (stat err %v)", err)+ }+}++// The other half of the migration: install.sh must expose the re-entry point+// the transient unit invokes, and it must rewrite the helper and both units+// without running a full install. This runs the real installer file.+func TestRootInstallScriptRepairAutoUpdateUnitsEntryPoint(t *testing.T) {+ tmpDir := t.TempDir()+ installDir := filepath.Join(tmpDir, "install")+ configDir := filepath.Join(tmpDir, "config")+ autoUpdateDest, servicePath, timerPath := prepareAutoUpdatePaths(t, tmpDir)++ if err := os.MkdirAll(filepath.Join(installDir, "scripts"), 0755); err != nil {+ t.Fatalf("mkdir install scripts dir: %v", err)+ }+ if err := os.MkdirAll(configDir, 0755); err != nil {+ t.Fatalf("mkdir config dir: %v", err)+ }+ if err := os.WriteFile(filepath.Join(installDir, "scripts", "pulse-auto-update.sh"),+ []byte("#!/usr/bin/env bash\necho repaired-helper\n"), 0755); err != nil {+ t.Fatalf("write release helper: %v", err)+ }++ installer, err := filepath.Abs(filepath.Join("..", "..", "install.sh"))+ if err != nil {+ t.Fatalf("resolve install.sh: %v", err)+ }+ cmd := exec.Command("bash", installer, "--repair-auto-update-units")+ cmd.Env = append(os.Environ(),+ "PULSE_INSTALL_DIR="+installDir,+ "PULSE_CONFIG_DIR="+configDir,+ "PULSE_AUTO_UPDATE_DEST="+autoUpdateDest,+ "PULSE_UPDATE_SERVICE_PATH="+servicePath,+ "PULSE_UPDATE_TIMER_PATH="+timerPath,+ "PULSE_AUTO_UPDATE_ASSET_REPAIR=1",+ )+ out, err := cmd.CombinedOutput()+ if err != nil {+ t.Fatalf("install.sh --repair-auto-update-units failed: %v\n%s", err, out)+ }++ helper, err := os.ReadFile(autoUpdateDest)+ if err != nil {+ t.Fatalf("repair did not install the helper: %v\n%s", err, out)+ }+ if !strings.Contains(string(helper), "repaired-helper") {+ t.Fatalf("repair installed the wrong helper:\n%s", helper)+ }+ if info, err := os.Stat(autoUpdateDest); err != nil {+ t.Fatalf("stat repaired helper: %v", err)+ } else if info.Mode().Perm() != 0755 {+ t.Fatalf("repaired helper mode = %v, want 0755 (the update unit's ExecStart)", info.Mode().Perm())+ }++ unit, err := os.ReadFile(servicePath)+ if err != nil {+ t.Fatalf("repair did not write the service unit: %v\n%s", err, out)+ }+ if !strings.Contains(string(unit), "ReadWritePaths=") ||+ !strings.Contains(string(unit), filepath.Dir(servicePath)) ||+ !strings.Contains(string(unit), filepath.Dir(autoUpdateDest)) {+ t.Fatalf("repaired unit did not carry the widened sandbox:\n%s", unit)+ }++ timer, err := os.ReadFile(timerPath)+ if err != nil {+ t.Fatalf("repair did not write the timer unit: %v\n%s", err, out)+ }+ if strings.Count(string(timer), "\nOnCalendar=") != 1 {+ t.Fatalf("repaired timer does not hold exactly one schedule:\n%s", timer)+ }+ assertNoAutoUpdateStagingLitter(t, filepath.Dir(autoUpdateDest), filepath.Dir(servicePath))+}diff --git a/scripts/tests/test-install-update-resilience.sh b/scripts/tests/test-install-update-resilience.shindex bf92467bd9..081cc7879a 100755--- a/scripts/tests/test-install-update-resilience.sh+++ b/scripts/tests/test-install-update-resilience.sh@@ -70,8 +70,10 @@ fi# --- Cases 5+: read-only-filesystem resilience (#1630) -----------------------# The unattended updater runs the installer under pulse-update.service, whose-# ProtectSystem=strict leaves /bin and /usr/local/bin read-only; transient-# read-only remounts hit the same paths. Writes outside the install dir must+# ProtectSystem=strict grants ReadWritePaths only for the install dir, config+# dir, /tmp and the auto-update helper and unit directories — so /bin (the+# default update-helper path) and /etc/profile stay read-only; transient+# read-only remounts hit the same paths. Writes outside the writable set must# be non-fatal: aborting used to kill the installer with errexit active after# the new binary was installed and the service stopped.TMPDIR_RO="$(mktemp -d)"