Modern Apps git

← Modern-Apps.git

pdf: bound the open-time read so large files fail cleanly (#951)

Commit
d2a238b750743dbc9bac8111a522e94d35ccdc0a
Author
Vayun Mathur <[email protected]>
When
2026-11-30 18:52 UTC (5 days ago)
Parents
efb59c5
Opening a large PDF crashed before the first page: SafePdfDocument.open
did an unbounded whole-file readBytes() into one ByteArray, and any
failure immediately read the whole file a second time just to probe
encryption. Two multi-hundred-MB allocations on top of the native
copy could kill the process outright. A page-count-scaling hasRedactions
walk also ran unconditionally at open.

The open path now reads the document bytes exactly once through a
chunked, capped reader (MAX_PDF_BYTES, 256 MiB): the reader aborts the
moment the cap is crossed without consuming the rest of the stream,
provider-declared oversize is rejected before the stream is opened,
and the buffer is pre-sized from the declared size. The new openOutcome
classifies Opened / NeedsPassword / Failed from that single read, so
password retries also cost one read, and oversized or unreadable input
lands on the existing viewer error state instead of dying mid-allocation.
passwordState and the cut-and-glue append picker use the same bounded
read. Redaction presence is probed lazily once editing starts rather
than at open. Already-bounded paths (image decode budget, page cache,
first render) were audited and left alone.

New SafePdfOpenBoundsTest: byte-exact chunk round-trips, exact-cap and
over-cap behavior (asserting the stream is never materialized whole),
a synthetic 600-page book opening through the real native engine, a
sparse 256 MiB+1 file failing cleanly, outcome classification, and an
over-budget embedded image skipped before allocation.
Verified: :pdf:testDevUnitTest passes (full module suite).

Diff

pdf/AGENTS.md
diff --git a/pdf/AGENTS.md b/pdf/AGENTS.mdindex 8b3cb16767..da30044f0f 100644--- a/pdf/AGENTS.md+++ b/pdf/AGENTS.md@@ -24,6 +24,7 @@ _Install: ./install pdf (dev by default)._ - `util/` holds only `PdfNative` (the Rust engine bridge) โ€” don't add more files there; the capture model is in `data/` - Search-index prewarm at open is page-count gated (`SafePdfDocument.MAX_PREWARM_PAGES`, 256): opening a document never eagerly interprets the whole book; larger documents build the same index lazily on first search - Adobe YCCK (APP14 transform 2) CMYK JPEGs reach the Rust decoder with all four samples in inverted-ink polarity; the CMYK32 arm inverts all four before converting (transform 0 samples are already true ink)+- Opening reads the document bytes once through a chunked, capped read (`SafePdfDocument.MAX_PDF_BYTES`, 256 MiB): oversized or unreadable inputs fail with the viewer error state instead of loading whole into the heap, the same read classifies encryption for the password prompt, and cut-and-glue appends use the same bounded read; redaction presence is probed lazily once editing starts, not at open  ## Key files ### Root โ€” entry + navigation
pdf/src/main/java/com/vayunmathur/pdf/platform/SafePdfDocument.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/platform/SafePdfDocument.kt b/pdf/src/main/java/com/vayunmathur/pdf/platform/SafePdfDocument.ktindex edba22136d..867d3f5001 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/platform/SafePdfDocument.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/platform/SafePdfDocument.kt@@ -4,7 +4,10 @@ import com.vayunmathur.pdf.util.PdfNative  import android.content.Context import android.net.Uri+import android.provider.OpenableColumns import com.vayunmathur.library.log.Log+import java.io.ByteArrayOutputStream+import java.io.InputStream import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext @@ -81,6 +84,20 @@ class SafePdfDocument private constructor(         data class Failed(val reason: String) : PageLoad     } +    /**+     * Outcome of one open attempt, classified from a single bounded read of+     * the document bytes so a failed open never triggers a second full read+     * just to ask whether the file was encrypted.+     */+    sealed interface OpenOutcome {+        /** Opened; carries document. */+        data class Opened(val document: SafePdfDocument) : OpenOutcome+        /** Encrypted: a password is needed ([rejected] if one was tried). */+        data class NeedsPassword(val rejected: Boolean) : OpenOutcome+        /** Unopenable; [notPdf] when the bytes lack a PDF header. */+        data class Failed(val notPdf: Boolean) : OpenOutcome+    }+     /** Decode page [index] (0-based), or `null` if the native render fails. */     suspend fun renderPage(index: Int): SafePdfPage? =         (renderPageResult(index) as? PageLoad.Decoded)?.page@@ -323,33 +340,115 @@ class SafePdfDocument private constructor(          * most a re-render if that page is requested again. The budget can therefore be tight.          */         private const val MAX_CACHED_BYTES = 96L * 1024 * 1024+        /**+         * Largest document the viewer will materialise, in bytes. The native+         * open API takes the whole file as one [ByteArray], so the Kotlin+         * copy plus the native parse must fit alongside the page cache in a+         * phone heap; past this size opening fails cleanly with the viewer's+         * error state instead of dying in an out-of-memory allocation while+         * reading. Reading itself is chunked and aborts the moment the cap+         * is crossed, so an oversized file is never fully loaded.+         */+        internal const val MAX_PDF_BYTES: Long = 256L * 1024 * 1024++        private const val READ_CHUNK_BYTES = 64 * 1024++        /**+         * Read [input] fully in chunks, or return `null` as soon as more+         * than [maxBytes] bytes have been seen (the rest of the stream is+         * never consumed). [expectedSize], when known, pre-sizes the buffer+         * so a large-but-legal file is accumulated in a single allocation+         * instead of a doubling copy.+         */+        internal fun readBoundedBytes(+            input: InputStream,+            maxBytes: Long,+            expectedSize: Long = -1L,+        ): ByteArray? {+            if (maxBytes < 0L) return null+            val initial = if (expectedSize in 1..maxBytes) expectedSize.toInt() else READ_CHUNK_BYTES+            val out = ByteArrayOutputStream(initial)+            val chunk = ByteArray(READ_CHUNK_BYTES)+            var total = 0L+            while (true) {+                val n = input.read(chunk)+                if (n < 0) break+                total += n+                if (total > maxBytes) return null+                out.write(chunk, 0, n)+            }+            return out.toByteArray()+        }++        /** Declared byte size of [uri] when the provider reports one, else -1. */+        private fun declaredSizeBytes(context: Context, uri: Uri): Long = runCatching {+            context.contentResolver.query(uri, arrayOf(OpenableColumns.SIZE), null, null, null)+                ?.use { cursor ->+                    if (cursor.moveToFirst() && !cursor.isNull(0)) cursor.getLong(0) else -1L+                } ?: -1L+        }.getOrDefault(-1L)++        /**+         * The bytes of [uri], read once through [readBoundedBytes]; `null`+         * when unreadable or larger than [maxBytes]. A provider-declared+         * size past the cap is rejected without opening the stream at all.+         */+        internal suspend fun readUriBytes(+            context: Context,+            uri: Uri,+            maxBytes: Long = MAX_PDF_BYTES,+        ): ByteArray? = withContext(Dispatchers.IO) {+            val declared = declaredSizeBytes(context, uri)+            if (declared > maxBytes) return@withContext null+            runCatching {+                context.contentResolver.openInputStream(uri)+                    ?.use { readBoundedBytes(it, maxBytes, declared) }+            }.getOrNull()+        }++        /** True if [bytes] begins like a real PDF (header in the first 1024 bytes). */+        private fun bytesLookLikePdf(bytes: ByteArray): Boolean =+            indexOf(bytes.copyOf(minOf(bytes.size, 1024)), "%PDF-".toByteArray(Charsets.US_ASCII)) >= 0++        /**+         * Open [uri] and classify the outcome from the same bytes: opened,+         * encrypted (password needed/rejected), or failed. This is the+         * viewer's open path โ€” one bounded read per attempt.+         */+        suspend fun openOutcome(+            context: Context,+            uri: Uri,+            password: String? = null,+        ): OpenOutcome = withContext(Dispatchers.IO) {+            if (!PdfNative.isAvailable) return@withContext OpenOutcome.Failed(notPdf = false)+            val bytes = readUriBytes(context, uri)+                ?: return@withContext OpenOutcome.Failed(notPdf = !looksLikePdf(context, uri))+            val handle = if (password == null) {+                PdfNative.openDocument(bytes)+            } else {+                PdfNative.openDocumentWithPassword(bytes, password)+            }+            if (handle != 0L) {+                return@withContext OpenOutcome.Opened(SafePdfDocument(handle, PdfNative.getPageCount(handle)))+            }+            if (PdfNative.pdfPasswordState(bytes) == 1) {+                return@withContext OpenOutcome.NeedsPassword(rejected = password != null)+            }+            OpenOutcome.Failed(notPdf = !bytesLookLikePdf(bytes))+        }+         /**          * Open [uri] as a safe PDF, or return `null` when the native lib is          * unavailable, the bytes can't be read, or parsing fails. Encrypted PDFs          * are opened with [password] (empty by default). Runs off the main thread.          */         suspend fun open(context: Context, uri: Uri, password: String? = null): SafePdfDocument? =-            withContext(Dispatchers.IO) {-                if (!PdfNative.isAvailable) return@withContext null-                val bytes = runCatching {-                    context.contentResolver.openInputStream(uri)?.use { it.readBytes() }-                }.getOrNull() ?: return@withContext null--                val handle = if (password == null) {-                    PdfNative.openDocument(bytes)-                } else {-                    PdfNative.openDocumentWithPassword(bytes, password)-                }-                if (handle == 0L) return@withContext null-                SafePdfDocument(handle, PdfNative.getPageCount(handle))-            }+            (openOutcome(context, uri, password) as? OpenOutcome.Opened)?.document          /** Encryption state of [uri]: 0 none, 1 needs password, 2 unsupported. */         suspend fun passwordState(context: Context, uri: Uri): Int =             withContext(Dispatchers.IO) {-                val bytes = runCatching {-                    context.contentResolver.openInputStream(uri)?.use { it.readBytes() }-                }.getOrNull() ?: return@withContext 0+                val bytes = readUriBytes(context, uri) ?: return@withContext 0                 PdfNative.pdfPasswordState(bytes)             } 
pdf/src/main/java/com/vayunmathur/pdf/ui/CutGlueScreen.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/ui/CutGlueScreen.kt b/pdf/src/main/java/com/vayunmathur/pdf/ui/CutGlueScreen.ktindex cf3e534828..65170b812e 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/ui/CutGlueScreen.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/ui/CutGlueScreen.kt@@ -59,6 +59,7 @@ import com.vayunmathur.library.ui.IconDelete import com.vayunmathur.library.ui.IconSave import com.vayunmathur.pdf.R import com.vayunmathur.pdf.platform.ComposePdfDocument+import com.vayunmathur.pdf.platform.SafePdfDocument import com.vayunmathur.pdf.platform.SafePdfPage import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch@@ -90,9 +91,9 @@ fun CutGlueScreen(onBack: () -> Unit) {         ActivityResultContracts.OpenDocument()     ) { uri: Uri? ->         if (uri != null) scope.launch {-            val bytes = withContext(Dispatchers.IO) {-                runCatching { context.contentResolver.openInputStream(uri)?.use { it.readBytes() } }.getOrNull()-            } ?: return@launch+            // Same bounded read as the viewer open: a huge source PDF is+            // refused instead of being loaded whole into the heap.+            val bytes = SafePdfDocument.readUriBytes(context, uri) ?: return@launch             val added = doc.appendPdf(bytes)             repeat(added) { pageKeys.add(nextKey++.toLong()) }         }
pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerLoad.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerLoad.kt b/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerLoad.ktindex f2788610fa..2ea665c1d8 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerLoad.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerLoad.kt@@ -44,15 +44,19 @@ internal fun rememberSafePdfDocument(      val loadState by produceState<LoadState>(LoadState.Loading, uri, password) {         value = LoadState.Loading-        val doc = SafePdfDocument.open(context, uri, password)-        value = if (doc != null) {-            needsPassword = false-            LoadState.Loaded(doc)-        } else {-            when (SafePdfDocument.passwordState(context, uri)) {-                1 -> { needsPassword = true; pwError = password != null; LoadState.Loading }-                else -> LoadState.Error(notPdf = !SafePdfDocument.looksLikePdf(context, uri))+        // One bounded read classifies opened / encrypted / failed; a failed+        // open no longer re-reads the whole file to ask about encryption.+        value = when (val outcome = SafePdfDocument.openOutcome(context, uri, password)) {+            is SafePdfDocument.OpenOutcome.Opened -> {+                needsPassword = false+                LoadState.Loaded(outcome.document)             }+            is SafePdfDocument.OpenOutcome.NeedsPassword -> {+                needsPassword = true+                pwError = outcome.rejected+                LoadState.Loading+            }+            is SafePdfDocument.OpenOutcome.Failed -> LoadState.Error(notPdf = outcome.notPdf)         }     }     val document = (loadState as? LoadState.Loaded)?.document@@ -82,9 +86,17 @@ internal fun rememberSafePdfDocument(     val outline by produceState(emptyList<SafeOutlineItem>(), document) {         value = document?.outline() ?: emptyList()     }-    // Show the Apply-redactions action only while redaction annotations exist.-    val hasRedactions by produceState(false, state.undoStack.size, state.redoStack.size, state.pageMgrVersion) {-        value = document?.hasRedactions() ?: false+    // Show the Apply-redactions action only while redaction annotations+    // exist. The native check walks every page's annotations, so it runs+    // lazily once editing starts (an explicit user action) instead of+    // scaling open time with the page count; before that the action simply+    // stays hidden. Once probed it keeps refreshing on edit bookkeeping.+    var redactionsProbed by remember(document) { mutableStateOf(false) }+    LaunchedEffect(state.editMode) { if (state.editMode) redactionsProbed = true }+    val hasRedactions by produceState(+        false, redactionsProbed, state.undoStack.size, state.redoStack.size, state.pageMgrVersion,+    ) {+        if (redactionsProbed) value = document?.hasRedactions() ?: false     }      LaunchedEffect(document) {
pdf/src/test/java/com/vayunmathur/pdf/platform/SafePdfOpenBoundsTest.kt
diff --git a/pdf/src/test/java/com/vayunmathur/pdf/platform/SafePdfOpenBoundsTest.kt b/pdf/src/test/java/com/vayunmathur/pdf/platform/SafePdfOpenBoundsTest.ktnew file mode 100644index 0000000000..965a98bef0--- /dev/null+++ b/pdf/src/test/java/com/vayunmathur/pdf/platform/SafePdfOpenBoundsTest.kt@@ -0,0 +1,168 @@+package com.vayunmathur.pdf.platform++import android.content.Context+import android.net.Uri+import androidx.test.core.app.ApplicationProvider+import java.io.ByteArrayInputStream+import java.io.File+import java.io.InputStream+import java.io.RandomAccessFile+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.GraphicsMode++/**+ * Issue #951: opening a large PDF crashed the app. The viewer open path+ * used to materialise the whole file with `readBytes()` (plus a second+ * whole-file read on the failure path to probe encryption). Opening now+ * goes through one chunked, capped read: oversized inputs fail with the+ * viewer's error state instead of an out-of-memory kill, and nothing at+ * open scales unboundedly with file size.+ */+@RunWith(RobolectricTestRunner::class)+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class SafePdfOpenBoundsTest {+    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    /** Generates zero bytes on demand; counts how many were consumed. */+    private class GeneratingInputStream(private val total: Long) : InputStream() {+        var bytesRead: Long = 0+            private set++        override fun read(): Int {+            if (bytesRead >= total) return -1+            bytesRead+++            return 0+        }++        override fun read(b: ByteArray, off: Int, len: Int): Int {+            if (bytesRead >= total) return -1+            val n = minOf(len.toLong(), total - bytesRead).toInt()+            bytesRead += n+            return n+        }+    }++    private fun manyPagePdf(pages: Int): ByteArray {+        val sb = StringBuilder("%PDF-1.4\n")+        val offsets = mutableListOf<Int>()+        fun obj(num: Int, body: String) {+            while (offsets.size < num - 1) offsets.add(0)+            offsets.add(num - 1, sb.length)+            sb.append("$num 0 obj\n$body\nendobj\n")+        }+        val fontObj = 3+        val kids = (0 until pages).joinToString(" ") { "${4 + it * 2} 0 R" }+        obj(1, "<< /Type /Catalog /Pages 2 0 R >>")+        obj(2, "<< /Type /Pages /Kids [$kids] /Count $pages >>")+        obj(fontObj, "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>")+        for (i in 0 until pages) {+            val pageObj = 4 + i * 2+            val contentObj = pageObj + 1+            val content = "BT /F1 12 Tf 72 720 Td (Page $i) Tj ET"+            obj(+                pageObj,+                "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] " ++                    "/Contents $contentObj 0 R /Resources << /Font << /F1 $fontObj 0 R >> >> >>",+            )+            obj(contentObj, "<< /Length ${content.length} >>\nstream\n$content\nendstream")+        }+        val total = 3 + pages * 2+        val xref = sb.length+        sb.append("xref\n0 ${total + 1}\n0000000000 65535 f \n")+        for (n in 1..total) {+            sb.append(offsets[n - 1].toString().padStart(10, '0')).append(" 00000 n \n")+        }+        sb.append("trailer\n<< /Size ${total + 1} /Root 1 0 R >>\nstartxref\n$xref\n%%EOF")+        return sb.toString().toByteArray(Charsets.US_ASCII)+    }++    private fun fileFor(bytes: ByteArray, name: String): Uri {+        val f = File(ctx.cacheDir, name)+        f.writeBytes(bytes)+        return Uri.fromFile(f)+    }++    @Test fun boundedReadRoundTripsContent() {+        for (size in listOf(0, 1, 65_535, 65_536, 65_537, 200_001)) {+            val data = ByteArray(size) { (it % 251).toByte() }+            val read = SafePdfDocument.readBoundedBytes(ByteArrayInputStream(data), maxBytes = 1_000_000)+            assertNotNull(read, "size $size")+            assertTrue(data.contentEquals(read), "size $size must round-trip byte-exact")+        }+    }++    @Test fun boundedReadAtExactCapSucceeds() {+        val cap = 100_000L+        val data = ByteArray(cap.toInt()) { 0x41 }+        val read = SafePdfDocument.readBoundedBytes(ByteArrayInputStream(data), maxBytes = cap)+        assertNotNull(read)+        assertEquals(cap, read.size.toLong())+    }++    @Test fun boundedReadOverCapReturnsNullAndStopsEarly() {+        // A 5 MB logical stream with a 100 KB cap: the reader must refuse+        // after at most one chunk past the cap, never consuming the stream.+        val stream = GeneratingInputStream(total = 5_000_000)+        val read = SafePdfDocument.readBoundedBytes(stream, maxBytes = 100_000)+        assertNull(read)+        assertTrue(+            stream.bytesRead <= 100_000 + 65_536,+            "reader consumed ${stream.bytesRead} bytes for a 100 KB cap",+        )+    }++    @Test fun openOutcomeClassifiesFromOneRead() { runBlocking {+        val garbage = SafePdfDocument.openOutcome(ctx, fileFor("hello".toByteArray(), "bounds-plain.pdf"))+        assertTrue(garbage is SafePdfDocument.OpenOutcome.Failed)+        assertTrue(garbage.notPdf)++        val fakeHeader = SafePdfDocument.openOutcome(+            ctx, fileFor("%PDF-1.4\nnot really a pdf".toByteArray(), "bounds-fake.pdf"),+        )+        assertTrue(fakeHeader is SafePdfDocument.OpenOutcome.Failed)+        assertFalse(fakeHeader.notPdf)++        val opened = SafePdfDocument.openOutcome(ctx, fileFor(manyPagePdf(3), "bounds-small.pdf"))+        assertTrue(opened is SafePdfDocument.OpenOutcome.Opened)+        opened.document.close()+    } }++    @Test fun openManyPageBookThroughBoundedPath() { runBlocking {+        val pages = 600+        val doc = SafePdfDocument.open(ctx, fileFor(manyPagePdf(pages), "bounds-book.pdf"))+        assertNotNull(doc)+        try {+            assertEquals(pages, doc.pageCount)+            // Page-count-scaled eager work stays gated at this size too.+            assertFalse(SafePdfDocument.shouldPrewarmSearch(doc.pageCount))+            assertNotNull(doc.renderPage(0))+            assertNotNull(doc.renderPage(pages - 1))+        } finally {+            doc.close()+        }+    } }++    @Test fun oversizedFileFailsCleanlyInsteadOfLoading() { runBlocking {+        val f = File(ctx.cacheDir, "bounds-huge.pdf")+        RandomAccessFile(f, "rw").use { it.setLength(SafePdfDocument.MAX_PDF_BYTES + 1) }+        assertNull(SafePdfDocument.open(ctx, Uri.fromFile(f)))+        val outcome = SafePdfDocument.openOutcome(ctx, Uri.fromFile(f))+        assertTrue(outcome is SafePdfDocument.OpenOutcome.Failed)+    } }++    @Test fun hugeEmbeddedImagePayloadIsSkippedNotDecoded() {+        // Format 1 is the JPEG passthrough; a payload past the image budget+        // is skipped before any bitmap allocation is attempted.+        val payload = ByteArray(SafePdfImages.MAX_IMAGE_DATA_BYTES + 1)+        assertNull(SafePdfImages.decodeBitmap(8_000, 8_000, 1, payload))+        assertTrue(SafePdfImages.imageTooLarge(payload.size))+    }+}