From 02e6c31d7a95142ed86795cc48d5226d1477023d Mon Sep 17 00:00:00 2001 From: Jozef Koval Date: Sun, 29 Nov 2026 01:02:33 +0100 Subject: [PATCH] fix(security): cancel the in-flight GeoRelay fetch and drop deferred prekey bundles on panic wipe (#1937) * fix(security): cancel in-flight GeoRelay fetch and drop deferred prekey bundles on panic wipe Follow-up to #1902. A detached task does not inherit cancellation, so resetForPanic() did not stop a relay-list request that had started. The fetch now forwards the cancel into the detached task. resetIdentityForPanic() left pendingPrekeyBundles in place, so a bundle deferred before the wipe entered the prekey store when its owner authenticated later. The reset now clears the map. Adds a fill, clear, probe test for the peer color cache behind a DEBUG-only probe. * test: place the GeoRelay request-cancel test before the Tor-wait test PR #1935 adds tests after the Tor-wait test. A different place keeps the two changes free of a merge conflict. --- bitchat/Nostr/GeoRelayDirectory.swift | 12 +++++- bitchat/Services/BLE/BLEService+Testing.swift | 5 +++ bitchat/Services/BLE/BLEService.swift | 3 ++ bitchat/Utils/Color+Peer.swift | 12 +++++- .../EndToEnd/PrekeyEndToEndTests.swift | 28 ++++++++++++++ .../Nostr/GeoRelayDirectoryTests.swift | 38 +++++++++++++++++++ .../Services/PanicWipeCoverageTests.swift | 11 ++++++ 7 files changed, 106 insertions(+), 3 deletions(-) diff --git a/bitchat/Nostr/GeoRelayDirectory.swift b/bitchat/Nostr/GeoRelayDirectory.swift index 1a44828b..e424f0b7 100644 --- a/bitchat/Nostr/GeoRelayDirectory.swift +++ b/bitchat/Nostr/GeoRelayDirectory.swift @@ -417,7 +417,7 @@ final class GeoRelayDirectory { let fetchData = await makeFetchData() guard !Task.isCancelled else { return .cancelled } - return await Task.detached(priority: .utility) { + let fetchTask = Task.detached(priority: .utility) { guard !Task.isCancelled else { return DetachedFetchOutcome.cancelled } do { let data = try await fetchData(request) @@ -436,7 +436,15 @@ final class GeoRelayDirectory { if Task.isCancelled { return .cancelled } return .network(error.localizedDescription) } - }.value + } + // A detached task does not inherit cancellation. Forward the caller's + // cancel (panic wipe, a newer fetch) so the checks above and the HTTP + // reader's own cancellation handler can stop a request in flight. + return await withTaskCancellationHandler { + await fetchTask.value + } onCancel: { + fetchTask.cancel() + } } private enum FetchFailure { diff --git a/bitchat/Services/BLE/BLEService+Testing.swift b/bitchat/Services/BLE/BLEService+Testing.swift index acae41c9..c0320802 100644 --- a/bitchat/Services/BLE/BLEService+Testing.swift +++ b/bitchat/Services/BLE/BLEService+Testing.swift @@ -147,6 +147,11 @@ extension BLEService { gossipSyncManager?._hasPrekeyBundle(for: peerID) ?? false } + /// Number of prekey bundles that wait for a Noise-authenticated signing key. + var _test_pendingPrekeyBundleCount: Int { + onEngine { pendingPrekeyBundles.count } + } + func _test_acceptsIngress(packet: BitchatPacket, boundPeerID: PeerID?) -> Bool { let claimedSenderID = PeerID(hexData: packet.senderID) guard case .success = BLEIngressLinkRegistry.packetContext( diff --git a/bitchat/Services/BLE/BLEService.swift b/bitchat/Services/BLE/BLEService.swift index b2e1fdba..5c54b8b0 100644 --- a/bitchat/Services/BLE/BLEService.swift +++ b/bitchat/Services/BLE/BLEService.swift @@ -782,6 +782,9 @@ final class BLEService: NSObject { pendingDirectedRelays.removeAll() ingressLinks.removeAll() verifiedDirectAnnounceOwners.removeAll() + // Bundles deferred before the wipe name pre-panic peers. A later + // Noise authentication must not ingest them into the fresh store. + pendingPrekeyBundles.removeAll() recentTrafficTracker.removeAll() scheduledRelays.cancelAll() // Proofs and revalidation epochs die with the identity; the diff --git a/bitchat/Utils/Color+Peer.swift b/bitchat/Utils/Color+Peer.swift index e8d0d10b..b8f23f1f 100644 --- a/bitchat/Utils/Color+Peer.swift +++ b/bitchat/Utils/Color+Peer.swift @@ -85,8 +85,18 @@ extension Color { peerColorCache.reset() } + private static func peerColorCacheKey(_ peerSeed: String, isDark: Bool) -> String { + peerSeed + (isDark ? "|dark" : "|light") + } + + #if DEBUG + static func hasCachedPeerColor(for peerSeed: String, isDark: Bool) -> Bool { + peerColorCache.lookup(peerColorCacheKey(peerSeed, isDark: isDark)).color != nil + } + #endif + init(peerSeed: String, isDark: Bool) { - let cacheKey = peerSeed + (isDark ? "|dark" : "|light") + let cacheKey = Self.peerColorCacheKey(peerSeed, isDark: isDark) let lookup = Self.peerColorCache.lookup(cacheKey) if let cached = lookup.color { self = cached diff --git a/bitchatTests/EndToEnd/PrekeyEndToEndTests.swift b/bitchatTests/EndToEnd/PrekeyEndToEndTests.swift index 15d3cafe..bcccb448 100644 --- a/bitchatTests/EndToEnd/PrekeyEndToEndTests.swift +++ b/bitchatTests/EndToEnd/PrekeyEndToEndTests.swift @@ -475,4 +475,32 @@ struct PrekeyEndToEndTests { #expect(!alice.prekeyBundleStore.hasUsableBundle(for: bob.noiseStaticPublicKeyData())) #expect(!alice._test_hasGossipPrekeyBundle(for: bob.myPeerID)) } + + @Test func panicResetDropsDeferredPrekeyBundle() async throws { + let (alice, aliceIdentity) = makeService() + let (bob, _) = makeService() + + let bobOut = PacketTap() + bob._test_onOutboundPacket = bobOut.record + let (announce, bundlePacket) = try await captureAnnounceAndBundle(from: bob, tap: bobOut) + + // Alice has no Noise-authenticated signing key for Bob, so his bundle + // waits in the deferred map. + alice._test_handlePacket(announce, fromPeerID: bob.myPeerID, preseedPeer: false) + alice._test_handlePacket(bundlePacket, fromPeerID: bob.myPeerID, preseedPeer: false) + await alice._test_drainAllPipelines() + #expect(alice._test_pendingPrekeyBundleCount == 1) + + alice.suspendForPanicReset() + alice.resetIdentityForPanic(currentNickname: "anon1234", restartServices: false) + alice.completePanicReset(restartServices: false) + #expect(alice._test_pendingPrekeyBundleCount == 0) + + // Bob authenticates after the wipe. His next announce must not pull + // the pre-panic bundle into the prekey store. + authenticateSigningKey(of: bob, in: aliceIdentity) + alice._test_handlePacket(announce, fromPeerID: bob.myPeerID, preseedPeer: false) + await alice._test_drainAllPipelines() + #expect(!alice.prekeyBundleStore.hasUsableBundle(for: bob.noiseStaticPublicKeyData())) + } } diff --git a/bitchatTests/Nostr/GeoRelayDirectoryTests.swift b/bitchatTests/Nostr/GeoRelayDirectoryTests.swift index fab7b627..2fcf5f37 100644 --- a/bitchatTests/Nostr/GeoRelayDirectoryTests.swift +++ b/bitchatTests/Nostr/GeoRelayDirectoryTests.swift @@ -561,6 +561,44 @@ final class GeoRelayDirectoryTests: XCTestCase { XCTAssertEqual(directory.debugClosestRelaysCacheCount, 0) } + func test_resetForPanic_cancelsFetchAfterRequestStarted() async { + let (started, startedContinuation) = AsyncStream.makeStream() + let (release, releaseContinuation) = AsyncStream.makeStream() + let (observed, observedContinuation) = AsyncStream.makeStream() + + let harness = makeHarness( + bundleCSV: """ + relay url,lat,lon + bundle.example,37.77,-122.41 + """, + fetchCSV: """ + relay url,lat,lon + remote.example,37.77,-122.41 + """, + fetchObserver: { + // Tor is ready and the request stage runs. + startedContinuation.yield() + for await _ in release { break } + observedContinuation.yield(Task.isCancelled) + } + ) + let directory = GeoRelayDirectory(dependencies: harness.dependencies) + + directory.prefetchIfNeeded(force: true) + for await _ in started { break } + + // Panic runs while the request is in flight. + directory.resetForPanic() + releaseContinuation.yield() + + var requestSawCancellation: Bool? + for await value in observed { + requestSawCancellation = value + break + } + XCTAssertEqual(requestSawCancellation, true, "resetForPanic() must cancel a request that has started") + } + func test_resetForPanic_cancelsInFlightFetchWithoutWritingCacheOrSchedulingRetry() async { final class Gate: @unchecked Sendable { private let lock = NSLock() diff --git a/bitchatTests/Services/PanicWipeCoverageTests.swift b/bitchatTests/Services/PanicWipeCoverageTests.swift index 006544e4..e9a3cfe6 100644 --- a/bitchatTests/Services/PanicWipeCoverageTests.swift +++ b/bitchatTests/Services/PanicWipeCoverageTests.swift @@ -548,6 +548,17 @@ final class PanicWipeCoverageTests: XCTestCase { XCTAssertFalse(CashuTokenDecoder.hasCachedDecode(for: huge)) } + func test_peerColorCache_clearPeerColorCache_evictsCachedSeed() { + let seed = "panic-peer-seed-\(UUID().uuidString)" + + _ = Color(peerSeed: seed, isDark: true) + XCTAssertTrue(Color.hasCachedPeerColor(for: seed, isDark: true)) + + Color.clearPeerColorCache() + + XCTAssertFalse(Color.hasCachedPeerColor(for: seed, isDark: true)) + } + func test_bleService_courierDepositAndSpray_fencedAcrossPanicLifecycle() async throws { func makeIsolatedBLEService() -> BLEService { let keychain = MockKeychain()