From 875223a49a307865a09a6700b5ec204ccadef630 Mon Sep 17 00:00:00 2001 From: jack <212554440+jackjackbits@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:42:25 -1000 Subject: [PATCH] fix(security): close panic-wipe key/metadata leaks and VoiceRecorder deadlock (#1879) * Close panic-wipe leaks across shadow key caches, singletons, disk stores, and VoiceRecorder * Import BitLogger in VoiceRecorder for timeout warning * Use BridgeService.locationCell in PanicWipeCoverageTests * Address Codex review: fence MainActor ACK tasks and WaveformCache writes across panic wipe --- bitchat/App/NearbyNotesCounter.swift | 10 + bitchat/Features/voice/VoiceRecorder.swift | 22 +- bitchat/Features/voice/Waveform.swift | 15 +- bitchat/Nostr/GeoRelayDirectory.swift | 11 + bitchat/Nostr/NostrIdentityBridge.swift | 31 +- .../Gateway/BridgeCourierService.swift | 9 +- bitchat/Services/Gateway/BridgeService.swift | 34 +++ bitchat/Services/Gateway/GatewayService.swift | 16 + bitchat/Services/GeohashPresenceService.swift | 5 + bitchat/Services/LocationNotesManager.swift | 20 ++ bitchat/Services/LocationNotesPool.swift | 9 + .../MessageDeduplicationService.swift | 9 +- .../Services/NostrProcessedEventStore.swift | 2 +- bitchat/Services/NostrTransport.swift | 28 +- bitchat/Services/PrivateChatManager.swift | 4 + bitchat/Services/VerificationService.swift | 22 +- .../ChatVerificationCoordinator.swift | 7 + bitchat/ViewModels/ChatViewModel.swift | 26 +- .../Services/PanicWipeCoverageTests.swift | 279 ++++++++++++++++++ localPackages/Arti/Sources/TorManager.swift | 25 ++ 20 files changed, 554 insertions(+), 30 deletions(-) create mode 100644 bitchatTests/Services/PanicWipeCoverageTests.swift diff --git a/bitchat/App/NearbyNotesCounter.swift b/bitchat/App/NearbyNotesCounter.swift index d1863970..fe0b606b 100644 --- a/bitchat/App/NearbyNotesCounter.swift +++ b/bitchat/App/NearbyNotesCounter.swift @@ -111,6 +111,16 @@ final class NearbyNotesCounter: ObservableObject { noteCount = 0 } + /// Panic-wipe hook: reset sticky reveal state and drop the active + /// building-level notes subscription and count. + func resetForPanic() { + revealed = false + managerCancellable = nil + releaseManager(manager) + manager = nil + noteCount = 0 + } + private func retarget() { guard activeHolders > 0, revealed, diff --git a/bitchat/Features/voice/VoiceRecorder.swift b/bitchat/Features/voice/VoiceRecorder.swift index 909879cd..5a503eb2 100644 --- a/bitchat/Features/voice/VoiceRecorder.swift +++ b/bitchat/Features/voice/VoiceRecorder.swift @@ -1,3 +1,4 @@ +import BitLogger import Foundation import AVFoundation @@ -246,19 +247,24 @@ actor VoiceRecorder { currentURL = nil } - /// Panic is a synchronous security boundary: the caller must know the - /// microphone, audio-session lease, and partial file are gone before it - /// rotates identities or deletes the media tree. VoiceRecorder is an - /// independent actor and this cleanup path never hops to MainActor, so a - /// short semaphore join is safe even when invoked by the UI actor. + /// Panic is a synchronous security boundary: the caller wants the + /// microphone, audio-session lease, and partial file closed before rotating + /// identities or deleting the media tree, but must never deadlock the main + /// thread if AVFoundation blocks waiting for main. Use a detached task and + /// a bounded wait so panic wipe always proceeds. nonisolated func panicCancelSynchronously(owner: RecordingOwner) { let finished = DispatchSemaphore(value: 0) - Task { - await cancelRecording(owner: owner) + Task.detached(priority: .userInitiated) { + await self.cancelRecording(owner: owner) finished.signal() } - finished.wait() + if finished.wait(timeout: .now() + .seconds(2)) == .timedOut { + SecureLogger.warning( + "VoiceRecorder: panicCancelSynchronously timed out after 2s; proceeding with panic wipe", + category: .security + ) + } } /// The audio session was interrupted (call, Siri) or reconfigured: stop diff --git a/bitchat/Features/voice/Waveform.swift b/bitchat/Features/voice/Waveform.swift index 333dacd9..d1899c57 100644 --- a/bitchat/Features/voice/Waveform.swift +++ b/bitchat/Features/voice/Waveform.swift @@ -14,6 +14,7 @@ final class WaveformCache { private let queue = DispatchQueue(label: "com.bitchat.waveform-cache", attributes: .concurrent) private var cache: [URL: (waveform: [Float], lastAccess: Date)] = [:] + private var wipeGeneration: UInt64 = 0 private let maxCacheSize = 20 // Limit cache to prevent unbounded memory growth private init() {} @@ -28,6 +29,7 @@ final class WaveformCache { func waveform(for url: URL, bins: Int = 120, completion: @escaping ([Float]) -> Void) { queue.async { [weak self] in guard let self = self else { return } + let generation = self.wipeGeneration // Check cache (read-only, no update needed on cache hit for performance) if let entry = self.cache[url] { @@ -42,6 +44,10 @@ final class WaveformCache { self.queue.async(flags: .barrier) { [weak self] in guard let self = self else { return } + guard self.wipeGeneration == generation else { + DispatchQueue.main.async { completion([]) } + return + } // Evict oldest entry if cache is full if self.cache.count >= self.maxCacheSize { @@ -51,8 +57,8 @@ final class WaveformCache { } self.cache[url] = (computed, Date()) + DispatchQueue.main.async { completion(computed) } } - DispatchQueue.main.async { completion(computed) } } } @@ -62,6 +68,13 @@ final class WaveformCache { } } + func resetForPanic() { + queue.sync(flags: .barrier) { + wipeGeneration &+= 1 + cache.removeAll(keepingCapacity: false) + } + } + static func computeWaveform(url: URL, bins: Int) -> [Float]? { guard bins > 0 else { return nil } // Use autoreleasepool to manage memory from audio buffer allocations diff --git a/bitchat/Nostr/GeoRelayDirectory.swift b/bitchat/Nostr/GeoRelayDirectory.swift index ea42e4f0..b0856d8d 100644 --- a/bitchat/Nostr/GeoRelayDirectory.swift +++ b/bitchat/Nostr/GeoRelayDirectory.swift @@ -619,6 +619,17 @@ final class GeoRelayDirectory { RunLoop.main.add(timer, forMode: .common) } + /// Panic-wipe hook: stop scheduled retries, clear the last-fetch timestamp, + /// and remove the cached relay CSV from Application Support. + func resetForPanic() { + cancelRetry() + retryAttempt = 0 + dependencies.userDefaults.removeObject(forKey: lastFetchKey) + if let cacheURL = dependencies.cacheURL() { + try? FileManager.default.removeItem(at: cacheURL) + } + } + var debugRetryAttempt: Int { retryAttempt } var debugHasRetryTask: Bool { cleanupState.retryTask != nil } var debugObserverCount: Int { cleanupState.observers.count } diff --git a/bitchat/Nostr/NostrIdentityBridge.swift b/bitchat/Nostr/NostrIdentityBridge.swift index 51d14e84..52cb4876 100644 --- a/bitchat/Nostr/NostrIdentityBridge.swift +++ b/bitchat/Nostr/NostrIdentityBridge.swift @@ -47,6 +47,16 @@ final class NostrIdentityBridge { return pubkey } + /// Drop in-memory private key caches without touching Keychain. + /// Used by shadow service bridges during panic wipe so post-panic events + /// cannot keep signing with pre-panic keys cached in memory. + func clearInMemoryCaches() { + cacheLock.lock() + deviceSeedCache = nil + derivedIdentityCache.removeAll() + cacheLock.unlock() + } + /// Clear all Nostr identity associations and current identity func clearAllAssociations() { // Must go through the injected keychain, not raw SecItem calls: @@ -54,14 +64,11 @@ final class NostrIdentityBridge { // would wipe the developer's real Nostr identity on every test run. keychain.deleteAll(service: keychainService) - deviceSeedCache = nil - // Also drop the in-memory derived per-geohash identities. These hold the - // actual secp256k1 private keys; if left cached, post-panic geohash + // Also drop the in-memory derived per-geohash identities and seed. These + // hold actual secp256k1 private keys; if left cached, post-panic geohash // messages would still be signed with pre-panic keys (linkable across the // wipe) until the app is force-quit. - cacheLock.lock() - derivedIdentityCache.removeAll() - cacheLock.unlock() + clearInMemoryCaches() } // MARK: - Per-Geohash Identities (Location Channels) @@ -69,11 +76,19 @@ final class NostrIdentityBridge { /// Returns a stable device seed used to derive unlinkable per-geohash identities. /// Stored only on device keychain. private func getOrCreateDeviceSeed() -> Data { - if let cached = deviceSeedCache { return cached } + cacheLock.lock() + if let cached = deviceSeedCache { + cacheLock.unlock() + return cached + } + cacheLock.unlock() + if let existing = keychain.load(key: deviceSeedKey, service: keychainService) { // Migrate to AfterFirstUnlockThisDeviceOnly for stability during lock keychain.save(key: deviceSeedKey, data: existing, service: keychainService, accessible: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly) + cacheLock.lock() deviceSeedCache = existing + cacheLock.unlock() return existing } // CryptoKit key generation cannot fail, unlike SecRandomCopyBytes — @@ -81,7 +96,9 @@ final class NostrIdentityBridge { let seed = SymmetricKey(size: .bits256).withUnsafeBytes { Data($0) } // Ensure availability after first unlock to prevent unintended rotation when locked keychain.save(key: deviceSeedKey, data: seed, service: keychainService, accessible: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly) + cacheLock.lock() deviceSeedCache = seed + cacheLock.unlock() return seed } diff --git a/bitchat/Services/Gateway/BridgeCourierService.swift b/bitchat/Services/Gateway/BridgeCourierService.swift index 80a20a36..edfbcedd 100644 --- a/bitchat/Services/Gateway/BridgeCourierService.swift +++ b/bitchat/Services/Gateway/BridgeCourierService.swift @@ -145,6 +145,7 @@ final class BridgeCourierService: ObservableObject { private let dedupStore: BridgeDropDedupStore private var dedupPersistScheduled = false + private var dedupPersistTask: Task? init(now: @escaping () -> Date = Date.init, dedupStore: BridgeDropDedupStore? = nil) { self.now = now @@ -183,10 +184,11 @@ final class BridgeCourierService: ObservableObject { private func persistDedup() { guard !dedupPersistScheduled else { return } dedupPersistScheduled = true - Task { @MainActor [weak self] in + dedupPersistTask = Task { @MainActor [weak self] in try? await Task.sleep(nanoseconds: UInt64(Limits.dedupPersistCoalesceSeconds * 1_000_000_000)) - guard let self else { return } + guard let self, !Task.isCancelled else { return } self.dedupPersistScheduled = false + self.dedupPersistTask = nil self.flushDedupSnapshot() } } @@ -203,6 +205,9 @@ final class BridgeCourierService: ObservableObject { /// Panic wipe: forget queued drops and the persisted dedup record. func wipe() { + dedupPersistTask?.cancel() + dedupPersistTask = nil + dedupPersistScheduled = false cancelActivePublishes() rejectedDropKeys = ExpiringIDSet( capacity: Limits.maxTrackedIDs, diff --git a/bitchat/Services/Gateway/BridgeService.swift b/bitchat/Services/Gateway/BridgeService.swift index 2138a397..5000784b 100644 --- a/bitchat/Services/Gateway/BridgeService.swift +++ b/bitchat/Services/Gateway/BridgeService.swift @@ -286,6 +286,40 @@ final class BridgeService: ObservableObject { onEnabledChanged?(enabled) } + /// Panic-wipe hook: disable bridge mode, clear its persisted toggle, drop + /// queued uplinks/downlinks, forget the active cell and remote participants, + /// and reset all loop-prevention caches. + func resetForPanic() { + if activeCell != nil || !subscribedCells.isEmpty { + closeSubscription?() + } + isEnabled = false + defaults.removeObject(forKey: Self.enabledKey) + activeCell = nil + subscribedCells = [] + queuedUplinks.removeAll(keepingCapacity: false) + pendingDownlinks.removeAll(keepingCapacity: false) + downlinkDrainScheduled = false + presenceTimerArmed = false + lastPresenceAt = .distantPast + uplinkDepositTimes.removeAll(keepingCapacity: false) + downlinkSendTimes.removeAll(keepingCapacity: false) + inboundEventTimes.removeAll(keepingCapacity: false) + inboundEventTimesBySigner.removeAll(keepingCapacity: false) + signatureVerificationTokens = Double(Limits.signatureVerificationAttemptsPerMinute) + signatureVerificationLastRefillAt = nil + participants.removeAll(keepingCapacity: false) + bridgedPeerCount = 0 + bridgedParticipants = [] + meshBroadcastEventIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs) + publishedEventIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs) + rebroadcastEventIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs) + injectedMessageIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs) + receivedEventIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs) + observedRadioMessageIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs) + onEnabledChanged?(false) + } + /// Recomputes the active cell and (re)opens or closes the subscription. /// Call on toggle changes, location updates, and relay connectivity /// changes; idempotent. diff --git a/bitchat/Services/Gateway/GatewayService.swift b/bitchat/Services/Gateway/GatewayService.swift index 0c7bdc9f..0eba2264 100644 --- a/bitchat/Services/Gateway/GatewayService.swift +++ b/bitchat/Services/Gateway/GatewayService.swift @@ -159,6 +159,22 @@ final class GatewayService: ObservableObject { onEnabledChanged?(enabled) } + /// Panic-wipe hook: disable gateway mode, clear its persisted toggle, and + /// drop queued uplinks/downlinks and loop-prevention caches. + func resetForPanic() { + isEnabled = false + defaults.removeObject(forKey: Self.enabledKey) + queuedUplinks.removeAll(keepingCapacity: false) + pendingDownlinks.removeAll(keepingCapacity: false) + downlinkDrainScheduled = false + uplinkDepositTimes.removeAll(keepingCapacity: false) + downlinkSendTimes.removeAll(keepingCapacity: false) + meshBroadcastEventIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs) + publishedEventIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs) + rebroadcastEventIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs) + onEnabledChanged?(false) + } + // MARK: - Mesh carrier ingress (both roles) /// Entry point for received `nostrCarrier` packets. `directedToUs` is diff --git a/bitchat/Services/GeohashPresenceService.swift b/bitchat/Services/GeohashPresenceService.swift index 15e8ade2..ce9a8d76 100644 --- a/bitchat/Services/GeohashPresenceService.swift +++ b/bitchat/Services/GeohashPresenceService.swift @@ -68,6 +68,7 @@ final class GeohashPresenceService: ObservableObject { // Per-broadcast decorrelation delay range in seconds private let burstMinDelay: TimeInterval private let burstMaxDelay: TimeInterval + private let clearIdentityCache: () -> Void // Privacy: Only broadcast to these levels private let allowedPrecisions: Set = [ @@ -86,6 +87,7 @@ final class GeohashPresenceService: ObservableObject { self.torIsReady = { TorManager.shared.isReady } self.torIsForeground = { TorManager.shared.isForeground() } self.deriveIdentity = { try idBridge.deriveIdentity(forGeohash: $0) } + self.clearIdentityCache = { idBridge.clearInMemoryCaches() } self.relayLookup = { geohash, count in GeoRelayDirectory.shared.closestRelays(toGeohash: geohash, count: count) } @@ -116,6 +118,7 @@ final class GeohashPresenceService: ObservableObject { torIsReady: @escaping () -> Bool, torIsForeground: @escaping () -> Bool, deriveIdentity: @escaping (String) throws -> NostrIdentity, + clearIdentityCache: @escaping () -> Void = {}, relayLookup: @escaping (String, Int) -> [String], relaySender: @escaping (NostrEvent, [String]) -> Void, sleeper: @escaping (UInt64) async -> Void = { nanoseconds in try? await Task.sleep(nanoseconds: nanoseconds) }, @@ -137,6 +140,7 @@ final class GeohashPresenceService: ObservableObject { self.torIsReady = torIsReady self.torIsForeground = torIsForeground self.deriveIdentity = deriveIdentity + self.clearIdentityCache = clearIdentityCache self.relayLookup = relayLookup self.relaySender = relaySender self.sleeper = sleeper @@ -167,6 +171,7 @@ final class GeohashPresenceService: ObservableObject { heartbeatTimer = nil pendingBroadcastTasks.values.forEach { $0.cancel() } pendingBroadcastTasks.removeAll(keepingCapacity: false) + clearIdentityCache() } private func setupObservers() { diff --git a/bitchat/Services/LocationNotesManager.swift b/bitchat/Services/LocationNotesManager.swift index 3e5b0cb5..5ffe67e6 100644 --- a/bitchat/Services/LocationNotesManager.swift +++ b/bitchat/Services/LocationNotesManager.swift @@ -24,6 +24,13 @@ struct LocationNotesDependencies { private static let idBridge = NostrIdentityBridge() + /// Panic-wipe hook: drop cached per-geohash secp256k1 keys held by the + /// live dependencies bridge so post-panic notes/drops cannot sign with + /// pre-panic identities. + static func clearCachedIdentitiesForPanic() { + idBridge.clearInMemoryCaches() + } + static let live = LocationNotesDependencies( relayLookup: { geohash, count in GeoRelayDirectory.shared.closestRelays(toGeohash: geohash, count: count) @@ -464,4 +471,17 @@ final class LocationNotesManager: ObservableObject { state = .idle errorMessage = nil } + + /// Panic-wipe hook: cancel relay subscriptions, stop timers, and erase + /// in-memory notes and pre-panic public key state. + func resetForPanic() { + cancel() + expiryPruneTimer?.invalidate() + expiryPruneTimer = nil + directoryUpdateCancellable = nil + notes.removeAll(keepingCapacity: false) + noteIDs.removeAll(keepingCapacity: false) + ownPubkey = nil + initialLoadComplete = false + } } diff --git a/bitchat/Services/LocationNotesPool.swift b/bitchat/Services/LocationNotesPool.swift index 9a6f2ec5..8dbdb6e1 100644 --- a/bitchat/Services/LocationNotesPool.swift +++ b/bitchat/Services/LocationNotesPool.swift @@ -58,4 +58,13 @@ final class LocationNotesPool { entries[manager.geohash] = (entry.manager, entry.refs - 1) } } + + /// Panic-wipe hook: cancel subscriptions, wipe in-memory notes/identities, + /// and drop every pooled manager. + func resetForPanic() { + for entry in entries.values { + entry.manager.resetForPanic() + } + entries.removeAll(keepingCapacity: false) + } } diff --git a/bitchat/Services/MessageDeduplicationService.swift b/bitchat/Services/MessageDeduplicationService.swift index 693365ca..4d1c2f3f 100644 --- a/bitchat/Services/MessageDeduplicationService.swift +++ b/bitchat/Services/MessageDeduplicationService.swift @@ -178,6 +178,7 @@ final class MessageDeduplicationService { private let nostrEventStore: NostrProcessedEventStore? private let nostrEventCapacity: Int private var persistScheduled = false + private var persistTask: Task? private var pendingPersistIDs: [String] = [] /// Creates a new deduplication service with specified capacities. @@ -279,10 +280,11 @@ final class MessageDeduplicationService { private func schedulePersistIfNeeded() { guard let nostrEventStore, !persistScheduled else { return } persistScheduled = true - Task { @MainActor [weak self] in + persistTask = Task { @MainActor [weak self] in try? await Task.sleep(nanoseconds: 2_000_000_000) - guard let self else { return } + guard let self, !Task.isCancelled else { return } self.persistScheduled = false + self.persistTask = nil let newIDs = self.pendingPersistIDs self.pendingPersistIDs.removeAll() nostrEventStore.append(newIDs, cap: self.nostrEventCapacity) @@ -314,6 +316,9 @@ final class MessageDeduplicationService { /// Clears all caches. This is the wipe/panic path: the persisted /// private-envelope record goes with everything else. func clearAll() { + persistTask?.cancel() + persistTask = nil + persistScheduled = false contentCache.clear() nostrEventCache.clear() nostrAckCache.clear() diff --git a/bitchat/Services/NostrProcessedEventStore.swift b/bitchat/Services/NostrProcessedEventStore.swift index ee70f0e7..a1312f38 100644 --- a/bitchat/Services/NostrProcessedEventStore.swift +++ b/bitchat/Services/NostrProcessedEventStore.swift @@ -56,7 +56,7 @@ final class NostrProcessedEventStore { } func wipe() { - ioQueue.async { [self] in + ioQueue.sync { guard let fileURL else { return } try? FileManager.default.removeItem(at: fileURL) } diff --git a/bitchat/Services/NostrTransport.swift b/bitchat/Services/NostrTransport.swift index 10f51219..2a1ff3e3 100644 --- a/bitchat/Services/NostrTransport.swift +++ b/bitchat/Services/NostrTransport.swift @@ -97,6 +97,7 @@ final class NostrTransport: Transport, @unchecked Sendable { private let queue = DispatchQueue(label: "chat.bitchat.nostr-ack-pacer") private var pending: [() -> Void] = [] private var isSending = false + private var generation: UInt64 = 0 private let interval: TimeInterval = TransportConfig.nostrReadAckInterval private let scheduleAfter: Scheduler @@ -113,15 +114,34 @@ final class NostrTransport: Transport, @unchecked Sendable { } } + /// Returns the current panic-wipe generation so in-flight `@MainActor` + /// ACK tasks can reject stale pre-panic work before signing/publishing. + func currentGeneration() -> UInt64 { + queue.sync { generation } + } + + /// Synchronously drops all queued ACK closures (which may capture + /// pre-panic Nostr identities and peer IDs) and fences any in-flight + /// pacing timer callback. + func resetForPanic() { + queue.sync { + self.generation &+= 1 + self.pending.removeAll(keepingCapacity: false) + self.isSending = false + } + } + /// Must be called on `queue`. private func processNext() { guard !isSending, !pending.isEmpty else { return } isSending = true + let currentGeneration = generation let send = pending.removeFirst() send() scheduleAfter(interval) { [weak self] in guard let self else { return } self.queue.async { + guard self.generation == currentGeneration else { return } self.isSending = false self.processNext() } @@ -274,7 +294,8 @@ final class NostrTransport: Transport, @unchecked Sendable { /// geohash acks ride throwaway transport instances that must stay alive /// until their ack leaves the queue. private func enqueueAck(_ ack: QueuedAck) { - dependencies.ackPacer.enqueue { self.sendAckItem(ack) } + let generation = dependencies.ackPacer.currentGeneration() + dependencies.ackPacer.enqueue { self.sendAckItem(ack, generation: generation) } } func sendFavoriteNotification(to peerID: PeerID, isFavorite: Bool) { @@ -356,8 +377,11 @@ extension NostrTransport { /// Sends a single ack item (invoked by the pacer, one per interval) - private func sendAckItem(_ item: QueuedAck) { + private func sendAckItem(_ item: QueuedAck, generation: UInt64) { Task { @MainActor in + // Reject ACKs that were already handed off to MainActor before a + // panic wipe so they cannot sign or publish with pre-panic keys. + guard dependencies.ackPacer.currentGeneration() == generation else { return } switch item { case .readDirect(let receipt, let peerID): guard let recipientNpub = resolveRecipientNpub(for: peerID), diff --git a/bitchat/Services/PrivateChatManager.swift b/bitchat/Services/PrivateChatManager.swift index 8f8ef08a..9b7e3e33 100644 --- a/bitchat/Services/PrivateChatManager.swift +++ b/bitchat/Services/PrivateChatManager.swift @@ -47,6 +47,10 @@ final class PrivateChatManager: ObservableObject { bindSelectionMirror() // didSet does not fire during init } + func resetForPanic() { + sentReadReceipts.removeAll(keepingCapacity: false) + } + /// Keeps `selectedPeer` in lock-step with the store's selection axis /// (including store-internal handoffs such as conversation migration). private func bindSelectionMirror() { diff --git a/bitchat/Services/VerificationService.swift b/bitchat/Services/VerificationService.swift index 26247379..15ade2e1 100644 --- a/bitchat/Services/VerificationService.swift +++ b/bitchat/Services/VerificationService.swift @@ -8,8 +8,20 @@ final class VerificationService { // identity operations go through the transport's narrow noise* wrappers // so the raw NoiseEncryptionService is never exposed. private var transport: Transport? + private let qrCacheLock = NSLock() + private var cachedQR: (nick: String, npub: String?, builtAt: Date, value: String)? + func configure(with transport: Transport) { self.transport = transport } + /// Panic-wipe hook: drop the cached signed verification QR immediately so + /// pre-panic Noise/Ed25519/npub keys cannot be re-served during the 60s + /// cache window. + func resetForPanic() { + qrCacheLock.lock() + cachedQR = nil + qrCacheLock.unlock() + } + /// Encapsulates the data encoded into a verification QR struct VerificationQR: Codable { let v: Int @@ -75,8 +87,10 @@ final class VerificationService { /// Build a signed QR string for the current identity func buildMyQRString(nickname: String, npub: String?) -> String? { // Simple short-lived cache to speed up sheet opening - struct Cache { static var last: (nick: String, npub: String?, builtAt: Date, value: String)? } - if let c = Cache.last, c.nick == nickname, c.npub == npub, Date().timeIntervalSince(c.builtAt) < 60 { + qrCacheLock.lock() + let cached = cachedQR + qrCacheLock.unlock() + if let c = cached, c.nick == nickname, c.npub == npub, Date().timeIntervalSince(c.builtAt) < 60 { return c.value } guard let transport = transport else { return nil } @@ -99,7 +113,9 @@ final class VerificationService { nonceB64: payload.nonceB64, sigHex: sig.hexEncodedString()) let out = signed.toURLString() - Cache.last = (nickname, npub, Date(), out) + qrCacheLock.lock() + cachedQR = (nickname, npub, Date(), out) + qrCacheLock.unlock() return out } diff --git a/bitchat/ViewModels/ChatVerificationCoordinator.swift b/bitchat/ViewModels/ChatVerificationCoordinator.swift index 42b39a94..b499530c 100644 --- a/bitchat/ViewModels/ChatVerificationCoordinator.swift +++ b/bitchat/ViewModels/ChatVerificationCoordinator.swift @@ -168,6 +168,13 @@ final class ChatVerificationCoordinator { self.context = context } + func resetForPanic() { + pendingQRVerifications.removeAll(keepingCapacity: false) + lastVerifyNonceByPeer.removeAll(keepingCapacity: false) + lastInboundVerifyChallengeAt.removeAll(keepingCapacity: false) + lastMutualToastAt.removeAll(keepingCapacity: false) + } + func verifyFingerprint(for peerID: PeerID) { guard let fingerprint = context.getFingerprint(for: peerID) else { return } diff --git a/bitchat/ViewModels/ChatViewModel.swift b/bitchat/ViewModels/ChatViewModel.swift index 36742d29..7ee5de4f 100644 --- a/bitchat/ViewModels/ChatViewModel.swift +++ b/bitchat/ViewModels/ChatViewModel.swift @@ -84,6 +84,7 @@ import SwiftUI import Combine import CommonCrypto import CoreBluetooth +import Tor #if os(iOS) import UIKit #endif @@ -1638,6 +1639,8 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage // counters describing all of it CourierStore.shared.wipe() BridgeCourierService.shared.wipe() + BridgeService.shared.resetForPanic() + GatewayService.shared.resetForPanic() messageRouter.wipeOutbox() GossipMessageArchive.wipeDefault() StoreAndForwardMetrics.shared.reset() @@ -1652,6 +1655,10 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage // A hand-added relay names an operator someone chose to route through, // which is the kind of trace a wipe should not leave behind. NostrRelaySettings.reset() + NearbyNotesCounter.shared.resetForPanic() + LocationNotesPool.shared.resetForPanic() + LocationNotesDependencies.clearCachedIdentitiesForPanic() + WaveformCache.shared.resetForPanic() // Drop private group keys and rosters (keychain + disk) groupStore.wipe() @@ -1672,7 +1679,9 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage SharedContentStore(defaults: sharedDefaults).discardAll() } - // Identity manager has cleared persisted identity data above + // Clear cached QR verification payload and pending verification state. + VerificationService.shared.resetForPanic() + verificationCoordinator.resetForPanic() // Clear autocomplete state autocompleteSuggestions.removeAll() @@ -1697,12 +1706,14 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage // Clear read receipt tracking sentReadReceipts.removeAll() + privateChatManager.resetForPanic() deduplicationService.clearAll() // IMPORTANT: Clear Nostr-related state - // Drop relay subscriptions, handlers, pending sends, and replay state. - // Geohash DM handlers can capture pre-wipe Nostr identities, so a plain - // disconnect is not enough here. + // Drop relay subscriptions, handlers, pending sends, paced ACKs, and + // replay state. Geohash DM handlers and paced ACK closures can capture + // pre-wipe Nostr identities, so a plain disconnect is not enough here. + NostrTransport.sharedAckPacer.resetForPanic() NostrRelayManager.shared.resetForPanicWipe() // Clearing relay handlers stops NEW events, but a detached gift-wrap // decrypt spawned just before the wipe still holds a pre-wipe key and @@ -1714,6 +1725,13 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage // Clear Nostr identity associations idBridge.clearAllAssociations() + // Wipe cached geo relay list and Arti Tor state on disk (keep unit + // tests away from the host user's Application Support tree). + if !TestEnvironment.isRunningTests { + GeoRelayDirectory.shared.resetForPanic() + TorManager.shared.wipeStateDirectoryForPanic() + } + // Replace the BLE identity while keeping the radio stopped. It may // reopen only after the durable panic transaction commits. if let panicTransport = meshService as? PanicResettingTransport { diff --git a/bitchatTests/Services/PanicWipeCoverageTests.swift b/bitchatTests/Services/PanicWipeCoverageTests.swift new file mode 100644 index 00000000..2d9108bb --- /dev/null +++ b/bitchatTests/Services/PanicWipeCoverageTests.swift @@ -0,0 +1,279 @@ +import BitFoundation +import Combine +import Foundation +import XCTest +@testable import bitchat + +@MainActor +final class PanicWipeCoverageTests: XCTestCase { + func test_nostrIdentityBridge_clearInMemoryCaches_rotatesAfterKeychainWipe() throws { + let keychain = PreviewKeychainManager() + let bridgeA = NostrIdentityBridge(keychain: keychain) + let bridgeB = NostrIdentityBridge(keychain: keychain) + + let beforeA = try bridgeA.deriveIdentity(forGeohash: "u4pruy") + let beforeB = try bridgeB.deriveIdentity(forGeohash: "u4pruy") + XCTAssertEqual(beforeA.publicKeyHex, beforeB.publicKeyHex) + + // Wipe keychain through primary bridge and clear shadow bridge cache. + bridgeA.clearAllAssociations() + bridgeB.clearInMemoryCaches() + + let afterB = try bridgeB.deriveIdentity(forGeohash: "u4pruy") + XCTAssertNotEqual(beforeA.publicKeyHex, afterB.publicKeyHex) + } + + func test_geohashPresenceService_stopForPanic_invokesClearIdentityCache() { + var clearCalls = 0 + let service = GeohashPresenceService( + availableChannelsProvider: { [] }, + locationChanges: Empty().eraseToAnyPublisher(), + torReadyPublisher: Empty().eraseToAnyPublisher(), + torIsReady: { false }, + torIsForeground: { true }, + deriveIdentity: { _ in try NostrIdentity.generate() }, + clearIdentityCache: { clearCalls += 1 }, + relayLookup: { _, _ in [] }, + relaySender: { _, _ in } + ) + + service.stopForPanic() + + XCTAssertEqual(clearCalls, 1) + } + + func test_bridgeService_resetForPanic_clearsPersistedToggleCellAndQueues() { + let suite = "PanicWipeBridge-\(UUID().uuidString)" + let defaults = UserDefaults(suiteName: suite)! + defaults.removePersistentDomain(forName: suite) + + var closedSubscriptions = 0 + var enabledNotifications: [Bool] = [] + let service = BridgeService(defaults: defaults) + service.locationCell = { "u4pruy" } + service.closeSubscription = { closedSubscriptions += 1 } + service.onEnabledChanged = { enabledNotifications.append($0) } + + service.setEnabled(true) + XCTAssertTrue(service.isEnabled) + XCTAssertEqual(defaults.bool(forKey: "bridge.userEnabled"), true) + XCTAssertEqual(service.activeCell, "u4pruy") + + service.resetForPanic() + + XCTAssertFalse(service.isEnabled) + XCTAssertNil(defaults.object(forKey: "bridge.userEnabled")) + XCTAssertNil(service.activeCell) + XCTAssertTrue(service.subscribedCells.isEmpty) + XCTAssertTrue(service.queuedUplinks.isEmpty) + XCTAssertEqual(service.bridgedPeerCount, 0) + XCTAssertTrue(service.bridgedParticipants.isEmpty) + XCTAssertGreaterThanOrEqual(closedSubscriptions, 1) + XCTAssertEqual(enabledNotifications.last, false) + } + + func test_gatewayService_resetForPanic_clearsPersistedToggleAndQueues() { + let suite = "PanicWipeGateway-\(UUID().uuidString)" + let defaults = UserDefaults(suiteName: suite)! + defaults.removePersistentDomain(forName: suite) + + var enabledNotifications: [Bool] = [] + let service = GatewayService(defaults: defaults) + service.onEnabledChanged = { enabledNotifications.append($0) } + + service.setEnabled(true) + XCTAssertTrue(service.isEnabled) + XCTAssertEqual(defaults.bool(forKey: "gateway.userEnabled"), true) + + service.resetForPanic() + + XCTAssertFalse(service.isEnabled) + XCTAssertNil(defaults.object(forKey: "gateway.userEnabled")) + XCTAssertTrue(service.queuedUplinks.isEmpty) + XCTAssertEqual(enabledNotifications.last, false) + } + + func test_nostrAckPacer_resetForPanic_dropsQueuedClosuresAndFencesInFlightTimer() { + final class PacerBox: @unchecked Sendable { + private let lock = NSLock() + private var callbacks: [@Sendable () -> Void] = [] + private var firedItems: [Int] = [] + + func addCallback(_ cb: @escaping @Sendable () -> Void) { + lock.lock() + callbacks.append(cb) + lock.unlock() + } + + func takeCallbacks() -> [@Sendable () -> Void] { + lock.lock() + defer { lock.unlock() } + return callbacks + } + + func recordFired(_ value: Int) { + lock.lock() + firedItems.append(value) + lock.unlock() + } + + func fired() -> [Int] { + lock.lock() + defer { lock.unlock() } + return firedItems + } + } + + let box = PacerBox() + let pacer = NostrTransport.AckPacer { _, action in + box.addCallback(action) + } + + let firstStarted = expectation(description: "first ack started") + pacer.enqueue { + box.recordFired(1) + firstStarted.fulfill() + } + pacer.enqueue { + box.recordFired(2) + } + wait(for: [firstStarted], timeout: TestConstants.settleTimeout) + + pacer.resetForPanic() + + // Fire the stale pre-panic timer callback; queued item #2 must never run. + for callback in box.takeCallbacks() { + callback() + } + + // Enqueue a post-panic item to flush the serial queue and verify #2 stayed dropped. + let postPanicDone = expectation(description: "post-panic ack ran") + pacer.enqueue { + box.recordFired(3) + postPanicDone.fulfill() + } + wait(for: [postPanicDone], timeout: TestConstants.settleTimeout) + + XCTAssertEqual(box.fired(), [1, 3]) + } + + func test_nostrTransport_resetForPanic_cancelsInFlightMainActorGeohashAck() async throws { + let dequeued = DispatchSemaphore(value: 0) + let pacer = NostrTransport.AckPacer { _, _ in + dequeued.signal() + } + var sentEvents: [NostrEvent] = [] + let sender = try NostrIdentity.generate() + let recipient = try NostrIdentity.generate() + let transport = NostrTransport( + keychain: PreviewKeychainManager(), + idBridge: NostrIdentityBridge(keychain: PreviewKeychainManager()), + dependencies: NostrTransport.Dependencies( + notificationCenter: NotificationCenter(), + loadFavorites: { [:] }, + favoriteStatusForNoiseKey: { _ in nil }, + favoriteStatusForPeerID: { _ in nil }, + currentIdentity: { sender }, + registerPendingGiftWrap: { _ in }, + sendEvent: { sentEvents.append($0) }, + scheduleAfter: { _, _ in }, + relayConnectivity: { Just(true).eraseToAnyPublisher() }, + ackPacer: pacer + ) + ) + + // Enqueue a geohash ACK and wait until AckPacer has dequeued it and + // handed off `Task { @MainActor in ... }` while we still hold MainActor. + transport.sendDeliveryAckGeohash( + for: "pre-panic-mid", + toRecipientHex: recipient.publicKeyHex, + from: sender + ) + XCTAssertEqual(dequeued.wait(timeout: .now() + TestConstants.settleTimeout), .success) + + // Panic runs on MainActor BEFORE the handed-off ACK task executes. + pacer.resetForPanic() + + // Yield so the already-queued MainActor ACK task gets a turn to run. + await Task.yield() + try? await Task.sleep(nanoseconds: 50_000_000) + + XCTAssertTrue(sentEvents.isEmpty, "Pre-panic MainActor ACK task must not publish after resetForPanic()") + } + + func test_verificationService_resetForPanic_evictsCachedQRString() throws { + let transport = MockTransport() + let service = VerificationService() + service.configure(with: transport) + + let nickname = "panic-qr-\(UUID().uuidString)" + let first = try XCTUnwrap(service.buildMyQRString(nickname: nickname, npub: nil)) + let cached = try XCTUnwrap(service.buildMyQRString(nickname: nickname, npub: nil)) + XCTAssertEqual(first, cached) + + service.resetForPanic() + let refreshed = try XCTUnwrap(service.buildMyQRString(nickname: nickname, npub: nil)) + XCTAssertNotEqual(first, refreshed) + } + + func test_nostrProcessedEventStore_wipe_deletesFileSynchronously() { + let tempDir = FileManager.default.temporaryDirectory + .appendingPathComponent("PanicProcessedEvents-\(UUID().uuidString)", isDirectory: true) + let fileURL = tempDir.appendingPathComponent("processed-events.json") + defer { try? FileManager.default.removeItem(at: tempDir) } + + let store = NostrProcessedEventStore(fileURL: fileURL) + store.append(["evt-1", "evt-2"], cap: 100) + // `load()` synchronizes on `ioQueue`, ensuring the async append wrote to disk. + XCTAssertEqual(store.load(), ["evt-1", "evt-2"]) + XCTAssertTrue(FileManager.default.fileExists(atPath: fileURL.path)) + + store.wipe() + + // Must be deleted synchronously before `wipe()` returns. + XCTAssertFalse(FileManager.default.fileExists(atPath: fileURL.path)) + XCTAssertTrue(store.load().isEmpty) + } + + func test_privateChatManager_resetForPanic_clearsSentReadReceipts() { + let manager = PrivateChatManager() + manager.sentReadReceipts.insert("msg-1") + manager.sentReadReceipts.insert("msg-2") + + manager.resetForPanic() + + XCTAssertTrue(manager.sentReadReceipts.isEmpty) + } + + func test_nearbyNotesCounter_resetForPanic_clearsRevealedAndReleasesManager() { + var released = 0 + let counter = NearbyNotesCounter( + managerFactory: { geohash in + LocationNotesManager( + geohash: geohash, + dependencies: LocationNotesDependencies( + relayLookup: { _, _ in [] }, + subscribe: { _, _, _, _, _ in }, + unsubscribe: { _ in }, + sendEvent: { _, _ in }, + deriveIdentity: { _ in try NostrIdentity.generate() }, + now: Date.init + ) + ) + }, + releaseManager: { manager in + if manager != nil { released += 1 } + }, + locationNotesEnabled: { true } + ) + + counter.reveal() + XCTAssertTrue(counter.revealed) + + counter.resetForPanic() + + XCTAssertFalse(counter.revealed) + XCTAssertEqual(counter.noteCount, 0) + XCTAssertGreaterThanOrEqual(released, 0) + } +} diff --git a/localPackages/Arti/Sources/TorManager.swift b/localPackages/Arti/Sources/TorManager.swift index e811bb84..0181ea58 100644 --- a/localPackages/Arti/Sources/TorManager.swift +++ b/localPackages/Arti/Sources/TorManager.swift @@ -83,6 +83,7 @@ public final class TorManager: ObservableObject { // dropped — it is recorded here and honored when the shutdown finishes. private var shutdownsInFlight = 0 private var startPendingAfterShutdown = false + private var wipeDataDirectoryOnShutdown = false private var bootstrapMonitorStarted = false // Fences the detached poll loop: shutdown, dormancy, and restart each bump // this, so a loop from a previous attempt cannot run out its deadline and @@ -402,6 +403,10 @@ public final class TorManager: ObservableObject { // Note: Don't clear startedAt here - it will be set fresh on next startIfNeeded() // Clearing it here races with startup and defeats the grace period self.shutdownsInFlight -= 1 + if self.shutdownsInFlight == 0 && self.wipeDataDirectoryOnShutdown { + self.wipeDataDirectoryOnShutdown = false + self.removeDataDirectoryOnDisk() + } if self.shutdownsInFlight == 0 && self.startPendingAfterShutdown { self.startPendingAfterShutdown = false SecureLogger.debug("TorManager: honoring start deferred during shutdown", category: .session) @@ -411,6 +416,26 @@ public final class TorManager: ObservableObject { } } + /// Panic-wipe hook: removes `Application Support/bitchat/arti` (guard + /// nodes, state, consensus cache). If Arti is currently shutting down, + /// defers removal until `arti_stop()` finishes so SQLite/state files are + /// deleted cleanly before any post-panic restart. + public func wipeStateDirectoryForPanic() { + if shutdownsInFlight > 0 || arti_is_running() != 0 { + wipeDataDirectoryOnShutdown = true + if shutdownsInFlight == 0 { + shutdownCompletely() + } + return + } + removeDataDirectoryOnDisk() + } + + private func removeDataDirectoryOnDisk() { + guard let dir = dataDirectoryURL() else { return } + try? FileManager.default.removeItem(at: dir) + } + private func restartArti() async { SecureLogger.debug("TorManager: restartArti() starting", category: .session) await MainActor.run {