diff --git a/bitchat/Identity/SecureIdentityStateManager.swift b/bitchat/Identity/SecureIdentityStateManager.swift index 77f8df85..50cbcf16 100644 --- a/bitchat/Identity/SecureIdentityStateManager.swift +++ b/bitchat/Identity/SecureIdentityStateManager.swift @@ -193,6 +193,7 @@ final class SecureIdentityStateManager: SecureIdentityStateManagerProtocol { /// state we must NOT persist (it would overwrite the real cache with data the /// next launch can't decrypt) and must NOT delete the existing cache. private var encryptionKeyIsEphemeral: Bool + private var cacheReadUnavailable: Bool = false init(_ keychain: KeychainManagerProtocol) { self.keychain = keychain @@ -266,20 +267,31 @@ final class SecureIdentityStateManager: SecureIdentityStateManagerProtocol { // MARK: - Secure Loading/Saving private func loadIdentityCache() { - guard let encryptedData = keychain.getIdentityKey(forKey: cacheKey) else { - // No existing cache, start fresh + switch keychain.getIdentityKeyWithResult(forKey: cacheKey) { + case .success(let encryptedData): + do { + let sealedBox = try AES.GCM.SealedBox(combined: encryptedData) + let decryptedData = try AES.GCM.open(sealedBox, using: encryptionKey) + cache = try JSONDecoder().decode(IdentityCache.self, from: decryptedData) + } catch { + cache = IdentityCache() + let deleted = keychain.deleteIdentityKey(forKey: cacheKey) + SecureLogger.warning( + "Discarded unreadable identity cache; starting fresh (deleted=\(deleted), error=\(error.localizedDescription))", + category: .security + ) + } + + case .itemNotFound: + // Genuine first run: no existing cache, start fresh. return - } - - do { - let sealedBox = try AES.GCM.SealedBox(combined: encryptedData) - let decryptedData = try AES.GCM.open(sealedBox, using: encryptionKey) - cache = try JSONDecoder().decode(IdentityCache.self, from: decryptedData) - } catch { - cache = IdentityCache() - let deleted = keychain.deleteIdentityKey(forKey: cacheKey) + + case .deviceLocked, .authenticationFailed, .accessDenied, .otherError: + // Transient/critical read failure: leave the persisted cache intact + // and avoid overwriting it during this session. + cacheReadUnavailable = true SecureLogger.warning( - "Discarded unreadable identity cache; starting fresh (deleted=\(deleted), error=\(error.localizedDescription))", + "Identity cache unavailable from keychain; refusing to overwrite persisted cache this session", category: .security ) } @@ -311,13 +323,13 @@ final class SecureIdentityStateManager: SecureIdentityStateManagerProtocol { /// can spin forever (observed as a CI test-suite hang), so the snapshot /// must be taken on `queue`, never off it. /// - Returns: `true` if persisted (or intentionally skipped under an ephemeral - /// session key), `false` if encoding/sealing/Keychain save failed. + /// session key or transient cache-read failure), `false` if encoding/sealing/Keychain save failed. @discardableResult private func persist(snapshot: IdentityCache) -> Bool { - // Never persist under an ephemeral key — it would overwrite the real - // cache with data the next launch cannot decrypt. - guard !encryptionKeyIsEphemeral else { - SecureLogger.debug("Skipping identity cache save (ephemeral key this session)", category: .security) + // Never persist under an ephemeral key or after a transient cache-read + // failure — doing so would overwrite persisted identity pins/blocks. + guard !encryptionKeyIsEphemeral, !cacheReadUnavailable else { + SecureLogger.debug("Skipping identity cache save (keychain unavailable at load)", category: .security) return true } @@ -686,6 +698,7 @@ final class SecureIdentityStateManager: SecureIdentityStateManagerProtocol { queue.sync(flags: .barrier) { self.cache = IdentityCache() + self.cacheReadUnavailable = false self.ephemeralSessions.removeAll() self.pendingSave = false diff --git a/bitchat/Nostr/NostrIdentityBridge.swift b/bitchat/Nostr/NostrIdentityBridge.swift index 5c7407ca..e497c6d9 100644 --- a/bitchat/Nostr/NostrIdentityBridge.swift +++ b/bitchat/Nostr/NostrIdentityBridge.swift @@ -1,4 +1,5 @@ import BitFoundation +import BitLogger import Foundation import CryptoKit @@ -65,6 +66,10 @@ final class NostrIdentityBridge { case .itemNotFound: break case .deviceLocked, .accessDenied, .authenticationFailed, .otherError: + SecureLogger.warning( + "Nostr identity unavailable from keychain; refusing to overwrite", + category: .security + ) return nil } @@ -126,7 +131,7 @@ final class NostrIdentityBridge { /// Returns a stable device seed used to derive unlinkable per-geohash identities, /// along with whether the seed is durably backed by Keychain and safe to cache. - private func getOrCreateDeviceSeed() -> (seed: Data, durable: Bool, generation: UInt64) { + private func getOrCreateDeviceSeed() throws -> (seed: Data, durable: Bool, generation: UInt64) { cacheLock.lock() if let cached = deviceSeedCache { let generation = cacheGeneration @@ -159,9 +164,17 @@ final class NostrIdentityBridge { case .itemNotFound: break case .deviceLocked, .accessDenied, .authenticationFailed, .otherError: - // Preserve the retry path without overwriting or caching a temporary seed. - let ephemeralSeed = SymmetricKey(size: .bits256).withUnsafeBytes { Data($0) } - return (ephemeralSeed, false, generation) + // Fail closed rather than overwriting the stored seed or deriving + // a throwaway geohash identity while Keychain is transiently locked. + SecureLogger.warning( + "Nostr device seed unavailable from keychain; refusing to overwrite", + category: .security + ) + throw NSError( + domain: "NostrIdentity", + code: -2, + userInfo: [NSLocalizedDescriptionKey: "Keychain unavailable for device seed"] + ) } // CryptoKit key generation cannot fail, unlike SecRandomCopyBytes — @@ -206,7 +219,7 @@ final class NostrIdentityBridge { } cacheLock.unlock() - let (seed, durable, generation) = getOrCreateDeviceSeed() + let (seed, durable, generation) = try getOrCreateDeviceSeed() guard let msg = geohash.data(using: .utf8) else { throw NSError(domain: "NostrIdentity", code: -1, userInfo: [NSLocalizedDescriptionKey: "Invalid geohash string"]) } diff --git a/bitchat/Services/Prekeys/LocalPrekeyStore.swift b/bitchat/Services/Prekeys/LocalPrekeyStore.swift index 26f9ec67..376d7313 100644 --- a/bitchat/Services/Prekeys/LocalPrekeyStore.swift +++ b/bitchat/Services/Prekeys/LocalPrekeyStore.swift @@ -77,7 +77,7 @@ final class LocalPrekeyStore { /// initial batch on first use. Sorted by ID for canonical signing bytes. func currentBundlePrekeys() -> (prekeys: [PrekeyBundle.Prekey], generatedAt: UInt64) { queue.sync { - loadLocked() + guard loadLocked() else { return ([], 0) } _ = replenishLocked() let prekeys = records .filter { $0.consumedAt == nil } @@ -96,7 +96,7 @@ final class LocalPrekeyStore { /// redelivery grace window. func privateKey(for id: UInt32) -> Curve25519.KeyAgreement.PrivateKey? { queue.sync { - loadLocked() + guard loadLocked() else { return nil } let date = now() guard let record = records.first(where: { $0.id == id }) else { return nil } if let consumedAt = record.consumedAt, @@ -120,7 +120,7 @@ final class LocalPrekeyStore { @discardableResult func markConsumed(_ id: UInt32) -> Bool { queue.sync { - loadLocked() + guard loadLocked() else { return false } guard let index = records.firstIndex(where: { $0.id == id }), records[index].consumedAt == nil else { return false } records[index].consumedAt = now() @@ -136,14 +136,14 @@ final class LocalPrekeyStore { @discardableResult func replenishIfNeeded() -> Bool { queue.sync { - loadLocked() + guard loadLocked() else { return false } return replenishLocked() } } var unconsumedCount: Int { queue.sync { - loadLocked() + guard loadLocked() else { return 0 } return records.filter { $0.consumedAt == nil }.count } } @@ -203,16 +203,29 @@ final class LocalPrekeyStore { generatedAt = max(nowMillis, generatedAt &+ 1) } - private func loadLocked() { - guard !loaded else { return } - loaded = true - guard let data = keychain.getIdentityKey(forKey: Self.keychainKey), - let persisted = try? JSONDecoder().decode(Persisted.self, from: data) else { - return + private func loadLocked() -> Bool { + guard !loaded else { return true } + switch keychain.getIdentityKeyWithResult(forKey: Self.keychainKey) { + case .success(let data): + loaded = true + if let persisted = try? JSONDecoder().decode(Persisted.self, from: data) { + records = persisted.records + nextID = persisted.nextID + generatedAt = persisted.generatedAt + } + return true + case .itemNotFound: + loaded = true + return true + case .deviceLocked, .authenticationFailed, .accessDenied, .otherError: + // Leave `loaded = false` so a subsequent unlocked call retries, + // and refuse to replenish/overwrite the persisted prekey store. + SecureLogger.warning( + "Local prekey store unavailable from keychain; refusing to overwrite", + category: .keychain + ) + return false } - records = persisted.records - nextID = persisted.nextID - generatedAt = persisted.generatedAt } private func persistLocked() { diff --git a/bitchatTests/Mocks/MockKeychain.swift b/bitchatTests/Mocks/MockKeychain.swift index f5e7bad1..eef9342c 100644 --- a/bitchatTests/Mocks/MockKeychain.swift +++ b/bitchatTests/Mocks/MockKeychain.swift @@ -16,6 +16,7 @@ final class MockKeychain: KeychainManagerProtocol { // BCH-01-009: Configurable error simulation for testing var simulatedReadError: KeychainReadResult? + var simulatedReadErrorKeys: Set? var simulatedSaveError: KeychainSaveResult? var simulatedGenericReadError: KeychainReadResult? var simulatedDeleteAllResult = true @@ -32,6 +33,10 @@ final class MockKeychain: KeychainManagerProtocol { func getIdentityKey(forKey key: String) -> Data? { getIdentityKeyCallCount += 1 + if simulatedReadError != nil, + simulatedReadErrorKeys == nil || simulatedReadErrorKeys?.contains(key) == true { + return nil + } return storage[key] } @@ -63,7 +68,8 @@ final class MockKeychain: KeychainManagerProtocol { // BCH-01-009: New methods with proper error classification func getIdentityKeyWithResult(forKey key: String) -> KeychainReadResult { getIdentityKeyCallCount += 1 - if let simulated = simulatedReadError { + if let simulated = simulatedReadError, + simulatedReadErrorKeys == nil || simulatedReadErrorKeys?.contains(key) == true { return simulated } if let data = storage[key] { @@ -92,6 +98,9 @@ final class MockKeychain: KeychainManagerProtocol { func load(key: String, service: String) -> Data? { loadCallCount += 1 + if simulatedGenericReadError != nil { + return nil + } return serviceStorage[service]?[key] } diff --git a/bitchatTests/Services/KeychainTransientReadSafetyTests.swift b/bitchatTests/Services/KeychainTransientReadSafetyTests.swift new file mode 100644 index 00000000..ce26fc2b --- /dev/null +++ b/bitchatTests/Services/KeychainTransientReadSafetyTests.swift @@ -0,0 +1,82 @@ +import BitFoundation +import Foundation +import XCTest +@testable import bitchat + +final class KeychainTransientReadSafetyTests: XCTestCase { + func test_secureIdentityStateManager_transientCacheReadErrorDoesNotOverwritePersistedPins() { + let keychain = MockKeychain() + let fingerprint = "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2" + + // First launch: persist a verified fingerprint in the identity cache. + let initial = SecureIdentityStateManager(keychain) + initial.setVerified(fingerprint: fingerprint, verified: true) + XCTAssertTrue(initial.isVerified(fingerprint: fingerprint)) + + // Second launch: encryption key succeeds, but reading cacheKey transiently fails. + keychain.simulatedReadError = .deviceLocked + keychain.simulatedReadErrorKeys = ["bitchat.identityCache.v2"] + let degraded = SecureIdentityStateManager(keychain) + XCTAssertFalse(degraded.isVerified(fingerprint: fingerprint)) + + // Mutating during the degraded session must NOT overwrite the persisted cache. + degraded.setVerified(fingerprint: "other-fp", verified: true) + degraded.forceSave() + + // Third launch (healthy): original verified fingerprint is still intact. + keychain.simulatedReadError = nil + keychain.simulatedReadErrorKeys = nil + let recovered = SecureIdentityStateManager(keychain) + XCTAssertTrue(recovered.isVerified(fingerprint: fingerprint)) + XCTAssertFalse(recovered.isVerified(fingerprint: "other-fp")) + } + + func test_nostrIdentityBridge_transientReadErrorsDoNotOverwriteIdentityOrDeviceSeed() throws { + let keychain = MockKeychain() + let bridge = NostrIdentityBridge(keychain: keychain) + + let originalIdentity = try XCTUnwrap(try bridge.getCurrentNostrIdentity()) + let originalGeo = try bridge.deriveIdentity(forGeohash: "u4pruy") + + // Simulate locked keychain on fresh bridge instances (cold cache). + keychain.simulatedGenericReadError = .deviceLocked + let lockedBridge = NostrIdentityBridge(keychain: keychain) + XCTAssertNil(try lockedBridge.getCurrentNostrIdentity()) + XCTAssertThrowsError(try lockedBridge.deriveIdentity(forGeohash: "u4pruy")) + + // Once unlocked, original identity and derived geohash key remain intact. + keychain.simulatedGenericReadError = nil + let recoveredBridge = NostrIdentityBridge(keychain: keychain) + let recoveredIdentity = try XCTUnwrap(try recoveredBridge.getCurrentNostrIdentity()) + let recoveredGeo = try recoveredBridge.deriveIdentity(forGeohash: "u4pruy") + XCTAssertEqual(recoveredIdentity.publicKeyHex, originalIdentity.publicKeyHex) + XCTAssertEqual(recoveredGeo.publicKeyHex, originalGeo.publicKeyHex) + } + + func test_localPrekeyStore_transientReadErrorFailsClosedAndRecoversWithoutOverwriting() throws { + let keychain = MockKeychain() + let store1 = LocalPrekeyStore(keychain: keychain) + let initialBundle = store1.currentBundlePrekeys() + XCTAssertFalse(initialBundle.prekeys.isEmpty) + let firstPrekeyID = try XCTUnwrap(initialBundle.prekeys.first?.id) + let firstPrivateBefore = try XCTUnwrap(store1.privateKey(for: firstPrekeyID)) + + // Simulate locked keychain on next launch: store must fail closed and + // must NOT latch `loaded = true` or overwrite Keychain with fresh IDs. + keychain.simulatedReadError = .deviceLocked + keychain.simulatedReadErrorKeys = ["prekeysV1"] + let store2 = LocalPrekeyStore(keychain: keychain) + XCTAssertTrue(store2.currentBundlePrekeys().prekeys.isEmpty) + XCTAssertNil(store2.privateKey(for: firstPrekeyID)) + XCTAssertFalse(store2.replenishIfNeeded()) + XCTAssertEqual(store2.unconsumedCount, 0) + + // Once unlocked, the SAME store2 instance retries loadLocked() and + // recovers the exact persisted prekey privates intact. + keychain.simulatedReadError = nil + keychain.simulatedReadErrorKeys = nil + let recoveredPrivate = try XCTUnwrap(store2.privateKey(for: firstPrekeyID)) + XCTAssertEqual(recoveredPrivate.rawRepresentation, firstPrivateBefore.rawRepresentation) + XCTAssertEqual(store2.currentBundlePrekeys().prekeys, initialBundle.prekeys) + } +}