Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / communicate-dev / src / test / java / com / vayunmathur / communicate / signal / SignalPayloadBuildersTest.kt
SignalPayloadBuildersTest.kt390 lines · 17.4 KiBRaw
| 1 | package com.vayunmathur.communicate.signal |
| 2 | |
| 3 | import com.google.protobuf.ByteString |
| 4 | import com.vayunmathur.communicate.data.signal.SignalAuthData |
| 5 | import com.vayunmathur.communicate.data.signal.transport.SignalPayload |
| 6 | import com.vayunmathur.communicate.data.signal.transport.applyDataOptionals |
| 7 | import com.vayunmathur.communicate.data.signal.transport.applyGroupV2 |
| 8 | import com.vayunmathur.communicate.data.signal.transport.buildWebSocketMessageForRequest |
| 9 | import com.vayunmathur.communicate.data.signal.transport.buildWebSocketMessageForResponse |
| 10 | import com.vayunmathur.communicate.data.signal.transport.buildWebSocketRequestMessage |
| 11 | import com.vayunmathur.communicate.data.signal.transport.buildWebSocketResponseMessage |
| 12 | import com.vayunmathur.communicate.data.signal.transport.encodeWebSocketRequest |
| 13 | import com.vayunmathur.communicate.data.signal.transport.encodeWebSocketResponse |
| 14 | import com.vayunmathur.communicate.data.signal.transport.nextRequestId |
| 15 | import kotlinx.serialization.json.Json |
| 16 | import kotlinx.serialization.json.jsonArray |
| 17 | import kotlinx.serialization.json.jsonObject |
| 18 | import kotlinx.serialization.json.jsonPrimitive |
| 19 | import org.whispersystems.signalservice.internal.push.SignalServiceProtos |
| 20 | import signal.proto.chat_websocket.SignalChatWebsocket.WebSocketMessage |
| 21 | import org.junit.runner.RunWith |
| 22 | import org.robolectric.RobolectricTestRunner |
| 23 | import kotlin.test.Test |
| 24 | import kotlin.test.assertEquals |
| 25 | import kotlin.test.assertFalse |
| 26 | import kotlin.test.assertNotNull |
| 27 | import kotlin.test.assertNull |
| 28 | import kotlin.test.assertTrue |
| 29 | |
| 30 | /** |
| 31 | * Wave 1 (w6 slice 2/6): [SignalPayload] builders — PUT bodies, Content/DataMessage variants, |
| 32 | * WebSocket framing, account attributes, shared contacts. Pure JVM, no network. |
| 33 | */ |
| 34 | @RunWith(RobolectricTestRunner::class) |
| 35 | class SignalPayloadBuildersTest { |
| 36 | |
| 37 | // ---- PUT body / request ---- |
| 38 | |
| 39 | @Test |
| 40 | fun putBody_defaultsOnlineFalseUrgentTrue() { |
| 41 | val body = SignalPayload.buildPutMessagesBody("aci", emptyList(), timestamp = 10L) |
| 42 | val root = Json.parseToJsonElement(body.toString(Charsets.UTF_8)).jsonObject |
| 43 | assertEquals("aci", root["destination"]?.jsonPrimitive?.content) |
| 44 | assertEquals("false", root["online"]?.jsonPrimitive?.content) |
| 45 | assertEquals("true", root["urgent"]?.jsonPrimitive?.content) |
| 46 | assertEquals(0, root["messages"]?.jsonArray?.size) |
| 47 | } |
| 48 | |
| 49 | @Test |
| 50 | fun putMessagesRequest_carriesVerbPathAndHeaders() { |
| 51 | val req = SignalPayload.buildPutMessagesRequest("aci-9", byteArrayOf(1), story = true, id = 5L) |
| 52 | assertEquals("PUT", req.verb) |
| 53 | assertEquals("/v1/messages/aci-9?story=true", req.path) |
| 54 | assertEquals(5L, req.id) |
| 55 | assertTrue(req.headersList.isNotEmpty()) |
| 56 | } |
| 57 | |
| 58 | @Test |
| 59 | fun keepaliveRequest_targetsKeepalivePath() { |
| 60 | val req = SignalPayload.buildKeepaliveRequest(id = 3L) |
| 61 | assertEquals("/v1/keepalive", req.path) |
| 62 | assertEquals(3L, req.id) |
| 63 | } |
| 64 | |
| 65 | // ---- DataMessage variants ---- |
| 66 | |
| 67 | @Test |
| 68 | fun dataMessage_derivesProtocolVersionFromContent() { |
| 69 | val plain = SignalPayload.buildDataMessage("hi", timestamp = 1L) |
| 70 | assertEquals(0, plain.requiredProtocolVersion) |
| 71 | |
| 72 | val reaction = SignalPayload.buildReaction("👍", false, targetSentTimestamp = 1L) |
| 73 | val withReaction = SignalPayload.buildDataMessage("x", timestamp = 1L, reaction = reaction) |
| 74 | assertEquals(4, withReaction.requiredProtocolVersion) |
| 75 | |
| 76 | val poll = SignalPayload.buildPollCreate("q?", listOf("a")) |
| 77 | val withPoll = SignalPayload.buildDataMessage("q?", timestamp = 1L, pollCreate = poll) |
| 78 | assertEquals(8, withPoll.requiredProtocolVersion) |
| 79 | |
| 80 | // Explicit override wins. |
| 81 | val forced = SignalPayload.buildDataMessage("x", timestamp = 1L, requiredProtocolVersion = 2) |
| 82 | assertEquals(2, forced.requiredProtocolVersion) |
| 83 | } |
| 84 | |
| 85 | @Test |
| 86 | fun dataMessage_appliesGroupV2AndOptionals() { |
| 87 | val masterKey = ByteArray(32) { 9 } |
| 88 | val dm = SignalPayload.buildDataMessage( |
| 89 | "body", timestamp = 2L, |
| 90 | groupV2MasterKey = masterKey, groupV2Revision = 4, groupV2Change = byteArrayOf(1), |
| 91 | bodyRanges = listOf(SignalPayload.buildBodyRange(0, 2)), |
| 92 | expireTimer = 60, |
| 93 | profileKey = ByteArray(32) { 3 }, |
| 94 | ) |
| 95 | assertTrue(dm.groupV2.masterKey.toByteArray().contentEquals(masterKey)) |
| 96 | assertEquals(4, dm.groupV2.revision) |
| 97 | assertEquals(1, dm.bodyRangesCount) |
| 98 | assertEquals(60, dm.expireTimer) |
| 99 | assertEquals(32, dm.profileKey.size()) |
| 100 | } |
| 101 | |
| 102 | @Test |
| 103 | fun sharedContact_refusesEmptyCard() { |
| 104 | assertNull(SignalPayload.buildSharedContact("", phoneNumbers = emptyList())) |
| 105 | // Blank numbers are skipped, but a non-empty phone list means "has numbers", |
| 106 | // so a blank-named card with a (blank) number entry still builds with no numbers. |
| 107 | val blankNumberCard = SignalPayload.buildSharedContact(" ", phoneNumbers = listOf("" to null))!! |
| 108 | assertEquals(0, blankNumberCard.numberCount) |
| 109 | } |
| 110 | |
| 111 | @Test |
| 112 | fun sharedContact_carriesNameNumbersEmailsAndOrg() { |
| 113 | val contact = SignalPayload.buildSharedContact( |
| 114 | "Ada", familyName = "Lovelace", |
| 115 | phoneNumbers = listOf("+15551234567" to null, "+15557654321" to "work", "" to null), |
| 116 | emails = listOf("[email protected]", ""), |
| 117 | organization = "Analytical Engines", |
| 118 | )!! |
| 119 | assertEquals("Ada", contact.name.givenName) |
| 120 | assertEquals("Lovelace", contact.name.familyName) |
| 121 | assertEquals(2, contact.numberCount) |
| 122 | assertEquals( |
| 123 | SignalServiceProtos.DataMessage.Contact.Phone.Type.MOBILE, |
| 124 | contact.getNumber(0).type, |
| 125 | ) |
| 126 | assertEquals( |
| 127 | SignalServiceProtos.DataMessage.Contact.Phone.Type.CUSTOM, |
| 128 | contact.getNumber(1).type, |
| 129 | ) |
| 130 | assertEquals("work", contact.getNumber(1).label) |
| 131 | assertEquals(1, contact.emailCount) |
| 132 | assertEquals( |
| 133 | SignalServiceProtos.DataMessage.Contact.Email.Type.HOME, |
| 134 | contact.getEmail(0).type, |
| 135 | ) |
| 136 | assertEquals("Analytical Engines", contact.organization) |
| 137 | } |
| 138 | |
| 139 | @Test |
| 140 | fun sharedContact_nameOnlyIsAccepted() { |
| 141 | // A name with no numbers still builds (only both-empty is refused). |
| 142 | assertNotNull(SignalPayload.buildSharedContact("Solo")) |
| 143 | } |
| 144 | |
| 145 | @Test |
| 146 | fun contentWithDataMessage_carriesSenderKeyAndPniSignature() { |
| 147 | val dm = SignalPayload.buildDataMessage("hi", timestamp = 1L) |
| 148 | val plain = SignalPayload.buildContentWithDataMessage(dm) |
| 149 | assertTrue(plain.hasDataMessage()) |
| 150 | |
| 151 | val skdm = byteArrayOf(5, 6) |
| 152 | val withSkdm = SignalPayload.buildContentWithDataMessage(dm, senderKeyDistributionMessage = skdm) |
| 153 | assertTrue(withSkdm.senderKeyDistributionMessage.toByteArray().contentEquals(skdm)) |
| 154 | |
| 155 | val pni = SignalServiceProtos.PniSignatureMessage.newBuilder() |
| 156 | .setPni(ByteString.copyFrom(ByteArray(16) { 1 })) |
| 157 | .setSignature(ByteString.copyFrom(byteArrayOf(2))).build() |
| 158 | val withPni = SignalPayload.buildContentWithDataMessage(dm, pniSignatureMessage = pni) |
| 159 | assertTrue(withPni.hasPniSignatureMessage()) |
| 160 | } |
| 161 | |
| 162 | @Test |
| 163 | fun receiptAndTypingAndEdit_builders() { |
| 164 | val receipt = SignalPayload.buildContentForReceipt( |
| 165 | SignalServiceProtos.ReceiptMessage.Type.VIEWED, listOf(7L), |
| 166 | ) |
| 167 | assertEquals(SignalServiceProtos.ReceiptMessage.Type.VIEWED, receipt.receiptMessage.type) |
| 168 | assertEquals(listOf(7L), receipt.receiptMessage.timestampList) |
| 169 | |
| 170 | val typing = SignalPayload.buildContentForTyping( |
| 171 | 8L, SignalServiceProtos.TypingMessage.Action.STARTED, groupId = byteArrayOf(1, 2), |
| 172 | ) |
| 173 | assertEquals(8L, typing.typingMessage.timestamp) |
| 174 | assertEquals(2, typing.typingMessage.groupId.size()) |
| 175 | |
| 176 | val dm = SignalPayload.buildDataMessage("new", timestamp = 3L) |
| 177 | val edit = SignalPayload.buildContentForEdit(99L, dm) |
| 178 | assertEquals(99L, edit.editMessage.targetSentTimestamp) |
| 179 | } |
| 180 | |
| 181 | @Test |
| 182 | fun reactionBuilder_withAciStringOrBinary() { |
| 183 | val byString = SignalPayload.buildReaction("❤", false, targetAuthorAci = "some-aci", targetSentTimestamp = 1L) |
| 184 | assertEquals("some-aci", byString.targetAuthorAci) |
| 185 | val byBinary = SignalPayload.buildReaction( |
| 186 | "❤", true, targetAuthorAciBinary = byteArrayOf(1), targetSentTimestamp = 2L, |
| 187 | ) |
| 188 | assertTrue(byBinary.remove) |
| 189 | assertEquals(1, byBinary.targetAuthorAciBinary.size()) |
| 190 | } |
| 191 | |
| 192 | @Test |
| 193 | fun deleteAndBodyRangeAndGroupContext() { |
| 194 | assertEquals(55L, SignalPayload.buildDelete(55L).targetSentTimestamp) |
| 195 | // mentionAci and style share a oneof: setting both keeps the last one set. |
| 196 | val mention = SignalPayload.buildBodyRange(1, 3, mentionAci = "aci") |
| 197 | assertEquals("aci", mention.mentionAci) |
| 198 | val styled = SignalPayload.buildBodyRange( |
| 199 | 1, 3, style = SignalServiceProtos.BodyRange.Style.BOLD, |
| 200 | ) |
| 201 | assertEquals(SignalServiceProtos.BodyRange.Style.BOLD, styled.style) |
| 202 | val binary = SignalPayload.buildBodyRange(1, 3, mentionAciBinary = byteArrayOf(4)) |
| 203 | assertTrue(binary.mentionAciBinary.toByteArray().contentEquals(byteArrayOf(4))) |
| 204 | |
| 205 | val ctx = SignalPayload.buildGroupContextV2(ByteArray(32) { 5 }, revision = 6) |
| 206 | assertEquals(6, ctx.revision) |
| 207 | val ctxChange = SignalPayload.buildGroupContextV2(ByteArray(32) { 5 }, 6, groupChange = byteArrayOf(9)) |
| 208 | assertTrue(ctxChange.hasGroupChange()) |
| 209 | } |
| 210 | |
| 211 | @Test |
| 212 | fun pollBuilders_carryQuestionOptionsAndVote() { |
| 213 | val create = SignalPayload.buildPollCreate("lunch?", listOf("a", "b"), allowMultiple = true) |
| 214 | assertEquals("lunch?", create.question) |
| 215 | assertEquals(listOf("a", "b"), create.optionsList) |
| 216 | assertTrue(create.allowMultiple) |
| 217 | |
| 218 | val vote = SignalPayload.buildPollVote( |
| 219 | targetAuthorAciBinary = byteArrayOf(1, 2), targetSentTimestamp = 10L, |
| 220 | optionIndexes = listOf(0), voteCount = 1, |
| 221 | ) |
| 222 | assertEquals(10L, vote.targetSentTimestamp) |
| 223 | assertEquals(listOf(0), vote.optionIndexesList) |
| 224 | assertEquals(1, vote.voteCount) |
| 225 | } |
| 226 | |
| 227 | @Test |
| 228 | fun accountAttributes_carryRegIdsAndCapabilities() { |
| 229 | val auth = SignalAuthData( |
| 230 | phoneNumber = "+15551234567", aci = "aci-x", registrationId = 11, |
| 231 | pniRegistrationId = 22, profileName = "Ada", |
| 232 | unidentifiedAccessKey = "QUJD", registrationLock = "lock-1", |
| 233 | ) |
| 234 | val parsed = org.json.JSONObject(SignalPayload.buildAccountAttributes(auth)) |
| 235 | assertEquals(11, parsed.getInt("registrationId")) |
| 236 | assertEquals(22, parsed.getInt("pniRegistrationId")) |
| 237 | assertEquals("Ada", parsed.getString("name")) |
| 238 | assertEquals("lock-1", parsed.getString("registrationLock")) |
| 239 | assertTrue(parsed.getJSONObject("capabilities").getBoolean("senderKey")) |
| 240 | assertTrue(parsed.isNull("signalingKey")) |
| 241 | |
| 242 | // Fallback paths: legacy single registrationId as PNI, auth-level lock. |
| 243 | // Note the builder omits pniRegistrationId when it equals the ACI id |
| 244 | // (single-identity auth); it only emits the field when they differ. |
| 245 | val legacy = SignalAuthData(phoneNumber = "+1", registrationId = 7, registrationLock = "rl") |
| 246 | val parsedLegacy = org.json.JSONObject(SignalPayload.buildAccountAttributes(legacy)) |
| 247 | assertEquals(7, parsedLegacy.getInt("registrationId")) |
| 248 | assertFalse(parsedLegacy.has("pniRegistrationId")) |
| 249 | assertEquals("rl", parsedLegacy.getString("registrationLock")) |
| 250 | |
| 251 | val splitIds = SignalAuthData( |
| 252 | phoneNumber = "+1", registrationId = 7, aciRegistrationId = 8, registrationLock = "rl", |
| 253 | ) |
| 254 | val parsedSplit = org.json.JSONObject(SignalPayload.buildAccountAttributes(splitIds)) |
| 255 | assertEquals(8, parsedSplit.getInt("registrationId")) |
| 256 | assertEquals(7, parsedSplit.getInt("pniRegistrationId")) |
| 257 | |
| 258 | val noLock = SignalAuthData(phoneNumber = "+1") |
| 259 | val parsedNoLock = org.json.JSONObject(SignalPayload.buildAccountAttributes(noLock, registrationLock = "x")) |
| 260 | assertEquals("x", parsedNoLock.getString("registrationLock")) |
| 261 | } |
| 262 | |
| 263 | @Test |
| 264 | fun userAgent_mentionsSignalAndroid() { |
| 265 | assertTrue(SignalPayload.userAgent().startsWith("Signal-Android")) |
| 266 | } |
| 267 | |
| 268 | // ---- WebSocket framing (SignalPayloadWs) ---- |
| 269 | |
| 270 | @Test |
| 271 | fun wsRequest_omitsEmptyBodyAndHeaders() { |
| 272 | val bare = SignalPayload.buildWebSocketRequestMessage("GET", "/v1/x", id = 1L) |
| 273 | assertFalse(bare.hasBody()) |
| 274 | assertEquals(0, bare.headersCount) |
| 275 | val withBody = SignalPayload.buildWebSocketRequestMessage( |
| 276 | "PUT", "/v1/y", body = byteArrayOf(1), id = 2L, headers = listOf("a:b"), |
| 277 | ) |
| 278 | assertTrue(withBody.hasBody()) |
| 279 | assertEquals(listOf("a:b"), withBody.headersList) |
| 280 | // Empty body array is treated as absent. |
| 281 | val emptyBody = SignalPayload.buildWebSocketRequestMessage("PUT", "/v1/y", body = ByteArray(0), id = 3L) |
| 282 | assertFalse(emptyBody.hasBody()) |
| 283 | } |
| 284 | |
| 285 | @Test |
| 286 | fun wsResponse_carriesBodyAndHeaders() { |
| 287 | val bare = SignalPayload.buildWebSocketResponseMessage(id = 1L) |
| 288 | assertEquals(200, bare.status) |
| 289 | assertEquals("OK", bare.message) |
| 290 | val full = SignalPayload.buildWebSocketResponseMessage( |
| 291 | id = 2L, status = 500, message = "err", body = byteArrayOf(9), headers = listOf("h:v"), |
| 292 | ) |
| 293 | assertEquals(500, full.status) |
| 294 | assertTrue(full.body.toByteArray().contentEquals(byteArrayOf(9))) |
| 295 | assertEquals(listOf("h:v"), full.headersList) |
| 296 | } |
| 297 | |
| 298 | @Test |
| 299 | fun wsMessageWrappers_setType() { |
| 300 | val req = SignalPayload.buildWebSocketRequestMessage("PUT", "/v1/k", id = 9L) |
| 301 | val wrapped = SignalPayload.buildWebSocketMessageForRequest(req) |
| 302 | assertEquals(WebSocketMessage.Type.REQUEST, wrapped.type) |
| 303 | val resp = SignalPayload.buildWebSocketResponseMessage(id = 9L) |
| 304 | val wrappedResp = SignalPayload.buildWebSocketMessageForResponse(resp) |
| 305 | assertEquals(WebSocketMessage.Type.RESPONSE, wrappedResp.type) |
| 306 | } |
| 307 | |
| 308 | @Test |
| 309 | fun wsEncode_roundTrips() { |
| 310 | val bytes = SignalPayload.encodeWebSocketRequest("PUT", "/v1/keepalive", id = 77L) |
| 311 | val decoded = WebSocketMessage.parseFrom(bytes) |
| 312 | assertEquals(77L, decoded.request.id) |
| 313 | val respBytes = SignalPayload.encodeWebSocketResponse(78L, status = 201, message = "Created") |
| 314 | val decodedResp = WebSocketMessage.parseFrom(respBytes) |
| 315 | assertEquals(201, decodedResp.response.status) |
| 316 | } |
| 317 | |
| 318 | @Test |
| 319 | fun nextRequestId_isPositive() { |
| 320 | assertTrue(SignalPayload.nextRequestId() > 0) |
| 321 | } |
| 322 | |
| 323 | // ---- applyGroupV2 / applyDataOptionals ---- |
| 324 | |
| 325 | @Test |
| 326 | fun applyGroupV2_setsOnlyPresentFields() { |
| 327 | val b = SignalServiceProtos.DataMessage.newBuilder().setBody("x") |
| 328 | SignalPayload.applyGroupV2(b, null, null, null) |
| 329 | assertFalse(b.build().hasGroupV2()) |
| 330 | |
| 331 | val b2 = SignalServiceProtos.DataMessage.newBuilder().setBody("x") |
| 332 | SignalPayload.applyGroupV2(b2, ByteArray(32) { 1 }, null, null) |
| 333 | assertTrue(b2.build().hasGroupV2()) |
| 334 | } |
| 335 | |
| 336 | @Test |
| 337 | fun applyDataOptionals_setsEveryField() { |
| 338 | val b = SignalServiceProtos.DataMessage.newBuilder().setBody("x") |
| 339 | SignalPayload.applyDataOptionals( |
| 340 | b, |
| 341 | bodyRanges = listOf(SignalPayload.buildBodyRange(0, 1)), |
| 342 | attachments = listOf( |
| 343 | SignalServiceProtos.AttachmentPointer.newBuilder().setCdnKey("k").build(), |
| 344 | ), |
| 345 | quote = SignalServiceProtos.DataMessage.Quote.newBuilder().setId(3L).build(), |
| 346 | reaction = SignalPayload.buildReaction("e", false, targetSentTimestamp = 1L), |
| 347 | delete = SignalPayload.buildDelete(2L), |
| 348 | pollCreate = SignalPayload.buildPollCreate("q", listOf("o")), |
| 349 | pollVote = SignalPayload.buildPollVote(targetSentTimestamp = 1L, optionIndexes = listOf(0)), |
| 350 | pollTerminate = SignalServiceProtos.DataMessage.PollTerminate.newBuilder() |
| 351 | .setTargetSentTimestamp(9L).build(), |
| 352 | expireTimer = 30, |
| 353 | profileKey = ByteArray(32) { 2 }, |
| 354 | contact = SignalPayload.buildSharedContact("N"), |
| 355 | ) |
| 356 | val dm = b.build() |
| 357 | assertEquals(1, dm.bodyRangesCount) |
| 358 | assertEquals(1, dm.attachmentsCount) |
| 359 | assertTrue(dm.hasQuote()) |
| 360 | assertTrue(dm.hasReaction()) |
| 361 | assertTrue(dm.hasDelete()) |
| 362 | assertTrue(dm.hasPollCreate()) |
| 363 | assertTrue(dm.hasPollVote()) |
| 364 | assertTrue(dm.hasPollTerminate()) |
| 365 | assertEquals(30, dm.expireTimer) |
| 366 | assertTrue(dm.hasProfileKey()) |
| 367 | assertEquals(1, dm.contactCount) |
| 368 | } |
| 369 | |
| 370 | // ---- deprecated JSON helpers ---- |
| 371 | |
| 372 | @Test |
| 373 | fun deprecatedBuilders_keepShape() { |
| 374 | val req = SignalPayload.buildWebSocketRequest("PUT", "/v1/x", body = byteArrayOf(1, 2), id = "z") |
| 375 | val reqJson = org.json.JSONObject(req) |
| 376 | assertEquals("REQUEST", reqJson.getString("type")) |
| 377 | assertEquals("PUT", reqJson.getString("verb")) |
| 378 | assertEquals("/v1/x", reqJson.getString("path")) |
| 379 | assertEquals("z", reqJson.getString("id")) |
| 380 | assertTrue(reqJson.has("body")) |
| 381 | val resp = SignalPayload.buildWebSocketResponse("z", 200, body = byteArrayOf(3)) |
| 382 | assertTrue(resp.contains("z")) |
| 383 | val legacy = SignalPayload.buildDataMessageLegacy("hi", timestamp = 5L, quoteId = 9L) |
| 384 | assertEquals("hi", legacy.getString("body")) |
| 385 | assertEquals(5L, legacy.getLong("timestamp")) |
| 386 | assertEquals(9L, legacy.getLong("quoteId")) |
| 387 | val withGroup = SignalPayload.buildDataMessageLegacy("hi", groupId = byteArrayOf(1)) |
| 388 | assertTrue(withGroup.has("groupId")) |
| 389 | } |
| 390 | } |