Modern Apps git

← Modern-Apps.git

office: fix crashes from hostile docs, sync ops and missing native lib

Commit
9fdbb129ff2f911a75cde05305ea203dc1f5967c
Author
Vayun Mathur <[email protected]>
When
2026-11-19 02:32 UTC (17 days ago)
Parents
6e2098f
Six crash paths:

- Live sync: applySignedOp decoded a collaborator-supplied
  sig with unguarded Base64.decode, and OfficeSync.getKey
  decoded the relay-stored key bundle the same way. A
  malformed sig/bundle threw IllegalArgumentException in an
  unguarded viewModelScope launch. Both now runCatching-
  decode and reject/return null.
- DrawingView indexed doc.pages[currentPage] with a
  remember-only page index; a live CRDT merge replacing the
  drawing with fewer pages threw IndexOutOfBoundsException
  in composition. Clamp per composition, mirroring
  PresentationView. Same stale-index fix in SlideshowDialog
  (slides[index] after slides shrink via merge).
- ExcelFormula.shiftSegment called toInt() on row digits the
  CELL regex leaves unbounded; =A9999999999 in an imported
  sheet threw NumberFormatException on Fill Down (the shift
  call is outside the surrounding try-catch). toIntOrNull and
  leave overflowing refs unshifted.
