Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / communicate-dev / src / test / java / com / vayunmathur / communicate / rcs / RcsSlice3Pass2MsrpTest.kt
RcsSlice3Pass2MsrpTest.kt367 lines · 15.3 KiBRaw
| 1 | package com.vayunmathur.communicate.rcs |
| 2 | |
| 3 | import android.content.Context |
| 4 | import androidx.test.core.app.ApplicationProvider |
| 5 | import com.vayunmathur.communicate.data.rcs.MsrpSetup |
| 6 | import com.vayunmathur.communicate.data.rcs.RcsMsrp |
| 7 | import com.vayunmathur.communicate.data.rcs.RcsMsrpFraming |
| 8 | import com.vayunmathur.communicate.data.rcs.RcsMsrpListen |
| 9 | import com.vayunmathur.communicate.data.rcs.RcsSession |
| 10 | import java.net.ServerSocket |
| 11 | import java.net.Socket |
| 12 | import java.util.concurrent.CopyOnWriteArrayList |
| 13 | import java.util.concurrent.CountDownLatch |
| 14 | import java.util.concurrent.TimeUnit |
| 15 | import java.util.concurrent.atomic.AtomicReference |
| 16 | import kotlinx.coroutines.runBlocking |
| 17 | import org.junit.runner.RunWith |
| 18 | import org.robolectric.RobolectricTestRunner |
| 19 | import org.robolectric.annotation.Config |
| 20 | import kotlin.test.Test |
| 21 | import kotlin.test.assertEquals |
| 22 | import kotlin.test.assertFalse |
| 23 | import kotlin.test.assertNotNull |
| 24 | import kotlin.test.assertNull |
| 25 | import kotlin.test.assertTrue |
| 26 | |
| 27 | /** |
| 28 | * Slice-3 pass 2: the MSRP socket layer over real loopback TCP — one-shot |
| 29 | * sends with FIFO acks, persistent connections (chunked SEND, inbound SEND |
| 30 | * delivery + auto-200, REPORT/AUTH handling, keepalives), and the |
| 31 | * accepted-socket wrapper. |
| 32 | */ |
| 33 | @RunWith(RobolectricTestRunner::class) |
| 34 | @Config(sdk = [34], shadows = [RcsSlice3Pass2ConnectivityShadow::class]) |
| 35 | class RcsSlice3Pass2MsrpTest { |
| 36 | |
| 37 | private val context: Context get() = ApplicationProvider.getApplicationContext() |
| 38 | |
| 39 | private fun session(port: Int, setup: MsrpSetup? = MsrpSetup.PASSIVE) = RcsSession( |
| 40 | dialogId = "pass2-d", callId = "pass2-c", localTag = "lt", remoteTag = "rt", |
| 41 | remoteUri = "sip:peer@rcs", conversationId = "conv-pass2", |
| 42 | msrpLocalPath = "msrp://127.0.0.1:$port/self;tcp", |
| 43 | msrpRemotePath = "msrp://127.0.0.1:$port/peer;tcp", |
| 44 | msrpSetup = setup, confirmed = true, |
| 45 | ) |
| 46 | |
| 47 | /** A loopback peer thread helper: runs [block] against one accepted socket. */ |
| 48 | private fun serveOnce(server: ServerSocket, block: (Socket) -> Unit): CountDownLatch { |
| 49 | val done = CountDownLatch(1) |
| 50 | Thread { |
| 51 | runCatching { server.accept().use(block) } |
| 52 | done.countDown() |
| 53 | }.apply { isDaemon = true; start() } |
| 54 | return done |
| 55 | } |
| 56 | |
| 57 | private fun readHead(input: java.io.BufferedReader): List<String> { |
| 58 | val lines = mutableListOf<String>() |
| 59 | var line = input.readLine() ?: return lines |
| 60 | var guard = 0 |
| 61 | while (line.isNotEmpty() && guard++ < 32) { |
| 62 | lines.add(line) |
| 63 | line = input.readLine() ?: break |
| 64 | } |
| 65 | return lines |
| 66 | } |
| 67 | |
| 68 | private fun readToMarker(input: java.io.BufferedReader, txid: String): String { |
| 69 | val sb = StringBuilder() |
| 70 | var line = input.readLine() |
| 71 | while (line != null && !line.startsWith("-------$txid")) { |
| 72 | sb.append(line).append("\r\n") |
| 73 | line = input.readLine() |
| 74 | } |
| 75 | return sb.toString() |
| 76 | } |
| 77 | |
| 78 | private fun respondOk(socket: Socket, txid: String, toPath: String) { |
| 79 | val out = socket.getOutputStream() |
| 80 | out.write(RcsMsrpFraming.buildErrorResponse(toPath, txid, 200, "OK")) |
| 81 | out.flush() |
| 82 | } |
| 83 | |
| 84 | // --- one-shot send --- |
| 85 | |
| 86 | @Test |
| 87 | fun oneShotSendDeliversChunksAndMatchesAcks() = runBlocking { |
| 88 | val server = ServerSocket(0) |
| 89 | val port = server.localPort |
| 90 | val received = AtomicReference<String>() |
| 91 | val done = serveOnce(server) { s -> |
| 92 | s.soTimeout = 15_000 |
| 93 | val input = s.getInputStream().bufferedReader(Charsets.UTF_8) |
| 94 | val all = StringBuilder() |
| 95 | // Payload below is > 4096 bytes, so three chunks arrive; ack each. |
| 96 | repeat(3) { |
| 97 | val head = readHead(input) |
| 98 | val txid = head.firstOrNull()?.split(" ")?.getOrNull(1).orEmpty() |
| 99 | val body = readToMarker(input, txid) |
| 100 | all.append(head.joinToString("\n")).append("\n").append(body) |
| 101 | val toPath = head.firstOrNull { it.startsWith("From-Path:", true) } |
| 102 | ?.substringAfter(":")?.trim().orEmpty() |
| 103 | respondOk(s, txid, toPath) |
| 104 | } |
| 105 | received.set(all.toString()) |
| 106 | } |
| 107 | // ASCII, newline-free payload: the peer reads it line-wise. |
| 108 | val payload = "msrp-one-shot-payload-".repeat(230).toByteArray(Charsets.UTF_8) |
| 109 | val ok = RcsMsrp.send(session(port), context, payload) |
| 110 | assertTrue(ok, "one-shot send was not acked") |
| 111 | assertTrue(done.await(15, TimeUnit.SECONDS)) |
| 112 | val wire = received.get() |
| 113 | assertTrue(wire.contains("MSRP "), wire.take(200)) |
| 114 | assertTrue(wire.contains("Byte-Range: 1-2048/5060"), wire.take(400)) |
| 115 | assertTrue(wire.contains("Byte-Range: 2049-4096/5060")) |
| 116 | assertTrue(wire.contains("Byte-Range: 4097-5060/5060")) |
| 117 | assertTrue(wire.contains("Content-Type: message/cpim")) |
| 118 | server.close() |
| 119 | } |
| 120 | |
| 121 | @Test |
| 122 | fun oneShotSendFailureModes() = runBlocking { |
| 123 | // Empty payload: nothing to send. |
| 124 | assertFalse(RcsMsrp.send(session(9), context, ByteArray(0))) |
| 125 | // No remote path. |
| 126 | assertFalse(RcsMsrp.send(session(9).copy(msrpRemotePath = null), context, byteArrayOf(1))) |
| 127 | // Unparseable path. |
| 128 | assertFalse( |
| 129 | RcsMsrp.send(session(9).copy(msrpRemotePath = "not-a-path"), context, byteArrayOf(1)), |
| 130 | ) |
| 131 | // Closed port: connection refused. |
| 132 | assertFalse(RcsMsrp.send(session(1), context, byteArrayOf(1, 2, 3))) |
| 133 | // Secure session without a known peer fingerprint: refused (no downgrade in one-shot send). |
| 134 | assertFalse( |
| 135 | RcsMsrp.send(session(1).copy(msrpSecure = true), context, byteArrayOf(1, 2, 3)), |
| 136 | ) |
| 137 | } |
| 138 | |
| 139 | @Test |
| 140 | fun oneShotSendNonSuccessAckFails() = runBlocking { |
| 141 | val server = ServerSocket(0) |
| 142 | val port = server.localPort |
| 143 | val done = serveOnce(server) { s -> |
| 144 | s.soTimeout = 15_000 |
| 145 | val input = s.getInputStream().bufferedReader(Charsets.UTF_8) |
| 146 | val head = readHead(input) |
| 147 | val txid = head.firstOrNull()?.split(" ")?.getOrNull(1).orEmpty() |
| 148 | readToMarker(input, txid) |
| 149 | val out = s.getOutputStream() |
| 150 | out.write(RcsMsrpFraming.buildErrorResponse("", txid, 413, "Message Too Large")) |
| 151 | out.flush() |
| 152 | } |
| 153 | assertFalse(RcsMsrp.send(session(port), context, "hello".toByteArray())) |
| 154 | assertTrue(done.await(15, TimeUnit.SECONDS)) |
| 155 | server.close() |
| 156 | } |
| 157 | |
| 158 | // --- connect() guards --- |
| 159 | |
| 160 | @Test |
| 161 | fun connectGuards() = runBlocking { |
| 162 | assertNull(RcsMsrp.connect(session(9).copy(msrpRemotePath = null), context) { _, _ -> }) |
| 163 | // Peer active + no listen socket: cannot establish. |
| 164 | assertNull(RcsMsrp.connect(session(9, MsrpSetup.ACTIVE), context) { _, _ -> }) |
| 165 | // Unreachable peer. |
| 166 | assertNull(RcsMsrp.connect(session(1), context) { _, _ -> }) |
| 167 | } |
| 168 | |
| 169 | /** The fake MSRP peer: ack our SEND, push an inbound SEND, REPORT, then AUTH expecting 501. */ |
| 170 | private fun runMsrpPeer( |
| 171 | server: ServerSocket, |
| 172 | port: Int, |
| 173 | chunksSeen: CopyOnWriteArrayList<String>, |
| 174 | peerLatch: CountDownLatch, |
| 175 | ) { |
| 176 | server.accept().use { s -> |
| 177 | s.soTimeout = 20_000 |
| 178 | val input = s.getInputStream().bufferedReader(Charsets.UTF_8) |
| 179 | val out = s.getOutputStream() |
| 180 | // 1) Read our SEND, ack it. |
| 181 | val head1 = readHead(input) |
| 182 | val tx1 = head1.firstOrNull()?.split(" ")?.getOrNull(1).orEmpty() |
| 183 | chunksSeen += readToMarker(input, tx1) |
| 184 | // OutChunk serialization appends CRLF before the marker; the |
| 185 | // body slice read here is line-based, so compare trimmed. |
| 186 | respondOk(s, tx1, "msrp://127.0.0.1:$port/self;tcp") |
| 187 | // 2) Send an inbound SEND to us; expect our auto-200. |
| 188 | val inbound = RcsMsrpFraming.splitSend( |
| 189 | toPath = "msrp://127.0.0.1:$port/self;tcp", |
| 190 | fromPath = "msrp://127.0.0.1:$port/peer;tcp", |
| 191 | payload = "inbound hello".toByteArray(Charsets.UTF_8), |
| 192 | messageId = "pass2-inbound-1", |
| 193 | ).single() |
| 194 | out.write(RcsMsrpFraming.serializeChunk(inbound)) |
| 195 | out.flush() |
| 196 | val respHead = readHead(input) |
| 197 | chunksSeen += respHead.joinToString("\n") |
| 198 | readToMarker(input, inbound.txid) |
| 199 | // 3) REPORT frame: queued by the reader, no response. |
| 200 | val report = RcsMsrpFraming.buildReport( |
| 201 | toPath = "msrp://127.0.0.1:$port/self;tcp", |
| 202 | fromPath = "msrp://127.0.0.1:$port/peer;tcp", |
| 203 | messageId = "pass2-msg-9", statusCode = 200, reason = "OK", |
| 204 | byteRange = "1-5/5", |
| 205 | ) |
| 206 | out.write(report) |
| 207 | out.flush() |
| 208 | // 4) AUTH frame: answered 501. |
| 209 | val authTx = "authtx123456" |
| 210 | out.write( |
| 211 | ("MSRP $authTx AUTH\r\nTo-Path: msrp://127.0.0.1:$port/self;tcp\r\n" + |
| 212 | "From-Path: msrp://127.0.0.1:$port/peer;tcp\r\n\r\n" + |
| 213 | "-------$authTx\$\r\n").toByteArray(Charsets.UTF_8), |
| 214 | ) |
| 215 | out.flush() |
| 216 | // Read frames until the 501 AUTH response arrives; our |
| 217 | // keepalive/report frames may interleave ahead of it. |
| 218 | var saw501 = false |
| 219 | var guard = 0 |
| 220 | while (!saw501 && guard++ < 8) { |
| 221 | val frameHead = readHead(input) |
| 222 | if (frameHead.isEmpty()) break |
| 223 | chunksSeen += frameHead.joinToString("\n") |
| 224 | val frameTx = frameHead.firstOrNull()?.split(" ")?.getOrNull(1).orEmpty() |
| 225 | readToMarker(input, frameTx) |
| 226 | if (frameHead.joinToString("\n").contains("501")) saw501 = true |
| 227 | } |
| 228 | chunksSeen += if (saw501) "SAW-501" else "NO-501" |
| 229 | // Wait for the test to finish its assertions, then close. |
| 230 | peerLatch.await(20, TimeUnit.SECONDS) |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | // --- persistent connection, both directions --- |
| 235 | |
| 236 | @Test |
| 237 | fun persistentConnectionBothDirections() = runBlocking { |
| 238 | val server = ServerSocket(0) |
| 239 | val port = server.localPort |
| 240 | val chunksSeen = CopyOnWriteArrayList<String>() |
| 241 | val peerLatch = CountDownLatch(1) |
| 242 | val peerErrors = AtomicReference<String>() |
| 243 | val peer = Thread { |
| 244 | try { |
| 245 | runMsrpPeer(server, port, chunksSeen, peerLatch) |
| 246 | } catch (e: Throwable) { |
| 247 | peerErrors.set(e.toString()) |
| 248 | } |
| 249 | } |
| 250 | peer.isDaemon = true |
| 251 | peer.start() |
| 252 | |
| 253 | val inboundBodies = CopyOnWriteArrayList<String>() |
| 254 | val conn = RcsMsrp.connect(session(port), context) { contentType, body -> |
| 255 | inboundBodies += "$contentType:${body.toString(Charsets.UTF_8)}" |
| 256 | } |
| 257 | assertNotNull(conn, "connect failed") |
| 258 | assertFalse(conn.isClosed()) |
| 259 | |
| 260 | // SEND through the persistent connection and await its ack. |
| 261 | assertTrue(conn.sendCpim("persistent hello".toByteArray(Charsets.UTF_8))) |
| 262 | // Empty payload is refused without touching the socket. |
| 263 | assertFalse(conn.sendCpim(ByteArray(0))) |
| 264 | |
| 265 | // Inbound SEND is delivered and auto-200ed (peer records the response). |
| 266 | val deadline = System.currentTimeMillis() + 15_000 |
| 267 | while (System.currentTimeMillis() < deadline && inboundBodies.isEmpty()) Thread.sleep(25) |
| 268 | assertEquals(listOf("message/cpim:inbound hello"), inboundBodies.toList()) |
| 269 | |
| 270 | // Keepalive + REPORT go out on the same socket. |
| 271 | assertTrue(conn.sendKeepalive()) |
| 272 | assertTrue(conn.sendReport("pass2-msg-9", 200, "OK", "1-5/5")) |
| 273 | |
| 274 | peerLatch.countDown() |
| 275 | peer.join(20_000) |
| 276 | assertNull(peerErrors.get()) |
| 277 | val peerWire = chunksSeen.joinToString("\n") |
| 278 | assertTrue(peerWire.contains("persistent hello"), peerWire.take(500)) |
| 279 | assertTrue(peerWire.contains("200 OK"), peerWire.take(500)) |
| 280 | assertTrue(peerWire.contains("SAW-501"), peerWire.take(800)) |
| 281 | |
| 282 | conn.close() |
| 283 | assertTrue(conn.isClosed()) |
| 284 | conn.close() |
| 285 | assertFalse(conn.sendCpim("after close".toByteArray())) |
| 286 | assertFalse(conn.sendKeepalive()) |
| 287 | assertFalse(conn.sendReport("m", 200, "OK", "1-1/1")) |
| 288 | server.close() |
| 289 | } |
| 290 | |
| 291 | @Test |
| 292 | fun connectSecureSessionWithoutFingerprintDowngradesToPlaintext() = runBlocking { |
| 293 | val server = ServerSocket(0) |
| 294 | val port = server.localPort |
| 295 | val done = serveOnce(server) { s -> |
| 296 | s.soTimeout = 15_000 |
| 297 | val input = s.getInputStream().bufferedReader(Charsets.UTF_8) |
| 298 | val head = readHead(input) |
| 299 | val txid = head.firstOrNull()?.split(" ")?.getOrNull(1).orEmpty() |
| 300 | readToMarker(input, txid) |
| 301 | respondOk(s, txid, "msrp://127.0.0.1:$port/self;tcp") |
| 302 | } |
| 303 | // Secure session, but no fingerprint was stashed for this call: |
| 304 | // connect() downgrades to plaintext rather than failing. |
| 305 | val conn = RcsMsrp.connect(session(port).copy(msrpSecure = true), context) { _, _ -> } |
| 306 | assertNotNull(conn) |
| 307 | assertTrue(conn.sendCpim("downgraded hello".toByteArray(Charsets.UTF_8))) |
| 308 | conn.close() |
| 309 | assertTrue(done.await(15, TimeUnit.SECONDS)) |
| 310 | server.close() |
| 311 | } |
| 312 | |
| 313 | // --- wrapAccepted --- |
| 314 | |
| 315 | @Test |
| 316 | fun wrapAcceptedDeliversInboundChunk() = runBlocking { |
| 317 | val server = ServerSocket(0) |
| 318 | val port = server.localPort |
| 319 | val accepted = CountDownLatch(1) |
| 320 | var serverSocket: Socket? = null |
| 321 | Thread { |
| 322 | runCatching { |
| 323 | serverSocket = server.accept() |
| 324 | } |
| 325 | accepted.countDown() |
| 326 | }.apply { isDaemon = true; start() } |
| 327 | |
| 328 | val client = Socket("127.0.0.1", port) |
| 329 | assertTrue(accepted.await(10, TimeUnit.SECONDS)) |
| 330 | val serverSide = serverSocket!! |
| 331 | |
| 332 | val delivered = CopyOnWriteArrayList<String>() |
| 333 | val head = RcsMsrpListen.AcceptedHead( |
| 334 | listOf( |
| 335 | "MSRP wrappedtx1 SEND", |
| 336 | "To-Path: msrp://127.0.0.1:$port/self;tcp", |
| 337 | "From-Path: msrp://127.0.0.1:$port/peer;tcp", |
| 338 | "Message-ID: wrapped-1", |
| 339 | "Byte-Range: 1-7/7", |
| 340 | "Content-Type: message/cpim", |
| 341 | ), |
| 342 | ) |
| 343 | assertTrue(head.replayBytes().toString(Charsets.UTF_8).startsWith("MSRP wrappedtx1 SEND\r\n")) |
| 344 | val conn = RcsMsrp.wrapAccepted( |
| 345 | serverSide, head, |
| 346 | localPath = "msrp://127.0.0.1:$port/self;tcp", |
| 347 | remotePath = "msrp://127.0.0.1:$port/peer;tcp", |
| 348 | ) { _, body -> delivered += body.toString(Charsets.UTF_8) } |
| 349 | // The reader replays the head; the client supplies body + marker. |
| 350 | client.getOutputStream().apply { |
| 351 | write("wrapped".toByteArray(Charsets.UTF_8)) |
| 352 | write("\r\n-------wrappedtx1\$\r\n".toByteArray(Charsets.UTF_8)) |
| 353 | flush() |
| 354 | } |
| 355 | val deadline = System.currentTimeMillis() + 15_000 |
| 356 | while (System.currentTimeMillis() < deadline && delivered.isEmpty()) Thread.sleep(25) |
| 357 | assertEquals(listOf("wrapped"), delivered.toList()) |
| 358 | // The auto-200 for the wrapped SEND comes back to the client. |
| 359 | client.soTimeout = 15_000 |
| 360 | val clientIn = client.getInputStream().bufferedReader(Charsets.UTF_8) |
| 361 | val responseHead = readHead(clientIn) |
| 362 | assertTrue(responseHead.joinToString("\n").contains("200 OK"), responseHead.toString()) |
| 363 | conn.close() |
| 364 | client.close() |
| 365 | server.close() |
| 366 | } |
| 367 | } |