Skip to Content
App AttestationSDK IntegrationSwift (iOS & macOS)

App attestation (iOS and macOS)

For Apple platform developers adding attestation to an app that already uses TrustPin pinning. At the end of this page, your requests carry a token your backend can verify, you can test it on a simulator, and you know what to check before release.

Using an AI coding agent? Install the TrustPin skill and let it wire this up for you.

How it works

TrustPinAttestKit uses Apple’s App Attest to have the attestation verifier you run check a device key, once per key. The verifier answers with a short-lived signed token, which the framework renews cheaply with the same key. The framework adds the token to requests for the hosts you choose, as the TrustPin-Attestation header, and your backend verifies it and decides what an unattested request may do.

The framework never blocks or fails your requests. When no token is available within a short, bounded time, the request is sent without the header.

What your app calls, and when:

Requirements

ItemRequirement
PlatformsiOS 15.0+, macOS 13.0+, watchOS 9.0+, tvOS 15.0+, Mac Catalyst 15.0+, visionOS 2.0+
Swift6.2 or later
TrustPinKitSet up in your app, at the same version as TrustPinAttestKit
VerifierDeployed, reachable over HTTPS, with a published policy
App AttestThe capability on your App ID and the entitlement in the app (Configure)

SDK and verifier compatibility

SDKVerifier
TrustPinAttestKit 7.1.0Contract version 2 or newer: verifier 1.0.0 or later

With an older verifier the state is failed(.verifierIncompatible, …) and no header is sent until the verifier is updated.

Before you write code: the policy

Your verifier checks every attestation against a signed policy, which you manage on the project’s Attestation page and publish with Sign and publish (see Setting up apps and the policy). These settings matter for an Apple app:

SettingWhat to setWhat it does
Attest Apple appsTeam ID and Bundle ID, for example ABCDE12345 and com.example.appAn unlisted app is refused with app_not_allowed, in both modes
Accept development buildsOn while you test builds run from XcodeWithout it, they are refused with dev_environment
Require token bindingOn to refuse tokens that are not bound to a sessionSee Bind tokens to the user’s session
Allow debug tokensOn if you test on simulators or emulators. Only your staging verifier, which has debug token hashes, accepts themSee Simulators and development
ModeMonitor (recommended to start), then EnforceMonitor issues a token even when a policy check fails and records the result in it

Register your verifier’s domain in your TrustPin project (how). Calls to the verifier are pinned by the TrustPin instance with the same identifier, and in strict mode an unregistered verifier host is never reached.

Install

Swift Package Manager

Add https://github.com/trustpin-cloud/swift.sdk, from 7.1.0. The package vends these products:

