diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Core/Wallet/WalletStorage.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Core/Wallet/WalletStorage.swift index e468cc44406..e4917d293c1 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/Core/Wallet/WalletStorage.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Core/Wallet/WalletStorage.swift @@ -26,6 +26,11 @@ import Security /// with the original name/description after a reinstall. /// * Enumeration of stored wallet ids (used by the orphan-mnemonic /// recovery flow in `ContentView`). +/// * A non-secret per-wallet presence marker at +/// `wallet.present.<64-char-hex-walletId>` under the sibling +/// service `.presence`, readable after the first +/// unlock so a locked device can still answer "does a wallet +/// exist?" — see [`walletPresence()`](x-source-tag://walletPresence). /// * Biometric-protected seed stash at `wallet.biometric` — not yet /// wired to a caller but kept because it's a different category /// (hardware-protected rather than a legacy PIN construct). @@ -57,6 +62,24 @@ public class WalletStorage { public static let metadataAccountPrefix = "wallet.metadata" private let biometricKeychainAccount = "wallet.biometric" + /// Keychain service for the per-wallet presence markers: + /// `.presence`. + /// + /// A sibling service rather than `keychainService` itself on purpose. + /// The markers are `AfterFirstUnlock` while every other per-wallet item + /// is `WhenUnlocked`, and a service-wide `SecItemCopyMatching` over a + /// mix of the two behaves badly on a locked device whichever way + /// securityd resolves it: fail the whole query and the marker is + /// unreadable exactly when it is needed; drop the locked rows and + /// `listWalletIdsWithMnemonic()` would return an empty inventory + /// instead of an error. Keeping each service homogeneous keeps both + /// answers honest. Derived from `keychainService` so the + /// `DASH_KEYCHAIN_SERVICE` override applies to both. + public static let presenceKeychainService = "\(keychainService).presence" + /// Base account string used to build per-wallet presence-marker + /// accounts via `perWalletPresenceMarkerAccount(for:)`. + public static let presenceMarkerAccountPrefix = "wallet.present" + public init() {} // MARK: - Per-Wallet Mnemonic Storage @@ -71,24 +94,49 @@ public class WalletStorage { } /// Store a mnemonic keyed by wallet id. + /// + /// Also maintains the wallet's presence marker (see `walletPresence()`) + /// under the invariant *marker ⇒ a mnemonic was stored*. The steps run + /// in the one order that keeps it across an interruption at any + /// point: the marker comes off before the old mnemonic is deleted, + /// and goes back on only after the new mnemonic is in place. A + /// process killed in between leaves at most a mnemonic without a + /// marker — the one direction of drift the presence read repairs — + /// never a marker without a mnemonic. For the same reason a failed + /// trailing marker write is not an error here: the mnemonic *is* + /// stored, and the next `walletPresence()` call on an unlocked + /// device backfills the marker. public func storeMnemonic(_ mnemonic: String, for walletId: Data) throws { - let data = Data(mnemonic.utf8) - let account = perWalletMnemonicAccount(for: walletId) + Self.mutationLock.lock() + defer { Self.mutationLock.unlock() } - let deleteQuery: [String: Any] = [ + try deletePresenceMarker(for: walletId) + try deleteMnemonicItem(for: walletId) + try addMnemonicItem(Data(mnemonic.utf8), for: walletId) + try? storePresenceMarker(for: walletId) + } + + /// Raw delete of the mnemonic item. Idempotent. Overridable so tests + /// can observe the order of the keychain steps without a keychain. + func deleteMnemonicItem(for walletId: Data) throws { + let query: [String: Any] = [ kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: keychainService, - kSecAttrAccount as String: account + kSecAttrAccount as String: perWalletMnemonicAccount(for: walletId) ] - let deleteStatus = SecItemDelete(deleteQuery as CFDictionary) - guard deleteStatus == errSecSuccess || deleteStatus == errSecItemNotFound else { - throw WalletStorageError.keychainError(deleteStatus) + let status = SecItemDelete(query as CFDictionary) + guard status == errSecSuccess || status == errSecItemNotFound else { + throw WalletStorageError.keychainError(status) } + } + /// Raw add of the mnemonic item; the caller has deleted any previous + /// one so the `kSecAttrAccessible` value is rewritten on every save. + func addMnemonicItem(_ data: Data, for walletId: Data) throws { let addQuery: [String: Any] = [ kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: keychainService, - kSecAttrAccount as String: account, + kSecAttrAccount as String: perWalletMnemonicAccount(for: walletId), kSecValueData as String: data, kSecAttrAccessible as String: kSecAttrAccessibleWhenUnlockedThisDeviceOnly ] @@ -221,30 +269,44 @@ public class WalletStorage { } /// Delete a mnemonic keyed by wallet id. Idempotent. + /// + /// The presence marker comes off first and the mnemonic second, so a + /// process killed between the two steps — or a mnemonic delete that + /// throws — leaves at most a mnemonic without a marker, which the next + /// unlocked presence read re-marks; never a marker without a mnemonic, + /// which a locked read would trust. The lock `walletPresence()` shares + /// keeps a presence read from backfilling the marker between the two + /// steps. public func deleteMnemonic(for walletId: Data) throws { - let account = perWalletMnemonicAccount(for: walletId) - let query: [String: Any] = [ - kSecClass as String: kSecClassGenericPassword, - kSecAttrService as String: keychainService, - kSecAttrAccount as String: account - ] - let status = SecItemDelete(query as CFDictionary) - guard status == errSecSuccess || status == errSecItemNotFound else { - throw WalletStorageError.keychainError(status) - } + Self.mutationLock.lock() + defer { Self.mutationLock.unlock() } + + try deletePresenceMarker(for: walletId) + try deleteMnemonicItem(for: walletId) } /// Enumerate all wallet ids with a stored mnemonic. /// /// Reads every `kSecClassGenericPassword` entry under - /// `org.dash.wallet`, keeps those whose account starts with + /// `keychainService`, keeps those whose account starts with /// `wallet.mnemonic.` followed by a 64-character lowercase hex /// string, and decodes the suffix back into 32-byte wallet ids. - /// Returns an empty array if the keychain has none. + /// Returns an empty array if the keychain has none. Throws while the + /// device is locked (the items are `WhenUnlocked`); see + /// `walletPresence()` for the question that has to be answered then. public func listWalletIdsWithMnemonic() throws -> [Data] { + try listWalletIds(service: keychainService, accountPrefix: mnemonicKeychainAccount) + } + + /// Wallet ids encoded in the accounts of every generic-password item + /// under `service` whose account is `.<64-hex>`. + /// `errSecItemNotFound` is an empty list; any other failure is thrown + /// as `keychainError` so "nothing there" and "could not look" stay + /// distinguishable. + private func listWalletIds(service: String, accountPrefix: String) throws -> [Data] { let query: [String: Any] = [ kSecClass as String: kSecClassGenericPassword, - kSecAttrService as String: keychainService, + kSecAttrService as String: service, kSecMatchLimit as String: kSecMatchLimitAll, kSecReturnAttributes as String: true ] @@ -258,7 +320,7 @@ public class WalletStorage { } guard let items = result as? [[String: Any]] else { return [] } - let prefix = "\(mnemonicKeychainAccount)." + let prefix = "\(accountPrefix)." var walletIds: [Data] = [] for item in items { guard let account = item[kSecAttrAccount as String] as? String, @@ -270,6 +332,181 @@ public class WalletStorage { return walletIds } + // MARK: - Wallet Presence Marker + // + // The mnemonic and metadata items are `WhenUnlockedThisDeviceOnly`, so + // a process launched while the device is locked (a background app + // refresh, a silent push) cannot even enumerate them: the inventory + // read fails and a naive caller concludes "no wallet" and shows the + // setup screen. The marker is the durable, non-secret answer to that + // one question. + // + // Invariant: marker ⇒ a mnemonic was stored for that id. The marker + // is maintained only inside `storeMnemonic` / `deleteMnemonic`, in an + // order that keeps the invariant across an interruption at any step + // (the marker goes on last and comes off first), and + // the three entry points that touch both items share one process-wide + // lock so a presence read cannot interleave with a write or delete + // (`PlatformWalletManager.deleteWallet` uses its own `WalletStorage` + // instance; the lock is static for that reason). Drift is therefore + // only ever a mnemonic *without* a marker — a wallet stored before the + // marker existed, a trailing marker write that failed — and every + // presence read made while the inventory is readable repairs it, in + // both directions: it rewrites the marker set to match the inventory. + // + // Security trade-off: `AfterFirstUnlockThisDeviceOnly` means anyone + // who can query this app's keychain after the first unlock since + // boot learns that a wallet exists here, and its 32-byte wallet id. + // The id is a hash, not key material; it identifies nothing outside + // this app and unlocks nothing. Like the mnemonic it stays in the + // keychain across a reinstall (which is why this is not a + // `UserDefaults` flag) and never syncs to iCloud. + + /// Serialises `storeMnemonic`, `deleteMnemonic` and `walletPresence()` + /// across every `WalletStorage` instance in the process. Held only + /// around keychain calls; never taken by the item-level helpers. + private static let mutationLock = NSLock() + + private func perWalletPresenceMarkerAccount(for walletId: Data) -> String { + let hex = walletId.map { String(format: "%02x", $0) }.joined() + return "\(Self.presenceMarkerAccountPrefix).\(hex)" + } + + /// Write (or rewrite) the presence marker for `walletId`. A lifecycle + /// step of `storeMnemonic` and of the reconciliation in + /// `walletPresence()`, not an SDK operation: a marker written on its + /// own would assert a wallet that may not exist. Delete-then-add like + /// the other writers so the accessibility class is re-applied on + /// every write. The payload is the wallet id itself — no secret. + func storePresenceMarker(for walletId: Data) throws { + let account = perWalletPresenceMarkerAccount(for: walletId) + + let deleteQuery: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: Self.presenceKeychainService, + kSecAttrAccount as String: account + ] + let deleteStatus = SecItemDelete(deleteQuery as CFDictionary) + guard deleteStatus == errSecSuccess || deleteStatus == errSecItemNotFound else { + throw WalletStorageError.keychainError(deleteStatus) + } + + let addQuery: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: Self.presenceKeychainService, + kSecAttrAccount as String: account, + kSecValueData as String: walletId, + kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly + ] + let status = SecItemAdd(addQuery as CFDictionary, nil) + guard status == errSecSuccess else { + throw WalletStorageError.keychainError(status) + } + } + + /// Delete the presence marker for `walletId`. Idempotent. A lifecycle + /// step of `storeMnemonic`, `deleteMnemonic` and the reconciliation in + /// `walletPresence()`; not an SDK operation. + func deletePresenceMarker(for walletId: Data) throws { + let query: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: Self.presenceKeychainService, + kSecAttrAccount as String: perWalletPresenceMarkerAccount(for: walletId) + ] + let status = SecItemDelete(query as CFDictionary) + guard status == errSecSuccess || status == errSecItemNotFound else { + throw WalletStorageError.keychainError(status) + } + } + + /// Wallet ids that carry a presence marker. Readable once the device + /// has been unlocked since boot, locked or not. Empty means "no + /// marker", which is *not* "no wallet" — see `walletPresence()`. + /// Throws `keychainError` before the first unlock or on any other + /// lookup failure. + public func markedWalletIds() throws -> [Data] { + try listWalletIds( + service: Self.presenceKeychainService, + accountPrefix: Self.presenceMarkerAccountPrefix + ) + } + + /// Three-way answer to "does this app hold at least one wallet?". + public enum WalletPresence: Sendable, Equatable { + /// The mnemonic inventory was readable and non-empty, or it was + /// unreadable and at least one wallet id is marked. + case present + /// The mnemonic inventory was readable and empty. The only verdict + /// on which a setup screen may be shown. + case absent + /// Could not tell: the marker set was unreadable (before the first + /// unlock, `errSecInteractionNotAllowed`, …) or it was empty and + /// the inventory was unreadable (a locked device with wallets + /// stored before the marker existed). Says nothing about whether + /// a wallet exists; decide later, not now. + case unknown(OSStatus) + } + + /// Whether at least one wallet exists, answerable on a locked device. + /// + /// The mnemonic inventory is the source of truth whenever it can be + /// read; the marker set stands in for it only while it cannot: + /// + /// 1. `markedWalletIds()` unreadable → `.unknown(status)`. + /// 2. `listWalletIdsWithMnemonic()` readable → verdict from it + /// (`.present` / `.absent`), and the marker set is reconciled to + /// it: a marker is written for every inventoried id without one + /// (wallets stored before the marker existed backfill themselves + /// on the first unlocked read) and any marker without a mnemonic + /// is removed. Best effort; a failed write or delete changes + /// nothing about the verdict. + /// 3. Inventory unreadable → marker set non-empty is `.present`, + /// empty is `.unknown(status)`. + /// + /// Invariant for callers: marker present ⇒ a mnemonic was stored for + /// that id; a missing marker on its own never means "no wallet" — only + /// a readable, empty inventory does. + /// + /// - Tag: walletPresence + public func walletPresence() -> WalletPresence { + Self.mutationLock.lock() + defer { Self.mutationLock.unlock() } + + let marked: [Data] + do { + marked = try markedWalletIds() + } catch { + return .unknown(Self.status(of: error)) + } + + let inventory: [Data] + do { + inventory = try listWalletIdsWithMnemonic() + } catch { + return marked.isEmpty ? .unknown(Self.status(of: error)) : .present + } + + let markedSet = Set(marked) + let inventorySet = Set(inventory) + for walletId in inventory where !markedSet.contains(walletId) { + try? storePresenceMarker(for: walletId) + } + for walletId in marked where !inventorySet.contains(walletId) { + try? deletePresenceMarker(for: walletId) + } + return inventory.isEmpty ? .absent : .present + } + + /// The `OSStatus` behind a `WalletStorageError.keychainError`; anything + /// else (an override that throws its own error) maps to + /// `errSecInternalError` so `unknown` still carries *a* status. + private static func status(of error: Error) -> OSStatus { + if case WalletStorageError.keychainError(let status) = error { + return status + } + return errSecInternalError + } + // MARK: - Per-Wallet Metadata Storage // // User-facing display strings (name + description) carried in diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/WalletPresenceTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/WalletPresenceTests.swift new file mode 100644 index 00000000000..60461d183b3 --- /dev/null +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/WalletPresenceTests.swift @@ -0,0 +1,372 @@ +import Security +import XCTest + +@testable import SwiftDashSDK + +/// The presence-marker lifecycle of `WalletStorage` — `storeMnemonic`, +/// `deleteMnemonic` and `walletPresence()` — run against an in-memory +/// keychain instead of the real one (the same reason +/// `IdentityResolverSignIntegrationTests` uses an in-memory storage: a +/// CI runner's keychain session is an environment, not what is under +/// test). The fake models the *outcome* of each keychain step on a +/// device in a given state — unreadable, readable-empty, readable-with- +/// ids — and records the order of the steps, so the invariant *marker ⇒ +/// a mnemonic was stored* can be checked at every interruption point +/// and across an interleaving between two storage instances. +final class WalletPresenceTests: XCTestCase { + /// One keychain shared by every `FakeStorage` in a test, the way the + /// real one is shared by every `WalletStorage()` in the process. + private final class FakeKeychain: @unchecked Sendable { + private let lock = NSLock() + private var mnemonics: Set = [] + private var markers: Set = [] + private var log: [String] = [] + + /// `nil` means readable; a status means every read of that set + /// throws `keychainError(status)`, as on a locked device. + var inventoryFailure: OSStatus? + var markerReadFailure: OSStatus? + var markerWriteFailure: OSStatus? + var markerDeleteFailure: OSStatus? + var mnemonicAddFailure: OSStatus? + var mnemonicDeleteFailure: OSStatus? + + func seed(mnemonics: [Data] = [], markers: [Data] = []) { + lock.withLock { + self.mnemonics = Set(mnemonics) + self.markers = Set(markers) + } + } + + var mnemonicIds: Set { lock.withLock { mnemonics } } + var markerIds: Set { lock.withLock { markers } } + var steps: [String] { lock.withLock { log } } + + private static func tag(_ id: Data) -> String { + String(format: "%02x", id.first ?? 0) + } + + func listMnemonics() throws -> [Data] { + try lock.withLock { + log.append("inventory") + if let status = inventoryFailure { throw WalletStorageError.keychainError(status) } + return Array(mnemonics) + } + } + + func listMarkers() throws -> [Data] { + try lock.withLock { + log.append("markers") + if let status = markerReadFailure { throw WalletStorageError.keychainError(status) } + return Array(markers) + } + } + + func addMnemonic(_ id: Data) throws { + try lock.withLock { + log.append("addMnemonic:\(Self.tag(id))") + if let status = mnemonicAddFailure { throw WalletStorageError.keychainError(status) } + mnemonics.insert(id) + } + } + + func deleteMnemonic(_ id: Data) throws { + try lock.withLock { + log.append("deleteMnemonic:\(Self.tag(id))") + if let status = mnemonicDeleteFailure { throw WalletStorageError.keychainError(status) } + mnemonics.remove(id) + } + } + + func addMarker(_ id: Data) throws { + try lock.withLock { + log.append("addMarker:\(Self.tag(id))") + if let status = markerWriteFailure { throw WalletStorageError.keychainError(status) } + markers.insert(id) + } + } + + func deleteMarker(_ id: Data) throws { + try lock.withLock { + log.append("deleteMarker:\(Self.tag(id))") + if let status = markerDeleteFailure { throw WalletStorageError.keychainError(status) } + markers.remove(id) + } + } + } + + /// `WalletStorage` whose keychain steps go to a `FakeKeychain`. Only + /// the item-level primitives are overridden; the lifecycle logic under + /// test is the real one. + private class FakeStorage: WalletStorage, @unchecked Sendable { + let keychain: FakeKeychain + + init(_ keychain: FakeKeychain) { + self.keychain = keychain + super.init() + } + + override func listWalletIdsWithMnemonic() throws -> [Data] { try keychain.listMnemonics() } + override func markedWalletIds() throws -> [Data] { try keychain.listMarkers() } + override func addMnemonicItem(_ data: Data, for walletId: Data) throws { + try keychain.addMnemonic(walletId) + } + override func deleteMnemonicItem(for walletId: Data) throws { try keychain.deleteMnemonic(walletId) } + override func storePresenceMarker(for walletId: Data) throws { try keychain.addMarker(walletId) } + override func deletePresenceMarker(for walletId: Data) throws { try keychain.deleteMarker(walletId) } + } + + private let walletA = Data(repeating: 0xA1, count: 32) + private let walletB = Data(repeating: 0xB2, count: 32) + private let locked: OSStatus = errSecInteractionNotAllowed + + // MARK: - Classification + + func testUnreadableMarkerIsUnknownWithoutConsultingTheInventory() { + let keychain = FakeKeychain() + keychain.seed(mnemonics: [walletA]) + keychain.markerReadFailure = locked // before the first unlock since boot + + XCTAssertEqual(FakeStorage(keychain).walletPresence(), .unknown(locked)) + XCTAssertEqual(keychain.steps, ["markers"], "an unreadable marker set ends the lookup") + } + + func testMarkedWalletIsPresentWhileTheInventoryIsUnreadable() { + let keychain = FakeKeychain() + keychain.seed(mnemonics: [walletA], markers: [walletA]) + keychain.inventoryFailure = locked + + XCTAssertEqual(FakeStorage(keychain).walletPresence(), .present) + XCTAssertEqual(keychain.steps, ["markers", "inventory"], "no writes while locked") + } + + func testEmptyMarkerSetWithUnreadableInventoryIsUnknownNotAbsent() { + // A locked device holding wallets stored before the marker + // existed: the marker set reads empty, the inventory cannot be read. + let keychain = FakeKeychain() + keychain.seed(mnemonics: [walletA]) + keychain.inventoryFailure = locked + + XCTAssertEqual(FakeStorage(keychain).walletPresence(), .unknown(locked)) + XCTAssertTrue(keychain.markerIds.isEmpty) + } + + func testReadableEmptyInventoryIsAbsent() { + let keychain = FakeKeychain() + + XCTAssertEqual(FakeStorage(keychain).walletPresence(), .absent) + XCTAssertEqual(keychain.steps, ["markers", "inventory"]) + } + + // MARK: - Reconciliation while the inventory is readable + + func testUnmarkedWalletsAreBackfilledFromTheInventory() { + let keychain = FakeKeychain() + keychain.seed(mnemonics: [walletA, walletB]) + + XCTAssertEqual(FakeStorage(keychain).walletPresence(), .present) + XCTAssertEqual(keychain.markerIds, [walletA, walletB]) + } + + func testMarkerWithoutMnemonicIsRemovedAndTheVerdictIsAbsent() { + // A phantom left by an older build or an interrupted write: the + // inventory is authoritative once readable. + let keychain = FakeKeychain() + keychain.seed(markers: [walletA]) + + XCTAssertEqual(FakeStorage(keychain).walletPresence(), .absent) + XCTAssertTrue(keychain.markerIds.isEmpty) + } + + func testMarkerSetIsRewrittenToMatchTheInventory() { + let keychain = FakeKeychain() + keychain.seed(mnemonics: [walletB], markers: [walletA]) + + XCTAssertEqual(FakeStorage(keychain).walletPresence(), .present) + XCTAssertEqual(keychain.markerIds, [walletB]) + } + + func testFailedBackfillDoesNotChangeTheVerdict() { + let keychain = FakeKeychain() + keychain.seed(mnemonics: [walletA]) + keychain.markerWriteFailure = errSecWrPerm + + XCTAssertEqual(FakeStorage(keychain).walletPresence(), .present) + XCTAssertTrue(keychain.markerIds.isEmpty) + } + + // MARK: - Ordering inside storeMnemonic / deleteMnemonic + + func testStoreWritesTheMnemonicBeforeTheMarker() throws { + let keychain = FakeKeychain() + + try FakeStorage(keychain).storeMnemonic("abandon", for: walletA) + + XCTAssertEqual( + keychain.steps, + ["deleteMarker:a1", "deleteMnemonic:a1", "addMnemonic:a1", "addMarker:a1"] + ) + XCTAssertEqual(keychain.mnemonicIds, [walletA]) + XCTAssertEqual(keychain.markerIds, [walletA]) + } + + func testFailedMnemonicWriteLeavesNoMarker() { + // The interruption the order exists for: a process killed after + // the marker step but before the mnemonic step must not leave a + // marker behind — so the marker step is last. + let keychain = FakeKeychain() + keychain.mnemonicAddFailure = errSecWrPerm + + XCTAssertThrowsError(try FakeStorage(keychain).storeMnemonic("abandon", for: walletA)) + XCTAssertTrue(keychain.markerIds.isEmpty) + XCTAssertFalse(keychain.steps.contains("addMarker:a1")) + } + + func testRewriteTakesTheMarkerOffBeforeTheDeleteAddGap() throws { + // A kill between the old mnemonic's delete and the new one's add + // must not retain the marker across the gap. + let keychain = FakeKeychain() + keychain.seed(mnemonics: [walletA], markers: [walletA]) + + try FakeStorage(keychain).storeMnemonic("abandon", for: walletA) + + let steps = keychain.steps + let markerOff = try XCTUnwrap(steps.firstIndex(of: "deleteMarker:a1")) + let mnemonicOff = try XCTUnwrap(steps.firstIndex(of: "deleteMnemonic:a1")) + XCTAssertLessThan(markerOff, mnemonicOff) + XCTAssertEqual(keychain.markerIds, [walletA]) + } + + func testFailedTrailingMarkerWriteDoesNotFailTheStore() throws { + let keychain = FakeKeychain() + keychain.markerWriteFailure = errSecWrPerm + + try FakeStorage(keychain).storeMnemonic("abandon", for: walletA) + + XCTAssertEqual(keychain.mnemonicIds, [walletA], "the mnemonic is stored") + XCTAssertTrue(keychain.markerIds.isEmpty, "the safe direction of drift") + keychain.markerWriteFailure = nil + XCTAssertEqual(FakeStorage(keychain).walletPresence(), .present) + XCTAssertEqual(keychain.markerIds, [walletA], "and the next unlocked read repairs it") + } + + func testDeleteRemovesTheMarkerBeforeTheMnemonic() throws { + let keychain = FakeKeychain() + keychain.seed(mnemonics: [walletA], markers: [walletA]) + + try FakeStorage(keychain).deleteMnemonic(for: walletA) + + XCTAssertEqual(keychain.steps, ["deleteMarker:a1", "deleteMnemonic:a1"]) + XCTAssertTrue(keychain.mnemonicIds.isEmpty) + XCTAssertTrue(keychain.markerIds.isEmpty) + } + + func testFailedMnemonicDeleteLeavesAnUnmarkedMnemonicNotAPhantom() { + // The interruption between the two deletions: the marker is + // already gone, the mnemonic is still there. A locked read then + // says unknown rather than present-for-a-wallet-that-is-gone, and + // an unlocked read re-marks the surviving mnemonic. + let keychain = FakeKeychain() + keychain.seed(mnemonics: [walletA], markers: [walletA]) + keychain.mnemonicDeleteFailure = errSecWrPerm + + XCTAssertThrowsError(try FakeStorage(keychain).deleteMnemonic(for: walletA)) + XCTAssertEqual(keychain.mnemonicIds, [walletA]) + XCTAssertTrue(keychain.markerIds.isEmpty, "the safe direction of drift") + + keychain.inventoryFailure = locked + XCTAssertEqual(FakeStorage(keychain).walletPresence(), .unknown(locked)) + + keychain.inventoryFailure = nil + XCTAssertEqual(FakeStorage(keychain).walletPresence(), .present) + XCTAssertEqual(keychain.markerIds, [walletA], "and the next unlocked read repairs it") + } + + func testFailedMarkerDeleteLeavesTheMnemonicInPlace() { + // The first step failing must not remove the mnemonic behind a + // marker that still exists. + let keychain = FakeKeychain() + keychain.seed(mnemonics: [walletA], markers: [walletA]) + keychain.markerDeleteFailure = errSecWrPerm + + XCTAssertThrowsError(try FakeStorage(keychain).deleteMnemonic(for: walletA)) + XCTAssertEqual(keychain.steps, ["deleteMarker:a1"]) + XCTAssertEqual(keychain.mnemonicIds, [walletA]) + XCTAssertEqual(keychain.markerIds, [walletA]) + } + + // MARK: - Interleaving across storage instances + + func testPresenceReadCannotBackfillAMarkerDuringADeletion() throws { + // `deleteMnemonic` on one instance is paused at its first keychain + // step (the marker delete); `walletPresence()` on a second + // instance (the inventory still lists the wallet, no marker yet) + // must wait for the deletion instead of backfilling a marker the + // deletion would then leave behind. + final class PausingStorage: FakeStorage, @unchecked Sendable { + let entered = DispatchSemaphore(value: 0) + let release = DispatchSemaphore(value: 0) + override func deletePresenceMarker(for walletId: Data) throws { + entered.signal() + release.wait() + try super.deletePresenceMarker(for: walletId) + } + } + + let keychain = FakeKeychain() + keychain.seed(mnemonics: [walletA]) + let deleting = PausingStorage(keychain) + let reading = FakeStorage(keychain) + + let walletA = walletA + let deleteDone = expectation(description: "delete finished") + Thread.detachNewThread { + try? deleting.deleteMnemonic(for: walletA) + deleteDone.fulfill() + } + XCTAssertEqual(deleting.entered.wait(timeout: .now() + 5), .success) + + let presenceDone = expectation(description: "presence finished") + let verdict = LockedBox(nil) + Thread.detachNewThread { + verdict.value = reading.walletPresence() + presenceDone.fulfill() + } + // The read is blocked behind the paused deletion: it has not + // touched the keychain yet. + Thread.sleep(forTimeInterval: 0.2) + XCTAssertNil(verdict.value) + XCTAssertFalse(keychain.steps.contains("markers")) + + deleting.release.signal() + wait(for: [deleteDone, presenceDone], timeout: 5) + + XCTAssertEqual(verdict.value, .absent) + XCTAssertTrue(keychain.mnemonicIds.isEmpty) + XCTAssertTrue(keychain.markerIds.isEmpty, "no marker survives the deletion") + } + + private final class LockedBox: @unchecked Sendable { + private let lock = NSLock() + private var stored: T + init(_ value: T) { stored = value } + var value: T { + get { lock.withLock { stored } } + set { lock.withLock { stored = newValue } } + } + } + + // MARK: - Layout + + func testMarkerServiceIsASiblingOfTheMnemonicService() { + // The marker items are `AfterFirstUnlock`, the mnemonic items + // `WhenUnlocked`; a shared service would make one service-wide + // query cover both accessibility classes. See the doc comment on + // `presenceKeychainService` for why that must not happen. + XCTAssertEqual( + WalletStorage.presenceKeychainService, + "\(WalletStorage.keychainService).presence" + ) + XCTAssertNotEqual(WalletStorage.presenceKeychainService, WalletStorage.keychainService) + } +}