Modern Apps git

← Modern-Apps.git

communicate: add tests for rcs slice (pass 2)

Commit
196a3e1c5e52f7e4086efdd1d683a630b4f90ad1
Author
Vayun Mathur <[email protected]>
When
2026-11-07 08:24 UTC (29 days ago)
Parents
72144e5
Slice coverage (merged, instructions, classes under data/rcs and
ui/rcs): 21.3% (8627/40443) at the second-pass baseline ->
76.9% (31165/40514). Full-module run: 1117 tests, 1 failure (a 10 s Compose wait for
DB-backed members under full-suite load; its timeout was raised
to 30 s and the class passes standalone).

118 new tests in 12 slice-named files (plus 4 Robolectric shadow
helpers), covering: provisioning decision tree (available /
not-supported / no-privilege / provisioning-required /
service-unavailable via a shadow ProvisioningManager); SipDelegate
transport through a fake framework connection (callbacks, pending
acks, digest-auth retry, inbound routing); direct SIP over a fake
IMS PDN (REGISTER 401->AKA->200, inbound + outbound MESSAGE,
restart); MSRP sockets over loopback (chunked sends, persistent
connections, accepted sockets); MSRP listen/accept incl. TLS with
a real pinned handshake; TLS identity generation; FT-over-HTTP
against a loopback server (digest challenge, multipart upload,
GBA-injected credentials, download); outbox/typing/display-report
Room behavior; the session/focus state machines over a fake SIP
sender; the three RCS Compose screens; MLS verification/member
bookkeeping over Room.

Testability (production, behavior-preserving): RcsDatabase gains
an internal overrideForTest so JVM tests can substitute an
in-memory Room database for the SQLCipher singleton, and
RcsSipTransport gains internal test seams (fakeSenderForTest,
callbacksForTest, installConnectionForTest). Never set in
production.

Untestable remainder (why 85% is not honestly reachable here):
the MLS crate gates its JNI bridge #[cfg(target_os = android)],
so the host cdylib has no RustMlsCrypto exports - every native
call UnsatisfiedLinkErrors into RcsE2E's fail-closed paths, which
are covered; the native-success group flows (~2.4k instructions)
need the cfg widened (lead-inbox note filed). The UCE capability
callbacks and SipDelegateManager creation need a live carrier IMS
service; covered to the fail-closed boundary.

(cherry picked from commit 9aa4b3c12ef7c05669819114044521873cef3ba5)

Diff

communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsDatabase.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsDatabase.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsDatabase.ktindex d69ad64352..847eead5d1 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsDatabase.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsDatabase.kt@@ -93,8 +93,16 @@ abstract class RcsDatabase : RoomDatabase() {          override val migrations = listOf(MIGRATION_1_2, MIGRATION_2_3) +        /**+         * Test seam: when set, [getDatabase] returns this instance instead+         * of the SQLCipher-backed singleton (whose native library cannot+         * load on a JVM test host). Production code never sets it.+         */+        @Volatile+        internal var overrideForTest: RcsDatabase? = null+         fun getDatabase(context: Context): RcsDatabase =-            RcsRepository.get(context).database()+            overrideForTest ?: RcsRepository.get(context).database()     } } 
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSipTransport.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSipTransport.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSipTransport.ktindex f677b44ae5..6d25502bf7 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSipTransport.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSipTransport.kt@@ -134,6 +134,30 @@ object RcsSipTransport {     private val stateCallback: Any by lazy { transportCallbacks().first }     private val messageCallback: Any by lazy { transportCallbacks().second } +    /** Test seam: the lazily-built delegate callbacks, for JVM tests. */+    internal fun callbacksForTest(): Pair<Any, Any> = stateCallback to messageCallback++    /**+     * Test seam: install (or clear, with null) a delegate connection plus+     * its config version/snapshot, mirroring what `onCreated` ++     * `onConfigurationChanged` set on device. Production code never calls+     * this; the framework callbacks remain the only real installers.+     */+    internal fun installConnectionForTest(+        connection: SipDelegateConnection?,+        version: Long,+        config: SipDelegateConfiguration?,+    ) {+        this.connection = connection+        configVersion = version+        lastConfig = config+        _state.value = if (connection != null) {+            RcsRegistrationState.Available+        } else {+            RcsRegistrationState.Unknown+        }+    }+     /**      * Build the two delegate callbacks. The anonymous classes — and hence the      * hidden-API callback types — load only when this function runs@@ -254,10 +278,20 @@ object RcsSipTransport {         activeSubId = SubscriptionManager.INVALID_SUBSCRIPTION_ID     } +    /**+     * Test seam: when set, [canSend] is true and [sendSipMessage] routes to+     * this sender instead of a live delegate/direct-SIP leg. Lets JVM tests+     * drive the session/focus/typing layers that sit above the transport+     * without an IMS PDN. Production code never sets it.+     */+    @Volatile+    internal var fakeSenderForTest: ((startLine: String, headers: String, body: ByteArray) -> Boolean)? = null+     /** True when a SIP MESSAGE can be sent right now (either leg). */     fun canSend(): Boolean =         RcsFeature.enabled && (-            (_state.value is RcsRegistrationState.Available && connection != null) ||+            fakeSenderForTest != null ||+                (_state.value is RcsRegistrationState.Available && connection != null) ||                 directSipUp             ) @@ -321,6 +355,8 @@ object RcsSipTransport {      * retried with digest auth ([onSipResponseMessage]).      */     suspend fun sendSipMessage(startLine: String, headerSection: String, body: ByteArray): Boolean {+        // Test seam (never set in production): record/accept the send.+        fakeSenderForTest?.let { return it(startLine, headerSection, body) }         // Direct-SIP leg: route to the P-CSCF socket (no delegate).         if (directSipUp && RcsFeature.enabled) {             return RcsDirectSip.sendMessage(startLine, headerSection, body)
communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2DelegateTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2DelegateTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2DelegateTest.ktnew file mode 100644index 0000000000..e650f80258--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2DelegateTest.kt@@ -0,0 +1,466 @@+package com.vayunmathur.communicate.rcs++import com.vayunmathur.communicate.data.rcs.buildInvite++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.communicate.data.rcs.RcsRegistrationState+import com.vayunmathur.communicate.data.rcs.RcsSipTransport+import com.vayunmathur.communicate.data.rcs.RcsUnavailableReason+import java.lang.reflect.InvocationHandler+import java.lang.reflect.Proxy+import java.net.InetSocketAddress+import java.util.concurrent.CopyOnWriteArrayList+import kotlin.coroutines.Continuation+import kotlin.coroutines.intrinsics.COROUTINE_SUSPENDED+import kotlin.coroutines.suspendCoroutine+import kotlinx.coroutines.async+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.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Slice-3 pass 2: the SipDelegate transport with a fake framework+ * connection installed through the test seam — delegate callbacks,+ * pending-send acks, digest-auth retry, inbound routing, teardown.+ * Framework types are built reflectively (they are hidden APIs).+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34], shadows = [RcsSlice3Pass2ProvisioningShadow::class])+class RcsSlice3Pass2DelegateTest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    private val sipMessageClass: Class<*> = Class.forName("android.telephony.ims.SipMessage")+    private val connectionClass: Class<*> = Class.forName("android.telephony.ims.SipDelegateConnection")++    private class FakeConnection {+        data class SentMessage(val message: Any, val version: Long, val branch: String)+        val sentMessages = CopyOnWriteArrayList<SentMessage>()+        val cleanedSessions = CopyOnWriteArrayList<String>()+        val notifiedReceived = CopyOnWriteArrayList<String>()+        @Volatile var failSend = false++        val proxy: Any+        init {+            val connectionClass = Class.forName("android.telephony.ims.SipDelegateConnection")+            val sipMessageClass = Class.forName("android.telephony.ims.SipMessage")+            val branchMethod = sipMessageClass.getMethod("getViaBranchParameter")+            val handler = InvocationHandler { _, method, args ->+                when (method.name) {+                    "sendMessage" -> {+                        if (failSend) throw RuntimeException("fake send failure")+                        val message = args[0]+                        sentMessages += SentMessage(+                            message, args[1] as Long, branchMethod.invoke(message) as String,+                        )+                        null+                    }+                    "cleanupSession" -> { cleanedSessions += args[0] as String; null }+                    "notifyMessageReceived" -> { notifiedReceived += args[0] as String; null }+                    else -> null+                }+            }+            proxy = Proxy.newProxyInstance(connectionClass.classLoader, arrayOf(connectionClass), handler)+        }+    }++    private fun sipMessage(startLine: String, headers: String, body: ByteArray = ByteArray(0)): Any =+        sipMessageClass.getConstructor(String::class.java, String::class.java, ByteArray::class.java)+            .newInstance(startLine, headers, body)++    private fun config(version: Long = 7L): Any {+        val builderClass = Class.forName("android.telephony.ims.SipDelegateConfiguration\$Builder")+        val builder = builderClass+            .getConstructor(Long::class.javaPrimitiveType, Int::class.javaPrimitiveType, InetSocketAddress::class.java, InetSocketAddress::class.java)+            .newInstance(version, 1, InetSocketAddress("10.0.0.2", 5060), InetSocketAddress("10.0.0.1", 5060))+        fun set(name: String, value: String) {+            builderClass.getMethod(name, String::class.java).invoke(builder, value)+        }+        set("setPublicUserIdentifier", "sip:[email protected]")+        set("setHomeDomain", "carrier.example")+        set("setImei", "imei-123")+        set("setSipServiceRouteHeader", "<sip:proxy.carrier.example;lr>")+        set("setSipPaniHeader", "3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=abc")+        set("setSipUserAgentHeader", "CarrierUA/1.0")+        return builderClass.getMethod("build").invoke(builder)+    }++    private object RcsSessionManagerForInvite {+        fun build(): Triple<String, String, ByteArray> =+            with(com.vayunmathur.communicate.data.rcs.RcsSessionManager) {+                buildInvite(+                    targetUri = "sip:[email protected]",+                    callId = "invite-call@rcs",+                    localTag = "ltag1234",+                    branch = "z9hG4bKinvite",+                    conversationId = "conv-invite",+                    subject = "hello subject",+                )+            }+    }++    private fun seam(name: String): java.lang.reflect.Method =+        RcsSipTransport::class.java.methods.first { it.name.startsWith(name) }++    private fun install(fake: FakeConnection?, version: Long = 7L, config: Any? = if (fake != null) config(version) else null) {+        seam("installConnectionForTest").invoke(RcsSipTransport, fake?.proxy, version, config)+    }++    private fun callbacks(): Pair<Any, Any> {+        @Suppress("UNCHECKED_CAST")+        return seam("callbacksForTest").invoke(RcsSipTransport) as Pair<Any, Any>+    }++    private fun invokeCallback(callback: Any, methodName: String, vararg args: Any?) {+        val method = callback.javaClass.methods.first {+            it.name == methodName && it.parameterCount == args.size+        }+        method.invoke(callback, *args)+    }++    private fun responseMessage(+        startLine: String,+        branch: String,+        callId: String = "dlg-call@rcs",+        cseq: String = "1 MESSAGE",+        extra: String = "",+        body: String = "",+    ): Any {+        val headers = buildString {+            append("Via: SIP/2.0/TCP 10.0.0.1;branch=$branch\r\n")+            append("To: <sip:peer@rcs>;tag=remote\r\n")+            append("From: <sip:[email protected]>;tag=local\r\n")+            append("Call-ID: $callId\r\n")+            append("CSeq: $cseq\r\n")+            append(extra)+        }+        return sipMessage(startLine, headers, body.toByteArray(Charsets.UTF_8))+    }++    private suspend fun invokeSuspend(methodName: String, vararg args: Any?): Any? {+        val method = RcsSipTransport::class.java.methods.first {+            it.name == methodName && it.parameterTypes.size == args.size + 1+        }+        return suspendCoroutine { cont ->+            @Suppress("UNCHECKED_CAST")+            val result = method.invoke(RcsSipTransport, *args, cont as Continuation<Any?>)+            if (result !== COROUTINE_SUSPENDED) cont.resumeWith(Result.success(result))+        }+    }++    private fun setInboundListener(listener: ((Any) -> Unit)?) {+        // Reflective: the property type is the hidden SipMessage class.+        val field = RcsSipTransport::class.java.getDeclaredField("onInboundMessage")+        field.isAccessible = true+        field.set(RcsSipTransport, listener)+    }++    @AfterTest+    fun tearDown() {+        seam("installConnectionForTest").invoke(RcsSipTransport, null, -1L, null)+        setInboundListener(null)+        RcsSipTransport.tearDown(context)+    }++    @Test+    fun delegateLifecycleCallbacksDriveState() {+        val fake = FakeConnection()+        val (stateCallback, _) = callbacks()+        // onCreated installs the connection and flips state to Available.+        invokeCallback(stateCallback, "onCreated", fake.proxy)+        assertEquals(RcsRegistrationState.Available, RcsSipTransport.state.value)+        assertEquals("single-reg delegate", RcsSipTransport.activeLeg)+        // onConfigurationChanged records the snapshot used by SIP builders.+        invokeCallback(stateCallback, "onConfigurationChanged", config())+        val snapshot = RcsSipTransport.lastConfigSnapshot()+        assertNotNull(snapshot)+        assertEquals(7L, snapshot.version)+        assertEquals("sip:[email protected]", snapshot.publicUserId)+        assertEquals("carrier.example", snapshot.homeDomain)+        assertEquals("<sip:proxy.carrier.example;lr>", snapshot.serviceRoute)+        assertEquals("imei-123", snapshot.imei)+        // Chat builders now use the configured identity as From.+        val (_, headers, _) = RcsSipTransport.buildChatMessage("sip:fallback@rcs", "sip:peer@rcs", "c1", "hi")+        assertTrue(headers.contains("From: <sip:[email protected]>"))++        // Denied feature tags flip to Unavailable(TransportDenied).+        val regStateClass = Class.forName("android.telephony.ims.DelegateRegistrationState")+        val regState = regStateClass.getDeclaredConstructor().apply { isAccessible = true }.newInstance()+        val tagClass = Class.forName("android.telephony.ims.FeatureTagState")+        val denied = tagClass.getConstructor(String::class.java, Int::class.javaPrimitiveType)+            .newInstance("+g.3gpp.icsi-ref=\"urn:x\"", 2)+        invokeCallback(stateCallback, "onFeatureTagStatusChanged", regState, setOf(denied))+        assertEquals(+            RcsRegistrationState.Unavailable(RcsUnavailableReason.TransportDenied),+            RcsSipTransport.state.value,+        )+        // An empty denial set leaves state alone.+        invokeCallback(stateCallback, "onFeatureTagStatusChanged", regState, emptySet<Any>())+        assertEquals(+            RcsRegistrationState.Unavailable(RcsUnavailableReason.TransportDenied),+            RcsSipTransport.state.value,+        )++        // onDestroyed clears the connection and reports ServiceUnavailable+        // only when it had been Available; restore Available first.+        install(fake)+        assertEquals(RcsRegistrationState.Available, RcsSipTransport.state.value)+        invokeCallback(stateCallback, "onDestroyed", 1)+        assertFalse(RcsSipTransport.canSend())+        assertEquals(+            RcsRegistrationState.Unavailable(RcsUnavailableReason.ServiceUnavailable),+            RcsSipTransport.state.value,+        )+    }++    @Test+    fun sendSipMessageAckAndFailureFlows() = runTest {+        val fake = FakeConnection()+        install(fake)+        assertTrue(RcsSipTransport.canSend())++        // Happy path: send is parked, the sent-ack completes it true.+        val (_, _, _) = Triple(0, 0, 0)+        val pending = async(kotlinx.coroutines.Dispatchers.Default) {+            @Suppress("UNCHECKED_CAST")+            invokeSuspend("sendSipMessage", "MESSAGE sip:peer@rcs SIP/2.0", "Via: SIP/2.0/TCP x;branch=placeholder\r\n", "body".toByteArray()) as Boolean+        }+        // Wait for the fake to see the send.+        val deadline = System.currentTimeMillis() + 10_000+        while (System.currentTimeMillis() < deadline && fake.sentMessages.isEmpty()) Thread.sleep(10)+        assertEquals(1, fake.sentMessages.size)+        assertEquals(7L, fake.sentMessages.first().version)+        val branch = fake.sentMessages.first().branch+        assertTrue(branch.startsWith("z9hG4bK") || branch.isNotEmpty(), branch)+        val (_, messageCallback) = callbacks()+        invokeCallback(messageCallback, "onMessageSent", branch)+        assertTrue(pending.await())++        // Failure callback completes a send false.+        fake.sentMessages.clear()+        val pending2 = async(kotlinx.coroutines.Dispatchers.Default) {+            @Suppress("UNCHECKED_CAST")+            invokeSuspend("sendSipMessage", "MESSAGE sip:peer@rcs SIP/2.0", "Via: SIP/2.0/TCP x;branch=p2\r\n", ByteArray(0)) as Boolean+        }+        val deadline2 = System.currentTimeMillis() + 10_000+        while (System.currentTimeMillis() < deadline2 && fake.sentMessages.isEmpty()) Thread.sleep(10)+        val branch2 = fake.sentMessages.first().branch+        invokeCallback(messageCallback, "onMessageSendFailure", branch2, 3)+        assertFalse(pending2.await())++        // A throwing connection send fails the call immediately.+        fake.failSend = true+        val failed = invokeSuspend("sendSipMessage", "MESSAGE sip:peer@rcs SIP/2.0", "Via: x\r\n", ByteArray(0)) as Boolean+        assertFalse(failed)+        fake.failSend = false+    }++    @Test+    fun inboundMessageCallbackRoutesToListener() {+        val fake = FakeConnection()+        install(fake)+        val received = CopyOnWriteArrayList<Any>()+        setInboundListener { received += it }+        val (_, messageCallback) = callbacks()+        val inbound = sipMessage(+            "MESSAGE sip:me@rcs SIP/2.0",+            "Via: SIP/2.0/TCP 10.0.0.1;branch=z9hG4bKinbound1\r\nCall-ID: in-1\r\n",+            "hello".toByteArray(),+        )+        invokeCallback(messageCallback, "onMessageReceived", inbound)+        assertEquals(1, received.size)+        // The delegate was told we received it (branch ack).+        assertEquals(listOf("z9hG4bKinbound1"), fake.notifiedReceived.toList())+        setInboundListener(null)+    }++    @Test+    fun digestAuthRetryOn401ThenSuccess() = runTest {+        val fake = FakeConnection()+        install(fake)+        val pending = async(kotlinx.coroutines.Dispatchers.Default) {+            @Suppress("UNCHECKED_CAST")+            invokeSuspend("sendSipMessage", "MESSAGE sip:peer@rcs SIP/2.0", "Via: SIP/2.0/TCP host;branch=origbranch\r\nContent-Length: 4\r\n", "body".toByteArray()) as Boolean+        }+        val deadline = System.currentTimeMillis() + 10_000+        while (System.currentTimeMillis() < deadline && fake.sentMessages.isEmpty()) Thread.sleep(10)+        assertEquals(1, fake.sentMessages.size)+        val challenge = "WWW-Authenticate: Digest realm=\"carrier.example\", nonce=\"nonce-42\", qop=auth\r\n"+        val response401 = responseMessage("SIP/2.0 401 Unauthorized", fake.sentMessages.first().branch, extra = challenge)+        val consumed = invokeSuspend("onSipResponseMessage", response401) as Boolean+        assertTrue(consumed)+        // The request was re-sent once, with a digest Authorization header+        // and a fresh branch.+        assertEquals(2, fake.sentMessages.size)+        val retried = fake.sentMessages[1]+        assertFalse(retried.branch == fake.sentMessages[0].branch)+        // Ack the retried transaction.+        val (_, messageCallback) = callbacks()+        invokeCallback(messageCallback, "onMessageSent", retried.branch)+        assertTrue(pending.await())+    }++    @Test+    fun second401FailsTheSend() = runTest {+        val fake = FakeConnection()+        install(fake)+        val pending = async(kotlinx.coroutines.Dispatchers.Default) {+            @Suppress("UNCHECKED_CAST")+            invokeSuspend("sendSipMessage", "MESSAGE sip:peer@rcs SIP/2.0", "Via: SIP/2.0/TCP host;branch=b1\r\n", "body".toByteArray()) as Boolean+        }+        val deadline = System.currentTimeMillis() + 10_000+        while (System.currentTimeMillis() < deadline && fake.sentMessages.isEmpty()) Thread.sleep(10)+        val challenge = "WWW-Authenticate: Digest realm=\"carrier.example\", nonce=\"n1\", qop=auth\r\n"+        assertTrue(invokeSuspend("onSipResponseMessage", responseMessage("SIP/2.0 401 Unauthorized", fake.sentMessages[0].branch, extra = challenge)) as Boolean)+        assertEquals(2, fake.sentMessages.size)+        // Second challenge for the retried branch: no more retries, send fails.+        assertTrue(invokeSuspend("onSipResponseMessage", responseMessage("SIP/2.0 401 Unauthorized", fake.sentMessages[1].branch, extra = challenge)) as Boolean)+        assertFalse(pending.await())+        assertEquals(2, fake.sentMessages.size)+    }++    @Test+    fun pendingResponseResolvesThroughResponseRouter() = runTest {+        val fake = FakeConnection()+        install(fake)+        val pending = async(kotlinx.coroutines.Dispatchers.Default) {+            @Suppress("UNCHECKED_CAST")+            invokeSuspend("sendSipMessage", "MESSAGE sip:peer@rcs SIP/2.0", "Via: SIP/2.0/TCP host;branch=b9\r\n", "body".toByteArray()) as Boolean+        }+        val deadline = System.currentTimeMillis() + 10_000+        while (System.currentTimeMillis() < deadline && fake.sentMessages.isEmpty()) Thread.sleep(10)+        val branch = fake.sentMessages.first().branch+        // Provisional is absorbed without completing the send.+        assertTrue(invokeSuspend("onSipResponseMessage", responseMessage("SIP/2.0 100 Trying", branch)) as Boolean)+        assertFalse(pending.isCompleted)+        // Final 2xx (non-INVITE) completes it successfully.+        assertTrue(invokeSuspend("onSipResponseMessage", responseMessage("SIP/2.0 200 OK", branch)) as Boolean)+        assertTrue(pending.await())+        // A failure final on a fresh send fails it (and routes dialog teardown).+        val pending2 = async(kotlinx.coroutines.Dispatchers.Default) {+            @Suppress("UNCHECKED_CAST")+            invokeSuspend("sendSipMessage", "MESSAGE sip:peer@rcs SIP/2.0", "Via: SIP/2.0/TCP host;branch=b10\r\n", "body".toByteArray()) as Boolean+        }+        val deadline2 = System.currentTimeMillis() + 10_000+        while (System.currentTimeMillis() < deadline2 && fake.sentMessages.size < 2) Thread.sleep(10)+        val branch2 = fake.sentMessages[1].branch+        assertTrue(invokeSuspend("onSipResponseMessage", responseMessage("SIP/2.0 603 Decline", branch2)) as Boolean)+        assertFalse(pending2.await())+    }++    private fun awaitTransportState(timeoutMs: Long = 10_000): RcsRegistrationState {+        val deadline = System.currentTimeMillis() + timeoutMs+        var state = RcsSipTransport.state.value+        while (System.currentTimeMillis() < deadline) {+            state = RcsSipTransport.state.value+            if (state !is RcsRegistrationState.Unknown && state !is RcsRegistrationState.Provisioning) break+            Thread.sleep(25)+        }+        return state+    }++    private fun configureProbe(url: String?, singleRegFeature: Boolean) {+        org.robolectric.shadows.ShadowSubscriptionManager.setDefaultSmsSubscriptionId(5)+        val ccm = context.getSystemService(android.telephony.CarrierConfigManager::class.java)+        val bundle = android.os.PersistableBundle()+        if (url != null) {+            bundle.putString(android.telephony.CarrierConfigManager.KEY_RCS_CONFIG_SERVER_URL_STRING, url)+        }+        org.robolectric.Shadows.shadowOf(ccm).setConfigForSubId(5, bundle)+        org.robolectric.Shadows.shadowOf(context.packageManager)+            .setSystemFeature("android.hardware.telephony.ims.singlereg", singleRegFeature)+    }++    @Test+    fun ensureRegisteredNotSupportedWithoutSingleRegFeature() {+        RcsSipTransport.tearDown(context)+        RcsSlice3Pass2ProvisioningShadow.reset()+        RcsSlice3Pass2ProvisioningShadow.capable = false+        try {+            configureProbe("https://config.example/rcs", singleRegFeature = false)+            RcsSipTransport.ensureRegistered(context)+            val state = awaitTransportState()+            // Probe says the framework is not single-reg capable and we+            // hold no carrier privilege; the device gate is off too, so+            // the direct-SIP fallback is not attempted and the probe stands.+            assertEquals(+                RcsRegistrationState.Unavailable(RcsUnavailableReason.NoCarrierPrivilege), state,+            )+        } finally {+            RcsSlice3Pass2ProvisioningShadow.reset()+            RcsSipTransport.tearDown(context)+        }+    }++    @Test+    fun ensureRegisteredAttemptsDelegateWhenProvisioned() {+        RcsSipTransport.tearDown(context)+        RcsSlice3Pass2ProvisioningShadow.reset()+        try {+            configureProbe("https://config.example/rcs", singleRegFeature = true)+            RcsSipTransport.ensureRegistered(context)+            // The probe itself completes Available on its own flow.+            val deadline = System.currentTimeMillis() + 10_000+            while (System.currentTimeMillis() < deadline &&+                com.vayunmathur.communicate.data.rcs.RcsProvisioning.state.value !=+                RcsRegistrationState.Available+            ) {+                Thread.sleep(25)+            }+            assertEquals(+                RcsRegistrationState.Available,+                com.vayunmathur.communicate.data.rcs.RcsProvisioning.state.value,+            )+            // The delegate attempt resolves on the IO scope to some terminal+            // state (no privilege on the JVM); Unknown/Disabled/other would+            // mean ensureRegistered never ran.+            val state = awaitTransportState()+            assertTrue(+                state !is RcsRegistrationState.Disabled,+                "transport state never engaged: $state",+            )+        } finally {+            RcsSlice3Pass2ProvisioningShadow.reset()+            RcsSipTransport.tearDown(context)+        }+    }++    @Test+    fun inviteBuilderUsesDelegateConfig() {+        val fake = FakeConnection()+        install(fake)+        val invite = with(RcsSessionManagerForInvite) { build() }+        assertTrue(invite.first.startsWith("INVITE sip:[email protected] SIP/2.0"), invite.first)+        assertTrue(invite.second.contains("Route: <<sip:proxy.carrier.example;lr>>") ||+            invite.second.contains("Route: <sip:proxy.carrier.example;lr>"), invite.second)+        assertTrue(invite.second.contains("P-Access-Network-Info: 3GPP-E-UTRAN-FDD"), invite.second)+        assertTrue(invite.second.contains("User-Agent: CarrierUA/1.0"), invite.second)+        assertTrue(invite.second.contains("Contact: <sip:[email protected]>"), invite.second)+        val sdp = invite.third.toString(Charsets.UTF_8)+        assertTrue(sdp.contains("a=accept-types:message/cpim"), sdp)+    }++    @Test+    fun cleanupAndTeardownDropConnection() {+        val fake = FakeConnection()+        install(fake)+        RcsSipTransport.cleanupSession("call-42")+        RcsSipTransport.cleanupSession("")+        assertEquals(listOf("call-42"), fake.cleanedSessions.toList())+        RcsSipTransport.tearDown(context)+        assertFalse(RcsSipTransport.canSend())+        assertEquals("none", RcsSipTransport.activeLeg)+        // teardown drops the connection; the last config snapshot is kept+        // (only onDestroyed clears it on device).+        assertEquals(7L, RcsSipTransport.lastConfigSnapshot()?.version)+    }+}
communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2DirectSipAuthTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2DirectSipAuthTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2DirectSipAuthTest.ktnew file mode 100644index 0000000000..7315aaae04--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2DirectSipAuthTest.kt@@ -0,0 +1,138 @@+package com.vayunmathur.communicate.rcs++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.communicate.data.rcs.RcsDirectSip+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.assertFalse+import kotlin.test.assertTrue++/**+ * Slice-3 pass 2: direct-SIP AKA registration — 401 challenge, digest+ * REGISTER built from the ISIM response (shadow TelephonyManager), 200 OK,+ * deregistration, and a full restart after stop (regression coverage for+ * the scope-cancellation restart bug).+ */+@RunWith(RobolectricTestRunner::class)+@Config(+    sdk = [34],+    shadows = [RcsSlice3Pass2ImsShadow::class, RcsSlice3Pass2TelephonyShadow::class],+)+class RcsSlice3Pass2DirectSipAuthTest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    @AfterTest+    fun tearDown() {+        RcsDirectSip.stop()+    }++    private class PcscfScript(val challengeFirst: Boolean) {+        val requests = CopyOnWriteArrayList<String>()+        val done = CountDownLatch(1)+        val error = java.util.concurrent.atomic.AtomicReference<String>()++        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()+                        fun readRequest(): List<String> {+                            val lines = mutableListOf<String>()+                            var line = input.readLine() ?: return lines+                            while (line.isNotEmpty()) {+                                lines += line+                                line = input.readLine() ?: break+                            }+                            return lines+                        }+                        fun respond(lines: List<String>, code: Int, reason: String, extra: String = "") {+                            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) }+                                ?.substringAfter(":")?.trim().orEmpty()+                            out.write(+                                ("SIP/2.0 $code $reason\r\nVia: SIP/2.0/TCP 127.0.0.1;branch=$branch\r\n" ++                                    "$callId\r\nCSeq: $cseq\r\n$extra" ++                                    "Contact: <sip:127.0.0.1:5060>;expires=600\r\n" ++                                    "Expires: 600\r\nContent-Length: 0\r\n\r\n").toByteArray(Charsets.UTF_8),+                            )+                            out.flush()+                        }+                        var first = true+                        while (true) {+                            val request = readRequest()+                            if (request.isEmpty()) break+                            requests += request.joinToString("\n")+                            if (first && challengeFirst) {+                                first = false+                                respond(+                                    request, 401, "Unauthorized",+                                    "WWW-Authenticate: Digest realm=\"carrier.example\", " ++                                        "nonce=\"bm9uY2UxMjM0NTY=\", qop=auth, algorithm=MD5\r\n",+                                )+                            } else {+                                respond(request, 200, "OK")+                                if (request.joinToString("\n").contains("expires=0")) break+                            }+                        }+                    }+                } catch (e: Throwable) {+                    error.set(e.toString())+                }+                done.countDown()+            }.apply { isDaemon = true; start() }+        }+    }++    @Test+    fun akaChallengeRegistrationAndRestart() = runBlocking {+        // --- First start: 401 -> AKA digest REGISTER -> 200. ---+        val server1 = ServerSocket(5060)+        val script1 = PcscfScript(challengeFirst = true)+        script1.serve(server1)+        assertTrue(RcsDirectSip.start(context, 1), "start failed: ${script1.requests}")+        assertTrue(RcsDirectSip.isRegistered())+        RcsDirectSip.stop()+        assertFalse(RcsDirectSip.isRegistered())+        assertTrue(script1.done.await(20, TimeUnit.SECONDS), "script1: ${script1.error.get()}")+        server1.close()+        assertEqualsRequests(script1)++        // --- Restart after stop: the stack must come back (scope fix). ---+        val server2 = ServerSocket(5060)+        val script2 = PcscfScript(challengeFirst = false)+        script2.serve(server2)+        assertTrue(RcsDirectSip.start(context, 1), "restart failed: ${script2.requests}")+        assertTrue(RcsDirectSip.isRegistered())+        RcsDirectSip.stop()+        assertTrue(script2.done.await(20, TimeUnit.SECONDS), "script2: ${script2.error.get()}")+        server2.close()+        assertTrue(script2.requests.first().contains("REGISTER sip:127.0.0.1"))+        assertTrue(script2.requests.last().contains("expires=0"))+        Unit+    }++    private fun assertEqualsRequests(script: PcscfScript) {+        val all = script.requests+        assertTrue(all.size >= 3, "requests=$all")+        assertTrue(all[0].contains("CSeq: 1 REGISTER"), all[0])+        val authed = all[1]+        assertTrue(authed.contains("Authorization: Digest "), authed)+        assertTrue(authed.contains("username="), authed)+        assertTrue(authed.contains("nonce=\"bm9uY2UxMjM0NTY=\""), authed)+        assertTrue(all.last().contains("expires=0"), all.last())+    }+}
communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2E2ETest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2E2ETest.kt b/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2E2ETest.ktnew file mode 100644index 0000000000..c6063f5f2a--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2E2ETest.kt@@ -0,0 +1,240 @@+package com.vayunmathur.communicate.rcs++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.communicate.data.rcs.RcsDatabase+import com.vayunmathur.communicate.data.rcs.RcsMlsGroup+import com.vayunmathur.communicate.data.rcs.RcsMlsIdentity+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 com.vayunmathur.communicate.data.rcs.e2e.e2eThreadFor+import com.vayunmathur.communicate.data.rcs.e2e.groupIdFor+import com.vayunmathur.communicate.data.rcs.e2e.hex+import com.vayunmathur.communicate.data.rcs.e2e.isMlsPayload+import com.vayunmathur.communicate.data.rcs.e2e.localE164+import com.vayunmathur.communicate.data.rcs.e2e.parseMembers+import com.vayunmathur.communicate.data.rcs.e2e.pruneMembers+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++/**+ * Slice-3 pass 2: RcsE2E Room-backed verification state, group/member+ * bookkeeping, and (when the host MLS library loads) a full native+ * identity → key-package → group → encrypt/decrypt round trip.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class RcsSlice3Pass2E2ETest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()+    private lateinit var testDb: RcsDatabase++    @BeforeTest+    fun setUp() {+        testDb = androidx.room3.Room.inMemoryDatabaseBuilder(context, RcsDatabase::class.java)+            .setDriver(androidx.sqlite.driver.bundled.BundledSQLiteDriver())+            .allowMainThreadQueries()+            .build()+        RcsDatabase.overrideForTest = testDb+        RcsPeerKeys.clear()+    }++    @AfterTest+    fun tearDown() {+        RcsDatabase.overrideForTest = null+        testDb.close()+        RcsPeerKeys.clear()+    }++    @Test+    fun verificationLifecycleThroughRoom() = runTest {+        val peer = "+15553003001"+        assertFalse(RcsE2E.isVerified(context, peer))+        // Verifying with no record is a no-op for isVerified.+        RcsE2E.setVerified(context, peer, true)+        assertFalse(RcsE2E.isVerified(context, peer))+        // Record verification against a package sketch.+        val pkg = byteArrayOf(1, 2, 3, 4, 5, 6)+        RcsE2E.setVerifiedWithPackage(context, peer, pkg)+        assertTrue(RcsE2E.isVerified(context, peer))+        // Same package: no identity-change warning.+        assertFalse(RcsE2E.checkPeerIdentityChange(context, peer, pkg))+        assertTrue(RcsE2E.isVerified(context, peer))+        // Different package: warning fires and verification is cleared.+        assertTrue(RcsE2E.checkPeerIdentityChange(context, peer, byteArrayOf(9, 9, 9)))+        assertFalse(RcsE2E.isVerified(context, peer))+        // Unverified peers never warn; empty packages never warn.+        assertFalse(RcsE2E.checkPeerIdentityChange(context, peer, byteArrayOf(8)))+        RcsE2E.setVerifiedWithPackage(context, peer, pkg)+        assertFalse(RcsE2E.checkPeerIdentityChange(context, peer, ByteArray(0)))+        // Toggle off via the plain setter.+        RcsE2E.setVerified(context, peer, false)+        assertFalse(RcsE2E.isVerified(context, peer))+        RcsE2E.setVerified(context, peer, true)+        assertTrue(RcsE2E.isVerified(context, peer))+    }++    @Test+    fun safetyFingerprintsFromCachedPackages() = runTest {+        val peer = "+15553003002"+        assertNull(RcsE2E.safetyFingerprint(peer))+        RcsPeerKeys.store(peer, byteArrayOf(42, 42, 42, 42))+        val fp = RcsE2E.safetyFingerprint(peer)+        assertNotNull(fp)+        // The digest digits are grouped in fours for read-off comparison.+        val groups = fp.split(" ")+        assertTrue(groups.size >= 16 && groups.all { it.all { c -> c.isDigit() } }, fp)+        assertEquals(fp, RcsE2E.safetyFingerprint(peer))+        // Our own side is empty until we publish (publishing needs transport).+        assertNull(RcsE2E.mySafetyFingerprint("+15553003003"))+        assertNull(RcsKeyDirectory.lastPublishedFor("+15553003003"))+    }++    @Test+    fun groupIdResolutionFromRoomRows() = runTest {+        // No group row.+        assertNull(RcsE2E.groupIdFor(context, "conv-pass2"))+        assertNull(with(RcsE2E) { groupIdFor(context, "conv-pass2") })+        // Pending pseudo-group is not a real group id.+        testDb.mlsGroupDao().upsert(+            RcsMlsGroup(groupIdHex = "pending:+1555", conversationId = "conv-pass2", storage = byteArrayOf(1)),+        )+        assertNull(RcsE2E.groupIdFor(context, "conv-pass2"))+        // A real hex id decodes to bytes (separate conversation: the DAO+        // returns one row per conversation).+        testDb.mlsGroupDao().upsert(+            RcsMlsGroup(groupIdHex = "00ff10ab", conversationId = "conv-pass2-real", storage = byteArrayOf(1)),+        )+        assertEquals(+            listOf(0.toByte(), 0xFF.toByte(), 0x10.toByte(), 0xAB.toByte()),+            RcsE2E.groupIdFor(context, "conv-pass2-real")?.toList(),+        )+        assertEquals(+            listOf(0.toByte(), 0xFF.toByte(), 0x10.toByte(), 0xAB.toByte()),+            with(RcsE2E) { groupIdFor(context, "conv-pass2-real") }?.toList(),+        )+    }++    @Test+    fun memberMapTrackingAndLeafLookup() = runTest {+        // parseMembers / pruneMembers are pure CSV helpers.+        assertEquals(emptyMap(), RcsE2E.parseMembers(""))+        assertEquals(mapOf("+1" to 0, "+2" to 3), RcsE2E.parseMembers("+1=0,+2=3"))+        assertEquals(mapOf("+1" to 0), RcsE2E.parseMembers("+1=0,bogus,+2=x,=2"))+        assertEquals("+1=0", RcsE2E.pruneMembers("+1=0,+2=3", setOf(3)))+        assertEquals("", RcsE2E.pruneMembers("+1=0", setOf(0)))++        // trackAddedMembers assigns sequential leaves after the current max.+        assertEquals("+1=1", RcsE2E.trackAddedMembers("", listOf("+1")))+        assertEquals("+1=1,+2=2", RcsE2E.trackAddedMembers("+1=1", listOf("+2", "+2", " ")))+        assertEquals("+9=5,+1=6", RcsE2E.trackAddedMembers("+9=5", listOf("+1")))++        // Leaf lookup reads the tracked map back from Room.+        testDb.mlsGroupDao().upsert(+            RcsMlsGroup(+                groupIdHex = "abcd", conversationId = "conv-pass2",+                storage = byteArrayOf(0), members = "+1555=1,+1666=2",+            ),+        )+        assertEquals(2, RcsE2E.leafIndexFor(context, "conv-pass2", "+1666"))+        assertEquals(1, RcsE2E.leafIndexFor(context, "conv-pass2", " +1555 "))+        assertNull(RcsE2E.leafIndexFor(context, "conv-pass2", "+1777"))+        assertNull(RcsE2E.leafIndexFor(context, "no-such-conv", "+1555"))+    }++    @Test+    fun localE164AndThreadHelpers() {+        // No line-1 number under Robolectric: null, never a throw.+        assertNull(RcsE2E.localE164(context))+        assertNull(with(RcsE2E) { localE164(context) })+        assertEquals("e2e:+1555", e2eThreadFor("+1555"))+        assertEquals("00ff", byteArrayOf(0, 0xFF.toByte()).hex())+        assertEquals("", ByteArray(0).hex())+    }++    @Test+    fun keyPackagePublishFailsClosedWithoutTransport() = runTest {+        assertFalse(RcsKeyDirectory.publishTo(context, "+15553003001", "+15553003002"))+        assertNull(RcsKeyDirectory.lastPublishedFor("+15553003001"))+    }++    @Test+    fun nativeMlsRoundTripWhenLibraryAvailable() = runTest {+        if (!RustMlsCrypto.isAvailable) {+            // Host library absent: every native entry point fails closed.+            assertNull(RcsE2E.identityFor(context, "+15553004001"))+            assertFalse(RcsE2E.isMlsPayload("Content-Type: ${RcsE2E.CT_MLS}\r\n\r\nQUJDRA=="))+            return@runTest+        }+        val me = "+15553004001"+        val peer = "+15553004002"+        // Identities generate once and persist in Room. On hosts where the+        // loaded crate cannot generate (stale/partial native build), every+        // native flow must fail closed instead.+        val identity = RcsE2E.identityFor(context, me)+        if (identity == null) {+            assertNull(RcsE2E.freshKeyPackage(context, me))+            assertNull(RcsE2E.createEncryptedGroup(context, me, "conv-mls-x", listOf(byteArrayOf(1))))+            assertNull(RcsE2E.joinEncryptedGroup(context, "conv-mls-x", byteArrayOf(1, 2, 3)))+            assertNull(RcsE2E.encryptTo(context, me, "conv-mls-x", byteArrayOf(1)))+            assertNull(RcsE2E.decryptFor(context, "conv-mls-x", byteArrayOf(1, 2, 3)))+            assertFalse(RcsE2E.removeMembers(context, me, "conv-mls-x", listOf(1)))+            assertFalse(RcsE2E.setupEncryptedGroup(context, me, "conv-mls-x", mapOf(peer to byteArrayOf(1))))+            assertFalse(RcsE2E.setupGroupWithPeer(context, me, "conv-mls-x", peer, byteArrayOf(1)))+            return@runTest+        }+        assertEquals(identity.toList(), RcsE2E.identityFor(context, me)?.toList())+        assertNull(RcsE2E.identityFor(context, ""))+        val row = testDb.mlsIdentityDao().get(me)+        assertNotNull(row)+        assertEquals(identity.toList(), row.identity.toList())++        // Key packages for both sides.+        val myKp = RcsE2E.freshKeyPackage(context, me)+        assertNotNull(myKp)+        val peerIdentity = RcsE2E.identityFor(context, peer)+        assertNotNull(peerIdentity)+        val peerKp = RcsE2E.freshKeyPackage(context, peer)+        assertNotNull(peerKp)++        // Create a group adding the peer, then join from the Welcome.+        val created = RcsE2E.createEncryptedGroup(context, me, "conv-mls-1", listOf(peerKp))+        assertNotNull(created)+        val (commit, welcome) = created+        assertTrue(commit.isNotEmpty() && welcome.isNotEmpty())+        val groupId = RcsE2E.joinEncryptedGroup(context, "conv-mls-2", welcome)+        assertNotNull(groupId)+        assertEquals(groupId.toList(), RcsE2E.groupIdFor(context, "conv-mls-1")?.toList())+        assertEquals(groupId.toList(), RcsE2E.groupIdFor(context, "conv-mls-2")?.toList())++        // Encrypt on one side, decrypt on the joined side.+        val payload = RcsE2E.encryptTo(context, me, "conv-mls-1", "secret hello".toByteArray(Charsets.UTF_8))+        assertNotNull(payload)+        val decrypted = RcsE2E.decryptFor(context, "conv-mls-2", payload)+        assertNotNull(decrypted)+        assertEquals("secret hello", decrypted.first.toString(Charsets.UTF_8))+        assertTrue(decrypted.second)++        // MLS payload detection sees the framed payload by content type.+        assertTrue(RcsE2E.isMlsPayload("Content-Type: ${RcsE2E.CT_MLS}\r\n\r\nAAAA"))+        assertTrue(with(RcsE2E) { isMlsPayload("Content-Type: ${RcsE2E.CT_WELCOME}\r\n\r\nAAAA") })++        // Group operations on unknown groups fail closed.+        assertNull(RcsE2E.encryptTo(context, me, "conv-unknown", byteArrayOf(1)))+        assertNull(RcsE2E.decryptFor(context, "conv-unknown", byteArrayOf(1, 2, 3)))+        assertNull(RcsE2E.joinEncryptedGroup(context, "conv-mls-3", byteArrayOf(1, 2, 3)))+        assertTrue(RcsE2E.createEncryptedGroup(context, me, "conv-x", emptyList()) == null)+    }+}
communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2FakeTransportTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2FakeTransportTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2FakeTransportTest.ktnew file mode 100644index 0000000000..05a6c249b6--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2FakeTransportTest.kt@@ -0,0 +1,416 @@+package com.vayunmathur.communicate.rcs++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.communicate.data.CommunicateAttachment+import com.vayunmathur.communicate.data.CommunicateRepository+import com.vayunmathur.communicate.data.rcs.RcsDatabase+import com.vayunmathur.communicate.data.rcs.RcsFileTransfer+import com.vayunmathur.communicate.data.rcs.RcsSessionManager+import com.vayunmathur.communicate.data.rcs.RcsSipTransport+import com.vayunmathur.communicate.data.rcs.RcsTyping+import com.vayunmathur.communicate.data.rcs.destroyHostedFocus+import com.vayunmathur.communicate.data.rcs.dropFocusSubscriber+import com.vayunmathur.communicate.data.rcs.focusMembers+import com.vayunmathur.communicate.data.rcs.hostGroupFocus+import com.vayunmathur.communicate.data.rcs.hostedFocusFor+import com.vayunmathur.communicate.data.rcs.inviteFocusMember+import com.vayunmathur.communicate.data.rcs.noteFocusJoin+import com.vayunmathur.communicate.data.rcs.noteFocusLeave+import com.vayunmathur.communicate.data.rcs.noteFocusSubscriber+import com.vayunmathur.communicate.data.rcs.onConferenceNotify+import com.vayunmathur.communicate.data.rcs.publishConferenceInfo+import com.vayunmathur.communicate.data.rcs.refreshEventSubscriptions+import com.vayunmathur.communicate.data.rcs.removeFocusMember+import com.vayunmathur.communicate.data.rcs.e2e.RcsE2E+import com.vayunmathur.communicate.data.rcs.e2e.RcsKeyDirectory+import com.vayunmathur.communicate.data.rcs.e2e.RustMlsCrypto+import com.vayunmathur.communicate.data.rcs.sendRcsDisplayReports+import com.vayunmathur.communicate.data.rcs.subscribeConferenceEvents+import java.util.UUID+import java.util.concurrent.CopyOnWriteArrayList+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++/**+ * Slice-3 pass 2: everything above the SIP transport, driven through the+ * transport's fake-sender test seam — outgoing sessions, focus hosting,+ * conference events, typing and display reports, file envelopes.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class RcsSlice3Pass2FakeTransportTest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()+    private lateinit var testDb: RcsDatabase++    data class Sent(val startLine: String, val headers: String, val body: ByteArray)++    private val sent = CopyOnWriteArrayList<Sent>()+    private var sendResult = true++    @BeforeTest+    fun setUp() {+        testDb = androidx.room3.Room.inMemoryDatabaseBuilder(context, RcsDatabase::class.java)+            .setDriver(androidx.sqlite.driver.bundled.BundledSQLiteDriver())+            .allowMainThreadQueries()+            .build()+        RcsDatabase.overrideForTest = testDb+        sent.clear()+        sendResult = true+        RcsSipTransport.fakeSenderForTest = { startLine, headers, body ->+            sent += Sent(startLine, headers, body.copyOf())+            sendResult+        }+        RcsSessionManager.sessionsMutable.value = emptyMap()+    }++    @AfterTest+    fun tearDown() {+        RcsSipTransport.fakeSenderForTest = null+        RcsSessionManager.sessionsMutable.value = emptyMap()+        RcsDatabase.overrideForTest = null+        testDb.close()+    }++    private fun sdpAnswer(setup: String = "passive"): String =+        "v=0\r\nm=message 2855 TCP/MSRP *\r\n" ++            "a=path:msrp://10.0.0.9:2855/peer;tcp\r\na=setup:$setup\r\n"++    @Test+    fun outgoingSessionLifecycleThroughFakeTransport() = runTest {+        val conv = "fake-conv-1"+        val dialogId = RcsSessionManager.startSession("tel:+15551234567", conv)+        assertNotNull(dialogId)+        val invite = sent.first()+        assertTrue(invite.startLine.startsWith("INVITE tel:+15551234567 SIP/2.0"), invite.startLine)+        assertTrue(invite.headers.contains("Conversation-ID: $conv"))+        assertTrue(invite.body.toString(Charsets.UTF_8).contains("a=setup:active"))+        val session = RcsSessionManager.sessionFor(conv)+        assertNotNull(session)+        assertFalse(session.confirmed)++        // The 200 OK answer establishes the dialog and triggers an ACK send.+        sent.clear()+        RcsSessionManager.onSipResponse(+            200, session.callId, "remote-tag-1", sdpAnswer(),+            "Contact: <sip:[email protected]>\r\nRecord-Route: <sip:proxy1;lr>\r\nRecord-Route: <sip:proxy2;lr>\r\n",+        )+        val established = RcsSessionManager.sessionFor(conv)+        assertNotNull(established)+        assertEquals("remote-tag-1", established.remoteTag)+        assertEquals("msrp://10.0.0.9:2855/peer;tcp", established.msrpRemotePath)+        assertEquals("sip:[email protected]", established.remoteContact)+        assertEquals(listOf("sip:proxy2;lr", "sip:proxy1;lr"), established.routeSet)+        assertTrue(established.confirmed)+        assertTrue(sent.any { it.startLine.startsWith("ACK ") }, sent.map { it.startLine }.toString())++        // In-dialog MESSAGE advances the CSeq.+        val cseqBefore = RcsSessionManager.sessionFor(conv)!!.nextCseq+        assertTrue(RcsSessionManager.sendInDialogMessage(conv, "cpim-body".toByteArray()))+        val msg = sent.last { it.startLine.startsWith("MESSAGE ") }+        assertTrue(msg.headers.contains("CSeq: $cseqBefore MESSAGE"))+        assertEquals(cseqBefore + 1, RcsSessionManager.sessionFor(conv)!!.nextCseq)++        // Terminate sends an in-dialog BYE and drops the session.+        assertTrue(RcsSessionManager.terminateSession(conv))+        assertTrue(sent.any { it.startLine.startsWith("BYE ") })+        assertNull(RcsSessionManager.sessionFor(conv))+    }++    @Test+    fun outgoingSessionFailureModes() = runTest {+        // Transport refuses the INVITE: no session is tracked.+        sendResult = false+        assertNull(RcsSessionManager.startSession("tel:+1555", "fake-conv-fail"))+        assertNull(RcsSessionManager.sessionFor("fake-conv-fail"))+        assertNull(RcsSessionManager.startGroupSession("sip:focus@rcs", "s", "fake-conv-fail"))+        sendResult = true++        // A failure response tears a pending session down.+        val conv = "fake-conv-2"+        val dialogId = RcsSessionManager.startGroupSession("sip:focus.example@rcs", "Weekly sync", conv)+        assertNotNull(dialogId)+        val groupInvite = sent.last { it.startLine.startsWith("INVITE ") }+        assertTrue(groupInvite.headers.contains("Subject: Weekly sync"))+        val session = RcsSessionManager.sessionFor(conv)+        assertNotNull(session)+        assertTrue(session.isGroup)+        RcsSessionManager.onSipResponse(486, session.callId, null, null)+        assertNull(RcsSessionManager.sessionFor(conv))+    }++    @Test+    fun acceptAndDeclineIncomingThroughFakeTransport() = runTest {+        val callId = "fake-in-${UUID.randomUUID()}"+        val offer = "v=0\r\nm=message 2855 TCP/MSRP *\r\n" ++            "a=path:msrp://10.0.0.9:2855/offer;tcp\r\na=setup:passive\r\n"+        val session = RcsSessionManager.onSipRequest(+            "INVITE", callId, "sip:+15557654321@rcs", "application/sdp", offer, "peer-tag",+        )+        assertNotNull(session)+        val conv = session.conversationId+        sent.clear()+        assertTrue(RcsSessionManager.acceptIncoming(conv))+        val ok200 = sent.first()+        assertEquals("SIP/2.0 200 OK", ok200.startLine)+        val answered = RcsSessionManager.sessionFor(conv)+        assertNotNull(answered)+        assertEquals("msrp://10.0.0.9:2855/offer;tcp", answered.msrpRemotePath)++        // Declining another incoming invite sends 488 and drops it.+        val callId2 = "fake-in2-${UUID.randomUUID()}"+        val session2 = RcsSessionManager.onSipRequest(+            "INVITE", callId2, "sip:+15557654322@rcs", "application/sdp", offer, "peer-tag2",+        )+        assertNotNull(session2)+        sent.clear()+        assertTrue(RcsSessionManager.declineIncoming(session2.conversationId))+        assertEquals("SIP/2.0 488 Not Acceptable Here", sent.first().startLine)+        assertNull(RcsSessionManager.sessionFor(session2.conversationId))+        assertFalse(RcsSessionManager.acceptIncoming("no-such-conv"))+    }++    @Test+    fun hostedFocusLifecycleThroughFakeTransport() = runTest {+        val conv = "fake-focus-1"+        val focusUri = RcsSessionManager.hostGroupFocus(+            conv, "Team chat", listOf("+15551001", " +15551002 ", "+15551001", ""),+        )+        assertNotNull(focusUri)+        assertTrue(focusUri.startsWith("conf:"))+        assertEquals(focusUri, RcsSessionManager.hostedFocusFor(conv))+        assertEquals(setOf("+15551001", "+15551002"), RcsSessionManager.focusMembers(focusUri))+        // One REFER per distinct peer.+        assertEquals(2, sent.count { it.startLine.startsWith("REFER ") })+        assertTrue(sent.all { it.headers.contains("Refer-To: <$focusUri>") })++        // Local join/leave bookkeeping.+        RcsSessionManager.noteFocusJoin(focusUri, " +15551003 ")+        assertTrue(RcsSessionManager.focusMembers(focusUri)!!.contains("+15551003"))+        RcsSessionManager.noteFocusLeave(focusUri, "+15551003")+        assertFalse(RcsSessionManager.focusMembers(focusUri)!!.contains("+15551003"))++        // Invite adds a member (REFER accepted); a failing REFER does not.+        assertTrue(RcsSessionManager.inviteFocusMember(conv, "+15551004"))+        assertTrue(RcsSessionManager.focusMembers(focusUri)!!.contains("+15551004"))+        sendResult = false+        assertFalse(RcsSessionManager.inviteFocusMember(conv, "+15551005"))+        assertFalse(RcsSessionManager.focusMembers(focusUri)!!.contains("+15551005"))+        sendResult = true+        assertFalse(RcsSessionManager.inviteFocusMember(conv, "  "))+        assertFalse(RcsSessionManager.inviteFocusMember("unknown-conv", "+1555"))++        // Remove drops the member even though the BYE is best-effort.+        assertTrue(RcsSessionManager.removeFocusMember(conv, "+15551004"))+        assertFalse(RcsSessionManager.focusMembers(focusUri)!!.contains("+15551004"))+        assertFalse(RcsSessionManager.removeFocusMember(conv, "+15551004"))++        // Destroy tears the focus down.+        assertTrue(RcsSessionManager.destroyHostedFocus(conv))+        assertNull(RcsSessionManager.hostedFocusFor(conv))+        assertNull(RcsSessionManager.focusMembers(focusUri))+    }++    @Test+    fun hostedFocusFailsWhenNoReferAccepted() = runTest {+        sendResult = false+        assertNull(RcsSessionManager.hostGroupFocus("fake-focus-2", "s", listOf("+15551001")))+        assertNull(RcsSessionManager.hostedFocusFor("fake-focus-2"))+        sendResult = true+        // No participants: nothing to host.+        assertNull(RcsSessionManager.hostGroupFocus("fake-focus-3", "s", emptyList()))+        assertNull(RcsSessionManager.hostGroupFocus("fake-focus-3", "s", listOf(" ", "")))+    }++    @Test+    fun conferenceSubscribeNotifyAndRefresh() = runTest {+        val conv = "fake-conf-1"+        val focusUri = "sip:focus.example@rcs"+        assertTrue(RcsSessionManager.subscribeConferenceEvents(focusUri, conv))+        val sub = sent.first { it.startLine.startsWith("SUBSCRIBE ") }+        assertTrue(sub.headers.contains("Event: conference"))+        assertTrue(sub.headers.contains("Accept: application/conference-info+xml"))+        // Idempotent re-subscribe.+        val sendsBefore = sent.size+        assertTrue(RcsSessionManager.subscribeConferenceEvents(focusUri, conv))+        assertEquals(sendsBefore, sent.size)++        // A NOTIFY reconciles members and records the version; stale repeats are ignored.+        fun conferenceInfo(version: Int, users: String, deleted: String = ""): String =+            "<conference-info entity=\"$focusUri\" version=\"$version\">" ++                "<users>$users$deleted</users></conference-info>"+        val userA = "<user entity=\"sip:+15551001@rcs\"><state>full</state></user>"+        val userB = "<user entity=\"sip:+15551002@rcs\"><state>full</state></user>"+        val (added1, removed1) = RcsSessionManager.onConferenceNotify(conv, conferenceInfo(1, userA))+        assertEquals(listOf("sip:+15551001@rcs"), added1)+        assertEquals(emptyList(), removed1)+        // Same version again: stale.+        val (addedStale, _) = RcsSessionManager.onConferenceNotify(conv, conferenceInfo(1, userB))+        assertEquals(emptyList(), addedStale)+        // Newer version with a deletion.+        val deletedB = "<user entity=\"sip:+15551002@rcs\" state=\"deleted\"></user>"+        val (added2, removed2) = RcsSessionManager.onConferenceNotify(+            conv, conferenceInfo(2, userA, deletedB),+        )+        assertEquals(listOf("sip:+15551001@rcs"), added2)+        assertEquals(listOf("sip:+15551002@rcs"), removed2)++        // Refresh re-SUBSCRIBEs on the same dialog.+        sent.clear()+        RcsSessionManager.refreshEventSubscriptions()+        assertTrue(sent.any { it.startLine.startsWith("SUBSCRIBE ") && it.headers.contains("CSeq: 2 SUBSCRIBE") })+    }++    @Test+    fun publishConferenceInfoToSubscribers() = runTest {+        val conv = "fake-pub-1"+        val focusUri = RcsSessionManager.hostGroupFocus(conv, "s", listOf("+15551001"))+        assertNotNull(focusUri)+        // No subscribers yet: publish is a no-op (but must not throw).+        sent.clear()+        RcsSessionManager.publishConferenceInfo(focusUri)+        assertTrue(sent.isEmpty())+        RcsSessionManager.noteFocusSubscriber("sub-call-9", focusUri)+        RcsSessionManager.publishConferenceInfo(focusUri)+        val notify = sent.first { it.startLine.startsWith("NOTIFY ") }+        assertTrue(notify.headers.contains("Call-ID: sub-call-9"))+        assertTrue(notify.headers.contains("Event: conference"))+        val body = notify.body.toString(Charsets.UTF_8)+        assertTrue(body.contains(focusUri), body)+        assertTrue(body.contains("+15551001"), body)+        // Version increments per publish.+        sent.clear()+        RcsSessionManager.publishConferenceInfo(focusUri)+        assertTrue(sent.first().body.toString(Charsets.UTF_8).contains("version=\"2\""))+        RcsSessionManager.dropFocusSubscriber("sub-call-9")+        sent.clear()+        RcsSessionManager.publishConferenceInfo(focusUri)+        assertTrue(sent.isEmpty())+        assertTrue(RcsSessionManager.destroyHostedFocus(conv))+    }++    @Test+    fun typingAndDisplayReportsThroughFakeTransport() = runTest {+        assertTrue(RcsSipTransport.canSend())+        // Pager-mode typing (no dialog for this recipient).+        assertTrue(RcsTyping.sendComposing("+15554001", true))+        val typingMsg = sent.last { it.startLine.startsWith("MESSAGE ") }+        assertTrue(typingMsg.headers.contains("Content-Type: application/im-iscomposing+xml"))+        assertTrue(typingMsg.body.toString(Charsets.UTF_8).contains("active"))+        assertTrue(RcsTyping.sendComposing("+15554001", false))++        // Display reports: cache inbound rows, then report each once.+        testDb.cachedMessageDao().upsert(+            com.vayunmathur.communicate.data.rcs.RcsCachedMessage(+                messageId = "fake-disp-1", conversationId = "+15554002", body = "hi",+                timestamp = 1, outgoing = false, imdnId = "imdn-fake-1",+            ),+        )+        testDb.cachedMessageDao().upsert(+            com.vayunmathur.communicate.data.rcs.RcsCachedMessage(+                messageId = "fake-disp-2", conversationId = "+15554002", body = "out",+                timestamp = 2, outgoing = true, imdnId = "imdn-fake-2",+            ),+        )+        sent.clear()+        with(CommunicateRepository) { sendRcsDisplayReports(context, "+15554002") }+        // Only the inbound row is reported.+        assertEquals(1, sent.count { it.startLine.startsWith("MESSAGE ") })+        assertTrue(sent.first().body.toString(Charsets.UTF_8).contains("imdn-fake-1"))+        // A second pass reports nothing new.+        sent.clear()+        with(CommunicateRepository) { sendRcsDisplayReports(context, "+15554002") }+        assertTrue(sent.isEmpty())+    }++    @Test+    fun conferenceNotifyReconcilesHostedFocusMembers() = runTest {+        val conv = "fake-conf-host"+        val focusUri = RcsSessionManager.hostGroupFocus(conv, "s", listOf("+15551001"))+        assertNotNull(focusUri)+        // A carrier-style NOTIFY naming our focus reconciles the member set.+        val body = "<conference-info entity=\"$focusUri\" version=\"1\">" ++            "<users>" ++            "<user entity=\"sip:+15551001@rcs\"><state>full</state></user>" ++            "<user entity=\"sip:+15551009@rcs\"><state>full</state></user>" ++            "</users></conference-info>"+        val (added, removed) = RcsSessionManager.onConferenceNotify(conv, body)+        assertEquals(listOf("sip:+15551001@rcs", "sip:+15551009@rcs"), added)+        assertEquals(emptyList(), removed)+        assertTrue(RcsSessionManager.focusMembers(focusUri)!!.contains("sip:+15551009@rcs"))+        // A newer version deleting a member removes it locally too.+        val body2 = "<conference-info entity=\"$focusUri\" version=\"2\">" ++            "<users>" ++            "<user entity=\"sip:+15551009@rcs\" state=\"deleted\"></user>" ++            "</users></conference-info>"+        val (_, removed2) = RcsSessionManager.onConferenceNotify(conv, body2)+        assertEquals(listOf("sip:+15551009@rcs"), removed2)+        assertFalse(RcsSessionManager.focusMembers(focusUri)!!.contains("sip:+15551009@rcs"))+        assertTrue(RcsSessionManager.destroyHostedFocus(conv))+    }++    @Test+    fun e2eEnvelopesThroughFakeTransportWhenNativeWorks() = runTest {+        // Key-package publication and encrypted setup ride the fake sender+        // when the native MLS crate works; without it they fail closed.+        val published = RcsKeyDirectory.publishTo(context, "+15557001", "+15557002")+        if (!RustMlsCrypto.isAvailable || RcsE2E.identityFor(context, "+15557001") == null) {+            assertFalse(published)+            // The key *request* envelope needs no crypto: it still sends.+            assertTrue(RcsE2E.requestKeyPackage("+15557002"))+            assertTrue(sent.any { it.body.toString(Charsets.UTF_8).contains(RcsE2E.CT_KEY_REQUEST) })+            return@runTest+        }+        assertTrue(published)+        assertNotNull(RcsKeyDirectory.lastPublishedFor("+15557001"))+        val kpMessage = sent.first { it.headers.contains(RcsE2E.CT_KEY_PACKAGE) || it.body.toString(Charsets.UTF_8).contains(RcsE2E.CT_KEY_PACKAGE) }+        assertTrue(kpMessage.body.toString(Charsets.UTF_8).contains(RcsE2E.CT_KEY_PACKAGE))+        assertTrue(RcsE2E.requestEncryptedChat(context, "+15557001", "+15557002"))+        assertTrue(sent.any { it.body.toString(Charsets.UTF_8).contains(RcsE2E.CT_KEY_REQUEST) })+    }++    @Test+    fun fileTransferEnvelopeThroughFakeTransport() = runTest {+        val attachment = CommunicateAttachment(+            contentUri = "content://media/42", mimeType = "image/png", fileName = "photo.png",+        )+        assertTrue(+            RcsFileTransfer.sendFiles(+                context, CommunicateRepository, "+15555001", "look at this", listOf(attachment),+            ),+        )+        val msg = sent.first { it.startLine.startsWith("MESSAGE ") }+        val wireBody = msg.body.toString(Charsets.UTF_8)+        assertTrue(wireBody.contains("FT-URL: content://media/42"), wireBody)+        assertTrue(wireBody.contains("FT-MIME: image/png"), wireBody)+        assertTrue(wireBody.contains("FT-NAME: photo.png"), wireBody)+        // The outgoing row was cached with the FT metadata.+        val rows = testDb.cachedMessageDao().getForConversation("+15555001")+        assertEquals(1, rows.size)+        assertEquals("look at this", rows.first().body)+        assertEquals("content://media/42", rows.first().ftUrl)+        assertEquals("image/png", rows.first().ftMime)++        // A rejected envelope does not cache and does not count as sent.+        sent.clear()+        sendResult = false+        assertFalse(+            RcsFileTransfer.sendFiles(+                context, CommunicateRepository, "+15555002", "", listOf(attachment),+            ),+        )+        assertTrue(testDb.cachedMessageDao().getForConversation("+15555002").isEmpty())+        sendResult = true+    }+}
communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2FtNetworkTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2FtNetworkTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2FtNetworkTest.ktnew file mode 100644index 0000000000..0127e0a6aa--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2FtNetworkTest.kt@@ -0,0 +1,286 @@+package com.vayunmathur.communicate.rcs++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.sun.net.httpserver.HttpServer+import com.vayunmathur.communicate.data.CommunicateAttachment+import com.vayunmathur.communicate.data.CommunicateRepository+import com.vayunmathur.communicate.data.rcs.MsrpSetup+import com.vayunmathur.communicate.data.rcs.RcsDatabase+import com.vayunmathur.communicate.data.rcs.RcsFileTransferHttp+import com.vayunmathur.communicate.data.rcs.RcsMsrpFraming+import com.vayunmathur.communicate.data.rcs.RcsSession+import com.vayunmathur.communicate.data.rcs.RcsSessionManager+import com.vayunmathur.communicate.data.rcs.RcsSipTransport+import java.io.File+import java.net.InetSocketAddress+import java.net.ServerSocket+import java.util.concurrent.CopyOnWriteArrayList+import java.util.concurrent.CountDownLatch+import java.util.concurrent.TimeUnit+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.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Slice-3 pass 2: FT-over-HTTP against a real loopback HTTP server (digest+ * challenge → multipart upload → download URL), FT-over-MSRP against a+ * loopback MSRP peer, and the full sendFile chain over the fake SIP sender.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34], shadows = [RcsSlice3Pass2ConnectivityShadow::class])+class RcsSlice3Pass2FtNetworkTest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()+    private lateinit var testDb: RcsDatabase+    private var http: HttpServer? = null+    private val sent = CopyOnWriteArrayList<Triple<String, String, ByteArray>>()++    @BeforeTest+    fun setUp() {+        testDb = androidx.room3.Room.inMemoryDatabaseBuilder(context, RcsDatabase::class.java)+            .setDriver(androidx.sqlite.driver.bundled.BundledSQLiteDriver())+            .allowMainThreadQueries()+            .build()+        RcsDatabase.overrideForTest = testDb+        sent.clear()+        RcsSipTransport.fakeSenderForTest = { s, h, b -> sent += Triple(s, h, b.copyOf()); true }+    }++    @AfterTest+    fun tearDown() {+        http?.stop(0)+        http = null+        RcsFileTransferHttp.contentServerUri = null+        RcsSipTransport.fakeSenderForTest = null+        RcsSessionManager.sessionsMutable.value = emptyMap()+        RcsDatabase.overrideForTest = null+        testDb.close()+    }++    private fun attachmentFor(bytes: ByteArray, name: String = "photo.png"): CommunicateAttachment {+        val file = File(context.cacheDir, name).apply { writeBytes(bytes) }+        return CommunicateAttachment(+            contentUri = android.net.Uri.fromFile(file).toString(),+            mimeType = "image/png", fileName = name,+        )+    }++    private fun startHttp(handler: (com.sun.net.httpserver.HttpExchange) -> Unit): String {+        val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0)+        server.createContext("/") { exchange -> handler(exchange) }+        server.executor = java.util.concurrent.Executors.newCachedThreadPool()+        server.start()+        http = server+        return "http://127.0.0.1:${server.address.port}/ft"+    }++    private fun digestChallenge(exchange: com.sun.net.httpserver.HttpExchange) {+        exchange.responseHeaders.set(+            "WWW-Authenticate",+            "Digest realm=\"rcs\", nonce=\"abc123nonce\", qop=auth",+        )+        exchange.sendResponseHeaders(401, -1)+        exchange.close()+    }++    @Test+    fun uploadHarvestsChallengeAndPostsMultipart() = runTest {+        val bodies = CopyOnWriteArrayList<ByteArray>()+        val authHeaders = CopyOnWriteArrayList<String>()+        val url = startHttp { exchange ->+            val body = exchange.requestBody.readAllBytes()+            if (exchange.requestHeaders.getFirst("Authorization") == null) {+                digestChallenge(exchange)+            } else {+                bodies += body+                authHeaders += exchange.requestHeaders.getFirst("Authorization")+                val payload = "https://files.example/dl/abc123".toByteArray()+                exchange.sendResponseHeaders(200, payload.size.toLong())+                exchange.responseBody.write(payload)+                exchange.close()+            }+        }+        RcsFileTransferHttp.contentServerUri = url+        val attachment = attachmentFor(ByteArray(64) { it.toByte() })+        val downloadUrl = RcsFileTransferHttp.upload(context, attachment)+        assertEquals("https://files.example/dl/abc123", downloadUrl)+        assertEquals(1, bodies.size)+        val multipart = bodies.first().toString(Charsets.ISO_8859_1)+        assertTrue(multipart.contains("name=\"tid\""), multipart.take(300))+        assertTrue(multipart.contains("filename=\"photo.png\""), multipart.take(400))+        assertTrue(authHeaders.first().startsWith("Digest username="), authHeaders.first())+        assertTrue(authHeaders.first().contains("nonce=\"abc123nonce\""))+    }++    @Test+    fun uploadUsesInjectedGbaCredentialsWhenPresent() = runTest {+        val authHeaders = CopyOnWriteArrayList<String>()+        val url = startHttp { exchange ->+            exchange.requestBody.readAllBytes()+            val auth = exchange.requestHeaders.getFirst("Authorization")+            if (auth == null) {+                digestChallenge(exchange)+            } else {+                authHeaders += auth+                val payload = "https://files.example/dl/gba1".toByteArray()+                exchange.sendResponseHeaders(200, payload.size.toLong())+                exchange.responseBody.write(payload)+                exchange.close()+            }+        }+        RcsFileTransferHttp.contentServerUri = url+        com.vayunmathur.communicate.data.rcs.RcsGbaAuth.injected =+            com.vayunmathur.communicate.data.rcs.RcsGbaAuth.GbaCredentials("bt-user-1", byteArrayOf(5, 6, 7))+        try {+            val downloadUrl = RcsFileTransferHttp.upload(context, attachmentFor(ByteArray(24) { 2 }))+            assertEquals("https://files.example/dl/gba1", downloadUrl)+            assertTrue(authHeaders.first().contains("username=\"bt-user-1\""), authHeaders.first())+        } finally {+            com.vayunmathur.communicate.data.rcs.RcsGbaAuth.injected = null+        }+    }++    @Test+    fun uploadRetryAfterSecond401GivesUp() = runTest {+        var requests = 0+        val url = startHttp { exchange ->+            requests+++            exchange.requestBody.readAllBytes()+            // Every POST is challenged, including the authenticated retry.+            digestChallenge(exchange)+        }+        RcsFileTransferHttp.contentServerUri = url+        val attachment = attachmentFor(ByteArray(16) { 1 })+        assertNull(RcsFileTransferHttp.upload(context, attachment))+        assertTrue(requests >= 2, "requests=$requests")+    }++    @Test+    fun uploadWithoutChallengeReturnsNull() = runTest {+        val url = startHttp { exchange ->+            exchange.requestBody.readAllBytes()+            val payload = "no challenge here".toByteArray()+            exchange.sendResponseHeaders(200, payload.size.toLong())+            exchange.responseBody.write(payload)+            exchange.close()+        }+        RcsFileTransferHttp.contentServerUri = url+        assertNull(RcsFileTransferHttp.upload(context, attachmentFor(ByteArray(8))))+    }++    @Test+    fun downloadFetchesBytesToCacheFile() = runTest {+        val payload = ByteArray(128) { (255 - it).toByte() }+        val url = startHttp { exchange ->+            exchange.sendResponseHeaders(200, payload.size.toLong())+            exchange.responseBody.write(payload)+            exchange.close()+        }+        val file = RcsFileTransferHttp.download(context, url)+        assertNotNull(file)+        assertEquals(payload.toList(), file.readBytes().toList())+        // A 404 download is rejected.+        val missing = startHttp { exchange ->+            exchange.sendResponseHeaders(404, -1)+            exchange.close()+        }+        assertNull(RcsFileTransferHttp.download(context, missing))+    }++    @Test+    fun sendFileOverHttpPathCachesAndSends() = runTest {+        val url = startHttp { exchange ->+            val body = exchange.requestBody.readAllBytes()+            if (exchange.requestHeaders.getFirst("Authorization") == null) {+                digestChallenge(exchange)+            } else {+                body.size+                val payload = "<resp>https://files.example/dl/send1</resp>".toByteArray()+                exchange.sendResponseHeaders(200, payload.size.toLong())+                exchange.responseBody.write(payload)+                exchange.close()+            }+        }+        RcsFileTransferHttp.contentServerUri = url+        val attachment = attachmentFor(ByteArray(32) { 3 }, "send.png")+        assertTrue(RcsFileTransferHttp.sendFile(context, CommunicateRepository, "+15556001", attachment, "caption here"))+        val ftMsg = sent.first { it.first.startsWith("MESSAGE ") }+        val wire = ftMsg.third.toString(Charsets.UTF_8)+        assertTrue(wire.contains("File-URL: https://files.example/dl/send1"), wire)+        val rows = testDb.cachedMessageDao().getForConversation("+15556001")+        assertEquals(1, rows.size)+        assertEquals("caption here", rows.first().body)+        assertEquals("https://files.example/dl/send1", rows.first().ftUrl)+    }++    @Test+    fun sendFileOverMsrpSession() = runTest {+        val server = ServerSocket(0)+        val port = server.localPort+        val peerDone = CountDownLatch(1)+        val peerError = java.util.concurrent.atomic.AtomicReference<String>()+        Thread {+            try {+                server.accept().use { s ->+                    s.soTimeout = 20_000+                    val input = s.getInputStream().bufferedReader(Charsets.UTF_8)+                    // Two CPIM SENDs (file descriptor chunks + descriptor): ack each frame.+                    repeat(2) {+                        // Read head.+                        val head = mutableListOf<String>()+                        var line = input.readLine()+                        var guard = 0+                        while (line != null && line.isNotEmpty() && guard++ < 32) {+                            head += line+                            line = input.readLine()+                        }+                        val txid = head.firstOrNull()?.split(" ")?.getOrNull(1).orEmpty()+                        // Consume body lines to the end marker.+                        while (true) {+                            val l = input.readLine() ?: break+                            if (l.startsWith("-------$txid")) break+                        }+                        val out = s.getOutputStream()+                        out.write(RcsMsrpFraming.buildErrorResponse("", txid, 200, "OK"))+                        out.flush()+                    }+                }+            } catch (e: Throwable) {+                peerError.set(e.toString())+            }+            peerDone.countDown()+        }.apply { isDaemon = true; start() }++        val recipient = "+15556002"+        RcsSessionManager.sessionsMutable.value = mapOf(+            recipient to RcsSession(+                dialogId = "ft-d", callId = "ft-call-1", localTag = "lt", remoteTag = "rt",+                remoteUri = "sip:peer@rcs", conversationId = recipient,+                msrpLocalPath = "msrp://127.0.0.1:$port/self;tcp",+                msrpRemotePath = "msrp://127.0.0.1:$port/peer;tcp",+                msrpSetup = MsrpSetup.PASSIVE, confirmed = true,+            ),+        )+        val png = java.util.Base64.getDecoder().decode(+            "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=",+        )+        val attachment = attachmentFor(png, "msrp.png")+        assertTrue(RcsFileTransferHttp.sendFile(context, CommunicateRepository, recipient, attachment, "via msrp"))+        assertTrue(peerDone.await(20, TimeUnit.SECONDS), "peer=${peerError.get()}")+        assertNull(peerError.get())+        val rows = testDb.cachedMessageDao().getForConversation(recipient)+        assertEquals(1, rows.size)+        assertEquals("msrp:ft-call-1", rows.first().ftUrl)+        assertEquals("via msrp", rows.first().body)+        server.close()+    }+}
communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2ImsShadow.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2ImsShadow.kt b/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2ImsShadow.ktnew file mode 100644index 0000000000..8590e2292b--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2ImsShadow.kt@@ -0,0 +1,75 @@+package com.vayunmathur.communicate.rcs++import android.net.ConnectivityManager+import android.net.LinkAddress+import android.net.LinkProperties+import android.net.Network+import android.net.NetworkCapabilities+import android.net.NetworkRequest+import java.net.InetAddress+import org.robolectric.annotation.Implementation+import org.robolectric.annotation.Implements+import org.robolectric.shadows.ShadowConnectivityManager+import org.robolectric.shadows.ShadowNetwork++/**+ * A fake IMS PDN for slice-3 pass 2: one network with IMS capability, link+ * properties carrying a wildcard local address (bindable, and not filtered+ * out as loopback by the production local-IP scan) plus a loopback P-CSCF.+ * Lets the IMS network, MSRP listen and direct-SIP layers run end to end+ * over loopback sockets.+ */+@Implements(ConnectivityManager::class)+class RcsSlice3Pass2ImsShadow : ShadowConnectivityManager() {++    @Implementation+    override fun getAllNetworks(): Array<Network> = arrayOf(imsNetwork)++    @Implementation+    override fun getNetworkCapabilities(network: Network?): NetworkCapabilities = imsCapabilities++    @Implementation+    override fun getLinkProperties(network: Network?): LinkProperties = imsLinkProperties()++    @Implementation+    override fun requestNetwork(request: NetworkRequest, callback: ConnectivityManager.NetworkCallback) {+        callback.onAvailable(imsNetwork)+    }++    companion object {+        val imsNetwork: Network = ShadowNetwork.newInstance(770_001)++        val imsCapabilities: NetworkCapabilities by lazy {+            val ctor = NetworkCapabilities::class.java.getDeclaredConstructor()+            ctor.isAccessible = true+            ctor.newInstance().also { caps ->+                val addCapability = NetworkCapabilities::class.java+                    .getMethod("addCapability", Int::class.javaPrimitiveType)+                addCapability.invoke(caps, NetworkCapabilities.NET_CAPABILITY_IMS)+                addCapability.invoke(caps, NetworkCapabilities.NET_CAPABILITY_MMTEL)+                NetworkCapabilities::class.java+                    .getMethod("addTransportType", Int::class.javaPrimitiveType)+                    .invoke(caps, NetworkCapabilities.TRANSPORT_CELLULAR)+            }+        }++        fun imsLinkProperties(): LinkProperties {+            val ctor = LinkProperties::class.java.getDeclaredConstructor()+            ctor.isAccessible = true+            val props = ctor.newInstance()+            val linkAddress = LinkAddress::class.java+                .getConstructor(InetAddress::class.java, Int::class.javaPrimitiveType)+                .apply { isAccessible = true }+                .newInstance(InetAddress.getByName("0.0.0.0"), 0)+            LinkProperties::class.java.getMethod("addLinkAddress", LinkAddress::class.java)+                .invoke(props, linkAddress)+            // P-CSCF list (hidden field; name varies by SDK level).+            val field = runCatching { LinkProperties::class.java.getDeclaredField("mPcscfServers") }+                .getOrElse { LinkProperties::class.java.getDeclaredField("mPcscfs") }+            field.isAccessible = true+            @Suppress("UNCHECKED_CAST")+            (field.get(props) as MutableList<InetAddress>).add(InetAddress.getByName("127.0.0.1"))+            return props+        }+    }+}
communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2ImsTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2ImsTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2ImsTest.ktnew file mode 100644index 0000000000..0f0be9fffb--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2ImsTest.kt@@ -0,0 +1,436 @@+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 com.vayunmathur.communicate.data.rcs.RcsMsrp+import com.vayunmathur.communicate.data.rcs.RcsMsrpListen+import com.vayunmathur.communicate.data.rcs.RcsMsrpTls+import java.net.ServerSocket+import java.net.Socket+import java.util.concurrent.CopyOnWriteArrayList+import java.util.concurrent.CountDownLatch+import java.util.concurrent.TimeUnit+import java.util.concurrent.atomic.AtomicReference+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.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Slice-3 pass 2 on a fake IMS PDN ([RcsSlice3Pass2ImsShadow]): the IMS+ * network scan/request, IMS-bound sockets, the MSRP listen/accept loop+ * (matched, unknown and TLS-on-plaintext routing), and a full direct-SIP+ * REGISTER + MESSAGE exchange against a loopback P-CSCF.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34], shadows = [RcsSlice3Pass2ImsShadow::class])+class RcsSlice3Pass2ImsTest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    @AfterTest+    fun tearDown() {+        RcsMsrpListen.stop()+        RcsDirectSip.stop()+        RcsImsNetwork.reset()+    }++    @Test+    fun imsNetworkScanFindsFakePdn() = runTest {+        RcsImsNetwork.reset()+        val network = RcsImsNetwork.imsNetwork(context, 1)+        assertNotNull(network)+        // Cached on the second call.+        assertEquals(network, RcsImsNetwork.imsNetwork(context, 1))+        assertEquals("0.0.0.0", RcsImsNetwork.lastLocalIp)+        assertEquals(listOf("0.0.0.0"), RcsImsNetwork.localIps(context, network))+        val listen = RcsImsNetwork.listenSocket(context)+        assertNotNull(listen)+        assertEquals("0.0.0.0", listen.localIp)+        assertTrue(listen.localPort > 0)+        assertEquals("msrp://0.0.0.0:${listen.localPort}/sess-9;tcp", listen.msrpPath("sess-9"))+        listen.close()+        RcsImsNetwork.reset()+        assertNull(RcsImsNetwork.lastLocalIp)+    }++    @Test+    fun imsSocketConnectsToLoopback() = runTest {+        val server = ServerSocket(0)+        val accepted = CountDownLatch(1)+        Thread {+            runCatching { server.accept().use { s -> s.getOutputStream().write(42) } }+            accepted.countDown()+        }.apply { isDaemon = true; start() }+        val socket = RcsImsNetwork.createSocket(context, "127.0.0.1", server.localPort, 5_000)+        assertNotNull(socket)+        assertTrue(socket.isConnected)+        assertEquals(42, socket.getInputStream().read())+        socket.close()+        assertTrue(accepted.await(10, TimeUnit.SECONDS))+        server.close()+    }++    // --- MSRP listen / accept routing ---++    private fun sendHeadAndBody(port: Int, head: String, body: String?): Socket {+        val socket = Socket("127.0.0.1", port)+        socket.soTimeout = 15_000+        val out = socket.getOutputStream()+        out.write(head.toByteArray(Charsets.UTF_8))+        out.flush()+        if (body != null) {+            out.write(body.toByteArray(Charsets.UTF_8))+            out.flush()+        }+        return socket+    }++    @Test+    fun listenAcceptRoutesMatchedPathAndRejectsUnknown() = runTest {+        val acceptedLatch = CountDownLatch(1)+        val acceptedConv = AtomicReference<String>()+        val acceptedHead = AtomicReference<RcsMsrpListen.AcceptedHead>()+        var acceptedSocket: Socket? = null+        assertTrue(+            RcsMsrpListen.ensureListening(context) { conv, socket, head ->+                acceptedConv.set(conv)+                acceptedHead.set(head)+                acceptedSocket = socket+                acceptedLatch.countDown()+            },+        )+        assertTrue(RcsMsrpListen.isListening())+        val port = RcsMsrpListen.listenPort()+        assertNotNull(port)+        assertEquals("0.0.0.0", RcsMsrpListen.listenIp())+        // Idempotent.+        assertTrue(RcsMsrpListen.ensureListening(context) { _, _, _ -> })++        val path = RcsMsrpListen.advertisePath(context, "ims-conv-1") { _, _, _ -> }+        assertNotNull(path)+        assertTrue(path.startsWith("msrp://0.0.0.0:$port/"))++        // Unknown path: 481 and close.+        val txUnknown = "unknowntx1"+        val rogue = sendHeadAndBody(+            port,+            "MSRP $txUnknown SEND\r\nTo-Path: msrp://0.0.0.0:$port/nope;tcp\r\n" ++                "From-Path: msrp://10.0.0.9/peer;tcp\r\n\r\n",+            null,+        )+        val rogueIn = rogue.getInputStream().bufferedReader(Charsets.UTF_8)+        val responseLine = rogueIn.readLine()+        assertTrue(responseLine?.contains("481") == true, "response=$responseLine")+        rogue.close()++        // Matched path: the accept callback receives the socket + head, and+        // wrapping it in an MSRP connection delivers the pending body.+        val tx = "matchedtx1"+        val client = sendHeadAndBody(+            port,+            "MSRP $tx SEND\r\nTo-Path: $path\r\nFrom-Path: msrp://10.0.0.9:2855/peer;tcp\r\n" ++                "Message-ID: ims-msg-1\r\nByte-Range: 1-5/5\r\nContent-Type: message/cpim\r\n\r\n",+            null,+        )+        assertTrue(acceptedLatch.await(15, TimeUnit.SECONDS), "no accept callback")+        assertEquals("ims-conv-1", acceptedConv.get())+        assertTrue(acceptedHead.get().lines.first().startsWith("MSRP $tx SEND"))+        val delivered = CopyOnWriteArrayList<String>()+        val conn = RcsMsrp.wrapAccepted(+            acceptedSocket!!, acceptedHead.get(), path,+            "msrp://10.0.0.9:2855/peer;tcp",+        ) { _, body -> delivered += body.toString(Charsets.UTF_8) }+        client.getOutputStream().apply {+            write("hello".toByteArray(Charsets.UTF_8))+            write("\r\n-------$tx\$\r\n".toByteArray(Charsets.UTF_8))+            flush()+        }+        val deadline = System.currentTimeMillis() + 15_000+        while (System.currentTimeMillis() < deadline && delivered.isEmpty()) Thread.sleep(25)+        assertEquals(listOf("hello"), delivered.toList())+        conn.close()+        client.close()+        RcsMsrpListen.stop()+        assertFalse(RcsMsrpListen.isListening())+        assertNull(RcsMsrpListen.listenPort())+    }++    @Test+    fun listenRejectsPlaintextOnSecurePath() = runTest {+        val acceptedLatch = CountDownLatch(1)+        assertTrue(RcsMsrpListen.ensureListening(context) { _, _, _ -> acceptedLatch.countDown() })+        val port = RcsMsrpListen.listenPort()!!+        val securePath = RcsMsrpListen.advertisePath(+            context, "ims-conv-secure", secure = true, peerFingerprint = "AA:BB",+        ) { _, _, _ -> }+        assertNotNull(securePath)+        val client = sendHeadAndBody(+            port,+            "MSRP securetx1 SEND\r\nTo-Path: $securePath\r\n" ++                "From-Path: msrp://10.0.0.9/peer;tcp\r\n\r\n",+            null,+        )+        // The socket is closed without an accept callback or a 481.+        val read = runCatching { client.getInputStream().read() }.getOrDefault(-2)+        assertEquals(-1, read)+        assertEquals(1L, acceptedLatch.count)+        client.close()+        // Dropping the pending path makes the same path unknown afterwards.+        RcsMsrpListen.dropPending("ims-conv-secure")+        RcsMsrpListen.stop()+    }++    @Test+    fun listenTlsByteOnPlainPathAttemptsHandshakeAndCloses() = runTest {+        val acceptedLatch = CountDownLatch(1)+        assertTrue(RcsMsrpListen.ensureListening(context) { _, _, _ -> acceptedLatch.countDown() })+        val port = RcsMsrpListen.listenPort()!!+        val plainPath = RcsMsrpListen.advertisePath(context, "ims-conv-tls") { _, _, _ -> }+        assertNotNull(plainPath)+        // A TLS ClientHello first byte routes to the TLS branch; the junk+        // that follows fails the handshake and the socket closes.+        val client = Socket("127.0.0.1", port)+        client.soTimeout = 15_000+        client.getOutputStream().apply {+            write(0x16)+            write("not-a-client-hello".toByteArray(Charsets.UTF_8))+            flush()+        }+        val read = runCatching { client.getInputStream().read() }.getOrDefault(-1)+        assertEquals(-1, read)+        assertEquals(1L, acceptedLatch.count)+        client.close()+        RcsMsrpListen.stop()+    }++    @Test+    fun listenTlsAcceptWithPinnedClient() = runTest {+        val identity = RcsMsrpTls.ensureIdentity(context)+        assertNotNull(identity)+        val acceptedLatch = CountDownLatch(1)+        val acceptedConv = AtomicReference<String>()+        val acceptedHead = AtomicReference<RcsMsrpListen.AcceptedHead>()+        var acceptedSocket: Socket? = null+        assertTrue(+            RcsMsrpListen.ensureListening(context) { conv, socket, head ->+                acceptedConv.set(conv)+                acceptedHead.set(head)+                acceptedSocket = socket+                acceptedLatch.countDown()+            },+        )+        val port = RcsMsrpListen.listenPort()!!+        val securePath = RcsMsrpListen.advertisePath(+            context, "ims-conv-tls-ok", secure = true, peerFingerprint = identity.fingerprint,+        ) { _, _, _ -> }+        assertNotNull(securePath)++        val client = RcsMsrpTls.clientSocket(context, "127.0.0.1", port, identity.fingerprint)+        assertNotNull(client, "TLS client could not handshake with the listen socket")+        val tx = "tlstx12345"+        client.getOutputStream().apply {+            write(+                ("MSRP $tx SEND\r\nTo-Path: $securePath\r\n" ++                    "From-Path: msrp://10.0.0.9:2855/peer;tcp\r\n" ++                    "Message-ID: ims-tls-1\r\nByte-Range: 1-4/4\r\n" ++                    "Content-Type: message/cpim\r\n\r\n").toByteArray(Charsets.UTF_8),+            )+            flush()+        }+        assertTrue(acceptedLatch.await(20, TimeUnit.SECONDS), "TLS accept never routed")+        assertEquals("ims-conv-tls-ok", acceptedConv.get())+        assertTrue(acceptedSocket is javax.net.ssl.SSLSocket)++        // The accepted connection delivers the chunk body like a plain one.+        val delivered = CopyOnWriteArrayList<String>()+        val conn = RcsMsrp.wrapAccepted(+            acceptedSocket!!, acceptedHead.get(), securePath,+            "msrp://10.0.0.9:2855/peer;tcp",+        ) { _, body -> delivered += body.toString(Charsets.UTF_8) }+        client.getOutputStream().apply {+            write("data".toByteArray(Charsets.UTF_8))+            write("\r\n-------$tx\$\r\n".toByteArray(Charsets.UTF_8))+            flush()+        }+        val deadline = System.currentTimeMillis() + 20_000+        while (System.currentTimeMillis() < deadline && delivered.isEmpty()) Thread.sleep(25)+        assertEquals(listOf("data"), delivered.toList())+        conn.close()+        client.close()+        RcsMsrpListen.stop()+    }++    @Test+    fun listenTlsAcceptRejectsWrongFingerprint() = runTest {+        val identity = RcsMsrpTls.ensureIdentity(context)+        assertNotNull(identity)+        val acceptedLatch = CountDownLatch(1)+        assertTrue(RcsMsrpListen.ensureListening(context) { _, _, _ -> acceptedLatch.countDown() })+        val port = RcsMsrpListen.listenPort()!!+        // The pending path pins a fingerprint our cert does not have.+        val securePath = RcsMsrpListen.advertisePath(+            context, "ims-conv-tls-bad", secure = true,+            peerFingerprint = "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:AA:BB:CC:DD:EE:FF",+        ) { _, _, _ -> }+        assertNotNull(securePath)+        val client = RcsMsrpTls.clientSocket(context, "127.0.0.1", port, identity.fingerprint)+        assertNotNull(client)+        client.getOutputStream().apply {+            write(+                ("MSRP badtx123 SEND\r\nTo-Path: $securePath\r\n" ++                    "From-Path: msrp://10.0.0.9:2855/peer;tcp\r\n\r\n").toByteArray(Charsets.UTF_8),+            )+            flush()+        }+        // The server closes after the fingerprint mismatch; no accept fires.+        val read = runCatching { client.getInputStream().read() }.getOrDefault(-1)+        assertEquals(-1, read)+        assertEquals(1L, acceptedLatch.count)+        client.close()+        RcsMsrpListen.stop()+    }++    @Test+    fun listenFirstByteEofClosesQuietly() = runTest {+        val acceptedLatch = CountDownLatch(1)+        assertTrue(RcsMsrpListen.ensureListening(context) { _, _, _ -> acceptedLatch.countDown() })+        val port = RcsMsrpListen.listenPort()!!+        // Connect and immediately close: the router reads EOF and drops it.+        Socket("127.0.0.1", port).close()+        Thread.sleep(500)+        assertEquals(1L, acceptedLatch.count)+        RcsMsrpListen.stop()+    }++    // --- Direct SIP over the fake PDN ---++    @Test+    fun directSipRegistersAndExchangesMessages() = kotlinx.coroutines.runBlocking {+        val server = ServerSocket(0)+        val port = server.localPort+        // The IMS shadow advertises the P-CSCF on 127.0.0.1:5060; bind there+        // instead by pointing the accepted server at the shadow's port.+        server.close()+        val pcscf = ServerSocket(5060)+        val requests = CopyOnWriteArrayList<String>()+        val inboundSent = CountDownLatch(1)+        val serverDone = CountDownLatch(1)+        Thread {+            try {+                pcscf.accept().use { s ->+                    s.soTimeout = 20_000+                    val input = s.getInputStream().bufferedReader(Charsets.UTF_8)+                    val out = s.getOutputStream()+                    fun readRequest(): List<String> {+                        val lines = mutableListOf<String>()+                        var line = input.readLine() ?: return lines+                        // Content-Length body, when present.+                        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 (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)+                        }+                        return lines+                    }+                    fun branchOf(lines: List<String>): String =+                        lines.firstOrNull { it.startsWith("Via:", true) }+                            ?.substringAfter("branch=")?.substringBefore(";")?.trim().orEmpty()+                    fun respond(lines: List<String>, code: Int, reason: String, extra: String = "") {+                        val branch = branchOf(lines)+                        val callId = lines.firstOrNull { it.startsWith("Call-ID:", true) }.orEmpty()+                        val cseq = lines.firstOrNull { it.startsWith("CSeq:", true) }+                            ?.substringAfter(":")?.trim().orEmpty()+                        out.write(+                            ("SIP/2.0 $code $reason\r\nVia: SIP/2.0/TCP 127.0.0.1;branch=$branch\r\n" ++                                "$callId\r\nCSeq: $cseq\r\n$extra" ++                                "Contact: <sip:127.0.0.1:5060>;expires=600\r\n" ++                                "Expires: 600\r\nContent-Length: 0\r\n\r\n").toByteArray(Charsets.UTF_8),+                        )+                        out.flush()+                    }+                    // 1) REGISTER -> 200 (no auth challenge in this script).+                    val register = readRequest()+                    requests += register.joinToString("\n")+                    respond(register, 200, "OK")+                    // 2) Inbound MESSAGE pushed to the client.+                    out.write(+                        ("MESSAGE sip:me@rcs SIP/2.0\r\nVia: SIP/2.0/TCP 127.0.0.1;branch=z9hG4bKinbound\r\n" ++                            "From: <sip:peer@rcs>;tag=p1\r\nTo: <sip:me@rcs>\r\n" ++                            "Call-ID: inbound-1@pcscf\r\nCSeq: 1 MESSAGE\r\n" ++                            "Content-Type: text/plain\r\nContent-Length: 5\r\n\r\nhello")+                            .toByteArray(Charsets.UTF_8),+                    )+                    out.flush()+                    inboundSent.countDown()+                    // 3) Outbound MESSAGE from the client -> 200 echoing its branch.+                    val message = readRequest()+                    requests += message.joinToString("\n")+                    respond(message, 200, "OK")+                    // 4) Deregistration REGISTER (expires=0) -> 200, then close.+                    val bye = readRequest()+                    requests += bye.joinToString("\n")+                    respond(bye, 200, "OK")+                }+            } catch (e: Throwable) {+                requests += "SERVER-ERROR: $e"+            }+            serverDone.countDown()+        }.apply { isDaemon = true; start() }++        // Shadow P-CSCF is 127.0.0.1 (default SIP port on the link props).+        val inbound = CopyOnWriteArrayList<Triple<String, String, String>>()+        RcsDirectSip.onInboundMessage = { startLine, headers, body ->+            inbound += Triple(startLine, headers, body.toString(Charsets.UTF_8))+        }+        val started = RcsDirectSip.start(context, 1)+        assertTrue(started, "direct SIP did not register: $requests")+        assertTrue(RcsDirectSip.isRegistered())+        assertTrue(inboundSent.await(15, TimeUnit.SECONDS))+        val deadline = System.currentTimeMillis() + 15_000+        while (System.currentTimeMillis() < deadline && inbound.isEmpty()) Thread.sleep(25)+        assertEquals(1, inbound.size)+        assertEquals("hello", inbound.first().third)+        assertTrue(inbound.first().first.startsWith("MESSAGE "))++        val sentOk = RcsDirectSip.sendMessage(+            "MESSAGE sip:peer@rcs SIP/2.0",+            "To: <sip:peer@rcs>\r\nContent-Type: message/cpim\r\n",+            "direct hello".toByteArray(Charsets.UTF_8),+        )+        assertTrue(sentOk, "MESSAGE was not acked: $requests")++        RcsDirectSip.stop()+        assertFalse(RcsDirectSip.isRegistered())+        assertTrue(serverDone.await(20, TimeUnit.SECONDS), "server: $requests")+        val registerWire = requests.first()+        assertTrue(registerWire.contains("REGISTER sip:127.0.0.1 SIP/2.0"), registerWire)+        assertTrue(registerWire.contains("Expires: 600"), registerWire)+        assertTrue(requests.any { it.contains("MESSAGE sip:peer@rcs SIP/2.0") }, requests.toString())+        assertTrue(requests.any { it.contains("expires=0") }, requests.mapIndexed { i, r -> "[$i] $r" }.toString())+        pcscf.close()+        Unit+    }+}
communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2MsrpTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2MsrpTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2MsrpTest.ktnew file mode 100644index 0000000000..9be491c74a--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2MsrpTest.kt@@ -0,0 +1,358 @@+package com.vayunmathur.communicate.rcs++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.communicate.data.rcs.MsrpSetup+import com.vayunmathur.communicate.data.rcs.RcsMsrp+import com.vayunmathur.communicate.data.rcs.RcsMsrpFraming+import com.vayunmathur.communicate.data.rcs.RcsMsrpListen+import com.vayunmathur.communicate.data.rcs.RcsSession+import java.net.ServerSocket+import java.net.Socket+import java.util.concurrent.CopyOnWriteArrayList+import java.util.concurrent.CountDownLatch+import java.util.concurrent.TimeUnit+import java.util.concurrent.atomic.AtomicReference+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.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Slice-3 pass 2: the MSRP socket layer over real loopback TCP — one-shot+ * sends with FIFO acks, persistent connections (chunked SEND, inbound SEND+ * delivery + auto-200, REPORT/AUTH handling, keepalives), and the+ * accepted-socket wrapper.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34], shadows = [RcsSlice3Pass2ConnectivityShadow::class])+class RcsSlice3Pass2MsrpTest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    private fun session(port: Int, setup: MsrpSetup? = MsrpSetup.PASSIVE) = RcsSession(+        dialogId = "pass2-d", callId = "pass2-c", localTag = "lt", remoteTag = "rt",+        remoteUri = "sip:peer@rcs", conversationId = "conv-pass2",+        msrpLocalPath = "msrp://127.0.0.1:$port/self;tcp",+        msrpRemotePath = "msrp://127.0.0.1:$port/peer;tcp",+        msrpSetup = setup, confirmed = true,+    )++    /** A loopback peer thread helper: runs [block] against one accepted socket. */+    private fun serveOnce(server: ServerSocket, block: (Socket) -> Unit): CountDownLatch {+        val done = CountDownLatch(1)+        Thread {+            runCatching { server.accept().use(block) }+            done.countDown()+        }.apply { isDaemon = true; start() }+        return done+    }++    private fun readHead(input: java.io.BufferedReader): List<String> {+        val lines = mutableListOf<String>()+        var line = input.readLine() ?: return lines+        var guard = 0+        while (line.isNotEmpty() && guard++ < 32) {+            lines.add(line)+            line = input.readLine() ?: break+        }+        return lines+    }++    private fun readToMarker(input: java.io.BufferedReader, txid: String): String {+        val sb = StringBuilder()+        while (true) {+            val l = input.readLine() ?: break+            if (l.startsWith("-------$txid")) break+            sb.append(l).append("\r\n")+        }+        return sb.toString()+    }++    private fun respondOk(socket: Socket, txid: String, toPath: String) {+        val out = socket.getOutputStream()+        out.write(RcsMsrpFraming.buildErrorResponse(toPath, txid, 200, "OK"))+        out.flush()+    }++    // --- one-shot send ---++    @Test+    fun oneShotSendDeliversChunksAndMatchesAcks() = runBlocking {+        val server = ServerSocket(0)+        val port = server.localPort+        val received = AtomicReference<String>()+        val done = serveOnce(server) { s ->+            s.soTimeout = 15_000+            val input = s.getInputStream().bufferedReader(Charsets.UTF_8)+            val all = StringBuilder()+            // Payload below is > 4096 bytes, so three chunks arrive; ack each.+            repeat(3) {+                val head = readHead(input)+                val txid = head.firstOrNull()?.split(" ")?.getOrNull(1).orEmpty()+                val body = readToMarker(input, txid)+                all.append(head.joinToString("\n")).append("\n").append(body)+                val toPath = head.firstOrNull { it.startsWith("From-Path:", true) }+                    ?.substringAfter(":")?.trim().orEmpty()+                respondOk(s, txid, toPath)+            }+            received.set(all.toString())+        }+        // ASCII, newline-free payload: the peer reads it line-wise.+        val payload = "msrp-one-shot-payload-".repeat(230).toByteArray(Charsets.UTF_8)+        val ok = RcsMsrp.send(session(port), context, payload)+        assertTrue(ok, "one-shot send was not acked")+        assertTrue(done.await(15, TimeUnit.SECONDS))+        val wire = received.get()+        assertTrue(wire.contains("MSRP "), wire.take(200))+        assertTrue(wire.contains("Byte-Range: 1-2048/5060"), wire.take(400))+        assertTrue(wire.contains("Byte-Range: 2049-4096/5060"))+        assertTrue(wire.contains("Byte-Range: 4097-5060/5060"))+        assertTrue(wire.contains("Content-Type: message/cpim"))+        server.close()+    }++    @Test+    fun oneShotSendFailureModes() = runBlocking {+        // Empty payload: nothing to send.+        assertFalse(RcsMsrp.send(session(9), context, ByteArray(0)))+        // No remote path.+        assertFalse(RcsMsrp.send(session(9).copy(msrpRemotePath = null), context, byteArrayOf(1)))+        // Unparseable path.+        assertFalse(+            RcsMsrp.send(session(9).copy(msrpRemotePath = "not-a-path"), context, byteArrayOf(1)),+        )+        // Closed port: connection refused.+        assertFalse(RcsMsrp.send(session(1), context, byteArrayOf(1, 2, 3)))+        // Secure session without a known peer fingerprint: refused (no downgrade in one-shot send).+        assertFalse(+            RcsMsrp.send(session(1).copy(msrpSecure = true), context, byteArrayOf(1, 2, 3)),+        )+    }++    @Test+    fun oneShotSendNonSuccessAckFails() = runBlocking {+        val server = ServerSocket(0)+        val port = server.localPort+        val done = serveOnce(server) { s ->+            s.soTimeout = 15_000+            val input = s.getInputStream().bufferedReader(Charsets.UTF_8)+            val head = readHead(input)+            val txid = head.firstOrNull()?.split(" ")?.getOrNull(1).orEmpty()+            readToMarker(input, txid)+            val out = s.getOutputStream()+            out.write(RcsMsrpFraming.buildErrorResponse("", txid, 413, "Message Too Large"))+            out.flush()+        }+        assertFalse(RcsMsrp.send(session(port), context, "hello".toByteArray()))+        assertTrue(done.await(15, TimeUnit.SECONDS))+        server.close()+    }++    // --- connect() guards ---++    @Test+    fun connectGuards() = runBlocking {+        assertNull(RcsMsrp.connect(session(9).copy(msrpRemotePath = null), context) { _, _ -> })+        // Peer active + no listen socket: cannot establish.+        assertNull(RcsMsrp.connect(session(9, MsrpSetup.ACTIVE), context) { _, _ -> })+        // Unreachable peer.+        assertNull(RcsMsrp.connect(session(1), context) { _, _ -> })+    }++    // --- persistent connection, both directions ---++    @Test+    fun persistentConnectionBothDirections() = runBlocking {+        val server = ServerSocket(0)+        val port = server.localPort+        val chunksSeen = CopyOnWriteArrayList<String>()+        val peerLatch = CountDownLatch(1)+        val peerErrors = AtomicReference<String>()+        val peer = Thread {+            try {+                server.accept().use { s ->+                    s.soTimeout = 20_000+                    val input = s.getInputStream().bufferedReader(Charsets.UTF_8)+                    val out = s.getOutputStream()+                    // 1) Read our SEND, ack it.+                    val head1 = readHead(input)+                    val tx1 = head1.firstOrNull()?.split(" ")?.getOrNull(1).orEmpty()+                    val body1 = readToMarker(input, tx1)+                    chunksSeen += body1+                    // OutChunk serialization appends CRLF before the marker; the+                    // body slice read here is line-based, so compare trimmed.+                    respondOk(s, tx1, "msrp://127.0.0.1:$port/self;tcp")+                    // 2) Send an inbound SEND to us; expect our auto-200.+                    val inbound = RcsMsrpFraming.splitSend(+                        toPath = "msrp://127.0.0.1:$port/self;tcp",+                        fromPath = "msrp://127.0.0.1:$port/peer;tcp",+                        payload = "inbound hello".toByteArray(Charsets.UTF_8),+                        messageId = "pass2-inbound-1",+                    ).single()+                    out.write(RcsMsrpFraming.serializeChunk(inbound))+                    out.flush()+                    val respHead = readHead(input)+                    chunksSeen += respHead.joinToString("\n")+                    readToMarker(input, inbound.txid)+                    // 3) REPORT frame: queued by the reader, no response.+                    val report = RcsMsrpFraming.buildReport(+                        toPath = "msrp://127.0.0.1:$port/self;tcp",+                        fromPath = "msrp://127.0.0.1:$port/peer;tcp",+                        messageId = "pass2-msg-9", statusCode = 200, reason = "OK",+                        byteRange = "1-5/5",+                    )+                    out.write(report)+                    out.flush()+                    // 4) AUTH frame: answered 501.+                    val authTx = "authtx123456"+                    out.write(+                        ("MSRP $authTx AUTH\r\nTo-Path: msrp://127.0.0.1:$port/self;tcp\r\n" ++                            "From-Path: msrp://127.0.0.1:$port/peer;tcp\r\n\r\n" ++                            "-------$authTx\$\r\n").toByteArray(Charsets.UTF_8),+                    )+                    out.flush()+                    // Read frames until the 501 AUTH response arrives; our+                    // keepalive/report frames may interleave ahead of it.+                    var saw501 = false+                    var guard = 0+                    while (!saw501 && guard++ < 8) {+                        val frameHead = readHead(input)+                        if (frameHead.isEmpty()) break+                        chunksSeen += frameHead.joinToString("\n")+                        val frameTx = frameHead.firstOrNull()?.split(" ")?.getOrNull(1).orEmpty()+                        readToMarker(input, frameTx)+                        if (frameHead.joinToString("\n").contains("501")) saw501 = true+                    }+                    chunksSeen += if (saw501) "SAW-501" else "NO-501"+                    // Wait for the test to finish its assertions, then close.+                    peerLatch.await(20, TimeUnit.SECONDS)+                }+            } catch (e: Throwable) {+                peerErrors.set(e.toString())+            }+        }+        peer.isDaemon = true+        peer.start()++        val inboundBodies = CopyOnWriteArrayList<String>()+        val conn = RcsMsrp.connect(session(port), context) { contentType, body ->+            inboundBodies += "$contentType:${body.toString(Charsets.UTF_8)}"+        }+        assertNotNull(conn, "connect failed")+        assertFalse(conn.isClosed())++        // SEND through the persistent connection and await its ack.+        assertTrue(conn.sendCpim("persistent hello".toByteArray(Charsets.UTF_8)))+        // Empty payload is refused without touching the socket.+        assertFalse(conn.sendCpim(ByteArray(0)))++        // Inbound SEND is delivered and auto-200ed (peer records the response).+        val deadline = System.currentTimeMillis() + 15_000+        while (System.currentTimeMillis() < deadline && inboundBodies.isEmpty()) Thread.sleep(25)+        assertEquals(listOf("message/cpim:inbound hello"), inboundBodies.toList())++        // Keepalive + REPORT go out on the same socket.+        assertTrue(conn.sendKeepalive())+        assertTrue(conn.sendReport("pass2-msg-9", 200, "OK", "1-5/5"))++        peerLatch.countDown()+        peer.join(20_000)+        assertNull(peerErrors.get())+        val peerWire = chunksSeen.joinToString("\n")+        assertTrue(peerWire.contains("persistent hello"), peerWire.take(500))+        assertTrue(peerWire.contains("200 OK"), peerWire.take(500))+        assertTrue(peerWire.contains("SAW-501"), peerWire.take(800))++        conn.close()+        assertTrue(conn.isClosed())+        conn.close()+        assertFalse(conn.sendCpim("after close".toByteArray()))+        assertFalse(conn.sendKeepalive())+        assertFalse(conn.sendReport("m", 200, "OK", "1-1/1"))+        server.close()+    }++    @Test+    fun connectSecureSessionWithoutFingerprintDowngradesToPlaintext() = runBlocking {+        val server = ServerSocket(0)+        val port = server.localPort+        val done = serveOnce(server) { s ->+            s.soTimeout = 15_000+            val input = s.getInputStream().bufferedReader(Charsets.UTF_8)+            val head = readHead(input)+            val txid = head.firstOrNull()?.split(" ")?.getOrNull(1).orEmpty()+            readToMarker(input, txid)+            respondOk(s, txid, "msrp://127.0.0.1:$port/self;tcp")+        }+        // Secure session, but no fingerprint was stashed for this call:+        // connect() downgrades to plaintext rather than failing.+        val conn = RcsMsrp.connect(session(port).copy(msrpSecure = true), context) { _, _ -> }+        assertNotNull(conn)+        assertTrue(conn.sendCpim("downgraded hello".toByteArray(Charsets.UTF_8)))+        conn.close()+        assertTrue(done.await(15, TimeUnit.SECONDS))+        server.close()+    }++    // --- wrapAccepted ---++    @Test+    fun wrapAcceptedDeliversInboundChunk() = runBlocking {+        val server = ServerSocket(0)+        val port = server.localPort+        val accepted = CountDownLatch(1)+        var serverSocket: Socket? = null+        Thread {+            runCatching {+                serverSocket = server.accept()+            }+            accepted.countDown()+        }.apply { isDaemon = true; start() }++        val client = Socket("127.0.0.1", port)+        assertTrue(accepted.await(10, TimeUnit.SECONDS))+        val serverSide = serverSocket!!++        val delivered = CopyOnWriteArrayList<String>()+        val head = RcsMsrpListen.AcceptedHead(+            listOf(+                "MSRP wrappedtx1 SEND",+                "To-Path: msrp://127.0.0.1:$port/self;tcp",+                "From-Path: msrp://127.0.0.1:$port/peer;tcp",+                "Message-ID: wrapped-1",+                "Byte-Range: 1-7/7",+                "Content-Type: message/cpim",+            ),+        )+        assertTrue(head.replayBytes().toString(Charsets.UTF_8).startsWith("MSRP wrappedtx1 SEND\r\n"))+        val conn = RcsMsrp.wrapAccepted(+            serverSide, head,+            localPath = "msrp://127.0.0.1:$port/self;tcp",+            remotePath = "msrp://127.0.0.1:$port/peer;tcp",+        ) { _, body -> delivered += body.toString(Charsets.UTF_8) }+        // The reader replays the head; the client supplies body + marker.+        client.getOutputStream().apply {+            write("wrapped".toByteArray(Charsets.UTF_8))+            write("\r\n-------wrappedtx1\$\r\n".toByteArray(Charsets.UTF_8))+            flush()+        }+        val deadline = System.currentTimeMillis() + 15_000+        while (System.currentTimeMillis() < deadline && delivered.isEmpty()) Thread.sleep(25)+        assertEquals(listOf("wrapped"), delivered.toList())+        // The auto-200 for the wrapped SEND comes back to the client.+        client.soTimeout = 15_000+        val clientIn = client.getInputStream().bufferedReader(Charsets.UTF_8)+        val responseHead = readHead(clientIn)+        assertTrue(responseHead.joinToString("\n").contains("200 OK"), responseHead.toString())+        conn.close()+        client.close()+        server.close()+    }+}
communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2ProvisioningShadow.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2ProvisioningShadow.kt b/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2ProvisioningShadow.ktnew file mode 100644index 0000000000..14343f1960--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2ProvisioningShadow.kt@@ -0,0 +1,28 @@+package com.vayunmathur.communicate.rcs++import android.telephony.ims.ProvisioningManager+import org.robolectric.annotation.Implementation+import org.robolectric.annotation.Implements++/**+ * Framework ProvisioningManager stand-in reporting single-registration+ * capable and no provisioning required, so the provisioning probe's+ * "available" path can run on the JVM.+ */+@Implements(ProvisioningManager::class)+class RcsSlice3Pass2ProvisioningShadow {+    @Implementation+    fun isRcsVolteSingleRegistrationCapable(): Boolean = capable++    @Implementation+    fun isRcsProvisioningRequiredForCapability(capability: Int, tech: Int): Boolean = provisioningRequired++    @Implementation+    fun getRcsProvisioningStatusForCapability(capability: Int, tech: Int): Boolean = !provisioningRequired++    companion object {+        @Volatile var capable = true+        @Volatile var provisioningRequired = false+        fun reset() { capable = true; provisioningRequired = false }+    }+}
communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2ProvisioningTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2ProvisioningTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2ProvisioningTest.ktnew file mode 100644index 0000000000..153401630d--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2ProvisioningTest.kt@@ -0,0 +1,201 @@+package com.vayunmathur.communicate.rcs++import android.content.Context+import android.os.PersistableBundle+import android.telephony.CarrierConfigManager+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.communicate.data.rcs.RcsCapabilityExchange+import com.vayunmathur.communicate.data.rcs.RcsGbaBootstrap+import com.vayunmathur.communicate.data.rcs.RcsHiddenApi+import com.vayunmathur.communicate.data.rcs.RcsProvisioning+import com.vayunmathur.communicate.data.rcs.RcsRegistrationState+import com.vayunmathur.communicate.data.rcs.RcsUnavailableReason+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import org.robolectric.annotation.Config+import org.robolectric.shadows.ShadowSubscriptionManager+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Slice-3 pass 2: the full provisioning decision tree. A shadow+ * ProvisioningManager that reports single-reg capable (this class) plus+ * carrier-config / system-feature control covers Available and both+ * negative mappings; without the shadow the framework verdict is false+ * and the privilege branch decides.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34], shadows = [RcsSlice3Pass2ProvisioningShadow::class])+class RcsSlice3Pass2ProvisioningTest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()+    private val subId = 5++    private fun setCarrierUrl(url: String?) {+        val ccm = context.getSystemService(CarrierConfigManager::class.java)+        val bundle = PersistableBundle()+        if (url != null) {+            bundle.putString(CarrierConfigManager.KEY_RCS_CONFIG_SERVER_URL_STRING, url)+        }+        shadowOf(ccm).setConfigForSubId(subId, bundle)+    }++    private fun setSingleRegFeature(enabled: Boolean) {+        shadowOf(context.packageManager)+            .setSystemFeature("android.hardware.telephony.ims.singlereg", enabled)+    }++    @Test+    fun probeAvailableWhenCapableAndFeaturePresent() = runTest {+        ShadowSubscriptionManager.setDefaultSmsSubscriptionId(subId)+        setCarrierUrl("https://config.example/rcs")+        setSingleRegFeature(true)+        val state = RcsProvisioning.probe(context, subId)+        assertEquals(RcsRegistrationState.Available, state)+        assertEquals(RcsRegistrationState.Available, RcsProvisioning.state.value)+        assertEquals("https://config.example/rcs", RcsProvisioning.lastConfigServerUrl)+    }++    @Test+    fun probeNotSupportedWhenFeatureMissingDespiteCapable() = runTest {+        setCarrierUrl("https://config.example/rcs")+        setSingleRegFeature(false)+        assertEquals(+            RcsRegistrationState.Unavailable(RcsUnavailableReason.NotSupported),+            RcsProvisioning.probe(context, subId),+        )+    }++    @Test+    fun probeBlankCarrierUrlStillProbesThrough() = runTest {+        // MVNO/Jibe case: no config URL, but single-reg says capable.+        setCarrierUrl(null)+        setSingleRegFeature(true)+        assertEquals(RcsRegistrationState.Available, RcsProvisioning.probe(context, subId))+        assertNull(RcsProvisioning.lastConfigServerUrl)+    }++    @Test+    fun probeProvisioningRequiredGate() = runTest {+        RcsSlice3Pass2ProvisioningShadow.provisioningRequired = true+        try {+            setCarrierUrl("https://config.example/rcs")+            setSingleRegFeature(true)+            assertEquals(+                RcsRegistrationState.Unavailable(RcsUnavailableReason.ProvisioningRequired),+                RcsProvisioning.probe(context, subId),+            )+        } finally {+            RcsSlice3Pass2ProvisioningShadow.reset()+        }+    }++    @Test+    fun probeCarrierConfigReadFailureIsServiceUnavailable() = runTest {+        val ccm = context.getSystemService(CarrierConfigManager::class.java)+        org.robolectric.Shadows.shadowOf(ccm).setReadPhoneStatePermission(false)+        try {+            assertEquals(+                RcsRegistrationState.Unavailable(RcsUnavailableReason.ServiceUnavailable),+                RcsProvisioning.probe(context, subId),+            )+        } finally {+            org.robolectric.Shadows.shadowOf(ccm).setReadPhoneStatePermission(true)+        }+    }++    @Test+    fun probeNoCarrierPrivilegeWhenFrameworkSaysNotCapable() = runTest {+        RcsSlice3Pass2ProvisioningShadow.capable = false+        try {+            setCarrierUrl("https://config.example/rcs")+            setSingleRegFeature(true)+            // Framework says not capable and we hold no carrier privilege.+            assertEquals(+                RcsRegistrationState.Unavailable(RcsUnavailableReason.NoCarrierPrivilege),+                RcsProvisioning.probe(context, subId),+            )+        } finally {+            RcsSlice3Pass2ProvisioningShadow.reset()+        }+    }++    @Test+    fun hiddenApiRegisterCallbackAgainstFrameworkManager() {+        val manager = RcsHiddenApi.provisioningManager(subId)+        assertNotNull(manager)+        val executor = java.util.concurrent.Executors.newSingleThreadExecutor()+        var calls = 0+        val ok = RcsHiddenApi.registerProvisioningCallback(+            manager, executor, "6.0", "UP_2.0",+            object : RcsHiddenApi.ProvisioningCallback {+                override fun onConfigurationChanged(configXml: ByteArray) { calls++ }+                override fun onConfigurationReset() { calls++ }+                override fun onRemoved() { calls++ }+            },+        )+        // The JVM framework accepts the registration (shadow service);+        // what matters here is that it never throws and no callback fires+        // without a carrier config change behind it.+        assertTrue(ok)+        assertEquals(0, calls)+        RcsHiddenApi.unregisterProvisioningCallback(manager)+        executor.shutdown()+    }++    @Test+    fun resetClearsProbeState() = runTest {+        setCarrierUrl("https://config.example/rcs")+        setSingleRegFeature(true)+        RcsProvisioning.probe(context, subId)+        RcsProvisioning.reset()+        assertEquals(RcsRegistrationState.Unknown, RcsProvisioning.state.value)+        assertNull(RcsProvisioning.lastConfigServerUrl)+    }++    @Test+    fun hiddenApiAgainstFrameworkProvisioningManager() {+        val manager = RcsHiddenApi.provisioningManager(subId)+        assertNotNull(manager)+        assertEquals(true, RcsHiddenApi.isSingleRegCapable(manager))+    }++    @Test+    fun capabilityQueriesWithValidSubscriptionReachImsManager() = runTest {+        ShadowSubscriptionManager.setDefaultSmsSubscriptionId(subId)+        // The UCE adapter under Robolectric has no carrier service behind+        // it; queries must still fail closed without throwing.+        assertFalse(RcsCapabilityExchange.isContactRcsCapable(context, "+15551234567"))+        assertEquals(+  

Diff truncated.