Modern Apps git

← Modern-Apps.git

communicate: add RCS pass-3 tests for MLS, inbound SIP and sync service

Commit
56230fd4d3d31f628abeafedac4a794d5aff3169
Author
Vayun Mathur <[email protected]>
When
2026-11-07 14:40 UTC (29 days ago)
Parents
cb1aa05
Slice: data/rcs/ + RCS telephony (RcsInboundParse, RcsSyncService,
RcsInboundDialog, RcsSyncLoops). New *RcsPass3Test files:

- WelcomeJoinRcsPass3Test: inbound Welcome -> join -> decrypt end
  to end through RcsSyncService.handleE2EEInbound, modelled as two
  devices (one in-memory RcsDatabase each): B publishes a key
  package, A creates the group, B joins from the Welcome on its own
  database (the fixed pseudo-thread storage path), A and B exchange
  application messages through the inbound route, commits absorb,
  negatives absorb, and an encrypted inbound through the service's
  transport callback lands in B's cached messages.
- MlsLifecycleRcsPass3Test: direct RustMlsCrypto lifecycle
  (identity/key-package/create/add/join/encrypt/decrypt/remove,
  payload-kind and magic probes, fail-closed garbage), a
  three-device group with member removal via tracked leaf indices,
  and transport-mediated setup/publish through the fake sender.
- InboundDialogRcsPass3Test: INVITE/re-INVITE/BYE/REFER/NOTIFY/
  SUBSCRIBE/UPDATE/OPTIONS with real SipMessage objects through
  the fake SIP sender, header parsing, and the full handleInbound
  chain via the transport callback.
- SyncServiceInboundRcsPass3Test / SyncServiceRcsPass3Test /
  InboundAsyncRcsPass3Test: service lifecycle and notification
  states, maintenance-loop first emissions, MSRP chunk routing
  (IMDN tracker, composing tracker, plain/CPIM into the cache),
  dialog dispatch, IMDN report sending, FT auto-fetch against a
  loopback HTTP server, focus relay, MSRP connection sync, and
  parseInbound revoke/edit/geopush/chunk/FT routes.
- SessionAcceptRcsPass3Test: incoming acceptance (passive/TLS
  answer branches with the fake IMS PDN), current-SDP rendering,
  decline, and the service passive MSRP accept.
- MsrpListenRcsPass3Test: listen routing branches — plaintext on
  a secure path, unknown/missing-path 481s, non-MSRP/EOF drops,
  dropped pending paths, and pinned TLS accepts.
- HiddenApiRcsPass3Test: hidden-API bridge against fake framework
  objects — provisioning callback subclass forwarding, single-reg
  tri-state, UCE fail-closed, MSRP connect/send over loopback.
- DirectSipRcsPass3Test: registration failure modes against a
  loopback P-CSCF (403, unanswerable AKA challenge, MESSAGE 404,
  deregistration). ConferenceEventsRcsPass3Test: conference-info
  parsing edges. GbaBootstrapRcsPass3Test: bootstrap fail-fast
  guards (the modem callback round trip cannot be driven under
  Robolectric; see the file header).

Slice INSTRUCTION coverage (merged, RCS-filtered test runs):
76.6% -> 82.5% (36358/44057 over data/rcs + telephony/Rcs*
classes; data/rcs alone 83.2%). 85% not reached: the remainder
is RcsE2EGroupsKt extension duplicates shadowed by RcsE2E
members (unreachable by construction), UCE/capability queries
and the GBA modem callback (hidden framework objects that
cannot be faked on the JVM), MSRP TLS accept-loop long tail,
delegate create/error mapping in RcsSipTransport, and
RcsDirectSip refresh/PCSCF-string fallback paths that need a
carrier IMS network. One pre-existing flake seen under load:
RcsSlice3Pass2UiTest compose timeout (passes standalone).

(cherry picked from commit fa0fe785bbdf91b9525776ef7c869c4196556448)

Diff

