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

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

Y1WaInboundTest.kt655 lines · 42.0 KiBRaw
1package com.vayunmathur.communicate.whatsapp
2
3import android.app.Application
4import android.util.Base64
5import androidx.room3.Room
6import androidx.test.core.app.ApplicationProvider
7import androidx.test.ext.junit.runners.AndroidJUnit4
8import com.google.protobuf.ByteString
9import com.vayunmathur.communicate.data.whatsapp.SentDM
10import com.vayunmathur.communicate.data.whatsapp.WhatsAppAuthData
11import com.vayunmathur.communicate.data.whatsapp.WhatsAppClient
12import com.vayunmathur.communicate.data.whatsapp.WhatsAppDatabase
13import com.vayunmathur.communicate.data.whatsapp.WhatsAppDiag
14import com.vayunmathur.communicate.data.whatsapp.WhatsAppEvent
15import com.vayunmathur.communicate.data.whatsapp.WhatsAppProtocol
16import com.vayunmathur.communicate.data.whatsapp.buildIncomingMediaAttachment
17import com.vayunmathur.communicate.data.whatsapp.buildPollVoteMessage
18import com.vayunmathur.communicate.data.whatsapp.createGroup
19import com.vayunmathur.communicate.data.whatsapp.cropResizeAvatar
20import com.vayunmathur.communicate.data.whatsapp.e2e.RustWhatsAppCrypto
21import com.vayunmathur.communicate.data.whatsapp.e2e.WhatsAppE2E
22import com.vayunmathur.communicate.data.whatsapp.encodeNode
23import com.vayunmathur.communicate.data.whatsapp.extractJid
24import com.vayunmathur.communicate.data.whatsapp.fetchAndEmitGroupInfo
25import com.vayunmathur.communicate.data.whatsapp.generateClientId
26import com.vayunmathur.communicate.data.whatsapp.generateRef
27import com.vayunmathur.communicate.data.whatsapp.generateToken
28import com.vayunmathur.communicate.data.whatsapp.getContactSuggestions
29import com.vayunmathur.communicate.data.whatsapp.getUserDevices
30import com.vayunmathur.communicate.data.whatsapp.handleAccountSync
31import com.vayunmathur.communicate.data.whatsapp.handleChatPresence
32import com.vayunmathur.communicate.data.whatsapp.handleDirty
33import com.vayunmathur.communicate.data.whatsapp.handleIdentityChange
34import com.vayunmathur.communicate.data.whatsapp.handleIncomingMessage
35import com.vayunmathur.communicate.data.whatsapp.handleNotification
36import com.vayunmathur.communicate.data.whatsapp.handlePictureUpdate
37import com.vayunmathur.communicate.data.whatsapp.handleRetryReceipt
38import com.vayunmathur.communicate.data.whatsapp.isLoggedIn
39import com.vayunmathur.communicate.data.whatsapp.isOwnJid
40import com.vayunmathur.communicate.data.whatsapp.logoutRemote
41import com.vayunmathur.communicate.data.whatsapp.padMessage
42import com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto
43import com.vayunmathur.communicate.data.whatsapp.queryGroupParticipants
44import com.vayunmathur.communicate.data.whatsapp.resolveChatSender
45import com.vayunmathur.communicate.data.whatsapp.resolveDeviceContactName
46import com.vayunmathur.communicate.data.whatsapp.resolveJID
47import com.vayunmathur.communicate.data.whatsapp.resolveMentionsInBody
48import com.vayunmathur.communicate.data.whatsapp.resolveName
49import com.vayunmathur.communicate.data.whatsapp.sendRetryReceipt
50import com.vayunmathur.communicate.data.whatsapp.setGroupAvatar
51import com.vayunmathur.communicate.data.whatsapp.setGroupName
52import com.vayunmathur.communicate.data.whatsapp.setGroupTopic
53import com.vayunmathur.communicate.data.whatsapp.transport.WhatsAppSocket
54import com.vayunmathur.communicate.data.whatsapp.updateGroupParticipants
55import java.io.ByteArrayOutputStream
56import java.security.MessageDigest
57import java.util.Collections
58import kotlin.test.AfterTest
59import kotlin.test.BeforeTest
60import kotlin.test.Test
61import kotlin.test.assertEquals
62import kotlin.test.assertFalse
63import kotlin.test.assertNotNull
64import kotlin.test.assertNull
65import kotlin.test.assertTrue
66import kotlinx.coroutines.CompletableDeferred
67import kotlinx.coroutines.CoroutineScope
68import kotlinx.coroutines.Dispatchers
69import kotlinx.coroutines.Job
70import kotlinx.coroutines.launch
71import kotlinx.coroutines.test.runTest
72import org.junit.runner.RunWith
73
74/**
75 * Y1: real inbound behaviour for WhatsAppClientInbound/Retry/Groups/Utils.
76 * Plain-body stanzas drive the no-crypto routing; encrypted stanzas are produced
77 * by a genuine peer [WhatsAppE2E] (host Rust crypto) so pkmsg/skmsg decrypt,
78 * edit/revoke/reaction/poll/history/app-state branches run end to end offline.
79 */
80@RunWith(AndroidJUnit4::class)
81class Y1WaInboundTest {
82
83 companion object {
84 fun b64(b: ByteArray): String = Base64.encodeToString(b, Base64.NO_WRAP)
85 fun unb64(s: String): ByteArray = Base64.decode(s, Base64.NO_WRAP)
86 fun authFor(idSeed: Int, spkSeed: Int, wid: String, lid: String): WhatsAppAuthData {
87 val idPriv = ByteArray(32) { (idSeed + it).toByte() }
88 val idPub = RustWhatsAppCrypto.publicFromPrivate(idPriv)!!
89 val spkPriv = ByteArray(32) { (spkSeed + it).toByte() }
90 val spkPub = RustWhatsAppCrypto.publicFromPrivate(spkPriv)!!
91 val sig = WhatsAppE2E.signSignedPreKey(idPriv, spkPub)
92 return WhatsAppAuthData(
93 phoneNumber = "+15550001", pushName = "Tester", wid = wid,
94 noisePrivateKey = b64(ByteArray(32) { 1 }), noisePublicKey = b64(ByteArray(32) { 2 }),
95 identityPrivateKey = b64(idPriv), identityPublicKey = b64(idPub),
96 registrationId = 14, signedPreKeyId = 5,
97 signedPreKeyPublic = b64(spkPub), signedPreKeyPrivate = b64(spkPriv),
98 signedPreKeySignature = b64(sig), lid = lid,
99 )
100 }
101 val AUTH: WhatsAppAuthData by lazy { authFor(1, 41, "[email protected]", "12345@lid") }
102 val PEER: WhatsAppAuthData by lazy { authFor(101, 141, "[email protected]", "67890@lid") }
103 const val PEER_JID = "[email protected]"
104 const val GROUP_JID = "[email protected]"
105 }
106
107 private lateinit var db: WhatsAppDatabase
108 private val events = Collections.synchronizedList(mutableListOf<WhatsAppEvent>())
109
110 @BeforeTest
111 fun setUp() {
112 val app = ApplicationProvider.getApplicationContext<Application>()
113 db = Room.inMemoryDatabaseBuilder(app, WhatsAppDatabase::class.java)
114 .setSingleConnectionPool().allowMainThreadQueries().build()
115 WhatsAppClient.appContext = app
116 WhatsAppClient.authData = AUTH
117 WhatsAppClient.db = db
118 WhatsAppClient.webSocket = WhatsAppSocket(AUTH)
119 WhatsAppClient.stateMutable.value = WhatsAppClient.State.Connected
120 WhatsAppClient.suppressReconnect = false
121 WhatsAppClient.fullHistorySync = false
122 listOf(
123 WhatsAppClient.nameCache, WhatsAppClient.lidToPhoneMap, WhatsAppClient.undecryptableTracker,
124 WhatsAppClient.retryResendCounts, WhatsAppClient.pollSecrets,
125 ).forEach { it.clear() }
126 WhatsAppClient.pendingMessageIDs.clear(); WhatsAppClient.processedEditIDs.clear()
127 WhatsAppClient.knownGroups.clear(); WhatsAppClient.recentSentDMs.clear()
128 WhatsAppClient.pendingIqs.clear(); WhatsAppClient.onDemandRequested.clear()
129 WhatsAppClient.appStateKeyRequested.clear()
130 WhatsAppDiag.clear(); events.clear()
131 CoroutineScope(Dispatchers.Default + Job()).launch { WhatsAppClient.events.collect { events.add(it) } }
132 // WhatsAppClient.events is a SharedFlow with no replay: an event
133 // emitted before this collector's subscription lands is dropped, so
134 // under load the first feed could race the subscription and its
135 // event was simply never recorded. Wait for the subscription itself.
136 com.vayunmathur.testsupport.awaitWithMainIdle(
137 "events collector subscribed", maxSteps = 100_000,
138 ) { WhatsAppClient.eventsMutable.subscriptionCount.value > 0 }
139 }
140
141 @AfterTest
142 fun tearDown() {
143 WhatsAppClient.fullHistorySync = true
144 WhatsAppClient.authData = AUTH
145 }
146
147 private fun await(label: String, cond: () -> Boolean) {
148 // Terminal-signal wait, not a wall clock: each step idles the main
149 // looper and yields so the IO-scope stanza pipeline and the Default
150 // event collector can actually run under CPU caps. The old 15 s
151 // sleep-poll expired while that work was merely starved.
152 try {
153 // cond reads `events`, a synchronizedList whose iterators are
154 // not themselves synchronized: evaluating the filter without
155 // holding the list's lock races the collector's adds (a tight
156 // pumped loop hits that race far sooner than a sleep-poll did).
157 com.vayunmathur.testsupport.awaitWithMainIdle(label, maxSteps = 100_000) {
158 synchronized(events) { cond() }
159 }
160 } catch (e: IllegalStateException) {
161 error("timeout $label diag=${WhatsAppDiag.log.value.takeLast(5)} events=$events")
162 }
163 }
164
165 private fun feed(node: WhatsAppProtocol.Node) =
166 WhatsAppClient.handleIncomingMessage(WhatsAppProtocol.encodeNode(node))
167
168 private fun peerEncryptNode(msg: WhatsAppE2EProto.Message, id: String, from: String = PEER_JID, participant: String? = null, extra: Map<String, String> = emptyMap()): WhatsAppProtocol.Node {
169 val app = ApplicationProvider.getApplicationContext<Application>()
170 val peerDb = Room.inMemoryDatabaseBuilder(app, WhatsAppDatabase::class.java)
171 .setSingleConnectionPool().allowMainThreadQueries().build()
172 val peer = WhatsAppE2E(peerDb, PEER)
173 peer.processPreKeyBundle(
174 AUTH.wid,
175 WhatsAppE2E.ParsedPreKeyBundle(
176 registrationId = AUTH.registrationId, preKeyId = null, preKeyPublic = null,
177 signedPreKeyId = AUTH.signedPreKeyId, signedPreKeyPublic = unb64(AUTH.signedPreKeyPublic),
178 signedPreKeySignature = unb64(AUTH.signedPreKeySignature), identityKey = unb64(AUTH.identityPublicKey),
179 ),
180 )
181 val enc = peer.encryptDM(AUTH.wid, WhatsAppProtocol.padMessage(msg.toByteArray()))
182 val attrs = mutableMapOf("from" to from, "id" to id, "type" to "text", "t" to "1700000000")
183 if (participant != null) attrs["participant"] = participant
184 attrs.putAll(extra)
185 return WhatsAppProtocol.Node(
186 tag = "message", attrs = attrs,
187 content = listOf(WhatsAppProtocol.Node(tag = "enc", attrs = mapOf("type" to enc.type, "v" to "2"), data = enc.data)),
188 )
189 }
190
191 private fun feedEncrypted(msg: WhatsAppE2EProto.Message, id: String, from: String = PEER_JID, participant: String? = null, extra: Map<String, String> = emptyMap()) =
192 feed(peerEncryptNode(msg, id, from, participant, extra))
193
194 private fun conv(text: String) = WhatsAppE2EProto.Message.newBuilder().setConversation(text).build()
195
196 @Test
197 fun `encrypted DM emits incoming with notify name and group DM attributes sender`() {
198 // Note: a body-only stanza is (correctly) treated as undecryptable by the
199 // client, so live routing is exercised with real encrypted stanzas.
200 feedEncrypted(conv("hello plain"), "p1", extra = mapOf("notify" to "Peer Name"))
201 await("dm") { events.filterIsInstance<WhatsAppEvent.IncomingMessage>().any { it.messageId == "p1" } }
202 val dm = events.filterIsInstance<WhatsAppEvent.IncomingMessage>().first { it.messageId == "p1" }
203 assertEquals("wa:$PEER_JID", dm.conversationId); assertEquals("hello plain", dm.body)
204 assertEquals("Peer Name", dm.peerName); assertEquals(1_700_000_000_000L, dm.timestamp)
205 assertNull(dm.senderId)
206 assertEquals("Peer Name", WhatsAppClient.nameCache[PEER_JID])
207 feedEncrypted(conv("group hi"), "p2", from = GROUP_JID, participant = PEER_JID)
208 await("group") { events.filterIsInstance<WhatsAppEvent.IncomingMessage>().any { it.messageId == "p2" } }
209 val g = events.filterIsInstance<WhatsAppEvent.IncomingMessage>().first { it.messageId == "p2" }
210 assertEquals(PEER_JID, g.senderId); assertNotNull(g.senderName)
211 assertFalse(WhatsAppClient.knownGroups.contains(GROUP_JID))
212 }
213
214 @Test
215 fun `encrypted own group message renders as outgoing`() {
216 feedEncrypted(conv("mine"), "p3", from = GROUP_JID, participant = AUTH.wid)
217 await("own") { events.filterIsInstance<WhatsAppEvent.MessageUpdate>().any { it.messageId == "p3" } }
218 val own = events.filterIsInstance<WhatsAppEvent.MessageUpdate>().first { it.messageId == "p3" }
219 assertTrue(own.outgoing); assertEquals("mine", own.body)
220 assertTrue(events.filterIsInstance<WhatsAppEvent.IncomingMessage>().none { it.messageId == "p3" })
221 }
222
223 @Test
224 fun `status broadcast and pending dedup are consumed silently`() {
225 feedEncrypted(conv("story"), "p4", from = "status@broadcast")
226 WhatsAppClient.pendingMessageIDs.add("p5")
227 feedEncrypted(conv("dup"), "p5")
228 Thread.sleep(700)
229 assertTrue(events.none { (it as? WhatsAppEvent.IncomingMessage)?.messageId in setOf("p4", "p5") })
230 assertFalse(WhatsAppClient.pendingMessageIDs.contains("p5"))
231 }
232
233 @Test
234 fun `sender_pn normalises LID addressed encrypted message to phone conversation`() {
235 feedEncrypted(conv("lid hi"), "p6", from = "99999@lid", extra = mapOf("sender_pn" to PEER_JID))
236 await("lid") { events.filterIsInstance<WhatsAppEvent.IncomingMessage>().any { it.messageId == "p6" } }
237 assertEquals("wa:$PEER_JID", events.filterIsInstance<WhatsAppEvent.IncomingMessage>().first { it.messageId == "p6" }.conversationId)
238 }
239
240 @Test
241 fun `failure stanzas map reasons to disconnected states`() {
242 fun failure(reason: String) = feed(WhatsAppProtocol.Node(tag = "failure", attrs = mapOf("reason" to reason)))
243 failure("405"); await("405") { WhatsAppClient.stateMutable.value.toString().contains("Client outdated") }
244 failure("503"); await("503") { WhatsAppClient.stateMutable.value.toString().contains("Temporarily banned") }
245 failure("999"); await("999") { WhatsAppClient.stateMutable.value.toString().contains("Connection failed: 999") }
246 failure("401"); await("401") { WhatsAppClient.stateMutable.value.toString().contains("Logged out") }
247 Thread.sleep(300); WhatsAppClient.authData = AUTH
248 WhatsAppClient.stateMutable.value = WhatsAppClient.State.Connected
249 }
250
251 @Test
252 fun `stream error conflict 401 515 and generic branches`() {
253 fun stream(attrs: Map<String, String>, child: WhatsAppProtocol.Node? = null) = feed(
254 WhatsAppProtocol.Node(tag = "stream:error", attrs = attrs, content = listOfNotNull(child)),
255 )
256 stream(mapOf("code" to "515")); await("515") { WhatsAppClient.stateMutable.value.toString().contains("Restart required") }
257 stream(emptyMap()); await("generic") { WhatsAppClient.stateMutable.value.toString().contains("Stream error") }
258 stream(mapOf("code" to "499"), WhatsAppProtocol.Node(tag = "conflict", attrs = mapOf("type" to "replaced")))
259 await("replaced") { WhatsAppClient.stateMutable.value.toString().contains("Session replaced") }
260 assertTrue(WhatsAppClient.suppressReconnect)
261 stream(mapOf("code" to "401"), WhatsAppProtocol.Node(tag = "conflict", attrs = mapOf("type" to "device_removed")))
262 await("removed") { WhatsAppClient.stateMutable.value == WhatsAppClient.State.NeedsSetup }
263 await("logged out event") { events.any { it is WhatsAppEvent.SourceLoggedOut } }
264 WhatsAppClient.suppressReconnect = false; WhatsAppClient.authData = AUTH
265 }
266
267 @Test
268 fun `success stanza authenticates and ib blocks are handled`() {
269 feed(WhatsAppProtocol.Node(tag = "success", attrs = mapOf("lid" to "12345@lid")))
270 await("auth diag") { WhatsAppDiag.log.value.any { it.contains("AUTHENTICATED") } }
271 assertEquals(WhatsAppClient.State.Connected, WhatsAppClient.stateMutable.value)
272 feed(
273 WhatsAppProtocol.Node(
274 tag = "ib", content = listOf(
275 WhatsAppProtocol.Node(tag = "dirty", attrs = mapOf("type" to "account_sync", "timestamp" to "42")),
276 WhatsAppProtocol.Node(tag = "offline_preview", attrs = mapOf("count" to "3", "message" to "2")),
277 WhatsAppProtocol.Node(tag = "offline", attrs = mapOf("count" to "3")),
278 ),
279 ),
280 )
281 await("dirty") { WhatsAppDiag.log.value.any { it.contains("cleaned dirty state: account_sync") } }
282 await("offline") { WhatsAppDiag.log.value.any { it.contains("offline sync completed") } }
283 }
284
285 @Test
286 fun `ack error iq completion and garbage bytes do not emit chat events`() {
287 val deferred = CompletableDeferred<WhatsAppProtocol.Node>()
288 WhatsAppClient.pendingIqs["iq-1"] = deferred
289 feed(WhatsAppProtocol.Node(tag = "iq", attrs = mapOf("id" to "iq-1", "type" to "result")))
290 await("iq done") { deferred.isCompleted }
291 feed(WhatsAppProtocol.Node(tag = "iq", attrs = mapOf("id" to "iq-unknown", "type" to "result")))
292 feed(WhatsAppProtocol.Node(tag = "ack", attrs = mapOf("class" to "message", "id" to "x", "error" to "404")))
293 await("ack diag") { WhatsAppDiag.log.value.any { it.contains("ack REJECTED") } }
294 WhatsAppClient.handleIncomingMessage(byteArrayOf(0x7f, 0x01, 0x02))
295 WhatsAppClient.handleIncomingMessage(ByteArray(0))
296 Thread.sleep(400)
297 assertTrue(events.filterIsInstance<WhatsAppEvent.IncomingMessage>().isEmpty())
298 }
299
300 @Test
301 fun `receipts delivered read read-self list and ignored types`() {
302 fun receipt(type: String?, id: String = "m1", list: List<String> = emptyList()) = WhatsAppProtocol.Node(
303 tag = "receipt",
304 attrs = buildMap { put("from", PEER_JID); put("id", id); put("t", "1700000000"); if (type != null) put("type", type) },
305 content = if (list.isEmpty()) emptyList() else listOf(
306 WhatsAppProtocol.Node(tag = "list", content = list.map { WhatsAppProtocol.Node(tag = "item", attrs = mapOf("id" to it)) }),
307 ),
308 )
309 feed(receipt(null)); feed(receipt("read", "m2")); feed(receipt("read-self", "m3"))
310 feed(receipt("read", "m4", listOf("m5", "m6"))); feed(receipt("played", "m7"))
311 feed(WhatsAppProtocol.Node(tag = "receipt", attrs = mapOf("type" to "read")))
312 await("receipts") { events.filterIsInstance<WhatsAppEvent.ReadReceipt>().size >= 5 }
313 val r = events.filterIsInstance<WhatsAppEvent.ReadReceipt>()
314 assertTrue(r.first { it.messageId == "m1" }.isDelivery)
315 assertFalse(r.first { it.messageId == "m2" }.isDelivery)
316 assertEquals(setOf("m4", "m5", "m6"), r.mapNotNull { it.messageId }.filter { it in setOf("m4", "m5", "m6") }.toSet())
317 assertTrue(r.none { it.messageId == "m7" })
318 assertTrue(r.all { it.conversationId == "wa:$PEER_JID" && it.senderId == PEER_JID })
319 }
320
321 @Test
322 fun `chat presence composing paused and LID participant reroute`() = runTest {
323 WhatsAppClient.lidToPhoneMap["67890@lid"] = PEER_JID
324 WhatsAppClient.handleChatPresence(
325 WhatsAppProtocol.Node(tag = "chatstate", attrs = mapOf("from" to GROUP_JID, "participant" to "67890@lid"),
326 content = listOf(WhatsAppProtocol.Node(tag = "composing", attrs = mapOf("media" to "audio")))),
327 )
328 WhatsAppClient.handleChatPresence(
329 WhatsAppProtocol.Node(tag = "chatstate", attrs = mapOf("from" to PEER_JID),
330 content = listOf(WhatsAppProtocol.Node(tag = "paused"))),
331 )
332 WhatsAppClient.handleChatPresence(WhatsAppProtocol.Node(tag = "chatstate"))
333 await("typing") { events.filterIsInstance<WhatsAppEvent.TypingIndicator>().size >= 2 }
334 val t = events.filterIsInstance<WhatsAppEvent.TypingIndicator>()
335 assertTrue(t[0].isTyping); assertEquals(PEER_JID, t[0].senderId); assertEquals("wa:$GROUP_JID", t[0].conversationId)
336 assertFalse(t[1].isTyping)
337 }
338
339 @Test
340 fun `identity picture and account sync direct handlers`() = runTest {
341 val notif = WhatsAppProtocol.Node(tag = "notification", attrs = mapOf("from" to PEER_JID, "participant" to "[email protected]", "t" to "1700000000"),
342 content = listOf(WhatsAppProtocol.Node(tag = "identity")))
343 WhatsAppClient.handleIdentityChange(notif, PEER_JID)
344 await("idchange") { events.filterIsInstance<WhatsAppEvent.IncomingMessage>().any { it.body.contains("Security code changed") } }
345 WhatsAppClient.handleIdentityChange(WhatsAppProtocol.Node(tag = "notification", attrs = mapOf("from" to PEER_JID)), PEER_JID)
346 WhatsAppClient.handlePictureUpdate(WhatsAppProtocol.Node(tag = "notification", content = listOf(WhatsAppProtocol.Node(tag = "set"))), PEER_JID)
347 WhatsAppClient.handlePictureUpdate(WhatsAppProtocol.Node(tag = "notification", content = listOf(WhatsAppProtocol.Node(tag = "delete"))), PEER_JID)
348 WhatsAppClient.handlePictureUpdate(WhatsAppProtocol.Node(tag = "notification"), PEER_JID)
349 WhatsAppClient.handleAccountSync(
350 WhatsAppProtocol.Node(tag = "notification", attrs = mapOf("from" to "s.whatsapp.net"), content = listOf(
351 WhatsAppProtocol.Node(tag = "push", attrs = mapOf("name" to "Pushy", "jid" to "[email protected]")),
352 WhatsAppProtocol.Node(tag = "contact", attrs = mapOf("name" to "Connie", "jid" to "[email protected]")),
353 WhatsAppProtocol.Node(tag = "push", attrs = mapOf("jid" to "[email protected]")),
354 )),
355 )
356 assertEquals("Pushy", WhatsAppClient.nameCache["[email protected]"])
357 assertEquals("Connie", WhatsAppClient.nameCache["[email protected]"])
358 assertNull(WhatsAppClient.nameCache["[email protected]"])
359 WhatsAppClient.handleNotification(WhatsAppProtocol.Node(tag = "notification"))
360 WhatsAppClient.handleNotification(WhatsAppProtocol.Node(tag = "notification", attrs = mapOf("type" to "devices", "from" to PEER_JID)))
361 WhatsAppClient.handleDirty(WhatsAppProtocol.Node(tag = "dirty"))
362 }
363
364 @Test
365 fun `undecryptable plaintext and garbage ciphertext fail closed with retry receipts`() {
366 repeat(2) { feed(WhatsAppProtocol.Node(tag = "message", attrs = mapOf("from" to PEER_JID, "id" to "u1", "type" to "text"))) }
367 await("tracker") { (WhatsAppClient.undecryptableTracker[PEER_JID] ?: 0) >= 2 }
368 assertTrue(events.filterIsInstance<WhatsAppEvent.IncomingMessage>().none { it.messageId == "u1" })
369 feed(
370 WhatsAppProtocol.Node(tag = "message", attrs = mapOf("from" to PEER_JID, "id" to "bad1", "type" to "text"),
371 content = listOf(WhatsAppProtocol.Node(tag = "enc", attrs = mapOf("type" to "msg"), data = byteArrayOf(9, 9, 9)))),
372 )
373 await("decrypt failed") { WhatsAppDiag.log.value.any { it.contains("DECRYPT FAILED") && it.contains("bad1") } }
374 assertTrue(events.filterIsInstance<WhatsAppEvent.IncomingMessage>().none { it.messageId == "bad1" })
375 }
376
377 @Test
378 fun `sendRetryReceipt caps at five and drops id-less nodes`() = runTest {
379 val node = WhatsAppProtocol.Node(tag = "message", attrs = mapOf("id" to "retry-me", "from" to PEER_JID, "type" to "text"))
380 repeat(6) { WhatsAppClient.sendRetryReceipt(node) }
381 assertTrue((WhatsAppClient.undecryptableTracker["retry:retry-me"] ?: 0) > 5)
382 WhatsAppClient.sendRetryReceipt(WhatsAppProtocol.Node(tag = "message", attrs = mapOf("from" to PEER_JID)))
383 WhatsAppClient.webSocket = null; WhatsAppClient.sendRetryReceipt(node)
384 WhatsAppClient.webSocket = WhatsAppSocket(AUTH)
385 }
386
387 @Test
388 fun `retry receipt resends cached DM then exhausts budget and ignores groups`() = runTest {
389 feedEncrypted(conv("seed session"), "seed-1")
390 await("seed") { events.filterIsInstance<WhatsAppEvent.IncomingMessage>().any { it.messageId == "seed-1" } }
391 val padded = WhatsAppProtocol.padMessage(conv("cached hello").toByteArray())
392 WhatsAppClient.recentSentDMs["cached-1"] = SentDM(to = PEER_JID, type = "text", msgPlaintextPadded = padded, dsmPlaintextPadded = null)
393 fun retry(id: String, from: String, participant: String? = null) = WhatsAppProtocol.Node(
394 tag = "receipt", attrs = buildMap { put("id", id); put("from", from); put("type", "retry"); if (participant != null) put("participant", participant) },
395 )
396 WhatsAppClient.handleRetryReceipt(retry("cached-1", PEER_JID))
397 await("resent") { WhatsAppDiag.log.value.any { it.contains("retry: resent cached-1") } }
398 WhatsAppClient.handleRetryReceipt(retry("nope-1", PEER_JID))
399 await("uncached") { WhatsAppDiag.log.value.any { it.contains("no cached message for nope-1") } }
400 WhatsAppClient.handleRetryReceipt(retry("cached-1", GROUP_JID))
401 WhatsAppClient.handleRetryReceipt(WhatsAppProtocol.Node(tag = "receipt", attrs = mapOf("type" to "retry")))
402 repeat(6) { WhatsAppClient.handleRetryReceipt(retry("cached-1", PEER_JID)) }
403 await("budget") { WhatsAppDiag.log.value.any { it.contains("retry: giving up on cached-1") } }
404 }
405
406 @Test
407 fun `encrypted DM text media view-once forwarded and own-device echo`() {
408 feedEncrypted(conv("secret hello"), "e1")
409 await("e1") { events.filterIsInstance<WhatsAppEvent.IncomingMessage>().any { it.messageId == "e1" } }
410 assertEquals("secret hello", events.filterIsInstance<WhatsAppEvent.IncomingMessage>().first { it.messageId == "e1" }.body)
411 val image = WhatsAppE2EProto.Message.newBuilder()
412 .setImageMessage(WhatsAppE2EProto.ImageMessage.newBuilder().setMimetype("image/jpeg").setCaption("a pic")).build()
413 feedEncrypted(image, "e2")
414 await("e2") { events.filterIsInstance<WhatsAppEvent.IncomingMessage>().any { it.messageId == "e2" } }
415 val img = events.filterIsInstance<WhatsAppEvent.IncomingMessage>().first { it.messageId == "e2" }
416 assertEquals("a pic", img.body); assertTrue(img.attachments.isEmpty())
417 val voInner = WhatsAppE2EProto.Message.newBuilder()
418 .setImageMessage(WhatsAppE2EProto.ImageMessage.newBuilder().setMimetype("image/jpeg")).build()
419 val vo = WhatsAppE2EProto.Message.newBuilder()
420 .setViewOnceMessageV2(WhatsAppE2EProto.FutureProofMessage.newBuilder().setMessage(voInner)).build()
421 feedEncrypted(vo, "e3")
422 await("e3") { events.filterIsInstance<WhatsAppEvent.IncomingMessage>().any { it.messageId == "e3" } }
423 assertTrue(events.filterIsInstance<WhatsAppEvent.IncomingMessage>().first { it.messageId == "e3" }.body.contains("View once"))
424 val ctx = WhatsAppE2EProto.ContextInfo.newBuilder().setIsForwarded(true).setForwardingScore(2)
425 .addMentionedJid(AUTH.wid).build()
426 val fwd = WhatsAppE2EProto.Message.newBuilder()
427 .setExtendedTextMessage(WhatsAppE2EProto.ExtendedTextMessage.newBuilder().setText("hi @15550001").setContextInfo(ctx)).build()
428 feedEncrypted(fwd, "e4")
429 await("e4") { events.filterIsInstance<WhatsAppEvent.IncomingMessage>().any { it.messageId == "e4" } }
430 val f = events.filterIsInstance<WhatsAppEvent.IncomingMessage>().first { it.messageId == "e4" }
431 assertTrue(f.body.contains("Forwarded") && f.body.contains("@You"), f.body)
432 val dsm = WhatsAppE2EProto.Message.newBuilder().setDeviceSentMessage(
433 WhatsAppE2EProto.DeviceSentMessage.newBuilder().setDestinationJid("[email protected]").setMessage(conv("from laptop")),
434 ).build()
435 feedEncrypted(dsm, "e5")
436 await("e5") { events.filterIsInstance<WhatsAppEvent.MessageUpdate>().any { it.messageId == "e5" } }
437 val own = events.filterIsInstance<WhatsAppEvent.MessageUpdate>().first { it.messageId == "e5" }
438 assertTrue(own.outgoing); assertEquals("wa:[email protected]", own.conversationId)
439 }
440
441 @Test
442 fun `encrypted revoke edit dedup ephemeral and reactions consume the stanza`() {
443 fun key(id: String) = WhatsAppE2EProto.MessageKey.newBuilder().setId(id).setFromMe(false).setRemoteJid(PEER_JID).build()
444 val revoke = WhatsAppE2EProto.Message.newBuilder().setProtocolMessage(
445 WhatsAppE2EProto.ProtocolMessage.newBuilder().setType(WhatsAppE2EProto.ProtocolMessage.Type.REVOKE).setKey(key("target-1")),
446 ).build()
447 feedEncrypted(revoke, "r1")
448 await("revoke") { events.filterIsInstance<WhatsAppEvent.MessageDeleted>().any { it.messageId == "target-1" } }
449 fun edit(body: String) = WhatsAppE2EProto.Message.newBuilder().setProtocolMessage(
450 WhatsAppE2EProto.ProtocolMessage.newBuilder().setType(WhatsAppE2EProto.ProtocolMessage.Type.MESSAGE_EDIT)
451 .setKey(key("target-2")).setEditedMessage(conv(body)),
452 ).build()
453 feedEncrypted(edit("edited body"), "edit-1")
454 await("edit") { events.filterIsInstance<WhatsAppEvent.MessageEdited>().any { it.newBody == "edited body" } }
455 feedEncrypted(edit("edited again"), "edit-1")
456 // No settle wait needed for the count: dedup is an atomic
457 // ConcurrentHashMap-set add (processedEditIDs), so whenever the
458 // duplicate stanza is processed it emits nothing — the count is 1
459 // at every instant after the first edit above, loaded or not.
460 assertEquals(1, events.filterIsInstance<WhatsAppEvent.MessageEdited>().size)
461 val eph = WhatsAppE2EProto.Message.newBuilder().setProtocolMessage(
462 WhatsAppE2EProto.ProtocolMessage.newBuilder().setType(WhatsAppE2EProto.ProtocolMessage.Type.EPHEMERAL_SETTING).setEphemeralExpiration(86400),
463 ).build()
464 feedEncrypted(eph, "eph1")
465 await("eph") { events.filterIsInstance<WhatsAppEvent.IncomingMessage>().any { it.messageId == "eph1" } }
466 fun reaction(emoji: String) = WhatsAppE2EProto.Message.newBuilder().setReactionMessage(
467 WhatsAppE2EProto.ReactionMessage.newBuilder().setKey(key("target-3")).setText(emoji),
468 ).build()
469 feedEncrypted(reaction("👍"), "rx1")
470 await("reaction") { events.filterIsInstance<WhatsAppEvent.ReactionReceived>().any { it.messageId == "target-3" } }
471 feedEncrypted(reaction(""), "rx2")
472 await("reaction removed") { events.filterIsInstance<WhatsAppEvent.ReactionRemoved>().any { it.messageId == "target-3" } }
473 }
474
475 @Test
476 fun `encrypted poll creation stores options and poll vote decrypts to names`() {
477 val secret = ByteArray(32) { (it * 3 + 5).toByte() }
478 val poll = WhatsAppE2EProto.Message.newBuilder()
479 .setPollCreationMessageV3(
480 WhatsAppE2EProto.PollCreationMessage.newBuilder().setName("Lunch?")
481 .addOptions(WhatsAppE2EProto.PollCreationMessage.Option.newBuilder().setOptionName("Pizza"))
482 .addOptions(WhatsAppE2EProto.PollCreationMessage.Option.newBuilder().setOptionName("Sushi")),
483 )
484 .setMessageContextInfo(WhatsAppE2EProto.MessageContextInfo.newBuilder().setMessageSecret(ByteString.copyFrom(secret)))
485 .build()
486 feedEncrypted(poll, "poll-1")
487 await("poll") { events.filterIsInstance<WhatsAppEvent.IncomingMessage>().any { it.messageId == "poll-1" } }
488 val p = events.filterIsInstance<WhatsAppEvent.IncomingMessage>().first { it.messageId == "poll-1" }
489 assertEquals("Lunch?", p.pollQuestion); assertEquals(listOf("Pizza", "Sushi"), p.pollOptions)
490 val hash = MessageDigest.getInstance("SHA-256").digest("Sushi".toByteArray())
491 val voteMsg = WhatsAppProtocol.buildPollVoteMessage(PEER_JID, "poll-1", PEER_JID, pollFromMe = false, PEER_JID, listOf(hash), secret)
492 feedEncrypted(voteMsg, "vote-1")
493 await("vote") { events.filterIsInstance<WhatsAppEvent.PollVote>().any { it.pollMessageId == "poll-1" } }
494 val v = events.filterIsInstance<WhatsAppEvent.PollVote>().first { it.pollMessageId == "poll-1" }
495 assertEquals(listOf("Sushi"), v.optionNames); assertEquals(PEER_JID, v.voterId)
496 val orphan = WhatsAppProtocol.buildPollVoteMessage(PEER_JID, "poll-unknown", PEER_JID, false, PEER_JID, listOf(hash), secret)
497 feedEncrypted(orphan, "vote-2"); Thread.sleep(400)
498 assertEquals(1, events.filterIsInstance<WhatsAppEvent.PollVote>().size)
499 }
500
501 @Test
502 fun `encrypted SKDM establishes sender key then group skmsg decrypts`() {
503 val app = ApplicationProvider.getApplicationContext<Application>()
504 val peerDb = Room.inMemoryDatabaseBuilder(app, WhatsAppDatabase::class.java)
505 .setSingleConnectionPool().allowMainThreadQueries().build()
506 val peer = WhatsAppE2E(peerDb, PEER)
507 peer.processPreKeyBundle(
508 AUTH.wid,
509 WhatsAppE2E.ParsedPreKeyBundle(AUTH.registrationId, null, null, AUTH.signedPreKeyId,
510 unb64(AUTH.signedPreKeyPublic), unb64(AUTH.signedPreKeySignature), unb64(AUTH.identityPublicKey)),
511 )
512 val skdmBytes = peer.createSenderKeyDistribution(GROUP_JID)
513 val skdmMsg = WhatsAppE2EProto.Message.newBuilder().setSenderKeyDistributionMessage(
514 WhatsAppE2EProto.SenderKeyDistributionMessage.newBuilder().setGroupId(GROUP_JID)
515 .setAxolotlSenderKeyDistributionMessage(ByteString.copyFrom(skdmBytes)),
516 ).build()
517 val enc1 = peer.encryptDM(AUTH.wid, WhatsAppProtocol.padMessage(skdmMsg.toByteArray()))
518 feed(
519 WhatsAppProtocol.Node(tag = "message", attrs = mapOf("from" to GROUP_JID, "id" to "skdm-1", "type" to "text", "participant" to PEER_JID),
520 content = listOf(WhatsAppProtocol.Node(tag = "enc", attrs = mapOf("type" to enc1.type), data = enc1.data))),
521 )
522 Thread.sleep(600)
523 assertTrue(events.filterIsInstance<WhatsAppEvent.IncomingMessage>().none { it.messageId == "skdm-1" })
524 val groupCipher = peer.encryptGroup(GROUP_JID, WhatsAppProtocol.padMessage(conv("group secret").toByteArray()))
525 feed(
526 WhatsAppProtocol.Node(tag = "message", attrs = mapOf("from" to GROUP_JID, "id" to "g1", "type" to "text", "participant" to PEER_JID),
527 content = listOf(WhatsAppProtocol.Node(tag = "enc", attrs = mapOf("type" to "skmsg"), data = groupCipher))),
528 )
529 await("group msg") { events.filterIsInstance<WhatsAppEvent.IncomingMessage>().any { it.messageId == "g1" } }
530 assertEquals("group secret", events.filterIsInstance<WhatsAppEvent.IncomingMessage>().first { it.messageId == "g1" }.body)
531 }
532
533 @Test
534 fun `encrypted history sync and app-state key share protocol messages are routed`() {
535 val history = WhatsAppE2EProto.HistorySync.newBuilder().setSyncType(0)
536 .addConversations(
537 WhatsAppE2EProto.HsConversation.newBuilder().setId(PEER_JID).setName("Peer")
538 .addMessages(
539 WhatsAppE2EProto.HistorySyncMsg.newBuilder().setMessage(
540 WhatsAppE2EProto.WebMessageInfo.newBuilder()
541 .setKey(WhatsAppE2EProto.HsMsgKey.newBuilder().setId("h1").setFromMe(false).setRemoteJid(PEER_JID))
542 .setMessage(conv("hist hello")).setMessageTimestamp(1700000000L),
543 ),
544 ),
545 ).build()
546 fun deflate(data: ByteArray): ByteArray {
547 val d = java.util.zip.Deflater(); d.setInput(data); d.finish()
548 val out = ByteArrayOutputStream(); val buf = ByteArray(4096)
549 while (!d.finished()) out.write(buf, 0, d.deflate(buf)); d.end(); return out.toByteArray()
550 }
551 val histMsg = WhatsAppE2EProto.Message.newBuilder().setProtocolMessage(
552 WhatsAppE2EProto.ProtocolMessage.newBuilder().setType(WhatsAppE2EProto.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION)
553 .setHistorySyncNotification(
554 WhatsAppE2EProto.HistorySyncNotification.newBuilder()
555 .setInitialHistBootstrapInlinePayload(ByteString.copyFrom(deflate(history.toByteArray()))),
556 ),
557 ).build()
558 feedEncrypted(histMsg, "hist-notif")
559 await("hist") { events.filterIsInstance<WhatsAppEvent.MessageUpdate>().any { it.body == "hist hello" } }
560 val shareMsg = WhatsAppE2EProto.Message.newBuilder().setProtocolMessage(
561 WhatsAppE2EProto.ProtocolMessage.newBuilder().setType(WhatsAppE2EProto.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE)
562 .setAppStateSyncKeyShare(
563 WhatsAppE2EProto.AppStateSyncKeyShare.newBuilder().addKeys(
564 WhatsAppE2EProto.AppStateSyncKey.newBuilder()
565 .setKeyId(WhatsAppE2EProto.AppStateSyncKeyId.newBuilder().setKeyId(ByteString.copyFrom(byteArrayOf(7, 7))))
566 .setKeyData(WhatsAppE2EProto.AppStateSyncKeyData.newBuilder().setKeyData(ByteString.copyFrom(ByteArray(32) { 9 }))),
567 ),
568 ),
569 ).build()
570 feedEncrypted(shareMsg, "share-1")
571 await("share") { WhatsAppDiag.log.value.any { it.contains("stored 1 sync key(s)") } }
572 }
573
574 @Test
575 fun `group operations validate state jid action and fail soft on dead socket`() = runTest {
576 assertEquals(emptyList(), WhatsAppClient.queryGroupParticipants(GROUP_JID))
577 assertEquals(emptyList(), WhatsAppClient.getUserDevices(emptyList()))
578 assertEquals(emptyList(), WhatsAppClient.getUserDevices(listOf("777", PEER_JID, "777:[email protected]")))
579 assertFalse(WhatsAppClient.setGroupName(GROUP_JID, "Name"))
580 assertFalse(WhatsAppClient.setGroupName(PEER_JID, "Name"))
581 assertFalse(WhatsAppClient.setGroupName("wa:", "Name"))
582 assertFalse(WhatsAppClient.setGroupTopic(GROUP_JID, "Topic", previousTopicId = "old"))
583 assertFalse(WhatsAppClient.updateGroupParticipants(GROUP_JID, listOf(PEER_JID), "add"))
584 assertFalse(WhatsAppClient.updateGroupParticipants(GROUP_JID, listOf(PEER_JID), "demote"))
585 assertFalse(WhatsAppClient.updateGroupParticipants(GROUP_JID, listOf(PEER_JID), "explode"))
586 assertFalse(WhatsAppClient.updateGroupParticipants(PEER_JID, listOf(PEER_JID), "add"))
587 assertNull(WhatsAppClient.createGroup("Subject", listOf(PEER_JID)))
588 assertNull(WhatsAppClient.createGroup("Subject", emptyList()))
589 WhatsAppClient.stateMutable.value = WhatsAppClient.State.Idle
590 assertFalse(WhatsAppClient.setGroupName(GROUP_JID, "Name"))
591 assertFalse(WhatsAppClient.setGroupTopic(GROUP_JID, "Topic"))
592 assertFalse(WhatsAppClient.updateGroupParticipants(GROUP_JID, listOf(PEER_JID), "add"))
593 assertFalse(WhatsAppClient.setGroupAvatar(GROUP_JID, ByteArray(4)))
594 assertNull(WhatsAppClient.createGroup("Subject", listOf(PEER_JID)))
595 WhatsAppClient.stateMutable.value = WhatsAppClient.State.Connected
596 WhatsAppClient.fetchAndEmitGroupInfo(PEER_JID)
597 WhatsAppClient.knownGroups.add(GROUP_JID); WhatsAppClient.fetchAndEmitGroupInfo(GROUP_JID)
598 WhatsAppClient.knownGroups.remove(GROUP_JID); WhatsAppClient.fetchAndEmitGroupInfo(GROUP_JID)
599 assertFalse(WhatsAppClient.knownGroups.contains(GROUP_JID))
600 }
601
602 @Test
603 fun `avatar crop scales small and large images to jpeg bounds`() = runTest {
604 fun png(w: Int, h: Int): ByteArray {
605 val bmp = android.graphics.Bitmap.createBitmap(w, h, android.graphics.Bitmap.Config.ARGB_8888)
606 return ByteArrayOutputStream().also { bmp.compress(android.graphics.Bitmap.CompressFormat.PNG, 100, it) }.toByteArray()
607 }
608 for ((w, h) in listOf(100 to 50, 800 to 400, 300 to 300)) {
609 val out = WhatsAppClient.cropResizeAvatar(png(w, h))
610 assertNotNull(out); assertTrue(out.size > 2)
611 assertEquals(0xFF.toByte(), out[0]); assertEquals(0xD8.toByte(), out[1])
612 }
613 assertFalse(WhatsAppClient.setGroupAvatar(PEER_JID, png(200, 200)))
614 assertFalse(WhatsAppClient.setGroupAvatar(GROUP_JID, png(200, 200)))
615 }
616
617 @Test
618 fun `utils jid name mention sender and generator edge cases`() = runTest {
619 assertEquals(PEER_JID, WhatsAppClient.extractJid("wa:wa:$PEER_JID")); assertNull(WhatsAppClient.extractJid("wa:"))
620 WhatsAppClient.lidToPhoneMap["[email protected]"] = PEER_JID
621 assertEquals(PEER_JID, WhatsAppClient.resolveJID("777@lid"))
622 assertEquals(AUTH.wid, WhatsAppClient.resolveJID("12345@lid"))
623 assertEquals("zzz@lid", WhatsAppClient.resolveJID("zzz@lid"))
624 assertEquals(GROUP_JID, WhatsAppClient.resolveJID(GROUP_JID))
625 assertTrue(WhatsAppClient.isOwnJid("15550001:[email protected]"))
626 assertTrue(WhatsAppClient.isOwnJid("12345@lid")); assertFalse(WhatsAppClient.isOwnJid("[email protected]"))
627 assertFalse(WhatsAppClient.isOwnJid(null)); assertFalse(WhatsAppClient.isOwnJid("@s.whatsapp.net"))
628 assertNull(WhatsAppClient.resolveDeviceContactName(null)); assertNull(WhatsAppClient.resolveDeviceContactName(""))
629 assertEquals("Meta AI", WhatsAppClient.resolveName("0@bot"))
630 assertEquals("+12345", WhatsAppClient.resolveName("[email protected]"))
631 assertEquals("hi @You and @Meta AI", WhatsAppClient.resolveMentionsInBody("hi @15550001 and @0", listOf(AUTH.wid, "0@bot")))
632 assertEquals("plain", WhatsAppClient.resolveMentionsInBody("plain", listOf(PEER_JID)))
633 val (sender, fromMe) = WhatsAppClient.resolveChatSender(
634 com.vayunmathur.communicate.data.whatsapp.WhatsAppMessage(id = "x", from = GROUP_JID, to = "", body = "b", timestamp = 1, type = "text", participant = "67890@lid"),
635 )
636 assertEquals("67890@lid", sender); assertFalse(fromMe)
637 assertEquals(24, WhatsAppClient.generateRef().length); assertEquals(24, WhatsAppClient.generateClientId().length)
638 assertEquals(32, WhatsAppClient.generateToken().length)
639 assertTrue(WhatsAppClient.isLoggedIn())
640 WhatsAppClient.stateMutable.value = WhatsAppClient.State.Idle; assertFalse(WhatsAppClient.isLoggedIn())
641 WhatsAppClient.stateMutable.value = WhatsAppClient.State.Connected
642 WhatsAppClient.nameCache.clear()
643 repeat(12) { WhatsAppClient.nameCache["[email protected]"] = "User $it" }
644 assertEquals(10, WhatsAppClient.getContactSuggestions("user").size)
645 assertEquals("User 3", WhatsAppClient.getContactSuggestions("user 3").single().displayName)
646 assertNull(WhatsAppClient.buildIncomingMediaAttachment(conv("hi"), "m1"))
647 val noKey = WhatsAppE2EProto.Message.newBuilder()
648 .setImageMessage(WhatsAppE2EProto.ImageMessage.newBuilder().setUrl("https://example.invalid/x")).build()
649 assertNull(WhatsAppClient.buildIncomingMediaAttachment(noKey, "m2"))
650 val noUrl = WhatsAppE2EProto.Message.newBuilder()
651 .setDocumentMessage(WhatsAppE2EProto.DocumentMessage.newBuilder().setMediaKey(ByteString.copyFrom(ByteArray(32)))).build()
652 assertNull(WhatsAppClient.buildIncomingMediaAttachment(noUrl, "m3"))
653 WhatsAppClient.logoutRemote(); Thread.sleep(300)
654 }
655}