Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
dependencies ▾

Modern-Apps.git / office / src / test / java / com / vayunmathur / office / platform / W4ShareOpenOnlineTest.kt

W4ShareOpenOnlineTest.kt331 lines · 14.0 KiBRaw
1package com.vayunmathur.office.platform
2
3import androidx.test.core.app.ApplicationProvider
4import com.vayunmathur.e2ee.E2ee
5import com.vayunmathur.e2ee.E2eeKeyStore
6import com.vayunmathur.e2ee.PqcIdentity
7import com.vayunmathur.library.network.SimpleResponse
8import com.vayunmathur.library.ui.odf.OdfContentBlock
9import com.vayunmathur.library.ui.odf.OdfDocument
10import com.vayunmathur.library.ui.odf.OdfParagraph
11import com.vayunmathur.library.ui.odf.OdfSpan
12import com.vayunmathur.library.util.DataStoreUtils
13import java.util.concurrent.CountDownLatch
14import java.util.concurrent.TimeUnit
15import kotlin.io.encoding.Base64
16import kotlin.test.AfterTest
17import kotlin.test.BeforeTest
18import kotlin.test.Test
19import kotlin.test.assertEquals
20import kotlin.test.assertNotNull
21import kotlin.test.assertNull
22import kotlin.test.assertTrue
23import kotlinx.coroutines.Dispatchers
24import kotlinx.coroutines.ExperimentalCoroutinesApi
25import kotlinx.coroutines.runBlocking
26import kotlinx.coroutines.test.UnconfinedTestDispatcher
27import kotlinx.coroutines.test.resetMain
28import kotlinx.coroutines.test.runTest
29import kotlinx.coroutines.test.setMain
30
31import com.vayunmathur.office.domain.DocumentTreeCrdt
32import com.vayunmathur.office.sync.OfficeSync
33import com.vayunmathur.office.sync.securityCode
34import com.vayunmathur.office.sync.sign
35/**
36 * W4: end-to-end (fake-relay) share / open-online flows.
37 *
38 * The scripted transport serves registration, key lookup, appends and
39 * per-channel pulls, so [OfficeViewModel.shareCurrentDocument],
40 * [OfficeViewModel.openOnlineDocument], join-request approval, member
41 * role changes and key rotation run their real success paths — including
42 * CRDT op exchange — with no network.
43 */
44@org.junit.runner.RunWith(org.robolectric.RobolectricTestRunner::class)
45@OptIn(ExperimentalCoroutinesApi::class)
46class W4ShareOpenOnlineTest {
47
48 private class MemStore : E2eeKeyStore {
49 private val m = HashMap<String, ByteArray>()
50 override suspend fun getBytes(name: String): ByteArray? = m[name]
51 override suspend fun setBytes(name: String, value: ByteArray, onlyIfAbsent: Boolean) {
52 if (onlyIfAbsent && m.containsKey(name)) return
53 m[name] = value
54 }
55 }
56
57 private val roboApp: android.app.Application
58 get() = ApplicationProvider.getApplicationContext()
59
60 private var previousTransport: OfficeSync.HttpTransport? = null
61 private val rawChannels = mutableMapOf<String, List<String>>()
62 private val appended = mutableListOf<Pair<String, List<String>>>()
63 private var getKeyStatus = 200
64
65 private fun channelOf(body: String): String =
66 Regex(""""channel":"([^"]+)"""").find(body)?.groupValues?.get(1) ?: ""
67
68 private fun resp(status: Int, body: String, url: String) =
69 SimpleResponse(status, "", body, emptyMap(), url)
70
71 @BeforeTest
72 fun setUp() {
73 Dispatchers.setMain(UnconfinedTestDispatcher())
74 previousTransport = OfficeSync.httpTransport
75 OfficeSync.httpTransport = OfficeSync.HttpTransport { url, body ->
76 when {
77 url.endsWith("/register") -> resp(200, "{}", url)
78 url.endsWith("/getkey") ->
79 if (getKeyStatus == 200) resp(200, Base64.encode(OfficeSync.publicBundle), url)
80 else resp(getKeyStatus, "", url)
81 url.endsWith("/append") -> {
82 val actions = Regex(""""actions":\[(.*?)\]""").find(body)?.groupValues?.get(1)
83 ?.let { Regex(""""([^"]*)"""").findAll(it).map { m -> m.groupValues[1] }.toList() }
84 ?: emptyList()
85 appended.add(channelOf(body) to actions)
86 resp(200, """{"seq":${appended.size}}""", url)
87 }
88 url.endsWith("/pull") -> {
89 val actions = rawChannels[channelOf(body)] ?: emptyList()
90 val jsonActions = actions.joinToString(",") { "\"$it\"" }
91 resp(200, """{"actions":[$jsonActions],"seq":${actions.size}}""", url)
92 }
93 else -> resp(404, "", url)
94 }
95 }
96 runBlocking {
97 if (runCatching { OfficeSync.identity }.isFailure) {
98 OfficeSync.identity = PqcIdentity.loadOrCreate(MemStore(), "w4share")
99 }
100 OfficeSync.init(roboApp)
101 }
102 }
103
104 @AfterTest
105 fun tearDown() {
106 OfficeSync.httpTransport = previousTransport
107 OfficeSync.stopLive()
108 Dispatchers.resetMain()
109 }
110
111 private fun loadedVm(text: String): OfficeViewModel {
112 val v = OfficeViewModel(roboApp)
113 v.stateMutable.value = OfficeViewModel.ViewState.Loaded(
114 OdfDocument.TextDocument(
115 title = "Doc",
116 content = listOf(OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan(text)))))))
117 return v
118 }
119
120 private fun await(timeoutMs: Long = 15_000, cond: () -> Boolean): Boolean {
121 val deadline = System.currentTimeMillis() + timeoutMs
122 while (System.currentTimeMillis() < deadline) {
123 if (cond()) return true
124 Thread.sleep(20)
125 }
126 return cond()
127 }
128
129 private fun stopJobs(v: OfficeViewModel) {
130 OfficeSync.stopLive()
131 v.livePollJob?.cancel()
132 v.presenceTickJob?.cancel()
133 v.caretPresenceJob?.cancel()
134 v.livePushJob?.cancel()
135 v.currentTree?.close()
136 }
137
138 private fun aesBlob(key: ByteArray, plain: String): String =
139 Base64.encode(E2ee.aesEncrypt(key, plain.encodeToByteArray()))
140
141 // ---- shareCurrentDocument ----
142
143 @Test
144 fun `sharing a local document delivers a sealed invite`() {
145 val v = loadedVm("shareable text")
146 try {
147 val latch = CountDownLatch(1)
148 var error: String? = "unset"
149 v.shareCurrentDocument("peer-device", docName = "My Shared Doc") { error = it; latch.countDown() }
150 assertTrue(latch.await(15, TimeUnit.SECONDS), "share callback")
151 assertNull(error)
152 assertNotNull(v.currentDocId)
153 assertEquals(OfficeRoles.OWNER, v.currentRole)
154 // The invite went to the recipient's inbox channel, sealed to their bundle.
155 val invite = appended.lastOrNull { it.first == "inbox:peer-device" }
156 assertNotNull(invite)
157 val opened = OfficeSync.identity.decrypt(Base64.decode(invite.second.single())).decodeToString()
158 val decoded = OfficeSync.json.decodeFromString<OfficeSync.Invite>(opened)
159 assertEquals(v.currentDocId, decoded.docId)
160 assertEquals("My Shared Doc", decoded.title)
161 // And the document is recorded in the online index.
162 val index = runBlocking { v.loadIndex(DataStoreUtils.getInstance(roboApp)) }
163 assertTrue(index.any { it.docId == v.currentDocId && it.owner })
164 } finally {
165 stopJobs(v)
166 }
167 }
168
169 @Test
170 fun `sharing with an unregistered recipient reports the reason`() {
171 val v = loadedVm("orphan text")
172 try {
173 getKeyStatus = 404
174 val latch = CountDownLatch(1)
175 var error: String? = null
176 v.shareCurrentDocument("ghost-device") { error = it; latch.countDown() }
177 assertTrue(latch.await(15, TimeUnit.SECONDS), "share callback")
178 assertNotNull(error)
179 assertTrue(error!!.contains("registered", ignoreCase = true), error!!)
180 } finally {
181 getKeyStatus = 200
182 stopJobs(v)
183 }
184 }
185
186 // ---- openOnlineDocument ----
187
188 private fun signedOpFor(v: OfficeViewModel, text: String, key: ByteArray): String {
189 val author = loadedVm(text)
190 val tree = DocumentTreeCrdt(OfficeSync.deviceId)
191 try {
192 val opsJson = tree.updateJson(author.exportFlat())
193 val sig = Base64.encode(runBlocking { OfficeSync.sign(opsJson.encodeToByteArray()) })
194 val signed = v.syncJson.encodeToString(SignedOp(OfficeSync.deviceId, sig, opsJson))
195 return aesBlob(key, signed)
196 } finally {
197 tree.close()
198 }
199 }
200
201 @Test
202 fun `opening an online document adopts its content and title`() {
203 val v = OfficeViewModel(roboApp)
204 val key = ByteArray(32) { 12 }
205 val docId = "online-doc-1"
206 try {
207 // Owner-signed rename waiting on the title channel.
208 val titleSig = Base64.encode(runBlocking { OfficeSync.sign(v.titleSigningBytes(docId, "Shared Title")) })
209 rawChannels["title:$docId"] = listOf(
210 aesBlob(key, v.syncJson.encodeToString(SignedTitle("Shared Title", titleSig))))
211 // The document's signed CRDT op on its own channel.
212 rawChannels[docId] = listOf(signedOpFor(v, "shared hello", key))
213
214 val meta = OfficeDocMeta(
215 docId = docId, title = "Old Title", keyB64 = Base64.encode(key),
216 owner = false, role = OfficeRoles.EDITOR,
217 ownerKeyB64 = Base64.encode(OfficeSync.publicBundle))
218 runBlocking { v.saveIndex(DataStoreUtils.getInstance(roboApp), listOf(meta)) }
219
220 v.openOnlineDocument(meta)
221 assertTrue(
222 await { (v.state.value as? OfficeViewModel.ViewState.Loaded) != null },
223 "state should load, was ${v.state.value}")
224 val doc = (v.state.value as OfficeViewModel.ViewState.Loaded).document
225 val text = (doc as OdfDocument.TextDocument).content
226 .filterIsInstance<OdfContentBlock.Paragraph>()
227 .joinToString("") { it.paragraph.spans.joinToString("") { s -> s.text } }
228 assertTrue(text.contains("shared hello"), text)
229 assertEquals(docId, v.currentDocId)
230 assertTrue(v.isEditModeMutable.value, "editors open in edit mode")
231 // The owner rename was folded into the local index.
232 val index = runBlocking { v.loadIndex(DataStoreUtils.getInstance(roboApp)) }
233 assertEquals("Shared Title", index.firstOrNull { it.docId == docId }?.title)
234 } finally {
235 stopJobs(v)
236 }
237 }
238
239 @Test
240 fun `opening an online document with no readable ops errors`() {
241 val v = OfficeViewModel(roboApp)
242 val key = ByteArray(32) { 13 }
243 val docId = "online-doc-empty"
244 try {
245 rawChannels[docId] = listOf(aesBlob(key, "not a signed op"))
246 val meta = OfficeDocMeta(
247 docId = docId, title = "Empty", keyB64 = Base64.encode(key),
248 owner = false, role = OfficeRoles.VIEWER,
249 ownerKeyB64 = Base64.encode(OfficeSync.publicBundle))
250 v.openOnlineDocument(meta)
251 assertTrue(
252 await { v.state.value is OfficeViewModel.ViewState.Error },
253 "state should error, was ${v.state.value}")
254 val message = (v.state.value as OfficeViewModel.ViewState.Error).message
255 assertTrue(message.contains("no readable content", ignoreCase = true), message)
256 } finally {
257 stopJobs(v)
258 }
259 }
260
261 // ---- approveJoinRequest / setMemberRole / securityCodeWith ----
262
263 @Test
264 fun `approving a join request invites the requester and clears the queue`() {
265 val v = OfficeViewModel(roboApp)
266 val key = ByteArray(32) { 14 }
267 val docId = "owned-doc"
268 try {
269 val ds = DataStoreUtils.getInstance(roboApp)
270 runBlocking {
271 v.saveIndex(ds, listOf(OfficeDocMeta(
272 docId = docId, title = "Owned", keyB64 = Base64.encode(key), owner = true)))
273 v.saveRequests(ds, listOf(OfficeSync.JoinRequest(docId = docId, requesterId = "req-9", name = "Nia")))
274 }
275 val latch = CountDownLatch(1)
276 var ok: Boolean? = null
277 v.approveJoinRequest(docId, "req-9", "Nia") { ok = it; latch.countDown() }
278 assertTrue(latch.await(15, TimeUnit.SECONDS), "approve callback")
279 assertEquals(true, ok)
280 assertTrue(appended.any { it.first == "inbox:req-9" }, appended.toString())
281 assertTrue(
282 await { runBlocking { v.loadRequests(ds) }.isEmpty() },
283 "pending request should be removed")
284 } finally {
285 stopJobs(v)
286 }
287 }
288
289 @Test
290 fun `set member role records the roster and revoking rotates the key`() = runTest {
291 val v = loadedVm("roster text")
292 val key = ByteArray(32) { 15 }
293 v.currentDocId = "roster-doc"
294 v.currentDocKey = key
295 v.currentRole = OfficeRoles.OWNER
296 v.currentOwnerKey = OfficeSync.publicBundle
297 v.memberKeyCache["member-1"] = OfficeSync.publicBundle
298 // Roster channel: one surviving member so rotation seals a wrap for them.
299 val member = OfficeMember("member-1", "Mel", OfficeRoles.EDITOR)
300 val sig = Base64.encode(OfficeSync.sign(v.memberSigningBytes("roster-doc", member)))
301 rawChannels["members:roster-doc"] = listOf(
302 aesBlob(key, v.syncJson.encodeToString(SignedMember(member, sig))))
303
304 val latch = CountDownLatch(1)
305 var ok: Boolean? = null
306 v.setMemberRole("member-1", OfficeRoles.REVOKED) { ok = it; latch.countDown() }
307 assertTrue(latch.await(15, TimeUnit.SECONDS), "role callback")
308 assertEquals(true, ok)
309 // Revocation rotated the content key to a new epoch.
310 assertTrue(await { v.currentEpoch == 1 }, "epoch should advance, was ${v.currentEpoch}")
311 assertTrue(!key.contentEquals(v.currentDocKey!!))
312 stopJobs(v)
313 }
314
315 @Test
316 fun `security code is derived for a registered peer`() {
317 val v = OfficeViewModel(roboApp)
318 try {
319 val latch = CountDownLatch(1)
320 var code: String? = null
321 v.securityCodeWith("peer-7") { code = it; latch.countDown() }
322 assertTrue(latch.await(15, TimeUnit.SECONDS), "code callback")
323 assertNotNull(code)
324 assertTrue(code!!.isNotBlank())
325 val expected = runBlocking { OfficeSync.securityCode(OfficeSync.publicBundle) }
326 assertEquals(expected, code)
327 } finally {
328 stopJobs(v)
329 }
330 }
331}