From 5c53d4a4667ea3696271f8ff7929b0161e91770c Mon Sep 17 00:00:00 2001 From: ykisana Date: Thu, 12 Nov 2026 15:15:55 -0600 Subject: [PATCH] fix: only trust location fixes Normal just received A location key could pass on an old fix: the unlock sheet trusted the system's last-known location by its wall-clock timestamp, so setting the device clock back made an hours-old fix look fresh. Simulated locations also passed. The unlock check now only reuses a fix Normal received in the last 30 seconds (measured on a monotonic clock), and rejects fixes that are stale, dated in the future, invalid or simulated. The map's grey dot still uses the last-known location. --- Normal/Services/Keys/LocationFixPolicy.swift | 22 +++++++ .../Services/Keys/LocationUnlockModel.swift | 10 +-- Normal/Services/LocationService.swift | 15 +++++ .../Services/LocationFixPolicyTests.swift | 57 ++++++++++++++++ .../Services/LocationUnlockModelTests.swift | 66 ++++++++++++++++--- .../TestSupport/FakeLocationProvider.swift | 5 +- 6 files changed, 159 insertions(+), 16 deletions(-) create mode 100644 Normal/Services/Keys/LocationFixPolicy.swift create mode 100644 NormalTests/Services/LocationFixPolicyTests.swift diff --git a/Normal/Services/Keys/LocationFixPolicy.swift b/Normal/Services/Keys/LocationFixPolicy.swift new file mode 100644 index 0000000..35c2f3d --- /dev/null +++ b/Normal/Services/Keys/LocationFixPolicy.swift @@ -0,0 +1,22 @@ +import CoreLocation +import Foundation + +struct LocationFixPolicy { + static let maxAge: TimeInterval = 30 + static let clockTolerance: TimeInterval = 5 + + var maxAccuracy: CLLocationAccuracy? + + static let inApp = LocationFixPolicy() + + func accepts(_ fix: CLLocation, now: Date = .now) -> Bool { + let age = now.timeIntervalSince(fix.timestamp) + guard age >= -Self.clockTolerance, + age <= Self.maxAge, + fix.horizontalAccuracy >= 0, + fix.sourceInformation?.isSimulatedBySoftware != true + else { return false } + guard let maxAccuracy else { return true } + return fix.horizontalAccuracy <= maxAccuracy + } +} diff --git a/Normal/Services/Keys/LocationUnlockModel.swift b/Normal/Services/Keys/LocationUnlockModel.swift index 08d5f15..558f1d3 100644 --- a/Normal/Services/Keys/LocationUnlockModel.swift +++ b/Normal/Services/Keys/LocationUnlockModel.swift @@ -23,8 +23,6 @@ final class LocationUnlockModel { private let provider: any LocationProviding private let pollInterval: Duration - private static let maxCacheAge: TimeInterval = 30 - init(keys: [Key], provider: any LocationProviding, pollInterval: Duration = .seconds(2)) { let locationKeys = Key.locationKeys(in: keys) self.locationKeys = locationKeys @@ -51,9 +49,7 @@ final class LocationUnlockModel { } func verifyFromCache() -> Bool { - guard let cached = provider.cachedLocation, - cached.timestamp.timeIntervalSinceNow > -Self.maxCacheAge - else { return false } + guard let cached = provider.recentLocation, LocationFixPolicy.inApp.accepts(cached) else { return false } location = cached hasValidLocation = true guard Key.locationKeyVerifies(keys: locationKeys, location: cached) else { return false } @@ -64,6 +60,10 @@ final class LocationUnlockModel { func checkOnce() async { do { let fix = try await provider.currentLocation() + guard LocationFixPolicy.inApp.accepts(fix) else { + phase = .unavailable + return + } location = fix hasValidLocation = true phase = Key.locationKeyVerifies(keys: locationKeys, location: fix) ? .verified : .outOfRange diff --git a/Normal/Services/LocationService.swift b/Normal/Services/LocationService.swift index 4f4cb68..2675671 100644 --- a/Normal/Services/LocationService.swift +++ b/Normal/Services/LocationService.swift @@ -30,6 +30,7 @@ enum LocationKeyError: Error, Equatable { protocol LocationProviding: AnyObject { var authorizationStatus: CLAuthorizationStatus { get } var cachedLocation: CLLocation? { get } + var recentLocation: CLLocation? { get } func currentLocation() async throws -> CLLocation } @@ -52,7 +53,18 @@ final class LocationService: NSObject, LocationProviding { return manager.location } + var recentLocation: CLLocation? { + if UITestSupport.isActive { + return CLLocation(latitude: 37.33182, longitude: -122.03118) + } + guard let lastFix, lastFix.receivedAt.duration(to: .now) <= .seconds(LocationFixPolicy.maxAge) else { + return nil + } + return lastFix.location + } + private let manager = CLLocationManager() + private var lastFix: (location: CLLocation, receivedAt: ContinuousClock.Instant)? private var locationContinuations: [CheckedContinuation] = [] private var authContinuations: [CheckedContinuation] = [] @@ -91,6 +103,9 @@ final class LocationService: NSObject, LocationProviding { } private func flushLocation(_ result: Result) { + if case let .success(location) = result { + lastFix = (location, .now) + } let pending = locationContinuations locationContinuations.removeAll() for c in pending { diff --git a/NormalTests/Services/LocationFixPolicyTests.swift b/NormalTests/Services/LocationFixPolicyTests.swift new file mode 100644 index 0000000..16b2615 --- /dev/null +++ b/NormalTests/Services/LocationFixPolicyTests.swift @@ -0,0 +1,57 @@ +import CoreLocation +import Foundation +@testable import Normal +import Testing + +struct LocationFixPolicyTests { + private let now = Date() + + private func fix(accuracy: CLLocationAccuracy = 10, age: TimeInterval = 0, simulated: Bool = false) -> CLLocation { + CLLocation( + coordinate: CLLocationCoordinate2D(latitude: 37.3349, longitude: -122.0090), + altitude: 0, + horizontalAccuracy: accuracy, + verticalAccuracy: 10, + course: 0, + courseAccuracy: 0, + speed: 0, + speedAccuracy: 0, + timestamp: now.addingTimeInterval(-age), + sourceInfo: CLLocationSourceInformation( + softwareSimulationState: simulated, + andExternalAccessoryState: false + ) + ) + } + + @Test func acceptsAFreshFix() { + #expect(LocationFixPolicy.inApp.accepts(fix(), now: now)) + } + + @Test func rejectsAnOldFix() { + #expect(!LocationFixPolicy.inApp.accepts(fix(age: 31), now: now)) + } + + @Test func rejectsAFixFromTheFuture() { + #expect(!LocationFixPolicy.inApp.accepts(fix(age: -60), now: now)) + } + + @Test func toleratesSmallClockDrift() { + #expect(LocationFixPolicy.inApp.accepts(fix(age: -2), now: now)) + } + + @Test func rejectsASimulatedFix() { + #expect(!LocationFixPolicy.inApp.accepts(fix(simulated: true), now: now)) + } + + @Test func rejectsAnInvalidFix() { + #expect(!LocationFixPolicy.inApp.accepts(fix(accuracy: -1), now: now)) + } + + @Test func appliesAnAccuracyLimit() { + let policy = LocationFixPolicy(maxAccuracy: 100) + #expect(policy.accepts(fix(accuracy: 100), now: now)) + #expect(!policy.accepts(fix(accuracy: 150), now: now)) + #expect(LocationFixPolicy.inApp.accepts(fix(accuracy: 1500), now: now)) + } +} diff --git a/NormalTests/Services/LocationUnlockModelTests.swift b/NormalTests/Services/LocationUnlockModelTests.swift index fac9e95..8dce14c 100644 --- a/NormalTests/Services/LocationUnlockModelTests.swift +++ b/NormalTests/Services/LocationUnlockModelTests.swift @@ -84,18 +84,30 @@ struct LocationUnlockModelTests { #expect(model.phase == .permissionDenied) } - private func cachedLocation(at coordinate: CLLocationCoordinate2D, secondsAgo: TimeInterval = 0) -> CLLocation { + private func fix( + at coordinate: CLLocationCoordinate2D, + secondsAgo: TimeInterval = 0, + simulated: Bool = false + ) -> CLLocation { CLLocation( coordinate: coordinate, altitude: 0, horizontalAccuracy: 10, verticalAccuracy: 10, - timestamp: Date(timeIntervalSinceNow: -secondsAgo) + course: 0, + courseAccuracy: 0, + speed: 0, + speedAccuracy: 0, + timestamp: Date(timeIntervalSinceNow: -secondsAgo), + sourceInfo: CLLocationSourceInformation( + softwareSimulationState: simulated, + andExternalAccessoryState: false + ) ) } @Test func verifiesInstantlyFromFreshInZoneCache() { - let provider = FakeLocationProvider(outcome: .throwGeneric, cachedLocation: cachedLocation(at: Self.cupertino)) + let provider = FakeLocationProvider(outcome: .throwGeneric, recentLocation: fix(at: Self.cupertino)) let model = LocationUnlockModel(keys: [locationKey(kind: .unblock)], provider: provider) #expect(model.verifyFromCache()) #expect(model.phase == .verified) @@ -104,7 +116,7 @@ struct LocationUnlockModelTests { @Test func ignoresStaleCache() { let provider = FakeLocationProvider( outcome: .throwGeneric, - cachedLocation: cachedLocation(at: Self.cupertino, secondsAgo: 120) + recentLocation: fix(at: Self.cupertino, secondsAgo: 120) ) let model = LocationUnlockModel(keys: [locationKey(kind: .unblock)], provider: provider) #expect(!model.verifyFromCache()) @@ -112,19 +124,19 @@ struct LocationUnlockModelTests { } @Test func ignoresCacheOutOfZone() { - let provider = FakeLocationProvider(outcome: .throwGeneric, cachedLocation: cachedLocation(at: Self.london)) + let provider = FakeLocationProvider(outcome: .throwGeneric, recentLocation: fix(at: Self.london)) let model = LocationUnlockModel(keys: [locationKey(kind: .unblock)], provider: provider) #expect(!model.verifyFromCache()) } @Test func ignoresMissingCache() { - let provider = FakeLocationProvider(outcome: .throwGeneric, cachedLocation: nil) + let provider = FakeLocationProvider(outcome: .throwGeneric) let model = LocationUnlockModel(keys: [locationKey(kind: .unblock)], provider: provider) #expect(!model.verifyFromCache()) } @Test func runVerifiesFromFreshCacheWithoutGPSWait() async { - let provider = FakeLocationProvider(outcome: .throwGeneric, cachedLocation: cachedLocation(at: Self.cupertino)) + let provider = FakeLocationProvider(outcome: .throwGeneric, recentLocation: fix(at: Self.cupertino)) let model = LocationUnlockModel(keys: [locationKey(kind: .unblock)], provider: provider) await model.run() #expect(model.phase == .verified) @@ -136,7 +148,7 @@ struct LocationUnlockModelTests { } @Test func freshCacheMarksLocationValidEvenWhenOutOfZone() { - let provider = FakeLocationProvider(outcome: .throwGeneric, cachedLocation: cachedLocation(at: Self.london)) + let provider = FakeLocationProvider(outcome: .throwGeneric, recentLocation: fix(at: Self.london)) let model = LocationUnlockModel(keys: [locationKey(kind: .unblock)], provider: provider) #expect(!model.verifyFromCache()) #expect(model.hasValidLocation) @@ -145,7 +157,7 @@ struct LocationUnlockModelTests { @Test func staleCacheDoesNotMarkLocationValid() { let provider = FakeLocationProvider( outcome: .throwGeneric, - cachedLocation: cachedLocation(at: Self.cupertino, secondsAgo: 120) + recentLocation: fix(at: Self.cupertino, secondsAgo: 120) ) let model = LocationUnlockModel(keys: [locationKey()], provider: provider) _ = model.verifyFromCache() @@ -174,11 +186,45 @@ struct LocationUnlockModelTests { @Test func runSeedsStaleCacheAsGreyDotLocation() async { let provider = FakeLocationProvider( outcome: .throwKeyError(.denied), - cachedLocation: cachedLocation(at: Self.cupertino, secondsAgo: 600) + cachedLocation: fix(at: Self.cupertino, secondsAgo: 600) ) let model = LocationUnlockModel(keys: [locationKey()], provider: provider) await model.run() #expect(model.location?.coordinate.latitude == Self.cupertino.latitude) #expect(!model.hasValidLocation) } + + @Test func ignoresFutureDatedRecentFix() { + let provider = FakeLocationProvider( + outcome: .throwGeneric, + recentLocation: fix(at: Self.cupertino, secondsAgo: -120) + ) + let model = LocationUnlockModel(keys: [locationKey(kind: .unblock)], provider: provider) + #expect(!model.verifyFromCache()) + #expect(!model.hasValidLocation) + } + + @Test func ignoresSimulatedRecentFix() { + let provider = FakeLocationProvider( + outcome: .throwGeneric, + recentLocation: fix(at: Self.cupertino, simulated: true) + ) + let model = LocationUnlockModel(keys: [locationKey(kind: .unblock)], provider: provider) + #expect(!model.verifyFromCache()) + } + + @Test func rejectsSimulatedFix() async { + let provider = FakeLocationProvider(outcome: .location(fix(at: Self.cupertino, simulated: true))) + let model = LocationUnlockModel(keys: [locationKey(kind: .unblock)], provider: provider) + await model.checkOnce() + #expect(model.phase == .unavailable) + #expect(!model.hasValidLocation) + } + + @Test func rejectsStaleFix() async { + let provider = FakeLocationProvider(outcome: .location(fix(at: Self.cupertino, secondsAgo: 120))) + let model = LocationUnlockModel(keys: [locationKey(kind: .unblock)], provider: provider) + await model.checkOnce() + #expect(model.phase == .unavailable) + } } diff --git a/NormalTests/TestSupport/FakeLocationProvider.swift b/NormalTests/TestSupport/FakeLocationProvider.swift index cf2d62e..4a544df 100644 --- a/NormalTests/TestSupport/FakeLocationProvider.swift +++ b/NormalTests/TestSupport/FakeLocationProvider.swift @@ -13,15 +13,18 @@ final class FakeLocationProvider: LocationProviding { var outcome: Outcome var authorizationStatus: CLAuthorizationStatus var cachedLocation: CLLocation? + var recentLocation: CLLocation? init( outcome: Outcome, authorizationStatus: CLAuthorizationStatus = .authorizedWhenInUse, - cachedLocation: CLLocation? = nil + cachedLocation: CLLocation? = nil, + recentLocation: CLLocation? = nil ) { self.outcome = outcome self.authorizationStatus = authorizationStatus self.cachedLocation = cachedLocation + self.recentLocation = recentLocation } convenience init(at coordinate: CLLocationCoordinate2D) {