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

Modern-Apps.git / communicate-dev / src / test / java / com / vayunmathur / communicate / whatsapp / W5Pass2SyncHistoryTest.kt

W5Pass2SyncHistoryTest.kt277 lines · 14.5 KiBRaw
1package com.vayunmathur.communicate.whatsapp
2
3import android.app.Application
4import androidx.test.core.app.ApplicationProvider
5import androidx.test.ext.junit.runners.AndroidJUnit4
6import com.google.protobuf.ByteString
7import com.vayunmathur.communicate.data.whatsapp.WhatsAppAuthData
8import com.vayunmathur.communicate.data.whatsapp.WhatsAppClient
9import com.vayunmathur.communicate.data.whatsapp.WhatsAppDiag
10import com.vayunmathur.communicate.data.whatsapp.WhatsAppEvent
11import com.vayunmathur.communicate.data.whatsapp.WhatsAppProtocol
12import com.vayunmathur.communicate.data.whatsapp.applyAppStateRecord
13import com.vayunmathur.communicate.data.whatsapp.emitHistoryConversation
14import com.vayunmathur.communicate.data.whatsapp.getAppStateKey
15import com.vayunmathur.communicate.data.whatsapp.handleAppStateKeyShare
16import com.vayunmathur.communicate.data.whatsapp.expandAppStateKeys
17import com.vayunmathur.communicate.data.whatsapp.handleHistorySync
18import com.vayunmathur.communicate.data.whatsapp.loadPollSecret
19import com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppAppStateProto
20import com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto
21import com.vayunmathur.communicate.data.whatsapp.sendHistoryOnDemandRequest
22import com.vayunmathur.communicate.data.whatsapp.sendHistorySyncReceipt
23import com.vayunmathur.communicate.data.whatsapp.storeAppStateKey
24import com.vayunmathur.communicate.data.whatsapp.transport.WhatsAppSocket
25import java.io.ByteArrayOutputStream
26import java.util.zip.Deflater
27import javax.crypto.Cipher
28import javax.crypto.spec.IvParameterSpec
29import javax.crypto.spec.SecretKeySpec
30import java.util.concurrent.CopyOnWriteArrayList
31import kotlin.test.AfterTest
32import kotlin.test.BeforeTest
33import kotlin.test.Test
34import kotlin.test.assertEquals
35import kotlin.test.assertNotNull
36import kotlin.test.assertNull
37import kotlin.test.assertTrue
38import kotlinx.coroutines.CoroutineScope
39import kotlinx.coroutines.Dispatchers
40import kotlinx.coroutines.cancel
41import kotlinx.coroutines.Job
42import kotlinx.coroutines.launch
43import kotlinx.coroutines.test.runTest
44import org.junit.runner.RunWith
45
46/**
47 * Pass-2 slice-1 (whatsapp sync): app-state key share + record application, and
48 * history-sync backfill, with the same deterministic no-DB/no-session harness as
49 * the client-actions tests.
50 */
51@RunWith(AndroidJUnit4::class)
52class W5Pass2SyncHistoryTest {
53
54 private val auth = WhatsAppAuthData(
55 phoneNumber = "+15550001", pushName = "Tester", wid = "[email protected]",
56 noisePrivateKey = "", noisePublicKey = "", identityPrivateKey = "", identityPublicKey = "",
57 registrationId = 14, signedPreKeyId = 1, signedPreKeyPublic = "", signedPreKeyPrivate = "",
58 signedPreKeySignature = "", lid = "12345@lid",
59 )
60
61 private lateinit var eventScope: CoroutineScope
62 // Written by the collector on Dispatchers.Default, read by the test
63 // thread after a signal wait (see the awaits below): must be the
64 // thread-safe list, not a plain ArrayList.
65 private val receivedEvents = CopyOnWriteArrayList<WhatsAppEvent>()
66
67 @BeforeTest
68 fun setUp() {
69 val app = ApplicationProvider.getApplicationContext<Application>()
70 WhatsAppClient.appContext = app
71 WhatsAppClient.authData = auth
72 WhatsAppClient.db = null
73 WhatsAppClient.webSocket = WhatsAppSocket(auth)
74 WhatsAppClient.stateMutable.value = WhatsAppClient.State.Connected
75 WhatsAppClient.nameCache.clear()
76 WhatsAppClient.lidToPhoneMap.clear()
77 WhatsAppClient.onDemandRequested.clear()
78 WhatsAppClient.onDemandPageCount.clear()
79 WhatsAppClient.appStateCollectionsFetching.clear()
80 WhatsAppClient.appStateKeyRequested.clear()
81 WhatsAppDiag.clear()
82 receivedEvents.clear()
83 eventScope = CoroutineScope(Dispatchers.Default + Job())
84 eventScope.launch { WhatsAppClient.events.collect { receivedEvents.add(it) } }
85 }
86
87 @AfterTest
88 fun tearDown() {
89 // Stop this method's collector: the SharedFlow broadcasts to every
90 // live collector, and an uncancelled scope would keep draining the
91 // singleton's stream (and writing into a stale list) for the rest
92 // of the JVM.
93 eventScope.cancel()
94 }
95
96 private fun deflate(data: ByteArray): ByteArray {
97 val deflater = Deflater()
98 deflater.setInput(data)
99 deflater.finish()
100 val out = ByteArrayOutputStream()
101 val buf = ByteArray(4096)
102 while (!deflater.finished()) {
103 val n = deflater.deflate(buf)
104 out.write(buf, 0, n)
105 }
106 return out.toByteArray()
107 }
108
109 @Test
110 fun `key share stores keys and kicks off collection fetches`() = runTest {
111 val share = WhatsAppE2EProto.AppStateSyncKeyShare.newBuilder()
112 .addKeys(
113 WhatsAppE2EProto.AppStateSyncKey.newBuilder()
114 .setKeyId(WhatsAppE2EProto.AppStateSyncKeyId.newBuilder().setKeyId(ByteString.copyFrom(byteArrayOf(1, 1))))
115 .setKeyData(WhatsAppE2EProto.AppStateSyncKeyData.newBuilder().setKeyData(ByteString.copyFrom(ByteArray(32) { 3 }))),
116 )
117 .addKeys(
118 WhatsAppE2EProto.AppStateSyncKey.newBuilder()
119 .setKeyId(WhatsAppE2EProto.AppStateSyncKeyId.newBuilder().setKeyId(ByteString.copyFrom(byteArrayOf())))
120 .setKeyData(WhatsAppE2EProto.AppStateSyncKeyData.newBuilder().setKeyData(ByteString.copyFrom(ByteArray(32)))),
121 )
122 .build()
123 WhatsAppClient.handleAppStateKeyShare(share)
124 // Only the non-empty key is stored.
125 assertNotNull(WhatsAppClient.getAppStateKey(byteArrayOf(1, 1)))
126 assertTrue(WhatsAppDiag.log.value.any { it.contains("stored 1 sync key(s)") })
127 // Every collection fetch fails soft (no Iq answer) and clears its in-flight mark.
128 assertTrue(WhatsAppClient.appStateCollectionsFetching.isEmpty())
129 assertTrue(WhatsAppDiag.log.value.any { it.contains("synced to v0") })
130 }
131
132 @Test
133 fun `app state contact record lands in the name cache`() = runTest {
134 val keyId = byteArrayOf(42, 42)
135 val keyData = ByteArray(32) { (it * 7 + 1).toByte() }
136 WhatsAppClient.storeAppStateKey(keyId, keyData)
137 val action = WhatsAppAppStateProto.SyncActionData.newBuilder()
138 .setIndex(ByteString.copyFrom("""["contact","[email protected]"]""".toByteArray()))
139 .setValue(
140 WhatsAppAppStateProto.SyncActionValue.newBuilder()
141 .setContactAction(WhatsAppAppStateProto.ContactAction.newBuilder().setFullName("Seven Of Nine")),
142 )
143 .build()
144 val record = encryptedRecord(keyId, keyData, action.toByteArray())
145 WhatsAppClient.applyAppStateRecord(record, isSet = true)
146 assertEquals("Seven Of Nine", WhatsAppClient.nameCache["[email protected]"])
147 // A REMOVE record and an unknown-key record change nothing.
148 WhatsAppClient.applyAppStateRecord(record, isSet = false)
149 val unknown = encryptedRecord(byteArrayOf(1), keyData, action.toByteArray())
150 WhatsAppClient.nameCache.clear()
151 WhatsAppClient.applyAppStateRecord(unknown, isSet = true)
152 assertTrue(WhatsAppClient.nameCache.isEmpty())
153 // Garbage plaintext is dropped silently.
154 val garbage = encryptedRecord(keyId, keyData, byteArrayOf(1, 2, 3, 4))
155 WhatsAppClient.applyAppStateRecord(garbage, isSet = true)
156 assertTrue(WhatsAppClient.nameCache.isEmpty())
157 }
158
159 private fun encryptedRecord(keyId: ByteArray, keyData: ByteArray, plain: ByteArray): WhatsAppAppStateProto.SyncdRecord {
160 val expanded = WhatsAppProtocol.expandAppStateKeys(keyData)
161 val iv = ByteArray(16) { it.toByte() }
162 val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
163 cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(expanded[1], "AES"), IvParameterSpec(iv))
164 val blob = iv + cipher.doFinal(plain) + ByteArray(32)
165 return WhatsAppAppStateProto.SyncdRecord.newBuilder()
166 .setKeyId(WhatsAppAppStateProto.KeyId.newBuilder().setId(ByteString.copyFrom(keyId)))
167 .setValue(WhatsAppAppStateProto.SyncdValue.newBuilder().setBlob(ByteString.copyFrom(blob)))
168 .build()
169 }
170
171 private fun historyMessage(id: String, body: String, fromMe: Boolean, ts: Long, pushName: String = "") =
172 WhatsAppE2EProto.HistorySyncMsg.newBuilder()
173 .setMessage(
174 WhatsAppE2EProto.WebMessageInfo.newBuilder()
175 .setKey(WhatsAppE2EProto.HsMsgKey.newBuilder().setId(id).setFromMe(fromMe).setRemoteJid("[email protected]"))
176 .setMessage(WhatsAppE2EProto.Message.newBuilder().setConversation(body))
177 .setMessageTimestamp(ts)
178 .setPushName(pushName),
179 )
180 .build()
181
182 @Test
183 fun `history sync emits conversations and messages and maps LIDs`() = runTest {
184 val history = WhatsAppE2EProto.HistorySync.newBuilder()
185 .setSyncType(WhatsAppClient.SYNC_INITIAL_BOOTSTRAP)
186 .setChunkOrder(1)
187 .addPhoneNumberToLidMappings(
188 WhatsAppE2EProto.PhoneNumberToLIDMapping.newBuilder()
189 .setPnJid("[email protected]").setLidJid("999@lid"),
190 )
191 .addConversations(
192 WhatsAppE2EProto.HsConversation.newBuilder()
193 .setId("[email protected]")
194 .setName("Seven")
195 .setUnreadCount(2)
196 .addMessages(historyMessage("h1", "hello from history", fromMe = false, ts = 1_700_000_000L, pushName = "Seven"))
197 .addMessages(historyMessage("h2", "reply from me", fromMe = true, ts = 1_700_000_100L)),
198 )
199 .addConversations(
200 WhatsAppE2EProto.HsConversation.newBuilder()
201 .setId("status@broadcast")
202 .addMessages(historyMessage("s1", "status junk", fromMe = false, ts = 1_700_000_000L)),
203 )
204 .build()
205 val notif = WhatsAppE2EProto.HistorySyncNotification.newBuilder()
206 .setInitialHistBootstrapInlinePayload(ByteString.copyFrom(deflate(history.toByteArray())))
207 .build()
208 WhatsAppClient.fullHistorySync = false // do not chase on-demand pages in this test
209 WhatsAppClient.handleHistorySync(notif, "notif-1")
210 assertEquals("[email protected]", WhatsAppClient.lidToPhoneMap["999@lid"])
211 // Events reach the collector on Dispatchers.Default asynchronously;
212 // wait for the terminal delivery instead of asserting on whatever
213 // has landed already (an immediate read races the collector and
214 // failed empty under load).
215 com.vayunmathur.testsupport.awaitWithMainIdle("history sync events delivered", maxSteps = 100_000) {
216 receivedEvents.filterIsInstance<WhatsAppEvent.MessageUpdate>().size >= 2 &&
217 receivedEvents.filterIsInstance<WhatsAppEvent.ConversationUpdate>().isNotEmpty()
218 }
219 val updates = receivedEvents.filterIsInstance<WhatsAppEvent.MessageUpdate>()
220 assertEquals(listOf("hello from history", "reply from me"), updates.map { it.body })
221 assertEquals(listOf(false, true), updates.map { it.outgoing })
222 val conv = receivedEvents.filterIsInstance<WhatsAppEvent.ConversationUpdate>().single()
223 assertEquals("wa:[email protected]", conv.conversationId)
224 assertEquals(2, conv.unreadCount)
225 assertEquals("reply from me", conv.lastPreview)
226 assertTrue(WhatsAppDiag.log.value.any { it.contains("emitted 2 message(s)") })
227 assertTrue(WhatsAppDiag.log.value.any { it.contains("hist_sync receipt for notif-1") })
228 WhatsAppClient.fullHistorySync = true
229 }
230
231 @Test
232 fun `history sync failures are logged not thrown`() = runTest {
233 val notif = WhatsAppE2EProto.HistorySyncNotification.newBuilder()
234 .setInitialHistBootstrapInlinePayload(ByteString.copyFrom(byteArrayOf(1, 2, 3)))
235 .build()
236 WhatsAppClient.handleHistorySync(notif, "notif-bad")
237 // No inline payload and no media host: still just a receipt.
238 WhatsAppClient.handleHistorySync(WhatsAppE2EProto.HistorySyncNotification.getDefaultInstance(), "notif-empty")
239 assertTrue(WhatsAppDiag.log.value.any { it.contains("hist_sync receipt for notif-empty") })
240 }
241
242 @Test
243 fun `emit history conversation skips empty and counts bodies`() = runTest {
244 val empty = WhatsAppE2EProto.HsConversation.newBuilder().setId("[email protected]").build()
245 assertEquals(0, WhatsAppClient.emitHistoryConversation(empty, "[email protected]", requestMore = false))
246 val conv = WhatsAppE2EProto.HsConversation.newBuilder()
247 .setId("[email protected]")
248 .setName("Group")
249 .addMessages(historyMessage("g1", "group hello", fromMe = false, ts = 1_700_000_000L))
250 .build()
251 assertEquals(1, WhatsAppClient.emitHistoryConversation(conv, "[email protected]", requestMore = false))
252 // Same delivery race as above: .single() on the not-yet-drained
253 // collector list threw NoSuchElementException under load.
254 com.vayunmathur.testsupport.awaitWithMainIdle("conversation update delivered", maxSteps = 100_000) {
255 receivedEvents.filterIsInstance<WhatsAppEvent.ConversationUpdate>().isNotEmpty()
256 }
257 val update = receivedEvents.filterIsInstance<WhatsAppEvent.ConversationUpdate>().single()
258 assertTrue(update.isGroup)
259 assertEquals("wa:[email protected]", update.conversationId)
260 }
261
262 @Test
263 fun `history receipts and on-demand dedupe`() = runTest {
264 WhatsAppClient.sendHistorySyncReceipt("")
265 WhatsAppClient.sendHistorySyncReceipt("m-1")
266 assertTrue(WhatsAppDiag.log.value.any { it.contains("hist_sync receipt for m-1") })
267 WhatsAppClient.sendHistoryOnDemandRequest("[email protected]", "old-1", oldestFromMe = false, oldestTsSec = 100L)
268 val diagAfterFirst = WhatsAppDiag.log.value.size
269 // The same cursor is deduped; an empty id is ignored before that.
270 WhatsAppClient.sendHistoryOnDemandRequest("[email protected]", "old-1", oldestFromMe = false, oldestTsSec = 100L)
271 WhatsAppClient.sendHistoryOnDemandRequest("[email protected]", "", oldestFromMe = false, oldestTsSec = 0L)
272 WhatsAppClient.sendHistoryOnDemandRequest("", "old-2", oldestFromMe = false, oldestTsSec = 0L)
273 assertEquals(1, WhatsAppClient.onDemandPageCount["[email protected]"])
274 assertTrue(WhatsAppDiag.log.value.size >= diagAfterFirst)
275 assertNull(WhatsAppClient.loadPollSecret("never-stored"))
276 }
277}