react-native-audio-browser 0.2.0-next.10 → 0.2.0-next.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -34,8 +34,8 @@ class AiaChasingTrustManagerTest {
34
34
  val r13 = CertFixtures.cert("letsencrypt-r13.pem")
35
35
  val delegate = FakeDelegate(trustsChainOfSize = 2)
36
36
  val tm =
37
- AiaChasingTrustManager(delegate) {
38
- if (it == "http://r13.i.lencr.org/") listOf(r13) else emptyList()
37
+ AiaChasingTrustManager(delegate) { url, _ ->
38
+ if (url == "http://r13.i.lencr.org/") listOf(r13) else emptyList()
39
39
  }
40
40
 
41
41
  // Must not throw: the leaf-only chain is rejected, AIA fills in R13, the [leaf, R13] chain
@@ -49,7 +49,7 @@ class AiaChasingTrustManagerTest {
49
49
  fun `rethrows the original failure when no intermediate can be fetched`() {
50
50
  val leaf = CertFixtures.cert("stationplaylist-leaf.pem")
51
51
  val delegate = FakeDelegate(trustsChainOfSize = 2)
52
- val tm = AiaChasingTrustManager(delegate) { emptyList() }
52
+ val tm = AiaChasingTrustManager(delegate) { _, _ -> emptyList() }
53
53
 
54
54
  assertThrows(CertificateException::class.java) { tm.checkServerTrusted(arrayOf(leaf), "RSA") }
55
55
 
@@ -63,7 +63,7 @@ class AiaChasingTrustManagerTest {
63
63
  val delegate = FakeDelegate(trustsChainOfSize = 1)
64
64
  var fetches = 0
65
65
  val tm =
66
- AiaChasingTrustManager(delegate) {
66
+ AiaChasingTrustManager(delegate) { _, _ ->
67
67
  fetches++
68
68
  emptyList()
69
69
  }
@@ -124,14 +124,222 @@ class AiaChasingTrustManagerTest {
124
124
  override fun getAcceptedIssuers(): Array<X509Certificate> = emptyArray()
125
125
  }
126
126
 
127
+ @Test
128
+ fun `a complete chain rejected for some other reason is not chased`() {
129
+ val leaf = CertFixtures.cert("stationplaylist-leaf.pem")
130
+ val r13 = CertFixtures.cert("letsencrypt-r13.pem")
131
+ val root = CertFixtures.cert("isrg-root-x1.pem")
132
+ // Trusts nothing — an expired chain, a hostname mismatch, a CT refusal all look like this:
133
+ // the delegate rejects a chain that is not missing anything.
134
+ val delegate =
135
+ object : X509TrustManager {
136
+ override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) =
137
+ throw CertificateException("certificate expired")
138
+
139
+ override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) = Unit
140
+
141
+ override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf(root)
142
+ }
143
+ var fetches = 0
144
+ val tm =
145
+ AiaChasingTrustManager(delegate) { _, _ ->
146
+ fetches++
147
+ emptyList()
148
+ }
149
+
150
+ assertThrows(CertificateException::class.java) {
151
+ tm.checkServerTrusted(arrayOf(leaf, r13), "RSA")
152
+ }
153
+
154
+ // Chasing could not have helped, so it must not have reached out to a host named by a
155
+ // certificate that just failed validation.
156
+ assertEquals(0, fetches)
157
+ }
158
+
159
+ @Test
160
+ fun `the original failure is kept when the completed chain fails too`() {
161
+ val leaf = CertFixtures.cert("stationplaylist-leaf.pem")
162
+ val r13 = CertFixtures.cert("letsencrypt-r13.pem")
163
+ // Trusts no chain of any size, so the retry fails as well.
164
+ val delegate = FakeDelegate(trustsChainOfSize = -1)
165
+ val tm = AiaChasingTrustManager(delegate) { _, _ -> listOf(r13) }
166
+
167
+ val thrown =
168
+ assertThrows(CertificateException::class.java) { tm.checkServerTrusted(arrayOf(leaf), "RSA") }
169
+
170
+ assertEquals(1, thrown.suppressed.size)
171
+ }
172
+
173
+ @Test
174
+ fun `client checks are forwarded, not routed through the server path`() {
175
+ val leaf = CertFixtures.cert("stationplaylist-leaf.pem")
176
+ var clientChecks = 0
177
+ val delegate =
178
+ object : X509ExtendedTrustManager() {
179
+ override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) =
180
+ throw CertificateException("server path must not be used for a client check")
181
+
182
+ override fun checkServerTrusted(
183
+ chain: Array<X509Certificate>,
184
+ authType: String,
185
+ socket: Socket?,
186
+ ) = throw CertificateException("server path must not be used for a client check")
187
+
188
+ override fun checkServerTrusted(
189
+ chain: Array<X509Certificate>,
190
+ authType: String,
191
+ engine: SSLEngine?,
192
+ ) = throw CertificateException("server path must not be used for a client check")
193
+
194
+ override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) {
195
+ clientChecks++
196
+ }
197
+
198
+ override fun checkClientTrusted(
199
+ chain: Array<X509Certificate>,
200
+ authType: String,
201
+ socket: Socket?,
202
+ ) {
203
+ clientChecks++
204
+ }
205
+
206
+ override fun checkClientTrusted(
207
+ chain: Array<X509Certificate>,
208
+ authType: String,
209
+ engine: SSLEngine?,
210
+ ) {
211
+ clientChecks++
212
+ }
213
+
214
+ override fun getAcceptedIssuers(): Array<X509Certificate> = emptyArray()
215
+ }
216
+ val tm = AiaChasingExtendedTrustManager(delegate) { _, _ -> emptyList() }
217
+
218
+ tm.checkClientTrusted(arrayOf(leaf), "RSA")
219
+ tm.checkClientTrusted(arrayOf(leaf), "RSA", null as Socket?)
220
+ tm.checkClientTrusted(arrayOf(leaf), "RSA", null as SSLEngine?)
221
+
222
+ assertEquals(3, clientChecks)
223
+ }
224
+
225
+ /** A delegate carrying the Android-specific hostname-aware method, as `RootTrustManager` does. */
226
+ @Suppress("unused")
227
+ private class HostAwareDelegate(private val trustsChainOfSize: Int) : X509TrustManager {
228
+ val hosts = mutableListOf<String>()
229
+
230
+ fun checkServerTrusted(
231
+ chain: Array<X509Certificate>,
232
+ authType: String,
233
+ host: String,
234
+ ): List<X509Certificate> {
235
+ hosts.add(host)
236
+ if (chain.size != trustsChainOfSize) {
237
+ throw CertificateException("Trust anchor for certification path not found.")
238
+ }
239
+ return chain.toList()
240
+ }
241
+
242
+ override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) =
243
+ throw CertificateException("the host-aware overload should have been used")
244
+
245
+ override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) = Unit
246
+
247
+ override fun getAcceptedIssuers(): Array<X509Certificate> = emptyArray()
248
+ }
249
+
250
+ @Test
251
+ fun `the X509TrustManagerExtensions signature is present and forwards the host`() {
252
+ val leaf = CertFixtures.cert("stationplaylist-leaf.pem")
253
+ val r13 = CertFixtures.cert("letsencrypt-r13.pem")
254
+ val delegate = HostAwareDelegate(trustsChainOfSize = 2)
255
+ val tm =
256
+ AiaChasingExtendedTrustManager(delegate) { url, _ ->
257
+ if (url == "http://r13.i.lencr.org/") listOf(r13) else emptyList()
258
+ }
259
+
260
+ // The method X509TrustManagerExtensions looks up reflectively must exist on the wrapper...
261
+ val method =
262
+ tm.javaClass.getMethod(
263
+ "checkServerTrusted",
264
+ Array<X509Certificate>::class.java,
265
+ String::class.java,
266
+ String::class.java,
267
+ )
268
+
269
+ // ...and must reach the delegate's own host-aware method, so pinning still sees the host.
270
+ val accepted = tm.checkServerTrusted(arrayOf(leaf), "RSA", "ca.example")
271
+
272
+ assertEquals(listOf(leaf, r13), accepted)
273
+ assertEquals(listOf("ca.example", "ca.example"), delegate.hosts)
274
+ assertEquals(List::class.java, method.returnType)
275
+ }
276
+
277
+ @Test
278
+ fun `the host-aware signature falls back to the extended overloads when the delegate lacks it`() {
279
+ val leaf = CertFixtures.cert("stationplaylist-leaf.pem")
280
+ val r13 = CertFixtures.cert("letsencrypt-r13.pem")
281
+ // An extended delegate without the Android-specific String-host method, whose two-argument
282
+ // form refuses outright — the domain-config case. The fallback must route through its
283
+ // extended overloads, and must report the AIA-completed chain that actually validated.
284
+ val delegate = FakeDomainConfigDelegate(trustsChainOfSize = 2)
285
+ val tm =
286
+ AiaChasingExtendedTrustManager(delegate) { url, _ ->
287
+ if (url == "http://r13.i.lencr.org/") listOf(r13) else emptyList()
288
+ }
289
+
290
+ val accepted = tm.checkServerTrusted(arrayOf(leaf), "RSA", "ca.example")
291
+
292
+ assertEquals(listOf(leaf, r13), accepted)
293
+ assertEquals(listOf(1, 2), delegate.hostnameAwareChecks)
294
+ }
295
+
296
+ /** A host-aware delegate that validates fine but reports an empty accepted chain. */
297
+ @Suppress("unused")
298
+ private class SilentHostAwareDelegate(private val trustsChainOfSize: Int) : X509TrustManager {
299
+ fun checkServerTrusted(
300
+ chain: Array<X509Certificate>,
301
+ authType: String,
302
+ host: String,
303
+ ): List<X509Certificate> {
304
+ if (chain.size != trustsChainOfSize) {
305
+ throw CertificateException("Trust anchor for certification path not found.")
306
+ }
307
+ return emptyList()
308
+ }
309
+
310
+ override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) =
311
+ throw CertificateException("the host-aware overload should have been used")
312
+
313
+ override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) = Unit
314
+
315
+ override fun getAcceptedIssuers(): Array<X509Certificate> = emptyArray()
316
+ }
317
+
318
+ @Test
319
+ fun `a delegate reporting an empty accepted chain still yields the chain that validated`() {
320
+ val leaf = CertFixtures.cert("stationplaylist-leaf.pem")
321
+ val r13 = CertFixtures.cert("letsencrypt-r13.pem")
322
+ val delegate = SilentHostAwareDelegate(trustsChainOfSize = 2)
323
+ val tm =
324
+ AiaChasingExtendedTrustManager(delegate) { url, _ ->
325
+ if (url == "http://r13.i.lencr.org/") listOf(r13) else emptyList()
326
+ }
327
+
328
+ // An empty list from the delegate on success must not be passed through: the checked chain
329
+ // is what it accepted, and a pinning consumer given [] would fail a valid connection.
330
+ val accepted = tm.checkServerTrusted(arrayOf(leaf), "RSA", "ca.example")
331
+
332
+ assertEquals(listOf(leaf, r13), accepted)
333
+ }
334
+
127
335
  @Test
