Modern Apps git

← Modern-Apps.git

network: bound text body reads to fail fast instead of OOM (#657)

Commit
2861ab0d2bbe09335f4727abd70503a063074e49
Author
vayun-mathur <[email protected]>
When
2026-10-13 23:58 UTC (1 month ago)
Parents
151e94f

Diff

library/network/src/main/java/com/vayunmathur/library/network/HttpUrlEngine.kt
diff --git a/library/network/src/main/java/com/vayunmathur/library/network/HttpUrlEngine.kt b/library/network/src/main/java/com/vayunmathur/library/network/HttpUrlEngine.ktindex 31c278ccd8..a5095cca39 100644--- a/library/network/src/main/java/com/vayunmathur/library/network/HttpUrlEngine.kt+++ b/library/network/src/main/java/com/vayunmathur/library/network/HttpUrlEngine.kt@@ -51,6 +51,13 @@ internal object HttpUrlEngine {      */     private const val MAX_PRESIZE = 1L * 1024 * 1024 +    /**+     * Hard cap on bodies decoded to [String] (see [readBodyText]). 16 MB of UTF-8 decodes to at+     * most ~32 MB of chars โ€” comfortably inside the heap โ€” while a runaway 200 MB+ response like+     * the one behind #657 fails fast instead of OOMing mid-read. Normal API bodies are kilobytes.+     */+    const val MAX_TEXT_BODY_BYTES = 16L * 1024 * 1024+     private val EMPTY_BYTES = ByteArray(0)      data class InternalResult(@@ -87,6 +94,10 @@ internal object HttpUrlEngine {     /** Read failure carrying how far the body got, so the caller can name the endpoint. */     class BodyReadException(val bytesRead: Long, cause: Throwable) : IOException(cause) +    /** Limit breach carrying how far the body got and the cap it hit. */+    class BodyTooLargeException(val bytesRead: Long, val maxBytes: Long) :+        IOException("Response body of at least $bytesRead bytes exceeds limit of $maxBytes bytes")+     fun openConnection(         urlString: String,         method: String,@@ -363,14 +374,18 @@ internal object HttpUrlEngine {      * size; otherwise fixed-size segments accumulate and a single exact-size array is assembled at      * the end. A header that over- or under-states the real length is tolerated, not trusted.      *+     * [maxBytes] caps the read, counted as bytes arrive so a lying or absent Content-Length+     * cannot defeat it; null (the default) preserves the historical unbounded byte path.+     *      * Pure in its arguments so it can be unit-tested without a network or a Context.      */     fun drainFully(         input: InputStream,         contentLengthHint: Long?,         isIdentityEncoding: Boolean,+        maxBytes: Long? = null,     ): ByteArray {-        val reader = BodyReader(input)+        val reader = BodyReader(input, maxBytes)         // Content-Length describes the encoded body, so it is only a size for identity encoding.         val hint = if (isIdentityEncoding) contentLengthHint else null         var presized: ByteArray? = null@@ -424,10 +439,17 @@ internal object HttpUrlEngine {     }      /** Fills caller's buffer from [input], tracking bytes read and naming read failures. */-    private class BodyReader(private val input: InputStream) {+    private class BodyReader(private val input: InputStream, private val maxBytes: Long? = null) {         var bytesRead = 0L             private set +        /** Accounts [n] fresh bytes, failing fast once a set cap is exceeded. */+        private fun account(n: Int) {+            bytesRead += n+            val cap = maxBytes+            if (cap != null && bytesRead > cap) throw BodyTooLargeException(bytesRead, cap)+        }+         // Fills target from [from] until full or EOF; returns how much of it is populated.         fun fill(target: ByteArray, from: Int): Int {             var used = from@@ -439,7 +461,7 @@ internal object HttpUrlEngine {                 }                 if (n < 0) break                 used += n-                bytesRead += n+                account(n)             }             return used         }@@ -464,7 +486,7 @@ internal object HttpUrlEngine {                 throw BodyReadException(bytesRead, e)             }             if (lead < 0) return false-            bytesRead += 1+            account(1)             val segment = ByteArray(SEGMENT_SIZE)             segment[0] = lead.toByte()             val used = fill(segment, 1)@@ -488,6 +510,29 @@ internal object HttpUrlEngine {         )     } +    /**+     * [drainFully] decoded as UTF-8, capped at [maxBytes] wire bytes.+     *+     * The bounded replacement for `reader.readText()` on the paths that still have to return a+     * whole body as [String]: the cap is counted during the read, never trusted from+     * Content-Length, and a breach names the endpoint with bytes read instead of OOMing โ€” the+     * unbounded `readText()` behind #657 grew a StringWriter until the 256 MB heap gave out.+     */+    fun readBodyText(response: OpenResponse, maxBytes: Long = MAX_TEXT_BODY_BYTES): String = try {+        drainFully(response.stream, response.contentLength, response.isIdentityEncoding, maxBytes)+            .toString(Charsets.UTF_8)+    } catch (e: BodyTooLargeException) {+        throw IOException(+            "Response body from ${response.finalUrl} exceeds $maxBytes bytes after ${e.bytesRead} bytes",+            e,+        )+    } catch (e: BodyReadException) {+        throw IOException(+            "Failed to read response body from ${response.finalUrl} after ${e.bytesRead} bytes",+            e,+        )+    }+     suspend fun internalExecute(         url: String,         method: String,
library/network/src/main/java/com/vayunmathur/library/network/NetworkClient.kt
diff --git a/library/network/src/main/java/com/vayunmathur/library/network/NetworkClient.kt b/library/network/src/main/java/com/vayunmathur/library/network/NetworkClient.ktindex 5de4933285..1a28fea3f2 100644--- a/library/network/src/main/java/com/vayunmathur/library/network/NetworkClient.kt+++ b/library/network/src/main/java/com/vayunmathur/library/network/NetworkClient.kt@@ -255,8 +255,10 @@ object NetworkClient {                 sslSocketFactory = resolveFactory(sslSocketFactory, useSystemTrust),             )             response.use {+                // Bounded like the byte path (#582): readText() grew a StringWriter with no cap+                // until the heap gave out (#657), so count bytes during the read and fail fast.                 val text = try {-                    it.stream.reader(Charsets.UTF_8).buffered().readText()+                    HttpUrlEngine.readBodyText(it)                 } catch (e: java.io.IOException) {                     throw java.io.IOException("Failed to read response body from ${it.finalUrl}", e)                 }
library/network/src/test/java/com/vayunmathur/library/network/HttpUrlEngineBodyTest.kt
diff --git a/library/network/src/test/java/com/vayunmathur/library/network/HttpUrlEngineBodyTest.kt b/library/network/src/test/java/com/vayunmathur/library/network/HttpUrlEngineBodyTest.ktindex a269170fe9..488eed3d24 100644--- a/library/network/src/test/java/com/vayunmathur/library/network/HttpUrlEngineBodyTest.kt+++ b/library/network/src/test/java/com/vayunmathur/library/network/HttpUrlEngineBodyTest.kt@@ -126,4 +126,78 @@ class HttpUrlEngineBodyTest {         }         assertEquals(300L, e.bytesRead)     }++    @Test+    fun uncapped_byte_path_stays_unbounded() {+        // The default (byte) path keeps its historical behavior: full body, no cap.+        val data = bytes(segment * 2 + 5)+        assertContentEquals(data, HttpUrlEngine.drainFully(trickle(data, 4096), null, true))+    }++    @Test+    fun capped_read_fails_fast_once_past_the_cap() {+        val data = bytes(10_000)+        val e = assertFailsWith<HttpUrlEngine.BodyTooLargeException> {+            HttpUrlEngine.drainFully(trickle(data, 512), data.size.toLong(), true, maxBytes = 1024)+        }+        assertTrue(e.bytesRead > 1024, "cap must be counted during the read, got ${e.bytesRead}")+        assertEquals(1024L, e.maxBytes)+    }++    @Test+    fun cap_is_counted_not_trusted_from_content_length() {+        // A lying small Content-Length must not defeat the cap: the excess still trips it.+        val data = bytes(10_000)+        assertFailsWith<HttpUrlEngine.BodyTooLargeException> {+            HttpUrlEngine.drainFully(trickle(data, 512), 100L, true, maxBytes = 1024)+        }+    }++    @Test+    fun body_under_the_cap_reads_exact() {+        val data = bytes(5000)+        assertContentEquals(+            data,+            HttpUrlEngine.drainFully(trickle(data, 137), data.size.toLong(), true, maxBytes = 8192),+        )+    }++    @Test+    fun read_body_text_names_endpoint_on_breach() {+        val data = bytes(10_000)+        val response = HttpUrlEngine.OpenResponse(+            status = 200,+            statusMessage = "OK",+            headers = emptyMap(),+            finalUrl = "https://example.test/api/v1/deals",+            stream = trickle(data, 512),+            hasStream = true,+            contentLength = null,+            isIdentityEncoding = true,+        )+        val e = assertFailsWith<IOException> {+            response.use { HttpUrlEngine.readBodyText(it, maxBytes = 1024) }+        }+        assertTrue(+            e.message!!.contains("https://example.test/api/v1/deals"),+            "breach must name the URL, got: ${e.message}",+        )+    }++    @Test+    fun read_body_text_decodes_small_bodies() {+        val text = "hello, deals"+        val payload = text.toByteArray(Charsets.UTF_8)+        val response = HttpUrlEngine.OpenResponse(+            status = 200,+            statusMessage = "OK",+            headers = emptyMap(),+            finalUrl = "https://example.test/api/v1/deals",+            stream = ByteArrayInputStream(payload),+            hasStream = true,+            contentLength = payload.size.toLong(),+            isIdentityEncoding = true,+        )+        assertEquals(text, response.use { HttpUrlEngine.readBodyText(it) })+    } }