0018 · iOS app: klav-ffi with uniffi, Face ID with the Secure Enclave, Credential Provider without network and approvals over APNs
- Status: accepted
- Date: 2026-11-03
Context
Phase 6 brings the iOS app (design §8, roadmap): unlock with Face ID, view, search and edit items, a Credential Provider Extension with passwords and one-time codes, push approvals and approving agent registration from the phone. ADR 0001 establishes that mobile uses the Rust core through uniffi with a native UI; 0011 put the client logic in klav-client and made the local key derived; 0013 solved Touch ID on the Mac with a CryptoKit shim. We need to decide:
- what
klav-ffiexposes and where the cryptography sits; - what the app stores, where and with what protection;
- how Face ID works, including in the simulator;
- how the extension unlocks and how it fits in its memory;
- how approvals reach the phone (APNs) and what the server signs with;
- how an agent is approved from the phone;
- how the Xcode project is generated, the minimum iOS version and CI.
Decision
1. klav-ffi: a KlavCore object on top of klav-client, with uniffi
- uniffi 0.32 with macros (
#[uniffi::export], no UDL).klav-ffiwrapsklav-client, notklav-coredirectly: the app does the same as the CLI (sign in on a new device, unlock, sync, CRUD, TOTP, approvals, agents) and a second client in Swift makes no sense. - Swift does no cryptography except the Secure Enclave's (creating the key, ECDH), the same as ADR 0013. HKDF, sealing the local key (type
0x42), the cache, OPAQUE, HPKE and signatures stay inklav-core. - Synchronous interface.
KlavCoreholds its own Tokio runtime and each method blocks until it finishes. The app calls them off the main thread (Task.detached). uniffi'sasyncfunctions would need thetokiofeature and an executor that crosses the FFI; blocking is simpler to test from Rust and is enough for an app with a single account. - The platform keystore is a Swift interface (
trait PlatformKeystorewith#[uniffi::export(with_foreign)]):create_key,wrapandunwrap(handle, ephemeral, reason), the same shape asklav-touchid. Rust stores the enrollment (faceid.json, same format astouchid.json), checks the policy (password every 14 days and after a restart) and seals or opens the local key; Swift only provides the Secure Enclave. - Errors as a uniffi
enumwith the cases the UI tells apart (wrong password, locked, no network, rollback, security, biometrics canceled or unavailable, password required, not found, conflict, invalid). Messages never carry values. unsafe: the code generated by uniffi hasextern "C"functions. The crate already allowsunsafe(withunsafe_code = "warn"); its own code has nounsafeblocks.uniffi-bindgenis a binary of the crate itself behind thebindgenfeature, so that the generator version is always the library's. Normal builds don't compileclapor the templates.- Licenses: uniffi is MPL-2.0 (per-file copyleft: it can be distributed inside an Apache-2.0 app as long as its files aren't modified). It comes in as an exception in
deny.tomlonly for theuniffi*crates. The generator pulls inbasic-toml(unmaintained, RUSTSEC-2026-0374) throughaskama; it is ignored with a reason because it only runs when generating the bindings and doesn't ship in the app. - XCFramework:
scripts/ios/build-xcframework.shbuildsklav-ffias astaticlibforaarch64-apple-iosandaarch64-apple-ios-sim, generates the bindings in library mode and assemblestarget/ios/KlavFFI.xcframework(header +module.modulemap) andtarget/ios/bindings/klav_ffi.swift. Everything undertarget/; nothing generated is committed. There is nox86_64slice: Intel Macs are left out of the simulator.
Secrets that cross the FFI as a Swift String: the master password and the Secret Key going in, and the revealed values, the password the extension fills and the TOTP codes going out. Swift can't zero them; the copy lives as long as the view does. It is the same trade-off as T33 (klavd socket) and it stays in the threat model.
2. What the app stores, where and with what protection
- The iOS
KLAV_HOMEis<contenedor del App Group>/klav, shared by the app and the extension:account.json,secret-key,session.bin,cache.bin(the last two sealed with the local key, as on the Mac) andfaceid.json. The app'sDocumentsdirectory is not used. completedata protection (NSFileProtectionComplete): the directory is created with that class and the files inherit it; the app applies it again after writing. The files can only be read with the phone unlocked. The app never touches the vault in the background with the phone locked: a notification is only shown, and the data is read when it is opened. Thecom.apple.developer.default-data-protection(NSFileProtectionComplete) entitlement reinforces it on real devices.- The Secret Key stays in a file, as on the Mac (ADR 0011 §5): on its own it opens nothing without the password, and the Keychain would force a second store with access groups. The App Group container isn't included in third-party iCloud backups and other apps can't see it.
- Preferences with no secrets (auto-lock, keyboard suggestions) in the App Group's
UserDefaults.
3. Face ID: the Secure Enclave wraps the local key
- Same as ADR 0013 and spec §12.3: a P-256 key in the Secure Enclave with
privateKeyUsage+biometryCurrentSet, stored asdataRepresentation(not in the Keychain). The first password unlock sets up Face ID without a dialog; each password unlock rewraps with a new ephemeral pair. Boot time (kern.boottime) also exists on iOS. - When unwrapping, Swift first authenticates with
LAContext.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics)and passes that context to the key: that way "canceled" is told apart from "the key no longer works" (biometrics changed → the enrollment is deleted and the password is asked for). - Simulator: the simulator has no Secure Enclave. In
DEBUGbuilds for the simulator (#if targetEnvironment(simulator) && DEBUG) the app usesSimulatorKeystore: a software P-256 key (CryptoKit) stored in a file in the container, behind the sameLAContext(simulated Face ID). That code doesn't exist in device or release builds: the compiler excludes it, and the app flags it in Settings ("Simulated Face ID"). On a device without a Secure Enclave, Face ID is simply not available. NSFaceIDUsageDescriptionexplains the use.
4. Credential Provider Extension: Face ID only, no network, read-only
- It never derives the KEK. Argon2id with 256 MiB doesn't fit in an extension's memory budget. The extension only unlocks with the local key wrapped by the Secure Enclave, with its own Face ID dialog (its own
LAContext). If there is no enrollment, if the policy asks for the password (14 days or a restart) or if the biometrics changed, it shows "Open Klav first" with the reason and doesn't offer to type the password. - No network and read-only. The extension opens
cache.binand computes the TOTP codes locally; it doesn't sync or renew tokens. That way it never competes with the app for the single-use refresh token (ADR 0011 §7). What it sees is what the app's last sync left. - No shared plaintext state. The app leaves nothing decrypted for the extension: there is no shared "unlocked" state; each process opens the cache on its own and drops the keys when it finishes.
- Site matching: the same rule as the browser extension and the SDK (
klav_core::site, ADR 0017 §5): the service's host must be the host of one of the item's URLs or a subdomain of it,www.is ignored, no Public Suffix List.klav-ffichecks it again when handing over a password or a code, not only when listing. - Keyboard suggestions (QuickType): the app registers in
ASCredentialIdentityStoreidentities with the domain, username and item ID (passwords) and, on iOS 18, one-time code identities. They are metadata that iOS keeps outside Klav; never secrets. They can be turned off in Settings (they are deleted from the store). - Memory: the limit isn't public and changes between versions; it is measured with
phys_footprintin the simulator and noted inios.md. The budget this ADR sets is to stay well below 50 MiB: a cache of a few hundred items, no Argon2id and no network. - Not verified in the simulator: that the
dataRepresentationof the Secure Enclave key works from the extension (another process, same device). The handle is encrypted by the device's enclave and doesn't depend on the bundle, so it should work; it is checked on Omar's iPhone (probar-fase-6.md).
5. Approvals over APNs
- The server sends with token authentication (
.p8, ES256):[push.apns]in the configuration orKLAV_APNS_KEY_PATH,KLAV_APNS_KEY_ID,KLAV_APNS_TEAM_ID,KLAV_APNS_TOPIC. If it isn't configured, nothing is sent and everything works as before. The key is read from the file at startup and is never logged. - Device token registration:
PUT /v1/devices/current/pushwith{token, environment: "sandbox"|"production"}andDELETEto remove it. One is stored per device (migration0009in SQLite and Postgres). Revoking the device or signing it out deletes it. So does a410/BadDeviceTokenfrom Apple. - The payload carries no server text and no secrets:
{"aps": {"alert": {"title-loc-key": "PUSH_APPROVAL_TITLE", "loc-key": "PUSH_APPROVAL_BODY"}, "sound": "default", "thread-id": "approval"}, "klav": {"type": "approval", "id": "<approval_id>"}}(orPUSH_AGENT_TITLE/PUSH_AGENT_BODYand"type": "agent"with the agent ID). The app supplies the text with its localized strings. Neither the agent's name, nor the reason, nor the item go through Apple; the app asks the server for them when the notification is opened. - When: when a pending approval (
ask) is created and when an agent registration request arrives. Sends go in a separate task after saving: an APNs failure never breaks the agent's request. - Against spam:
POST /v1/agents/registerisn't authenticated (anyone who knows the email can ask). In addition to the maximum of 20 pending requests, the server sends at most 5 registration pushes per account per hour; the other requests are still visible in the app. - ES256 signature with
aws-lc-rs, not withp256/ecdsa: those RustCrypto crates, in the version in the tree, usecrypto-bigint0.5.5, which has timing leaks (RUSTSEC-2026-0387). Today that advisory is ignored because no secret goes through that arithmetic (ADR 0009); signing with the APNs key would be exactly that.aws-lc-rsis already approved for client TLS (ADR 0011), the server needs it anyway to speak HTTP/2 over TLS with Apple (reqwestwithrustls), and its ECDSA P-256 is constant-time. It is transport authentication, not vault cryptography: it doesn't enterklav-coreand doesn't change ADR 0005. The JWT is renewed every 40 minutes (Apple asks for between 20 and 60). - Relay for self-hosters: phase 8. Until then, a self-hosted server can only send to an app signed with its own APNs key.
6. Approving an agent from the phone
- The app lists the pending registration requests and shows the 6 words (spec §13.1). The person picks which projects to share, compares the words with the ones in the agent's terminal and confirms with Face ID.
klav-clientrecomputes the words from the identity the server gives before signing the grant (ADR 0014 §1.3). - The policy is that of
klav agent approvewith no options (the defaults from design §5.2); fine-grained permissions, domains and schedule stay in the CLI. Optional: expiry (1 day, 7 days, 30 days or no expiry). - Action approvals (
ask) are decided the same way as in the CLI: deny, approve once or approve for 15 minutes, always with Face ID (no key: presence). Without Face ID, with the phone's passcode (deviceOwnerAuthentication).
7. Project, minimum version and CI
- XcodeGen:
apps/ios/project.ymlis committed; the.xcodeprojis generated (xcodegen generate) and is in.gitignore. The development team and the bundle ID prefix go inapps/ios/Config/Local.xcconfig(not committed; there is a template), so no account details are fixed in the repository. By default:dev.klav.ios,dev.klav.ios.credentialsand the App Groupgroup.dev.klav.ios. - iOS 18 minimum: it is the version that lets a Credential Provider Extension offer one-time codes.
- SwiftUI, with no third-party Swift dependencies.
- DerivedData in
target/: the scripts pass-derivedDataPath, by defaulttarget/xcode/ios-derived, which is on an external disk whentarget/is a link there (overridable withKLAV_IOS_DERIVEDor the local build config, ios.md §5). - CI stays on Linux. macOS runners cost 10 times more on a private repository. In CI:
klav-ffiis built and tested with the rest of the workspace, and one step generates the Swift bindings in library mode (it catches an interface uniffi can't export). The iOS build andxcodebuild testin the simulator are a local gate before each iOS PR (scripts/ios/test.sh). If the repository becomes public (free macOS runners), a macOS job is added. - Network: Rust opens its own sockets, so App Transport Security doesn't apply to
klav-client;http://127.0.0.1only works in development becauseklav-clientalready limits it to loopback (ADR 0011).
8. Implementation defaults
They were chosen by whoever implemented the phase, without consulting anyone. Changing them doesn't touch the cryptography or the protocol:
- Auto-lock: 1 minute in the background (options: on leaving, 1, 5 or 15 minutes, 1 hour).
- Face ID and keyboard suggestions: on by default.
- Notification permission: asked after the first unlock, not on install.
- Agent requests: "Approve once" is the main action. "Approve 15 min" is the secondary one. Deny doesn't ask for Face ID.
- Expiry when approving an agent: "No end", like
klav agent approvewithout--expires. If the account has a single project, it comes already selected. - Requests without APNs: the app fetches them again every 8 s while it is in the foreground.
- Clipboard: local to the device (no Handoff) and expires after 30 s, like the browser extension.
Consequences
klav-ffigains uniffi (MPL-2.0, exception indeny.toml) and stops being an empty crate. Building it for iOS needs theaarch64-apple-iosandaarch64-apple-ios-simtargets and Xcode.klav-servergainsreqwestwithrustls/aws-lc-rsand HTTP/2 (the Docker image buildsaws-lc-syswith the C compiler it already ships).- What can't be tested without Omar: real Face ID, the Secure Enclave key from the extension, real APNs (sandbox and production), the extension on the iPhone and TestFlight. It stays as a list in
probar-fase-6.mdand in the roadmap. - The extension doesn't see what changed since the app's last sync; opening the app syncs.
- An iPhone without Face ID or Touch ID, or with an expired policy, doesn't autofill until the app is opened.