Close identity and adoption holes in credential scoping

Four issues from an external review of the previous commit.

The scope was resolved once at startup, so signing out or switching Apple
account while the app kept running left it pinned to the old identity -
reads and writes would then reach the previous account's retained
credentials, which is the exact leak scoping exists to prevent.
CredentialIdentityScope now observes NSUbiquityIdentityDidChange and
re-resolves.

Legacy deletion authority checked only the instance and the identity, not
the account. On an instance with several accounts, deleting any of them
satisfied the marker lookup and could retire the legacy item another
account had adopted, logging out devices still on the previous release.
The marker's accountID is now required to match.

A first-time resolution that failed (launched offline, CloudKit
unreachable) was never retried, disabling credentials for the rest of the
process. resolve() now retries with backoff, and resolveIfNeeded() runs on
foreground activation.

Adoption re-checked nothing at execution time, so a scoped credential
delivered by iCloud Keychain between rendering the offer and tapping it
would be overwritten with the older legacy secret. Adoption now re-verifies
eligibility and writes with a non-replacing add, leaving a duplicate
strictly alone.

Adds regression tests for the sibling-account deletion and the adoption
race.
This commit is contained in:
Arkadiusz Fal
2026-08-23 23:39:06 +02:00
parent 9fd0a71035
commit c4053d5100
6 changed files with 215 additions and 30 deletions

View File

@@ -72,6 +72,25 @@ struct KeychainCredentialStore: Sendable {
return value
}
/// Writes a value **only if the key is currently empty**, returning
/// `errSecDuplicateItem` otherwise.
///
/// Used by legacy adoption: between rendering the offer and the user
/// tapping it, iCloud Keychain may deliver the real scoped credential, and
/// a replacing write would silently overwrite it with the older secret.
@discardableResult
func addIfAbsent(_ value: String, forKey key: String, synchronizable: Bool) -> OSStatus {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: service,
kSecAttrAccount as String: key,
kSecAttrSynchronizable as String: synchronizable,
kSecValueData as String: Data(value.utf8)
]
return SecItemAdd(query as CFDictionary, nil)
}
/// Writes a value, replacing any existing item in either synchronizable form.
@discardableResult
func set(_ value: String, forKey key: String, synchronizable: Bool) -> OSStatus {