App attestation (Flutter)
For Flutter developers adding attestation to an app that already uses TrustPin pinning (trustpin_sdk). At the end of this page, your requests carry a token your backend can verify, on iOS, macOS and Android.
How it works
trustpin_attest wraps the native attestation modules: TrustPinAttestKit on iOS and macOS, and kotlin-attest on Android. The device attests a key once with the attestation verifier you run, using Apple App Attest, or Android Key Attestation and Google Play Integrity as your policy asks. The verifier answers with a short-lived signed token, which the SDK renews cheaply with the same key. trustpin_sdk’s TrustPinHttpClient and TrustPinDioInterceptor add the token to requests for the hosts you choose, in the TrustPin-Attestation header, and your backend verifies it.
The SDK never blocks or fails your requests. When no token is ready within a short, bounded time, the request goes out without the header, and your backend decides what to do.
What your Dart code calls, and when:
Requests sent through a client without TrustPinHttpClient or TrustPinDioInterceptor never get the header automatically. See Send the header.
Requirements
| Item | Requirement |
|---|---|
| Flutter | 3.44.0 or later. iOS and macOS build through Swift Package Manager only (no CocoaPods) |
| iOS, macOS | iOS 15 or later, macOS 13 or later |
| Android | API 25 or later, Kotlin 2.3.0 or later |
trustpin_sdk | Set up in your app, at the same version as trustpin_attest |
| Verifier | Deployed, reachable over HTTPS, with a published policy |
| Devices | iOS and macOS: a device that supports App Attest. Android: hardware-backed key attestation, and Google Play only if your policy uses Play Integrity. Simulators and emulators need a debug token |
SDK and verifier compatibility
| SDK | Verifier |
|---|---|
trustpin_attest 7.1.x | Contract version 2 or newer: verifier 1.0.0 or later |
With an older verifier the state is failed with VERIFIER_INCOMPATIBLE, and no header is sent until the verifier is upgraded. The app recovers on its own at the next attempt, with no update or reinstall.
Before you write code: the policy
Your verifier checks every attestation against a signed policy, which you manage on the project’s Attestation page in the TrustPin console and publish with Sign and publish. These settings matter for a Flutter app; Setting up apps and the policy explains each one.
| Setting | What to set |
|---|---|
| Attest Apple apps | Team ID and Bundle ID of the iOS app, and of the macOS app if you ship one |
| Accept development builds | On while you test builds run from Xcode or flutter run on a device |
| Attest Android apps | Package name and every Signing certificate SHA-256: your debug key, and the Play app signing key for builds from Google Play |
| Evidence (Android) | Key Attestation only is the simplest start. The other options use Play Integrity, which needs a Google Cloud project number |
| Require token binding | On once your API checks the binding. See Bind tokens to the user’s session |
| Allow debug tokens | On if you test on simulators or emulators. Only your staging verifier, which has debug token hashes, accepts them |
| Mode | Monitor (recommended to start), then Enforce |
Register your verifier’s domain in your TrustPin project. Calls to the verifier are pinned by the TrustPin instance with the same identifier, and in strict mode an unregistered host is never reached. See Registering the verifier’s domain.
Install
-
Add both packages, at the same version, to
pubspec.yaml, then runflutter pub get:dependencies: trustpin_sdk: ^7.1.1 trustpin_attest: ^7.1.1They bring the native 7.1.x modules with them (7.1.1 or later on Android).
-
iOS and macOS: Swift Package Manager must be on. It is by default from Flutter 3.44; if you turned it off, turn it back on:
flutter config --enable-swift-package-manager -
iOS and macOS: enable App Attest on the App ID in the Apple Developer portal, then in Xcode add the App Attest capability to the
Runnertarget (ios/Runner.xcworkspace, andmacos/Runner.xcworkspacefor macOS). It adds this entitlement:<key>com.apple.developer.devicecheck.appattest-environment</key> <string>development</string>Use
developmentfor builds run from Xcode orflutter run, which needs Accept development builds on, andproductionfor TestFlight and the App Store. -
Android: set
minSdkto 25 or higher inandroid/app/build.gradle.kts(orbuild.gradle), and build with the Kotlin Gradle plugin 2.3.0 or later, inandroid/settings.gradle.kts:// android/app/build.gradle.kts android { defaultConfig { minSdk = 25 } }// android/settings.gradle.kts plugins { id("org.jetbrains.kotlin.android") version "2.3.0" apply false }
Configure
Add the attestation keys to the native configuration files your pinning setup already reads.
iOS, ios/Runner/TrustPin-Info.plist (and macOS, macos/Runner/TrustPin-Info.plist):
<key>AttestVerifierURL</key>
<string>https://attest.example.com</string>
<key>AttestedHosts</key>
<array>
<string>api.example.com</string>
</array>Android, android/app/src/main/assets/trustpin.json:
{
"organization_id": "<organization id>",
"project_id": "<project id>",
"public_key": "<project public key>",
"attest_verifier_url": "https://attest.example.com",
"attested_hosts": ["api.example.com"]
}| Key (plist / JSON) | Required | Notes |
|---|---|---|
AttestVerifierURL / attest_verifier_url | Yes | Your verifier’s base URL: https:// on a host name, without credentials, query or fragment. A deployment path is allowed. IP addresses are refused |
AttestedHosts / attested_hosts | Yes | One to fifty host names that receive the header, each exact or *.example.com for exactly one label. No other host ever receives it |
google_cloud_project_number | Android, only for Play Integrity | Your Google Cloud project number (string or number). Leave it out otherwise: with a number, the app contacts Google Play services from setup on |
For Play Integrity, the same number goes in the policy’s Google Cloud project number, and your verifier’s operator enables Play Integrity on the verifier. See Android apps.
Other files or configuration in code. setupWithNativeBundle(iosFileName: …, macosFileName: …, androidFileName: …) reads other files, for example one per flavor. TrustPinAttest.shared.setup(TrustPinAttestConfiguration(verifierUrl: Uri.parse('https://attest.example.com'), attestedHosts: ['api.example.com'])) takes the values in code instead, with an optional googleCloudProjectNumber (an int, Android only).
Set up
Set up pinning first, then attestation, once per launch, before runApp:
import 'package:flutter/material.dart';
import 'package:trustpin_attest/trustpin_attest.dart';
import 'package:trustpin_sdk/trustpin_sdk.dart';
// Empty unless you run with --dart-define=TRUSTPIN_DEBUG_TOKEN=<token>.
const debugToken = String.fromEnvironment('TRUSTPIN_DEBUG_TOKEN');
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
try {
await TrustPin.shared.setupWithNativeBundle();
} on TrustPinException catch (e) {
debugPrint('Pinning setup: ${e.code}');
}
try {
await TrustPinAttest.shared.setupWithNativeBundle(
debugToken: debugToken.isEmpty ? null : debugToken,
);
await TrustPinAttest.shared.bindToHeader('Authorization');
await TrustPinAttest.shared.prefetch();
} on TrustPinAttestException catch (e) {
// INVALID_CONFIGURATION: fix the attestation keys.
// ALREADY_INITIALIZED after a hot restart: the native setup is still in place.
debugPrint('Attestation setup: ${e.code}');
}
runApp(const MyApp());
}setupWithNativeBundlevalidates the configuration and loads a device key from an earlier launch. It makes no verifier call.prefetch()starts attestation in the background, so the first request doesn’t wait. It never throws.- Setup is one-shot: a second call on the same instance throws
ALREADY_INITIALIZED. A hot restart keeps the native setup, so expect that code after one. - A failed setup never stops your app: requests go out without the header.
- Named instances:
TrustPinAttest.instance('payments')pairs withTrustPin.instance('payments'), which must be set up first. Pass that pinning instance to the HTTP integrations withinstance:.
Check: run the app with debug logging on (see Logging) and read the state. It reaches ready:
final state = await TrustPinAttest.shared.state;
debugPrint('$state'); // TrustPinAttestReady(expiresAt: …)On a simulator or emulator, pass a debug token first.
Bind tokens to the user’s session
A bound token is valid only with the session it was issued for. Only a SHA-256 of the value leaves the device; the value itself is never sent or logged.
| Mode | Call | Use it when |
|---|---|---|
| Header binding | await TrustPinAttest.shared.bindToHeader('Authorization') | Your requests carry the session in a header. Each request’s token is bound to that header’s value |
| Fixed binding | await TrustPinAttest.shared.setTokenBinding(sessionId) | You have one session value, or a transport without such a header (gRPC, WebSockets) |
- Each mode clears the other.
setTokenBinding(null)removes the fixed binding only.bindToHeader(null)stops header binding and also clears a fixed binding, so it removes every binding. - A binding change renews the token with the existing device key. It is not a new attestation.
prefetch()with header binding attests early but can’t bind yet; the first request carrying the header renews the token once more, cheaply.- With Require token binding on, no token exists until a binding is known: the state is failed with
BINDING_REQUIREDand anullretryAt. That’s expected before sign-in, and attestation resumes as soon as a binding is set.
Send the header
A. package:http. Use TrustPinHttpClient:
import 'package:trustpin_sdk/trustpin_sdk.dart';
final client = TrustPinHttpClient.create();
final response = await client.get(
Uri.parse('https://api.example.com/v1/items'),
headers: {'Authorization': 'Bearer $session'},
);B. Dio. Add TrustPinDioInterceptor, and pass it the Dio instance so it can follow redirects of attested requests:
import 'package:dio/dio.dart';
import 'package:trustpin_sdk/trustpin_sdk.dart';
final dio = Dio();
dio.interceptors.add(TrustPinDioInterceptor(dio: dio));C. Another HTTP client. Ask for the headers and add them yourself. attestationHeaders never throws; an empty map means no header for this request:
final url = Uri.parse('https://api.example.com/v1/items');
final headers = {'Authorization': 'Bearer $session'};
headers.addAll(await TrustPin.shared.attestationHeaders(url, headers: headers));If your client follows redirects itself, rebuild each hop’s headers with TrustPin.shared.redirectedRequestHeaders(newUrl, headers: headers).
D. Anything else (gRPC, WebSockets). Send await TrustPinAttest.shared.getToken() in the TrustPin-Attestation header (TrustPinAttest.headerName).
These rules apply to every path:
- HTTPS and attested hosts only. Other requests never get the header.
- A header the request already carries is kept. The integrations add theirs only when there is none.
- Redirects.
TrustPinHttpClientandTrustPinDioInterceptor(givendio:) follow redirects of attestedGETandHEADrequests themselves, pin each hop, and ask for a header for the new URL only. Withoutdio:, the redirect response reaches your code. - Bounded wait. When no token is ready in time, the request goes out without the header.
Sensitive operations
For an operation your backend must not accept on a reused token alone, such as a payment, send an assertion next to the token. It binds the device’s attested key to a SHA-256 digest of your choice, typically the request body. This example uses the crypto package:
import 'dart:convert';
import 'dart:typed_data';
import 'package:crypto/crypto.dart';
import 'package:http/http.dart' as http;
import 'package:trustpin_attest/trustpin_attest.dart';
import 'package:trustpin_sdk/trustpin_sdk.dart';
Future<http.Response> sendTransfer(TrustPinHttpClient client, String session) async {
final url = Uri.parse('https://api.example.com/v1/transfer');
final body = utf8.encode(jsonEncode({'amount': '1.00', 'to': 'demo'}));
final headers = {
'Authorization': 'Bearer $session',
'Content-Type': 'application/json',
};
final attest = TrustPinAttest.shared;
// With header binding, ask for this request's token first, so it is bound
// to this Authorization value; then add the token and the assertion.
headers.addAll(await attest.attestationHeaders(url, method: 'POST', headers: headers));
headers.addAll(await attest.assertionHeaders(Uint8List.fromList(sha256.convert(body).bytes)));
return client.post(url, headers: headers, body: body);
}assertionHeadersreturns both headers:TrustPin-Attestationwith the token andTrustPin-Assertion(TrustPinAttest.assertionHeaderName) with the assertion. Your backend passes both, with its own digest of what it received, to your verifier. See Assertions for sensitive operations.- Each call produces a new assertion, one per operation, and costs one round trip to your verifier besides your request.
- It throws
INVALID_DIGESTfor a digest that isn’t 32 bytes, and the same errorgetToken()would when no token is available.
Verify the token in your API
The header carries a signed JWT issued 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 without a valid token is your decision, per endpoint. See Verifying tokens in your API.
The token’s sub identifies the device key. It changes when the device attests a new key, so don’t use it as a stable device identifier.
Simulators, emulators and development
Simulators and emulators can’t provide evidence your policy accepts. For development, your verifier’s operator issues a debug token, and the policy (Allow debug tokens) and the verifier must both allow it. The setup code already passes one from the build; run with:
flutter run --dart-define=TRUSTPIN_DEBUG_TOKEN=<debug token>- iOS: used on the simulator only, never on a device.
- Android: used in debuggable builds, on emulators and real devices. To test real device evidence, run without the token or turn Allow debug tokens off. A debug token identifies the app by the package name it runs under, so a debug build with an
applicationIdSuffixmust be listed in the policy as its own package. - macOS: never used. Test on the Mac with the
developmententitlement and Accept development builds on. - Release builds never pass the token to the platform. Never put it in a file in the app.
- Debug tokens carry
tp.envdebug, which production APIs refuse.
State, errors and logging
await TrustPinAttest.shared.state returns the current state. stateChanges emits the current state first, then every change:
TrustPinAttest.shared.stateChanges.listen((state) {
switch (state) {
case TrustPinAttestUnavailable():
debugPrint('No token yet');
case TrustPinAttestAttesting():
debugPrint('Attesting…');
case TrustPinAttestReady(:final expiresAt):
debugPrint('Token ready until $expiresAt');
case TrustPinAttestFailed(:final error, :final retryAt):
debugPrint('Failed: ${error.code} ${error.reasons}, next attempt after ${retryAt ?? 'restart'}');
}
});Retry time. No timer runs after a failure: nothing is tried before retryAt, and the next request, getToken() or prefetch() after it starts a new attempt. A null retryAt means no new attempt in this launch, until reset() or a restart. The exception is BINDING_REQUIRED, which resumes as soon as a binding is set.
Errors are TrustPinAttestException, with a stable code (and getters such as isAttestationFailed), a message, and reasons for ATTESTATION_FAILED:
| Code | Meaning | What to do |
|---|---|---|
INVALID_CONFIGURATION | A configuration value was rejected, or the file is missing | Fix the keys; on iOS and macOS, check that TrustPin-Info.plist is in the Runner target |
ALREADY_INITIALIZED | Setup was called again on this instance | Set up once per launch. Expected after a hot restart |
NOT_SET_UP | Called before setup | Call setupWithNativeBundle first |
UNSUPPORTED_DEVICE | iOS and macOS: this device can’t attest the app (for example, a Mac without App Attest). All platforms: new keys keep failing on it | Expected on some hardware. No header is sent |
EVIDENCE_UNAVAILABLE | The device can’t produce the evidence the policy requires, or Play Integrity is needed and the app has no project number | Review Evidence, or configure the project number |
BINDING_REQUIRED | The policy requires a binding and none is set yet | Expected before sign-in |
ATTESTATION_FAILED | The verifier refused; reasons carries its codes, such as app_not_allowed | See Troubleshooting |
VERIFIER_UNAVAILABLE | The verifier couldn’t be reached securely, including when strict pinning refuses its host | Check the URL and the verifier. In strict mode, register its domain |
VERIFIER_INCOMPATIBLE | The verifier is older than contract version 2 | Upgrade the verifier to 1.0.0 or later. No app change is needed |
INVALID_DIGEST | assertionHeaders got a digest that isn’t 32 bytes | Hash the payload with SHA-256 first |
New codes can appear in a minor release, and other failures carry INVALID_ARGUMENTS, CANCELLED or ATTEST_ERROR: handle unknown ones.
Logging
Logging is off by default. Turn it on per instance in development; whether each request got the header is logged at debug. Without a listener on TrustPinAttest.logs, messages go to the platform log (Xcode console, logcat).
await TrustPinAttest.shared.setLogLevel(TrustPinAttestLogLevel.debug); // none, error, warning, info, debug
TrustPinAttest.logs.listen((log) {
debugPrint('[attest/${log.instanceId}] ${log.level.value}: ${log.message}');
});Log lines never contain tokens, key certificates, bound values or debug tokens.
Events
TrustPinAttest.shared.events delivers TrustPinAttestEvent values for your metrics: keys generated or replaced, attestations and renewals with their durations, refusals and waits with their end, unsupported devices, an unreachable verifier, and assertions. Only events after you start listening are delivered.
TrustPinAttest.shared.events.listen((event) {
switch (event) {
case TrustPinAttestAttestationSucceeded(:final duration):
debugPrint('Attested in ${duration.inMilliseconds} ms');
case TrustPinAttestRefused(:final retryAt):
debugPrint('Refused, next attempt after ${retryAt ?? 'restart'}');
default:
break;
}
});Events never carry a token, a key or a device identifier. New event types can appear in a minor release: keep a default case.
Reset and backups
await TrustPinAttest.shared.reset() discards the device key and token; the next request attests a new key, and the token’s sub changes. Use it for support flows, such as a “repair attestation” action, not routinely. It does nothing before setup.
Device keys and key certificates are never backed up or synced: a restored or reinstalled app attests again.
Rolling out
Start with the policy in Monitor (recommended to start), measure requests without a header and fail results, then switch to Enforce. See Rolling out: monitor to enforce.
Before a release build:
- The iOS and macOS entitlement says
production. - The policy lists the Play app signing certificate for builds from Google Play.
- Allow debug tokens is off in the production policy. Release builds never send a debug token.
- The log level is back to
noneorerror. google_cloud_project_numberis set only if the policy uses Play Integrity, and your Data safety form says so (see Privacy).
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Requests arrive without the header | The host isn’t in the attested hosts, the URL is http://, the request didn’t go through TrustPinHttpClient or TrustPinDioInterceptor, or there is no token yet | Check the host list and the client, read the state, and turn on debug logging |
Failed with UNSUPPORTED_DEVICE on the iOS simulator | No debug token | Run with --dart-define=TRUSTPIN_DEBUG_TOKEN=… |
ATTESTATION_FAILED with app_not_allowed | The app ID, package name or signing certificate isn’t in the policy | Add it. Builds from Google Play are signed with the Play app signing key |
ATTESTATION_FAILED with dev_environment | A development build on an Apple device, with Accept development builds off | Turn it on while testing |
Failed with VERIFIER_UNAVAILABLE every time | The verifier’s domain isn’t registered, the verifier is down, or its URL is wrong | Register the domain, then check the URL and the verifier |
ALREADY_INITIALIZED during development | A hot restart re-ran main() | Harmless; a full restart clears it |
| A Dio redirect returns the 3xx response | TrustPinDioInterceptor was created without dio: | Pass the Dio instance |
| The Android build fails with Kotlin metadata errors | The app builds with a Kotlin plugin older than 2.3.0 | Raise it in android/settings.gradle.kts |
Privacy
trustpin_attest sends evidence and tokens only to your own verifier, and nothing to TrustPin. Bound values never leave the device, and tokens identify a device key, not a person. On iOS and macOS the plugin and the native framework ship privacy manifests (no tracking, no collected data). On Android, with a Google Cloud project number configured, declare your use of the Play Integrity API in Play Console’s Data safety form. If you forward events to a third-party service, that disclosure is yours to make.
Next steps
- Verifying tokens in your API: the next step on the path.
- Rolling out: monitor to enforce
- Certificate pinning for Flutter
- trustpin_attest on pub.dev , and the sample app ’s Attestation tab