office: add automated tests for share round-trip (flat-ODF reparse) and end-to-end sharing/roles
- Commit
84aacf93985d1893fb2e30217b235d9e7e5d6910- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-06 15:05 UTC (5 months ago)
- Parents
9307c60
Diff
office/src/main/java/com/vayunmathur/office/util/OfficeViewModel.kt
diff --git a/office/src/main/java/com/vayunmathur/office/util/OfficeViewModel.kt b/office/src/main/java/com/vayunmathur/office/util/OfficeViewModel.ktindex 79309d2d1b..58b395b725 100644--- a/office/src/main/java/com/vayunmathur/office/util/OfficeViewModel.kt+++ b/office/src/main/java/com/vayunmathur/office/util/OfficeViewModel.kt@@ -35,6 +35,18 @@ data class OfficeDocMeta( val ownerKeyB64: String = "", ) +/** Builds the local metadata for a shared document from an incoming invite (carries role + owner key). */+fun officeDocMetaFromInvite(inv: OfficeSync.Invite): OfficeDocMeta =+ OfficeDocMeta(+ docId = inv.docId,+ title = inv.title,+ keyB64 = inv.key,+ owner = false,+ charMode = inv.charMode,+ role = inv.role,+ ownerKeyB64 = inv.ownerKey,+ )+ /** Document access roles. Enforced entirely client-side via signature checks (server is a pure relay). */ object OfficeRoles { const val OWNER = "owner"@@ -2070,7 +2082,7 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application) val index = loadIndex(ds).associateBy { it.docId }.toMutableMap() for (inv in res.invites) { if (!index.containsKey(inv.docId)) {- index[inv.docId] = OfficeDocMeta(inv.docId, inv.title, inv.key, owner = false, charMode = inv.charMode, role = inv.role, ownerKeyB64 = inv.ownerKey)+ index[inv.docId] = officeDocMetaFromInvite(inv) } } saveIndex(ds, index.values.toList())
office/src/test/java/com/vayunmathur/office/odf/FlatOdfRoundTripTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/odf/FlatOdfRoundTripTest.kt b/office/src/test/java/com/vayunmathur/office/odf/FlatOdfRoundTripTest.ktnew file mode 100644index 0000000000..49123adb65--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/odf/FlatOdfRoundTripTest.kt@@ -0,0 +1,74 @@+package com.vayunmathur.office.odf++import com.vayunmathur.library.ui.odf.OdfCell+import com.vayunmathur.library.ui.odf.OdfContentBlock+import com.vayunmathur.library.ui.odf.OdfDocument+import com.vayunmathur.library.ui.odf.OdfParagraph+import com.vayunmathur.library.ui.odf.OdfRow+import com.vayunmathur.library.ui.odf.OdfSerializer+import com.vayunmathur.library.ui.odf.OdfSheet+import com.vayunmathur.library.ui.odf.OdfSlide+import com.vayunmathur.library.ui.odf.OdfSlideElement+import com.vayunmathur.library.ui.odf.OdfFrame+import com.vayunmathur.library.ui.odf.OdfSpan+import org.junit.Test+import org.xmlpull.v1.XmlPullParser+import org.xmlpull.v1.XmlPullParserFactory+import java.io.StringReader++/**+ * Regression guard for online sharing: the recipient (and the owner reopening from the Online tab)+ * rebuilds a document by running it back through [OdfSerializer.serializeFlat] and then re-parsing+ * it. If the serialized flat ODF isn't well-formed or uses an undeclared namespace prefix, parsing+ * throws "undefined prefix: X" / "missing content.xml" and the shared doc won't open.+ *+ * These tests re-parse the serializer output with a **namespace-aware** pull parser, which fails on+ * exactly those errors (this is what caught the missing `xmlns:meta` on the flat root).+ */+class FlatOdfRoundTripTest {++ /** Parses [xml] with namespace processing on; throws on malformed XML or an undeclared prefix. */+ private fun assertWellFormedWithNamespaces(xml: String) {+ val factory = XmlPullParserFactory.newInstance()+ factory.isNamespaceAware = true+ val parser = factory.newPullParser()+ parser.setInput(StringReader(xml))+ var event = parser.eventType+ while (event != XmlPullParser.END_DOCUMENT) {+ event = parser.next() // resolving each element's prefix; throws if undeclared+ }+ }++ @Test+ fun text_document_flat_is_wellformed() {+ val doc = OdfDocument.TextDocument(+ title = "Round Trip",+ content = listOf(+ OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("Hello ", bold = true), OdfSpan("world")))),+ OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("second paragraph"))))+ )+ )+ assertWellFormedWithNamespaces(OdfSerializer.serializeFlat(doc))+ }++ @Test+ fun spreadsheet_flat_is_wellformed() {+ val doc = OdfDocument.Spreadsheet(+ title = "Sheet",+ sheets = listOf(OdfSheet("Sheet 1", listOf(OdfRow(listOf(OdfCell(text = "A1"), OdfCell(text = "B1"))))))+ )+ assertWellFormedWithNamespaces(OdfSerializer.serializeFlat(doc))+ }++ @Test+ fun presentation_flat_is_wellformed() {+ val doc = OdfDocument.Presentation(+ title = "Deck",+ slides = listOf(OdfSlide("Slide 1", listOf(+ OdfSlideElement.Frame(OdfFrame(x = 10f, y = 10f, width = 300f, height = 80f,+ paragraphs = listOf(OdfParagraph(listOf(OdfSpan("Title"))))))+ )))+ )+ assertWellFormedWithNamespaces(OdfSerializer.serializeFlat(doc))+ }+}
office/src/test/java/com/vayunmathur/office/util/OfficeSharingE2ETest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/util/OfficeSharingE2ETest.kt b/office/src/test/java/com/vayunmathur/office/util/OfficeSharingE2ETest.ktnew file mode 100644index 0000000000..f8c8bd460c--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/util/OfficeSharingE2ETest.kt@@ -0,0 +1,140 @@+package com.vayunmathur.office.util++import com.vayunmathur.e2ee.E2ee+import com.vayunmathur.e2ee.E2eeKeyStore+import com.vayunmathur.e2ee.Pqc+import com.vayunmathur.e2ee.PqcIdentity+import com.vayunmathur.library.ui.odf.OdfContentBlock+import com.vayunmathur.library.ui.odf.OdfDocument+import com.vayunmathur.library.ui.odf.OdfParagraph+import com.vayunmathur.library.ui.odf.OdfSpan+import kotlinx.coroutines.runBlocking+import kotlinx.serialization.json.Json+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertTrue+import org.junit.Test+import kotlin.io.encoding.Base64++/**+ * End-to-end simulation of Office document sharing across two "devices", using the real crypto+ * (PQC ML-KEM/ML-DSA), CRDT, text codec, and the actual wire types ([SignedOp], [SignedMember],+ * [OfficeSync.Invite]) — only the network is replaced by an in-memory relay. This guards the whole+ * pipeline that kept breaking: invite delivery, owner-signed roster, signed-op verification + role+ * gate, CRDT merge, and document reconstruction.+ */+class OfficeSharingE2ETest {++ private val json = Json { ignoreUnknownKeys = true }++ private class MemStore : E2eeKeyStore {+ private val m = HashMap<String, ByteArray>()+ override fun getBytes(name: String) = m[name]+ override suspend fun setBytes(name: String, value: ByteArray, onlyIfAbsent: Boolean) {+ if (onlyIfAbsent && m.containsKey(name)) return+ m[name] = value+ }+ }++ /** In-memory relay: append-only channels + a public-key directory. */+ private class Relay {+ val channels = HashMap<String, MutableList<String>>()+ val directory = HashMap<String, ByteArray>()+ fun append(ch: String, blob: String) { channels.getOrPut(ch) { mutableListOf() }.add(blob) }+ fun pull(ch: String) = channels[ch]?.toList() ?: emptyList()+ }++ private fun memberBytes(docId: String, m: OfficeMember) = "$docId|${m.id}|${m.role}".encodeToByteArray()++ private fun textDoc(vararg paras: String) = OdfDocument.TextDocument(+ title = "E2E",+ content = paras.map { OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan(it)))) }+ )++ private fun paraTexts(doc: OdfDocument.TextDocument) =+ doc.content.mapNotNull { (it as? OdfContentBlock.Paragraph)?.paragraph?.spans?.joinToString("") { s -> s.text } }++ @Test+ fun owner_shares_editor_reconstructs_document_and_viewer_is_rejected() = runBlocking {+ val relay = Relay()+ val owner = PqcIdentity.loadOrCreate(MemStore(), "o")+ val editor = PqcIdentity.loadOrCreate(MemStore(), "e")+ val ownerId = "owner"; val editorId = "editor"+ relay.directory[ownerId] = owner.publicBundle+ relay.directory[editorId] = editor.publicBundle++ val docId = "doc-1"+ val docKey = E2ee.newContentKey()+ val ownerDoc = textDoc("Shared heading", "A paragraph of content")++ // ---- Owner: push signed op + owner-signed roster + invite ----+ val crdtO = DocumentCrdt(ownerId)+ val opsJson = json.encodeToString(crdtO.update(TextDocCodec.toCells(ownerDoc)))+ val signedOp = SignedOp(ownerId, Base64.encode(owner.sign(opsJson.encodeToByteArray())), opsJson)+ relay.append(docId, Base64.encode(E2ee.aesEncrypt(docKey, json.encodeToString(signedOp).encodeToByteArray())))++ for (m in listOf(OfficeMember(ownerId, "Owner", OfficeRoles.OWNER), OfficeMember(editorId, "", OfficeRoles.EDITOR))) {+ val sm = SignedMember(m, Base64.encode(owner.sign(memberBytes(docId, m))))+ relay.append("members:$docId", Base64.encode(E2ee.aesEncrypt(docKey, json.encodeToString(sm).encodeToByteArray())))+ }+ val invite = OfficeSync.Invite(docId, Base64.encode(docKey), ownerDoc.title, charMode = true, role = OfficeRoles.EDITOR, ownerKey = Base64.encode(owner.publicBundle))+ relay.append("inbox:$editorId", Base64.encode(Pqc.encryptTo(editor.publicBundle, json.encodeToString(invite).encodeToByteArray())))++ // ---- Editor: open the shared document ----+ val inv = json.decodeFromString<OfficeSync.Invite>(+ editor.decrypt(Base64.decode(relay.pull("inbox:$editorId").single())).decodeToString()+ )+ assertEquals(OfficeRoles.EDITOR, inv.role)+ assertTrue("invite must carry owner key", inv.ownerKey.isNotBlank())+ val recDocKey = Base64.decode(inv.key)+ val ownerKey = Base64.decode(inv.ownerKey)++ // roster: honor only owner-signed records+ val roleById = HashMap<String, String>()+ for (blob in relay.pull("members:$docId")) {+ val sm = json.decodeFromString<SignedMember>(E2ee.aesDecrypt(recDocKey, Base64.decode(blob)).decodeToString())+ if (Pqc.verify(ownerKey, memberBytes(docId, sm.member), Base64.decode(sm.sig))) roleById[sm.member.id] = sm.member.role+ }+ assertEquals(OfficeRoles.OWNER, roleById[ownerId])++ // ops: verify author signature + editor/owner role, then apply+ val crdtR = DocumentCrdt(editorId)+ for (blob in relay.pull(docId)) {+ val so = json.decodeFromString<SignedOp>(E2ee.aesDecrypt(recDocKey, Base64.decode(blob)).decodeToString())+ val authorKey = relay.directory[so.author] ?: continue+ val sigOk = Pqc.verify(authorKey, so.ops.encodeToByteArray(), Base64.decode(so.sig))+ val roleOk = OfficeRoles.canEdit(roleById[so.author] ?: OfficeRoles.VIEWER)+ if (sigOk && roleOk) crdtR.apply(json.decodeFromString(so.ops))+ }+ val rebuilt = TextDocCodec.fromCells(crdtR.render(), OdfDocument.TextDocument(inv.title, emptyList()))+ assertEquals(paraTexts(ownerDoc), paraTexts(rebuilt)) // reconstructed identically++ // ---- Negative: a viewer's forged op is rejected ----+ roleById[editorId] = OfficeRoles.VIEWER+ val forgedOps = DocumentCrdt(editorId).update(TextDocCodec.toCells(textDoc("malicious edit")))+ val forgedJson = json.encodeToString(forgedOps)+ val forged = SignedOp(editorId, Base64.encode(editor.sign(forgedJson.encodeToByteArray())), forgedJson)+ val sigOk = Pqc.verify(relay.directory[editorId]!!, forged.ops.encodeToByteArray(), Base64.decode(forged.sig))+ val roleOk = OfficeRoles.canEdit(roleById[forged.author] ?: OfficeRoles.VIEWER)+ assertTrue("signature itself is valid", sigOk)+ assertFalse("but a viewer's edit must be rejected by the role gate", sigOk && roleOk)++ // ---- Negative: an op that lies about authorship fails signature verification ----+ val liar = SignedOp(ownerId, Base64.encode(editor.sign(forgedJson.encodeToByteArray())), forgedJson)+ assertFalse(+ "editor cannot forge an op as the owner (wrong signing key)",+ Pqc.verify(relay.directory[ownerId]!!, liar.ops.encodeToByteArray(), Base64.decode(liar.sig))+ )+ }++ @Test+ fun invite_maps_to_metadata_with_role_and_owner_key() {+ val inv = OfficeSync.Invite("d", "k", "Title", charMode = true, role = OfficeRoles.VIEWER, ownerKey = "OWNERKEY")+ val meta = officeDocMetaFromInvite(inv)+ assertEquals("d", meta.docId)+ assertEquals(OfficeRoles.VIEWER, meta.role)+ assertEquals("OWNERKEY", meta.ownerKeyB64) // the field whose omission caused empty docs+ assertTrue(meta.charMode)+ assertFalse(meta.owner)+ }+}