Colota - Android GPS Location tracker
fix(service): stop lighting the location indicator while paused (#638)
Max Dietrich947a05a009a6
diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.mdindex 232a3438..7a07a781 100644--- a/apps/docs/docs/development/architecture.md+++ b/apps/docs/docs/development/architecture.md@@ -209,7 +209,7 @@ Orchestrates batch location uploads with:### NetworkManager-HTTP client. Injects auth headers, caches connectivity checks, and detects unmetered connections, specific SSIDs and VPN status for sync condition filtering. Endpoint policy (HTTPS-for-public, private host detection) is delegated to `UrlSafety`.+HTTP client. Injects auth headers, caches connectivity checks, and detects unmetered connections and VPN status for sync condition filtering. SSID detection needs a location-flagged network callback, which is attributed as location access, so it is registered only while the `wifi_ssid` condition is active or the SSID picker asks. Endpoint policy (HTTPS-for-public, private host detection) is delegated to `UrlSafety`.For mTLS-protected endpoints, builds the `HttpsURLConnection` with a custom `SSLSocketFactory` supplied by `ClientCertSslContextProvider` (per-instance, never `setDefaultSSLSocketFactory()` - the override is scoped to outbound location sync, not the whole process).diff --git a/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt b/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.ktindex 223ed96c..739324fb 100644--- a/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt@@ -765,7 +765,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :@ReactMethodfun getCurrentSsid(promise: Promise) {- promise.resolve(networkManager.getCurrentSsid())+ networkManager.readSsidOnce { promise.resolve(it) }}@ReactMethoddiff --git a/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.kt b/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.ktindex 2a08de9d..2a13bd0d 100644--- a/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.kt@@ -768,6 +768,18 @@ class LocationForegroundService : Service() {private fun handleZoneRecheckAction() {// A cached fix while paused is usually the stale home fix - force a fresh one so a departure exits.if (insidePauseZone) {+ // Holds own their resume: re-evaluate on the last fix so a zone edit applies, without probing.+ if (isWifiPaused || isMotionlessPaused) {+ val cached = lastKnownLocation+ if (cached != null) {+ recheckZoneWithLocation(cached)+ } else {+ // A restart under a hold never gets a fix, so settle the edit from the zone row.+ val zone = currentZoneName?.let { geofenceHelper.getGeofenceByName(it) }+ if (zone == null) exitPauseZone() else applyZoneSettingsIfChanged(zone)+ }+ return+ }requestFreshOrLastLocation { location, probed ->if (location != null) {lastKnownLocation = location@@ -1631,6 +1643,9 @@ class LocationForegroundService : Service() {}private fun pushConfigToSyncManager() {+ // Only wifi_ssid reads the SSID, and reading it is attributed as location access.+ networkManager.setSsidTracking(config.syncCondition == "wifi_ssid")+// Instant mode bypasses the queue and posts one flat payload, which 4xxs// forever against /api/v1/overland/batches. Defensive net under the UI guard.val effectiveFormat = if (config.syncIntervalSeconds == 0 && config.apiFormat == ApiFormat.OVERLAND_BATCH) {diff --git a/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.kt b/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.ktindex b31634f4..6aff5a2f 100644--- a/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.kt@@ -8,6 +8,8 @@ import com.Colota.util.AppLoggerimport com.Colota.sync.tls.ClientCertSslContextProviderimport com.Colota.util.TimedCacheimport android.os.Build+import android.os.Handler+import android.os.Looperimport android.net.ConnectivityManagerimport android.net.Networkimport android.net.NetworkCapabilities@@ -19,6 +21,7 @@ import java.net.URLimport java.net.URLEncoderimport java.nio.charset.StandardCharsetsimport java.security.UnrecoverableKeyException+import java.util.concurrent.atomic.AtomicBooleanimport java.time.Instantimport java.time.ZoneIdimport java.time.format.DateTimeFormatter@@ -35,6 +38,7 @@ class NetworkManager(private val context: Context) {private const val CONNECTION_TIMEOUT = 10000private const val READ_TIMEOUT = 10000private const val NETWORK_CHECK_CACHE_MS = 5000L+ private const val SSID_PROBE_TIMEOUT_MS = 3000Lprivate const val ERROR_BODY_MAX_CHARS = 200private val WHITESPACE = Regex("\\s+")}@@ -43,6 +47,7 @@ class NetworkManager(private val context: Context) {@Volatile private var currentSsid: String = ""@Volatile private var isVpn: Boolean = false+ @Volatile private var ssidTracking: Boolean = falseprivate val wifiManager = context.getSystemService(Context.WIFI_SERVICE) as? WifiManager// Lazy so existing unit tests that mock Context don't trigger EncryptedSharedPreferences init.@@ -55,11 +60,77 @@ class NetworkManager(private val context: Context) {clientCertProvider.invalidate()}- private val networkCallback = createNetworkCallback()+ private var networkCallback = createNetworkCallback(withSsid = false)- private fun createNetworkCallback(): ConnectivityManager.NetworkCallback {+ /**+ * The location-flagged callback notes FINE_LOCATION on every delivery, which lights the privacy+ * indicator with GPS stopped. Register it only while the SSID is needed; VPN state needs no flag.+ */+ @Synchronized+ fun setSsidTracking(enabled: Boolean) {+ if (enabled == ssidTracking) return+ try {+ connectivityManager.unregisterNetworkCallback(networkCallback)+ } catch (e: Exception) {+ AppLogger.e(TAG, "Failed to unregister network callback", e)+ }+ networkCallback = createNetworkCallback(withSsid = enabled)+ try {+ connectivityManager.registerDefaultNetworkCallback(networkCallback)+ // Committed only once a callback is live, so a failed swap can be retried.+ ssidTracking = enabled+ if (!enabled) currentSsid = ""+ } catch (e: Exception) {+ AppLogger.e(TAG, "Failed to register network callback", e)+ }+ }++ /** One-shot SSID read for the picker: the flagged callback is registered for this call only. */+ fun readSsidOnce(onResult: (String) -> Unit) {+ if (ssidTracking) {+ onResult(currentSsid)+ return+ }++ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {+ // Below S the SSID comes from WifiManager, not the callback, so waiting on one would+ // only stall and would return "" whenever there is no default network.+ onResult(readSsid(null))+ return+ }++ val done = AtomicBoolean(false)+ var probe: ConnectivityManager.NetworkCallback? = null+ fun finish(ssid: String) {+ if (!done.compareAndSet(false, true)) return+ probe?.let {+ try {+ connectivityManager.unregisterNetworkCallback(it)+ } catch (e: Exception) {+ AppLogger.e(TAG, "Failed to unregister SSID probe", e)+ }+ }+ onResult(ssid)+ }++ probe = object : ConnectivityManager.NetworkCallback(FLAG_INCLUDE_LOCATION_INFO) {+ override fun onCapabilitiesChanged(network: Network, caps: NetworkCapabilities) = finish(readSsid(caps))+ }++ try {+ connectivityManager.registerDefaultNetworkCallback(probe)+ } catch (e: Exception) {+ AppLogger.e(TAG, "Failed to register SSID probe", e)+ probe = null+ finish("")+ return+ }+ Handler(Looper.getMainLooper()).postDelayed({ finish("") }, SSID_PROBE_TIMEOUT_MS)+ }++ private fun createNetworkCallback(withSsid: Boolean): ConnectivityManager.NetworkCallback {fun update(caps: NetworkCapabilities) {- currentSsid = readSsid(caps)+ if (withSsid) currentSsid = readSsid(caps)isVpn = caps.hasTransport(NetworkCapabilities.TRANSPORT_VPN)}fun clear() {@@ -67,7 +138,7 @@ class NetworkManager(private val context: Context) {isVpn = false}- return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {+ return if (withSsid && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {object : ConnectivityManager.NetworkCallback(FLAG_INCLUDE_LOCATION_INFO) {override fun onCapabilitiesChanged(network: Network, caps: NetworkCapabilities) = update(caps)override fun onLost(network: Network) = clear()@@ -80,9 +151,9 @@ class NetworkManager(private val context: Context) {}}- private fun readSsid(caps: NetworkCapabilities): String {+ private fun readSsid(caps: NetworkCapabilities?): String {return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {- (caps.transportInfo as? WifiInfo)?.ssid?.removeSurrounding("\"") ?: ""+ (caps?.transportInfo as? WifiInfo)?.ssid?.removeSurrounding("\"") ?: ""} else {@Suppress("DEPRECATION")wifiManager?.connectionInfo?.ssid?.removeSurrounding("\"") ?: ""@@ -447,7 +518,7 @@ class NetworkManager(private val context: Context) {/*** Returns true when connected to a WiFi network matching the given SSID.- * SSID is updated via NetworkCallback with FLAG_INCLUDE_LOCATION_INFO.+ * Only meaningful while setSsidTracking(true) holds the location-flagged callback.*/fun isConnectedToSsid(ssid: String): Boolean {if (ssid.isBlank()) return false@@ -460,8 +531,6 @@ class NetworkManager(private val context: Context) {*/fun isVpnConnected(): Boolean = isVpn- fun getCurrentSsid(): String = currentSsid-fun destroy() {try {connectivityManager.unregisterNetworkCallback(networkCallback)diff --git a/apps/mobile/android/app/src/test/java/com/Colota/service/LocationForegroundServiceTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/service/LocationForegroundServiceTest.ktindex decb207e..8bd8a7d8 100644--- a/apps/mobile/android/app/src/test/java/com/Colota/service/LocationForegroundServiceTest.kt+++ b/apps/mobile/android/app/src/test/java/com/Colota/service/LocationForegroundServiceTest.kt@@ -795,6 +795,68 @@ class LocationForegroundServiceTest {assertEquals(freshLocation, getField<Location?>("lastKnownLocation"))}+ @Test+ fun `only the wifi_ssid condition turns SSID tracking on`() {+ // Reading the SSID is attributed as location access, so it must follow the condition needing it.+ setField("config", ServiceConfig(endpoint = "https://example.com", syncCondition = "wifi_ssid"))+ invokePushConfigToSyncManager()+ verify { networkManager.setSsidTracking(true) }++ setField("config", ServiceConfig(endpoint = "https://example.com", syncCondition = "any"))+ invokePushConfigToSyncManager()+ verify { networkManager.setSsidTracking(false) }+ }++ @Test+ fun `ACTION_RECHECK_ZONE during a hold with no cached fix still applies a zone edit`() {+ setField("lastKnownLocation", null)+ setField("insidePauseZone", true)+ setField("currentZoneName", "Home")+ setField("currentZoneGeofence", homeGeofence)+ setField("isWifiPaused", true)+ every { geofenceHelper.getGeofenceByName("Home") } returns null++ invokeHandleZoneRecheckAction()++ verify(exactly = 0) { locationProvider.getCurrentLocation(any(), any()) }+ assertFalse(getField("insidePauseZone"))+ }++ @Test+ fun `ACTION_RECHECK_ZONE during a hold still applies a zone edit`() {+ // A zone edit must take effect during a hold, or GPS stays dead until the user leaves the wifi.+ val cached = mockLocation(lat = 48.0, lon = 11.0)+ setField("lastKnownLocation", cached)+ setField("insidePauseZone", true)+ setField("currentZoneName", "Home")+ setField("currentZoneGeofence", homeGeofence)+ setField("isWifiPaused", true)+ every { geofenceHelper.getPauseZone(cached) } returns null++ invokeHandleZoneRecheckAction()++ verify(exactly = 0) { locationProvider.getCurrentLocation(any(), any()) }+ assertFalse(getField("insidePauseZone"))+ }++ @Test+ fun `ACTION_RECHECK_ZONE during a motionless hold requests no fresh fix`() {+ setField("lastKnownLocation", null)+ setField("insidePauseZone", true)+ setField("currentZoneName", "Home")+ setField("currentZoneGeofence", homeGeofence)+ setField("isMotionlessPaused", true)+ val pausing = geofence("Home", pauseOnMotionless = true)+ setField("currentZoneGeofence", pausing)+ every { geofenceHelper.getGeofenceByName("Home") } returns pausing++ invokeHandleZoneRecheckAction()++ verify(exactly = 0) { locationProvider.getCurrentLocation(any(), any()) }+ verify(exactly = 0) { locationProvider.getLastLocation(any(), any()) }+ assertTrue(getField("insidePauseZone"))+ }+// =========================================================================// #444 - restored / paused zone recheck against a fresh fix// =========================================================================@@ -2652,6 +2714,12 @@ class LocationForegroundServiceTest {method.invoke(service)}+ private fun invokePushConfigToSyncManager() {+ val method = LocationForegroundService::class.java.getDeclaredMethod("pushConfigToSyncManager")+ method.isAccessible = true+ method.invoke(service)+ }+private fun invokeRecheckZoneWithLocation(location: Location) {val method = LocationForegroundService::class.java.getDeclaredMethod("recheckZoneWithLocation", Location::class.javadiff --git a/apps/mobile/android/app/src/test/java/com/Colota/sync/NetworkManagerTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/sync/NetworkManagerTest.ktindex ac189c7e..d6e06883 100644--- a/apps/mobile/android/app/src/test/java/com/Colota/sync/NetworkManagerTest.kt+++ b/apps/mobile/android/app/src/test/java/com/Colota/sync/NetworkManagerTest.kt@@ -1,5 +1,10 @@package com.Colota.sync+import android.content.Context+import android.net.ConnectivityManager+import android.net.NetworkCapabilities+import android.net.wifi.WifiInfo+import android.net.wifi.WifiManagerimport org.json.JSONObjectimport org.junit.Assert.*import org.junit.Test@@ -9,8 +14,8 @@ import org.junit.Afterimport org.junit.Before/**- * Tests for NetworkManager's pure-logic methods.- * Network I/O and Android ConnectivityManager are not tested here (require instrumented tests).+ * Tests for NetworkManager's pure-logic methods, plus callback registration against a mocked+ * ConnectivityManager. Network I/O still needs instrumented tests.*/class NetworkManagerTest {@@ -28,6 +33,82 @@ class NetworkManagerTest {unmockkObject(AppLogger)}+ // --- network callback registration ---++ private fun newManagerWith(cm: ConnectivityManager): NetworkManager {+ val ctx = mockk<Context>(relaxed = true)+ every { ctx.getSystemService(Context.CONNECTIVITY_SERVICE) } returns cm+ every { ctx.getSystemService(Context.WIFI_SERVICE) } returns null+ return NetworkManager(ctx)+ }++ @Test+ fun `setSsidTracking swaps the callback in both directions`() {+ val cm = mockk<ConnectivityManager>(relaxed = true)+ val manager = newManagerWith(cm)++ verify(exactly = 1) { cm.registerDefaultNetworkCallback(any<ConnectivityManager.NetworkCallback>()) }+ verify(exactly = 0) { cm.unregisterNetworkCallback(any<ConnectivityManager.NetworkCallback>()) }++ manager.setSsidTracking(true)+ verify(exactly = 1) { cm.unregisterNetworkCallback(any<ConnectivityManager.NetworkCallback>()) }+ verify(exactly = 2) { cm.registerDefaultNetworkCallback(any<ConnectivityManager.NetworkCallback>()) }++ manager.setSsidTracking(false)+ verify(exactly = 2) { cm.unregisterNetworkCallback(any<ConnectivityManager.NetworkCallback>()) }+ verify(exactly = 3) { cm.registerDefaultNetworkCallback(any<ConnectivityManager.NetworkCallback>()) }+ }++ @Test+ fun `setSsidTracking with an unchanged value does not churn the callback`() {+ val cm = mockk<ConnectivityManager>(relaxed = true)+ val manager = newManagerWith(cm)++ manager.setSsidTracking(false)+ manager.setSsidTracking(false)+ verify(exactly = 1) { cm.registerDefaultNetworkCallback(any<ConnectivityManager.NetworkCallback>()) }++ manager.setSsidTracking(true)+ manager.setSsidTracking(true)+ verify(exactly = 2) { cm.registerDefaultNetworkCallback(any<ConnectivityManager.NetworkCallback>()) }+ }++ @Test+ fun `the SSID is only read while tracking is on`() {+ val cm = mockk<ConnectivityManager>(relaxed = true)+ val slot = slot<ConnectivityManager.NetworkCallback>()+ every { cm.registerDefaultNetworkCallback(capture(slot)) } just Runs+ val info = mockk<WifiInfo>(relaxed = true)+ every { info.ssid } returns "\"HomeNet\""+ val wifi = mockk<WifiManager>(relaxed = true)+ every { wifi.connectionInfo } returns info+ val ctx = mockk<Context>(relaxed = true)+ every { ctx.getSystemService(Context.CONNECTIVITY_SERVICE) } returns cm+ every { ctx.getSystemService(Context.WIFI_SERVICE) } returns wifi+ val manager = NetworkManager(ctx)++ slot.captured.onCapabilitiesChanged(mockk(relaxed = true), mockk(relaxed = true))+ assertFalse(manager.isConnectedToSsid("HomeNet"))++ manager.setSsidTracking(true)+ slot.captured.onCapabilitiesChanged(mockk(relaxed = true), mockk(relaxed = true))+ assertTrue(manager.isConnectedToSsid("HomeNet"))+ }++ @Test+ fun `the plain callback still tracks VPN state`() {+ val cm = mockk<ConnectivityManager>(relaxed = true)+ val slot = slot<ConnectivityManager.NetworkCallback>()+ every { cm.registerDefaultNetworkCallback(capture(slot)) } just Runs+ val manager = newManagerWith(cm)++ val caps = mockk<NetworkCapabilities>(relaxed = true)+ every { caps.hasTransport(NetworkCapabilities.TRANSPORT_VPN) } returns true+ slot.captured.onCapabilitiesChanged(mockk(relaxed = true), caps)++ assertTrue(manager.isVpnConnected())+ }+// --- buildQueryString ---@Testdiff --git a/fastlane/metadata/android/en-US/changelogs/48.txt b/fastlane/metadata/android/en-US/changelogs/48.txtindex 446b20db..62d07c63 100644--- a/fastlane/metadata/android/en-US/changelogs/48.txt+++ b/fastlane/metadata/android/en-US/changelogs/48.txt@@ -6,3 +6,4 @@- Auto-export keeps its schedule after a backup restore- An aborted backup restore starts tracking again instead of leaving it off- Uploads to a local server recover after a temporary DNS failure instead of waiting for an app restart+- The location privacy indicator no longer lights up when GPS is not running