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 / W5Pass2BackupImporterTest.kt

W5Pass2BackupImporterTest.kt164 lines · 7.2 KiBRaw
1package com.vayunmathur.communicate.whatsapp
2
3import android.content.Context
4import android.database.sqlite.SQLiteDatabase
5import androidx.room3.Room
6import androidx.test.core.app.ApplicationProvider
7import androidx.test.ext.junit.runners.AndroidJUnit4
8import com.vayunmathur.communicate.data.whatsapp.WhatsAppDatabase
9import com.vayunmathur.communicate.data.whatsapp.backup.BackupImporter
10import com.vayunmathur.library.util.databases
11import java.io.ByteArrayOutputStream
12import java.io.File
13import java.util.zip.GZIPOutputStream
14import javax.crypto.Cipher
15import javax.crypto.Mac
16import javax.crypto.spec.GCMParameterSpec
17import javax.crypto.spec.SecretKeySpec
18import kotlin.test.BeforeTest
19import kotlin.test.Test
20import kotlin.test.assertEquals
21import kotlin.test.assertNotNull
22import kotlin.test.assertTrue
23import kotlinx.coroutines.test.runTest
24import org.junit.runner.RunWith
25
26/**
27 * Pass-2 slice-1 (whatsapp backup): BackupImporter end-to-end offline - build a
28 * real msgstore SQLite file, wrap it in a crypt15 blob (same HKDF/GCM recipe as
29 * the decryptor tests), import it into an in-memory Room cache, and assert the
30 * mapped rows. Plus the decrypt/schema failure results.
31 */
32@RunWith(AndroidJUnit4::class)
33class W5Pass2BackupImporterTest {
34
35 private lateinit var context: Context
36 private lateinit var room: WhatsAppDatabase
37 private val backupKey = ByteArray(32) { (it * 7 + 1).toByte() }
38
39 @BeforeTest
40 fun setUp() {
41 context = ApplicationProvider.getApplicationContext<Context>()
42 room = Room.inMemoryDatabaseBuilder(context, WhatsAppDatabase::class.java)
43 .setSingleConnectionPool()
44 .allowMainThreadQueries().build()
45 // BackupImporter reaches its Room cache through WhatsAppRepository, whose
46 // builder consults this shared cache first.
47 synchronized(databases) { databases[WhatsAppDatabase::class] = room }
48 }
49
50 private fun hmac(key: ByteArray, msg: ByteArray): ByteArray {
51 val mac = Mac.getInstance("HmacSHA256")
52 mac.init(SecretKeySpec(key, "HmacSHA256"))
53 return mac.doFinal(msg)
54 }
55
56 private fun hkdf(ikm: ByteArray, salt: ByteArray, info: ByteArray, len: Int): ByteArray {
57 val prk = hmac(salt, ikm)
58 val out = ByteArray(len)
59 var t = ByteArray(0)
60 var pos = 0
61 var c = 1
62 while (pos < len) {
63 val mac = Mac.getInstance("HmacSHA256")
64 mac.init(SecretKeySpec(prk, "HmacSHA256"))
65 mac.update(t); mac.update(info); mac.update(c.toByte())
66 t = mac.doFinal()
67 val n = minOf(t.size, len - pos)
68 System.arraycopy(t, 0, out, pos, n)
69 pos += n; c++
70 }
71 return out
72 }
73
74 private fun varint(v: Long): ByteArray {
75 val out = ByteArrayOutputStream()
76 var x = v
77 while (true) {
78 var b = (x and 0x7F).toInt()
79 x = x ushr 7
80 if (x != 0L) b = b or 0x80
81 out.write(b)
82 if (x == 0L) break
83 }
84 return out.toByteArray()
85 }
86
87 private fun encryptBlob(plainDb: ByteArray, key: ByteArray): ByteArray {
88 val iv = ByteArray(16) { (it + 3).toByte() }
89 val inner = ByteArrayOutputStream()
90 inner.write(0x0A); inner.write(varint(16)); inner.write(iv)
91 val innerBytes = inner.toByteArray()
92 val header = ByteArrayOutputStream()
93 header.write(varint(innerBytes.size.toLong())); header.write(innerBytes)
94 val aesKey = hkdf(key, ByteArray(32), "backup encryption".toByteArray(Charsets.UTF_8), 32)
95 val cipher = Cipher.getInstance("AES/GCM/NoPadding")
96 cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(aesKey, "AES"), GCMParameterSpec(128, iv))
97 val gzipped = ByteArrayOutputStream().also { GZIPOutputStream(it).use { g -> g.write(plainDb) } }.toByteArray()
98 return header.toByteArray() + cipher.doFinal(gzipped)
99 }
100
101 /** A minimal modern msgstore: jid/chat/message with three importable rows. */
102 private fun msgstoreBytes(): ByteArray {
103 val file = File(context.cacheDir, "msgstore_fixture.db")
104 file.delete()
105 val db = SQLiteDatabase.openOrCreateDatabase(file, null)
106 db.execSQL("CREATE TABLE jid (_id INTEGER PRIMARY KEY, raw_string TEXT)")
107 db.execSQL("CREATE TABLE chat (_id INTEGER PRIMARY KEY, jid_row_id INTEGER)")
108 db.execSQL(
109 "CREATE TABLE message (key_id TEXT, from_me INTEGER, timestamp INTEGER, text_data TEXT, chat_row_id INTEGER)",
110 )
111 db.execSQL("INSERT INTO jid VALUES (1, '[email protected]'), (2, '[email protected]')")
112 db.execSQL("INSERT INTO chat VALUES (1, 1), (2, 2)")
113 db.execSQL(
114 "INSERT INTO message VALUES " +
115 "('K1', 0, 1700000000000, 'hello from them', 1), " +
116 "('K2', 1, 1700000060000, 'reply from me', 1), " +
117 "('K3', 0, 1700000120000, 'group hello', 2), " +
118 "(NULL, 0, 1700000180000, 'keyless row is skipped', 1)",
119 )
120 db.close()
121 return file.readBytes().also { file.delete() }
122 }
123
124 @Test
125 fun `import maps msgstore rows into the room cache`() = runTest {
126 val result = BackupImporter.import(context, encryptBlob(msgstoreBytes(), backupKey), backupKey)
127 assertEquals(emptyList(), result.errors)
128 assertEquals(2, result.conversationCount)
129 assertEquals(3, result.messageCount)
130 val dm = room.cachedMessageDao().getForConversation("[email protected]")
131 assertEquals(listOf("hello from them", "reply from me"), dm.map { it.body })
132 assertEquals(listOf(false, true), dm.map { it.outgoing })
133 assertEquals(1_700_000_000_000L, dm.first().timestamp)
134 assertNotNull(room.cachedMessageDao().get("K3"))
135 assertNotNull(room.conversationDao().getConversation("[email protected]"))
136 assertNotNull(room.conversationDao().getConversation("[email protected]"))
137 // Re-importing the same backup is deduped by message key.
138 val again = BackupImporter.import(context, encryptBlob(msgstoreBytes(), backupKey), backupKey)
139 assertEquals(3, again.messageCount)
140 assertEquals(2, room.cachedMessageDao().getForConversation("[email protected]").size)
141 }
142
143 @Test
144 fun `decrypt failures report instead of throwing`() = runTest {
145 val garbage = BackupImporter.import(context, byteArrayOf(1, 2, 3), backupKey)
146 assertEquals(0, garbage.messageCount)
147 assertTrue(garbage.errors.single().startsWith("Decrypt failed"), garbage.errors.toString())
148 val wrongKey = BackupImporter.import(
149 context, encryptBlob(msgstoreBytes(), backupKey), ByteArray(32) { 99 },
150 )
151 assertEquals(0, wrongKey.messageCount)
152 assertTrue(wrongKey.errors.single().startsWith("Decrypt failed"), wrongKey.errors.toString())
153 }
154
155 @Test
156 fun `a decryptable non-msgstore payload reports a schema failure`() = runTest {
157 val result = BackupImporter.import(
158 context, encryptBlob("SQLite format 3\u0000not-a-real-msgstore".toByteArray(Charsets.ISO_8859_1), backupKey), backupKey,
159 )
160 assertEquals(0, result.messageCount)
161 assertEquals(0, result.conversationCount)
162 assertTrue(result.errors.isNotEmpty(), "expected a reported failure, got success")
163 }
164}