taxi: bound Lyft parsers and guard service start and stores
- Commit
c27c0ce09ebf1d67464490fe48dd055c309fe289- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-19 01:55 UTC (17 days ago)
- Parents
f592990
Crash paths on untrusted server bytes and persisted state: - LyftProto read fixed64 bytes, length-delimited ranges and varints with no bounds checks; a truncated or lying Lyft protobuf body threw ArrayIndexOutOfBounds/ StringIndexOutOfBounds out of ProtoMessage construction and the string/message accessors, crashing the driver-location poll loop (fallback only fired on null, never on throw). The parser now validates every field against the message end, caps varint length, and keeps fields read so far on truncation. parseDriverLocation also runCatches both formats, and the lyftStr/lyftLong/lyftDbl helpers plus LyftCardTokenizer's jsonObject/jsonArray accesses use safe casts: kotlinx's typed accessors throw IllegalArgumentException when a server field is an object/array instead of the expected shape. - RideTrackingService.start called startForegroundService after async booking work; backgrounded by then, that throws ForegroundServiceStartNotAllowedException (API 31+). Caught. - LyftTokenStore/UberSession read DataStore .first() bare; a corrupt preferences file throws CorruptionException on every read and crashed every caller. Reads now degrade to signed-out. Verification: ./gradlew :taxi:testDevUnitTest and ./check taxi (run after this commit).
Diff
taxi/src/main/java/com/vayunmathur/taxi/data/lyft/LyftTokenStore.kt
diff --git a/taxi/src/main/java/com/vayunmathur/taxi/data/lyft/LyftTokenStore.kt b/taxi/src/main/java/com/vayunmathur/taxi/data/lyft/LyftTokenStore.ktindex 1cf3ccda56..59175c39dc 100644--- a/taxi/src/main/java/com/vayunmathur/taxi/data/lyft/LyftTokenStore.kt+++ b/taxi/src/main/java/com/vayunmathur/taxi/data/lyft/LyftTokenStore.kt@@ -26,17 +26,25 @@ class LyftTokenStore(private val context: Context) { } } + // A corrupt preferences file throws (CorruptionException/IOException) on every+ // read; that must read as "signed out", not crash every caller.+ private suspend fun prefs() = try {+ context.lyftDataStore.data.first()+ } catch (_: Exception) {+ null+ }+ suspend fun accessToken(): String? =- context.lyftDataStore.data.first()[accessKey]?.takeIf { it.isNotBlank() }+ prefs()?.get(accessKey)?.takeIf { it.isNotBlank() } suspend fun refreshToken(): String? =- context.lyftDataStore.data.first()[refreshKey]?.takeIf { it.isNotBlank() }+ prefs()?.get(refreshKey)?.takeIf { it.isNotBlank() } - suspend fun userId(): String? = context.lyftDataStore.data.first()[userIdKey]+ suspend fun userId(): String? = prefs()?.get(userIdKey) /** Treats the token as expired a minute early so a call never races the expiry. */ suspend fun isExpired(): Boolean {- val expiresAt = context.lyftDataStore.data.first()[expiresAtKey] ?: return true+ val expiresAt = prefs()?.get(expiresAtKey) ?: return true return System.currentTimeMillis() >= expiresAt - EXPIRY_SKEW_MS }
taxi/src/main/java/com/vayunmathur/taxi/data/uber/UberSession.kt
diff --git a/taxi/src/main/java/com/vayunmathur/taxi/data/uber/UberSession.kt b/taxi/src/main/java/com/vayunmathur/taxi/data/uber/UberSession.ktindex eb267b2e46..846acad223 100644--- a/taxi/src/main/java/com/vayunmathur/taxi/data/uber/UberSession.kt+++ b/taxi/src/main/java/com/vayunmathur/taxi/data/uber/UberSession.kt@@ -24,7 +24,12 @@ class UberSession(private val context: Context) { private val signedInKey = booleanPreferencesKey("signed_in") suspend fun isSignedIn(): Boolean =- context.uberDataStore.data.first()[signedInKey] ?: false+ // A corrupt preferences file throws on read; that reads as signed out.+ try {+ context.uberDataStore.data.first()[signedInKey] ?: false+ } catch (_: Exception) {+ false+ } suspend fun setSignedIn(value: Boolean) { context.uberDataStore.edit { it[signedInKey] = value }
taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftCardTokenizer.kt
diff --git a/taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftCardTokenizer.kt b/taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftCardTokenizer.ktindex 3986aa5acc..48a42f83a6 100644--- a/taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftCardTokenizer.kt+++ b/taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftCardTokenizer.kt@@ -10,8 +10,7 @@ import javax.net.ssl.SSLSocketFactory import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.buildJsonObject-import kotlinx.serialization.json.jsonArray-import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.put import kotlinx.serialization.json.putJsonObject @@ -98,7 +97,7 @@ internal class LyftCardTokenizer( fun parseConfigJson(raw: String): TokenizerConfig? { val root = runCatching { json.parseToJsonElement(raw) }.getOrNull() as? JsonObject ?: return null- val strategies = root["strategies"]?.jsonArray?.mapNotNull { it as? JsonObject }+ val strategies = (root["strategies"] as? JsonArray)?.mapNotNull { it as? JsonObject } ?: return null strategies.firstNotNullOfOrNull(::setupIntentConfig)?.let { return it } strategies.firstNotNullOfOrNull { s: JsonObject ->@@ -204,7 +203,7 @@ internal class LyftCardTokenizer( }.getOrElse { return TokenizeResult.Err("Stripe SetupIntent request failed: ${it.message}") } val root = runCatching { json.parseToJsonElement(resp.text) as? JsonObject }.getOrNull() if (!resp.isSuccess) {- val msg = root?.get("error")?.jsonObject?.lyftStr("message")+ val msg = (root?.get("error") as? JsonObject)?.lyftStr("message") ?: "Stripe HTTP ${resp.status}: ${resp.text.take(ERROR_BODY_PREVIEW_MAX)}" return TokenizeResult.Err(msg) }@@ -245,7 +244,7 @@ internal class LyftCardTokenizer( }.getOrElse { return TokenizeResult.Err("Stripe request failed: ${it.message}") } val root = runCatching { json.parseToJsonElement(resp.text) as? JsonObject }.getOrNull() if (!resp.isSuccess) {- val msg = root?.get("error")?.jsonObject?.lyftStr("message")+ val msg = (root?.get("error") as? JsonObject)?.lyftStr("message") ?: "Stripe HTTP ${resp.status}: ${resp.text.take(ERROR_BODY_PREVIEW_MAX)}" return TokenizeResult.Err(msg) }@@ -295,14 +294,14 @@ internal class LyftCardTokenizer( }.getOrElse { return TokenizeResult.Err("Braintree request failed: ${it.message}") } val root = runCatching { json.parseToJsonElement(resp.text) as? JsonObject }.getOrNull() // Braintree GraphQL returns 200 with a non-empty `errors` array on failure.- val errors = root?.get("errors")?.jsonArray+ val errors = root?.get("errors") as? JsonArray if (!resp.isSuccess || !errors.isNullOrEmpty()) {- val msg = errors?.firstOrNull()?.jsonObject?.lyftStr("message")+ val msg = (errors?.firstOrNull() as? JsonObject)?.lyftStr("message") ?: "Braintree HTTP ${resp.status}: ${resp.text.take(ERROR_BODY_PREVIEW_MAX)}" return TokenizeResult.Err(msg) }- val nonce = root?.get("data")?.jsonObject- ?.get("tokenizeCreditCard")?.jsonObject+ val dataObj = root?.get("data") as? JsonObject+ val nonce = (dataObj?.get("tokenizeCreditCard") as? JsonObject) ?.lyftStr("token") ?: return TokenizeResult.Err("Braintree returned no nonce") Log.dev(TAG, "Braintree tokenized ••${card.last4} -> nonce ${nonce.take(NONCE_LOG_PREFIX_LENGTH)}…")@@ -324,7 +323,7 @@ internal class LyftCardTokenizer( val obj = runCatching { json.parseToJsonElement(raw) as? JsonObject }.getOrNull() ?: return null val fingerprint = obj.lyftStr("authorizationFingerprint") ?: return null- val url = obj["graphQL"]?.jsonObject?.lyftStr("url")+ val url = (obj["graphQL"] as? JsonObject)?.lyftStr("url") ?: "https://payments.braintree-api.com/graphql" return url to fingerprint }
taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftProto.kt
diff --git a/taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftProto.kt b/taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftProto.ktindex 88fb2e31c4..f812fec929 100644--- a/taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftProto.kt+++ b/taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftProto.kt@@ -13,33 +13,52 @@ internal class ProtoMessage(private val buf: ByteArray, start: Int, private val private val ranges = HashMap<Int, MutableList<IntArray>>() init {+ // The buffer is a server response: every length/offset below is untrusted.+ // A truncated or lying field stops the parse with whatever was read so far+ // instead of throwing ArrayIndexOutOfBounds out of the accessors later. var p = start- loop@ while (p < end) {- val (tag, afterTag) = readVarint(buf, p)- p = afterTag- val field = (tag ushr TAG_FIELD_SHIFT).toInt()- when ((tag and WIRE_TYPE_MASK).toInt()) {- WIRE_VARINT -> {- val (v, np) = readVarint(buf, p); p = np- varints.getOrPut(field) { mutableListOf() }.add(v)- }- WIRE_FIXED64 -> {- var v = 0L- for (i in 0 until FIXED64_BYTES) {- v = v or ((buf[p + i].toLong() and BYTE_MASK) shl (BITS_PER_BYTE * i))+ var malformed = false+ try {+ while (p < end && !malformed) {+ val (tag, afterTag) = readVarint(buf, p)+ p = afterTag+ val field = (tag ushr TAG_FIELD_SHIFT).toInt()+ when ((tag and WIRE_TYPE_MASK).toInt()) {+ WIRE_VARINT -> {+ val (v, np) = readVarint(buf, p); p = np+ varints.getOrPut(field) { mutableListOf() }.add(v) }- p += FIXED64_BYTES- fixed64.getOrPut(field) { mutableListOf() }.add(v)- }- WIRE_LENGTH_DELIMITED -> {- val (len, np) = readVarint(buf, p); p = np- val s = p; val e = p + len.toInt()- ranges.getOrPut(field) { mutableListOf() }.add(intArrayOf(s, e))- p = e+ WIRE_FIXED64 -> {+ if (p + FIXED64_BYTES > end) {+ malformed = true+ } else {+ var v = 0L+ for (i in 0 until FIXED64_BYTES) {+ v = v or ((buf[p + i].toLong() and BYTE_MASK) shl (BITS_PER_BYTE * i))+ }+ p += FIXED64_BYTES+ fixed64.getOrPut(field) { mutableListOf() }.add(v)+ }+ }+ WIRE_LENGTH_DELIMITED -> {+ val (len, np) = readVarint(buf, p); p = np+ if (len < 0 || len > (end - p).toLong()) {+ malformed = true+ } else {+ val s = p; val e = p + len.toInt()+ ranges.getOrPut(field) { mutableListOf() }.add(intArrayOf(s, e))+ p = e+ }+ }+ WIRE_FIXED32 -> {+ if (p + FIXED32_BYTES > end) malformed = true else p += FIXED32_BYTES+ }+ // Unknown/invalid wire type: stop rather than misread.+ else -> malformed = true }- WIRE_FIXED32 -> p += FIXED32_BYTES- else -> break@loop // unknown/invalid wire type: stop rather than misread }+ } catch (_: IndexOutOfBoundsException) {+ // Truncated varint at the buffer end; keep the fields read so far. } } @@ -86,16 +105,20 @@ internal class ProtoMessage(private val buf: ByteArray, start: Int, private val private const val VARINT_PAYLOAD_BITS = 7 private const val VARINT_PAYLOAD_MASK = 0x7f private const val VARINT_CONTINUATION = 0x80+ private const val MAX_VARINT_SHIFT = 63 fun readVarint(buf: ByteArray, from: Int): Pair<Long, Int> { var p = from var shift = 0 var result = 0L while (true) {+ if (p >= buf.size) throw IndexOutOfBoundsException("varint past end") val b = buf[p++].toInt() and BYTE_MASK.toInt() result = result or ((b and VARINT_PAYLOAD_MASK).toLong() shl shift) if (b < VARINT_CONTINUATION) break shift += VARINT_PAYLOAD_BITS+ // A 64-bit varint is at most 10 bytes; a longer run is malformed.+ if (shift > MAX_VARINT_SHIFT) throw IndexOutOfBoundsException("varint too long") } return result to p }
taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftRideParser.kt
diff --git a/taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftRideParser.kt b/taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftRideParser.ktindex 877c1b5ffe..47d063f7ab 100644--- a/taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftRideParser.kt+++ b/taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftRideParser.kt@@ -10,6 +10,7 @@ import com.vayunmathur.taxi.data.RideStopInfo import com.vayunmathur.taxi.data.VehicleInfo import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.booleanOrNull import kotlinx.serialization.json.contentOrNull import kotlinx.serialization.json.doubleOrNull@@ -123,7 +124,13 @@ internal class LyftRideParser(private val json: Json) { val loc = (root["location"] as? JsonObject) ?: root return toDriverLocationJson(loc) }- return if (isProto) (proto() ?: asJson()) else (asJson() ?: proto())+ // Neither format may throw into the tracking poll loop: a malformed+ // driver-location body is "no location yet", not a crash.+ return if (isProto) {+ (runCatching { proto() }.getOrNull() ?: runCatching { asJson() }.getOrNull())+ } else {+ (runCatching { asJson() }.getOrNull() ?: runCatching { proto() }.getOrNull())+ } } fun toDriverLocationJson(o: JsonObject): DriverLocation? {@@ -244,8 +251,13 @@ internal class LyftRideParser(private val json: Json) { } } -internal fun JsonObject.lyftStr(key: String) = this[key]?.jsonPrimitive?.contentOrNull+// (this[key] as? JsonPrimitive): the typed accessor throws IllegalArgumentException+// when a server field is an object/array instead of a scalar.+internal fun JsonObject.lyftStr(key: String) =+ (this[key] as? JsonPrimitive)?.contentOrNull -internal fun JsonObject.lyftLong(key: String) = this[key]?.jsonPrimitive?.longOrNull+internal fun JsonObject.lyftLong(key: String) =+ (this[key] as? JsonPrimitive)?.longOrNull -internal fun JsonObject.lyftDbl(key: String) = this[key]?.jsonPrimitive?.doubleOrNull+internal fun JsonObject.lyftDbl(key: String) =+ (this[key] as? JsonPrimitive)?.doubleOrNull
taxi/src/main/java/com/vayunmathur/taxi/notifications/RideTrackingService.kt
diff --git a/taxi/src/main/java/com/vayunmathur/taxi/notifications/RideTrackingService.kt b/taxi/src/main/java/com/vayunmathur/taxi/notifications/RideTrackingService.ktindex f3969c7680..49cb343563 100644--- a/taxi/src/main/java/com/vayunmathur/taxi/notifications/RideTrackingService.kt+++ b/taxi/src/main/java/com/vayunmathur/taxi/notifications/RideTrackingService.kt@@ -170,7 +170,14 @@ class RideTrackingService : Service() { if (rideId.isNullOrBlank()) return val intent = Intent(context, RideTrackingService::class.java) .putExtra(EXTRA_RIDE_ID, rideId)- context.startForegroundService(intent)+ // Called after async booking work: the app may no longer be+ // foreground-eligible, and startForegroundService then throws+ // ForegroundServiceStartNotAllowedException (API 31+).+ try {+ context.startForegroundService(intent)+ } catch (e: IllegalStateException) {+ Log.error(TAG, "cannot start ride tracking from background", e)+ } } fun stop(context: Context) {