Colota - Android GPS Location tracker
refactor: extract misplaced helpers from NetworkManager, SyncManager, BackupServiceModule
Max Dietriche71ac3c6c158
diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.mdindex a1d79b66..436e5274 100644--- a/apps/docs/docs/development/architecture.md+++ b/apps/docs/docs/development/architecture.md@@ -166,10 +166,14 @@ Orchestrates batch location uploads with:### NetworkManager-HTTP client. Validates endpoints, enforces HTTPS for public hosts, injects auth headers, caches connectivity checks, and detects unmetered connections, specific SSIDs and VPN status for sync condition filtering.+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`.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).+### UrlSafety++HTTP endpoint policy: HTTPS is required for public hosts, HTTP is only allowed when the host resolves to a private/local address (loopback, RFC 1918 site-local, link-local, or CGNAT 100.64.0.0/10). Resolves hostnames via `InetAddress` so server.local-style mDNS names work, with a per-hostname cache. Pure validation with no transport state, also exposed to the JS bridge for pre-save endpoint checks.+### ClientCertSslContextProviderBuilds the cached `SSLSocketFactory` used for mTLS. The key managers are supplied by `DynamicKeyManager` so the cert source can be swapped without rebuilding the SSL context; trust managers come from a `CompositeX509TrustManager` that layers an optional user-imported CA on top of Android's system roots. Includes a lazy migration: legacy PKCS12 + password material in `EncryptedSharedPreferences` (if any) is unwrapped into Android Keystore the first time the provider builds a factory or the Settings UI calls `runMigrationIfNeeded`. Legacy storage is wiped only on permanent failures (bad blob, wrong password, PKCS12-shape errors); transient failures (AndroidKeyStore unavailable, OOM) leave legacy data so the next request can retry.@@ -229,7 +233,7 @@ For backups, two `internal` methods support the export/import flow without expos| `MotionStateDetector` / `RawSensorMotionDetector` | Single detector behind a `MotionState { STATIONARY, MOVING }` interface. Backed by 30s-batched accelerometer variance (hysteresis: > 0.30 m/s² for 3s -> MOVING; < 0.15 m/s² for the configured per-zone dwell -> STATIONARY) and parallel `TYPE_SIGNIFICANT_MOTION` as a fast-path for sharp events. Fans out to both motionless-pause and stationary-profile exit consumers via one callback site in `LocationForegroundService.onMotionStateChange`. || `DeviceInfoHelper` | Device metadata and battery status with caching || `FileOperations` | File I/O, sharing via FileProvider, and clipboard access |-| `PayloadBuilder` | Builds JSON payloads with dynamic field mapping |+| `PayloadBuilder` | Builds outgoing JSON payloads (field-mapped, Overland batch envelope, Traccar JSON) and extracts envelope custom fields || `ServiceConfig` | Centralized configuration data class || `TimedCache` | Generic TTL cache used for queue count, device info, profiles, and network state || `BuildConfigModule` | Exposes build constants (SDK versions, app version) to JS |diff --git a/apps/docs/docs/development/local-setup.md b/apps/docs/docs/development/local-setup.mdindex be5dd29f..550b96cc 100644--- a/apps/docs/docs/development/local-setup.md+++ b/apps/docs/docs/development/local-setup.md@@ -166,14 +166,16 @@ cd apps/mobile/androidTest files are located in `apps/mobile/android/app/src/test/java/com/Colota/`. The tests cover:- **SyncManager** - Instant/periodic sync modes, retry logic, Wi-Fi only gating, backoff-- **NetworkManager** - HTTPS enforcement, private host detection, header masking, query strings+- **NetworkManager** - Query string building, URL variable substitution+- **UrlSafety** - HTTPS-for-public enforcement, private/CGNAT host detection+- **AppLogger** - Sensitive HTTP header value masking- **DatabaseHelper** - Data model, cutoff calculations, batch operations- **SecureStorageHelper** - Basic Auth, Bearer token, custom headers, JSON parsing- **DeviceInfoHelper** - Battery threshold logic, status code mapping, percentage calculation- **NotificationHelper** - Status text generation, throttling, movement filter, deduplication- **LocationForegroundService** - Battery shutdown, accuracy filtering, zone state machine- **ServiceConfig** - Database/Intent/ReadableMap parsing, defaults, round-trips-- **PayloadBuilder** - JSON payload construction and field map parsing+- **PayloadBuilder** - Payload construction (field-mapped, Overland, Traccar) and field map parsing- **GeofenceHelper** - Haversine distance calculations and radius checks- **TimedCache** - TTL cache logicdiff --git a/apps/mobile/android/app/src/main/java/com/colota/bridge/BackupServiceModule.kt b/apps/mobile/android/app/src/main/java/com/colota/bridge/BackupServiceModule.ktindex 614e68c6..5555498d 100644--- a/apps/mobile/android/app/src/main/java/com/colota/bridge/BackupServiceModule.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/bridge/BackupServiceModule.kt@@ -356,7 +356,4 @@ class BackupServiceModule(reactContext: ReactApplicationContext) :else -> "E_BACKUP_UNKNOWN"}- private fun readableArrayToCharArray(codes: ReadableArray): CharArray {- return CharArray(codes.size()) { i -> codes.getInt(i).toChar() }- }}diff --git a/apps/mobile/android/app/src/main/java/com/colota/bridge/BridgeUtils.kt b/apps/mobile/android/app/src/main/java/com/colota/bridge/BridgeUtils.ktindex 411dd89d..a6d47fb1 100644--- a/apps/mobile/android/app/src/main/java/com/colota/bridge/BridgeUtils.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/bridge/BridgeUtils.kt@@ -7,6 +7,7 @@ package com.Colota.bridgeimport com.Colota.util.AppLoggerimport com.facebook.react.bridge.Promise+import com.facebook.react.bridge.ReadableArrayimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.launch@@ -33,3 +34,10 @@ internal fun CoroutineScope.launchForPromise(}}}++/**+ * Converts a JS-side array of UTF-16 code points (passed as ints) to a CharArray.+ * Used for passwords so the secret never lands in a Java String's intern pool.+ */+internal fun readableArrayToCharArray(codes: ReadableArray): CharArray =+ CharArray(codes.size()) { i -> codes.getInt(i).toChar() }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 98a53b35..ecc79de5 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@@ -24,6 +24,7 @@ import com.Colota.service.getIntOrNullimport com.Colota.service.getStringOrNullimport com.Colota.service.getBooleanOrNullimport com.Colota.sync.NetworkManager+import com.Colota.sync.UrlSafetyimport com.Colota.util.DeviceInfoHelperimport com.Colota.export.AutoExportConfigimport com.Colota.export.AutoExportScheduler@@ -668,12 +669,12 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :@ReactMethodfun isValidEndpointProtocol(endpoint: String, promise: Promise) = executeAsync(promise) {- networkManager.isValidProtocol(endpoint)+ UrlSafety.isValidProtocol(endpoint)}@ReactMethodfun isPrivateEndpoint(endpoint: String, promise: Promise) = executeAsync(promise) {- networkManager.isPrivateEndpoint(endpoint)+ UrlSafety.isPrivateEndpoint(endpoint)}@ReactMethoddiff --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 549ff63a..d4b2b144 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@@ -167,7 +167,7 @@ class NetworkManager(private val context: Context) {AppLogger.d(TAG, "Method: ${connection.requestMethod}")AppLogger.d(TAG, "Headers:")connection.requestProperties.forEach { (key, values) ->- val masked = values.map { maskSensitiveHeaderValue(key, it) }+ val masked = values.map { AppLogger.maskSensitiveHeaderValue(key, it) }AppLogger.d(TAG, "$key: ${masked.joinToString()}")}if (!isGet) {@@ -176,88 +176,6 @@ class NetworkManager(private val context: Context) {AppLogger.d(TAG, "===================")}- /**- * Returns true if the endpoint's host resolves to a private/local address.- * Performs DNS resolution and caches the result.- */- fun isPrivateEndpoint(endpoint: String): Boolean {- val host = try {- URL(endpoint).host ?: return false- } catch (_: Exception) { return false }- return isPrivateHost(host)- }-- /**- * Validates that the endpoint uses an allowed protocol.- * HTTPS is required for public hosts; HTTP is only allowed for private/local addresses.- * Performs DNS resolution to detect hostnames that resolve to private IPs.- */- fun isValidProtocol(endpoint: String): Boolean {- val url = try { URL(endpoint) } catch (_: Exception) { return false }- val protocol = url.protocol.lowercase()- val host = url.host ?: return false-- if (protocol != "http" && protocol != "https") return false-- if (protocol == "http" && !isPrivateHost(host)) {- return false- }- return true- }-- /** Per-hostname cache of the DNS lookup + private-range check. */- private val privateHostCache = java.util.concurrent.ConcurrentHashMap<String, Boolean>()-- /**- * Checks if the given host is private or local.- * Matches Android's local network definition:- * loopback, site-local (RFC 1918), link-local, and CGNAT (100.64.0.0/10).- */- private fun isPrivateHost(host: String): Boolean {- if (host == "localhost") return true- return privateHostCache.getOrPut(host) {- try {- val address = java.net.InetAddress.getByName(host)- address.isAnyLocalAddress ||- address.isLoopbackAddress ||- address.isSiteLocalAddress ||- address.isLinkLocalAddress ||- isCgnatAddress(address)- } catch (e: Exception) {- false- }- }- }-- /** Checks if the address falls in the CGNAT range 100.64.0.0/10. */- private fun isCgnatAddress(address: java.net.InetAddress): Boolean {- val bytes = address.address- if (bytes.size != 4) return false- val a = bytes[0].toInt() and 0xFF- val b = bytes[1].toInt() and 0xFF- return a == 100 && b in 64..127- }-- /**- * Masks the value of sensitive headers before logging.- * Shows the first 4 characters followed by "***", or the full value- * if it is shorter than 4 characters (replaced entirely with "***").- */- private fun maskSensitiveHeaderValue(headerName: String, headerValue: String): String {- val sensitivePatterns = listOf(- "authorization", "bearer", "token", "secret", "password", "api-key", "apikey"- )- val nameLower = headerName.lowercase()- val isSensitive = sensitivePatterns.any { pattern -> nameLower.contains(pattern) }- if (!isSensitive) return headerValue-- return if (headerValue.length > 4) {- "${headerValue.substring(0, 4)}***"- } else {- "***"- }- }-suspend fun sendBatchToEndpoint(items: List<JSONObject>,customFields: Map<String, String>,@@ -279,7 +197,7 @@ class NetworkManager(private val context: Context) {return@withContext BatchResult.NetworkError}- if (!isValidProtocol(resolvedEndpoint)) {+ if (!UrlSafety.isValidProtocol(resolvedEndpoint)) {AppLogger.e(TAG, "Protocol blocked or invalid: $endpoint")return@withContext BatchResult.NetworkError}@@ -298,7 +216,7 @@ class NetworkManager(private val context: Context) {writeBody(connection, envelope)return@withContext readBatchResponse(connection, items.size)} catch (e: java.net.SocketException) {- if (isPrivateHost(url.host ?: "") && e.message?.contains("EPERM") == true) {+ if (UrlSafety.isPrivateHost(url.host ?: "") && e.message?.contains("EPERM") == true) {AppLogger.e(TAG, "Local network access denied - grant Local Network Access permission", e)} else {AppLogger.e(TAG, "Network error: ${e.message}", e)@@ -350,7 +268,7 @@ class NetworkManager(private val context: Context) {} catch (_: Exception) {return@withContext TestEndpointResult(false, errorMessage = "Invalid URL: $resolvedEndpoint")}- if (!isValidProtocol(resolvedEndpoint)) {+ if (!UrlSafety.isValidProtocol(resolvedEndpoint)) {return@withContext TestEndpointResult(false,errorMessage = "HTTPS is required for public endpoints. HTTP is only allowed for private/local addresses."@@ -393,7 +311,7 @@ class NetworkManager(private val context: Context) {} catch (e: UnrecoverableKeyException) {TestEndpointResult(false, errorMessage = "Client certificate password is incorrect - re-import the .p12")} catch (e: java.net.SocketException) {- val msg = if (isPrivateHost(url.host ?: "") && e.message?.contains("EPERM") == true) {+ val msg = if (UrlSafety.isPrivateHost(url.host ?: "") && e.message?.contains("EPERM") == true) {"Local network access denied - grant Local Network Access permission"} else "Network error: ${e.message}"TestEndpointResult(false, errorMessage = msg)diff --git a/apps/mobile/android/app/src/main/java/com/colota/sync/PayloadBuilder.kt b/apps/mobile/android/app/src/main/java/com/colota/sync/PayloadBuilder.ktindex 64f35826..cca58c62 100644--- a/apps/mobile/android/app/src/main/java/com/colota/sync/PayloadBuilder.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/sync/PayloadBuilder.kt@@ -17,6 +17,23 @@ object PayloadBuilder {private const val TAG = "PayloadBuilder"+ // Field names buildLocationPayload writes when usesFixedFieldNames=true. Anything else in+ // an outgoing payload is a user-configured custom field (device_id, tid, etc.) and lifts+ // to envelope level via extractEnvelopeCustomFields.+ private val canonicalLocationKeys = setOf("lat", "lon", "acc", "alt", "vel", "batt", "bs", "tst", "bear")++ fun extractEnvelopeCustomFields(payload: JSONObject): Map<String, String> {+ val fields = mutableMapOf<String, String>()+ val keys = payload.keys()+ while (keys.hasNext()) {+ val key = keys.next()+ if (key !in canonicalLocationKeys) {+ fields[key] = payload.optString(key, "")+ }+ }+ return fields+ }+fun buildLocationPayload(location: Location,timestamp: Long,diff --git a/apps/mobile/android/app/src/main/java/com/colota/sync/SyncManager.kt b/apps/mobile/android/app/src/main/java/com/colota/sync/SyncManager.ktindex f66f0ecd..4f63dd2c 100644--- a/apps/mobile/android/app/src/main/java/com/colota/sync/SyncManager.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/sync/SyncManager.kt@@ -37,10 +37,6 @@ class SyncManager(@Volatile private var apiFormat: ApiFormat = ApiFormat.FIELD_MAPPED@Volatile private var overlandBatchSize: Int = 50- // Names PayloadBuilder writes when usesFixedFieldNames=true. Anything else in the payload- // is a user-configured custom field (device_id, tid, etc.) and lifts to envelope level.- private val canonicalLocationKeys = setOf("lat", "lon", "acc", "alt", "vel", "batt", "bs", "tst", "bear")-private var syncJob: Job? = null@Volatile private var lastSyncTime: Long = 0@Volatile var lastSuccessfulSyncTime: Long = 0@@ -345,7 +341,7 @@ class SyncManager(val parseableItems = parsed.map { it.first }val payloads = parsed.map { it.second }- val customFields = extractEnvelopeCustomFields(payloads.first())+ val customFields = PayloadBuilder.extractEnvelopeCustomFields(payloads.first())val result = networkManager.sendBatchToEndpoint(items = payloads,@@ -387,18 +383,6 @@ class SyncManager(}}- private fun extractEnvelopeCustomFields(payload: JSONObject): Map<String, String> {- val fields = mutableMapOf<String, String>()- val keys = payload.keys()- while (keys.hasNext()) {- val key = keys.next()- if (key !in canonicalLocationKeys) {- fields[key] = payload.optString(key, "")- }- }- return fields- }-private fun calculateNextSyncDelay(): Long {if (syncIntervalSeconds <= 0) {return if (getCachedQueuedCount() > 0) {diff --git a/apps/mobile/android/app/src/main/java/com/colota/sync/UrlSafety.kt b/apps/mobile/android/app/src/main/java/com/colota/sync/UrlSafety.ktnew file mode 100644index 00000000..a69ceeb0--- /dev/null+++ b/apps/mobile/android/app/src/main/java/com/colota/sync/UrlSafety.kt@@ -0,0 +1,74 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++package com.Colota.sync++import java.net.InetAddress+import java.net.URL+import java.util.concurrent.ConcurrentHashMap++/**+ * HTTP endpoint policy: which protocols and hosts the app is willing to talk to.+ * Pure validation, no transport state.+ */+object UrlSafety {++ /** Per-hostname cache of the DNS lookup + private-range check. */+ private val privateHostCache = ConcurrentHashMap<String, Boolean>()++ /** Performs DNS resolution and caches the result. */+ fun isPrivateEndpoint(endpoint: String): Boolean {+ val host = try {+ URL(endpoint).host ?: return false+ } catch (_: Exception) { return false }+ return isPrivateHost(host)+ }++ /**+ * HTTPS is required for public hosts; HTTP is only allowed for private/local addresses.+ * Performs DNS resolution to detect hostnames that resolve to private IPs.+ */+ fun isValidProtocol(endpoint: String): Boolean {+ val url = try { URL(endpoint) } catch (_: Exception) { return false }+ val protocol = url.protocol.lowercase()+ val host = url.host ?: return false++ if (protocol != "http" && protocol != "https") return false++ if (protocol == "http" && !isPrivateHost(host)) {+ return false+ }+ return true+ }++ /**+ * Matches Android's local network definition:+ * loopback, site-local (RFC 1918), link-local, and CGNAT (100.64.0.0/10).+ */+ fun isPrivateHost(host: String): Boolean {+ if (host == "localhost") return true+ return privateHostCache.getOrPut(host) {+ try {+ val address = InetAddress.getByName(host)+ address.isAnyLocalAddress ||+ address.isLoopbackAddress ||+ address.isSiteLocalAddress ||+ address.isLinkLocalAddress ||+ isCgnatAddress(address)+ } catch (e: Exception) {+ false+ }+ }+ }++ /** Checks if the address falls in the CGNAT range 100.64.0.0/10. */+ private fun isCgnatAddress(address: InetAddress): Boolean {+ val bytes = address.address+ if (bytes.size != 4) return false+ val a = bytes[0].toInt() and 0xFF+ val b = bytes[1].toInt() and 0xFF+ return a == 100 && b in 64..127+ }+}diff --git a/apps/mobile/android/app/src/main/java/com/colota/util/AppLogger.kt b/apps/mobile/android/app/src/main/java/com/colota/util/AppLogger.ktindex f89298e9..13e209c7 100644--- a/apps/mobile/android/app/src/main/java/com/colota/util/AppLogger.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/util/AppLogger.kt@@ -33,4 +33,24 @@ object AppLogger {val t = PREFIX + tagif (throwable != null) Log.e(t, msg, throwable) else Log.e(t, msg)}++ private val sensitiveHeaderPatterns = listOf(+ "authorization", "bearer", "token", "secret", "password", "api-key", "apikey"+ )++ /**+ * Masks the value of sensitive HTTP headers before logging.+ * Shows the first 4 characters followed by "***", or "***" for values shorter than 5.+ */+ fun maskSensitiveHeaderValue(headerName: String, headerValue: String): String {+ val nameLower = headerName.lowercase()+ val isSensitive = sensitiveHeaderPatterns.any { pattern -> nameLower.contains(pattern) }+ if (!isSensitive) return headerValue++ return if (headerValue.length > 4) {+ "${headerValue.substring(0, 4)}***"+ } else {+ "***"+ }+ }}diff --git a/apps/mobile/android/app/src/main/res/xml/network_security_config.xml b/apps/mobile/android/app/src/main/res/xml/network_security_config.xmlindex 1e493880..a8b367a3 100644--- a/apps/mobile/android/app/src/main/res/xml/network_security_config.xml+++ b/apps/mobile/android/app/src/main/res/xml/network_security_config.xml@@ -6,7 +6,7 @@self-hosted servers on private networks (10.x.x.x, 192.168.x.x, 172.16-31.x.x).Actual enforcement happens at the app level:- - NetworkManager.isValidProtocol() restricts HTTP to private hosts+ - UrlSafety.isValidProtocol() restricts HTTP to private hosts- settingsValidation.isEndpointAllowed() blocks public HTTP endpoints in the UITrust anchors: system only. User-installed device CAs are deliberatelydiff --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 69a6b427..84df6a49 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@@ -28,230 +28,6 @@ class NetworkManagerTest {unmockkObject(AppLogger)}- // --- isValidProtocol ----- @Test- fun `isValidProtocol accepts https for public host`() {- val manager = createNetworkManagerViaReflection()- assertTrue(manager.isValidProtocol("https://example.com/api"))- }-- @Test- fun `isValidProtocol rejects http for public host`() {- val manager = createNetworkManagerViaReflection()- assertFalse(manager.isValidProtocol("http://example.com/api"))- }-- @Test- fun `isValidProtocol accepts http for localhost`() {- val manager = createNetworkManagerViaReflection()- assertTrue(manager.isValidProtocol("http://localhost:8080/api"))- }-- @Test- fun `isValidProtocol accepts http for 127_0_0_1`() {- val manager = createNetworkManagerViaReflection()- assertTrue(manager.isValidProtocol("http://127.0.0.1:3000/api"))- }-- @Test- fun `isValidProtocol accepts http for 192_168 address`() {- val manager = createNetworkManagerViaReflection()- assertTrue(manager.isValidProtocol("http://192.168.1.100/api"))- }-- @Test- fun `isValidProtocol accepts http for 10_x address`() {- val manager = createNetworkManagerViaReflection()- assertTrue(manager.isValidProtocol("http://10.0.0.1/api"))- }-- @Test- fun `isValidProtocol accepts http for 172_16 range`() {- val manager = createNetworkManagerViaReflection()- assertTrue(manager.isValidProtocol("http://172.16.0.1/api"))- assertTrue(manager.isValidProtocol("http://172.31.255.255/api"))- }-- @Test- fun `isValidProtocol rejects http for 172_32 (outside private range)`() {- val manager = createNetworkManagerViaReflection()- assertFalse(manager.isValidProtocol("http://172.32.0.1/api"))- }-- @Test- fun `isValidProtocol accepts http for CGNAT range`() {- val manager = createNetworkManagerViaReflection()- assertTrue(manager.isValidProtocol("http://100.64.0.1/api"))- assertTrue(manager.isValidProtocol("http://100.127.255.255/api"))- }-- @Test- fun `isValidProtocol rejects ftp protocol`() {- val manager = createNetworkManagerViaReflection()- assertFalse(manager.isValidProtocol("ftp://example.com/file"))- }-- @Test- fun `isValidProtocol returns false for malformed URL`() {- val manager = createNetworkManagerViaReflection()- assertFalse(manager.isValidProtocol("not-a-url"))- }-- @Test- fun `isValidProtocol returns false for empty string`() {- val manager = createNetworkManagerViaReflection()- assertFalse(manager.isValidProtocol(""))- }-- @Test- fun `isValidProtocol accepts https for any host`() {- val manager = createNetworkManagerViaReflection()- assertTrue(manager.isValidProtocol("https://192.168.1.1/api"))- assertTrue(manager.isValidProtocol("https://localhost/api"))- }-- // --- isPrivateEndpoint (public wrapper) ----- @Test- fun `isPrivateEndpoint returns true for private IP endpoint`() {- val manager = createNetworkManagerViaReflection()- assertTrue(manager.isPrivateEndpoint("http://192.168.1.1/api"))- }-- @Test- fun `isPrivateEndpoint returns true for localhost`() {- val manager = createNetworkManagerViaReflection()- assertTrue(manager.isPrivateEndpoint("http://localhost:8080/api"))- }-- @Test- fun `isPrivateEndpoint returns false for public host`() {- val manager = createNetworkManagerViaReflection()- assertFalse(manager.isPrivateEndpoint("https://example.com/api"))- }-- @Test- fun `isPrivateEndpoint returns true for 127_0_0_1`() {- val manager = createNetworkManagerViaReflection()- assertTrue(manager.isPrivateEndpoint("http://127.0.0.1/api"))- }-- @Test- fun `isPrivateEndpoint returns true for 10_x address`() {- val manager = createNetworkManagerViaReflection()- assertTrue(manager.isPrivateEndpoint("http://10.0.0.1/api"))- assertTrue(manager.isPrivateEndpoint("http://10.255.255.255/api"))- }-- @Test- fun `isPrivateEndpoint returns true for 172_16 range`() {- val manager = createNetworkManagerViaReflection()- assertTrue(manager.isPrivateEndpoint("http://172.16.0.1/api"))- assertTrue(manager.isPrivateEndpoint("http://172.31.255.255/api"))- }-- @Test- fun `isPrivateEndpoint returns true for CGNAT range`() {- val manager = createNetworkManagerViaReflection()- assertTrue(manager.isPrivateEndpoint("http://100.64.0.1/api"))- assertTrue(manager.isPrivateEndpoint("http://100.127.255.255/api"))- }-- @Test- fun `isPrivateEndpoint returns true regardless of protocol`() {- val manager = createNetworkManagerViaReflection()- assertTrue(manager.isPrivateEndpoint("http://192.168.1.1/api"))- assertTrue(manager.isPrivateEndpoint("https://192.168.1.1/api"))- assertTrue(manager.isPrivateEndpoint("http://localhost/api"))- assertTrue(manager.isPrivateEndpoint("https://localhost/api"))- }-- @Test- fun `isPrivateEndpoint returns false for public domain`() {- val manager = createNetworkManagerViaReflection()- assertFalse(manager.isPrivateEndpoint("http://example.com/api"))- assertFalse(manager.isPrivateEndpoint("https://example.com/api"))- }-- @Test- fun `isPrivateEndpoint resolves hostname via DNS`() {- // localhost resolves to 127.0.0.1 via InetAddress - proves the DNS path works.- // Testing hostnames like "server.local" -> 192.168.x.x requires mDNS which- // is not available in unit tests, but the code path is the same: InetAddress.getByName()- // -> isSiteLocalAddress. The example.com test below proves public DNS resolution works.- val manager = createNetworkManagerViaReflection()- assertTrue(manager.isPrivateEndpoint("http://localhost:8080/api"))- }-- @Test- fun `isPrivateEndpoint returns false for unresolvable host`() {- val manager = createNetworkManagerViaReflection()- assertFalse(manager.isPrivateEndpoint("http://this-host-does-not-exist-xyz.invalid/api"))- }-- @Test- fun `isPrivateEndpoint returns false for malformed URL`() {- val manager = createNetworkManagerViaReflection()- assertFalse(manager.isPrivateEndpoint("not-a-url"))- }-- // --- maskSensitiveHeaderValue ----- @Test- fun `maskSensitiveHeaderValue masks authorization header`() {- val result = invokeMask("Authorization", "Bearer abcdef12345")- assertEquals("Bear***", result)- }-- @Test- fun `maskSensitiveHeaderValue masks api-key header`() {- val result = invokeMask("X-Api-Key", "secret12345")- assertEquals("secr***", result)- }-- @Test- fun `maskSensitiveHeaderValue masks token header`() {- val result = invokeMask("X-Token", "mytoken123")- assertEquals("myto***", result)- }-- @Test- fun `maskSensitiveHeaderValue masks password header`() {- val result = invokeMask("X-Password", "pass1234")- assertEquals("pass***", result)- }-- @Test- fun `maskSensitiveHeaderValue does not mask non-sensitive header`() {- val result = invokeMask("Content-Type", "application/json")- assertEquals("application/json", result)- }-- @Test- fun `maskSensitiveHeaderValue masks short value entirely`() {- val result = invokeMask("Authorization", "ab")- assertEquals("***", result)- }-- @Test- fun `maskSensitiveHeaderValue masks exactly 4 char value entirely`() {- val result = invokeMask("Authorization", "abcd")- assertEquals("***", result)- }-- @Test- fun `maskSensitiveHeaderValue masks 5 char value with prefix`() {- val result = invokeMask("Authorization", "abcde")- assertEquals("abcd***", result)- }-- @Test- fun `maskSensitiveHeaderValue is case insensitive for header names`() {- val result = invokeMask("AUTHORIZATION", "Bearer token123")- assertEquals("Bear***", result)- }-// --- buildQueryString ---@Test@@ -315,15 +91,6 @@ class NetworkManagerTest {// --- Reflection helpers to access private methods ---- private fun invokeMask(headerName: String, headerValue: String): String {- val method = NetworkManager::class.java.getDeclaredMethod(- "maskSensitiveHeaderValue", String::class.java, String::class.java- )- method.isAccessible = true- val manager = createNetworkManagerViaReflection()- return method.invoke(manager, headerName, headerValue) as String- }-private fun invokeBuildQueryString(payload: JSONObject): String {val method = NetworkManager::class.java.getDeclaredMethod("buildQueryString", JSONObject::class.java)method.isAccessible = truediff --git a/apps/mobile/android/app/src/test/java/com/Colota/sync/UrlSafetyTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/sync/UrlSafetyTest.ktnew file mode 100644index 00000000..550afac9--- /dev/null+++ b/apps/mobile/android/app/src/test/java/com/Colota/sync/UrlSafetyTest.kt@@ -0,0 +1,150 @@+package com.Colota.sync++import org.junit.Assert.*+import org.junit.Test++class UrlSafetyTest {++ // --- isValidProtocol ---++ @Test+ fun `isValidProtocol accepts https for public host`() {+ assertTrue(UrlSafety.isValidProtocol("https://example.com/api"))+ }++ @Test+ fun `isValidProtocol rejects http for public host`() {+ assertFalse(UrlSafety.isValidProtocol("http://example.com/api"))+ }++ @Test+ fun `isValidProtocol accepts http for localhost`() {+ assertTrue(UrlSafety.isValidProtocol("http://localhost:8080/api"))+ }++ @Test+ fun `isValidProtocol accepts http for 127_0_0_1`() {+ assertTrue(UrlSafety.isValidProtocol("http://127.0.0.1:3000/api"))+ }++ @Test+ fun `isValidProtocol accepts http for 192_168 address`() {+ assertTrue(UrlSafety.isValidProtocol("http://192.168.1.100/api"))+ }++ @Test+ fun `isValidProtocol accepts http for 10_x address`() {+ assertTrue(UrlSafety.isValidProtocol("http://10.0.0.1/api"))+ }++ @Test+ fun `isValidProtocol accepts http for 172_16 range`() {+ assertTrue(UrlSafety.isValidProtocol("http://172.16.0.1/api"))+ assertTrue(UrlSafety.isValidProtocol("http://172.31.255.255/api"))+ }++ @Test+ fun `isValidProtocol rejects http for 172_32 (outside private range)`() {+ assertFalse(UrlSafety.isValidProtocol("http://172.32.0.1/api"))+ }++ @Test+ fun `isValidProtocol accepts http for CGNAT range`() {+ assertTrue(UrlSafety.isValidProtocol("http://100.64.0.1/api"))+ assertTrue(UrlSafety.isValidProtocol("http://100.127.255.255/api"))+ }++ @Test+ fun `isValidProtocol rejects ftp protocol`() {+ assertFalse(UrlSafety.isValidProtocol("ftp://example.com/file"))+ }++ @Test+ fun `isValidProtocol returns false for malformed URL`() {+ assertFalse(UrlSafety.isValidProtocol("not-a-url"))+ }++ @Test+ fun `isValidProtocol returns false for empty string`() {+ assertFalse(UrlSafety.isValidProtocol(""))+ }++ @Test+ fun `isValidProtocol accepts https for any host`() {+ assertTrue(UrlSafety.isValidProtocol("https://192.168.1.1/api"))+ assertTrue(UrlSafety.isValidProtocol("https://localhost/api"))+ }++ // --- isPrivateEndpoint ---++ @Test+ fun `isPrivateEndpoint returns true for private IP endpoint`() {+ assertTrue(UrlSafety.isPrivateEndpoint("http://192.168.1.1/api"))+ }++ @Test+ fun `isPrivateEndpoint returns true for localhost`() {+ assertTrue(UrlSafety.isPrivateEndpoint("http://localhost:8080/api"))+ }++ @Test+ fun `isPrivateEndpoint returns false for public host`() {+ assertFalse(UrlSafety.isPrivateEndpoint("https://example.com/api"))+ }++ @Test+ fun `isPrivateEndpoint returns true for 127_0_0_1`() {+ assertTrue(UrlSafety.isPrivateEndpoint("http://127.0.0.1/api"))+ }++ @Test+ fun `isPrivateEndpoint returns true for 10_x address`() {+ assertTrue(UrlSafety.isPrivateEndpoint("http://10.0.0.1/api"))+ assertTrue(UrlSafety.isPrivateEndpoint("http://10.255.255.255/api"))+ }++ @Test+ fun `isPrivateEndpoint returns true for 172_16 range`() {+ assertTrue(UrlSafety.isPrivateEndpoint("http://172.16.0.1/api"))+ assertTrue(UrlSafety.isPrivateEndpoint("http://172.31.255.255/api"))+ }++ @Test+ fun `isPrivateEndpoint returns true for CGNAT range`() {+ assertTrue(UrlSafety.isPrivateEndpoint("http://100.64.0.1/api"))+ assertTrue(UrlSafety.isPrivateEndpoint("http://100.127.255.255/api"))+ }++ @Test+ fun `isPrivateEndpoint returns true regardless of protocol`() {+ assertTrue(UrlSafety.isPrivateEndpoint("http://192.168.1.1/api"))+ assertTrue(UrlSafety.isPrivateEndpoint("https://192.168.1.1/api"))+ assertTrue(UrlSafety.isPrivateEndpoint("http://localhost/api"))+ assertTrue(UrlSafety.isPrivateEndpoint("https://localhost/api"))+ }++ @Test+ fun `isPrivateEndpoint returns false for public domain`() {+ assertFalse(UrlSafety.isPrivateEndpoint("http://example.com/api"))+ assertFalse(UrlSafety.isPrivateEndpoint("https://example.com/api"))+ }++ @Test+ fun `isPrivateEndpoint resolves hostname via DNS`() {+ // localhost resolves to 127.0.0.1 via InetAddress - proves the DNS path works.+ // Testing hostnames like "server.local" -> 192.168.x.x requires mDNS which+ // is not available in unit tests, but the code path is the same: InetAddress.getByName()+ // -> isSiteLocalAddress. The example.com test below proves public DNS resolution works.+ assertTrue(UrlSafety.isPrivateEndpoint("http://localhost:8080/api"))+ }++ @Test+ fun `isPrivateEndpoint returns false for unresolvable host`() {+ assertFalse(UrlSafety.isPrivateEndpoint("http://this-host-does-not-exist-xyz.invalid/api"))+ }++ @Test+ fun `isPrivateEndpoint returns false for malformed URL`() {+ assertFalse(UrlSafety.isPrivateEndpoint("not-a-url"))+ }+}diff --git a/apps/mobile/android/app/src/test/java/com/Colota/util/AppLoggerTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/util/AppLoggerTest.ktnew file mode 100644index 00000000..ae275e52--- /dev/null+++ b/apps/mobile/android/app/src/test/java/com/Colota/util/AppLoggerTest.kt@@ -0,0 +1,52 @@+package com.Colota.util++import org.junit.Assert.*+import org.junit.Test++class AppLoggerTest {++ @Test+ fun `maskSensitiveHeaderValue masks authorization header`() {+ assertEquals("Bear***", AppLogger.maskSensitiveHeaderValue("Authorization", "Bearer abcdef12345"))+ }++ @Test+ fun `maskSensitiveHeaderValue masks api-key header`() {+ assertEquals("secr***", AppLogger.maskSensitiveHeaderValue("X-Api-Key", "secret12345"))+ }++ @Test+ fun `maskSensitiveHeaderValue masks token header`() {+ assertEquals("myto***", AppLogger.maskSensitiveHeaderValue("X-Token", "mytoken123"))+ }++ @Test+ fun `maskSensitiveHeaderValue masks password header`() {+ assertEquals("pass***", AppLogger.maskSensitiveHeaderValue("X-Password", "pass1234"))+ }++ @Test+ fun `maskSensitiveHeaderValue does not mask non-sensitive header`() {+ assertEquals("application/json", AppLogger.maskSensitiveHeaderValue("Content-Type", "application/json"))+ }++ @Test+ fun `maskSensitiveHeaderValue masks short value entirely`() {+ assertEquals("***", AppLogger.maskSensitiveHeaderValue("Authorization", "ab"))+ }++ @Test+ fun `maskSensitiveHeaderValue masks exactly 4 char value entirely`() {+ assertEquals("***", AppLogger.maskSensitiveHeaderValue("Authorization", "abcd"))+ }++ @Test+ fun `maskSensitiveHeaderValue masks 5 char value with prefix`() {+ assertEquals("abcd***", AppLogger.maskSensitiveHeaderValue("Authorization", "abcde"))+ }++ @Test+ fun `maskSensitiveHeaderValue is case insensitive for header names`() {+ assertEquals("Bear***", AppLogger.maskSensitiveHeaderValue("AUTHORIZATION", "Bearer token123"))+ }+}