Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
dependencies ▾

Modern-Apps.git / communicate-dev / src / test / java / com / vayunmathur / communicate / signal / Y3SignalPipelineServerTest.kt

Y3SignalPipelineServerTest.kt749 lines · 43.3 KiBRaw
1package com.vayunmathur.communicate.signal
2
3// FIXTURE RELATIVE-TIME EXCEPTION: timestamps are seeded relative to the wall clock the code under test reads internally, so the fresh/expired/relative-time branch under test keeps its meaning; a fixed past instant would silently change that branch.
4
5import androidx.room3.Room
6import androidx.sqlite.driver.bundled.BundledSQLiteDriver
7import androidx.test.core.app.ApplicationProvider
8import com.google.protobuf.ByteString
9import com.sun.net.httpserver.HttpServer
10import com.vayunmathur.communicate.data.signal.SignalAuthData
11import com.vayunmathur.communicate.data.signal.SignalCachedMessage
12import com.vayunmathur.communicate.data.signal.SignalClient
13import com.vayunmathur.communicate.data.signal.SignalConversation
14import com.vayunmathur.communicate.data.signal.SignalDatabase
15import com.vayunmathur.communicate.data.signal.SignalEvent
16import com.vayunmathur.communicate.data.signal.SignalGroups
17import com.vayunmathur.communicate.data.signal.SignalProtocol
18import com.vayunmathur.communicate.data.signal.createGroup
19import com.vayunmathur.communicate.data.signal.e2e.SignalE2E
20import com.vayunmathur.communicate.data.signal.e2e.ensureLocalPreKeys
21import com.vayunmathur.communicate.data.signal.e2e.hasSignedPreKeyMatching
22import com.vayunmathur.communicate.data.signal.ensureLocalPreKeys as clientEnsureLocalPreKeys
23import com.vayunmathur.communicate.data.signal.establishSession
24import com.vayunmathur.communicate.data.signal.handleInboundFrame
25import com.vayunmathur.communicate.data.signal.putMessages
26import com.vayunmathur.communicate.data.signal.refreshGroup
27import com.vayunmathur.communicate.data.signal.registration.SignalRegistrationKeys
28import com.vayunmathur.communicate.data.signal.sendContent
29import com.vayunmathur.communicate.data.signal.sendMedia
30import com.vayunmathur.communicate.data.signal.sendMessage
31import com.vayunmathur.communicate.data.signal.setGroupName
32import com.vayunmathur.communicate.data.signal.transport.SignalAttachmentUpload
33import com.vayunmathur.communicate.data.signal.transport.SignalGroupsApi
34import com.vayunmathur.communicate.data.signal.transport.SignalKeysApi
35import com.vayunmathur.communicate.data.signal.transport.SignalPayload
36import com.vayunmathur.communicate.data.signal.transport.SignalSocket
37import com.vayunmathur.communicate.data.signal.updateGroupParticipants
38import java.io.InputStream
39import java.io.OutputStream
40import java.net.InetAddress
41import java.net.InetSocketAddress
42import java.net.ServerSocket
43import java.net.Socket
44import java.security.MessageDigest
45import java.util.Collections
46import java.util.UUID
47import java.util.concurrent.ConcurrentLinkedQueue
48import kotlin.io.encoding.Base64
49import kotlin.io.encoding.ExperimentalEncodingApi
50import kotlin.test.AfterTest
51import kotlin.test.BeforeTest
52import kotlin.test.Test
53import kotlin.test.assertEquals
54import kotlin.test.assertFalse
55import kotlin.test.assertNotNull
56import kotlin.test.assertNull
57import kotlin.test.assertTrue
58import kotlinx.coroutines.CoroutineScope
59import kotlinx.coroutines.Dispatchers
60import kotlinx.coroutines.Job
61import kotlinx.coroutines.SupervisorJob
62import kotlinx.coroutines.launch
63import kotlinx.coroutines.runBlocking
64import kotlinx.coroutines.test.runTest
65import org.junit.runner.RunWith
66import org.robolectric.RobolectricTestRunner
67import org.robolectric.annotation.Config
68import org.signal.libsignal.zkgroup.groups.ClientZkGroupCipher
69import org.signal.libsignal.zkgroup.groups.GroupSecretParams
70import org.signal.storageservice.storage.protos.groups.Group
71import org.signal.storageservice.storage.protos.groups.GroupResponse
72import org.signal.storageservice.storage.protos.groups.Member
73import org.whispersystems.signalservice.internal.push.SignalServiceProtos
74import signal.proto.chat_websocket.SignalChatWebsocket.WebSocketMessage
75import signal.proto.chat_websocket.SignalChatWebsocket.WebSocketRequestMessage
76import signal.proto.chat_websocket.SignalChatWebsocket.WebSocketResponseMessage
77
78/**
79 * Y3 pipeline: SignalGroupOps / SignalSendPipeline / SignalMessaging /
80 * SignalInbound driven against scripted localhost HTTP (lead *BaseForTest
81 * seams) and a raw RFC6455 WebSocket server, with a real two-party E2E store
82 * and in-memory SignalDatabase. Private helpers (groupChange,
83 * fetchGroupState, reconcileDevices, signedPreKeyMatchesServer,
84 * putMessagesOverSocket, sendEncryptedAttempt, buildAttachmentPointer,
85 * cacheOutgoingMedia, sendRetryReceipt, emitServerReceipt,
86 * captureSenderKeys) are exercised through their public/internal callers.
87 */
88@OptIn(ExperimentalEncodingApi::class)
89@RunWith(RobolectricTestRunner::class)
90@Config(sdk = [34])
91class Y3SignalPipelineServerTest {
92
93 private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()
94 private val selfAci = "123e4567-e89b-42d3-a456-426614174000"
95 private val bobAci = "7c1d9b4e-aaaa-bbbb-cccc-ddddeeeeffff"
96 private val carolAci = "123e4567-e89b-42d3-a456-426614174001"
97
98 private lateinit var db: SignalDatabase
99 private lateinit var dbBob: SignalDatabase
100 private lateinit var authA: SignalAuthData
101 private lateinit var authB: SignalAuthData
102 private lateinit var alice: SignalE2E
103 private lateinit var bob: SignalE2E
104 private val servers = mutableListOf<HttpScript>()
105 private val wsServers = mutableListOf<RawWs>()
106 private val sockets = mutableListOf<SignalSocket>()
107
108 @BeforeTest fun setUp() {
109 db = Room.inMemoryDatabaseBuilder(ctx, SignalDatabase::class.java)
110 .setDriver(BundledSQLiteDriver()).allowMainThreadQueries().build()
111 dbBob = Room.inMemoryDatabaseBuilder(ctx, SignalDatabase::class.java)
112 .setDriver(BundledSQLiteDriver()).allowMainThreadQueries().build()
113 authA = SignalRegistrationKeys.generate("+14155552671").authScaffold.copy(aci = selfAci, pni = "PNI:$carolAci")
114 authB = SignalRegistrationKeys.generate("+14155550000").authScaffold.copy(aci = bobAci)
115 alice = SignalE2E(db, authA); bob = SignalE2E(dbBob, authB)
116 SignalClient.db = db; SignalClient.authData = authA; SignalClient.e2e = alice
117 SignalClient.socket = null; SignalClient.unauthSocket = null; SignalClient.appContext = null
118 SignalClient.preKeysPrepared.set(false); SignalClient.discoveryRunning.set(false)
119 SignalClient.pendingIdentityChanges.clear()
120 resetSeams()
121 }
122 @AfterTest fun tearDown() {
123 sockets.forEach { runCatching { it.disconnect() } }; sockets.clear()
124 wsServers.forEach { it.close() }; wsServers.clear()
125 servers.forEach { it.close() }; servers.clear()
126 resetSeams()
127 SignalClient.db = null; SignalClient.authData = null; SignalClient.e2e = null
128 SignalClient.socket = null; SignalClient.unauthSocket = null
129 SignalClient.pendingIdentityChanges.clear()
130 db.close(); dbBob.close()
131 }
132 private fun resetSeams() {
133 SignalGroupsApi.storageBaseForTest = null; SignalGroupsApi.chatBaseForTest = null
134 SignalKeysApi.chatBaseForTest = null
135 SignalAttachmentUpload.chatBaseForTest = null
136 }
137
138 // ---------- scripted HTTP ----------
139 data class HReq(val method: String, val path: String, val query: String?, val headers: Map<String, String>, val body: ByteArray)
140 data class HResp(val status: Int, val body: ByteArray, val type: String = "application/json") {
141 constructor(status: Int, text: String) : this(status, text.encodeToByteArray())
142 }
143 class HttpScript(private val handler: (HReq) -> HResp) : AutoCloseable {
144 val requests = Collections.synchronizedList(mutableListOf<HReq>())
145 private val http = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0)
146 val base: String get() = "http://127.0.0.1:${http.address.port}"
147 init {
148 http.createContext("/") { ex ->
149 val req = HReq(ex.requestMethod, ex.requestURI.path, ex.requestURI.rawQuery,
150 ex.requestHeaders.mapValues { it.value.firstOrNull() ?: "" }, ex.requestBody.readBytes())
151 requests.add(req)
152 val resp = runCatching { handler(req) }.getOrElse { HResp(500, "handler: $it") }
153 ex.responseHeaders.add("Content-Type", resp.type)
154 ex.sendResponseHeaders(resp.status, resp.body.size.toLong())
155 ex.responseBody.use { it.write(resp.body) }
156 }; http.start()
157 }
158 override fun close() = http.stop(0)
159 }
160 private fun http(handler: (HReq) -> HResp) = HttpScript(handler).also { servers.add(it) }
161
162 // ---------- raw WebSocket ----------
163 class RawWs : AutoCloseable {
164 private val server = ServerSocket(0, 50, InetAddress.getByName("127.0.0.1"))
165 val port: Int = server.localPort
166 val requests = Collections.synchronizedList(mutableListOf<WebSocketRequestMessage>())
167 val rawFrames = Collections.synchronizedList(mutableListOf<ByteArray>())
168 @Volatile var responder: (WebSocketRequestMessage) -> Pair<Int, ByteArray> =
169 { 200 to "ok".encodeToByteArray() }
170 @Volatile private var running = true
171 private val thread = Thread {
172 while (running) {
173 try { val s = server.accept(); Thread { handle(s) }.start() } catch (_: Exception) { break }
174 }
175 }.apply { isDaemon = true; start() }
176
177 private fun handle(s: Socket) {
178 try {
179 val input = s.getInputStream(); val output = s.getOutputStream()
180 val header = readHandshake(input)
181 val key = Regex("Sec-WebSocket-Key:\\s*(\\S+)").find(header)?.groupValues?.get(1) ?: ""
182 val accept = java.util.Base64.getEncoder().encodeToString(
183 MessageDigest.getInstance("SHA-1").digest((key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").toByteArray(Charsets.US_ASCII)))
184 output.write(("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: $accept\r\nx-signal-timestamp: 1700000000\r\n\r\n").toByteArray(Charsets.US_ASCII)); output.flush()
185 var open = true
186 while (open) {
187 val frame = readFrame(input)
188 if (frame == null || frame.first == 0x8) {
189 open = false
190 } else {
191 rawFrames.add(frame.second)
192 val msg = runCatching { WebSocketMessage.parseFrom(frame.second) }.getOrNull()
193 if (msg != null && msg.type == WebSocketMessage.Type.REQUEST && msg.hasRequest()) {
194 val req = msg.request; requests.add(req)
195 val (status, body) = responder(req)
196 val resp = WebSocketMessage.newBuilder().setType(WebSocketMessage.Type.RESPONSE)
197 .setResponse(WebSocketResponseMessage.newBuilder().setId(req.id).setStatus(status)
198 .setMessage(if (status in 200..299) "OK" else "err")
199 .setBody(ByteString.copyFrom(body)).build()).build()
200 synchronized(output) { writeFrame(output, 0x2, resp.toByteArray()) }
201 }
202 }
203 }
204 } catch (_: Exception) { } finally { runCatching { s.close() } }
205 }
206 private fun readHandshake(input: InputStream): String {
207 val buf = StringBuilder()
208 var matched = 0
209 val end = "\r\n\r\n"
210 while (matched < 4) {
211 val b = input.read()
212 if (b == -1) break
213 buf.append(b.toChar())
214 matched = if (b.toChar() == end[matched]) matched + 1 else if (b.toChar() == '\r') 1 else 0
215 }
216 return buf.toString()
217 }
218 private fun readFrame(input: InputStream): Pair<Int, ByteArray>? {
219 val b1 = input.read(); if (b1 == -1) return null
220 val b2 = input.read(); if (b2 == -1) return null
221 val opcode = b1 and 0x0F; val masked = (b2 and 0x80) != 0
222 var len = (b2 and 0x7F).toLong()
223 if (len == 126L) len = ((input.read() shl 8) or input.read()).toLong()
224 else if (len == 127L) { var v = 0L; repeat(8) { v = (v shl 8) or input.read().toLong() }; len = v }
225 val mask = if (masked) ByteArray(4) { input.read().toByte() } else null
226 val payload = ByteArray(len.toInt()); var off = 0
227 while (off < payload.size) {
228 val n = input.read(payload, off, payload.size - off)
229 if (n == -1) return null
230 off += n
231 }
232 if (mask != null) for (i in payload.indices) payload[i] = (payload[i].toInt() xor mask[i % 4].toInt()).toByte()
233 return opcode to payload
234 }
235 private fun writeFrame(output: OutputStream, opcode: Int, payload: ByteArray) {
236 val out = java.io.ByteArrayOutputStream(); out.write(0x80 or opcode)
237 when { payload.size < 126 -> out.write(payload.size)
238 payload.size <= 0xFFFF -> { out.write(126); out.write(payload.size shr 8); out.write(payload.size) }
239 else -> { out.write(127); repeat(8) { out.write((payload.size.toLong() shr (56 - it * 8)).toInt()) } } }
240 out.write(payload); output.write(out.toByteArray()); output.flush()
241 }
242 fun messageRequests(): List<WebSocketRequestMessage> =
243 synchronized(requests) { requests.filter { it.path.contains("/v1/messages") } }
244 override fun close() { running = false; runCatching { server.close() } }
245 }
246 private fun ws() = RawWs().also { wsServers.add(it) }
247
248 private fun await(label: String, timeoutMs: Long = 12_000, cond: () -> Boolean) {
249 val deadline = System.currentTimeMillis() + timeoutMs
250 while (System.currentTimeMillis() < deadline) {
251 if (cond()) return
252 Thread.sleep(20)
253 }
254 error("timeout $label")
255 }
256 private fun connectWs(server: RawWs, authenticated: Boolean = true): SignalSocket {
257 val sock = SignalSocket(ctx, authA, host = "127.0.0.1", port = server.port, useTls = false, authenticated = authenticated)
258 sockets.add(sock)
259 val states = Collections.synchronizedList(mutableListOf<SignalSocket.ConnectionState>())
260 val scope = CoroutineScope(Dispatchers.Default + SupervisorJob())
261 val job = scope.launch { sock.connectionState.collect { states.add(it) } }
262 sock.connect()
263 await("ws connected") { states.any { it is SignalSocket.ConnectionState.Connected } }
264 job.cancel()
265 return sock
266 }
267
268 // ---------- key bundles over HTTP ----------
269 private fun b64u(bytes: ByteArray): String = Base64.Default.encode(bytes).trimEnd('=')
270 private fun bundleJson(deviceId: Int, identity: ByteArray, regId: Int,
271 signed: SignalE2E.PreKeyUpload.KeyEntity, kyber: SignalE2E.PreKeyUpload.KeyEntity,
272 one: SignalE2E.PreKeyUpload.KeyEntity?): String {
273 val oneJson = one?.let { ""","preKey":{"keyId":${it.id},"publicKey":"${b64u(it.publicKey)}"}""" } ?: ""
274 return """{"identityKey":"${b64u(identity)}","devices":[{"deviceId":$deviceId,"registrationId":$regId,""" +
275 """"signedPreKey":{"keyId":${signed.id},"publicKey":"${b64u(signed.publicKey)}","signature":"${b64u(signed.signature!!)}"},""" +
276 """"pqPreKey":{"keyId":${kyber.id},"publicKey":"${b64u(kyber.publicKey)}","signature":"${b64u(kyber.signature!!)}"}$oneJson}]}"""
277 }
278 private var bobSigned: SignalE2E.PreKeyUpload.KeyEntity? = null
279 private var bobKyber: SignalE2E.PreKeyUpload.KeyEntity? = null
280 private var bobOne: SignalE2E.PreKeyUpload.KeyEntity? = null
281 private fun bobBundleJson(deviceIds: List<Int> = listOf(1)): String {
282 val up = bob.ensureLocalPreKeys()
283 // First ensure rotates signed + generates kyber/one-time; later
284 // ensures report nothing new, so cache the first batch.
285 if (bobSigned == null) {
286 bobSigned = up.signedPreKey; bobKyber = up.lastResortKyber; bobOne = up.oneTimeEcPreKeys.firstOrNull()
287 }
288 val signed = bobSigned ?: error("bob signed")
289 val kyber = bobKyber ?: error("bob kyber")
290 val identity = android.util.Base64.decode(authB.effectiveAciPublic(), android.util.Base64.NO_WRAP)
291 // Rebuild a multi-device document from the single-device helper.
292 val per = deviceIds.map { id ->
293 val single = bundleJson(id, identity, authB.effectiveAciRegId(), signed, kyber, bobOne)
294 org.json.JSONObject(single).getJSONArray("devices").getJSONObject(0).toString()
295 }
296 return """{"identityKey":"${b64u(identity)}","devices":[${per.joinToString(",")}]}"""
297 }
298 // After the first ensure, signed rotates once and is then stored; recover it
299 // by rotating is wrong, so tests call bobBundleJson before any other ensure.
300 private fun bobRotatedSigned(): SignalE2E.PreKeyUpload.KeyEntity = error("signed already consumed")
301 private fun keysServerForBob(deviceIds: List<Int> = listOf(1)): HttpScript {
302 val json = bobBundleJson(deviceIds)
303 return http { req -> if (req.path.startsWith("/v2/keys/")) HResp(200, json) else HResp(404, "{}") }
304 }
305 private fun establishBob(): HttpScript {
306 val srv = keysServerForBob(); SignalKeysApi.chatBaseForTest = srv.base
307 return srv
308 }
309 private fun content(text: String, ts: Long): SignalServiceProtos.Content =
310 SignalServiceProtos.Content.newBuilder()
311 .setDataMessage(SignalServiceProtos.DataMessage.newBuilder().setBody(text).setTimestamp(ts)).build()
312
313 private fun collectEvents(block: suspend () -> Unit): List<SignalEvent> {
314 val seen = Collections.synchronizedList(mutableListOf<SignalEvent>())
315 val job = CoroutineScope(Dispatchers.Unconfined + SupervisorJob()).launch { SignalClient.events.collect { seen.add(it) } }
316 kotlinx.coroutines.runBlocking { block() }
317 Thread.sleep(150); job.cancel()
318 return seen
319 }
320
321 // ---------- reconcileDevices / signedPreKeyMatchesServer / putMessagesOverSocket ----------
322
323 @Test fun send_reconciles409MissingDeviceThenRetriesOverSocket() = runBlocking {
324 val keys = establishBobWithDevices()
325 val server = ws()
326 val statuses = ConcurrentLinkedQueue(listOf(409, 200))
327 server.responder = { req ->
328 if (req.path.contains("/v1/messages")) {
329 val s = statuses.poll() ?: 200
330 if (s == 409) s to """{"missingDevices":[2],"extraDevices":[]}""".encodeToByteArray() else s to ByteArray(0)
331 } else 200 to ByteArray(0)
332 }
333 SignalClient.socket = connectWs(server)
334 assertTrue(SignalClient.establishSession(alice, bobAci))
335 assertFalse(alice.hasSession(bobAci, 2))
336 assertTrue(SignalClient.sendContent(bobAci, content("reconcile me", 4242L)))
337 assertEquals(2, server.messageRequests().size)
338 assertTrue(alice.hasSession(bobAci, 2))
339 assertTrue(keys.requests.any { it.path == "/v2/keys/$bobAci/*" })
340 // Second attempt encrypts for both devices.
341 val second = org.json.JSONObject(server.messageRequests()[1].body.toByteArray().decodeToString())
342 assertEquals(2, second.getJSONArray("messages").length())
343 }
344 private fun establishBobWithDevices(): HttpScript {
345 // First fetch (establishSession) sees device 1 only; the reconcile
346 // fetch that follows a 409/410 sees devices 1+2.
347 val json1 = bobBundleJson(listOf(1))
348 val json12 = bobBundleJson(listOf(1, 2))
349 val gets = java.util.concurrent.atomic.AtomicInteger(0)
350 val srv = http { req ->
351 if (req.path.startsWith("/v2/keys/")) HResp(200, if (gets.incrementAndGet() == 1) json1 else json12)
352 else HResp(404, "{}")
353 }
354 SignalKeysApi.chatBaseForTest = srv.base; return srv
355 }
356
357 @Test fun send_reconciles410StaleDeviceThenRetries() = runBlocking {
358 establishBobWithDevices()
359 val server = ws()
360 val statuses = ConcurrentLinkedQueue(listOf(410, 200))
361 server.responder = { req ->
362 if (req.path.contains("/v1/messages")) {
363 val s = statuses.poll() ?: 200
364 if (s == 410) s to """{"staleDevices":[1]}""".encodeToByteArray() else s to ByteArray(0)
365 } else 200 to ByteArray(0)
366 }
367 SignalClient.socket = connectWs(server)
368 assertTrue(SignalClient.establishSession(alice, bobAci))
369 assertTrue(SignalClient.sendContent(bobAci, content("stale", 4343L)))
370 assertEquals(2, server.messageRequests().size)
371 assertTrue(alice.hasSession(bobAci, 1))
372 }
373
374 @Test fun send_reconcileWithNoFetchableDeviceGivesUpAfterOneAttempt() = runBlocking {
375 establishBob() // only device 1 on offer
376 val server = ws()
377 server.responder = { req ->
378 if (req.path.contains("/v1/messages")) 409 to """{"missingDevices":[9],"extraDevices":[]}""".encodeToByteArray()
379 else 200 to ByteArray(0)
380 }
381 SignalClient.socket = connectWs(server)
382 assertTrue(SignalClient.establishSession(alice, bobAci))
383 assertFalse(SignalClient.sendContent(bobAci, content("no device 9", 4444L)))
384 assertEquals(1, server.messageRequests().size)
385 }
386
387 @Test fun putMessagesOverSocket_statusMappingAndSealedFallback() = runBlocking {
388 val server = ws(); SignalClient.socket = connectWs(server)
389 val body = SignalPayload.buildPutMessagesBody(bobAci,
390 listOf(SignalPayload.OutgoingPushMessage(1, 1, 1234, byteArrayOf(1))), timestamp = 1L)
391 server.responder = { 200 to ByteArray(0) }
392 assertTrue(SignalClient.putMessages(bobAci, body, null) is SignalClient.SendOutcome.Success)
393 server.responder = { req -> if (req.path.contains("/v1/messages")) 409 to """{"missingDevices":[2]}""".encodeToByteArray() else 200 to ByteArray(0) }
394 val changed = SignalClient.putMessages(bobAci, body, null)
395 assertTrue(changed is SignalClient.SendOutcome.DeviceSetChanged); assertEquals(409, changed.status)
396 server.responder = { req -> if (req.path.contains("/v1/messages")) 500 to ByteArray(0) else 200 to ByteArray(0) }
397 assertEquals(SignalClient.SendOutcome.Failed(500), SignalClient.putMessages(bobAci, body, null))
398
399 // Sealed: unauth socket refuses 401, identified socket accepts.
400 val unauthServer = ws(); SignalClient.unauthSocket = connectWs(unauthServer, authenticated = false)
401 unauthServer.responder = { req -> if (req.path.contains("/v1/messages")) 401 to ByteArray(0) else 200 to ByteArray(0) }
402 server.responder = { 200 to ByteArray(0) }
403 assertTrue(SignalClient.putMessages(bobAci, body, ByteArray(16) { 3 }) is SignalClient.SendOutcome.Success)
404 assertEquals(1, unauthServer.messageRequests().size)
405 assertTrue(unauthServer.messageRequests()[0].headersList.any { it.startsWith("Unidentified-Access-Key:") },
406 "${unauthServer.messageRequests()[0].headersList}")
407 }
408
409 @Test fun ensureLocalPreKeys_freshUploadsEverythingToLocalhost() = runTest {
410 var putBody: String? = null
411 val srv = http { req ->
412 if (req.method == "PUT" && req.path == "/v2/keys") { putBody = req.body.decodeToString(); HResp(200, "{}") } else HResp(404, "{}")
413 }
414 SignalKeysApi.chatBaseForTest = srv.base
415 SignalClient.clientEnsureLocalPreKeys()
416 assertTrue(SignalClient.preKeysPrepared.get())
417 val json = org.json.JSONObject(assertNotNull(putBody))
418 assertTrue(json.has("signedPreKey")); assertTrue(json.has("pqLastResortPreKey"))
419 assertTrue(json.getJSONArray("preKeys").length() > 0)
420 // markPreKeysUploaded ran: stored one-time keys are flagged uploaded.
421 assertTrue(db.e2ePreKeyDao().getAll().all { it.uploaded })
422 }
423
424 @Test fun ensureLocalPreKeys_signedMatchSkipsUploadMismatchRotatesAndUploads() = runTest {
425 val first = alice.ensureLocalPreKeys()
426 val signed = first.signedPreKey ?: error("rotated signed")
427 val kyber = first.lastResortKyber ?: error("kyber")
428 fun ownJson(signedPublic: ByteArray): String = bundleJson(1, alice.ownIdentityPublicKey,
429 authA.effectiveAciRegId(),
430 SignalE2E.PreKeyUpload.KeyEntity(signed.id, signedPublic, signed.signature),
431 kyber, null)
432 var served = ownJson(signed.publicKey)
433 val alice2 = SignalE2E(db, authA.copy(signedPreKeyId = signed.id))
434 SignalClient.e2e = alice2
435 val srv = http { req ->
436 when {
437 req.method == "GET" && req.path.startsWith("/v2/keys/") -> HResp(200, served)
438 req.method == "PUT" && req.path == "/v2/keys" -> HResp(200, "{}")
439 else -> HResp(404, "{}")
440 }
441 }
442 SignalKeysApi.chatBaseForTest = srv.base
443 // Matching server copy: GET happens, no PUT, guard stays latched.
444 SignalClient.preKeysPrepared.set(false); SignalClient.clientEnsureLocalPreKeys()
445 assertTrue(srv.requests.any { it.method == "GET" })
446 srv.requests.filter { it.method == "PUT" }.forEach { putReq ->
447 assertNull(org.json.JSONObject(putReq.body.decodeToString()).optJSONObject("signedPreKey"))
448 }
449 assertTrue(alice2.hasSignedPreKeyMatching(signed.id, signed.publicKey))
450 // Mismatched server copy (Bob's signed public under Alice's id): rotate + PUT.
451 val bobUp = bob.ensureLocalPreKeys()
452 served = ownJson((bobUp.signedPreKey ?: signed).publicKey)
453 srv.requests.clear(); SignalClient.preKeysPrepared.set(false); SignalClient.clientEnsureLocalPreKeys()
454 val put = srv.requests.single { it.method == "PUT" }
455 val putJson = org.json.JSONObject(put.body.decodeToString())
456 assertEquals(signed.id + 1, putJson.getJSONObject("signedPreKey").getInt("keyId"))
457 assertTrue(alice2.hasSignedPreKeyMatching(signed.id + 1,
458 Base64.Default.decode(putJson.getJSONObject("signedPreKey").getString("publicKey")
459 .let { it + "=".repeat((4 - it.length % 4) % 4) })))
460 }
461
462 @Test fun sendEncryptedAttempt_successCachesMessageViaSendMessage() = runBlocking {
463 establishBob()
464 val server = ws(); server.responder = { 200 to ByteArray(0) }
465 SignalClient.socket = connectWs(server)
466 assertTrue(SignalClient.establishSession(alice, bobAci))
467 val id = SignalClient.sendMessage(bobAci, "delivered y3")
468 assertNotNull(id)
469 val rows = db.cachedMessageDao().getForConversation(bobAci)
470 assertEquals(1, rows.size); assertEquals("delivered y3", rows[0].body); assertTrue(rows[0].outgoing)
471 assertEquals(1, server.messageRequests().size)
472 }
473
474 // ---------- SignalGroupOps (server-accepted) ----------
475
476 private fun todayAligned(): Long { val now = System.currentTimeMillis() / 1000; return now - (now % 86_400) }
477 /** Mint a zkgroup auth credential locally with libsignal's server ops. */
478 private fun mintCredential(): ByteArray? = try {
479 val secret = org.signal.libsignal.zkgroup.ServerSecretParams.generate()
480 val ops = org.signal.libsignal.zkgroup.auth.ServerZkAuthOperations(secret)
481 val uuid = Regex("[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}")
482 val pni = authA.pni.takeIf { uuid.matches(it) } ?: carolAci
483 val aci = runCatching { org.signal.libsignal.protocol.ServiceId.Aci.parseFromString(selfAci) }
484 .getOrElse { org.signal.libsignal.protocol.ServiceId.Aci(java.util.UUID.fromString(selfAci)) }
485 val pniObj = runCatching { org.signal.libsignal.protocol.ServiceId.Pni.parseFromString(pni) }
486 .getOrElse { org.signal.libsignal.protocol.ServiceId.Pni(java.util.UUID.fromString(pni)) }
487 ops.issueAuthCredentialWithPniZkc(
488 java.security.SecureRandom(), aci, pniObj,
489 java.time.Instant.ofEpochSecond(todayAligned()),
490 ).serialize()
491 } catch (e: Throwable) {
492 System.err.println("mintCredential unavailable: $e")
493 null
494 }
495
496 private class GroupWorld(val convId: String, val masterKey: ByteArray, val secretParams: GroupSecretParams)
497
498 private fun groupWorld(name: String = "Before", revision: Int = 0): GroupWorld {
499 val (masterKey, _) = SignalGroups.generateMasterKeyAndSecretParams()
500 val convId = SignalProtocol.toConversationId("", masterKey)
501 kotlinx.coroutines.runBlocking {
502 db.conversationDao().upsert(SignalConversation(chatId = convId, isGroup = true, name = name,
503 participants = bobAci, groupMasterKey = masterKey, groupRevision = revision))
504 }
505 return GroupWorld(convId, masterKey, GroupSecretParams(SignalGroups.secretParamsFor(masterKey)))
506 }
507
508 /** Chat credential server + storage server wired into the group seams. */
509 private fun wireGroupServers(storage: (HReq) -> HResp): Pair<HttpScript, HttpScript> {
510 val credential = mintCredential()
511 assertNotNull(credential, "zkgroup server credential minting unavailable on this host")
512 val credB64 = Base64.Default.encode(credential)
513 val chat = http { req ->
514 if (req.path == "/v1/certificate/auth/group")
515 HResp(200, """{"credentials":[{"redemptionTime":${todayAligned()},"credential":"$credB64"}]}""")
516 else HResp(404, "{}")
517 }
518 val store = http(storage)
519 SignalGroupsApi.chatBaseForTest = chat.base; SignalGroupsApi.storageBaseForTest = store.base
520 return chat to store
521 }
522
523 // NOTE (unreachable accepted path): groupChange/refreshGroup first fetch
524 // credentials from chat, then SignalGroupsApi.authorizationFor verifies
525 // the credential against the *hardcoded production* zkgroup
526 // ServerPublicParams. A credential minted locally (random server secret)
527 // cannot verify against those params, and there is no seam for them, so
528 // the server-accepted PATCH/GET-storage step cannot be reached offline.
529 // What IS covered here, and was offline-only before: the credential fetch
530 // really goes to the scripted chat server, the op then fails closed, and
531 // local state is untouched. Accepted PATCH/GET at the transport level is
532 // covered in Y3SignalServerApiTest (patchGroup/fetchGroup/proof).
533 @Test fun groupOps_setGroupName_fetchesCredentialsThenFailsClosedAtZkVerification() = runTest {
534 val world = groupWorld()
535 val (chat, store) = wireGroupServers { req ->
536 if (req.method == "PATCH") HResp(200, byteArrayOf(), "application/x-protobuf") else HResp(404, "{}")
537 }
538 assertFalse(SignalClient.setGroupName(world.convId, "After"))
539 val row = db.conversationDao().getConversation(world.convId)!!
540 assertEquals("Before", row.name); assertEquals(0, row.groupRevision)
541 assertTrue(chat.requests.any { it.path == "/v1/certificate/auth/group" })
542 assertTrue(store.requests.none { it.method == "PATCH" }) // authorization precedes storage
543 }
544
545 @Test fun groupOps_setGroupName_noCredentialsKeepsRowAndSkipsStorage() = runTest {
546 val world = groupWorld()
547 val chat = http { HResp(200, """{"credentials":[]}""") }
548 val store = http { HResp(200, byteArrayOf(), "application/x-protobuf") }
549 SignalGroupsApi.chatBaseForTest = chat.base; SignalGroupsApi.storageBaseForTest = store.base
550 assertFalse(SignalClient.setGroupName(world.convId, "After"))
551 val row = db.conversationDao().getConversation(world.convId)!!
552 assertEquals("Before", row.name); assertEquals(0, row.groupRevision)
553 assertEquals(1, chat.requests.size); assertTrue(store.requests.isEmpty())
554 }
555
556 @Test fun groupOps_updateGroupParticipants_fetchesCredentialsThenFailsClosed() = runTest {
557 val world = groupWorld()
558 val (chat, store) = wireGroupServers { req ->
559 if (req.method == "PATCH") HResp(200, byteArrayOf(), "application/x-protobuf") else HResp(404, "{}")
560 }
561 val seen = mutableListOf<SignalEvent>()
562 val job = launch(Dispatchers.Unconfined) { SignalClient.events.collect { seen.add(it) } }
563 assertFalse(SignalClient.updateGroupParticipants(world.convId, listOf(carolAci), "add"))
564 job.cancel()
565 // No participant event is emitted for a change the server never accepted.
566 assertTrue(seen.none { it is SignalEvent.ParticipantAdded }, "$seen")
567 assertTrue(chat.requests.any { it.path == "/v1/certificate/auth/group" })
568 assertTrue(store.requests.none { it.method == "PATCH" })
569 }
570
571 @Test fun groupOps_refreshGroup_fetchesCredentialsThenFailsClosed() = runTest {
572 val world = groupWorld(name = "Old", revision = 0)
573 val (chat, store) = wireGroupServers { HResp(404, "{}") }
574 assertFalse(SignalClient.refreshGroup(world.convId))
575 val row = db.conversationDao().getConversation(world.convId)!!
576 assertEquals("Old", row.name); assertEquals(0, row.groupRevision)
577 assertEquals(bobAci, row.participants)
578 assertTrue(chat.requests.any { it.path == "/v1/certificate/auth/group" })
579 assertTrue(store.requests.none { it.method == "GET" }) // authorization precedes storage
580 }
581
582 @Test fun groupOps_createGroup_persistsWithServerReachableChat() = runTest {
583 // createGroup itself uses SignalGroups.putNewGroup (fixed chat host),
584 // so offline it still persists locally; assert the row/key contract.
585 val id = SignalClient.createGroup("Y3 Group", listOf(bobAci, carolAci))
586 assertNotNull(id)
587 val row = db.conversationDao().getConversation(id)!!
588 assertTrue(row.isGroup); assertEquals("Y3 Group", row.name)
589 assertEquals(32, row.groupMasterKey!!.size); assertEquals(0, row.groupRevision)
590 assertTrue(row.participants.contains(bobAci))
591 }
592
593 // ---------- SignalMessaging sendMedia ----------
594
595 @Test fun sendMedia_uploadsEncryptedBlobAndCachesPointerMessage() = runBlocking {
596 establishBob()
597 val wsServer = ws(); wsServer.responder = { 200 to ByteArray(0) }
598 SignalClient.socket = connectWs(wsServer)
599 assertTrue(SignalClient.establishSession(alice, bobAci))
600 val cdn = http { req -> if (req.method == "POST") HResp(201, byteArrayOf()) else HResp(404, byteArrayOf()) }
601 val chat = http { HResp(200, """{"cdn":3,"key":"media-key-1","signedUploadLocation":"${cdn.base}/upload/m","headers":{"x-amz-meta":"mm"}}""") }
602 SignalAttachmentUpload.chatBaseForTest = chat.base
603
604 val plain = "y3 media bytes \u0001\u0002".encodeToByteArray()
605 val id = SignalClient.sendMedia(bobAci, plain, "image/png", "pic.png")
606 assertNotNull(id)
607 // CDN received encrypted bytes (not plaintext), form was requested.
608 assertEquals(1, cdn.requests.size); assertFalse(cdn.requests[0].body.contentEquals(plain))
609 assertTrue(cdn.requests[0].body.size > plain.size)
610 assertTrue(chat.requests.any { it.path == "/v4/attachments/form/upload" })
611 // Cached outgoing media row from cacheOutgoingMedia.
612 val rows = db.cachedMessageDao().getForConversation(bobAci)
613 assertEquals(1, rows.size); assertEquals("[Media: image/png]", rows[0].body); assertTrue(rows[0].outgoing)
614 // The encrypted WS payload decrypts on Bob's side to a pointer for our form.
615 val putJson = org.json.JSONObject(wsServer.messageRequests().single().body.toByteArray().decodeToString())
616 val msg = putJson.getJSONArray("messages").getJSONObject(0)
617 val cipherBytes = Base64.Default.decode(msg.getString("content"))
618 val isPreKey = msg.getInt("type") == SignalServiceProtos.Envelope.Type.PREKEY_MESSAGE.number
619 val decrypted = bob.decryptDM(selfAci, 1, isPreKey, cipherBytes)
620 val contentProto = SignalServiceProtos.Content.parseFrom(SignalProtocol.stripMessagePadding(decrypted))
621 val pointer = contentProto.dataMessage.attachmentsList.single()
622 assertEquals("media-key-1", pointer.cdnKey); assertEquals(3, pointer.cdnNumber)
623 assertEquals("image/png", pointer.contentType); assertEquals(plain.size, pointer.size)
624 assertEquals("pic.png", pointer.fileName); assertTrue(pointer.key.size() > 0); assertTrue(pointer.digest.size() > 0)
625 }
626
627 @Test fun sendMedia_formRefusedFailsWithoutUploadOrCache() = runTest {
628 val chat = http { HResp(404, "{}") }; SignalAttachmentUpload.chatBaseForTest = chat.base
629 val seen = mutableListOf<SignalEvent>()
630 val job = launch(Dispatchers.Unconfined) { SignalClient.events.collect { seen.add(it) } }
631 assertNull(SignalClient.sendMedia(bobAci, byteArrayOf(1, 2, 3), "image/png"))
632 job.cancel()
633 assertTrue(seen.any { it is SignalEvent.SendFailed }, "$seen")
634 assertTrue(db.cachedMessageDao().getForConversation(bobAci).isEmpty())
635 }
636
637 // ---------- SignalInbound ----------
638
639 private fun wsFrame(envelope: SignalServiceProtos.Envelope, id: Long = 99L): ByteArray =
640 WebSocketMessage.newBuilder().setType(WebSocketMessage.Type.REQUEST)
641 .setRequest(WebSocketRequestMessage.newBuilder().setVerb("PUT").setPath("/api/v1/message")
642 .setId(id).setBody(ByteString.copyFrom(envelope.toByteArray())).build())
643 .build().toByteArray()
644
645 @Test fun inbound_serverDeliveryReceipt_emitsDeliveryReadReceipt() = runTest {
646 val seen = mutableListOf<SignalEvent>()
647 val job = launch(Dispatchers.Unconfined) { SignalClient.events.collect { seen.add(it) } }
648 val envelope = SignalServiceProtos.Envelope.newBuilder()
649 .setType(SignalServiceProtos.Envelope.Type.SERVER_DELIVERY_RECEIPT)
650 .setSourceServiceId(bobAci).setSourceDeviceId(1)
651 .setClientTimestamp(1_700_000_111_000L).setServerGuid("guid-y3")
652 .build()
653 SignalClient.handleInboundFrame(wsFrame(envelope))
654 job.cancel()
655 val receipt = seen.filterIsInstance<SignalEvent.ReadReceipt>().single()
656 assertTrue(receipt.isDelivery); assertEquals(bobAci, receipt.conversationId)
657 assertEquals("guid-y3", receipt.messageId); assertEquals(1_700_000_111_000L, receipt.timestamp)
658 }
659
660 @Test fun inbound_undecryptableEnvelope_emitsErrorAndSendsRetryReceipt() = runBlocking {
661 establishBob()
662 val server = ws(); server.responder = { 200 to ByteArray(0) }
663 SignalClient.socket = connectWs(server)
664 assertTrue(SignalClient.establishSession(alice, bobAci))
665 val seen = mutableListOf<SignalEvent>()
666 val job = launch(Dispatchers.Unconfined) { SignalClient.events.collect { seen.add(it) } }
667 // A real Bob->Alice whisper ciphertext with a flipped MAC byte: it
668 // parses as a SignalMessage (so a retry receipt can be built for it)
669 // but Alice's decrypt must reject it.
670 val aliceUp2 = alice.ensureLocalPreKeys()
671 val aSigned2 = aliceUp2.signedPreKey ?: error("alice signed")
672 bob.processPreKeyBundle(selfAci, 1, SignalE2E.ParsedPreKeyBundle(
673 registrationId = authA.effectiveAciRegId(),
674 preKeyId = aliceUp2.oneTimeEcPreKeys.firstOrNull()?.id,
675 preKeyPublic = aliceUp2.oneTimeEcPreKeys.firstOrNull()?.publicKey,
676 signedPreKeyId = aSigned2.id, signedPreKeyPublic = aSigned2.publicKey,
677 signedPreKeySignature = aSigned2.signature!!,
678 identityKey = android.util.Base64.decode(authA.effectiveAciPublic(), android.util.Base64.NO_WRAP),
679 kyberPreKeyId = (aliceUp2.lastResortKyber ?: error("alice kyber")).id,
680 kyberPreKeyPublic = aliceUp2.lastResortKyber!!.publicKey,
681 kyberPreKeySignature = aliceUp2.lastResortKyber!!.signature!!))
682 val genuine = bob.encryptDM(selfAci, 1, SignalProtocol.padMessageBody(content("tamper", 3L).toByteArray()))
683 val tampered = genuine.data.copyOf().also { it[it.lastIndex] = (it[it.lastIndex].toInt() xor 0xFF).toByte() }
684 val envelope = SignalServiceProtos.Envelope.newBuilder()
685 .setType(SignalServiceProtos.Envelope.Type.PREKEY_MESSAGE)
686 .setSourceServiceId(bobAci).setSourceDeviceId(1)
687 .setClientTimestamp(1_700_000_222_000L)
688 .setContent(ByteString.copyFrom(tampered))
689 .build()
690 SignalClient.handleInboundFrame(wsFrame(envelope))
691 job.cancel()
692 assertTrue(seen.any { it is SignalEvent.DecryptionError && it.senderAci == bobAci }, "$seen")
693 // sendRetryReceipt put a PLAINTEXT_CONTENT message to Bob over the socket.
694 val puts = server.messageRequests().filter { it.path.contains(bobAci) }
695 assertEquals(1, puts.size)
696 val putJson = org.json.JSONObject(puts[0].body.toByteArray().decodeToString())
697 val msg = putJson.getJSONArray("messages").getJSONObject(0)
698 assertEquals(SignalServiceProtos.Envelope.Type.PLAINTEXT_CONTENT.number, msg.getInt("type"))
699 assertEquals(1, msg.getInt("destinationDeviceId"))
700 assertTrue(Base64.Default.decode(msg.getString("content")).isNotEmpty())
701 }
702
703 @Test fun inbound_captureSenderKeys_storesProfileKeyAndSenderKey() = runBlocking {
704 // Establish Bob->Alice double-ratchet: Alice consumes Bob's bundle,
705 // Bob opens Alice's pre-key message, then Bob can send whisper.
706 assertTrue(run {
707 val srv = keysServerForBob(); SignalKeysApi.chatBaseForTest = srv.base
708 SignalClient.establishSession(alice, bobAci)
709 })
710 val aliceUp = alice.ensureLocalPreKeys()
711 val aSigned = aliceUp.signedPreKey ?: error("alice signed")
712 // Bob consumes Alice's bundle directly (his side of the session).
713 bob.processPreKeyBundle(selfAci, 1, SignalE2E.ParsedPreKeyBundle(
714 registrationId = authA.effectiveAciRegId(),
715 preKeyId = aliceUp.oneTimeEcPreKeys.firstOrNull()?.id,
716 preKeyPublic = aliceUp.oneTimeEcPreKeys.firstOrNull()?.publicKey,
717 signedPreKeyId = aSigned.id, signedPreKeyPublic = aSigned.publicKey,
718 signedPreKeySignature = aSigned.signature!!,
719 identityKey = android.util.Base64.decode(authA.effectiveAciPublic(), android.util.Base64.NO_WRAP),
720 kyberPreKeyId = (aliceUp.lastResortKyber ?: error("alice kyber")).id,
721 kyberPreKeyPublic = aliceUp.lastResortKyber!!.publicKey,
722 kyberPreKeySignature = aliceUp.lastResortKyber!!.signature!!))
723 val setup = alice.encryptDM(bobAci, 1, SignalProtocol.padMessageBody(content("setup", 1L).toByteArray()))
724 bob.decryptDM(selfAci, 1, isPreKey = true, ciphertext = setup.data)
725
726 val distId = UUID.randomUUID()
727 val skdm = bob.createSenderKeyDistribution(distId)
728 val profileKey = ByteArray(32) { (it + 40).toByte() }
729 val dm = SignalPayload.buildDataMessage(body = "keys attached", timestamp = 1_700_000_333_000L, profileKey = profileKey)
730 val contentProto = SignalPayload.buildContentWithDataMessage(dm, senderKeyDistributionMessage = skdm)
731 val enc = bob.encryptDM(selfAci, 1, SignalProtocol.padMessageBody(contentProto.toByteArray()))
732
733 val seen = mutableListOf<SignalEvent>()
734 val job = launch(Dispatchers.Unconfined) { SignalClient.events.collect { seen.add(it) } }
735 val envelope = SignalServiceProtos.Envelope.newBuilder()
736 .setType(SignalServiceProtos.Envelope.Type.DOUBLE_RATCHET)
737 .setSourceServiceId(bobAci).setSourceDeviceId(1)
738 .setClientTimestamp(1_700_000_333_000L)
739 .setContent(ByteString.copyFrom(enc.data))
740 .build()
741 SignalClient.handleInboundFrame(wsFrame(envelope))
742 job.cancel()
743 assertTrue(seen.any { it is SignalEvent.IncomingMessage && it.body == "keys attached" }, "$seen")
744 // captureSenderKeys: profile key row + sender-key record usable by Alice.
745 assertTrue(db.profileKeyDao().get(bobAci)!!.profileKey.contentEquals(profileKey))
746 val groupCipher = bob.encryptGroup(distId, "group secret".toByteArray())
747 assertEquals("group secret", alice.decryptGroup(bobAci, 1, groupCipher.data).decodeToString())
748 }
749}