Klav Atlas

0018 · iOS app: klav-ffi with uniffi, Face ID with the Secure Enclave, Credential Provider without network and approvals over APNs

Mainmainfe8e2a0c8c24· 2026-12-05

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:

  1. what klav-ffi exposes and where the cryptography sits;
  2. what the app stores, where and with what protection;
  3. how Face ID works, including in the simulator;
  4. how the extension unlocks and how it fits in its memory;
  5. how approvals reach the phone (APNs) and what the server signs with;
  6. how an agent is approved from the phone;
  7. 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-ffi wraps klav-client, not klav-core directly: 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 in klav-core.
  • Synchronous interface. KlavCore holds its own Tokio runtime and each method blocks until it finishes. The app calls them off the main thread (Task.detached). uniffi's async functions would need the tokio feature 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 PlatformKeystore with #[uniffi::export(with_foreign)]): create_key, wrap and unwrap(handle, ephemeral, reason), the same shape as klav-touchid. Rust stores the enrollment (faceid.json, same format as touchid.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 enum with 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 has extern "C" functions. The crate already allows unsafe (with unsafe_code = "warn"); its own code has no unsafe blocks.
  • uniffi-bindgen is a binary of the crate itself behind the bindgen feature, so that the generator version is always the library's. Normal builds don't compile clap or 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.toml only for the uniffi* crates. The generator pulls in basic-toml (unmaintained, RUSTSEC-2026-0374) through askama; 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.sh builds klav-ffi as a staticlib for aarch64-apple-ios and aarch64-apple-ios-sim, generates the bindings in library mode and assembles target/ios/KlavFFI.xcframework (header + module.modulemap) and target/ios/bindings/klav_ffi.swift. Everything under target/; nothing generated is committed. There is no x86_64 slice: 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_HOME is <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) and faceid.json. The app's Documents directory is not used.
  • complete data 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. The com.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 as dataRepresentation (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 DEBUG builds for the simulator (#if targetEnvironment(simulator) && DEBUG) the app uses SimulatorKeystore: a software P-256 key (CryptoKit) stored in a file in the container, behind the same LAContext (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.
  • NSFaceIDUsageDescription explains 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.bin and 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-ffi checks it again when handing over a password or a code, not only when listing.
  • Keyboard suggestions (QuickType): the app registers in ASCredentialIdentityStore identities 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_footprint in the simulator and noted in ios.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 dataRepresentation of 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 or KLAV_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/push with {token, environment: "sandbox"|"production"} and DELETE to remove it. One is stored per device (migration 0009 in SQLite and Postgres). Revoking the device or signing it out deletes it. So does a 410/BadDeviceToken from 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>"}} (or PUSH_AGENT_TITLE/PUSH_AGENT_BODY and "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/register isn'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 with p256/ecdsa: those RustCrypto crates, in the version in the tree, use crypto-bigint 0.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-rs is already approved for client TLS (ADR 0011), the server needs it anyway to speak HTTP/2 over TLS with Apple (reqwest with rustls), and its ECDSA P-256 is constant-time. It is transport authentication, not vault cryptography: it doesn't enter klav-core and 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-client recomputes the words from the identity the server gives before signing the grant (ADR 0014 §1.3).
  • The policy is that of klav agent approve with 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.yml is committed; the .xcodeproj is generated (xcodegen generate) and is in .gitignore. The development team and the bundle ID prefix go in apps/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.credentials and the App Group group.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 default target/xcode/ios-derived, which is on an external disk when target/ is a link there (overridable with KLAV_IOS_DERIVED or the local build config, ios.md §5).
  • CI stays on Linux. macOS runners cost 10 times more on a private repository. In CI: klav-ffi is 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 and xcodebuild test in 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.1 only works in development because klav-client already 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 approve without --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-ffi gains uniffi (MPL-2.0, exception in deny.toml) and stops being an empty crate. Building it for iOS needs the aarch64-apple-ios and aarch64-apple-ios-sim targets and Xcode.
  • klav-server gains reqwest with rustls/aws-lc-rs and HTTP/2 (the Docker image builds aws-lc-sys with 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.md and 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.