ProductWhat it is
TrustPinKitThe pinning framework
TrustPinAttestKitThe attestation framework. Import it as TrustPinAttestKit; its API lives on the TrustPinAttest type
TrustPinKitAlamofireOptional Alamofire integration, Alamofire 5.10.0 or later. Swift Package Manager only
dependencies: [ .package(url: "https://github.com/trustpin-cloud/swift.sdk", from: "7.1.0") ], targets: [ .target( name: "YourApp", dependencies: [ .product(name: "TrustPinKit", package: "swift.sdk"), .product(name: "TrustPinAttestKit", package: "swift.sdk"), // Only if you use Alamofire: .product(name: "TrustPinKitAlamofire", package: "swift.sdk") ] ) ]

CocoaPods

pod 'TrustPinKit', '~> 7.1' pod 'TrustPinAttestKit', '~> 7.1'

TrustPinAttestKit requires TrustPinKit at exactly the same version; CocoaPods resolves it for you.

Configure

  1. App Attest capability. Enable App Attest on the App ID in the Apple Developer portal. In Xcode, add the App Attest capability to the app target. It adds this entitlement:

    <key>com.apple.developer.devicecheck.appattest-environment</key> <string>development</string>

    Builds run from Xcode attest in the development environment, which needs Accept development builds in the policy. TestFlight and App Store builds attest in production.

  2. Verifier and hosts. Add two keys to the TrustPin-Info.plist that already holds your pinning configuration:

    <key>AttestVerifierURL</key> <string>https://attest.example.com</string> <key>AttestedHosts</key> <array> <string>api.example.com</string> </array>
    KeyTypeRequiredNotes
    AttestVerifierURLStringYesHTTPS base URL of your verifier, without a version segment. A path is allowed (https://api.example.com/attest). No credentials, query, fragment or IP address
    AttestedHostsArray of StringYesOne to fifty hosts whose requests receive the header, no duplicates. *.example.com covers exactly one label. IP addresses are not accepted

    Other keys are ignored, so the pinning and attestation keys share one file. TrustPinAttestConfiguration.fromPlist(_:fileName:) reads another bundle or file name.

To configure in code instead:

let configuration = try TrustPinAttestConfiguration( verifierURL: URL(string: "https://attest.example.com")!, attestedHosts: ["api.example.com"] )

An invalid value throws TrustPinAttestError.invalidConfiguration, and the reason is printed to the console with the [TrustPinAttest] prefix.

Staging and production builds. Each environment has its own verifier URL. Point each build configuration at its own: ship one plist per configuration and pass its name to fromPlist(_:fileName:), or configure in code and choose the URL with a compilation condition, for example #if STAGING, with STAGING set under Swift Compiler - Custom Flags for the staging configuration.

Set up

Set up pinning first, then attestation, once per launch:

import SwiftUI import TrustPinKit import TrustPinAttestKit @main struct MyApp: App { init() { Task { do { // autoRegisterURLProtocol adds the header to URLSession.shared (path A below). try await TrustPin.setup(.fromPlist(), autoRegisterURLProtocol: true) try await TrustPinAttest.setup(.fromPlist()) TrustPinAttest.bindToHeader("Authorization") TrustPinAttest.prefetch() } catch { // The pinning or attestation configuration is invalid. } } } var body: some Scene { WindowGroup { ContentView() } } }
  • setup validates the configuration and loads any key attested in an earlier launch. It makes no call to your verifier.
  • prefetch() starts attestation in the background, so your first request doesn’t wait. It never throws. Without it, the first attestation starts at setTokenBinding(_:), getToken() or the first request to an attested host.
  • A second setup of one instance throws alreadyInitialized; one made while the first is still running throws invalidConfiguration.
  • Set up the pinning instance with the same identifier first. Without it, verifier calls fail with verifierUnavailable.
  • Named instances. If you use named TrustPin instances, try TrustPinAttest.instance(id: "payments") pairs with TrustPin.instance(id: "payments"), which must be set up first. The static calls use the default instance, and the URL protocol serves the default instance only.

Check. Turn on logging and watch the state while you develop. Put these lines at the start of the setup Task, before TrustPinAttest.setup: the listener doesn’t replay earlier states.

TrustPinAttest.set(logLevel: .info) TrustPinAttest.setStateListener { state in print("Attestation:", state) }

Within a few seconds of launch the state reaches ready(expiresAt:). On a simulator this needs a debug token (Simulators and development). If it shows failed, look the error up in Errors.

Bind tokens to the user’s session

A bound token is valid only with the session it was issued for, so a token copied out of one session is useless in another. Only a SHA-256 of the value travels: the value never leaves the device and is never logged.

ModeCallUse it when
Header bindingTrustPinAttest.bindToHeader("Authorization")Your requests carry the session in a header. Each request’s token is bound to that header’s value on that request
Fixed bindingTrustPinAttest.setTokenBinding(sessionValue)You have one session value, or a client that sends no such header (gRPC, WebSockets)
  • Each mode clears the other.
  • A binding change renews the token with the existing key; it is not a new attestation. setTokenBinding renews at once; with header binding, the next request carrying the new value renews it.
  • Sign-out. With header binding there is nothing to call: requests without the header get unbound tokens. With fixed binding, call setTokenBinding(nil) on sign-out and setTokenBinding(newValue) on the next sign-in. bindToHeader(nil) stops header binding and also clears a fixed binding.
  • Required binding. With Require token binding on, no token exists until a binding is known, and the state is failed(.bindingRequired, retryAt: .distantFuture). That is expected before sign-in. With header binding, the first request carrying the header gets the token. With fixed binding, call setTokenBinding(_:) before prefetch().
  • prefetch() with header binding attests early but can’t bind, since there is no request yet. The first bound request renews the token once more, cheaply.
  • With header binding, getToken() returns a token bound to the most recent request the instance saw.

Your API compares the token’s bind claim with the SHA-256 of the same header value (Verifying tokens in your API).

Send the header

Pick the path that matches your networking code.

A. URLSession.shared with the TrustPin URL protocol. Set up pinning with autoRegisterURLProtocol: true, as in Set up. Requests to the attested hosts get the header automatically:

var request = URLRequest(url: URL(string: "https://api.example.com/v1/items")!) request.setValue("Bearer \(sessionToken)", forHTTPHeaderField: "Authorization") let (data, response) = try await URLSession.shared.data(for: request)

This path serves the default instance only, and only URLSession.shared.

B. Your own URLSession. A pinning delegate can’t change headers, so ask for the header per request:

let session = URLSession( configuration: .default, delegate: TrustPin.makeURLSessionDelegate(), delegateQueue: nil ) var request = URLRequest(url: URL(string: "https://api.example.com/v1/items")!) request.setValue("Bearer \(sessionToken)", forHTTPHeaderField: "Authorization") request = await TrustPinAttest.addingAttestation(to: request) // after setting Authorization let (data, response) = try await session.data(for: request)

Set the bound header before calling addingAttestation(to:), so the token is bound to it. TrustPinAttest.attestationHeaders(for:) returns the same header as a dictionary.

C. Alamofire. Add the adapter and the redirect handler from TrustPinKitAlamofire:

import Alamofire import TrustPinKitAlamofire let session = Session( interceptor: Interceptor(adapters: [TrustPinAttestationAdapter()]), serverTrustManager: ServerTrustManager(evaluators: [ "api.example.com": TrustPinServerTrustEvaluating() ]), redirectHandler: TrustPinAttestationRedirectHandler() )

For a named instance, pass instance: try TrustPin.instance(id: "payments") to each initializer.

D. Anything else (gRPC, WebSockets). Read the token and send it yourself:

let token = try await TrustPinAttest.getToken() // Send it in the TrustPinAttest.headerName ("TrustPin-Attestation") header.

getToken() throws the error that explains why no token is available (Errors).

These rules apply to every path:

  • HTTPS only. The header is never added to a plain http:// request.

  • Attested hosts only. Other hosts never receive it.

  • A header your app sets. Paths A and C never replace a TrustPin-Attestation header the request already carries. addingAttestation(to:) sets it, because your app asked.

  • Redirects. The header never follows a redirect unchecked: the URL protocol, the delegates from TrustPin.makeURLSessionDelegate() and the Alamofire redirect handler remove it and ask again for the new destination. If your session needs its own delegate, create it with TrustPin.makeURLSessionDelegate(forwardingTo: yourDelegate): pinning and the redirect rule apply first, then your callbacks run. A session that uses no TrustPin delegate must call TrustPin.redirectedRequest(_:) in its redirect callback:

    func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest: URLRequest, completionHandler: @escaping @Sendable (URLRequest?) -> Void) { Task { completionHandler(await TrustPin.redirectedRequest(newRequest)) } }
  • Bounded wait. If no token is ready, a request waits a short, bounded time, then goes out without the header. While the framework is waiting after a failure, it goes out at once without the header.

  • Adding the header yourself everywhere. Call TrustPin.setAttestationProvider(nil) after TrustPinAttest.setup; then only paths B and D add it.

Sensitive operations

For an operation your backend must not accept on a reused token alone (a payment, a change of beneficiary), send an assertion bound to that operation with the token:

import CryptoKit import TrustPinAttestKit let body = try JSONEncoder().encode(transfer) // the exact bytes you send var request = URLRequest(url: URL(string: "https://api.example.com/v1/transfer")!) request.httpMethod = "POST" request.httpBody = body request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.setValue("Bearer \(sessionToken)", forHTTPHeaderField: "Authorization") // With header binding, let the framework see this request's Authorization value first. request = await TrustPinAttest.addingAttestation(to: request) let headers = try await TrustPinAttest.assertionHeaders(payloadDigest: Data(SHA256.hash(data: body))) for (name, value) in headers { request.setValue(value, forHTTPHeaderField: name) } let (data, response) = try await session.data(for: request) // your pinned session (path B), or URLSession.shared with path A
  • The result holds the TrustPin-Attestation token and the TrustPin-Assertion header (TrustPinAttest.assertionHeaderName). Your backend passes both, with its own digest of the same bytes, to your verifier (Assertions for sensitive operations).
  • The token comes first. When no token is available, it throws the same error getToken() would, and nothing is sent.
  • Digest. Anything but a 32-byte SHA-256 digest throws invalidDigest.
  • Cost. Each call produces a new assertion and costs one round trip to your verifier besides your request.
  • Your verifier and your API decide which endpoints require an assertion. For endpoints that reuse the token, a short token lifetime and a required binding are the recommended configuration.

Verify the token in your API

Requests to the attested hosts carry TrustPin-Attestation: <token>, a JWT signed by your verifier. Your API checks its signature against the verifier’s published keys, its type, issuer, audience, expiry and project, and its binding, and refuses debug tokens in production. What to do with a request that has no valid token is your decision, per endpoint. See Verifying tokens in your API.

In the token, tp.plat is apple and tp.app is TEAMID.bundle.id. sub identifies the device key and changes when the device attests a new key, so don’t use it as a stable device identifier.

Simulators and development

Simulators can’t run App Attest. For development, your verifier’s operator can issue a debug token (how). The policy (Allow debug tokens) and the verifier must both allow it.

  1. In Xcode, Edit Scheme, Run, Arguments, Environment Variables: set TRUSTPIN_DEBUG_TOKEN to the token. Never put a debug token in the app bundle or a plist.
  2. A debug token presents the app as TEAMID.bundle.id, taken from the build’s signing team and bundle ID. No App Attest or signing check applies, but the policy must list that app. If the verifier answers app_not_allowed, the simulator build has no signing team or another bundle ID: also set TRUSTPIN_DEBUG_APP_ID to the app as listed in the policy, for example ABCDE12345.com.example.app.
  3. Run from Xcode. Scheme variables don’t reach an app opened from the home screen.

The debug path exists only in the simulator builds of the framework, so device builds never use a debug token. Debug tokens carry tp.env debug, which production APIs refuse.

On a real device, builds run from Xcode attest with App Attest in the development environment, which needs Accept development builds.

Devices without App Attest

Where the OS reports App Attest unsupported (some Macs, for example), the state becomes failed(.unsupportedDevice, retryAt: .distantFuture) and requests are sent without the header. Your backend decides whether to serve them.

Use TrustPinAttestKit from the app process. Apple supports App Attest in apps and in Action, extensible SSO and watchOS extensions only, and TrustPinAttestKit doesn’t support app extensions that share the app’s Keychain.

State, errors and logging

State

TrustPinAttest.state is one of four cases. setStateListener(_:) receives every change in order, on a background queue; it doesn’t replay the current state, so read state first.

StateMeaning
unavailableNo token yet: after setup, before the first attestation, after reset(), or after a token expired with no renewal possible
attestingAn attestation or a renewal is in progress
ready(expiresAt:)A token is available until expiresAt; it is renewed before then
failed(error, retryAt:)The last attempt failed with a TrustPinAttestError

Retry time. No timer runs after a failure. Nothing is tried before retryAt; the next request, getToken() or prefetch() after it starts a new attempt. .distantFuture means no new attempt in this launch until reset() or a relaunch. The exception is bindingRequired, which resumes as soon as a binding is set. Your verifier can set how long a device waits; such a wait, and the wait after a refusal, survive a relaunch.

To act on the state, for example in a diagnostics screen:

switch TrustPinAttest.state { case .ready: break case .failed(.bindingRequired, _): break // expected before sign-in case .failed(let error, let retryAt): print("Attestation failed: \(error), next attempt after \(retryAt)") case .unavailable, .attesting: break @unknown default: break }

Errors

setup, getToken() and assertionHeaders(payloadDigest:) throw a TrustPinAttestError, and failed carries one:

CaseMeaningWhat to do
invalidConfigurationA plist key is missing or invalid, or another setup is in progressFix the plist; read the [TrustPinAttest] console line. Set up once
alreadyInitializedsetup was called twice on one instanceSet up once per launch
notSetUpA call before setupCall setup first
unsupportedDeviceApp Attest is unavailable on this device, or new keys keep failing on itExpected on simulators without a debug token. On a device, see Support flow
evidenceUnavailableThe policy asks for evidence this device can’t provideCheck the policy’s Apple settings
bindingRequiredThe policy requires a binding and none is setExpected before sign-in. See Bind tokens
attestationFailed(reasons:)The verifier refused the attestation. reasons holds its reason codes, or one the framework supplies (http_<status>, invalid_key, invalid_input)Read reasons (Troubleshooting). The framework waits before attesting again; the wait survives a relaunch, and an app update or reset() ends it
verifierUnavailableThe verifier couldn’t be reached securelyCheck connectivity and the verifier’s health. In strict mode, register the verifier’s domain
verifierIncompatibleThe verifier is older than contract version 2Update the verifier to 1.0.0 or later. No app change is needed
invalidDigestassertionHeaders(payloadDigest:) was given something other than 32 bytesPass a SHA-256 digest

TrustPinAttestState, TrustPinAttestError and TrustPinAttestEvent may gain cases in a minor release: switch over them with @unknown default.

Logging

Logging is off by default.

TrustPinAttest.set(logLevel: .info) // .none, .error, .warning, .info, .debug; per instance TrustPinAttest.setLogSink(TrustPinAttestClosureLogSink { level, instanceId, message in myLogger.log("[attest/\(instanceId)] \(message)") // process-wide; nil restores the default })

Without a sink, messages go to unified logging, subsystem cloud.trustpin.swift.attest (filter on it in Console). Whether a request got the header is logged at .debug. Tokens, key certificates, bound values and debug tokens are never logged. Use .error or .none in release builds.

Events

TrustPinAttest.setEventListener { event in … } or for await event in TrustPinAttest.events deliver TrustPinAttestEvent values for your metrics, in order. A slow listener never delays a request.

TrustPinAttest.setEventListener { event in switch event { case .attestationSucceeded(let duration): metrics.timing("attest", duration) case .refused: metrics.count("attest.refused") case .waitEntered(let until): metrics.gauge("attest.wait_until", until.timeIntervalSince1970) default: break } }
EventCarries
keyGeneratedNothing
keyReplaced(count:)Recent replacements
attestationSucceeded(duration:), refreshSucceeded(duration:), assertionSucceeded(duration:)Seconds
attestationFailed(reasons:retryAt:)Reason codes and the next attempt time
refreshFailed(_:), assertionFailed(_:)The TrustPinAttestError
refused(retryAt:)The next attempt time
waitEntered(until:)The wait’s end
waitCleared, deviceUnsupported, verifierUnavailableNothing

Events never carry a token, a key or a device identifier.

Reset and backups

await TrustPinAttest.reset() discards the attested key and the token, ends any wait after a refusal, and returns once the discard is complete. The next request attests a new key, with a new sub. Use it for support flows, for example a “repair attestation” action, not routinely: every new key counts toward Apple’s per-device metric, which can’t be reset.

Apple recommends one key per user account on each device. If several users sign in to your app on one device, call reset() when a different user signs in, not on every sign-out.

Keychain items are this-device-only and never synced, so keys and key certificates aren’t backed up. A restored app attests again.

Before you release

  • The release build’s verifier URL and attested hosts point at production, and the verifier’s domain is registered in your TrustPin project.
  • The production policy lists the app’s Team ID and Bundle ID, with Accept development builds and Allow debug tokens off.
  • Your API refuses tp.env debug and checks bind if you bind tokens.
  • A TestFlight build reaches ready and your API logs a verified token with tp.env production.
  • The log level is .error or .none.

Rolling out

Start in Monitor (recommended to start), measure the requests without a header and the fail results, then switch to Enforce. See Rolling out.

With a large user base, enable attestation in stages. Apple may throttle attestation traffic, and suggests ramping up no more than 10 million users a day per app and staying under 100 attestation requests a second across all installations (Apple’s guidance ). A rate limit your verifier applies, answered with 429 and Retry-After, slows your apps before they reach Apple.

Troubleshooting

SymptomLikely causeFix
Requests arrive without the headerThe host isn’t in AttestedHosts, the URL is http://, the session doesn’t add headers, or there is no token yetRead TrustPinAttest.state, turn on .debug logging, and check the paths: a session with your own delegate needs addingAttestation(to:)
attestationFailed(reasons: ["app_not_allowed"])The policy doesn’t list this app, or the verifier serves a different TrustPin projectCheck Team ID and Bundle ID. On simulators, check TRUSTPIN_DEBUG_APP_ID
attestationFailed(reasons: ["dev_environment"])A build run from Xcode, with Accept development builds offTurn it on while testing
failed(.unsupportedDevice, …) on a simulatorNo debug token, or the app wasn’t launched from XcodeSimulators and development
failed(.verifierUnavailable, …) every timeThe verifier’s domain isn’t registered (strict mode), the verifier is down, or AttestVerifierURL is wrongRegister the domain, then check the URL and the verifier’s health
failed(.bindingRequired, …) before sign-inRequire token binding is onExpected. The first bound request gets the token
failed(.verifierIncompatible, …)The verifier speaks a contract version below 2Update the verifier to 1.0.0 or later
Tokens renew on every requestThe bound header’s value changes on every requestBind to a value that is stable within a session
attestationFailed(reasons: ["too_many_attestations"])The verifier’s per-key limitThe framework keeps the key and waits for retryAt. Look for a loop calling assertionHeaders
Your API refuses a valid-looking tokenWrong audience or project in the check, a binding computed from a different header value, or clock skewSee Verifying tokens in your API

Support flow

failed(.unsupportedDevice, …) after repeated key rejections, or a refusal that persists, is cleared by await TrustPinAttest.reset() once the cause is fixed. Report a device that keeps failing after a reset to your verifier’s operator with the time of the attempt: the verifier logs every attestation and its reasons, which tells a throttled device from a refused one.

Privacy

TrustPinAttestKit ships its own privacy manifest: no tracking, no collected data, no required-reason APIs. It sends evidence and tokens only to your verifier, and nothing to TrustPin. The device key never leaves the Secure Enclave, and bound values never leave the device. Tokens identify a device key, not a person, and change when the key does. If you forward events to a third-party service, that disclosure is yours to make.

Next steps