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

Modern-Apps.git / communicate-dev / src / test / java / com / vayunmathur / communicate / rcs / RcsSlice3Pass2DirectSipAuthTest.kt

RcsSlice3Pass2DirectSipAuthTest.kt174 lines · 7.2 KiBRaw
1package com.vayunmathur.communicate.rcs
2
3import android.content.Context
4import androidx.test.core.app.ApplicationProvider
5import com.vayunmathur.communicate.data.rcs.RcsDirectSip
6import java.net.ServerSocket
7import java.util.concurrent.CopyOnWriteArrayList
8import java.util.concurrent.CountDownLatch
9import java.util.concurrent.TimeUnit
10import kotlinx.coroutines.runBlocking
11import org.junit.runner.RunWith
12import org.robolectric.RobolectricTestRunner
13import org.robolectric.annotation.Config
14import kotlin.test.AfterTest
15import kotlin.test.Test
16import kotlin.test.assertFalse
17import kotlin.test.assertTrue
18
19/**
20 * Slice-3 pass 2: direct-SIP AKA registration — 401 challenge, digest
21 * REGISTER built from the ISIM response (shadow TelephonyManager), 200 OK,
22 * deregistration, and a full restart after stop (regression coverage for
23 * the scope-cancellation restart bug).
24 */
25@RunWith(RobolectricTestRunner::class)
26@Config(
27 sdk = [34],
28 shadows = [RcsSlice3Pass2ImsShadow::class, RcsSlice3Pass2TelephonyShadow::class],
29)
30class RcsSlice3Pass2DirectSipAuthTest {
31
32 private val context: Context get() = ApplicationProvider.getApplicationContext()
33
34 @AfterTest
35 fun tearDown() {
36 RcsDirectSip.stop()
37 }
38
39 /**
40 * The fake P-CSCF must listen on 5060 (the shadow advertises it and
41 * production dials that port). Three test classes bind it, and Gradle
42 * workers pull classes dynamically, so any two can listen at once:
43 * SO_REUSEADDR covers TIME_WAIT from earlier registrations, and the
44 * bounded retry waits out another class's active listen (bounded by
45 * that class's method runtime). Without this, 5060 binds flake with
46 * BindException under load (both directions observed).
47 */
48 private fun pcscfSocket(): ServerSocket {
49 // Attempt-counted, never clock-bounded: Robolectric substitutes
50 // System.currentTimeMillis with its paused scheduler clock, which
51 // can leap past any wall-clock deadline instantly.
52 var attempts = 0
53 while (true) {
54 try {
55 return ServerSocket().apply {
56 reuseAddress = true
57 bind(java.net.InetSocketAddress(5060))
58 }
59 } catch (e: java.net.BindException) {
60 if (++attempts >= 600) throw e
61 Thread.sleep(100)
62 }
63 }
64 }
65
66 private class PcscfScript(val challengeFirst: Boolean) {
67 val requests = CopyOnWriteArrayList<String>()
68 val done = CountDownLatch(1)
69 val error = java.util.concurrent.atomic.AtomicReference<String>()
70
71 fun serve(server: ServerSocket) {
72 Thread {
73 try {
74 server.accept().use { s ->
75 s.soTimeout = 20_000
76 val input = s.getInputStream().bufferedReader(Charsets.UTF_8)
77 val out = s.getOutputStream()
78 var first = true
79 var request = readRequest(input)
80 while (request.isNotEmpty()) {
81 requests += request.joinToString("\n")
82 val finished = if (first && challengeFirst) {
83 first = false
84 respond(out, request, 401, "Unauthorized",
85 "WWW-Authenticate: Digest realm=\"carrier.example\", " +
86 "nonce=\"bm9uY2UxMjM0NTY=\", qop=auth, algorithm=MD5\r\n")
87 false
88 } else {
89 respond(out, request, 200, "OK")
90 request.joinToString("\n").contains("expires=0")
91 }
92 request = if (finished) emptyList() else readRequest(input)
93 }
94 }
95 } catch (e: Throwable) {
96 error.set(e.toString())
97 }
98 done.countDown()
99 }.apply { isDaemon = true; start() }
100 }
101
102 /** Read one SIP request head; empty at end of stream. */
103 private fun readRequest(input: java.io.BufferedReader): List<String> {
104 val lines = mutableListOf<String>()
105 var line = input.readLine() ?: return lines
106 while (line.isNotEmpty()) {
107 lines += line
108 line = input.readLine() ?: return lines
109 }
110 return lines
111 }
112
113 /** Write a SIP response echoing Via branch / Call-ID / CSeq. */
114 private fun respond(
115 out: java.io.OutputStream,
116 lines: List<String>,
117 code: Int,
118 reason: String,
119 extra: String = "",
120 ) {
121 val branch = lines.firstOrNull { it.startsWith("Via:", true) }
122 ?.substringAfter("branch=")?.substringBefore(";")?.trim().orEmpty()
123 val callId = lines.firstOrNull { it.startsWith("Call-ID:", true) }.orEmpty()
124 val cseq = lines.firstOrNull { it.startsWith("CSeq:", true) }
125 ?.substringAfter(":")?.trim().orEmpty()
126 out.write(
127 ("SIP/2.0 $code $reason\r\nVia: SIP/2.0/TCP 127.0.0.1;branch=$branch\r\n" +
128 "$callId\r\nCSeq: $cseq\r\n$extra" +
129 "Contact: <sip:127.0.0.1:5060>;expires=600\r\n" +
130 "Expires: 600\r\nContent-Length: 0\r\n\r\n").toByteArray(Charsets.UTF_8),
131 )
132 out.flush()
133 }
134 }
135
136 @Test
137 fun akaChallengeRegistrationAndRestart() = runBlocking {
138 // --- First start: 401 -> AKA digest REGISTER -> 200. ---
139 val server1 = pcscfSocket()
140 val script1 = PcscfScript(challengeFirst = true)
141 script1.serve(server1)
142 assertTrue(RcsDirectSip.start(context, 1), "start failed: ${script1.requests}")
143 assertTrue(RcsDirectSip.isRegistered())
144 RcsDirectSip.stop()
145 assertFalse(RcsDirectSip.isRegistered())
146 assertTrue(script1.done.await(20, TimeUnit.SECONDS), "script1: ${script1.error.get()}")
147 server1.close()
148 assertEqualsRequests(script1)
149
150 // --- Restart after stop: the stack must come back (scope fix). ---
151 val server2 = pcscfSocket()
152 val script2 = PcscfScript(challengeFirst = false)
153 script2.serve(server2)
154 assertTrue(RcsDirectSip.start(context, 1), "restart failed: ${script2.requests}")
155 assertTrue(RcsDirectSip.isRegistered())
156 RcsDirectSip.stop()
157 assertTrue(script2.done.await(20, TimeUnit.SECONDS), "script2: ${script2.error.get()}")
158 server2.close()
159 assertTrue(script2.requests.first().contains("REGISTER sip:127.0.0.1"))
160 assertTrue(script2.requests.last().contains("expires=0"))
161 Unit
162 }
163
164 private fun assertEqualsRequests(script: PcscfScript) {
165 val all = script.requests
166 assertTrue(all.size >= 3, "requests=$all")
167 assertTrue(all[0].contains("CSeq: 1 REGISTER"), all[0])
168 val authed = all[1]
169 assertTrue(authed.contains("Authorization: Digest "), authed)
170 assertTrue(authed.contains("username="), authed)
171 assertTrue(authed.contains("nonce=\"bm9uY2UxMjM0NTY=\""), authed)
172 assertTrue(all.last().contains("expires=0"), all.last())
173 }
174}