- OdfParserInline repeated text:c spaces uncapped; a hostile
  .odt with text:c=2000000000 OOMed (an Error, escaping the
  caller's catch (Exception)). Cap at MAX_SPACES 4096 like
  OdfParserSheet (constant widened private -> internal).
- OfficeNative loaded office_engine in init with no fallback:
  UnsatisfiedLinkError became ExceptionInInitializerError in
  SpreadsheetView composition. Load defensively with an
  isAvailable flag; createWorkbook returns 0 when unavailable
  and rememberNativeSpreadsheetValues falls back to literal
  cell text (the fallback the SpreadsheetValues indirection
  exists for).

Verification: ./gradlew :office:testDevUnitTest and
:photos/:passwords:testDevUnitTest (office/photos pass;
passwords needed its own fix, in its commit),
./check photos office passwords (exit 0).

Diff

office/src/main/java/com/vayunmathur/office/data/odf/ExcelFormula.kt
diff --git a/office/src/main/java/com/vayunmathur/office/data/odf/ExcelFormula.kt b/office/src/main/java/com/vayunmathur/office/data/odf/ExcelFormula.ktindex ae6d048a63..a62f8274c6 100644--- a/office/src/main/java/com/vayunmathur/office/data/odf/ExcelFormula.kt+++ b/office/src/main/java/com/vayunmathur/office/data/odf/ExcelFormula.kt@@ -85,8 +85,10 @@ internal object ExcelFormula {         val rowAbs = m.groupValues[REF_COL_ABS] == "$"         val col = if (colAbs) m.groupValues[REF_COL] else indexToCol(             (colToIndex(m.groupValues[REF_COL]) + dCol).coerceAtLeast(0))-        val row = if (rowAbs) m.groupValues[REF_ROW].toInt() else {-            (m.groupValues[REF_ROW].toInt() + dRow).coerceAtLeast(1)+        // Row digits are unbounded in the regex; an overflowing row is left unshifted.+        val rowNum = m.groupValues[REF_ROW].toIntOrNull() ?: return@replace m.value+        val row = if (rowAbs) rowNum else {+            (rowNum + dRow).coerceAtLeast(1)         }         "${m.groupValues[REF_SHEET]}$col${m.groupValues[REF_COL_ABS]}$row"     }
office/src/main/java/com/vayunmathur/office/data/odf/OdfParserInline.kt
diff --git a/office/src/main/java/com/vayunmathur/office/data/odf/OdfParserInline.kt b/office/src/main/java/com/vayunmathur/office/data/odf/OdfParserInline.ktindex adff65c65f..a428c277e8 100644--- a/office/src/main/java/com/vayunmathur/office/data/odf/OdfParserInline.kt+++ b/office/src/main/java/com/vayunmathur/office/data/odf/OdfParserInline.kt@@ -134,7 +134,8 @@ private fun OdfParser.applyInlineStyleTag(             acc.currentHref = getAttr(parser, "href")         }         "tab" -> acc.textBuffer.append("\t")-        "s" -> acc.textBuffer.append(" ".repeat((getAttr(parser, "c")?.toIntOrNull() ?: 1)))+        // Cap like OdfParserSheet: a hostile text:c must not OOM the parser.+        "s" -> acc.textBuffer.append(" ".repeat((getAttr(parser, "c")?.toIntOrNull() ?: 1).coerceIn(0, MAX_SPACES)))         "line-break" -> acc.textBuffer.append("\n")         "frame" -> {             acc.pendingFrameW = parseDimension(getAttr(parser, "width"))
office/src/main/java/com/vayunmathur/office/data/odf/OdfParserSheet.kt
diff --git a/office/src/main/java/com/vayunmathur/office/data/odf/OdfParserSheet.kt b/office/src/main/java/com/vayunmathur/office/data/odf/OdfParserSheet.ktindex 985a567e3d..19dda88794 100644--- a/office/src/main/java/com/vayunmathur/office/data/odf/OdfParserSheet.kt+++ b/office/src/main/java/com/vayunmathur/office/data/odf/OdfParserSheet.kt@@ -18,7 +18,7 @@ import org.xmlpull.v1.XmlPullParser private const val MAX_REPEATED_ROWS = 200 private const val MAX_REPEATED_COLS = 1000 private const val MAX_REPEATED_CELLS = 100-private const val MAX_SPACES = 4096+internal const val MAX_SPACES = 4096  internal fun OdfParser.parseSpreadsheet(     xml: String, styles: Map<String, StyleInfo>, numberStyles: Map<String, OdfNumberFormat>,
office/src/main/java/com/vayunmathur/office/platform/OfficeViewModelSyncA.kt
diff --git a/office/src/main/java/com/vayunmathur/office/platform/OfficeViewModelSyncA.kt b/office/src/main/java/com/vayunmathur/office/platform/OfficeViewModelSyncA.ktindex 173865fafd..ca0c52d0e8 100644--- a/office/src/main/java/com/vayunmathur/office/platform/OfficeViewModelSyncA.kt+++ b/office/src/main/java/com/vayunmathur/office/platform/OfficeViewModelSyncA.kt@@ -155,7 +155,9 @@ internal suspend fun OfficeViewModel.applySignedOp(tree: DocumentTreeCrdt, plain         OfficeRoles.canEdit(currentMembers[so.author] ?: OfficeRoles.VIEWER)     if (!allowed) return false     val authorKey = memberKey(so.author) ?: return false-    if (!OfficeSync.verify(authorKey, so.ops.encodeToByteArray(), Base64.decode(so.sig))) return false+    // Collaborator-supplied sig may not be Base64; a bad sig is a reject, not a crash.+    val sigBytes = runCatching { Base64.decode(so.sig) }.getOrNull() ?: return false+    if (!OfficeSync.verify(authorKey, so.ops.encodeToByteArray(), sigBytes)) return false     tree.applyJson(so.ops)     return true }
office/src/main/java/com/vayunmathur/office/sync/OfficeSync.kt
diff --git a/office/src/main/java/com/vayunmathur/office/sync/OfficeSync.kt b/office/src/main/java/com/vayunmathur/office/sync/OfficeSync.ktindex da05b49d74..838335a5b8 100644--- a/office/src/main/java/com/vayunmathur/office/sync/OfficeSync.kt+++ b/office/src/main/java/com/vayunmathur/office/sync/OfficeSync.kt@@ -76,7 +76,8 @@ object OfficeSync {      suspend fun getKey(id: String): ByteArray? {         val r = raw("/getkey", IdReq(id)) ?: return null-        return if (r.status == HTTP_OK) Base64.decode(r.body) else null+        // Relay stores registrations verbatim; a malformed bundle must not crash the caller.+        return if (r.status == HTTP_OK) runCatching { Base64.decode(r.body) }.getOrNull() else null     }      fun newDocumentKey(): ByteArray = E2ee.newContentKey()
office/src/main/java/com/vayunmathur/office/ui/DrawingViews.kt
diff --git a/office/src/main/java/com/vayunmathur/office/ui/DrawingViews.kt b/office/src/main/java/com/vayunmathur/office/ui/DrawingViews.ktindex 200854261c..8e4890479d 100644--- a/office/src/main/java/com/vayunmathur/office/ui/DrawingViews.kt+++ b/office/src/main/java/com/vayunmathur/office/ui/DrawingViews.kt@@ -48,6 +48,8 @@ fun DrawingView(doc: OdfDocument.Drawing) {         stringResource(R.string.empty_drawing),         modifier = Modifier.padding(16.dp)); return }     var currentPage by remember { mutableIntStateOf(0) }+    // A live merge may replace the drawing with fewer pages while paged to the end.+    currentPage = currentPage.coerceIn(0, doc.pages.size - 1)     Column(modifier = Modifier.fillMaxSize()) {         LazyColumn(modifier = Modifier.weight(1f).padding(8.dp)) { item { SlideCard(doc.pages[currentPage]) } }         if (doc.pages.size > 1) Surface(tonalElevation = 3.dp) {
office/src/main/java/com/vayunmathur/office/ui/PresentationViews.kt
diff --git a/office/src/main/java/com/vayunmathur/office/ui/PresentationViews.kt b/office/src/main/java/com/vayunmathur/office/ui/PresentationViews.ktindex 0486b21aed..1c14a2c7ad 100644--- a/office/src/main/java/com/vayunmathur/office/ui/PresentationViews.kt+++ b/office/src/main/java/com/vayunmathur/office/ui/PresentationViews.kt@@ -185,6 +185,8 @@ private fun SlideshowDialog(     onSlideChange: (Int) -> Unit,     onDismiss: () -> Unit) {     var index by remember { mutableIntStateOf(startIndex.coerceIn(0, slides.size - 1)) }+    // Slides may shrink via a live merge while the slideshow is open.+    if (slides.isNotEmpty()) index = index.coerceIn(0, slides.size - 1)     Dialog(         onDismissRequest = { onSlideChange(index); onDismiss() },         properties = DialogProperties(usePlatformDefaultWidth = false)) {
office/src/main/java/com/vayunmathur/office/ui/SpreadsheetValues.kt
diff --git a/office/src/main/java/com/vayunmathur/office/ui/SpreadsheetValues.kt b/office/src/main/java/com/vayunmathur/office/ui/SpreadsheetValues.ktindex a31814c71f..2492611e88 100644--- a/office/src/main/java/com/vayunmathur/office/ui/SpreadsheetValues.kt+++ b/office/src/main/java/com/vayunmathur/office/ui/SpreadsheetValues.kt@@ -19,6 +19,17 @@ interface SpreadsheetValues {  @Composable fun rememberNativeSpreadsheetValues(doc: OdfDocument.Spreadsheet): SpreadsheetValues {+    if (!OfficeNative.isAvailable) {+        // No native engine on this ABI: show literal cell text instead of crashing.+        return remember(doc) {+            object : SpreadsheetValues {+                override fun display(sheet: Int, row: Int, col: Int): String =+                    doc.sheets.getOrNull(sheet)?.rows?.getOrNull(row)?.cells?.getOrNull(col)?.text ?: ""++                override fun isNumeric(sheet: Int, row: Int, col: Int): Boolean = false+            }+        }+    }     val handle = remember(doc) {         OfficeNative.createWorkbook(doc.sheets, System.currentTimeMillis(), doc.namedRanges)     }
office/src/main/java/com/vayunmathur/office/util/OfficeNative.kt
diff --git a/office/src/main/java/com/vayunmathur/office/util/OfficeNative.kt b/office/src/main/java/com/vayunmathur/office/util/OfficeNative.ktindex c56b46f8bd..b14289c62b 100644--- a/office/src/main/java/com/vayunmathur/office/util/OfficeNative.kt+++ b/office/src/main/java/com/vayunmathur/office/util/OfficeNative.kt@@ -35,8 +35,12 @@ import kotlinx.serialization.json.Json  * number with no workbook (XLSX cell display).  */ object OfficeNative {-    init {+    /** False when the native lib is absent for this ABI; callers must fall back, not crash. */+    val isAvailable: Boolean = try {         System.loadLibrary("office_engine")+        true+    } catch (expected: UnsatisfiedLinkError) {+        false     }      // ---- Document tree CRDT ----@@ -101,7 +105,7 @@ object OfficeNative {         sheets: List<OdfSheet>,         nowMillis: Long = System.currentTimeMillis(),         namedRanges: List<OdfNamedRange> = emptyList(),-    ): Long = nativeCreateWorkbook(buildWorkbookJson(sheets, namedRanges), nowMillis)+    ): Long = if (isAvailable) nativeCreateWorkbook(buildWorkbookJson(sheets, namedRanges), nowMillis) else 0      // ---- Workbook serialization (must agree with the serde schema in formula.rs) ----