From f13c63c886e0e5495f15a72340aef431451445cb Mon Sep 17 00:00:00 2001 From: "pulse-triage[bot]" <249995291+pulse-triage[bot]@users.noreply.github.com> Date: Mon, 9 Nov 2026 22:36:14 +0000 Subject: [PATCH] Publish updater assets through private exact-file stages Allocate private same-directory stages for all updater assets, reject redirected or non-regular destinations, preserve effective masks and publish with exact atomic renames. Retain preferences and optional setup policy, and report partial publication without claiming rollback. Exercise the real installer and both consumers with temporary filesystem fault controls. Contract-Neutral: Private staging and exact-file publication preserve the existing updater unit contents, schedule, permissions, consent, preference, API and service lifecycle contracts; only unsafe filesystem destinations and failed writes are refused. Change-source: pulse-maintainer --- install.sh | 100 ++++++-- scripts/installtests/install_sh_test.go | 2 + .../installtests/pulse_auto_update_test.go | 17 ++ scripts/installtests/root_install_sh_test.go | 7 +- .../tests/test_auto_update_service_state.py | 234 ++++++++++++++++++ scripts/tests/test_server_update_timer.py | 11 +- 6 files changed, 343 insertions(+), 28 deletions(-) diff --git a/install.sh b/install.sh index 193de3678e..1dc6a4498b 100644 --- a/install.sh +++ b/install.sh @@ -4946,6 +4946,33 @@ auto_update_units_refreshable() { return 0 } +# A linked/masked or non-regular destination belongs to operator reconciliation, +# not an automatic conversion into a Pulse-owned file. Check the complete set +# before staging and publication; each rename also rechecks its own destination. +auto_update_asset_destinations_regular() { + local asset + for asset in "$@"; do + if [[ -L "$asset" || ( -e "$asset" && ! -f "$asset" ) ]]; then + print_warn "Cannot replace redirected or non-regular auto-update asset ($asset); inspect the destination before retrying." + return 1 + fi + done + return 0 +} + +# Only this invocation's exclusively allocated stages are supplied here. Never +# adopt, truncate or clean up the old fixed .tmp names or another run's files. +cleanup_auto_update_asset_stages() { + local stage + for stage in "$@"; do + [[ -n "$stage" ]] || continue + if ! rm -f -- "$stage"; then + print_warn "Could not remove staged auto-update asset ($stage); inspect the retained staging file before retrying." + fi + done + 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). @@ -4960,6 +4987,7 @@ install_auto_update_assets() { local update_timer_unit update_timer_unit="$(basename "$update_timer_path")" auto_update_units_refreshable "$update_timer_path" "$update_service_path" || return 1 + auto_update_asset_destinations_regular "$auto_update_dest" "$update_service_path" "$update_timer_path" || return 1 local auto_update_bin_dir update_unit_dir update_timer_dir auto_update_bin_dir="$(dirname "$auto_update_dest")" update_unit_dir="$(dirname "$update_service_path")" @@ -5004,21 +5032,21 @@ install_auto_update_assets() { # 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" + cleanup_auto_update_asset_stages "$staged_helper" return 1 fi else print_info "Downloading auto-update script..." if ! AUTO_UPDATE_DEST="$staged_helper" download_auto_update_script; then print_warn "Could not download the auto-update helper after multiple attempts." - rm -f "$staged_helper" + cleanup_auto_update_asset_stages "$staged_helper" return 1 fi fi if ! configure_auto_update_script_repo "$staged_helper"; then print_warn "Could not configure the auto-update helper for the selected release repo." - rm -f "$staged_helper" + cleanup_auto_update_asset_stages "$staged_helper" return 1 fi @@ -5027,8 +5055,17 @@ install_auto_update_assets() { # 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" + local staged_service="" staged_timer="" + if ! staged_service=$(mktemp "${update_service_path}.staged.XXXXXX"); then + print_warn "Could not stage ${update_service_path}; existing auto-update assets were not changed." + cleanup_auto_update_asset_stages "$staged_helper" + return 1 + fi + if ! staged_timer=$(mktemp "${update_timer_path}.staged.XXXXXX"); then + print_warn "Could not stage ${update_timer_path}; existing auto-update assets were not changed." + cleanup_auto_update_asset_stages "$staged_helper" "$staged_service" + return 1 + fi # The heredoc is unquoted so the installer substitutes paths/names; the # rendered unit must contain no unexpanded $ (in particular never $$, @@ -5080,7 +5117,7 @@ WantedBy=multi-user.target EOF then print_warn "Could not write ${update_service_path}." - rm -f "$staged_helper" "$staged_service" + cleanup_auto_update_asset_stages "$staged_helper" "$staged_service" "$staged_timer" return 1 fi @@ -5105,13 +5142,13 @@ WantedBy=timers.target EOF then print_warn "Could not write ${update_timer_path}." - rm -f "$staged_helper" "$staged_service" "$staged_timer" + cleanup_auto_update_asset_stages "$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" + cleanup_auto_update_asset_stages "$staged_helper" "$staged_service" "$staged_timer" return 1 fi @@ -5119,26 +5156,49 @@ EOF # 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" + cleanup_auto_update_asset_stages "$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 + # mktemp creates private files; preserve the installed unit modes even + # when the installer itself runs under a private umask. + if ! chmod 0644 "$staged_service" || ! chmod 0644 "$staged_timer"; then + print_warn "Could not set auto-update unit permissions; existing assets were not changed." + cleanup_auto_update_asset_stages "$staged_helper" "$staged_service" "$staged_timer" + return 1 + fi + + # Rendering is not a lock. Reconfirm effective masks and the complete set + # before the first publication, then recheck each destination at its swap. + if ! auto_update_units_refreshable "$update_timer_path" "$update_service_path" || + ! auto_update_asset_destinations_regular "$auto_update_dest" "$update_service_path" "$update_timer_path"; then + cleanup_auto_update_asset_stages "$staged_helper" "$staged_service" "$staged_timer" + return 1 + fi + + # Each same-directory rename is atomic, not the three-file set. Keep the + # helper -> service -> timer dependency order and never move a stage INTO + # an unexpected directory. A later failure reports the partial publication; + # it does not claim rollback or change preferences, enablement or starts. + if ! auto_update_asset_destinations_regular "$auto_update_dest" || + ! mv -fT -- "$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" + cleanup_auto_update_asset_stages "$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" + if ! auto_update_asset_destinations_regular "$update_service_path" || + ! mv -fT -- "$staged_service" "$update_service_path"; then + print_warn "Auto-update helper was installed, but service publication is unconfirmed (${update_service_path}); inspect the assets before retrying." + cleanup_auto_update_asset_stages "$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" + if ! auto_update_asset_destinations_regular "$update_timer_path" || + ! mv -fT -- "$staged_timer" "$update_timer_path"; then + print_warn "Auto-update helper and service were installed, but timer publication is unconfirmed (${update_timer_path}); inspect the assets before retrying." + cleanup_auto_update_asset_stages "$staged_timer" + # The complete new service is already on disk. Reconcile its loaded + # definition even on partial publication, without enabling/starting it. + safe_systemctl daemon-reload return 1 fi diff --git a/scripts/installtests/install_sh_test.go b/scripts/installtests/install_sh_test.go index 81917ebae7..8b0bf5c338 100644 --- a/scripts/installtests/install_sh_test.go +++ b/scripts/installtests/install_sh_test.go @@ -3778,6 +3778,8 @@ func extractInstallAutoUpdateAssetsShellFunctions(t *testing.T) string { 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, "auto_update_asset_destinations_regular") + "\n" + + extractRootInstallShellFunction(t, "cleanup_auto_update_asset_stages") + "\n" + extractRootInstallShellFunction(t, "install_auto_update_assets") } diff --git a/scripts/installtests/pulse_auto_update_test.go b/scripts/installtests/pulse_auto_update_test.go index ee58636ea1..8ca6ed0564 100644 --- a/scripts/installtests/pulse_auto_update_test.go +++ b/scripts/installtests/pulse_auto_update_test.go @@ -1359,3 +1359,20 @@ result=$(get_latest_stable_version) t.Fatalf("missing parser must stop before discovery: %v\n%s", err, out) } } + +// These controls exercise actual same-directory writes with no manager or +// production access. Both real optional callers retain their nonfatal policy. +func TestInstallAutoUpdateAssetPublication(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("Unix server installer filesystem controls") + } + runParallelPythonFixtureControls(t, repoFile("scripts", "tests", "test_auto_update_service_state.py"), "UpdateAssetPublication", []string{ + "test_nonregular_destinations_refuse_before_staging_or_helper_replacement", + "test_foreign_fixed_temp_paths_survive_private_staging_and_exact_renames", + "test_preparation_failures_preserve_all_three_assets_and_preferences", + "test_publication_failure_stops_without_claiming_a_three_file_rollback", + "test_changed_destinations_and_new_effective_masks_never_report_success", + "test_both_optional_callers_complete_without_enable_or_start_after_refusal", + "test_cleanup_failure_retains_owned_stages_and_primary_failure", + }, 45*time.Second, "PULSE_INSTALLER_UNDER_TEST="+repoFile("install.sh")) +} diff --git a/scripts/installtests/root_install_sh_test.go b/scripts/installtests/root_install_sh_test.go index 6da158319a..23c9d58e45 100644 --- a/scripts/installtests/root_install_sh_test.go +++ b/scripts/installtests/root_install_sh_test.go @@ -2267,7 +2267,7 @@ func TestInstallAutoUpdateAssetsWritesUnitsAtomically(t *testing.T) { // 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 "$@"; }`, + stub: `mv() { if [[ "${@: -1}" == "` + "SERVICE_PATH_PLACEHOLDER" + `" ]]; then return 1; fi; command mv "$@"; }`, }, } { t.Run(tc.name, func(t *testing.T) { @@ -2508,8 +2508,9 @@ esac t.Fatalf("install.sh --repair-auto-update-units failed: %v\n%s", err, out) } calls, err := os.ReadFile(callsPath) - if err != nil || string(calls) != "list-unit-files --no-legend --no-pager --full -- pulse-update.timer pulse-update.service\ndaemon-reload\n" { - t.Fatalf("repair did not inspect both units before its only manager operation: %v\n%s", err, calls) + const maskInventory = "list-unit-files --no-legend --no-pager --full -- pulse-update.timer pulse-update.service\n" + if err != nil || string(calls) != maskInventory+maskInventory+"daemon-reload\n" { + t.Fatalf("repair did not inspect both units before staging and publication, followed only by reload: %v\n%s", err, calls) } helper, err := os.ReadFile(autoUpdateDest) diff --git a/scripts/tests/test_auto_update_service_state.py b/scripts/tests/test_auto_update_service_state.py index b009f7b4b1..30c98f439c 100644 --- a/scripts/tests/test_auto_update_service_state.py +++ b/scripts/tests/test_auto_update_service_state.py @@ -1093,5 +1093,239 @@ with patch.object(Path, 'iterdir', entries), patch.object(Path, 'stat', descript self.assert_saved(f) +class UpdateAssetPublication(unittest.TestCase): + """Real optional asset writes, always confined to ordinary temporary files.""" + + HARNESS = r''' +source "$INSTALLER" +record() { printf '%s\n' "$*" >> "$FIXTURE/operations"; } +print_info() { echo "$*"; } +print_warn() { echo "WARN: $*"; } +print_success() { echo "SUCCESS: $*"; } +safe_systemctl() { record "manager $*"; } +download_auto_update_script() { record unexpected-download; return 98; } +systemctl() { return 99; } # Presence only; inventory below never uses the host. +unit_file_inventory() { + record inventory + if [[ "$FAULT" == inventory ]]; then return 73; fi + local state=disabled + if [[ "$FAULT" == mask || ( "$FAULT" == late-mask && -e "$FIXTURE/rendered" ) ]]; then state=masked-runtime; fi + printf 'pulse-update.timer %s\npulse-update.service disabled\n' "$state" +} +migrate_auto_update_assets_outside_sandbox() { record migration; return 1; } +last_arg() { for last; do :; done; printf '%s' "$last"; } +mktemp() { + local path; path=$(last_arg "$@") + record "allocate $path" + case "$FAULT:$path" in + allocate-helper:*.sh.staged.*|allocate-service:*.service.staged.*|allocate-timer:*.timer.staged.*) return 74 ;; + esac + command mktemp "$@" +} +cat_count=0 +cat() { + cat_count=$((cat_count + 1)) + record "render $cat_count" + touch "$FIXTURE/rendered" + if [[ "$FAULT" == "render-$cat_count" || ( "$FAULT" == cleanup && "$cat_count" == 1 ) ]]; then printf 'partial unit\n'; return 75; fi + if [[ "$FAULT" == during-render-directory && "$cat_count" == 1 ]]; then + command mv "$PULSE_UPDATE_SERVICE_PATH" "$FIXTURE/displaced-service" + mkdir "$PULSE_UPDATE_SERVICE_PATH" + fi + command cat "$@" +} +chmod() { + local path; path=$(last_arg "$@") + record "mode $1 $path" + case "$FAULT:$path" in + mode-service:*.service.staged.*|mode-timer:*.timer.staged.*) return 76 ;; + esac + if [[ "$FAULT" == mode-helper && "$path" == *.sh.staged.* && "$path" != *.repo.* ]]; then return 76; fi + command chmod "$@" +} +mv() { + local path; path=$(last_arg "$@") + record "publish $path" + case "$FAULT:$path" in + publish-helper:*/pulse-auto-update.sh|publish-service:*/pulse-update.service|publish-timer:*/pulse-update.timer) return 77 ;; + esac + if [[ "$FAULT" == after-admission-directory && "$path" == "$PULSE_UPDATE_SERVICE_PATH" ]]; then + command mv "$path" "$FIXTURE/displaced-service" + mkdir "$path" + fi + # All three live swaps must be exact non-directory renames; the separate + # helper repository rewrite is also real but not one of these boundaries. + if [[ "$STRICT_SWAP" == true && ( "$path" == "$PULSE_AUTO_UPDATE_DEST" || "$path" == "$PULSE_UPDATE_SERVICE_PATH" || "$path" == "$PULSE_UPDATE_TIMER_PATH" ) ]]; then + [[ "$#" == 4 && "$1" == -fT && "$2" == -- && "$3" == "$4".staged.* ]] || return 96 + local wanted=644 + [[ "$path" != "$PULSE_AUTO_UPDATE_DEST" ]] || wanted=755 + [[ "$(python3 -c 'import os,stat,sys; print(oct(stat.S_IMODE(os.stat(sys.argv[1]).st_mode))[2:])' "$3")" == "$wanted" ]] || return 97 + fi + command mv "$@" +} +rm() { + record cleanup + [[ "$FAULT" != cleanup ]] || return 78 + command rm "$@" +} +umask 077 +status=0 +# Real callers suppress errexit for the whole producer. Keep that context. +if [[ "$CALLER" == setup ]]; then + ENABLE_AUTO_UPDATES=true + selected_update_channel() { echo stable; } + setup_auto_updates || status=$? +elif [[ "$CALLER" == refresh ]]; then + refresh_auto_updates || status=$? +else + install_auto_update_assets || status=$? +fi +printf 'RESULT=%s\n' "$status" +exit "$status" +''' + + def exercise(self, *, fault="none", odd=None, caller="assets", strict=False, foreign=False): + installer = Path(os.environ.get("PULSE_INSTALLER_UNDER_TEST", ROOT / "install.sh")).resolve() + with tempfile.TemporaryDirectory(prefix="pulse-update-publication-") as directory: + f = Path(directory) + for name in ("install/scripts", "bin", "units", "config"): + (f / name).mkdir(parents=True) + paths = [f / "bin/pulse-auto-update.sh", f / "units/pulse-update.service", f / "units/pulse-update.timer"] + original = [b"#!/bin/bash\necho old helper\n", b"previous complete service\n", b"previous complete timer\n"] + for path, data in zip(paths, original): + path.write_bytes(data) + path.chmod(0o750 if path == paths[0] else 0o640) + (f / "install/scripts/pulse-auto-update.sh").write_bytes(b"#!/bin/bash\necho new helper\n") + saved = b'{"autoUpdateEnabled":false,"updateChannel":"beta","operatorSetting":"retained"}\n' + (f / "config/system.json").write_bytes(saved) + target = f / "unrelated" + target.write_bytes(b"unrelated saved bytes\n") + if odd: + index, kind = odd + path = paths[index] + path.unlink() + if kind == "directory": path.mkdir() + elif kind == "fifo": os.mkfifo(path) + elif kind == "file-link": path.symlink_to(target) + elif kind == "directory-link": path.symlink_to(f / "config", target_is_directory=True) + elif kind == "dangling": path.symlink_to(f / "absent") + elif kind == "mask": path.symlink_to("/dev/null") + else: raise ValueError(kind) + if foreign: + Path(str(paths[1]) + ".tmp").symlink_to(target) + Path(str(paths[2]) + ".tmp").write_bytes(b"another invocation's temp bytes\n") + env = dict(os.environ, FIXTURE=str(f), INSTALLER=str(installer), FAULT=fault, CALLER=caller, + STRICT_SWAP=str(strict).lower(), PULSE_INSTALL_DIR=str(f / "install"), PULSE_CONFIG_DIR=str(f / "config"), + PULSE_AUTO_UPDATE_DEST=str(paths[0]), PULSE_UPDATE_SERVICE_PATH=str(paths[1]), + PULSE_UPDATE_TIMER_PATH=str(paths[2]), GITHUB_REPO="rcourtman/Pulse", PULSE_SERVICE_NAME="pulse") + result = subprocess.run(["bash", "-c", self.HARNESS], env=env, capture_output=True, text=True, timeout=15) + snapshots = [] + for path in paths: + kind = "link" if path.is_symlink() else ("directory" if path.is_dir() else ("file" if path.is_file() else "other")) + snapshots.append(dict(kind=kind, data=path.read_bytes() if kind == "file" else None, + mode=(path.stat().st_mode & 0o777) if kind == "file" else None, + entries=sorted(p.name for p in path.iterdir()) if kind == "directory" else [], + link=os.readlink(path) if kind == "link" else None)) + return dict(exit=result.returncode, output=result.stdout + result.stderr, snapshots=snapshots, original=original, + ops=(f / "operations").read_text().splitlines() if (f / "operations").exists() else [], + target=target.read_bytes(), config=(f / "config/system.json").read_bytes(), saved=saved, + stages=[p.name for parent in (f / "bin", f / "units") for p in parent.iterdir() if ".staged." in p.name], + displaced=(f / "displaced-service").read_bytes() if (f / "displaced-service").exists() else None, + foreign_link=Path(str(paths[1]) + ".tmp").is_symlink(), + foreign_data=Path(str(paths[2]) + ".tmp").read_bytes() if foreign and Path(str(paths[2]) + ".tmp").is_file() else None) + + def assert_preserved(self, evidence, except_index=None): + for i, (snapshot, original) in enumerate(zip(evidence["snapshots"], evidence["original"])): + if i != except_index: + self.assertEqual(snapshot["data"], original, evidence) + self.assertEqual(snapshot["mode"], 0o750 if i == 0 else 0o640, evidence) + self.assertEqual(evidence["config"], evidence["saved"], evidence) + self.assertEqual(evidence["target"], b"unrelated saved bytes\n", evidence) + self.assertFalse(any(op.startswith("manager ") for op in evidence["ops"]), evidence) + self.assertEqual(evidence["stages"], [], evidence) + + def test_nonregular_destinations_refuse_before_staging_or_helper_replacement(self): + for index in range(3): + for kind in ("directory", "fifo", "file-link", "directory-link", "dangling", "mask"): + with self.subTest(asset=index, kind=kind): + e = self.exercise(odd=(index, kind)) + self.assertNotEqual(e["exit"], 0, e) + self.assert_preserved(e, except_index=index) + self.assertFalse(any(op.startswith(("allocate ", "publish ", "render ", "mode ")) for op in e["ops"]), e) + if kind == "directory": self.assertEqual(e["snapshots"][index]["entries"], [], e) + if "link" in kind or kind in ("dangling", "mask"): self.assertEqual(e["snapshots"][index]["kind"], "link", e) + + def test_foreign_fixed_temp_paths_survive_private_staging_and_exact_renames(self): + e = self.exercise(foreign=True, strict=True) + self.assertEqual(e["exit"], 0, e) + self.assertTrue(e["foreign_link"], e) + self.assertEqual(e["target"], b"unrelated saved bytes\n", e) + self.assertEqual(e["foreign_data"], b"another invocation's temp bytes\n", e) + self.assertEqual([s["kind"] for s in e["snapshots"]], ["file"] * 3, e) + self.assertEqual([s["mode"] for s in e["snapshots"]], [0o755, 0o644, 0o644], e) + self.assertIn(b'GITHUB_REPO="rcourtman/Pulse"\n', e["snapshots"][0]["data"]) + self.assertIn(b"OnCalendar=*-*-* 02:00:00\n", e["snapshots"][2]["data"]) + self.assertEqual([line for line in e["snapshots"][2]["data"].splitlines() if line.startswith(b"OnCalendar=")], [b"OnCalendar=*-*-* 02:00:00"]) + self.assertEqual([op for op in e["ops"] if op.startswith("manager ")], ["manager daemon-reload"], e) + self.assertEqual(e["config"], e["saved"], e) + self.assertEqual(e["stages"], [], e) + + def test_preparation_failures_preserve_all_three_assets_and_preferences(self): + for fault in ("allocate-helper", "allocate-service", "allocate-timer", "render-1", "render-2", "mode-helper", "mode-service", "mode-timer"): + with self.subTest(fault=fault): + e = self.exercise(fault=fault) + self.assertNotEqual(e["exit"], 0, e) + self.assert_preserved(e) + + def test_publication_failure_stops_without_claiming_a_three_file_rollback(self): + for index, fault in enumerate(("publish-helper", "publish-service", "publish-timer")): + with self.subTest(fault=fault): + e = self.exercise(fault=fault) + self.assertNotEqual(e["exit"], 0, e) + for i, s in enumerate(e["snapshots"]): + if i < index: self.assertNotEqual(s["data"], e["original"][i], e) + else: self.assertEqual(s["data"], e["original"][i], e) + self.assertEqual(e["config"], e["saved"], e) + managers = [op for op in e["ops"] if op.startswith("manager ")] + self.assertEqual(managers, ["manager daemon-reload"] if index == 2 else [], e) + if index > 0: self.assertIn("publication is unconfirmed", e["output"], e) + self.assertEqual(e["stages"], [], e) + + def test_changed_destinations_and_new_effective_masks_never_report_success(self): + for fault in ("during-render-directory", "after-admission-directory", "late-mask"): + with self.subTest(fault=fault): + e = self.exercise(fault=fault) + self.assertNotEqual(e["exit"], 0, e) + self.assertFalse(any(op.startswith("manager ") for op in e["ops"]), e) + self.assertEqual(e["stages"], [], e) + self.assertEqual(e["config"], e["saved"], e) + if fault != "late-mask": + self.assertEqual(e["snapshots"][1]["kind"], "directory", e) + self.assertEqual(e["snapshots"][1]["entries"], [], e) + self.assertEqual(e["displaced"], e["original"][1], e) + self.assertEqual(e["snapshots"][2]["data"], e["original"][2], e) + if fault != "after-admission-directory": + self.assertEqual(e["snapshots"][0]["data"], e["original"][0], e) + + def test_cleanup_failure_retains_owned_stages_and_primary_failure(self): + e = self.exercise(fault="cleanup") + self.assertNotEqual(e["exit"], 0, e) + self.assertEqual([s["data"] for s in e["snapshots"]], e["original"], e) + self.assertEqual(e["config"], e["saved"], e) + self.assertTrue(e["stages"], e) + self.assertIn("Could not remove staged auto-update asset", e["output"], e) + self.assertFalse(any(op.startswith("manager ") for op in e["ops"]), e) + + def test_both_optional_callers_complete_without_enable_or_start_after_refusal(self): + for caller in ("setup", "refresh"): + for fault, odd in (("none", (1, "directory")), ("mask", None), ("inventory", None), ("allocate-timer", None)): + with self.subTest(caller=caller, fault=fault, odd=odd): + e = self.exercise(caller=caller, fault=fault, odd=odd) + self.assertEqual(e["exit"], 0, e) # Optional setup must not strand monitoring. + self.assert_preserved(e, except_index=1 if odd else None) + self.assertIn("WARN:", e["output"], e) + self.assertNotIn("SUCCESS:", e["output"], e) + + if __name__ == "__main__": unittest.main() diff --git a/scripts/tests/test_server_update_timer.py b/scripts/tests/test_server_update_timer.py index f015542ca2..08f6f02ff8 100644 --- a/scripts/tests/test_server_update_timer.py +++ b/scripts/tests/test_server_update_timer.py @@ -387,11 +387,12 @@ class ServerUpdateTimerTest(unittest.TestCase): service = "pulse-" + "department-" * 12 e = self.exercise(flow="version", state="disabled", service=service) self.assert_refreshed(e, False) - self.assertEqual(e["calls"][-2], - f"list-unit-files --no-legend --no-pager --full -- {service}-update.timer {service}-update.service") - self.assertTrue(e["calls"][:-2]) - self.assertTrue(all(call == f"list-unit-files --no-legend --no-pager --full -- {service}-update.timer" - for call in e["calls"][:-2])) + timer_inventory = f"list-unit-files --no-legend --no-pager --full -- {service}-update.timer" + asset_inventory = f"{timer_inventory} {service}-update.service" + # Discover the timer first, then check both units before staging and + # again before publishing. Every read must keep the complete names. + self.assertEqual(e["calls"], [timer_inventory, timer_inventory, + asset_inventory, asset_inventory, "daemon-reload"]) @unittest.skipUnless(REAL_SYSTEMCTL, "systemctl filesystem inventory is unavailable") def test_real_systemctl_inventory_and_complete_flow_use_only_fixture_root(self):