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

Modern-Apps.git / communicate-dev / src / test / java / com / vayunmathur / communicate / rcs / RcsSlice3Pass2E2ETest.kt

RcsSlice3Pass2E2ETest.kt256 lines · 11.7 KiBRaw
1package com.vayunmathur.communicate.rcs
2
3import android.content.Context
4import androidx.test.core.app.ApplicationProvider
5import com.vayunmathur.communicate.data.rcs.RcsDatabase
6import com.vayunmathur.communicate.data.rcs.RcsMlsGroup
7import com.vayunmathur.communicate.data.rcs.RcsMlsIdentity
8import com.vayunmathur.communicate.data.rcs.e2e.RcsE2E
9import com.vayunmathur.communicate.data.rcs.e2e.RcsKeyDirectory
10import com.vayunmathur.communicate.data.rcs.e2e.RcsPeerKeys
11import com.vayunmathur.communicate.data.rcs.e2e.RustMlsCrypto
12import com.vayunmathur.communicate.data.rcs.e2e.e2eThreadFor
13import com.vayunmathur.communicate.data.rcs.e2e.hex
14import com.vayunmathur.communicate.data.rcs.e2e.parseMembers
15import com.vayunmathur.communicate.data.rcs.e2e.pruneMembers
16import kotlinx.coroutines.test.runTest
17import org.junit.runner.RunWith
18import org.robolectric.RobolectricTestRunner
19import kotlin.test.AfterTest
20import kotlin.test.BeforeTest
21import kotlin.test.Test
22import kotlin.test.assertEquals
23import kotlin.test.assertFalse
24import kotlin.test.assertNotNull
25import kotlin.test.assertNull
26import kotlin.test.assertTrue
27
28/**
29 * Slice-3 pass 2: RcsE2E Room-backed verification state, group/member
30 * bookkeeping, and (when the host MLS library loads) a full native
31 * identity → key-package → group → encrypt/decrypt round trip.
32 */
33@RunWith(RobolectricTestRunner::class)
34class RcsSlice3Pass2E2ETest {
35
36 private val context: Context get() = ApplicationProvider.getApplicationContext()
37 private lateinit var testDb: RcsDatabase
38 private lateinit var deviceB: RcsDatabase
39
40 private fun newDb(): RcsDatabase =
41 androidx.room3.Room.inMemoryDatabaseBuilder(context, RcsDatabase::class.java)
42 .setDriver(androidx.sqlite.driver.bundled.BundledSQLiteDriver())
43 .allowMainThreadQueries()
44 .build()
45
46 private suspend fun <T> onDb(db: RcsDatabase, block: suspend () -> T): T {
47 RcsDatabase.overrideForTest = db
48 try {
49 return block()
50 } finally {
51 RcsDatabase.overrideForTest = testDb
52 }
53 }
54
55 @BeforeTest
56 fun setUp() {
57 testDb = newDb()
58 deviceB = newDb()
59 RcsDatabase.overrideForTest = testDb
60 RcsPeerKeys.clear()
61 }
62
63 @AfterTest
64 fun tearDown() {
65 RcsDatabase.overrideForTest = null
66 testDb.close()
67 deviceB.close()
68 RcsPeerKeys.clear()
69 }
70
71 @Test
72 fun verificationLifecycleThroughRoom() = runTest {
73 val peer = "+15553003001"
74 assertFalse(RcsE2E.isVerified(context, peer))
75 // Verifying with no record is a no-op for isVerified.
76 RcsE2E.setVerified(context, peer, true)
77 assertFalse(RcsE2E.isVerified(context, peer))
78 // Record verification against a package sketch.
79 val pkg = byteArrayOf(1, 2, 3, 4, 5, 6)
80 RcsE2E.setVerifiedWithPackage(context, peer, pkg)
81 assertTrue(RcsE2E.isVerified(context, peer))
82 // Same package: no identity-change warning.
83 assertFalse(RcsE2E.checkPeerIdentityChange(context, peer, pkg))
84 assertTrue(RcsE2E.isVerified(context, peer))
85 // Different package: warning fires and verification is cleared.
86 assertTrue(RcsE2E.checkPeerIdentityChange(context, peer, byteArrayOf(9, 9, 9)))
87 assertFalse(RcsE2E.isVerified(context, peer))
88 // Unverified peers never warn; empty packages never warn.
89 assertFalse(RcsE2E.checkPeerIdentityChange(context, peer, byteArrayOf(8)))
90 RcsE2E.setVerifiedWithPackage(context, peer, pkg)
91 assertFalse(RcsE2E.checkPeerIdentityChange(context, peer, ByteArray(0)))
92 // Toggle off via the plain setter.
93 RcsE2E.setVerified(context, peer, false)
94 assertFalse(RcsE2E.isVerified(context, peer))
95 RcsE2E.setVerified(context, peer, true)
96 assertTrue(RcsE2E.isVerified(context, peer))
97 }
98
99 @Test
100 fun safetyFingerprintsFromCachedPackages() = runTest {
101 val peer = "+15553003002"
102 assertNull(RcsE2E.safetyFingerprint(peer))
103 RcsPeerKeys.store(peer, byteArrayOf(42, 42, 42, 42))
104 val fp = RcsE2E.safetyFingerprint(peer)
105 assertNotNull(fp)
106 // The digest digits are grouped in fours for read-off comparison.
107 val groups = fp.split(" ")
108 assertTrue(groups.size >= 16 && groups.all { it.all { c -> c.isDigit() } }, fp)
109 assertEquals(fp, RcsE2E.safetyFingerprint(peer))
110 // Our own side is empty until we publish (publishing needs transport).
111 assertNull(RcsE2E.mySafetyFingerprint("+15553003003"))
112 assertNull(RcsKeyDirectory.lastPublishedFor("+15553003003"))
113 }
114
115 @Test
116 fun groupIdResolutionFromRoomRows() = runTest {
117 // No group row.
118 assertNull(RcsE2E.groupIdFor(context, "conv-pass2"))
119 assertNull(with(RcsE2E) { groupIdFor(context, "conv-pass2") })
120 // Pending pseudo-group is not a real group id.
121 testDb.mlsGroupDao().upsert(
122 RcsMlsGroup(groupIdHex = "pending:+1555", conversationId = "conv-pass2", storage = byteArrayOf(1)),
123 )
124 assertNull(RcsE2E.groupIdFor(context, "conv-pass2"))
125 // A real hex id decodes to bytes (separate conversation: the DAO
126 // returns one row per conversation).
127 testDb.mlsGroupDao().upsert(
128 RcsMlsGroup(groupIdHex = "00ff10ab", conversationId = "conv-pass2-real", storage = byteArrayOf(1)),
129 )
130 assertEquals(
131 listOf(0.toByte(), 0xFF.toByte(), 0x10.toByte(), 0xAB.toByte()),
132 RcsE2E.groupIdFor(context, "conv-pass2-real")?.toList(),
133 )
134 assertEquals(
135 listOf(0.toByte(), 0xFF.toByte(), 0x10.toByte(), 0xAB.toByte()),
136 with(RcsE2E) { groupIdFor(context, "conv-pass2-real") }?.toList(),
137 )
138 }
139
140 @Test
141 fun memberMapTrackingAndLeafLookup() = runTest {
142 // parseMembers / pruneMembers are pure CSV helpers.
143 assertEquals(emptyMap(), RcsE2E.parseMembers(""))
144 assertEquals(mapOf("+1" to 0, "+2" to 3), RcsE2E.parseMembers("+1=0,+2=3"))
145 assertEquals(mapOf("+1" to 0), RcsE2E.parseMembers("+1=0,bogus,+2=x,=2"))
146 assertEquals("+1=0", RcsE2E.pruneMembers("+1=0,+2=3", setOf(3)))
147 assertEquals("", RcsE2E.pruneMembers("+1=0", setOf(0)))
148
149 // trackAddedMembers assigns sequential leaves after the current max.
150 assertEquals("+1=1", RcsE2E.trackAddedMembers("", listOf("+1")))
151 assertEquals("+1=1,+2=2", RcsE2E.trackAddedMembers("+1=1", listOf("+2", "+2", " ")))
152 assertEquals("+9=5,+1=6", RcsE2E.trackAddedMembers("+9=5", listOf("+1")))
153
154 // Leaf lookup reads the tracked map back from Room.
155 testDb.mlsGroupDao().upsert(
156 RcsMlsGroup(
157 groupIdHex = "abcd", conversationId = "conv-pass2",
158 storage = byteArrayOf(0), members = "+1555=1,+1666=2",
159 ),
160 )
161 assertEquals(2, RcsE2E.leafIndexFor(context, "conv-pass2", "+1666"))
162 assertEquals(1, RcsE2E.leafIndexFor(context, "conv-pass2", " +1555 "))
163 assertNull(RcsE2E.leafIndexFor(context, "conv-pass2", "+1777"))
164 assertNull(RcsE2E.leafIndexFor(context, "no-such-conv", "+1555"))
165 }
166
167 @Test
168 fun localE164AndThreadHelpers() {
169 // No line-1 number under Robolectric: null, never a throw.
170 assertNull(RcsE2E.localE164(context))
171 assertNull(with(RcsE2E) { localE164(context) })
172 assertEquals("e2e:+1555", e2eThreadFor("+1555"))
173 assertEquals("00ff", byteArrayOf(0, 0xFF.toByte()).hex())
174 assertEquals("", ByteArray(0).hex())
175 }
176
177 @Test
178 fun keyPackagePublishFailsClosedWithoutTransport() = runTest {
179 assertFalse(RcsKeyDirectory.publishTo(context, "+15553003001", "+15553003002"))
180 assertNull(RcsKeyDirectory.lastPublishedFor("+15553003001"))
181 }
182
183 @Test
184 fun nativeMlsRoundTripWhenLibraryAvailable() = runTest {
185 if (!RustMlsCrypto.isAvailable) {
186 // Host library absent: every native entry point fails closed.
187 assertNull(RcsE2E.identityFor(context, "+15553004001"))
188 assertFalse(RcsE2E.isMlsPayload("Content-Type: ${RcsE2E.CT_MLS}\r\n\r\nQUJDRA=="))
189 return@runTest
190 }
191 val me = "+15553004001"
192 val peer = "+15553004002"
193 // Identities generate once and persist in Room. On hosts where the
194 // loaded crate cannot generate (stale/partial native build), every
195 // native flow must fail closed instead.
196 val identity = RcsE2E.identityFor(context, me)
197 if (identity == null) {
198 assertNull(RcsE2E.freshKeyPackage(context, me))
199 assertNull(RcsE2E.createEncryptedGroup(context, me, "conv-mls-x", listOf(byteArrayOf(1))))
200 assertNull(RcsE2E.joinEncryptedGroup(context, "conv-mls-x", byteArrayOf(1, 2, 3)))
201 assertNull(RcsE2E.encryptTo(context, me, "conv-mls-x", byteArrayOf(1)))
202 assertNull(RcsE2E.decryptFor(context, "conv-mls-x", byteArrayOf(1, 2, 3)))
203 assertFalse(RcsE2E.removeMembers(context, me, "conv-mls-x", listOf(1)))
204 assertFalse(RcsE2E.setupEncryptedGroup(context, me, "conv-mls-x", mapOf(peer to byteArrayOf(1))))
205 assertFalse(RcsE2E.setupGroupWithPeer(context, me, "conv-mls-x", peer, byteArrayOf(1)))
206 return@runTest
207 }
208 assertEquals(identity.toList(), RcsE2E.identityFor(context, me)?.toList())
209 assertNull(RcsE2E.identityFor(context, ""))
210 val row = testDb.mlsIdentityDao().get(me)
211 assertNotNull(row)
212 assertEquals(identity.toList(), row.identity.toList())
213
214 // Key packages for both sides. The peer lives on a second
215 // database: one Room row per group id cannot hold both the
216 // creator's and the joiner's snapshot of the same group, so
217 // modelling both devices in one DB (as this test used to)
218 // makes the join replace the creator's row.
219 val myKp = RcsE2E.freshKeyPackage(context, me)
220 assertNotNull(myKp)
221 val peerKp = onDb(deviceB) {
222 val peerIdentity = RcsE2E.identityFor(context, peer)
223 assertNotNull(peerIdentity)
224 RcsE2E.freshKeyPackage(context, peer)
225 }
226 assertNotNull(peerKp)
227
228 // Create a group adding the peer, then join from the Welcome.
229 val created = RcsE2E.createEncryptedGroup(context, me, "conv-mls-1", listOf(peerKp))
230 assertNotNull(created)
231 val (commit, welcome) = created
232 assertTrue(commit.isNotEmpty() && welcome.isNotEmpty())
233 val groupId = onDb(deviceB) { RcsE2E.joinEncryptedGroup(context, "conv-mls-2", welcome) }
234 assertNotNull(groupId)
235 assertEquals(groupId.toList(), RcsE2E.groupIdFor(context, "conv-mls-1")?.toList())
236 assertEquals(groupId.toList(), onDb(deviceB) { RcsE2E.groupIdFor(context, "conv-mls-2") }?.toList())
237
238 // Encrypt on one side, decrypt on the joined side.
239 val payload = RcsE2E.encryptTo(context, me, "conv-mls-1", "secret hello".toByteArray(Charsets.UTF_8))
240 assertNotNull(payload)
241 val decrypted = onDb(deviceB) { RcsE2E.decryptFor(context, "conv-mls-2", payload) }
242 assertNotNull(decrypted)
243 assertEquals("secret hello", decrypted.first.toString(Charsets.UTF_8))
244 assertTrue(decrypted.second)
245
246 // MLS payload detection sees the framed payload by content type.
247 assertTrue(RcsE2E.isMlsPayload("Content-Type: ${RcsE2E.CT_MLS}\r\n\r\nAAAA"))
248 assertTrue(with(RcsE2E) { isMlsPayload("Content-Type: ${RcsE2E.CT_WELCOME}\r\n\r\nAAAA") })
249
250 // Group operations on unknown groups fail closed.
251 assertNull(RcsE2E.encryptTo(context, me, "conv-unknown", byteArrayOf(1)))
252 assertNull(RcsE2E.decryptFor(context, "conv-unknown", byteArrayOf(1, 2, 3)))
253 assertNull(RcsE2E.joinEncryptedGroup(context, "conv-mls-3", byteArrayOf(1, 2, 3)))
254 assertTrue(RcsE2E.createEncryptedGroup(context, me, "conv-x", emptyList()) == null)
255 }
256}