# Sign iOS Builds with App Store Connect API Key

Canonical: https://figment.so/blog/mac-app-store-connect-api-ci-signing

Create a team API key with the App Manager role, load the .p8 from a CI secret with a cleanup trap, and pass it to Fastlane or xcodebuild. No 2FA prompts, no 30-day session expiry.

Replace Apple ID auth with an [App Store Connect API key](https://developer.apple.com/documentation/appstoreconnectapi/generating_tokens_for_api_requests), keep the `.p8` out of Git and out of `env > file` dumps, and run the pipeline on a Mac that matches your toolchain. The key signs short-lived tokens, so CI never hits a 2FA prompt or a 30-day session expiry. The sections below create the key, load it safely, wire it into Fastlane and `xcodebuild`, and rotate it without downtime.

## Why does Apple ID auth fail in headless CI?

Apple ID authentication in older Fastlane and Xcode flows relies on a session cookie that typically lapses within about 30 days. When it expires, the next TestFlight upload, cert fetch, or App Store Connect query fails with a 2FA prompt that no headless runner can answer, and the release pipeline stalls until someone re-authenticates on a trusted device.

The [App Store Connect API](https://developer.apple.com/documentation/appstoreconnectapi/generating_tokens_for_api_requests) uses a private key to sign short-lived JWTs instead. There is no interactive session, no 2FA, and the key is valid until you revoke it. Fastlane's [App Store Connect API documentation](https://docs.fastlane.tools/app-store-connect-api/) describes the same action-based flow for `match`, `gym`, `pilot`, `deliver` and `precheck`.

## How do I create the API key with the right role?

1. Sign in to App Store Connect, open **Users and Access**, pick the **Integrations** tab, then **App Store Connect API**.
2. Create a **Team Key** rather than an individual key so provisioning and signing endpoints are reachable.
3. Assign the narrowest role that works. **App Manager** is enough for signing, certificate and TestFlight operations; reserve **Admin** for keys that must manage users.
4. Download the `.p8` file immediately. App Store Connect shows it once and does not offer a re-download.
5. Record the **Key ID** (10-character alphanumeric) and the **Issuer ID** (UUID at the top of the page).

Store the three values as CI secrets in your provider's secret manager. Do not dump the entire environment to a file; `env > file` leaks every unrelated secret at the same time. If you need to carry secrets to a new CI, transfer the names and let each system re-inject the values.

## How do I load the .p8 safely from a CI secret?

Base64-encode the `.p8` once so string-only secret stores (GitHub Actions, GitLab CI, Bitrise, Jenkins Credentials) can hold it verbatim:

```bash
# Run locally, paste the output into the CI secret value
base64 -i AuthKey_XXXXXXXXXX.p8 | pbcopy
```

Then add three secrets: `ASC_KEY_CONTENT` (the base64 text), `ASC_KEY_ID`, and `ASC_ISSUER_ID`.

The script below is the artifact for this guide. Source it at the start of the job. It tightens the umask **before** touching disk, writes the key to a private temp path, and removes it on exit, success or failure, with a trap.

```bash
#!/usr/bin/env bash
# setup-asc-key.sh: source me: `source ./setup-asc-key.sh`
# Requires CI secrets: ASC_KEY_CONTENT (base64 .p8), ASC_KEY_ID, ASC_ISSUER_ID
set -euo pipefail

: "${ASC_KEY_CONTENT:?Set ASC_KEY_CONTENT to the base64-encoded .p8 content}"
: "${ASC_KEY_ID:?Set ASC_KEY_ID to the 10-character key ID}"
: "${ASC_ISSUER_ID:?Set ASC_ISSUER_ID to the team issuer UUID}"

# Restrictive perms BEFORE any file is created
_old_umask=$(umask)
umask 077

_ASC_KEY_DIR=$(mktemp -d "${TMPDIR:-/tmp}/asc-key.XXXXXX")
_ASC_KEY_FILE="$_ASC_KEY_DIR/AuthKey_${ASC_KEY_ID}.p8"

cleanup() { rm -rf "$_ASC_KEY_DIR"; }
trap cleanup EXIT INT TERM

printf '%s' "$ASC_KEY_CONTENT" | base64 --decode > "$_ASC_KEY_FILE"
umask "$_old_umask"

export ASC_KEY_PATH="$_ASC_KEY_FILE"
# Read by Fastlane's app_store_connect_api_key action when invoked with no args
export APP_STORE_CONNECT_API_KEY_KEY_ID="$ASC_KEY_ID"
export APP_STORE_CONNECT_API_KEY_ISSUER_ID="$ASC_ISSUER_ID"
export APP_STORE_CONNECT_API_KEY_KEY_FILEPATH="$_ASC_KEY_FILE"

echo "ASC key staged at $_ASC_KEY_FILE (removed when this shell exits)"
```

Note that a separate CI step runs in a separate shell: the `trap` only cleans up inside the shell that sourced the script. If your CI splits steps across shells, add an explicit teardown step and treat machine-failure cleanup as the runner's responsibility, not the script's.

The Fastfile side is a single call that every other action can reuse:

```ruby
# Fastfile
lane :build_and_upload do
  api_key = app_store_connect_api_key(
    key_id:       ENV.fetch("ASC_KEY_ID"),
    issuer_id:    ENV.fetch("ASC_ISSUER_ID"),
    key_filepath: ENV.fetch("ASC_KEY_PATH"),
    duration:     1200,   # seconds; Fastlane caps this at 1200
    in_house:     false
  )

  match(type: "appstore", api_key: api_key, readonly: true)
  gym(scheme: ENV.fetch("APP_SCHEME"), configuration: "Release")
  pilot(api_key: api_key, skip_waiting_for_build_processing: true)
end
```

Pass the project's real scheme through `APP_SCHEME`. Do not hard-code a placeholder your CI has no way to build.

## How do I use the key with xcodebuild directly?

For projects without Fastlane, three flags cover `archive` and `-exportArchive`:

```bash
xcodebuild \
  -scheme "$APP_SCHEME" \
  -configuration Release \
  -archivePath "build/${APP_SCHEME}.xcarchive" \
  -authenticationKeyPath     "$ASC_KEY_PATH" \
  -authenticationKeyID       "$ASC_KEY_ID" \
  -authenticationKeyIssuerID "$ASC_ISSUER_ID" \
  archive
```

Use the same three flags for the `-exportArchive` step that uploads to App Store Connect. Keep `set -e` on the job so a failed signing step stops the pipeline; a build that exits non-zero is not a benchmark.

## How do I verify the key before archiving?

A 20-minute archive followed by an auth failure wastes a runner slot. Run a tiny verification lane first so bad keys surface in seconds:

```ruby
lane :verify_asc_key do
  api_key = app_store_connect_api_key(
    key_id:       ENV.fetch("ASC_KEY_ID"),
    issuer_id:    ENV.fetch("ASC_ISSUER_ID"),
    key_filepath: ENV.fetch("ASC_KEY_PATH"),
    duration:     600
  )
  Spaceship::ConnectAPI.token = api_key
  apps = Spaceship::ConnectAPI::App.all(limit: 1)
  UI.user_error!("No apps visible to this key") if apps.empty?
  UI.success("ASC key valid: #{apps.length} app visible")
end
```

Wire `fastlane verify_asc_key` as a short-timeout job ahead of the archive job in your pipeline graph. Only the full archive depends on it, so a bad rotation fails in under a minute instead of after twenty.

## How do I rotate the key without downtime?

Keys cannot be edited in place, but two keys can be valid at once:

1. Generate a new team key in App Store Connect; leave the current one active.
2. Update CI secrets to the new Key ID, Issuer ID, and `.p8`.
3. Run `verify_asc_key` and one full release-branch build against the new key.
4. Revoke the old key once the new one has shipped a build.

Name keys with a clear purpose and date (`CI-prod-2026-11`) so the revoke decision is obvious. Document who holds the downloaded `.p8` for break-glass access, because App Store Connect does not re-issue it.

## Are signing and upload jobs light enough for the Intel Mac VM?

Signing and uploading are light jobs. The [Intel Mac VM](/mac-hosting#intel-vm) at $25 a month can run them on macOS Sequoia, where Apple lists Xcode 26.0 to 26.3. For device builds with Xcode 26.4 or later, arm64-only binaries or visionOS, use the [Apple Silicon Mac VM](/mac-hosting#apple-silicon-vm) at $39 a month. Xcode 26.4 and later need macOS Tahoe 26.2 or later, and Xcode 27 needs Tahoe 26.6 or later. If the pipeline also runs large builds, the [Dedicated M4 Pro 48 GB](/mac-hosting#dedicated-m4-pro) at $349 a month is a whole Mac with 48GB of memory.

Replacing a laptop under a desk with the Apple Silicon Mac VM costs $39 × 12 = $468 a year, before tax. [CloudMac](https://cloudmac.org/) publishes $999/year for an M4 / 16 GB / 256 GB Mac mini (about $83.25/month) and $99.99/month on [its pricing page](https://cloudmac.org/pricing). That is a whole M4 with more memory, where the VM has 4GB and shared vCPUs. Figment runs the Mac and network; you manage your CI and Apple accounts.

**Related guides:**
- [Rotate Provisioning Profiles in CI Safely](/blog/mac-provisioning-profile-rotation-ci)
- [Parallelize XCTests Across Multiple Mac Nodes](/blog/mac-xctest-parallel-ci-nodes)
- [Xcode on Windows: Remote Mac Setup](/blog/mac-xcode-on-windows-remote-setup)
