things: guard BLE adapter, addresses, scans and prefs reads
- Commit
e3c54c370b28f37ceaebc77f727c0b2a23f28f0a- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-19 01:54 UTC (17 days ago)
- Parents
2fbc67f
Runtime throw paths around the BLE stack and persisted state: - BleManager/ScaleBleManager dereferenced getSystemService (BluetoothManager).adapter at construction; on a device without a Bluetooth stack that NPEs inside DeviceController.init() at every launch. Adapter and scanner are now nullable and degrade to no devices. - adapter.getRemoteDevice(persistedAddress) and ScanFilter .setDeviceAddress throw IllegalArgumentException on a corrupt or legacy persisted MAC, crashing auto-reconnect on every launch. Both are now guarded and drop the connection/watch. - Scan entry points (bottle/scale startScan, device.name in the bottle scan callback) throw SecurityException when BLUETOOTH permissions are revoked after the gate; only the scale watch callback caught this. All scan starts and the name read are now guarded. - SharedPreferences reads of the wrong persisted type throw ClassCastException; refreshPaired, hasRememberedDevice, autoConnectSavedDevices, scaleUserIndex (called from init), scaleUserKey, savedScaleCategory and savedScaleEncryptsResistance now treat a wrong-typed value as absent, matching the existing guarded telemetry/profile reads. Verification: ./gradlew :things:testDevUnitTest and ./check things (run after this commit).
Diff
things/src/main/java/com/vayunmathur/things/platform/BleManager.kt
diff --git a/things/src/main/java/com/vayunmathur/things/platform/BleManager.kt b/things/src/main/java/com/vayunmathur/things/platform/BleManager.ktindex 6cadef3b81..dbada05d1e 100644--- a/things/src/main/java/com/vayunmathur/things/platform/BleManager.kt+++ b/things/src/main/java/com/vayunmathur/things/platform/BleManager.kt@@ -1,6 +1,7 @@ package com.vayunmathur.things.platform import android.annotation.SuppressLint+import android.bluetooth.BluetoothAdapter import android.bluetooth.BluetoothDevice import android.bluetooth.BluetoothGatt import android.bluetooth.BluetoothGattCallback@@ -82,9 +83,11 @@ class BleManager { /** Scanned WaterH bottle identified by display name and Bluetooth address. */ data class BleDevice(val name: String, val address: String) - private val bluetoothManager = DeviceController.appContext.getSystemService(BluetoothManager::class.java)- private val adapter = bluetoothManager.adapter- private val scanner get() = adapter.bluetoothLeScanner+ // Nullable: a device without a Bluetooth stack (or with it off at the service+ // level) must degrade to "no devices", not crash DeviceController.init().+ private val adapter: BluetoothAdapter? =+ DeviceController.appContext.getSystemService(BluetoothManager::class.java)?.adapter+ private val scanner get() = adapter?.bluetoothLeScanner private var gatt: BluetoothGatt? = null // The device we want to stay connected to, and whether the last disconnect was user-initiated.@@ -127,7 +130,13 @@ class BleManager { private val scanCallback = object : ScanCallback() { override fun onScanResult(callbackType: Int, result: ScanResult) {- val name = result.device.name ?: return+ // getName() is permission-gated on API 31+; a scan that started before a+ // revocation must drop the result, not crash the callback.+ val name = try {+ result.device.name+ } catch (_: SecurityException) {+ return+ } ?: return if (!name.startsWith("WaterH", ignoreCase = true)) return val addr = result.device.address if (DeviceController.discoveredDevices.none { it.address == addr }) {@@ -151,7 +160,14 @@ class BleManager { val settings = ScanSettings.Builder() .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) .build()- scanner?.startScan(null, settings, scanCallback)+ try {+ scanner?.startScan(null, settings, scanCallback)+ } catch (e: SecurityException) {+ // Permission revoked between the gate and the scan start.+ Log.error(TAG, "startScan not permitted", e)+ DeviceController.scanning.value = false+ return+ } DeviceController.connectionState.value = SCANNING_STATE handler.removeCallbacks(scanTimeout) handler.postDelayed(scanTimeout, SCAN_TIMEOUT_MS)@@ -183,7 +199,18 @@ class BleManager { stopScan() DeviceController.bottleLink.value = DeviceController.LinkState.Connecting DeviceController.connectionState.value = "Connecting..."- val device = adapter.getRemoteDevice(address)+ // A persisted address can be corrupt/legacy; getRemoteDevice throws on it.+ val device = try {+ adapter?.getRemoteDevice(address)+ } catch (e: IllegalArgumentException) {+ Log.error(TAG, "invalid bluetooth address", e)+ null+ }+ if (device == null) {+ DeviceController.bottleLink.value = DeviceController.LinkState.Waiting+ DeviceController.connectionState.value = "Invalid device address"+ return+ } gatt = device.connectGatt(DeviceController.appContext, autoConnect, gattCallback, BluetoothDevice.TRANSPORT_LE) }
things/src/main/java/com/vayunmathur/things/platform/DeviceController.kt
diff --git a/things/src/main/java/com/vayunmathur/things/platform/DeviceController.kt b/things/src/main/java/com/vayunmathur/things/platform/DeviceController.ktindex 428af6e5c6..f05f04d2a6 100644--- a/things/src/main/java/com/vayunmathur/things/platform/DeviceController.kt+++ b/things/src/main/java/com/vayunmathur/things/platform/DeviceController.kt@@ -149,9 +149,17 @@ object DeviceController { } catch (_: Exception) {} } + /** A persisted value stored under the wrong type throws ClassCastException. */+ internal fun savedAddress(key: String): String? =+ try {+ prefs.getString(key, null)+ } catch (_: ClassCastException) {+ null+ }+ private fun refreshPaired() {- bottlePaired.value = prefs.getString(BOTTLE_ADDRESS_KEY, null) != null- scalePaired.value = prefs.getString(SCALE_ADDRESS_KEY, null) != null+ bottlePaired.value = savedAddress(BOTTLE_ADDRESS_KEY) != null+ scalePaired.value = savedAddress(SCALE_ADDRESS_KEY) != null } /** Marshal onto the main thread; replaces the Activity's `runOnUiThread`. */@@ -200,16 +208,16 @@ object DeviceController { /** Reconnect to any remembered devices. No-op without permission or a powered-on adapter. */ fun autoConnectSavedDevices() { if (!hasBluetoothConnectPermission() || !bluetoothEnabled()) return- prefs.getString(BOTTLE_ADDRESS_KEY, null)?.let { bleManager.connect(it) }+ savedAddress(BOTTLE_ADDRESS_KEY)?.let { bleManager.connect(it) } // The scale is powered off between weigh-ins, so wait for it passively rather than // burning a doomed active attempt on every launch.- prefs.getString(SCALE_ADDRESS_KEY, null)?.let { scaleBleManager.connect(it, passive = true) }+ savedAddress(SCALE_ADDRESS_KEY)?.let { scaleBleManager.connect(it, passive = true) } } /** Whether at least one device is remembered (drives the service lifecycle). */ fun hasRememberedDevice(): Boolean =- prefs.getString(BOTTLE_ADDRESS_KEY, null) != null ||- prefs.getString(SCALE_ADDRESS_KEY, null) != null+ savedAddress(BOTTLE_ADDRESS_KEY) != null ||+ savedAddress(SCALE_ADDRESS_KEY) != null /** Last-resort cleanup when the service is intentionally stopped. */ fun closeManagers() {
things/src/main/java/com/vayunmathur/things/platform/DeviceSessions.kt
diff --git a/things/src/main/java/com/vayunmathur/things/platform/DeviceSessions.kt b/things/src/main/java/com/vayunmathur/things/platform/DeviceSessions.ktindex 76ff0c5b13..c0222d0017 100644--- a/things/src/main/java/com/vayunmathur/things/platform/DeviceSessions.kt+++ b/things/src/main/java/com/vayunmathur/things/platform/DeviceSessions.kt@@ -104,10 +104,19 @@ fun DeviceController.saveScaleAdvertisedTraits(category: Int, encryptsResistance } fun DeviceController.savedScaleCategory(): Int? =- if (devicePrefs.contains(SCALE_CATEGORY_KEY)) devicePrefs.getInt(SCALE_CATEGORY_KEY, 0) else null+ // Wrong-typed persisted values throw ClassCastException; treat as absent.+ try {+ if (devicePrefs.contains(SCALE_CATEGORY_KEY)) devicePrefs.getInt(SCALE_CATEGORY_KEY, 0) else null+ } catch (_: ClassCastException) {+ null+ } fun DeviceController.savedScaleEncryptsResistance(): Boolean =- devicePrefs.getBoolean(SCALE_ENCRYPT_RES_KEY, false)+ try {+ devicePrefs.getBoolean(SCALE_ENCRYPT_RES_KEY, false)+ } catch (_: ClassCastException) {+ false+ } // --- Scale user slot --- @@ -119,11 +128,20 @@ fun DeviceController.savedScaleEncryptsResistance(): Boolean = * recoverable only by resetting the scale. */ fun DeviceController.scaleUserIndex(): Int? =- if (devicePrefs.contains(SCALE_USER_INDEX_KEY)) devicePrefs.getInt(SCALE_USER_INDEX_KEY, 0) else null+ // Called from init(); a wrong-typed persisted slot must not crash startup.+ try {+ if (devicePrefs.contains(SCALE_USER_INDEX_KEY)) devicePrefs.getInt(SCALE_USER_INDEX_KEY, 0) else null+ } catch (_: ClassCastException) {+ null+ } /** Stable per-slot secret. Generated once; the scale expects the same value on every visit. */ fun DeviceController.scaleUserKey(): Int {- val existing = devicePrefs.getInt(SCALE_USER_KEY_KEY, 0)+ val existing = try {+ devicePrefs.getInt(SCALE_USER_KEY_KEY, 0)+ } catch (_: ClassCastException) {+ 0+ } if (existing in MIN_SCALE_USER_KEY..MAX_SCALE_USER_KEY) return existing val generated = Random.nextInt(MIN_SCALE_USER_KEY, SCALE_USER_KEY_BOUND) devicePrefs.edit { putInt(SCALE_USER_KEY_KEY, generated) }
things/src/main/java/com/vayunmathur/things/platform/ScaleBleConnection.kt
diff --git a/things/src/main/java/com/vayunmathur/things/platform/ScaleBleConnection.kt b/things/src/main/java/com/vayunmathur/things/platform/ScaleBleConnection.ktindex 6be345bc0c..f9284f9b54 100644--- a/things/src/main/java/com/vayunmathur/things/platform/ScaleBleConnection.kt+++ b/things/src/main/java/com/vayunmathur/things/platform/ScaleBleConnection.kt@@ -82,7 +82,14 @@ internal fun ScaleBleManager.startScanNow(scanCallback: ScanCallback) { val settings = ScanSettings.Builder() .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) .build()- scanner?.startScan(null, settings, scanCallback)+ try {+ scanner?.startScan(null, settings, scanCallback)+ } catch (e: SecurityException) {+ // Permission revoked between the gate and the scan start.+ Log.error(ScaleBleManager.TAG, "startScan not permitted", e)+ DeviceController.scaleScanning.value = false+ return+ } DeviceController.scaleConnectionState.value = SCALE_SCANNING_STATE handler.removeCallbacks(scanTimeout) handler.postDelayed(scanTimeout, ScaleBleManager.SCAN_TIMEOUT_MS)@@ -109,7 +116,14 @@ internal fun ScaleBleManager.startWatchNow(address: String, watchCallback: ScanC if (watchAddress == address) return stopWatch() watchAddress = address- val filters = listOf(ScanFilter.Builder().setDeviceAddress(address).build())+ // setDeviceAddress throws on a corrupt persisted address; drop the watch instead.+ val filters = try {+ listOf(ScanFilter.Builder().setDeviceAddress(address).build())+ } catch (e: IllegalArgumentException) {+ Log.error(ScaleBleManager.TAG, "invalid bluetooth address", e)+ watchAddress = null+ return+ } val settings = ScanSettings.Builder() .setScanMode(ScanSettings.SCAN_MODE_LOW_POWER) .build()
things/src/main/java/com/vayunmathur/things/platform/ScaleBleManager.kt
diff --git a/things/src/main/java/com/vayunmathur/things/platform/ScaleBleManager.kt b/things/src/main/java/com/vayunmathur/things/platform/ScaleBleManager.ktindex 3481581079..33a1472a0f 100644--- a/things/src/main/java/com/vayunmathur/things/platform/ScaleBleManager.kt+++ b/things/src/main/java/com/vayunmathur/things/platform/ScaleBleManager.kt@@ -1,6 +1,7 @@ package com.vayunmathur.things.platform import android.annotation.SuppressLint+import android.bluetooth.BluetoothAdapter import android.bluetooth.BluetoothDevice import android.bluetooth.BluetoothGatt import android.bluetooth.BluetoothGattCallback@@ -84,9 +85,10 @@ class ScaleBleManager { /** Scanned BLE scale identified by display name and Bluetooth address. */ data class ScaleBleDevice(val name: String, val address: String) - private val bluetoothManager = DeviceController.appContext.getSystemService(BluetoothManager::class.java)- private val adapter = bluetoothManager.adapter- internal val scanner get() = adapter.bluetoothLeScanner+ // Nullable for the same reason as BleManager: no Bluetooth stack, no crash.+ private val adapter: BluetoothAdapter? =+ DeviceController.appContext.getSystemService(BluetoothManager::class.java)?.adapter+ internal val scanner get() = adapter?.bluetoothLeScanner internal var gatt: BluetoothGatt? = null // See BleManager: keep connect() idempotent so repeated auto-connect calls don't stack a@@ -190,7 +192,16 @@ class ScaleBleManager { internal fun stopWatch() = stopWatchNow(watchCallback) - private fun openGatt(address: String) = openGattFor(adapter.getRemoteDevice(address))+ private fun openGatt(address: String) {+ // A persisted address can be corrupt/legacy; getRemoteDevice throws on it.+ val device = try {+ adapter?.getRemoteDevice(address)+ } catch (e: IllegalArgumentException) {+ Log.error(TAG, "invalid bluetooth address", e)+ null+ } ?: return+ openGattFor(device)+ } internal fun openGattFor(device: BluetoothDevice) = openGattNow(device)