diff --git a/bitchat/App/NearbyNotesCounter.swift b/bitchat/App/NearbyNotesCounter.swift index d1863970..d90cad27 100644 --- a/bitchat/App/NearbyNotesCounter.swift +++ b/bitchat/App/NearbyNotesCounter.swift @@ -85,9 +85,9 @@ final class NearbyNotesCounter: ObservableObject { .receive(on: DispatchQueue.main) .sink { [weak self] _ in self?.retarget() } // CoreLocation can revoke authorization while the view remains - // mounted. `availableChannels` deliberately retains its last value, - // so permission must be an independent invalidation signal or the - // building REQ survives on stale coordinates. + // mounted. Revocation also clears `availableChannels`, but + // permission stays an independent invalidation signal so the + // building REQ never depends on that list being current. permissionCancellable = locationManager.$permissionState .receive(on: DispatchQueue.main) .sink { [weak self] _ in self?.retarget() } diff --git a/bitchat/Services/Gateway/BridgeService.swift b/bitchat/Services/Gateway/BridgeService.swift index 2138a397..8b67e962 100644 --- a/bitchat/Services/Gateway/BridgeService.swift +++ b/bitchat/Services/Gateway/BridgeService.swift @@ -336,6 +336,19 @@ final class BridgeService: ObservableObject { return nil } + /// What `locationCell` should return: the neighborhood channel from this + /// device's last location fix, or nil while location access is not + /// authorized. Revoking access clears the channel list too, but the + /// cell is published to relays, so it is checked here as well rather + /// than trusting that list to be current. + static func ownLocationCell( + from channels: [GeohashChannel], + permission: LocationChannelManager.PermissionState + ) -> String? { + guard permission == .authorized else { return nil } + return channels.first { $0.level == .neighborhood }?.geohash + } + // One switch does the right thing: while bridging, a device with // internet automatically serves its island (accepts deposits, carries // remote messages onto the radio). The marginal cost over bridging diff --git a/bitchat/Services/GeohashPresenceService.swift b/bitchat/Services/GeohashPresenceService.swift index 15e8ade2..5cb2b557 100644 --- a/bitchat/Services/GeohashPresenceService.swift +++ b/bitchat/Services/GeohashPresenceService.swift @@ -39,6 +39,9 @@ private final class GeohashPresenceTimerAdapter: GeohashPresenceTimerProtocol { /// - Broadcasts Kind 20001 events to low-precision geohash channels /// - Uses randomized timing (40-80s loop) and decorrelated bursts /// - Respects privacy by NOT broadcasting to Neighborhood/Block/Building levels +/// - Sends nothing while location access is not authorized, so revoking it +/// mid-session stops presence; the loop keeps running and resumes once +/// access returns @MainActor final class GeohashPresenceService: ObservableObject { static let shared = GeohashPresenceService() @@ -49,6 +52,7 @@ final class GeohashPresenceService: ObservableObject { private var heartbeatGeneration: UInt64 = 0 private var started = false private let availableChannelsProvider: () -> [GeohashChannel] + private let isLocationAuthorized: () -> Bool private let locationChanges: AnyPublisher<[GeohashChannel], Never> private let torReadyPublisher: AnyPublisher private let torIsReady: () -> Bool @@ -79,6 +83,7 @@ final class GeohashPresenceService: ObservableObject { private init() { let idBridge = NostrIdentityBridge() self.availableChannelsProvider = { LocationStateManager.shared.availableChannels } + self.isLocationAuthorized = { LocationStateManager.shared.permissionState == .authorized } self.locationChanges = LocationStateManager.shared.$availableChannels.eraseToAnyPublisher() self.torReadyPublisher = NotificationCenter.default.publisher(for: .TorDidBecomeReady) .map { _ in () } @@ -111,6 +116,7 @@ final class GeohashPresenceService: ObservableObject { internal init( availableChannelsProvider: @escaping () -> [GeohashChannel], + isLocationAuthorized: @escaping () -> Bool, locationChanges: AnyPublisher<[GeohashChannel], Never>, torReadyPublisher: AnyPublisher, torIsReady: @escaping () -> Bool, @@ -132,6 +138,7 @@ final class GeohashPresenceService: ObservableObject { burstMaxDelay: TimeInterval = 5.0 ) { self.availableChannelsProvider = availableChannelsProvider + self.isLocationAuthorized = isLocationAuthorized self.locationChanges = locationChanges self.torReadyPublisher = torReadyPublisher self.torIsReady = torIsReady @@ -250,7 +257,11 @@ final class GeohashPresenceService: ObservableObject { return } - // 2. Get channels + // 2. Get channels. They say where the device was at its last fix, + // so they are only announced while location is still authorized. + // Like geohash sampling, this checks the permission itself instead + // of trusting the channel list to have been cleared. + guard isLocationAuthorized() else { return } let channels = availableChannelsProvider() guard !channels.isEmpty else { return } @@ -274,9 +285,11 @@ final class GeohashPresenceService: ObservableObject { await sleeper(nanoseconds) guard let self else { return } + // Access can be revoked during the decorrelation delay. guard !Task.isCancelled, self.started, - self.heartbeatGeneration == generation else { + self.heartbeatGeneration == generation, + self.isLocationAuthorized() else { self.pendingBroadcastTasks.removeValue(forKey: taskID) return } diff --git a/bitchat/Services/LocationStateManager.swift b/bitchat/Services/LocationStateManager.swift index 209fab6c..9ac951b2 100644 --- a/bitchat/Services/LocationStateManager.swift +++ b/bitchat/Services/LocationStateManager.swift @@ -404,7 +404,10 @@ final class LocationStateManager: NSObject, CLLocationManagerDelegate, Observabl } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { - guard let loc = locations.last else { return } + // A fix CoreLocation queued before a revocation can still arrive + // after it. It must not refill the channels the revocation cleared, + // nor go out for geocoding. + guard isAuthorizedNow, let loc = locations.last else { return } computeChannels(from: loc.coordinate) reverseGeocodeLocation(loc) } @@ -415,6 +418,15 @@ final class LocationStateManager: NSObject, CLLocationManagerDelegate, Observabl // MARK: - Private Helpers (Permission) + /// CoreLocation's current answer. `permissionState` trails it by a + /// main-actor hop, so a callback that arrives in between checks this. + private var isAuthorizedNow: Bool { + switch cl.authorizationStatus { + case .authorizedAlways, .authorizedWhenInUse, .authorized: return true + default: return false + } + } + @discardableResult private func updatePermissionState(from status: CLAuthorizationStatus) -> PermissionState { let newState: PermissionState @@ -432,7 +444,19 @@ final class LocationStateManager: NSObject, CLLocationManagerDelegate, Observabl if newState != .authorized { endLiveRefresh() } - Task { @MainActor in self.permissionState = newState } + Task { @MainActor in + // Fail closed: the last fix says where this device was, and + // presence, the bridge and the channel list all read it. Forget + // it here rather than rely on every reader checking permission, + // and before the new state publishes so no observer sees the + // revocation beside stale cells. Bookmarks and teleports are + // explicit choices and stay. + if newState != .authorized { + if !self.availableChannels.isEmpty { self.availableChannels = [] } + if !self.locationNames.isEmpty { self.locationNames = [:] } + } + self.permissionState = newState + } return newState } @@ -473,7 +497,13 @@ final class LocationStateManager: NSObject, CLLocationManagerDelegate, Observabl guard let self = self else { return } if let pm = placemarks?.first { let names = self.locationNamesByLevel(from: pm) - Task { @MainActor in self.locationNames = names } + Task { @MainActor in + // The lookup can outlast a revocation that cleared the + // names. Main-actor tasks run in order, so this sees the + // published state of any revocation that came first. + guard self.permissionState == .authorized else { return } + self.locationNames = names + } } } } diff --git a/bitchat/ViewModels/ChatViewModelBootstrapper.swift b/bitchat/ViewModels/ChatViewModelBootstrapper.swift index 14de9c9b..deec95a7 100644 --- a/bitchat/ViewModels/ChatViewModelBootstrapper.swift +++ b/bitchat/ViewModels/ChatViewModelBootstrapper.swift @@ -451,9 +451,11 @@ private extension ChatViewModelBootstrapper { } bridge.relaysConnected = { NostrRelayManager.shared.isConnected } bridge.locationCell = { [weak viewModel] in - viewModel?.locationManager.availableChannels - .first { $0.level == .neighborhood }? - .geohash + guard let location = viewModel?.locationManager else { return nil } + return BridgeService.ownLocationCell( + from: location.availableChannels, + permission: location.permissionState + ) } bridge.requestLocationFix = { [weak viewModel] in viewModel?.locationManager.refreshChannels() diff --git a/bitchat/ViewModels/GeoChannelCoordinator.swift b/bitchat/ViewModels/GeoChannelCoordinator.swift index 64a8db5d..6785bc74 100644 --- a/bitchat/ViewModels/GeoChannelCoordinator.swift +++ b/bitchat/ViewModels/GeoChannelCoordinator.swift @@ -139,9 +139,9 @@ final class GeoChannelCoordinator { if state == .authorized { self.locationManager.refreshChannels() } - // Cached channels outlive authorization by design. Recompute - // regardless of direction so revocation tears down regional - // sampling instead of continuing from stale coordinates. + // Revocation also clears the cached channels, but recompute + // regardless of direction so tearing down regional sampling + // never depends on that list being current. self.updateSampling() } .store(in: &cancellables) diff --git a/bitchatTests/GeoChannelCoordinatorContextTests.swift b/bitchatTests/GeoChannelCoordinatorContextTests.swift index ac6b135f..8ea28702 100644 --- a/bitchatTests/GeoChannelCoordinatorContextTests.swift +++ b/bitchatTests/GeoChannelCoordinatorContextTests.swift @@ -259,7 +259,6 @@ struct GeoChannelCoordinatorContextTests { #expect(await waitUntil { context.beginSamplingCalls.last?.count == GeohashChannelLevel.allCases.count }) - let cachedChannels = locationManager.availableChannels let endCountBeforeRevocation = context.endSamplingCount locationManager.locationManager(CLLocationManager(), didChangeAuthorization: .denied) @@ -268,7 +267,9 @@ struct GeoChannelCoordinatorContextTests { locationManager.permissionState == .denied && context.endSamplingCount > endCountBeforeRevocation }) - #expect(locationManager.availableChannels == cachedChannels) + // Revocation also clears the cached channels; the coordinator's own + // permission check would end sampling either way. + #expect(locationManager.availableChannels.isEmpty) // A bookmark is an explicit remote scope and does not derive from // the now-revoked device location. diff --git a/bitchatTests/NearbyNotesCounterTests.swift b/bitchatTests/NearbyNotesCounterTests.swift index 5e328197..35c7dfb2 100644 --- a/bitchatTests/NearbyNotesCounterTests.swift +++ b/bitchatTests/NearbyNotesCounterTests.swift @@ -77,7 +77,7 @@ final class NearbyNotesCounterTests: XCTestCase { XCTAssertEqual(counter.noteCount, 0) } - func test_permissionRevocation_releasesBuildingSubscriptionDespiteCachedChannels() async throws { + func test_permissionRevocation_releasesBuildingSubscription() async throws { let relays = SubscriptionRecorder() let settings = LocationNotesSettingsStub() let locationManager = try await makeAuthorizedLocationManager() @@ -99,10 +99,9 @@ final class NearbyNotesCounterTests: XCTestCase { XCTAssertTrue(denied) let released = await waitUntil { relays.unsubscribeCount == 1 } XCTAssertTrue(released) - XCTAssertTrue( - locationManager.availableChannels.contains { $0.level == .building }, - "the privacy boundary must not depend on cached channels being cleared" - ) + // Revocation also clears the cached channels, so the counter's own + // permission check and the empty list both release the REQ. + XCTAssertTrue(locationManager.availableChannels.isEmpty) XCTAssertEqual(counter.noteCount, 0) counter.deactivate() diff --git a/bitchatTests/Services/BridgeServiceTests.swift b/bitchatTests/Services/BridgeServiceTests.swift index 24ffb54e..f585d1c7 100644 --- a/bitchatTests/Services/BridgeServiceTests.swift +++ b/bitchatTests/Services/BridgeServiceTests.swift @@ -214,6 +214,53 @@ struct BridgeServiceTests { #expect(fixture.service.activeCell == "u4prux") } + @Test func ownLocationCellNeedsLocationAccess() { + let channels = GeohashChannelLevel.allCases.map { + GeohashChannel(level: $0, geohash: String("u4pruydqqvj".prefix($0.precision))) + } + + #expect(BridgeService.ownLocationCell(from: channels, permission: .authorized) == Self.cell) + let withoutAccess: [LocationChannelManager.PermissionState] = [.notDetermined, .denied, .restricted] + for permission in withoutAccess { + #expect(BridgeService.ownLocationCell(from: channels, permission: permission) == nil) + } + } + + @Test func revokedLocationClosesTheRendezvousUntilAccessReturns() { + let fixture = Fixture(enabled: true) + var permission = LocationChannelManager.PermissionState.authorized + // The last fix stays in the list, so only the permission can close it. + let lastFix = [GeohashChannel(level: .neighborhood, geohash: Self.cell)] + fixture.service.locationCell = { + BridgeService.ownLocationCell(from: lastFix, permission: permission) + } + fixture.service.refreshRendezvous() + #expect(fixture.service.activeCell == Self.cell) + + permission = .denied + fixture.service.refreshRendezvous() + + #expect(fixture.service.activeCell == nil) + #expect(fixture.closedSubscriptions == 1) + // Past the presence throttle, so a live cell would publish again. + let publishedBeforeRevocation = fixture.published.count + fixture.advance(BridgeService.Limits.presenceIntervalSeconds) + fixture.fireScheduledTimers() + fixture.service.bridgeOutgoing( + content: "still here?", + senderPeerID: PeerID(str: "0011223344556677"), + timestamp: Date() + ) + #expect(fixture.published.count == publishedBeforeRevocation, "nothing goes to the old cell") + + permission = .authorized + fixture.service.refreshRendezvous() + + #expect(fixture.service.activeCell == Self.cell) + #expect(fixture.openedSubscriptions.count == 2) + #expect(fixture.published.last?.cell == Self.cell, "presence resumes") + } + @Test func disablingClosesSubscriptionAndClearsState() { let fixture = Fixture(enabled: true) fixture.service.refreshRendezvous() diff --git a/bitchatTests/Services/GeohashPresenceServiceTests.swift b/bitchatTests/Services/GeohashPresenceServiceTests.swift index 127c0052..14fe3eaa 100644 --- a/bitchatTests/Services/GeohashPresenceServiceTests.swift +++ b/bitchatTests/Services/GeohashPresenceServiceTests.swift @@ -125,6 +125,77 @@ final class GeohashPresenceServiceTests: XCTestCase { XCTAssertEqual(scheduler.intervals, [22, 22]) } + func test_performHeartbeat_sendsNothingWhileLocationIsRevokedAndResumesWhenRestored() async { + let scheduler = MockGeohashPresenceScheduler() + var authorized = true + var delaysStarted = 0 + var sentGeohashes: [String] = [] + let service = makeService( + scheduler: scheduler, + isLocationAuthorized: { authorized }, + relaySender: { event, _ in + if let geohash = event.tags.first(where: { $0.first == "g" })?[1] { + sentGeohashes.append(geohash) + } + }, + sleeper: { _ in delaysStarted += 1 } + ) + + service.start() + service.performHeartbeat() + let sentWhileAuthorized = await waitUntil { sentGeohashes == ["9q8yy"] } + XCTAssertTrue(sentWhileAuthorized) + + // Revoked mid-session. The provider still returns the last fix, so + // only the permission check can keep this heartbeat quiet, and it + // should not even schedule a send. + authorized = false + service.performHeartbeat() + let scheduledWhileRevoked = await waitUntil(timeout: TestConstants.negativeWaitWindow) { + delaysStarted > 1 || sentGeohashes.count > 1 + } + XCTAssertFalse(scheduledWhileRevoked) + + authorized = true + service.performHeartbeat() + let resumed = await waitUntil { sentGeohashes == ["9q8yy", "9q8yy"] } + XCTAssertTrue(resumed) + XCTAssertEqual(delaysStarted, 2) + // The loop kept rescheduling while revoked, so nothing has to restart it. + XCTAssertEqual(scheduler.intervals, [40, 40, 40, 40]) + } + + func test_revocationDuringDecorrelationDelay_dropsThePendingBroadcast() async throws { + let identity = try NostrIdentity.generate() + var authorized = true + var sleeperContinuation: CheckedContinuation? + var sendCount = 0 + let service = makeService( + scheduler: MockGeohashPresenceScheduler(), + isLocationAuthorized: { authorized }, + deriveIdentity: { _ in identity }, + relaySender: { _, _ in sendCount += 1 }, + sleeper: { _ in + await withCheckedContinuation { continuation in + sleeperContinuation = continuation + } + }, + burstMinDelay: 1, + burstMaxDelay: 1 + ) + + service.start() + service.performHeartbeat() + let delayStarted = await waitUntil { sleeperContinuation != nil } + XCTAssertTrue(delayStarted) + + authorized = false + sleeperContinuation?.resume() + let sent = await waitUntil(timeout: TestConstants.negativeWaitWindow) { sendCount > 0 } + + XCTAssertFalse(sent) + } + func test_stopForPanic_cancelsTimerAndSuppressesDelayedBroadcast() async throws { let identity = try NostrIdentity.generate() let scheduler = MockGeohashPresenceScheduler() @@ -195,6 +266,7 @@ final class GeohashPresenceServiceTests: XCTestCase { availableChannels: [GeohashChannel] = [ GeohashChannel(level: .city, geohash: "9q8yy") ], + isLocationAuthorized: @escaping () -> Bool = { true }, torIsReady: @escaping () -> Bool = { true }, torIsForeground: @escaping () -> Bool = { true }, deriveIdentity: @escaping (String) throws -> NostrIdentity = { _ in try NostrIdentity.generate() }, @@ -210,6 +282,7 @@ final class GeohashPresenceServiceTests: XCTestCase { let torReadySubject = PassthroughSubject() return GeohashPresenceService( availableChannelsProvider: { availableChannels }, + isLocationAuthorized: isLocationAuthorized, locationChanges: locationSubject.eraseToAnyPublisher(), torReadyPublisher: torReadySubject.eraseToAnyPublisher(), torIsReady: torIsReady, diff --git a/bitchatTests/Services/LocationStateManagerTests.swift b/bitchatTests/Services/LocationStateManagerTests.swift index 46114d26..eb7036e4 100644 --- a/bitchatTests/Services/LocationStateManagerTests.swift +++ b/bitchatTests/Services/LocationStateManagerTests.swift @@ -104,7 +104,6 @@ final class LocationStateManagerTests: XCTestCase { ) let channelsLoaded = await waitUntil { !manager.availableChannels.isEmpty } XCTAssertTrue(channelsLoaded) - let cachedChannels = manager.availableChannels manager.addBookmark("u4pru") manager.markTeleported(for: "9q8yy", true) manager.select(.location(GeohashChannel(level: .city, geohash: "9q8yy"))) @@ -121,11 +120,70 @@ final class LocationStateManagerTests: XCTestCase { XCTAssertEqual(locationManager.stopUpdatingLocationCallCount, 1) XCTAssertEqual(locationManager.desiredAccuracy, kCLLocationAccuracyHundredMeters) XCTAssertEqual(locationManager.distanceFilter, TransportConfig.locationDistanceFilterMeters) - XCTAssertEqual(manager.availableChannels, cachedChannels, "cached display state can remain") + XCTAssertEqual(manager.availableChannels, [], "channels from the last fix go with the permission") XCTAssertEqual(manager.bookmarks, ["u4pru"]) XCTAssertTrue(manager.teleported, "an explicit remote selection survives device revocation") } + func test_permissionRevocation_forgetsTheLastFixUntilReauthorized() async { + let locationManager = MockLocationManager(authorizationStatus: .authorizedAlways) + let geocoder = MockLocationGeocoder() + geocoder.enqueue(placemarks: [makePlacemark(country: "United States", locality: "Honolulu")]) + let manager = LocationStateManager( + storage: makeStorage(), + locationManager: locationManager, + geocoder: geocoder, + shouldInitializeCoreLocation: true + ) + let authorized = await waitUntil { manager.permissionState == .authorized } + XCTAssertTrue(authorized) + let honolulu = CLLocation(latitude: 21.2850, longitude: -157.8357) + + manager.locationManager(CLLocationManager(), didUpdateLocations: [honolulu]) + let fixLoaded = await waitUntil { + !manager.availableChannels.isEmpty && manager.locationNames[.city] == "Honolulu" + } + XCTAssertTrue(fixLoaded) + + // Another fix whose place-name lookup is still out when access goes. + geocoder.holdsCompletions = true + geocoder.enqueue(placemarks: [makePlacemark(country: "United States", locality: "Honolulu")]) + manager.locationManager(CLLocationManager(), didUpdateLocations: [honolulu]) + + // CoreLocation updates its status before it tells the delegate. + locationManager.authorizationStatus = .denied + manager.locationManager(CLLocationManager(), didChangeAuthorization: .denied) + + let denied = await waitUntil { manager.permissionState == .denied } + XCTAssertTrue(denied) + XCTAssertEqual(manager.availableChannels, []) + XCTAssertEqual(manager.locationNames, [:]) + + // The lookup that outlasted the revocation lands, and a fix + // CoreLocation had already queued arrives. That fix is not even + // sent for geocoding. + geocoder.completePending() + manager.locationManager(CLLocationManager(), didUpdateLocations: [honolulu]) + XCTAssertEqual(geocoder.reverseRequests.count, 2) + + locationManager.authorizationStatus = .authorizedAlways + manager.locationManager(CLLocationManager(), didChangeAuthorization: .authorizedAlways) + + let reauthorized = await waitUntil { manager.permissionState == .authorized } + XCTAssertTrue(reauthorized) + // Main-actor tasks run in order, so anything the late arrivals + // queued has run by now: neither brought the last fix back. + XCTAssertEqual(manager.availableChannels, []) + XCTAssertEqual(manager.locationNames, [:]) + XCTAssertEqual(locationManager.requestLocationCallCount, 1, "access returning asks for a fresh fix") + + manager.locationManager(CLLocationManager(), didUpdateLocations: [honolulu]) + let channelsBack = await waitUntil { + manager.availableChannels.count == GeohashChannelLevel.allCases.count + } + XCTAssertTrue(channelsBack) + } + func test_didUpdateLocations_computesChannelsAndReverseGeocodesFriendlyNames() async { let geocoder = MockLocationGeocoder() geocoder.enqueue( @@ -408,12 +466,22 @@ private final class MockLocationGeocoder: LocationStateGeocoding { private(set) var cancelCallCount = 0 private(set) var reverseRequests: [CLLocation] = [] + /// When set, lookups wait for `completePending()`, as if still out on + /// the network. + var holdsCompletions = false private var responses: [Response] = [] + private var pendingCompletions: [() -> Void] = [] func enqueue(placemarks: [CLPlacemark]?, error: Error? = nil) { responses.append(Response(placemarks: placemarks, error: error)) } + func completePending() { + let completions = pendingCompletions + pendingCompletions.removeAll() + completions.forEach { $0() } + } + func cancelGeocode() { cancelCallCount += 1 } @@ -424,6 +492,11 @@ private final class MockLocationGeocoder: LocationStateGeocoding { ) { reverseRequests.append(location) let response = responses.isEmpty ? Response(placemarks: nil, error: nil) : responses.removeFirst() - completionHandler(response.placemarks, response.error) + let complete = { completionHandler(response.placemarks, response.error) } + if holdsCompletions { + pendingCompletions.append(complete) + } else { + complete() + } } }