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

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

Y2SignalSocketRegTest.kt823 lines · 42.2 KiBRaw
1package com.vayunmathur.communicate.signal
2
3import androidx.test.core.app.ApplicationProvider
4import com.google.protobuf.ByteString
5import com.sun.net.httpserver.HttpServer
6import com.vayunmathur.communicate.data.signal.SignalAuthData
7import com.vayunmathur.communicate.data.signal.SignalGroups
8import com.vayunmathur.communicate.data.signal.registration.RegistrationHttpClient
9import com.vayunmathur.communicate.data.signal.registration.SignalRegistrationKeys
10import com.vayunmathur.communicate.data.signal.transport.SignalAttachmentUpload
11import com.vayunmathur.communicate.data.signal.transport.SignalCdsi
12import com.vayunmathur.communicate.data.signal.transport.SignalGroupsApi
13import com.vayunmathur.communicate.data.signal.transport.SignalKeysApi
14import com.vayunmathur.communicate.data.signal.transport.SignalSocket
15import java.io.InputStream
16import java.io.OutputStream
17import java.net.InetAddress
18import java.net.InetSocketAddress
19import java.net.ServerSocket
20import java.net.Socket
21import java.security.MessageDigest
22import java.util.Collections
23import java.util.concurrent.CompletableFuture
24import java.util.concurrent.ConcurrentHashMap
25import kotlin.test.Test
26import kotlin.test.assertEquals
27import kotlin.test.assertFalse
28import kotlin.test.assertNotNull
29import kotlin.test.assertNull
30import kotlin.test.assertTrue
31import kotlinx.coroutines.CompletableDeferred
32import kotlinx.coroutines.CoroutineScope
33import kotlinx.coroutines.Dispatchers
34import kotlinx.coroutines.SupervisorJob
35import kotlinx.coroutines.async
36import kotlinx.coroutines.runBlocking
37import org.junit.runner.RunWith
38import org.robolectric.RobolectricTestRunner
39import org.signal.libsignal.zkgroup.groups.GroupSecretParams
40import signal.proto.chat_websocket.SignalChatWebsocket.WebSocketMessage
41import signal.proto.chat_websocket.SignalChatWebsocket.WebSocketRequestMessage
42import signal.proto.chat_websocket.SignalChatWebsocket.WebSocketResponseMessage
43
44/**
45 * Y2 wave-1: SignalSocket against a raw RFC6455 server on 127.0.0.1
46 * (HTTP upgrade + Sec-WebSocket-Accept, masked client frames, unmasked
47 * binary WebSocketMessage replies), private plumbing via reflection, and
48 * RegistrationHttpClient branches not covered by the pass-3 suite, plus
49 * parse/decrypt edges for Groups/Keys/CDSI/Attachment APIs whose network
50 * entry points are hardcoded to https://chat.signal.org / storage hosts
51 * (no baseUrl seam, so their live fetch paths are unreachable offline).
52 */
53@RunWith(RobolectricTestRunner::class)
54class Y2SignalSocketRegTest {
55
56 private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()
57 private val aci = "3f0e5a2c-1111-2222-3333-444455556666"
58 private val pni = "4f0e5a2c-1111-2222-3333-444455556666"
59
60 private fun auth(aciValue: String = aci, password: String = "pw-secret", authenticatedAci: Boolean = true) =
61 SignalAuthData(
62 phoneNumber = "+14155552671",
63 aci = if (authenticatedAci) aciValue else "",
64 pni = pni, deviceId = 3, password = password, registered = true,
65 )
66
67 // ---------------- raw WebSocket server ----------------
68
69 private class RawWsServer(
70 private val closeCode: Int? = null,
71 ) : AutoCloseable {
72 private val server = ServerSocket(0, 50, InetAddress.getByName("127.0.0.1"))
73 val port: Int = server.localPort
74 val handshakes = Collections.synchronizedList(mutableListOf<String>())
75 val frames = Collections.synchronizedList(mutableListOf<Pair<Int, ByteArray>>())
76 @Volatile var acceptCount = 0
77 @Volatile private var clientOut: OutputStream? = null
78 @Volatile private var running = true
79 private val thread = Thread {
80 while (running) {
81 try {
82 val s = server.accept()
83 acceptCount++
84 Thread { handle(s) }.start()
85 } catch (_: Exception) { break }
86 }
87 }.apply { isDaemon = true; start() }
88
89 private fun handle(s: Socket) {
90 try {
91 val input = s.getInputStream()
92 val output = s.getOutputStream()
93 clientOut = output
94 sendUpgrade(input, output)
95 if (closeAfterHandshake(output, s)) return
96 serveFrames(input, output)
97 } catch (_: Exception) {
98 } finally {
99 runCatching { s.close() }
100 }
101 }
102
103 private fun sendUpgrade(input: InputStream, output: OutputStream) {
104 val header = readHandshake(input)
105 handshakes.add(header)
106 val key = Regex("Sec-WebSocket-Key:\\s*(\\S+)").find(header)?.groupValues?.get(1) ?: ""
107 val accept = java.util.Base64.getEncoder().encodeToString(
108 MessageDigest.getInstance("SHA-1")
109 .digest((key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").toByteArray(Charsets.US_ASCII)))
110 output.write(
111 ("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" +
112 "Sec-WebSocket-Accept: $accept\r\nx-signal-timestamp: 1700000000\r\n\r\n")
113 .toByteArray(Charsets.US_ASCII))
114 output.flush()
115 }
116
117 private fun closeAfterHandshake(output: OutputStream, s: Socket): Boolean {
118 val code = closeCode ?: return false
119 Thread.sleep(120)
120 writeFrame(output, 0x8, byteArrayOf((code shr 8).toByte(), code.toByte()))
121 Thread.sleep(120)
122 s.close()
123 return true
124 }
125
126 private fun serveFrames(input: InputStream, output: OutputStream) {
127 var open = true
128 while (open) {
129 val frame = readFrame(input)
130 if (frame == null || frame.first == 0x8) {
131 open = false
132 } else {
133 frames.add(frame)
134 maybeReply(output, frame)
135 }
136 }
137 }
138
139 private fun maybeReply(output: OutputStream, frame: Pair<Int, ByteArray>) {
140 if (frame.first != 0x2 && frame.first != 0x1) return
141 val msg = runCatching { WebSocketMessage.parseFrom(frame.second) }.getOrNull() ?: return
142 if (msg.type != WebSocketMessage.Type.REQUEST || !msg.hasRequest()) return
143 val req = msg.request
144 if (req.path.contains("noreply")) return
145 val resp = WebSocketMessage.newBuilder()
146 .setType(WebSocketMessage.Type.RESPONSE)
147 .setResponse(
148 WebSocketResponseMessage.newBuilder()
149 .setId(req.id).setStatus(200).setMessage("OK")
150 .setBody(ByteString.copyFrom("resp:".toByteArray() + req.body.toByteArray()))
151 .build())
152 .build()
153 synchronized(output) { writeFrame(output, 0x2, resp.toByteArray()) }
154 }
155
156 private fun readHandshake(input: InputStream): String {
157 val buf = StringBuilder()
158 var matched = 0
159 val end = "\r\n\r\n"
160 while (matched < 4) {
161 val b = input.read()
162 if (b == -1) break
163 buf.append(b.toChar())
164 matched = if (b.toChar() == end[matched]) matched + 1 else if (b.toChar() == '\r') 1 else 0
165 }
166 return buf.toString()
167 }
168
169 private fun readFrame(input: InputStream): Pair<Int, ByteArray>? {
170 val b1 = input.read(); if (b1 == -1) return null
171 val b2 = input.read(); if (b2 == -1) return null
172 val opcode = b1 and 0x0F
173 val masked = (b2 and 0x80) != 0
174 var len = (b2 and 0x7F).toLong()
175 if (len == 126L) {
176 len = ((input.read() shl 8) or input.read()).toLong()
177 } else if (len == 127L) {
178 var v = 0L; repeat(8) { v = (v shl 8) or input.read().toLong() }; len = v
179 }
180 val mask = if (masked) ByteArray(4) { input.read().toByte() } else null
181 val payload = ByteArray(len.toInt())
182 var off = 0
183 while (off < payload.size) {
184 val n = input.read(payload, off, payload.size - off)
185 if (n == -1) return null
186 off += n
187 }
188 if (mask != null) for (i in payload.indices) {
189 payload[i] = (payload[i].toInt() xor mask[i % 4].toInt()).toByte()
190 }
191 return opcode to payload
192 }
193
194 fun writeFrame(output: OutputStream, opcode: Int, payload: ByteArray) {
195 val out = java.io.ByteArrayOutputStream()
196 out.write(0x80 or opcode)
197 when {
198 payload.size < 126 -> out.write(payload.size)
199 payload.size <= 0xFFFF -> { out.write(126); out.write(payload.size shr 8); out.write(payload.size) }
200 else -> { out.write(127); repeat(8) { out.write((payload.size.toLong() shr (56 - it * 8)).toInt()) } }
201 }
202 out.write(payload)
203 output.write(out.toByteArray()); output.flush()
204 }
205
206 fun pushToClient(bytes: ByteArray) {
207 val out = clientOut ?: error("no client yet")
208 synchronized(out) { writeFrame(out, 0x2, bytes) }
209 }
210
211 fun requestFrames(): List<WebSocketRequestMessage> = synchronized(frames) {
212 frames.mapNotNull { (_, payload) ->
213 runCatching { WebSocketMessage.parseFrom(payload) }.getOrNull()
214 ?.takeIf { it.type == WebSocketMessage.Type.REQUEST && it.hasRequest() }?.request
215 }
216 }
217
218 override fun close() {
219 running = false
220 runCatching { server.close() }
221 }
222 }
223
224 private fun await(label: String, timeoutMs: Long = 12_000, cond: () -> Boolean) {
225 // Step-counted from the caller's budget, not wall-clock:
226 // Robolectric's substituted clock can run ahead of real time, so
227 // a currentTimeMillis deadline expired under CI load while the
228 // socket work it waited for (real threads) was still landing.
229 // Each step sleeps real time, so the budget is a real duration.
230 var steps = (timeoutMs / 20).toInt()
231 while (steps-- > 0) {
232 if (cond()) return
233 Thread.sleep(20)
234 }
235 if (cond()) return
236 error("timeout $label")
237 }
238
239 /**
240 * Snapshot of a synchronized list for safe iteration: iterating a
241 * `Collections.synchronizedList` without holding its monitor races the
242 * socket/server threads appending to it (ConcurrentModificationException).
243 */
244 private fun <T> List<T>.snapshot(): List<T> = synchronized(this) { toList() }
245
246 private fun socketFor(port: Int, authenticated: Boolean = true, aciValue: String = aci, password: String = "pw-secret", passwordOverride: String? = null) =
247 SignalSocket(
248 context = ctx, authData = auth(aciValue, password, authenticated),
249 host = "127.0.0.1", port = port, useTls = false,
250 passwordOverride = passwordOverride, authenticated = authenticated,
251 )
252
253 @Test
254 fun `raw websocket handshake keepalive and raw sends`() = runBlocking {
255 RawWsServer().use { server ->
256 val socket = socketFor(server.port)
257 val states = Collections.synchronizedList(mutableListOf<SignalSocket.ConnectionState>())
258 val scope = CoroutineScope(Dispatchers.Default + SupervisorJob())
259 val stateJob = scope.async { socket.connectionState.collect { states.add(it) } }
260 socket.connect()
261 await("connected") { states.snapshot().any { it is SignalSocket.ConnectionState.Connected } }
262
263 // Handshake carried Basic aci.deviceId auth.
264 await("handshake") { server.handshakes.snapshot().isNotEmpty() }
265 val hs = server.handshakes.snapshot().first()
266 assertTrue(hs.contains("GET /v1/websocket/"), hs)
267 val authLine = hs.lines().first { it.startsWith("Authorization:") }
268 val decoded = String(
269 java.util.Base64.getDecoder().decode(authLine.substringAfter("Basic ").trim()),
270 Charsets.UTF_8)
271 assertEquals("$aci.3:pw-secret", decoded)
272 assertTrue(hs.contains("X-Signal-Receive-Stories: true"), hs)
273
274 // The immediate keepalive has the real Signal shape.
275 await("keepalive") { server.requestFrames().any { it.path == "/v1/keepalive" } }
276 val keepalive = server.requestFrames().first { it.path == "/v1/keepalive" }
277 assertEquals("PUT", keepalive.verb); assertTrue(keepalive.id != 0L)
278
279 // Raw binary + text sends arrive as frames.
280 assertTrue(socket.send(byteArrayOf(9, 8, 7)))
281 assertTrue(socket.sendText("plain-text"))
282 await("raw frames") {
283 server.frames.snapshot().any { it.second.contentEquals(byteArrayOf(9, 8, 7)) } &&
284 server.frames.snapshot().any { it.second.decodeToString() == "plain-text" }
285 }
286 socket.disconnect()
287 stateJob.cancel()
288 }
289 }
290
291 @Test
292 fun `raw websocket request response push and disconnect`() = runBlocking {
293 RawWsServer().use { server ->
294 val socket = socketFor(server.port)
295 val states = Collections.synchronizedList(mutableListOf<SignalSocket.ConnectionState>())
296 val inbox = Collections.synchronizedList(mutableListOf<ByteArray>())
297 val scope = CoroutineScope(Dispatchers.Default + SupervisorJob())
298 val stateJob = scope.async { socket.connectionState.collect { states.add(it) } }
299 val msgJob = scope.async { socket.messages.collect { inbox.add(it) } }
300 socket.connect()
301 await("connected") { states.snapshot().any { it is SignalSocket.ConnectionState.Connected } }
302
303 // Request/response correlation: generated id and explicit id.
304 val req = WebSocketRequestMessage.newBuilder()
305 .setVerb("GET").setPath("/v1/test").setBody(ByteString.copyFrom("hello".toByteArray())).build()
306 val result = socket.sendRequestAwaitingResponse(req, timeoutMs = 8_000)
307 assertNotNull(result); assertTrue(result.isSuccess); assertEquals(200, result.status)
308 assertEquals("resp:hello", result.body.decodeToString())
309 val req2 = WebSocketRequestMessage.newBuilder()
310 .setVerb("POST").setPath("/v1/test2").setId(4242L).build()
311 assertEquals(200, socket.sendRequestAwaitingResponse(req2, timeoutMs = 8_000)?.status)
312 assertTrue(server.requestFrames().any { it.id == 4242L })
313
314 // sendResponse is framed as a RESPONSE message.
315 assertTrue(socket.sendResponse(
316 WebSocketResponseMessage.newBuilder().setId(77L).setStatus(204).build()))
317 await("response frame") {
318 synchronized(server.frames) {
319 server.frames.any { (_, p) ->
320 runCatching { WebSocketMessage.parseFrom(p) }.getOrNull()
321 ?.let { it.type == WebSocketMessage.Type.RESPONSE && it.response.id == 77L } == true
322 }
323 }
324 }
325
326 // A server-pushed request lands on the messages flow verbatim.
327 val push = WebSocketMessage.newBuilder()
328 .setType(WebSocketMessage.Type.REQUEST)
329 .setRequest(WebSocketRequestMessage.newBuilder()
330 .setId(999L).setVerb("GET").setPath("/v1/messages").build())
331 .build().toByteArray()
332 server.pushToClient(push)
333 await("push") { inbox.snapshot().any { it.contentEquals(push) } }
334
335 socket.disconnect()
336 await("disconnected state") {
337 states.snapshot().any { it is SignalSocket.ConnectionState.Disconnected && it.reason == "client disconnect" }
338 }
339 assertFalse(socket.send(byteArrayOf(1)))
340 stateJob.cancel(); msgJob.cancel()
341 }
342 }
343
344 @Test
345 fun `request timeout returns null without leaking the pending entry`() = runBlocking {
346 RawWsServer().use { server ->
347 val socket = socketFor(server.port)
348 val states = Collections.synchronizedList(mutableListOf<SignalSocket.ConnectionState>())
349 val scope = CoroutineScope(Dispatchers.Default + SupervisorJob())
350 val job = scope.async { socket.connectionState.collect { states.add(it) } }
351 socket.connect()
352 await("connected") { states.snapshot().any { it is SignalSocket.ConnectionState.Connected } }
353 val start = System.currentTimeMillis()
354 val result = socket.sendRequestAwaitingResponse(
355 WebSocketRequestMessage.newBuilder().setVerb("GET").setPath("/noreply").build(),
356 timeoutMs = 400L)
357 val elapsed = System.currentTimeMillis() - start
358 assertNull(result)
359 assertTrue(elapsed < 6_000, "elapsed ${elapsed}ms")
360 val pending = getField<Map<*, *>>(socket, "pending")
361 assertTrue(pending.isEmpty(), "pending leaked: $pending")
362 socket.disconnect(); job.cancel()
363 }
364 }
365
366 @Test
367 fun `close 4401 surfaces invalid auth and stops the reconnect loop`() {
368 RawWsServer(closeCode = 4401).use { server ->
369 val socket = socketFor(server.port)
370 val states = Collections.synchronizedList(mutableListOf<SignalSocket.ConnectionState>())
371 val scope = CoroutineScope(Dispatchers.Default + SupervisorJob())
372 val job = scope.async { socket.connectionState.collect { states.add(it) } }
373 socket.connect()
374 await("4401 disconnected") {
375 states.snapshot().any { it is SignalSocket.ConnectionState.Disconnected && it.reason.contains("4401") }
376 }
377 val accepts = server.acceptCount
378 Thread.sleep(1_500)
379 assertEquals(accepts, server.acceptCount, "4401 must not reconnect")
380 socket.disconnect(); job.cancel()
381 }
382 }
383
384 @Test
385 fun `unauthenticated socket sends no credentials on the wire`() {
386 RawWsServer().use { server ->
387 val socket = socketFor(server.port, authenticated = false)
388 val states = Collections.synchronizedList(mutableListOf<SignalSocket.ConnectionState>())
389 val scope = CoroutineScope(Dispatchers.Default + SupervisorJob())
390 val job = scope.async { socket.connectionState.collect { states.add(it) } }
391 socket.connect()
392 await("connected") { states.snapshot().any { it is SignalSocket.ConnectionState.Connected } }
393 await("handshake") { server.handshakes.snapshot().isNotEmpty() }
394 assertFalse(server.handshakes.snapshot().first().contains("Authorization:"), server.handshakes.snapshot().first())
395 socket.disconnect(); job.cancel()
396 }
397 }
398
399 // ---------------- reflection plumbing ----------------
400
401 @Suppress("UNCHECKED_CAST")
402 private fun <T> getField(target: Any, name: String): T {
403 val f = target.javaClass.getDeclaredField(name).apply { isAccessible = true }
404 return f.get(target) as T
405 }
406
407 private fun invoke(target: Any, name: String, vararg args: Pair<Class<*>, Any?>): Any? {
408 val m = target.javaClass.getDeclaredMethod(name, *args.map { it.first }.toTypedArray())
409 .apply { isAccessible = true }
410 return m.invoke(target, *args.map { it.second }.toTypedArray())
411 }
412
413 @Test
414 fun `wsUrl authHeaders and close error mapping via reflection`() {
415 val insecure = SignalSocket(ctx, auth(), host = "example.test", port = 8080, useTls = false)
416 assertEquals("ws://example.test:8080/v1/websocket/", invoke(insecure, "wsUrl"))
417 val secure = SignalSocket(ctx, auth(), host = "example.test", port = 443, useTls = true)
418 assertEquals("wss://example.test:443/v1/websocket/", invoke(secure, "wsUrl"))
419
420 val headers = invoke(insecure, "authHeaders") as Map<*, *>
421 val basic = headers["Authorization"] as String
422 val decoded = String(
423 android.util.Base64.decode(basic.removePrefix("Basic "), android.util.Base64.NO_WRAP),
424 Charsets.UTF_8)
425 assertEquals("$aci.3:pw-secret", decoded)
426 assertEquals("true", headers["X-Signal-Receive-Stories"])
427
428 // Phone-number login when ACI is empty, override password wins, unauth has no credentials.
429 val phone = SignalSocket(ctx, auth(authenticatedAci = false), host = "h", port = 1, useTls = false)
430 val phoneHeaders = invoke(phone, "authHeaders") as Map<*, *>
431 val phoneDecoded = String(
432 android.util.Base64.decode(
433 (phoneHeaders["Authorization"] as String).removePrefix("Basic "),
434 android.util.Base64.NO_WRAP), Charsets.UTF_8)
435 assertEquals("+14155552671:pw-secret", phoneDecoded)
436 val override = SignalSocket(
437 ctx, auth(), host = "h", port = 1, useTls = false, passwordOverride = "override-pw")
438 val overrideHeaders = invoke(override, "authHeaders") as Map<*, *>
439 val overrideDecoded = String(
440 android.util.Base64.decode(
441 (overrideHeaders["Authorization"] as String).removePrefix("Basic "),
442 android.util.Base64.NO_WRAP), Charsets.UTF_8)
443 assertEquals("$aci.3:override-pw", overrideDecoded)
444 val unauth = SignalSocket(ctx, auth(), host = "h", port = 1, useTls = false, authenticated = false)
445 val unauthHeaders = invoke(unauth, "authHeaders") as Map<*, *>
446 assertFalse(unauthHeaders.containsKey("Authorization"))
447 assertTrue(unauthHeaders.containsKey("User-Agent"))
448
449 assertEquals("ws close 4401 invalid auth",
450 (invoke(insecure, "closeError", Int::class.java to 4401) as Throwable).message)
451 assertEquals("ws close 4409 connected elsewhere",
452 (invoke(insecure, "closeError", Int::class.java to 4409) as Throwable).message)
453 assertEquals("ws close 1006",
454 (invoke(insecure, "closeError", Int::class.java to 1006) as Throwable).message)
455 val id1 = invoke(insecure, "nextRequestId") as Long
456 val id2 = invoke(insecure, "nextRequestId") as Long
457 assertTrue(id1 != 0L && id2 != 0L && id1 != id2)
458 }
459
460 @Test
461 fun `completePending and failAllPending resolve only matching waiters`() = runBlocking {
462 val socket = socketFor(port = 9)
463 val pending: ConcurrentHashMap<Long, CompletableDeferred<WebSocketResponseMessage?>> =
464 getField(socket, "pending")
465 val waiter = CompletableDeferred<WebSocketResponseMessage?>()
466 pending[55L] = waiter
467 // Garbage, a REQUEST frame, and an unknown id must not complete it.
468 invoke(socket, "completePending", ByteArray::class.java to byteArrayOf(1, 2, 3))
469 val requestMsg = WebSocketMessage.newBuilder()
470 .setType(WebSocketMessage.Type.REQUEST)
471 .setRequest(WebSocketRequestMessage.newBuilder().setId(55L).build()).build().toByteArray()
472 invoke(socket, "completePending", ByteArray::class.java to requestMsg)
473 val unknown = WebSocketMessage.newBuilder()
474 .setType(WebSocketMessage.Type.RESPONSE)
475 .setResponse(WebSocketResponseMessage.newBuilder().setId(99L).setStatus(200).build())
476 .build().toByteArray()
477 invoke(socket, "completePending", ByteArray::class.java to unknown)
478 assertFalse(waiter.isCompleted)
479 val mine = WebSocketMessage.newBuilder()
480 .setType(WebSocketMessage.Type.RESPONSE)
481 .setResponse(WebSocketResponseMessage.newBuilder().setId(55L).setStatus(201).setMessage("made").build())
482 .build().toByteArray()
483 invoke(socket, "completePending", ByteArray::class.java to mine)
484 assertEquals(201, waiter.await()?.status)
485 assertTrue(pending.isEmpty())
486
487 val w1 = CompletableDeferred<WebSocketResponseMessage?>()
488 val w2 = CompletableDeferred<WebSocketResponseMessage?>()
489 pending[1L] = w1; pending[2L] = w2
490 invoke(socket, "failAllPending")
491 assertNull(w1.await()); assertNull(w2.await()); assertTrue(pending.isEmpty())
492 Unit
493 }
494
495 // ---------------- registration (scripted localhost) ----------------
496
497 private data class Req(val method: String, val path: String, val body: String, val auth: String?)
498
499 private class RegServer : AutoCloseable {
500 val requests = Collections.synchronizedList(mutableListOf<Req>())
501 @Volatile var handler: (String, String, String) -> Pair<Int, String> =
502 { _, _, _ -> 404 to """{"error":"unscripted"}""" }
503 private val server: HttpServer = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0)
504 val baseUrl: String get() = "http://127.0.0.1:${server.address.port}"
505 init {
506 server.createContext("/") { exchange ->
507 val body = exchange.requestBody.readBytes().decodeToString()
508 requests.add(Req(
509 exchange.requestMethod, exchange.requestURI.path, body,
510 exchange.requestHeaders.getFirst("Authorization")))
511 val (status, response) = handler(exchange.requestMethod, exchange.requestURI.path, body)
512 val bytes = response.encodeToByteArray()
513 exchange.responseHeaders.add("Content-Type", "application/json")
514 exchange.sendResponseHeaders(status, bytes.size.toLong())
515 exchange.responseBody.use { it.write(bytes) }
516 }
517 server.start()
518 }
519 override fun close() { server.stop(0) }
520 }
521
522 private fun sessionJson(id: String = "sess1", allowed: Boolean = true, info: List<String> = emptyList(), verified: Boolean = false) =
523 """{"id":"$id","allowedToRequestCode":$allowed,"requestedInformation":[${info.joinToString(",") { "\"$it\"" }}],"verified":$verified,"nextSms":30,"nextCall":60}"""
524
525 private fun regClient(server: RegServer) = RegistrationHttpClient(ctx).apply { baseUrl = server.baseUrl }
526
527 @Test
528 fun `registration code request lock rate-limit and captcha-after-code branches`() = runBlocking {
529 RegServer().use { server ->
530 val client = regClient(server)
531 // 423 on session creation.
532 server.handler = { _, path, _ ->
533 if (path == "/v1/verification/session") 423 to """{"timeRemaining":9}""" else 404 to "{}"
534 }
535 var r = client.requestSmsCode("+15550102030")
536 assertEquals("error", r.status); assertTrue(r.reason!!.contains("423"), "${r.reason}")
537
538 // Session ok, code request 429 then 423.
539 server.handler = { _, path, _ ->
540 when {
541 path.endsWith("/code") -> 429 to """{"retryAfter":5}"""
542 else -> 200 to sessionJson()
543 }
544 }
545 r = client.requestVoiceCode("+15550102030")
546 assertEquals("error", r.status); assertTrue(r.reason!!.contains("429"), "${r.reason}")
547 server.handler = { _, path, _ ->
548 when {
549 path.endsWith("/code") -> 423 to """{}"""
550 else -> 200 to sessionJson()
551 }
552 }
553 r = client.requestSmsCode("+15550102030")
554 assertTrue(r.reason!!.contains("423"), "${r.reason}")
555
556 // Code response asking for captcha (structured, then raw-body variant).
557 server.handler = { _, path, _ ->
558 when {
559 path.endsWith("/code") -> 200 to sessionJson(allowed = false, info = listOf("captcha"))
560 else -> 200 to sessionJson()
561 }
562 }
563 r = client.requestSmsCode("+15550102030")
564 assertEquals("captcha", r.status); assertTrue(r.needsCaptcha)
565 server.handler = { _, path, _ ->
566 when {
567 path.endsWith("/code") -> 200 to
568 """{"id":"sess1","allowedToRequestCode":false,"requestedInformation":[],"verified":false,"note":"CAPTCHA needed"}"""
569 else -> 200 to sessionJson()
570 }
571 }
572 assertEquals("captcha", client.requestSmsCode("+15550102030").status)
573
574 // Challenges listed but code allowed: the gate must not short-circuit.
575 server.handler = { _, path, _ ->
576 when {
577 path.endsWith("/code") -> 200 to sessionJson()
578 else -> 200 to sessionJson(allowed = true, info = listOf("captcha", "pushChallenge"))
579 }
580 }
581 assertEquals("sent", client.requestSmsCode("+15550102030").status)
582 }
583 }
584
585 @Test
586 fun `registration scaffold reuse regeneration and sessionId alias`() = runBlocking {
587 RegServer().use { server ->
588 val client = regClient(server)
589 server.handler = { _, path, _ ->
590 when {
591 path.contains("/sess-alias/code") -> 200 to sessionJson(id = "sess-alias")
592 path.endsWith("/code") -> 200 to sessionJson()
593 // Session id carried as sessionId, not id.
594 else -> 200 to """{"sessionId":"sess-alias","allowedToRequestCode":true,"requestedInformation":[],"verified":false}"""
595 }
596 }
597 // Registered scaffold for the same number is reused verbatim.
598 val registered = SignalRegistrationKeys.generate("+15550102030").authScaffold
599 .copy(registered = true, password = "keep-me")
600 SignalAuthData.save(ctx, registered)
601 assertEquals("sent", client.requestSmsCode("+15550102030").status)
602 val afterReuse = SignalAuthData.load(ctx)!!
603 assertEquals("keep-me", afterReuse.password)
604 assertEquals("sess-alias", afterReuse.verificationSessionId)
605 assertTrue(server.requests.snapshot().any { it.path == "/v1/verification/session/sess-alias/code" },
606 "${server.requests.snapshot()}")
607
608 // Stale 32-byte UAK scaffold is regenerated for the same number.
609 val stale = SignalRegistrationKeys.generate("+15550102030").authScaffold.copy(
610 registered = false,
611 unidentifiedAccessKey = android.util.Base64.encodeToString(ByteArray(32) { 7 }, android.util.Base64.NO_WRAP),
612 password = "stale-pw")
613 SignalAuthData.save(ctx, stale)
614 assertEquals("sent", client.requestSmsCode("+15550102030").status)
615 val afterRegen = SignalAuthData.load(ctx)!!
616 assertTrue(afterRegen.password != "stale-pw")
617 assertEquals(16, android.util.Base64.decode(afterRegen.unidentifiedAccessKey, android.util.Base64.NO_WRAP).size)
618
619 // A scaffold for a different number is not reused.
620 val other = SignalRegistrationKeys.generate("+19999999999").authScaffold.copy(password = "other-pw")
621 SignalAuthData.save(ctx, other)
622 assertEquals("sent", client.requestSmsCode("+15550102030").status)
623 assertEquals("+15550102030", SignalAuthData.load(ctx)!!.phoneNumber)
624 }
625 }
626
627 @Test
628 fun `verify code filtering and 409-verified registration success`() = runBlocking {
629 RegServer().use { server ->
630 val client = regClient(server)
631 // No scaffold at all.
632 SignalAuthData.clear(ctx)
633 val noKeys = client.verifyCode("123456")
634 assertEquals("error", noKeys.status); assertEquals("no_keys", noKeys.reason)
635
636 val scaffold = SignalRegistrationKeys.generate("+15550102030").authScaffold
637 .copy(verificationSessionId = "sessV")
638 SignalAuthData.save(ctx, scaffold)
639 // 409 whose body says verified:true still proceeds to registration; code is digit-filtered.
640 server.handler = { _, path, _ ->
641 when {
642 path.endsWith("/code") -> 409 to sessionJson(id = "sessV", verified = true)
643 path == "/v1/registration" -> 200 to """{"aci":"aci-only-1"}"""
644 else -> 404 to "{}"
645 }
646 }
647 val ok = client.verifyCode("12-34 56")
648 assertTrue(ok.ok, "$ok"); assertEquals("aci-only-1", ok.aci); assertNull(ok.pni)
649 val codeReq = server.requests.snapshot().first { it.method == "PUT" }
650 assertTrue(codeReq.body.contains("\"code\":\"123456\""), codeReq.body)
651 val regReq = server.requests.snapshot().first { it.path == "/v1/registration" }
652 assertNotNull(regReq.auth); assertTrue(regReq.auth!!.startsWith("Basic "))
653 val regBody = org.json.JSONObject(regReq.body)
654 assertEquals("sessV", regBody.getString("sessionId"))
655 assertTrue(regBody.has("aciIdentityKey")); assertTrue(regBody.has("pniIdentityKey"))
656 assertTrue(regBody.has("aciPqLastResortPreKey")); assertTrue(regBody.getBoolean("requireAtomic"))
657 }
658 }
659
660 @Test
661 fun `verify code registration failures missing password and http errors`() = runBlocking {
662 RegServer().use { server ->
663 val client = regClient(server)
664 val scaffold = SignalRegistrationKeys.generate("+15550102030").authScaffold
665 .copy(verificationSessionId = "sessV")
666 // Registration HTTP error is reported with the raw body and does not persist registration.
667 SignalAuthData.save(ctx, scaffold)
668 server.handler = { _, path, _ ->
669 when {
670 path.endsWith("/code") -> 200 to sessionJson(id = "sessV", verified = true)
671 else -> 422 to """{"error":"bad uak"}"""
672 }
673 }
674 val failed = client.verifyCode("654321")
675 assertEquals("error", failed.status); assertEquals("HTTP 422", failed.reason)
676 assertTrue(failed.raw.contains("bad uak")); assertNull(failed.auth)
677
678 // A 200 registration body with no account id is not success.
679 server.handler = { _, path, _ ->
680 when {
681 path.endsWith("/code") -> 200 to sessionJson(id = "sessV", verified = true)
682 else -> 200 to """{"storageCapable":true}"""
683 }
684 }
685 val noId = client.verifyCode("654321")
686 assertEquals("error", noId.status); assertNull(noId.auth)
687
688 // Missing password stops before the registration POST.
689 SignalAuthData.save(ctx, scaffold.copy(password = ""))
690 server.requests.clear()
691 server.handler = { _, path, _ ->
692 when {
693 path.endsWith("/code") -> 200 to sessionJson(id = "sessV", verified = true)
694 else -> 200 to """{"uuid":"x"}"""
695 }
696 }
697 val noPw = client.verifyCode("654321")
698 assertEquals("missing_password", noPw.reason)
699 assertTrue(server.requests.snapshot().none { it.path == "/v1/registration" })
700
701 // Unverified code submission HTTP error propagates as an error result.
702 SignalAuthData.save(ctx, scaffold)
703 server.handler = { _, _, _ -> 500 to """{"error":"boom"}""" }
704 val httpErr = client.verifyCode("000000")
705 assertEquals("error", httpErr.status); assertTrue(httpErr.reason!!.contains("500"), "${httpErr.reason}")
706 }
707 }
708
709 @Test
710 fun `captcha submit guards and whoami variants`() { runBlocking {
711 RegServer().use { server ->
712 val client = regClient(server)
713 SignalAuthData.clear(ctx)
714 var r = client.submitCaptcha("+15550102030", "signalcaptcha://tok")
715 assertEquals("no_session", r.reason)
716 assertTrue(r.raw.contains("request a code first"))
717 val scaffold = SignalRegistrationKeys.generate("+15550102030").authScaffold
718 .copy(verificationSessionId = "sessC")
719 SignalAuthData.save(ctx, scaffold)
720 r = client.submitCaptcha("+15550102030", "signalcaptcha://")
721 assertEquals("empty_captcha", r.reason)
722 r = client.submitCaptcha("+15550102030", " ")
723 assertEquals("empty_captcha", r.reason)
724
725 // whoami: registered+password probes; 500 is not existence; no password stays live-only.
726 SignalAuthData.save(ctx, scaffold.copy(registered = true))
727 server.handler = { _, _, _ -> 200 to """{"number":"+15550102030","aci":"aci-9","pni":"pni-9"}""" }
728 assertTrue(client.checkExists("+15550102030").exists)
729 server.handler = { _, _, _ -> 500 to """{}""" }
730 assertFalse(client.checkExists("+15550102030").exists)
731 SignalAuthData.save(ctx, scaffold.copy(registered = true, password = ""))
732 val liveOnly = client.checkExists("+15550102030")
733 assertFalse(liveOnly.exists); assertTrue(liveOnly.reason!!.contains("CDSIv2"))
734
735 // whoami against a dead port is a caught error result, not a throw.
736 val dead = RegistrationHttpClient(ctx).apply { baseUrl = "http://127.0.0.1:1" }
737 SignalAuthData.save(ctx, scaffold.copy(registered = true))
738 val err = dead.checkExists("+15550102030")
739 assertFalse(err.exists); assertNotNull(err.reason)
740 }
741 } }
742
743 // ---------------- groups / keys / cdsi / attachment parse edges ----------------
744
745 private fun kb64(bytes: ByteArray): String =
746 kotlin.io.encoding.Base64.Default.encode(bytes).trimEnd('=')
747
748 @Test
749 fun `groups keys cdsi and attachment uncovered parse and crypto branches`() = runBlocking {
750 // Groups credentials: entries missing time/credential are skipped individually.
751 val cred = kotlin.io.encoding.Base64.Default.encode(ByteArray(48) { 3 })
752 val parsedCreds = SignalGroupsApi.parseCredentials(
753 """{"credentials":[{"credential":"$cred"},{"redemptionTime":5},{"redemptionTime":6,"credential":"$cred"}]}""",
754 warn = {})
755 assertEquals(listOf(6L), parsedCreds.map { it.redemptionTimeSeconds })
756
757 // authorizationFor fails closed on unparseable ACI and on a bogus credential.
758 val masterKey = ByteArray(32) { (it + 1).toByte() }
759 val secretParams = GroupSecretParams(SignalGroups.secretParamsFor(masterKey))
760 val badAuth = SignalAuthData(phoneNumber = "+1", aci = "not-a-uuid", pni = pni)
761 assertNull(SignalGroupsApi.authorizationFor(
762 badAuth, secretParams, SignalGroupsApi.DayCredential(1_700_000_000L, ByteArray(48) { 1 })))
763 val goodIdsBadCred = SignalAuthData(phoneNumber = "+1", aci = aci, pni = pni)
764 assertNull(SignalGroupsApi.authorizationFor(
765 goodIdsBadCred, secretParams, SignalGroupsApi.DayCredential(1_700_000_000L, ByteArray(10) { 1 })))
766
767 // decryptGroup: presented + undecryptable members skipped, garbage title becomes "".
768 val cipher = org.signal.libsignal.zkgroup.groups.ClientZkGroupCipher(secretParams)
769 val validUserId = cipher.encrypt(
770 org.signal.libsignal.protocol.ServiceId.Aci.parseFromString(aci)).serialize()
771 val group = org.signal.storageservice.storage.protos.groups.Group.newBuilder()
772 .setTitle(ByteString.copyFrom(byteArrayOf(1, 2, 3)))
773 .setVersion(3)
774 .addMembers(org.signal.storageservice.storage.protos.groups.Member.newBuilder()
775 .setUserId(ByteString.copyFrom(validUserId))
776 .setPresentation(ByteString.copyFrom(byteArrayOf(9)))
777 .build())
778 .addMembers(org.signal.storageservice.storage.protos.groups.Member.newBuilder()
779 .setUserId(ByteString.copyFrom(byteArrayOf(4, 5, 6))).build())
780 .addMembers(org.signal.storageservice.storage.protos.groups.Member.newBuilder()
781 .setUserId(ByteString.copyFrom(validUserId)).build())
782 .build()
783 val state = SignalGroupsApi.decryptGroup(secretParams, group)!!
784 assertEquals("", state.title); assertEquals(3, state.revision)
785 assertEquals(1, state.memberAcis.size)
786
787 // Keys: a device whose one-time key is undecodable keeps its bundle with no pre-key;
788 // a device with no deviceId is skipped; non-array devices yields empty.
789 fun device(extra: String) = """{"deviceId":2,"registrationId":7,"signedPreKey":{"keyId":11,"publicKey":"${kb64(ByteArray(33) { 1 })}","signature":"${kb64(ByteArray(64) { 2 })}"},"pqPreKey":{"keyId":31,"publicKey":"${kb64(ByteArray(33) { 3 })}","signature":"${kb64(ByteArray(64) { 4 })}"}$extra}"""
790 val body = """{"identityKey":"${kb64(ByteArray(33) { 9 })}","devices":[${device(",\"preKey\":{\"keyId\":21,\"publicKey\":\"A\"}")},{"registrationId":1}]}"""
791 val bundles = SignalKeysApi.parse(body, aci, warn = {})
792 assertEquals(1, bundles.size)
793 assertNull(bundles[0].bundle.preKeyId); assertNull(bundles[0].bundle.preKeyPublic)
794 assertEquals(31, bundles[0].bundle.kyberPreKeyId)
795 assertTrue(SignalKeysApi.parse("""{"identityKey":"${kb64(ByteArray(33) { 9 })}","devices":"nope"}""", aci, warn = {}).isEmpty())
796 assertTrue(SignalKeysApi.parse("""{"identityKey":"${kb64(ByteArray(33) { 9 })}","devices":[{"deviceId":0}]}""", aci, warn = {}).isEmpty())
797
798 // CDSI credentials: non-string fields are rejected; empty lookup preserves the token.
799 assertNull(SignalCdsi.parseCredentials("""{"username":["u"],"password":"p"}""", warn = {}))
800 assertNull(SignalCdsi.parseCredentials("""{"username":"u","password":["p"]}""", warn = {}))
801 val token = byteArrayOf(5, 6, 7)
802 val empty = SignalCdsi.lookup(SignalCdsi.Credentials("u", "p"), emptySet(), emptySet(), token)
803 assertNotNull(empty); assertTrue(empty.discovered.isEmpty())
804 assertTrue(empty.token!!.contentEquals(token))
805
806 // Attachment form: numeric header values stringify, string cdn rejects the form,
807 // non-object headers degrade to empty, and CDN2 upload refuses without network.
808 val form = SignalAttachmentUpload.parseForm(
809 """{"cdn":3,"key":"k2","signedUploadLocation":"https://cdn.example/x","headers":{"x-amz-meta":42,"host":"h"}}""",
810 warn = {})!!
811 assertEquals("42", form.headers["x-amz-meta"])
812 // kotlinx's JsonPrimitive.int coerces a quoted numeric cdn, so this form parses.
813 assertEquals(3, SignalAttachmentUpload.parseForm(
814 """{"cdn":"3","key":"k","signedUploadLocation":"https://x"}""", warn = {})!!.cdn)
815 val noHeaders = SignalAttachmentUpload.parseForm(
816 """{"cdn":3,"key":"k","signedUploadLocation":"https://x","headers":[1]}""", warn = {})!!
817 assertTrue(noHeaders.headers.isEmpty())
818 assertFalse(SignalAttachmentUpload.upload(
819 SignalAttachmentUpload.UploadForm(2, "k", emptyMap(), "https://cdn.example/x"),
820 byteArrayOf(1, 2), null))
821 Unit
822 }
823}