From 7ba50e3c1294e7be85c823370f55a9b80c041b85 Mon Sep 17 00:00:00 2001 From: Tolga Ergin Date: Wed, 25 Nov 2026 00:21:38 +0000 Subject: [PATCH 1/5] Install and self-update on Macs without Xcode or the Command Line Tools lpm self-update ran /usr/bin/stapler and install.sh ran `xcrun stapler`. Both are xcrun shims: stapler needs Xcode, so self-update refused every update on a Mac with only the Command Line Tools, and both failed on a Mac with neither. GitHub's macOS runners have Xcode, so no test saw it. Both now confirm the notarization ticket the way `stapler validate` does, with tools every Mac ships with: they look up Apple's ticket record for the app's SHA-256 code-directory hash over HTTPS and require it to equal the stapled ticket byte for byte. A missing, revoked or different ticket fails at once; an unanswered lookup is retried for about two minutes as before. The code-signature check now also requires LPM's Developer ID identity and `notarized`, which verifies the stapled ticket's Apple signature offline on a Mac that hasn't seen this code. Gatekeeper's assessment is unchanged. The provisioning profile is decoded in process (self-update) or with openssl (install.sh) instead of `security cms -D`, which needs a default keychain. Self-update runs its validation tools with only the system PATH, so variables such as DEVELOPER_DIR can't change what they do. Tests: - macOS validation may run only programs that ship with macOS; a test fails for any xcrun shim, and install.sh's harness checks its tools the same way - the ticket lookup's answers, retries and refusals, in Rust and install.sh - real signed releases, including swapped and garbage tickets - a new CI job removes Xcode, or Xcode and the Command Line Tools, from a macOS runner, then installs and upgrades through install.sh, checks an affected v0.85.0 install, and self-updates this build to the latest signed stable and nightly releases; it also runs daily - the release candidate's installer smoke runs without developer tools Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 3 + .../release-upgrade-compatibility.yml | 166 ++++++ .github/workflows/release.yml | 21 +- Cargo.lock | 1 + crates/lpm-cli/Cargo.toml | 1 + crates/lpm-cli/src/commands/self_update.rs | 535 ++++++++--------- .../src/commands/self_update/notarization.rs | 540 ++++++++++++++++++ .../src/commands/self_update/validation.rs | 70 ++- install.sh | 178 ++++-- npm/release/upgrade-recovery.md | 10 + scripts/ci/macos-developer-tools.sh | 120 ++++ scripts/ci/test-macos-developer-tools.sh | 110 ++++ tests/install-sh/run.sh | 186 +++--- tests/install-sh/serve.py | 83 +++ 14 files changed, 1635 insertions(+), 389 deletions(-) create mode 100644 crates/lpm-cli/src/commands/self_update/notarization.rs create mode 100755 scripts/ci/macos-developer-tools.sh create mode 100755 scripts/ci/test-macos-developer-tools.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4ed0e5423..159f089df 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -124,6 +124,9 @@ 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 unlocked gnome-keyring helper run: bash scripts/ci/test-with-unlocked-gnome-keyring.sh diff --git a/.github/workflows/release-upgrade-compatibility.yml b/.github/workflows/release-upgrade-compatibility.yml index 20e216de2..be91126a6 100644 --- a/.github/workflows/release-upgrade-compatibility.yml +++ b/.github/workflows/release-upgrade-compatibility.yml @@ -14,7 +14,12 @@ on: - 'scripts/ci/test-verify-release-signing-policy.sh' - 'install.sh' - 'tests/install-sh/**' + - 'scripts/ci/macos-developer-tools.sh' - '.github/workflows/release-upgrade-compatibility.yml' + # Apple's ticket service and the latest releases change without a commit + # here, so these checks also run daily. + schedule: + - cron: '41 9 * * *' workflow_dispatch: permissions: @@ -98,3 +103,164 @@ jobs: done export LPM_TEST_MACOS_RELEASE_ARCHIVES="$RUNNER_TEMP/v0.76.5/lpm-darwin-arm64.zip:$RUNNER_TEMP/v0.77.0-nightly.20260909.177.e3196a5/lpm-darwin-arm64.zip" cargo test --locked -p lpm-cli --bin lpm-rs signed_macos_releases_pass_validation -- --ignored --nocapture + + # Every hosted macOS runner has Xcode and the Command Line Tools, which + # LPM's users mostly don't. These checks run with neither, and with only the + # Command Line Tools, against real signed releases. + macos-without-developer-tools: + name: macOS with developer tools ${{ matrix.developer-tools }} + if: ${{ !github.event.pull_request.draft }} + strategy: + fail-fast: false + matrix: + developer-tools: [none, command-line-tools] + runs-on: macos-15 + timeout-minutes: 45 + env: + # 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 }} + # 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: ${{ runner.os }}-release-upgrade-1.99.1-${{ hashFiles('Cargo.lock') }} + restore-keys: ${{ runner.os }}-release-upgrade-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 + latest_stable=$(gh release view --repo lpm-dev/rust-client --json tagName --jq .tagName) + latest_nightly=$(gh release list --repo lpm-dev/rust-client --limit 30 --json tagName,isPrerelease \ + --jq 'map(select(.isPrerelease)) | .[0].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 lpm-darwin-arm64.zip --pattern SHA256SUMS.txt + (cd "$RUNNER_TEMP/releases/$tag" && grep ' lpm-darwin-arm64.zip$' SHA256SUMS.txt | shasum -a 256 --check) + archives="${archives:+$archives:}$RUNNER_TEMP/releases/$tag/lpm-darwin-arm64.zip" + done + { + echo "LATEST_STABLE=$latest_stable" + echo "LATEST_NIGHTLY=$latest_nightly" + echo "LPM_TEST_MACOS_RELEASE_ARCHIVES=$archives" + } >> "$GITHUB_ENV" + + - 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 + run: | + unset DEVELOPER_DIR + "$SELF_UPDATE_TESTS" --ignored --test-threads=1 signed_macos_release + + - name: Fresh install through the official installer + run: | + set -euo pipefail + unset DEVELOPER_DIR + rm -rf "$HOME/.lpm" + env PATH=/usr/bin:/bin:/usr/sbin:/sbin SHELL=/bin/zsh sh install.sh + test "$(LPM_NO_UPDATE_CHECK=1 "$HOME/.lpm/bin/lpm" --version | sed -n 1p)" = "lpm ${LATEST_STABLE#v}" + + - name: In-place upgrade of an affected install through the official installer + 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}" + "$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 'notarization-ticket validation failed' "$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 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 ${LATEST_STABLE#v}" + grep -q 'release' "$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 + env: + GITHUB_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + unset DEVELOPER_DIR + lpm="$HOME/.lpm/bin/lpm" + status=0 + "$lpm" self-update --channel nightly --refresh > "$RUNNER_TEMP/latest-self-update.log" 2>&1 || status=$? + cat "$RUNNER_TEMP/latest-self-update.log" + latest="${LATEST_STABLE#v}" + if [ "$(printf '%s\n%s\n' "$latest" "$LAST_UPDATER_NEEDING_XCODE" | sort -V | tail -n 1)" = "$LAST_UPDATER_NEEDING_XCODE" ]; then + test "$status" -ne 0 + grep -q 'notarization-ticket validation failed' "$RUNNER_TEMP/latest-self-update.log" + echo "::notice::$LATEST_STABLE still needs Xcode to update; its users recover through the installer" + else + test "$status" -eq 0 + test "$(LPM_NO_UPDATE_CHECK=1 "$lpm" --version | sed -n 1p)" = "lpm ${LATEST_NIGHTLY#v}" + fi + + - name: Self-update from this build to the latest signed releases + 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" + "$lpm" self-update --channel "$channel" --refresh + if [ "$channel" = stable ]; then expected="$LATEST_STABLE"; else expected="$LATEST_NIGHTLY"; fi + test "$(LPM_NO_UPDATE_CHECK=1 "$lpm" --version | sed -n 1p)" = "lpm ${expected#v}" + /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" 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/commands/self_update.rs b/crates/lpm-cli/src/commands/self_update.rs index c080f1410..9c8c6b7ad 100644 --- a/crates/lpm-cli/src/commands/self_update.rs +++ b/crates/lpm-cli/src/commands/self_update.rs @@ -20,6 +20,8 @@ use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; mod cargo_metadata; mod download; +#[cfg(any(target_os = "macos", test))] +mod notarization; mod probe; #[cfg(any(windows, test))] mod sandbox_helper; @@ -2377,7 +2379,9 @@ async fn run_standalone_update( let staged_bundle = stage_macos_bundle( assets.staged_binary.temporary.path(), &macos_layout.app_parent, - )?; + human_output, + ) + .await?; VersionProbe::verify_staged_path(&staged_bundle.executable, version)?; install_staged_macos_bundle(&macos_layout, staged_bundle, version)?; } @@ -2767,29 +2771,25 @@ struct StagedMacOSBundle { staging_root: tempfile::TempDir, app_bundle: PathBuf, executable: PathBuf, - notarization: ConfirmedNotarization, + /// Apple's notarization service confirmed this ticket for this code. + notarization: StapledNotarization, } -/// The code-directory hash and stapled notarization ticket of a bundle whose -/// ticket Apple's ticketing service confirmed. +/// The code-directory hash and stapled notarization ticket of a bundle. #[cfg(target_os = "macos")] #[derive(Debug, PartialEq, Eq)] -struct ConfirmedNotarization { +struct StapledNotarization { + /// The SHA-256 code-directory hash, truncated to 20 bytes, in lower-case + /// hex. cdhash: String, 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 StapledNotarization { + /// A bundle moved from one whose ticket Apple confirmed must carry the + /// same code and the same ticket, instead of Apple being asked again. + fn confirm_same_bundle(&self, installed: &StapledNotarization) -> Result<(), LpmError> { if self == installed { return Ok(()); } @@ -2801,9 +2801,10 @@ impl ConfirmedNotarization { } #[cfg(target_os = "macos")] -fn stage_macos_bundle( +async fn stage_macos_bundle( archive_path: &Path, app_parent: &Path, + human_output: bool, ) -> Result { validate_macos_bundle_zip(archive_path)?; let staging_root = tempfile::Builder::new() @@ -2811,7 +2812,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 +2822,31 @@ 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 stapled = inspect_signed_macos_app_bundle(&app_bundle)?; + notarization::confirm_stapled_ticket( + ¬arization::lookup_client()?, + notarization::TICKET_LOOKUP_URL, + &stapled.cdhash, + &stapled.ticket, + ¬arization::RETRY_DELAYS, + |delay, detail| { + if human_output { + install_ui::phase_untrusted(&format!( + "Apple's notarization service did not answer ({detail}); checking the \ + notarization ticket again in {}s", + delay.as_secs() + )); + } + }, + ) + .await?; + assess_macos_app_bundle_with_gatekeeper(&app_bundle)?; let executable = app_bundle.join(MACOS_INTERNAL_EXECUTABLE); Ok(StagedMacOSBundle { staging_root, app_bundle, executable, - notarization, + notarization: stapled, }) } @@ -2950,30 +2969,48 @@ fn validate_macos_app_inventory(app_bundle: &Path) -> Result<(), LpmError> { Ok(()) } +/// The programs macOS bundle validation runs. Each must ship with macOS: an +/// `xcrun` shim such as `/usr/bin/stapler` fails on a Mac without Xcode or the +/// Command Line Tools, and an updater that runs one can never update there. +#[cfg(target_os = "macos")] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum MacOSTool { + Codesign, + Ditto, + PlistBuddy, + Spctl, +} + +#[cfg(target_os = "macos")] +impl MacOSTool { + #[cfg(test)] + const ALL: [Self; 4] = [Self::Codesign, Self::Ditto, Self::PlistBuddy, Self::Spctl]; + + const fn path(self) -> &'static str { + match self { + Self::Codesign => "/usr/bin/codesign", + Self::Ditto => "/usr/bin/ditto", + Self::PlistBuddy => "/usr/libexec/PlistBuddy", + Self::Spctl => "/usr/sbin/spctl", + } + } +} + #[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 +3031,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,27 +3075,84 @@ 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, plus a +/// notarization ticket. Until a code directory's ticket is cached system-wide +/// the ticket can only come from the app itself, so on a Mac that hasn't seen +/// this code the check verifies the stapled ticket's Apple signature without +/// the network. 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}" + )) + }) +} + +/// Checks everything about an app bundle that needs no network: its +/// contents, its code signature and notarization requirement, its signing +/// identity, entitlements and provisioning profile. Returns its SHA-256 +/// code-directory hash and stapled ticket. #[cfg(target_os = "macos")] -fn validate_macos_app_bundle( - app_bundle: &Path, - notarization_check: NotarizationCheck<'_>, -) -> Result { +fn inspect_signed_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", )?; @@ -3122,19 +3174,25 @@ fn validate_macos_app_bundle( "macOS app has an unexpected Team ID or bundle identifier".to_string(), )); } + if detail_value("Hash type").and_then(|value| value.split_whitespace().next()) != Some("sha256") + { + return Err(LpmError::SelfUpdate( + "macOS app signature does not have a SHA-256 code directory".to_string(), + )); + } let Some(cdhash) = detail_value("CDHash").filter(|cdhash| !cdhash.is_empty()) else { return Err(LpmError::SelfUpdate( "macOS app signature has no code-directory hash".to_string(), )); }; - let notarization = ConfirmedNotarization { + let notarization = StapledNotarization { cdhash: cdhash.to_string(), 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 +3208,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,17 +3228,13 @@ fn validate_macos_app_bundle( .to_string(), )); } + Ok(notarization) +} - 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)?, - } +#[cfg(target_os = "macos")] +fn assess_macos_app_bundle_with_gatekeeper(app_bundle: &Path) -> Result<(), LpmError> { run_macos_validation_tool( - "/usr/sbin/spctl", + MacOSTool::Spctl, &[ OsStr::new("--assess"), OsStr::new("--type"), @@ -3199,7 +3244,7 @@ fn validate_macos_app_bundle( ], "macOS Gatekeeper validation", )?; - Ok(notarization) + Ok(()) } #[cfg(target_os = "macos")] @@ -3270,10 +3315,9 @@ 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 = inspect_signed_macos_app_bundle(&layout.app_bundle)?; + staged.notarization.confirm_same_bundle(&installed)?; + assess_macos_app_bundle_with_gatekeeper(&layout.app_bundle)?; 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)?; @@ -4072,9 +4116,9 @@ mod tests { } #[cfg(target_os = "macos")] - #[test] + #[tokio::test] #[ignore = "requires signed release archives in LPM_TEST_MACOS_RELEASE_ARCHIVES"] - fn signed_macos_releases_pass_validation_and_reject_removed_sealed_resources() { + async fn signed_macos_releases_pass_validation_and_reject_removed_sealed_resources() { 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::>(); @@ -4091,7 +4135,9 @@ 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, false) + .await + .unwrap_or_else(|error| panic!("{}: {error}", archive.display())); let output = std::process::Command::new(&staged.executable) .arg("--version") .output() @@ -4111,7 +4157,8 @@ mod tests { } for archive in archives { let parent = tempfile::tempdir().unwrap(); - let staged = stage_macos_bundle(&archive, parent.path()) + let staged = stage_macos_bundle(&archive, parent.path(), false) + .await .unwrap_or_else(|error| panic!("{}: {error}", archive.display())); let icon = staged.app_bundle.join("Contents/Resources/LPMCLI.icns"); let sealed = if icon.exists() { @@ -4120,16 +4167,81 @@ mod tests { staged.executable.clone() }; std::fs::remove_file(sealed).unwrap(); + assert!(inspect_signed_macos_app_bundle(&staged.app_bundle).is_err()); + } + } + + /// Before Apple's record is cached the `notarized` requirement rejects a + /// swapped ticket, and afterwards the record comparison does; either way + /// the bundle must not stage. + #[cfg(target_os = "macos")] + #[tokio::test] + #[ignore = "requires two signed release archives in LPM_TEST_MACOS_RELEASE_ARCHIVES"] + async fn signed_macos_release_carrying_another_release_s_ticket_is_not_staged() { + 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 extracted = |archive: &Path| { + let root = tempfile::tempdir().unwrap(); + let status = std::process::Command::new("/usr/bin/ditto") + .args([ + OsStr::new("-x"), + OsStr::new("-k"), + archive.as_os_str(), + root.path().as_os_str(), + ]) + .status() + .unwrap(); + assert!(status.success()); + root + }; + let donor = extracted(second); + let donor_ticket = std::fs::read( + donor + .path() + .join(MACOS_APP_NAME) + .join("Contents/CodeResources"), + ) + .unwrap(); + + for ticket in [donor_ticket, b"not a notarization ticket".to_vec()] { + let swapped = extracted(first); + let app_bundle = swapped.path().join(MACOS_APP_NAME); + std::fs::write(app_bundle.join("Contents/CodeResources"), &ticket).unwrap(); + let archive = swapped.path().join("swapped.zip"); + let status = std::process::Command::new("/usr/bin/ditto") + .args([ + OsStr::new("-c"), + OsStr::new("-k"), + OsStr::new("--keepParent"), + app_bundle.as_os_str(), + archive.as_os_str(), + ]) + .status() + .unwrap(); + assert!(status.success()); + let parent = tempfile::tempdir().unwrap(); + + let error = stage_macos_bundle(&archive, parent.path(), false) + .await + .unwrap_err() + .to_string(); + assert!( - validate_macos_app_bundle(&staged.app_bundle, NotarizationCheck::AskApple).is_err() + error.contains("not the one Apple issued") + || error.contains("code-signature and notarization validation"), + "{error}" ); } } #[cfg(target_os = "macos")] - #[test] + #[tokio::test] #[ignore = "requires signed release archives in LPM_TEST_MACOS_RELEASE_ARCHIVES"] - fn signed_macos_release_whose_ticket_changes_after_staging_is_not_installed() { + async fn signed_macos_release_whose_ticket_changes_after_staging_is_not_installed() { let archives = std::env::var_os("LPM_TEST_MACOS_RELEASE_ARCHIVES") .expect("set LPM_TEST_MACOS_RELEASE_ARCHIVES to signed release ZIP paths"); let archive = std::env::split_paths(&archives) @@ -4146,7 +4258,9 @@ mod tests { lpm_link: bin.join("lpm"), lpx_link: bin.join("lpx"), }; - let staged = stage_macos_bundle(&archive, &layout.app_parent).unwrap(); + let staged = stage_macos_bundle(&archive, &layout.app_parent, false) + .await + .unwrap(); std::fs::write( staged.app_bundle.join("Contents/CodeResources"), b"replaced notarization ticket", @@ -6837,158 +6951,33 @@ bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb lpm-linux-x64 assert_eq!(output.stdout, argument.as_bytes()); } + /// 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. #[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", - ); - assert!(result.is_err(), "validation output must be bounded"); - } + fn macos_bundle_validation_runs_only_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); - #[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); - } + for tool in MacOSTool::ALL { + assert_ne!(tool.path(), "/usr/bin/xcrun"); + assert!( + !shims.contains(&file_identity(tool.path())), + "{} is an xcrun shim, which needs Xcode or the Command Line Tools", + tool.path() + ); } - result.unwrap(); - assert!( - elapsed < Duration::from_secs(3), - "inherited pipe delayed completion: {elapsed:?}" - ); - } - - /// 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(" "); - 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(), - ), - ) - .unwrap(); - std::fs::set_permissions(&stapler, std::fs::Permissions::from_mode(0o755)).unwrap(); - stapler - } - - #[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() - } - - #[cfg(target_os = "macos")] - #[test] - fn notarization_ticket_check_outlasts_a_brief_cloudkit_outage() { - let directory = tempfile::tempdir().unwrap(); - let stapler = fake_stapler(directory.path(), &[68, 68, 0]); - - validate_notarization_ticket( - stapler.to_str().unwrap(), - Path::new("/Applications/LPM CLI.app"), - &[Duration::ZERO; 2], - ) - .unwrap(); - - assert_eq!( - stapler_runs(directory.path()), - vec!["validate /Applications/LPM CLI.app"; 3] - ); - } - - #[cfg(target_os = "macos")] - #[test] - fn notarization_ticket_check_reports_a_lasting_cloudkit_outage_in_stapler_s_words() { - let directory = tempfile::tempdir().unwrap(); - let stapler = fake_stapler(directory.path(), &[68, 68, 68, 68, 68, 68, 0]); - - 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(); - - assert!( - error.contains("CloudKit's response is inconsistent"), - "{error}" - ); - assert_eq!( - stapler_runs(directory.path()).len(), - NOTARIZATION_TICKET_RETRY_DELAYS.len() + 1 - ); - } - - #[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::>(); - - assert_eq!(install_sh_delays, NOTARIZATION_TICKET_RETRY_DELAYS); } #[cfg(target_os = "macos")] - fn fixture_notarization() -> ConfirmedNotarization { - ConfirmedNotarization { + fn fixture_notarization() -> StapledNotarization { + StapledNotarization { cdhash: "0f1e2d3c4b5a69788796a5b4c3d2e1f00f1e2d3c".to_string(), ticket: b"stapled notarization ticket".to_vec(), } @@ -7007,11 +6996,11 @@ bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb lpm-linux-x64 fn moved_bundle_with_different_code_or_ticket_is_rejected() { let confirmed = fixture_notarization(); for installed in [ - ConfirmedNotarization { + StapledNotarization { cdhash: "a1b2c3d4e5f60718293a4b5c6d7e8f9001122334".to_string(), ..fixture_notarization() }, - ConfirmedNotarization { + StapledNotarization { ticket: b"replaced notarization ticket".to_vec(), ..fixture_notarization() }, @@ -7028,22 +7017,4 @@ bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb lpm-linux-x64 ); } } - - #[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/notarization.rs b/crates/lpm-cli/src/commands/self_update/notarization.rs new file mode 100644 index 000000000..da00f0226 --- /dev/null +++ b/crates/lpm-cli/src/commands/self_update/notarization.rs @@ -0,0 +1,540 @@ +//! Confirms a macOS app's stapled notarization ticket with Apple. +//! +//! Apple's notarization service publishes the ticket it issues for each +//! notarized code directory as a record in a public CloudKit database, named +//! after the code-directory hash. `stapler validate` fetches that record and +//! compares its ticket with the one stapled to the app. This module does the +//! same over HTTPS, because `/usr/bin/stapler` and `xcrun` only run on a Mac +//! with Xcode or the Command Line Tools installed. + +use base64::Engine as _; +use lpm_common::LpmError; +use std::time::Duration; + +/// The lookup endpoint of Apple's ticket database, which `stapler` and +/// Gatekeeper's online notarization check also query. +pub(super) const TICKET_LOOKUP_URL: &str = "https://api.apple-cloudkit.com/database/1/com.apple.gk.ticket-delivery/production/public/records/lookup"; + +/// 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. +pub(super) const RETRY_DELAYS: [Duration; 5] = [ + Duration::from_secs(2), + Duration::from_secs(5), + Duration::from_secs(15), + Duration::from_secs(30), + Duration::from_secs(60), +]; + +/// A ticket record is under 4 KiB; anything far larger isn't one. +const RESPONSE_MAX_BYTES: usize = 64 * 1024; + +/// Record errors CloudKit reports for load or outages, which clear up. +const TRANSIENT_SERVER_ERRORS: [&str; 5] = [ + "THROTTLED", + "TRY_AGAIN_LATER", + "SERVICE_UNAVAILABLE", + "INTERNAL_ERROR", + "ZONE_BUSY", +]; + +/// What Apple's ticket database said about one code directory. +#[derive(Debug, PartialEq, Eq)] +enum Lookup { + /// Apple holds this ticket for the code directory. + Issued(Vec), + /// Apple holds no ticket for the code directory: it was never notarized, + /// or its ticket was revoked. + NotIssued, + /// The service answered with an error that asking again won't change. + Refused(String), + /// The service gave no usable answer, which it may give later. + Unavailable(String), +} + +/// An HTTP client for ticket lookups. A redirect is an unexpected answer, so +/// none is followed. +pub(super) fn lookup_client() -> Result { + lpm_http::client_builder() + .redirect(reqwest::redirect::Policy::none()) + .connect_timeout(Duration::from_secs(10)) + .timeout(Duration::from_secs(30)) + .build() + .map_err(|error| LpmError::Network(format!("failed to create HTTP client: {error}"))) +} + +/// Confirms that Apple's ticket database holds exactly `stapled_ticket` for +/// the code directory whose SHA-256 hash is `cdhash`. +/// +/// While the service gives no usable answer, it is asked again after each of +/// `retry_delays`, and `on_retry` hears of each wait and what the service +/// said first. A ticket that +/// differs from the stapled one, a missing or revoked ticket, and any other +/// refusal fail at once. +pub(super) async fn confirm_stapled_ticket( + client: &reqwest::Client, + lookup_url: &str, + cdhash: &str, + stapled_ticket: &[u8], + retry_delays: &[Duration], + mut on_retry: impl FnMut(Duration, &str), +) -> Result<(), LpmError> { + let record_name = record_name(cdhash)?; + let mut retry_delays = retry_delays.iter(); + loop { + match lookup(client, lookup_url, &record_name).await { + Lookup::Issued(ticket) if ticket == stapled_ticket => return Ok(()), + Lookup::Issued(_) => { + return Err(LpmError::SelfUpdate( + "the notarization ticket stapled to the macOS app is not the one Apple issued \ + for its code" + .to_string(), + )); + } + Lookup::NotIssued => { + return Err(LpmError::SelfUpdate( + "Apple has not issued a notarization ticket for the macOS app's code, or has \ + revoked it" + .to_string(), + )); + } + Lookup::Refused(detail) => { + return Err(LpmError::SelfUpdate(format!( + "Apple's notarization service refused to look up the macOS app's ticket \ + ({detail})" + ))); + } + Lookup::Unavailable(detail) => match retry_delays.next() { + Some(delay) => { + on_retry(*delay, &detail); + tokio::time::sleep(*delay).await; + } + None => { + return Err(LpmError::Network(format!( + "Apple's notarization service did not answer while checking the macOS \ + app's ticket ({detail}); try again in a few minutes" + ))); + } + }, + } + } +} + +/// The record holding the ticket for a SHA-256 code directory: `2/`, the +/// digest type (2 is SHA-256), then the hash truncated to 20 bytes. +fn record_name(cdhash: &str) -> Result { + let well_formed = cdhash.len() == 40 + && cdhash + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)); + if !well_formed { + return Err(LpmError::SelfUpdate( + "macOS app signature has a malformed code-directory hash".to_string(), + )); + } + Ok(format!("2/2/{cdhash}")) +} + +async fn lookup(client: &reqwest::Client, lookup_url: &str, record_name: &str) -> Lookup { + let request = serde_json::json!({ "records": [{ "recordName": record_name }] }); + let mut response = match client + .post(lookup_url) + .header("User-Agent", "lpm-cli") + .json(&request) + .send() + .await + { + Ok(response) => response, + Err(error) => { + return Lookup::Unavailable(lpm_http::display_error(&error.without_url()).to_string()); + } + }; + let status = response.status(); + if status == reqwest::StatusCode::TOO_MANY_REQUESTS || status.is_server_error() { + return Lookup::Unavailable(format!("HTTP {}", status.as_u16())); + } + if status != reqwest::StatusCode::OK { + return Lookup::Refused(format!("HTTP {}", status.as_u16())); + } + let mut body = Vec::with_capacity( + response + .content_length() + .map_or(0, |length| (length as usize).min(RESPONSE_MAX_BYTES)), + ); + loop { + match response.chunk().await { + Ok(Some(chunk)) if body.len() + chunk.len() <= RESPONSE_MAX_BYTES => { + body.extend_from_slice(&chunk); + } + Ok(Some(_)) => return Lookup::Unavailable("an oversized answer".to_string()), + Ok(None) => break, + Err(error) => { + return Lookup::Unavailable( + lpm_http::display_error(&error.without_url()).to_string(), + ); + } + } + } + parse_lookup(&body, record_name) +} + +#[derive(serde::Deserialize)] +struct LookupResponse { + records: Vec, +} + +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase")] +struct TicketRecord { + record_name: String, + server_error_code: Option, + #[serde(default)] + deleted: bool, + fields: Option, +} + +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase")] +struct TicketFields { + signed_ticket: Option, +} + +#[derive(serde::Deserialize)] +struct BytesField { + value: String, +} + +fn parse_lookup(body: &[u8], record_name: &str) -> Lookup { + let Ok(LookupResponse { records }) = serde_json::from_slice(body) else { + return Lookup::Unavailable("an unreadable answer".to_string()); + }; + let [record] = records.as_slice() else { + return Lookup::Unavailable("an answer about other records".to_string()); + }; + if record.record_name != record_name { + return Lookup::Unavailable("an answer about another record".to_string()); + } + if let Some(code) = &record.server_error_code { + if code == "NOT_FOUND" { + return Lookup::NotIssued; + } + let code = displayable_server_error(code); + return if TRANSIENT_SERVER_ERRORS.contains(&code) { + Lookup::Unavailable(code.to_string()) + } else { + Lookup::Refused(code.to_string()) + }; + } + if record.deleted { + return Lookup::NotIssued; + } + let Some(value) = record + .fields + .as_ref() + .and_then(|fields| fields.signed_ticket.as_ref()) + .map(|ticket| ticket.value.as_str()) + else { + return Lookup::Unavailable("an answer without a ticket".to_string()); + }; + match base64::engine::general_purpose::STANDARD.decode(value) { + Ok(ticket) if !ticket.is_empty() => Lookup::Issued(ticket), + _ => Lookup::Unavailable("an unreadable ticket".to_string()), + } +} + +/// CloudKit error codes are upper-case identifiers; anything else is shown +/// as unrecognized rather than echoed. +fn displayable_server_error(code: &str) -> &str { + let identifier = !code.is_empty() + && code.len() <= 40 + && code + .bytes() + .all(|byte| byte.is_ascii_uppercase() || byte == b'_'); + if identifier { + code + } else { + "an unrecognized error" + } +} + +#[cfg(test)] +mod tests { + use super::*; + use wiremock::matchers::{body_json, header, method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + const CDHASH: &str = "2333a682bac997f34eb811423fc9630552dc316a"; + const RECORD: &str = "2/2/2333a682bac997f34eb811423fc9630552dc316a"; + const TICKET: &[u8] = b"s8ch stapled notarization ticket"; + + fn issued(ticket: &[u8]) -> serde_json::Value { + serde_json::json!({ "records": [{ + "recordName": RECORD, + "recordType": "DeveloperIDTicket", + "fields": { "signedTicket": { + "value": base64::engine::general_purpose::STANDARD.encode(ticket), + "type": "BYTES", + }}, + "pluginFields": {}, + "recordChangeTag": "mwpb0rxw", + "deleted": false, + }]}) + } + + fn record_error(code: &str) -> serde_json::Value { + serde_json::json!({ "records": [{ + "recordName": RECORD, + "reason": "Record not found", + "serverErrorCode": code, + }]}) + } + + /// Answers the ticket lookup with `answers` in turn, the last one for + /// every later request. + async fn ticket_service(answers: Vec) -> MockServer { + let server = MockServer::start().await; + let last = answers.len() - 1; + for (index, answer) in answers.into_iter().enumerate() { + let mock = Mock::given(method("POST")) + .and(path("/lookup")) + .and(header("content-type", "application/json")) + .and(body_json( + serde_json::json!({ "records": [{ "recordName": RECORD }] }), + )) + .respond_with(answer); + if index == last { + mock.mount(&server).await; + } else { + mock.up_to_n_times(1).mount(&server).await; + } + } + server + } + + async fn confirm(server: &MockServer, retries: usize) -> (Result<(), LpmError>, Vec) { + let mut waits = Vec::new(); + let result = confirm_stapled_ticket( + &lookup_client().unwrap(), + &format!("{}/lookup", server.uri()), + CDHASH, + TICKET, + &vec![Duration::from_millis(1); retries], + |delay, _| waits.push(delay), + ) + .await; + (result, waits) + } + + async fn lookups(server: &MockServer) -> usize { + server.received_requests().await.unwrap().len() + } + + #[tokio::test] + async fn stapled_ticket_matching_apple_s_record_is_confirmed_with_one_lookup() { + let server = ticket_service(vec![ + ResponseTemplate::new(200).set_body_json(issued(TICKET)), + ]) + .await; + + let (result, waits) = confirm(&server, 5).await; + + result.unwrap(); + assert!(waits.is_empty()); + assert_eq!(lookups(&server).await, 1); + } + + #[tokio::test] + async fn ticket_check_outlasts_a_brief_outage_of_apple_s_ticket_service() { + let server = ticket_service(vec![ + ResponseTemplate::new(503), + ResponseTemplate::new(200).set_body_json(record_error("THROTTLED")), + ResponseTemplate::new(429), + ResponseTemplate::new(200).set_body_string("captive portal"), + ResponseTemplate::new(200).set_body_json(issued(TICKET)), + ]) + .await; + + let (result, waits) = confirm(&server, 5).await; + + result.unwrap(); + assert_eq!(waits.len(), 4); + assert_eq!(lookups(&server).await, 5); + } + + #[tokio::test] + async fn lasting_outage_of_apple_s_ticket_service_fails_as_a_network_error() { + let server = ticket_service(vec![ResponseTemplate::new(503)]).await; + + let (result, waits) = confirm(&server, 5).await; + + let error = result.unwrap_err(); + assert!(matches!(error, LpmError::Network(_)), "{error:?}"); + let error = error.to_string(); + assert!(error.contains("did not answer"), "{error}"); + assert!(error.contains("HTTP 503"), "{error}"); + assert_eq!(waits.len(), 5); + assert_eq!(lookups(&server).await, 6); + } + + #[tokio::test] + async fn unreachable_ticket_service_is_retried_then_reported() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let address = listener.local_addr().unwrap(); + drop(listener); + let mut waits = Vec::new(); + + let error = confirm_stapled_ticket( + &lookup_client().unwrap(), + &format!("http://{address}/lookup"), + CDHASH, + TICKET, + &[Duration::from_millis(1); 2], + |delay, _| waits.push(delay), + ) + .await + .unwrap_err(); + + assert!(matches!(error, LpmError::Network(_)), "{error:?}"); + assert_eq!(waits.len(), 2); + } + + #[tokio::test] + async fn stapled_ticket_other_than_apple_s_record_is_rejected_without_retrying() { + let server = ticket_service(vec![ + ResponseTemplate::new(200).set_body_json(issued(b"another release's ticket")), + ]) + .await; + + let (result, waits) = confirm(&server, 5).await; + + let error = result.unwrap_err().to_string(); + assert!(error.contains("not the one Apple issued"), "{error}"); + assert!(waits.is_empty()); + assert_eq!(lookups(&server).await, 1); + } + + #[tokio::test] + async fn code_apple_never_notarized_is_rejected_without_retrying() { + let server = ticket_service(vec![ + ResponseTemplate::new(200).set_body_json(record_error("NOT_FOUND")), + ]) + .await; + + let (result, waits) = confirm(&server, 5).await; + + let error = result.unwrap_err(); + assert!(matches!(error, LpmError::SelfUpdate(_)), "{error:?}"); + assert!(error.to_string().contains("has not issued"), "{error}"); + assert!(waits.is_empty()); + assert_eq!(lookups(&server).await, 1); + } + + #[tokio::test] + async fn deleted_ticket_record_is_rejected_without_retrying() { + let mut deleted = issued(TICKET); + deleted["records"][0]["deleted"] = serde_json::Value::Bool(true); + let server = ticket_service(vec![ResponseTemplate::new(200).set_body_json(deleted)]).await; + + let (result, waits) = confirm(&server, 5).await; + + assert!(result.unwrap_err().to_string().contains("revoked")); + assert!(waits.is_empty()); + } + + #[tokio::test] + async fn refused_lookup_fails_at_once_and_names_the_refusal() { + for (answer, refusal) in [ + ( + ResponseTemplate::new(200).set_body_json(record_error("ACCESS_DENIED")), + "ACCESS_DENIED", + ), + (ResponseTemplate::new(400), "HTTP 400"), + ( + ResponseTemplate::new(302).insert_header("location", "https://example.com/"), + "HTTP 302", + ), + ] { + let server = ticket_service(vec![answer]).await; + + let (result, waits) = confirm(&server, 5).await; + + let error = result.unwrap_err().to_string(); + assert!(error.contains(refusal), "{error}"); + assert!(waits.is_empty(), "{refusal} was retried"); + assert_eq!(lookups(&server).await, 1, "{refusal} was retried"); + } + } + + #[test] + fn answer_about_another_record_is_not_taken_for_this_one() { + let mut other = issued(TICKET); + other["records"][0]["recordName"] = + serde_json::Value::from("2/2/0000000000000000000000000000000000000000"); + + assert!(matches!( + parse_lookup(&serde_json::to_vec(&other).unwrap(), RECORD), + Lookup::Unavailable(_) + )); + } + + #[test] + fn unrecognized_server_error_is_not_echoed() { + let answer = serde_json::to_vec(&record_error("\u{1b}[31mbad")).unwrap(); + + assert_eq!( + parse_lookup(&answer, RECORD), + Lookup::Refused("an unrecognized error".to_string()) + ); + } + + #[test] + fn ticket_lookup_accepts_only_a_sha_256_code_directory_hash() { + assert_eq!(record_name(CDHASH).unwrap(), RECORD); + for malformed in [ + "", + "2333A682BAC997F34EB811423FC9630552DC316A", + "2333a682bac997f34eb811423fc9630552dc316a00", + "2333a682bac997f34eb811423fc9630552dc316\"", + ] { + assert!(record_name(malformed).is_err(), "{malformed:?}"); + } + } + + #[test] + fn ticket_retries_wait_out_the_same_outage_as_install_sh() { + let install_sh = std::fs::read_to_string( + std::path::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::>(); + + assert_eq!(install_sh_delays, RETRY_DELAYS); + } + + #[test] + fn ticket_lookup_queries_the_same_record_store_as_install_sh() { + let install_sh = std::fs::read_to_string( + std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../install.sh"), + ) + .unwrap(); + + assert!( + install_sh.contains(&format!( + "NOTARIZATION_TICKET_LOOKUP_URL=\"{TICKET_LOOKUP_URL}\"" + )), + "install.sh must look tickets up where self-update does" + ); + assert!(install_sh.contains("ticket_record=\"2/2/")); + } +} diff --git a/crates/lpm-cli/src/commands/self_update/validation.rs b/crates/lpm-cli/src/commands/self_update/validation.rs index a2e3f3769..e147317b0 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. Variables of the caller's, +/// such as `DEVELOPER_DIR`, would otherwise change what the system tools do. +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/install.sh b/install.sh index ec1d2f090..ec3db31e9 100755 --- a/install.sh +++ b/install.sh @@ -30,6 +30,11 @@ 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, plus a notarization +# ticket. Until a code directory's ticket is cached system-wide the ticket can +# only come from the app itself, so on a Mac that hasn't seen this code the +# check verifies the stapled ticket's Apple signature without the network. +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 @@ -226,24 +231,39 @@ 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. +MACOS_BASE64_TOOL="/usr/bin/base64" 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_PLUTIL_TOOL="/usr/bin/plutil" +MACOS_SPCTL_TOOL="/usr/sbin/spctl" 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 +# Apple publishes the ticket it issues for each notarized code directory as a +# record in a public CloudKit database, named after the code-directory hash. +# `stapler validate` compares that record with the ticket stapled to the app; +# the installer does the same with curl. +NOTARIZATION_TICKET_LOOKUP_URL="https://api.apple-cloudkit.com/database/1/com.apple.gk.ticket-delivery/production/public/records/lookup" + +if [ -n "${LPM_INSTALL_TEST_CODESIGN:-}${LPM_INSTALL_TEST_OPENSSL:-}${LPM_INSTALL_TEST_SPCTL:-}${LPM_INSTALL_TEST_TICKET_LOOKUP_URL:-}" ]; then if [ "$OS" != "Darwin" ] || \ [ -z "${LPM_INSTALL_TEST_API_URL:-}" ] || \ [ -z "${LPM_INSTALL_TEST_DOWNLOAD_BASE:-}" ]; then echo "ERROR: macOS tool overrides require both loopback test endpoints on macOS" exit 1 fi + if [ -n "${LPM_INSTALL_TEST_TICKET_LOOKUP_URL:-}" ] && ! is_loopback_http "$LPM_INSTALL_TEST_TICKET_LOOKUP_URL"; then + echo "ERROR: LPM_INSTALL_TEST_TICKET_LOOKUP_URL must point at 127.0.0.1 / localhost / [::1] over http" + exit 1 + fi MACOS_CODESIGN_TOOL="${LPM_INSTALL_TEST_CODESIGN:-$MACOS_CODESIGN_TOOL}" - MACOS_SECURITY_TOOL="${LPM_INSTALL_TEST_SECURITY:-$MACOS_SECURITY_TOOL}" + MACOS_OPENSSL_TOOL="${LPM_INSTALL_TEST_OPENSSL:-$MACOS_OPENSSL_TOOL}" MACOS_SPCTL_TOOL="${LPM_INSTALL_TEST_SPCTL:-$MACOS_SPCTL_TOOL}" - MACOS_XCRUN_TOOL="${LPM_INSTALL_TEST_XCRUN:-$MACOS_XCRUN_TOOL}" + NOTARIZATION_TICKET_LOOKUP_URL="${LPM_INSTALL_TEST_TICKET_LOOKUP_URL:-$NOTARIZATION_TICKET_LOOKUP_URL}" fi REQUESTED_VERSION="${LPM_INSTALL_VERSION:-}" @@ -652,30 +672,104 @@ 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 +# Record errors Apple's ticket service reports for load or outages. +NOTARIZATION_TICKET_TRANSIENT_ERRORS=" THROTTLED TRY_AGAIN_LATER SERVICE_UNAVAILABLE INTERNAL_ERROR ZONE_BUSY " + +notarization_ticket_field() { + "$MACOS_PLISTBUDDY_TOOL" -c "Print :records:0:$1" "$ticket_plist" 2>/dev/null +} + +# Looks up the ticket record named $ticket_record. Sets ticket_lookup to +# issued (Apple's ticket is in $ticket_issued), not-issued (no ticket, or a +# revoked one), refused (an error asking again won't change) or unavailable, +# and ticket_lookup_detail to what the service said. +lookup_notarization_ticket() { + ticket_lookup="unavailable" + ticket_lookup_detail="no answer" + rm -f "$ticket_response" "$ticket_plist" "$ticket_issued" + ticket_http_status=$(curl -sS --max-time 30 -o "$ticket_response" -w '%{http_code}' \ + -H 'Content-Type: application/json' \ + --data "{\"records\":[{\"recordName\":\"$ticket_record\"}]}" \ + "$NOTARIZATION_TICKET_LOOKUP_URL") || return 0 + case "$ticket_http_status" in + 200) ;; + 429|5[0-9][0-9]) ticket_lookup_detail="HTTP $ticket_http_status"; return 0 ;; + *) ticket_lookup="refused"; ticket_lookup_detail="HTTP $ticket_http_status"; return 0 ;; + esac + if ! "$MACOS_PLUTIL_TOOL" -convert xml1 -o "$ticket_plist" "$ticket_response" >/dev/null 2>&1; then + ticket_lookup_detail="an unreadable answer" + return 0 + fi + if "$MACOS_PLISTBUDDY_TOOL" -c 'Print :records:1' "$ticket_plist" >/dev/null 2>&1 || \ + [ "$(notarization_ticket_field recordName || true)" != "$ticket_record" ]; then + ticket_lookup_detail="an answer about another record" + return 0 + fi + ticket_server_error=$(notarization_ticket_field serverErrorCode || true) + case "$ticket_server_error" in + '') ;; + NOT_FOUND) ticket_lookup="not-issued"; return 0 ;; + *[!A-Z_]*) ticket_lookup="refused"; ticket_lookup_detail="an unrecognized error"; return 0 ;; + *) + ticket_lookup_detail="$ticket_server_error" + case "$NOTARIZATION_TICKET_TRANSIENT_ERRORS" in + *" $ticket_server_error "*) ;; + *) ticket_lookup="refused" ;; + esac + return 0 + ;; + esac + if [ "$(notarization_ticket_field deleted || true)" = "true" ]; then + ticket_lookup="not-issued" + return 0 + fi + if ! ticket_value=$(notarization_ticket_field fields:signedTicket:value); then + ticket_lookup_detail="an answer without a ticket" + return 0 + fi + if ! printf '%s' "$ticket_value" | "$MACOS_BASE64_TOOL" -D > "$ticket_issued" 2>/dev/null || \ + [ ! -s "$ticket_issued" ]; then + ticket_lookup_detail="an unreadable ticket" + return 0 + fi + ticket_lookup="issued" +} -validate_notarization_ticket() { +# Confirms that Apple's ticket database holds exactly the ticket stapled to an +# app bundle, for the code directory whose SHA-256 hash is $3. The service has +# kept failing for over 20 s at a time, so the lookups spread over about two +# minutes before giving up. +confirm_notarization_ticket() { ticket_bundle="$1" ticket_label="$2" + ticket_record="2/2/$3" + ticket_response="$STAGE_DIR/notarization-ticket.json" + ticket_plist="$STAGE_DIR/notarization-ticket.plist" + ticket_issued="$STAGE_DIR/notarization-ticket" 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 + lookup_notarization_ticket + case "$ticket_lookup" in + issued) + if cmp -s "$ticket_issued" "$ticket_bundle/Contents/CodeResources"; then + return 0 + fi + echo "ERROR: the notarization ticket stapled to $ticket_label is not the one Apple issued for its code." + return 1 + ;; + not-issued) + echo "ERROR: Apple has not issued a notarization ticket for $ticket_label, or has revoked it." + return 1 + ;; + refused) + echo "ERROR: Apple's notarization service refused to look up the ticket of $ticket_label ($ticket_lookup_detail)." + return 1 + ;; + esac 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." + echo "ERROR: Apple's notarization service did not answer while checking $ticket_label ($ticket_lookup_detail). 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..." + echo "Apple's notarization service did not answer ($ticket_lookup_detail); checking the notarization ticket again in ${ticket_retry_delay}s..." sleep "$ticket_retry_delay" done } @@ -709,7 +803,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,8 +837,8 @@ 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 @@ -754,9 +848,20 @@ validate_macos_bundle() { echo "ERROR: $app_label has an unexpected signing identity." return 1 fi + signed_hash_type=$(printf '%s\n' "$signature_details" | awk -F= '/^Hash type=/{split($2, value, " "); print value[1]}') + if [ "$signed_hash_type" != "sha256" ]; then + echo "ERROR: $app_label is not signed with a SHA-256 code directory." + return 1 + fi app_cdhash=$(printf '%s\n' "$signature_details" | awk -F= '/^CDHash=/{print $2}') - if [ -z "$app_cdhash" ]; then - echo "ERROR: $app_label has no code-directory hash." + case "$app_cdhash" in + *[!0-9a-f]*|'') + echo "ERROR: $app_label has no well-formed code-directory hash." + return 1 + ;; + esac + if [ "${#app_cdhash}" -ne 40 ]; then + echo "ERROR: $app_label has no well-formed code-directory hash." return 1 fi @@ -765,23 +870,26 @@ 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. profile_plist="$STAGE_DIR/profile.plist" - if ! "$MACOS_SECURITY_TOOL" cms -D -i "$app_profile" > "$profile_plist"; then + if ! "$MACOS_OPENSSL_TOOL" smime -verify -noverify -nosigs -inform DER -in "$app_profile" -out "$profile_plist" 2>/dev/null; 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" && \ @@ -791,7 +899,7 @@ validate_macos_bundle() { fi if [ -z "$confirmed_bundle" ]; then - validate_notarization_ticket "$app_bundle" "$app_label" || return 1 + confirm_notarization_ticket "$app_bundle" "$app_label" "$app_cdhash" || 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." diff --git a/npm/release/upgrade-recovery.md b/npm/release/upgrade-recovery.md index 7257a89c7..6e2634f83 100644 --- a/npm/release/upgrade-recovery.md +++ b/npm/release/upgrade-recovery.md @@ -17,6 +17,16 @@ 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 +``` + +The installer and later versions of `lpm self-update` check the ticket with tools every Mac ships with, so `lpm self-update` works again after this one reinstall. + ### 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-developer-tools.sh b/scripts/ci/macos-developer-tools.sh new file mode 100755 index 000000000..53d0aef03 --- /dev/null +++ b/scripts/ci/macos-developer-tools.sh @@ -0,0 +1,120 @@ +#!/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}" +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" +} + +hide() { + local mode="$1" state_dir="$2" + [ ! -e "$state_dir/moved" ] || fail "$state_dir already records hidden developer tools" + mkdir -p "$state_dir/hidden" + : >"$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 + rm -f "${TMPDIR:-/tmp}"/xcrun_db* + 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" + if env -u DEVELOPER_DIR "$STAPLER_BIN" validate "$COMMAND_LINE_TOOLS_DIR" >/dev/null 2>&1; then + fail "$STAPLER_BIN still runs, so this is not a Mac with only the Command Line Tools" + fi + 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") + $SUDO "$XCODE_SELECT_BIN" --reset || status=1 + rm -f "${TMPDIR:-/tmp}"/xcrun_db* + [ "$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-developer-tools.sh b/scripts/ci/test-macos-developer-tools.sh new file mode 100755 index 000000000..a65891206 --- /dev/null +++ b/scripts/ci/test-macos-developer-tools.sh @@ -0,0 +1,110 @@ +#!/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 + chmod +x "$work/runner/bin/"* +} + +run_helper() { + MACOS_APPLICATIONS_DIR="$work/runner/Applications" \ + MACOS_COMMAND_LINE_TOOLS_DIR="$work/runner/CommandLineTools" \ + XCODE_SELECT_BIN="$work/runner/bin/xcode-select" \ + XCRUN_BIN="$work/runner/bin/xcrun" \ + STAPLER_BIN="$work/runner/bin/stapler" \ + SUDO="" \ + TMPDIR="$work" \ + bash "$helper" "$@" +} + +apps() { + (cd "$work/runner/Applications" && ls -d -- *.app | sort | tr '\n' ' ') +} + +make_runner +if run_helper verify none >/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 +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" diff --git a/tests/install-sh/run.sh b/tests/install-sh/run.sh index 094727330..55ad25cf7 100755 --- a/tests/install-sh/run.sh +++ b/tests/install-sh/run.sh @@ -237,6 +237,11 @@ case " $* " in *" -dvvv "*) echo 'Identifier=dev.lpm.cli' >&2 echo 'TeamIdentifier=823S8YKMRW' >&2 + if [ -n "${LPM_TEST_TOOL_STATE:-}" ] && [ -e "$LPM_TEST_TOOL_STATE/sha1-code-directory" ]; then + echo 'Hash type=sha1 size=20' >&2 + else + echo 'Hash type=sha256 size=32' >&2 + fi if staged_override staged-cdhash; then echo "CDHash=$(cat "$LPM_TEST_TOOL_STATE/staged-cdhash")" >&2 else @@ -246,16 +251,20 @@ case " $* " in esac exit 0 EOF - cat > "$CLEAN_PATH_DIR/security" <<'EOF' + # Decodes a provisioning profile the way `openssl smime -out` does. + cat > "$CLEAN_PATH_DIR/openssl" <<'EOF' #!/bin/sh -cat <<'PLIST' +[ "$1 $2 $3 $4 $5 $6" = "smime -verify -noverify -nosigs -inform DER" ] || exit 99 +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" "$CLEAN_PATH_DIR/spctl" fi } @@ -267,14 +276,14 @@ run_install_sh() { install_root="$(mktemp -d)" fi test_codesign="" - test_security="" + test_openssl="" test_spctl="" - test_xcrun="" + test_ticket_lookup="" if [ "$(PATH="$CLEAN_PATH_DIR" uname -s)" = "Darwin" ]; then test_codesign="$CLEAN_PATH_DIR/codesign" - test_security="$CLEAN_PATH_DIR/security" + test_openssl="$CLEAN_PATH_DIR/openssl" test_spctl="$CLEAN_PATH_DIR/spctl" - test_xcrun="$CLEAN_PATH_DIR/xcrun" + test_ticket_lookup="http://127.0.0.1:$SERVER_PORT/ticket-lookup" fi set +e RUN_OUT="$( @@ -282,9 +291,9 @@ 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_OPENSSL="$test_openssl" \ LPM_INSTALL_TEST_SPCTL="$test_spctl" \ - LPM_INSTALL_TEST_XCRUN="$test_xcrun" \ + LPM_INSTALL_TEST_TICKET_LOOKUP_URL="$test_ticket_lookup" \ 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:-}" \ @@ -391,6 +400,32 @@ build_clean_path sh -n "$INSTALL_SH" || fail "install.sh has shell syntax errors" pass "install.sh shell syntax" +# ── Case 1b: every macOS tool the installer runs ships with 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. +if grep -v '^[[:space:]]*#' "$INSTALL_SH" | grep -Eq '(^|[^[:alnum:]_])(xcrun|stapler|xcode-select)([^[:alnum:]_]|$)'; then + fail "install.sh runs a developer tool: $(grep -n -E '(xcrun|stapler|xcode-select)' "$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" + pass "install.sh runs only macOS tools that work without Xcode or the Command Line Tools" +fi + # ── Case 2: sudo transition fails before installer activity ─── sudo_path_dir="$(mktemp -d)" sudo_home_dir="$(mktemp -d)" @@ -758,112 +793,123 @@ 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 fixture server stands in for Apple's ticket database: each lookup is + # answered with the next scripted outcome. Apple is asked about the + # downloaded bundle only; the staged copy must carry the same code and the + # same 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' + rm -f "$CLEAN_PATH_DIR/sleep" + cat > "$CLEAN_PATH_DIR/sleep" <<'EOF_SLEEP' #!/bin/sh printf '%s\n' "$*" >> "$LPM_TEST_TOOL_STATE/sleep-requests" -EOF - chmod +x "$CLEAN_PATH_DIR/xcrun" "$CLEAN_PATH_DIR/sleep" +EOF_SLEEP + chmod +x "$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' 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" + run_with_ticket_outcomes() { + printf '%s\n' "$@" > "$fdir/ticket-outcomes" + : > "$fdir/ticket-requests" : > "$tool_state/sleep-requests" 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)" + TICKET_LOOKUPS="$(grep -c '' "$fdir/ticket-requests" || true)" SLEEP_REQUESTS="$(tr '\n' ' ' < "$tool_state/sleep-requests")" } - run_with_stapler_outcomes 68 68 0 + run_with_ticket_outcomes issued + [ "$RUN_RC" -eq 0 ] || fail "a confirmed notarization ticket failed the install with exit $RUN_RC: $RUN_OUT" + [ "$TICKET_LOOKUPS" -eq 1 ] || fail "one install looked up its notarization ticket $TICKET_LOOKUPS times, expected once" + [ "$(cat "$fdir/ticket-requests")" = "2/2/0f1e2d3c4b5a69788796a5b4c3d2e1f00f1e2d3c" ] \ + || fail "the ticket lookup asked for '$(cat "$fdir/ticket-requests")' instead of the SHA-256 code directory's record" + [ -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 confirms the stapled ticket with Apple's ticket database once" + + run_with_ticket_outcomes 503 503 issued [ "$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" + || fail "a brief outage of Apple's ticket service failed the install with exit $RUN_RC: $RUN_OUT" + [ "$TICKET_LOOKUPS" -eq 3 ] || fail "a brief outage looked the ticket up $TICKET_LOOKUPS 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" + [ -L "$RUN_INSTALL_DIR/lpm" ] || fail "install after a brief outage did not link lpm" + pass "macOS install outlasts a brief outage of Apple's ticket service" - run_with_stapler_outcomes 68 68 68 68 68 0 + run_with_ticket_outcomes throttled 429 garbage wrongrecord drop issued [ "$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" + || fail "an outage of about two minutes failed the install with exit $RUN_RC: $RUN_OUT" + [ "$TICKET_LOOKUPS" -eq 6 ] || fail "an outage of about two minutes looked the ticket up $TICKET_LOOKUPS 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" + [ -L "$RUN_INSTALL_DIR/lpm" ] || fail "install after an outage of about two minutes did not link lpm" + pass "macOS install retries every answer of Apple's ticket service that may change" - 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" + run_with_ticket_outcomes 503 503 503 503 503 503 issued + [ "$RUN_RC" -ne 0 ] || fail "a lasting outage of Apple's ticket service must fail the install" + [ "$TICKET_LOOKUPS" -eq 6 ] || fail "a lasting outage looked the ticket up $TICKET_LOOKUPS 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" + || fail "a lasting 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 LPM CLI.app (HTTP 503)" \ + || fail "a lasting outage was reported as something else: $RUN_OUT" + [ ! -e "$RUN_INSTALL_DIR/lpm" ] || fail "a lasting outage must not install anything" + pass "macOS install fails closed on a lasting outage of Apple's ticket service" printf '%s' 'a1b2c3d4e5f60718293a4b5c6d7e8f9001122334' > "$tool_state/staged-cdhash" - run_with_stapler_outcomes 0 0 + run_with_ticket_outcomes issued 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" + [ "$TICKET_LOOKUPS" -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" \ || 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" : > "$tool_state/tamper-staged-ticket" - run_with_stapler_outcomes 0 0 + run_with_ticket_outcomes issued 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" + [ "$TICKET_LOOKUPS" -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" \ || 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" + for refusal in \ + "other:is not the one Apple issued for its code" \ + "notfound:Apple has not issued a notarization ticket" \ + "deleted:Apple has not issued a notarization ticket" \ + "denied:refused to look up the ticket of downloaded LPM CLI.app (ACCESS_DENIED)" \ + "400:refused to look up the ticket of downloaded LPM CLI.app (HTTP 400)" + do + outcome="${refusal%%:*}" + expected_error="${refusal#*:}" + run_with_ticket_outcomes "$outcome" issued + [ "$RUN_RC" -ne 0 ] || fail "ticket outcome '$outcome' must fail the install" + [ "$TICKET_LOOKUPS" -eq 1 ] || fail "ticket outcome '$outcome' was retried ($TICKET_LOOKUPS lookups)" + [ -z "$SLEEP_REQUESTS" ] || fail "ticket outcome '$outcome' waited '$SLEEP_REQUESTS'" + echo "$RUN_OUT" | grep -qF "$expected_error" \ + || fail "ticket outcome '$outcome' was reported as something else: $RUN_OUT" + [ ! -e "$RUN_INSTALL_DIR/lpm" ] || fail "ticket outcome '$outcome' must not install anything" + done + pass "macOS install rejects a ticket Apple didn't issue, a revoked one, and refused lookups without retrying" + + : > "$tool_state/sha1-code-directory" + run_with_ticket_outcomes issued + rm -f "$tool_state/sha1-code-directory" + [ "$RUN_RC" -ne 0 ] || fail "a bundle without a SHA-256 code directory must fail the install" + [ "$TICKET_LOOKUPS" -eq 0 ] || fail "a bundle without a SHA-256 code directory was looked up with Apple" + echo "$RUN_OUT" | grep -q "is not signed with a SHA-256 code directory" \ + || fail "a bundle without a SHA-256 code directory was reported as something else: $RUN_OUT" + pass "macOS install requires the SHA-256 code directory Apple's ticket is filed under" 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 diff --git a/tests/install-sh/serve.py b/tests/install-sh/serve.py index cb1541a2c..fbee44e6b 100755 --- a/tests/install-sh/serve.py +++ b/tests/install-sh/serve.py @@ -14,13 +14,26 @@ A fixture file named `*.STATUS` holds an HTTP status code; the URL without that suffix answers with that status and an empty body. + +POST /ticket-lookup stands in for Apple's notarization ticket database. +Each request's record name is appended to `ticket-requests`; the nth +request is answered with line n of `ticket-outcomes` (default `issued`): +`issued` returns the ticket in `ticket-issued` (default +`fixture-notarization-ticket`), `other` returns a different ticket, +`notfound`/`deleted`/`throttled`/`denied` return those record states, +`wrongrecord` answers about another record, `garbage` returns a non-JSON +page, `drop` closes the connection, and a number answers with that status. """ +import base64 import http.server +import json import os import socketserver import sys +DEFAULT_TICKET = b"fixture-notarization-ticket" + def main() -> int: if len(sys.argv) != 3: @@ -68,6 +81,76 @@ def do_GET(self) -> None: # noqa: N802 — stdlib API self.send_header("Content-Length", "0") self.end_headers() + def do_POST(self) -> None: # noqa: N802 — stdlib API + if self.path != "/ticket-lookup": + self.send_response(404) + self.send_header("Content-Length", "0") + self.end_headers() + return + length = int(self.headers.get("Content-Length", "0")) + request = json.loads(self.rfile.read(length)) + record_name = request["records"][0]["recordName"] + requests = os.path.join(fixture_dir, "ticket-requests") + with open(requests, "a", encoding="utf-8") as f: + f.write(record_name + "\n") + with open(requests, encoding="utf-8") as f: + index = len(f.read().splitlines()) - 1 + outcome = "issued" + outcomes = os.path.join(fixture_dir, "ticket-outcomes") + if os.path.isfile(outcomes): + with open(outcomes, encoding="utf-8") as f: + lines = f.read().split() + if index < len(lines): + outcome = lines[index] + if outcome == "drop": + self.close_connection = True + self.connection.shutdown(2) + return + if outcome.isdigit(): + self.send_response(int(outcome)) + self.send_header("Content-Length", "0") + self.end_headers() + return + if outcome == "garbage": + self.answer(200, b"captive portal") + return + record = {"recordName": record_name} + if outcome in ("issued", "other", "deleted"): + ticket = DEFAULT_TICKET + issued = os.path.join(fixture_dir, "ticket-issued") + if os.path.isfile(issued): + with open(issued, "rb") as f: + ticket = f.read() + if outcome == "other": + ticket = b"another-release-ticket" + record.update( + recordType="DeveloperIDTicket", + fields={ + "signedTicket": { + "value": base64.b64encode(ticket).decode("ascii"), + "type": "BYTES", + } + }, + deleted=outcome == "deleted", + ) + elif outcome == "wrongrecord": + record.update(recordName="2/2/" + "0" * 40, fields={}) + else: + codes = { + "notfound": "NOT_FOUND", + "throttled": "THROTTLED", + "denied": "ACCESS_DENIED", + } + record.update(reason="fixture", serverErrorCode=codes[outcome]) + self.answer(200, json.dumps({"records": [record]}).encode("utf-8")) + + def answer(self, status: int, body: bytes) -> None: + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + def log_message(self, fmt: str, *args: object) -> None: # noqa: N802 return From 50a241c60ffe62d7979d6326d7a89febc837280a Mon Sep 17 00:00:00 2001 From: Tolga Ergin Date: Wed, 25 Nov 2026 00:52:32 +0000 Subject: [PATCH 2/5] Hold install.sh's ticket lookup to self-update's rules, and run the gates From the council's first review round: - install.sh's lookup no longer lets ~/.curlrc decide: it refuses redirects and reads the status from the response headers, so `location` or `fail` there can't change the outcome, while its proxy settings still apply. It reads at most 64 KiB, extracts each field on its own so a JSON null elsewhere in the answer can't hide the ticket, requires every field to have its JSON type, caps an echoed error code at 40 characters, and retries HTTP 408. Character classes are spelled out, so locales that collate a-f with A-E can't widen them. Self-update now also retries 408, takes a null `deleted` as absent and reads the body through lpm_http::read_body_capped. - Test endpoints must be the exact loopback host with an all-digit port; a user-info `@` let a lookalike URL reach another host. - The fake codesign accepts only the pinned requirement, and parity tests hold the requirement, transient errors and size limit to install.sh's. New tests cover an extra record, an empty or undecodable ticket, nulls, an oversized answer, malformed fields and code-directory hashes, and an oversized or corrupt provisioning profile. A real-network test confirms Apple's record matches a release's own ticket and no other. - The developer-tools-free job moves to its own workflow, so only it runs daily. Its v0.85.0 configuration step no longer starts a background update check that held the update lock; expected versions come from where install.sh and lpm self-update look; the restore step reselects the developer directory selected before; the Command Line Tools check requires the stapler shim's own refusal. - The macOS CI build checks now run the installer harness, so its macOS cases, the no-shim check among them, gate every pull request. - Comments no longer claim `notarized` proves the stapled ticket offline: the system may answer it from its cache or Apple's service. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 5 + .../macos-without-developer-tools.yml | 203 ++++++++++++++++++ .../release-upgrade-compatibility.yml | 166 -------------- crates/lpm-cli/src/commands/self_update.rs | 133 +++++++++++- .../src/commands/self_update/notarization.rs | 151 ++++++++++--- install.sh | 124 +++++++---- npm/release/upgrade-recovery.md | 2 +- scripts/ci/macos-developer-tools.sh | 34 ++- scripts/ci/test-macos-developer-tools.sh | 28 ++- tests/install-sh/run.sh | 115 +++++++++- tests/install-sh/serve.py | 33 ++- 11 files changed, 724 insertions(+), 270 deletions(-) create mode 100644 .github/workflows/macos-without-developer-tools.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 159f089df..3f8614453 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -503,6 +503,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 Xcode or Command Line Tools. + - 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..b71044a8c --- /dev/null +++ b/.github/workflows/macos-without-developer-tools.yml @@ -0,0 +1,203 @@ +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: + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + paths: + - 'crates/lpm-cli/src/commands/self_update*' + - 'crates/lpm-cli/src/commands/self_update/**' + - 'crates/lpm-cli/src/release_lookup.rs' + - 'crates/lpm-http/**' + - 'install.sh' + - 'tests/install-sh/**' + - 'scripts/ci/macos-developer-tools.sh' + - 'scripts/ci/test-macos-developer-tools.sh' + - '.github/workflows/macos-without-developer-tools.yml' + # Apple's ticket service and 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: macOS with developer tools ${{ matrix.developer-tools }} + if: ${{ !github.event.pull_request.draft }} + strategy: + fail-fast: false + matrix: + developer-tools: [none, command-line-tools] + runs-on: macos-15 + timeout-minutes: 45 + env: + # 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: ${{ runner.os }}-release-upgrade-1.99.1-${{ hashFiles('Cargo.lock') }} + restore-keys: ${{ runner.os }}-release-upgrade-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) + updater_stable=$(curl -fsSL https://registry.npmjs.org/@lpm-registry/cli/latest | jq -er .version) + updater_nightly=$(curl -fsSL https://registry.npmjs.org/@lpm-registry/cli/nightly | jq -er .version) + 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 lpm-darwin-arm64.zip --pattern SHA256SUMS.txt + (cd "$RUNNER_TEMP/releases/$tag" && grep ' lpm-darwin-arm64.zip$' SHA256SUMS.txt | shasum -a 256 --check) + archives="${archives:+$archives:}$RUNNER_TEMP/releases/$tag/lpm-darwin-arm64.zip" + done + { + echo "INSTALLER_STABLE=${installer_stable#v}" + echo "UPDATER_STABLE=$updater_stable" + echo "UPDATER_NIGHTLY=$updater_nightly" + echo "LPM_TEST_MACOS_RELEASE_ARCHIVES=$archives" + } >> "$GITHUB_ENV" + + - 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 + run: | + unset DEVELOPER_DIR + "$SELF_UPDATE_TESTS" --ignored --test-threads=1 signed_macos_release + + - name: Fresh install through the official installer + run: | + set -euo pipefail + unset DEVELOPER_DIR + rm -rf "$HOME/.lpm" + env PATH=/usr/bin:/bin:/usr/sbin:/sbin SHELL=/bin/zsh 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 + 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" + # The version is named so the job asks GitHub's API for the latest + # release once, in the fresh install, within its unauthenticated limit. + 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 -qx 'minimum-release-age-secs = 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 + env: + GITHUB_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + unset DEVELOPER_DIR + lpm="$HOME/.lpm/bin/lpm" + status=0 + "$lpm" self-update --channel nightly --refresh > "$RUNNER_TEMP/latest-self-update.log" 2>&1 || status=$? + cat "$RUNNER_TEMP/latest-self-update.log" + 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.log" + echo "::notice::$INSTALLER_STABLE still needs Xcode to update; its users recover through the installer" + else + test "$status" -eq 0 + test "$(LPM_NO_UPDATE_CHECK=1 "$lpm" --version | sed -n 1p)" = "lpm $UPDATER_NIGHTLY" + fi + + - name: Self-update from this build to the latest signed releases + 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" + "$lpm" self-update --channel "$channel" --refresh + if [ "$channel" = stable ]; then expected="$UPDATER_STABLE"; else expected="$UPDATER_NIGHTLY"; fi + test "$(LPM_NO_UPDATE_CHECK=1 "$lpm" --version | sed -n 1p)" = "lpm $expected" + /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" diff --git a/.github/workflows/release-upgrade-compatibility.yml b/.github/workflows/release-upgrade-compatibility.yml index be91126a6..20e216de2 100644 --- a/.github/workflows/release-upgrade-compatibility.yml +++ b/.github/workflows/release-upgrade-compatibility.yml @@ -14,12 +14,7 @@ on: - 'scripts/ci/test-verify-release-signing-policy.sh' - 'install.sh' - 'tests/install-sh/**' - - 'scripts/ci/macos-developer-tools.sh' - '.github/workflows/release-upgrade-compatibility.yml' - # Apple's ticket service and the latest releases change without a commit - # here, so these checks also run daily. - schedule: - - cron: '41 9 * * *' workflow_dispatch: permissions: @@ -103,164 +98,3 @@ jobs: done export LPM_TEST_MACOS_RELEASE_ARCHIVES="$RUNNER_TEMP/v0.76.5/lpm-darwin-arm64.zip:$RUNNER_TEMP/v0.77.0-nightly.20260909.177.e3196a5/lpm-darwin-arm64.zip" cargo test --locked -p lpm-cli --bin lpm-rs signed_macos_releases_pass_validation -- --ignored --nocapture - - # Every hosted macOS runner has Xcode and the Command Line Tools, which - # LPM's users mostly don't. These checks run with neither, and with only the - # Command Line Tools, against real signed releases. - macos-without-developer-tools: - name: macOS with developer tools ${{ matrix.developer-tools }} - if: ${{ !github.event.pull_request.draft }} - strategy: - fail-fast: false - matrix: - developer-tools: [none, command-line-tools] - runs-on: macos-15 - timeout-minutes: 45 - env: - # 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 }} - # 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: ${{ runner.os }}-release-upgrade-1.99.1-${{ hashFiles('Cargo.lock') }} - restore-keys: ${{ runner.os }}-release-upgrade-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 - latest_stable=$(gh release view --repo lpm-dev/rust-client --json tagName --jq .tagName) - latest_nightly=$(gh release list --repo lpm-dev/rust-client --limit 30 --json tagName,isPrerelease \ - --jq 'map(select(.isPrerelease)) | .[0].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 lpm-darwin-arm64.zip --pattern SHA256SUMS.txt - (cd "$RUNNER_TEMP/releases/$tag" && grep ' lpm-darwin-arm64.zip$' SHA256SUMS.txt | shasum -a 256 --check) - archives="${archives:+$archives:}$RUNNER_TEMP/releases/$tag/lpm-darwin-arm64.zip" - done - { - echo "LATEST_STABLE=$latest_stable" - echo "LATEST_NIGHTLY=$latest_nightly" - echo "LPM_TEST_MACOS_RELEASE_ARCHIVES=$archives" - } >> "$GITHUB_ENV" - - - 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 - run: | - unset DEVELOPER_DIR - "$SELF_UPDATE_TESTS" --ignored --test-threads=1 signed_macos_release - - - name: Fresh install through the official installer - run: | - set -euo pipefail - unset DEVELOPER_DIR - rm -rf "$HOME/.lpm" - env PATH=/usr/bin:/bin:/usr/sbin:/sbin SHELL=/bin/zsh sh install.sh - test "$(LPM_NO_UPDATE_CHECK=1 "$HOME/.lpm/bin/lpm" --version | sed -n 1p)" = "lpm ${LATEST_STABLE#v}" - - - name: In-place upgrade of an affected install through the official installer - 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}" - "$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 'notarization-ticket validation failed' "$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 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 ${LATEST_STABLE#v}" - grep -q 'release' "$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 - env: - GITHUB_TOKEN: ${{ github.token }} - run: | - set -euo pipefail - unset DEVELOPER_DIR - lpm="$HOME/.lpm/bin/lpm" - status=0 - "$lpm" self-update --channel nightly --refresh > "$RUNNER_TEMP/latest-self-update.log" 2>&1 || status=$? - cat "$RUNNER_TEMP/latest-self-update.log" - latest="${LATEST_STABLE#v}" - if [ "$(printf '%s\n%s\n' "$latest" "$LAST_UPDATER_NEEDING_XCODE" | sort -V | tail -n 1)" = "$LAST_UPDATER_NEEDING_XCODE" ]; then - test "$status" -ne 0 - grep -q 'notarization-ticket validation failed' "$RUNNER_TEMP/latest-self-update.log" - echo "::notice::$LATEST_STABLE still needs Xcode to update; its users recover through the installer" - else - test "$status" -eq 0 - test "$(LPM_NO_UPDATE_CHECK=1 "$lpm" --version | sed -n 1p)" = "lpm ${LATEST_NIGHTLY#v}" - fi - - - name: Self-update from this build to the latest signed releases - 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" - "$lpm" self-update --channel "$channel" --refresh - if [ "$channel" = stable ]; then expected="$LATEST_STABLE"; else expected="$LATEST_NIGHTLY"; fi - test "$(LPM_NO_UPDATE_CHECK=1 "$lpm" --version | sed -n 1p)" = "lpm ${expected#v}" - /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" diff --git a/crates/lpm-cli/src/commands/self_update.rs b/crates/lpm-cli/src/commands/self_update.rs index 9c8c6b7ad..af1a064eb 100644 --- a/crates/lpm-cli/src/commands/self_update.rs +++ b/crates/lpm-cli/src/commands/self_update.rs @@ -2984,7 +2984,13 @@ enum MacOSTool { #[cfg(target_os = "macos")] impl MacOSTool { #[cfg(test)] - const ALL: [Self; 4] = [Self::Codesign, Self::Ditto, Self::PlistBuddy, Self::Spctl]; + const ALL: [Self; 4] = { + // A new tool must be listed here, or this match stops compiling. + match Self::Codesign { + Self::Codesign | Self::Ditto | Self::PlistBuddy | Self::Spctl => {} + } + [Self::Codesign, Self::Ditto, Self::PlistBuddy, Self::Spctl] + }; const fn path(self) -> &'static str { match self { @@ -3076,11 +3082,11 @@ 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, plus a -/// notarization ticket. Until a code directory's ticket is cached system-wide -/// the ticket can only come from the app itself, so on a Mac that hasn't seen -/// this code the check verifies the stapled ticket's Apple signature without -/// the network. The leading `=` marks inline requirement text. +/// Application signature of LPM's team over its bundle identifier, and code +/// Apple notarized. The system confirms `notarized` from the stapled ticket, +/// its ticket cache or Apple's service, so only the ticket-record comparison +/// proves which ticket the app carries. The leading `=` marks inline +/// requirement text. #[cfg(target_os = "macos")] fn macos_code_requirement() -> String { format!( @@ -3157,7 +3163,7 @@ fn inspect_signed_macos_app_bundle(app_bundle: &Path) -> Result>(); + let [first, second, ..] = archives.as_slice() else { + panic!("LPM_TEST_MACOS_RELEASE_ARCHIVES must name two signed release archives"); + }; + let mut signed = Vec::new(); + for archive in [first, second] { + let parent = tempfile::tempdir().unwrap(); + let staged = stage_macos_bundle(archive, parent.path(), false) + .await + .unwrap_or_else(|error| panic!("{}: {error}", archive.display())); + signed.push(staged.notarization); + } + async fn confirm(cdhash: &str, ticket: &[u8]) -> Result<(), LpmError> { + notarization::confirm_stapled_ticket( + ¬arization::lookup_client()?, + notarization::TICKET_LOOKUP_URL, + cdhash, + ticket, + ¬arization::RETRY_DELAYS, + |_, _| {}, + ) + .await + } + + confirm(&signed[0].cdhash, &signed[0].ticket).await.unwrap(); + for ticket in [signed[1].ticket.as_slice(), b"not a notarization ticket"] { + let error = confirm(&signed[0].cdhash, ticket) + .await + .unwrap_err() + .to_string(); + assert!(error.contains("not the one Apple issued"), "{error}"); + } + } + + /// Depending on what the system already knows of the code, the `notarized` + /// requirement or the ticket-record comparison rejects a swapped ticket; + /// either way the bundle must not stage. #[cfg(target_os = "macos")] #[tokio::test] #[ignore = "requires two signed release archives in LPM_TEST_MACOS_RELEASE_ARCHIVES"] @@ -6951,6 +7000,70 @@ bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb lpm-linux-x64 assert_eq!(output.stdout, argument.as_bytes()); } + #[cfg(target_os = "macos")] + #[test] + 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 install_sh_requirement = install_sh + .lines() + .find_map(|line| line.strip_prefix("MACOS_CODE_REQUIREMENT=\"")) + .and_then(|value| value.strip_suffix('"')) + .expect("install.sh pins a code requirement") + .replace("\\\"", "\"") + .replace("$EXPECTED_BUNDLE_ID", MACOS_EXPECTED_BUNDLE_ID) + .replace("$EXPECTED_TEAM_ID", MACOS_EXPECTED_TEAM_ID); + + assert_eq!( + format!("={install_sh_requirement}"), + macos_code_requirement() + ); + } + + /// `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 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) + ); + } + + #[cfg(target_os = "macos")] + #[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( + &oversized, + vec![0_u8; MACOS_PROVISIONING_PROFILE_MAX_BYTES as usize + 1], + ) + .unwrap(); + 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. diff --git a/crates/lpm-cli/src/commands/self_update/notarization.rs b/crates/lpm-cli/src/commands/self_update/notarization.rs index da00f0226..8a14465b9 100644 --- a/crates/lpm-cli/src/commands/self_update/notarization.rs +++ b/crates/lpm-cli/src/commands/self_update/notarization.rs @@ -67,9 +67,8 @@ pub(super) fn lookup_client() -> Result { /// /// While the service gives no usable answer, it is asked again after each of /// `retry_delays`, and `on_retry` hears of each wait and what the service -/// said first. A ticket that -/// differs from the stapled one, a missing or revoked ticket, and any other -/// refusal fail at once. +/// said first. A ticket that differs from the stapled one, a missing or +/// revoked ticket, and any other refusal fail at once. pub(super) async fn confirm_stapled_ticket( client: &reqwest::Client, lookup_url: &str, @@ -136,7 +135,7 @@ fn record_name(cdhash: &str) -> Result { async fn lookup(client: &reqwest::Client, lookup_url: &str, record_name: &str) -> Lookup { let request = serde_json::json!({ "records": [{ "recordName": record_name }] }); - let mut response = match client + let response = match client .post(lookup_url) .header("User-Agent", "lpm-cli") .json(&request) @@ -149,32 +148,22 @@ async fn lookup(client: &reqwest::Client, lookup_url: &str, record_name: &str) - } }; let status = response.status(); - if status == reqwest::StatusCode::TOO_MANY_REQUESTS || status.is_server_error() { + if status == reqwest::StatusCode::REQUEST_TIMEOUT + || status == reqwest::StatusCode::TOO_MANY_REQUESTS + || status.is_server_error() + { return Lookup::Unavailable(format!("HTTP {}", status.as_u16())); } if status != reqwest::StatusCode::OK { return Lookup::Refused(format!("HTTP {}", status.as_u16())); } - let mut body = Vec::with_capacity( - response - .content_length() - .map_or(0, |length| (length as usize).min(RESPONSE_MAX_BYTES)), - ); - loop { - match response.chunk().await { - Ok(Some(chunk)) if body.len() + chunk.len() <= RESPONSE_MAX_BYTES => { - body.extend_from_slice(&chunk); - } - Ok(Some(_)) => return Lookup::Unavailable("an oversized answer".to_string()), - Ok(None) => break, - Err(error) => { - return Lookup::Unavailable( - lpm_http::display_error(&error.without_url()).to_string(), - ); - } + match lpm_http::read_body_capped(response, RESPONSE_MAX_BYTES).await { + Ok(body) => parse_lookup(&body, record_name), + Err(lpm_http::ResponseBodyError::Read(error)) => { + Lookup::Unavailable(lpm_http::display_error(&error.without_url()).to_string()) } + Err(_) => Lookup::Unavailable("an oversized answer".to_string()), } - parse_lookup(&body, record_name) } #[derive(serde::Deserialize)] @@ -187,8 +176,7 @@ struct LookupResponse { struct TicketRecord { record_name: String, server_error_code: Option, - #[serde(default)] - deleted: bool, + deleted: Option, fields: Option, } @@ -208,7 +196,7 @@ fn parse_lookup(body: &[u8], record_name: &str) -> Lookup { return Lookup::Unavailable("an unreadable answer".to_string()); }; let [record] = records.as_slice() else { - return Lookup::Unavailable("an answer about other records".to_string()); + return Lookup::Unavailable("an answer about another record".to_string()); }; if record.record_name != record_name { return Lookup::Unavailable("an answer about another record".to_string()); @@ -224,7 +212,7 @@ fn parse_lookup(body: &[u8], record_name: &str) -> Lookup { Lookup::Refused(code.to_string()) }; } - if record.deleted { + if record.deleted == Some(true) { return Lookup::NotIssued; } let Some(value) = record @@ -348,16 +336,18 @@ mod tests { ResponseTemplate::new(503), ResponseTemplate::new(200).set_body_json(record_error("THROTTLED")), ResponseTemplate::new(429), + ResponseTemplate::new(408), ResponseTemplate::new(200).set_body_string("captive portal"), + ResponseTemplate::new(200).set_body_bytes(vec![b' '; RESPONSE_MAX_BYTES + 1]), ResponseTemplate::new(200).set_body_json(issued(TICKET)), ]) .await; - let (result, waits) = confirm(&server, 5).await; + let (result, waits) = confirm(&server, 6).await; result.unwrap(); - assert_eq!(waits.len(), 4); - assert_eq!(lookups(&server).await, 5); + assert_eq!(waits.len(), 6); + assert_eq!(lookups(&server).await, 7); } #[tokio::test] @@ -476,6 +466,80 @@ mod tests { )); } + /// install.sh's harness feeds the same malformed records to its parser. + #[test] + fn malformed_record_fields_are_classified_as_install_sh_classifies_them() { + let mut deleted_string = issued(TICKET); + deleted_string["records"][0]["deleted"] = serde_json::Value::from("yes"); + let mut numeric_error = record_error("NOT_FOUND"); + numeric_error["records"][0]["serverErrorCode"] = serde_json::Value::from(5); + let mut numeric_ticket = issued(TICKET); + numeric_ticket["records"][0]["fields"]["signedTicket"]["value"] = + serde_json::Value::from(5); + + for answer in [deleted_string, numeric_error, numeric_ticket] { + assert_eq!( + parse_lookup(&serde_json::to_vec(&answer).unwrap(), RECORD), + Lookup::Unavailable("an unreadable answer".to_string()), + "{answer}" + ); + } + assert_eq!( + parse_lookup(&serde_json::to_vec(&record_error("")).unwrap(), RECORD), + Lookup::Refused("an unrecognized error".to_string()) + ); + } + + #[test] + fn answers_that_name_no_single_ticket_are_not_taken_as_one() { + let mut two_records = issued(TICKET); + let record = two_records["records"][0].clone(); + two_records["records"].as_array_mut().unwrap().push(record); + let mut empty_ticket = issued(b""); + empty_ticket["records"][0]["fields"]["signedTicket"]["value"] = serde_json::Value::from(""); + let mut undecodable_ticket = issued(TICKET); + undecodable_ticket["records"][0]["fields"]["signedTicket"]["value"] = + serde_json::Value::from("not base64!"); + + for (answer, detail) in [ + ( + serde_json::json!({ "records": [] }), + "an answer about another record", + ), + (two_records, "an answer about another record"), + (empty_ticket, "an unreadable ticket"), + (undecodable_ticket, "an unreadable ticket"), + ] { + assert_eq!( + parse_lookup(&serde_json::to_vec(&answer).unwrap(), RECORD), + Lookup::Unavailable(detail.to_string()), + "{answer}" + ); + } + } + + #[test] + fn null_fields_apple_may_add_do_not_hide_the_ticket() { + let mut answer = issued(TICKET); + answer["records"][0]["deleted"] = serde_json::Value::Null; + answer["records"][0]["zoneID"] = serde_json::Value::Null; + + assert_eq!( + parse_lookup(&serde_json::to_vec(&answer).unwrap(), RECORD), + Lookup::Issued(TICKET.to_vec()) + ); + } + + #[test] + fn overlong_server_error_is_not_echoed() { + let answer = serde_json::to_vec(&record_error(&"A".repeat(41))).unwrap(); + + assert_eq!( + parse_lookup(&answer, RECORD), + Lookup::Refused("an unrecognized error".to_string()) + ); + } + #[test] fn unrecognized_server_error_is_not_echoed() { let answer = serde_json::to_vec(&record_error("\u{1b}[31mbad")).unwrap(); @@ -522,6 +586,33 @@ mod tests { assert_eq!(install_sh_delays, RETRY_DELAYS); } + #[test] + fn ticket_lookup_classifies_answers_by_the_same_limits_as_install_sh() { + let install_sh = std::fs::read_to_string( + std::path::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}="))) + .unwrap_or_else(|| panic!("install.sh sets {name}")) + .trim_matches('"') + .to_string() + }; + + assert_eq!( + assignment("NOTARIZATION_TICKET_TRANSIENT_ERRORS") + .split_whitespace() + .collect::>(), + TRANSIENT_SERVER_ERRORS + ); + assert_eq!( + assignment("NOTARIZATION_TICKET_RESPONSE_MAX_BYTES"), + RESPONSE_MAX_BYTES.to_string() + ); + } + #[test] fn ticket_lookup_queries_the_same_record_store_as_install_sh() { let install_sh = std::fs::read_to_string( diff --git a/install.sh b/install.sh index ec3db31e9..60b7295ac 100755 --- a/install.sh +++ b/install.sh @@ -30,10 +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, plus a notarization -# ticket. Until a code directory's ticket is cached system-wide the ticket can -# only come from the app itself, so on a Mac that hasn't seen this code the -# check verifies the stapled ticket's Apple signature without the network. +# A Developer ID Application signature of LPM's team, and code Apple +# notarized. The system confirms `notarized` from the stapled ticket, its +# ticket cache or Apple's service, so only the ticket-record comparison below +# proves which ticket the app carries. 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" @@ -202,17 +202,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 @@ -674,43 +679,72 @@ require_reported_version() { # Record errors Apple's ticket service reports for load or outages. NOTARIZATION_TICKET_TRANSIENT_ERRORS=" THROTTLED TRY_AGAIN_LATER SERVICE_UNAVAILABLE INTERNAL_ERROR ZONE_BUSY " +# A ticket record is under 4 KiB; anything far larger isn't one. +NOTARIZATION_TICKET_RESPONSE_MAX_BYTES=65536 + +# Prints the lookup answer's value at the plist key path $1 as a one-value +# XML plist. Each field is extracted on its own, so a JSON null elsewhere in +# the answer, which a plist can't hold, doesn't hide the ones the check reads. +notarization_ticket_extract() { + "$MACOS_PLUTIL_TOOL" -extract "$1" xml1 -o - "$ticket_response" 2>/dev/null +} -notarization_ticket_field() { - "$MACOS_PLISTBUDDY_TOOL" -c "Print :records:0:$1" "$ticket_plist" 2>/dev/null +# Prints the string at key path $1. Returns 1 when the answer has no such +# value and 2 when it isn't a string. +notarization_ticket_string() { + ticket_field_xml=$(notarization_ticket_extract "$1") || return 1 + case "$ticket_field_xml" in + *""*) return 0 ;; + *""*) ;; + *) return 2 ;; + esac + printf '%s\n' "$ticket_field_xml" | sed -n 's:.*\(.*\).*:\1:p' } # Looks up the ticket record named $ticket_record. Sets ticket_lookup to # issued (Apple's ticket is in $ticket_issued), not-issued (no ticket, or a # revoked one), refused (an error asking again won't change) or unavailable, -# and ticket_lookup_detail to what the service said. +# and ticket_lookup_detail to what the service said. The user's ~/.curlrc +# still applies, for its proxy settings, so redirects are refused and the +# status is read from the response headers rather than curl's exit status. lookup_notarization_ticket() { ticket_lookup="unavailable" ticket_lookup_detail="no answer" - rm -f "$ticket_response" "$ticket_plist" "$ticket_issued" - ticket_http_status=$(curl -sS --max-time 30 -o "$ticket_response" -w '%{http_code}' \ + rm -f "$ticket_response" "$ticket_headers" "$ticket_issued" + curl -sS --max-time 30 --max-redirs 0 -D "$ticket_headers" -o - \ -H 'Content-Type: application/json' \ --data "{\"records\":[{\"recordName\":\"$ticket_record\"}]}" \ - "$NOTARIZATION_TICKET_LOOKUP_URL") || return 0 + "$NOTARIZATION_TICKET_LOOKUP_URL" | head -c "$((NOTARIZATION_TICKET_RESPONSE_MAX_BYTES + 1))" > "$ticket_response" || true + ticket_http_status=$(awk '/^HTTP\//{status=$2} END{print status}' "$ticket_headers" 2>/dev/null || true) case "$ticket_http_status" in 200) ;; - 429|5[0-9][0-9]) ticket_lookup_detail="HTTP $ticket_http_status"; return 0 ;; + '') return 0 ;; + 408|429|5[0-9][0-9]) ticket_lookup_detail="HTTP $ticket_http_status"; return 0 ;; *) ticket_lookup="refused"; ticket_lookup_detail="HTTP $ticket_http_status"; return 0 ;; esac - if ! "$MACOS_PLUTIL_TOOL" -convert xml1 -o "$ticket_plist" "$ticket_response" >/dev/null 2>&1; then - ticket_lookup_detail="an unreadable answer" + if [ "$(wc -c < "$ticket_response")" -gt "$NOTARIZATION_TICKET_RESPONSE_MAX_BYTES" ]; then + ticket_lookup_detail="an oversized answer" return 0 fi - if "$MACOS_PLISTBUDDY_TOOL" -c 'Print :records:1' "$ticket_plist" >/dev/null 2>&1 || \ - [ "$(notarization_ticket_field recordName || true)" != "$ticket_record" ]; then + if notarization_ticket_extract records.1 >/dev/null || \ + ! ticket_answered_record=$(notarization_ticket_string records.0.recordName) || \ + [ "$ticket_answered_record" != "$ticket_record" ]; then ticket_lookup_detail="an answer about another record" return 0 fi - ticket_server_error=$(notarization_ticket_field serverErrorCode || true) - case "$ticket_server_error" in - '') ;; - NOT_FOUND) ticket_lookup="not-issued"; return 0 ;; - *[!A-Z_]*) ticket_lookup="refused"; ticket_lookup_detail="an unrecognized error"; return 0 ;; - *) + ticket_field_status=0 + ticket_server_error=$(notarization_ticket_string records.0.serverErrorCode) || ticket_field_status=$? + case "$ticket_field_status" in + 0) + case "$ticket_server_error" in + NOT_FOUND) ticket_lookup="not-issued"; return 0 ;; + ''|*[!ABCDEFGHIJKLMNOPQRSTUVWXYZ_]*) ticket_server_error="" ;; + esac + if [ -z "$ticket_server_error" ] || [ "${#ticket_server_error}" -gt 40 ]; then + ticket_lookup="refused" + ticket_lookup_detail="an unrecognized error" + return 0 + fi ticket_lookup_detail="$ticket_server_error" case "$NOTARIZATION_TICKET_TRANSIENT_ERRORS" in *" $ticket_server_error "*) ;; @@ -718,15 +752,21 @@ lookup_notarization_ticket() { esac return 0 ;; + 2) ticket_lookup_detail="an unreadable answer"; return 0 ;; esac - if [ "$(notarization_ticket_field deleted || true)" = "true" ]; then - ticket_lookup="not-issued" - return 0 - fi - if ! ticket_value=$(notarization_ticket_field fields:signedTicket:value); then - ticket_lookup_detail="an answer without a ticket" - return 0 + if ticket_deleted_xml=$(notarization_ticket_extract records.0.deleted); then + case "$ticket_deleted_xml" in + *""*) ;; + *""*) ticket_lookup="not-issued"; return 0 ;; + *) ticket_lookup_detail="an unreadable answer"; return 0 ;; + esac fi + ticket_field_status=0 + ticket_value=$(notarization_ticket_string records.0.fields.signedTicket.value) || ticket_field_status=$? + case "$ticket_field_status" in + 1) ticket_lookup_detail="an answer without a ticket"; return 0 ;; + 2) ticket_lookup_detail="an unreadable answer"; return 0 ;; + esac if ! printf '%s' "$ticket_value" | "$MACOS_BASE64_TOOL" -D > "$ticket_issued" 2>/dev/null || \ [ ! -s "$ticket_issued" ]; then ticket_lookup_detail="an unreadable ticket" @@ -744,7 +784,7 @@ confirm_notarization_ticket() { ticket_label="$2" ticket_record="2/2/$3" ticket_response="$STAGE_DIR/notarization-ticket.json" - ticket_plist="$STAGE_DIR/notarization-ticket.plist" + ticket_headers="$STAGE_DIR/notarization-ticket.headers" ticket_issued="$STAGE_DIR/notarization-ticket" for ticket_retry_delay in 2 5 15 30 60 ""; do lookup_notarization_ticket @@ -842,20 +882,20 @@ validate_macos_bundle() { 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 - signed_hash_type=$(printf '%s\n' "$signature_details" | awk -F= '/^Hash type=/{split($2, value, " "); print value[1]}') + signed_hash_type=$(printf '%s\n' "$signature_details" | sed -n 's/^Hash type=\([^ ]*\).*/\1/p') if [ "$signed_hash_type" != "sha256" ]; then echo "ERROR: $app_label is not signed with a SHA-256 code directory." 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') case "$app_cdhash" in - *[!0-9a-f]*|'') + *[!0123456789abcdef]*|'') echo "ERROR: $app_label has no well-formed code-directory hash." return 1 ;; diff --git a/npm/release/upgrade-recovery.md b/npm/release/upgrade-recovery.md index 6e2634f83..094c51555 100644 --- a/npm/release/upgrade-recovery.md +++ b/npm/release/upgrade-recovery.md @@ -25,7 +25,7 @@ Later versions accept both signing identities, so `lpm self-update` works again curl -fsSL https://cli.lpm.dev/install | sh ``` -The installer and later versions of `lpm self-update` check the ticket with tools every Mac ships with, so `lpm self-update` works again after this one reinstall. +The installer checks the ticket with tools every Mac ships with, and so does `lpm self-update` from this release on. The reinstall installs this release or a later one, so later updates work through `lpm self-update` again. ### macOS standalone upgrades from 0.76.5 diff --git a/scripts/ci/macos-developer-tools.sh b/scripts/ci/macos-developer-tools.sh index 53d0aef03..62795698a 100755 --- a/scripts/ci/macos-developer-tools.sh +++ b/scripts/ci/macos-developer-tools.sh @@ -10,6 +10,9 @@ COMMAND_LINE_TOOLS_DIR="${MACOS_COMMAND_LINE_TOOLS_DIR:-/Library/Developer/Comma XCODE_SELECT_BIN="${XCODE_SELECT_BIN:-/usr/bin/xcode-select}" XCRUN_BIN="${XCRUN_BIN:-/usr/bin/xcrun}" STAPLER_BIN="${STAPLER_BIN:-/usr/bin/stapler}" +# xcrun caches where tools are in TMPDIR and in the per-user temporary +# directory, which differ when TMPDIR is overridden. +XCRUN_CACHE_DIRS="${XCRUN_CACHE_DIRS:-${TMPDIR:-/tmp} $(getconf DARWIN_USER_TEMP_DIR 2>/dev/null || true)}" SUDO="${SUDO-sudo}" usage() { @@ -43,10 +46,18 @@ hide_path() { printf '%s\t%s\n' "$path" "$hidden" >>"$state_dir/moved" } +clear_xcrun_cache() { + local directory + for directory in $XCRUN_CACHE_DIRS; do + rm -f "$directory"/xcrun_db* + 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 @@ -61,7 +72,7 @@ hide() { [ -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 - rm -f "${TMPDIR:-/tmp}"/xcrun_db* + clear_xcrun_cache verify "$mode" } @@ -79,9 +90,14 @@ verify() { else selected=$(env -u DEVELOPER_DIR "$XCODE_SELECT_BIN" -p) [ "$selected" = "$COMMAND_LINE_TOOLS_DIR" ] || fail "the selected developer directory is $selected" - if env -u DEVELOPER_DIR "$STAPLER_BIN" validate "$COMMAND_LINE_TOOLS_DIR" >/dev/null 2>&1; then - fail "$STAPLER_BIN still runs, so this is not a Mac with only the Command Line Tools" - fi + # 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" } @@ -93,8 +109,14 @@ restore() { 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") - $SUDO "$XCODE_SELECT_BIN" --reset || status=1 - rm -f "${TMPDIR:-/tmp}"/xcrun_db* + 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" } diff --git a/scripts/ci/test-macos-developer-tools.sh b/scripts/ci/test-macos-developer-tools.sh index a65891206..025f29b8e 100755 --- a/scripts/ci/test-macos-developer-tools.sh +++ b/scripts/ci/test-macos-developer-tools.sh @@ -44,11 +44,18 @@ selected=\$(cat "$work/runner/selected") [ -n "\$selected" ] && [ -d "\$selected" ] || exit 1 echo "\$selected/usr/bin/\$2" EOF + # Like /usr/bin/stapler: it refuses to run without Xcode selected, unless + # working-stapler exists, when it runs and rejects an unstapled bundle. cat >"$work/runner/bin/stapler" <&2; exit 1 ;; +*) echo "xcode-select: error: tool 'stapler' requires Xcode, but active developer directory '\$(cat "$work/runner/selected")' is a command line tools instance" >&2; exit 1 ;; esac EOF chmod +x "$work/runner/bin/"* @@ -60,6 +67,7 @@ run_helper() { XCODE_SELECT_BIN="$work/runner/bin/xcode-select" \ XCRUN_BIN="$work/runner/bin/xcrun" \ STAPLER_BIN="$work/runner/bin/stapler" \ + XCRUN_CACHE_DIRS="$work" \ SUDO="" \ TMPDIR="$work" \ bash "$helper" "$@" @@ -96,6 +104,14 @@ 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 @@ -108,3 +124,13 @@ 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/xcrun_db" +run_helper hide none "$work/state" >/dev/null +[ ! -e "$work/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" diff --git a/tests/install-sh/run.sh b/tests/install-sh/run.sh index 55ad25cf7..8c1c2eca8 100755 --- a/tests/install-sh/run.sh +++ b/tests/install-sh/run.sh @@ -199,7 +199,7 @@ write_signed_release() { build_clean_path() { CLEAN_PATH_DIR="$(mktemp -d)" # Tools install.sh shells out to during the integrity flow. - for tool in sh id uname mktemp rm basename dirname grep awk curl sed cat tr cut chmod mv mkdir ln find readlink cp cmp sleep; do + for tool in sh id uname mktemp rm basename dirname grep awk curl sed cat tr cut chmod mv mkdir ln find readlink cp cmp sleep head wc; do src="$(command -v "$tool" 2>/dev/null || true)" if [ -n "$src" ]; then ln -s "$src" "$CLEAN_PATH_DIR/$tool" @@ -227,6 +227,14 @@ 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 + [ "$requirement" = "$expected_requirement" ] || { echo "test-requirement: code failed to satisfy specified code requirement(s)" >&2; exit 3; } if staged_override tamper-staged-ticket; then printf 'replaced-notarization-ticket' > "$bundle/Contents/CodeResources" fi @@ -244,6 +252,8 @@ case " $* " in fi if staged_override staged-cdhash; then echo "CDHash=$(cat "$LPM_TEST_TOOL_STATE/staged-cdhash")" >&2 + elif [ -n "${LPM_TEST_TOOL_STATE:-}" ] && [ -e "$LPM_TEST_TOOL_STATE/cdhash" ]; then + echo "CDHash=$(cat "$LPM_TEST_TOOL_STATE/cdhash")" >&2 else echo 'CDHash=0f1e2d3c4b5a69788796a5b4c3d2e1f00f1e2d3c' >&2 fi @@ -512,17 +522,34 @@ 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 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="$(LPM_INSTALL_TEST_API_URL=http://127.0.0.1:1/x LPM_INSTALL_TEST_DOWNLOAD_BASE=http://127.0.0.1:1 \ + LPM_INSTALL_TEST_TICKET_LOOKUP_URL="$spoofed_url" sh "$INSTALL_SH" 2>&1)" || actual_exit=$? + [ "$actual_exit" -ne 0 ] || fail "the ticket lookup override must fail closed for $spoofed_url" + if [ "$HOST_OS" = "Darwin" ]; then + echo "$out" | grep -q "LPM_INSTALL_TEST_TICKET_LOOKUP_URL must point at 127.0.0.1" \ + || fail "the ticket lookup override accepted $spoofed_url: $out" + fi +done +for override in LPM_INSTALL_TEST_CODESIGN LPM_INSTALL_TEST_OPENSSL LPM_INSTALL_TEST_SPCTL LPM_INSTALL_TEST_TICKET_LOOKUP_URL; do + actual_exit=0 + out="$(env "$override=http://127.0.0.1:1/fake" 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 ───────────────────────────────────────── @@ -886,7 +913,9 @@ EOF_SLEEP "notfound:Apple has not issued a notarization ticket" \ "deleted:Apple has not issued a notarization ticket" \ "denied:refused to look up the ticket of downloaded LPM CLI.app (ACCESS_DENIED)" \ - "400:refused to look up the ticket of downloaded LPM CLI.app (HTTP 400)" + "400:refused to look up the ticket of downloaded LPM CLI.app (HTTP 400)" \ + "emptyerror:refused to look up the ticket of downloaded LPM CLI.app (an unrecognized error)" \ + "longerror:refused to look up the ticket of downloaded LPM CLI.app (an unrecognized error)" do outcome="${refusal%%:*}" expected_error="${refusal#*:}" @@ -900,6 +929,72 @@ EOF_SLEEP done pass "macOS install rejects a ticket Apple didn't issue, a revoked one, and refused lookups without retrying" + run_with_ticket_outcomes deletedstring issued + [ "$RUN_RC" -eq 0 ] || fail "a malformed deleted field then a ticket failed the install with exit $RUN_RC: $RUN_OUT" + [ "$TICKET_LOOKUPS" -eq 2 ] || fail "a record whose deleted field isn't a boolean was taken as an answer ($TICKET_LOOKUPS lookups)" + echo "$RUN_OUT" | grep -qF "did not answer (an unreadable answer)" \ + || fail "a malformed deleted field was not reported as unreadable: $RUN_OUT" + pass "macOS install doesn't take a record with a malformed deleted field as an answer" + + run_with_ticket_outcomes extrarecord emptyticket 408 issued + [ "$RUN_RC" -eq 0 ] || fail "answers naming no single ticket then a ticket failed the install with exit $RUN_RC: $RUN_OUT" + [ "$TICKET_LOOKUPS" -eq 4 ] || fail "answers naming no single ticket were taken as one ($TICKET_LOOKUPS lookups, expected 4)" + for detail in "an answer about another record" "an unreadable ticket" "HTTP 408"; do + echo "$RUN_OUT" | grep -qF "did not answer ($detail)" || fail "'$detail' was not retried as such: $RUN_OUT" + done + pass "macOS install retries answers that name no single ticket, and a request timeout" + + run_with_ticket_outcomes withnull + [ "$RUN_RC" -eq 0 ] || fail "JSON nulls beside the ticket failed the install with exit $RUN_RC: $RUN_OUT" + [ "$TICKET_LOOKUPS" -eq 1 ] || fail "JSON nulls beside the ticket made the install look it up $TICKET_LOOKUPS times" + pass "macOS install reads the ticket past JSON nulls in the answer" + + run_with_ticket_outcomes huge issued + [ "$RUN_RC" -eq 0 ] || fail "an oversized answer then a ticket failed the install with exit $RUN_RC: $RUN_OUT" + [ "$TICKET_LOOKUPS" -eq 2 ] || fail "an oversized answer was looked up $TICKET_LOOKUPS times, expected 2" + echo "$RUN_OUT" | grep -qF "did not answer (an oversized answer)" \ + || fail "an oversized answer was not reported as one: $RUN_OUT" + pass "macOS install reads at most 64 KiB of an answer from Apple's ticket service" + + # A user's ~/.curlrc may follow redirects and fail on HTTP errors; neither + # may change what the lookup decides. + printf '{"records":[{"recordName":"2/2/0f1e2d3c4b5a69788796a5b4c3d2e1f00f1e2d3c","fields":{"signedTicket":{"value":"%s","type":"BYTES"}}}]}' \ + "$(printf 'fixture-notarization-ticket' | base64)" > "$fdir/redirected-ticket" + curlrc_home="$(mktemp -d)" + printf 'location\nfail\n' > "$curlrc_home/.curlrc" + for refusal in "302:(HTTP 302)" "403:(HTTP 403)"; do + outcome="${refusal%%:*}" + RUN_INSTALL_ROOT_OVERRIDE="$curlrc_home" + run_with_ticket_outcomes "$outcome" issued + unset RUN_INSTALL_ROOT_OVERRIDE + [ "$RUN_RC" -ne 0 ] || fail "with a ~/.curlrc, ticket outcome '$outcome' must fail the install" + [ "$TICKET_LOOKUPS" -eq 1 ] || fail "with a ~/.curlrc, ticket outcome '$outcome' was retried ($TICKET_LOOKUPS lookups)" + echo "$RUN_OUT" | grep -qF "refused to look up the ticket of downloaded LPM CLI.app ${refusal#*:}" \ + || fail "with a ~/.curlrc, ticket outcome '$outcome' was reported as something else: $RUN_OUT" + done + rm -rf "$curlrc_home" "$fdir/redirected-ticket" + pass "macOS install decides on Apple's answer whatever ~/.curlrc says" + + for malformed_cdhash in \ + 'ABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDE' \ + '0f1e2d3c4b5a69788796a5b4c3d2e1f00f1e2d3' \ + '0f1e2d3c4b5a69788796a5b4c3d2e1f00f1e2d3c0' + do + printf '%s' "$malformed_cdhash" > "$tool_state/cdhash" + harness_lang="${LANG-}" harness_lc_all="${LC_ALL-}" + export LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8 + run_with_ticket_outcomes issued + LANG="$harness_lang" LC_ALL="$harness_lc_all" + [ -n "$LANG" ] || unset LANG + [ -n "$LC_ALL" ] || unset LC_ALL + rm -f "$tool_state/cdhash" + [ "$RUN_RC" -ne 0 ] || fail "code-directory hash '$malformed_cdhash' must fail the install" + [ "$TICKET_LOOKUPS" -eq 0 ] || fail "code-directory hash '$malformed_cdhash' was looked up with Apple" + echo "$RUN_OUT" | grep -q "has no well-formed code-directory hash" \ + || fail "code-directory hash '$malformed_cdhash' was reported as something else: $RUN_OUT" + done + pass "macOS install looks up only a 40-digit lower-case code-directory hash, in any locale" + : > "$tool_state/sha1-code-directory" run_with_ticket_outcomes issued rm -f "$tool_state/sha1-code-directory" diff --git a/tests/install-sh/serve.py b/tests/install-sh/serve.py index fbee44e6b..544fab518 100755 --- a/tests/install-sh/serve.py +++ b/tests/install-sh/serve.py @@ -21,8 +21,14 @@ `issued` returns the ticket in `ticket-issued` (default `fixture-notarization-ticket`), `other` returns a different ticket, `notfound`/`deleted`/`throttled`/`denied` return those record states, +`deletedstring`, `emptyerror` and `longerror` return malformed `deleted` +and `serverErrorCode` fields, `withnull` adds JSON nulls to an issued +ticket, `extrarecord` answers with two records, `emptyticket` with an empty +ticket, `wrongrecord` answers about another record, `garbage` returns a non-JSON -page, `drop` closes the connection, and a number answers with that status. +page, `huge` streams 256 KiB without a length, `drop` closes the +connection, and a number answers with that status (a 3xx redirects to +`/redirected-ticket`). """ import base64 @@ -108,14 +114,26 @@ def do_POST(self) -> None: # noqa: N802 — stdlib API return if outcome.isdigit(): self.send_response(int(outcome)) + if outcome.startswith("3"): + self.send_header("Location", "/redirected-ticket") self.send_header("Content-Length", "0") self.end_headers() return + if outcome == "huge": + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Transfer-Encoding", "chunked") + self.end_headers() + chunk = b"x" * 65536 + for _ in range(4): + self.wfile.write(f"{len(chunk):x}\r\n".encode("ascii") + chunk + b"\r\n") + self.wfile.write(b"0\r\n\r\n") + return if outcome == "garbage": self.answer(200, b"captive portal") return record = {"recordName": record_name} - if outcome in ("issued", "other", "deleted"): + if outcome in ("issued", "other", "deleted", "deletedstring", "withnull", "extrarecord", "emptyticket"): ticket = DEFAULT_TICKET issued = os.path.join(fixture_dir, "ticket-issued") if os.path.isfile(issued): @@ -123,6 +141,8 @@ def do_POST(self) -> None: # noqa: N802 — stdlib API ticket = f.read() if outcome == "other": ticket = b"another-release-ticket" + if outcome == "emptyticket": + ticket = b"" record.update( recordType="DeveloperIDTicket", fields={ @@ -131,8 +151,10 @@ def do_POST(self) -> None: # noqa: N802 — stdlib API "type": "BYTES", } }, - deleted=outcome == "deleted", + deleted="yes" if outcome == "deletedstring" else outcome == "deleted", ) + if outcome == "withnull": + record.update(deleted=None, zoneID=None) elif outcome == "wrongrecord": record.update(recordName="2/2/" + "0" * 40, fields={}) else: @@ -140,9 +162,12 @@ def do_POST(self) -> None: # noqa: N802 — stdlib API "notfound": "NOT_FOUND", "throttled": "THROTTLED", "denied": "ACCESS_DENIED", + "emptyerror": "", + "longerror": "A" * 41, } record.update(reason="fixture", serverErrorCode=codes[outcome]) - self.answer(200, json.dumps({"records": [record]}).encode("utf-8")) + records = [record, record] if outcome == "extrarecord" else [record] + self.answer(200, json.dumps({"records": records}).encode("utf-8")) def answer(self, status: int, body: bytes) -> None: self.send_response(status) From 90c9faf521aefe3bb910224e2bc2139d2f5b0261 Mon Sep 17 00:00:00 2001 From: Tolga Ergin Date: Wed, 25 Nov 2026 01:09:50 +0000 Subject: [PATCH 3/5] Read Apple's ticket answer as strictly in install.sh as in self-update From the council's second review round: - Every field's type is checked on the root element of its extracted value, so a string or boolean wrapped in an array or object no longer passes, and all fields are checked before any decides, as self-update's parser does. `records` must be an array holding exactly one object: plutil can't tell a missing second element from a null one, so the serialized array is compared with its first record. A ticket must be standard padded base64, which base64 -D alone doesn't enforce. - A 200 whose transfer failed is retried as "an incomplete answer" instead of being parsed, a status line without a reason phrase or with a CR is read correctly, and an interim 1xx status is retried. - Tests: container-typed, numeric and non-JSON fields, a null or object `records`, undecodable base64, a truncated answer, and a client that must hang up on an endless answer, so dropping the 64 KiB cap fails. The requirement parity test reads install.sh's bundle and team values. - The workflow runs the live ticket-database test and fails unless all four signed-release tests ran, retries a fresh install that GitHub's shared unauthenticated limit refused, reads the expected versions after each update, and has its own cache key. The developer-tools helper keeps cache directories with spaces intact. Co-Authored-By: Claude Opus 5.5 --- .../macos-without-developer-tools.yml | 37 +++-- crates/lpm-cli/src/commands/self_update.rs | 18 ++- .../src/commands/self_update/notarization.rs | 19 ++- install.sh | 149 ++++++++++++------ scripts/ci/macos-developer-tools.sh | 10 +- scripts/ci/test-macos-developer-tools.sh | 7 +- tests/install-sh/run.sh | 22 +++ tests/install-sh/serve.py | 43 ++++- 8 files changed, 225 insertions(+), 80 deletions(-) diff --git a/.github/workflows/macos-without-developer-tools.yml b/.github/workflows/macos-without-developer-tools.yml index b71044a8c..34d4385d0 100644 --- a/.github/workflows/macos-without-developer-tools.yml +++ b/.github/workflows/macos-without-developer-tools.yml @@ -68,8 +68,8 @@ jobs: ~/.cargo/registry ~/.cargo/git target - key: ${{ runner.os }}-release-upgrade-1.99.1-${{ hashFiles('Cargo.lock') }} - restore-keys: ${{ runner.os }}-release-upgrade-1.99.1- + key: ${{ runner.os }}-without-developer-tools-1.99.1-${{ hashFiles('Cargo.lock') }} + restore-keys: ${{ runner.os }}-without-developer-tools-1.99.1- - name: Build this updater and its signed-release tests run: | @@ -91,8 +91,6 @@ jobs: # 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) - updater_stable=$(curl -fsSL https://registry.npmjs.org/@lpm-registry/cli/latest | jq -er .version) - updater_nightly=$(curl -fsSL https://registry.npmjs.org/@lpm-registry/cli/nightly | jq -er .version) archives="" for tag in v0.76.5 v0.77.0-nightly.20260909.177.e3196a5; do mkdir -p "$RUNNER_TEMP/releases/$tag" @@ -103,8 +101,6 @@ jobs: done { echo "INSTALLER_STABLE=${installer_stable#v}" - echo "UPDATER_STABLE=$updater_stable" - echo "UPDATER_NIGHTLY=$updater_nightly" echo "LPM_TEST_MACOS_RELEASE_ARCHIVES=$archives" } >> "$GITHUB_ENV" @@ -113,16 +109,31 @@ jobs: - name: This updater verifies real signed releases run: | + set -euo pipefail unset DEVELOPER_DIR - "$SELF_UPDATE_TESTS" --ignored --test-threads=1 signed_macos_release + "$SELF_UPDATE_TESTS" --ignored --test-threads=1 signed_macos_release apple_s_ticket_database \ + | tee "$RUNNER_TEMP/signed-release-tests.log" + grep -q 'test result: ok. 4 passed' "$RUNNER_TEMP/signed-release-tests.log" - name: Fresh install through the official installer + env: + GH_TOKEN: ${{ github.token }} run: | set -euo pipefail unset DEVELOPER_DIR rm -rf "$HOME/.lpm" - env PATH=/usr/bin:/bin:/usr/sbin:/sbin SHELL=/bin/zsh sh install.sh - test "$(LPM_NO_UPDATE_CHECK=1 "$HOME/.lpm/bin/lpm" --version | sed -n 1p)" = "lpm $INSTALLER_STABLE" + # The installer asks GitHub's API for the latest release without a + # token; hosted runners share that limit, so a refusal is retried. + for attempt in 1 2 3; do + status=0 + env PATH=/usr/bin:/bin:/usr/sbin:/sbin SHELL=/bin/zsh sh install.sh > "$RUNNER_TEMP/fresh-install.log" 2>&1 || status=$? + cat "$RUNNER_TEMP/fresh-install.log" + [ "$status" -ne 0 ] && grep -q 'Failed to detect latest stable version' "$RUNNER_TEMP/fresh-install.log" || break + sleep 60 + done + test "$status" -eq 0 + installer_stable=$(gh release view --repo lpm-dev/rust-client --json tagName --jq .tagName) + test "$(LPM_NO_UPDATE_CHECK=1 "$HOME/.lpm/bin/lpm" --version | sed -n 1p)" = "lpm ${installer_stable#v}" - name: In-place upgrade of an affected install through the official installer env: @@ -172,7 +183,9 @@ jobs: echo "::notice::$INSTALLER_STABLE still needs Xcode to update; its users recover through the installer" else test "$status" -eq 0 - test "$(LPM_NO_UPDATE_CHECK=1 "$lpm" --version | sed -n 1p)" = "lpm $UPDATER_NIGHTLY" + # Read after the update, so a nightly published meanwhile counts. + nightly=$(curl -fsSL https://registry.npmjs.org/@lpm-registry/cli/nightly | jq -er .version) + test "$(LPM_NO_UPDATE_CHECK=1 "$lpm" --version | sed -n 1p)" = "lpm $nightly" fi - name: Self-update from this build to the latest signed releases @@ -191,7 +204,9 @@ jobs: 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" "$lpm" self-update --channel "$channel" --refresh - if [ "$channel" = stable ]; then expected="$UPDATER_STABLE"; else expected="$UPDATER_NIGHTLY"; fi + if [ "$channel" = stable ]; then tag=latest; else tag=nightly; fi + # Read after the update, so a release published meanwhile counts. + expected=$(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 $expected" /usr/bin/codesign --verify --strict \ -R '=anchor apple generic and certificate leaf[subject.OU] = "823S8YKMRW" and notarized' "$app" diff --git a/crates/lpm-cli/src/commands/self_update.rs b/crates/lpm-cli/src/commands/self_update.rs index af1a064eb..41715b6af 100644 --- a/crates/lpm-cli/src/commands/self_update.rs +++ b/crates/lpm-cli/src/commands/self_update.rs @@ -7006,14 +7006,18 @@ bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb lpm-linux-x64 let install_sh = std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("../../install.sh")) .unwrap(); - let install_sh_requirement = install_sh - .lines() - .find_map(|line| line.strip_prefix("MACOS_CODE_REQUIREMENT=\"")) - .and_then(|value| value.strip_suffix('"')) - .expect("install.sh pins a code requirement") + 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", MACOS_EXPECTED_BUNDLE_ID) - .replace("$EXPECTED_TEAM_ID", MACOS_EXPECTED_TEAM_ID); + .replace("$EXPECTED_BUNDLE_ID", &assignment("EXPECTED_BUNDLE_ID")) + .replace("$EXPECTED_TEAM_ID", &assignment("EXPECTED_TEAM_ID")); assert_eq!( format!("={install_sh_requirement}"), diff --git a/crates/lpm-cli/src/commands/self_update/notarization.rs b/crates/lpm-cli/src/commands/self_update/notarization.rs index 8a14465b9..e757e4681 100644 --- a/crates/lpm-cli/src/commands/self_update/notarization.rs +++ b/crates/lpm-cli/src/commands/self_update/notarization.rs @@ -477,7 +477,24 @@ mod tests { numeric_ticket["records"][0]["fields"]["signedTicket"]["value"] = serde_json::Value::from(5); - for answer in [deleted_string, numeric_error, numeric_ticket] { + let mut array_deleted = issued(TICKET); + array_deleted["records"][0]["deleted"] = serde_json::json!([false]); + let mut array_ticket = issued(TICKET); + let value = array_ticket["records"][0]["fields"]["signedTicket"]["value"].clone(); + array_ticket["records"][0]["fields"]["signedTicket"]["value"] = serde_json::json!([value]); + let record = issued(TICKET)["records"][0].clone(); + let null_record = serde_json::json!({ "records": [record, null] }); + let dict_records = serde_json::json!({ "records": { "0": record } }); + + for answer in [ + deleted_string, + numeric_error, + numeric_ticket, + array_deleted, + array_ticket, + null_record, + dict_records, + ] { assert_eq!( parse_lookup(&serde_json::to_vec(&answer).unwrap(), RECORD), Lookup::Unavailable("an unreadable answer".to_string()), diff --git a/install.sh b/install.sh index 60b7295ac..bc79b4cd5 100755 --- a/install.sh +++ b/install.sh @@ -682,23 +682,30 @@ NOTARIZATION_TICKET_TRANSIENT_ERRORS=" THROTTLED TRY_AGAIN_LATER SERVICE_UNAVAIL # A ticket record is under 4 KiB; anything far larger isn't one. NOTARIZATION_TICKET_RESPONSE_MAX_BYTES=65536 -# Prints the lookup answer's value at the plist key path $1 as a one-value -# XML plist. Each field is extracted on its own, so a JSON null elsewhere in -# the answer, which a plist can't hold, doesn't hide the ones the check reads. +# Prints the lookup answer's value at key path $1, in plutil's format $2. +# Each value is extracted on its own, so a JSON null elsewhere in the answer, +# which a plist can't hold, doesn't hide the ones the check reads. notarization_ticket_extract() { - "$MACOS_PLUTIL_TOOL" -extract "$1" xml1 -o - "$ticket_response" 2>/dev/null + "$MACOS_PLUTIL_TOOL" -extract "$1" "$2" -o - "$ticket_response" 2>/dev/null +} + +# Prints the root element of the value at key path $1: the line after +# `` in its one-value XML plist. +notarization_ticket_root() { + notarization_ticket_extract "$1" xml1 | sed -n '/^$/{n;p;q;}' } # Prints the string at key path $1. Returns 1 when the answer has no such # value and 2 when it isn't a string. notarization_ticket_string() { - ticket_field_xml=$(notarization_ticket_extract "$1") || return 1 - case "$ticket_field_xml" in - *""*) return 0 ;; - *""*) ;; + ticket_field_root=$(notarization_ticket_root "$1") + case "$ticket_field_root" in + '') return 1 ;; + ''|'') return 0 ;; + ''*'') ;; *) return 2 ;; esac - printf '%s\n' "$ticket_field_xml" | sed -n 's:.*\(.*\).*:\1:p' + printf '%s\n' "$ticket_field_root" | sed -n 's:^\(.*\)$:\1:p' } # Looks up the ticket record named $ticket_record. Sets ticket_lookup to @@ -710,64 +717,105 @@ notarization_ticket_string() { lookup_notarization_ticket() { ticket_lookup="unavailable" ticket_lookup_detail="no answer" - rm -f "$ticket_response" "$ticket_headers" "$ticket_issued" - curl -sS --max-time 30 --max-redirs 0 -D "$ticket_headers" -o - \ - -H 'Content-Type: application/json' \ - --data "{\"records\":[{\"recordName\":\"$ticket_record\"}]}" \ - "$NOTARIZATION_TICKET_LOOKUP_URL" | head -c "$((NOTARIZATION_TICKET_RESPONSE_MAX_BYTES + 1))" > "$ticket_response" || true - ticket_http_status=$(awk '/^HTTP\//{status=$2} END{print status}' "$ticket_headers" 2>/dev/null || true) + rm -f "$ticket_response" "$ticket_headers" "$ticket_issued" "$ticket_transfer" + { + ticket_transfer_status=0 + curl -sS --max-time 30 --max-redirs 0 -D "$ticket_headers" -o - \ + -H 'Content-Type: application/json' \ + --data "{\"records\":[{\"recordName\":\"$ticket_record\"}]}" \ + "$NOTARIZATION_TICKET_LOOKUP_URL" || ticket_transfer_status=$? + printf '%s\n' "$ticket_transfer_status" > "$ticket_transfer" + } | head -c "$((NOTARIZATION_TICKET_RESPONSE_MAX_BYTES + 1))" > "$ticket_response" || true + ticket_http_status=$(awk '/^HTTP\//{sub(/\r$/, ""); status=$2} END{print status}' "$ticket_headers" 2>/dev/null || true) + case "$ticket_http_status" in + [0123456789][0123456789][0123456789]) ;; + *) ticket_http_status="" ;; + esac case "$ticket_http_status" in 200) ;; '') return 0 ;; - 408|429|5[0-9][0-9]) ticket_lookup_detail="HTTP $ticket_http_status"; return 0 ;; + 1[0-9][0-9]|408|429|5[0-9][0-9]) ticket_lookup_detail="HTTP $ticket_http_status"; return 0 ;; *) ticket_lookup="refused"; ticket_lookup_detail="HTTP $ticket_http_status"; return 0 ;; esac if [ "$(wc -c < "$ticket_response")" -gt "$NOTARIZATION_TICKET_RESPONSE_MAX_BYTES" ]; then ticket_lookup_detail="an oversized answer" return 0 fi - if notarization_ticket_extract records.1 >/dev/null || \ - ! ticket_answered_record=$(notarization_ticket_string records.0.recordName) || \ - [ "$ticket_answered_record" != "$ticket_record" ]; then + if [ "$(cat "$ticket_transfer" 2>/dev/null)" != 0 ]; then + if [ -s "$ticket_response" ]; then + ticket_lookup_detail="an incomplete answer" + fi + return 0 + fi + # `records` must be an array of objects, and hold only one: plutil writes + # it as `[`, that record and `]`, whatever the record's key order. + ticket_records_json=$(notarization_ticket_extract records json || true) + if [ "$ticket_records_json" = "[]" ]; then ticket_lookup_detail="an answer about another record" return 0 fi + ticket_record_json=$(notarization_ticket_extract records.0 json || true) + case "$ticket_records_json:$ticket_record_json" in + '['*']:{'*'}') ;; + *) ticket_lookup_detail="an unreadable answer"; return 0 ;; + esac ticket_field_status=0 - ticket_server_error=$(notarization_ticket_string records.0.serverErrorCode) || ticket_field_status=$? - case "$ticket_field_status" in - 0) - case "$ticket_server_error" in - NOT_FOUND) ticket_lookup="not-issued"; return 0 ;; - ''|*[!ABCDEFGHIJKLMNOPQRSTUVWXYZ_]*) ticket_server_error="" ;; - esac - if [ -z "$ticket_server_error" ] || [ "${#ticket_server_error}" -gt 40 ]; then - ticket_lookup="refused" - ticket_lookup_detail="an unrecognized error" - return 0 - fi - ticket_lookup_detail="$ticket_server_error" - case "$NOTARIZATION_TICKET_TRANSIENT_ERRORS" in - *" $ticket_server_error "*) ;; - *) ticket_lookup="refused" ;; - esac - return 0 - ;; - 2) ticket_lookup_detail="an unreadable answer"; return 0 ;; + ticket_answered_record=$(notarization_ticket_string records.0.recordName) || ticket_field_status=$? + if [ "$ticket_field_status" -ne 0 ]; then + ticket_lookup_detail="an unreadable answer" + return 0 + fi + if [ "${#ticket_records_json}" -ne "$((${#ticket_record_json} + 2))" ] || \ + [ "$ticket_answered_record" != "$ticket_record" ]; then + ticket_lookup_detail="an answer about another record" + return 0 + fi + # Every field must have its JSON type before any decides, as self-update's + # parser requires. + ticket_error_status=0 + ticket_server_error=$(notarization_ticket_string records.0.serverErrorCode) || ticket_error_status=$? + ticket_value_status=0 + ticket_value=$(notarization_ticket_string records.0.fields.signedTicket.value) || ticket_value_status=$? + ticket_deleted=$(notarization_ticket_root records.0.deleted) + case "$ticket_error_status:$ticket_value_status:$ticket_deleted" in + 2:*|*:2:*|*:*:''|*:*:''|*:*:) ;; + *) ticket_error_status=2 ;; esac - if ticket_deleted_xml=$(notarization_ticket_extract records.0.deleted); then - case "$ticket_deleted_xml" in - *""*) ;; - *""*) ticket_lookup="not-issued"; return 0 ;; - *) ticket_lookup_detail="an unreadable answer"; return 0 ;; + case "$ticket_error_status:$ticket_value_status:$ticket_deleted" in + 2:*|*:2:*) ticket_lookup_detail="an unreadable answer"; return 0 ;; + esac + if [ "$ticket_error_status" -eq 0 ]; then + case "$ticket_server_error" in + NOT_FOUND) ticket_lookup="not-issued"; return 0 ;; + ''|*[!ABCDEFGHIJKLMNOPQRSTUVWXYZ_]*) ticket_server_error="" ;; + esac + if [ -z "$ticket_server_error" ] || [ "${#ticket_server_error}" -gt 40 ]; then + ticket_lookup="refused" + ticket_lookup_detail="an unrecognized error" + return 0 + fi + ticket_lookup_detail="$ticket_server_error" + case "$NOTARIZATION_TICKET_TRANSIENT_ERRORS" in + *" $ticket_server_error "*) ;; + *) ticket_lookup="refused" ;; esac + return 0 fi - ticket_field_status=0 - ticket_value=$(notarization_ticket_string records.0.fields.signedTicket.value) || ticket_field_status=$? - case "$ticket_field_status" in - 1) ticket_lookup_detail="an answer without a ticket"; return 0 ;; - 2) ticket_lookup_detail="an unreadable answer"; return 0 ;; + if [ "$ticket_deleted" = '' ]; then + ticket_lookup="not-issued" + return 0 + fi + if [ "$ticket_value_status" -eq 1 ]; then + ticket_lookup_detail="an answer without a ticket" + return 0 + fi + # Standard padded base64 only, as self-update's decoder requires: base64 -D + # would skip characters outside the alphabet. + case "$ticket_value" in + *[!ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=]*) ticket_value="" ;; esac - if ! printf '%s' "$ticket_value" | "$MACOS_BASE64_TOOL" -D > "$ticket_issued" 2>/dev/null || \ + if [ -z "$ticket_value" ] || [ $((${#ticket_value} % 4)) -ne 0 ] || \ + ! printf '%s' "$ticket_value" | "$MACOS_BASE64_TOOL" -D > "$ticket_issued" 2>/dev/null || \ [ ! -s "$ticket_issued" ]; then ticket_lookup_detail="an unreadable ticket" return 0 @@ -785,6 +833,7 @@ confirm_notarization_ticket() { ticket_record="2/2/$3" ticket_response="$STAGE_DIR/notarization-ticket.json" ticket_headers="$STAGE_DIR/notarization-ticket.headers" + ticket_transfer="$STAGE_DIR/notarization-ticket.transfer" ticket_issued="$STAGE_DIR/notarization-ticket" for ticket_retry_delay in 2 5 15 30 60 ""; do lookup_notarization_ticket diff --git a/scripts/ci/macos-developer-tools.sh b/scripts/ci/macos-developer-tools.sh index 62795698a..443cf2537 100755 --- a/scripts/ci/macos-developer-tools.sh +++ b/scripts/ci/macos-developer-tools.sh @@ -12,7 +12,11 @@ XCRUN_BIN="${XCRUN_BIN:-/usr/bin/xcrun}" STAPLER_BIN="${STAPLER_BIN:-/usr/bin/stapler}" # xcrun caches where tools are in TMPDIR and in the per-user temporary # directory, which differ when TMPDIR is overridden. -XCRUN_CACHE_DIRS="${XCRUN_CACHE_DIRS:-${TMPDIR:-/tmp} $(getconf DARWIN_USER_TEMP_DIR 2>/dev/null || true)}" +if [ -n "${XCRUN_CACHE_DIR:-}" ]; then + XCRUN_CACHE_DIRS=("$XCRUN_CACHE_DIR") +else + XCRUN_CACHE_DIRS=("${TMPDIR:-/tmp}" "$(getconf DARWIN_USER_TEMP_DIR 2>/dev/null || true)") +fi SUDO="${SUDO-sudo}" usage() { @@ -48,8 +52,8 @@ hide_path() { clear_xcrun_cache() { local directory - for directory in $XCRUN_CACHE_DIRS; do - rm -f "$directory"/xcrun_db* + for directory in "${XCRUN_CACHE_DIRS[@]}"; do + [ -n "$directory" ] && rm -f "$directory"/xcrun_db* done } diff --git a/scripts/ci/test-macos-developer-tools.sh b/scripts/ci/test-macos-developer-tools.sh index 025f29b8e..e9e838ee5 100755 --- a/scripts/ci/test-macos-developer-tools.sh +++ b/scripts/ci/test-macos-developer-tools.sh @@ -67,7 +67,7 @@ run_helper() { XCODE_SELECT_BIN="$work/runner/bin/xcode-select" \ XCRUN_BIN="$work/runner/bin/xcrun" \ STAPLER_BIN="$work/runner/bin/stapler" \ - XCRUN_CACHE_DIRS="$work" \ + XCRUN_CACHE_DIR="$work/cache dir" \ SUDO="" \ TMPDIR="$work" \ bash "$helper" "$@" @@ -127,9 +127,10 @@ 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/xcrun_db" +mkdir -p "$work/cache dir" +: >"$work/cache dir/xcrun_db" run_helper hide none "$work/state" >/dev/null -[ ! -e "$work/xcrun_db" ] || fail "hiding developer tools left xcrun's cache of their paths" +[ ! -e "$work/cache dir/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" diff --git a/tests/install-sh/run.sh b/tests/install-sh/run.sh index 8c1c2eca8..c5b75ff5f 100755 --- a/tests/install-sh/run.sh +++ b/tests/install-sh/run.sh @@ -944,6 +944,26 @@ EOF_SLEEP done pass "macOS install retries answers that name no single ticket, and a request timeout" + run_with_ticket_outcomes nullrecord dictrecords arraydeleted arrayticket badbase64 issued + [ "$RUN_RC" -eq 0 ] || fail "malformed answers then a ticket failed the install with exit $RUN_RC: $RUN_OUT" + [ "$TICKET_LOOKUPS" -eq 6 ] || fail "a malformed answer carrying the ticket was taken as an answer ($TICKET_LOOKUPS lookups, expected 6)" + for detail in "an answer about another record" "an unreadable answer" "an unreadable ticket"; do + echo "$RUN_OUT" | grep -qF "did not answer ($detail)" || fail "'$detail' was not retried as such: $RUN_OUT" + done + run_with_ticket_outcomes numericticket numericerror garbage issued + [ "$RUN_RC" -eq 0 ] || fail "malformed answers then a ticket failed the install with exit $RUN_RC: $RUN_OUT" + [ "$TICKET_LOOKUPS" -eq 4 ] || fail "a numeric field or a non-JSON page was taken as an answer ($TICKET_LOOKUPS lookups, expected 4)" + [ "$(echo "$RUN_OUT" | grep -cF "did not answer (an unreadable answer)")" -eq 3 ] \ + || fail "numeric fields and a non-JSON page were not all retried as unreadable: $RUN_OUT" + pass "macOS install takes only a well-formed answer about exactly one record" + + run_with_ticket_outcomes truncated issued + [ "$RUN_RC" -eq 0 ] || fail "a truncated answer then a ticket failed the install with exit $RUN_RC: $RUN_OUT" + [ "$TICKET_LOOKUPS" -eq 2 ] || fail "a truncated answer was taken as an answer ($TICKET_LOOKUPS lookups, expected 2)" + echo "$RUN_OUT" | grep -qF "did not answer (an incomplete answer)" \ + || fail "a truncated answer was not reported as incomplete: $RUN_OUT" + pass "macOS install retries an answer cut off before its end" + run_with_ticket_outcomes withnull [ "$RUN_RC" -eq 0 ] || fail "JSON nulls beside the ticket failed the install with exit $RUN_RC: $RUN_OUT" [ "$TICKET_LOOKUPS" -eq 1 ] || fail "JSON nulls beside the ticket made the install look it up $TICKET_LOOKUPS times" @@ -954,6 +974,8 @@ EOF_SLEEP [ "$TICKET_LOOKUPS" -eq 2 ] || fail "an oversized answer was looked up $TICKET_LOOKUPS times, expected 2" echo "$RUN_OUT" | grep -qF "did not answer (an oversized answer)" \ || fail "an oversized answer was not reported as one: $RUN_OUT" + [ -s "$fdir/ticket-hangups" ] || fail "the install read an oversized answer to its end instead of stopping at 64 KiB" + rm -f "$fdir/ticket-hangups" pass "macOS install reads at most 64 KiB of an answer from Apple's ticket service" # A user's ~/.curlrc may follow redirects and fail on HTTP errors; neither diff --git a/tests/install-sh/serve.py b/tests/install-sh/serve.py index 544fab518..c8c5350e5 100755 --- a/tests/install-sh/serve.py +++ b/tests/install-sh/serve.py @@ -24,9 +24,12 @@ `deletedstring`, `emptyerror` and `longerror` return malformed `deleted` and `serverErrorCode` fields, `withnull` adds JSON nulls to an issued ticket, `extrarecord` answers with two records, `emptyticket` with an empty -ticket, +ticket, `truncated` closes the connection before its declared length, and +`nullrecord`/`dictrecords`/`arraydeleted`/`arrayticket`/`badbase64`/ +`numericticket`/`numericerror` carry the issued ticket in a malformed answer, `wrongrecord` answers about another record, `garbage` returns a non-JSON -page, `huge` streams 256 KiB without a length, `drop` closes the +page, `huge` streams 16 MiB without a length (and notes in `ticket-hangups` a +client that hangs up first), `drop` closes the connection, and a number answers with that status (a 3xx redirects to `/redirected-ticket`). """ @@ -125,13 +128,42 @@ def do_POST(self) -> None: # noqa: N802 — stdlib API self.send_header("Transfer-Encoding", "chunked") self.end_headers() chunk = b"x" * 65536 - for _ in range(4): - self.wfile.write(f"{len(chunk):x}\r\n".encode("ascii") + chunk + b"\r\n") - self.wfile.write(b"0\r\n\r\n") + try: + for _ in range(256): + self.wfile.write(f"{len(chunk):x}\r\n".encode("ascii") + chunk + b"\r\n") + self.wfile.flush() + self.wfile.write(b"0\r\n\r\n") + except (BrokenPipeError, ConnectionResetError): + with open(os.path.join(fixture_dir, "ticket-hangups"), "a", encoding="utf-8") as f: + f.write(record_name + "\n") return if outcome == "garbage": self.answer(200, b"captive portal") return + if outcome == "truncated": + body = json.dumps({"records": [{"recordName": record_name, "fields": {"signedTicket": {"value": base64.b64encode(DEFAULT_TICKET).decode("ascii")}}}]}).encode("utf-8") + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body) + 100)) + self.end_headers() + self.wfile.write(body) + self.wfile.flush() + self.close_connection = True + self.connection.shutdown(2) + return + shapes = { + "nullrecord": lambda r: {"records": [r, None]}, + "dictrecords": lambda r: {"records": {"0": r}}, + "arraydeleted": lambda r: {"records": [dict(r, deleted=[False])]}, + "arrayticket": lambda r: {"records": [dict(r, fields={"signedTicket": {"value": [r["fields"]["signedTicket"]["value"]]}})]}, + "badbase64": lambda r: {"records": [dict(r, fields={"signedTicket": {"value": "not base64!"}})]}, + "numericticket": lambda r: {"records": [dict(r, fields={"signedTicket": {"value": 5}})]}, + } + if outcome in shapes: + ticket = base64.b64encode(DEFAULT_TICKET).decode("ascii") + record = {"recordName": record_name, "deleted": False, "fields": {"signedTicket": {"value": ticket}}} + self.answer(200, json.dumps(shapes[outcome](record)).encode("utf-8")) + return record = {"recordName": record_name} if outcome in ("issued", "other", "deleted", "deletedstring", "withnull", "extrarecord", "emptyticket"): ticket = DEFAULT_TICKET @@ -164,6 +196,7 @@ def do_POST(self) -> None: # noqa: N802 — stdlib API "denied": "ACCESS_DENIED", "emptyerror": "", "longerror": "A" * 41, + "numericerror": 5, } record.update(reason="fixture", serverErrorCode=codes[outcome]) records = [record, record] if outcome == "extrarecord" else [record] From 399d7843a3820df3ca3d111fb4927c466b073f3d Mon Sep 17 00:00:00 2001 From: Tolga Ergin Date: Wed, 25 Nov 2026 01:38:14 +0000 Subject: [PATCH 4/5] Read Apple's ticket answer the same way on every macOS version From the council's third review round, and the new workflow's first runs: - plutil on macOS 15 can't write JSON holding a null, so the round-2 check that compared the serialized `records` with its first record failed there for any null in the answer, and a genuine answer with one would have failed every install. install.sh now extracts single values only, as XML, which a null elsewhere doesn't touch on any version; a second record or an empty `records` still means another record. Shapes only a non-Apple server could send, such as `[record, null]`, are read by their record, the same on every version; the exact ticket still decides. - `fields` and `signedTicket` must be objects when present, a present `signedTicket` must hold a string value, and a string across lines is judged as a string. - Tests pin each guard: base64 outside the standard padded alphabet, a malformed field beside NOT_FOUND, an answer of exactly 65,536 and of 65,537 bytes, an interim-only 100, a status line without a reason phrase, a confirmed ticket with a ~/.curlrc (whose CURL_HOME the harness pins), and a Rust oversized answer that would otherwise be a valid ticket, with each retry's detail asserted. - The workflow names the fresh install's version, since the shared unauthenticated GitHub limit refused all three tries on a runner, and accepts v0.85.0's quoted release-age value. Each updater check compares the version the updater reports choosing with the dist-tag before or after the update. The developer-tools helper skips an empty per-user temporary directory instead of stopping under set -e. Co-Authored-By: Claude Opus 5.5 --- .../macos-without-developer-tools.yml | 46 +++++----- .../src/commands/self_update/notarization.rs | 87 ++++++++++++++++--- install.sh | 49 +++++++---- scripts/ci/macos-developer-tools.sh | 11 ++- scripts/ci/test-macos-developer-tools.sh | 24 ++++- tests/install-sh/run.sh | 51 +++++++++-- tests/install-sh/serve.py | 43 +++++++-- 7 files changed, 233 insertions(+), 78 deletions(-) diff --git a/.github/workflows/macos-without-developer-tools.yml b/.github/workflows/macos-without-developer-tools.yml index 34d4385d0..c50868db9 100644 --- a/.github/workflows/macos-without-developer-tools.yml +++ b/.github/workflows/macos-without-developer-tools.yml @@ -116,24 +116,15 @@ jobs: grep -q 'test result: ok. 4 passed' "$RUNNER_TEMP/signed-release-tests.log" - name: Fresh install through the official installer - env: - GH_TOKEN: ${{ github.token }} run: | set -euo pipefail unset DEVELOPER_DIR rm -rf "$HOME/.lpm" - # The installer asks GitHub's API for the latest release without a - # token; hosted runners share that limit, so a refusal is retried. - for attempt in 1 2 3; do - status=0 - env PATH=/usr/bin:/bin:/usr/sbin:/sbin SHELL=/bin/zsh sh install.sh > "$RUNNER_TEMP/fresh-install.log" 2>&1 || status=$? - cat "$RUNNER_TEMP/fresh-install.log" - [ "$status" -ne 0 ] && grep -q 'Failed to detect latest stable version' "$RUNNER_TEMP/fresh-install.log" || break - sleep 60 - done - test "$status" -eq 0 - installer_stable=$(gh release view --repo lpm-dev/rust-client --json tagName --jq .tagName) - test "$(LPM_NO_UPDATE_CHECK=1 "$HOME/.lpm/bin/lpm" --version | sed -n 1p)" = "lpm ${installer_stable#v}" + # 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 env: @@ -159,12 +150,10 @@ jobs: || { 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" - # The version is named so the job asks GitHub's API for the latest - # release once, in the fresh install, within its unauthenticated limit. 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 -qx 'minimum-release-age-secs = 259200' "$HOME/.lpm/config.toml" + grep -Eqx 'minimum-release-age-secs = "?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 @@ -174,8 +163,10 @@ jobs: 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 > "$RUNNER_TEMP/latest-self-update.log" 2>&1 || status=$? + NO_COLOR=1 "$lpm" self-update --channel nightly --refresh > "$RUNNER_TEMP/latest-self-update.log" 2>&1 || status=$? cat "$RUNNER_TEMP/latest-self-update.log" 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 @@ -183,9 +174,9 @@ jobs: echo "::notice::$INSTALLER_STABLE still needs Xcode to update; its users recover through the installer" else test "$status" -eq 0 - # Read after the update, so a nightly published meanwhile counts. - nightly=$(curl -fsSL https://registry.npmjs.org/@lpm-registry/cli/nightly | jq -er .version) - test "$(LPM_NO_UPDATE_CHECK=1 "$lpm" --version | sed -n 1p)" = "lpm $nightly" + chosen=$(sed -n 's/.*LPM updated to \([^ ]*\).*/\1/p' "$RUNNER_TEMP/latest-self-update.log") + [ "$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 @@ -203,11 +194,16 @@ jobs: 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" - "$lpm" self-update --channel "$channel" --refresh if [ "$channel" = stable ]; then tag=latest; else tag=nightly; fi - # Read after the update, so a release published meanwhile counts. - expected=$(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 $expected" + 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 diff --git a/crates/lpm-cli/src/commands/self_update/notarization.rs b/crates/lpm-cli/src/commands/self_update/notarization.rs index e757e4681..8d7c2cbc9 100644 --- a/crates/lpm-cli/src/commands/self_update/notarization.rs +++ b/crates/lpm-cli/src/commands/self_update/notarization.rs @@ -162,7 +162,10 @@ async fn lookup(client: &reqwest::Client, lookup_url: &str, record_name: &str) - Err(lpm_http::ResponseBodyError::Read(error)) => { Lookup::Unavailable(lpm_http::display_error(&error.without_url()).to_string()) } - Err(_) => Lookup::Unavailable("an oversized answer".to_string()), + Err( + lpm_http::ResponseBodyError::DeclaredTooLarge { .. } + | lpm_http::ResponseBodyError::StreamedTooLarge { .. }, + ) => Lookup::Unavailable("an oversized answer".to_string()), } } @@ -298,7 +301,9 @@ mod tests { server } - async fn confirm(server: &MockServer, retries: usize) -> (Result<(), LpmError>, Vec) { + /// Confirms `TICKET` against `server`, returning the outcome and what the + /// service said before each retry. + async fn confirm(server: &MockServer, retries: usize) -> (Result<(), LpmError>, Vec) { let mut waits = Vec::new(); let result = confirm_stapled_ticket( &lookup_client().unwrap(), @@ -306,7 +311,7 @@ mod tests { CDHASH, TICKET, &vec![Duration::from_millis(1); retries], - |delay, _| waits.push(delay), + |_, detail| waits.push(detail.to_string()), ) .await; (result, waits) @@ -338,7 +343,7 @@ mod tests { ResponseTemplate::new(429), ResponseTemplate::new(408), ResponseTemplate::new(200).set_body_string("captive portal"), - ResponseTemplate::new(200).set_body_bytes(vec![b' '; RESPONSE_MAX_BYTES + 1]), + ResponseTemplate::new(200).set_body_bytes(padded_issued(RESPONSE_MAX_BYTES + 1)), ResponseTemplate::new(200).set_body_json(issued(TICKET)), ]) .await; @@ -346,10 +351,44 @@ mod tests { let (result, waits) = confirm(&server, 6).await; result.unwrap(); - assert_eq!(waits.len(), 6); + assert_eq!( + waits, + [ + "HTTP 503", + "THROTTLED", + "HTTP 429", + "HTTP 408", + "an unreadable answer", + "an oversized answer", + ] + ); assert_eq!(lookups(&server).await, 7); } + /// An answer that issues `TICKET`, padded to exactly `size` bytes. + fn padded_issued(size: usize) -> Vec { + let mut answer = issued(TICKET); + answer["records"][0]["padding"] = serde_json::Value::from(""); + let unpadded = serde_json::to_vec(&answer).unwrap().len(); + answer["records"][0]["padding"] = serde_json::Value::from("x".repeat(size - unpadded)); + let body = serde_json::to_vec(&answer).unwrap(); + assert_eq!(body.len(), size); + body + } + + #[tokio::test] + async fn answer_of_exactly_the_size_limit_is_read() { + let server = ticket_service(vec![ + ResponseTemplate::new(200).set_body_bytes(padded_issued(RESPONSE_MAX_BYTES)), + ]) + .await; + + let (result, waits) = confirm(&server, 5).await; + + result.unwrap(); + assert!(waits.is_empty(), "{waits:?}"); + } + #[tokio::test] async fn lasting_outage_of_apple_s_ticket_service_fails_as_a_network_error() { let server = ticket_service(vec![ResponseTemplate::new(503)]).await; @@ -466,7 +505,8 @@ mod tests { )); } - /// install.sh's harness feeds the same malformed records to its parser. + /// install.sh's harness feeds the same malformed records to its parser, + /// apart from the null-holding ones noted below. #[test] fn malformed_record_fields_are_classified_as_install_sh_classifies_them() { let mut deleted_string = issued(TICKET); @@ -483,8 +523,17 @@ mod tests { let value = array_ticket["records"][0]["fields"]["signedTicket"]["value"].clone(); array_ticket["records"][0]["fields"]["signedTicket"]["value"] = serde_json::json!([value]); let record = issued(TICKET)["records"][0].clone(); - let null_record = serde_json::json!({ "records": [record, null] }); let dict_records = serde_json::json!({ "records": { "0": record } }); + let mut numeric_fields = issued(TICKET); + numeric_fields["records"][0]["fields"] = serde_json::Value::from(5); + numeric_fields["records"][0]["serverErrorCode"] = serde_json::Value::from("ACCESS_DENIED"); + let mut empty_signed_ticket = issued(TICKET); + empty_signed_ticket["records"][0]["fields"]["signedTicket"] = serde_json::json!({}); + empty_signed_ticket["records"][0]["serverErrorCode"] = + serde_json::Value::from("ACCESS_DENIED"); + let mut null_ticket_value = issued(TICKET); + null_ticket_value["records"][0]["fields"]["signedTicket"]["value"] = + serde_json::Value::Null; for answer in [ deleted_string, @@ -492,8 +541,10 @@ mod tests { numeric_ticket, array_deleted, array_ticket, - null_record, dict_records, + numeric_fields, + empty_signed_ticket, + null_ticket_value, ] { assert_eq!( parse_lookup(&serde_json::to_vec(&answer).unwrap(), RECORD), @@ -501,10 +552,22 @@ mod tests { "{answer}" ); } - assert_eq!( - parse_lookup(&serde_json::to_vec(&record_error("")).unwrap(), RECORD), - Lookup::Refused("an unrecognized error".to_string()) - ); + for code in ["", "BAD\nCODE"] { + assert_eq!( + parse_lookup(&serde_json::to_vec(&record_error(code)).unwrap(), RECORD), + Lookup::Refused("an unrecognized error".to_string()), + "{code:?}" + ); + } + // plutil can't extract a value that holds a JSON null, so install.sh + // reads `[record, null]`, `{"0": record}` and null-holding containers + // by their record alone, where this parser retries. Either way only + // the exact ticket confirms. + let null_record = serde_json::json!({ "records": [issued(TICKET)["records"][0], null] }); + assert!(matches!( + parse_lookup(&serde_json::to_vec(&null_record).unwrap(), RECORD), + Lookup::Unavailable(_) + )); } #[test] diff --git a/install.sh b/install.sh index bc79b4cd5..493b73423 100755 --- a/install.sh +++ b/install.sh @@ -682,17 +682,19 @@ NOTARIZATION_TICKET_TRANSIENT_ERRORS=" THROTTLED TRY_AGAIN_LATER SERVICE_UNAVAIL # A ticket record is under 4 KiB; anything far larger isn't one. NOTARIZATION_TICKET_RESPONSE_MAX_BYTES=65536 -# Prints the lookup answer's value at key path $1, in plutil's format $2. -# Each value is extracted on its own, so a JSON null elsewhere in the answer, -# which a plist can't hold, doesn't hide the ones the check reads. +# Prints the lookup answer's value at key path $1 as a one-value XML plist. +# Values are extracted one by one: a plist can't hold a JSON null, so a null +# fails only the extraction of a value that holds it, and plutil writes JSON +# holding a null only on some macOS versions. notarization_ticket_extract() { - "$MACOS_PLUTIL_TOOL" -extract "$1" "$2" -o - "$ticket_response" 2>/dev/null + "$MACOS_PLUTIL_TOOL" -extract "$1" xml1 -o - "$ticket_response" 2>/dev/null } # Prints the root element of the value at key path $1: the line after -# `` in its one-value XML plist. +# ``. Prints nothing for a missing or null value, or one +# that holds a null. notarization_ticket_root() { - notarization_ticket_extract "$1" xml1 | sed -n '/^$/{n;p;q;}' + notarization_ticket_extract "$1" | sed -n '/^$/{n;p;q;}' } # Prints the string at key path $1. Returns 1 when the answer has no such @@ -703,6 +705,9 @@ notarization_ticket_string() { '') return 1 ;; ''|'') return 0 ;; ''*'') ;; + # A string across lines: no identifier, record name or base64 ticket has + # one, so it is judged as an empty string. + ''*) return 0 ;; *) return 2 ;; esac printf '%s\n' "$ticket_field_root" | sed -n 's:^\(.*\)$:\1:p' @@ -747,26 +752,21 @@ lookup_notarization_ticket() { fi return 0 fi - # `records` must be an array of objects, and hold only one: plutil writes - # it as `[`, that record and `]`, whatever the record's key order. - ticket_records_json=$(notarization_ticket_extract records json || true) - if [ "$ticket_records_json" = "[]" ]; then + # The answer must be about this record alone: a second record, or none, + # means it is about something else. + if notarization_ticket_extract records.1 >/dev/null || \ + notarization_ticket_extract records.1.recordName >/dev/null || \ + [ "$(notarization_ticket_root records)" = '' ]; then ticket_lookup_detail="an answer about another record" return 0 fi - ticket_record_json=$(notarization_ticket_extract records.0 json || true) - case "$ticket_records_json:$ticket_record_json" in - '['*']:{'*'}') ;; - *) ticket_lookup_detail="an unreadable answer"; return 0 ;; - esac ticket_field_status=0 ticket_answered_record=$(notarization_ticket_string records.0.recordName) || ticket_field_status=$? if [ "$ticket_field_status" -ne 0 ]; then ticket_lookup_detail="an unreadable answer" return 0 fi - if [ "${#ticket_records_json}" -ne "$((${#ticket_record_json} + 2))" ] || \ - [ "$ticket_answered_record" != "$ticket_record" ]; then + if [ "$ticket_answered_record" != "$ticket_record" ]; then ticket_lookup_detail="an answer about another record" return 0 fi @@ -777,8 +777,19 @@ lookup_notarization_ticket() { ticket_value_status=0 ticket_value=$(notarization_ticket_string records.0.fields.signedTicket.value) || ticket_value_status=$? ticket_deleted=$(notarization_ticket_root records.0.deleted) - case "$ticket_error_status:$ticket_value_status:$ticket_deleted" in - 2:*|*:2:*|*:*:''|*:*:''|*:*:) ;; + case "$ticket_deleted" in + ''|''|'') ;; + *) ticket_error_status=2 ;; + esac + # `fields` and `signedTicket` are objects when present, and a signedTicket + # holds its value. + case "$(notarization_ticket_root records.0.fields)" in + ''|''|'') ;; + *) ticket_error_status=2 ;; + esac + case "$(notarization_ticket_root records.0.fields.signedTicket)" in + '') ;; + ''|'') [ "$ticket_value_status" -eq 0 ] || ticket_error_status=2 ;; *) ticket_error_status=2 ;; esac case "$ticket_error_status:$ticket_value_status:$ticket_deleted" in diff --git a/scripts/ci/macos-developer-tools.sh b/scripts/ci/macos-developer-tools.sh index 443cf2537..3e37f4236 100755 --- a/scripts/ci/macos-developer-tools.sh +++ b/scripts/ci/macos-developer-tools.sh @@ -10,13 +10,10 @@ COMMAND_LINE_TOOLS_DIR="${MACOS_COMMAND_LINE_TOOLS_DIR:-/Library/Developer/Comma 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. -if [ -n "${XCRUN_CACHE_DIR:-}" ]; then - XCRUN_CACHE_DIRS=("$XCRUN_CACHE_DIR") -else - XCRUN_CACHE_DIRS=("${TMPDIR:-/tmp}" "$(getconf DARWIN_USER_TEMP_DIR 2>/dev/null || true)") -fi +XCRUN_CACHE_DIRS=("${TMPDIR:-/tmp}" "$("$GETCONF_BIN" DARWIN_USER_TEMP_DIR 2>/dev/null || true)") SUDO="${SUDO-sudo}" usage() { @@ -53,7 +50,9 @@ hide_path() { clear_xcrun_cache() { local directory for directory in "${XCRUN_CACHE_DIRS[@]}"; do - [ -n "$directory" ] && rm -f "$directory"/xcrun_db* + if [ -n "$directory" ]; then + rm -f "$directory"/xcrun_db* + fi done } diff --git a/scripts/ci/test-macos-developer-tools.sh b/scripts/ci/test-macos-developer-tools.sh index e9e838ee5..f64ee5988 100755 --- a/scripts/ci/test-macos-developer-tools.sh +++ b/scripts/ci/test-macos-developer-tools.sh @@ -58,6 +58,14 @@ case "\$(cat "$work/runner/selected")" in *) echo "xcode-select: error: tool 'stapler' requires Xcode, but active developer directory '\$(cat "$work/runner/selected")' is a command line tools instance" >&2; exit 1 ;; esac EOF + # Like getconf: prints the per-user temporary directory, or nothing when + # getconf-fails exists. + cat >"$work/runner/bin/getconf" <