diff --git a/.env b/.env index 6ee8f2bb..149c5bd3 100644 --- a/.env +++ b/.env @@ -1,14 +1,4 @@ -# Build a release locally using: op run --env-file="./.env" -- make release -APPLE_DEVELOPER_ID_PKCS12_B64="op://Apple/Apple DeveloperID Application PKCS12 base64/notesPlain" -APPLE_DEVELOPER_ID_PKCS12_PASSWORD="op://Apple/DeveloperID Application p12 password/password" - -APPLE_INSTALLER_PKCS12_B64="op://Apple/Developer ID Installer PKCS12 base64/notesPlain" -APPLE_INSTALLER_PKCS12_PASSWORD="op://Apple/DeveloperID Installer Password/password" - -APPLE_ID="op://Apple/3apcadvvcojjbpxnd7m5fgh5wm/username" -APPLE_ID_PASSWORD="op://Apple/3apcadvvcojjbpxnd7m5fgh5wm/password" - +# Build an unsigned release locally using: op run --env-file="./.env" -- make release +# Release signing happens in CI only; see RELEASING.md. APP_PROF="op://Apple/Provisioning Profiles/profiles/application_base64" EXT_PROF="op://Apple/Provisioning Profiles/profiles/extension_base64" - -SPARKLE_PRIVATE_KEY="op://Apple/Private key for signing Sparkle updates/notesPlain" \ No newline at end of file diff --git a/.github/actions/kms-signing/action.yml b/.github/actions/kms-signing/action.yml new file mode 100644 index 00000000..61e31f1f --- /dev/null +++ b/.github/actions/kms-signing/action.yml @@ -0,0 +1,71 @@ +name: "Set up Cloud KMS signing" +description: | + Prepares a Linux job to run scripts/sign.sh with the Apple Developer ID keys + in Google Cloud KMS: installs the rcodesign built by the release workflow's + rcodesign job and the Cloud KMS PKCS#11 library, and authenticates as + desktop-macos-signer. Only release.yml in the "signing" environment, on main + or a published vX.Y.Z release, can obtain that identity (coder/gcp, + projects/production/coder-release-signing). + + The credentials are not exported to the job's environment: pass + outputs.credentials-file to the signing step only. +outputs: + credentials-file: + description: Google credentials for desktop-macos-signer. + value: ${{ steps.auth.outputs.credentials_file_path }} + pkcs11-library: + description: Path to the Cloud KMS PKCS#11 library. + value: /usr/local/lib/libkmsp11.so + kms-pkcs11-config: + description: Path to the PKCS#11 library's config, naming the apple-codesign key ring. + value: ${{ steps.config.outputs.path }} +runs: + using: "composite" + steps: + - name: Download rcodesign + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: rcodesign + path: ${{ runner.temp }}/rcodesign + + - name: Install rcodesign and the Cloud KMS PKCS#11 library + shell: bash + run: | + set -euo pipefail + sudo install -m 0755 "$RUNNER_TEMP/rcodesign/rcodesign" /usr/local/bin/rcodesign + rcodesign --version + + wget -q -O "$RUNNER_TEMP/libkmsp11.tar.gz" https://github.com/GoogleCloudPlatform/kms-integrations/releases/download/pkcs11-v1.9/libkmsp11-1.9-linux-amd64.tar.gz + echo "5397f965073cd5d1e2c43e5148f102f31a7c835902f97eb41c7c9c0f1b876a40 $RUNNER_TEMP/libkmsp11.tar.gz" | sha256sum -c + sudo tar -xzf "$RUNNER_TEMP/libkmsp11.tar.gz" \ + -C /usr/local/lib \ + --strip-components=1 \ + libkmsp11-1.9-linux-amd64/libkmsp11.so + rm "$RUNNER_TEMP/libkmsp11.tar.gz" + + - name: Write the PKCS#11 library config + id: config + shell: bash + run: | + set -euo pipefail + dir="$RUNNER_TEMP/kms-signing" + rm -rf "$dir" + mkdir -m 700 "$dir" + # The library refuses a config file writable by anyone but the owner. + ( + umask 077 + cat > "$dir/kmsp11.yaml" <> "$GITHUB_OUTPUT" + + - name: Authenticate to Google Cloud + id: auth + uses: google-github-actions/auth@7c6bc770dae815cd3e89ee6cdf493a5fab2cc093 # v3.0.0 + with: + workload_identity_provider: projects/720429782538/locations/global/workloadIdentityPools/github-release-signing/providers/coder-desktop-macos + service_account: desktop-macos-signer@coder-release-signing.iam.gserviceaccount.com + export_environment_variables: false diff --git a/.github/rcodesign/pkcs11-single-init.patch b/.github/rcodesign/pkcs11-single-init.patch new file mode 100644 index 00000000..59e84ede --- /dev/null +++ b/.github/rcodesign/pkcs11-single-init.patch @@ -0,0 +1,307 @@ +Fix PKCS#11 module double-initialization in apple-codesign. + +A PKCS#11 module can only be initialized once per process. rcodesign on +upstream main initializes the module both while resolving the certificate +source and again for each signing operation; the second C_Initialize fails +with CKR_CRYPTOKI_ALREADY_INITIALIZED, which breaks signing with the Google +Cloud KMS PKCS#11 library (and any other PKCS#11 module). + +This is the apple-codesign/src portion of the upstream fix: +https://github.com/indygreg/apple-platform-rs/pull/350 +(head commit 399e5a8e57ba6c35d1c221be7424f6ba3cfddd6b) + +Drop this patch once the pull request lands and the pinned revision in +release.yml is bumped past it. + +diff --git a/apple-codesign/src/cli/certificate_source.rs b/apple-codesign/src/cli/certificate_source.rs +index b7d30c00a..df6babaec 100644 +--- a/apple-codesign/src/cli/certificate_source.rs ++++ b/apple-codesign/src/cli/certificate_source.rs +@@ -29,10 +29,7 @@ use { + }; + + #[cfg(feature = "pkcs11")] +-use { +- crate::pkcs11::Pkcs11PrivateKey, +- cryptoki::context::{CInitializeArgs, CInitializeFlags, Pkcs11}, +-}; ++use crate::pkcs11::{initialized_module, Pkcs11PrivateKey}; + + #[cfg(target_os = "macos")] + use crate::macos::{keychain_find_code_signing_certificates, KeychainDomain}; +@@ -768,10 +765,9 @@ impl KeySource for Pkcs11SigningKey { + None => return Ok(Default::default()), + }; + +- info!("initializing PKCS11 library: {}", library_path.display()); +- +- let pkcs11 = Pkcs11::new(library_path.clone())?; +- pkcs11.initialize(CInitializeArgs::new(CInitializeFlags::OS_LOCKING_OK))?; ++ // Shared with the signing operations that follow: the module can only be ++ // initialized once per process. ++ let pkcs11 = initialized_module(&library_path)?; + + let slots = pkcs11.get_slots_with_token()?; + if slots.is_empty() { +diff --git a/apple-codesign/src/pkcs11.rs b/apple-codesign/src/pkcs11.rs +index bd0219f1a..c931975b3 100644 +--- a/apple-codesign/src/pkcs11.rs ++++ b/apple-codesign/src/pkcs11.rs +@@ -8,6 +8,7 @@ use { + bytes::Bytes, + cryptoki::{ + context::{CInitializeArgs, CInitializeFlags, Pkcs11}, ++ error::RvError, + mechanism::{Mechanism, MechanismType}, + object::{Attribute, AttributeType, ObjectClass, ObjectHandle}, + session::UserType, +@@ -15,7 +16,11 @@ use { + }, + log::{info, warn}, + signature::Signer, +- std::{collections::HashMap, path::PathBuf}, ++ std::{ ++ collections::HashMap, ++ path::{Path, PathBuf}, ++ sync::{LazyLock, Mutex, MutexGuard}, ++ }, + x509_certificate::{ + rfc3447::DigestInfo, CapturedX509Certificate, DigestAlgorithm, KeyAlgorithm, KeyInfoSigner, + Sign, Signature, SignatureAlgorithm, X509CertificateError, +@@ -23,6 +28,114 @@ use { + zeroize::Zeroizing, + }; + ++/// A PKCS#11 module context plus how it came to be initialized. ++struct ModuleContext { ++ context: Pkcs11, ++ ++ /// Whether the `C_Initialize` backing this context was issued by us. ++ /// ++ /// False when the module reported it was already initialized, in which case something ++ /// else owns that initialization and we must not finalize it out from under it. ++ initialized_here: bool, ++} ++ ++/// Process-wide registry of initialized PKCS#11 module contexts, keyed by library path. ++/// ++/// A PKCS#11 module is initialized once per process: `C_Initialize` on a module that is ++/// already initialized fails with `CKR_CRYPTOKI_ALREADY_INITIALIZED`. Certificate resolution ++/// and every signing operation each need a context, so contexts are created once and shared ++/// rather than created on demand. Dropping a [Pkcs11] does not finalize the module (cryptoki ++/// has no finalize-on-drop), so creating them on demand leaves the module initialized and ++/// makes every subsequent initialization fail. ++static MODULE_CONTEXTS: LazyLock>> = ++ LazyLock::new(|| Mutex::new(HashMap::new())); ++ ++/// Key a module by its resolved path so different spellings of the same library share a context. ++fn module_key(library_path: &Path) -> PathBuf { ++ std::fs::canonicalize(library_path).unwrap_or_else(|_| library_path.to_path_buf()) ++} ++ ++fn module_contexts() -> MutexGuard<'static, HashMap> { ++ // The registry has no invariant that a panic could break, so a poisoned lock is usable. ++ MODULE_CONTEXTS.lock().unwrap_or_else(|e| e.into_inner()) ++} ++ ++/// Obtain an initialized context for a PKCS#11 module, initializing it on first use. ++/// ++/// Repeated calls for the same library return the same context. ++pub(crate) fn initialized_module(library_path: &Path) -> Result { ++ let key = module_key(library_path); ++ let mut contexts = module_contexts(); ++ ++ if let Some(existing) = contexts.get(&key) { ++ return Ok(existing.context.clone()); ++ } ++ ++ let context = Pkcs11::new(library_path)?; ++ ++ let initialized_here = ++ match context.initialize(CInitializeArgs::new(CInitializeFlags::OS_LOCKING_OK)) { ++ Ok(()) => { ++ info!("initialized PKCS11 library: {}", library_path.display()); ++ true ++ } ++ // Something else in this process already initialized the module. That ++ // initialization is usable as-is, so adopt it instead of failing. ++ Err(cryptoki::error::Error::Pkcs11(RvError::CryptokiAlreadyInitialized, _)) => { ++ warn!( ++ "PKCS11 library {} is already initialized; reusing that initialization", ++ library_path.display() ++ ); ++ false ++ } ++ Err(e) => return Err(e.into()), ++ }; ++ ++ contexts.insert( ++ key, ++ ModuleContext { ++ context: context.clone(), ++ initialized_here, ++ }, ++ ); ++ ++ Ok(context) ++} ++ ++/// Finalize a PKCS#11 module and forget its context. ++/// ++/// Does nothing when the module is unknown or when its initialization is owned by something ++/// else. A later [initialized_module] call for the same library initializes it again. ++/// ++/// There is no use counting: the first caller to finalize a library finalizes it for every ++/// [Pkcs11PrivateKey] sharing it. The CLI resolves at most one private key, and the ++/// re-initialization above makes that recoverable, so this only matters to embedders ++/// driving several keys on one module. ++pub(crate) fn finalize_module(library_path: &Path) -> Result<(), AppleCodesignError> { ++ let key = module_key(library_path); ++ let mut contexts = module_contexts(); ++ ++ let Some(entry) = contexts.remove(&key) else { ++ return Ok(()); ++ }; ++ ++ if !entry.initialized_here { ++ return Ok(()); ++ } ++ ++ // finalize() consumes the context; clone so `entry` survives a failure. ++ if let Err(e) = entry.context.clone().finalize() { ++ // The module is most likely still initialized and still ours, so keep the entry ++ // rather than orphaning a module nothing can finalize later. ++ contexts.insert(key, entry); ++ return Err(e.into()); ++ } ++ ++ info!("finalized PKCS11 library: {}", library_path.display()); ++ ++ Ok(()) ++} ++ + pub struct Pkcs11PrivateKey { + library_path: PathBuf, + slot_id: u64, +@@ -112,8 +225,7 @@ impl Pkcs11PrivateKey { + where + F: FnOnce(&cryptoki::session::Session) -> Result, + { +- let pkcs11 = Pkcs11::new(&self.library_path)?; +- pkcs11.initialize(CInitializeArgs::new(CInitializeFlags::OS_LOCKING_OK))?; ++ let pkcs11 = initialized_module(&self.library_path)?; + + let slots = pkcs11.get_slots_with_token()?; + let slot = slots +@@ -471,8 +583,13 @@ impl PrivateKey for Pkcs11PrivateKey { + } + + fn finish(&self) -> Result<(), AppleCodesignError> { +- // Could implement cleanup logic here if needed +- // For now, PKCS11 sessions are cleaned up automatically ++ // Sessions close on drop. The module context outlives them and is finalized here so ++ // the process pairs its C_Initialize with a C_Finalize. A module that refuses to ++ // finalize is not a reason to fail a signing run that already wrote its output. ++ if let Err(e) = finalize_module(&self.library_path) { ++ warn!("failed to finalize PKCS11 library: {}", e); ++ } ++ + Ok(()) + } + } +@@ -483,3 +600,95 @@ impl From for AppleCodesignError { + AppleCodesignError::Pkcs11Error(format!("PKCS11 error: {}", err)) + } + } ++ ++#[cfg(test)] ++mod test { ++ use super::*; ++ ++ /// Path to a PKCS#11 module to exercise, if the environment provides one. ++ /// ++ /// Tests below need a real, spec compliant module. Point this at one to run them, e.g. ++ /// `APPLE_CODESIGN_TEST_PKCS11_LIBRARY=/usr/lib/softhsm/libsofthsm2.so`. The module ++ /// does not need an initialized token; only initialization and slot enumeration are ++ /// exercised. ++ /// ++ /// The name deliberately avoids the `RCODESIGN_` prefix, which the CLI consumes as ++ /// configuration and rejects for unknown keys. ++ fn test_library() -> Option { ++ let path = PathBuf::from(std::env::var_os("APPLE_CODESIGN_TEST_PKCS11_LIBRARY")?); ++ ++ if path.exists() { ++ Some(path) ++ } else { ++ panic!( ++ "APPLE_CODESIGN_TEST_PKCS11_LIBRARY does not exist: {}", ++ path.display() ++ ); ++ } ++ } ++ ++ /// Walks the full module lifecycle in one test because the registry is process global. ++ #[test] ++ fn module_context_is_shared_and_finalized() { ++ let Some(library) = test_library() else { ++ eprintln!("skipping: APPLE_CODESIGN_TEST_PKCS11_LIBRARY is not set"); ++ return; ++ }; ++ ++ // Stand in for a module the loader keeps resident: it is already initialized by ++ // the time we ask for a context. Adopting that initialization is what keeps this ++ // from failing with CKR_CRYPTOKI_ALREADY_INITIALIZED. ++ let foreign = Pkcs11::new(&library).unwrap(); ++ foreign ++ .initialize(CInitializeArgs::new(CInitializeFlags::OS_LOCKING_OK)) ++ .unwrap(); ++ ++ let adopted = initialized_module(&library).expect("adopting an initialized module"); ++ adopted ++ .get_slots_with_token() ++ .expect("adopted context works"); ++ ++ // Every later request reuses that context rather than initializing a second time. ++ let reused = initialized_module(&library).expect("reusing the adopted module"); ++ reused.get_slots_with_token().expect("reused context works"); ++ ++ { ++ let contexts = module_contexts(); ++ assert_eq!(contexts.len(), 1, "both requests share one registry entry"); ++ assert!( ++ !contexts.values().next().unwrap().initialized_here, ++ "an adopted initialization is not ours to finalize" ++ ); ++ } ++ ++ // The initialization is not ours, so finalizing must leave it alone. ++ finalize_module(&library).expect("finalize skips a foreign initialization"); ++ foreign ++ .get_slots_with_token() ++ .expect("foreign initialization survived"); ++ foreign.finalize().unwrap(); ++ ++ // Nothing holds the module now, so the next context owns its initialization and ++ // finalizing it is what pairs our C_Initialize with a C_Finalize. ++ let owned = initialized_module(&library).expect("initializing a finalized module"); ++ owned.get_slots_with_token().expect("owned context works"); ++ ++ { ++ let contexts = module_contexts(); ++ assert!( ++ contexts.values().next().unwrap().initialized_here, ++ "we performed this initialization" ++ ); ++ } ++ ++ finalize_module(&library).expect("finalizing our own initialization"); ++ assert!(module_contexts().is_empty(), "finalize forgets the context"); ++ ++ // Finalizing forgets the context, so the module can be initialized again. ++ initialized_module(&library).expect("initializing again after finalize"); ++ finalize_module(&library).unwrap(); ++ ++ // Finalizing a module we know nothing about is a no-op. ++ finalize_module(&library).expect("finalize is idempotent"); ++ } ++} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ce0b0458..d5b2bb42 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -22,11 +22,278 @@ concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: ${{ !contains(github.ref, 'tags/')}} +# The Developer ID Application key lives in Google Cloud KMS, which only Linux +# can reach (through the Cloud KMS PKCS#11 library), so the release alternates +# between macOS and Linux: +# build (macOS) unsigned app +# sign-app (Linux) sign the app with the Developer ID Application certificate +# package (macOS) unsigned installer around the signed app +# sign-pkg (Linux) sign the installer with the Developer ID Installer certificate, notarize, staple +# publish (macOS) Sparkle signature, release assets, appcast +# Only jobs in the "signing" environment get the signing identity, the Developer +# ID Installer key, the App Store Connect key and the Sparkle key. jobs: build: name: Build Coder Desktop runs-on: ${{ github.repository_owner == 'coder' && 'depot-macos-26' || 'macos-26'}} if: ${{ github.repository_owner == 'coder' }} + permissions: + contents: read + outputs: + version: ${{ steps.version.outputs.version }} + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + fetch-tags: true + persist-credentials: false + + - name: Switch XCode Version + uses: maxim-lobanov/setup-xcode@ed7a3b1fda3918c0306d1b724322adc0b8cc0a90 # v1.7.0 + with: + xcode-version: "26.5.0" + + - name: Setup Nix + uses: ./.github/actions/nix-devshell + + - name: Version + id: version + run: echo "version=$(./scripts/version.sh --short)" >> "$GITHUB_OUTPUT" + + - name: Build + env: + APP_PROF: ${{ secrets.CODER_DESKTOP_APP_PROVISIONPROFILE_B64 }} + EXT_PROF: ${{ secrets.CODER_DESKTOP_EXTENSION_PROVISIONPROFILE_B64 }} + run: make release + + # A tar keeps the bundle's symlinks and permissions. + - name: Archive unsigned app + run: tar -C "$out" -cf "$RUNNER_TEMP/unsigned-app.tar" "Coder Desktop.app" + + - name: Upload unsigned app + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: unsigned-app + path: ${{ runner.temp }}/unsigned-app.tar + retention-days: 1 + + - name: Upload dSYMs + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: dsyms + path: ${{ github.workspace }}/outputs/out/coder-desktop-dsyms.zip + retention-days: 1 + + # Built in its own job so the signing jobs don't compile code with signing + # credentials loaded. PKCS#11 support isn't in a published apple-codesign + # release, so build it at a pinned revision, with the fix from + # .github/rcodesign/pkcs11-single-init.patch. + rcodesign: + name: Build rcodesign + runs-on: ubuntu-24.04 + if: ${{ github.repository_owner == 'coder' }} + permissions: + contents: read + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Build rcodesign + env: + RCODESIGN_REV: 0ebbd2ef3b96d5adccc30b1cad4deea38cd735c4 + run: | + set -euo pipefail + rustup toolchain install --profile minimal stable + rustup default stable + src="$RUNNER_TEMP/apple-platform-rs" + git init -q "$src" + git -C "$src" fetch -q --depth 1 https://github.com/indygreg/apple-platform-rs.git "$RCODESIGN_REV" + git -C "$src" checkout -q FETCH_HEAD + git -C "$src" apply "$GITHUB_WORKSPACE/.github/rcodesign/pkcs11-single-init.patch" + cargo install \ + --locked \ + --path "$src/apple-codesign" \ + --features pkcs11 \ + --bin rcodesign \ + --root "$RUNNER_TEMP/rcodesign-install" + mkdir -p "$RUNNER_TEMP/rcodesign" + cp "$RUNNER_TEMP/rcodesign-install/bin/rcodesign" "$RUNNER_TEMP/rcodesign/rcodesign" + + - name: Upload rcodesign + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: rcodesign + path: ${{ runner.temp }}/rcodesign/rcodesign + retention-days: 1 + + sign-app: + name: Sign app + needs: [build, rcodesign] + runs-on: ubuntu-24.04 + environment: signing + permissions: + contents: read + # for the desktop-macos-signer identity + id-token: write + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Set up Cloud KMS signing + id: kms + uses: ./.github/actions/kms-signing + + - name: Download unsigned app + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: unsigned-app + path: ${{ runner.temp }} + + - name: Sign app + env: + PKCS11_LIBRARY: ${{ steps.kms.outputs.pkcs11-library }} + KMS_PKCS11_CONFIG: ${{ steps.kms.outputs.kms-pkcs11-config }} + GOOGLE_APPLICATION_CREDENTIALS: ${{ steps.kms.outputs.credentials-file }} + run: | + set -euo pipefail + work="$RUNNER_TEMP/app" + mkdir -p "$work" + tar -C "$work" -xf "$RUNNER_TEMP/unsigned-app.tar" + ./scripts/sign.sh app "$work/Coder Desktop.app" + tar -C "$work" -cf "$RUNNER_TEMP/signed-app.tar" "Coder Desktop.app" + + - name: Upload signed app + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: signed-app + path: ${{ runner.temp }}/signed-app.tar + retention-days: 1 + + package: + name: Package installer + needs: [build, sign-app] + runs-on: ${{ github.repository_owner == 'coder' && 'depot-macos-26' || 'macos-26'}} + permissions: + contents: read + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Download signed app + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: signed-app + path: ${{ runner.temp }} + + # Check rcodesign's signature with Apple's own tools before shipping it. + - name: Verify app signature + run: | + set -euo pipefail + work="$RUNNER_TEMP/app" + mkdir -p "$work" + tar -C "$work" -xf "$RUNNER_TEMP/signed-app.tar" + app="$work/Coder Desktop.app" + team='anchor apple generic and certificate leaf[subject.OU] = "4399GN35BJ"' + codesign --verify --deep --strict --verbose=2 "$app" + for code in "$app" \ + "$app/Contents/MacOS/com.coder.Coder-Desktop.Helper" \ + "$app/Contents/Library/SystemExtensions/com.coder.Coder-Desktop.VPN.systemextension"; do + codesign --verify --strict -R="$team" "$code" + codesign --display --verbose=2 --entitlements - "$code" + done + + - name: Package + env: + VERSION: ${{ needs.build.outputs.version }} + run: | + ./scripts/package.sh \ + --app "$RUNNER_TEMP/app/Coder Desktop.app" \ + --version "$VERSION" \ + --output "$RUNNER_TEMP/Coder-Desktop.pkg" + + - name: Upload unsigned installer + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: unsigned-pkg + path: ${{ runner.temp }}/Coder-Desktop.pkg + retention-days: 1 + + sign-pkg: + name: Sign and notarize installer + needs: [rcodesign, package] + runs-on: ubuntu-24.04 + environment: signing + permissions: + contents: read + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Download rcodesign + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: rcodesign + path: ${{ runner.temp }}/rcodesign + + - name: Install rcodesign + run: sudo install -m 0755 "$RUNNER_TEMP/rcodesign/rcodesign" /usr/local/bin/rcodesign + + - name: Download unsigned installer + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: unsigned-pkg + path: ${{ runner.temp }}/pkg + + - name: Sign installer + env: + APPLE_INSTALLER_PKCS12_B64: ${{ secrets.APPLE_INSTALLER_PKCS12_B64 }} + APPLE_INSTALLER_PKCS12_PASSWORD: ${{ secrets.APPLE_INSTALLER_PKCS12_PASSWORD }} + run: | + set -euo pipefail + dir="$(mktemp -d)" + trap 'rm -rf "$dir"' EXIT + ( + umask 077 + printf '%s' "$APPLE_INSTALLER_PKCS12_B64" | base64 -d > "$dir/installer.p12" + printf '%s' "$APPLE_INSTALLER_PKCS12_PASSWORD" > "$dir/installer.pw" + ) + INSTALLER_P12_FILE="$dir/installer.p12" INSTALLER_P12_PASSWORD_FILE="$dir/installer.pw" \ + ./scripts/sign.sh pkg "$RUNNER_TEMP/pkg/Coder-Desktop.pkg" + + - name: Notarize installer + env: + AC_APIKEY_ISSUER_ID: ${{ secrets.AC_APIKEY_ISSUER_ID }} + AC_APIKEY_ID: ${{ secrets.AC_APIKEY_ID }} + AC_APIKEY_P8_BASE64: ${{ secrets.AC_APIKEY_P8_BASE64 }} + run: | + set -euo pipefail + export AC_APIKEY_FILE="$RUNNER_TEMP/apple_apikey.p8" + trap 'rm -f "$AC_APIKEY_FILE"' EXIT + (umask 077 && printf '%s' "$AC_APIKEY_P8_BASE64" | base64 -d > "$AC_APIKEY_FILE") + ./scripts/notarize.sh "$RUNNER_TEMP/pkg/Coder-Desktop.pkg" + + - name: Upload signed installer + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: signed-pkg + path: ${{ runner.temp }}/pkg/Coder-Desktop.pkg + retention-days: 1 + + publish: + name: Publish + needs: [build, sign-pkg] + runs-on: ${{ github.repository_owner == 'coder' && 'depot-macos-26' || 'macos-26'}} + # Holds the Sparkle update signing key. + environment: signing permissions: # To upload assets to the release contents: write @@ -48,29 +315,39 @@ jobs: - name: Setup Nix uses: ./.github/actions/nix-devshell - - name: Authenticate to Google Cloud - id: gcloud_auth - uses: google-github-actions/auth@7c6bc770dae815cd3e89ee6cdf493a5fab2cc093 # v3.0.0 + - name: Download signed installer + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: - workload_identity_provider: ${{ secrets.GCP_WORKLOAD_ID_PROVIDER }} - service_account: ${{ secrets.GCP_SERVICE_ACCOUNT }} - token_format: "access_token" + name: signed-pkg + path: ${{ github.workspace }}/outputs/out - - name: Setup GCloud SDK - uses: google-github-actions/setup-gcloud@aa5489c8933f4cc7a4f7d45035b3b1440c9c10db # v3.0.1 + - name: Download dSYMs + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: dsyms + path: ${{ github.workspace }}/outputs/out - - name: Build + - name: Verify installer + run: | + set -euo pipefail + pkgutil --check-signature "$out/Coder-Desktop.pkg" + xcrun stapler validate "$out/Coder-Desktop.pkg" + spctl --assess --type install --verbose=2 "$out/Coder-Desktop.pkg" + + # sign_update comes from the Sparkle release the app links, checked + # against the checksum in Sparkle's Package.swift that SwiftPM verifies. + - name: Sign update env: - APPLE_DEVELOPER_ID_PKCS12_B64: ${{ secrets.APPLE_DEVELOPER_ID_PKCS12_B64 }} - APPLE_DEVELOPER_ID_PKCS12_PASSWORD: ${{ secrets.APPLE_DEVELOPER_ID_PKCS12_PASSWORD }} - APPLE_INSTALLER_PKCS12_B64: ${{ secrets.APPLE_INSTALLER_PKCS12_B64 }} - APPLE_INSTALLER_PKCS12_PASSWORD: ${{ secrets.APPLE_INSTALLER_PKCS12_PASSWORD }} - APPLE_ID: ${{ secrets.APPLE_NOTARYTOOL_USERNAME }} - APPLE_ID_PASSWORD: ${{ secrets.APPLE_NOTARYTOOL_PASSWORD }} - APP_PROF: ${{ secrets.CODER_DESKTOP_APP_PROVISIONPROFILE_B64 }} - EXT_PROF: ${{ secrets.CODER_DESKTOP_EXTENSION_PROVISIONPROFILE_B64 }} SPARKLE_PRIVATE_KEY: ${{ secrets.SPARKLE_PRIVATE_KEY }} - run: make release + run: | + set -euo pipefail + sparkle="$RUNNER_TEMP/sparkle" + mkdir -p "$sparkle" + curl -fsSL -o "$sparkle/sparkle.zip" https://github.com/sparkle-project/Sparkle/releases/download/2.7.0/Sparkle-for-Swift-Package-Manager.zip + echo "a1fb05c4fd6b73bc351f4d326e6171473b7a99b7f2bfa8f5f69f7281f66dc387 $sparkle/sparkle.zip" | shasum -a 256 -c + unzip -q "$sparkle/sparkle.zip" bin/sign_update -d "$sparkle" + signature=$(printf '%s' "$SPARKLE_PRIVATE_KEY" | "$sparkle/bin/sign_update" "$out/Coder-Desktop.pkg" --ed-key-file -) + echo "$signature" > "$out/Coder-Desktop.pkg.sig" # Upload as artifact in dry-run mode - name: Upload Build Artifact @@ -81,6 +358,18 @@ jobs: path: ${{ github.workspace }}/outputs/out retention-days: 7 + - name: Authenticate to Google Cloud + if: ${{ !inputs.dryrun }} + uses: google-github-actions/auth@7c6bc770dae815cd3e89ee6cdf493a5fab2cc093 # v3.0.0 + with: + workload_identity_provider: ${{ secrets.GCP_WORKLOAD_ID_PROVIDER }} + service_account: ${{ secrets.GCP_SERVICE_ACCOUNT }} + token_format: "access_token" + + - name: Setup GCloud SDK + if: ${{ !inputs.dryrun }} + uses: google-github-actions/setup-gcloud@aa5489c8933f4cc7a4f7d45035b3b1440c9c10db # v3.0.1 + # Upload to release in non-dry-run mode - name: Upload Release Assets if: ${{ !inputs.dryrun }} @@ -109,7 +398,7 @@ jobs: name: Update homebrew-coder cask runs-on: ${{ github.repository_owner == 'coder' && 'depot-macos-26' || 'macos-26'}} if: ${{ github.repository_owner == 'coder' && github.event_name == 'release' }} - needs: build + needs: publish # Holds the coder-package-publisher App key; release tags only, approved by a release manager. environment: release-publish steps: diff --git a/Makefile b/Makefile index 4172f04d..e2ea6074 100644 --- a/Makefile +++ b/Makefile @@ -55,11 +55,6 @@ ifeq ($(strip $(GIT_COMMIT_HASH)),) $(error GIT_COMMIT_HASH cannot be empty) endif -# Define the keychain file name first -KEYCHAIN_FILE := app-signing.keychain-db -# Use shell to get the absolute path only if the file exists -APP_SIGNING_KEYCHAIN := $(if $(wildcard $(KEYCHAIN_FILE)),$(shell realpath $(KEYCHAIN_FILE)),$(abspath $(KEYCHAIN_FILE))) - .PHONY: setup setup: \ $(addprefix $(PROJECT)/Resources/,$(MUTAGEN_RESOURCES)) \ @@ -93,22 +88,8 @@ $(MUTAGEN_PROTO_SWIFTS): --grpc-swift_out=$(PROJECT)/VPNLib/FileSync/MutagenSDK \ $(patsubst %.pb.swift,%.proto,$@) -$(KEYCHAIN_FILE): - security create-keychain -p "" "$(APP_SIGNING_KEYCHAIN)" - security set-keychain-settings -lut 21600 "$(APP_SIGNING_KEYCHAIN)" - security unlock-keychain -p "" "$(APP_SIGNING_KEYCHAIN)" - @tempfile=$$(mktemp); \ - echo "$$APPLE_DEVELOPER_ID_PKCS12_B64" | base64 -d > $$tempfile; \ - security import $$tempfile -P '$(APPLE_DEVELOPER_ID_PKCS12_PASSWORD)' -A -t cert -f pkcs12 -k "$(APP_SIGNING_KEYCHAIN)"; \ - rm $$tempfile - @tempfile=$$(mktemp); \ - echo "$$APPLE_INSTALLER_PKCS12_B64" | base64 -d > $$tempfile; \ - security import $$tempfile -P '$(APPLE_INSTALLER_PKCS12_PASSWORD)' -A -t cert -f pkcs12 -k "$(APP_SIGNING_KEYCHAIN)"; \ - rm $$tempfile - security list-keychains -d user -s $$(security list-keychains -d user | tr -d '\"') "$(APP_SIGNING_KEYCHAIN)" - .PHONY: release -release: $(KEYCHAIN_FILE) ## Create a release build of Coder Desktop +release: ## Build an unsigned release of Coder Desktop (signed by scripts/sign.sh) @APP_PROF_PATH="$$(mktemp)"; \ EXT_PROF_PATH="$$(mktemp)"; \ echo -n "$$APP_PROF" | base64 -d > "$$APP_PROF_PATH"; \ @@ -116,9 +97,7 @@ release: $(KEYCHAIN_FILE) ## Create a release build of Coder Desktop ./scripts/build.sh \ --app-prof-path "$$APP_PROF_PATH" \ --ext-prof-path "$$EXT_PROF_PATH" \ - --version $(MARKETING_VERSION) \ - --keychain "$(APP_SIGNING_KEYCHAIN)" \ - --sparkle-private-key "$$SPARKLE_PRIVATE_KEY"; \ + --version $(MARKETING_VERSION); \ rm "$$APP_PROF_PATH" "$$EXT_PROF_PATH" .PHONY: fmt @@ -153,7 +132,7 @@ lint/actions: ## Lint GitHub Actions zizmor . .PHONY: clean -clean: clean/project clean/keychain clean/build clean/mutagen ## Clean project and artifacts +clean: clean/project clean/build clean/mutagen ## Clean project and artifacts .PHONY: clean/project clean/project: @@ -164,14 +143,6 @@ clean/project: fi find . -name "*.entitlements" -type f -delete -.PHONY: clean/keychain -clean/keychain: - @if [ -e "$(APP_SIGNING_KEYCHAIN)" ]; then \ - echo "Cleaning keychain: '$(APP_SIGNING_KEYCHAIN)'"; \ - security delete-keychain "$(APP_SIGNING_KEYCHAIN)"; \ - rm -f "$(APP_SIGNING_KEYCHAIN)"; \ - fi - .PHONY: clean/build clean/build: rm -rf build/ release/ $$out diff --git a/RELEASING.md b/RELEASING.md index 650da52b..968f0d25 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -28,6 +28,53 @@ point at. [homebrew-coder](https://github.com/coder/homebrew-coder) cask. Wait for it to finish, then review and merge the cask pull request. +## Signing + +The Developer ID Application private key is the one coder/coder signs with. It +lives in Google Cloud KMS (`coder-release-signing` project, +`apple-codesign/developer-id-application`, managed in coder/gcp) and cannot be +exported. Apple's `codesign` can't use it, so `release.yml` signs on Linux with +[rcodesign](https://github.com/indygreg/apple-platform-rs) through the Cloud +KMS PKCS#11 library. The installer is signed with the Developer ID Installer +certificate and key from a PKCS#12 file in the `signing` environment. + +1. `build` (macOS) builds the app without signing it (`scripts/build.sh`). +2. `sign-app` (Linux) signs it with the Developer ID Application certificate + (`scripts/sign.sh app`). +3. `package` (macOS) checks the signature with `codesign` and builds the + installer (`scripts/package.sh`). +4. `sign-pkg` (Linux) signs the installer with the Developer ID Installer + certificate (`scripts/sign.sh pkg`), then notarizes and staples it + (`scripts/notarize.sh`). +5. `publish` (macOS) checks the installer with `spctl`, signs the Sparkle + update and publishes. + +Only jobs in the `signing` environment can use the keys, and only on `main` +or a published `vX.Y.Z` release. That environment holds: + +| Secret | Value | +| --------------------------------- | -------------------------------------------------- | +| `APPLE_INSTALLER_PKCS12_B64` | Developer ID Installer PKCS#12, base64-encoded | +| `APPLE_INSTALLER_PKCS12_PASSWORD` | Its password | +| `AC_APIKEY_ISSUER_ID` | App Store Connect API key issuer ID (notarization) | +| `AC_APIKEY_ID` | App Store Connect API key ID | +| `AC_APIKEY_P8_BASE64` | The API key's `.p8` file, base64-encoded | +| `SPARKLE_PRIVATE_KEY` | Sparkle EdDSA update signing key | + +The Application certificate is public and committed in `signing/`, with the +entitlements each executable is signed with in `signing/entitlements/`. If you +change an entitlement in `Coder-Desktop/project.yml`, change it there too: +release builds are signed with those files, not with Xcode's. + +To try `scripts/sign.sh` without the real keys, sign with a throwaway +certificate (it won't pass Gatekeeper, but shows what gets signed and how): + +```bash +rcodesign generate-self-signed-certificate --person-name test --p12-file test.p12 --p12-password test +printf test > test.pw +P12_FILE=test.p12 P12_PASSWORD_FILE=test.pw ./scripts/sign.sh app "path/to/Coder Desktop.app" +``` + ## Updating provisioning profiles Release builds are signed with two provisioning profiles, one for the app @@ -55,5 +102,6 @@ When a profile expires or needs regenerating: **Secrets and variables** > **Actions**. To check new profiles before cutting a release, run the `release` workflow -manually with **dryrun** enabled. The build is uploaded as a workflow artifact -instead of a release asset. +manually on `main` with **dryrun** enabled. The build is signed, notarized and +uploaded as a workflow artifact instead of a release asset. The signing jobs +only run on `main`, so a dry run from another branch stops after `build`. diff --git a/scripts/build.sh b/scripts/build.sh index e1589dbb..2762d7c6 100755 --- a/scripts/build.sh +++ b/scripts/build.sh @@ -1,35 +1,27 @@ #!/usr/bin/env bash +# Builds an unsigned release of Coder Desktop: "$out/Coder Desktop.app", with +# its provisioning profiles embedded, and "$out/coder-desktop-dsyms.zip". +# +# The app is signed afterwards by ./scripts/sign.sh, which runs on Linux +# because the Developer ID keys live in Google Cloud KMS, and then packaged by +# ./scripts/package.sh. set -euo pipefail # Add standard Nix environment variables out="${out:-release}" -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -# Build Documentation @ https://developer.apple.com/forums/thread/737894 -APPLE_TEAM_ID="4399GN35BJ" -CODE_SIGN_IDENTITY="Developer ID Application: Coder Technologies Inc (${APPLE_TEAM_ID})" -CODE_SIGN_INSTALLER_IDENTITY="Developer ID Installer: Coder Technologies Inc (${APPLE_TEAM_ID})" -PKG_SCRIPTS="$SCRIPT_DIR/../pkgbuild/scripts/" - -# Default values pulled in from env APP_PROF_PATH=${APP_PROF_PATH:-""} EXT_PROF_PATH=${EXT_PROF_PATH:-""} -KEYCHAIN=${KEYCHAIN:-""} VERSION=${VERSION:-""} -SPARKLE_PRIVATE_KEY=${SPARKLE_PRIVATE_KEY:-""} -# Function to display usage usage() { - echo "Usage: $0 [--app-prof-path ] [--ext-prof-path ] [--keychain ]" - echo " --app-prof-path Set the APP_PROF_PATH variable" - echo " --ext-prof-path Set the EXT_PROF_PATH variable" - echo " --keychain Set the KEYCHAIN variable" - echo " --sparkle-private-key Set the SPARKLE_PRIVATE_KEY variable" - echo " --version Set the VERSION variable to fetch and generate the cask file for" - echo " -h, --help Display this help message" + echo "Usage: $0 --app-prof-path --ext-prof-path --version " + echo " --app-prof-path Provisioning profile for the app" + echo " --ext-prof-path Provisioning profile for the network extension" + echo " --version Version being built, without a leading 'v'" + echo " -h, --help Display this help message" } -# Parse command line arguments while [[ "$#" -gt 0 ]]; do case $1 in --app-prof-path) @@ -40,14 +32,6 @@ while [[ "$#" -gt 0 ]]; do EXT_PROF_PATH="$2" shift 2 ;; - --keychain) - KEYCHAIN="$2" - shift 2 - ;; - --sparkle-private-key) - SPARKLE_PRIVATE_KEY="$2" - shift 2 - ;; --version) VERSION="$2" shift 2 @@ -64,18 +48,16 @@ while [[ "$#" -gt 0 ]]; do esac done -# Check if required variables are set -if [[ -z "$APP_PROF_PATH" || -z "$EXT_PROF_PATH" || -z "$KEYCHAIN" || -z "$SPARKLE_PRIVATE_KEY" ]]; then +if [[ -z "$APP_PROF_PATH" || -z "$EXT_PROF_PATH" ]]; then echo "Missing required values" echo "APP_PROF_PATH: $APP_PROF_PATH" echo "EXT_PROF_PATH: $EXT_PROF_PATH" - echo "KEYCHAIN: $KEYCHAIN" echo usage exit 1 fi -# Assert version is not empty and starts with v +# Assert version is not empty and starts with a number [ -z "$VERSION" ] && { echo "Error: VERSION cannot be empty" echo @@ -90,41 +72,19 @@ fi exit 1 } -XCODE_PROVISIONING_PROFILES_DIR="$HOME/Library/Developer/Xcode/UserData/Provisioning Profiles" -ALT_PROVISIONING_PROFILES_DIR="$HOME/Library/MobileDevice/Provisioning Profiles" -mkdir -p "$XCODE_PROVISIONING_PROFILES_DIR" -mkdir -p "$ALT_PROVISIONING_PROFILES_DIR" - -get_uuid() { - strings "$1" | grep -E -o '[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}' -} - -# Extract the ID of each provisioning profile -APP_PROVISIONING_PROFILE_ID=$(get_uuid "$APP_PROF_PATH") -EXT_PROVISIONING_PROFILE_ID=$(get_uuid "$EXT_PROF_PATH") -PTP_SUFFIX="-systemextension" - -# Install Provisioning Profiles -cp "$APP_PROF_PATH" "${XCODE_PROVISIONING_PROFILES_DIR}/${APP_PROVISIONING_PROFILE_ID}.provisionprofile" -cp "$APP_PROF_PATH" "${ALT_PROVISIONING_PROFILES_DIR}/${APP_PROVISIONING_PROFILE_ID}.provisionprofile" -cp "$EXT_PROF_PATH" "${XCODE_PROVISIONING_PROFILES_DIR}/${EXT_PROVISIONING_PROFILE_ID}.provisionprofile" -cp "$EXT_PROF_PATH" "${ALT_PROVISIONING_PROFILES_DIR}/${EXT_PROVISIONING_PROFILE_ID}.provisionprofile" - -export APP_PROVISIONING_PROFILE_ID -export EXT_PROVISIONING_PROFILE_ID -export PTP_SUFFIX +# Populated at `xcodegen` time. +export PTP_SUFFIX="-systemextension" make clean/project clean/build make -mkdir -p "$out" -mkdir build +mkdir -p "$out" build +out="$(cd "$out" && pwd)" -# Archive the app ARCHIVE_PATH="./build/Coder-Desktop.xcarchive" -mkdir -p build +# Signing happens later, with rcodesign, so Xcode only builds. xcodebuild \ -project "Coder-Desktop/Coder-Desktop.xcodeproj" \ -scheme "Coder Desktop" \ @@ -133,76 +93,23 @@ xcodebuild \ archive \ -skipMacroValidation \ -skipPackagePluginValidation \ - CODE_SIGN_STYLE=Manual \ - CODE_SIGN_IDENTITY="$CODE_SIGN_IDENTITY" \ - CODE_SIGN_INJECT_BASE_ENTITLEMENTS=NO \ - CODE_SIGN_ALLOW_ENTITLEMENTS_MODIFICATION=YES \ - OTHER_CODE_SIGN_FLAGS='--timestamp' | xcbeautify - -# Create exportOptions.plist -EXPORT_OPTIONS_PATH="./build/exportOptions.plist" -cat >"$EXPORT_OPTIONS_PATH" < - - - - method - developer-id - teamID - ${APPLE_TEAM_ID} - signingStyle - manual - provisioningProfiles - - com.coder.Coder-Desktop - ${APP_PROVISIONING_PROFILE_ID} - com.coder.Coder-Desktop.VPN - ${EXT_PROVISIONING_PROFILE_ID} - - - -EOF - -# Export the archive -EXPORT_PATH="./build/export" -xcodebuild \ - -exportArchive \ - -archivePath "$ARCHIVE_PATH" \ - -exportOptionsPlist "$EXPORT_OPTIONS_PATH" \ - -exportPath "$EXPORT_PATH" + CODE_SIGNING_REQUIRED=NO \ + CODE_SIGNING_ALLOWED=NO | xcbeautify + +BUILT_APP_PATH="$(find "$ARCHIVE_PATH/Products" -maxdepth 3 -type d -name "Coder Desktop.app" -print -quit)" +[[ -n "$BUILT_APP_PATH" ]] || { + echo "Error: no Coder Desktop.app in $ARCHIVE_PATH/Products" + exit 1 +} -BUILT_APP_PATH="$EXPORT_PATH/Coder Desktop.app" -PKG_PATH="$out/Coder-Desktop.pkg" +APP_PATH="$out/Coder Desktop.app" DSYM_ZIPPED_PATH="$out/coder-desktop-dsyms.zip" -APP_ZIPPED_PATH="$out/coder-desktop-universal.zip" - -pkgbuild --component "$BUILT_APP_PATH" \ - --scripts "$PKG_SCRIPTS" \ - --identifier "com.coder.Coder-Desktop" \ - --version "$VERSION" \ - --install-location "/Applications/" \ - --timestamp \ - --sign "$CODE_SIGN_INSTALLER_IDENTITY" \ - "$PKG_PATH" - -# Notarize -xcrun notarytool store-credentials "notarytool-credentials" \ - --apple-id "$APPLE_ID" \ - --team-id "$APPLE_TEAM_ID" \ - --password "$APPLE_ID_PASSWORD" \ - --keychain "$KEYCHAIN" - -xcrun notarytool submit "$PKG_PATH" \ - --keychain-profile "notarytool-credentials" \ - --keychain "$KEYCHAIN" \ - --wait - -# Staple the notarization to the app and pkg, so they work without internet -xcrun stapler staple "$PKG_PATH" -xcrun stapler staple "$BUILT_APP_PATH" - -signature=$(echo "$SPARKLE_PRIVATE_KEY" | ~/Library/Developer/Xcode/DerivedData/Coder-Desktop-*/SourcePackages/artifacts/sparkle/Sparkle/bin/sign_update "$PKG_PATH" --ed-key-file -) -echo "$signature" >"$PKG_PATH.sig" + +ditto "$BUILT_APP_PATH" "$APP_PATH" + +# Xcode embeds the provisioning profiles when it signs; we don't let it. +cp "$APP_PROF_PATH" "$APP_PATH/Contents/embedded.provisionprofile" +cp "$EXT_PROF_PATH" "$APP_PATH/Contents/Library/SystemExtensions/com.coder.Coder-Desktop.VPN.systemextension/Contents/embedded.provisionprofile" # Add dsym to build artifacts (cd "$ARCHIVE_PATH/dSYMs" && zip -9 -r --symlinks "$DSYM_ZIPPED_PATH" ./*) diff --git a/scripts/notarize.sh b/scripts/notarize.sh new file mode 100755 index 00000000..c9854cab --- /dev/null +++ b/scripts/notarize.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +# Notarizes a signed installer with Apple and staples the ticket to it, using +# rcodesign so it can run on Linux next to ./scripts/sign.sh. +# +# Usage: ./scripts/notarize.sh path/to/Coder-Desktop.pkg +# +# Requires the App Store Connect API key in: +# - $AC_APIKEY_ISSUER_ID: the key's issuer UUID +# - $AC_APIKEY_ID: the key ID +# - $AC_APIKEY_FILE: the path to the key's .p8 file +set -euo pipefail + +[[ $# -eq 1 ]] || { + echo "Usage: $0 path/to/Coder-Desktop.pkg" >&2 + exit 1 +} +: "${AC_APIKEY_ISSUER_ID:?}" "${AC_APIKEY_ID:?}" "${AC_APIKEY_FILE:?}" + +key_file="$(mktemp)" +chmod 600 "$key_file" +trap 'rm -f "$key_file"' EXIT +rcodesign encode-app-store-connect-api-key \ + "$AC_APIKEY_ISSUER_ID" \ + "$AC_APIKEY_ID" \ + "$AC_APIKEY_FILE" \ + >"$key_file" + +# Apple's notary service fails intermittently, so try twice. +attempts=2 +for i in $(seq 1 "$attempts"); do + rc=0 + rcodesign notary-submit \ + --api-key-file "$key_file" \ + --wait \ + --staple \ + "$1" && break || rc=$? + echo "rcodesign notary-submit exited with $rc" >&2 + if [[ $i -lt $attempts ]]; then + echo "Retrying in 30 seconds" >&2 + sleep 30 + fi +done +exit "$rc" diff --git a/scripts/package.sh b/scripts/package.sh new file mode 100755 index 00000000..f2b1a8df --- /dev/null +++ b/scripts/package.sh @@ -0,0 +1,56 @@ +#!/usr/bin/env bash +# Packages a signed Coder Desktop.app into an unsigned installer. The installer +# is signed afterwards by ./scripts/sign.sh, which runs on Linux because the +# Developer ID keys live in Google Cloud KMS. +# +# Usage: ./scripts/package.sh --app "path/to/Coder Desktop.app" --version --output path/to/Coder-Desktop.pkg +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PKG_SCRIPTS="$SCRIPT_DIR/../pkgbuild/scripts/" + +APP_PATH="" +VERSION="" +OUTPUT="" + +usage() { + echo "Usage: $0 --app --version --output " +} + +while [[ "$#" -gt 0 ]]; do + case $1 in + --app) + APP_PATH="$2" + shift 2 + ;; + --version) + VERSION="$2" + shift 2 + ;; + --output) + OUTPUT="$2" + shift 2 + ;; + -h | --help) + usage + exit 0 + ;; + *) + echo "Unknown parameter passed: $1" + usage + exit 1 + ;; + esac +done + +if [[ -z "$APP_PATH" || -z "$VERSION" || -z "$OUTPUT" ]]; then + usage + exit 1 +fi + +pkgbuild --component "$APP_PATH" \ + --scripts "$PKG_SCRIPTS" \ + --identifier "com.coder.Coder-Desktop" \ + --version "$VERSION" \ + --install-location "/Applications/" \ + "$OUTPUT" diff --git a/scripts/sign.sh b/scripts/sign.sh new file mode 100755 index 00000000..17b8cdca --- /dev/null +++ b/scripts/sign.sh @@ -0,0 +1,134 @@ +#!/usr/bin/env bash +# Signs a Coder Desktop release with rcodesign. CI runs this on Linux: the +# Developer ID Application private key lives in Google Cloud KMS, which Apple's +# codesign can't use. +# +# Usage: +# ./scripts/sign.sh app "path/to/Coder Desktop.app" +# ./scripts/sign.sh pkg path/to/Coder-Desktop.pkg +# +# `app` signs, in place, an app built by ./scripts/build.sh (unsigned, with its +# provisioning profiles embedded) with the Developer ID Application +# certificate. Coder's own executables get the hardened runtime and the +# entitlements in signing/entitlements. Prebuilt executables (Sparkle, mutagen, +# the Swift runtime) keep the identifier, flags and entitlements they were +# built with. The key comes from one of: +# - Google Cloud KMS, through the Cloud KMS PKCS#11 library: set +# $PKCS11_LIBRARY to libkmsp11.so (rcodesign must be built with the +# "pkcs11" feature) and $KMS_PKCS11_CONFIG to the library's config naming +# the apple-codesign key ring. Google credentials that can sign with the +# developer-id-application key must be available, e.g. via +# $GOOGLE_APPLICATION_CREDENTIALS. The certificate is +# signing/developer-id-application.pem. +# - A PKCS#12 file, to try signing with a throwaway certificate: set +# $P12_FILE and $P12_PASSWORD_FILE. +# +# `pkg` signs, in place, an installer built by ./scripts/package.sh with the +# Developer ID Installer certificate and key in the PKCS#12 file +# $INSTALLER_P12_FILE, whose password is in $INSTALLER_P12_PASSWORD_FILE. +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" + +die() { + echo "error: $*" >&2 + exit 1 +} + +[[ $# -eq 2 ]] || die "usage: $0 app|pkg PATH" +kind="$1" +target="$2" +command -v rcodesign >/dev/null || die "rcodesign is not installed" + +# app_key_args prints the rcodesign arguments selecting the Developer ID +# Application key. +app_key_args() { + if [[ -n "${PKCS11_LIBRARY:-}" ]]; then + [[ -n "${KMS_PKCS11_CONFIG:-}" ]] || die "KMS_PKCS11_CONFIG must be set with PKCS11_LIBRARY" + printf '%s\0' \ + --pkcs11-library "$PKCS11_LIBRARY" \ + --pkcs11-key-label developer-id-application \ + --pkcs11-certificate-file "$ROOT/signing/developer-id-application.pem" + elif [[ -n "${P12_FILE:-}" ]]; then + printf '%s\0' --p12-file "$P12_FILE" --p12-password-file "${P12_PASSWORD_FILE:?}" + else + die "set PKCS11_LIBRARY or P12_FILE" + fi +} +# is_macho FILE succeeds if FILE is a Mach-O or universal binary. +is_macho() { + case "$(head -c 4 "$1" | od -An -tx1 | tr -d ' \n')" in + cafebabe | feedface | feedfacf | cefaedfe | cffaedfe) return 0 ;; + *) return 1 ;; + esac +} + +sign_app() { + local app="$1" + local vpn="Contents/Library/SystemExtensions/com.coder.Coder-Desktop.VPN.systemextension" + local helper="Contents/MacOS/com.coder.Coder-Desktop.Helper" + local ent="$ROOT/signing/entitlements" + + [[ -f "$app/Contents/embedded.provisionprofile" ]] || die "$app has no provisioning profile" + [[ -f "$app/$vpn/Contents/embedded.provisionprofile" ]] || die "$app/$vpn has no provisioning profile" + + local -a args + mapfile -d '' args < <(app_key_args) + + # Coder's executables. A path scope applies to the bundle or binary at that + # path; an unscoped setting applies to the app's main executable. + args+=( + --code-signature-flags runtime + --entitlements-xml-file "$ent/app.plist" + --code-signature-flags "$helper:runtime" + --entitlements-xml-file "$helper:$ent/helper.plist" + --code-signature-flags "$vpn:runtime" + --entitlements-xml-file "$vpn:$ent/vpn.plist" + --code-signature-flags "$vpn/Contents/Frameworks/VPNLib.framework/Versions/A:runtime" + --code-signature-flags "$vpn/Contents/Frameworks/CoderSDK.framework/Versions/A:runtime" + ) + + # rcodesign names a bundle's main executable after its CFBundleIdentifier and + # any other binary after its file name, which would rename prebuilt binaries + # such as Sparkle's Autoupdate. Keep the identifier of every binary that was + # already signed by something other than the linker; Xcode did the same. + local file rel info id + while IFS= read -r -d '' file; do + is_macho "$file" || continue + rel="${file#"$app"/}" + info="$(rcodesign print-signature-info "$file" 2>/dev/null)" || continue + grep -q 'LINKER_SIGNED' <<<"$info" && continue + id="$(grep -m1 -E '^ +identifier: ' <<<"$info" | sed -E 's/^ +identifier: //')" || continue + args+=(--binary-identifier "$rel:$id") + done < <(find "$app" -type f -print0 | sort -z) + + rcodesign sign "${args[@]}" "$app" +} + +sign_pkg() { + local pkg="$1" dir + : "${INSTALLER_P12_FILE:?}" "${INSTALLER_P12_PASSWORD_FILE:?}" + command -v openssl >/dev/null || die "openssl is not installed" + + # rcodesign only reads PKCS#12 files in the legacy encryption (Keychain + # Access exports); re-encode whatever we were given into that form. + dir="$(mktemp -d)" + # shellcheck disable=SC2064 # expand $dir now + trap "rm -rf '$dir'" RETURN + ( + umask 077 + openssl pkcs12 -legacy -in "$INSTALLER_P12_FILE" -passin "file:$INSTALLER_P12_PASSWORD_FILE" -nodes -out "$dir/installer.pem" + openssl pkcs12 -export -legacy -in "$dir/installer.pem" -out "$dir/installer.p12" -passout "file:$INSTALLER_P12_PASSWORD_FILE" + ) + + rcodesign sign \ + --p12-file "$dir/installer.p12" \ + --p12-password-file "$INSTALLER_P12_PASSWORD_FILE" \ + "$pkg" +} + +case "$kind" in +app) sign_app "${target%/}" ;; +pkg) sign_pkg "$target" ;; +*) die "unknown kind $kind (expected app or pkg)" ;; +esac diff --git a/signing/developer-id-application.pem b/signing/developer-id-application.pem new file mode 100644 index 00000000..5d9e2480 --- /dev/null +++ b/signing/developer-id-application.pem @@ -0,0 +1,34 @@ +-----BEGIN CERTIFICATE----- +MIIF2DCCBMCgAwIBAgIQFhzmYU3rs/oPjecZY2YpVDANBgkqhkiG9w0BAQsFADBe +MS0wKwYDVQQDDCREZXZlbG9wZXIgSUQgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkx +CzAJBgNVBAsMAkcyMRMwEQYDVQQKDApBcHBsZSBJbmMuMQswCQYDVQQGEwJVUzAe +Fw0yNjExMTUwNzA3MDVaFw0yNzEyMTUwNzA3MDRaMIGnMRowGAYKCZImiZPyLGQB +AQwKNDM5OUdOMzVCSjFGMEQGA1UEAww9RGV2ZWxvcGVyIElEIEFwcGxpY2F0aW9u +OiBDb2RlciBUZWNobm9sb2dpZXMgSW5jICg0Mzk5R04zNUJKKTETMBEGA1UECwwK +NDM5OUdOMzVCSjEfMB0GA1UECgwWQ29kZXIgVGVjaG5vbG9naWVzIEluYzELMAkG +A1UEBhMCVVMwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDHvIeQK7xT +1/ox6Mnecl/Z5+OorXgJ6EQXB9+GKxpfP/Gcl+s0mw6RfRNSL3Vs43RayNUyeFjM +Gt4ehFJF7DHKXT2+9lPa0UGsGl5JUJqHEt7dIvWgJjKihPNP0fMgIjcr+nr+EAXl +QUE6wQOc6NM3PULmucGveR9Na+szPbEljf+ilE5WcxgfBwwHDBlJtDFsJT3uX0wL +9dUsY/1K8cwofgxzKmddhAFdWYV0QTIY1xMDkPoKW40Eyym43MJVy8P7l/quP1ig +p/S8UmaOPrXIHWlmwHFqJtVjkS/1KQKwCPd7rDgiZPwQlKLc+01jSlg4fydcET/q +iMKxjXFjgpDDAgMBAAGjggJGMIICQjAMBgNVHRMBAf8EAjAAMB8GA1UdIwQYMBaA +FPg6DGkRduDtrNHrpln6N9XEVbAeMHIGCCsGAQUFBwEBBGYwZDAuBggrBgEFBQcw +AoYiaHR0cDovL2NlcnRzLmFwcGxlLmNvbS9kZXZpZGcyLmRlcjAyBggrBgEFBQcw +AYYmaHR0cDovL29jc3AuYXBwbGUuY29tL29jc3AwMy1kZXZpZGcyMDEwggEeBgNV +HSAEggEVMIIBETCCAQ0GCSqGSIb3Y2QFATCB/zCBwwYIKwYBBQUHAgIwgbYMgbNS +ZWxpYW5jZSBvbiB0aGlzIGNlcnRpZmljYXRlIGJ5IGFueSBwYXJ0eSBhc3N1bWVz +IGFjY2VwdGFuY2Ugb2YgdGhlIHRoZW4gYXBwbGljYWJsZSBzdGFuZGFyZCB0ZXJt +cyBhbmQgY29uZGl0aW9ucyBvZiB1c2UsIGNlcnRpZmljYXRlIHBvbGljeSBhbmQg +Y2VydGlmaWNhdGlvbiBwcmFjdGljZSBzdGF0ZW1lbnRzLjA3BggrBgEFBQcCARYr +aHR0cHM6Ly93d3cuYXBwbGUuY29tL2NlcnRpZmljYXRlYXV0aG9yaXR5LzAWBgNV +HSUBAf8EDDAKBggrBgEFBQcDAzAdBgNVHQ4EFgQUOBtcscn6uhTzAjEWL8euo+QI +TUYwDgYDVR0PAQH/BAQDAgeAMB8GCiqGSIb3Y2QGASEEEQwPMjAyMDA1MjkwMDAw +MDBaMBMGCiqGSIb3Y2QGAQ0BAf8EAgUAMA0GCSqGSIb3DQEBCwUAA4IBAQCBiRI5 +ezd3+5TBcJgrTf0w/haLtrWnrNlbInYtfZ5CmHalR2CHVaOl49kL5E9VN88eIaAh +BsyIseFrIMIKlajLVz7Cejf+cGjJzh/a+feSlGNihaFpIG62JMKNia4DrjsWWEve +ac8My5NXtE/H9P6O+FEUjoj2749kBMZZvGamD/0yQcGFHIJV4B50tEXKQuiwHHqg +j+qOZxlOtAoNNycrWXxyayEagvOoalOqoWonOChGlRlCWnvFhz567gOtfEUeuASA +urUHxxNa3qSNjJ3VmUzCuCGI3oFuOBfZ3V2YbOfArYUZiv+byjHu6I/p11g+JAtH +ei9b50ogpVWnmPo1 +-----END CERTIFICATE----- diff --git a/signing/entitlements/app.plist b/signing/entitlements/app.plist new file mode 100644 index 00000000..1c389f67 --- /dev/null +++ b/signing/entitlements/app.plist @@ -0,0 +1,20 @@ + + + + + com.apple.application-identifier + 4399GN35BJ.com.coder.Coder-Desktop + com.apple.developer.networking.networkextension + + packet-tunnel-provider-systemextension + + com.apple.developer.system-extension.install + + com.apple.developer.team-identifier + 4399GN35BJ + com.apple.security.application-groups + + 4399GN35BJ.com.coder.Coder-Desktop + + + diff --git a/signing/entitlements/helper.plist b/signing/entitlements/helper.plist new file mode 100644 index 00000000..139443d2 --- /dev/null +++ b/signing/entitlements/helper.plist @@ -0,0 +1,8 @@ + + + + + com.apple.application-identifier + 4399GN35BJ.com.coder.Coder-Desktop.Helper + + diff --git a/signing/entitlements/vpn.plist b/signing/entitlements/vpn.plist new file mode 100644 index 00000000..46bcb76c --- /dev/null +++ b/signing/entitlements/vpn.plist @@ -0,0 +1,24 @@ + + + + + com.apple.application-identifier + 4399GN35BJ.com.coder.Coder-Desktop.VPN + com.apple.developer.networking.networkextension + + packet-tunnel-provider-systemextension + + com.apple.developer.team-identifier + 4399GN35BJ + com.apple.security.app-sandbox + + com.apple.security.application-groups + + 4399GN35BJ.com.coder.Coder-Desktop + + com.apple.security.network.client + + com.apple.security.network.server + + +