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.
This commit is contained in:
Jozef Koval authored and GitHub committed 2026-11-28 14:02:33 -10:00
1 parent 1c63ae6cab
commit 02e6c31d7a
7 files changed
+106 -3

No files matched your search

+10 -2
View File
@@ -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 {
@@ -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(
+3
View File
@@ -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
+11 -1
View File
@@ -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
@@ -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()))
}
}
@@ -561,6 +561,44 @@ final class GeoRelayDirectoryTests: XCTestCase {
XCTAssertEqual(directory.debugClosestRelaysCacheCount, 0)
}
func test_resetForPanic_cancelsFetchAfterRequestStarted() async {
let (started, startedContinuation) = AsyncStream<Void>.makeStream()
let (release, releaseContinuation) = AsyncStream<Void>.makeStream()
let (observed, observedContinuation) = AsyncStream<Bool>.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()
@@ -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()