Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / communicate-dev / src / test / java / com / vayunmathur / communicate / signal / Y1SignalMessagingGroupTest.kt
Y1SignalMessagingGroupTest.kt727 lines ยท 34.7 KiBRaw
| 1 | package com.vayunmathur.communicate.signal |
| 2 | |
| 3 | import androidx.room3.Room |
| 4 | import androidx.sqlite.driver.bundled.BundledSQLiteDriver |
| 5 | import androidx.test.core.app.ApplicationProvider |
| 6 | import com.google.protobuf.ByteString |
| 7 | import com.vayunmathur.communicate.data.signal.SignalAuthData |
| 8 | import com.vayunmathur.communicate.data.signal.SignalCachedMessage |
| 9 | import com.vayunmathur.communicate.data.signal.SignalClient |
| 10 | import com.vayunmathur.communicate.data.signal.SignalConversation |
| 11 | import com.vayunmathur.communicate.data.signal.SignalDatabase |
| 12 | import com.vayunmathur.communicate.data.signal.SignalEvent |
| 13 | import com.vayunmathur.communicate.data.signal.SignalGroups |
| 14 | import com.vayunmathur.communicate.data.signal.SignalPollOptionData |
| 15 | import com.vayunmathur.communicate.data.signal.SignalProtocol |
| 16 | import com.vayunmathur.communicate.data.signal.SignalServiceData |
| 17 | import com.vayunmathur.communicate.data.signal.conversationForGroupId |
| 18 | import com.vayunmathur.communicate.data.signal.createGroup |
| 19 | import com.vayunmathur.communicate.data.signal.downloadMedia |
| 20 | import com.vayunmathur.communicate.data.signal.editMessage |
| 21 | import com.vayunmathur.communicate.data.signal.e2e.SignalE2E |
| 22 | import com.vayunmathur.communicate.data.signal.e2e.ensureLocalPreKeys |
| 23 | import com.vayunmathur.communicate.data.signal.groupAuthorization |
| 24 | import com.vayunmathur.communicate.data.signal.handleInboundFrame |
| 25 | import com.vayunmathur.communicate.data.signal.markRead |
| 26 | import com.vayunmathur.communicate.data.signal.poll |
| 27 | import com.vayunmathur.communicate.data.signal.readReceipt |
| 28 | import com.vayunmathur.communicate.data.signal.refreshGroup |
| 29 | import com.vayunmathur.communicate.data.signal.refreshPresence |
| 30 | import com.vayunmathur.communicate.data.signal.registration.SignalRegistrationKeys |
| 31 | import com.vayunmathur.communicate.data.signal.rememberInboundGroup |
| 32 | import com.vayunmathur.communicate.data.signal.removeReaction |
| 33 | import com.vayunmathur.communicate.data.signal.revoke |
| 34 | import com.vayunmathur.communicate.data.signal.sendContactCard |
| 35 | import com.vayunmathur.communicate.data.signal.sendMedia |
| 36 | import com.vayunmathur.communicate.data.signal.sendPollVote |
| 37 | import com.vayunmathur.communicate.data.signal.sendReaction |
| 38 | import com.vayunmathur.communicate.data.signal.sendTyping |
| 39 | import com.vayunmathur.communicate.data.signal.setGroupName |
| 40 | import com.vayunmathur.communicate.data.signal.transport.SignalPayload |
| 41 | import com.vayunmathur.communicate.data.signal.updateGroupParticipants |
| 42 | import kotlin.test.AfterTest |
| 43 | import kotlin.test.BeforeTest |
| 44 | import kotlin.test.Test |
| 45 | import kotlin.test.assertEquals |
| 46 | import kotlin.test.assertFalse |
| 47 | import kotlin.test.assertNotNull |
| 48 | import kotlin.test.assertNull |
| 49 | import kotlin.test.assertTrue |
| 50 | import kotlinx.coroutines.CoroutineScope |
| 51 | import kotlinx.coroutines.Dispatchers |
| 52 | import kotlinx.coroutines.async |
| 53 | import kotlinx.coroutines.flow.first |
| 54 | import kotlinx.coroutines.launch |
| 55 | import kotlinx.coroutines.test.runTest |
| 56 | import kotlinx.coroutines.withTimeoutOrNull |
| 57 | import org.junit.runner.RunWith |
| 58 | import org.robolectric.RobolectricTestRunner |
| 59 | import org.whispersystems.signalservice.internal.push.SignalServiceProtos |
| 60 | import signal.proto.chat_websocket.SignalChatWebsocket.WebSocketMessage |
| 61 | import signal.proto.chat_websocket.SignalChatWebsocket.WebSocketRequestMessage |
| 62 | |
| 63 | /** |
| 64 | * Y1: SignalMessaging (reactions / edit / revoke / polls / receipts / typing / |
| 65 | * media / contact cards) and SignalGroupOps (create / rename / membership / |
| 66 | * refresh / inbound-group learning), plus the inbound dispatch branches |
| 67 | * those features mirror. Offline sends fail closed; local DB + event |
| 68 | * effects are the contract. Inbound cases run a real Alice<->Bob E2E |
| 69 | * session through [handleInboundFrame]. |
| 70 | */ |
| 71 | @RunWith(RobolectricTestRunner::class) |
| 72 | class Y1SignalMessagingGroupTest { |
| 73 | |
| 74 | private lateinit var db: SignalDatabase |
| 75 | private lateinit var dbBob: SignalDatabase |
| 76 | private val selfAci = "aaaaaaaa-1111-2222-3333-444455556666" |
| 77 | private val peer = "3f0e5a2c-1111-2222-3333-444455556666" |
| 78 | private val bobAci = "7c1d9b4e-aaaa-bbbb-cccc-ddddeeeeffff" |
| 79 | |
| 80 | @BeforeTest |
| 81 | fun open() { |
| 82 | val ctx = ApplicationProvider.getApplicationContext<android.content.Context>() |
| 83 | db = Room.inMemoryDatabaseBuilder(ctx, SignalDatabase::class.java) |
| 84 | .setDriver(BundledSQLiteDriver()).allowMainThreadQueries().build() |
| 85 | dbBob = Room.inMemoryDatabaseBuilder(ctx, SignalDatabase::class.java) |
| 86 | .setDriver(BundledSQLiteDriver()).allowMainThreadQueries().build() |
| 87 | SignalClient.db = db |
| 88 | SignalClient.e2e = null |
| 89 | SignalClient.authData = SignalAuthData(phoneNumber = "+14155552671", aci = selfAci, password = "secret") |
| 90 | SignalClient.socket = null |
| 91 | SignalClient.unauthSocket = null |
| 92 | SignalClient.appContext = null |
| 93 | SignalClient.pendingIdentityChanges.clear() |
| 94 | } |
| 95 | |
| 96 | @AfterTest |
| 97 | fun close() { |
| 98 | SignalClient.db = null |
| 99 | SignalClient.authData = null |
| 100 | SignalClient.e2e = null |
| 101 | SignalClient.appContext = null |
| 102 | SignalClient.pendingIdentityChanges.clear() |
| 103 | db.close() |
| 104 | dbBob.close() |
| 105 | } |
| 106 | |
| 107 | // ---------- reactions ---------- |
| 108 | |
| 109 | @Test |
| 110 | fun reactionOnGroupMessage_emitsWithSelfAsSender() = runTest { |
| 111 | val (masterKey, _) = SignalGroups.generateMasterKeyAndSecretParams() |
| 112 | val groupId = SignalProtocol.toConversationId("", masterKey) |
| 113 | db.conversationDao().upsert( |
| 114 | SignalConversation(chatId = groupId, isGroup = true, groupMasterKey = masterKey, participants = peer), |
| 115 | ) |
| 116 | db.cachedMessageDao().upsert( |
| 117 | SignalCachedMessage(messageId = "g-msg", conversationId = groupId, body = "hi", timestamp = 5000L, outgoing = false, senderId = peer), |
| 118 | ) |
| 119 | val seen = mutableListOf<SignalEvent>() |
| 120 | val job = launch(Dispatchers.Unconfined) { SignalClient.events.collect { seen.add(it) } } |
| 121 | assertTrue(SignalClient.sendReaction(groupId, "g-msg", "๐ฅ")) |
| 122 | job.cancel() |
| 123 | val r = seen.filterIsInstance<SignalEvent.ReactionReceived>().single() |
| 124 | assertEquals(groupId, r.conversationId) |
| 125 | assertEquals("g-msg", r.messageId) |
| 126 | assertEquals(selfAci, r.senderId) |
| 127 | assertEquals("๐ฅ", r.emoji) |
| 128 | } |
| 129 | |
| 130 | @Test |
| 131 | fun reactionOnUnknownMessageAndRemoveBothEmit() = runTest { |
| 132 | val seen = mutableListOf<SignalEvent>() |
| 133 | val job = launch(Dispatchers.Unconfined) { SignalClient.events.collect { seen.add(it) } } |
| 134 | assertTrue(SignalClient.sendReaction(peer, "ghost", "๐")) |
| 135 | assertTrue(SignalClient.removeReaction(peer, "ghost")) |
| 136 | // Empty emoji is exactly the remove path, even called directly. |
| 137 | assertTrue(SignalClient.sendReaction(peer, "ghost", "")) |
| 138 | job.cancel() |
| 139 | assertEquals(1, seen.filterIsInstance<SignalEvent.ReactionReceived>().size) |
| 140 | assertEquals(2, seen.filterIsInstance<SignalEvent.ReactionRemoved>().size) |
| 141 | assertTrue(seen.filterIsInstance<SignalEvent.ReactionRemoved>().all { it.senderId == selfAci }) |
| 142 | } |
| 143 | |
| 144 | @Test |
| 145 | fun reactionUsesCachedAuthorEvenWhenOutgoing() = runTest { |
| 146 | db.cachedMessageDao().upsert( |
| 147 | SignalCachedMessage(messageId = "mine", conversationId = peer, body = "x", timestamp = 1234L, outgoing = true, senderId = selfAci), |
| 148 | ) |
| 149 | val seen = mutableListOf<SignalEvent>() |
| 150 | val job = launch(Dispatchers.Unconfined) { SignalClient.events.collect { seen.add(it) } } |
| 151 | SignalClient.sendReaction(peer, "mine", "๐") |
| 152 | job.cancel() |
| 153 | assertEquals(selfAci, seen.filterIsInstance<SignalEvent.ReactionReceived>().single().senderId) |
| 154 | } |
| 155 | |
| 156 | // ---------- edit / revoke ---------- |
| 157 | |
| 158 | @Test |
| 159 | fun editUnknownMessage_emitsButCreatesNoRow() = runTest { |
| 160 | val seen = mutableListOf<SignalEvent>() |
| 161 | val job = launch(Dispatchers.Unconfined) { SignalClient.events.collect { seen.add(it) } } |
| 162 | assertTrue(SignalClient.editMessage(peer, "no-such", "replacement")) |
| 163 | job.cancel() |
| 164 | assertNull(db.cachedMessageDao().get("no-such")) |
| 165 | val e = seen.filterIsInstance<SignalEvent.MessageEdited>().single() |
| 166 | assertEquals("replacement", e.newBody) |
| 167 | assertEquals(peer, e.conversationId) |
| 168 | } |
| 169 | |
| 170 | @Test |
| 171 | fun editCachedMessage_updatesBodyAndEditedFlagOnly() = runTest { |
| 172 | db.cachedMessageDao().upsert( |
| 173 | SignalCachedMessage(messageId = "e1", conversationId = peer, body = "orig", timestamp = 10L, outgoing = true, senderId = selfAci, status = 1), |
| 174 | ) |
| 175 | SignalClient.editMessage(peer, "e1", "corrected") |
| 176 | val row = db.cachedMessageDao().get("e1")!! |
| 177 | assertEquals("corrected", row.body) |
| 178 | assertTrue(row.isEdited) |
| 179 | assertFalse(row.isRevoked) |
| 180 | assertEquals(10L, row.timestamp) |
| 181 | } |
| 182 | |
| 183 | @Test |
| 184 | fun revokeCachedMessage_clearsBodyAndSetsRevoked() = runTest { |
| 185 | db.cachedMessageDao().upsert( |
| 186 | SignalCachedMessage(messageId = "r1", conversationId = peer, body = "secret", timestamp = 20L, outgoing = true, senderId = selfAci), |
| 187 | ) |
| 188 | val seen = mutableListOf<SignalEvent>() |
| 189 | val job = launch(Dispatchers.Unconfined) { SignalClient.events.collect { seen.add(it) } } |
| 190 | assertTrue(SignalClient.revoke(peer, "r1")) |
| 191 | job.cancel() |
| 192 | val row = db.cachedMessageDao().get("r1")!! |
| 193 | assertTrue(row.isRevoked) |
| 194 | assertEquals("", row.body) |
| 195 | val d = seen.filterIsInstance<SignalEvent.MessageDeleted>().single() |
| 196 | assertEquals("r1", d.messageId) |
| 197 | assertEquals(peer, d.conversationId) |
| 198 | } |
| 199 | |
| 200 | @Test |
| 201 | fun revokeUnknownMessage_stillEmitsDelete() = runTest { |
| 202 | val seen = mutableListOf<SignalEvent>() |
| 203 | val job = launch(Dispatchers.Unconfined) { SignalClient.events.collect { seen.add(it) } } |
| 204 | assertTrue(SignalClient.revoke(peer, "ghost-del")) |
| 205 | job.cancel() |
| 206 | assertEquals("ghost-del", seen.filterIsInstance<SignalEvent.MessageDeleted>().single().messageId) |
| 207 | assertNull(db.cachedMessageDao().get("ghost-del")) |
| 208 | } |
| 209 | |
| 210 | // ---------- polls ---------- |
| 211 | |
| 212 | @Test |
| 213 | fun poll_persistsServiceDataAndOutgoingRow() = runTest { |
| 214 | val id = SignalClient.poll(peer, "Best colour?", listOf("red", "blue", "green")) |
| 215 | assertNotNull(id) |
| 216 | val row = db.cachedMessageDao().get(id)!! |
| 217 | assertEquals("Best colour?", row.body) |
| 218 | assertTrue(row.outgoing) |
| 219 | assertEquals(selfAci, row.senderId) |
| 220 | val sd = SignalServiceData.parse(row.serviceData)!! |
| 221 | assertEquals("Best colour?", sd.pollQuestion) |
| 222 | assertEquals(listOf("red", "blue", "green"), sd.pollOptions.map { it.name }) |
| 223 | assertEquals(selfAci, sd.senderId) |
| 224 | } |
| 225 | |
| 226 | @Test |
| 227 | fun poll_emptyOptionsStillCreatesPoll() = runTest { |
| 228 | val id = SignalClient.poll(peer, "Empty?", emptyList()) |
| 229 | assertNotNull(id) |
| 230 | val sd = SignalServiceData.parse(db.cachedMessageDao().get(id)!!.serviceData)!! |
| 231 | assertTrue(sd.pollOptions.isEmpty()) |
| 232 | } |
| 233 | |
| 234 | @Test |
| 235 | fun pollVote_multipleKnownOptionsEmitInGivenOrder() = runTest { |
| 236 | val id = SignalClient.poll(peer, "Pick", listOf("a", "b", "c"))!! |
| 237 | val seen = mutableListOf<SignalEvent>() |
| 238 | val job = launch(Dispatchers.Unconfined) { SignalClient.events.collect { seen.add(it) } } |
| 239 | assertTrue(SignalClient.sendPollVote(peer, id, listOf("c", "a"))) |
| 240 | job.cancel() |
| 241 | val v = seen.filterIsInstance<SignalEvent.PollVote>().single() |
| 242 | assertEquals(listOf("c", "a"), v.optionNames) |
| 243 | assertEquals(id, v.pollMessageId) |
| 244 | assertEquals(selfAci, v.voterId) |
| 245 | } |
| 246 | |
| 247 | @Test |
| 248 | fun pollVote_unknownOptionNameFallsBackButEmitsGivenNames() = runTest { |
| 249 | val id = SignalClient.poll(peer, "Pick", listOf("a", "b"))!! |
| 250 | val seen = mutableListOf<SignalEvent>() |
| 251 | val job = launch(Dispatchers.Unconfined) { SignalClient.events.collect { seen.add(it) } } |
| 252 | assertTrue(SignalClient.sendPollVote(peer, id, listOf("not-an-option"))) |
| 253 | job.cancel() |
| 254 | assertEquals(listOf("not-an-option"), seen.filterIsInstance<SignalEvent.PollVote>().single().optionNames) |
| 255 | } |
| 256 | |
| 257 | @Test |
| 258 | fun pollVote_pollWithNonUuidSenderStillEmits() = runTest { |
| 259 | db.cachedMessageDao().upsert( |
| 260 | SignalCachedMessage( |
| 261 | messageId = "p-bad-author", conversationId = peer, body = "Q", timestamp = 88L, |
| 262 | outgoing = false, senderId = "not-a-uuid", |
| 263 | serviceData = SignalServiceData(pollQuestion = "Q", pollOptions = listOf(SignalPollOptionData("x"))).serialize(), |
| 264 | ), |
| 265 | ) |
| 266 | val seen = mutableListOf<SignalEvent>() |
| 267 | val job = launch(Dispatchers.Unconfined) { SignalClient.events.collect { seen.add(it) } } |
| 268 | assertTrue(SignalClient.sendPollVote(peer, "p-bad-author", listOf("x"))) |
| 269 | job.cancel() |
| 270 | assertEquals(1, seen.filterIsInstance<SignalEvent.PollVote>().size) |
| 271 | } |
| 272 | |
| 273 | // ---------- receipts / markRead / typing / presence ---------- |
| 274 | |
| 275 | @Test |
| 276 | fun readReceipt_unknownIdUsesSuppliedTimestampAndId() = runTest { |
| 277 | val seen = mutableListOf<SignalEvent>() |
| 278 | val job = launch(Dispatchers.Unconfined) { SignalClient.events.collect { seen.add(it) } } |
| 279 | assertTrue(SignalClient.readReceipt(peer, "missing-id", 31337L)) |
| 280 | job.cancel() |
| 281 | val r = seen.filterIsInstance<SignalEvent.ReadReceipt>().single() |
| 282 | assertEquals("missing-id", r.messageId) |
| 283 | assertEquals(31337L, r.timestampMs) |
| 284 | assertFalse(r.isDelivery) |
| 285 | } |
| 286 | |
| 287 | @Test |
| 288 | fun markRead_advancesStatusAndEmitsPerIdIncludingUnknown() = runTest { |
| 289 | db.cachedMessageDao().upsert( |
| 290 | SignalCachedMessage(messageId = "m1", conversationId = peer, body = "a", timestamp = 1L, outgoing = false, senderId = peer, status = 1), |
| 291 | ) |
| 292 | val seen = mutableListOf<SignalEvent>() |
| 293 | val job = launch(Dispatchers.Unconfined) { SignalClient.events.collect { seen.add(it) } } |
| 294 | SignalClient.markRead(peer, listOf("m1", "ghost")) |
| 295 | job.cancel() |
| 296 | assertEquals(3, db.cachedMessageDao().get("m1")?.status) |
| 297 | assertEquals(setOf("m1", "ghost"), seen.filterIsInstance<SignalEvent.ReadReceipt>().map { it.messageId }.toSet()) |
| 298 | } |
| 299 | |
| 300 | @Test |
| 301 | fun markRead_emptyListEmitsNothing() = runTest { |
| 302 | val seen = mutableListOf<SignalEvent>() |
| 303 | val job = launch(Dispatchers.Unconfined) { SignalClient.events.collect { seen.add(it) } } |
| 304 | SignalClient.markRead(peer, emptyList()) |
| 305 | job.cancel() |
| 306 | assertTrue(seen.filterIsInstance<SignalEvent.ReadReceipt>().isEmpty()) |
| 307 | } |
| 308 | |
| 309 | @Test |
| 310 | fun typingInGroupConversation_emitsWithSelfSender() = runTest { |
| 311 | val (masterKey, _) = SignalGroups.generateMasterKeyAndSecretParams() |
| 312 | val groupId = SignalProtocol.toConversationId("", masterKey) |
| 313 | db.conversationDao().upsert(SignalConversation(chatId = groupId, isGroup = true, groupMasterKey = masterKey)) |
| 314 | val seen = mutableListOf<SignalEvent>() |
| 315 | val job = launch(Dispatchers.Unconfined) { SignalClient.events.collect { seen.add(it) } } |
| 316 | SignalClient.sendTyping(groupId, true) |
| 317 | job.cancel() |
| 318 | val t = seen.filterIsInstance<SignalEvent.TypingIndicator>().single() |
| 319 | assertEquals(groupId, t.conversationId) |
| 320 | assertEquals(selfAci, t.senderId) |
| 321 | assertTrue(t.isTyping) |
| 322 | } |
| 323 | |
| 324 | @Test |
| 325 | fun presence_isAlwaysOfflineNoOp() = runTest { |
| 326 | val first = CoroutineScope(Dispatchers.Unconfined).async { SignalClient.events.first() } |
| 327 | SignalClient.refreshPresence(peer) |
| 328 | val e = withTimeoutOrNull(5_000) { first.await() } as? SignalEvent.PresenceUpdate |
| 329 | assertNotNull(e) |
| 330 | assertFalse(e.isOnline) |
| 331 | assertEquals(peer, e.conversationId) |
| 332 | assertTrue(e.lastSeen > 0L) |
| 333 | } |
| 334 | |
| 335 | // ---------- media / contact card ---------- |
| 336 | |
| 337 | @Test |
| 338 | fun sendMedia_emptyBytesFailsAtUploadForm() = runTest { |
| 339 | val first = CoroutineScope(Dispatchers.Unconfined).async { SignalClient.events.first() } |
| 340 | assertNull(SignalClient.sendMedia(peer, ByteArray(0), "image/png")) |
| 341 | val e = withTimeoutOrNull(15_000) { first.await() } |
| 342 | assertTrue(e is SignalEvent.SendFailed && e.conversationId == peer, "got $e") |
| 343 | assertTrue(db.cachedMessageDao().getForConversation(peer).isEmpty()) |
| 344 | } |
| 345 | |
| 346 | @Test |
| 347 | fun downloadMedia_unreachableAndMalformedUrlsReturnNull() = runTest { |
| 348 | assertNull(SignalClient.downloadMedia("not a url", ByteArray(64) { 1 }, "image/png")) |
| 349 | assertNull(SignalClient.downloadMedia("https://cdn.signal.org/attachments/missing-y1", ByteArray(64) { 1 }, "image/png")) |
| 350 | } |
| 351 | |
| 352 | @Test |
| 353 | fun contactCard_nameOnlyBuildsButFailsOffline_nameAndNumbersEmptyRefused() = runTest { |
| 354 | assertFalse(SignalClient.sendContactCard(peer, "", null, emptyList(), emptyList())) |
| 355 | assertFalse(SignalClient.sendContactCard(peer, "Ada", null, emptyList(), emptyList())) |
| 356 | assertFalse( |
| 357 | SignalClient.sendContactCard(peer, "", null, listOf("+14155550001" to null), emptyList()), |
| 358 | ) |
| 359 | } |
| 360 | |
| 361 | // ---------- group ops ---------- |
| 362 | |
| 363 | @Test |
| 364 | fun createGroup_persistsRowKeyRevisionAndEmitsConversationUpdate() = runTest { |
| 365 | val seen = mutableListOf<SignalEvent>() |
| 366 | val job = launch(Dispatchers.Unconfined) { SignalClient.events.collect { seen.add(it) } } |
| 367 | val id = SignalClient.createGroup("Y1 Group", listOf(peer, bobAci)) |
| 368 | job.cancel() |
| 369 | assertNotNull(id) |
| 370 | assertTrue(id.startsWith("group:")) |
| 371 | val row = db.conversationDao().getConversation(id)!! |
| 372 | assertEquals("Y1 Group", row.name) |
| 373 | assertTrue(row.isGroup) |
| 374 | assertEquals("$peer,$bobAci", row.participants) |
| 375 | assertEquals(0, row.groupRevision) |
| 376 | assertEquals(32, row.groupMasterKey!!.size) |
| 377 | // The id is derived from that very master key, not from the key itself. |
| 378 | assertEquals(id, SignalProtocol.toConversationId("", row.groupMasterKey)) |
| 379 | val upd = seen.filterIsInstance<SignalEvent.ConversationUpdate>().single() |
| 380 | assertEquals(id, upd.conversationId) |
| 381 | assertEquals("Y1 Group", upd.peerName) |
| 382 | assertEquals(2, upd.participantCount) |
| 383 | assertTrue(upd.isGroup) |
| 384 | } |
| 385 | |
| 386 | @Test |
| 387 | fun createGroup_emptyContactsAndNoAuthCases() = runTest { |
| 388 | val id = SignalClient.createGroup("Solo", emptyList()) |
| 389 | assertNotNull(id) |
| 390 | assertEquals("", db.conversationDao().getConversation(id)?.participants) |
| 391 | // Without auth the server call cannot be made, but local persistence |
| 392 | // is skipped too because createGroup returns before upsert? No: auth |
| 393 | // check is before the emit/upsert only for putNewGroup; with no auth |
| 394 | // it returns null and creates nothing new. |
| 395 | val before = db.conversationDao().getRecent(50).size |
| 396 | SignalClient.authData = null |
| 397 | assertNull(SignalClient.createGroup("NoAuth", listOf(peer))) |
| 398 | assertEquals(before, db.conversationDao().getRecent(50).size) |
| 399 | } |
| 400 | |
| 401 | @Test |
| 402 | fun createGroup_secondGroupGetsFreshKeyAndId() = runTest { |
| 403 | val a = SignalClient.createGroup("A", listOf(peer))!! |
| 404 | val b = SignalClient.createGroup("B", listOf(peer))!! |
| 405 | assertTrue(a != b) |
| 406 | val ka = db.conversationDao().getConversation(a)!!.groupMasterKey!! |
| 407 | val kb = db.conversationDao().getConversation(b)!!.groupMasterKey!! |
| 408 | assertFalse(ka.contentEquals(kb)) |
| 409 | } |
| 410 | |
| 411 | @Test |
| 412 | fun setGroupName_keylessAndUnknownGroupsFailWithoutTouchingRow() = runTest { |
| 413 | db.conversationDao().upsert(SignalConversation(chatId = "group:keyless-y1", isGroup = true, name = "Old")) |
| 414 | assertFalse(SignalClient.setGroupName("group:keyless-y1", "New")) |
| 415 | assertEquals("Old", db.conversationDao().getConversation("group:keyless-y1")?.name) |
| 416 | assertFalse(SignalClient.setGroupName("group:absent-y1", "New")) |
| 417 | } |
| 418 | |
| 419 | @Test |
| 420 | fun setGroupName_withKeyButServerUnreachableKeepsOldNameAndRevision() = runTest { |
| 421 | val (masterKey, _) = SignalGroups.generateMasterKeyAndSecretParams() |
| 422 | val convId = SignalProtocol.toConversationId("", masterKey) |
| 423 | db.conversationDao().upsert( |
| 424 | SignalConversation(chatId = convId, isGroup = true, name = "Before", groupMasterKey = masterKey, groupRevision = 4), |
| 425 | ) |
| 426 | val seen = mutableListOf<SignalEvent>() |
| 427 | val job = launch(Dispatchers.Unconfined) { SignalClient.events.collect { seen.add(it) } } |
| 428 | assertFalse(SignalClient.setGroupName(convId, "After")) |
| 429 | job.cancel() |
| 430 | val row = db.conversationDao().getConversation(convId)!! |
| 431 | assertEquals("Before", row.name) |
| 432 | assertEquals(4, row.groupRevision) |
| 433 | assertTrue(seen.filterIsInstance<SignalEvent.ConversationNameChanged>().isEmpty()) |
| 434 | } |
| 435 | |
| 436 | @Test |
| 437 | fun updateGroupParticipants_removeAndBogusActionsRefusedLocally() = runTest { |
| 438 | val (masterKey, _) = SignalGroups.generateMasterKeyAndSecretParams() |
| 439 | val convId = SignalProtocol.toConversationId("", masterKey) |
| 440 | db.conversationDao().upsert( |
| 441 | SignalConversation(chatId = convId, isGroup = true, participants = peer, groupMasterKey = masterKey, groupRevision = 1), |
| 442 | ) |
| 443 | val seen = mutableListOf<SignalEvent>() |
| 444 | val job = launch(Dispatchers.Unconfined) { SignalClient.events.collect { seen.add(it) } } |
| 445 | assertFalse(SignalClient.updateGroupParticipants(convId, listOf(bobAci), "remove")) |
| 446 | assertFalse(SignalClient.updateGroupParticipants(convId, listOf(bobAci), "bogus")) |
| 447 | assertFalse(SignalClient.updateGroupParticipants("group:absent", listOf(bobAci), "add")) |
| 448 | job.cancel() |
| 449 | assertTrue(seen.filterIsInstance<SignalEvent.ParticipantAdded>().isEmpty()) |
| 450 | assertTrue(seen.filterIsInstance<SignalEvent.ParticipantRemoved>().isEmpty()) |
| 451 | assertEquals(peer, db.conversationDao().getConversation(convId)?.participants) |
| 452 | } |
| 453 | |
| 454 | @Test |
| 455 | fun updateGroupParticipants_addWithKeyButServerUnreachableEmitsNothing() = runTest { |
| 456 | val (masterKey, _) = SignalGroups.generateMasterKeyAndSecretParams() |
| 457 | val convId = SignalProtocol.toConversationId("", masterKey) |
| 458 | db.conversationDao().upsert( |
| 459 | SignalConversation(chatId = convId, isGroup = true, participants = peer, groupMasterKey = masterKey, groupRevision = 2), |
| 460 | ) |
| 461 | val seen = mutableListOf<SignalEvent>() |
| 462 | val job = launch(Dispatchers.Unconfined) { SignalClient.events.collect { seen.add(it) } } |
| 463 | assertFalse(SignalClient.updateGroupParticipants(convId, listOf(bobAci), "add")) |
| 464 | job.cancel() |
| 465 | assertTrue(seen.filterIsInstance<SignalEvent.ParticipantAdded>().isEmpty()) |
| 466 | // Local membership is not optimistically rewritten on a rejected change. |
| 467 | assertEquals(peer, db.conversationDao().getConversation(convId)?.participants) |
| 468 | assertEquals(2, db.conversationDao().getConversation(convId)?.groupRevision) |
| 469 | } |
| 470 | |
| 471 | @Test |
| 472 | fun refreshGroup_guardsAndUnreachableServerLeaveRowUntouched() = runTest { |
| 473 | assertFalse(SignalClient.refreshGroup("group:absent")) |
| 474 | db.conversationDao().upsert(SignalConversation(chatId = "group:keyless-r", isGroup = true, name = "K")) |
| 475 | assertFalse(SignalClient.refreshGroup("group:keyless-r")) |
| 476 | val (masterKey, _) = SignalGroups.generateMasterKeyAndSecretParams() |
| 477 | val convId = SignalProtocol.toConversationId("", masterKey) |
| 478 | db.conversationDao().upsert( |
| 479 | SignalConversation(chatId = convId, isGroup = true, name = "Keep", participants = peer, groupMasterKey = masterKey, groupRevision = 7), |
| 480 | ) |
| 481 | assertFalse(SignalClient.refreshGroup(convId)) |
| 482 | val row = db.conversationDao().getConversation(convId)!! |
| 483 | assertEquals("Keep", row.name) |
| 484 | assertEquals(peer, row.participants) |
| 485 | assertEquals(7, row.groupRevision) |
| 486 | SignalClient.authData = null |
| 487 | assertFalse(SignalClient.refreshGroup(convId)) |
| 488 | } |
| 489 | |
| 490 | @Test |
| 491 | fun rememberInboundGroup_createsThenMergesMembership() = runTest { |
| 492 | val (masterKey, _) = SignalGroups.generateMasterKeyAndSecretParams() |
| 493 | val convId = SignalProtocol.toConversationId("", masterKey) |
| 494 | SignalClient.rememberInboundGroup(convId, masterKey, bobAci) |
| 495 | var row = db.conversationDao().getConversation(convId)!! |
| 496 | assertTrue(row.isGroup) |
| 497 | assertTrue(row.groupMasterKey!!.contentEquals(masterKey)) |
| 498 | assertEquals(setOf(bobAci, selfAci), row.participants.split(",").toSet()) |
| 499 | // A second sender is merged; duplicates and our own id are not repeated. |
| 500 | SignalClient.rememberInboundGroup(convId, masterKey, peer) |
| 501 | row = db.conversationDao().getConversation(convId)!! |
| 502 | assertEquals(setOf(bobAci, selfAci, peer), row.participants.split(",").toSet()) |
| 503 | SignalClient.rememberInboundGroup(convId, masterKey, peer) |
| 504 | row = db.conversationDao().getConversation(convId)!! |
| 505 | assertEquals(3, row.participants.split(",").size) |
| 506 | } |
| 507 | |
| 508 | @Test |
| 509 | fun rememberInboundGroup_preservesExistingNameAndReplacesKey() = runTest { |
| 510 | val (k1, _) = SignalGroups.generateMasterKeyAndSecretParams() |
| 511 | val (k2, _) = SignalGroups.generateMasterKeyAndSecretParams() |
| 512 | val convId = SignalProtocol.toConversationId("", k1) |
| 513 | db.conversationDao().upsert( |
| 514 | SignalConversation(chatId = convId, isGroup = true, name = "Named", participants = peer, groupMasterKey = k1, groupRevision = 5), |
| 515 | ) |
| 516 | SignalClient.rememberInboundGroup(convId, k2, bobAci) |
| 517 | val row = db.conversationDao().getConversation(convId)!! |
| 518 | assertEquals("Named", row.name) |
| 519 | assertTrue(row.groupMasterKey!!.contentEquals(k2)) |
| 520 | assertEquals(setOf(peer, bobAci, selfAci), row.participants.split(",").toSet()) |
| 521 | } |
| 522 | |
| 523 | @Test |
| 524 | fun conversationForGroupId_andGroupAuthorizationOffline() = runTest { |
| 525 | val (masterKey, _) = SignalGroups.generateMasterKeyAndSecretParams() |
| 526 | val convId = SignalProtocol.toConversationId("", masterKey) |
| 527 | db.conversationDao().upsert( |
| 528 | SignalConversation(chatId = convId, isGroup = true, groupMasterKey = masterKey), |
| 529 | ) |
| 530 | val groupIdBytes = SignalGroups.groupIdentifierBytes(masterKey) |
| 531 | assertEquals(convId, SignalClient.conversationForGroupId(groupIdBytes)?.chatId) |
| 532 | assertNull(SignalClient.conversationForGroupId(ByteArray(32) { 9 })) |
| 533 | // Credentials cannot be fetched offline, so no authorization is minted. |
| 534 | assertNull(SignalClient.groupAuthorization(groupIdBytes)) |
| 535 | } |
| 536 | |
| 537 | // ---------- inbound dispatch (real E2E Bob -> Alice) ---------- |
| 538 | |
| 539 | private lateinit var alice: SignalE2E |
| 540 | private lateinit var bob: SignalE2E |
| 541 | private lateinit var authA: SignalAuthData |
| 542 | private lateinit var authB: SignalAuthData |
| 543 | |
| 544 | private fun wireE2E() { |
| 545 | authA = SignalRegistrationKeys.generate("+14155552671").authScaffold.copy(aci = selfAci) |
| 546 | authB = SignalRegistrationKeys.generate("+14155550000").authScaffold.copy(aci = bobAci) |
| 547 | alice = SignalE2E(db, authA) |
| 548 | bob = SignalE2E(dbBob, authB) |
| 549 | SignalClient.authData = authA |
| 550 | SignalClient.e2e = alice |
| 551 | } |
| 552 | |
| 553 | private fun bobBundle(): SignalE2E.ParsedPreKeyBundle { |
| 554 | val upload = bob.ensureLocalPreKeys() |
| 555 | val signed = upload.signedPreKey ?: error("no signed") |
| 556 | val kyber = upload.lastResortKyber ?: error("no kyber") |
| 557 | return SignalE2E.ParsedPreKeyBundle( |
| 558 | registrationId = authB.effectiveAciRegId(), |
| 559 | preKeyId = upload.oneTimeEcPreKeys.firstOrNull()?.id, |
| 560 | preKeyPublic = upload.oneTimeEcPreKeys.firstOrNull()?.publicKey, |
| 561 | signedPreKeyId = signed.id, |
| 562 | signedPreKeyPublic = signed.publicKey, |
| 563 | signedPreKeySignature = signed.signature ?: ByteArray(0), |
| 564 | identityKey = android.util.Base64.decode(authB.effectiveAciPublic(), android.util.Base64.NO_WRAP), |
| 565 | kyberPreKeyId = kyber.id, |
| 566 | kyberPreKeyPublic = kyber.publicKey, |
| 567 | kyberPreKeySignature = kyber.signature ?: ByteArray(0), |
| 568 | ) |
| 569 | } |
| 570 | |
| 571 | private suspend fun feedFromBob(content: SignalServiceProtos.Content, ts: Long): SignalEvent? { |
| 572 | if (!alice.hasSession(bobAci, 1)) alice.processPreKeyBundle(bobAci, 1, bobBundle()) |
| 573 | val padded = SignalProtocol.padMessageBody(content.toByteArray()) |
| 574 | val enc = alice.encryptDM(bobAci, 1, padded) |
| 575 | bob.decryptDM(authA.aci, 1, isPreKey = true, ciphertext = enc.data) |
| 576 | val back = bob.encryptDM(authA.aci, 1, padded) |
| 577 | val envelope = SignalServiceProtos.Envelope.newBuilder() |
| 578 | .setType(SignalServiceProtos.Envelope.Type.DOUBLE_RATCHET) |
| 579 | .setSourceServiceId(bobAci).setSourceDeviceId(1) |
| 580 | .setClientTimestamp(ts).setContent(ByteString.copyFrom(back.data)).build() |
| 581 | val frame = WebSocketMessage.newBuilder().setType(WebSocketMessage.Type.REQUEST) |
| 582 | .setRequest( |
| 583 | WebSocketRequestMessage.newBuilder().setVerb("PUT").setPath("/api/v1/message") |
| 584 | .setId(77L).setBody(ByteString.copyFrom(envelope.toByteArray())).build(), |
| 585 | ).build().toByteArray() |
| 586 | val deferred = CoroutineScope(Dispatchers.Unconfined).async { SignalClient.events.first() } |
| 587 | SignalClient.handleInboundFrame(frame) |
| 588 | return withTimeoutOrNull(5_000) { deferred.await() } |
| 589 | } |
| 590 | |
| 591 | private fun dmContent(dm: SignalServiceProtos.DataMessage): SignalServiceProtos.Content = |
| 592 | SignalServiceProtos.Content.newBuilder().setDataMessage(dm).build() |
| 593 | |
| 594 | @Test |
| 595 | fun inboundReactionRemove_resolvesTargetIdByTimestamp() = runTest { |
| 596 | wireE2E() |
| 597 | db.cachedMessageDao().upsert( |
| 598 | SignalCachedMessage(messageId = "target-1", conversationId = bobAci, body = "hi", timestamp = 1_700_000_000_000L, outgoing = true, senderId = selfAci), |
| 599 | ) |
| 600 | val dm = SignalPayload.buildDataMessage( |
| 601 | body = "", timestamp = 1_700_000_001_000L, |
| 602 | reaction = SignalPayload.buildReaction(emoji = "", remove = true, targetSentTimestamp = 1_700_000_000_000L), |
| 603 | ) |
| 604 | val e = feedFromBob(dmContent(dm), 1_700_000_001_000L) |
| 605 | assertTrue(e is SignalEvent.ReactionRemoved, "got $e") |
| 606 | assertEquals("target-1", e.messageId) |
| 607 | assertEquals(bobAci, e.senderId) |
| 608 | } |
| 609 | |
| 610 | @Test |
| 611 | fun inboundDelete_resolvesTargetId() = runTest { |
| 612 | wireE2E() |
| 613 | db.cachedMessageDao().upsert( |
| 614 | SignalCachedMessage(messageId = "victim", conversationId = bobAci, body = "bye", timestamp = 1_700_000_010_000L, outgoing = false, senderId = bobAci), |
| 615 | ) |
| 616 | val delDm = SignalPayload.buildDataMessage( |
| 617 | body = "", timestamp = 1_700_000_011_000L, |
| 618 | delete = SignalPayload.buildDelete(targetSentTimestamp = 1_700_000_010_000L), |
| 619 | ) |
| 620 | val del = feedFromBob(dmContent(delDm), 1_700_000_011_000L) |
| 621 | assertTrue(del is SignalEvent.MessageDeleted && del.messageId == "victim", "got $del") |
| 622 | } |
| 623 | |
| 624 | @Test |
| 625 | fun inboundEdit_resolvesTargetId() = runTest { |
| 626 | wireE2E() |
| 627 | db.cachedMessageDao().upsert( |
| 628 | SignalCachedMessage(messageId = "victim", conversationId = bobAci, body = "bye", timestamp = 1_700_000_010_000L, outgoing = false, senderId = bobAci), |
| 629 | ) |
| 630 | val editContent = SignalPayload.buildContentForEdit( |
| 631 | targetSentTimestamp = 1_700_000_010_000L, |
| 632 | newDataMessage = SignalPayload.buildDataMessage(body = "edited!", timestamp = 1_700_000_012_000L), |
| 633 | ) |
| 634 | val edit = feedFromBob(editContent, 1_700_000_012_000L) |
| 635 | assertTrue(edit is SignalEvent.MessageEdited, "got $edit") |
| 636 | assertEquals("victim", edit.messageId) |
| 637 | assertEquals("edited!", edit.newBody) |
| 638 | } |
| 639 | |
| 640 | @Test |
| 641 | fun inboundReadReceiptForUnknownOutgoing_usesTimestampAsId() = runTest { |
| 642 | wireE2E() |
| 643 | val content = SignalServiceProtos.Content.newBuilder() |
| 644 | .setReceiptMessage( |
| 645 | SignalServiceProtos.ReceiptMessage.newBuilder() |
| 646 | .setType(SignalServiceProtos.ReceiptMessage.Type.READ) |
| 647 | .addTimestamp(1_700_000_020_000L), |
| 648 | ).build() |
| 649 | val e = feedFromBob(content, 1_700_000_021_000L) |
| 650 | assertTrue(e is SignalEvent.ReadReceipt, "got $e") |
| 651 | assertFalse(e.isDelivery) |
| 652 | assertEquals("1700000020000", e.messageId) |
| 653 | } |
| 654 | |
| 655 | @Test |
| 656 | fun inboundTypingStopped_emitsNotTyping() = runTest { |
| 657 | wireE2E() |
| 658 | val content = SignalServiceProtos.Content.newBuilder() |
| 659 | .setTypingMessage( |
| 660 | SignalServiceProtos.TypingMessage.newBuilder() |
| 661 | .setTimestamp(1_700_000_030_000L) |
| 662 | .setAction(SignalServiceProtos.TypingMessage.Action.STOPPED), |
| 663 | ).build() |
| 664 | val e = feedFromBob(content, 1_700_000_030_000L) |
| 665 | assertTrue(e is SignalEvent.TypingIndicator && !e.isTyping, "got $e") |
| 666 | } |
| 667 | |
| 668 | @Test |
| 669 | fun inboundSyncViewed_emitsReadReceiptResolvedByTimestamp() = runTest { |
| 670 | wireE2E() |
| 671 | db.cachedMessageDao().upsert( |
| 672 | SignalCachedMessage(messageId = "seen-1", conversationId = bobAci, body = "hi", timestamp = 1_700_000_040_000L, outgoing = false, senderId = bobAci), |
| 673 | ) |
| 674 | val content = SignalServiceProtos.Content.newBuilder() |
| 675 | .setSyncMessage( |
| 676 | SignalServiceProtos.SyncMessage.newBuilder() |
| 677 | .addViewed( |
| 678 | SignalServiceProtos.SyncMessage.Viewed.newBuilder() |
| 679 | .setTimestamp(1_700_000_040_000L).build(), |
| 680 | ), |
| 681 | ).build() |
| 682 | val e = feedFromBob(content, 1_700_000_041_000L) |
| 683 | assertTrue(e is SignalEvent.ReadReceipt, "got $e") |
| 684 | assertEquals("seen-1", e.messageId) |
| 685 | assertFalse(e.isDelivery) |
| 686 | } |
| 687 | |
| 688 | @Test |
| 689 | fun inboundAttachments_videoAndFileTypesAndEmptyKeyDropped() = runTest { |
| 690 | wireE2E() |
| 691 | fun pointer(key: String, mime: String) = SignalServiceProtos.AttachmentPointer.newBuilder() |
| 692 | .setCdnKey(key).setCdnNumber(3).setContentType(mime).setSize(5) |
| 693 | .setKey(ByteString.copyFrom(ByteArray(64) { 2 })).build() |
| 694 | val dm = SignalServiceProtos.DataMessage.newBuilder() |
| 695 | .setBody("media").setTimestamp(1_700_000_050_000L) |
| 696 | .addAttachments(pointer("vidkey", "video/mp4")) |
| 697 | .addAttachments(pointer("", "image/png")) |
| 698 | .addAttachments(pointer("docKey", "application/pdf")) |
| 699 | .build() |
| 700 | val e = feedFromBob(dmContent(dm), 1_700_000_050_000L) |
| 701 | assertTrue(e is SignalEvent.IncomingMessage, "got $e") |
| 702 | val atts = e.attachments |
| 703 | assertEquals(2, atts.size) |
| 704 | assertEquals("video", atts[0].attachmentType) |
| 705 | assertEquals("https://cdn3.signal.org/attachments/vidkey", atts[0].url) |
| 706 | assertEquals("file", atts[1].attachmentType) |
| 707 | } |
| 708 | |
| 709 | @Test |
| 710 | fun inboundGroupText_createsGroupConversationAndFilesMessageThere() = runTest { |
| 711 | wireE2E() |
| 712 | val (masterKey, _) = SignalGroups.generateMasterKeyAndSecretParams() |
| 713 | val groupConv = SignalProtocol.toConversationId("", masterKey) |
| 714 | val dm = SignalPayload.buildDataMessage( |
| 715 | body = "hello group", timestamp = 1_700_000_060_000L, |
| 716 | groupV2MasterKey = masterKey, groupV2Revision = 2, |
| 717 | ) |
| 718 | val e = feedFromBob(dmContent(dm), 1_700_000_060_000L) |
| 719 | assertTrue(e is SignalEvent.IncomingMessage, "got $e") |
| 720 | assertEquals(groupConv, e.conversationId) |
| 721 | assertEquals("hello group", e.body) |
| 722 | val row = db.conversationDao().getConversation(groupConv) |
| 723 | assertNotNull(row) |
| 724 | assertTrue(row.isGroup) |
| 725 | assertTrue(row.participants.split(",").contains(bobAci)) |
| 726 | } |
| 727 | } |