Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Update swift passkey assertion logic (#2180)

Leendert de Borst88a02c4645f4
diff --git a/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Passkey.swift b/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Passkey.swift
index 029d1ed00..7776a3d84 100644
--- a/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Passkey.swift
+++ b/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Passkey.swift
@@ -186,11 +186,33 @@ extension CredentialProviderViewController: PasskeyProviderDelegate {
prfInputs = extractPrfInputs(from: extensionInput)
}
- // Pick the credential algorithm from the RP's requested algorithms,
- // honoring RP preference order. Falls back to ES256 if none/unsupported.
+ /*
+ * Choose the credential algorithm from the RP’s requested list, preserving RP order.
+ * iOS only exposes this list through `supportedAlgorithms`.
+ *
+ * Note on iOS limitation: as of iOS 18, RS256 (-257) is not forwarded to credential provider
+ * extensions. Even if the RP requests RS256, iOS only provides ES256 (-7), so RS256
+ * registration cannot work on iOS. RS256 signing is still supported for passkeys
+ * created elsewhere and synced into the vault.
+ *
+ * This matches Apple’s embedded assertion behavior: Secure Enclave uses ES256
+ * because it supports elliptic-curve keys, not RSA keys.
+ * https://developer.apple.com/documentation/authenticationservices/creating-an-embedded-assertion
+ */
let requestedAlgorithms = passkeyRequest.supportedAlgorithms.map { $0.rawValue }
- let algorithm = (try? PasskeyAuthenticator.pickSupportedAlgorithm(requestedAlgorithms))
- ?? PasskeyAuthenticator.algES256
+
+ let algorithm: Int
+ do {
+ algorithm = try PasskeyAuthenticator.pickSupportedAlgorithm(requestedAlgorithms)
+ } catch {
+ // We don't support the requested algorithm, so decline the request.
+ extensionContext.cancelRequest(withError: NSError(
+ domain: ASExtensionErrorDomain,
+ code: ASExtensionError.failed.rawValue,
+ userInfo: [NSLocalizedDescriptionKey: "No supported passkey algorithm requested by the relying party"]
+ ))
+ return
+ }
// Store parameters for use in viewWillAppear
// Vault unlock and UI display will happen in viewWillAppear
@@ -336,6 +358,31 @@ extension CredentialProviderViewController: PasskeyProviderDelegate {
self.currentHostingController = hostingController
}
+ /// Maximum time to wait for a best-effort server sync/upload before proceeding offline.
+ /// Keeps passkey creation responsive when the server is slow or unreachable.
+ private static let bestEffortSyncTimeoutSeconds: TimeInterval = 5
+
+ /// Runs an async operation with a best-effort timeout.
+ /// Returns the operation's result, or `nil` if `seconds` elapse first.
+ /// On timeout the in-flight operation is cancelled (e.g. URLSession requests abort), so the
+ /// caller can proceed without blocking the user. The operation never returns `nil` itself, so a
+ /// `nil` result unambiguously means "timed out".
+ private func withBestEffortTimeout<T>(
+ seconds: TimeInterval,
+ operation: @escaping () async -> T
+ ) async -> T? {
+ await withTaskGroup(of: T?.self) { group in
+ group.addTask { await operation() }
+ group.addTask {
+ try? await Task.sleep(nanoseconds: UInt64(seconds * 1_000_000_000))
+ return nil
+ }
+ let result = await group.next() ?? nil
+ group.cancelAll()
+ return result
+ }
+ }
+
/**
* Create passkey directly in Swift (called when user clicks the button)
*/
@@ -357,12 +404,22 @@ extension CredentialProviderViewController: PasskeyProviderDelegate {
// Initialize WebApiService for vault sync/mutate and favicon extraction
let webApiService = WebApiService()
- // Step 1: Check server connectivity by syncing vault before creating passkey
+ // Step 1: Best-effort vault sync before creating the passkey.
+ // We try to sync immediately so the passkey is created on top of the latest vault,
+ // but we never let a slow or unreachable server block the user. If the sync doesn't
+ // finish within a few seconds we proceed offline: the passkey is stored locally and
+ // the vault stays marked dirty, so it syncs automatically on the next opportunity
+ // (main app launch or next autofill run).
viewModel.setLoading(true, message: NSLocalizedString("vault_syncing", comment: "Checking connection..."))
- let syncResult = await vaultStore.syncVaultWithServer(using: webApiService)
- if !syncResult.success && !syncResult.wasOffline {
- // Server connectivity check failed
+ let syncResult = await self.withBestEffortTimeout(seconds: Self.bestEffortSyncTimeoutSeconds) {
+ await vaultStore.syncVaultWithServer(using: webApiService)
+ }
+
+ // Only surface an error for a fast, definitive failure (e.g. session expired or
+ // password changed). A timeout (nil) or an offline result is treated as best-effort,
+ // and we continue creating the passkey locally.
+ if let syncResult, !syncResult.success, !syncResult.wasOffline {
viewModel.setLoading(false)
// Show appropriate error dialog based on error type
@@ -445,12 +502,18 @@ extension CredentialProviderViewController: PasskeyProviderDelegate {
)
}
- // Step 5: Upload vault changes to server
+ // Step 5: Best-effort upload of the new passkey to the server, bounded by the same
+ // timeout so a slow server can't hang the "creating passkey" overlay. On timeout or
+ // failure the passkey stays saved locally with the vault marked dirty and syncs later.
viewModel.setLoading(true, message: NSLocalizedString("creating_passkey", comment: "Uploading vault..."))
- do {
- try await vaultStore.mutateVault(using: webApiService)
- } catch {
- // Continue even if upload fails - passkey is saved locally
+ _ = await self.withBestEffortTimeout(seconds: Self.bestEffortSyncTimeoutSeconds) { () -> Bool in
+ do {
+ try await vaultStore.mutateVault(using: webApiService)
+ return true
+ } catch {
+ // Continue even if upload fails: the passkey is saved locally
+ return false
+ }
}
// Step 6: Update the IdentityStore with the new credential (async call)
diff --git a/apps/mobile-app/ios/Autofill/Structs/PasskeyRegistrationParams.swift b/apps/mobile-app/ios/Autofill/Structs/PasskeyRegistrationParams.swift
index da33ceb4f..b35b34155 100644
--- a/apps/mobile-app/ios/Autofill/Structs/PasskeyRegistrationParams.swift
+++ b/apps/mobile-app/ios/Autofill/Structs/PasskeyRegistrationParams.swift
@@ -19,4 +19,4 @@ public struct PasskeyRegistrationParams {
public let prfInputs: PrfInputs?
/// The chosen COSE credential algorithm (-7 ES256, -257 RS256)
public let algorithm: Int
-}
\ No newline at end of file
+}
diff --git a/apps/mobile-app/ios/VaultStoreKit/Passkeys/PasskeyAuthenticator.swift b/apps/mobile-app/ios/VaultStoreKit/Passkeys/PasskeyAuthenticator.swift
index 278c34af9..4dcdd2dbb 100644
--- a/apps/mobile-app/ios/VaultStoreKit/Passkeys/PasskeyAuthenticator.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/Passkeys/PasskeyAuthenticator.swift
@@ -336,150 +336,6 @@ public class PasskeyAuthenticator {
return kty
}
- // MARK: - RSA Key Management (RS256)
-
- /**
- * Generate an RSA-2048 key pair (returns the private SecKey).
- */
- private static func generateRsaKey() throws -> SecKey {
- let attributes: [String: Any] = [
- kSecAttrKeyType as String: kSecAttrKeyTypeRSA,
- kSecAttrKeySizeInBits as String: 2048
- ]
- var error: Unmanaged<CFError>?
- guard let key = SecKeyCreateRandomKey(attributes as CFDictionary, &error) else {
- throw PasskeyError.keyGenerationFailed
- }
- return key
- }
-
- /**
- * Extract (modulus, exponent) from an RSA private key's public component.
- * SecKeyCopyExternalRepresentation of an RSA public key is PKCS#1
- * RSAPublicKey ::= SEQUENCE { modulus INTEGER, publicExponent INTEGER }.
- */
- private static func rsaModulusAndExponent(privateKey: SecKey) throws -> (n: Data, e: Data) {
- guard let publicKey = SecKeyCopyPublicKey(privateKey) else {
- throw PasskeyError.invalidPublicKey
- }
- var error: Unmanaged<CFError>?
- guard let der = SecKeyCopyExternalRepresentation(publicKey, &error) as Data? else {
- throw PasskeyError.invalidPublicKey
- }
- let ints = try parseDerIntegerSequence(der)
- guard ints.count == 2 else { throw PasskeyError.invalidPublicKey }
- return (ints[0], ints[1])
- }
-
- /**
- * Export RSA public key as JWK: {kty: "RSA", n, e}.
- */
- private static func exportRsaPublicKeyAsJWK(privateKey: SecKey) throws -> Data {
- let (n, e) = try rsaModulusAndExponent(privateKey: privateKey)
- let jwk: [String: Any] = [
- "kty": "RSA",
- "n": n.base64URLEncodedString(),
- "e": e.base64URLEncodedString()
- ]
- return try JSONSerialization.data(withJSONObject: jwk)
- }
-
- /**
- * Export RSA private key as JWK: {kty: "RSA", n, e, d, p, q, dp, dq, qi}.
- * SecKeyCopyExternalRepresentation of an RSA private key is PKCS#1
- * RSAPrivateKey ::= SEQUENCE { version, modulus, publicExponent, privateExponent,
- * prime1, prime2, exponent1, exponent2, coefficient } (9 INTEGERs).
- */
- private static func exportRsaPrivateKeyAsJWK(privateKey: SecKey) throws -> Data {
- var error: Unmanaged<CFError>?
- guard let der = SecKeyCopyExternalRepresentation(privateKey, &error) as Data? else {
- throw PasskeyError.invalidPrivateKey
- }
- let ints = try parseDerIntegerSequence(der)
- guard ints.count >= 9 else { throw PasskeyError.invalidPrivateKey }
- let jwk: [String: Any] = [
- "kty": "RSA",
- "n": ints[1].base64URLEncodedString(),
- "e": ints[2].base64URLEncodedString(),
- "d": ints[3].base64URLEncodedString(),
- "p": ints[4].base64URLEncodedString(),
- "q": ints[5].base64URLEncodedString(),
- "dp": ints[6].base64URLEncodedString(),
- "dq": ints[7].base64URLEncodedString(),
- "qi": ints[8].base64URLEncodedString()
- ]
- return try JSONSerialization.data(withJSONObject: jwk)
- }
-
- /**
- * Import an RSA private key from JWK and sign data with RS256
- * (RSASSA-PKCS1-v1.5 over SHA-256). The ".message" variant hashes the
- * input internally, matching how P256.signature(for:) hashes its input.
- */
- private static func signRsa(jwkData: Data, dataToSign: Data) throws -> Data {
- let key = try importRsaPrivateKeyFromJWK(jwkData: jwkData)
- var error: Unmanaged<CFError>?
- guard let sig = SecKeyCreateSignature(
- key,
- .rsaSignatureMessagePKCS1v15SHA256,
- dataToSign as CFData,
- &error
- ) as Data? else {
- throw PasskeyError.invalidSignature
- }
- return sig
- }
-
- /**
- * Build a PKCS#1 RSAPrivateKey from a JWK and import it as a SecKey.
- */
- private static func importRsaPrivateKeyFromJWK(jwkData: Data) throws -> SecKey {
- guard let jwk = try JSONSerialization.jsonObject(with: jwkData) as? [String: Any],
- let nB64 = jwk["n"] as? String,
- let eB64 = jwk["e"] as? String,
- let dB64 = jwk["d"] as? String,
- let pB64 = jwk["p"] as? String,
- let qB64 = jwk["q"] as? String,
- let dpB64 = jwk["dp"] as? String,
- let dqB64 = jwk["dq"] as? String,
- let qiB64 = jwk["qi"] as? String else {
- throw PasskeyError.invalidJWK
- }
-
- let n = try Data(base64URLEncoded: nB64)
- let e = try Data(base64URLEncoded: eB64)
- let d = try Data(base64URLEncoded: dB64)
- let p = try Data(base64URLEncoded: pB64)
- let q = try Data(base64URLEncoded: qB64)
- let dp = try Data(base64URLEncoded: dpB64)
- let dq = try Data(base64URLEncoded: dqB64)
- let qi = try Data(base64URLEncoded: qiB64)
-
- // PKCS#1 RSAPrivateKey DER (version 0, two-prime)
- let der = derSequence([
- derInteger(Data([0x00])), // version
- derInteger(n),
- derInteger(e),
- derInteger(d),
- derInteger(p),
- derInteger(q),
- derInteger(dp),
- derInteger(dq),
- derInteger(qi)
- ])
-
- let attributes: [String: Any] = [
- kSecAttrKeyType as String: kSecAttrKeyTypeRSA,
- kSecAttrKeyClass as String: kSecAttrKeyClassPrivate,
- kSecAttrKeySizeInBits as String: n.count * 8
- ]
- var error: Unmanaged<CFError>?
- guard let key = SecKeyCreateWithData(der as CFData, attributes as CFDictionary, &error) else {
- throw PasskeyError.invalidPrivateKey
- }
- return key
- }
-
// MARK: - CBOR Encoding
/**
@@ -541,6 +397,7 @@ public class PasskeyAuthenticator {
* CBOR map: {1: 3 (kty: RSA), 3: -257 (alg: RS256), -1: n (modulus), -2: e (exponent)}
*/
private static func buildCoseRsaRs256(privateKey: SecKey) throws -> Data {
+ // swiftlint:disable:next identifier_name - n/e are the standard RSA modulus/exponent names (RFC 8230)
let (n, e) = try rsaModulusAndExponent(privateKey: privateKey)
var cbor = Data()
@@ -798,6 +655,160 @@ public class PasskeyAuthenticator {
}
}
+// MARK: - RSA Key Management (RS256)
+
+/*
+ * RSA helpers live in an extension to keep the main type body within SwiftLint's
+ * type_body_length limit. Same-file `private` access keeps them callable from the class.
+ */
+extension PasskeyAuthenticator {
+
+ /**
+ * Generate an RSA-2048 key pair (returns the private SecKey).
+ */
+ private static func generateRsaKey() throws -> SecKey {
+ let attributes: [String: Any] = [
+ kSecAttrKeyType as String: kSecAttrKeyTypeRSA,
+ kSecAttrKeySizeInBits as String: 2048
+ ]
+ var error: Unmanaged<CFError>?
+ guard let key = SecKeyCreateRandomKey(attributes as CFDictionary, &error) else {
+ throw PasskeyError.keyGenerationFailed
+ }
+ return key
+ }
+
+ /**
+ * Extract (modulus, exponent) from an RSA private key's public component.
+ * SecKeyCopyExternalRepresentation of an RSA public key is PKCS#1
+ * RSAPublicKey ::= SEQUENCE { modulus INTEGER, publicExponent INTEGER }.
+ */
+ private static func rsaModulusAndExponent(privateKey: SecKey) throws -> (n: Data, e: Data) {
+ guard let publicKey = SecKeyCopyPublicKey(privateKey) else {
+ throw PasskeyError.invalidPublicKey
+ }
+ var error: Unmanaged<CFError>?
+ guard let der = SecKeyCopyExternalRepresentation(publicKey, &error) as Data? else {
+ throw PasskeyError.invalidPublicKey
+ }
+ let ints = try parseDerIntegerSequence(der)
+ guard ints.count == 2 else { throw PasskeyError.invalidPublicKey }
+ return (ints[0], ints[1])
+ }
+
+ /**
+ * Export RSA public key as JWK: {kty: "RSA", n, e}.
+ */
+ private static func exportRsaPublicKeyAsJWK(privateKey: SecKey) throws -> Data {
+ // swiftlint:disable:next identifier_name - n/e are the standard RSA modulus/exponent names (RFC 8230)
+ let (n, e) = try rsaModulusAndExponent(privateKey: privateKey)
+ let jwk: [String: Any] = [
+ "kty": "RSA",
+ "n": n.base64URLEncodedString(),
+ "e": e.base64URLEncodedString()
+ ]
+ return try JSONSerialization.data(withJSONObject: jwk)
+ }
+
+ /**
+ * Export RSA private key as JWK: {kty: "RSA", n, e, d, p, q, dp, dq, qi}.
+ * SecKeyCopyExternalRepresentation of an RSA private key is PKCS#1
+ * RSAPrivateKey ::= SEQUENCE { version, modulus, publicExponent, privateExponent,
+ * prime1, prime2, exponent1, exponent2, coefficient } (9 INTEGERs).
+ */
+ private static func exportRsaPrivateKeyAsJWK(privateKey: SecKey) throws -> Data {
+ var error: Unmanaged<CFError>?
+ guard let der = SecKeyCopyExternalRepresentation(privateKey, &error) as Data? else {
+ throw PasskeyError.invalidPrivateKey
+ }
+ let ints = try parseDerIntegerSequence(der)
+ guard ints.count >= 9 else { throw PasskeyError.invalidPrivateKey }
+ let jwk: [String: Any] = [
+ "kty": "RSA",
+ "n": ints[1].base64URLEncodedString(),
+ "e": ints[2].base64URLEncodedString(),
+ "d": ints[3].base64URLEncodedString(),
+ "p": ints[4].base64URLEncodedString(),
+ "q": ints[5].base64URLEncodedString(),
+ "dp": ints[6].base64URLEncodedString(),
+ "dq": ints[7].base64URLEncodedString(),
+ "qi": ints[8].base64URLEncodedString()
+ ]
+ return try JSONSerialization.data(withJSONObject: jwk)
+ }
+
+ /**
+ * Import an RSA private key from JWK and sign data with RS256
+ * (RSASSA-PKCS1-v1.5 over SHA-256). The ".message" variant hashes the
+ * input internally, matching how P256.signature(for:) hashes its input.
+ */
+ private static func signRsa(jwkData: Data, dataToSign: Data) throws -> Data {
+ let key = try importRsaPrivateKeyFromJWK(jwkData: jwkData)
+ var error: Unmanaged<CFError>?
+ guard let sig = SecKeyCreateSignature(
+ key,
+ .rsaSignatureMessagePKCS1v15SHA256,
+ dataToSign as CFData,
+ &error
+ ) as Data? else {
+ throw PasskeyError.invalidSignature
+ }
+ return sig
+ }
+
+ /**
+ * Build a PKCS#1 RSAPrivateKey from a JWK and import it as a SecKey.
+ */
+ private static func importRsaPrivateKeyFromJWK(jwkData: Data) throws -> SecKey {
+ guard let jwk = try JSONSerialization.jsonObject(with: jwkData) as? [String: Any],
+ let nB64 = jwk["n"] as? String,
+ let eB64 = jwk["e"] as? String,
+ let dB64 = jwk["d"] as? String,
+ let pB64 = jwk["p"] as? String,
+ let qB64 = jwk["q"] as? String,
+ let dpB64 = jwk["dp"] as? String,
+ let dqB64 = jwk["dq"] as? String,
+ let qiB64 = jwk["qi"] as? String else {
+ throw PasskeyError.invalidJWK
+ }
+
+ // swiftlint:disable identifier_name - n/e/d/p/q/dp/dq/qi are the standard RSA/JWK component names (RFC 7518)
+ let n = try Data(base64URLEncoded: nB64)
+ let e = try Data(base64URLEncoded: eB64)
+ let d = try Data(base64URLEncoded: dB64)
+ let p = try Data(base64URLEncoded: pB64)
+ let q = try Data(base64URLEncoded: qB64)
+ let dp = try Data(base64URLEncoded: dpB64)
+ let dq = try Data(base64URLEncoded: dqB64)
+ let qi = try Data(base64URLEncoded: qiB64)
+ // swiftlint:enable identifier_name
+
+ // PKCS#1 RSAPrivateKey DER (version 0, two-prime)
+ let der = derSequence([
+ derInteger(Data([0x00])), // version
+ derInteger(n),
+ derInteger(e),
+ derInteger(d),
+ derInteger(p),
+ derInteger(q),
+ derInteger(dp),
+ derInteger(dq),
+ derInteger(qi)
+ ])
+
+ let attributes: [String: Any] = [
+ kSecAttrKeyType as String: kSecAttrKeyTypeRSA,
+ kSecAttrKeyClass as String: kSecAttrKeyClassPrivate,
+ kSecAttrKeySizeInBits as String: n.count * 8
+ ]
+ var error: Unmanaged<CFError>?
+ guard let key = SecKeyCreateWithData(der as CFData, attributes as CFDictionary, &error) else {
+ throw PasskeyError.invalidPrivateKey
+ }
+ return key
+ }
+}
+
// MARK: - Supporting Types
public struct PasskeyCreationResult {