Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / communicate-dev / src / test / java / com / vayunmathur / communicate / whatsapp / Y1WaE2eSyncTest.kt
Y1WaE2eSyncTest.kt543 lines · 34.7 KiBRaw
| 1 | package com.vayunmathur.communicate.whatsapp |
| 2 | |
| 3 | import android.app.Application |
| 4 | import android.util.Base64 |
| 5 | import androidx.room3.Room |
| 6 | import androidx.test.core.app.ApplicationProvider |
| 7 | import androidx.test.ext.junit.runners.AndroidJUnit4 |
| 8 | import com.google.protobuf.ByteString |
| 9 | import com.vayunmathur.communicate.data.whatsapp.WhatsAppAuthData |
| 10 | import com.vayunmathur.communicate.data.whatsapp.WhatsAppClient |
| 11 | import com.vayunmathur.communicate.data.whatsapp.WhatsAppConversation |
| 12 | import com.vayunmathur.communicate.data.whatsapp.WhatsAppDatabase |
| 13 | import com.vayunmathur.communicate.data.whatsapp.WhatsAppDiag |
| 14 | import com.vayunmathur.communicate.data.whatsapp.WhatsAppEvent |
| 15 | import com.vayunmathur.communicate.data.whatsapp.WhatsAppPollSecret |
| 16 | import com.vayunmathur.communicate.data.whatsapp.WhatsAppProtocol |
| 17 | import com.vayunmathur.communicate.data.whatsapp.appStateVersion |
| 18 | import com.vayunmathur.communicate.data.whatsapp.applyAppStateRecord |
| 19 | import com.vayunmathur.communicate.data.whatsapp.downloadAppStateBlob |
| 20 | import com.vayunmathur.communicate.data.whatsapp.e2e.RustWhatsAppCrypto |
| 21 | import com.vayunmathur.communicate.data.whatsapp.e2e.WhatsAppE2E |
| 22 | import com.vayunmathur.communicate.data.whatsapp.emitHistoryConversation |
| 23 | import com.vayunmathur.communicate.data.whatsapp.expandAppStateKeys |
| 24 | import com.vayunmathur.communicate.data.whatsapp.fetchAppStateCollection |
| 25 | import com.vayunmathur.communicate.data.whatsapp.getAppStateKey |
| 26 | import com.vayunmathur.communicate.data.whatsapp.handleAppStateKeyShare |
| 27 | import com.vayunmathur.communicate.data.whatsapp.handleHistorySync |
| 28 | import com.vayunmathur.communicate.data.whatsapp.inflateZlib |
| 29 | import com.vayunmathur.communicate.data.whatsapp.kickoffBackfill |
| 30 | import com.vayunmathur.communicate.data.whatsapp.loadPollSecret |
| 31 | import com.vayunmathur.communicate.data.whatsapp.padMessage |
| 32 | import com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppAppStateProto |
| 33 | import com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto |
| 34 | import com.vayunmathur.communicate.data.whatsapp.requestAppStateKey |
| 35 | import com.vayunmathur.communicate.data.whatsapp.sendHistoryOnDemandRequest |
| 36 | import com.vayunmathur.communicate.data.whatsapp.sendHistorySyncReceipt |
| 37 | import com.vayunmathur.communicate.data.whatsapp.setAppStateVersion |
| 38 | import com.vayunmathur.communicate.data.whatsapp.storeAppStateKey |
| 39 | import com.vayunmathur.communicate.data.whatsapp.storePollOptions |
| 40 | import com.vayunmathur.communicate.data.whatsapp.storePollSecret |
| 41 | import com.vayunmathur.communicate.data.whatsapp.transport.WhatsAppSocket |
| 42 | import com.vayunmathur.communicate.data.whatsapp.unpadMessage |
| 43 | import java.io.ByteArrayOutputStream |
| 44 | import java.security.MessageDigest |
| 45 | import java.util.Collections |
| 46 | import java.util.zip.Deflater |
| 47 | import javax.crypto.Cipher |
| 48 | import javax.crypto.spec.IvParameterSpec |
| 49 | import javax.crypto.spec.SecretKeySpec |
| 50 | import kotlin.test.AfterTest |
| 51 | import kotlin.test.BeforeTest |
| 52 | import kotlin.test.Test |
| 53 | import kotlin.test.assertEquals |
| 54 | import kotlin.test.assertFailsWith |
| 55 | import kotlin.test.assertFalse |
| 56 | import kotlin.test.assertNotNull |
| 57 | import kotlin.test.assertNull |
| 58 | import kotlin.test.assertTrue |
| 59 | import kotlinx.coroutines.CoroutineScope |
| 60 | import kotlinx.coroutines.cancel |
| 61 | import kotlinx.coroutines.Dispatchers |
| 62 | import kotlinx.coroutines.Job |
| 63 | import kotlinx.coroutines.launch |
| 64 | import kotlinx.coroutines.test.runTest |
| 65 | import org.junit.runner.RunWith |
| 66 | |
| 67 | /** |
| 68 | * Y1: WhatsAppE2E (real host-Rust X3DH/Double-Ratchet/sender-key round trips and |
| 69 | * bundle-node parsing) plus WhatsAppClientSync (app-state keys/records, poll |
| 70 | * stores, history-sync emission and on-demand pagination guards). |
| 71 | */ |
| 72 | @RunWith(AndroidJUnit4::class) |
| 73 | class Y1WaE2eSyncTest { |
| 74 | |
| 75 | companion object { |
| 76 | fun b64(b: ByteArray): String = Base64.encodeToString(b, Base64.NO_WRAP) |
| 77 | fun unb64(s: String): ByteArray = Base64.decode(s, Base64.NO_WRAP) |
| 78 | fun authFor(idSeed: Int, spkSeed: Int, wid: String, reg: Int): WhatsAppAuthData { |
| 79 | val idPriv = ByteArray(32) { (idSeed + it).toByte() } |
| 80 | val idPub = RustWhatsAppCrypto.publicFromPrivate(idPriv)!! |
| 81 | val spkPriv = ByteArray(32) { (spkSeed + it).toByte() } |
| 82 | val spkPub = RustWhatsAppCrypto.publicFromPrivate(spkPriv)!! |
| 83 | return WhatsAppAuthData( |
| 84 | phoneNumber = "+15550001", pushName = "Tester", wid = wid, |
| 85 | noisePrivateKey = b64(ByteArray(32) { 1 }), noisePublicKey = b64(ByteArray(32) { 2 }), |
| 86 | identityPrivateKey = b64(idPriv), identityPublicKey = b64(idPub), |
| 87 | registrationId = reg, signedPreKeyId = 5, |
| 88 | signedPreKeyPublic = b64(spkPub), signedPreKeyPrivate = b64(spkPriv), |
| 89 | signedPreKeySignature = b64(WhatsAppE2E.signSignedPreKey(idPriv, spkPub)), lid = "12345@lid", |
| 90 | ) |
| 91 | } |
| 92 | val ALICE: WhatsAppAuthData by lazy { authFor(1, 41, "[email protected]", 14) } |
| 93 | val BOB: WhatsAppAuthData by lazy { authFor(101, 141, "[email protected]", 99) } |
| 94 | const val GROUP = "[email protected]" |
| 95 | } |
| 96 | |
| 97 | private lateinit var dbA: WhatsAppDatabase |
| 98 | private lateinit var dbB: WhatsAppDatabase |
| 99 | private val events = Collections.synchronizedList(mutableListOf<WhatsAppEvent>()) |
| 100 | |
| 101 | private fun newDb(): WhatsAppDatabase { |
| 102 | val app = ApplicationProvider.getApplicationContext<Application>() |
| 103 | return Room.inMemoryDatabaseBuilder(app, WhatsAppDatabase::class.java) |
| 104 | .setSingleConnectionPool().allowMainThreadQueries().build() |
| 105 | } |
| 106 | |
| 107 | @BeforeTest |
| 108 | fun setUp() { |
| 109 | val app = ApplicationProvider.getApplicationContext<Application>() |
| 110 | dbA = newDb(); dbB = newDb() |
| 111 | WhatsAppClient.appContext = app |
| 112 | WhatsAppClient.authData = ALICE |
| 113 | WhatsAppClient.db = dbA |
| 114 | WhatsAppClient.webSocket = WhatsAppSocket(ALICE) |
| 115 | WhatsAppClient.stateMutable.value = WhatsAppClient.State.Connected |
| 116 | WhatsAppClient.fullHistorySync = false |
| 117 | WhatsAppClient.nameCache.clear(); WhatsAppClient.lidToPhoneMap.clear() |
| 118 | WhatsAppClient.pollSecrets.clear(); WhatsAppClient.onDemandRequested.clear() |
| 119 | WhatsAppClient.onDemandPageCount.clear(); WhatsAppClient.appStateCollectionsFetching.clear() |
| 120 | WhatsAppClient.appStateKeyRequested.clear() |
| 121 | WhatsAppDiag.clear(); events.clear() |
| 122 | eventScope = CoroutineScope(Dispatchers.Default + Job()) |
| 123 | eventScope.launch { WhatsAppClient.events.collect { events.add(it) } } |
| 124 | } |
| 125 | |
| 126 | private lateinit var eventScope: CoroutineScope |
| 127 | |
| 128 | @AfterTest |
| 129 | fun tearDown() { |
| 130 | eventScope.cancel() |
| 131 | } |
| 132 | |
| 133 | private fun bundleFor(auth: WhatsAppAuthData, withOneTime: Pair<Int, ByteArray>? = null) = |
| 134 | WhatsAppE2E.ParsedPreKeyBundle( |
| 135 | registrationId = auth.registrationId, |
| 136 | preKeyId = withOneTime?.first, preKeyPublic = withOneTime?.second, |
| 137 | signedPreKeyId = auth.signedPreKeyId, signedPreKeyPublic = unb64(auth.signedPreKeyPublic), |
| 138 | signedPreKeySignature = unb64(auth.signedPreKeySignature), identityKey = unb64(auth.identityPublicKey), |
| 139 | ) |
| 140 | |
| 141 | private fun deflate(data: ByteArray): ByteArray { |
| 142 | val d = Deflater(); d.setInput(data); d.finish() |
| 143 | val out = ByteArrayOutputStream(); val buf = ByteArray(4096) |
| 144 | while (!d.finished()) out.write(buf, 0, d.deflate(buf)); d.end(); return out.toByteArray() |
| 145 | } |
| 146 | |
| 147 | // ---------- E2E: addressing, prekey-id scan, signing ---------- |
| 148 | |
| 149 | @Test |
| 150 | fun `signal address parsing and parsePreKeyIdFromMessage wire scan`() { |
| 151 | val e2e = WhatsAppE2E(dbA, ALICE) |
| 152 | assertEquals("15550002" to 0, e2e.signalAddress("[email protected]")) |
| 153 | assertEquals("15550002" to 7, e2e.signalAddress("15550002:[email protected]")) |
| 154 | assertEquals("15550002" to 0, e2e.signalAddress("[email protected]")) |
| 155 | assertEquals("15550002" to 0, e2e.signalAddress("15550002:[email protected]")) |
| 156 | assertEquals("x" to 0, e2e.signalAddress("x@lid")) |
| 157 | // version byte, field1 varint 42 |
| 158 | assertEquals(42, WhatsAppE2E.parsePreKeyIdFromMessage(byteArrayOf(0x33, 0x08, 42))) |
| 159 | // field2 length-delimited skipped, then field1 = 300 (varint) |
| 160 | assertEquals(300, WhatsAppE2E.parsePreKeyIdFromMessage(byteArrayOf(0x33, 0x12, 2, 1, 2, 0x08, 0xAC.toByte(), 0x02))) |
| 161 | assertNull(WhatsAppE2E.parsePreKeyIdFromMessage(ByteArray(0))) |
| 162 | assertNull(WhatsAppE2E.parsePreKeyIdFromMessage(byteArrayOf(0x33, 0x08))) // truncated varint value |
| 163 | assertNull(WhatsAppE2E.parsePreKeyIdFromMessage(byteArrayOf(0x33, 0x12, 9, 1))) // truncated len field |
| 164 | assertNull(WhatsAppE2E.parsePreKeyIdFromMessage(byteArrayOf(0x33, 0x10, 5))) // field2 varint, no field1 |
| 165 | // XEdDSA sign/verify through Rust, tamper fails. |
| 166 | val msg = byteArrayOf(5) + unb64(ALICE.signedPreKeyPublic) |
| 167 | val sig = WhatsAppE2E.signSignedPreKey(unb64(ALICE.identityPrivateKey), unb64(ALICE.signedPreKeyPublic)) |
| 168 | assertEquals(64, sig.size) |
| 169 | assertTrue(RustWhatsAppCrypto.verify(unb64(ALICE.identityPublicKey), msg, sig)) |
| 170 | assertFalse(RustWhatsAppCrypto.verify(unb64(ALICE.identityPublicKey), byteArrayOf(9, 9), sig)) |
| 171 | e2e.ensureSignedPreKeyStored() // documented no-op |
| 172 | assertTrue(RustWhatsAppCrypto.isAvailable) |
| 173 | } |
| 174 | |
| 175 | // ---------- E2E: DM round trip both directions ---------- |
| 176 | |
| 177 | @Test |
| 178 | fun `x3dh session encrypt decrypt round trip and session lifecycle`() { |
| 179 | val alice = WhatsAppE2E(dbA, ALICE); val bob = WhatsAppE2E(dbB, BOB) |
| 180 | assertFalse(alice.hasSession(BOB.wid)); assertFalse(bob.hasSession(ALICE.wid)) |
| 181 | assertFailsWith<IllegalStateException> { alice.encryptDM(BOB.wid, WhatsAppProtocol.padMessage("x".toByteArray())) } |
| 182 | assertFailsWith<IllegalStateException> { bob.decryptDM(ALICE.wid, isPreKey = false, ciphertext = byteArrayOf(1)) } |
| 183 | |
| 184 | bob.processPreKeyBundle(ALICE.wid, bundleFor(ALICE)) |
| 185 | assertTrue(bob.hasSession(ALICE.wid)) |
| 186 | val proto = WhatsAppE2EProto.Message.newBuilder().setConversation("hello alice").build() |
| 187 | val first = bob.encryptDM(ALICE.wid, WhatsAppProtocol.padMessage(proto.toByteArray())) |
| 188 | assertEquals("pkmsg", first.type) |
| 189 | val plain1 = alice.decryptDM(BOB.wid, isPreKey = true, ciphertext = first.data) |
| 190 | assertEquals("hello alice", WhatsAppE2EProto.Message.parseFrom(WhatsAppProtocol.unpadMessage(plain1)).conversation) |
| 191 | assertTrue(alice.hasSession(BOB.wid)) |
| 192 | |
| 193 | // Reply on the established (non-prekey) ratchet, decrypted as msg. |
| 194 | val reply = alice.encryptDM(BOB.wid, WhatsAppProtocol.padMessage( |
| 195 | WhatsAppE2EProto.Message.newBuilder().setConversation("hi bob").build().toByteArray())) |
| 196 | assertEquals("msg", reply.type) |
| 197 | val plain2 = bob.decryptDM(ALICE.wid, isPreKey = false, ciphertext = reply.data) |
| 198 | assertEquals("hi bob", WhatsAppE2EProto.Message.parseFrom(WhatsAppProtocol.unpadMessage(plain2)).conversation) |
| 199 | |
| 200 | // Garbage pkmsg and tampered msg both fail (Rust throws), never yield plaintext. |
| 201 | assertFailsWith<Exception> { alice.decryptDM(BOB.wid, isPreKey = true, ciphertext = byteArrayOf(1, 2, 3)) } |
| 202 | alice.deleteSession(BOB.wid); assertFalse(alice.hasSession(BOB.wid)) |
| 203 | alice.deleteSession("[email protected]") // absent delete is fine |
| 204 | } |
| 205 | |
| 206 | @Test |
| 207 | fun `one-time prekey is consumed on inbound pkmsg decrypt`() = runTest { |
| 208 | val alice = WhatsAppE2E(dbA, ALICE); val bob = WhatsAppE2E(dbB, BOB) |
| 209 | // Alice seeds one-time prekeys via the retry-keys builder (stores id 1 in her DB). |
| 210 | val keysNode = alice.buildRetryReceiptKeysNode(accountDeviceIdentity = byteArrayOf(4, 5)) |
| 211 | val keyNode = keysNode.getChildren().first { it.tag == "key" } |
| 212 | val oneTimeId = keyNode.getChildByTag("id")!!.data!!.let { ((it[0].toInt() and 0xFF) shl 16) or ((it[1].toInt() and 0xFF) shl 8) or (it[2].toInt() and 0xFF) } |
| 213 | val oneTimePub = keyNode.getChildByTag("value")!!.data!! |
| 214 | assertNotNull(dbA.e2ePreKeyDao().get(oneTimeId)) |
| 215 | bob.processPreKeyBundle(ALICE.wid, bundleFor(ALICE, withOneTime = oneTimeId to oneTimePub)) |
| 216 | val enc = bob.encryptDM(ALICE.wid, WhatsAppProtocol.padMessage( |
| 217 | WhatsAppE2EProto.Message.newBuilder().setConversation("with otp").build().toByteArray())) |
| 218 | val plain = alice.decryptDM(BOB.wid, isPreKey = true, ciphertext = enc.data) |
| 219 | assertEquals("with otp", WhatsAppE2EProto.Message.parseFrom(WhatsAppProtocol.unpadMessage(plain)).conversation) |
| 220 | assertNull(dbA.e2ePreKeyDao().get(oneTimeId)) // one-time key deleted after use |
| 221 | } |
| 222 | |
| 223 | // ---------- E2E: bundle node parsing + upload content ---------- |
| 224 | |
| 225 | private fun idBytes(id: Int) = byteArrayOf((id shr 16).toByte(), (id shr 8).toByte(), id.toByte()) |
| 226 | private fun keyChild(tag: String, id: Int, value: ByteArray, sig: ByteArray? = null) = WhatsAppProtocol.Node( |
| 227 | tag = tag, content = listOfNotNull( |
| 228 | WhatsAppProtocol.Node(tag = "id", data = idBytes(id)), |
| 229 | WhatsAppProtocol.Node(tag = "value", data = value), |
| 230 | sig?.let { WhatsAppProtocol.Node(tag = "signature", data = it) }, |
| 231 | ), |
| 232 | ) |
| 233 | |
| 234 | @Test |
| 235 | fun `parsePreKeyBundleNode accepts valid and rejects malformed bundles`() { |
| 236 | val e2e = WhatsAppE2E(dbA, ALICE) |
| 237 | val reg = WhatsAppProtocol.Node(tag = "registration", data = byteArrayOf(0, 0, 0, 99)) |
| 238 | val keys = WhatsAppProtocol.Node(tag = "keys", content = listOf( |
| 239 | WhatsAppProtocol.Node(tag = "identity", data = ByteArray(32) { 7 }), |
| 240 | keyChild("key", 12, ByteArray(32) { 8 }), |
| 241 | keyChild("skey", 5, ByteArray(32) { 9 }, ByteArray(64) { 3 }), |
| 242 | )) |
| 243 | val user = WhatsAppProtocol.Node(tag = "user", content = listOf(reg, keys)) |
| 244 | val parsed = e2e.parsePreKeyBundleNode(0, user)!! |
| 245 | assertEquals(99, parsed.registrationId); assertEquals(12, parsed.preKeyId) |
| 246 | assertEquals(5, parsed.signedPreKeyId); assertEquals(32, parsed.identityKey.size) |
| 247 | assertTrue(parsed.preKeyPublic!!.contentEquals(ByteArray(32) { 8 })) |
| 248 | // Bundle without the optional one-time key parses with null prekey. |
| 249 | val noOtpKeys = WhatsAppProtocol.Node(tag = "keys", content = listOf( |
| 250 | WhatsAppProtocol.Node(tag = "identity", data = ByteArray(32) { 7 }), |
| 251 | keyChild("skey", 5, ByteArray(32) { 9 }, ByteArray(64) { 3 }), |
| 252 | )) |
| 253 | val noOtp = e2e.parsePreKeyBundleNode(2, WhatsAppProtocol.Node(tag = "user", content = listOf(reg, noOtpKeys)))!! |
| 254 | assertNull(noOtp.preKeyId); assertNull(noOtp.preKeyPublic) |
| 255 | // Malformed variants all return null rather than throwing. |
| 256 | assertNull(e2e.parsePreKeyBundleNode(0, WhatsAppProtocol.Node(tag = "user", content = listOf( |
| 257 | WhatsAppProtocol.Node(tag = "error"), reg, keys)))) |
| 258 | assertNull(e2e.parsePreKeyBundleNode(0, WhatsAppProtocol.Node(tag = "user", content = listOf(keys)))) // no registration |
| 259 | assertNull(e2e.parsePreKeyBundleNode(0, WhatsAppProtocol.Node(tag = "user", content = listOf( |
| 260 | WhatsAppProtocol.Node(tag = "registration", data = byteArrayOf(1)), keys)))) // short registration |
| 261 | val badIdentity = WhatsAppProtocol.Node(tag = "keys", content = listOf( |
| 262 | WhatsAppProtocol.Node(tag = "identity", data = ByteArray(31)), |
| 263 | keyChild("skey", 5, ByteArray(32) { 9 }, ByteArray(64) { 3 }))) |
| 264 | assertNull(e2e.parsePreKeyBundleNode(0, WhatsAppProtocol.Node(tag = "user", content = listOf(reg, badIdentity)))) |
| 265 | val badSig = WhatsAppProtocol.Node(tag = "keys", content = listOf( |
| 266 | WhatsAppProtocol.Node(tag = "identity", data = ByteArray(32)), |
| 267 | keyChild("skey", 5, ByteArray(32) { 9 }, ByteArray(63)))) |
| 268 | assertNull(e2e.parsePreKeyBundleNode(0, WhatsAppProtocol.Node(tag = "user", content = listOf(reg, badSig)))) |
| 269 | val badKeyVal = WhatsAppProtocol.Node(tag = "keys", content = listOf( |
| 270 | WhatsAppProtocol.Node(tag = "identity", data = ByteArray(32)), |
| 271 | keyChild("key", 12, ByteArray(10)), |
| 272 | keyChild("skey", 5, ByteArray(32) { 9 }, ByteArray(64) { 3 }))) |
| 273 | // A malformed one-time key is treated as absent, not as a fatal bundle error. |
| 274 | val badKeyParsed = e2e.parsePreKeyBundleNode(0, WhatsAppProtocol.Node(tag = "user", content = listOf(reg, badKeyVal)))!! |
| 275 | assertNull(badKeyParsed.preKeyId); assertNull(badKeyParsed.preKeyPublic) |
| 276 | } |
| 277 | |
| 278 | @Test |
| 279 | fun `prekey upload content shape refill counts and uploaded marking`() = runTest { |
| 280 | val e2e = WhatsAppE2E(dbA, ALICE) |
| 281 | val content = e2e.buildPreKeyUploadContent(initialUpload = false) |
| 282 | assertEquals(listOf("registration", "type", "identity", "list", "skey"), content.map { it.tag }) |
| 283 | assertTrue(content[0].data!!.contentEquals(byteArrayOf(0, 0, 0, 14))) |
| 284 | assertTrue(content[1].data!!.contentEquals(byteArrayOf(5))) |
| 285 | assertTrue(content[2].data!!.contentEquals(unb64(ALICE.identityPublicKey))) |
| 286 | assertEquals(50, content[3].getChildren().size) |
| 287 | assertEquals(50, dbA.e2ePreKeyDao().getCount()) |
| 288 | assertEquals(50, dbA.e2ePreKeyDao().getUnuploaded().size) |
| 289 | e2e.markPreKeysUploaded() |
| 290 | assertEquals(0, dbA.e2ePreKeyDao().getUnuploaded().size) |
| 291 | // Refill continues ids from the stored max, never reusing one-time ids. |
| 292 | val again = e2e.buildPreKeyUploadContent(initialUpload = false) |
| 293 | assertEquals(100, dbA.e2ePreKeyDao().getCount()) |
| 294 | val firstIds = content[3].getChildren().map { it.getChildByTag("id")!!.data!!.joinToString("") { b -> "%02x".format(b) } }.toSet() |
| 295 | val secondIds = again[3].getChildren().map { it.getChildByTag("id")!!.data!!.joinToString("") { b -> "%02x".format(b) } }.toSet() |
| 296 | assertTrue(firstIds.intersect(secondIds).isEmpty()) |
| 297 | // Retry keys node: with and without device identity. |
| 298 | val withId = e2e.buildRetryReceiptKeysNode(byteArrayOf(1, 2)) |
| 299 | assertEquals(listOf("type", "identity", "key", "skey", "device-identity"), withId.getChildren().map { it.tag }) |
| 300 | val without = e2e.buildRetryReceiptKeysNode(null) |
| 301 | assertEquals(listOf("type", "identity", "key", "skey"), without.getChildren().map { it.tag }) |
| 302 | } |
| 303 | |
| 304 | // ---------- E2E: sender keys ---------- |
| 305 | |
| 306 | @Test |
| 307 | fun `sender key distribution group round trip and failure modes`() { |
| 308 | val alice = WhatsAppE2E(dbA, ALICE); val bob = WhatsAppE2E(dbB, BOB) |
| 309 | val skdm = alice.createSenderKeyDistribution(GROUP) |
| 310 | assertTrue(skdm.isNotEmpty()) |
| 311 | bob.processSenderKeyDistribution(GROUP, ALICE.wid, skdm) |
| 312 | val proto = WhatsAppE2EProto.Message.newBuilder().setConversation("group hello").build() |
| 313 | val cipher = alice.encryptGroup(GROUP, WhatsAppProtocol.padMessage(proto.toByteArray())) |
| 314 | val plain = bob.decryptGroup(GROUP, ALICE.wid, cipher) |
| 315 | assertEquals("group hello", WhatsAppE2EProto.Message.parseFrom(WhatsAppProtocol.unpadMessage(plain)).conversation) |
| 316 | // Second creation rotates the sender key; a fresh peer can still join from the new SKDM. |
| 317 | val dbC = newDb(); val carol = WhatsAppE2E(dbC, authFor(201, 241, "[email protected]", 7)) |
| 318 | val skdm2 = alice.createSenderKeyDistribution(GROUP) |
| 319 | carol.processSenderKeyDistribution(GROUP, ALICE.wid, skdm2) |
| 320 | val cipher2 = alice.encryptGroup(GROUP, WhatsAppProtocol.padMessage(proto.toByteArray())) |
| 321 | assertEquals("group hello", WhatsAppE2EProto.Message.parseFrom( |
| 322 | WhatsAppProtocol.unpadMessage(carol.decryptGroup(GROUP, ALICE.wid, cipher2))).conversation) |
| 323 | // Failures: no sender key, garbage SKDM, tampered group ciphertext. |
| 324 | assertFailsWith<IllegalStateException> { carol.decryptGroup(GROUP, BOB.wid, cipher) } |
| 325 | assertFailsWith<Exception> { bob.processSenderKeyDistribution(GROUP, ALICE.wid, byteArrayOf(1, 2, 3)) } |
| 326 | assertFailsWith<Exception> { bob.decryptGroup(GROUP, ALICE.wid, cipher.copyOf().also { it[it.size - 1] = (it[it.size - 1] + 1).toByte() }) } |
| 327 | // Device-scoped addressing: distribution from a :3 device is a distinct sender key slot. |
| 328 | bob.processSenderKeyDistribution(GROUP, "15550001:[email protected]", skdm) |
| 329 | assertFailsWith<IllegalStateException> { bob.decryptGroup("[email protected]", ALICE.wid, cipher) } |
| 330 | } |
| 331 | |
| 332 | // ---------- Sync: app-state keys / versions / records ---------- |
| 333 | |
| 334 | @Test |
| 335 | fun `app state key store version and corrupted values`() = runTest { |
| 336 | WhatsAppClient.storeAppStateKey(byteArrayOf(1, 2), ByteArray(32) { 4 }) |
| 337 | assertTrue(WhatsAppClient.getAppStateKey(byteArrayOf(1, 2))!!.contentEquals(ByteArray(32) { 4 })) |
| 338 | assertNull(WhatsAppClient.getAppStateKey(byteArrayOf(9, 9))) |
| 339 | // Corrupted stored base64 decodes to null instead of throwing. |
| 340 | WhatsAppClient.appStatePrefs.edit().putString( |
| 341 | "key_${android.util.Base64.encodeToString(byteArrayOf(3, 3), android.util.Base64.NO_WRAP)}", "!!!not-base64!!!", |
| 342 | ).commit() |
| 343 | assertNull(WhatsAppClient.getAppStateKey(byteArrayOf(3, 3))) |
| 344 | assertEquals(0L, WhatsAppClient.appStateVersion("regular")) |
| 345 | WhatsAppClient.setAppStateVersion("regular", 123L) |
| 346 | assertEquals(123L, WhatsAppClient.appStateVersion("regular")) |
| 347 | WhatsAppClient.setAppStateVersion("regular", 0L) |
| 348 | } |
| 349 | |
| 350 | private fun encryptedRecord(keyId: ByteArray, keyData: ByteArray, plain: ByteArray): WhatsAppAppStateProto.SyncdRecord { |
| 351 | val expanded = WhatsAppProtocol.expandAppStateKeys(keyData) |
| 352 | val iv = ByteArray(16) { it.toByte() } |
| 353 | val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding") |
| 354 | cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(expanded[1], "AES"), IvParameterSpec(iv)) |
| 355 | val blob = iv + cipher.doFinal(plain) + ByteArray(32) |
| 356 | return WhatsAppAppStateProto.SyncdRecord.newBuilder() |
| 357 | .setKeyId(WhatsAppAppStateProto.KeyId.newBuilder().setId(ByteString.copyFrom(keyId))) |
| 358 | .setValue(WhatsAppAppStateProto.SyncdValue.newBuilder().setBlob(ByteString.copyFrom(blob))) |
| 359 | .build() |
| 360 | } |
| 361 | |
| 362 | private suspend fun applyAction(indexJson: String, value: WhatsAppAppStateProto.SyncActionValue, keyId: ByteArray = byteArrayOf(42, 42)) { |
| 363 | val keyData = ByteArray(32) { (it * 7 + 1).toByte() } |
| 364 | WhatsAppClient.storeAppStateKey(keyId, keyData) |
| 365 | val action = WhatsAppAppStateProto.SyncActionData.newBuilder() |
| 366 | .setIndex(ByteString.copyFrom(indexJson.toByteArray())).setValue(value).build() |
| 367 | WhatsAppClient.applyAppStateRecord(encryptedRecord(keyId, keyData, action.toByteArray()), isSet = true) |
| 368 | } |
| 369 | |
| 370 | @Test |
| 371 | fun `app state records contact fallbacks and silent drop branches`() = runTest { |
| 372 | dbA.conversationDao().upsert(WhatsAppConversation(chatJid = "[email protected]")) |
| 373 | // contact with firstName fallback, cached under both resolved and raw jids |
| 374 | applyAction("""["contact","[email protected]"]""", |
| 375 | WhatsAppAppStateProto.SyncActionValue.newBuilder().setContactAction( |
| 376 | WhatsAppAppStateProto.ContactAction.newBuilder().setFirstName("Bobby")).build()) |
| 377 | assertEquals("Bobby", WhatsAppClient.nameCache["[email protected]"]) |
| 378 | // empty contact name and non-SET do not overwrite |
| 379 | applyAction("""["contact","[email protected]"]""", |
| 380 | WhatsAppAppStateProto.SyncActionValue.newBuilder().setContactAction( |
| 381 | WhatsAppAppStateProto.ContactAction.newBuilder()).build()) |
| 382 | assertEquals("Bobby", WhatsAppClient.nameCache["[email protected]"]) |
| 383 | // mute/pin/archive/read land on the conversation row |
| 384 | applyAction("""["mute","[email protected]"]""", |
| 385 | WhatsAppAppStateProto.SyncActionValue.newBuilder().setMuteAction( |
| 386 | WhatsAppAppStateProto.MuteAction.newBuilder().setMuteEndTimestamp(777L)).build()) |
| 387 | applyAction("""["archive","[email protected]"]""", |
| 388 | WhatsAppAppStateProto.SyncActionValue.newBuilder().setArchiveChatAction( |
| 389 | WhatsAppAppStateProto.ArchiveChatAction.newBuilder().setArchived(true)).build()) |
| 390 | applyAction("""["markChatAsRead","[email protected]"]""", |
| 391 | WhatsAppAppStateProto.SyncActionValue.newBuilder().setMarkChatAsReadAction( |
| 392 | WhatsAppAppStateProto.MarkChatAsReadAction.newBuilder().setRead(true)).build()) |
| 393 | val row = dbA.conversationDao().getConversation("[email protected]")!! |
| 394 | assertEquals(777L, row.muteEndTime); assertTrue(row.archived); assertFalse(row.markedAsUnread) |
| 395 | // unknown action / empty index / bad JSON / garbage proto / short blob / unknown key: silent no-ops |
| 396 | applyAction("""["label","[email protected]"]""", WhatsAppAppStateProto.SyncActionValue.newBuilder().build()) |
| 397 | applyAction("""[]""", WhatsAppAppStateProto.SyncActionValue.newBuilder().build()) |
| 398 | val keyId = byteArrayOf(42, 42); val keyData = ByteArray(32) { (it * 7 + 1).toByte() } |
| 399 | WhatsAppClient.applyAppStateRecord(encryptedRecord(keyId, keyData, "not json at all".toByteArray()), isSet = true) |
| 400 | WhatsAppClient.applyAppStateRecord(encryptedRecord(byteArrayOf(8, 8), keyData, |
| 401 | WhatsAppAppStateProto.SyncActionData.newBuilder().setIndex(ByteString.copyFrom("""["mute","x"]""".toByteArray())).build().toByteArray()), isSet = true) |
| 402 | val shortBlob = WhatsAppAppStateProto.SyncdRecord.newBuilder() |
| 403 | .setKeyId(WhatsAppAppStateProto.KeyId.newBuilder().setId(ByteString.copyFrom(keyId))) |
| 404 | .setValue(WhatsAppAppStateProto.SyncdValue.newBuilder().setBlob(ByteString.copyFrom(byteArrayOf(1, 2)))).build() |
| 405 | WhatsAppClient.applyAppStateRecord(shortBlob, isSet = true) |
| 406 | WhatsAppClient.applyAppStateRecord(encryptedRecord(keyId, keyData, |
| 407 | WhatsAppAppStateProto.SyncActionData.newBuilder().setIndex(ByteString.copyFrom("""["mute","[email protected]"]""".toByteArray())).build().toByteArray()), isSet = false) |
| 408 | assertEquals(row, dbA.conversationDao().getConversation("[email protected]")) |
| 409 | // downloadAppStateBlob: empty path and dead media connection both null |
| 410 | assertNull(WhatsAppClient.downloadAppStateBlob(WhatsAppAppStateProto.ExternalBlobReference.getDefaultInstance())) |
| 411 | assertNull(WhatsAppClient.downloadAppStateBlob( |
| 412 | WhatsAppAppStateProto.ExternalBlobReference.newBuilder().setDirectPath("/x?y=").build())) |
| 413 | } |
| 414 | |
| 415 | @Test |
| 416 | fun `key share dedupes collection fetching guards and missing key requests`() = runTest { |
| 417 | val share = WhatsAppE2EProto.AppStateSyncKeyShare.newBuilder() |
| 418 | .addKeys(WhatsAppE2EProto.AppStateSyncKey.newBuilder() |
| 419 | .setKeyId(WhatsAppE2EProto.AppStateSyncKeyId.newBuilder().setKeyId(ByteString.copyFrom(byteArrayOf(5, 5)))) |
| 420 | .setKeyData(WhatsAppE2EProto.AppStateSyncKeyData.newBuilder().setKeyData(ByteString.copyFrom(ByteArray(32) { 2 })))) |
| 421 | .addKeys(WhatsAppE2EProto.AppStateSyncKey.newBuilder() |
| 422 | .setKeyId(WhatsAppE2EProto.AppStateSyncKeyId.newBuilder().setKeyId(ByteString.copyFrom(ByteArray(0)))) |
| 423 | .setKeyData(WhatsAppE2EProto.AppStateSyncKeyData.newBuilder().setKeyData(ByteString.copyFrom(ByteArray(32))))) |
| 424 | .build() |
| 425 | WhatsAppClient.handleAppStateKeyShare(share) |
| 426 | assertNotNull(WhatsAppClient.getAppStateKey(byteArrayOf(5, 5))) |
| 427 | assertTrue(WhatsAppDiag.log.value.any { it.contains("stored 1 sync key(s)") }) |
| 428 | assertTrue(WhatsAppClient.appStateCollectionsFetching.isEmpty()) |
| 429 | // In-flight guard: a pre-marked collection is not refetched. |
| 430 | WhatsAppClient.appStateCollectionsFetching.add("regular") |
| 431 | WhatsAppClient.fetchAppStateCollection("regular", fullSync = true) |
| 432 | assertTrue(WhatsAppClient.appStateCollectionsFetching.contains("regular")) |
| 433 | WhatsAppClient.appStateCollectionsFetching.remove("regular") |
| 434 | // Missing-key request is deduped by base64 key id and fails soft without a session. |
| 435 | WhatsAppClient.requestAppStateKey(byteArrayOf(6, 6)) |
| 436 | val sizeAfterFirst = WhatsAppClient.appStateKeyRequested.size |
| 437 | WhatsAppClient.requestAppStateKey(byteArrayOf(6, 6)) |
| 438 | assertEquals(sizeAfterFirst, WhatsAppClient.appStateKeyRequested.size) |
| 439 | assertEquals(1, sizeAfterFirst) |
| 440 | } |
| 441 | |
| 442 | // ---------- Sync: poll stores ---------- |
| 443 | |
| 444 | @Test |
| 445 | fun `poll option hashes and secret hex round trip through the database`() = runTest { |
| 446 | WhatsAppClient.storePollOptions("poll-9", listOf("Yes", "No")) |
| 447 | val yesHash = MessageDigest.getInstance("SHA-256").digest("Yes".toByteArray()) |
| 448 | .joinToString("") { "%02x".format(it) } |
| 449 | assertEquals("Yes", dbA.pollOptionDao().getByHash("poll-9", yesHash)?.optionName) |
| 450 | assertEquals(2, dbA.pollOptionDao().getByMessageId("poll-9").size) |
| 451 | assertNull(dbA.pollOptionDao().getByHash("poll-9", "00")) |
| 452 | WhatsAppClient.storePollSecret("poll-9", byteArrayOf(1, 2, 3, 127)) |
| 453 | assertTrue(WhatsAppClient.loadPollSecret("poll-9")!!.contentEquals(byteArrayOf(1, 2, 3, 127))) |
| 454 | // DB-backed load (cache cleared) decodes hex; corrupt hex yields null. |
| 455 | WhatsAppClient.pollSecrets.clear() |
| 456 | assertTrue(WhatsAppClient.loadPollSecret("poll-9")!!.contentEquals(byteArrayOf(1, 2, 3, 127))) |
| 457 | dbA.pollSecretDao().upsert(WhatsAppPollSecret("poll-bad", "zzzz")) |
| 458 | assertNull(WhatsAppClient.loadPollSecret("poll-bad")) |
| 459 | assertNull(WhatsAppClient.loadPollSecret("poll-absent")) |
| 460 | // No DB: stores are no-ops, loads miss. |
| 461 | WhatsAppClient.db = null |
| 462 | WhatsAppClient.storePollOptions("x", listOf("A")); WhatsAppClient.storePollSecret("x", byteArrayOf(1)) |
| 463 | WhatsAppClient.pollSecrets["x"]?.let { assertTrue(it.contentEquals(byteArrayOf(1))) } // in-memory still set |
| 464 | WhatsAppClient.db = dbA |
| 465 | } |
| 466 | |
| 467 | // ---------- Sync: history ---------- |
| 468 | |
| 469 | private fun histMsg(id: String, body: String?, fromMe: Boolean, ts: Long, push: String = "") = |
| 470 | WhatsAppE2EProto.HistorySyncMsg.newBuilder().setMessage( |
| 471 | WhatsAppE2EProto.WebMessageInfo.newBuilder() |
| 472 | .setKey(WhatsAppE2EProto.HsMsgKey.newBuilder().setId(id).setFromMe(fromMe).setRemoteJid("[email protected]")) |
| 473 | .apply { if (body != null) setMessage(WhatsAppE2EProto.Message.newBuilder().setConversation(body)) } |
| 474 | .setMessageTimestamp(ts).setPushName(push), |
| 475 | ).build() |
| 476 | |
| 477 | @Test |
| 478 | fun `history sync LID chats empty bodies group rows and receipts`() = runTest { |
| 479 | WhatsAppClient.lidToPhoneMap["999@lid"] = "[email protected]" |
| 480 | val history = WhatsAppE2EProto.HistorySync.newBuilder().setSyncType(WhatsAppClient.SYNC_INITIAL_BOOTSTRAP) |
| 481 | .addPhoneNumberToLidMappings(WhatsAppE2EProto.PhoneNumberToLIDMapping.newBuilder().setPnJid("[email protected]").setLidJid("888@lid")) |
| 482 | .addConversations(WhatsAppE2EProto.HsConversation.newBuilder().setId("999@lid").setUnreadCount(1) |
| 483 | .addMessages(histMsg("a1", "first", false, 1700000000L, "Alice")) |
| 484 | .addMessages(histMsg("a2", null, false, 1700000100L)) // no message proto: skipped |
| 485 | .addMessages(histMsg("a3", "mine", true, 1700000200L))) |
| 486 | .addConversations(WhatsAppE2EProto.HsConversation.newBuilder().setId("[email protected]").setName("Grp") |
| 487 | .addMessages(histMsg("g1", "group hist", false, 1700000000L))) |
| 488 | .addConversations(WhatsAppE2EProto.HsConversation.newBuilder().setId("[email protected]")) // empty |
| 489 | .build() |
| 490 | val notif = WhatsAppE2EProto.HistorySyncNotification.newBuilder() |
| 491 | .setInitialHistBootstrapInlinePayload(ByteString.copyFrom(deflate(history.toByteArray()))).build() |
| 492 | WhatsAppClient.handleHistorySync(notif, "hn-1") |
| 493 | assertEquals("[email protected]", WhatsAppClient.lidToPhoneMap["888@lid"]) |
| 494 | // Events reach the collector on Dispatchers.Default asynchronously; |
| 495 | // asserting immediately raced it and dropped the last conversation |
| 496 | // under load. Wait for the terminal delivery (step-bounded). |
| 497 | com.vayunmathur.testsupport.awaitWithMainIdle("history sync events delivered", maxSteps = 100_000) { |
| 498 | events.filterIsInstance<WhatsAppEvent.MessageUpdate>().size >= 3 && |
| 499 | events.filterIsInstance<WhatsAppEvent.ConversationUpdate>().size >= 2 |
| 500 | } |
| 501 | val updates = events.filterIsInstance<WhatsAppEvent.MessageUpdate>() |
| 502 | assertEquals(listOf("first", "mine", "group hist"), updates.map { it.body }) |
| 503 | val convs = events.filterIsInstance<WhatsAppEvent.ConversationUpdate>() |
| 504 | assertEquals(setOf("wa:[email protected]", "wa:[email protected]"), convs.map { it.conversationId }.toSet()) |
| 505 | assertTrue(convs.first { it.isGroup }.peerName == "Grp") |
| 506 | assertEquals("mine", convs.first { !it.isGroup }.lastPreview) |
| 507 | assertTrue(WhatsAppDiag.log.value.any { it.contains("hist_sync receipt for hn-1") }) |
| 508 | // Corrupt inline blob and missing payload: logged, receipt still attempted, nothing emitted. |
| 509 | val before = events.size |
| 510 | WhatsAppClient.handleHistorySync( |
| 511 | WhatsAppE2EProto.HistorySyncNotification.newBuilder() |
| 512 | .setInitialHistBootstrapInlinePayload(ByteString.copyFrom(byteArrayOf(1, 2, 3))).build(), "hn-2") |
| 513 | WhatsAppClient.handleHistorySync(WhatsAppE2EProto.HistorySyncNotification.getDefaultInstance(), "hn-3") |
| 514 | WhatsAppClient.sendHistorySyncReceipt(""); WhatsAppClient.sendHistorySyncReceipt("hn-9") |
| 515 | assertEquals(before, events.size) |
| 516 | // Direct emit: empty conversation returns 0 and emits nothing. |
| 517 | assertEquals(0, WhatsAppClient.emitHistoryConversation( |
| 518 | WhatsAppE2EProto.HsConversation.newBuilder().setId("[email protected]").build(), "[email protected]", false)) |
| 519 | } |
| 520 | |
| 521 | @Test |
| 522 | fun `on-demand pagination dedupes cursors and stops at the page cap`() = runTest { |
| 523 | WhatsAppClient.kickoffBackfill() |
| 524 | assertTrue(WhatsAppDiag.log.value.any { it.contains("awaiting pushed history") }) |
| 525 | WhatsAppClient.sendHistoryOnDemandRequest("[email protected]", "old-1", false, 100L) |
| 526 | WhatsAppClient.sendHistoryOnDemandRequest("[email protected]", "old-1", false, 100L) |
| 527 | WhatsAppClient.sendHistoryOnDemandRequest("[email protected]", "", false, 0L) |
| 528 | WhatsAppClient.sendHistoryOnDemandRequest("", "old-2", false, 0L) |
| 529 | assertEquals(1, WhatsAppClient.onDemandPageCount["[email protected]"]) |
| 530 | assertEquals(1, WhatsAppClient.onDemandRequested.size) |
| 531 | // A distinct older cursor paginates once more. |
| 532 | WhatsAppClient.sendHistoryOnDemandRequest("[email protected]", "old-0", true, 50L) |
| 533 | assertEquals(2, WhatsAppClient.onDemandPageCount["[email protected]"]) |
| 534 | // At the cap, a fresh cursor is recorded as requested but no request is built/sent. |
| 535 | WhatsAppClient.onDemandPageCount["[email protected]"] = WhatsAppClient.MAX_ON_DEMAND_PAGES_PER_CHAT |
| 536 | WhatsAppClient.sendHistoryOnDemandRequest("[email protected]", "ancient", false, 1L) |
| 537 | assertTrue(WhatsAppDiag.log.value.any { it.contains("hit page cap for [email protected]") }) |
| 538 | // inflateZlib: valid round trip and empty input. |
| 539 | assertTrue(WhatsAppClient.inflateZlib(deflate("hello zlib".toByteArray())).contentEquals("hello zlib".toByteArray())) |
| 540 | assertEquals(0, WhatsAppClient.inflateZlib(ByteArray(0)).size) |
| 541 | assertTrue(WhatsAppClient.inflateZlib(deflate(ByteArray(0))).isEmpty()) |
| 542 | } |
| 543 | } |