diff --git a/.github/workflows/unified-agent-native.yml b/.github/workflows/unified-agent-native.yml index 45684aa2c9..56b41ff07e 100644 --- a/.github/workflows/unified-agent-native.yml +++ b/.github/workflows/unified-agent-native.yml @@ -395,7 +395,7 @@ jobs: shell: bash run: | set -euo pipefail - brew install bash gnu-tar gawk + brew install bash gnu-tar gawk flock linux_bash="$(brew --prefix bash)/bin/bash" test -x "$linux_bash" "$linux_bash" -c '(( BASH_VERSINFO[0] >= 5 ))' @@ -419,6 +419,11 @@ jobs: test -x "$gnu_awk" "$gnu_awk" --version | grep -F 'GNU Awk' > /dev/null ln -s "$gnu_awk" "$fixture_bin/awk" + # The standalone systemd updater locks its installation directory. + # Supply the same flock interface only to these Linux-script fixtures. + fixture_flock="$(brew --prefix flock)/bin/flock" + test -x "$fixture_flock" + ln -s "$fixture_flock" "$fixture_bin/flock" printf 'PULSE_INSTALLER_FIXTURE_BIN=%s\n' "$fixture_bin" >> "$GITHUB_ENV" # Observe the existing generated NAS watchdog/collector control before diff --git a/scripts/installtests/native_installer_fixture_tools_test.go b/scripts/installtests/native_installer_fixture_tools_test.go index e4eb601edd..6abbae70b8 100644 --- a/scripts/installtests/native_installer_fixture_tools_test.go +++ b/scripts/installtests/native_installer_fixture_tools_test.go @@ -202,7 +202,7 @@ func runNativeInstallerFixtureCommand(t *testing.T, limit time.Duration, env []s func TestNativeInstallerFixtureToolsAreRealAndStepLocal(t *testing.T) { supply, preflight, installer := nativeInstallerFixtureSteps(t) - for _, scenario := range []string{"real tools", "symlinked fixture root", "streamed version output", "failed version producer", "install failure", "missing bash", "legacy bash", "missing stat", "non-GNU chmod", "missing cp", "non-GNU cp", "missing mv", "non-GNU mv", "missing ln", "non-GNU ln", "missing readlink", "non-GNU readlink", "missing sha256sum", "non-GNU sha256sum", "missing tar", "non-GNU tar", "missing awk", "non-GNU awk"} { + for _, scenario := range []string{"real tools", "symlinked fixture root", "streamed version output", "failed version producer", "install failure", "missing bash", "legacy bash", "missing stat", "non-GNU chmod", "missing cp", "non-GNU cp", "missing mv", "non-GNU mv", "missing ln", "non-GNU ln", "missing readlink", "non-GNU readlink", "missing sha256sum", "non-GNU sha256sum", "missing tar", "non-GNU tar", "missing awk", "non-GNU awk", "missing flock"} { t.Run(scenario, func(t *testing.T) { root := t.TempDir() if scenario == "symlinked fixture root" { @@ -223,21 +223,21 @@ func TestNativeInstallerFixtureToolsAreRealAndStepLocal(t *testing.T) { brew := `#!/bin/sh printf '%s\n' "$*" >> "$BREW_CALLS" case "$*" in - 'install bash gnu-tar gawk') exit "${BREW_EXIT:-0}" ;; + 'install bash gnu-tar gawk flock') exit "${BREW_EXIT:-0}" ;; '--prefix bash'|'--prefix coreutils') printf '%s\n' "$TOOLS_PREFIX" ;; '--prefix gnu-tar') printf '%s\n' "$TAR_PREFIX" ;; - '--prefix gawk') printf '%s\n' "$TOOLS_PREFIX" ;; + '--prefix gawk'|'--prefix flock') printf '%s\n' "$TOOLS_PREFIX" ;; *) exit 64 ;; esac ` if err := os.WriteFile(filepath.Join(bin, "brew"), []byte(brew), 0700); err != nil { t.Fatal(err) } - tools := []string{"bash", "stat", "chmod", "chown", "cp", "mv", "ln", "readlink", "sha256sum", "tar", "awk"} + tools := []string{"bash", "stat", "chmod", "chown", "cp", "mv", "ln", "readlink", "sha256sum", "tar", "awk", "flock"} installed := make(map[string]string) for _, name := range tools { leaf, toolPrefix := name, prefix - if name != "bash" { + if name != "bash" && name != "flock" { leaf = "g" + name } if name == "tar" { @@ -277,7 +277,7 @@ esac // Native macOS defaults must not be the fallback for Linux-only // archive extraction, canonicalization or atomic replacement. Real // GNU tools must win even when the native names are unsuitable. - for _, name := range []string{"cp", "mv", "readlink", "sha256sum", "tar", "awk"} { + for _, name := range []string{"cp", "mv", "readlink", "sha256sum", "tar", "awk", "flock"} { if err := os.WriteFile(filepath.Join(bin, name), []byte("#!/bin/sh\nprintf 'native BSD utility reached\\n' >&2\nexit 64\n"), 0700); err != nil { t.Fatal(err) } @@ -317,14 +317,14 @@ esac } entries, err := os.ReadDir(fixtureBin) if err != nil || len(entries) != len(tools) { - t.Fatal("fixture supply must select only Bash/stat/chmod/chown/cp/mv/ln/readlink/sha256sum/tar/awk") + t.Fatal("fixture supply must select only Bash/stat/chmod/chown/cp/mv/ln/readlink/sha256sum/tar/awk/flock") } for _, name := range tools { if target, err := os.Readlink(filepath.Join(fixtureBin, name)); err != nil || target != installed[name] { t.Fatalf("%s did not bind the verified installed executable", name) } } - if data, err := os.ReadFile(calls); err != nil || string(data) != "install bash gnu-tar gawk\n--prefix bash\n--prefix coreutils\n--prefix gnu-tar\n--prefix gawk\n" { + if data, err := os.ReadFile(calls); err != nil || string(data) != "install bash gnu-tar gawk flock\n--prefix bash\n--prefix coreutils\n--prefix gnu-tar\n--prefix gawk\n--prefix flock\n" { t.Fatal("fixture supply changed its fixed package/resource selection") } if scenario == "real tools" { @@ -344,13 +344,22 @@ esac set -eu test "$*" = "scripts/installtests/run_unix_contracts.py --phase $EXPECTED_PHASE" || exit 91 test "$(command -v bash)" = "$PULSE_INSTALLER_FIXTURE_BIN/bash" || exit 92 -for tool in stat chmod chown cp mv ln readlink sha256sum tar awk; do +for tool in stat chmod chown cp mv ln readlink sha256sum tar awk flock; do test "$(command -v "$tool")" = "$PULSE_INSTALLER_FIXTURE_BIN/$tool" || exit 93 done # The expected readlink result must use a physical root too. A temporary # directory reached through a legitimate parent symlink is not itself the # canonical spelling (notably /var on macOS). PROBE_ROOT="$(cd "$PROBE_ROOT" && pwd -P)" +# The real standalone updater takes a nonblocking exclusive directory lock. +# A second open of that same directory must fail until the holder closes it. +exec {fixture_lock}< "$PROBE_ROOT" +flock --exclusive --nonblock "$fixture_lock" +bash -c 'exec {contender}< "$1"; if flock --exclusive --nonblock "$contender"; then exit 99; fi' _ "$PROBE_ROOT" +exec {fixture_lock}<&- +exec {fixture_lock}< "$PROBE_ROOT" +flock --exclusive --nonblock "$fixture_lock" +exec {fixture_lock}<&- # Exercise the actual Linux-only flags with real executables and file bytes. # Neither a filename check nor a --version double can establish these semantics. printf 'archive bytes\n' > "$PROBE_ROOT/source" diff --git a/scripts/installtests/pulse_auto_update_test.go b/scripts/installtests/pulse_auto_update_test.go index 82f0405224..3ea51fd741 100644 --- a/scripts/installtests/pulse_auto_update_test.go +++ b/scripts/installtests/pulse_auto_update_test.go @@ -163,6 +163,38 @@ func TestAutoUpdateDownloadFailures(t *testing.T) { } } +// Competing invocations use the same real installation-directory lock, even +// through an alias. No host manager, network or published installer is used. +func TestAutoUpdateTransactionLock(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, "python3", repoFile("scripts", "tests", "test_auto_update_service_state.py"), "-v", "UpdateTransactionLock") + cmd.Env = append(os.Environ(), "PULSE_AUTO_UPDATER_UNDER_TEST="+repoFile("scripts", "pulse-auto-update.sh")) + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("updater transaction lock controls: %v\n%s", err, out) + } + for _, name := range []string{ + "test_same_directory_refuses_competing_transaction", + "test_directory_alias_cannot_start_a_second_transaction", + "test_independent_installations_do_not_block_each_other", + "test_lock_is_released_after_success_and_failed_installation", + "test_unavailable_or_missing_lock_has_no_service_or_installer_action", + "test_service_observation_refusal_releases_the_early_lock", + "test_non_directory_or_missing_installation_never_starts_a_transaction", + } { + passed := false + for _, line := range strings.Split(string(out), "\n") { + if strings.HasPrefix(line, name+" (") && strings.HasSuffix(line, " ... ok") { + passed = true + } + } + if !passed { + t.Fatalf("required updater transaction control %s did not pass:\n%s", name, out) + } + } +} + // Service-state admission is independent of the signed/metadata transaction // matrix below; no native service or published input is used by this fixture. func TestAutoUpdateServiceStateFailsClosed(t *testing.T) { diff --git a/scripts/pulse-auto-update.sh b/scripts/pulse-auto-update.sh index 43c65bc696..1f32928acf 100755 --- a/scripts/pulse-auto-update.sh +++ b/scripts/pulse-auto-update.sh @@ -591,6 +591,29 @@ perform_update() { log error "Refusing to install prerelease version $new_version via unattended updater" return 1 fi + + # systemd serializes one unit, not direct invocations or differently named + # timers using the same installation. Hold its directory inode through + # backup, replacement and recovery. This also covers symlink aliases, + # creates no stale lock file and never waits behind another transaction. + local update_lock_fd="" + if ! command -v flock >/dev/null 2>&1; then + log error "flock is required for the auto-update lock; no update attempted" + return 1 + fi + if [[ ! -d "$INSTALL_DIR" ]] || ! { exec {update_lock_fd}< "$INSTALL_DIR"; } 2>/dev/null; then + log error "Cannot open the installed Pulse directory for locking; no update attempted" + return 1 + fi + if ! flock --exclusive --nonblock "$update_lock_fd"; then + exec {update_lock_fd}<&- + log error "Auto-update directory lock is busy or unavailable; no update attempted" + return 1 + fi + # Early service-state refusals must release the descriptor too. The full + # transaction trap below takes over only after that observation succeeds. + trap 'trap - RETURN; exec {update_lock_fd}<&-' RETURN + local installer_tmp="" local signature_tmp="" local backup_dir="" @@ -619,7 +642,7 @@ perform_update() { # trap is not scoped to the function that set it, so leaving it installed # makes it re-run when any later function returns — with these locals gone # that aborted the updater under set -u after a successful update (#2128). - trap 'trap - RETURN; rm -f -- "${installer_tmp:-}" "${signature_tmp:-}" "${restore_files[@]}"; if [[ -n "$backup_dir" && "$retain_backup" == "false" ]]; then rm -rf -- "$backup_dir"; fi; if [[ "$restart_allowed" == "true" ]]; then ensure_service_restarted "$service_name" "$service_was_active"; fi' RETURN + trap 'trap - RETURN; rm -f -- "${installer_tmp:-}" "${signature_tmp:-}" "${restore_files[@]}"; if [[ -n "$backup_dir" && "$retain_backup" == "false" ]]; then rm -rf -- "$backup_dir"; fi; if [[ "$restart_allowed" == "true" ]]; then ensure_service_restarted "$service_name" "$service_was_active"; fi; exec {update_lock_fd}<&-' RETURN log info "Starting update to $new_version" @@ -693,7 +716,7 @@ perform_update() { "PULSE_SERVICE_NAME=$service_name" \ "PULSE_INSTALL_DIR=$INSTALL_DIR" \ "PULSE_CONFIG_DIR=$CONFIG_DIR" \ - bash "$installer_tmp" "${installer_args[@]}" 2>&1 | ( + bash "$installer_tmp" "${installer_args[@]}" {update_lock_fd}<&- 2>&1 | ( collector_status=0 line="" # Drain even after a failed log write: closing this pipe early can diff --git a/scripts/tests/test_auto_update_service_state.py b/scripts/tests/test_auto_update_service_state.py index 6c9cfa721d..957f45fd53 100644 --- a/scripts/tests/test_auto_update_service_state.py +++ b/scripts/tests/test_auto_update_service_state.py @@ -11,6 +11,7 @@ import os from pathlib import Path import shutil import shlex +import signal import subprocess import sys import tempfile @@ -794,5 +795,212 @@ class RunningExecutable(unittest.TestCase): self.assertEqual(observations, 1) self.assertLess(elapsed, 8) + +# Exclusion uses real file locks, independent of the manager double above. +LOCK_HARNESS = r''' +source "$UPDATER" +log() { printf '[%s] %s\n' "$1" "${*:2}"; } +detect_service_name() { echo pulse-fixture; } +read_update_service_state() { + echo observed >> "$FIXTURE/manager-$LABEL" + if [[ "$STATE_FAULT" == true ]]; then return 1; fi + echo inactive +} +verify_release_signature() { :; } +download_update_asset() { + echo downloaded >> "$FIXTURE/download-$LABEL" + if [[ "$1" == *.sshsig ]]; then printf 'fixture signature\n' > "$2" + else cp "$FIXTURE/installer" "$2"; fi +} +mktemp() { + local -a args=("$@") + local last=$((${#args[@]} - 1)) + if [[ "${args[last]}" == /tmp/* ]]; then + args[last]="$FIXTURE/tmp/${args[last]##*/}" + fi + command mktemp "${args[@]}" +} +if [[ "$LOCK_FAULT" == unavailable ]]; then + flock() { return 69; } +elif [[ "$LOCK_FAULT" == missing ]]; then + command() { + if [[ "$1" == -v && "$2" == flock ]]; then return 1; fi + builtin command "$@" + } +fi +status=0 +perform_update v6.6.0 || status=$? +printf 'STATUS=%s\n' "$status" +[[ -z "$(trap -p RETURN)" ]] || { echo 'RETURN trap leaked'; exit 98; } +exit "$status" +''' + +LOCK_INSTALLER = r'''#!/bin/bash +set -euo pipefail +# A long-lived installer child must not inherit the updater's lock descriptor. +python3 - <<'CHECK' +import os +from pathlib import Path +installed = Path(os.environ["PULSE_INSTALL_DIR"]) +descriptors = Path('/proc/self/fd') if Path('/proc/self/fd').is_dir() else Path('/dev/fd') +for item in descriptors.iterdir(): + try: + if item.samefile(installed): + raise SystemExit('installer inherited the update directory lock') + except FileNotFoundError: + pass +CHECK +printf '%s\n' "$LABEL" >> "$FIXTURE/entered" +if [[ "$BLOCK" == true ]]; then + touch "$FIXTURE/ready" + # Bounded even if its test controller fails; all owned children are reaped. + for ((i=0; i<250; i++)); do + [[ -f "$FIXTURE/release" ]] && break + sleep 0.02 + done + [[ -f "$FIXTURE/release" ]] || exit 97 +fi +cp "$FIXTURE/new-pulse" "$PULSE_INSTALL_DIR/bin/pulse" +printf 'v6.6.0\n' > "$PULSE_INSTALL_DIR/VERSION" +exit "$INSTALLER_EXIT" +''' + + +class UpdateTransactionLock(unittest.TestCase): + def setUp(self): + self.assertIsNotNone(shutil.which("flock"), "flock is required for the actual directory-lock controls") + self.temporary = tempfile.TemporaryDirectory(prefix="pulse-update-lock-") + self.addCleanup(self.temporary.cleanup) + self.root = Path(self.temporary.name) + self.processes = [] + self.addCleanup(self.stop_children) + self.first = self.fixture("first") + + def stop_children(self): + for process in self.processes: + if process.poll() is None: + os.killpg(process.pid, signal.SIGKILL) + process.communicate(timeout=5) + + def fixture(self, name): + f = self.root / name + for directory in (f / "install/bin", f / "config", f / "tmp"): + directory.mkdir(parents=True) + for path, content in ((f / "install/bin/pulse", "#!/bin/sh\necho 'Pulse v6.5.0'\n"), + (f / "new-pulse", "#!/bin/sh\necho 'Pulse v6.6.0'\n"), + (f / "installer", LOCK_INSTALLER)): + path.write_text(content) + path.chmod(0o700) + (f / "install/VERSION").write_text("v6.5.0\n") + (f / "config/system.json").write_text("saved settings\n") + (f / "config/agent-id").write_text("saved identity\n") + return f + + def start(self, fixture, label, *, block=False, install=None, installer_exit=0, lock_fault="", state_fault=False): + env = dict(os.environ, UPDATER=str(UPDATER), FIXTURE=str(fixture), LABEL=label, + BLOCK="true" if block else "false", INSTALLER_EXIT=str(installer_exit), + LOCK_FAULT=lock_fault, STATE_FAULT="true" if state_fault else "false", PULSE_INSTALL_DIR=str(install or fixture / "install"), + PULSE_CONFIG_DIR=str(fixture / "config"), PULSE_SERVICE_NAME="pulse-fixture") + process = subprocess.Popen(["bash", "-c", LOCK_HARNESS], env=env, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, text=True, start_new_session=True) + self.processes.append(process) + return process + + def finish(self, process, expected): + output, error = process.communicate(timeout=10) + self.assertEqual(process.returncode, expected, output + error) + self.assertIn(f"STATUS={expected}", output) + self.assertNotIn("trap leaked", output) + return output + error + + def wait_ready(self): + deadline = time.monotonic() + 4 + while not (self.first / "ready").exists() and time.monotonic() < deadline: + time.sleep(0.02) + self.assertTrue((self.first / "ready").exists(), "first transaction did not enter its private installer") + + def release(self, process): + (self.first / "release").touch() + self.finish(process, 0) + + def assert_saved(self, fixture): + self.assertEqual((fixture / "config/system.json").read_text(), "saved settings\n") + self.assertEqual((fixture / "config/agent-id").read_text(), "saved identity\n") + self.assertEqual(list((fixture / "tmp").iterdir()), []) + + def competing(self, alias=False): + first = self.start(self.first, "holder", block=True) + self.wait_ready() + destination = self.first / "install" + if alias: + destination = self.root / "same directory alias" + destination.symlink_to(self.first / "install", target_is_directory=True) + second = self.start(self.first, "contender", install=destination) + output = self.finish(second, 1) + self.assertIn("lock", output) + self.assertFalse((self.first / "manager-contender").exists()) + self.assertFalse((self.first / "download-contender").exists()) + self.assertEqual((self.first / "entered").read_text().splitlines(), ["holder"]) + self.assertEqual((self.first / "install/VERSION").read_text(), "v6.5.0\n") + self.release(first) + self.assertEqual((self.first / "install/VERSION").read_text(), "v6.6.0\n") + self.assert_saved(self.first) + + def test_same_directory_refuses_competing_transaction(self): + self.competing() + + def test_directory_alias_cannot_start_a_second_transaction(self): + self.competing(alias=True) + + def test_independent_installations_do_not_block_each_other(self): + first = self.start(self.first, "holder", block=True) + self.wait_ready() + independent = self.fixture("independent") + self.finish(self.start(independent, "independent"), 0) + self.assertIsNone(first.poll()) + self.assertEqual((independent / "install/VERSION").read_text(), "v6.6.0\n") + self.release(first) + self.assert_saved(self.first) + self.assert_saved(independent) + + def test_lock_is_released_after_success_and_failed_installation(self): + for status in (0, 23): + with self.subTest(installer_exit=status): + f = self.fixture("sequential-" + str(status)) + self.finish(self.start(f, "first", installer_exit=status), 0 if status == 0 else 1) + self.assertEqual((f / "install/VERSION").read_text(), "v6.6.0\n" if status == 0 else "v6.5.0\n") + self.finish(self.start(f, "next"), 0) + self.assertEqual((f / "entered").read_text().splitlines(), ["first", "next"]) + self.assert_saved(f) + + def test_service_observation_refusal_releases_the_early_lock(self): + self.finish(self.start(self.first, "unobserved", state_fault=True), 1) + self.assertFalse((self.first / "download-unobserved").exists()) + self.assertFalse((self.first / "entered").exists()) + self.assertEqual((self.first / "install/VERSION").read_text(), "v6.5.0\n") + self.finish(self.start(self.first, "next"), 0) + self.assert_saved(self.first) + + def test_non_directory_or_missing_installation_never_starts_a_transaction(self): + for destination in (self.first / "config/agent-id", self.first / "missing"): + with self.subTest(destination=destination.name): + self.finish(self.start(self.first, "refused", install=destination), 1) + for marker in ("manager-refused", "download-refused", "entered"): + self.assertFalse((self.first / marker).exists(), marker) + self.assertEqual((self.first / "install/VERSION").read_text(), "v6.5.0\n") + self.assert_saved(self.first) + + def test_unavailable_or_missing_lock_has_no_service_or_installer_action(self): + for fault in ("unavailable", "missing"): + with self.subTest(fault=fault): + f = self.fixture(fault) + output = self.finish(self.start(f, "refused", lock_fault=fault), 1) + self.assertIn("lock", output) + for marker in ("manager-refused", "download-refused", "entered"): + self.assertFalse((f / marker).exists(), marker) + self.assertEqual((f / "install/VERSION").read_text(), "v6.5.0\n") + self.assert_saved(f) + + if __name__ == "__main__": unittest.main()