diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4ed0e5423..3f8614453 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 @@ -500,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..c50868db9 --- /dev/null +++ b/.github/workflows/macos-without-developer-tools.yml @@ -0,0 +1,214 @@ +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 }}-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: | + set -euo pipefail + tests=$(cargo test --locked -p lpm-cli --bin lpm-rs --no-run --message-format=json \ + | jq -r 'select(.reason == "compiler-artifact" and .profile.test and .target.name == "lpm-rs") | .executable') + test -x "$tests" + LPM_BUILD_VERSION="$FIXED_BUILD_VERSION" cargo build --locked -p lpm-cli --bin lpm-rs + mkdir -p "$RUNNER_TEMP/fixed" + cp target/debug/lpm-rs "$RUNNER_TEMP/fixed/lpm-rs" + test "$(LPM_NO_UPDATE_CHECK=1 "$RUNNER_TEMP/fixed/lpm-rs" --version | sed -n 1p)" = "lpm $FIXED_BUILD_VERSION" + echo "SELF_UPDATE_TESTS=$tests" >> "$GITHUB_ENV" + + - name: Download real signed releases + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + # install.sh follows GitHub's latest release; lpm self-update follows + # the npm dist-tags first, which GitHub releases precede. + installer_stable=$(gh release view --repo lpm-dev/rust-client --json tagName --jq .tagName) + archives="" + for tag in v0.76.5 v0.77.0-nightly.20260909.177.e3196a5; do + mkdir -p "$RUNNER_TEMP/releases/$tag" + gh release download "$tag" --repo lpm-dev/rust-client --dir "$RUNNER_TEMP/releases/$tag" \ + --pattern 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 "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: | + set -euo pipefail + unset DEVELOPER_DIR + "$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 + run: | + set -euo pipefail + unset DEVELOPER_DIR + rm -rf "$HOME/.lpm" + # The version is named: the installer's own latest-release lookup + # is unauthenticated, and hosted runners share GitHub's hourly + # limit for it. tests/install-sh covers that lookup. + env PATH=/usr/bin:/bin:/usr/sbin:/sbin SHELL=/bin/zsh LPM_INSTALL_VERSION="v$INSTALLER_STABLE" sh install.sh + test "$(LPM_NO_UPDATE_CHECK=1 "$HOME/.lpm/bin/lpm" --version | sed -n 1p)" = "lpm $INSTALLER_STABLE" + + - name: In-place upgrade of an affected install through the official installer + env: + GITHUB_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + unset DEVELOPER_DIR + rm -rf "$HOME/.lpm" + lpm="$HOME/.lpm/bin/lpm" + env PATH=/usr/bin:/bin:/usr/sbin:/sbin SHELL=/bin/zsh \ + LPM_INSTALL_VERSION="$AFFECTED_VERSION" LPM_INSTALL_MIN_VERSION_OVERRIDE=1 sh install.sh + test "$(LPM_NO_UPDATE_CHECK=1 "$lpm" --version | sed -n 1p)" = "lpm ${AFFECTED_VERSION#v}" + # With LPM_NO_UPDATE_CHECK, no background update check can hold the + # update lock when the self-update below starts. + LPM_NO_UPDATE_CHECK=1 "$lpm" config release-age --set 3d + printf 'kept across upgrades\n' > "$HOME/.lpm/upgrade-sentinel" + if "$lpm" self-update > "$RUNNER_TEMP/affected-self-update.log" 2>&1; then + cat "$RUNNER_TEMP/affected-self-update.log" + echo "::error::$AFFECTED_VERSION updated itself, so developer tools were not removed" + exit 1 + fi + grep -q "$UPDATER_NEEDS_XCODE" "$RUNNER_TEMP/affected-self-update.log" \ + || { cat "$RUNNER_TEMP/affected-self-update.log"; exit 1; } + (cd "$HOME/.lpm" && find . -type f ! -path './bin/*' ! -path './libexec/*' -print0 \ + | xargs -0 shasum -a 256) > "$RUNNER_TEMP/settings" + env PATH=/usr/bin:/bin:/usr/sbin:/sbin SHELL=/bin/zsh LPM_INSTALL_VERSION="v$INSTALLER_STABLE" sh install.sh + (cd "$HOME/.lpm" && shasum -a 256 --check --quiet "$RUNNER_TEMP/settings") + test "$(LPM_NO_UPDATE_CHECK=1 "$lpm" --version | sed -n 1p)" = "lpm $INSTALLER_STABLE" + grep -Eqx 'minimum-release-age-secs = "?259200"?' "$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" + nightly() { curl -fsSL https://registry.npmjs.org/@lpm-registry/cli/nightly | jq -er .version; } + before=$(nightly) + status=0 + 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 + 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 + 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 + env: + GITHUB_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + unset DEVELOPER_DIR + lpm="$HOME/.lpm/bin/lpm" + app="$HOME/.lpm/libexec/LPM CLI.app" + (cd "$HOME/.lpm" && find . -type f ! -path './bin/*' ! -path './libexec/*' ! -name update-check.json -print0 \ + | xargs -0 shasum -a 256) > "$RUNNER_TEMP/settings" + for channel in stable nightly; do + rm -rf "$app" + mkdir -p "$app/Contents/MacOS" + cp "$RUNNER_TEMP/fixed/lpm-rs" "$app/Contents/MacOS/lpm-rs" + test "$(LPM_NO_UPDATE_CHECK=1 "$lpm" --version | sed -n 1p)" = "lpm $FIXED_BUILD_VERSION" + if [ "$channel" = stable ]; then tag=latest; else tag=nightly; fi + before=$(curl -fsSL "https://registry.npmjs.org/@lpm-registry/cli/$tag" | jq -er .version) + "$lpm" self-update --channel "$channel" --refresh --json | tee "$RUNNER_TEMP/self-update-$channel.json" + jq -e '.applied and .verified' "$RUNNER_TEMP/self-update-$channel.json" + chosen=$(jq -er .latest "$RUNNER_TEMP/self-update-$channel.json") + # What the updater chose must be the release the dist-tag named, + # before or after the update, and must be what got installed. + [ "$chosen" = "$before" ] || \ + [ "$chosen" = "$(curl -fsSL "https://registry.npmjs.org/@lpm-registry/cli/$tag" | jq -er .version)" ] + test "$(LPM_NO_UPDATE_CHECK=1 "$lpm" --version | sed -n 1p)" = "lpm $chosen" + /usr/bin/codesign --verify --strict \ + -R '=anchor apple generic and certificate leaf[subject.OU] = "823S8YKMRW" and notarized' "$app" + done + (cd "$HOME/.lpm" && shasum -a 256 --check --quiet "$RUNNER_TEMP/settings") + + - name: Restore developer tools + if: always() + run: bash scripts/ci/macos-developer-tools.sh restore "$RUNNER_TEMP/developer-tools" 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..5230053af 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,54 @@ 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] = { + // 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 { + 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 +3037,11 @@ fn macos_validation_failure(description: &str, output: &std::process::Output) -> )) } -/// `stapler validate` checks the stapled ticket against Apple's CloudKit -/// record and exits with `EX_NOHOST` when CloudKit doesn't answer. -#[cfg(target_os = "macos")] -const STAPLER_CLOUDKIT_UNREACHABLE: i32 = 68; - -/// CloudKit lookups have kept failing for over 20 s at a time, so the checks -/// spread over about two minutes before giving up, as install.sh's do. -#[cfg(target_os = "macos")] -const NOTARIZATION_TICKET_RETRY_DELAYS: [Duration; 5] = [ - Duration::from_secs(2), - Duration::from_secs(5), - Duration::from_secs(15), - Duration::from_secs(30), - Duration::from_secs(60), -]; - -/// Validates the bundle's stapled notarization ticket, running `stapler` -/// again after each of `retry_delays` while CloudKit doesn't answer. Any -/// other failure, an invalid or missing ticket among them, fails at once. -#[cfg(target_os = "macos")] -fn validate_notarization_ticket( - stapler: &str, - app_bundle: &Path, - retry_delays: &[Duration], -) -> Result<(), LpmError> { - const DESCRIPTION: &str = "macOS notarization-ticket validation"; - let arguments = [OsStr::new("validate"), app_bundle.as_os_str()]; - let mut retry_delays = retry_delays.iter(); - loop { - let output = run_macos_validation_tool_once(stapler, &arguments, DESCRIPTION)?; - if output.status.success() { - return Ok(()); - } - match retry_delays.next() { - Some(delay) if output.status.code() == Some(STAPLER_CLOUDKIT_UNREACHABLE) => { - std::thread::sleep(*delay); - } - _ => return Err(macos_validation_failure(DESCRIPTION, &output)), - } - } -} - #[cfg(target_os = "macos")] fn plist_buddy_value(plist: &Path, key: &str) -> Result { let command = format!("Print :{key}"); let output = run_macos_validation_tool( - "/usr/libexec/PlistBuddy", + MacOSTool::PlistBuddy, &[OsStr::new("-c"), command.as_ref(), plist.as_os_str()], "provisioning-profile metadata validation", )?; @@ -3080,32 +3081,89 @@ 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, 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!( + "=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")] -fn validate_macos_app_bundle( - app_bundle: &Path, - notarization_check: NotarizationCheck<'_>, -) -> Result { +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 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", )?; let details = format!( - "{}{}", + "{}\n{}", String::from_utf8_lossy(&details.stdout), String::from_utf8_lossy(&details.stderr) ); @@ -3122,19 +3180,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 +3214,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 +3234,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 +3250,7 @@ fn validate_macos_app_bundle( ], "macOS Gatekeeper validation", )?; - Ok(notarization) + Ok(()) } #[cfg(target_os = "macos")] @@ -3270,10 +3321,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 +4122,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 +4141,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 +4163,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 +4173,124 @@ mod tests { staged.executable.clone() }; std::fs::remove_file(sealed).unwrap(); + assert!(inspect_signed_macos_app_bundle(&staged.app_bundle).is_err()); + } + } + + /// The record comparison against Apple's live ticket database, which the + /// staging test below can't reach when the `notarized` requirement + /// rejects a swapped ticket first. + #[cfg(target_os = "macos")] + #[tokio::test] + #[ignore = "requires two signed release archives in LPM_TEST_MACOS_RELEASE_ARCHIVES"] + async fn apple_s_ticket_database_confirms_only_a_ticket_for_the_release_s_code() { + 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 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 a ticket for its code"), "{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"] + 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 a ticket for its code") + || 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 +4307,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", @@ -6839,156 +7002,99 @@ bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb lpm-linux-x64 #[cfg(target_os = "macos")] #[test] - fn macos_validation_refuses_excessive_output() { - let result = run_macos_validation_tool( - "/bin/sh", - &[ - OsStr::new("-c"), - OsStr::new("/usr/bin/head -c 2097152 /dev/zero"), - ], - "noisy validation fixture", - ); - assert!(result.is_err(), "validation output must be bounded"); - } + fn code_requirement_is_the_one_install_sh_enforces() { + let install_sh = + std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("../../install.sh")) + .unwrap(); + let assignment = |name: &str| { + install_sh + .lines() + .find_map(|line| line.strip_prefix(&format!("{name}=\""))) + .and_then(|value| value.strip_suffix('"')) + .unwrap_or_else(|| panic!("install.sh sets {name}")) + .to_string() + }; + let install_sh_requirement = assignment("MACOS_CODE_REQUIREMENT") + .replace("\\\"", "\"") + .replace("$EXPECTED_BUNDLE_ID", &assignment("EXPECTED_BUNDLE_ID")) + .replace("$EXPECTED_TEAM_ID", &assignment("EXPECTED_TEAM_ID")); - #[cfg(target_os = "macos")] - #[test] - fn macos_validation_does_not_wait_for_inherited_output_after_parent_exit() { - let directory = tempfile::tempdir().unwrap(); - let pid_file = directory.path().join("child-pid"); - let script = format!("/bin/sleep 5 & echo $! > '{}'; exit 0", pid_file.display()); - let started = Instant::now(); - let result = run_macos_validation_tool( - "/bin/sh", - &[OsStr::new("-c"), OsStr::new(&script)], - "detached output fixture", - ); - let elapsed = started.elapsed(); - if let Ok(pid) = std::fs::read_to_string(pid_file) - .unwrap() - .trim() - .parse::() - { - // SAFETY: the PID belongs to the disposable child created by this test. - unsafe { - libc::kill(pid, libc::SIGKILL); - } - } - result.unwrap(); - assert!( - elapsed < Duration::from_secs(3), - "inherited pipe delayed completion: {elapsed:?}" + assert_eq!( + format!("={install_sh_requirement}"), + macos_code_requirement() ); } - /// 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() - } - + /// `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 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(); + 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!( - stapler_runs(directory.path()), - vec!["validate /Applications/LPM CLI.app"; 3] + output.status.code(), + Some(3), + "{}", + String::from_utf8_lossy(&output.stderr) ); } #[cfg(target_os = "macos")] #[test] - fn notarization_ticket_check_reports_a_lasting_cloudkit_outage_in_stapler_s_words() { + fn provisioning_profile_that_is_oversized_or_not_cms_is_rejected() { 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()], + let oversized = directory.path().join("oversized.provisionprofile"); + std::fs::write( + &oversized, + vec![0_u8; MACOS_PROVISIONING_PROFILE_MAX_BYTES as usize + 1], ) - .unwrap_err() - .to_string(); + .unwrap(); + let corrupt = directory.path().join("corrupt.provisionprofile"); + std::fs::write(&corrupt, b"not a CMS envelope").unwrap(); - assert!( - error.contains("CloudKit's response is inconsistent"), - "{error}" - ); - assert_eq!( - stapler_runs(directory.path()).len(), - NOTARIZATION_TICKET_RETRY_DELAYS.len() + 1 - ); + 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. #[cfg(target_os = "macos")] #[test] - fn notarization_ticket_retries_wait_out_the_same_cloudkit_outage_as_install_sh() { - let install_sh = - std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("../../install.sh")) - .unwrap(); - let schedule = install_sh - .lines() - .find_map(|line| { - line.trim() - .strip_prefix("for ticket_retry_delay in ")? - .strip_suffix("; do") - }) - .expect("install.sh retries the notarization ticket check"); - let install_sh_delays = schedule - .split_whitespace() - .filter(|delay| *delay != "\"\"") - .map(|delay| Duration::from_secs(delay.parse().unwrap())) - .collect::>(); + fn 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); - assert_eq!(install_sh_delays, NOTARIZATION_TICKET_RETRY_DELAYS); + 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() + ); + } } #[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 +7113,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 +7134,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..b42d9727b --- /dev/null +++ b/crates/lpm-cli/src/commands/self_update/notarization.rs @@ -0,0 +1,781 @@ +//! 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 +//! accepts the stapled ticket while the record stands, as long as the stapled +//! ticket is the record's or another ticket for the same code, which Apple +//! issues when the code is notarized again. 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 a ticket for the code +/// directory whose SHA-256 hash is `cdhash`, and that `stapled_ticket` is +/// that ticket or another one for the same code. +/// +/// 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 stapled ticket for other code, 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 || is_ticket_for(stapled_ticket, cdhash) => + { + return Ok(()); + } + Lookup::Issued(_) => { + return Err(LpmError::SelfUpdate( + "the notarization ticket stapled to the macOS app is not a ticket 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" + ))); + } + }, + } + } +} + +/// Whether `ticket` is a ticket Apple issued for the code directory whose +/// hash is `cdhash`: it carries the `s8ch` magic and, among its listed code +/// directories, that hash. Its bytes come from the Sigstore-verified release +/// archive, and Apple's record shows the code is notarized, so the stapled +/// ticket only has to be for this code. +fn is_ticket_for(ticket: &[u8], cdhash: &str) -> bool { + let Some(hash) = (0..cdhash.len()) + .step_by(2) + .map(|at| u8::from_str_radix(cdhash.get(at..at + 2)?, 16).ok()) + .collect::>>() + else { + return false; + }; + ticket.starts_with(b"s8ch") && ticket.windows(hash.len()).any(|window| window == hash) +} + +/// 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 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::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())); + } + 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( + lpm_http::ResponseBodyError::DeclaredTooLarge { .. } + | lpm_http::ResponseBodyError::StreamedTooLarge { .. }, + ) => Lookup::Unavailable("an oversized answer".to_string()), + } +} + +#[derive(serde::Deserialize)] +struct LookupResponse { + records: Vec, +} + +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase")] +struct TicketRecord { + record_name: String, + server_error_code: Option, + deleted: Option, + 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 another record".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 == Some(true) { + 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 + } + + /// 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(), + &format!("{}/lookup", server.uri()), + CDHASH, + TICKET, + &vec![Duration::from_millis(1); retries], + |_, detail| waits.push(detail.to_string()), + ) + .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(408), + ResponseTemplate::new(200).set_body_string("captive portal"), + ResponseTemplate::new(200).set_body_bytes(padded_issued(RESPONSE_MAX_BYTES + 1)), + ResponseTemplate::new(200).set_body_json(issued(TICKET)), + ]) + .await; + + let (result, waits) = confirm(&server, 6).await; + + result.unwrap(); + 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; + + 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); + } + + /// A ticket as Apple writes them: the `s8ch` magic, then, among the rest, + /// the 20-byte code-directory hash of the code it was issued for. + fn ticket_for(cdhash: &str, rest: &[u8]) -> Vec { + let mut ticket = b"s8ch".to_vec(); + ticket.extend( + (0..cdhash.len()) + .step_by(2) + .map(|at| u8::from_str_radix(&cdhash[at..at + 2], 16).unwrap()), + ); + ticket.extend_from_slice(rest); + ticket + } + + async fn confirm_stapled(server: &MockServer, stapled: &[u8]) -> Result<(), LpmError> { + confirm_stapled_ticket( + &lookup_client().unwrap(), + &format!("{}/lookup", server.uri()), + CDHASH, + stapled, + &[], + |_, _| {}, + ) + .await + } + + #[tokio::test] + async fn stapled_ticket_apple_reissued_for_the_same_code_is_accepted() { + let server = ticket_service(vec![ + ResponseTemplate::new(200) + .set_body_json(issued(&ticket_for(CDHASH, b"second notarization"))), + ]) + .await; + + confirm_stapled(&server, &ticket_for(CDHASH, b"first notarization")) + .await + .unwrap(); + } + + #[tokio::test] + async fn stapled_ticket_for_other_code_or_none_is_rejected_without_retrying() { + let other_code = "0f1e2d3c4b5a69788796a5b4c3d2e1f00f1e2d3c"; + let mut unmarked = ticket_for(CDHASH, b"first notarization"); + unmarked[..4].copy_from_slice(b"xxxx"); + for stapled in [ + ticket_for(other_code, b"another release's ticket"), + unmarked, + TICKET.to_vec(), + ] { + let server = ticket_service(vec![ + ResponseTemplate::new(200).set_body_json(issued(&ticket_for(CDHASH, b"issued"))), + ]) + .await; + + let error = confirm_stapled(&server, &stapled) + .await + .unwrap_err() + .to_string(); + + assert!(error.contains("not a ticket for its code"), "{error}"); + 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(_) + )); + } + + /// 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); + 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); + + 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 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, + numeric_error, + numeric_ticket, + array_deleted, + array_ticket, + dict_records, + numeric_fields, + empty_signed_ticket, + null_ticket_value, + ] { + assert_eq!( + parse_lookup(&serde_json::to_vec(&answer).unwrap(), RECORD), + Lookup::Unavailable("an unreadable answer".to_string()), + "{answer}" + ); + } + 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] + 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(); + + 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_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( + 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..4bd6e50d5 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, 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" MACOS_BUNDLE=0 @@ -197,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 @@ -226,24 +236,41 @@ 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` accepts the stapled ticket while that record stands, as +# long as the stapled ticket is the record's or another ticket for the same +# code, which Apple issues when the code is notarized again. 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 +679,215 @@ 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 " +# 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 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" xml1 -o - "$ticket_response" 2>/dev/null +} + +# Prints the root element of the value at key path $1: the line after +# ``. Prints nothing for a missing or null value, or one +# that holds a null. +notarization_ticket_root() { + notarization_ticket_extract "$1" | 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_root=$(notarization_ticket_root "$1") + case "$ticket_field_root" in + '') 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' +} -validate_notarization_ticket() { +# 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. 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_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 ;; + 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 [ "$(cat "$ticket_transfer" 2>/dev/null)" != 0 ]; then + if [ -s "$ticket_response" ]; then + ticket_lookup_detail="an incomplete answer" + fi + return 0 + fi + # 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_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_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_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 + 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 + 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 [ -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 + fi + ticket_lookup="issued" +} + +# Whether the file $1 is a ticket for the code directory whose hash is $2: it +# carries the `s8ch` magic and, among its listed code directories, that hash. +# Its bytes come from the verified release archive, and Apple's record shows +# the code is notarized, so the stapled ticket only has to be for this code. +is_ticket_for() { + [ "$(head -c 4 "$1")" = s8ch ] || return 1 + ticket_bytes=" $(od -An -v -tx1 "$1" | tr -s ' \n' ' ') " + ticket_hash=" $(printf '%s\n' "$2" | sed 's/../& /g')" + case "$ticket_bytes" in + *"$ticket_hash"*) return 0 ;; + esac + return 1 +} + +# Confirms that Apple's ticket database holds a ticket for the code directory +# whose SHA-256 hash is $3, and that the ticket stapled to the app bundle is +# that ticket or another one for the same code. 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_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 - 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" || \ + is_ticket_for "$ticket_bundle/Contents/CodeResources" "$3"; then + return 0 + fi + echo "ERROR: the notarization ticket stapled to $ticket_label is not a ticket 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 +921,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,20 +955,31 @@ validate_macos_bundle() { return 1 fi - if ! "$MACOS_CODESIGN_TOOL" --verify --strict --verbose=4 "$app_bundle"; then - echo "ERROR: $app_label failed code-signature validation." + if ! "$MACOS_CODESIGN_TOOL" --verify --strict --verbose=4 -R "=$MACOS_CODE_REQUIREMENT" "$app_bundle"; then + echo "ERROR: $app_label failed code-signature and notarization validation." return 1 fi signature_details=$("$MACOS_CODESIGN_TOOL" -dvvv "$app_bundle" 2>&1) || return 1 - signed_team=$(printf '%s\n' "$signature_details" | awk -F= '/^TeamIdentifier=/{print $2}') - signed_identifier=$(printf '%s\n' "$signature_details" | awk -F= '/^Identifier=/{print $2}') + signed_team=$(printf '%s\n' "$signature_details" | sed -n 's/^TeamIdentifier=//p') + signed_identifier=$(printf '%s\n' "$signature_details" | sed -n 's/^Identifier=//p') if [ "$signed_team" != "$EXPECTED_TEAM_ID" ] || [ "$signed_identifier" != "$EXPECTED_BUNDLE_ID" ]; then echo "ERROR: $app_label has an unexpected signing identity." return 1 fi - app_cdhash=$(printf '%s\n' "$signature_details" | awk -F= '/^CDHash=/{print $2}') - if [ -z "$app_cdhash" ]; then - echo "ERROR: $app_label has no code-directory hash." + 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" | sed -n 's/^CDHash=//p') + case "$app_cdhash" in + *[!0123456789abcdef]*|'') + 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 +988,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 +1017,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..094c51555 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 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 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..3e37f4236 --- /dev/null +++ b/scripts/ci/macos-developer-tools.sh @@ -0,0 +1,145 @@ +#!/bin/bash +# Turns a disposable macOS runner into a Mac without Xcode, and optionally +# without the Command Line Tools, so later steps exercise what LPM's users +# have. GitHub-hosted runners come with both. `restore` puts them back so the +# job's post steps, which need git, still work. +set -euo pipefail + +APPLICATIONS_DIR="${MACOS_APPLICATIONS_DIR:-/Applications}" +COMMAND_LINE_TOOLS_DIR="${MACOS_COMMAND_LINE_TOOLS_DIR:-/Library/Developer/CommandLineTools}" +XCODE_SELECT_BIN="${XCODE_SELECT_BIN:-/usr/bin/xcode-select}" +XCRUN_BIN="${XCRUN_BIN:-/usr/bin/xcrun}" +STAPLER_BIN="${STAPLER_BIN:-/usr/bin/stapler}" +GETCONF_BIN="${GETCONF_BIN:-getconf}" +# xcrun caches where tools are in TMPDIR and in the per-user temporary +# directory, which differ when TMPDIR is overridden. +XCRUN_CACHE_DIRS=("${TMPDIR:-/tmp}" "$("$GETCONF_BIN" DARWIN_USER_TEMP_DIR 2>/dev/null || true)") +SUDO="${SUDO-sudo}" + +usage() { + echo "usage: $0 hide | verify | restore " >&2 + exit 64 +} + +fail() { + echo "error: $*" >&2 + exit 1 +} + +require_mode() { + case "${1:-}" in + none | command-line-tools) ;; + *) usage ;; + esac +} + +xcode_apps() { + find "$APPLICATIONS_DIR" -maxdepth 1 -name 'Xcode*.app' \( -type d -o -type l \) -print +} + +# Moves a developer-tools path into the state directory under a name without +# the .app suffix, so Launch Services no longer finds it as Xcode. +hide_path() { + local path="$1" state_dir="$2" + local hidden + hidden="$state_dir/hidden/$(basename "$path").hidden" + $SUDO mv "$path" "$hidden" + printf '%s\t%s\n' "$path" "$hidden" >>"$state_dir/moved" +} + +clear_xcrun_cache() { + local directory + for directory in "${XCRUN_CACHE_DIRS[@]}"; do + if [ -n "$directory" ]; then + rm -f "$directory"/xcrun_db* + fi + done +} + +hide() { + local mode="$1" state_dir="$2" + [ ! -e "$state_dir/moved" ] || fail "$state_dir already records hidden developer tools" + mkdir -p "$state_dir/hidden" + env -u DEVELOPER_DIR "$XCODE_SELECT_BIN" -p >"$state_dir/selected" 2>/dev/null || : >"$state_dir/selected" + : >"$state_dir/moved" + local app + while IFS= read -r app; do + hide_path "$app" "$state_dir" + done < <(xcode_apps) + if [ "$mode" = none ]; then + if [ -e "$COMMAND_LINE_TOOLS_DIR" ]; then + hide_path "$COMMAND_LINE_TOOLS_DIR" "$state_dir" + fi + $SUDO "$XCODE_SELECT_BIN" --reset || true + else + [ -d "$COMMAND_LINE_TOOLS_DIR" ] || fail "this runner has no Command Line Tools at $COMMAND_LINE_TOOLS_DIR" + $SUDO "$XCODE_SELECT_BIN" --switch "$COMMAND_LINE_TOOLS_DIR" + fi + clear_xcrun_cache + verify "$mode" +} + +verify() { + local mode="$1" + [ -z "$(xcode_apps)" ] || fail "Xcode is still installed: $(xcode_apps | tr '\n' ' ')" + if [ "$mode" = none ]; then + [ ! -e "$COMMAND_LINE_TOOLS_DIR" ] || fail "the Command Line Tools are still installed" + if selected=$(env -u DEVELOPER_DIR "$XCODE_SELECT_BIN" -p 2>/dev/null); then + fail "a developer directory is still selected: $selected" + fi + if found=$(env -u DEVELOPER_DIR "$XCRUN_BIN" --find stapler 2>/dev/null); then + fail "xcrun still finds stapler at $found" + fi + else + selected=$(env -u DEVELOPER_DIR "$XCODE_SELECT_BIN" -p) + [ "$selected" = "$COMMAND_LINE_TOOLS_DIR" ] || fail "the selected developer directory is $selected" + # A stapler that runs rejects this directory too, so only the shim's + # own refusal shows that stapler needs Xcode here. + local refusal + refusal=$(env -u DEVELOPER_DIR "$STAPLER_BIN" validate "$COMMAND_LINE_TOOLS_DIR" 2>&1 || true) + case "$refusal" in + *"requires Xcode"*) ;; + *) fail "$STAPLER_BIN did not refuse to run without Xcode: $refusal" ;; + esac + fi + echo "developer tools: $mode" +} + +restore() { + local state_dir="$1" + [ -f "$state_dir/moved" ] || return 0 + local original hidden status=0 + while IFS=$'\t' read -r original hidden; do + $SUDO mv "$hidden" "$original" || status=1 + done < <(tail -r "$state_dir/moved" 2>/dev/null || tac "$state_dir/moved") + local selected + selected=$(cat "$state_dir/selected" 2>/dev/null || true) + if [ -n "$selected" ]; then + $SUDO "$XCODE_SELECT_BIN" --switch "$selected" || status=1 + else + $SUDO "$XCODE_SELECT_BIN" --reset || status=1 + fi + clear_xcrun_cache + [ "$status" -eq 0 ] || fail "some developer tools could not be restored" + rm -f "$state_dir/moved" +} + +case "${1:-}" in +hide) + [ "$#" -eq 3 ] || usage + require_mode "$2" + hide "$2" "$3" + ;; +verify) + [ "$#" -eq 2 ] || usage + require_mode "$2" + verify "$2" + ;; +restore) + [ "$#" -eq 2 ] || usage + restore "$2" + ;; +*) + usage + ;; +esac diff --git a/scripts/ci/test-macos-developer-tools.sh b/scripts/ci/test-macos-developer-tools.sh new file mode 100755 index 000000000..f64ee5988 --- /dev/null +++ b/scripts/ci/test-macos-developer-tools.sh @@ -0,0 +1,153 @@ +#!/bin/bash +set -euo pipefail + +script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +helper="$script_dir/macos-developer-tools.sh" +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT + +fail() { + echo "FAIL: $*" >&2 + exit 1 +} + +# A fake runner: two Xcode installations, a symlink to one of them, an +# unrelated app, the Command Line Tools, and developer-tool commands whose +# answers follow the selected developer directory the way Apple's do. +make_runner() { + rm -rf "$work/runner" "$work/state" + mkdir -p "$work/runner/Applications/Xcode_16.4.app/Contents/Developer/usr/bin" \ + "$work/runner/Applications/Xcode_26.0.app/Contents/Developer/usr/bin" \ + "$work/runner/Applications/Safari.app" \ + "$work/runner/CommandLineTools/usr/bin" "$work/runner/bin" + ln -s "$work/runner/Applications/Xcode_16.4.app" "$work/runner/Applications/Xcode.app" + printf '%s\n' "$work/runner/Applications/Xcode.app/Contents/Developer" >"$work/runner/selected" + cat >"$work/runner/bin/xcode-select" <"$work/runner/selected" + elif [ -d "$work/runner/CommandLineTools" ]; then + echo "$work/runner/CommandLineTools" >"$work/runner/selected" + else + : >"$work/runner/selected" + fi + ;; +--switch) echo "\$2" >"$work/runner/selected" ;; +-p) selected=\$(cat "$work/runner/selected"); [ -n "\$selected" ] && [ -d "\$selected" ] || exit 2; echo "\$selected" ;; +esac +EOF + cat >"$work/runner/bin/xcrun" <"$work/runner/bin/stapler" <&2; exit 1 ;; +esac +EOF + # Like getconf: prints the per-user temporary directory, or nothing when + # getconf-fails exists. + cat >"$work/runner/bin/getconf" </dev/null 2>&1; then + fail "verify accepted a runner that still has Xcode" +fi + +run_helper hide none "$work/state" >/dev/null +[ "$(apps)" = "Safari.app " ] || fail "hiding developer tools left these apps: $(apps)" +[ ! -e "$work/runner/CommandLineTools" ] || fail "the Command Line Tools were not hidden" +if run_helper hide none "$work/state" >/dev/null 2>&1; then + fail "hiding twice would lose track of the first hidden tools" +fi +run_helper restore "$work/state" +[ "$(apps)" = "Safari.app Xcode.app Xcode_16.4.app Xcode_26.0.app " ] || fail "restore left these apps: $(apps)" +[ -L "$work/runner/Applications/Xcode.app" ] || fail "restore did not keep Xcode.app a symlink" +[ -d "$work/runner/CommandLineTools/usr/bin" ] || fail "restore did not bring the Command Line Tools back" +[ "$(cat "$work/runner/selected")" = "$work/runner/Applications/Xcode.app/Contents/Developer" ] \ + || fail "restore did not select Xcode again" +echo "PASS: a runner without developer tools is verified and restored" + +run_helper hide command-line-tools "$work/state" >/dev/null +[ "$(apps)" = "Safari.app " ] || fail "hiding Xcode left these apps: $(apps)" +[ -d "$work/runner/CommandLineTools" ] || fail "the Command Line Tools must stay" +[ "$(cat "$work/runner/selected")" = "$work/runner/CommandLineTools" ] || fail "the Command Line Tools were not selected" +run_helper restore "$work/state" +[ "$(apps)" = "Safari.app Xcode.app Xcode_16.4.app Xcode_26.0.app " ] || fail "restore left these apps: $(apps)" +echo "PASS: a runner with only the Command Line Tools is verified and restored" + +make_runner +: >"$work/runner/working-stapler" +if run_helper hide command-line-tools "$work/state" >/dev/null 2>&1; then + fail "a stapler that runs and merely rejects its input was taken for Apple's Xcode-only shim" +fi +run_helper restore "$work/state" +echo "PASS: a working stapler is not mistaken for a Mac with only the Command Line Tools" + +make_runner +rm -rf "$work/runner/CommandLineTools" +if run_helper hide command-line-tools "$work/state" >/dev/null 2>&1; then + fail "a runner without the Command Line Tools cannot stand for one that has only them" +fi +run_helper restore "$work/state" +echo "PASS: a missing Command Line Tools installation is reported" + +make_runner +run_helper restore "$work/state" +[ "$(apps)" = "Safari.app Xcode.app Xcode_16.4.app Xcode_26.0.app " ] || fail "restore without hidden tools changed apps" +echo "PASS: restore without hidden tools changes nothing" + +make_runner +printf '%s\n' "$work/runner/Applications/Xcode_26.0.app/Contents/Developer" >"$work/runner/selected" +: >"$work/cache dir/xcrun_db" +: >"$work/user temp/xcrun_db" +run_helper hide none "$work/state" >/dev/null +[ ! -e "$work/cache dir/xcrun_db" ] && [ ! -e "$work/user temp/xcrun_db" ] \ + || fail "hiding developer tools left xcrun's cache of their paths" +run_helper restore "$work/state" +[ "$(cat "$work/runner/selected")" = "$work/runner/Applications/Xcode_26.0.app/Contents/Developer" ] \ + || fail "restore selected $(cat "$work/runner/selected") instead of the Xcode selected before" +echo "PASS: restore selects the developer directory selected before" + +make_runner +: >"$work/runner/getconf-fails" +run_helper hide none "$work/state" >/dev/null || fail "hide stopped when getconf named no per-user temporary directory" +run_helper restore "$work/state" || fail "restore stopped when getconf named no per-user temporary directory" +[ "$(apps)" = "Safari.app Xcode.app Xcode_16.4.app Xcode_26.0.app " ] || fail "restore left these apps: $(apps)" +echo "PASS: a missing per-user temporary directory doesn't stop hide or restore" diff --git a/tests/install-sh/run.sh b/tests/install-sh/run.sh index 094727330..341037215 100755 --- a/tests/install-sh/run.sh +++ b/tests/install-sh/run.sh @@ -173,7 +173,9 @@ write_release_asset() { > "$fixture_app/Contents/Info.plist" fi printf 'fixture-profile' > "$fixture_app/Contents/embedded.provisionprofile" - printf 'fixture-notarization-ticket' > "$fixture_app/Contents/CodeResources" + # A ticket for the fixture's code: Apple's `s8ch` magic and the code + # directory hash the fake codesign reports, as raw bytes. + printf 's8ch\017\036\055\074\113\132\151\170\207\226\245\264\303\322\341\360\017\036\055\074fixture-notarization-ticket' > "$fixture_app/Contents/CodeResources" if [ "$include_macos_icon" = "1" ]; then printf 'fixture-icon' > "$fixture_app/Contents/Resources/LPMCLI.icns" fi @@ -199,7 +201,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 od; do src="$(command -v "$tool" 2>/dev/null || true)" if [ -n "$src" ]; then ln -s "$src" "$CLEAN_PATH_DIR/$tool" @@ -227,9 +229,25 @@ 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 + # The downloaded bundle's ticket names its code but lacks Apple's magic. + case "$bundle" in + */extracted/*) + if [ -n "${LPM_TEST_TOOL_STATE:-}" ] && [ -e "$LPM_TEST_TOOL_STATE/unmarked-ticket" ]; then + printf 'xxxx\017\036\055\074\113\132\151\170\207\226\245\264\303\322\341\360\017\036\055\074fixture-notarization-ticket' > "$bundle/Contents/CodeResources" + fi + ;; + esac ;; *" --entitlements "*) printf '%s\n' 'keychain-access-groups823S8YKMRW.dev.lpm.vault.shared' @@ -237,8 +255,15 @@ 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 + 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 @@ -246,16 +271,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 +296,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 +311,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:-}" \ @@ -292,6 +321,7 @@ run_install_sh() { LPM_TEST_COSIGN_REFUSED_TRIGGER="${LPM_TEST_COSIGN_REFUSED_TRIGGER:-}" \ RELEASE_COMMIT="${RELEASE_COMMIT:-}" \ HOME="$install_root" \ + CURL_HOME="$install_root" \ LPM_INSTALL_INSECURE="${LPM_INSTALL_INSECURE:-}" \ LPM_INSTALL_MIN_VERSION_OVERRIDE="${LPM_INSTALL_MIN_VERSION_OVERRIDE:-}" \ LPM_INSTALL_REQUIRE_SIGSTORE="${LPM_INSTALL_REQUIRE_SIGSTORE:-}" \ @@ -391,6 +421,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)" @@ -477,17 +533,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 ───────────────────────────────────────── @@ -758,112 +831,269 @@ 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" + # Apple issues a new ticket when the same code is notarized again; the + # stapled one stands while it is a ticket for this code. + run_with_ticket_outcomes other + [ "$RUN_RC" -eq 0 ] || fail "a ticket Apple issued again for the same code failed the install with exit $RUN_RC: $RUN_OUT" + [ "$TICKET_LOOKUPS" -eq 1 ] || fail "a ticket Apple issued again for the same code was looked up $TICKET_LOOKUPS times" + printf '%s' 'a1b2c3d4e5f60718293a4b5c6d7e8f9001122334' > "$tool_state/cdhash" + run_with_ticket_outcomes other issued + rm -f "$tool_state/cdhash" + [ "$RUN_RC" -ne 0 ] || fail "a stapled ticket for other code must fail the install" + [ "$TICKET_LOOKUPS" -eq 1 ] || fail "a stapled ticket for other code was retried ($TICKET_LOOKUPS lookups)" + echo "$RUN_OUT" | grep -qF "is not a ticket for its code" \ + || fail "a stapled ticket for other code was reported as something else: $RUN_OUT" + [ ! -e "$RUN_INSTALL_DIR/lpm" ] || fail "a stapled ticket for other code must not install anything" + : > "$tool_state/unmarked-ticket" + run_with_ticket_outcomes other issued + rm -f "$tool_state/unmarked-ticket" + [ "$RUN_RC" -ne 0 ] || fail "a stapled file without Apple's ticket magic must fail the install" + echo "$RUN_OUT" | grep -qF "is not a ticket for its code" \ + || fail "a stapled file without Apple's ticket magic was reported as something else: $RUN_OUT" + pass "macOS install takes a ticket Apple issued again for the same code, and no ticket for other code" + + for refusal in \ + "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)" \ + "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)" \ + "multilineerror:refused to look up the ticket of downloaded LPM CLI.app (an unrecognized error)" + 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" + + 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 norecords 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 5 ] || fail "a malformed answer carrying the ticket was taken as an answer ($TICKET_LOOKUPS lookups, expected 5)" + for counted in "1:an answer about another record" "2:an unreadable answer" "1:an unreadable ticket"; do + [ "$(echo "$RUN_OUT" | grep -cF "did not answer (${counted#*:})")" -eq "${counted%%:*}" ] \ + || fail "malformed answers were not retried as ${counted%%:*} x '${counted#*:}': $RUN_OUT" + done + run_with_ticket_outcomes dashticket unpaddedticket notfoundnumericticket issued + [ "$RUN_RC" -eq 0 ] || fail "nonstandard base64 or a malformed field beside NOT_FOUND failed the install with exit $RUN_RC: $RUN_OUT" + [ "$TICKET_LOOKUPS" -eq 4 ] || fail "nonstandard base64 or a malformed field beside NOT_FOUND decided the lookup ($TICKET_LOOKUPS lookups, expected 4)" + for counted in "2:an unreadable ticket" "1:an unreadable answer"; do + [ "$(echo "$RUN_OUT" | grep -cF "did not answer (${counted#*:})")" -eq "${counted%%:*}" ] \ + || fail "nonstandard base64 and a malformed field beside NOT_FOUND were not retried as ${counted%%:*} x '${counted#*:}': $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" + run_with_ticket_outcomes numericfields emptysignedticket nullticketvalue issued + [ "$RUN_RC" -eq 0 ] || fail "malformed ticket containers then a ticket failed the install with exit $RUN_RC: $RUN_OUT" + [ "$TICKET_LOOKUPS" -eq 4 ] || fail "a malformed ticket container decided the lookup ($TICKET_LOOKUPS lookups, expected 4)" + for counted in "2:an unreadable answer" "1:an answer without a ticket"; do + [ "$(echo "$RUN_OUT" | grep -cF "did not answer (${counted#*:})")" -eq "${counted%%:*}" ] \ + || fail "malformed ticket containers were not retried as ${counted%%:*} x '${counted#*:}': $RUN_OUT" + done + 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" + pass "macOS install reads the ticket past JSON nulls in the answer" + + run_with_ticket_outcomes exactcap + [ "$RUN_RC" -eq 0 ] || fail "a 65,536-byte answer failed the install with exit $RUN_RC: $RUN_OUT" + [ "$TICKET_LOOKUPS" -eq 1 ] || fail "a 65,536-byte answer was looked up $TICKET_LOOKUPS times, expected once" + run_with_ticket_outcomes overcap issued + [ "$RUN_RC" -eq 0 ] || fail "a 65,537-byte answer then a ticket failed the install with exit $RUN_RC: $RUN_OUT" + [ "$TICKET_LOOKUPS" -eq 2 ] || fail "a 65,537-byte answer was taken as an answer ($TICKET_LOOKUPS lookups, expected 2)" + echo "$RUN_OUT" | grep -qF "did not answer (an oversized answer)" \ + || fail "a 65,537-byte answer was not reported as oversized: $RUN_OUT" + pass "macOS install reads an answer of up to 65,536 bytes and no more" + + run_with_ticket_outcomes interimonly noreason + [ "$RUN_RC" -eq 0 ] || fail "an interim-only answer then a reasonless 200 failed the install with exit $RUN_RC: $RUN_OUT" + [ "$TICKET_LOOKUPS" -eq 2 ] || fail "an interim-only answer was looked up $TICKET_LOOKUPS times, expected 2 lookups" + echo "$RUN_OUT" | grep -qF "did not answer (HTTP 100)" \ + || fail "an interim-only answer was not retried as HTTP 100: $RUN_OUT" + pass "macOS install retries an interim-only answer and reads a status line without a reason phrase" + + 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" + [ -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 + # may change what the lookup decides. + printf '{"records":[{"recordName":"2/2/0f1e2d3c4b5a69788796a5b4c3d2e1f00f1e2d3c","fields":{"signedTicket":{"value":"%s","type":"BYTES"}}}]}' \ + "$(base64 < "$fdir/.bundle-fixture/LPM CLI.app/Contents/CodeResources")" > "$fdir/redirected-ticket" + curlrc_home="$(mktemp -d)" + printf 'location\nfail\n' > "$curlrc_home/.curlrc" + RUN_INSTALL_ROOT_OVERRIDE="$curlrc_home" + run_with_ticket_outcomes issued + [ "$RUN_RC" -eq 0 ] || fail "with a ~/.curlrc, a confirmed ticket failed the install with exit $RUN_RC: $RUN_OUT" + [ "$TICKET_LOOKUPS" -eq 1 ] || fail "with a ~/.curlrc, a confirmed ticket was looked up $TICKET_LOOKUPS times" + for refusal in "302:(HTTP 302)" "403:(HTTP 403)"; do + outcome="${refusal%%:*}" + run_with_ticket_outcomes "$outcome" issued + [ "$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 + unset RUN_INSTALL_ROOT_OVERRIDE + 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" + [ "$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..76ba60ba3 100755 --- a/tests/install-sh/serve.py +++ b/tests/install-sh/serve.py @@ -14,13 +14,47 @@ 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 +the fixture bundle's stapled ticket), `other` returns another 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, `truncated` closes the connection before its declared length, and +`norecords` names no record, `arraydeleted`/`arrayticket`/`badbase64`/ +`numericticket`/`numericerror`/`numericfields`/`emptysignedticket`/ +`nullticketvalue` carry the issued ticket in a malformed answer, `multilineerror` returns an error code with a +newline, `dashticket`/`unpaddedticket` carry base64 outside the standard +padded alphabet, `notfoundnumericticket` pairs NOT_FOUND with a numeric +ticket, `exactcap`/`overcap` pad an issued +ticket's answer to 65,536 and 65,537 bytes, `interimonly` sends only +`100 Continue`, `noreason` answers `HTTP/1.1 200` without a reason phrase, +`wrongrecord` answers about another record, `garbage` returns a non-JSON +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`). """ +import base64 import http.server +import json import os import socketserver import sys +# The fixture bundle's stapled ticket: Apple's `s8ch` magic and the code +# directory hash the harness's fake codesign reports, as raw bytes. +DEFAULT_TICKET = ( + b"s8ch" + + bytes.fromhex("0f1e2d3c4b5a69788796a5b4c3d2e1f00f1e2d3c") + + b"fixture-notarization-ticket" +) + def main() -> int: if len(sys.argv) != 3: @@ -68,6 +102,152 @@ 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)) + 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 + 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 OSError: + 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 + ticket_value = base64.b64encode(DEFAULT_TICKET).decode("ascii") + issued_record = {"recordName": record_name, "deleted": False, "fields": {"signedTicket": {"value": ticket_value}}} + if outcome in ("exactcap", "overcap"): + size = 65536 if outcome == "exactcap" else 65537 + body = json.dumps({"records": [dict(issued_record, padding="")]}).encode("utf-8") + body = json.dumps({"records": [dict(issued_record, padding="x" * (size - len(body)))]}).encode("utf-8") + assert len(body) == size + self.answer(200, body) + return + if outcome == "interimonly": + self.wfile.write(b"HTTP/1.1 100 Continue\r\n\r\n") + self.wfile.flush() + self.close_connection = True + self.connection.shutdown(2) + return + if outcome == "noreason": + body = json.dumps({"records": [issued_record]}).encode("utf-8") + self.wfile.write(b"HTTP/1.1 200\r\nContent-Type: application/json\r\nContent-Length: " + str(len(body)).encode("ascii") + b"\r\n\r\n" + body) + self.wfile.flush() + self.close_connection = True + 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 = { + "norecords": lambda r: {"records": []}, + "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}})]}, + "numericfields": lambda r: {"records": [dict(r, fields=5, serverErrorCode="ACCESS_DENIED")]}, + "emptysignedticket": lambda r: {"records": [dict(r, fields={"signedTicket": {}}, serverErrorCode="ACCESS_DENIED")]}, + "nullticketvalue": lambda r: {"records": [dict(r, fields={"signedTicket": {"value": None}})]}, + "multilineerror": lambda r: {"records": [dict(r, serverErrorCode="BAD\nCODE")]}, + "dashticket": lambda r: {"records": [dict(r, fields={"signedTicket": {"value": "Zm9v-m9v"}})]}, + "unpaddedticket": lambda r: {"records": [dict(r, fields={"signedTicket": {"value": "YWJjZA"}})]}, + "notfoundnumericticket": lambda r: {"records": [dict(r, serverErrorCode="NOT_FOUND", 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 + 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" + if outcome == "emptyticket": + ticket = b"" + record.update( + recordType="DeveloperIDTicket", + fields={ + "signedTicket": { + "value": base64.b64encode(ticket).decode("ascii"), + "type": "BYTES", + } + }, + 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: + codes = { + "notfound": "NOT_FOUND", + "throttled": "THROTTLED", + "denied": "ACCESS_DENIED", + "emptyerror": "", + "longerror": "A" * 41, + "numericerror": 5, + } + record.update(reason="fixture", serverErrorCode=codes[outcome]) + 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) + 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