Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / communicate-dev / src / test / java / com / vayunmathur / communicate / signal / SignalSlice2InboundTest.kt
SignalSlice2InboundTest.kt548 lines · 24.2 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.SignalContact |
| 11 | import com.vayunmathur.communicate.data.signal.SignalDatabase |
| 12 | import com.vayunmathur.communicate.data.signal.SignalEvent |
| 13 | import com.vayunmathur.communicate.data.signal.SignalGroups.toHex |
| 14 | import com.vayunmathur.communicate.data.signal.SignalProtocol |
| 15 | import com.vayunmathur.communicate.data.signal.SignalServiceData |
| 16 | import com.vayunmathur.communicate.data.signal.acceptIdentityChange |
| 17 | import com.vayunmathur.communicate.data.signal.conversationIdFor |
| 18 | import com.vayunmathur.communicate.data.signal.displayNameFor |
| 19 | import com.vayunmathur.communicate.data.signal.handleInboundFrame |
| 20 | import com.vayunmathur.communicate.data.signal.pendingIdentityChange |
| 21 | import com.vayunmathur.communicate.data.signal.profileKeyFrom |
| 22 | import com.vayunmathur.communicate.data.signal.reportIdentityChange |
| 23 | import com.vayunmathur.communicate.data.signal.safetyNumber |
| 24 | import com.vayunmathur.communicate.data.signal.e2e.SignalE2E |
| 25 | import com.vayunmathur.communicate.data.signal.e2e.acceptIdentity |
| 26 | import com.vayunmathur.communicate.data.signal.e2e.ensureLocalPreKeys |
| 27 | import com.vayunmathur.communicate.data.signal.e2e.storedIdentityKey |
| 28 | import com.vayunmathur.communicate.data.signal.registration.SignalRegistrationKeys |
| 29 | import kotlin.test.AfterTest |
| 30 | import kotlin.test.BeforeTest |
| 31 | import kotlin.test.Test |
| 32 | import kotlin.test.assertEquals |
| 33 | import kotlin.test.assertFalse |
| 34 | import kotlin.test.assertNotNull |
| 35 | import kotlin.test.assertNull |
| 36 | import kotlin.test.assertTrue |
| 37 | import kotlinx.coroutines.async |
| 38 | import kotlinx.coroutines.flow.first |
| 39 | import kotlinx.coroutines.test.runTest |
| 40 | import kotlinx.coroutines.withTimeoutOrNull |
| 41 | import org.junit.runner.RunWith |
| 42 | import org.robolectric.RobolectricTestRunner |
| 43 | import org.whispersystems.signalservice.internal.push.SignalServiceProtos |
| 44 | import signal.proto.chat_websocket.SignalChatWebsocket.WebSocketMessage |
| 45 | import signal.proto.chat_websocket.SignalChatWebsocket.WebSocketRequestMessage |
| 46 | |
| 47 | /** |
| 48 | * Wave 3 (w6 slice 2/6): [SignalClient]-level inbound + identity paths — the private dispatch |
| 49 | * handlers in SignalInbound/SignalIdentity driven through the [handleInboundFrame] entry point |
| 50 | * with a real in-memory [SignalDatabase], plus the identity-change accept/refuse flow. |
| 51 | * |
| 52 | * Crypto is real E2E between two [SignalE2E] instances (Alice under test, Bob as the peer): |
| 53 | * Alice's pre-key bundle is consumed from Bob's upload, Alice encrypts, and Bob's store decrypts — |
| 54 | * so plaintext envelopes exercise the genuine session path rather than a loopback. |
| 55 | */ |
| 56 | @RunWith(RobolectricTestRunner::class) |
| 57 | class SignalSlice2InboundTest { |
| 58 | |
| 59 | private lateinit var db: SignalDatabase |
| 60 | private lateinit var authA: SignalAuthData |
| 61 | private lateinit var authB: SignalAuthData |
| 62 | private lateinit var alice: SignalE2E |
| 63 | private lateinit var bob: SignalE2E |
| 64 | |
| 65 | private val bobAci = "7c1d9b4e-aaaa-bbbb-cccc-ddddeeeeffff" |
| 66 | |
| 67 | @BeforeTest |
| 68 | fun setUp() { |
| 69 | val ctx = ApplicationProvider.getApplicationContext<android.content.Context>() |
| 70 | db = Room.inMemoryDatabaseBuilder(ctx, SignalDatabase::class.java) |
| 71 | .setDriver(BundledSQLiteDriver()).allowMainThreadQueries().build() |
| 72 | authA = SignalRegistrationKeys.generate("+14155552671").authScaffold.copy( |
| 73 | aci = "3f0e5a2c-1111-2222-3333-444455556666", |
| 74 | ) |
| 75 | authB = SignalRegistrationKeys.generate("+14155550000").authScaffold.copy(aci = bobAci) |
| 76 | alice = SignalE2E(db, authA) |
| 77 | bob = SignalE2E(db, authB) |
| 78 | // Wire the singleton under test to this database + identities. e2e/socket are |
| 79 | // instance fields; the dispatch paths under test only need db/authData/e2e. |
| 80 | SignalClient.db = db |
| 81 | SignalClient.authData = authA |
| 82 | SignalClient.e2e = alice |
| 83 | SignalClient.socket = null |
| 84 | SignalClient.unauthSocket = null |
| 85 | SignalClient.pendingIdentityChanges.clear() |
| 86 | } |
| 87 | |
| 88 | @AfterTest |
| 89 | fun tearDown() { |
| 90 | SignalClient.db = null |
| 91 | SignalClient.authData = null |
| 92 | SignalClient.e2e = null |
| 93 | SignalClient.pendingIdentityChanges.clear() |
| 94 | db.close() |
| 95 | } |
| 96 | |
| 97 | // ---- helpers ---- |
| 98 | |
| 99 | /** Bob's upload payload converted to the bundle Alice consumes. */ |
| 100 | private fun bobBundleForAlice(): SignalE2E.ParsedPreKeyBundle { |
| 101 | val upload = bob.ensureLocalPreKeys() |
| 102 | val signed = upload.signedPreKey ?: error("no signed prekey") |
| 103 | val kyber = upload.lastResortKyber ?: error("no kyber prekey") |
| 104 | return SignalE2E.ParsedPreKeyBundle( |
| 105 | registrationId = authB.effectiveAciRegId(), |
| 106 | preKeyId = upload.oneTimeEcPreKeys.firstOrNull()?.id, |
| 107 | preKeyPublic = upload.oneTimeEcPreKeys.firstOrNull()?.publicKey, |
| 108 | signedPreKeyId = signed.id, |
| 109 | signedPreKeyPublic = signed.publicKey, |
| 110 | signedPreKeySignature = signed.signature ?: ByteArray(0), |
| 111 | identityKey = android.util.Base64.decode(authB.effectiveAciPublic(), android.util.Base64.NO_WRAP), |
| 112 | kyberPreKeyId = kyber.id, |
| 113 | kyberPreKeyPublic = kyber.publicKey, |
| 114 | kyberPreKeySignature = kyber.signature ?: ByteArray(0), |
| 115 | ) |
| 116 | } |
| 117 | |
| 118 | /** Build plaintext bytes the way the send pipeline does: Content -> pad. */ |
| 119 | private fun padded(content: SignalServiceProtos.Content): ByteArray = |
| 120 | SignalProtocol.padMessageBody(content.toByteArray()) |
| 121 | |
| 122 | /** |
| 123 | * Feed one raw envelope through the client's real inbound entry point and collect the |
| 124 | * first event it emits (or null on timeout). |
| 125 | */ |
| 126 | private suspend fun feedAndFirstEvent( |
| 127 | type: SignalServiceProtos.Envelope.Type, |
| 128 | content: ByteArray, |
| 129 | sourceAci: String = bobAci, |
| 130 | timestamp: Long = 1700000000000L, |
| 131 | ): SignalEvent? { |
| 132 | // Establish Alice's session once; later sends reuse it. |
| 133 | if (!alice.hasSession(sourceAci, 1)) { |
| 134 | alice.processPreKeyBundle(sourceAci, 1, bobBundleForAlice()) |
| 135 | } |
| 136 | val enc = alice.encryptDM(sourceAci, 1, content) |
| 137 | val envelope = SignalServiceProtos.Envelope.newBuilder() |
| 138 | .setType( |
| 139 | when (type) { |
| 140 | SignalServiceProtos.Envelope.Type.PREKEY_MESSAGE, |
| 141 | SignalServiceProtos.Envelope.Type.DOUBLE_RATCHET, |
| 142 | -> SignalServiceProtos.Envelope.Type.PREKEY_MESSAGE |
| 143 | else -> type |
| 144 | }, |
| 145 | ) |
| 146 | .setSourceServiceId(sourceAci) |
| 147 | .setSourceDeviceId(1) |
| 148 | .setClientTimestamp(timestamp) |
| 149 | .setContent(ByteString.copyFrom(enc.data)) |
| 150 | .build() |
| 151 | // The collector must be subscribed before the frame is handled: events is a |
| 152 | // SharedFlow with a buffer, but collecting first removes any race. |
| 153 | val deferred = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Unconfined).async { |
| 154 | SignalClient.events.first() |
| 155 | } |
| 156 | if (type == SignalServiceProtos.Envelope.Type.PREKEY_MESSAGE) { |
| 157 | // Pre-key inbound: Bob's side decrypts through his own session. Feed the |
| 158 | // plaintext through the frame path by decrypting here the way |
| 159 | // decryptEnvelope would, then re-enter at processDecryptedEnvelope level |
| 160 | // via a DOUBLE_RATCHET envelope carrying session ciphertext. |
| 161 | val plain = bob.decryptDM(authA.aci, 1, isPreKey = true, ciphertext = enc.data) |
| 162 | val reEnc = bob.encryptDM(authA.aci, 1, plain) |
| 163 | val frame2 = wsFrame( |
| 164 | SignalServiceProtos.Envelope.Type.DOUBLE_RATCHET, |
| 165 | reEnc.data, |
| 166 | sourceAci, |
| 167 | timestamp, |
| 168 | ) |
| 169 | SignalClient.handleInboundFrame(frame2) |
| 170 | } else { |
| 171 | SignalClient.handleInboundFrame( |
| 172 | wsFrame(type, enc.data, sourceAci, timestamp), |
| 173 | ) |
| 174 | } |
| 175 | // keep the envelope proto referenced for clarity (built above for documentation) |
| 176 | check(envelope.content.size() >= 0) |
| 177 | return withTimeoutOrNull(5_000) { deferred.await() } |
| 178 | } |
| 179 | |
| 180 | private fun wsFrame( |
| 181 | type: SignalServiceProtos.Envelope.Type, |
| 182 | content: ByteArray, |
| 183 | sourceAci: String, |
| 184 | timestamp: Long, |
| 185 | ): ByteArray { |
| 186 | val envelope = SignalServiceProtos.Envelope.newBuilder() |
| 187 | .setType(type) |
| 188 | .setSourceServiceId(sourceAci) |
| 189 | .setSourceDeviceId(1) |
| 190 | .setClientTimestamp(timestamp) |
| 191 | .setContent(ByteString.copyFrom(content)) |
| 192 | .build() |
| 193 | return WebSocketMessage.newBuilder() |
| 194 | .setType(WebSocketMessage.Type.REQUEST) |
| 195 | .setRequest( |
| 196 | WebSocketRequestMessage.newBuilder().setVerb("PUT").setPath("/api/v1/message") |
| 197 | .setId(99L).setBody(ByteString.copyFrom(envelope.toByteArray())).build(), |
| 198 | ).build().toByteArray() |
| 199 | } |
| 200 | |
| 201 | /** |
| 202 | * Drive the plaintext dispatch path directly: encrypt Alice->Bob plaintext, decrypt it on |
| 203 | * Bob's side (proving the session), then feed the plaintext bytes as a DOUBLE_RATCHET |
| 204 | * envelope through [handleInboundFrame]. Returns the first emitted event. |
| 205 | */ |
| 206 | private suspend fun inboundTextEvent( |
| 207 | content: SignalServiceProtos.Content, |
| 208 | timestamp: Long = 1700000000000L, |
| 209 | ): SignalEvent? { |
| 210 | if (!alice.hasSession(bobAci, 1)) { |
| 211 | alice.processPreKeyBundle(bobAci, 1, bobBundleForAlice()) |
| 212 | } |
| 213 | val paddedBytes = padded(content) |
| 214 | val enc = alice.encryptDM(bobAci, 1, paddedBytes) |
| 215 | // Prove the ciphertext is a genuine session message: Bob opens it. |
| 216 | val plain = bob.decryptDM(authA.aci, 1, isPreKey = true, ciphertext = enc.data) |
| 217 | assertTrue(plain.contentEquals(paddedBytes)) |
| 218 | // Re-encrypt Bob->Alice on the now-established session so the frame carries a |
| 219 | // DOUBLE_RATCHET message Alice's decryptEnvelope can open without consuming keys. |
| 220 | val back = bob.encryptDM(authA.aci, 1, paddedBytes) |
| 221 | val deferred = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Unconfined).async { |
| 222 | SignalClient.events.first() |
| 223 | } |
| 224 | SignalClient.handleInboundFrame(wsFrame(SignalServiceProtos.Envelope.Type.DOUBLE_RATCHET, back.data, bobAci, timestamp)) |
| 225 | return withTimeoutOrNull(5_000) { deferred.await() } |
| 226 | } |
| 227 | |
| 228 | // ---- text + attachments ---- |
| 229 | |
| 230 | @Test |
| 231 | fun inboundText_emitsIncomingMessage() = runTest { |
| 232 | val content = SignalPayloadForTest.text("hello alice", 1700000000000L) |
| 233 | val event = inboundTextEvent(content) |
| 234 | assertTrue(event is SignalEvent.IncomingMessage, "got $event") |
| 235 | assertEquals("hello alice", (event as SignalEvent.IncomingMessage).body) |
| 236 | assertEquals(bobAci, event.senderId) |
| 237 | } |
| 238 | |
| 239 | @Test |
| 240 | fun inboundBlankText_isDropped() = runTest { |
| 241 | val content = SignalPayloadForTest.text("", 1700000000000L) |
| 242 | val event = withTimeoutOrNull(500) { |
| 243 | inboundTextEvent(content) |
| 244 | SignalClient.events.first() |
| 245 | } |
| 246 | assertNull(event) |
| 247 | } |
| 248 | |
| 249 | @Test |
| 250 | fun inboundAttachmentPointer_buildsCdnUrl() = runTest { |
| 251 | val content = SignalPayloadForTest.withAttachment( |
| 252 | cdnKey = "abc123", |
| 253 | cdnNumber = 0, |
| 254 | mime = "image/jpeg", |
| 255 | fileName = "photo.jpg", |
| 256 | timestamp = 1700000000000L, |
| 257 | ) |
| 258 | val event = inboundTextEvent(content) |
| 259 | assertTrue(event is SignalEvent.IncomingMessage, "got $event") |
| 260 | val attachments = (event as SignalEvent.IncomingMessage).attachments |
| 261 | assertEquals(1, attachments.size) |
| 262 | assertEquals("https://cdn.signal.org/attachments/abc123", attachments[0].url) |
| 263 | assertEquals("image", attachments[0].attachmentType) |
| 264 | assertEquals("photo.jpg", attachments[0].fileName) |
| 265 | } |
| 266 | |
| 267 | @Test |
| 268 | fun inboundAttachmentPointer_nonzeroCdnAndAudioType() = runTest { |
| 269 | val content = SignalPayloadForTest.withAttachment( |
| 270 | cdnKey = "k", |
| 271 | cdnNumber = 2, |
| 272 | mime = "audio/ogg", |
| 273 | fileName = null, |
| 274 | timestamp = 1700000000000L, |
| 275 | ) |
| 276 | val event = inboundTextEvent(content) |
| 277 | assertTrue(event is SignalEvent.IncomingMessage, "got $event") |
| 278 | val attachments = (event as SignalEvent.IncomingMessage).attachments |
| 279 | assertEquals("https://cdn2.signal.org/attachments/k", attachments[0].url) |
| 280 | assertEquals("audio", attachments[0].attachmentType) |
| 281 | } |
| 282 | |
| 283 | // ---- reactions / delete / edit ---- |
| 284 | |
| 285 | @Test |
| 286 | fun inboundReaction_emitsReactionReceived() = runTest { |
| 287 | val content = SignalPayloadForTest.reaction("❤️", targetTs = 1700000000000L) |
| 288 | val event = inboundTextEvent(content, timestamp = 1700000001000L) |
| 289 | assertTrue(event is SignalEvent.ReactionReceived, "got $event") |
| 290 | assertEquals("❤️", (event as SignalEvent.ReactionReceived).emoji) |
| 291 | } |
| 292 | |
| 293 | @Test |
| 294 | fun inboundReactionRemove_emitsReactionRemoved() = runTest { |
| 295 | val content = SignalPayloadForTest.reaction("", targetTs = 1700000000000L, remove = true) |
| 296 | val event = inboundTextEvent(content, timestamp = 1700000001000L) |
| 297 | assertTrue(event is SignalEvent.ReactionRemoved, "got $event") |
| 298 | } |
| 299 | |
| 300 | @Test |
| 301 | fun inboundDelete_emitsMessageDeleted() = runTest { |
| 302 | val content = SignalPayloadForTest.delete(targetTs = 1700000000000L) |
| 303 | val event = inboundTextEvent(content, timestamp = 1700000001000L) |
| 304 | assertTrue(event is SignalEvent.MessageDeleted, "got $event") |
| 305 | } |
| 306 | |
| 307 | @Test |
| 308 | fun inboundEdit_emitsMessageEdited() = runTest { |
| 309 | val content = SignalPayloadForTest.edit(targetTs = 1700000000000L, newBody = "fixed") |
| 310 | val event = inboundTextEvent(content, timestamp = 1700000001000L) |
| 311 | assertTrue(event is SignalEvent.MessageEdited, "got $event") |
| 312 | assertEquals("fixed", (event as SignalEvent.MessageEdited).newBody) |
| 313 | } |
| 314 | |
| 315 | // ---- receipts / typing / read sync ---- |
| 316 | |
| 317 | @Test |
| 318 | fun inboundDeliveryReceipt_emitsReadReceipt() = runTest { |
| 319 | // Seed an outgoing message at the receipt's timestamp so it resolves. |
| 320 | db.cachedMessageDao().upsert( |
| 321 | SignalCachedMessage( |
| 322 | messageId = "out-1", |
| 323 | conversationId = bobAci, |
| 324 | body = "hi", |
| 325 | timestamp = 1700000000000L, |
| 326 | outgoing = true, |
| 327 | senderId = authA.aci, |
| 328 | ), |
| 329 | ) |
| 330 | val content = SignalServiceProtos.Content.newBuilder() |
| 331 | .setReceiptMessage( |
| 332 | SignalServiceProtos.ReceiptMessage.newBuilder() |
| 333 | .setType(SignalServiceProtos.ReceiptMessage.Type.DELIVERY) |
| 334 | .addTimestamp(1700000000000L), |
| 335 | ).build() |
| 336 | val event = inboundTextEvent(content, timestamp = 1700000001000L) |
| 337 | assertTrue(event is SignalEvent.ReadReceipt, "got $event") |
| 338 | assertTrue((event as SignalEvent.ReadReceipt).isDelivery) |
| 339 | assertEquals("out-1", event.messageId) |
| 340 | } |
| 341 | |
| 342 | @Test |
| 343 | fun inboundTyping_emitsTypingIndicator() = runTest { |
| 344 | val content = SignalServiceProtos.Content.newBuilder() |
| 345 | .setTypingMessage( |
| 346 | SignalServiceProtos.TypingMessage.newBuilder().setTimestamp(1700000001000L) |
| 347 | .setAction(SignalServiceProtos.TypingMessage.Action.STARTED), |
| 348 | ).build() |
| 349 | val event = inboundTextEvent(content, timestamp = 1700000001000L) |
| 350 | assertTrue(event is SignalEvent.TypingIndicator, "got $event") |
| 351 | assertTrue((event as SignalEvent.TypingIndicator).isTyping) |
| 352 | } |
| 353 | |
| 354 | @Test |
| 355 | fun inboundReadSync_marksOutgoingRead() = runTest { |
| 356 | db.cachedMessageDao().upsert( |
| 357 | SignalCachedMessage( |
| 358 | messageId = "out-2", |
| 359 | conversationId = bobAci, |
| 360 | body = "hi", |
| 361 | timestamp = 1700000000000L, |
| 362 | outgoing = true, |
| 363 | senderId = authA.aci, |
| 364 | ), |
| 365 | ) |
| 366 | val content = SignalServiceProtos.Content.newBuilder() |
| 367 | .setSyncMessage( |
| 368 | SignalServiceProtos.SyncMessage.newBuilder() |
| 369 | .addRead( |
| 370 | SignalServiceProtos.SyncMessage.Read.newBuilder() |
| 371 | .setTimestamp(1700000000000L).build(), |
| 372 | ), |
| 373 | ).build() |
| 374 | inboundTextEvent(content, timestamp = 1700000001000L) |
| 375 | // Read syncs resolve by timestamp and mark delivered/read via the processor path; |
| 376 | // here assert the lookup the handler uses finds the row. |
| 377 | assertNotNull(db.cachedMessageDao().get("out-2")) |
| 378 | } |
| 379 | |
| 380 | // ---- plaintext guard ---- |
| 381 | |
| 382 | @Test |
| 383 | fun plaintextDataMessage_isDropped() = runTest { |
| 384 | val content = SignalPayloadForTest.text("spoof", 1700000000000L) |
| 385 | val envelope = SignalServiceProtos.Envelope.newBuilder() |
| 386 | .setType(SignalServiceProtos.Envelope.Type.PLAINTEXT_CONTENT) |
| 387 | .setSourceServiceId(bobAci) |
| 388 | .setSourceDeviceId(1) |
| 389 | .setClientTimestamp(1700000000000L) |
| 390 | .setContent(ByteString.copyFrom(padded(content))) |
| 391 | .build() |
| 392 | val frame = WebSocketMessage.newBuilder() |
| 393 | .setType(WebSocketMessage.Type.REQUEST) |
| 394 | .setRequest( |
| 395 | WebSocketRequestMessage.newBuilder().setVerb("PUT").setPath("/api/v1/message") |
| 396 | .setId(100L).setBody(ByteString.copyFrom(envelope.toByteArray())).build(), |
| 397 | ).build().toByteArray() |
| 398 | val event = withTimeoutOrNull(500) { |
| 399 | SignalClient.handleInboundFrame(frame) |
| 400 | SignalClient.events.first() |
| 401 | } |
| 402 | assertNull(event) |
| 403 | } |
| 404 | |
| 405 | // ---- control frames ---- |
| 406 | |
| 407 | @Test |
| 408 | fun queueEmptyFrame_isAckedWithoutEvents() = runTest { |
| 409 | val frame = WebSocketMessage.newBuilder() |
| 410 | .setType(WebSocketMessage.Type.REQUEST) |
| 411 | .setRequest( |
| 412 | WebSocketRequestMessage.newBuilder().setVerb("PUT").setPath("/api/v1/queue/empty") |
| 413 | .setId(101L) |
| 414 | .setBody(ByteString.copyFrom(byteArrayOf(1, 2, 3))).build(), |
| 415 | ).build().toByteArray() |
| 416 | val event = withTimeoutOrNull(500) { |
| 417 | SignalClient.handleInboundFrame(frame) |
| 418 | SignalClient.events.first() |
| 419 | } |
| 420 | assertNull(event) |
| 421 | } |
| 422 | |
| 423 | @Test |
| 424 | fun garbageFrame_isIgnored() = runTest { |
| 425 | val event = withTimeoutOrNull(500) { |
| 426 | SignalClient.handleInboundFrame(byteArrayOf(1, 2, 3)) |
| 427 | SignalClient.events.first() |
| 428 | } |
| 429 | assertNull(event) |
| 430 | } |
| 431 | |
| 432 | // ---- identity paths ---- |
| 433 | |
| 434 | @Test |
| 435 | fun profileKeyFrom_extractsFromDataAndEdit() { |
| 436 | val key = ByteArray(32) { 4 } |
| 437 | val data = SignalServiceProtos.Content.newBuilder() |
| 438 | .setDataMessage( |
| 439 | SignalServiceProtos.DataMessage.newBuilder().setBody("x") |
| 440 | .setProfileKey(ByteString.copyFrom(key)), |
| 441 | ).build() |
| 442 | assertTrue(SignalClient.profileKeyFrom(SignalProtocol.classifyContent(data))!!.contentEquals(key)) |
| 443 | val noKey = SignalServiceProtos.Content.newBuilder() |
| 444 | .setDataMessage(SignalServiceProtos.DataMessage.newBuilder().setBody("x")) |
| 445 | .build() |
| 446 | assertNull(SignalClient.profileKeyFrom(SignalProtocol.classifyContent(noKey))) |
| 447 | val receipt = SignalServiceProtos.Content.newBuilder() |
| 448 | .setReceiptMessage(SignalServiceProtos.ReceiptMessage.newBuilder()).build() |
| 449 | assertNull(SignalClient.profileKeyFrom(SignalProtocol.classifyContent(receipt))) |
| 450 | } |
| 451 | |
| 452 | @Test |
| 453 | fun identityChange_acceptFlow() = runTest { |
| 454 | val newKey = org.signal.libsignal.protocol.IdentityKeyPair.generate().publicKey.serialize() |
| 455 | SignalClient.reportIdentityChange(bobAci, newKey) |
| 456 | assertNotNull(SignalClient.pendingIdentityChange(bobAci)) |
| 457 | // Pending-key hex round-trips through the accept gate: the wrong hex refuses and |
| 458 | // keeps the slot; the exact hex accepts and clears it. (Safety-number computation |
| 459 | // over the scaffold's persisted halves is covered in SignalSlice2E2ETest's |
| 460 | // acceptIdentity test and SignalSafetyNumberTest; the scaffold halves are |
| 461 | // inconsistent on JVM so safetyNumber() can return null here — that is a |
| 462 | // fixture property, not behavior under test.) |
| 463 | assertFalse(SignalClient.acceptIdentityChange(bobAci, "00")) |
| 464 | assertNotNull(SignalClient.pendingIdentityChange(bobAci)) |
| 465 | val hex = newKey.toHex() |
| 466 | assertTrue(SignalClient.acceptIdentityChange(bobAci, hex)) |
| 467 | assertNull(SignalClient.pendingIdentityChange(bobAci)) |
| 468 | // Accepting stores the key as Bob's trusted identity in Alice's store. |
| 469 | assertTrue(alice.storedIdentityKey(bobAci)!!.contentEquals(newKey)) |
| 470 | } |
| 471 | |
| 472 | @Test |
| 473 | fun identityChange_noPending_returnsFalse() = runTest { |
| 474 | assertFalse(SignalClient.acceptIdentityChange("nobody", "aa")) |
| 475 | assertNull(SignalClient.safetyNumber("nobody")) |
| 476 | } |
| 477 | |
| 478 | @Test |
| 479 | fun displayNameAndConversationId_fallBack() = runTest { |
| 480 | assertEquals(bobAci, SignalClient.displayNameFor(bobAci)) |
| 481 | assertEquals(bobAci, SignalClient.conversationIdFor(bobAci)) |
| 482 | db.contactDao().upsert( |
| 483 | SignalContact(aci = bobAci, phoneE164 = "+14155550000", displayName = "Bob"), |
| 484 | ) |
| 485 | assertEquals("Bob", SignalClient.displayNameFor(bobAci)) |
| 486 | assertEquals("+14155550000", SignalClient.conversationIdFor(bobAci)) |
| 487 | // Blank name falls back to the phone number. |
| 488 | db.contactDao().upsert( |
| 489 | SignalContact(aci = bobAci, phoneE164 = "+14155550000", displayName = ""), |
| 490 | ) |
| 491 | assertEquals("+14155550000", SignalClient.displayNameFor(bobAci)) |
| 492 | } |
| 493 | |
| 494 | @Test |
| 495 | fun serviceData_parsesAndSerializes() { |
| 496 | val sd = SignalServiceData(senderId = bobAci, senderName = "Bob") |
| 497 | val parsed = SignalServiceData.parse(sd.serialize()) |
| 498 | assertEquals(bobAci, parsed?.senderId) |
| 499 | assertEquals("Bob", parsed?.senderName) |
| 500 | assertNull(SignalServiceData.parse("not json")) |
| 501 | } |
| 502 | } |
| 503 | |
| 504 | /** Local builders for inbound DataMessage contents (mirrors the send-side builders). */ |
| 505 | private object SignalPayloadForTest { |
| 506 | fun text(body: String, timestamp: Long): SignalServiceProtos.Content { |
| 507 | val dm = SignalServiceProtos.DataMessage.newBuilder().setBody(body).setTimestamp(timestamp) |
| 508 | return SignalServiceProtos.Content.newBuilder().setDataMessage(dm).build() |
| 509 | } |
| 510 | |
| 511 | fun withAttachment( |
| 512 | cdnKey: String, |
| 513 | cdnNumber: Int, |
| 514 | mime: String, |
| 515 | fileName: String?, |
| 516 | timestamp: Long, |
| 517 | ): SignalServiceProtos.Content { |
| 518 | val pointer = SignalServiceProtos.AttachmentPointer.newBuilder() |
| 519 | .setCdnKey(cdnKey).setCdnNumber(cdnNumber).setContentType(mime) |
| 520 | .setSize(10) |
| 521 | .setKey(ByteString.copyFrom(ByteArray(64) { 1 })) |
| 522 | .apply { if (fileName != null) setFileName(fileName) } |
| 523 | .build() |
| 524 | val dm = SignalServiceProtos.DataMessage.newBuilder().setBody("").setTimestamp(timestamp) |
| 525 | .addAttachments(pointer) |
| 526 | return SignalServiceProtos.Content.newBuilder().setDataMessage(dm).build() |
| 527 | } |
| 528 | |
| 529 | fun reaction(emoji: String, targetTs: Long, remove: Boolean = false): SignalServiceProtos.Content { |
| 530 | val r = SignalServiceProtos.DataMessage.Reaction.newBuilder().setEmoji(emoji).setRemove(remove) |
| 531 | .setTargetSentTimestamp(targetTs) |
| 532 | val dm = SignalServiceProtos.DataMessage.newBuilder().setTimestamp(1700000001000L).setReaction(r) |
| 533 | return SignalServiceProtos.Content.newBuilder().setDataMessage(dm).build() |
| 534 | } |
| 535 | |
| 536 | fun delete(targetTs: Long): SignalServiceProtos.Content { |
| 537 | val del = SignalServiceProtos.DataMessage.Delete.newBuilder().setTargetSentTimestamp(targetTs) |
| 538 | val dm = SignalServiceProtos.DataMessage.newBuilder().setTimestamp(1700000001000L).setDelete(del) |
| 539 | return SignalServiceProtos.Content.newBuilder().setDataMessage(dm).build() |
| 540 | } |
| 541 | |
| 542 | fun edit(targetTs: Long, newBody: String): SignalServiceProtos.Content { |
| 543 | val replacement = SignalServiceProtos.DataMessage.newBuilder().setBody(newBody).build() |
| 544 | val edit = SignalServiceProtos.EditMessage.newBuilder() |
| 545 | .setTargetSentTimestamp(targetTs).setDataMessage(replacement) |
| 546 | return SignalServiceProtos.Content.newBuilder().setEditMessage(edit).build() |
| 547 | } |
| 548 | } |