communicate/src/test/java/com/vayunmathur/communicate/rcs/ConferenceEventsRcsPass3Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/rcs/ConferenceEventsRcsPass3Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/rcs/ConferenceEventsRcsPass3Test.ktnew file mode 100644index 0000000000..6ea5e98996--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/rcs/ConferenceEventsRcsPass3Test.kt@@ -0,0 +1,89 @@+package com.vayunmathur.communicate.rcs++import com.vayunmathur.communicate.data.rcs.RcsConferenceEvents+import com.vayunmathur.communicate.data.rcs.RcsConferenceEvents.Participant+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/** Pass 3: conference-info parsing edge cases (deleted markers in each+ *  position, display text handling, missing attributes) and sipfrag. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class ConferenceEventsRcsPass3Test {++    @Test fun parseFullDocumentWithDeletedVariants() {+        val body = """+            <conference-info xmlns="urn:ietf:params:xml:ns:conference-info" entity="sip:conf-9@rcs" version="3" state="full">+              <users>+                <user entity="sip:+1001@rcs"><display-text>Alice</display-text><state>full</state></user>+                <user entity="sip:+1002@rcs" state="deleted"><display-text>Bob</display-text></user>+                <user entity="sip:+1003@rcs"><state>deleted</state></user>+                <user entity="sip:+1004@rcs"><endpoint state="deleted"/></user>+                <user entity="sip:+1005@rcs"><display-text>  </display-text></user>+                <user entity="sip:+1006@rcs"><state>partial</state><display-text>Carol</display-text></user>+              </users>+            </conference-info>+        """.trimIndent()+        val info = RcsConferenceEvents.parseConferenceInfo(body)+        assertNotNull(info)+        assertEquals("sip:conf-9@rcs", info.entity)+        assertEquals(3, info.version)+        assertEquals(+            listOf(+                Participant("sip:+1001@rcs", "full", "Alice"),+                Participant("sip:+1005@rcs", "full", null),+                Participant("sip:+1006@rcs", "partial", "Carol"),+            ),+            info.users,+        )+        assertEquals(+            listOf("sip:+1002@rcs", "sip:+1003@rcs"),+            RcsConferenceEvents.deletedUris(body).take(2),+        )+        assertTrue(RcsConferenceEvents.deletedUris(body).contains("sip:+1002@rcs"))+    }++    @Test fun parseDefaultsAndNonConferenceBodies() {+        assertNull(RcsConferenceEvents.parseConferenceInfo("just text"))+        assertNull(RcsConferenceEvents.parseConferenceInfo(""))+        assertEquals(emptyList(), RcsConferenceEvents.deletedUris("just text"))+        // No entity / no version attributes default to "" and 0.+        val info = RcsConferenceEvents.parseConferenceInfo(+            "<conference-info><users><user entity=\"sip:+1@rcs\"></user></users></conference-info>",+        )+        assertNotNull(info)+        assertEquals("", info.entity)+        assertEquals(0, info.version)+        assertEquals(listOf(Participant("sip:+1@rcs", "full", null)), info.users)+        // Malformed version also defaults.+        val bad = RcsConferenceEvents.parseConferenceInfo(+            "<conference-info entity=\"sip:c@rcs\" version=\"x\"></conference-info>",+        )+        assertEquals(0, bad?.version)+    }++    @Test fun buildParseRoundTrip() {+        val body = RcsConferenceEvents.buildConferenceInfo("sip:conf@rcs", 7, listOf("+1001", "sip:+1002@rcs"))+        val info = RcsConferenceEvents.parseConferenceInfo(body)+        assertNotNull(info)+        assertEquals("sip:conf@rcs", info.entity)+        assertEquals(7, info.version)+        assertEquals(2, info.users.size)+        assertTrue(info.users.any { it.uri.contains("+1001") })+    }++    @Test fun sipfragBuildAndParse() {+        val ok = RcsConferenceEvents.buildSipfrag(200, "OK")+        assertEquals(200 to "OK", RcsConferenceEvents.parseSipfrag(ok))+        val declined = RcsConferenceEvents.buildSipfrag(603, "Decline")+        assertEquals(603 to "Decline", RcsConferenceEvents.parseSipfrag(declined))+        assertNull(RcsConferenceEvents.parseSipfrag("garbage"))+        assertNull(RcsConferenceEvents.parseSipfrag(""))+    }+}
communicate/src/test/java/com/vayunmathur/communicate/rcs/DirectSipRcsPass3Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/rcs/DirectSipRcsPass3Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/rcs/DirectSipRcsPass3Test.ktnew file mode 100644index 0000000000..ba5cfea417--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/rcs/DirectSipRcsPass3Test.kt@@ -0,0 +1,174 @@+package com.vayunmathur.communicate.rcs++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.communicate.data.rcs.RcsDirectSip+import com.vayunmathur.communicate.data.rcs.RcsImsNetwork+import java.net.ServerSocket+import java.util.concurrent.CopyOnWriteArrayList+import java.util.concurrent.CountDownLatch+import java.util.concurrent.TimeUnit+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.AfterTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * Pass 3: direct-SIP registration failure modes against a loopback+ * P-CSCF on the shadow IMS PDN — rejection, unanswerable AKA+ * challenge, failed authenticated REGISTER, MESSAGE errors, and+ * deregistration. (The happy paths live in the pass-2 IMS tests.)+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34], shadows = [RcsSlice3Pass2ImsShadow::class])+class DirectSipRcsPass3Test {+    private val context: Context get() = ApplicationProvider.getApplicationContext()++    @AfterTest fun tearDown() {+        RcsDirectSip.stop()+        RcsDirectSip.onInboundMessage = null+        RcsImsNetwork.reset()+    }++    /** One-connection P-CSCF script; [handler] maps request text to a response or null (close). */+    private class Pcscf(private val handler: (String) -> String?) {+        val requests = CopyOnWriteArrayList<String>()+        val done = CountDownLatch(1)+        fun serve(server: ServerSocket) {+            Thread {+                try {+                    server.accept().use { s ->+                        s.soTimeout = 20_000+                        val input = s.getInputStream().bufferedReader(Charsets.UTF_8)+                        val out = s.getOutputStream()+                        while (true) {+                            val lines = mutableListOf<String>()+                            var line = input.readLine() ?: break+                            var contentLength = 0+                            while (line.isNotEmpty()) {+                                lines += line+                                if (line.startsWith("Content-Length:", true)) {+                                    contentLength = line.substringAfter(":").trim().toIntOrNull() ?: 0+                                }+                                line = input.readLine() ?: break+                            }+                            if (lines.isEmpty()) break+                            if (contentLength > 0) {+                                val chars = CharArray(contentLength)+                                var read = 0+                                while (read < contentLength) {+                                    val r = input.read(chars, read, contentLength - read)+                                    if (r < 0) break+                                    read += r+                                }+                                lines += String(chars, 0, read)+                            }+                            val request = lines.joinToString("\r\n")+                            requests += request+                            val response = handler(request) ?: break+                            // Echo Via branch / Call-ID / CSeq like a real P-CSCF.+                            val branch = lines.firstOrNull { it.startsWith("Via:", true) }+                                ?.substringAfter("branch=")?.substringBefore(";")?.trim().orEmpty()+                            val callId = lines.firstOrNull { it.startsWith("Call-ID:", true) }.orEmpty()+                            val cseq = lines.firstOrNull { it.startsWith("CSeq:", true) }.orEmpty()+                            out.write(+                                ("$response\r\nVia: SIP/2.0/TCP 127.0.0.1;branch=$branch\r\n" ++                                    "$callId\r\n$cseq\r\nContent-Length: 0\r\n\r\n").toByteArray(Charsets.UTF_8),+                            )+                            out.flush()+                        }+                    }+                } catch (_: Throwable) {+                    // Client went away mid-script.+                }+                done.countDown()+            }.apply { isDaemon = true; start() }+        }+    }++    private suspend fun withPcscf(handler: (String) -> String?, block: suspend (Pcscf) -> Unit) {+        val server = ServerSocket(5060)+        val pcscf = Pcscf(handler)+        pcscf.serve(server)+        try {+            block(pcscf)+        } finally {+            runCatching { server.close() }+            RcsDirectSip.stop()+        }+    }++    @Test fun idleEdgesWithoutRegistration() = runBlocking {+        assertFalse(RcsDirectSip.start(context, -1))+        assertFalse(RcsDirectSip.isRegistered())+        assertFalse(+            RcsDirectSip.sendMessage("MESSAGE sip:x@rcs SIP/2.0", "To: <sip:x@rcs>\r\n", "hi".toByteArray()),+        )+        RcsDirectSip.stop()+        RcsDirectSip.stop()+        assertFalse(RcsDirectSip.isRegistered())+    }++    @Test fun registerRejected403FailsStart() = runBlocking {+        withPcscf(handler = { "SIP/2.0 403 Forbidden" }) { pcscf ->+            assertFalse(RcsDirectSip.start(context, 1))+            assertFalse(RcsDirectSip.isRegistered())+            assertTrue(pcscf.done.await(15, TimeUnit.SECONDS), "requests=${pcscf.requests}")+            assertTrue(pcscf.requests.first().contains("REGISTER"))+        }+    }++    @Test fun challengeWithoutAkaFailsStart() = runBlocking {+        withPcscf(+            handler = { request ->+                if (request.contains("Authorization:")) "SIP/2.0 200 OK"+                else "SIP/2.0 401 Unauthorized\r\nWWW-Authenticate: Digest realm=\"rcs\", nonce=\"abc123\", algorithm=MD5, qop=\"auth\""+            },+        ) { pcscf ->+            // No Telephony shadow here: getIccAuthentication returns null, so+            // the AKA challenge cannot be answered and start must fail.+            assertFalse(RcsDirectSip.start(context, 1))+            assertFalse(RcsDirectSip.isRegistered())+            assertTrue(pcscf.done.await(15, TimeUnit.SECONDS), "requests=${pcscf.requests}")+            // Only the initial REGISTER was sent (plus stop()'s deregister).+            assertTrue(pcscf.requests.none { it.contains("Authorization:") }, "${pcscf.requests}")+        }+    }++    @Test fun messageErrorResponseFailsSendAndStopDeregisters() = runBlocking {+        var sawMessage = false+        withPcscf(+            handler = { request ->+                when {+                    request.startsWith("MESSAGE") -> {+                        sawMessage = true+                        "SIP/2.0 404 Not Found"+                    }+                    request.contains("Expires: 0") -> "SIP/2.0 200 OK"+                    else -> "SIP/2.0 200 OK\r\nContact: <sip:127.0.0.1:5060>;expires=600\r\nExpires: 600"+                }+            },+        ) { pcscf ->+            assertTrue(RcsDirectSip.start(context, 1))+            assertTrue(RcsDirectSip.isRegistered())+            assertFalse(+                RcsDirectSip.sendMessage(+                    "MESSAGE sip:peer@rcs SIP/2.0",+                    "To: <sip:peer@rcs>\r\nContent-Type: message/cpim\r\n",+                    "hello".toByteArray(Charsets.UTF_8),+                ),+            )+            assertTrue(sawMessage)+            RcsDirectSip.stop()+            assertFalse(RcsDirectSip.isRegistered())+            assertTrue(pcscf.done.await(15, TimeUnit.SECONDS), "requests=${pcscf.requests}")+            assertTrue(pcscf.requests.any { it.contains("Expires: 0") }, "${pcscf.requests}")+            assertEquals(3, pcscf.requests.size)+        }+    }+}
communicate/src/test/java/com/vayunmathur/communicate/rcs/GbaBootstrapRcsPass3Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/rcs/GbaBootstrapRcsPass3Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/rcs/GbaBootstrapRcsPass3Test.ktnew file mode 100644index 0000000000..10bd7ebab7--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/rcs/GbaBootstrapRcsPass3Test.kt@@ -0,0 +1,42 @@+package com.vayunmathur.communicate.rcs++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.communicate.data.rcs.RcsGbaBootstrap+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.shadows.ShadowSubscriptionManager+import kotlin.test.AfterTest+import kotlin.test.Test+import kotlin.test.assertNull++/**+ * Pass 3: GBA bootstrap fail-fast guards. The modem round trip itself+ * (TelephonyManager.bootstrapAuthenticationRequest, reached+ * reflectively by production) silently no-ops under Robolectric —+ * neither the default shadow nor an exact-signature custom shadow+ * receives the reflective call — so onKeysAvailable delivery cannot+ * be driven on the JVM; that path is exercised on-device only.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class GbaBootstrapRcsPass3Test {+    private val context: Context get() = ApplicationProvider.getApplicationContext()++    @AfterTest fun tearDown() {+        ShadowSubscriptionManager.setDefaultSmsSubscriptionId(-1)+    }++    @Test fun blankUrlFailsFast() = runBlocking {+        ShadowSubscriptionManager.setDefaultSmsSubscriptionId(1)+        assertNull(RcsGbaBootstrap.bootstrap(context, "", force = false))+        assertNull(RcsGbaBootstrap.bootstrap(context, "   ", force = true))+    }++    @Test fun invalidSubscriptionFailsFast() = runBlocking {+        ShadowSubscriptionManager.setDefaultSmsSubscriptionId(-1)+        assertNull(RcsGbaBootstrap.bootstrap(context, "https://naf.example.com", force = false))+    }+}
communicate/src/test/java/com/vayunmathur/communicate/rcs/HiddenApiRcsPass3Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/rcs/HiddenApiRcsPass3Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/rcs/HiddenApiRcsPass3Test.ktnew file mode 100644index 0000000000..2a87176438--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/rcs/HiddenApiRcsPass3Test.kt@@ -0,0 +1,156 @@+package com.vayunmathur.communicate.rcs++import android.content.Context+import android.net.Uri+import android.telephony.ims.RcsClientConfiguration+import android.telephony.ims.`ProvisioningManager$RcsProvisioningCallback`+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.communicate.data.rcs.RcsHiddenApi+import com.vayunmathur.communicate.data.rcs.RcsMsrp+import com.vayunmathur.communicate.data.rcs.RcsSession+import java.net.ServerSocket+import java.net.Socket+import java.util.concurrent.CopyOnWriteArrayList+import java.util.concurrent.Executors+import java.util.concurrent.TimeUnit+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Pass 3: the hidden-API reflection bridge against hand-written fake+ * framework objects (UCE capability callbacks via dynamic proxy,+ * provisioning callback via the concrete stub subclass), plus MSRP+ * connection failure edges over loopback sockets.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class HiddenApiRcsPass3Test {+    private val context: Context get() = ApplicationProvider.getApplicationContext()+    private val executor = Executors.newSingleThreadExecutor()++    @Test fun uceBridgeFailsClosedWithoutAdapterMethods() {+        val callback = object : RcsHiddenApi.UceCallback {+            override fun onCapabilitiesReceived(caps: List<*>) {}+            override fun onComplete() {}+            override fun onError(errorCode: Int, retryAfterMillis: Long) {}+        }+        // No reflective requestCapabilities/requestAvailability methods here.+        assertFalse(RcsHiddenApi.requestUceCapabilities(Any(), emptyList(), executor, callback))+        assertFalse(+            RcsHiddenApi.requestUceAvailability(Any(), Uri.parse("tel:+15550007002"), executor, callback),+        )+    }++    /** Stands in for ProvisioningManager (matched reflectively). */+    class FakeProvisioningManager {+        var config: RcsClientConfiguration? = null+        var callback: `ProvisioningManager$RcsProvisioningCallback`? = null+        var unregisteredWith: Any? = null+        fun setRcsClientConfiguration(config: RcsClientConfiguration) { this.config = config }+        fun registerRcsProvisioningCallback(+            executor: java.util.concurrent.Executor,+            callback: `ProvisioningManager$RcsProvisioningCallback`,+        ) { this.callback = callback }+        fun unregisterRcsProvisioningCallback(callback: `ProvisioningManager$RcsProvisioningCallback`) {+            unregisteredWith = callback+        }+        fun isRcsVolteSingleRegistrationCapable(): Boolean = true+    }++    class ThrowingProvisioningManager {+        fun isRcsVolteSingleRegistrationCapable(): Boolean = throw RuntimeException("dead")+    }++    @Test fun provisioningCallbackSubclassForwardsEvents() {+        val pm = FakeProvisioningManager()+        var changed: ByteArray? = null+        var resets = 0+        var removed = 0+        val callback = object : RcsHiddenApi.ProvisioningCallback {+            override fun onConfigurationChanged(configXml: ByteArray) { changed = configXml }+            override fun onConfigurationReset() { resets++ }+            override fun onRemoved() { removed++ }+        }+        assertTrue(RcsHiddenApi.registerProvisioningCallback(pm, executor, "6.0", "UP_2.0", callback))+        assertNotNull(pm.config)+        val subclass = pm.callback+        assertNotNull(subclass)+        subclass.onConfigurationChanged("<rcs/>".toByteArray())+        assertEquals("<rcs/>", changed?.toString(Charsets.UTF_8))+        subclass.onConfigurationReset()+        subclass.onRemoved()+        assertEquals(1, resets)+        assertEquals(1, removed)+        // Unregister without a proxy is a no-op; with one it dispatches.+        RcsHiddenApi.unregisterProvisioningCallback(pm)+        RcsHiddenApi.unregisterProvisioningCallback(pm, subclass)+        // Single-reg tri-state.+        assertEquals(true, RcsHiddenApi.isSingleRegCapable(pm))+        assertNull(RcsHiddenApi.isSingleRegCapable(ThrowingProvisioningManager()))+        assertNull(RcsHiddenApi.isSingleRegCapable(Any()))+        // The reflective delegate-manager lookup resolves under Robolectric.+        assertNotNull(RcsHiddenApi.sipDelegateManager(context, 1))+    }++    @Test fun msrpConnectRefusedAndSendEdges() = runBlocking {+        // No listener: connect fails closed.+        val dead = RcsSession(+            dialogId = "d-ms", callId = "ms-1", localTag = "lt", remoteTag = "rt",+            remoteUri = "sip:+15550007009@rcs", conversationId = "ms-conv",+            msrpRemotePath = "msrp://127.0.0.1:1/dead;tcp",+            msrpLocalPath = "msrp://127.0.0.1/local;tcp",+        )+        assertNull(RcsMsrp.connect(dead, context) { _, _ -> })+        // No remote path at all.+        assertNull(RcsMsrp.connect(dead.copy(msrpRemotePath = null), context) { _, _ -> })++        // Loopback pair: SEND round trip in both directions.+        val server = ServerSocket(0)+        try {+            val port = server.localPort+            val clientSession = dead.copy(+                dialogId = "d-ms2", callId = "ms-2",+                msrpRemotePath = "msrp://127.0.0.1:$port/peer;tcp",+            )+            val receivedByServer = CopyOnWriteArrayList<ByteArray>()+            val acceptedRef = java.util.concurrent.atomic.AtomicReference<RcsMsrp.MsrpConnection>()+            val acceptThread = Thread {+                runCatching {+                    val socket: Socket = server.accept()+                    val conn = RcsMsrp.wrapAccepted(+                        socket,+                        com.vayunmathur.communicate.data.rcs.RcsMsrpListen.AcceptedHead(emptyList()),+                        "msrp://127.0.0.1:$port/peer;tcp",+                        "msrp://127.0.0.1/local;tcp",+                    ) { _, body -> receivedByServer += body }+                    acceptedRef.set(conn)+                }+            }.apply { isDaemon = true; start() }++            val conn = RcsMsrp.connect(clientSession, context) { _, _ -> }+            assertNotNull(conn)+            assertTrue(conn.sendCpim("hello msrp".toByteArray()))+            val deadline = System.currentTimeMillis() + 10_000+            while (receivedByServer.isEmpty() && System.currentTimeMillis() < deadline) Thread.sleep(10)+            assertEquals("hello msrp", receivedByServer.firstOrNull()?.toString(Charsets.UTF_8))+            // Empty payload and closed connection refuse to send.+            assertFalse(conn.sendCpim(ByteArray(0)))+            conn.close()+            assertTrue(conn.isClosed())+            assertFalse(conn.sendCpim("late".toByteArray()))+            acceptedRef.get()?.close()+            acceptThread.join(TimeUnit.SECONDS.toMillis(5))+        } finally {+            server.close()+        }+    }+}
communicate/src/test/java/com/vayunmathur/communicate/rcs/MlsLifecycleRcsPass3Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/rcs/MlsLifecycleRcsPass3Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/rcs/MlsLifecycleRcsPass3Test.ktnew file mode 100644index 0000000000..daaf6e7511--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/rcs/MlsLifecycleRcsPass3Test.kt@@ -0,0 +1,252 @@+package com.vayunmathur.communicate.rcs++import android.content.Context+import androidx.room3.Room+import androidx.sqlite.driver.bundled.BundledSQLiteDriver+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.communicate.data.rcs.RcsDatabase+import com.vayunmathur.communicate.data.rcs.RcsSipTransport+import com.vayunmathur.communicate.data.rcs.e2e.RcsE2E+import com.vayunmathur.communicate.data.rcs.e2e.RcsKeyDirectory+import com.vayunmathur.communicate.data.rcs.e2e.RcsPeerKeys+import com.vayunmathur.communicate.data.rcs.e2e.RustMlsCrypto+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Pass 3: the native MLS lifecycle directly and as a three-device group —+ * identity/key-package/group/join/encrypt/decrypt/remove — plus the+ * transport-mediated setup helpers through the fake-sender seam.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class MlsLifecycleRcsPass3Test {++    private val context: Context get() = ApplicationProvider.getApplicationContext()+    private lateinit var deviceA: RcsDatabase+    private lateinit var deviceB: RcsDatabase+    private lateinit var deviceC: RcsDatabase++    private fun newDb(): RcsDatabase =+        Room.inMemoryDatabaseBuilder(context, RcsDatabase::class.java)+            .setDriver(BundledSQLiteDriver())+            .allowMainThreadQueries()+            .build()++    private suspend fun <T> onDevice(db: RcsDatabase, block: suspend () -> T): T {+        RcsDatabase.overrideForTest = db+        try {+            return block()+        } finally {+            RcsDatabase.overrideForTest = deviceA+        }+    }++    private val sent = mutableListOf<Triple<String, String, ByteArray>>()++    @BeforeTest fun setUp() {+        deviceA = newDb(); deviceB = newDb(); deviceC = newDb()+        RcsDatabase.overrideForTest = deviceA+        RcsPeerKeys.clear()+        sent.clear()+    }++    @AfterTest fun tearDown() {+        RcsSipTransport.fakeSenderForTest = null+        RcsDatabase.overrideForTest = null+        deviceA.close(); deviceB.close(); deviceC.close()+        RcsPeerKeys.clear()+    }++    @Test fun directNativeLifecycleAndKindProbes() {+        if (!RustMlsCrypto.isAvailable) {+            // Fail-closed probes without the library.+            assertEquals(2, runCatching { RustMlsCrypto.payloadKind(byteArrayOf(1)) }.getOrElse { 2 })+            return+        }+        val aId = RustMlsCrypto.generateIdentity("+15550002001".toByteArray())?.getOrNull(1)+        val bId = RustMlsCrypto.generateIdentity("+15550002002".toByteArray())?.getOrNull(1)+        assertNotNull(aId); assertNotNull(bId)++        val bPkg = RustMlsCrypto.buildKeyPackage(ByteArray(0), bId)+        assertNotNull(bPkg)+        val (bStorage, kpB) = bPkg[0] to bPkg[1]++        val created = RustMlsCrypto.createGroup(ByteArray(0), aId)+        assertNotNull(created)+        var aStorage = created[0]+        val groupId = created[1]+        assertTrue(groupId.isNotEmpty())++        val added = RustMlsCrypto.addMembers(aStorage, aId, groupId, arrayOf(kpB))+        assertNotNull(added)+        aStorage = added[0]+        val commit = added[1]+        val welcome = added[2]++        // Framing probes: welcome kind 0, ciphertext kind 1, junk kind 2.+        assertEquals(0, RustMlsCrypto.payloadKind(welcome))+        assertEquals(2, RustMlsCrypto.payloadKind(byteArrayOf(0, 1, 2, 3)))+        val welcomeMagic = RustMlsCrypto.welcomeMagic()+        assertNotNull(welcomeMagic)+        assertTrue(welcome.copyOf(welcomeMagic.size).contentEquals(welcomeMagic))++        val joined = RustMlsCrypto.joinGroup(bStorage, welcome)+        assertNotNull(joined)+        var bStorageNow = joined[0]+        assertEquals(groupId.toList(), joined[1].toList())++        val encrypted = RustMlsCrypto.encrypt(aStorage, aId, groupId, "direct hello".toByteArray())+        assertNotNull(encrypted)+        aStorage = encrypted[0]+        val payload = encrypted[1]+        assertEquals(1, RustMlsCrypto.payloadKind(payload))+        val messageMagic = RustMlsCrypto.messageMagic()+        assertNotNull(messageMagic)+        assertTrue(payload.copyOf(messageMagic.size).contentEquals(messageMagic))++        val decrypted = RustMlsCrypto.decrypt(bStorageNow, groupId, payload)+        assertNotNull(decrypted)+        bStorageNow = decrypted[0]+        assertEquals(1.toByte(), decrypted[1].firstOrNull())+        assertEquals("direct hello", decrypted[2].toString(Charsets.UTF_8))++        // Removing leaf 1 (B) yields a commit; afterwards B cannot read new+        // ciphertext, whether or not its crate accepts merging the removal+        // commit (a removed member is outside the new epoch either way).+        val removed = RustMlsCrypto.removeMembers(aStorage, aId, groupId, "1".toByteArray(Charsets.US_ASCII))+        assertNotNull(removed)+        aStorage = removed[0]+        // The raw commit lacks the message framing, so the crate may throw+        // here rather than return null; RcsE2E.decryptFor runCatches this.+        val merged = runCatching { RustMlsCrypto.decrypt(bStorageNow, groupId, removed[1]) }.getOrNull()+        if (merged != null) {+            assertEquals(0.toByte(), merged[1].firstOrNull())+            bStorageNow = merged[0]+        }+        val afterRemoval = RustMlsCrypto.encrypt(aStorage, aId, groupId, "after removal".toByteArray())+        assertNotNull(afterRemoval)+        assertNull(runCatching { RustMlsCrypto.decrypt(bStorageNow, groupId, afterRemoval[1]) }.getOrNull())++        // Garbage inputs fail closed (null, or a native error the Kotlin+        // layer converts to null).+        assertNull(runCatching { RustMlsCrypto.joinGroup(ByteArray(0), byteArrayOf(1, 2, 3)) }.getOrNull())+        assertNull(runCatching { RustMlsCrypto.decrypt(bStorageNow, groupId, byteArrayOf(4, 5, 6)) }.getOrNull())+        assertNull(runCatching { RustMlsCrypto.encrypt(ByteArray(0), aId, groupId, byteArrayOf(1)) }.getOrNull())+    }++    @Test fun threeDeviceGroupCreateJoinDecryptAndRemove() = runTest {+        if (!RustMlsCrypto.isAvailable) return@runTest+        val meA = "+15550002001"+        val meB = "+15550002002"+        val meC = "+15550002003"+        val groupConv = "group-pass3"++        val kpB = onDevice(deviceB) {+            RcsE2E.identityFor(context, meB)+            RcsE2E.freshKeyPackage(context, meB)+        }+        val kpC = onDevice(deviceC) {+            RcsE2E.identityFor(context, meC)+            RcsE2E.freshKeyPackage(context, meC)+        }+        assertNotNull(kpB); assertNotNull(kpC)++        val created = RcsE2E.createEncryptedGroup(context, meA, groupConv, listOf(kpB, kpC))+        assertNotNull(created)+        val (_, welcome) = created++        val gidB = onDevice(deviceB) { RcsE2E.joinEncryptedGroup(context, groupConv, welcome) }+        val gidC = onDevice(deviceC) { RcsE2E.joinEncryptedGroup(context, groupConv, welcome) }+        assertNotNull(gidB); assertNotNull(gidC)+        assertEquals(gidB.toList(), gidC.toList())++        // A broadcasts; both joiners read it.+        val payload = RcsE2E.encryptTo(context, meA, groupConv, "hi all".toByteArray())+        assertNotNull(payload)+        val readB = onDevice(deviceB) { RcsE2E.decryptFor(context, groupConv, payload) }+        val readC = onDevice(deviceC) { RcsE2E.decryptFor(context, groupConv, payload) }+        assertEquals("hi all", readB?.first?.toString(Charsets.UTF_8))+        assertEquals("hi all", readC?.first?.toString(Charsets.UTF_8))++        // Removal through the E.164 map on a second tracked group: no+        // transport, so the commit cannot be delivered and the call reports+        // false, but the member map is still pruned locally. Fresh key+        // packages: the ones above were consumed by the first group.+        val kpB2 = onDevice(deviceB) { RcsE2E.freshKeyPackage(context, meB) }+        val kpC2 = onDevice(deviceC) { RcsE2E.freshKeyPackage(context, meC) }+        assertNotNull(kpB2); assertNotNull(kpC2)+        val trackedConv = "group-pass3-tracked"+        RcsE2E.setupEncryptedGroup(context, meA, trackedConv, mapOf(meB to kpB2, meC to kpC2))+        assertEquals(1, RcsE2E.leafIndexFor(context, trackedConv, meB) ?: -1)+        assertNotNull(RcsE2E.leafIndexFor(context, trackedConv, meC))+        val removed = RcsE2E.removeMembersByE164(context, meA, trackedConv, listOf(meC, "+15559999999"))+        assertFalse(removed) // no transport seam installed in this test+        assertNull(RcsE2E.leafIndexFor(context, trackedConv, meC))+        assertNotNull(RcsE2E.leafIndexFor(context, trackedConv, meB))+        // Removing nobody / unknown groups fails closed.+        assertFalse(RcsE2E.removeMembersByE164(context, meA, trackedConv, emptyList()))+        assertFalse(RcsE2E.removeMembers(context, meA, "no-group", listOf(1)))+        assertFalse(RcsE2E.removeMembers(context, meA, trackedConv, emptyList()))+    }++    @Test fun transportMediatedSetupPublishesAndWelcomes() = runTest {+        if (!RustMlsCrypto.isAvailable) return@runTest+        RcsSipTransport.fakeSenderForTest = { startLine, headers, body ->+            sent += Triple(startLine, headers, body.copyOf())+            true+        }+        val meA = "+15550002001"+        val meB = "+15550002002"++        // Publishing our key package reaches the fake transport and is cached.+        assertTrue(RcsKeyDirectory.publishTo(context, meA, meB))+        assertNotNull(RcsKeyDirectory.lastPublishedFor(meA))+        assertTrue(sent.any { it.second.contains(RcsE2E.CT_KEY_PACKAGE) || String(it.third).contains(RcsE2E.CT_KEY_PACKAGE) })++        // Key-package request flows also succeed with a sender installed.+        assertTrue(RcsE2E.requestKeyPackage(meB))+        assertTrue(RcsE2E.requestEncryptedChat(context, meA, meB))++        // B's package arrives (cached in memory, as the inbound route does),+        // then a full 1:1 setup sends Welcome + commit through the transport.+        val kpB = onDevice(deviceB) {+            RcsE2E.identityFor(context, meB)+            RcsE2E.freshKeyPackage(context, meB)+        }+        assertNotNull(kpB)+        val ok = RcsE2E.setupGroupWithPeer(context, meA, meB, meB, kpB)+        assertTrue(ok)+        assertNotNull(RcsE2E.groupIdFor(context, meB))+        assertNotNull(RcsE2E.leafIndexFor(context, meB, meB))+        val bodies = sent.map { String(it.third) }+        assertTrue(bodies.any { it.contains(RcsE2E.CT_WELCOME) }, "sent kinds: ${sent.size}")+        assertTrue(bodies.any { it.contains(RcsE2E.CT_COMMIT) })+    }++    @Test fun transportRefusalPropagatesAsFalse() = runTest {+        if (!RustMlsCrypto.isAvailable) return@runTest+        RcsSipTransport.fakeSenderForTest = { _, _, _ -> false }+        val meA = "+15550002001"+        val meB = "+15550002002"+        val kpB = onDevice(deviceB) {+            RcsE2E.identityFor(context, meB)+            RcsE2E.freshKeyPackage(context, meB)+        }+        assertNotNull(kpB)+        // The group is created locally, but every send is refused.+        assertFalse(RcsE2E.setupGroupWithPeer(context, meA, meB, meB, kpB))+        assertNotNull(RcsE2E.groupIdFor(context, meB))+        assertFalse(RcsKeyDirectory.publishTo(context, meA, meB))+    }+}
communicate/src/test/java/com/vayunmathur/communicate/rcs/MsrpListenRcsPass3Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/rcs/MsrpListenRcsPass3Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/rcs/MsrpListenRcsPass3Test.ktnew file mode 100644index 0000000000..2203c0031a--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/rcs/MsrpListenRcsPass3Test.kt@@ -0,0 +1,184 @@+package com.vayunmathur.communicate.rcs++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.communicate.data.rcs.RcsImsNetwork+import com.vayunmathur.communicate.data.rcs.RcsMsrpListen+import com.vayunmathur.communicate.data.rcs.RcsMsrpTls+import java.net.Socket+import java.util.concurrent.CopyOnWriteArrayList+import java.util.concurrent.CountDownLatch+import java.util.concurrent.TimeUnit+import javax.net.ssl.SSLSocket+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++/**+ * Pass 3: MSRP listen routing branches not covered by the pass-2 socket+ * tests — plaintext-on-secure rejection, non-MSRP/EOF sockets, 481s,+ * pending-path drops, and full TLS accepts (pinned and on plain paths).+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34], shadows = [RcsSlice3Pass2ImsShadow::class])+class MsrpListenRcsPass3Test {+    private val context: Context get() = ApplicationProvider.getApplicationContext()++    private data class Accepted(val conversationId: String, val socket: Socket, val head: RcsMsrpListen.AcceptedHead)++    private val accepted = CopyOnWriteArrayList<Accepted>()+    private val acceptedLatch = CountDownLatch(1)++    @BeforeTest fun setUp() {+        accepted.clear()+        runBlocking {+            RcsImsNetwork.reset()+            assertTrue(+                RcsMsrpListen.ensureListening(context) { conv, socket, head ->+                    accepted += Accepted(conv, socket, head)+                    acceptedLatch.countDown()+                },+            )+        }+        assertTrue(RcsMsrpListen.isListening())+    }++    @AfterTest fun tearDown() {+        accepted.forEach { runCatching { it.socket.close() } }+        RcsMsrpListen.stop()+        RcsImsNetwork.reset()+    }++    private fun port(): Int = assertNotNull(RcsMsrpListen.listenPort())++    private fun sendRaw(bytes: ByteArray): Socket {+        val socket = Socket("127.0.0.1", port())+        socket.soTimeout = 15_000+        socket.getOutputStream().write(bytes)+        socket.getOutputStream().flush()+        return socket+    }++    private fun sendHead(txid: String, toPath: String?): Socket {+        val head = buildString {+            append("MSRP $txid SEND\r\n")+            if (toPath != null) append("To-Path: $toPath\r\n")+            append("From-Path: msrp://10.0.0.9/peer;tcp\r\n")+            append("Message-ID: m-$txid\r\n")+            append("Content-Type: text/plain\r\n\r\n")+        }+        return sendRaw(head.toByteArray(Charsets.UTF_8))+    }++    private fun readUntilClosed(socket: Socket): String {+        val out = java.io.ByteArrayOutputStream()+        val buf = ByteArray(4096)+        try {+            while (true) {+                val n = socket.getInputStream().read(buf)+                if (n < 0) break+                out.write(buf, 0, n)+                if (out.size() > 8192) break+            }+        } catch (_: Exception) {+            // Timeout/reset also prove the server closed its side.+        }+        return out.toString(Charsets.UTF_8)+    }++    @Test fun acceptedHeadReplayBytes() {+        val head = RcsMsrpListen.AcceptedHead(listOf("MSRP t SEND", "To-Path: msrp://x/y;tcp"))+        assertEquals(+            "MSRP t SEND\r\nTo-Path: msrp://x/y;tcp\r\n\r\n",+            head.replayBytes().toString(Charsets.UTF_8),+        )+        assertEquals("\r\n", RcsMsrpListen.AcceptedHead(emptyList()).replayBytes().toString(Charsets.UTF_8))+    }++    @Test fun plaintextOnSecurePathRejectedSilently() = runBlocking {+        val path = RcsMsrpListen.advertisePath(context, "conv-secure", secure = true) { _, _, _ -> }+        assertNotNull(path)+        val socket = sendHead("txsec", path)+        val response = readUntilClosed(socket)+        // No 481 for downgrade attempts: the socket is simply dropped.+        assertTrue(!response.contains("481"), response)+        assertTrue(accepted.isEmpty())+        socket.close()+    }++    @Test fun unknownAndMissingPathsGet481() {+        val unknown = sendHead("txunk", "msrp://0.0.0.0:${port()}/nope;tcp")+        assertTrue(readUntilClosed(unknown).contains("MSRP txunk 481"))+        unknown.close()+        val missing = sendHead("txmiss", null)+        assertTrue(readUntilClosed(missing).contains("MSRP txmiss 481"))+        missing.close()+        assertTrue(accepted.isEmpty())+    }++    @Test fun nonMsrpAndEofSocketsDroppedListenerSurvives() {+        val http = sendRaw("GET / HTTP/1.1\r\nHost: x\r\n\r\n".toByteArray())+        readUntilClosed(http)+        http.close()+        val eof = Socket("127.0.0.1", port())+        eof.close()+        // Listener still works afterwards.+        assertTrue(RcsMsrpListen.isListening())+        assertTrue(accepted.isEmpty())+    }++    @Test fun droppedPendingPathNoLongerMatches() = runBlocking {+        val path = RcsMsrpListen.advertisePath(context, "conv-drop") { _, _, _ -> }+        assertNotNull(path)+        RcsMsrpListen.notePeerFingerprint("conv-drop", "AA:BB")+        RcsMsrpListen.dropPending("conv-drop")+        val socket = sendHead("txdrop", path)+        assertTrue(readUntilClosed(socket).contains("MSRP txdrop 481"))+        socket.close()+        assertTrue(accepted.isEmpty())+    }++    @Test fun tlsAcceptOnSecurePath() = runBlocking {+        val path = RcsMsrpListen.advertisePath(context, "conv-tls", secure = true) { _, _, _ -> }+        assertNotNull(path)+        val serverIdentity = RcsMsrpTls.ensureIdentity(context)+        assertNotNull(serverIdentity)+        val ssl = RcsMsrpTls.clientSocket(context, "127.0.0.1", port(), serverIdentity.fingerprint)+        assertNotNull(ssl)+        ssl.getOutputStream().write(+            ("MSRP txtls SEND\r\nTo-Path: $path\r\nFrom-Path: msrps://10.0.0.9/peer;tcp\r\n\r\n")+                .toByteArray(Charsets.UTF_8),+        )+        ssl.getOutputStream().flush()+        assertTrue(acceptedLatch.await(15, TimeUnit.SECONDS), "no TLS accept")+        val got = accepted.first()+        assertEquals("conv-tls", got.conversationId)+        assertTrue(got.socket is SSLSocket)+        assertTrue(got.head.lines.first().startsWith("MSRP txtls SEND"))+        ssl.close()+    }++    @Test fun tlsOnPlainPathAcceptedAnyway() = runBlocking {+        val path = RcsMsrpListen.advertisePath(context, "conv-plain-tls", secure = false) { _, _, _ -> }+        assertNotNull(path)+        val serverIdentity = RcsMsrpTls.ensureIdentity(context)+        assertNotNull(serverIdentity)+        val ssl = RcsMsrpTls.clientSocket(context, "127.0.0.1", port(), serverIdentity.fingerprint)+        assertNotNull(ssl)+        ssl.getOutputStream().write(+            ("MSRP txtls2 SEND\r\nTo-Path: $path\r\nFrom-Path: msrps://10.0.0.9/peer;tcp\r\n\r\n")+                .toByteArray(Charsets.UTF_8),+        )+        ssl.getOutputStream().flush()+        assertTrue(acceptedLatch.await(15, TimeUnit.SECONDS), "no TLS-on-plain accept")+        assertEquals("conv-plain-tls", accepted.first().conversationId)+        ssl.close()+    }+}
communicate/src/test/java/com/vayunmathur/communicate/rcs/SessionAcceptRcsPass3Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/rcs/SessionAcceptRcsPass3Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/rcs/SessionAcceptRcsPass3Test.ktnew file mode 100644index 0000000000..3e44fe4c14--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/rcs/SessionAcceptRcsPass3Test.kt@@ -0,0 +1,189 @@+package com.vayunmathur.communicate.rcs++import android.content.Context+import androidx.room3.Room+import androidx.sqlite.driver.bundled.BundledSQLiteDriver+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.communicate.data.rcs.RcsDatabase+import com.vayunmathur.communicate.data.rcs.RcsImsNetwork+import com.vayunmathur.communicate.data.rcs.RcsMsrpListen+import com.vayunmathur.communicate.data.rcs.RcsSession+import com.vayunmathur.communicate.data.rcs.RcsSessionManager+import com.vayunmathur.communicate.data.rcs.RcsSipTransport+import com.vayunmathur.communicate.data.rcs.MsrpSetup+import com.vayunmathur.communicate.telephony.onMsrpAccepted+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import java.net.ServerSocket+import java.net.Socket+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Pass 3: incoming-session acceptance (passive/TLS answer branches),+ * current-SDP rendering, and the sync service's passive MSRP accept.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34], shadows = [RcsSlice3Pass2ImsShadow::class])+class SessionAcceptRcsPass3Test {+    private val context: Context get() = ApplicationProvider.getApplicationContext()+    private lateinit var testDb: RcsDatabase+    private val sent = mutableListOf<Triple<String, String, ByteArray>>()+    private var sendResult = true++    @BeforeTest fun setUp() {+        testDb = Room.inMemoryDatabaseBuilder(context, RcsDatabase::class.java)+            .setDriver(BundledSQLiteDriver())+            .allowMainThreadQueries()+            .build()+        RcsDatabase.overrideForTest = testDb+        sent.clear()+        sendResult = true+        RcsSipTransport.fakeSenderForTest = { startLine, headers, body ->+            sent += Triple(startLine, headers, body.copyOf())+            sendResult+        }+        RcsSessionManager.sessionsMutable.value = emptyMap()+        RcsSessionManager.listenContextProvider = { context }+    }++    @AfterTest fun tearDown() {+        RcsMsrpListen.stop()+        RcsImsNetwork.reset()+        RcsSessionManager.listenContextProvider = null+        RcsSipTransport.fakeSenderForTest = null+        RcsDatabase.overrideForTest = null+        testDb.close()+        RcsSessionManager.sessionsMutable.value = emptyMap()+    }++    private fun session(+        conversationId: String,+        localPath: String? = null,+        setup: MsrpSetup? = null,+        secure: Boolean = false,+    ) = RcsSession(+        dialogId = "d-$conversationId", callId = "call-$conversationId",+        localTag = "lt", remoteTag = "rt", remoteUri = "sip:$conversationId@rcs",+        conversationId = conversationId,+        msrpLocalPath = localPath, msrpSetup = setup, msrpSecure = secure,+    )++    @Test fun currentSdpVariants() {+        assertNull(RcsSessionManager.currentSdpFor("missing"))+        RcsSessionManager.sessionsMutable.value = mapOf(+            "c-nopath" to session("c-nopath"),+            "c-tls" to session("c-tls", "msrp://10.0.0.1:9999/x;tcp", MsrpSetup.ACTIVE, secure = true),+            "c-plain" to session("c-plain", "msrp://10.0.0.1/x;tcp"),+        )+        assertNull(RcsSessionManager.currentSdpFor("c-nopath"))+        val tls = String(RcsSessionManager.currentSdpFor("c-tls")!!, Charsets.UTF_8)+        assertTrue(tls.contains("9999 TCP/TLS/MSRP"), tls)+        assertTrue(tls.contains("a=setup:passive"), tls)+        assertTrue(tls.contains("a=path:msrp://10.0.0.1:9999/x;tcp"), tls)+        val plain = String(RcsSessionManager.currentSdpFor("c-plain")!!, Charsets.UTF_8)+        assertTrue(plain.contains("2855 TCP/MSRP"), plain)+        assertTrue(plain.contains("a=setup:active"), plain)+    }++    @Test fun acceptIncomingUnknownAndTransportRefusal() = runBlocking {+        assertEquals(false, RcsSessionManager.acceptIncoming("nope"))+        // Incoming session stashed by an INVITE request, then accepted.+        val sdp = "v=0\r\nm=message 2855 TCP/MSRP *\r\na=path:msrp://10.0.0.9:2855/p;tcp\r\na=setup:passive\r\n"+        RcsSessionManager.onSipRequest(+            "INVITE", "call-acc@h", "sip:+15550006001@rcs", "application/sdp", sdp, "tag1",+        )+        assertNotNull(RcsSessionManager.sessionFor("+15550006001"))+        sendResult = false+        assertEquals(false, RcsSessionManager.acceptIncoming("+15550006001"))+        sendResult = true+        assertEquals(true, RcsSessionManager.acceptIncoming("+15550006001"))+        assertTrue(sent.any { it.first == "SIP/2.0 200 OK" })+    }++    @Test fun acceptIncomingPassiveWhenOfferActiveAndListening() = runBlocking {+        // Start the passive listener so listenPathFor can advertise a path.+        RcsMsrpListen.ensureListening(context) { _, _, _ -> }+        assertTrue(RcsMsrpListen.isListening())+        val sdp = "v=0\r\nm=message 2855 TCP/MSRP *\r\na=path:msrp://10.0.0.9:2855/p;tcp\r\na=setup:active\r\n"+        RcsSessionManager.onSipRequest(+            "INVITE", "call-passive@h", "sip:+15550006002@rcs", "application/sdp", sdp, "tag2",+        )+        val ok = RcsSessionManager.acceptIncoming("+15550006002")+        assertTrue(ok)+        val answer = sent.firstOrNull { it.first == "SIP/2.0 200 OK" }+        assertNotNull(answer)+        val body = String(answer.third, Charsets.UTF_8)+        // Listening answer offers our own path with setup:passive.+        assertTrue(body.contains("a=setup:passive") || body.contains("a=path:msrp"), body)+    }++    @Test fun acceptIncomingSecureOfferDowngradesOrPinsTls() = runBlocking {+        RcsMsrpListen.ensureListening(context) { _, _, _ -> }+        val sdp = "v=0\r\nm=message 2855 TCP/TLS/MSRP *\r\na=path:msrps://10.0.0.9:2855/p;tcp\r\n" ++            "a=setup:active\r\na=fingerprint:SHA-256 AA:BB:CC:DD:EE:FF:00:11:22:33:44:55:66:77:88:99:" ++            "AA:BB:CC:DD:EE:FF:00:11:22:33:44:55:66:77:88:99\r\n"+        RcsSessionManager.onSipRequest(+            "INVITE", "call-tls@h", "sip:+15550006003@rcs", "application/sdp", sdp, "tag3",+        )+        val ok = RcsSessionManager.acceptIncoming("+15550006003")+        assertTrue(ok)+        val answer = sent.firstOrNull { it.first == "SIP/2.0 200 OK" }+        assertNotNull(answer)+        // Either a pinned TLS answer (fingerprint) or the plaintext downgrade;+        // both are valid dialogs and must carry an SDP body.+        assertTrue(String(answer.third, Charsets.UTF_8).contains("m=message"))+    }++    @Test fun declineIncomingRemovesSession() = runBlocking {+        val sdp = "v=0\r\nm=message 2855 TCP/MSRP *\r\na=path:msrp://10.0.0.9:2855/p;tcp\r\n"+        RcsSessionManager.onSipRequest(+            "INVITE", "call-dec@h", "sip:+15550006004@rcs", "application/sdp", sdp, "tag4",+        )+        assertNotNull(RcsSessionManager.sessionFor("+15550006004"))+        RcsSessionManager.declineIncoming("+15550006004")+        assertNull(RcsSessionManager.sessionFor("+15550006004"))+    }++    @Test fun onMsrpAcceptedRegistersConnectionAndFeedsChunks() = runBlocking {+        // Session for the conversation (as an INVITE would have stashed).+        RcsSessionManager.sessionsMutable.value = mapOf(+            "+15550006005" to session("+15550006005", "msrp://127.0.0.1:1/local;tcp"),+        )+        val service = Robolectric.setupService(com.vayunmathur.communicate.telephony.RcsSyncService::class.java)+        val server = ServerSocket(0)+        try {+            val client = Socket("127.0.0.1", server.localPort)+            val accepted = server.accept()+            val head = RcsMsrpListen.AcceptedHead(+                listOf(+                    "MSRP tx-accept SEND",+                    "To-Path: msrp://127.0.0.1:1/local;tcp",+                    "From-Path: msrp://127.0.0.1:2/peer;tcp",+                    "Byte-Range: 1-5/5",+                    "Content-Type: text/plain",+                ),+            )+            service.onMsrpAccepted("+15550006005", accepted, head)+            assertTrue(service.msrpConnections.containsKey("+15550006005"))+            // Unknown conversation: socket is closed, nothing registered.+            val client2 = Socket("127.0.0.1", server.localPort)+            val accepted2 = server.accept()+            service.onMsrpAccepted("+19999999", accepted2, head)+            assertTrue(!service.msrpConnections.containsKey("+19999999"))+            client.close()+            client2.close()+        } finally {+            server.close()+            service.onDestroy()+        }+    }+}
communicate/src/test/java/com/vayunmathur/communicate/telephony/InboundAsyncRcsPass3Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/telephony/InboundAsyncRcsPass3Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/telephony/InboundAsyncRcsPass3Test.ktnew file mode 100644index 0000000000..b4367c75c1--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/telephony/InboundAsyncRcsPass3Test.kt@@ -0,0 +1,182 @@+package com.vayunmathur.communicate.telephony++import androidx.room3.Room+import androidx.sqlite.driver.bundled.BundledSQLiteDriver+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.communicate.data.rcs.RcsCachedMessage+import com.vayunmathur.communicate.data.rcs.RcsDatabase+import com.vayunmathur.communicate.data.rcs.buildEditBody+import com.vayunmathur.communicate.data.rcs.buildGeopushBody+import com.vayunmathur.communicate.data.rcs.buildRevokeBody+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Pass 3: parseInbound's side-effecting routes — revoke/edit applied to+ * cached rows on the service scope, geopush rows, large-message chunk+ * reassembly through the SIP path, FT descriptors, IMDN receipts.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class InboundAsyncRcsPass3Test {+    private val app get() = ApplicationProvider.getApplicationContext<android.app.Application>()+    private lateinit var testDb: RcsDatabase++    @BeforeTest fun setUp() {+        testDb = Room.inMemoryDatabaseBuilder(app, RcsDatabase::class.java)+            .setDriver(BundledSQLiteDriver())+            .allowMainThreadQueries()+            .build()+        RcsDatabase.overrideForTest = testDb+    }++    @AfterTest fun tearDown() {+        RcsDatabase.overrideForTest = null+        testDb.close()+    }++    private fun service() = Robolectric.setupService(RcsSyncService::class.java)++    private fun envelope(raw: String, contentType: String? = "text/plain", callId: String = "c-p3") =+        Envelope(from = "+15550004001", contentType = contentType, raw = raw, callId = callId, viaBranch = "br")++    private fun awaitDb(timeoutMs: Long = 10_000, condition: suspend () -> Boolean) {+        val deadline = System.currentTimeMillis() + timeoutMs+        while (!runBlocking { condition() } && System.currentTimeMillis() < deadline) Thread.sleep(15)+        assertTrue(runBlocking { condition() }, "db condition not met")+    }++    @Test fun revokeBlanksCachedRowAndReturnsReceipt() = runBlocking {+        testDb.cachedMessageDao().upsert(+            RcsCachedMessage(messageId = "orig-1", conversationId = "+15550004001", body = "secret", timestamp = 1, outgoing = false),+        )+        val service = service()+        val parsed = service.parseInbound(envelope(buildRevokeBody("orig-1")))+        assertNotNull(parsed)+        assertEquals(InboundKind.Receipt, parsed.kind)+        awaitDb { testDb.cachedMessageDao().get("orig-1")?.body == "" }+        // Revoking an unknown row still returns a receipt and changes nothing.+        val again = service.parseInbound(envelope(buildRevokeBody("missing-id"), callId = "c-p3b"))+        assertEquals(InboundKind.Receipt, again?.kind)+        service.onDestroy()+    }++    @Test fun editSwapsCachedRowBody() = runBlocking {+        testDb.cachedMessageDao().upsert(+            RcsCachedMessage(messageId = "orig-2", conversationId = "+15550004001", body = "old text", timestamp = 1, outgoing = false),+        )+        val service = service()+        val parsed = service.parseInbound(envelope(buildEditBody("orig-2", "new text")))+        assertEquals(InboundKind.Receipt, parsed?.kind)+        awaitDb { testDb.cachedMessageDao().get("orig-2")?.body == "new text" }+        service.onDestroy()+    }++    @Test fun geopushBecomesLocationRow() {+        val service = service()+        val parsed = service.parseInbound(envelope(buildGeopushBody(37.42, -122.08, "HQ")))+        assertNotNull(parsed)+        assertEquals("HQ", parsed.body)+        assertEquals("geo:37.42,-122.08", parsed.ftUrl)+        assertEquals("application/vnd.gsma.rcs.geopush+xml", parsed.ftMime)+        // Unlabelled push falls back to the coordinate text.+        val plain = service.parseInbound(envelope(buildGeopushBody(1.5, 2.5), callId = "c-geo2"))+        assertEquals("📍 1.5, 2.5", plain?.body)+        service.onDestroy()+    }++    @Test fun largeMessageChunksReassembleInOrder() {+        val service = service()+        // Part 2 arrives first: only a receipt, nothing to show yet.+        val second = service.parseInbound(+            envelope("Message-ID: big-1\r\nPart: 2/2\r\n\r\nworld", callId = "c-chunk2"),+        )+        assertEquals(InboundKind.Receipt, second?.kind)+        val first = service.parseInbound(+            envelope("Message-ID: big-1\r\nPart: 1/2\r\n\r\nhello", callId = "c-chunk1"),+        )+        assertNotNull(first)+        assertEquals(InboundKind.Text, first.kind)+        assertEquals("helloworld", first.body) // parts are trimmed before joining+        assertEquals("in-big-1", first.messageId)+        service.onDestroy()+    }++    @Test fun bufferLargeChunkRejectsBadPartNumbers() {+        assertNull(bufferLargeChunk("conv", "id", 0, 2, "x"))+        assertNull(bufferLargeChunk("conv", "id", 3, 2, "x"))+        assertNull(bufferLargeChunk("conv", "id", 1, 0, "x"))+        assertNull(bufferLargeChunk("conv", "id2", 1, 2, "Message-ID: id2\r\nPart: 1/2\r\n\r\nonly"))+        assertEquals(+            "onlyb",+            bufferLargeChunk("conv", "id2", 2, 2, "Message-ID: id2\r\nPart: 2/2\r\n\r\nb"),+        )+    }++    @Test fun fileTransferDescriptorExposesUrlAndMime() {+        val service = service()+        val body = "File-URL: https://files.example.com/a.jpg\r\nFile-MIME: image/jpeg\r\n\r\nphoto"+        val parsed = service.parseInbound(envelope(body))+        assertNotNull(parsed)+        assertEquals("https://files.example.com/a.jpg", parsed.ftUrl)+        assertEquals("image/jpeg", parsed.ftMime)+        assertTrue(parsed.body.contains("photo"))+        service.onDestroy()+    }++    @Test fun imdnEnvelopeReturnsReceiptAndRecordsDisposition() {+        val service = service()+        val imdn = """+            <?xml version="1.0"?>+            <imdn xmlns="urn:ietf:params:xml:ns:imdn">+              <message-id>orig-9</message-id>+              <status><display/></status>+            </imdn>+        """.trimIndent()+        val parsed = service.parseInbound(+            envelope(imdn, contentType = "message/imdn+xml", callId = "c-imdn"),+        )+        assertEquals(InboundKind.Receipt, parsed?.kind)+        assertEquals(+            com.vayunmathur.communicate.data.rcs.ImdnDisposition.Displayed,+            com.vayunmathur.communicate.data.rcs.RcsImdn.statusFor("orig-9"),+        )+        service.onDestroy()+    }++    @Test fun decodeAndExtractHelpers() {+        // decodePayloadBody: raw, CRLF-wrapped, LF-wrapped, junk.+        assertEquals(+            "hello",+            decodePayloadBody("aGVsbG8=")?.toString(Charsets.UTF_8),+        )+        assertEquals(+            "hello",+            decodePayloadBody("Content-Type: x\r\n\r\naGVsbG8=")?.toString(Charsets.UTF_8),+        )+        assertEquals(+            "hello",+            decodePayloadBody("hdr\n\naGVsbG8=")?.toString(Charsets.UTF_8),+        )+        assertNull(decodePayloadBody("   "))+        assertNull(decodePayloadBody("!!!"))+        // extractTextBody: plain, cpim, blank, cpim without payload.+        assertEquals("plain", extractTextBody("plain".toByteArray()))+        assertNull(extractTextBody("   ".toByteArray()))+        assertNull(extractTextBody("Content-Type: message/cpim\r\n\r\n".toByteArray()))+        assertEquals(+            "inner",+            extractTextBody("Content-Type: message/cpim\r\n\r\nhdr\r\n\r\ninner".toByteArray()),+        )+    }+}
communicate/src/test/java/com/vayunmathur/communicate/telephony/InboundDialogRcsPass3Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/telephony/InboundDialogRcsPass3Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/telephony/InboundDialogRcsPass3Test.ktnew file mode 100644index 0000000000..037169b9f6--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/telephony/InboundDialogRcsPass3Test.kt@@ -0,0 +1,264 @@+package com.vayunmathur.communicate.telephony++import android.telephony.ims.SipMessage+import androidx.room3.Room+import androidx.sqlite.driver.bundled.BundledSQLiteDriver+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.communicate.data.rcs.RcsDatabase+import com.vayunmathur.communicate.data.rcs.RcsSessionManager+import com.vayunmathur.communicate.data.rcs.RcsSipTransport+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Pass 3: inbound SIP dialog methods (INVITE/re-INVITE/BYE/REFER/NOTIFY/+ * SUBSCRIBE/UPDATE/OPTIONS) driven with real [SipMessage] objects through+ * the fake SIP sender, plus the full handleInbound chain reached through+ * the transport's inbound callback.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class InboundDialogRcsPass3Test {+    private val app get() = ApplicationProvider.getApplicationContext<android.app.Application>()+    private lateinit var testDb: RcsDatabase+    private val sent = mutableListOf<Triple<String, String, ByteArray>>()++    @BeforeTest fun setUp() {+        testDb = Room.inMemoryDatabaseBuilder(app, RcsDatabase::class.java)+            .setDriver(BundledSQLiteDriver())+            .allowMainThreadQueries()+            .build()+        RcsDatabase.overrideForTest = testDb+        sent.clear()+        RcsSipTransport.fakeSenderForTest = { startLine, headers, body ->+            sent += Triple(startLine, headers, body.copyOf())+            true+        }+        RcsSessionManager.sessionsMutable.value = emptyMap()+    }++    @AfterTest fun tearDown() {+        RcsSipTransport.fakeSenderForTest = null+        RcsDatabase.overrideForTest = null+        testDb.close()+        RcsSessionManager.sessionsMutable.value = emptyMap()+    }++    private fun service() = Robolectric.setupService(RcsSyncService::class.java)++    private fun sip(+        startLine: String,+        callId: String = "call-p3@host",+        from: String = "<sip:+15550005001@rcs>;tag=ftag1",+        extraHeaders: String = "",+        body: String = "",+        contentType: String? = null,+    ): SipMessage {+        val headers = buildString {+            append("Via: SIP/2.0/TCP 10.0.0.1;branch=z9hG4bKp3\r\n")+            append("From: $from\r\n")+            append("To: <sip:+15550005002@rcs>\r\n")+            append("Call-ID: $callId\r\n")+            append("CSeq: 1 ${startLine.substringBefore(' ')}\r\n")+            if (contentType != null) append("Content-Type: $contentType\r\n")+            append(extraHeaders)+            append("Content-Length: ${body.toByteArray().size}\r\n")+        }+        return SipMessage(startLine, headers, body.toByteArray(Charsets.UTF_8))+    }++    private fun offerSdp(): String =+        "v=0\r\no=- 1 1 IN IP4 10.0.0.1\r\ns=-\r\nc=IN IP4 10.0.0.1\r\nt=0 0\r\n" ++            "m=message 2855 TCP/MSRP *\r\na=path:msrp://10.0.0.1:2855/sess1;tcp\r\na=setup:active\r\n"++    @Test fun inviteWithSdpCreatesSessionAndAccepts() = runBlocking {+        val service = service()+        service.handleInboundInvite(sip("INVITE sip:+15550005002@rcs SIP/2.0", body = offerSdp(), contentType = "application/sdp"))+        val session = RcsSessionManager.sessionFor("+15550005001")+        assertNotNull(session)+        assertEquals("call-p3@host", session.callId)+        assertTrue(sent.any { it.first.startsWith("SIP/2.0 200") }, "sent=${sent.map { it.first }}")+        service.onDestroy()+    }++    @Test fun inviteWithoutSdpDeclines() = runBlocking {+        val service = service()+        service.handleInboundInvite(sip("INVITE sip:+15550005002@rcs SIP/2.0", body = "no sdp here"))+        assertTrue(+            sent.any { it.first.startsWith("SIP/2.0 603") || it.first.startsWith("SIP/2.0 488") },+            "sent=${sent.map { it.first }}",+        )+        service.onDestroy()+    }++    @Test fun inviteWithoutFromIsDropped() = runBlocking {+        val service = service()+        val msg = sip("INVITE sip:x@rcs SIP/2.0", from = "<sip:@rcs>;tag=t", body = offerSdp())+        service.handleInboundInvite(msg)+        assertTrue(sent.isEmpty())+        assertNull(RcsSessionManager.sessionFor(""))+        service.onDestroy()+    }++    @Test fun reInviteOnKnownDialogAnswersWithoutNewSession() = runBlocking {+        val service = service()+        service.handleInboundInvite(sip("INVITE sip:+15550005002@rcs SIP/2.0", body = offerSdp(), contentType = "application/sdp"))+        assertEquals(1, RcsSessionManager.sessions.value.size)+        sent.clear()+        service.handleInboundInvite(+            sip("INVITE sip:+15550005002@rcs SIP/2.0", body = offerSdp(), contentType = "application/sdp"),+        )+        // The re-INVITE is answered on the existing dialog (200 with current+        // SDP, or a decline when the session never produced one) — crucially+        // it must not create a second session entry.+        assertTrue(RcsSessionManager.sessions.value.size <= 1)+        assertTrue(sent.isNotEmpty(), "re-INVITE produced no response: $sent")+        service.onDestroy()+    }++    @Test fun byeTearsDownSession() = runBlocking {+        val service = service()+        service.handleInboundInvite(sip("INVITE sip:+15550005002@rcs SIP/2.0", body = offerSdp(), contentType = "application/sdp"))+        assertNotNull(RcsSessionManager.sessionFor("+15550005001"))+        service.handleInboundBye(sip("BYE sip:+15550005002@rcs SIP/2.0"))+        assertNull(RcsSessionManager.sessionFor("+15550005001"))+        // BYE without Call-ID is ignored (build one with an empty header set).+        service.handleInboundBye(SipMessage("BYE sip:x SIP/2.0", "Via: SIP/2.0/TCP h;branch=z\r\n", ByteArray(0)))+        service.onDestroy()+    }++    @Test fun optionsAnswersWithFeatureTags() = runBlocking {+        val service = service()+        service.handleInboundOptions(sip("OPTIONS sip:+15550005002@rcs SIP/2.0"))+        val ok = sent.firstOrNull { it.first == "SIP/2.0 200 OK" }+        assertNotNull(ok)+        assertTrue(ok.second.contains("Accept-Contact:"))+        service.onDestroy()+    }++    @Test fun notifyReferAndConferencePaths() = runBlocking {+        val service = service()+        // Refer status NOTIFY: parses the sipfrag and answers 200.+        service.handleInboundNotify(+            sip(+                "NOTIFY sip:+15550005002@rcs SIP/2.0",+                extraHeaders = "Event: refer\r\n",+                body = "SIP/2.0 200 OK\r\n",+                contentType = "message/sipfrag",+            ),+        )+        assertTrue(sent.any { it.first == "SIP/2.0 200 OK" }, "sent=${sent.map { it.first }}")+        sent.clear()+        // Conference NOTIFY without a subscription still answers 200.+        service.handleInboundNotify(+            sip(+                "NOTIFY sip:+15550005002@rcs SIP/2.0",+                extraHeaders = "Event: conference\r\n",+                body = "<conference-info xmlns=\"urn:ietf:params:xml:ns:conference-info\"/>",+                contentType = "application/conference-info+xml",+            ),+        )+        assertTrue(sent.any { it.first == "SIP/2.0 200 OK" })+        service.onDestroy()+    }++    @Test fun subscribeConferenceAcceptedAndBadEventRejected() = runBlocking {+        val service = service()+        service.handleInboundSubscribe(+            sip("SUBSCRIBE sip:conf@rcs SIP/2.0", extraHeaders = "Event: conference\r\n"),+        )+        assertTrue(sent.any { it.first.startsWith("SIP/2.0 202") }, "sent=${sent.map { it.first }}")+        sent.clear()+        service.handleInboundSubscribe(+            sip("SUBSCRIBE sip:conf@rcs SIP/2.0", extraHeaders = "Event: presence\r\n"),+        )+        assertTrue(sent.any { it.first.startsWith("SIP/2.0 489") }, "sent=${sent.map { it.first }}")+        service.onDestroy()+    }++    @Test fun updateKnownAndUnknownDialogs() = runBlocking {+        val service = service()+        // Unknown Call-ID: 481.+        service.handleInboundUpdate(sip("UPDATE sip:+15550005002@rcs SIP/2.0", callId = "unknown@host"))+        assertTrue(sent.any { it.first.startsWith("SIP/2.0 481") }, "sent=${sent.map { it.first }}")+        // Known dialog from an INVITE: 200 or 488 depending on SDP state.+        service.handleInboundInvite(sip("INVITE sip:+15550005002@rcs SIP/2.0", body = offerSdp(), contentType = "application/sdp"))+        sent.clear()+        service.handleInboundUpdate(sip("UPDATE sip:+15550005002@rcs SIP/2.0"))+        assertTrue(+            sent.any { it.first.startsWith("SIP/2.0 200") || it.first.startsWith("SIP/2.0 488") },+            "sent=${sent.map { it.first }}",+        )+        service.onDestroy()+    }++    @Test fun referJoinsConferenceAndReportsStatus() = runBlocking {+        val service = service()+        service.handleInboundRefer(+            sip(+                "REFER sip:+15550005002@rcs SIP/2.0",+                extraHeaders = "Refer-To: <sip:[email protected]>\r\n",+            ),+        )+        assertTrue(sent.any { it.first.startsWith("SIP/2.0 202") }, "sent=${sent.map { it.first }}")+        // Status NOTIFY follows (200 when the join leg was accepted).+        assertTrue(sent.any { it.first.startsWith("NOTIFY") }, "sent=${sent.map { it.first }}")+        sent.clear()+        // REFER with no Refer-To goes nowhere.+        service.handleInboundRefer(sip("REFER sip:+15550005002@rcs SIP/2.0", callId = "refer2@host"))+        assertTrue(sent.isEmpty())+        service.onDestroy()+    }++    @Test fun headerValueParsing() {+        val headers = "Via: SIP/2.0/TCP h;branch=z9\r\nfrom: <sip:+1@x>;tag=t\r\nX-Empty: \r\n"+        assertEquals("<sip:+1@x>;tag=t", headerValue(headers, "From:"))+        assertEquals("SIP/2.0/TCP h;branch=z9", headerValue(headers, "Via:"))+        assertNull(headerValue(headers, "Missing:"))+        assertNull(headerValue(headers, "X-Empty:"))+        assertNull(headerValue("", "From:"))+    }++    @Test fun handleInboundThroughTransportCallbackCachesMessage() {+        val service = service()+        // Plain start kicks off registration in the service scope, which+        // installs the inbound callback on the transport.+        assertEquals(android.app.Service.START_STICKY, service.onStartCommand(null, 0, 3))+        val deadline = System.currentTimeMillis() + 15_000+        while (RcsSipTransport.onInboundMessage == null && System.currentTimeMillis() < deadline) {+            Thread.sleep(20)+        }+        val callback = RcsSipTransport.onInboundMessage+        assertNotNull(callback, "inbound callback was never installed")+        // A SIP response start line routes to the response handler, no row.+        callback(SipMessage("SIP/2.0 200 OK", "Via: SIP/2.0/TCP h;branch=z9hG4bKx\r\nCall-ID: cb1@h\r\n", ByteArray(0)))+        // A MESSAGE is parsed and cached into the RCS database.+        callback(+            sip(+                "MESSAGE sip:+15550005002@rcs SIP/2.0",+                callId = "cb-msg@host",+                body = "inbound hello",+                contentType = "text/plain",+            ),+        )+        val dbDeadline = System.currentTimeMillis() + 15_000+        var rows = runBlocking { testDb.cachedMessageDao().getForConversation("+15550005001") }+        while (rows.isEmpty() && System.currentTimeMillis() < dbDeadline) {+            Thread.sleep(25)+            rows = runBlocking { testDb.cachedMessageDao().getForConversation("+15550005001") }+        }+        assertEquals(1, rows.size)+        assertEquals("inbound hello", rows[0].body)+        service.onDestroy()+    }+}
communicate/src/test/java/com/vayunmathur/communicate/telephony/SyncServiceInboundRcsPass3Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/telephony/SyncServiceInboundRcsPass3Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/telephony/SyncServiceInboundRcsPass3Test.ktnew file mode 100644index 0000000000..8c08393d70--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/telephony/SyncServiceInboundRcsPass3Test.kt@@ -0,0 +1,206 @@+package com.vayunmathur.communicate.telephony++import android.telephony.ims.SipMessage+import androidx.room3.Room+import androidx.sqlite.driver.bundled.BundledSQLiteDriver+import androidx.test.core.app.ApplicationProvider+import com.sun.net.httpserver.HttpServer+import com.vayunmathur.communicate.data.rcs.RcsDatabase+import com.vayunmathur.communicate.data.rcs.RcsSession+import com.vayunmathur.communicate.data.rcs.RcsSessionManager+import com.vayunmathur.communicate.data.rcs.RcsSipTransport+import com.vayunmathur.communicate.data.rcs.hostGroupFocus+import com.vayunmathur.communicate.data.rcs.hostGroupFocus+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import java.net.InetSocketAddress+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Pass 3: the private SyncService inbound pipeline reached the way+ * production reaches it — through the transport's inbound callback —+ * covering dialog dispatch, IMDN report sending, FT auto-fetch against+ * a loopback HTTP server, focus relay, and MSRP connection sync.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class SyncServiceInboundRcsPass3Test {+    private val app get() = ApplicationProvider.getApplicationContext<android.app.Application>()+    private lateinit var testDb: RcsDatabase+    private val sent = mutableListOf<Triple<String, String, ByteArray>>()++    @BeforeTest fun setUp() {+        testDb = Room.inMemoryDatabaseBuilder(app, RcsDatabase::class.java)+            .setDriver(BundledSQLiteDriver())+            .allowMainThreadQueries()+            .build()+        RcsDatabase.overrideForTest = testDb+        sent.clear()+        RcsSipTransport.fakeSenderForTest = { startLine, headers, body ->+            sent += Triple(startLine, headers, body.copyOf())+            true+        }+        RcsSessionManager.sessionsMutable.value = emptyMap()+    }++    @AfterTest fun tearDown() {+        RcsSipTransport.fakeSenderForTest = null+        RcsDatabase.overrideForTest = null+        testDb.close()+        RcsSessionManager.sessionsMutable.value = emptyMap()+    }++    private fun sip(+        startLine: String,+        callId: String = "in-p3@host",+        from: String = "<sip:+15550005001@rcs>;tag=ftag1",+        body: String = "",+        contentType: String? = null,+        extraHeaders: String = "",+    ): SipMessage {+        val headers = buildString {+            append("Via: SIP/2.0/TCP 10.0.0.1;branch=z9hG4bKin\r\n")+            append("From: $from\r\n")+            append("To: <sip:+15550005002@rcs>\r\n")+            append("Call-ID: $callId\r\n")+            append("CSeq: 1 ${startLine.substringBefore(' ')}\r\n")+            if (contentType != null) append("Content-Type: $contentType\r\n")+            append(extraHeaders)+            append("Content-Length: ${body.toByteArray().size}\r\n")+        }+        return SipMessage(startLine, headers, body.toByteArray(Charsets.UTF_8))+    }++    /** Starts the service and waits for its inbound callback registration. */+    private fun serviceWithCallback(): RcsSyncService {+        val service = Robolectric.setupService(RcsSyncService::class.java)+        assertEquals(android.app.Service.START_STICKY, service.onStartCommand(null, 0, 3))+        val deadline = System.currentTimeMillis() + 15_000+        while (RcsSipTransport.onInboundMessage == null && System.currentTimeMillis() < deadline) {+            Thread.sleep(20)+        }+        assertNotNull(RcsSipTransport.onInboundMessage, "inbound callback never installed")+        return service+    }++    private fun awaitDb(timeoutMs: Long = 15_000, condition: suspend () -> Boolean) {+        val deadline = System.currentTimeMillis() + timeoutMs+        while (!runBlocking { condition() } && System.currentTimeMillis() < deadline) Thread.sleep(25)+        assertTrue(runBlocking { condition() }, "db condition not met")+    }++    @Test fun dialogMethodsDispatchThroughCallback() {+        val service = serviceWithCallback()+        val callback = RcsSipTransport.onInboundMessage!!+        val offer = "v=0\r\nm=message 2855 TCP/MSRP *\r\na=path:msrp://10.0.0.1:2855/s;tcp\r\n"+        callback(sip("INVITE sip:+15550005002@rcs SIP/2.0", body = offer, contentType = "application/sdp"))+        val deadline = System.currentTimeMillis() + 15_000+        while (RcsSessionManager.sessionFor("+15550005001") == null && System.currentTimeMillis() < deadline) {+            Thread.sleep(25)+        }+        assertNotNull(RcsSessionManager.sessionFor("+15550005001"))+        // OPTIONS through the same dispatch answers 200.+        sent.clear()+        callback(sip("OPTIONS sip:+15550005002@rcs SIP/2.0", callId = "in-opt@host"))+        val optDeadline = System.currentTimeMillis() + 15_000+        while (sent.none { it.first == "SIP/2.0 200 OK" } && System.currentTimeMillis() < optDeadline) {+            Thread.sleep(25)+        }+        assertTrue(sent.any { it.first == "SIP/2.0 200 OK" }, "sent=${sent.map { it.first }}")+        // BYE tears the session down again.+        callback(sip("BYE sip:+15550005002@rcs SIP/2.0", callId = "in-p3@host"))+        val byeDeadline = System.currentTimeMillis() + 15_000+        while (RcsSessionManager.sessionFor("+15550005001") != null && System.currentTimeMillis() < byeDeadline) {+            Thread.sleep(25)+        }+        assertNull(RcsSessionManager.sessionFor("+15550005001"))+        service.onDestroy()+    }++    @Test fun imdnReportSentForInboundWithMessageId() {+        val service = serviceWithCallback()+        val callback = RcsSipTransport.onInboundMessage!!+        val cpim = "Content-Type: message/cpim\r\n\r\n" ++            "From: <sip:+15550005001@rcs>\r\nimdn.Message-ID: orig-77\r\nContent-Type: text/plain\r\n\r\nhello imdn"+        callback(sip("MESSAGE sip:+15550005002@rcs SIP/2.0", body = cpim, contentType = "message/cpim"))+        awaitDb { testDb.cachedMessageDao().getForConversation("+15550005001").isNotEmpty() }+        val deadline = System.currentTimeMillis() + 15_000+        while (sent.none { String(it.third).contains("orig-77") } && System.currentTimeMillis() < deadline) {+            Thread.sleep(25)+        }+        assertTrue(sent.any { String(it.third).contains("orig-77") }, "no IMDN report sent: ${sent.size}")+        service.onDestroy()+    }++    @Test fun fileTransferAutoFetchRewritesRowToLocalFile() {+        val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0)+        server.createContext("/a.jpg") { exchange ->+            val bytes = "fake-jpeg-bytes".toByteArray()+            exchange.sendResponseHeaders(200, bytes.size.toLong())+            exchange.responseBody.use { it.write(bytes) }+            exchange.close()+        }+        server.start()+        try {+            val service = serviceWithCallback()+            val callback = RcsSipTransport.onInboundMessage!!+            val url = "http://127.0.0.1:${server.address.port}/a.jpg"+            val body = "File-URL: $url\r\nFile-MIME: image/jpeg\r\n\r\nphoto"+            callback(sip("MESSAGE sip:+15550005002@rcs SIP/2.0", body = body, contentType = "text/plain"))+            awaitDb {+                testDb.cachedMessageDao().getForConversation("+15550005001")+                    .any { it.ftUrl?.startsWith("file:") == true }+            }+            service.onDestroy()+        } finally {+            server.stop(0)+        }+    }++    @Test fun focusRelayFansOutToOtherMembers() = runBlocking {+        val service = Robolectric.setupService(RcsSyncService::class.java)+        val conv = "relay-conv-p3"+        val focusUri = RcsSessionManager.hostGroupFocus(conv, "Team", listOf("+15550005001", "+15550005002"))+        assertNotNull(focusUri)+        sent.clear()+        service.relayFocusMessage(+            InboundRcs(conversationId = conv, body = "hi team", senderId = "+15550005001", messageId = "r1"),+            rawBody = "hi team",+        )+        // Only the other member receives the relay.+        assertEquals(1, sent.count { it.first.startsWith("MESSAGE sip:+15550005002@rcs") })+        assertEquals(0, sent.count { it.first.startsWith("MESSAGE sip:+15550005001@rcs") })+        // A blank raw body relays nothing.+        sent.clear()+        service.relayFocusMessage(+            InboundRcs(conversationId = conv, body = "hi", senderId = "+15550005001", messageId = "r2"),+            rawBody = "",+        )+        assertTrue(sent.isEmpty())+        service.onDestroy()+    }++    @Test fun syncMsrpConnectionAttemptsAndCleansUp() = runBlocking {+        val service = Robolectric.setupService(RcsSyncService::class.java)+        val session = RcsSession(+            dialogId = "d-p3", callId = "msrp-p3", localTag = "lt", remoteTag = "rt",+            remoteUri = "sip:+15550005001@rcs", conversationId = "msrp-conv-p3",+            msrpRemotePath = "msrp://127.0.0.1:1/none;tcp",+        )+        // Nothing listens on port 1: connect fails closed, no bound path.+        service.syncMsrpConnection("msrp-conv-p3", session, "msrp://127.0.0.1:1/none;tcp")+        assertTrue(service.boundPaths.isEmpty() || !service.boundPaths.containsKey("msrp-conv-p3"))+        // Same call again (still failing) and with a changed path: also clean.+        service.syncMsrpConnection("msrp-conv-p3", session, "msrp://127.0.0.1:2/none;tcp")+        service.onDestroy()+    }+}
communicate/src/test/java/com/vayunmathur/communicate/telephony/SyncServiceRcsPass3Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/telephony/SyncServiceRcsPass3Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/telephony/SyncServiceRcsPass3Test.ktnew file mode 100644index 0000000000..813d9f05f6--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/telephony/SyncServiceRcsPass3Test.kt@@ -0,0 +1,180 @@+package com.vayunmathur.communicate.telephony++import android.app.Application+import android.app.NotificationManager+import android.content.Intent+import androidx.room3.Room+import androidx.sqlite.driver.bundled.BundledSQLiteDriver+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.communicate.data.rcs.ImdnDisposition+import com.vayunmathur.communicate.data.rcs.RcsDatabase+import com.vayunmathur.communicate.data.rcs.RcsImdn+import com.vayunmathur.communicate.data.rcs.RcsRegistrationState+import com.vayunmathur.communicate.data.rcs.RcsSession+import com.vayunmathur.communicate.data.rcs.RcsUnavailableReason+import com.vayunmathur.communicate.data.rcs.buildIsComposingBody+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import org.robolectric.annotation.Config+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Pass 3: RcsSyncService helpers — notification states, companion+ * start/stop intents, maintenance-loop first emissions, MSRP chunk+ * routing (IMDN / composing / plain text into the cache), shutdown.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class SyncServiceRcsPass3Test {+    private val app get() = ApplicationProvider.getApplicationContext<Application>()+    private lateinit var testDb: RcsDatabase++    @BeforeTest fun setUp() {+        testDb = Room.inMemoryDatabaseBuilder(app, RcsDatabase::class.java)+            .setDriver(BundledSQLiteDriver())+            .allowMainThreadQueries()+            .build()+        RcsDatabase.overrideForTest = testDb+    }++    @AfterTest fun tearDown() {+        RcsDatabase.overrideForTest = null+        testDb.close()+    }++    private fun service() = Robolectric.setupService(RcsSyncService::class.java)++    /** Polls [condition] (async service work runs on real IO threads). */+    private fun awaitTrue(timeoutMs: Long = 10_000, condition: () -> Boolean) {+        val deadline = System.currentTimeMillis() + timeoutMs+        while (!condition() && System.currentTimeMillis() < deadline) Thread.sleep(15)+        assertTrue(condition(), "condition not met within ${timeoutMs}ms")+    }++    @Test fun companionStartAndStopIssueForegroundIntents() {+        RcsSyncService.start(app)+        val started = Shadows.shadowOf(app).nextStartedService+        assertNotNull(started)+        assertEquals(RcsSyncService::class.java.name, started.component?.className)+        assertNull(started.action)+        RcsSyncService.stop(app)+        val stopped = Shadows.shadowOf(app).nextStartedService+        assertNotNull(stopped)+        assertEquals("com.vayunmathur.communicate.rcs.STOP_SYNC", stopped.action)+    }++    @Test fun updateSyncNotificationForEachState() {+        val service = service()+        val nm = Shadows.shadowOf(app.getSystemService(NotificationManager::class.java))+        service.updateSyncNotification(RcsRegistrationState.Available)+        assertNotNull(nm.getNotification(4723))+        service.updateSyncNotification(RcsRegistrationState.Unavailable(RcsUnavailableReason.NoSubscription))+        assertNotNull(nm.getNotification(4723))+        service.updateSyncNotification(RcsRegistrationState.Provisioning)+        service.updateSyncNotification(RcsRegistrationState.Unknown)+        service.updateSyncNotification(RcsRegistrationState.Disabled)+        assertNotNull(nm.getNotification(4723))+        service.onDestroy()+    }++    @Test fun startCommandNonStopActionGoesSticky() {+        val service = service()+        val result = service.onStartCommand(Intent("com.example.OTHER"), 0, 11)+        assertEquals(android.app.Service.START_STICKY, result)+        service.onDestroy()+    }++    @Test fun maintenanceLoopsFirstEmissionsAndShutdown() {+        val service = service()+        service.startMaintenanceLoops()+        // Teardown watch collects the transport state immediately and posts+        // the sync notification; the lifecycle loop sweeps empty sessions.+        val nm = Shadows.shadowOf(app.getSystemService(NotificationManager::class.java))+        awaitTrue { nm.getNotification(4723) != null }+        service.startMsrpLifecycle()+        service.startOutboxPump()+        service.shutdown()+        // Shutdown stops the service itself.+        assertTrue(Shadows.shadowOf(service).isStoppedBySelf)+        service.onDestroy()+    }++    @Test fun msrpChunkImdnUpdatesReceiptTracker() = runBlocking {+        val service = service()+        val session = RcsSession(+            dialogId = "d1", callId = "call-p3", localTag = "lt", remoteTag = "rt",+            remoteUri = "sip:+15550003001@rcs", conversationId = "+15550003001",+        )+        val imdn = """+            <?xml version="1.0"?>+            <imdn xmlns="urn:ietf:params:xml:ns:imdn">+              <message-id>msg-p3-1</message-id>+              <status><positive-delivery/></status>+            </imdn>+        """.trimIndent()+        service.handleMsrpChunk("+15550003001", session, "message/imdn+xml", imdn.toByteArray())+        assertEquals(ImdnDisposition.Delivered, RcsImdn.statusFor("msg-p3-1"))+        service.onDestroy()+    }++    @Test fun msrpChunkComposingUpdatesTypingState() = runBlocking {+        val service = service()+        val session = RcsSession(+            dialogId = "d2", callId = "call-p3-2", localTag = "lt", remoteTag = "rt",+            remoteUri = "sip:+15550003002@rcs", conversationId = "+15550003002",+        )+        service.handleMsrpChunk(+            "+15550003002", session, "application/im-iscomposing+xml",+            buildIsComposingBody(true).toByteArray(),+        )+        assertEquals(+            true,+            com.vayunmathur.communicate.data.rcs.RcsSessionManager.typing.value["+15550003002"],+        )+        service.onDestroy()+    }++    @Test fun msrpChunkPlainAndCpimTextLandsInCache() = runBlocking {+        val service = service()+        val session = RcsSession(+            dialogId = "d3", callId = "call-p3-3", localTag = "lt", remoteTag = "rt",+            remoteUri = "sip:+15550003003@rcs", conversationId = "+15550003003",+        )+        service.handleMsrpChunk("+15550003003", session, "text/plain", "plain hello".toByteArray())+        var rows = testDb.cachedMessageDao().getForConversation("+15550003003")+        assertEquals(1, rows.size)+        assertEquals("plain hello", rows[0].body)+        assertEquals(false, rows[0].outgoing)++        // CPIM-wrapped text unwraps before caching; blank bodies are dropped.+        val cpim = "Content-Type: message/cpim\r\n\r\nFrom: <sip:+15550003003@x>\r\nContent-Type: text/plain\r\n\r\nwrapped hello"+        service.handleMsrpChunk("+15550003003", session, "message/cpim", cpim.toByteArray())+        rows = testDb.cachedMessageDao().getForConversation("+15550003003")+        assertEquals(2, rows.size)+        assertTrue(rows.any { it.body == "wrapped hello" })+        service.handleMsrpChunk("+15550003003", session, "text/plain", "   ".toByteArray())+        assertEquals(2, testDb.cachedMessageDao().getForConversation("+15550003003").size)+        // Conversation unread count accumulated.+        assertEquals(2, testDb.conversationDao().getConversation("+15550003003")?.unreadCount)+        service.onDestroy()+    }++    @Test fun relayWithoutHostedFocusIsNoOp() = runBlocking {+        val service = service()+        // No hosted focus for this conversation: returns quietly.+        service.relayFocusMessage(+            InboundRcs(conversationId = "+1999", body = "x", senderId = "+1999", messageId = "m1"),+            rawBody = "raw",+        )+        service.onDestroy()+    }+}
communicate/src/test/java/com/vayunmathur/communicate/telephony/WelcomeJoinRcsPass3Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/telephony/WelcomeJoinRcsPass3Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/telephony/WelcomeJoinRcsPass3Test.ktnew file mode 100644index 0000000000..7a75900772--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/telephony/WelcomeJoinRcsPass3Test.kt@@ -0,0 +1,301 @@+package com.vayunmathur.communicate.telephony++import android.content.Context+import android.util.Base64+import androidx.room3.Room+import androidx.sqlite.driver.bundled.BundledSQLiteDriver+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.communicate.data.rcs.RcsDatabase+import com.vayunmathur.communicate.data.rcs.e2e.RcsE2E+import com.vayunmathur.communicate.data.rcs.e2e.RcsPeerKeys+import com.vayunmathur.communicate.data.rcs.e2e.RustMlsCrypto+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Pass 3: the inbound Welcome -> join -> decrypt path end to end through+ * [RcsSyncService.handleE2EEInbound] (the entry the task names as+ * RcsInboundParse.handleWelcome's caller), modelled as two devices, each+ * with its own in-memory RcsDatabase via [RcsDatabase.overrideForTest].+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class WelcomeJoinRcsPass3Test {++    private val context: Context get() = ApplicationProvider.getApplicationContext()+    private lateinit var deviceA: RcsDatabase+    private lateinit var deviceB: RcsDatabase++    private fun newDb(): RcsDatabase =+        Room.inMemoryDatabaseBuilder(context, RcsDatabase::class.java)+            .setDriver(BundledSQLiteDriver())+            .allowMainThreadQueries()+            .build()++    private inline fun <T> onDevice(db: RcsDatabase, block: () -> T): T {+        RcsDatabase.overrideForTest = db+        try {+            return block()+        } finally {+            RcsDatabase.overrideForTest = deviceA+        }+    }++    private suspend fun <T> onDeviceSuspend(db: RcsDatabase, block: suspend () -> T): T {+        RcsDatabase.overrideForTest = db+        try {+            return block()+        } finally {+            RcsDatabase.overrideForTest = deviceA+        }+    }++    @BeforeTest fun setUp() {+        deviceA = newDb()+        deviceB = newDb()+        RcsDatabase.overrideForTest = deviceA+        RcsPeerKeys.clear()+    }++    @AfterTest fun tearDown() {+        RcsDatabase.overrideForTest = null+        deviceA.close()+        deviceB.close()+        RcsPeerKeys.clear()+    }++    private fun envelope(from: String, contentType: String, body: String, callId: String) =+        Envelope(from = from, contentType = contentType, raw = body, callId = callId, viaBranch = "br-p3")++    private fun wrapped(contentType: String, payload: ByteArray): String =+        "Content-Type: $contentType\r\n\r\n" + Base64.encodeToString(payload, Base64.NO_WRAP)++    @Test fun welcomeJoinThenEncryptedMessageEndToEnd() = runTest {+        val service = Robolectric.setupService(RcsSyncService::class.java)+        try {+            if (!RustMlsCrypto.isAvailable) {+                // No host MLS library: the whole E2EE inbound route absorbs.+                val out = service.handleE2EEInbound(+                    envelope("+15550001002", RcsE2E.CT_WELCOME, wrapped(RcsE2E.CT_WELCOME, byteArrayOf(1, 2, 3)), "w0"),+                )+                assertNull(out)+                return@runTest+            }+            val meA = "+15550001001"+            val meB = "+15550001002"++            // Device B creates its identity and a key package to publish.+            val kpB = onDeviceSuspend(deviceB) {+                assertNotNull(RcsE2E.identityFor(context, meB))+                RcsE2E.freshKeyPackage(context, meB)+            }+            assertNotNull(kpB)++            // Device A adds B and gets the Welcome for B (A's thread is with B).+            val created = RcsE2E.createEncryptedGroup(context, meA, meB, listOf(kpB))+            assertNotNull(created)+            val (commit, welcome) = created++            // B receives the Welcome through the sync service inbound route.+            val notice = onDeviceSuspend(deviceB) {+                service.handleE2EEInbound(+                    envelope(meA, RcsE2E.CT_WELCOME, wrapped(RcsE2E.CT_WELCOME, welcome), "w1"),+                )+            }+            assertNotNull(notice)+            assertEquals(meA, notice.conversationId)+            assertEquals(meA, notice.senderId)+            assertEquals("🔒 Encrypted chat started", notice.body)+            assertEquals(InboundKind.Text, notice.kind)+            assertTrue(notice.messageId.startsWith("in-welcome-"))++            // The joined group is persisted on B and matches A's group id.+            val groupOnB = onDeviceSuspend(deviceB) { RcsE2E.groupIdFor(context, meA) }+            val groupOnA = RcsE2E.groupIdFor(context, meB)+            assertNotNull(groupOnB)+            assertEquals(groupOnA?.toList(), groupOnB.toList())++            // A encrypts; B receives the application message through the same+            // inbound route and sees the plaintext as an inbox row.+            val payload = RcsE2E.encryptTo(context, meA, meB, "hello over rcs".toByteArray(Charsets.UTF_8))+            assertNotNull(payload)+            val row = onDeviceSuspend(deviceB) {+                service.handleE2EEInbound(+                    envelope(meA, RcsE2E.CT_MLS, wrapped(RcsE2E.CT_MLS, payload), "m1"),+                )+            }+            assertNotNull(row)+            assertEquals("hello over rcs", row.body)+            assertEquals(meA, row.conversationId)+            assertTrue(row.messageId.startsWith("in-mls-"))++            // The add-commit delivered as data is absorbed without a row.+            val commitRow = onDeviceSuspend(deviceB) {+                service.handleE2EEInbound(+                    envelope(meA, RcsE2E.CT_COMMIT, wrapped(RcsE2E.CT_COMMIT, commit), "m2"),+                )+            }+            assertNull(commitRow)++            // B replies in the group; A decrypts through its inbound route.+            val reply = onDeviceSuspend(deviceB) {+                RcsE2E.encryptTo(context, meB, meA, "reply hello".toByteArray(Charsets.UTF_8))+            }+            assertNotNull(reply)+            val replyRow = service.handleE2EEInbound(+                envelope(meB, RcsE2E.CT_MLS, wrapped(RcsE2E.CT_MLS, reply), "m3"),+            )+            assertNotNull(replyRow)+            assertEquals("reply hello", replyRow.body)+        } finally {+            service.onDestroy()+        }+    }++    @Test fun welcomeNegativesAreAbsorbed() = runTest {+        val service = Robolectric.setupService(RcsSyncService::class.java)+        try {+            // Undecodable body.+            assertNull(+                service.handleE2EEInbound(+                    envelope("+15550001002", RcsE2E.CT_WELCOME, "Content-Type: ${RcsE2E.CT_WELCOME}\r\n\r\n!!!not-base64!!!", "w-bad"),+                ),+            )+            // Decodable but not a Welcome.+            assertNull(+                service.handleE2EEInbound(+                    envelope("+15550001002", RcsE2E.CT_WELCOME, wrapped(RcsE2E.CT_WELCOME, byteArrayOf(9, 8, 7, 6, 5)), "w-junk"),+                ),+            )+            // Plain text is not E2EE at all.+            assertNull(+                service.handleE2EEInbound(+                    envelope("+15550001002", "text/plain", "just a hello", "t1"),+                ),+            )+            // MLS data for a conversation with no group cannot decrypt.+            assertNull(+                service.handleE2EEInbound(+                    envelope(+                        "+15550009999", RcsE2E.CT_MLS,+                        wrapped(RcsE2E.CT_MLS, byteArrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9)), "m-x",+                    ),+                ),+            )+        } finally {+            service.onDestroy()+        }+    }++    @Test fun keyPackageAndKeyRequestInboundKinds() = runTest {+        val service = Robolectric.setupService(RcsSyncService::class.java)+        try {+            if (!RustMlsCrypto.isAvailable) return@runTest+            val meB = "+15550001002"+            val kpB = onDeviceSuspend(deviceB) {+                RcsE2E.identityFor(context, meB)+                RcsE2E.freshKeyPackage(context, meB)+            }+            assertNotNull(kpB)+            // B's publication arrives at A: cached, answered with a Typing-kind+            // control result, and no group auto-forms (no local number here).+            val kpBody = "Content-Type: ${RcsE2E.CT_KEY_PACKAGE}\r\n\r\n" ++                java.util.Base64.getEncoder().encodeToString(kpB)+            val kpResult = service.handleE2EEInbound(+                envelope(meB, RcsE2E.CT_KEY_PACKAGE, kpBody, "kp1"),+            )+            assertNotNull(kpResult)+            assertEquals(InboundKind.Typing, kpResult.kind)+            assertEquals(kpB.toList(), RcsPeerKeys.get(meB)?.toList())++            // A key request is absorbed the same way.+            val reqResult = service.handleE2EEInbound(+                envelope(meB, RcsE2E.CT_KEY_REQUEST, "Content-Type: ${RcsE2E.CT_KEY_REQUEST}\r\n\r\nrequest", "kr1"),+            )+            assertNotNull(reqResult)+            assertEquals(InboundKind.Typing, reqResult.kind)+            assertTrue(reqResult.messageId.startsWith("in-kreq-"))+        } finally {+            service.onDestroy()+        }+    }++    @Test fun encryptedInboundThroughServiceCallbackIsCached() = runTest {+        if (!RustMlsCrypto.isAvailable) return@runTest+        val meA = "+15550001001"+        val meB = "+15550001002"+        val kpB = onDeviceSuspend(deviceB) {+            RcsE2E.identityFor(context, meB)+            RcsE2E.freshKeyPackage(context, meB)+        }+        assertNotNull(kpB)+        val created = RcsE2E.createEncryptedGroup(context, meA, meB, listOf(kpB))+        assertNotNull(created)+        val welcome = created.second+        val service = Robolectric.setupService(RcsSyncService::class.java)+        try {+            // B joins the way production does, then starts its sync service.+            val notice = onDeviceSuspend(deviceB) {+                service.handleE2EEInbound(+                    envelope(meA, RcsE2E.CT_WELCOME, wrapped(RcsE2E.CT_WELCOME, welcome), "w-cb"),+                )+            }+            assertNotNull(notice)+            assertEquals(+                android.app.Service.START_STICKY,+                service.onStartCommand(null, 0, 5),+            )+            val deadline = System.currentTimeMillis() + 15_000+            while (+                com.vayunmathur.communicate.data.rcs.RcsSipTransport.onInboundMessage == null &&+                System.currentTimeMillis() < deadline+            ) {+                Thread.sleep(20)+            }+            val callback = com.vayunmathur.communicate.data.rcs.RcsSipTransport.onInboundMessage+            assertNotNull(callback)+            // A sends an application message; on B it decrypts and caches.+            val payload = RcsE2E.encryptTo(context, meA, meB, "cached secret".toByteArray(Charsets.UTF_8))+            assertNotNull(payload)+            val headers = buildString {+                append("Via: SIP/2.0/TCP 10.0.0.1;branch=z9hG4bKcb\r\n")+                append("From: <sip:$meA@rcs>;tag=t1\r\n")+                append("To: <sip:$meB@rcs>\r\n")+                append("Call-ID: cb-mls@host\r\n")+                append("CSeq: 1 MESSAGE\r\n")+                append("Content-Type: ${RcsE2E.CT_MLS}\r\n")+            }+            val raw = wrapped(RcsE2E.CT_MLS, payload)+            // Keep B's database installed while the service scope handles+            // the message asynchronously (the callback only enqueues it).+            RcsDatabase.overrideForTest = deviceB+            callback(+                android.telephony.ims.SipMessage(+                    "MESSAGE sip:$meB@rcs SIP/2.0", headers, raw.toByteArray(Charsets.UTF_8),+                ),+            )+            // The service scope caches asynchronously into B's database.+            val dbDeadline = System.currentTimeMillis() + 15_000+            var bodies = emptyList<String>()+            while (System.currentTimeMillis() < dbDeadline) {+                bodies = deviceB.cachedMessageDao().getForConversation(meA).map { it.body }+                if ("cached secret" in bodies) break+                Thread.sleep(25)+            }+            assertTrue("cached secret" in bodies, "cached bodies: $bodies")+        } finally {+            RcsDatabase.overrideForTest = deviceA+            service.onDestroy()+        }+    }+}