128
336
  fun `forwards to the hostname-aware overload the platform requires`() {
129
337
  val leaf = CertFixtures.cert("stationplaylist-leaf.pem")
130
338
  val r13 = CertFixtures.cert("letsencrypt-r13.pem")
131
339
  val delegate = FakeDomainConfigDelegate(trustsChainOfSize = 2)
132
340
  val tm =
133
- AiaChasingExtendedTrustManager(delegate) {
134
- if (it == "http://r13.i.lencr.org/") listOf(r13) else emptyList()
341
+ AiaChasingExtendedTrustManager(delegate) { url, _ ->
342
+ if (url == "http://r13.i.lencr.org/") listOf(r13) else emptyList()
135
343
  }
136
344
 
137
345
  // The socket overload must reach the delegate's socket overload. Routing it through the
@@ -147,7 +355,7 @@ class AiaChasingTrustManagerTest {
147
355
  val leaf = CertFixtures.cert("stationplaylist-leaf.pem")
148
356
  val delegate = FakeDomainConfigDelegate(trustsChainOfSize = 1)
149
357
 
150
- AiaChasingExtendedTrustManager(delegate) { emptyList() }
358
+ AiaChasingExtendedTrustManager(delegate) { _, _ -> emptyList() }
151
359
  .checkServerTrusted(arrayOf(leaf), "RSA", null as SSLEngine?)
152
360
 
153
361
  assertEquals(listOf(1), delegate.hostnameAwareChecks)
@@ -159,8 +367,8 @@ class AiaChasingTrustManagerTest {
159
367
  val r13 = CertFixtures.cert("letsencrypt-r13.pem")
160
368
  val delegate = FakeDelegate(trustsChainOfSize = 2)
161
369
  val tm =
162
- AiaChasingExtendedTrustManager(delegate) {
163
- if (it == "http://r13.i.lencr.org/") listOf(r13) else emptyList()
370
+ AiaChasingExtendedTrustManager(delegate) { url, _ ->
371
+ if (url == "http://r13.i.lencr.org/") listOf(r13) else emptyList()
164
372
  }
165
373
 
166
374
  tm.checkServerTrusted(arrayOf(leaf), "RSA", null as Socket?)
@@ -174,7 +382,7 @@ class AiaChasingTrustManagerTest {
174
382
  val r13 = CertFixtures.cert("letsencrypt-r13.pem")
175
383
  // Trusts nothing, whatever the chain.
176
384
  val delegate = FakeDomainConfigDelegate(trustsChainOfSize = -1)
177
- val tm = AiaChasingExtendedTrustManager(delegate) { listOf(r13) }
385
+ val tm = AiaChasingExtendedTrustManager(delegate) { _, _ -> listOf(r13) }
178
386
 
179
387
  assertThrows(CertificateException::class.java) {
180
388
  tm.checkServerTrusted(arrayOf(leaf), "RSA", null as Socket?)
@@ -0,0 +1,322 @@
1
+ package com.audiobrowser.tls
2
+
3
+ import java.net.InetAddress
4
+ import java.net.ServerSocket
5
+ import java.security.cert.X509Certificate
6
+ import java.util.concurrent.CountDownLatch
7
+ import java.util.concurrent.TimeUnit
8
+ import java.util.concurrent.atomic.AtomicInteger
9
+ import java.util.concurrent.atomic.AtomicReference
10
+ import javax.security.auth.x500.X500Principal
11
+ import kotlin.concurrent.thread
12
+ import org.junit.After
13
+ import org.junit.Assert.assertEquals
14
+ import org.junit.Assert.assertFalse
15
+ import org.junit.Assert.assertTrue
16
+ import org.junit.Test
17
+ import org.mockito.Mockito.mock
18
+ import org.mockito.Mockito.`when`
19
+
20
+ /**
21
+ * Exercises [CachingCertificateFetcher.fetch] against a real loopback server.
22
+ *
23
+ * The safety helpers have their own unit tests, but a predicate that is never consulted protects
24
+ * nothing: these cover the *wiring*, so that removing the `isSafeUrl` guard or swapping
25
+ * `readCapped` back for a plain read-to-EOF fails a test rather than passing silently.
26
+ */
27
+ class CachingCertificateFetcherCallSiteTest {
28
+
29
+ private var server: ServerSocket? = null
30
+
31
+ @After
32
+ fun tearDown() {
33
+ server?.close()
34
+ }
35
+
36
+ /**
37
+ * Serves [response] to every connection, recording the request line of the first. [handled]
38
+ * counts accepted connections.
39
+ */
40
+ private fun startServer(
41
+ response: ByteArray = "HTTP/1.0 404 Not Found\r\n\r\n".toByteArray(),
42
+ handled: AtomicInteger = AtomicInteger(),
43
+ firstRequest: AtomicReference<String> = AtomicReference(),
44
+ ): Int {
45
+ val socket = ServerSocket(0, 50, InetAddress.getByName("127.0.0.1"))
46
+ server = socket
47
+ thread(isDaemon = true) {
48
+ while (!socket.isClosed) {
49
+ try {
50
+ socket.accept().use { client ->
51
+ handled.incrementAndGet()
52
+ val request = ByteArray(1024)
53
+ val read = client.getInputStream().read(request)
54
+ firstRequest.compareAndSet(null, String(request, 0, maxOf(read, 0)))
55
+ client.getOutputStream().apply {
56
+ write(response)
57
+ flush()
58
+ }
59
+ }
60
+ } catch (e: Exception) {
61
+ return@thread // socket closed, or the client hung up
62
+ }
63
+ }
64
+ }
65
+ return socket.localPort
66
+ }
67
+
68
+ @Test
69
+ fun `a URL carrying CRLF never reaches the network`() {
70
+ val handled = AtomicInteger()
71
+ val port = startServer(handled = handled)
72
+
73
+ // Without the isSafeUrl guard this connects and emits "SET foo bar" as its own request line.
74
+ val certs = CachingCertificateFetcher().fetch("http://127.0.0.1:$port/\r\nSET foo bar\r\n")
75
+
76
+ assertTrue(certs.isEmpty())
77
+ assertEquals("the request must not be sent at all", 0, handled.get())
78
+ }
79
+
80
+ @Test
81
+ fun `a well-formed URL does reach the network, so the guard is not just refusing everything`() {
82
+ val handled = AtomicInteger()
83
+ val request = AtomicReference<String>()
84
+ val port = startServer(handled = handled, firstRequest = request)
85
+
86
+ CachingCertificateFetcher().fetch("http://127.0.0.1:$port/issuer.crt")
87
+
88
+ assertEquals(1, handled.get())
89
+ assertTrue("request line was: ${request.get()}", request.get().startsWith("GET /issuer.crt "))
90
+ }
91
+
92
+ @Test
93
+ fun `a non-default port is carried in the Host header`() {
94
+ val request = AtomicReference<String>()
95
+ val port = startServer(firstRequest = request)
96
+
97
+ CachingCertificateFetcher().fetch("http://127.0.0.1:$port/issuer.crt")
98
+
99
+ assertTrue(
100
+ "headers were: ${request.get()}",
101
+ request.get().contains("Host: 127.0.0.1:$port\r\n"),
102
+ )
103
+ }
104
+
105
+ @Test(timeout = 30_000)
106
+ fun `an oversized response is abandoned rather than read to EOF`() {
107
+ // Asserting only that the fetch fails would prove nothing — 4 MiB crosses loopback in
108
+ // milliseconds and would fail to parse either way. What has to be true is that the client
109
+ // stopped reading, which shows up as the server's write not draining.
110
+ val socket = ServerSocket(0, 50, InetAddress.getByName("127.0.0.1"))
111
+ server = socket
112
+ val written = AtomicInteger()
113
+ val finished = CountDownLatch(1)
114
+ thread(isDaemon = true) {
115
+ runCatching {
116
+ socket.accept().use { client ->
117
+ client.getInputStream().read(ByteArray(1024))
118
+ val out = client.getOutputStream()
119
+ out.write("HTTP/1.0 200 OK\r\n\r\n".toByteArray())
120
+ val chunk = ByteArray(64 * 1024)
121
+ // 64 MiB — far past the 1 MiB cap. Once the client stops reading and closes, this
122
+ // throws a broken pipe, which is the signal we want.
123
+ repeat(1024) {
124
+ out.write(chunk)
125
+ written.addAndGet(chunk.size)
126
+ }
127
+ }
128
+ }
129
+ finished.countDown()
130
+ }
131
+
132
+ val certs = CachingCertificateFetcher().fetch("http://127.0.0.1:${socket.localPort}/big.crt")
133
+
134
+ assertTrue(certs.isEmpty())
135
+ assertTrue(finished.await(20, TimeUnit.SECONDS))
136
+ // Socket buffers mean the server gets somewhat past the cap before the write fails, but it
137
+ // must be nowhere near the 64 MiB it wanted to send.
138
+ assertTrue(
139
+ "server wrote ${written.get()} bytes; the read was not cut off",
140
+ written.get() < 16 shl 20,
141
+ )
142
+ }
143
+
144
+ @Test(timeout = 30_000)
145
+ fun `a real certificate is fetched, parsed and then served from cache`() {
146
+ // The success path, end to end over a socket: every other wire test serves a failure, so a
147
+ // broken body offset or a broken cache write would not show up anywhere.
148
+ val der = CertFixtures.bytes("letsencrypt-r13.der")
149
+ val handled = AtomicInteger()
150
+ val port =
151
+ startServer(
152
+ response =
153
+ ("HTTP/1.0 200 OK\r\nContent-Type: application/pkix-cert\r\n\r\n").toByteArray() + der,
154
+ handled = handled,
155
+ )
156
+ val fetcher = CachingCertificateFetcher()
157
+ val url = "http://127.0.0.1:$port/r13.der"
158
+
159
+ val certs = fetcher.fetch(url)
160
+
161
+ assertEquals(1, certs.size)
162
+ assertEquals("CN=R13,O=Let's Encrypt,C=US", certs.first().subjectX500Principal.name)
163
+
164
+ // Second call must be served from the cache, not the network.
165
+ assertEquals(certs, fetcher.fetch(url))
166
+ assertEquals("a successful fetch must be cached", 1, handled.get())
167
+ }
168
+
169
+ /**
170
+ * A mock certificate whose AIA extension lists [url] as its one CA-Issuers location, so
171
+ * [AiaCertChaser.completeChain] chases it with this fetcher — the real wiring, end to end.
172
+ */
173
+ private fun certPointingAt(url: String): X509Certificate {
174
+ // Short-form DER lengths only; a loopback URL is far under 128 bytes.
175
+ fun der(tag: Int, content: ByteArray) =
176
+ byteArrayOf(tag.toByte(), content.size.toByte()) + content
177
+ val caIssuersOid = byteArrayOf(0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x30, 0x02)
178
+ val aia =
179
+ der(
180
+ 0x04,
181
+ der(
182
+ 0x30,
183
+ der(0x30, der(0x06, caIssuersOid) + der(0x86, url.toByteArray(Charsets.US_ASCII))),
184
+ ),
185
+ )
186
+ return mock(X509Certificate::class.java).also {
187
+ `when`(it.getExtensionValue("1.3.6.1.5.5.7.1.1")).thenReturn(aia)
188
+ // Distinct principals, or the chaser reads the mock as a self-signed root and never fetches.
189
+ `when`(it.subjectX500Principal).thenReturn(X500Principal("CN=leaf"))
190
+ `when`(it.issuerX500Principal).thenReturn(X500Principal("CN=issuer"))
191
+ }
192
+ }
193
+
194
+ @Test(timeout = 30_000)
195
+ fun `a drip-feeding server is cut off by the chase deadline, not only the per-fetch caps`() {
196
+ // One byte every 100 ms: each read lands well inside the socket timeout, so per-read limits
197
+ // never fire, and the per-fetch read budget alone would let this run for its full 10 s. The
198
+ // walk's 1 s budget must cut the fetch *itself* — not merely decline to start the next one.
199
+ val socket = ServerSocket(0, 50, InetAddress.getByName("127.0.0.1"))
200
+ server = socket
201
+ thread(isDaemon = true) {
202
+ runCatching {
203
+ socket.accept().use { client ->
204
+ client.getInputStream().read(ByteArray(1024))
205
+ val out = client.getOutputStream()
206
+ out.write("HTTP/1.0 200 OK\r\n\r\n".toByteArray())
207
+ out.flush()
208
+ repeat(300) { // 30 s of drip on offer; the client must not stay for it
209
+ out.write(0)
210
+ out.flush()
211
+ Thread.sleep(100)
212
+ }
213
+ }
214
+ }
215
+ }
216
+ val fetcher = CachingCertificateFetcher()
217
+ val cert = certPointingAt("http://127.0.0.1:${socket.localPort}/drip.crt")
218
+
219
+ val started = System.nanoTime()
220
+ val completed =
221
+ AiaCertChaser.completeChain(listOf(cert), budgetMs = 1_000) { url, deadline ->
222
+ fetcher.fetch(url, deadline)
223
+ }
224
+ val elapsedMs = (System.nanoTime() - started) / 1_000_000
225
+
226
+ assertEquals(listOf(cert), completed)
227
+ // Well past the 1 s budget to absorb scheduling noise, but far short of the 10 s the
228
+ // per-fetch read budget alone would have allowed.
229
+ assertTrue("chase ran for $elapsedMs ms", elapsedMs < 8_000)
230
+ }
231
+
232
+ @Test(timeout = 30_000)
233
+ fun `the chase deadline spans redirect hops, not just fetch starts`() {
234
+ // Every hop stalls 1 s and then redirects back to itself. Each hop sits comfortably inside
235
+ // the per-operation timeouts, so only a deadline threaded through the redirect recursion
236
+ // can end the fetch — without one it walks all 5 redirects, ~6 s here.
237
+ val socket = ServerSocket(0, 50, InetAddress.getByName("127.0.0.1"))
238
+ server = socket
239
+ thread(isDaemon = true) {
240
+ while (!socket.isClosed) {
241
+ try {
242
+ socket.accept().use { client ->
243
+ client.getInputStream().read(ByteArray(1024))
244
+ Thread.sleep(1_000)
245
+ client.getOutputStream().apply {
246
+ write("HTTP/1.0 302 Found\r\nLocation: /again.crt\r\n\r\n".toByteArray())
247
+ flush()
248
+ }
249
+ }
250
+ } catch (e: Exception) {
251
+ return@thread
252
+ }
253
+ }
254
+ }
255
+ val fetcher = CachingCertificateFetcher()
256
+
257
+ val started = System.nanoTime()
258
+ val certs =
259
+ fetcher.fetch(
260
+ "http://127.0.0.1:${socket.localPort}/loop.crt",
261
+ deadlineNanos = System.nanoTime() + 1_500 * 1_000_000L,
262
+ )
263
+ val elapsedMs = (System.nanoTime() - started) / 1_000_000
264
+
265
+ assertTrue(certs.isEmpty())
266
+ assertTrue("fetch ran for $elapsedMs ms across redirect hops", elapsedMs < 4_000)
267
+ }
268
+
269
+ @Test(timeout = 30_000)
270
+ fun `a server that accepts and never answers is bounded by the read timeout`() {
271
+ val socket = ServerSocket(0, 50, InetAddress.getByName("127.0.0.1"))
272
+ server = socket
273
+ val accepted = CountDownLatch(1)
274
+ // Accept, then hold the connection open saying nothing at all.
275
+ thread(isDaemon = true) {
276
+ runCatching {
277
+ val client = socket.accept()
278
+ accepted.countDown()
279
+ Thread.sleep(60_000)
280
+ client.close()
281
+ }
282
+ }
283
+
284
+ val certs =
285
+ CachingCertificateFetcher(connectTimeoutMs = 2_000, readTimeoutMs = 1_000)
286
+ .fetch("http://127.0.0.1:${socket.localPort}/hangs.crt")
287
+
288
+ assertTrue(accepted.await(10, TimeUnit.SECONDS))
289
+ assertTrue(certs.isEmpty())
290
+ }
291
+
292
+ @Test
293
+ fun `a non-http scheme is never fetched`() {
294
+ val handled = AtomicInteger()
295
+ val port = startServer(handled = handled)
296
+
297
+ assertTrue(CachingCertificateFetcher().fetch("ftp://127.0.0.1:$port/issuer.crt").isEmpty())
298
+ assertTrue(CachingCertificateFetcher().fetch("file:///etc/hosts").isEmpty())
299
+ assertEquals(0, handled.get())
300
+ }
301
+
302
+ @Test
303
+ fun `a failed fetch is not cached, so it stays retryable`() {
304
+ val handled = AtomicInteger()
305
+ val port = startServer(handled = handled)
306
+ val fetcher = CachingCertificateFetcher()
307
+ val url = "http://127.0.0.1:$port/issuer.crt"
308
+
309
+ fetcher.fetch(url)
310
+ fetcher.fetch(url)
311
+
312
+ assertEquals("both attempts must hit the network", 2, handled.get())
313
+ }
314
+
315
+ @Test
316
+ fun `the cache is bounded`() {
317
+ // Far more distinct URLs than MAX_CACHE_ENTRIES; nothing is cached here (every fetch fails),
318
+ // but the bound is what stops an attacker-chosen URL space from growing without limit.
319
+ assertFalse(CachingCertificateFetcher.MAX_CACHE_ENTRIES <= 0)
320
+ assertTrue(CachingCertificateFetcher.MAX_CACHE_ENTRIES <= 128)
321
+ }
322
+ }
@@ -5,6 +5,12 @@
5
5
  /// These stubs declare `Equatable` for test ergonomics — the generated
6
6
  /// Nitro types do NOT. Shared `ios/` sources must not rely on conformances
7
7
  /// that exist only here: `swift test` compiles, the app build breaks.
8
+ ///
9
+ /// Property names and types ARE checked against `nitrogen/generated/ios/swift`
10
+ /// by `src/nitro-stub-drift.test.ts`, which runs in the JS CI job — neither
11
+ /// native job can see both files at once. Declaring fewer properties than the
12
+ /// real type is fine and deliberate; spelling one differently is what that
13
+ /// test catches. Conformances and default values are still on you.
8
14
 
9
15
  struct ArtworkVariants: Equatable {
10
16
  var light: String
@@ -23,7 +29,7 @@
23
29
  }
24
30
 
25
31
  struct Track: Equatable {
26
- var id: String
32
+ var id: String?
27
33
  var url: String?
28
34
  var src: String?
29
35
  var request: TrackRequest?
@@ -63,9 +69,19 @@
63
69
  }
64
70
  }
65
71
 
72
+ enum HttpMethod {
73
+ case get
74
+ case post
75
+ case put
76
+ case patch
77
+ case delete
78
+ case head
79
+ case options
80
+ }
81
+
66
82
  struct ImageSource: Equatable {
67
83
  var uri: String
68
- var method: String?
84
+ var method: HttpMethod?
69
85
  var headers: [String: String]?
70
86
  var body: String?
71
87
  }
@@ -813,13 +813,13 @@ struct ComputedPropertyTests {
813
813
  let q = QueueManager()
814
814
  q.setQueue(tracks("a", "b", "c", "d"))
815
815
  q.shuffleEnabled = true
816
- let nextFromProp = q.nextTracks.map(\.id)
816
+ let nextFromProp = q.nextTracks.map { $0.id! }
817
817
  // Navigate forward only as many times as nextTracks reports
818
818
  // (nextTracks does not include wrapped tracks)
819
819
  var nextFromNav: [String] = []
820
820
  for _ in 0 ..< nextFromProp.count {
821
821
  _ = q.next()
822
- nextFromNav.append(q.currentTrack!.id)
822
+ nextFromNav.append(q.currentTrack!.id!)
823
823
  }
824
824
  #expect(nextFromProp == nextFromNav)
825
825
  }
@@ -832,12 +832,12 @@ struct ComputedPropertyTests {
832
832
  for _ in 0 ..< 3 {
833
833
  _ = q.next()
834
834
  }
835
- let prevFromProp = q.previousTracks.map(\.id)
835
+ let prevFromProp = q.previousTracks.map { $0.id! }
836
836
  // Navigate backward the same number of times
837
837
  var prevFromNav: [String] = []
838
838
  for _ in 0 ..< prevFromProp.count {
839
839
  _ = q.previous()
840
- prevFromNav.insert(q.currentTrack!.id, at: 0)
840
+ prevFromNav.insert(q.currentTrack!.id!, at: 0)
841
841
  }
842
842
  #expect(prevFromProp == prevFromNav)
843
843
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-audio-browser",
3
- "version": "0.2.0-next.10",
3
+ "version": "0.2.0-next.11",
4
4
  "description": "react-native-audio-browser is a react native package built with Nitro",
5
5
  "keywords": [
6
6
  "react-native",
@@ -52,7 +52,8 @@
52
52
  "build": "yarn prepare",
53
53
  "clean": "del-cli android/build example/android/build example/android/app/build example/ios/build lib",
54
54
  "codegen": "node codegen/index.js --logLevel=\"debug\" && node post-script.cjs && node codegen/strip-struct-equality.cjs && yarn build",
55
- "prepare": "bob build",
55
+ "prepare": "bob build && yarn hooks:install",
56
+ "hooks:install": "git config core.hooksPath .githooks || exit 0",
56
57
  "example": "yarn workspace example-native",
57
58
  "ci:format": "oxfmt --check --ignore-path .gitignore --ignore-path .oxfmtignore .",
58
59
  "ci:format:ios": "swiftformat --lint ios",