diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4ed0e5423..65a996c44 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -124,6 +124,12 @@ jobs: - name: Test Apple signing-service retry helper run: bash scripts/ci/test-with-apple-service-retry.sh + - name: Test macOS developer-tools helper + run: bash scripts/ci/test-macos-developer-tools.sh + + - name: Test macOS Apple-services helper + run: bash scripts/ci/test-macos-apple-services.sh + - name: Test unlocked gnome-keyring helper run: bash scripts/ci/test-with-unlocked-gnome-keyring.sh @@ -500,6 +506,11 @@ jobs: "$RUNNER_TEMP/LPM CLI.app" \ "$RUNNER_TEMP/lpm-cli.provisionprofile" + # Only macOS runs the installer's macOS checks, among them that it needs + # no developer tools, Gatekeeper assessor or Apple service. + - name: Shell installer regressions on macOS + run: sh tests/install-sh/run.sh + macos-workspace: name: macOS workspace checks needs: [macos-workspace-tests, macos-build-checks] diff --git a/.github/workflows/macos-without-developer-tools.yml b/.github/workflows/macos-without-developer-tools.yml new file mode 100644 index 000000000..d9d05c5cc --- /dev/null +++ b/.github/workflows/macos-without-developer-tools.yml @@ -0,0 +1,258 @@ +name: macOS without developer tools + +# Every hosted macOS runner has Xcode and the Command Line Tools, which most of +# LPM's users don't. These checks remove them, then install, upgrade and +# self-update against real signed releases, as such a Mac does. On the oldest +# and newest macOS that GitHub hosts they also drop all traffic to the hosts +# macOS asks about notarization tickets and certificate revocation, and to +# Apple's networks, as a firewall that blocks Apple does. +on: + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + paths: + - 'Cargo.lock' + - 'crates/lpm-cli/Cargo.toml' + - 'crates/lpm-cli/src/cli/format.rs' + - 'crates/lpm-cli/src/json_contract.rs' + - 'crates/lpm-cli/src/release_channel.rs' + - 'crates/lpm-cli/src/commands/self_update*' + - 'crates/lpm-cli/src/commands/self_update/**' + - 'crates/lpm-cli/src/sigstore*' + - 'crates/lpm-cli/src/sigstore_verify/**' + - 'crates/lpm-common/src/error.rs' + - 'crates/lpm-common/src/process_output*' + - 'crates/lpm-cli/src/release_lookup.rs' + - 'crates/lpm-http/**' + - 'install.sh' + - 'tests/install-sh/**' + - 'scripts/ci/macos-apple-services.sh' + - 'scripts/ci/test-macos-apple-services.sh' + - 'scripts/ci/macos-developer-tools.sh' + - 'scripts/ci/test-macos-developer-tools.sh' + - '.github/workflows/macos-without-developer-tools.yml' + # The latest releases change without a commit here, so the checks also run + # daily. + schedule: + - cron: '41 9 * * *' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: macos-without-developer-tools-${{ github.ref }} + cancel-in-progress: true + +env: + CARGO_INCREMENTAL: '0' + CARGO_PROFILE_DEV_DEBUG: '0' + CARGO_PROFILE_TEST_DEBUG: '0' + +jobs: + macos-without-developer-tools: + name: ${{ matrix.runner }}, developer tools ${{ matrix.developer-tools }}, Apple services ${{ matrix.apple-services }} + if: ${{ !github.event.pull_request.draft }} + strategy: + fail-fast: false + matrix: + include: + - runner: macos-15 + developer-tools: none + apple-services: blocked + asset: lpm-darwin-arm64.zip + - runner: macos-26 + developer-tools: none + apple-services: blocked + asset: lpm-darwin-arm64.zip + - runner: macos-15-intel + developer-tools: command-line-tools + apple-services: reachable + asset: lpm-darwin-x64.zip + runs-on: ${{ matrix.runner }} + timeout-minutes: 60 + env: + ASSET: ${{ matrix.asset }} + # A standalone install whose updater runs /usr/bin/stapler. + AFFECTED_VERSION: v0.85.0 + # The last stable release whose updater needs Xcode. + LAST_UPDATER_NEEDING_XCODE: 0.88.0 + DEVELOPER_TOOLS: ${{ matrix.developer-tools }} + # What an updater that runs /usr/bin/stapler reports on this Mac: the + # shim's own refusal when only the Command Line Tools are installed. + UPDATER_NEEDS_XCODE: ${{ matrix.developer-tools == 'command-line-tools' && 'requires Xcode' || 'notarization-ticket validation failed' }} + # Older than every release, so this build updates to each of them. + FIXED_BUILD_VERSION: 0.0.1 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master + with: + toolchain: '1.99.1' + - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: | + ~/.cargo/registry + ~/.cargo/git + target + key: ${{ matrix.runner }}-without-developer-tools-1.99.1-${{ hashFiles('Cargo.lock') }} + restore-keys: ${{ matrix.runner }}-without-developer-tools-1.99.1- + + - name: Build this updater and its signed-release tests + run: | + set -euo pipefail + tests=$(cargo test --locked -p lpm-cli --bin lpm-rs --no-run --message-format=json \ + | jq -r 'select(.reason == "compiler-artifact" and .profile.test and .target.name == "lpm-rs") | .executable') + test -x "$tests" + LPM_BUILD_VERSION="$FIXED_BUILD_VERSION" cargo build --locked -p lpm-cli --bin lpm-rs + mkdir -p "$RUNNER_TEMP/fixed" + cp target/debug/lpm-rs "$RUNNER_TEMP/fixed/lpm-rs" + test "$(LPM_NO_UPDATE_CHECK=1 "$RUNNER_TEMP/fixed/lpm-rs" --version | sed -n 1p)" = "lpm $FIXED_BUILD_VERSION" + echo "SELF_UPDATE_TESTS=$tests" >> "$GITHUB_ENV" + + - name: Download real signed releases + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + # install.sh follows GitHub's latest release; lpm self-update follows + # the npm dist-tags first, which GitHub releases precede. + installer_stable=$(gh release view --repo lpm-dev/rust-client --json tagName --jq .tagName) + archives="" + for tag in v0.76.5 v0.77.0-nightly.20260909.177.e3196a5; do + mkdir -p "$RUNNER_TEMP/releases/$tag" + gh release download "$tag" --repo lpm-dev/rust-client --dir "$RUNNER_TEMP/releases/$tag" \ + --pattern "$ASSET" --pattern SHA256SUMS.txt + (cd "$RUNNER_TEMP/releases/$tag" && awk -v asset="$ASSET" '$2 == asset' SHA256SUMS.txt | shasum -a 256 --check) + archives="${archives:+$archives:}$RUNNER_TEMP/releases/$tag/$ASSET" + done + { + echo "INSTALLER_STABLE=${installer_stable#v}" + echo "LPM_TEST_MACOS_RELEASE_ARCHIVES=$archives" + } >> "$GITHUB_ENV" + + # Before anything on this Mac checks a release, so the system has no + # notarization answers cached for them. + - name: Block Apple's services + if: matrix.apple-services == 'blocked' + run: bash scripts/ci/macos-apple-services.sh block "$RUNNER_TEMP/apple-services" + + - name: Remove developer tools + run: bash scripts/ci/macos-developer-tools.sh hide "$DEVELOPER_TOOLS" "$RUNNER_TEMP/developer-tools" + + - name: This updater verifies real signed releases + timeout-minutes: 5 + run: | + set -euo pipefail + unset DEVELOPER_DIR + "$SELF_UPDATE_TESTS" --ignored --test-threads=1 signed_macos_release \ + | tee "$RUNNER_TEMP/signed-release-tests.log" + grep -q 'test result: ok. 3 passed' "$RUNNER_TEMP/signed-release-tests.log" + + - name: Fresh install through the official installer + timeout-minutes: 5 + run: | + set -euo pipefail + unset DEVELOPER_DIR + rm -rf "$HOME/.lpm" + # The version is named: the installer's own latest-release lookup + # is unauthenticated, and hosted runners share GitHub's hourly + # limit for it. tests/install-sh covers that lookup. + env PATH=/usr/bin:/bin:/usr/sbin:/sbin SHELL=/bin/zsh LPM_INSTALL_VERSION="v$INSTALLER_STABLE" sh install.sh + test "$(LPM_NO_UPDATE_CHECK=1 "$HOME/.lpm/bin/lpm" --version | sed -n 1p)" = "lpm $INSTALLER_STABLE" + + - name: In-place upgrade of an affected install through the official installer + timeout-minutes: 5 + env: + GITHUB_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + unset DEVELOPER_DIR + rm -rf "$HOME/.lpm" + lpm="$HOME/.lpm/bin/lpm" + env PATH=/usr/bin:/bin:/usr/sbin:/sbin SHELL=/bin/zsh \ + LPM_INSTALL_VERSION="$AFFECTED_VERSION" LPM_INSTALL_MIN_VERSION_OVERRIDE=1 sh install.sh + test "$(LPM_NO_UPDATE_CHECK=1 "$lpm" --version | sed -n 1p)" = "lpm ${AFFECTED_VERSION#v}" + # With LPM_NO_UPDATE_CHECK, no background update check can hold the + # update lock when the self-update below starts. + LPM_NO_UPDATE_CHECK=1 "$lpm" config release-age --set 3d + printf 'kept across upgrades\n' > "$HOME/.lpm/upgrade-sentinel" + if "$lpm" self-update > "$RUNNER_TEMP/affected-self-update.log" 2>&1; then + cat "$RUNNER_TEMP/affected-self-update.log" + echo "::error::$AFFECTED_VERSION updated itself, so developer tools were not removed" + exit 1 + fi + grep -q "$UPDATER_NEEDS_XCODE" "$RUNNER_TEMP/affected-self-update.log" \ + || { cat "$RUNNER_TEMP/affected-self-update.log"; exit 1; } + (cd "$HOME/.lpm" && find . -type f ! -path './bin/*' ! -path './libexec/*' -print0 \ + | xargs -0 shasum -a 256) > "$RUNNER_TEMP/settings" + env PATH=/usr/bin:/bin:/usr/sbin:/sbin SHELL=/bin/zsh LPM_INSTALL_VERSION="v$INSTALLER_STABLE" sh install.sh + (cd "$HOME/.lpm" && shasum -a 256 --check --quiet "$RUNNER_TEMP/settings") + test "$(LPM_NO_UPDATE_CHECK=1 "$lpm" --version | sed -n 1p)" = "lpm $INSTALLER_STABLE" + grep -Eqx 'minimum-release-age-secs = (259200|"259200")' "$HOME/.lpm/config.toml" + test "$(grep -c '\.lpm/bin' "$HOME/.zshrc")" -eq 1 + + - name: The latest stable release's own updater takes the newest nightly + timeout-minutes: 5 + env: + GITHUB_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + unset DEVELOPER_DIR + lpm="$HOME/.lpm/bin/lpm" + nightly() { curl -fsSL https://registry.npmjs.org/@lpm-registry/cli/nightly | jq -er .version; } + before=$(nightly) + status=0 + "$lpm" self-update --channel nightly --refresh --json \ + > "$RUNNER_TEMP/latest-self-update.json" 2> "$RUNNER_TEMP/latest-self-update.err" || status=$? + cat "$RUNNER_TEMP/latest-self-update.json" "$RUNNER_TEMP/latest-self-update.err" + if [ "$(printf '%s\n%s\n' "$INSTALLER_STABLE" "$LAST_UPDATER_NEEDING_XCODE" | sort -V | tail -n 1)" = "$LAST_UPDATER_NEEDING_XCODE" ]; then + test "$status" -ne 0 + grep -q "$UPDATER_NEEDS_XCODE" "$RUNNER_TEMP/latest-self-update.json" "$RUNNER_TEMP/latest-self-update.err" + echo "::notice::$INSTALLER_STABLE still needs Xcode to update; its users recover through the installer" + else + test "$status" -eq 0 + jq -e '.applied and .verified' "$RUNNER_TEMP/latest-self-update.json" + chosen=$(jq -er .latest "$RUNNER_TEMP/latest-self-update.json") + [ "$chosen" = "$before" ] || [ "$chosen" = "$(nightly)" ] + test "$(LPM_NO_UPDATE_CHECK=1 "$lpm" --version | sed -n 1p)" = "lpm $chosen" + fi + + - name: Self-update from this build to the latest signed releases + timeout-minutes: 5 + env: + GITHUB_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + unset DEVELOPER_DIR + lpm="$HOME/.lpm/bin/lpm" + app="$HOME/.lpm/libexec/LPM CLI.app" + (cd "$HOME/.lpm" && find . -type f ! -path './bin/*' ! -path './libexec/*' ! -name update-check.json -print0 \ + | xargs -0 shasum -a 256) > "$RUNNER_TEMP/settings" + for channel in stable nightly; do + rm -rf "$app" + mkdir -p "$app/Contents/MacOS" + cp "$RUNNER_TEMP/fixed/lpm-rs" "$app/Contents/MacOS/lpm-rs" + test "$(LPM_NO_UPDATE_CHECK=1 "$lpm" --version | sed -n 1p)" = "lpm $FIXED_BUILD_VERSION" + if [ "$channel" = stable ]; then tag=latest; else tag=nightly; fi + before=$(curl -fsSL "https://registry.npmjs.org/@lpm-registry/cli/$tag" | jq -er .version) + "$lpm" self-update --channel "$channel" --refresh --json | tee "$RUNNER_TEMP/self-update-$channel.json" + jq -e '.applied and .verified' "$RUNNER_TEMP/self-update-$channel.json" + chosen=$(jq -er .latest "$RUNNER_TEMP/self-update-$channel.json") + # What the updater chose must be the release the dist-tag named, + # before or after the update, and must be what got installed. + [ "$chosen" = "$before" ] || \ + [ "$chosen" = "$(curl -fsSL "https://registry.npmjs.org/@lpm-registry/cli/$tag" | jq -er .version)" ] + test "$(LPM_NO_UPDATE_CHECK=1 "$lpm" --version | sed -n 1p)" = "lpm $chosen" + /usr/bin/codesign --verify --strict \ + -R '=anchor apple generic and certificate leaf[subject.OU] = "823S8YKMRW" and notarized' "$app" + done + (cd "$HOME/.lpm" && shasum -a 256 --check --quiet "$RUNNER_TEMP/settings") + + - name: Restore developer tools + if: always() + run: bash scripts/ci/macos-developer-tools.sh restore "$RUNNER_TEMP/developer-tools" + + - name: Restore Apple's services + if: always() && matrix.apple-services == 'blocked' + run: bash scripts/ci/macos-apple-services.sh restore "$RUNNER_TEMP/apple-services" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d3a668f9b..c723b0957 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1884,6 +1884,13 @@ jobs: printf '{"tag_name":"v%s","published_at":"%s"}\n' "$version" "$published_at" \ > "staged-release/release-v${version}.json" + python_prefix=$(python3 -c 'import sys; print(sys.base_prefix)') + case "$python_prefix" in + /Library/Developer/*|/Applications/Xcode*) + echo "::error::python3 comes from developer tools ($python_prefix), which this smoke test removes" + exit 1 + ;; + esac python3 -m http.server 8765 --bind 127.0.0.1 \ --directory staged-release >"$RUNNER_TEMP/lpm-release-server.log" 2>&1 & server_pid=$! @@ -1904,7 +1911,15 @@ jobs: test ! -e "$HOME/.lpm/bin/lpm" - LPM_INSTALL_TEST_DOWNLOAD_BASE=http://127.0.0.1:8765 sh install.sh + # Users' Macs mostly have neither Xcode nor the Command Line Tools, + # so the installer must not need them. + bash scripts/ci/macos-developer-tools.sh hide none "$RUNNER_TEMP/developer-tools" + ( + unset DEVELOPER_DIR + env PATH=/usr/bin:/bin:/usr/sbin:/sbin \ + LPM_INSTALL_TEST_DOWNLOAD_BASE=http://127.0.0.1:8765 sh install.sh + ) + bash scripts/ci/macos-developer-tools.sh restore "$RUNNER_TEMP/developer-tools" app="$HOME/.lpm/libexec/LPM CLI.app" executable="$app/Contents/MacOS/lpm-rs" @@ -1948,6 +1963,10 @@ jobs: scripts/ci/with-apple-service-retry.sh stapler validate "$app" /usr/sbin/spctl --assess --type execute --verbose=4 "$app" + - name: Restore developer tools + if: always() && matrix.platform == 'macos' + run: bash scripts/ci/macos-developer-tools.sh restore "$RUNNER_TEMP/developer-tools" + seal-candidate: name: Seal stable release candidate needs: diff --git a/Cargo.lock b/Cargo.lock index 6babdb9e9..4647161ef 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3644,6 +3644,7 @@ dependencies = [ "rustix", "same-file", "secrecy", + "security-framework 3.7.0", "serde", "serde_json", "serde_yaml", diff --git a/crates/lpm-cli/Cargo.toml b/crates/lpm-cli/Cargo.toml index a9c1824bc..9ea00bc63 100644 --- a/crates/lpm-cli/Cargo.toml +++ b/crates/lpm-cli/Cargo.toml @@ -177,6 +177,7 @@ block2 = { version = "0.6", default-features = false, features = ["std"] } objc2 = { version = "0.6", default-features = false, features = ["std"] } objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSError", "NSString"] } objc2-local-authentication = { version = "0.3", default-features = false, features = ["std", "LAContext", "block2"] } +security-framework = { version = "3", features = ["OSX_10_15"] } [target.'cfg(windows)'.dependencies] # The generated Windows Hello bindings need none of windows-core's proc macros. diff --git a/crates/lpm-cli/src/cli/format.rs b/crates/lpm-cli/src/cli/format.rs index 157ce7673..8bd3c7500 100644 --- a/crates/lpm-cli/src/cli/format.rs +++ b/crates/lpm-cli/src/cli/format.rs @@ -546,6 +546,14 @@ fn next_steps_for_error(error: &lpm_common::LpmError) -> Option Some(crate::json_contract::command_next_steps( + recovery, + reinstall_command, + )), _ => None, } } @@ -1089,7 +1097,8 @@ fn slim_error_lines(error: &lpm_common::LpmError) -> Vec { lpm_common::LpmError::ProvenanceUnavailable(reason) => { diagnostic_lines("Provenance unavailable", Some(reason), error) } - lpm_common::LpmError::SelfUpdate(reason) => { + lpm_common::LpmError::SelfUpdate(reason) + | lpm_common::LpmError::StandaloneSelfUpdate { reason, .. } => { diagnostic_lines("Self-update refused", Some(reason), error) } lpm_common::LpmError::SecurityFloor(reason) => { diff --git a/crates/lpm-cli/src/commands/self_update.rs b/crates/lpm-cli/src/commands/self_update.rs index c080f1410..25cce581c 100644 --- a/crates/lpm-cli/src/commands/self_update.rs +++ b/crates/lpm-cli/src/commands/self_update.rs @@ -30,8 +30,8 @@ pub(crate) mod verify_release; mod windows_trust; use self::download::{ - StagedAsset, ensure_staged_file_unchanged, fetch_asset_to_staged_file, fetch_bounded, - safe_remote_label, + StagedAsset, StagedAssetError, ensure_staged_file_unchanged, fetch_asset_to_staged_file, + fetch_bounded, safe_remote_label, }; #[cfg(test)] use self::download::{create_staged_binary, finish_staged_binary}; @@ -379,8 +379,14 @@ pub async fn run( } InstallMethod::Standalone => { standalone_update = Some( - run_standalone_update(&latest, ¤t_executable, &account_home, !json_output) - .await?, + run_standalone_update( + &latest, + ¤t_executable, + &account_home, + target_channel, + !json_output, + ) + .await?, ); } } @@ -2337,6 +2343,110 @@ fn verify_release_asset_digest( }) } +/// What a standalone update refused that the official installer can take over +/// from. Other refusals name no installer, since reinstalling wouldn't fix +/// them. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum StandaloneRefusal { + /// The release's provenance or integrity. + ReleaseVerification, + /// A verified release, or an installation outside the installer's layout, + /// that this updater's checks don't accept. The installer applies its + /// current checks afresh. + Compatibility, +} + +/// A refusal the official installer can take over from names it, so a +/// refusal never leaves the user without a way to update. Without cosign the +/// installer can't tell who published a Linux release's checksums, so a Linux +/// release the updater couldn't verify is reinstalled only with its signature +/// required; on macOS the installer checks the app's Developer ID signature, +/// which only LPM's signing identity can produce. Windows has no such +/// installer. +fn with_installer_recovery( + error: LpmError, + channel: ReleaseChannel, + refusal: StandaloneRefusal, +) -> LpmError { + let LpmError::SelfUpdate(reason) = error else { + return error; + }; + if !cfg!(unix) { + return LpmError::SelfUpdate(reason); + } + let channel = channel.as_str(); + let (recovery, reinstall_command) = if refusal == StandaloneRefusal::ReleaseVerification + && cfg!(not(target_os = "macos")) + { + ( + "If this release keeps failing verification, install cosign and reinstall LPM CLI \ + with the official installer, which then checks the release's signature itself \ + and keeps your settings", + format!( + "curl -fsSL https://cli.lpm.dev/install | LPM_INSTALL_CHANNEL={channel} \ + LPM_INSTALL_REQUIRE_SIGSTORE=1 sh" + ), + ) + } else { + ( + "Reinstall LPM CLI with the official installer, which verifies the release itself \ + and keeps your settings", + format!("curl -fsSL https://cli.lpm.dev/install | LPM_INSTALL_CHANNEL={channel} sh"), + ) + }; + LpmError::StandaloneSelfUpdate { + reason, + recovery: recovery.to_string(), + reinstall_command, + } +} + +/// Runs `check` on the staged release asset between two checks that it is +/// still the verified file. A file that changed or went away is refused as +/// that, which reinstalling doesn't fix, even when it also made `check` fail; +/// only a failed check of the verified file names the installer. +fn check_staged_asset( + staged: &StagedAsset, + channel: ReleaseChannel, + check: impl FnOnce() -> Result, +) -> Result { + ensure_staged_file_unchanged(&staged.temporary, &staged.sha256)?; + let checked = check(); + ensure_staged_file_unchanged(&staged.temporary, &staged.sha256)?; + checked + .map_err(|error| with_installer_recovery(error, channel, StandaloneRefusal::Compatibility)) +} + +/// Runs the staged app's executable to check its version. A failed probe names +/// the installer only when the bundle is still the one that was validated; a +/// bundle that changed afterwards is refused as that, without it. +#[cfg(target_os = "macos")] +fn probe_staged_macos_bundle( + staged: &StagedMacOSBundle, + version: &str, + channel: ReleaseChannel, +) -> Result<(), LpmError> { + let Err(error) = VersionProbe::verify_staged_path(&staged.executable, version) else { + return Ok(()); + }; + let still_validated = validate_macos_app_bundle(&staged.app_bundle) + .is_ok_and(|fingerprint| fingerprint == staged.fingerprint); + if still_validated { + return Err(with_installer_recovery( + error, + channel, + StandaloneRefusal::Compatibility, + )); + } + let probe_failure = match error { + LpmError::SelfUpdate(reason) => reason, + other => other.to_string(), + }; + Err(LpmError::SelfUpdate(format!( + "staged macOS app bundle changed after it was validated ({probe_failure})" + ))) +} + /// Download and replace the binary in-place for standalone installations. /// /// Every fetched byte is anchored to the Sigstore-signed `SHA256SUMS.txt` @@ -2354,31 +2464,41 @@ async fn run_standalone_update( version: &str, current_executable: &Path, account_home: &Path, + channel: ReleaseChannel, human_output: bool, ) -> Result { + let refused = |refusal| move |error| with_installer_recovery(error, channel, refusal); validate_standalone_install_location(current_executable)?; #[cfg(not(target_os = "macos"))] let _ = account_home; #[cfg(target_os = "macos")] - let macos_layout = prepare_macos_standalone_layout(current_executable, account_home)?; + let macos_layout = prepare_macos_standalone_layout( + macos_standalone_layout_for(current_executable, account_home) + .map_err(refused(StandaloneRefusal::Compatibility))?, + )?; #[cfg(target_os = "macos")] let staging_anchor = macos_layout.app_parent.join(".lpm-release-asset.zip"); #[cfg(not(target_os = "macos"))] let staging_anchor = current_executable.to_path_buf(); - let assets = verify_and_stage_for_standalone(version, &staging_anchor, human_output).await?; + let assets = verify_and_stage_for_standalone(version, &staging_anchor, human_output) + .await + .map_err(|failure| match failure { + StagingFailure::ReleaseVerification(error) => { + refused(StandaloneRefusal::ReleaseVerification)(error) + } + StagingFailure::Local(error) => error, + })?; #[cfg(target_os = "macos")] { - ensure_staged_file_unchanged( - &assets.staged_binary.temporary, - &assets.staged_binary.sha256, - )?; - let staged_bundle = stage_macos_bundle( - assets.staged_binary.temporary.path(), - &macos_layout.app_parent, - )?; - VersionProbe::verify_staged_path(&staged_bundle.executable, version)?; + let staged_bundle = check_staged_asset(&assets.staged_binary, channel, || { + stage_macos_bundle( + assets.staged_binary.temporary.path(), + &macos_layout.app_parent, + ) + })?; + probe_staged_macos_bundle(&staged_bundle, version, channel)?; install_staged_macos_bundle(&macos_layout, staged_bundle, version)?; } @@ -2386,15 +2506,9 @@ async fn run_standalone_update( let sandbox_helper = None; #[cfg(not(target_os = "macos"))] let sandbox_helper = { - VersionProbe::verify_staged( - &assets.staged_binary.temporary, - &assets.staged_binary.sha256, - version, - )?; - ensure_staged_file_unchanged( - &assets.staged_binary.temporary, - &assets.staged_binary.sha256, - )?; + check_staged_asset(&assets.staged_binary, channel, || { + VersionProbe::verify_staged_version(&assets.staged_binary.temporary, version) + })?; let StagedAsset { temporary, sha256, .. } = assets.staged_binary; @@ -2587,7 +2701,7 @@ fn macos_standalone_layout_for( let internal_executable = app_bundle.join(MACOS_INTERNAL_EXECUTABLE); if current_executable != internal_executable { return Err(LpmError::SelfUpdate(format!( - "macOS standalone updates require execution from {}; reinstall with https://github.com/lpm-dev/rust-client/blob/main/install.sh", + "macOS standalone updates require execution from {}", internal_executable.display() ))); } @@ -2601,12 +2715,10 @@ fn macos_standalone_layout_for( #[cfg(target_os = "macos")] fn prepare_macos_standalone_layout( - current_executable: &Path, - account_home: &Path, + layout: MacOSStandaloneLayout, ) -> Result { use std::os::unix::fs::{DirBuilderExt as _, MetadataExt as _, PermissionsExt as _}; - let layout = macos_standalone_layout_for(current_executable, account_home)?; if let Ok(metadata) = std::fs::symlink_metadata(&layout.app_parent) { if metadata.file_type().is_symlink() || !metadata.is_dir() { return Err(LpmError::SelfUpdate(format!( @@ -2767,35 +2879,28 @@ struct StagedMacOSBundle { staging_root: tempfile::TempDir, app_bundle: PathBuf, executable: PathBuf, - notarization: ConfirmedNotarization, + fingerprint: BundleFingerprint, } -/// The code-directory hash and stapled notarization ticket of a bundle whose -/// ticket Apple's ticketing service confirmed. +/// What identifies a validated app bundle: its code-directory hash and its +/// stapled notarization ticket. #[cfg(target_os = "macos")] #[derive(Debug, PartialEq, Eq)] -struct ConfirmedNotarization { +struct BundleFingerprint { cdhash: String, - ticket: Vec, + stapled_ticket: Vec, } #[cfg(target_os = "macos")] -enum NotarizationCheck<'a> { - AskApple, - /// The bundle was moved from one whose ticket Apple confirmed, so it must - /// carry the same code and the same ticket instead of asking Apple again. - SameAs(&'a ConfirmedNotarization), -} - -#[cfg(target_os = "macos")] -impl ConfirmedNotarization { - fn confirm_same_bundle(&self, installed: &ConfirmedNotarization) -> Result<(), LpmError> { +impl BundleFingerprint { + /// The bundle moved into place must be the staged one that was validated, + /// with the same code and the same ticket. + fn confirm_same_bundle(&self, installed: &BundleFingerprint) -> Result<(), LpmError> { if self == installed { return Ok(()); } Err(LpmError::SelfUpdate( - "installed macOS app differs from the staged bundle whose notarization ticket Apple confirmed" - .to_string(), + "installed macOS app differs from the staged bundle that was validated".to_string(), )) } } @@ -2811,7 +2916,7 @@ fn stage_macos_bundle( .tempdir_in(app_parent) .map_err(LpmError::Io)?; run_macos_validation_tool( - "/usr/bin/ditto", + MacOSTool::Ditto, &[ OsStr::new("-x"), OsStr::new("-k"), @@ -2821,13 +2926,13 @@ fn stage_macos_bundle( "macOS app extraction", )?; let app_bundle = staging_root.path().join(MACOS_APP_NAME); - let notarization = validate_macos_app_bundle(&app_bundle, NotarizationCheck::AskApple)?; + let fingerprint = validate_macos_app_bundle(&app_bundle)?; let executable = app_bundle.join(MACOS_INTERNAL_EXECUTABLE); Ok(StagedMacOSBundle { staging_root, app_bundle, executable, - notarization, + fingerprint, }) } @@ -2950,30 +3055,54 @@ fn validate_macos_app_inventory(app_bundle: &Path) -> Result<(), LpmError> { Ok(()) } +/// The programs macOS bundle validation runs. Each must ship with macOS and +/// work without Apple's services: an `xcrun` shim such as `/usr/bin/stapler` +/// fails on a Mac without Xcode or the Command Line Tools, and Gatekeeper's +/// assessors answer from the Mac's security policy and Apple's services. An +/// updater that depends on either can't update every Mac. +#[cfg(target_os = "macos")] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum MacOSTool { + Codesign, + Ditto, + PlistBuddy, +} + +#[cfg(target_os = "macos")] +impl MacOSTool { + #[cfg(test)] + const ALL: [Self; 3] = { + // A new variant breaks this match, a reminder to list it here too. + match Self::Codesign { + Self::Codesign | Self::Ditto | Self::PlistBuddy => {} + } + [Self::Codesign, Self::Ditto, Self::PlistBuddy] + }; + + const fn path(self) -> &'static str { + match self { + Self::Codesign => "/usr/bin/codesign", + Self::Ditto => "/usr/bin/ditto", + Self::PlistBuddy => "/usr/libexec/PlistBuddy", + } + } +} + #[cfg(target_os = "macos")] fn run_macos_validation_tool( - program: &str, + tool: MacOSTool, arguments: &[&OsStr], description: &str, ) -> Result { - let output = run_macos_validation_tool_once(program, arguments, description)?; + let output = validation::run(tool.path(), arguments, description, Duration::from_secs(60))?; if !output.status.success() { return Err(macos_validation_failure(description, &output)); } Ok(output) } -#[cfg(target_os = "macos")] -fn run_macos_validation_tool_once( - program: &str, - arguments: &[&OsStr], - description: &str, -) -> Result { - validation::run(program, arguments, description, Duration::from_secs(60)) -} - /// Names the failure in the tool's own words: its stderr, or its stdout -/// when stderr is empty, which is where `stapler` reports. +/// when stderr is empty. #[cfg(target_os = "macos")] fn macos_validation_failure(description: &str, output: &std::process::Output) -> LpmError { let stderr = String::from_utf8_lossy(&output.stderr); @@ -2994,53 +3123,11 @@ fn macos_validation_failure(description: &str, output: &std::process::Output) -> )) } -/// `stapler validate` checks the stapled ticket against Apple's CloudKit -/// record and exits with `EX_NOHOST` when CloudKit doesn't answer. -#[cfg(target_os = "macos")] -const STAPLER_CLOUDKIT_UNREACHABLE: i32 = 68; - -/// CloudKit lookups have kept failing for over 20 s at a time, so the checks -/// spread over about two minutes before giving up, as install.sh's do. -#[cfg(target_os = "macos")] -const NOTARIZATION_TICKET_RETRY_DELAYS: [Duration; 5] = [ - Duration::from_secs(2), - Duration::from_secs(5), - Duration::from_secs(15), - Duration::from_secs(30), - Duration::from_secs(60), -]; - -/// Validates the bundle's stapled notarization ticket, running `stapler` -/// again after each of `retry_delays` while CloudKit doesn't answer. Any -/// other failure, an invalid or missing ticket among them, fails at once. -#[cfg(target_os = "macos")] -fn validate_notarization_ticket( - stapler: &str, - app_bundle: &Path, - retry_delays: &[Duration], -) -> Result<(), LpmError> { - const DESCRIPTION: &str = "macOS notarization-ticket validation"; - let arguments = [OsStr::new("validate"), app_bundle.as_os_str()]; - let mut retry_delays = retry_delays.iter(); - loop { - let output = run_macos_validation_tool_once(stapler, &arguments, DESCRIPTION)?; - if output.status.success() { - return Ok(()); - } - match retry_delays.next() { - Some(delay) if output.status.code() == Some(STAPLER_CLOUDKIT_UNREACHABLE) => { - std::thread::sleep(*delay); - } - _ => return Err(macos_validation_failure(DESCRIPTION, &output)), - } - } -} - #[cfg(target_os = "macos")] fn plist_buddy_value(plist: &Path, key: &str) -> Result { let command = format!("Print :{key}"); let output = run_macos_validation_tool( - "/usr/libexec/PlistBuddy", + MacOSTool::PlistBuddy, &[OsStr::new("-c"), command.as_ref(), plist.as_os_str()], "provisioning-profile metadata validation", )?; @@ -3080,32 +3167,86 @@ fn macos_entitlement_inspection_arguments(app_bundle: &Path) -> [&OsStr; 4] { ] } +/// The code requirement every LPM macOS app satisfies: a Developer ID +/// Application signature of LPM's team over its bundle identifier, on code +/// Apple notarized. `codesign` judges `notarized` itself, from the stapled +/// ticket when Apple can't be reached. The leading `=` marks inline +/// requirement text. +#[cfg(target_os = "macos")] +fn macos_code_requirement() -> String { + format!( + "=anchor apple generic and identifier \"{MACOS_EXPECTED_BUNDLE_ID}\" \ + and certificate 1[field.1.2.840.113635.100.6.2.6] exists \ + and certificate leaf[field.1.2.840.113635.100.6.1.13] exists \ + and certificate leaf[subject.OU] = \"{MACOS_EXPECTED_TEAM_ID}\" \ + and notarized" + ) +} + +/// Profiles are about 12 KiB; the bound keeps a hostile one out of memory. +#[cfg(target_os = "macos")] +const MACOS_PROVISIONING_PROFILE_MAX_BYTES: u64 = 1024 * 1024; + +/// Decodes the provisioning profile's CMS envelope in process. `security cms +/// -D` would import the envelope's certificates into the default keychain, +/// and fails for an account without one. The profile is a sealed resource of +/// the code signature verified first, so only its content is needed. +#[cfg(target_os = "macos")] +fn decode_provisioning_profile(profile: &Path) -> Result, LpmError> { + use std::io::Read as _; + + let mut message = Vec::new(); + std::fs::File::open(profile) + .map_err(LpmError::Io)? + .take(MACOS_PROVISIONING_PROFILE_MAX_BYTES + 1) + .read_to_end(&mut message) + .map_err(LpmError::Io)?; + if message.len() as u64 > MACOS_PROVISIONING_PROFILE_MAX_BYTES { + return Err(LpmError::SelfUpdate( + "macOS provisioning profile exceeds its size limit".to_string(), + )); + } + let decode = || { + let decoder = security_framework::cms::CMSDecoder::create()?; + decoder.update_message(&message)?; + decoder.finalize_message()?; + decoder.get_content() + }; + decode().map_err(|error| { + LpmError::SelfUpdate(format!( + "macOS provisioning profile could not be decoded: {error}" + )) + }) +} + +/// Validates an app bundle's contents, code signature and notarization, +/// signing identity, entitlements and provisioning profile. #[cfg(target_os = "macos")] -fn validate_macos_app_bundle( - app_bundle: &Path, - notarization_check: NotarizationCheck<'_>, -) -> Result { +fn validate_macos_app_bundle(app_bundle: &Path) -> Result { use std::io::Write as _; validate_macos_app_inventory(app_bundle)?; + let requirement = macos_code_requirement(); run_macos_validation_tool( - "/usr/bin/codesign", + MacOSTool::Codesign, &[ OsStr::new("--verify"), OsStr::new("--strict"), OsStr::new("--verbose=4"), + OsStr::new("-R"), + OsStr::new(&requirement), app_bundle.as_os_str(), ], - "macOS app code-signature validation", + "macOS app code-signature and notarization validation", )?; let details = run_macos_validation_tool( - "/usr/bin/codesign", + MacOSTool::Codesign, &[OsStr::new("-dvvv"), app_bundle.as_os_str()], "macOS app signing-identity inspection", )?; let details = format!( - "{}{}", + "{}\n{}", String::from_utf8_lossy(&details.stdout), String::from_utf8_lossy(&details.stderr) ); @@ -3127,14 +3268,15 @@ fn validate_macos_app_bundle( "macOS app signature has no code-directory hash".to_string(), )); }; - let notarization = ConfirmedNotarization { + let fingerprint = BundleFingerprint { cdhash: cdhash.to_string(), - ticket: std::fs::read(app_bundle.join("Contents/CodeResources")).map_err(LpmError::Io)?, + stapled_ticket: std::fs::read(app_bundle.join("Contents/CodeResources")) + .map_err(LpmError::Io)?, }; let entitlement_arguments = macos_entitlement_inspection_arguments(app_bundle); let signed_entitlements = run_macos_validation_tool( - "/usr/bin/codesign", + MacOSTool::Codesign, &entitlement_arguments, "macOS app entitlement inspection", )?; @@ -3150,20 +3292,11 @@ fn validate_macos_app_bundle( )); } - let profile = app_bundle.join("Contents/embedded.provisionprofile"); - let decoded_profile = run_macos_validation_tool( - "/usr/bin/security", - &[ - OsStr::new("cms"), - OsStr::new("-D"), - OsStr::new("-i"), - profile.as_os_str(), - ], - "macOS provisioning-profile decoding", - )?; + let decoded_profile = + decode_provisioning_profile(&app_bundle.join("Contents/embedded.provisionprofile"))?; let mut profile_plist = tempfile::NamedTempFile::new().map_err(LpmError::Io)?; profile_plist - .write_all(&decoded_profile.stdout) + .write_all(&decoded_profile) .map_err(LpmError::Io)?; profile_plist.flush().map_err(LpmError::Io)?; let profile_team = plist_buddy_value(profile_plist.path(), "TeamIdentifier:0")?; @@ -3179,27 +3312,7 @@ fn validate_macos_app_bundle( .to_string(), )); } - - match notarization_check { - NotarizationCheck::AskApple => validate_notarization_ticket( - "/usr/bin/stapler", - app_bundle, - &NOTARIZATION_TICKET_RETRY_DELAYS, - )?, - NotarizationCheck::SameAs(confirmed) => confirmed.confirm_same_bundle(¬arization)?, - } - run_macos_validation_tool( - "/usr/sbin/spctl", - &[ - OsStr::new("--assess"), - OsStr::new("--type"), - OsStr::new("execute"), - OsStr::new("--verbose=4"), - app_bundle.as_os_str(), - ], - "macOS Gatekeeper validation", - )?; - Ok(notarization) + Ok(fingerprint) } #[cfg(target_os = "macos")] @@ -3270,10 +3383,8 @@ fn install_staged_macos_bundle( installed_lpm = true; lpm_common::replace_symlink_atomic(&layout.lpx_link, link_target).map_err(LpmError::Io)?; installed_lpx = true; - validate_macos_app_bundle( - &layout.app_bundle, - NotarizationCheck::SameAs(&staged.notarization), - )?; + let installed = validate_macos_app_bundle(&layout.app_bundle)?; + staged.fingerprint.confirm_same_bundle(&installed)?; let final_executable = layout.app_bundle.join(MACOS_INTERNAL_EXECUTABLE); VersionProbe::verify_staged_path(&final_executable, version)?; let expected_executable = std::fs::canonicalize(&final_executable).map_err(LpmError::Io)?; @@ -3377,9 +3488,7 @@ async fn fetch_verified_release_manifest( .await? .ok_or_else(|| { LpmError::SelfUpdate(format!( - "release v{version} does not ship SHA256SUMS.txt — this release predates LPM's \ - signed-install gate. Install manually from \ - https://github.com/lpm-dev/rust-client/releases/v{version}" + "release v{version} does not ship SHA256SUMS.txt, so it can't be verified" )) }) }; @@ -3389,26 +3498,23 @@ async fn fetch_verified_release_manifest( .ok_or_else(|| { LpmError::SelfUpdate(format!( "release v{version} ships SHA256SUMS.txt but not SHA256SUMS.txt.sigstore — \ - cannot cryptographically verify the manifest. Install manually." + cannot cryptographically verify the manifest" )) }) }; let release_metadata = async { - fetch_github_release(version) - .await - .map_err(|e| match e { - LookupError::NotFound(_) => LpmError::SelfUpdate(format!( - "GitHub has no release at tag v{version} — cannot anchor the Sigstore replay window. \ - Install manually." - )), - LookupError::MalformedResponse(msg) => LpmError::SelfUpdate(format!( - "release v{version} did not expose valid release metadata: {msg}. \ + fetch_github_release(version).await.map_err(|e| match e { + LookupError::NotFound(_) => LpmError::SelfUpdate(format!( + "GitHub has no release at tag v{version} — cannot anchor the Sigstore replay window" + )), + LookupError::MalformedResponse(msg) => LpmError::SelfUpdate(format!( + "release v{version} did not expose valid release metadata: {msg}. \ Cannot bind the Sigstore attestation to the requested release." - )), - other => LpmError::Network(format!( - "could not fetch release metadata for v{version}: {other}" - )), - }) + )), + other => LpmError::Network(format!( + "could not fetch release metadata for v{version}: {other}" + )), + }) }; let (manifest_bytes, bundle_bytes, release) = @@ -3419,33 +3525,72 @@ async fn fetch_verified_release_manifest( verify_release_manifest(version, &manifest_bytes, &bundle_bytes, &release) } +/// Why a standalone release couldn't be staged: it didn't verify, or +/// something on this machine failed, such as a staged file replaced under the +/// updater. Only the first is the release's doing. +#[derive(Debug)] +enum StagingFailure { + ReleaseVerification(LpmError), + Local(LpmError), +} + +impl From for StagingFailure { + fn from(error: LpmError) -> Self { + Self::Local(error) + } +} + +impl StagingFailure { + /// An asset larger than this updater accepts is the release's doing, so + /// a release that outgrows the cap still names the installer. + fn from_asset_error(error: StagedAssetError) -> Self { + match error { + StagedAssetError::TooLarge(error) => Self::ReleaseVerification(error), + StagedAssetError::Failed(error) => Self::Local(error), + } + } + + #[cfg(test)] + fn into_error(self) -> LpmError { + match self { + Self::ReleaseVerification(error) | Self::Local(error) => error, + } + } +} + async fn verify_and_stage_for_standalone( version: &str, staging_anchor: &std::path::Path, human_output: bool, -) -> Result { +) -> Result { let (platform, ext) = detect_platform()?; let binary_name = standalone_asset_name_for(std::env::consts::OS, platform, ext); let asset_url = github_release_download_url(version, &binary_name); let client = release_http_client()?; - let release = fetch_verified_release_manifest(&client, version, human_output).await?; + let release = fetch_verified_release_manifest(&client, version, human_output) + .await + .map_err(StagingFailure::ReleaseVerification)?; if !release.entries.contains_key(&binary_name) { - return Err(LpmError::SelfUpdate(format!( - "SHA256SUMS.txt does not enumerate `{binary_name}` for this platform — release pipeline may be missing artifacts" + return Err(StagingFailure::ReleaseVerification(LpmError::SelfUpdate( + format!( + "SHA256SUMS.txt does not enumerate `{binary_name}` for this platform — release pipeline may be missing artifacts" + ), ))); } let staged = fetch_asset_to_staged_file(&client, &asset_url, ASSET_MAX_BYTES, staging_anchor) - .await? + .await + .map_err(StagingFailure::from_asset_error)? .ok_or_else(|| { - LpmError::SelfUpdate(format!( + StagingFailure::ReleaseVerification(LpmError::SelfUpdate(format!( "release v{version} advertises `{binary_name}` in SHA256SUMS.txt but the asset is missing at {} — release-pipeline bug", safe_remote_label(&asset_url) - )) + ))) })?; - let audit = verify_release_asset_digest(&release, staged.sha256.clone(), &binary_name)?; + let audit = verify_release_asset_digest(&release, staged.sha256.clone(), &binary_name) + .map_err(StagingFailure::ReleaseVerification)?; if human_output { install_ui::done_untrusted(&format!( @@ -3480,7 +3625,9 @@ async fn verify_and_stage_for_standalone( #[cfg(test)] async fn verify_and_fetch_for_standalone(version: &str) -> Result { let destination = std::env::temp_dir().join("lpm-self-update-test-bin"); - verify_and_stage_for_standalone(version, &destination, false).await + verify_and_stage_for_standalone(version, &destination, false) + .await + .map_err(StagingFailure::into_error) } /// Atomically swap the running binary at `current_exe` for a verified, @@ -4091,7 +4238,8 @@ mod tests { lpx_link: bin.join("lpx"), }; for archive in archives.iter().chain(archives.first()) { - let staged = stage_macos_bundle(archive, &layout.app_parent).unwrap(); + let staged = stage_macos_bundle(archive, &layout.app_parent) + .unwrap_or_else(|error| panic!("{}: {error}", archive.display())); let output = std::process::Command::new(&staged.executable) .arg("--version") .output() @@ -4120,12 +4268,55 @@ mod tests { staged.executable.clone() }; std::fs::remove_file(sealed).unwrap(); - assert!( - validate_macos_app_bundle(&staged.app_bundle, NotarizationCheck::AskApple).is_err() - ); + assert!(validate_macos_app_bundle(&staged.app_bundle).is_err()); } } + #[cfg(target_os = "macos")] + #[test] + #[ignore = "requires two signed release archives in LPM_TEST_MACOS_RELEASE_ARCHIVES"] + fn signed_macos_release_probe_names_the_installer_only_for_the_validated_bundle() { + let archives = std::env::var_os("LPM_TEST_MACOS_RELEASE_ARCHIVES") + .expect("set LPM_TEST_MACOS_RELEASE_ARCHIVES to signed release ZIP paths"); + let archives = std::env::split_paths(&archives).collect::>(); + let [first, second, ..] = archives.as_slice() else { + panic!("LPM_TEST_MACOS_RELEASE_ARCHIVES must name two signed release archives"); + }; + let parent = tempfile::tempdir().unwrap(); + let staged = stage_macos_bundle(first, parent.path()).unwrap(); + + let error = probe_staged_macos_bundle(&staged, "0.0.0", ReleaseChannel::Stable) + .expect_err("a release reports its own version, not 0.0.0"); + assert!( + matches!(&error, LpmError::StandaloneSelfUpdate { reason, .. } if reason.contains("exact version 0.0.0")), + "a failed probe of the validated bundle must name the installer: {error:?}" + ); + + // Another genuine release validates too, but isn't the bundle that was. + let other_parent = tempfile::tempdir().unwrap(); + let other = stage_macos_bundle(second, other_parent.path()).unwrap(); + assert_ne!(other.fingerprint, staged.fingerprint); + std::fs::remove_dir_all(&staged.app_bundle).unwrap(); + std::fs::rename(&other.app_bundle, &staged.app_bundle).unwrap(); + let error = probe_staged_macos_bundle(&staged, "0.0.0", ReleaseChannel::Stable) + .expect_err("a release reports its own version, not 0.0.0"); + assert!( + matches!(&error, LpmError::SelfUpdate(reason) if reason.contains("changed after it was validated")), + "another validly signed bundle must be refused as a changed bundle, without the installer: {error:?}" + ); + + std::fs::write(&staged.executable, b"#!/bin/sh\nexit 1\n").unwrap(); + let error = probe_staged_macos_bundle(&staged, "0.0.0", ReleaseChannel::Stable) + .expect_err("a replaced executable must not pass the probe"); + assert!( + matches!(&error, LpmError::SelfUpdate(reason) if reason.contains("changed after it was validated")), + "a bundle changed after validation must be refused as that, without the installer: {error:?}" + ); + } + + /// Whether `codesign` still finds the code notarized depends on what the + /// system recorded from the first check; either way the bundle must not + /// be installed. #[cfg(target_os = "macos")] #[test] #[ignore = "requires signed release archives in LPM_TEST_MACOS_RELEASE_ARCHIVES"] @@ -4158,9 +4349,8 @@ mod tests { .to_string(); assert!( - error.contains( - "differs from the staged bundle whose notarization ticket Apple confirmed" - ), + error.contains("differs from the staged bundle that was validated") + || error.contains("code-signature and notarization validation"), "{error}" ); assert!(!layout.app_bundle.exists()); @@ -4268,7 +4458,7 @@ mod tests { staging_root, app_bundle: staged_app, executable: staged_executable, - notarization: fixture_notarization(), + fingerprint: fixture_fingerprint(), }; let error = install_staged_macos_bundle(&layout, staged, "0.75.0") @@ -4321,7 +4511,7 @@ mod tests { staging_root, app_bundle: staged_app, executable: staged_executable, - notarization: fixture_notarization(), + fingerprint: fixture_fingerprint(), }; let error = install_staged_macos_bundle(&layout, staged, "0.75.0") @@ -5218,6 +5408,176 @@ bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb lpm-linux-x64 .await; } + /// A release without a manifest can't be verified, which is the release's + /// doing. + #[tokio::test] + async fn release_without_a_manifest_is_a_release_verification_failure() { + let server = wiremock::MockServer::start().await; + mount_release_metadata(&server).await; + mount_placeholder_bundle(&server).await; + wiremock::Mock::given(wiremock::matchers::method("GET")) + .and(wiremock::matchers::path("/download/v0.42.0/SHA256SUMS.txt")) + .respond_with(wiremock::ResponseTemplate::new(404)) + .mount(&server) + .await; + + run_standalone_against_server(&server, "0.42.0", || async { + let destination = tempfile::tempdir().unwrap(); + let failure = + verify_and_stage_for_standalone("0.42.0", &destination.path().join("lpm"), false) + .await + .expect_err("a release without a manifest must not stage"); + assert!( + matches!( + &failure, + StagingFailure::ReleaseVerification(LpmError::SelfUpdate(reason)) + if reason.contains("does not ship SHA256SUMS.txt") + ), + "{failure:?}" + ); + }) + .await; + } + + /// Serves the published v0.84.0 release, whose manifest and Sigstore + /// bundle verify, with `asset` as every platform's release asset. The + /// release ships assets only for the targets these tests run on. + #[cfg(any( + all( + target_os = "macos", + any(target_arch = "x86_64", target_arch = "aarch64") + ), + all(target_os = "linux", target_arch = "x86_64"), + all(target_os = "linux", target_arch = "aarch64", not(target_env = "musl")), + all(windows, target_arch = "x86_64") + ))] + async fn mount_real_v0_84_0_release(server: &wiremock::MockServer, asset: &'static [u8]) { + let (manifest, bundle) = real_v0_84_0_release_assets(); + let routes = [ + ( + "/releases/tags/v0.84.0".to_string(), + wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "tag_name": "v0.84.0", + "published_at": REAL_V0_84_0_PUBLISHED_AT, + "target_commitish": REAL_V0_84_0_SOURCE_COMMIT, + })), + ), + ( + "/download/v0.84.0/SHA256SUMS.txt".to_string(), + wiremock::ResponseTemplate::new(200).set_body_bytes(manifest), + ), + ( + "/download/v0.84.0/SHA256SUMS.txt.sigstore".to_string(), + wiremock::ResponseTemplate::new(200).set_body_bytes(bundle), + ), + ]; + for (path, response) in routes { + wiremock::Mock::given(wiremock::matchers::method("GET")) + .and(wiremock::matchers::path(path)) + .respond_with(response) + .mount(server) + .await; + } + wiremock::Mock::given(wiremock::matchers::method("GET")) + .and(wiremock::matchers::path_regex(r"^/download/v0\.84\.0/lpm-")) + .respond_with(wiremock::ResponseTemplate::new(200).set_body_bytes(asset)) + .mount(server) + .await; + } + + #[cfg(any( + all( + target_os = "macos", + any(target_arch = "x86_64", target_arch = "aarch64") + ), + all(target_os = "linux", target_arch = "x86_64"), + all(target_os = "linux", target_arch = "aarch64", not(target_env = "musl")), + all(windows, target_arch = "x86_64") + ))] + #[tokio::test] + async fn release_asset_that_differs_from_its_signed_digest_is_a_release_verification_failure() { + let server = wiremock::MockServer::start().await; + mount_real_v0_84_0_release(&server, b"not the signed release asset").await; + + run_standalone_against_server(&server, "0.84.0", || async { + let destination = tempfile::tempdir().unwrap(); + let failure = + verify_and_stage_for_standalone("0.84.0", &destination.path().join("lpm"), false) + .await + .expect_err("an asset that isn't the signed one must not stage"); + assert!( + matches!( + &failure, + StagingFailure::ReleaseVerification(LpmError::SelfUpdate(reason)) + if reason.contains("SHA-256 mismatch") + ), + "{failure:?}" + ); + }) + .await; + } + + #[test] + fn release_asset_over_the_size_cap_is_a_release_verification_failure() { + let too_large = StagedAssetError::TooLarge(LpmError::SelfUpdate("cap".to_string())); + let failed = StagedAssetError::Failed(LpmError::SelfUpdate("disk".to_string())); + + assert!(matches!( + StagingFailure::from_asset_error(too_large), + StagingFailure::ReleaseVerification(_) + )); + assert!(matches!( + StagingFailure::from_asset_error(failed), + StagingFailure::Local(_) + )); + } + + /// Staging errors no step marks as the release's, such as an I/O failure, + /// are local. + #[test] + fn unmarked_staging_errors_are_local() { + let error = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "staging"); + assert!(matches!( + StagingFailure::from(LpmError::Io(error)), + StagingFailure::Local(LpmError::Io(_)) + )); + } + + /// Staging that fails on this machine, after the release verified, isn't + /// the release's doing. + #[cfg(any( + all( + target_os = "macos", + any(target_arch = "x86_64", target_arch = "aarch64") + ), + all(target_os = "linux", target_arch = "x86_64"), + all(target_os = "linux", target_arch = "aarch64", not(target_env = "musl")), + all(windows, target_arch = "x86_64") + ))] + #[tokio::test] + async fn staging_that_fails_on_this_machine_is_a_local_failure() { + let server = wiremock::MockServer::start().await; + mount_real_v0_84_0_release(&server, b"not the signed release asset").await; + + run_standalone_against_server(&server, "0.84.0", || async { + let destination = tempfile::tempdir().unwrap(); + let missing_directory = destination.path().join("missing"); + let failure = + verify_and_stage_for_standalone("0.84.0", &missing_directory.join("lpm"), false) + .await + .expect_err("staging into a missing directory must fail"); + assert!( + matches!( + &failure, + StagingFailure::Local(LpmError::Io(error)) + if error.kind() == std::io::ErrorKind::NotFound + ), + "{failure:?}" + ); + }) + .await; + } + #[tokio::test] async fn standalone_update_refuses_when_manifest_is_404() { let server = wiremock::MockServer::start().await; @@ -5238,10 +5598,7 @@ bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb lpm-linux-x64 .expect_err("missing manifest must fail-closed"); match err { LpmError::SelfUpdate(msg) => { - assert!( - msg.contains("predates LPM's signed-install gate"), - "msg: {msg}" - ); + assert!(msg.contains("does not ship SHA256SUMS.txt"), "msg: {msg}"); assert!(msg.contains("0.42.0"), "version must appear: {msg}"); } other => panic!("expected SelfUpdate, got {other:?}"), @@ -5440,11 +5797,7 @@ bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb lpm-linux-x64 .expect_err("missing release tag must fail-closed"); match err { LpmError::SelfUpdate(msg) => { - assert!( - msg.contains("no release at tag v0.42.0") - || msg.contains("Install manually"), - "msg points the user at manual install: {msg}" - ); + assert!(msg.contains("no release at tag v0.42.0"), "msg: {msg}"); } other => panic!("expected SelfUpdate, got {other:?}"), } @@ -6839,211 +7192,298 @@ bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb lpm-linux-x64 #[cfg(target_os = "macos")] #[test] - fn macos_validation_refuses_excessive_output() { - let result = run_macos_validation_tool( - "/bin/sh", - &[ - OsStr::new("-c"), - OsStr::new("/usr/bin/head -c 2097152 /dev/zero"), - ], - "noisy validation fixture", + fn code_requirement_is_the_one_install_sh_enforces() { + let install_sh = + std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("../../install.sh")) + .unwrap(); + let assignment = |name: &str| { + install_sh + .lines() + .find_map(|line| line.strip_prefix(&format!("{name}=\""))) + .and_then(|value| value.strip_suffix('"')) + .unwrap_or_else(|| panic!("install.sh sets {name}")) + .to_string() + }; + let install_sh_requirement = assignment("MACOS_CODE_REQUIREMENT") + .replace("\\\"", "\"") + .replace("$EXPECTED_BUNDLE_ID", &assignment("EXPECTED_BUNDLE_ID")) + .replace("$EXPECTED_TEAM_ID", &assignment("EXPECTED_TEAM_ID")); + + assert_eq!( + format!("={install_sh_requirement}"), + macos_code_requirement() ); - assert!(result.is_err(), "validation output must be bounded"); } + /// `codesign` exits 3 when code fails a requirement and 1 when it can't + /// parse one; an Apple platform binary fails LPM's requirement. #[cfg(target_os = "macos")] #[test] - fn macos_validation_does_not_wait_for_inherited_output_after_parent_exit() { - let directory = tempfile::tempdir().unwrap(); - let pid_file = directory.path().join("child-pid"); - let script = format!("/bin/sleep 5 & echo $! > '{}'; exit 0", pid_file.display()); - let started = Instant::now(); - let result = run_macos_validation_tool( - "/bin/sh", - &[OsStr::new("-c"), OsStr::new(&script)], - "detached output fixture", - ); - let elapsed = started.elapsed(); - if let Ok(pid) = std::fs::read_to_string(pid_file) - .unwrap() - .trim() - .parse::() - { - // SAFETY: the PID belongs to the disposable child created by this test. - unsafe { - libc::kill(pid, libc::SIGKILL); - } - } - result.unwrap(); - assert!( - elapsed < Duration::from_secs(3), - "inherited pipe delayed completion: {elapsed:?}" + fn code_requirement_parses_and_rejects_code_lpm_did_not_sign() { + let requirement = macos_code_requirement(); + let output = std::process::Command::new(MacOSTool::Codesign.path()) + .args(["--verify", "--strict", "-R", &requirement, "/usr/bin/true"]) + .output() + .unwrap(); + + assert_eq!( + output.status.code(), + Some(3), + "{}", + String::from_utf8_lossy(&output.stderr) ); } - /// A `stapler` that exits with `exit_codes[n]` on its nth run, reporting - /// on stdout as the real one does, and records each run's arguments. #[cfg(target_os = "macos")] - fn fake_stapler(directory: &Path, exit_codes: &[i32]) -> PathBuf { - use std::os::unix::fs::PermissionsExt as _; - let runs = directory.join("runs"); - let stapler = directory.join("stapler"); - let codes = exit_codes - .iter() - .map(i32::to_string) - .collect::>() - .join(" "); + #[test] + fn provisioning_profile_that_is_oversized_or_not_cms_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let oversized = directory.path().join("oversized.provisionprofile"); std::fs::write( - &stapler, - format!( - "#!/bin/sh\n\ - printf '%s\\n' \"$*\" >> '{runs}'\n\ - code=$(echo '{codes}' | cut -d' ' -f$(($(wc -l < '{runs}'))))\n\ - if [ \"$code\" = 0 ]; then echo 'The validate action worked!'; exit 0; fi\n\ - echo \"CloudKit's response is inconsistent with expections: (null)\"\n\ - echo \"The validate action failed! Error $code.\"\n\ - exit \"$code\"\n", - runs = runs.display(), - ), + &oversized, + vec![0_u8; MACOS_PROVISIONING_PROFILE_MAX_BYTES as usize + 1], ) .unwrap(); - std::fs::set_permissions(&stapler, std::fs::Permissions::from_mode(0o755)).unwrap(); - stapler + let corrupt = directory.path().join("corrupt.provisionprofile"); + std::fs::write(&corrupt, b"not a CMS envelope").unwrap(); + + let oversized = decode_provisioning_profile(&oversized) + .unwrap_err() + .to_string(); + let corrupt = decode_provisioning_profile(&corrupt) + .unwrap_err() + .to_string(); + + assert!(oversized.contains("exceeds its size limit"), "{oversized}"); + assert!(corrupt.contains("could not be decoded"), "{corrupt}"); } + /// Every `xcrun` shim in `/usr/bin` is a hard link of `git` (the Command + /// Line Tools shims) or of `xcodebuild` (the Xcode-only shims), and needs + /// a developer directory that a Mac without developer tools doesn't have. + /// Gatekeeper's assessors answer from the Mac's security policy and + /// Apple's services, so they can refuse a genuine release. #[cfg(target_os = "macos")] - fn stapler_runs(directory: &Path) -> Vec { - std::fs::read_to_string(directory.join("runs")) - .unwrap() - .lines() - .map(str::to_string) - .collect() + #[test] + fn macos_bundle_validation_runs_only_local_programs_that_ship_with_macos() { + use std::os::unix::fs::MetadataExt as _; + let file_identity = |path: &str| { + let metadata = + std::fs::metadata(path).unwrap_or_else(|error| panic!("{path}: {error}")); + (metadata.dev(), metadata.ino()) + }; + let shims = ["/usr/bin/git", "/usr/bin/xcodebuild"].map(file_identity); + let shim_runner_and_assessors = [ + "/usr/bin/xcrun", + "/usr/sbin/spctl", + "/usr/bin/syspolicy_check", + ]; + + for tool in MacOSTool::ALL { + assert!( + !shim_runner_and_assessors.contains(&tool.path()), + "{} can refuse a genuine release on some Macs", + tool.path() + ); + assert!( + !shims.contains(&file_identity(tool.path())), + "{} is an xcrun shim, which needs Xcode or the Command Line Tools", + tool.path() + ); + } } - #[cfg(target_os = "macos")] + #[cfg(unix)] + fn installer_recovery(channel: ReleaseChannel, refusal: StandaloneRefusal) -> (String, String) { + match with_installer_recovery( + LpmError::SelfUpdate("refused".to_string()), + channel, + refusal, + ) { + LpmError::StandaloneSelfUpdate { + reason, + recovery, + reinstall_command, + } => { + assert_eq!(reason, "refused"); + (recovery, reinstall_command) + } + other => panic!("expected a refusal naming the installer, got {other:?}"), + } + } + + #[cfg(unix)] #[test] - fn notarization_ticket_check_outlasts_a_brief_cloudkit_outage() { - let directory = tempfile::tempdir().unwrap(); - let stapler = fake_stapler(directory.path(), &[68, 68, 0]); + fn refusal_the_installer_can_take_over_names_it_for_its_channel() { + for (channel, command) in [ + ( + ReleaseChannel::Stable, + "curl -fsSL https://cli.lpm.dev/install | LPM_INSTALL_CHANNEL=stable sh", + ), + ( + ReleaseChannel::Nightly, + "curl -fsSL https://cli.lpm.dev/install | LPM_INSTALL_CHANNEL=nightly sh", + ), + ] { + let (_, reinstall_command) = + installer_recovery(channel, StandaloneRefusal::Compatibility); + assert_eq!(reinstall_command, command); + } + } - validate_notarization_ticket( - stapler.to_str().unwrap(), - Path::new("/Applications/LPM CLI.app"), - &[Duration::ZERO; 2], - ) - .unwrap(); + /// Without cosign, the installer can't tell who published a Linux + /// release's checksums, so it could install what the updater refused. + #[cfg(all(unix, not(target_os = "macos")))] + #[test] + fn release_refused_by_verification_on_linux_is_reinstalled_only_with_its_signature_checked() { + let (recovery, reinstall_command) = installer_recovery( + ReleaseChannel::Stable, + StandaloneRefusal::ReleaseVerification, + ); assert_eq!( - stapler_runs(directory.path()), - vec!["validate /Applications/LPM CLI.app"; 3] + reinstall_command, + "curl -fsSL https://cli.lpm.dev/install | LPM_INSTALL_CHANNEL=stable LPM_INSTALL_REQUIRE_SIGSTORE=1 sh" ); + assert!(recovery.contains("cosign"), "{recovery}"); } + /// The installer checks the app's Developer ID signature, which only + /// LPM's signing identity can produce. #[cfg(target_os = "macos")] #[test] - fn notarization_ticket_check_reports_a_lasting_cloudkit_outage_in_stapler_s_words() { + fn release_refused_by_verification_on_macos_is_reinstalled_through_the_developer_id_check() { + assert_eq!( + installer_recovery( + ReleaseChannel::Stable, + StandaloneRefusal::ReleaseVerification + ), + installer_recovery(ReleaseChannel::Stable, StandaloneRefusal::Compatibility) + ); + } + + /// A staged binary that runs the shell `script` when probed. + #[cfg(unix)] + fn staged_script(directory: &Path, script: &str) -> StagedAsset { + use sha2::Digest as _; + use std::io::Write as _; + + let body = format!("#!/bin/sh\n{script}\n"); + let mut temporary = download::create_staged_binary(&directory.join("lpm")).unwrap(); + temporary.as_file_mut().write_all(body.as_bytes()).unwrap(); + StagedAsset { + byte_len: body.len(), + sha256: hex::encode(sha2::Sha256::digest(body.as_bytes())), + temporary: download::finish_staged_binary(temporary).unwrap(), + } + } + + #[cfg(unix)] + #[test] + fn staged_binary_that_reports_another_version_names_the_installer() { let directory = tempfile::tempdir().unwrap(); - let stapler = fake_stapler(directory.path(), &[68, 68, 68, 68, 68, 68, 0]); + let staged = staged_script(directory.path(), "printf 'lpm 1.2.2\\n'"); - let error = validate_notarization_ticket( - stapler.to_str().unwrap(), - Path::new("/Applications/LPM CLI.app"), - &[Duration::ZERO; NOTARIZATION_TICKET_RETRY_DELAYS.len()], - ) - .unwrap_err() - .to_string(); + let error = check_staged_asset(&staged, ReleaseChannel::Stable, || { + VersionProbe::verify_staged_version(&staged.temporary, "1.2.3") + }) + .unwrap_err(); assert!( - error.contains("CloudKit's response is inconsistent"), - "{error}" + matches!(&error, LpmError::StandaloneSelfUpdate { reason, .. } if reason.contains("exact version 1.2.3")), + "{error:?}" ); - assert_eq!( - stapler_runs(directory.path()).len(), - NOTARIZATION_TICKET_RETRY_DELAYS.len() + 1 + } + + /// A staged file that changes while it is checked fails the check too, + /// but the refusal is the changed file, which reinstalling doesn't fix. + #[cfg(unix)] + #[test] + fn staged_asset_that_changes_while_checked_is_refused_without_an_installer() { + let directory = tempfile::tempdir().unwrap(); + let staged = staged_script(directory.path(), "printf 'lpm 1.2.3\\n'"); + + let error = check_staged_asset(&staged, ReleaseChannel::Stable, || -> Result<(), _> { + std::fs::write(staged.temporary.path(), b"replaced").unwrap(); + Err(LpmError::SelfUpdate( + "the replaced asset didn't validate".to_string(), + )) + }) + .unwrap_err(); + + assert!( + matches!(&error, LpmError::SelfUpdate(reason) if reason.contains("changed after verification")), + "a staged file that changed while checked must be refused as that, naming no installer: {error:?}" ); } - #[cfg(target_os = "macos")] #[test] - fn notarization_ticket_retries_wait_out_the_same_cloudkit_outage_as_install_sh() { - let install_sh = - std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("../../install.sh")) - .unwrap(); - let schedule = install_sh - .lines() - .find_map(|line| { - line.trim() - .strip_prefix("for ticket_retry_delay in ")? - .strip_suffix("; do") - }) - .expect("install.sh retries the notarization ticket check"); - let install_sh_delays = schedule - .split_whitespace() - .filter(|delay| *delay != "\"\"") - .map(|delay| Duration::from_secs(delay.parse().unwrap())) - .collect::>(); + fn failures_other_than_a_refusal_keep_their_own_error() { + let error = with_installer_recovery( + LpmError::Network("connection reset".to_string()), + ReleaseChannel::Stable, + StandaloneRefusal::ReleaseVerification, + ); - assert_eq!(install_sh_delays, NOTARIZATION_TICKET_RETRY_DELAYS); + assert!( + matches!(&error, LpmError::Network(message) if message == "connection reset"), + "{error:?}" + ); + } + + #[cfg(windows)] + #[test] + fn windows_refusals_name_no_installer() { + let error = with_installer_recovery( + LpmError::SelfUpdate("refused".to_string()), + ReleaseChannel::Stable, + StandaloneRefusal::Compatibility, + ); + + assert!( + matches!(&error, LpmError::SelfUpdate(reason) if reason == "refused"), + "{error:?}" + ); } #[cfg(target_os = "macos")] - fn fixture_notarization() -> ConfirmedNotarization { - ConfirmedNotarization { + fn fixture_fingerprint() -> BundleFingerprint { + BundleFingerprint { cdhash: "0f1e2d3c4b5a69788796a5b4c3d2e1f00f1e2d3c".to_string(), - ticket: b"stapled notarization ticket".to_vec(), + stapled_ticket: b"stapled notarization ticket".to_vec(), } } #[cfg(target_os = "macos")] #[test] - fn moved_bundle_with_the_confirmed_code_and_ticket_needs_no_second_ticket_check() { - fixture_notarization() - .confirm_same_bundle(&fixture_notarization()) + fn moved_bundle_with_the_validated_code_and_ticket_is_accepted() { + fixture_fingerprint() + .confirm_same_bundle(&fixture_fingerprint()) .unwrap(); } #[cfg(target_os = "macos")] #[test] fn moved_bundle_with_different_code_or_ticket_is_rejected() { - let confirmed = fixture_notarization(); + let validated = fixture_fingerprint(); for installed in [ - ConfirmedNotarization { + BundleFingerprint { cdhash: "a1b2c3d4e5f60718293a4b5c6d7e8f9001122334".to_string(), - ..fixture_notarization() + ..fixture_fingerprint() }, - ConfirmedNotarization { - ticket: b"replaced notarization ticket".to_vec(), - ..fixture_notarization() + BundleFingerprint { + stapled_ticket: b"replaced notarization ticket".to_vec(), + ..fixture_fingerprint() }, ] { - let error = confirmed + let error = validated .confirm_same_bundle(&installed) .unwrap_err() .to_string(); assert!( - error.contains( - "differs from the staged bundle whose notarization ticket Apple confirmed" - ), + error.contains("differs from the staged bundle that was validated"), "{error}" ); } } - - #[cfg(target_os = "macos")] - #[test] - fn notarization_ticket_check_rejects_an_invalid_ticket_at_once() { - let directory = tempfile::tempdir().unwrap(); - let stapler = fake_stapler(directory.path(), &[65, 0]); - - let error = validate_notarization_ticket( - stapler.to_str().unwrap(), - Path::new("/Applications/LPM CLI.app"), - &[Duration::ZERO; 2], - ) - .unwrap_err() - .to_string(); - - assert!(error.contains("Error 65"), "{error}"); - assert_eq!(stapler_runs(directory.path()).len(), 1); - } } diff --git a/crates/lpm-cli/src/commands/self_update/download.rs b/crates/lpm-cli/src/commands/self_update/download.rs index e079ecb7a..a8684f005 100644 --- a/crates/lpm-cli/src/commands/self_update/download.rs +++ b/crates/lpm-cli/src/commands/self_update/download.rs @@ -1,6 +1,38 @@ use lpm_common::LpmError; use sha2::{Digest, Sha256}; +/// Why a release asset couldn't be staged. +#[derive(Debug)] +pub(super) enum StagedAssetError { + /// The asset is larger than this updater accepts, which is the release's + /// doing. + TooLarge(LpmError), + /// Downloading or staging it failed. + Failed(LpmError), +} + +impl From for StagedAssetError { + fn from(error: LpmError) -> Self { + Self::Failed(error) + } +} + +impl From for LpmError { + fn from(error: StagedAssetError) -> Self { + match error { + StagedAssetError::TooLarge(error) | StagedAssetError::Failed(error) => error, + } + } +} + +impl std::fmt::Display for StagedAssetError { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::TooLarge(error) | Self::Failed(error) => error.fmt(formatter), + } + } +} + pub(super) async fn fetch_bounded( client: &reqwest::Client, url: &str, @@ -33,7 +65,7 @@ async fn fetch_bounded_response( client: &reqwest::Client, url: &str, max_bytes: usize, -) -> Result, LpmError> { +) -> Result, StagedAssetError> { let response = client .get(url) .header("User-Agent", "lpm-cli") @@ -52,20 +84,20 @@ async fn fetch_bounded_response( return Ok(None); } if !status.is_success() { - return Err(LpmError::Network(format!( + return Err(StagedAssetError::Failed(LpmError::Network(format!( "fetch {} returned HTTP {}", safe_remote_label(url), status.as_u16() - ))); + )))); } if let Some(advertised) = response.content_length() && advertised > max_bytes as u64 { - return Err(LpmError::SelfUpdate(format!( + return Err(StagedAssetError::TooLarge(LpmError::SelfUpdate(format!( "{} advertises {advertised} bytes; cap of {max_bytes} would be exceeded — refusing the download", safe_remote_label(url) - ))); + )))); } Ok(Some(response)) } @@ -228,7 +260,7 @@ pub(super) async fn fetch_asset_to_staged_file( url: &str, max_bytes: usize, current_exe: &std::path::Path, -) -> Result, LpmError> { +) -> Result, StagedAssetError> { use std::io::Write as _; let Some(mut response) = fetch_bounded_response(client, url, max_bytes).await? else { @@ -245,7 +277,9 @@ pub(super) async fn fetch_asset_to_staged_file( )) })? { if byte_len.saturating_add(chunk.len()) > max_bytes { - return Err(body_exceeded_cap(url, max_bytes)); + return Err(StagedAssetError::TooLarge(body_exceeded_cap( + url, max_bytes, + ))); } temporary.as_file_mut().write_all(&chunk).map_err(|error| { LpmError::Io(std::io::Error::new( @@ -385,6 +419,7 @@ mod tests { join_server(server).await.unwrap(); assert!(error.to_string().contains("mid-stream"), "error: {error}"); + assert!(matches!(error, StagedAssetError::TooLarge(_)), "{error:?}"); assert_eq!( std::fs::read_dir(destination_dir.path()).unwrap().count(), 0, @@ -392,6 +427,26 @@ mod tests { ); } + #[tokio::test(flavor = "current_thread")] + async fn staged_asset_download_refuses_an_advertised_size_over_the_cap_as_too_large() { + let (url, server) = spawn_fixed_body_server_with_length(1024, Some(64 * 1024 * 1024)); + let client = super::super::release_http_client().unwrap(); + let destination_dir = tempdir().unwrap(); + let current_exe = destination_dir.path().join("lpm"); + + let error = fetch_asset_to_staged_file(&client, &url, 1024 * 1024, ¤t_exe) + .await + .expect_err("an advertised size over the cap must be refused"); + drop(server); + + assert!(matches!(error, StagedAssetError::TooLarge(_)), "{error:?}"); + assert!(error.to_string().contains("advertises"), "error: {error}"); + assert_eq!( + std::fs::read_dir(destination_dir.path()).unwrap().count(), + 0 + ); + } + #[tokio::test(flavor = "current_thread")] async fn release_download_errors_do_not_expose_override_query_secrets() { use std::io::{Read as _, Write as _}; diff --git a/crates/lpm-cli/src/commands/self_update/probe.rs b/crates/lpm-cli/src/commands/self_update/probe.rs index a2092dcb2..e8b838713 100644 --- a/crates/lpm-cli/src/commands/self_update/probe.rs +++ b/crates/lpm-cli/src/commands/self_update/probe.rs @@ -861,13 +861,14 @@ impl LauncherBinding { } impl VersionProbe { + /// Runs the staged binary and checks the version it reports. The caller + /// checks that the staged file is still the verified one, before and + /// after. #[cfg(any(not(target_os = "macos"), test))] - pub(super) fn verify_staged( + pub(super) fn verify_staged_version( temporary: &tempfile::NamedTempFile, - expected_sha256: &str, version: &str, ) -> Result<(), LpmError> { - super::download::ensure_staged_file_unchanged(temporary, expected_sha256)?; let path = temporary.path(); let path = std::fs::canonicalize(path).map_err(|error| { LpmError::SelfUpdate(format!( @@ -2612,7 +2613,6 @@ mod tests { #[cfg(unix)] #[test] fn staged_release_probe_rejects_a_binary_with_the_wrong_embedded_version() { - use sha2::Digest as _; use std::io::Write as _; use std::os::unix::fs::PermissionsExt; @@ -2626,10 +2626,9 @@ mod tests { .as_file() .set_permissions(std::fs::Permissions::from_mode(0o755)) .unwrap(); - let sha256 = hex::encode(sha2::Sha256::digest(body)); let temporary = super::super::download::finish_staged_binary(temporary).unwrap(); - let error = VersionProbe::verify_staged(&temporary, &sha256, "1.2.3").unwrap_err(); + let error = VersionProbe::verify_staged_version(&temporary, "1.2.3").unwrap_err(); assert!( error.to_string().contains("exact version 1.2.3"), "unexpected error: {error}" diff --git a/crates/lpm-cli/src/commands/self_update/validation.rs b/crates/lpm-cli/src/commands/self_update/validation.rs index a2e3f3769..4980f2cce 100644 --- a/crates/lpm-cli/src/commands/self_update/validation.rs +++ b/crates/lpm-cli/src/commands/self_update/validation.rs @@ -5,6 +5,10 @@ use std::time::{Duration, Instant}; const OUTPUT_LIMIT: usize = 1024 * 1024; +/// The only environment a validation program gets, so none of the caller's +/// variables can change what a system tool does or prints. +const VALIDATION_PATH: &str = "/usr/bin:/bin:/usr/sbin:/sbin"; + pub(super) fn run( program: &str, arguments: &[&OsStr], @@ -16,7 +20,10 @@ pub(super) fn run( let mut session = lpm_common::process_output::CaptureSession::default(); let output = session .capture_output( - Command::new(program).args(arguments), + Command::new(program) + .args(arguments) + .env_clear() + .env("PATH", VALIDATION_PATH), OUTPUT_LIMIT + 1, |_| { if started.elapsed() >= timeout { @@ -63,4 +70,65 @@ mod tests { assert!(started.elapsed() < Duration::from_secs(3)); lpm_common::with_exclusive_lock(&lock_path, || Ok::<_, LpmError>(())).unwrap(); } + + #[test] + fn macos_validation_refuses_excessive_output() { + let result = run( + "/bin/sh", + &[ + OsStr::new("-c"), + OsStr::new("/usr/bin/head -c 2097152 /dev/zero"), + ], + "noisy validation fixture", + Duration::from_secs(60), + ); + assert!(result.is_err(), "validation output must be bounded"); + } + + #[test] + fn macos_validation_does_not_wait_for_inherited_output_after_parent_exit() { + let directory = tempfile::tempdir().unwrap(); + let pid_file = directory.path().join("child-pid"); + let script = format!("/bin/sleep 5 & echo $! > '{}'; exit 0", pid_file.display()); + let started = Instant::now(); + let result = run( + "/bin/sh", + &[OsStr::new("-c"), OsStr::new(&script)], + "detached output fixture", + Duration::from_secs(60), + ); + let elapsed = started.elapsed(); + if let Ok(pid) = std::fs::read_to_string(pid_file) + .unwrap() + .trim() + .parse::() + { + // SAFETY: the PID belongs to the disposable child created by this test. + unsafe { + libc::kill(pid, libc::SIGKILL); + } + } + result.unwrap(); + assert!( + elapsed < Duration::from_secs(3), + "inherited pipe delayed completion: {elapsed:?}" + ); + } + + #[test] + fn validation_programs_see_only_the_system_path() { + let output = run( + "/usr/bin/env", + &[], + "environment fixture", + Duration::from_secs(60), + ) + .unwrap(); + + assert!(output.status.success()); + assert_eq!( + String::from_utf8(output.stdout).unwrap(), + format!("PATH={VALIDATION_PATH}\n") + ); + } } diff --git a/crates/lpm-common/src/error.rs b/crates/lpm-common/src/error.rs index 5ca4f0846..02de883e7 100644 --- a/crates/lpm-common/src/error.rs +++ b/crates/lpm-common/src/error.rs @@ -832,26 +832,31 @@ pub enum LpmError { )] ProvenanceUnavailable(String), - /// `lpm self-update` standalone path refused to swap the binary - /// because the release artifacts failed an integrity gate - /// (`SHA256SUMS.txt` missing on a release that predates the - /// signed-install gate, Sigstore bundle rejected, SHA mismatch, - /// identity pin not satisfied, replay window violated, etc.). - /// Distinct from `Network` so the CLI can render remediation copy - /// that names the manual install URL. + /// `lpm self-update` refused the update: the release didn't verify, or the + /// installation, its package manager or this machine's state made the + /// update unsafe. The reason says which. Distinct from `Network`, which + /// retrying fixes. #[error("self-update refused: {0}")] #[diagnostic( code(lpm::self_update), help( - "The downloaded release could not be cryptographically verified. \ - If this is a release that predates LPM's signed-install gate, install \ - manually from https://github.com/lpm-dev/rust-client/releases. \ - Otherwise the release artifacts may be tampered or the manifest may be missing — \ - retry, and if the failure persists report at https://github.com/lpm-dev/rust-client/issues." + "Fix what the reason above names, or retry later. If it keeps failing, report it at \ + https://github.com/lpm-dev/rust-client/issues." ) )] SelfUpdate(String), + /// A standalone install's self-update refused the update, with how the + /// official installer can take over: it verifies the release itself and + /// installs it in `~/.lpm`, keeping the user's settings. + #[error("self-update refused: {reason}")] + #[diagnostic(code(lpm::self_update), help("{recovery}:\n{reinstall_command}"))] + StandaloneSelfUpdate { + reason: String, + recovery: String, + reinstall_command: String, + }, + #[error("security floor refused: {0}")] #[diagnostic( code(lpm::security_floor), @@ -1077,7 +1082,7 @@ impl LpmError { LpmError::SelfUpdateRateLimited(_) => "self_update_rate_limited", LpmError::ProvenanceVerification(_) => "provenance_verification", LpmError::ProvenanceUnavailable(_) => "provenance_unavailable", - LpmError::SelfUpdate(_) => "self_update", + LpmError::SelfUpdate(_) | LpmError::StandaloneSelfUpdate { .. } => "self_update", LpmError::SecurityFloor(_) => "security_floor", LpmError::SecurityApprovalStore(_) => "security_approval_store", LpmError::SecurityApprovalRequired(_) => "security_approval_required", @@ -1458,6 +1463,11 @@ mod tests { })), LpmError::SelfUpdatePaused("x".into()), LpmError::SelfUpdateRateLimited("x".into()), + LpmError::StandaloneSelfUpdate { + reason: "x".into(), + recovery: "x".into(), + reinstall_command: "x".into(), + }, LpmError::SecurityFloor("x".into()), LpmError::SecurityApprovalStore("x".into()), LpmError::SudoNotSupported, @@ -1521,6 +1531,43 @@ mod tests { assert!(help.contains("GH_TOKEN"), "help: {help}"); } + /// A refusal can be about the installation rather than the release, so + /// its help points at the reason instead of claiming verification failed. + #[test] + fn self_update_refusal_help_points_at_the_reason() { + let help = LpmError::SelfUpdate("x".into()).help().unwrap().to_string(); + + assert!(help.contains("the reason above"), "help: {help}"); + assert!( + !help.contains("could not be cryptographically verified"), + "help: {help}" + ); + assert!( + !help.to_lowercase().contains("install manually"), + "help: {help}" + ); + } + + #[test] + fn refused_standalone_self_update_is_a_self_update_error_naming_the_reinstall_command() { + let error = LpmError::StandaloneSelfUpdate { + reason: "the release is not signed".into(), + recovery: "Reinstall LPM CLI with the official installer".into(), + reinstall_command: "curl -fsSL https://cli.lpm.dev/install | sh".into(), + }; + + assert_eq!(error.error_code(), "self_update"); + assert_eq!( + error.to_string(), + "self-update refused: the release is not signed" + ); + let help = error.help().unwrap().to_string(); + assert_eq!( + help, + "Reinstall LPM CLI with the official installer:\ncurl -fsSL https://cli.lpm.dev/install | sh" + ); + } + #[test] fn project_layout_help_recommends_replacing_node_modules_without_store_cleanup() { let error = LpmError::ProjectLayout("x".into()); diff --git a/install.sh b/install.sh index ec1d2f090..42a592932 100755 --- a/install.sh +++ b/install.sh @@ -30,6 +30,10 @@ EXPECTED_BUNDLE_ID="dev.lpm.cli" EXPECTED_TEAM_ID="823S8YKMRW" EXPECTED_ACCESS_GROUP="$EXPECTED_TEAM_ID.dev.lpm.vault.shared" EXPECTED_PROFILE_ACCESS_GROUP="$EXPECTED_TEAM_ID.*" +# A Developer ID Application signature of LPM's team, on code Apple +# notarized. codesign judges `notarized` itself, from the stapled ticket when +# Apple can't be reached. +MACOS_CODE_REQUIREMENT="anchor apple generic and identifier \"$EXPECTED_BUNDLE_ID\" and certificate 1[field.1.2.840.113635.100.6.2.6] exists and certificate leaf[field.1.2.840.113635.100.6.1.13] exists and certificate leaf[subject.OU] = \"$EXPECTED_TEAM_ID\" and notarized" # v0.76.5 is the last signed app bundle that does not declare an icon. MACOS_ICON_FIRST_VERSION="v0.76.6" MACOS_BUNDLE=0 @@ -197,17 +201,22 @@ is_loopback_http() { *) return 1 ;; esac loopback_authority=${loopback_authority%%/*} + # Only the exact host, then an optional all-digit port: anything else, a + # user-info `@` among it, would let curl reach another host. case "$loopback_authority" in - 127.0.0.1|localhost|'[::1]') return 0 ;; - 127.0.0.1:*|localhost:*|'[::1]':*) - loopback_port=${loopback_authority##*:} - case "$loopback_port" in - ''|*[!0-9]*) return 1 ;; - *) return 0 ;; - esac - ;; + 127.0.0.1*) loopback_port=${loopback_authority#127.0.0.1} ;; + localhost*) loopback_port=${loopback_authority#localhost} ;; + '[::1]'*) loopback_port=${loopback_authority#'[::1]'} ;; *) return 1 ;; esac + case "$loopback_port" in + '') return 0 ;; + :*) loopback_port=${loopback_port#:} ;; + *) return 1 ;; + esac + case "$loopback_port" in + ''|*[!0123456789]*) return 1 ;; + esac } if [ -n "${LPM_INSTALL_TEST_API_URL:-}" ] && ! is_loopback_http "$LPM_INSTALL_TEST_API_URL"; then @@ -226,14 +235,17 @@ if [ -n "${LPM_INSTALL_TEST_INTERRUPT_AFTER:-}" ] && { \ exit 1 fi +# Every macOS tool below ships with macOS. None may be an xcrun shim such as +# /usr/bin/stapler, which fails on a Mac without Xcode or the Command Line +# Tools, or one of Gatekeeper's assessors (spctl, syspolicy_check), which +# answer from the Mac's security policy and Apple's services. MACOS_CODESIGN_TOOL="/usr/bin/codesign" -MACOS_SECURITY_TOOL="/usr/bin/security" -MACOS_SPCTL_TOOL="/usr/sbin/spctl" -MACOS_XCRUN_TOOL="/usr/bin/xcrun" MACOS_DITTO_TOOL="/usr/bin/ditto" +MACOS_OPENSSL_TOOL="/usr/bin/openssl" +MACOS_PLISTBUDDY_TOOL="/usr/libexec/PlistBuddy" MACOS_UNZIP_TOOL="/usr/bin/unzip" -if [ -n "${LPM_INSTALL_TEST_CODESIGN:-}${LPM_INSTALL_TEST_SECURITY:-}${LPM_INSTALL_TEST_SPCTL:-}${LPM_INSTALL_TEST_XCRUN:-}" ]; then +if [ -n "${LPM_INSTALL_TEST_CODESIGN:-}${LPM_INSTALL_TEST_OPENSSL:-}" ]; then if [ "$OS" != "Darwin" ] || \ [ -z "${LPM_INSTALL_TEST_API_URL:-}" ] || \ [ -z "${LPM_INSTALL_TEST_DOWNLOAD_BASE:-}" ]; then @@ -241,9 +253,7 @@ if [ -n "${LPM_INSTALL_TEST_CODESIGN:-}${LPM_INSTALL_TEST_SECURITY:-}${LPM_INSTA exit 1 fi MACOS_CODESIGN_TOOL="${LPM_INSTALL_TEST_CODESIGN:-$MACOS_CODESIGN_TOOL}" - MACOS_SECURITY_TOOL="${LPM_INSTALL_TEST_SECURITY:-$MACOS_SECURITY_TOOL}" - MACOS_SPCTL_TOOL="${LPM_INSTALL_TEST_SPCTL:-$MACOS_SPCTL_TOOL}" - MACOS_XCRUN_TOOL="${LPM_INSTALL_TEST_XCRUN:-$MACOS_XCRUN_TOOL}" + MACOS_OPENSSL_TOOL="${LPM_INSTALL_TEST_OPENSSL:-$MACOS_OPENSSL_TOOL}" fi REQUESTED_VERSION="${LPM_INSTALL_VERSION:-}" @@ -652,43 +662,14 @@ require_reported_version() { fi } -# stapler validate checks the stapled ticket against Apple's CloudKit record -# and exits with EX_NOHOST when CloudKit doesn't answer. CloudKit lookups have -# kept failing for over 20 s at a time, so the checks spread over about two -# minutes before giving up. -STAPLER_CLOUDKIT_UNREACHABLE=68 - -validate_notarization_ticket() { - ticket_bundle="$1" - ticket_label="$2" - for ticket_retry_delay in 2 5 15 30 60 ""; do - ticket_status=0 - "$MACOS_XCRUN_TOOL" stapler validate "$ticket_bundle" || ticket_status=$? - if [ "$ticket_status" -eq 0 ]; then - return 0 - fi - if [ "$ticket_status" -ne "$STAPLER_CLOUDKIT_UNREACHABLE" ]; then - echo "ERROR: $ticket_label does not contain a valid notarization ticket." - return 1 - fi - if [ -z "$ticket_retry_delay" ]; then - echo "ERROR: Apple's notarization service did not answer while checking $ticket_label. Try again in a few minutes." - return 1 - fi - echo "Apple's notarization service did not answer; checking the notarization ticket again in ${ticket_retry_delay}s..." - sleep "$ticket_retry_delay" - done -} - # Validates an app bundle and sets app_cdhash to its code-directory hash. Given -# a bundle Apple already confirmed and that bundle's hash, the bundle is a copy -# of it: instead of asking Apple again, it must carry the same code and the -# same stapled ticket. +# a bundle validated before and that bundle's hash, the bundle is a copy of it +# and must carry the same code and the same stapled ticket. validate_macos_bundle() { app_bundle="$1" app_label="$2" - confirmed_bundle="${3:-}" - confirmed_cdhash="${4:-}" + validated_bundle="${3:-}" + validated_cdhash="${4:-}" app_contents="$app_bundle/Contents" app_executable="$app_contents/MacOS/lpm-rs" app_icon="$app_contents/Resources/LPMCLI.icns" @@ -709,7 +690,7 @@ validate_macos_bundle() { fi done - declared_icon=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIconFile' "$app_contents/Info.plist" 2>/dev/null || true) + declared_icon=$("$MACOS_PLISTBUDDY_TOOL" -c 'Print :CFBundleIconFile' "$app_contents/Info.plist" 2>/dev/null || true) icon_required=0 if ! version_lt "$VERSION" "$MACOS_ICON_FIRST_VERSION"; then icon_required=1 @@ -743,18 +724,18 @@ validate_macos_bundle() { return 1 fi - if ! "$MACOS_CODESIGN_TOOL" --verify --strict --verbose=4 "$app_bundle"; then - echo "ERROR: $app_label failed code-signature validation." + if ! "$MACOS_CODESIGN_TOOL" --verify --strict --verbose=4 -R "=$MACOS_CODE_REQUIREMENT" "$app_bundle"; then + echo "ERROR: $app_label failed code-signature and notarization validation." return 1 fi signature_details=$("$MACOS_CODESIGN_TOOL" -dvvv "$app_bundle" 2>&1) || return 1 - signed_team=$(printf '%s\n' "$signature_details" | awk -F= '/^TeamIdentifier=/{print $2}') - signed_identifier=$(printf '%s\n' "$signature_details" | awk -F= '/^Identifier=/{print $2}') + signed_team=$(printf '%s\n' "$signature_details" | sed -n 's/^TeamIdentifier=//p') + signed_identifier=$(printf '%s\n' "$signature_details" | sed -n 's/^Identifier=//p') if [ "$signed_team" != "$EXPECTED_TEAM_ID" ] || [ "$signed_identifier" != "$EXPECTED_BUNDLE_ID" ]; then echo "ERROR: $app_label has an unexpected signing identity." return 1 fi - app_cdhash=$(printf '%s\n' "$signature_details" | awk -F= '/^CDHash=/{print $2}') + app_cdhash=$(printf '%s\n' "$signature_details" | sed -n 's/^CDHash=//p') if [ -z "$app_cdhash" ]; then echo "ERROR: $app_label has no code-directory hash." return 1 @@ -765,23 +746,30 @@ validate_macos_bundle() { echo "ERROR: $app_label has no readable signed entitlements." return 1 fi - signed_access_groups=$(/usr/libexec/PlistBuddy -c 'Print :keychain-access-groups' "$signed_entitlements" 2>/dev/null) || return 1 + signed_access_groups=$("$MACOS_PLISTBUDDY_TOOL" -c 'Print :keychain-access-groups' "$signed_entitlements" 2>/dev/null) || return 1 if ! plist_array_contains_exact "$signed_access_groups" "$EXPECTED_ACCESS_GROUP"; then echo "ERROR: $app_label does not have the LPM Vault shared Keychain access group." return 1 fi + # security cms -D would import the profile's certificates into the default + # keychain, and fails for an account without one. The profile is a sealed + # resource of the code signature verified above, so it only needs decoding. + # macOS's openssl reads OPENSSL_CONF, and with an OpenSSL 3 configuration + # there it writes nothing yet exits 0. profile_plist="$STAGE_DIR/profile.plist" - if ! "$MACOS_SECURITY_TOOL" cms -D -i "$app_profile" > "$profile_plist"; then + rm -f "$profile_plist" + if ! (unset OPENSSL_CONF; "$MACOS_OPENSSL_TOOL" smime -verify -noverify -nosigs -inform DER -in "$app_profile" -out "$profile_plist" 2>/dev/null) || \ + [ ! -s "$profile_plist" ]; then echo "ERROR: $app_label has an unreadable provisioning profile." return 1 fi - profile_team=$(/usr/libexec/PlistBuddy -c 'Print :TeamIdentifier:0' "$profile_plist" 2>/dev/null) || return 1 + profile_team=$("$MACOS_PLISTBUDDY_TOOL" -c 'Print :TeamIdentifier:0' "$profile_plist" 2>/dev/null) || return 1 profile_application=$( - /usr/libexec/PlistBuddy -c 'Print :Entitlements:com.apple.application-identifier' "$profile_plist" 2>/dev/null || - /usr/libexec/PlistBuddy -c 'Print :Entitlements:application-identifier' "$profile_plist" 2>/dev/null + "$MACOS_PLISTBUDDY_TOOL" -c 'Print :Entitlements:com.apple.application-identifier' "$profile_plist" 2>/dev/null || + "$MACOS_PLISTBUDDY_TOOL" -c 'Print :Entitlements:application-identifier' "$profile_plist" 2>/dev/null ) || return 1 - profile_access_groups=$(/usr/libexec/PlistBuddy -c 'Print :Entitlements:keychain-access-groups' "$profile_plist" 2>/dev/null) || return 1 + profile_access_groups=$("$MACOS_PLISTBUDDY_TOOL" -c 'Print :Entitlements:keychain-access-groups' "$profile_plist" 2>/dev/null) || return 1 if [ "$profile_team" != "$EXPECTED_TEAM_ID" ] || \ [ "$profile_application" != "$EXPECTED_TEAM_ID.$EXPECTED_BUNDLE_ID" ] || \ { ! plist_array_contains_exact "$profile_access_groups" "$EXPECTED_ACCESS_GROUP" && \ @@ -790,15 +778,10 @@ validate_macos_bundle() { return 1 fi - if [ -z "$confirmed_bundle" ]; then - validate_notarization_ticket "$app_bundle" "$app_label" || return 1 - elif [ "$app_cdhash" != "$confirmed_cdhash" ] || \ - ! cmp -s "$confirmed_bundle/Contents/CodeResources" "$app_ticket"; then - echo "ERROR: $app_label differs from the downloaded bundle whose notarization ticket Apple confirmed." - return 1 - fi - if ! "$MACOS_SPCTL_TOOL" --assess --type execute --verbose=4 "$app_bundle"; then - echo "ERROR: Gatekeeper rejected $app_label." + if [ -n "$validated_bundle" ] && \ + { [ "$app_cdhash" != "$validated_cdhash" ] || \ + ! cmp -s "$validated_bundle/Contents/CodeResources" "$app_ticket"; }; then + echo "ERROR: $app_label differs from the downloaded bundle that was validated." return 1 fi } diff --git a/npm/release/upgrade-recovery.md b/npm/release/upgrade-recovery.md index 7257a89c7..0ad6b722c 100644 --- a/npm/release/upgrade-recovery.md +++ b/npm/release/upgrade-recovery.md @@ -17,6 +17,18 @@ cargo install --git https://github.com/lpm-dev/rust-client --tag v lpm- Later versions accept both signing identities, so `lpm self-update` works again after this one reinstall. npm, Homebrew, and nightly installations are not affected. +### macOS standalone upgrades without Xcode from 0.76.0 to 0.88.0 + +`lpm self-update` in 0.76.0 to 0.88.0, and in nightly releases built before this fix, checks the release's notarization ticket with `stapler`, which macOS runs only when Xcode is installed. On a Mac without Xcode, including one with only the Command Line Tools, it stops with `tool 'stapler' requires Xcode` or another `xcrun` or `xcode-select` error. The release is not tampered. Rerun the installer once: + +```sh +curl -fsSL https://cli.lpm.dev/install | sh +``` + +On the nightly channel, run `curl -fsSL https://cli.lpm.dev/install | LPM_INSTALL_CHANNEL=nightly sh` instead. + +The installer checks the release with tools every Mac ships with and needs neither Xcode nor a connection to Apple, and so does `lpm self-update` from this release on. The reinstall keeps your settings and installs this release or a later one, so later updates work through `lpm self-update` again. + ### macOS standalone upgrades from 0.76.5 The standalone updater in 0.76.5 rejects newer signed app bundles with an icon. If it reports an unexpected `Contents/Resources/` entry, rerun the installer once: diff --git a/scripts/ci/macos-apple-services.sh b/scripts/ci/macos-apple-services.sh new file mode 100755 index 000000000..9112e79bf --- /dev/null +++ b/scripts/ci/macos-apple-services.sh @@ -0,0 +1,154 @@ +#!/usr/bin/env bash +# Cuts a hosted macOS runner off from Apple's services, as a firewall that +# silently drops their traffic does, so the checks after it show that +# installing and updating LPM needs none of them and doesn't stall without +# them. +# +# macos-apple-services.sh block block them and confirm it +# macos-apple-services.sh restore undo block +set -euo pipefail + +# The hosts macOS asks about notarization tickets, certificate revocation and +# Apple's intermediate certificates. Some are served from outside Apple's +# networks, so the addresses each resolves to are blocked too, and the hosts +# file pins each name to them, or to a dropped placeholder for an address +# family DNS gave none in, so a later lookup can't land somewhere else. +APPLE_HOSTS=(api.apple-cloudkit.com ocsp.apple.com ocsp2.apple.com crl.apple.com valid.apple.com certs.apple.com www.apple.com) +APPLE_NETWORKS_V4="17.0.0.0/8" +APPLE_NETWORKS_V6="2620:149::/32 2a01:b740::/32 2403:300::/32" + +HOSTS_FILE="${HOSTS_FILE:-/etc/hosts}" +DEFAULT_PF_CONF="${DEFAULT_PF_CONF:-/etc/pf.conf}" +PFCTL_BIN="${PFCTL_BIN:-/sbin/pfctl}" +DIG_BIN="${DIG_BIN:-/usr/bin/dig}" +CURL_BIN="${CURL_BIN:-/usr/bin/curl}" +DSCACHEUTIL_BIN="${DSCACHEUTIL_BIN:-/usr/bin/dscacheutil}" +KILLALL_BIN="${KILLALL_BIN:-/usr/bin/killall}" +SUDO="${SUDO-sudo}" + +die() { + echo "::error::$*" >&2 + exit 1 +} + +flush_name_cache() { + $SUDO "$DSCACHEUTIL_BIN" -flushcache + $SUDO "$KILLALL_BIN" -HUP mDNSResponder 2>/dev/null || true +} + +# Succeeds when a TCP connection to $1 on port 443 opens, at the address $2 +# when given rather than the one its name resolves to. curl counts the +# connections it opened, whatever failed afterwards: a TLS error, or a service +# that accepts and then stalls, still opened one. No proxy or ~/.curlrc may +# stand in for the destination. +connects() { + local resolve=() opened + [ -n "${2:-}" ] && resolve=(--resolve "$1:443:$2") + opened=$("$CURL_BIN" -q -sS -o /dev/null --noproxy '*' --connect-timeout 5 --max-time 15 \ + -w '%{num_connects}' ${resolve[@]+"${resolve[@]}"} "https://$1/" 2>/dev/null) || true + [ "${opened:-0}" -gt 0 ] 2>/dev/null +} + +# Prints "host address" for each address DNS gives host $1. dig asks the DNS +# server directly, past the hosts file. +dns_addresses() { + "$DIG_BIN" +short "$1" A | grep -E '^[0-9]+(\.[0-9]+){3}$' | sed "s/^/$1 /" || true + "$DIG_BIN" +short "$1" AAAA | grep -E '^[0-9A-Fa-f]*:[0-9A-Fa-f:]+$' | sed "s/^/$1 /" || true +} + +# Records the addresses to block in $1/addresses, and in $1/targets what +# answers now and must not once blocked: each host by name, and for each host +# its first address in Apple's IPv4 network and its first in Apple's IPv6 +# networks that the runner reaches. +record_baseline() { + local addresses="$1/addresses" targets="$1/targets" host address + : >"$addresses" + : >"$targets" + connects api.github.com || die "GitHub is unreachable before blocking anything" + for host in "${APPLE_HOSTS[@]}"; do + connects "$host" || die "$host is unreachable before blocking, so blocking it would show nothing" + printf '%s\n' "$host" >>"$targets" + dns_addresses "$host" >>"$addresses" + grep -q "^$host " "$addresses" || die "DNS gave no address for $host to block" + awk -v host="$host" '$1 == host && $2 !~ /:/ { found = 1 } END { exit !found }' "$addresses" || + printf '%s 192.0.2.1\n' "$host" >>"$addresses" + awk -v host="$host" '$1 == host && $2 ~ /:/ { found = 1 } END { exit !found }' "$addresses" || + printf '%s 100::1\n' "$host" >>"$addresses" + address=$(awk -v host="$host" '$1 == host && $2 ~ /^17\./ { print $2; exit }' "$addresses") + if [ -n "$address" ] && connects "$host" "$address"; then + printf '%s %s\n' "$host" "$address" >>"$targets" + fi + while read -r address; do + if connects "$host" "[$address]"; then + printf '%s [%s]\n' "$host" "$address" >>"$targets" + break + fi + done < <(awk -v host="$host" '$1 == host && tolower($2) ~ /^(2620:149|2a01:b740|2403:300):/ { print $2 }' "$addresses") + done + grep -q ' 17\.' "$targets" || + die "no address in Apple's IPv4 network answered before blocking, so the firewall can't be shown to work" +} + +confirm_blocked() { + local host address + while read -r host address; do + if connects "$host" "$address"; then + die "$host is still reachable${address:+ at $address}" + fi + done <"$1/targets" + connects api.github.com || die "blocking Apple's services also blocked GitHub" + echo "Apple's services are unreachable:" + sed 's/^/ /' "$1/targets" +} + +block() { + local state=$1 outside + mkdir -p "$state" + record_baseline "$state" + cp "$HOSTS_FILE" "$state/hosts" + { + printf '\n# Apple services blocked by scripts/ci/macos-apple-services.sh\n' + awk '{ print $2, $1 }' "$state/addresses" + } | $SUDO tee -a "$HOSTS_FILE" >/dev/null + # Addresses inside Apple's networks are left to the network entries, so + # the probes of those addresses show the network entries work. + outside=$(awk '$2 !~ /^17\./ && tolower($2) !~ /^(2620:149|2a01:b740|2403:300):/ { print $2 }' "$state/addresses" | + sort -u | tr '\n' ' ') + printf 'table const { %s %s %s}\nblock drop out quick from any to \n' \ + "$APPLE_NETWORKS_V4" "$APPLE_NETWORKS_V6" "$outside" >"$state/pf.conf" + if ! $SUDO "$PFCTL_BIN" -E -f "$state/pf.conf" 2>"$state/pfctl.log"; then + cat "$state/pfctl.log" >&2 + die "pfctl refused the rules" + fi + sed -n 's/^Token : //p' "$state/pfctl.log" >"$state/pf-token" + if [ ! -s "$state/pf-token" ]; then + cat "$state/pfctl.log" >&2 + die "pfctl did not enable the firewall" + fi + flush_name_cache + confirm_blocked "$state" +} + +restore() { + local state=$1 + if [ -f "$state/hosts" ]; then + $SUDO cp "$state/hosts" "$HOSTS_FILE" + fi + if [ -s "$state/pf-token" ]; then + $SUDO "$PFCTL_BIN" -f "$DEFAULT_PF_CONF" 2>/dev/null || true + $SUDO "$PFCTL_BIN" -X "$(cat "$state/pf-token")" 2>/dev/null || true + fi + flush_name_cache +} + +case "${1:-}" in +block) + [ "$#" -eq 2 ] || die "usage: $0 block " + block "$2" + ;; +restore) + [ "$#" -eq 2 ] || die "usage: $0 restore " + restore "$2" + ;; +*) die "usage: $0 block|restore " ;; +esac diff --git a/scripts/ci/macos-developer-tools.sh b/scripts/ci/macos-developer-tools.sh new file mode 100755 index 000000000..3e37f4236 --- /dev/null +++ b/scripts/ci/macos-developer-tools.sh @@ -0,0 +1,145 @@ +#!/bin/bash +# Turns a disposable macOS runner into a Mac without Xcode, and optionally +# without the Command Line Tools, so later steps exercise what LPM's users +# have. GitHub-hosted runners come with both. `restore` puts them back so the +# job's post steps, which need git, still work. +set -euo pipefail + +APPLICATIONS_DIR="${MACOS_APPLICATIONS_DIR:-/Applications}" +COMMAND_LINE_TOOLS_DIR="${MACOS_COMMAND_LINE_TOOLS_DIR:-/Library/Developer/CommandLineTools}" +XCODE_SELECT_BIN="${XCODE_SELECT_BIN:-/usr/bin/xcode-select}" +XCRUN_BIN="${XCRUN_BIN:-/usr/bin/xcrun}" +STAPLER_BIN="${STAPLER_BIN:-/usr/bin/stapler}" +GETCONF_BIN="${GETCONF_BIN:-getconf}" +# xcrun caches where tools are in TMPDIR and in the per-user temporary +# directory, which differ when TMPDIR is overridden. +XCRUN_CACHE_DIRS=("${TMPDIR:-/tmp}" "$("$GETCONF_BIN" DARWIN_USER_TEMP_DIR 2>/dev/null || true)") +SUDO="${SUDO-sudo}" + +usage() { + echo "usage: $0 hide | verify | restore " >&2 + exit 64 +} + +fail() { + echo "error: $*" >&2 + exit 1 +} + +require_mode() { + case "${1:-}" in + none | command-line-tools) ;; + *) usage ;; + esac +} + +xcode_apps() { + find "$APPLICATIONS_DIR" -maxdepth 1 -name 'Xcode*.app' \( -type d -o -type l \) -print +} + +# Moves a developer-tools path into the state directory under a name without +# the .app suffix, so Launch Services no longer finds it as Xcode. +hide_path() { + local path="$1" state_dir="$2" + local hidden + hidden="$state_dir/hidden/$(basename "$path").hidden" + $SUDO mv "$path" "$hidden" + printf '%s\t%s\n' "$path" "$hidden" >>"$state_dir/moved" +} + +clear_xcrun_cache() { + local directory + for directory in "${XCRUN_CACHE_DIRS[@]}"; do + if [ -n "$directory" ]; then + rm -f "$directory"/xcrun_db* + fi + done +} + +hide() { + local mode="$1" state_dir="$2" + [ ! -e "$state_dir/moved" ] || fail "$state_dir already records hidden developer tools" + mkdir -p "$state_dir/hidden" + env -u DEVELOPER_DIR "$XCODE_SELECT_BIN" -p >"$state_dir/selected" 2>/dev/null || : >"$state_dir/selected" + : >"$state_dir/moved" + local app + while IFS= read -r app; do + hide_path "$app" "$state_dir" + done < <(xcode_apps) + if [ "$mode" = none ]; then + if [ -e "$COMMAND_LINE_TOOLS_DIR" ]; then + hide_path "$COMMAND_LINE_TOOLS_DIR" "$state_dir" + fi + $SUDO "$XCODE_SELECT_BIN" --reset || true + else + [ -d "$COMMAND_LINE_TOOLS_DIR" ] || fail "this runner has no Command Line Tools at $COMMAND_LINE_TOOLS_DIR" + $SUDO "$XCODE_SELECT_BIN" --switch "$COMMAND_LINE_TOOLS_DIR" + fi + clear_xcrun_cache + verify "$mode" +} + +verify() { + local mode="$1" + [ -z "$(xcode_apps)" ] || fail "Xcode is still installed: $(xcode_apps | tr '\n' ' ')" + if [ "$mode" = none ]; then + [ ! -e "$COMMAND_LINE_TOOLS_DIR" ] || fail "the Command Line Tools are still installed" + if selected=$(env -u DEVELOPER_DIR "$XCODE_SELECT_BIN" -p 2>/dev/null); then + fail "a developer directory is still selected: $selected" + fi + if found=$(env -u DEVELOPER_DIR "$XCRUN_BIN" --find stapler 2>/dev/null); then + fail "xcrun still finds stapler at $found" + fi + else + selected=$(env -u DEVELOPER_DIR "$XCODE_SELECT_BIN" -p) + [ "$selected" = "$COMMAND_LINE_TOOLS_DIR" ] || fail "the selected developer directory is $selected" + # A stapler that runs rejects this directory too, so only the shim's + # own refusal shows that stapler needs Xcode here. + local refusal + refusal=$(env -u DEVELOPER_DIR "$STAPLER_BIN" validate "$COMMAND_LINE_TOOLS_DIR" 2>&1 || true) + case "$refusal" in + *"requires Xcode"*) ;; + *) fail "$STAPLER_BIN did not refuse to run without Xcode: $refusal" ;; + esac + fi + echo "developer tools: $mode" +} + +restore() { + local state_dir="$1" + [ -f "$state_dir/moved" ] || return 0 + local original hidden status=0 + while IFS=$'\t' read -r original hidden; do + $SUDO mv "$hidden" "$original" || status=1 + done < <(tail -r "$state_dir/moved" 2>/dev/null || tac "$state_dir/moved") + local selected + selected=$(cat "$state_dir/selected" 2>/dev/null || true) + if [ -n "$selected" ]; then + $SUDO "$XCODE_SELECT_BIN" --switch "$selected" || status=1 + else + $SUDO "$XCODE_SELECT_BIN" --reset || status=1 + fi + clear_xcrun_cache + [ "$status" -eq 0 ] || fail "some developer tools could not be restored" + rm -f "$state_dir/moved" +} + +case "${1:-}" in +hide) + [ "$#" -eq 3 ] || usage + require_mode "$2" + hide "$2" "$3" + ;; +verify) + [ "$#" -eq 2 ] || usage + require_mode "$2" + verify "$2" + ;; +restore) + [ "$#" -eq 2 ] || usage + restore "$2" + ;; +*) + usage + ;; +esac diff --git a/scripts/ci/test-macos-apple-services.sh b/scripts/ci/test-macos-apple-services.sh new file mode 100755 index 000000000..3382bec0a --- /dev/null +++ b/scripts/ci/test-macos-apple-services.sh @@ -0,0 +1,282 @@ +#!/bin/bash +set -euo pipefail + +script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +helper="$script_dir/macos-apple-services.sh" +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT + +fail() { + echo "FAIL: $*" >&2 + exit 1 +} + +# A fake runner. +# +# dig answers a host's A records from dns-a. when that exists and from +# dns-a otherwise, and its AAAA records likewise from dns-aaaa. By default +# every host has one address in Apple's IPv4 network and one in its IPv6 +# network, and ocsp.apple.com is served only from outside Apple's networks. +# +# curl answers only when its first argument is -q and it gets --noproxy '*', +# as the probe must ignore ~/.curlrc and proxies. It reaches a host by name +# when any address the hosts file pins it to is reachable, as curl tries +# each, or at an address of its own when the hosts file doesn't name it; at +# a --resolve address it uses that one. An address is unreachable when the +# firewall's active rules drop the table and the table +# names it or a network holding it. Without IPv6 (no-ipv6) no IPv6 address +# is reached. A host in never-answers times out whatever happens. A "host +# status" line in answers-anyway connects whatever is blocked and then exits +# with that status, such as 35 for a TLS error or 28 for a service that +# accepts and then stalls. For -w it prints how many connections it opened, +# or the connect time. As with macOS's curl, the connect time stays 0 for a +# connection that opened and then stalled in the TLS handshake, so a probe +# that went back to it takes such a service for a blocked one. +# +# pfctl applies the rules it is given: none of them when inert-firewall +# exists, none of the IPv6 entries when inert-ipv6 exists, none of the network +# entries when inert-networks exists, and it refuses them when pfctl-fails +# exists. +make_runner() { + rm -rf "$work/runner" "$work/state" + mkdir -p "$work/runner/bin" + printf '127.0.0.1 localhost\n' >"$work/runner/hosts" + printf 'default rules\n' >"$work/runner/pf.conf" + printf '17.253.0.1\n' >"$work/runner/dns-a" + printf '2a01:b740::1\n' >"$work/runner/dns-aaaa" + printf '2.22.144.17\n' >"$work/runner/dns-a.ocsp.apple.com" + printf '2a02:26f0::1\n' >"$work/runner/dns-aaaa.ocsp.apple.com" + : >"$work/runner/active-rules" + : >"$work/runner/never-answers" + : >"$work/runner/answers-anyway" + : >"$work/runner/calls" + cat >"$work/runner/bin/pfctl" <>"$work/runner/calls" +case "\$1" in +-E) + [ -e "$work/runner/pfctl-fails" ] && { echo "pfctl: syntax error" >&2; exit 1; } + if [ -e "$work/runner/inert-ipv6" ]; then + awk '{ out = ""; for (i = 1; i <= NF; i++) if (\$i !~ /:/) out = out (out == "" ? "" : " ") \$i; print out }' "\$3" >"$work/runner/active-rules" + elif [ -e "$work/runner/inert-networks" ]; then + awk '{ out = ""; for (i = 1; i <= NF; i++) if (\$i !~ /\//) out = out (out == "" ? "" : " ") \$i; print out }' "\$3" >"$work/runner/active-rules" + elif [ ! -e "$work/runner/inert-firewall" ]; then + cp "\$3" "$work/runner/active-rules" + fi + echo "pf enabled" >&2 + echo "Token : 4242" >&2 + ;; +-f) cp "\$2" "$work/runner/active-rules" ;; +-X) [ "\$2" = 4242 ] || exit 1 ;; +esac +EOF + cat >"$work/runner/bin/dig" <"$work/runner/bin/curl" <' "\$rules" || return 0 + grep -Eq "[ {]\$1[ }]" "\$rules" && return 1 + case "\$1" in + 17.*) grep -Fq '17.0.0.0/8' "\$rules" && return 1 ;; + 2a01:b740:*) grep -Fq '2a01:b740::/32' "\$rules" && return 1 ;; + esac + return 0 +} +if [ -n "\$address" ]; then + address="\${address#[}" + address="\${address%]}" + if reachable "\$address"; then connected 0; fi + unconnected 28 +fi +pinned=\$(awk -v host="\$host" '\$2 == host { print \$1 }' "$work/runner/hosts") +[ -n "\$pinned" ] || connected 0 +for address in \$pinned; do + if reachable "\$address"; then connected 0; fi +done +unconnected 28 +EOF + printf '#!/bin/bash\necho "dscacheutil $*" >>"%s"\n' "$work/runner/calls" >"$work/runner/bin/dscacheutil" + printf '#!/bin/bash\necho "killall $*" >>"%s"\n' "$work/runner/calls" >"$work/runner/bin/killall" + chmod +x "$work/runner/bin/"* +} + +run_helper() { + HOSTS_FILE="$work/runner/hosts" \ + DEFAULT_PF_CONF="$work/runner/pf.conf" \ + PFCTL_BIN="$work/runner/bin/pfctl" \ + DIG_BIN="$work/runner/bin/dig" \ + CURL_BIN="$work/runner/bin/curl" \ + DSCACHEUTIL_BIN="$work/runner/bin/dscacheutil" \ + KILLALL_BIN="$work/runner/bin/killall" \ + SUDO="" \ + bash "$helper" "$@" +} + +# Runs block, which must fail with an error containing $2, or else fail the +# test with $3. When $1 is "before-blocking", block must also have left the +# hosts file alone. +expect_block_failure() { + local output + if output=$(run_helper block "$work/state" 2>&1); then + fail "$3" + fi + case "$output" in + *"$2"*) ;; + *) fail "$3: $output" ;; + esac + if [ "$1" = before-blocking ] && [ "$(cat "$work/runner/hosts")" != "127.0.0.1 localhost" ]; then + fail "block changed the hosts file before it knew it could show the block works" + fi +} + +make_runner +: >"$work/runner/dns-aaaa.www.apple.com" +: >"$work/runner/dns-a.certs.apple.com" +run_helper block "$work/state" >/dev/null || fail "block did not confirm Apple's services unreachable" +grep -Fxq "192.0.2.1 certs.apple.com" "$work/runner/hosts" \ + || fail "a host DNS gave no IPv4 address is not pinned to a dropped one, so an IPv4 lookup could reach it" +grep -Fq ' 192.0.2.1 ' "$work/runner/active-rules" || fail "the IPv4 placeholder a host is pinned to is not dropped" +for host in api.apple-cloudkit.com ocsp2.apple.com crl.apple.com valid.apple.com www.apple.com; do + grep -Fxq "17.253.0.1 $host" "$work/runner/hosts" || fail "$host is not pinned to its address" + grep -Fxq "$host 17.253.0.1" "$work/state/targets" || fail "$host's address in Apple's network was not checked" +done +grep -Fxq "100::1 www.apple.com" "$work/runner/hosts" \ + || fail "a host DNS gave no IPv6 address is not pinned to a dropped one, so an IPv6 lookup could reach it" +grep -Fq ' 100::1 ' "$work/runner/active-rules" || fail "the IPv6 placeholder a host is pinned to is not dropped" +grep -Fxq "192.0.2.1 ocsp.apple.com" "$work/runner/hosts" && fail "a host with an IPv4 address was pinned to the placeholder too" +if grep -Fq ' 17.253.0.1 ' "$work/runner/active-rules"; then + fail "an address inside Apple's network is listed on its own, so the network entry is never shown to work" +fi +grep -Fxq "2a02:26f0::1 ocsp.apple.com" "$work/runner/hosts" || fail "ocsp.apple.com is not pinned to its IPv6 address outside Apple's networks" +grep -Fxq "ocsp.apple.com" "$work/state/targets" || fail "ocsp.apple.com was not checked by name" +grep -Fq ' 2a02:26f0::1 ' "$work/runner/active-rules" \ + || fail "the firewall does not drop an IPv6 address outside Apple's networks that an Apple host resolves to" +for host in api.apple-cloudkit.com ocsp2.apple.com crl.apple.com valid.apple.com certs.apple.com; do + grep -Fxq "2a01:b740::1 $host" "$work/runner/hosts" || fail "$host is not pinned to its IPv6 address" + grep -Fxq "$host [2a01:b740::1]" "$work/state/targets" || fail "$host's IPv6 address was not checked" + grep -Fxq "$host" "$work/state/targets" || fail "$host was not checked by name" +done +grep -Fxq "2.22.144.17 ocsp.apple.com" "$work/runner/hosts" || fail "ocsp.apple.com is not pinned to its address outside Apple's network" +grep -Fq '2.22.144.17' "$work/runner/active-rules" \ + || fail "the firewall does not block an address outside Apple's networks that an Apple host resolves to" +grep -Fq '17.0.0.0/8' "$work/runner/active-rules" \ + || fail "the firewall does not block Apple's IPv4 network: $(cat "$work/runner/active-rules")" +grep -Fq '2a01:b740::/32' "$work/runner/active-rules" \ + || fail "the firewall does not block Apple's IPv6 networks: $(cat "$work/runner/active-rules")" +grep -q 'dscacheutil -flushcache' "$work/runner/calls" || fail "block did not flush the name cache" +run_helper restore "$work/state" +[ "$(cat "$work/runner/hosts")" = "127.0.0.1 localhost" ] || fail "restore left this hosts file: $(cat "$work/runner/hosts")" +[ "$(cat "$work/runner/active-rules")" = "default rules" ] || fail "restore did not reload the default firewall rules" +grep -Fxq 'pfctl -X 4242' "$work/runner/calls" || fail "restore did not release the firewall token" +echo "PASS: Apple's hosts are pinned to their addresses, which the firewall drops, and restore undoes it" + +make_runner +printf 'ocsp.apple.com 0\n' >"$work/runner/answers-anyway" +expect_block_failure after-blocking "ocsp.apple.com is still reachable" "block reported Apple's services unreachable while one still answered" +echo "PASS: block fails when an Apple service still answers" + +make_runner +printf 'ocsp.apple.com 35\n' >"$work/runner/answers-anyway" +expect_block_failure after-blocking "ocsp.apple.com is still reachable" "a TLS error after connecting was taken for a blocked service" +echo "PASS: a service that connects and then fails TLS still counts as reachable" + +make_runner +printf 'ocsp.apple.com 28\n' >"$work/runner/answers-anyway" +expect_block_failure after-blocking "ocsp.apple.com is still reachable" "a service that accepts and then stalls was taken for a blocked one" +echo "PASS: a service that accepts a connection and then stalls still counts as reachable" + +make_runner +: >"$work/runner/inert-firewall" +expect_block_failure after-blocking "still reachable" "block reported Apple's services unreachable while the firewall let them through" +echo "PASS: block fails when the firewall doesn't stop the traffic" + +make_runner +: >"$work/runner/inert-networks" +expect_block_failure after-blocking "api.apple-cloudkit.com is still reachable" "block reported Apple's network unreachable while only single addresses were dropped" +echo "PASS: block fails when the firewall drops single addresses but not Apple's networks" + +make_runner +: >"$work/runner/inert-ipv6" +expect_block_failure after-blocking "api.apple-cloudkit.com is still reachable" "block reported Apple's IPv6 network unreachable while the firewall let it through" +echo "PASS: block fails when the firewall doesn't stop traffic to Apple's IPv6 network" + +make_runner +: >"$work/runner/no-ipv6" +: >"$work/runner/inert-ipv6" +run_helper block "$work/state" >/dev/null || fail "a runner without IPv6 can't show the IPv6 rules work, and needn't" +if grep -q '\[' "$work/state/targets"; then + fail "an IPv6 address the runner never reached was taken as checked" +fi +echo "PASS: IPv6 is checked only where the runner reaches it" + +make_runner +printf 'crl.apple.com\n' >"$work/runner/never-answers" +expect_block_failure before-blocking "crl.apple.com is unreachable before blocking" "a service that never answered was taken for a blocked one" +echo "PASS: block fails before blocking when a service doesn't answer to begin with" + +make_runner +printf '2.22.144.17\n' >"$work/runner/dns-a" +expect_block_failure before-blocking "no address in Apple's IPv4 network answered" "block proceeded with no address in Apple's network to check the firewall against" +echo "PASS: block fails before blocking when no address in Apple's network answers" + +make_runner +: >"$work/runner/dns-a.crl.apple.com" +: >"$work/runner/dns-aaaa.crl.apple.com" +expect_block_failure before-blocking "DNS gave no address for crl.apple.com" "block proceeded with a host it had no address to block for" +echo "PASS: block fails before blocking when DNS gives a host no address" + +make_runner +: >"$work/runner/pfctl-fails" +expect_block_failure after-blocking "pfctl refused the rules" "block succeeded although the firewall refused its rules" +run_helper restore "$work/state" +[ "$(cat "$work/runner/hosts")" = "127.0.0.1 localhost" ] || fail "restore after a refused block left this hosts file: $(cat "$work/runner/hosts")" +echo "PASS: a refused firewall rule set fails block, and restore still undoes it" + +make_runner +run_helper restore "$work/state" +[ "$(cat "$work/runner/hosts")" = "127.0.0.1 localhost" ] || fail "restore without a block changed the hosts file" +if grep -q '^pfctl' "$work/runner/calls"; then + fail "restore without a block changed the firewall" +fi +echo "PASS: restore without a block changes nothing" diff --git a/scripts/ci/test-macos-developer-tools.sh b/scripts/ci/test-macos-developer-tools.sh new file mode 100755 index 000000000..f64ee5988 --- /dev/null +++ b/scripts/ci/test-macos-developer-tools.sh @@ -0,0 +1,153 @@ +#!/bin/bash +set -euo pipefail + +script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +helper="$script_dir/macos-developer-tools.sh" +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT + +fail() { + echo "FAIL: $*" >&2 + exit 1 +} + +# A fake runner: two Xcode installations, a symlink to one of them, an +# unrelated app, the Command Line Tools, and developer-tool commands whose +# answers follow the selected developer directory the way Apple's do. +make_runner() { + rm -rf "$work/runner" "$work/state" + mkdir -p "$work/runner/Applications/Xcode_16.4.app/Contents/Developer/usr/bin" \ + "$work/runner/Applications/Xcode_26.0.app/Contents/Developer/usr/bin" \ + "$work/runner/Applications/Safari.app" \ + "$work/runner/CommandLineTools/usr/bin" "$work/runner/bin" + ln -s "$work/runner/Applications/Xcode_16.4.app" "$work/runner/Applications/Xcode.app" + printf '%s\n' "$work/runner/Applications/Xcode.app/Contents/Developer" >"$work/runner/selected" + cat >"$work/runner/bin/xcode-select" <"$work/runner/selected" + elif [ -d "$work/runner/CommandLineTools" ]; then + echo "$work/runner/CommandLineTools" >"$work/runner/selected" + else + : >"$work/runner/selected" + fi + ;; +--switch) echo "\$2" >"$work/runner/selected" ;; +-p) selected=\$(cat "$work/runner/selected"); [ -n "\$selected" ] && [ -d "\$selected" ] || exit 2; echo "\$selected" ;; +esac +EOF + cat >"$work/runner/bin/xcrun" <"$work/runner/bin/stapler" <&2; exit 1 ;; +esac +EOF + # Like getconf: prints the per-user temporary directory, or nothing when + # getconf-fails exists. + cat >"$work/runner/bin/getconf" </dev/null 2>&1; then + fail "verify accepted a runner that still has Xcode" +fi + +run_helper hide none "$work/state" >/dev/null +[ "$(apps)" = "Safari.app " ] || fail "hiding developer tools left these apps: $(apps)" +[ ! -e "$work/runner/CommandLineTools" ] || fail "the Command Line Tools were not hidden" +if run_helper hide none "$work/state" >/dev/null 2>&1; then + fail "hiding twice would lose track of the first hidden tools" +fi +run_helper restore "$work/state" +[ "$(apps)" = "Safari.app Xcode.app Xcode_16.4.app Xcode_26.0.app " ] || fail "restore left these apps: $(apps)" +[ -L "$work/runner/Applications/Xcode.app" ] || fail "restore did not keep Xcode.app a symlink" +[ -d "$work/runner/CommandLineTools/usr/bin" ] || fail "restore did not bring the Command Line Tools back" +[ "$(cat "$work/runner/selected")" = "$work/runner/Applications/Xcode.app/Contents/Developer" ] \ + || fail "restore did not select Xcode again" +echo "PASS: a runner without developer tools is verified and restored" + +run_helper hide command-line-tools "$work/state" >/dev/null +[ "$(apps)" = "Safari.app " ] || fail "hiding Xcode left these apps: $(apps)" +[ -d "$work/runner/CommandLineTools" ] || fail "the Command Line Tools must stay" +[ "$(cat "$work/runner/selected")" = "$work/runner/CommandLineTools" ] || fail "the Command Line Tools were not selected" +run_helper restore "$work/state" +[ "$(apps)" = "Safari.app Xcode.app Xcode_16.4.app Xcode_26.0.app " ] || fail "restore left these apps: $(apps)" +echo "PASS: a runner with only the Command Line Tools is verified and restored" + +make_runner +: >"$work/runner/working-stapler" +if run_helper hide command-line-tools "$work/state" >/dev/null 2>&1; then + fail "a stapler that runs and merely rejects its input was taken for Apple's Xcode-only shim" +fi +run_helper restore "$work/state" +echo "PASS: a working stapler is not mistaken for a Mac with only the Command Line Tools" + +make_runner +rm -rf "$work/runner/CommandLineTools" +if run_helper hide command-line-tools "$work/state" >/dev/null 2>&1; then + fail "a runner without the Command Line Tools cannot stand for one that has only them" +fi +run_helper restore "$work/state" +echo "PASS: a missing Command Line Tools installation is reported" + +make_runner +run_helper restore "$work/state" +[ "$(apps)" = "Safari.app Xcode.app Xcode_16.4.app Xcode_26.0.app " ] || fail "restore without hidden tools changed apps" +echo "PASS: restore without hidden tools changes nothing" + +make_runner +printf '%s\n' "$work/runner/Applications/Xcode_26.0.app/Contents/Developer" >"$work/runner/selected" +: >"$work/cache dir/xcrun_db" +: >"$work/user temp/xcrun_db" +run_helper hide none "$work/state" >/dev/null +[ ! -e "$work/cache dir/xcrun_db" ] && [ ! -e "$work/user temp/xcrun_db" ] \ + || fail "hiding developer tools left xcrun's cache of their paths" +run_helper restore "$work/state" +[ "$(cat "$work/runner/selected")" = "$work/runner/Applications/Xcode_26.0.app/Contents/Developer" ] \ + || fail "restore selected $(cat "$work/runner/selected") instead of the Xcode selected before" +echo "PASS: restore selects the developer directory selected before" + +make_runner +: >"$work/runner/getconf-fails" +run_helper hide none "$work/state" >/dev/null || fail "hide stopped when getconf named no per-user temporary directory" +run_helper restore "$work/state" || fail "restore stopped when getconf named no per-user temporary directory" +[ "$(apps)" = "Safari.app Xcode.app Xcode_16.4.app Xcode_26.0.app " ] || fail "restore left these apps: $(apps)" +echo "PASS: a missing per-user temporary directory doesn't stop hide or restore" diff --git a/tests/install-sh/run.sh b/tests/install-sh/run.sh index 094727330..d9dc274e9 100755 --- a/tests/install-sh/run.sh +++ b/tests/install-sh/run.sh @@ -214,8 +214,11 @@ build_clean_path() { if [ "$(PATH="$CLEAN_PATH_DIR" uname -s)" = "Darwin" ]; then ln -s "$(command -v ditto)" "$CLEAN_PATH_DIR/ditto" ln -s "$(command -v unzip)" "$CLEAN_PATH_DIR/unzip" - # A staged copy reports the CDHash in $LPM_TEST_TOOL_STATE/staged-cdhash - # and has its stapled ticket replaced when tamper-staged-ticket exists. + # Verifying fails as for code that isn't LPM's notarized Developer ID + # code unless install.sh passes LPM's exact requirement, or when + # $LPM_TEST_TOOL_STATE/unsatisfied-requirement exists. A staged copy + # reports the CDHash in staged-cdhash and has its stapled ticket replaced + # when tamper-staged-ticket exists. cat > "$CLEAN_PATH_DIR/codesign" <<'EOF' #!/bin/sh for bundle in "$@"; do :; done @@ -227,6 +230,18 @@ staged_override() { } case " $* " in *" --verify "*) + expected_requirement='=anchor apple generic and identifier "dev.lpm.cli" and certificate 1[field.1.2.840.113635.100.6.2.6] exists and certificate leaf[field.1.2.840.113635.100.6.1.13] exists and certificate leaf[subject.OU] = "823S8YKMRW" and notarized' + requirement="" + previous="" + for argument in "$@"; do + [ "$previous" = -R ] && requirement="$argument" + previous="$argument" + done + if [ "$requirement" != "$expected_requirement" ] || \ + { [ -n "${LPM_TEST_TOOL_STATE:-}" ] && [ -e "$LPM_TEST_TOOL_STATE/unsatisfied-requirement" ]; }; then + echo "$bundle: code failed to satisfy specified code requirement(s)" >&2 + exit 3 + fi if staged_override tamper-staged-ticket; then printf 'replaced-notarization-ticket' > "$bundle/Contents/CodeResources" fi @@ -246,16 +261,28 @@ case " $* " in esac exit 0 EOF - cat > "$CLEAN_PATH_DIR/security" <<'EOF' + # Decodes a provisioning profile the way `openssl smime -out` does. Like + # macOS's LibreSSL, it writes nothing yet exits 0 when OPENSSL_CONF names + # a configuration, and it writes nothing when profile-not-written exists. + cat > "$CLEAN_PATH_DIR/openssl" <<'EOF' #!/bin/sh -cat <<'PLIST' +[ "$1 $2 $3 $4 $5 $6" = "smime -verify -noverify -nosigs -inform DER" ] || exit 99 +if [ -n "${OPENSSL_CONF:-}" ]; then + echo "failed to load configuration" >&2 + exit 0 +fi +if [ -n "${LPM_TEST_TOOL_STATE:-}" ] && [ -e "$LPM_TEST_TOOL_STATE/profile-not-written" ]; then + exit 0 +fi +while [ "$#" -gt 0 ]; do + [ "$1" = -out ] && out="$2" + shift +done +cat > "$out" <<'PLIST' TeamIdentifier823S8YKMRWEntitlementscom.apple.application-identifier823S8YKMRW.dev.lpm.clikeychain-access-groups823S8YKMRW.* PLIST EOF - printf '#!/bin/sh\nexit 0\n' > "$CLEAN_PATH_DIR/spctl" - printf '#!/bin/sh\nexit 0\n' > "$CLEAN_PATH_DIR/xcrun" - chmod +x "$CLEAN_PATH_DIR/codesign" "$CLEAN_PATH_DIR/security" \ - "$CLEAN_PATH_DIR/spctl" "$CLEAN_PATH_DIR/xcrun" + chmod +x "$CLEAN_PATH_DIR/codesign" "$CLEAN_PATH_DIR/openssl" fi } @@ -267,14 +294,10 @@ run_install_sh() { install_root="$(mktemp -d)" fi test_codesign="" - test_security="" - test_spctl="" - test_xcrun="" + test_openssl="" if [ "$(PATH="$CLEAN_PATH_DIR" uname -s)" = "Darwin" ]; then test_codesign="$CLEAN_PATH_DIR/codesign" - test_security="$CLEAN_PATH_DIR/security" - test_spctl="$CLEAN_PATH_DIR/spctl" - test_xcrun="$CLEAN_PATH_DIR/xcrun" + test_openssl="$CLEAN_PATH_DIR/openssl" fi set +e RUN_OUT="$( @@ -282,9 +305,7 @@ run_install_sh() { LPM_INSTALL_TEST_API_URL="http://127.0.0.1:$SERVER_PORT/api.json" \ LPM_INSTALL_TEST_DOWNLOAD_BASE="http://127.0.0.1:$SERVER_PORT" \ LPM_INSTALL_TEST_CODESIGN="$test_codesign" \ - LPM_INSTALL_TEST_SECURITY="$test_security" \ - LPM_INSTALL_TEST_SPCTL="$test_spctl" \ - LPM_INSTALL_TEST_XCRUN="$test_xcrun" \ + LPM_INSTALL_TEST_OPENSSL="$test_openssl" \ LPM_INSTALL_TEST_INTERRUPT_AFTER="${LPM_INSTALL_TEST_INTERRUPT_AFTER:-}" \ LPM_MV_FAILURE_COUNT_FILE="${LPM_MV_FAILURE_COUNT_FILE:-}" \ LPM_TEST_TOOL_STATE="${LPM_TEST_TOOL_STATE:-}" \ @@ -292,6 +313,7 @@ run_install_sh() { LPM_TEST_COSIGN_REFUSED_TRIGGER="${LPM_TEST_COSIGN_REFUSED_TRIGGER:-}" \ RELEASE_COMMIT="${RELEASE_COMMIT:-}" \ HOME="$install_root" \ + CURL_HOME="$install_root" \ LPM_INSTALL_INSECURE="${LPM_INSTALL_INSECURE:-}" \ LPM_INSTALL_MIN_VERSION_OVERRIDE="${LPM_INSTALL_MIN_VERSION_OVERRIDE:-}" \ LPM_INSTALL_REQUIRE_SIGSTORE="${LPM_INSTALL_REQUIRE_SIGSTORE:-}" \ @@ -391,6 +413,34 @@ build_clean_path sh -n "$INSTALL_SH" || fail "install.sh has shell syntax errors" pass "install.sh shell syntax" +# ── Case 1b: the installer depends only on the release and macOS ─ +# Each xcrun shim in /usr/bin is a hard link of git (the Command Line Tools +# shims) or xcodebuild (the Xcode-only shims, stapler among them), and fails +# on a Mac without developer tools. Gatekeeper's assessors and Apple's +# services answer from the Mac's security policy and the network, so a +# genuine release could be refused on some Macs. +if grep -v '^[[:space:]]*#' "$INSTALL_SH" | grep -Eq '(^|[^[:alnum:]_])(xcrun|stapler|xcode-select|spctl|syspolicy_check)([^[:alnum:]_]|$)|apple(-cloudkit)?\.com'; then + fail "install.sh depends on a developer tool, a Gatekeeper assessor or an Apple service: $(grep -n -E '(xcrun|stapler|xcode-select|spctl|syspolicy_check)|apple(-cloudkit)?\.com' "$INSTALL_SH" | grep -v ':[[:space:]]*#')" +fi +if [ "$HOST_OS" = "Darwin" ]; then + shim_identities="$(stat -f '%d:%i' /usr/bin/git /usr/bin/xcodebuild)" + harness_clean_path_dir="${CLEAN_PATH_DIR:-}" + build_clean_path + absolute_tools="$(sed -n 's/^MACOS_[A-Z0-9_]*_TOOL="\(\/[^"]*\)"$/\1/p' "$INSTALL_SH")" + [ -n "$absolute_tools" ] || fail "found no macOS tool paths in install.sh" + for tool in $absolute_tools $(find "$CLEAN_PATH_DIR" -type l); do + resolved="$tool" + [ -L "$tool" ] && resolved="$(readlink "$tool")" + [ -x "$resolved" ] || fail "$resolved does not ship with this macOS" + if printf '%s\n' "$shim_identities" | grep -Fxq "$(stat -L -f '%d:%i' "$resolved")"; then + fail "install.sh runs $resolved, an xcrun shim that needs Xcode or the Command Line Tools" + fi + done + rm -rf "$CLEAN_PATH_DIR" + CLEAN_PATH_DIR="$harness_clean_path_dir" +fi +pass "install.sh needs no developer tool, Gatekeeper assessor or Apple service" + # ── Case 2: sudo transition fails before installer activity ─── sudo_path_dir="$(mktemp -d)" sudo_home_dir="$(mktemp -d)" @@ -477,17 +527,26 @@ echo "$out" | grep -q "127.0.0.1" || fail "expected loopback-only error: $out" for spoofed_url in \ "http://localhost.attacker.example/x" \ "http://127.0.0.1.attacker.example/x" \ - "http://localhost:80.attacker.example/x" + "http://localhost:80.attacker.example/x" \ + "http://127.0.0.1:1@attacker.example:80/x" \ + "http://localhost:x@attacker.example:80/x" \ + "http://[::1]:1@attacker.example:80/x" \ + "http://127.0.0.1@attacker.example/x" do + for override in LPM_INSTALL_TEST_API_URL LPM_INSTALL_TEST_DOWNLOAD_BASE; do + actual_exit=0 + out="$(env "$override=$spoofed_url" sh "$INSTALL_SH" 2>&1)" || actual_exit=$? + [ "$actual_exit" -ne 0 ] || fail "$override must fail closed for $spoofed_url" + echo "$out" | grep -q "must point at 127.0.0.1" || fail "$override accepted $spoofed_url: $out" + done +done +for override in LPM_INSTALL_TEST_CODESIGN LPM_INSTALL_TEST_OPENSSL; do actual_exit=0 - out="$(LPM_INSTALL_TEST_API_URL="$spoofed_url" sh "$INSTALL_SH" 2>&1)" || actual_exit=$? - [ "$actual_exit" -ne 0 ] || fail "loopback-prefix hostname should fail-closed: $spoofed_url" + out="$(env "$override=/tmp/fake-tool" sh "$INSTALL_SH" 2>&1)" || actual_exit=$? + [ "$actual_exit" -ne 0 ] || fail "$override should require loopback endpoints" + echo "$out" | grep -q "loopback test endpoints" \ + || fail "$override failure did not explain the loopback requirement: $out" done -actual_exit=0 -out="$(LPM_INSTALL_TEST_CODESIGN="/tmp/fake-codesign" sh "$INSTALL_SH" 2>&1)" || actual_exit=$? -[ "$actual_exit" -ne 0 ] || fail "macOS tool override should require loopback endpoints" -echo "$out" | grep -q "loopback test endpoints" \ - || fail "tool-override failure did not explain the loopback requirement: $out" pass "test-override env vars are loopback-gated" # ── Case 5: happy path ───────────────────────────────────────── @@ -758,114 +817,68 @@ if [ "$HOST_OS" = "Darwin" ]; then rm -rf "$fdir" pass "icon-bearing macOS release requires its declared icon" - # stapler validate exits 68 (EX_NOHOST) while Apple's CloudKit ticket - # lookup doesn't answer. Apple is asked about the downloaded bundle only; - # the staged copy must carry the same code and the same stapled ticket. + # The downloaded bundle must be LPM's notarized Developer ID code, and the + # staged copy must carry its code and its stapled ticket. tool_state="$(mktemp -d)" - rm -f "$CLEAN_PATH_DIR/xcrun" "$CLEAN_PATH_DIR/sleep" - cat > "$CLEAN_PATH_DIR/xcrun" <<'EOF' -#!/bin/sh -[ "$1" = stapler ] && [ "$2" = validate ] && [ "$#" -eq 3 ] || exit 99 -printf '%s\n' "$3" >> "$LPM_TEST_TOOL_STATE/stapler-runs" -run=$(grep -c '' "$LPM_TEST_TOOL_STATE/stapler-runs") -status=$(sed -n "${run}p" "$LPM_TEST_TOOL_STATE/stapler-outcomes") -[ "$status" -eq 0 ] || echo "The validate action failed! Error $status." -exit "$status" -EOF - cat > "$CLEAN_PATH_DIR/sleep" <<'EOF' -#!/bin/sh -printf '%s\n' "$*" >> "$LPM_TEST_TOOL_STATE/sleep-requests" -EOF - chmod +x "$CLEAN_PATH_DIR/xcrun" "$CLEAN_PATH_DIR/sleep" fdir="$(mktemp -d)" printf '{"tag_name": "%s"}\n' "$FIXTURE_VERSION" > "$fdir/api.json" - write_release_asset "$fdir" 'notarization-retry-binary-bytes' + write_release_asset "$fdir" 'bundle-validation-binary-bytes' sha="$($SHA_TOOL "$fdir/$RELEASE_ASSET" | awk '{print $1}')" printf '%s %s\n' "$sha" "$RELEASE_ASSET" > "$fdir/SHA256SUMS.txt" printf 'dummy-sigstore-bundle' > "$fdir/SHA256SUMS.txt.sigstore" - run_with_stapler_outcomes() { - printf '%s\n' "$@" > "$tool_state/stapler-outcomes" - : > "$tool_state/stapler-runs" - : > "$tool_state/sleep-requests" + run_with_tool_state() { trap 'stop_server' EXIT start_server "$fdir" LPM_TEST_TOOL_STATE="$tool_state" run_install_sh stop_server trap - EXIT - STAPLER_RUNS="$(grep -c '' "$tool_state/stapler-runs" || true)" - SLEEP_REQUESTS="$(tr '\n' ' ' < "$tool_state/sleep-requests")" } - run_with_stapler_outcomes 68 68 0 - [ "$RUN_RC" -eq 0 ] \ - || fail "a brief CloudKit outage failed the install with exit $RUN_RC: $RUN_OUT" - [ "$STAPLER_RUNS" -eq 3 ] || fail "brief CloudKit outage ran stapler $STAPLER_RUNS times, expected 3" - [ "$SLEEP_REQUESTS" = "2 5 " ] || fail "notarization ticket retries waited '$SLEEP_REQUESTS', expected '2 5 '" - echo "$RUN_OUT" | grep -q "checking the notarization ticket again in 2s" \ - || fail "notarization ticket retry was not announced: $RUN_OUT" - [ -L "$RUN_INSTALL_DIR/lpm" ] || fail "install after a brief CloudKit outage did not link lpm" - pass "macOS install outlasts a brief CloudKit outage while checking the notarization ticket" - - run_with_stapler_outcomes 68 68 68 68 68 0 - [ "$RUN_RC" -eq 0 ] \ - || fail "a two-minute CloudKit outage failed the install with exit $RUN_RC: $RUN_OUT" - [ "$STAPLER_RUNS" -eq 6 ] || fail "two-minute CloudKit outage ran stapler $STAPLER_RUNS times, expected 6" - [ "$SLEEP_REQUESTS" = "2 5 15 30 60 " ] \ - || fail "notarization ticket retries waited '$SLEEP_REQUESTS', expected '2 5 15 30 60 '" - [ -L "$RUN_INSTALL_DIR/lpm" ] || fail "install after a two-minute CloudKit outage did not link lpm" - pass "macOS install outlasts a CloudKit outage of about two minutes" - - run_with_stapler_outcomes 68 68 68 68 68 68 0 - [ "$RUN_RC" -ne 0 ] || fail "a lasting CloudKit outage must fail the install" - [ "$STAPLER_RUNS" -eq 6 ] || fail "lasting CloudKit outage ran stapler $STAPLER_RUNS times, expected 6" - [ "$SLEEP_REQUESTS" = "2 5 15 30 60 " ] \ - || fail "lasting CloudKit outage waited '$SLEEP_REQUESTS', expected '2 5 15 30 60 '" - echo "$RUN_OUT" | grep -q "Apple's notarization service did not answer while checking downloaded" \ - || fail "lasting CloudKit outage was reported as something else: $RUN_OUT" - [ ! -e "$RUN_INSTALL_DIR/lpm" ] || fail "lasting CloudKit outage must not install anything" - pass "macOS install fails closed on a lasting CloudKit outage" - - run_with_stapler_outcomes 0 68 68 68 68 68 68 - [ "$RUN_RC" -eq 0 ] \ - || fail "CloudKit going quiet after the downloaded bundle passed failed the install with exit $RUN_RC: $RUN_OUT" - [ "$STAPLER_RUNS" -eq 1 ] || fail "one install asked Apple about its notarization ticket $STAPLER_RUNS times, expected once" - [ -z "$SLEEP_REQUESTS" ] || fail "a confirmed notarization ticket still waited '$SLEEP_REQUESTS'" - [ -L "$RUN_INSTALL_DIR/lpm" ] || fail "install with a confirmed notarization ticket did not link lpm" - pass "macOS install asks Apple about the notarization ticket once" + harness_openssl_conf="${OPENSSL_CONF-}" + export OPENSSL_CONF="$tool_state/openssl3.cnf" + run_with_tool_state + if [ -n "$harness_openssl_conf" ]; then OPENSSL_CONF="$harness_openssl_conf"; else unset OPENSSL_CONF; fi + [ "$RUN_RC" -eq 0 ] || fail "an OPENSSL_CONF in the environment failed the install with exit $RUN_RC: $RUN_OUT" + [ -L "$RUN_INSTALL_DIR/lpm" ] || fail "an OPENSSL_CONF in the environment kept lpm from being installed" + pass "macOS install decodes the provisioning profile whatever OPENSSL_CONF says" + + : > "$tool_state/profile-not-written" + run_with_tool_state + rm -f "$tool_state/profile-not-written" + [ "$RUN_RC" -ne 0 ] || fail "a provisioning profile openssl didn't decode must fail the install" + echo "$RUN_OUT" | grep -q "downloaded LPM CLI.app has an unreadable provisioning profile" \ + || fail "a provisioning profile openssl didn't decode was reported as something else: $RUN_OUT" + [ ! -e "$RUN_INSTALL_DIR/lpm" ] || fail "a provisioning profile openssl didn't decode must not install anything" + pass "macOS install refuses a provisioning profile openssl exits 0 without decoding" + + : > "$tool_state/unsatisfied-requirement" + run_with_tool_state + rm -f "$tool_state/unsatisfied-requirement" + [ "$RUN_RC" -ne 0 ] || fail "a bundle that isn't LPM's notarized Developer ID code must fail the install" + echo "$RUN_OUT" | grep -q "downloaded LPM CLI.app failed code-signature and notarization validation" \ + || fail "a bundle that isn't LPM's notarized Developer ID code was reported as something else: $RUN_OUT" + [ ! -e "$RUN_INSTALL_DIR/lpm" ] || fail "a bundle that isn't LPM's notarized Developer ID code must not install anything" + pass "macOS install refuses a bundle that isn't LPM's notarized Developer ID code" printf '%s' 'a1b2c3d4e5f60718293a4b5c6d7e8f9001122334' > "$tool_state/staged-cdhash" - run_with_stapler_outcomes 0 0 + run_with_tool_state rm -f "$tool_state/staged-cdhash" [ "$RUN_RC" -ne 0 ] || fail "a staged copy with different code must fail the install" - [ "$STAPLER_RUNS" -eq 1 ] || fail "a staged copy with different code was checked with Apple instead of against the download" - echo "$RUN_OUT" | grep -q "staged LPM CLI.app differs from the downloaded bundle" \ + echo "$RUN_OUT" | grep -q "staged LPM CLI.app differs from the downloaded bundle that was validated" \ || fail "a staged copy with different code was reported as something else: $RUN_OUT" [ ! -e "$RUN_INSTALL_DIR/lpm" ] || fail "a staged copy with different code must not install anything" - pass "macOS install rejects a staged copy whose code differs from the confirmed download" + pass "macOS install rejects a staged copy whose code differs from the validated download" : > "$tool_state/tamper-staged-ticket" - run_with_stapler_outcomes 0 0 + run_with_tool_state rm -f "$tool_state/tamper-staged-ticket" [ "$RUN_RC" -ne 0 ] || fail "a staged copy with a different ticket must fail the install" - [ "$STAPLER_RUNS" -eq 1 ] || fail "a staged copy with a different ticket was checked with Apple instead of against the download" - echo "$RUN_OUT" | grep -q "staged LPM CLI.app differs from the downloaded bundle" \ + echo "$RUN_OUT" | grep -q "staged LPM CLI.app differs from the downloaded bundle that was validated" \ || fail "a staged copy with a different ticket was reported as something else: $RUN_OUT" [ ! -e "$RUN_INSTALL_DIR/lpm" ] || fail "a staged copy with a different ticket must not install anything" - pass "macOS install rejects a staged copy whose stapled ticket differs from the confirmed download" - - run_with_stapler_outcomes 65 0 - [ "$RUN_RC" -ne 0 ] || fail "an invalid notarization ticket must fail the install" - [ "$STAPLER_RUNS" -eq 1 ] || fail "invalid notarization ticket was retried ($STAPLER_RUNS stapler runs)" - [ -z "$SLEEP_REQUESTS" ] || fail "invalid notarization ticket waited '$SLEEP_REQUESTS'" - echo "$RUN_OUT" | grep -q "does not contain a valid notarization ticket" \ - || fail "invalid notarization ticket failure was unclear: $RUN_OUT" - [ ! -e "$RUN_INSTALL_DIR/lpm" ] || fail "invalid notarization ticket must not install anything" - pass "macOS install rejects an invalid notarization ticket without retrying" + pass "macOS install rejects a staged copy whose stapled ticket differs from the validated download" rm -rf "$fdir" "$tool_state" - printf '#!/bin/sh\nexit 0\n' > "$CLEAN_PATH_DIR/xcrun" - rm -f "$CLEAN_PATH_DIR/sleep" - ln -s "$(command -v sleep)" "$CLEAN_PATH_DIR/sleep" fi # ── Case 10: manifest 404 fails closed ──────────────────────── diff --git a/tests/workflows/tests/self_update.rs b/tests/workflows/tests/self_update.rs index b05ef5047..06eb9bd9c 100644 --- a/tests/workflows/tests/self_update.rs +++ b/tests/workflows/tests/self_update.rs @@ -1564,6 +1564,226 @@ fn self_update_recent_failure_short_circuits_with_backoff_error() { ); } +/// Runs a standalone `lpm self-update` that must be refused, against release +/// endpoints that know no release, as a human and with `--json`. +#[cfg(unix)] +fn refused_standalone_self_update( + project: &TempProject, + standalone: &std::path::Path, + releases: &str, + channel: Option<&str>, +) -> (String, serde_json::Value) { + let mut arguments = vec!["self-update"]; + if let Some(channel) = channel { + arguments.extend(["--channel", channel]); + } + let run = |json: bool| { + let mut command = lpm_from_path(project, standalone); + command + .env( + "LPM_GITHUB_RELEASE_BY_TAG_URL_OVERRIDE", + format!("{releases}/releases/tags/v{{tag}}"), + ) + .env( + "LPM_GITHUB_RELEASE_DOWNLOAD_URL_OVERRIDE", + format!("{releases}/download/v{{tag}}/{{file}}"), + ); + if json { + command.arg("--json"); + } + let output = command.args(&arguments).output().unwrap(); + assert!( + !output.status.success(), + "stdout: {}\nstderr: {}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr), + ); + output + }; + let human = String::from_utf8(run(false).stderr).unwrap(); + let json = run(true); + let envelope = serde_json::from_slice(&json.stdout).unwrap_or_else(|error| { + panic!( + "{error}\nstdout: {}\nstderr: {}", + String::from_utf8_lossy(&json.stdout), + String::from_utf8_lossy(&json.stderr), + ) + }); + (human, envelope) +} + +#[cfg(unix)] +fn assert_refusal_names(human: &str, envelope: &serde_json::Value, installer: &str) { + assert!(human.contains("Self-update refused"), "{human}"); + assert!(human.contains(installer), "{human}"); + assert_eq!(envelope["success"], false, "{envelope}"); + assert_eq!(envelope["error_code"], "self_update", "{envelope}"); + assert!( + envelope["error"] + .as_str() + .is_some_and(|error| error.starts_with("self-update refused: ")), + "{envelope}" + ); + assert_eq!( + envelope["next_steps"][0]["command"], installer, + "{envelope}" + ); +} + +/// Seeds update caches that name a newer release on both channels, so no +/// release lookup reaches the network. +#[cfg(unix)] +fn seed_newer_releases_on_both_channels(project: &TempProject) { + std::fs::create_dir_all(cache_path(project).parent().unwrap()).expect("mkdir ~/.lpm"); + let payload = serde_json::json!({ + "latest": "99999.0.0", + "lastCheck": now_secs(), + "nightly": { + "latest": "99999.0.0-nightly.20990101.1.0000000", + "lastCheck": now_secs(), + }, + }); + std::fs::write(cache_path(project), payload.to_string()).expect("seed update caches"); +} + +/// Reinstalling doesn't fix an installation directory any account can write +/// to, so that refusal names no installer and explains itself. +#[cfg(unix)] +#[tokio::test] +async fn refused_shared_writable_standalone_installation_names_no_reinstall() { + use std::os::unix::fs::PermissionsExt as _; + + let releases = support::mock_registry::MockRegistry::start().await; + let project = TempProject::empty(r#"{"name":"su","version":"1.0.0"}"#); + seed_newer_releases_on_both_channels(&project); + let bin = project.home().join(".lpm").join("bin"); + std::fs::create_dir_all(&bin).unwrap(); + let standalone = bin.join("lpm"); + std::fs::copy(support::lpm_binary(), &standalone).unwrap(); + std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o777)).unwrap(); + + let (human, envelope) = + refused_standalone_self_update(&project, &standalone, &releases.url(), None); + + assert!(human.contains("Self-update refused"), "{human}"); + assert!( + human.contains("shared-writable install directory"), + "{human}" + ); + assert!(!human.contains("cli.lpm.dev/install"), "{human}"); + assert_eq!(envelope["error_code"], "self_update", "{envelope}"); + assert!(envelope.get("next_steps").is_none(), "{envelope}"); +} + +/// A macOS standalone install updates only from the installer's app-bundle +/// layout, so a copy outside it names the installer, which puts LPM CLI there +/// and keeps the user's settings. +#[cfg(target_os = "macos")] +#[tokio::test] +async fn standalone_install_outside_the_installer_layout_names_the_installer_for_its_channel() { + let releases = support::mock_registry::MockRegistry::start().await; + for (channel, installer) in [ + ( + None, + "curl -fsSL https://cli.lpm.dev/install | LPM_INSTALL_CHANNEL=stable sh", + ), + ( + Some("nightly"), + "curl -fsSL https://cli.lpm.dev/install | LPM_INSTALL_CHANNEL=nightly sh", + ), + ] { + let project = TempProject::empty(r#"{"name":"su","version":"1.0.0"}"#); + seed_newer_releases_on_both_channels(&project); + let bin = project.home().join(".lpm").join("bin"); + std::fs::create_dir_all(&bin).unwrap(); + let standalone = bin.join("lpm"); + std::fs::copy(support::lpm_binary(), &standalone).unwrap(); + + let (human, envelope) = + refused_standalone_self_update(&project, &standalone, &releases.url(), channel); + + assert!(human.contains("require execution from"), "{human}"); + assert_refusal_names(&human, &envelope, installer); + if channel.is_none() { + let mut snapshot = envelope; + snapshot["error"] = serde_json::json!(""); + insta::assert_json_snapshot!(snapshot, @r#" + { + "schema_version": 1, + "success": false, + "error": "", + "error_code": "self_update", + "next_steps": [ + { + "description": "Reinstall LPM CLI with the official installer, which verifies the release itself and keeps your settings", + "command": "curl -fsSL https://cli.lpm.dev/install | LPM_INSTALL_CHANNEL=stable sh" + } + ] + } + "#); + } + } +} + +/// A release the updater couldn't verify is reinstalled only through a check +/// that authenticates its publisher: the app's Developer ID signature on +/// macOS, and on Linux the release's Sigstore signature, which the installer +/// checks only when told to require it. +#[cfg(unix)] +#[tokio::test] +async fn standalone_release_refused_by_verification_names_an_installer_that_authenticates_it() { + let releases = support::mock_registry::MockRegistry::start().await; + let project = TempProject::empty(r#"{"name":"su","version":"1.0.0"}"#); + seed_newer_releases_on_both_channels(&project); + let standalone = if cfg!(target_os = "macos") { + project + .home() + .join(".lpm/libexec/LPM CLI.app/Contents/MacOS/lpm-rs") + } else { + project.home().join(".lpm/bin/lpm") + }; + std::fs::create_dir_all(standalone.parent().unwrap()).unwrap(); + std::fs::copy(support::lpm_binary(), &standalone).unwrap(); + + let (human, envelope) = + refused_standalone_self_update(&project, &standalone, &releases.url(), None); + + let installer = if cfg!(target_os = "macos") { + "curl -fsSL https://cli.lpm.dev/install | LPM_INSTALL_CHANNEL=stable sh" + } else { + "curl -fsSL https://cli.lpm.dev/install | LPM_INSTALL_CHANNEL=stable LPM_INSTALL_REQUIRE_SIGSTORE=1 sh" + }; + assert_refusal_names(&human, &envelope, installer); + // The manifest, its Sigstore bundle and the release are fetched together, + // so whichever the mock refuses first names the reason. + assert!( + human.contains("no release at tag v99999.0.0") + || human.contains("release v99999.0.0 does not ship SHA256SUMS.txt") + || human.contains( + "release v99999.0.0 ships SHA256SUMS.txt but not SHA256SUMS.txt.sigstore" + ), + "the refusal must come from verifying the release: {human}" + ); + if cfg!(not(target_os = "macos")) { + let mut snapshot = envelope; + snapshot["error"] = serde_json::json!(""); + insta::assert_json_snapshot!(snapshot, @r#" + { + "schema_version": 1, + "success": false, + "error": "", + "error_code": "self_update", + "next_steps": [ + { + "description": "If this release keeps failing verification, install cosign and reinstall LPM CLI with the official installer, which then checks the release's signature itself and keeps your settings", + "command": "curl -fsSL https://cli.lpm.dev/install | LPM_INSTALL_CHANNEL=stable LPM_INSTALL_REQUIRE_SIGSTORE=1 sh" + } + ] + } + "#); + } +} + // ─── release-workflow signing gate ──────────────────────────────────── const V0_84_0_SOURCE_COMMIT: &str = "35edeab28d25a6851519629e99e478c3cd810c3a";