@onekeyfe/react-native-sni-connect 6.7.0-5 → 6.7.0-50
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.
- package/README.md +111 -65
- package/android/src/main/java/com/sniconnect/SniConnectModule.kt +144 -13
- package/android/src/main/java/com/sniconnect/SniConnectValidation.kt +68 -0
- package/android/src/main/java/com/sniconnect/SniPinnedTransport.kt +89 -1
- package/android/src/test/java/com/sniconnect/SniConnectValidationTest.kt +235 -1
- package/ios/SniConnect.mm +27 -0
- package/ios/SniConnect.swift +63 -0
- package/ios/SniConnectClient.swift +27 -4
- package/ios/SniConnectValidation.swift +71 -0
- package/ios/Tests/SniConnectValidationTests/SniConnectValidationTests.swift +113 -0
- package/lib/module/NativeSniConnect.js +6 -0
- package/lib/module/index.js +11 -0
- package/lib/typescript/src/NativeSniConnect.d.ts +15 -0
- package/lib/typescript/src/index.d.ts +4 -2
- package/package.json +7 -7
- package/src/NativeSniConnect.ts +20 -0
- package/src/index.tsx +18 -0
|
@@ -1,15 +1,25 @@
|
|
|
1
1
|
package com.sniconnect
|
|
2
2
|
|
|
3
|
+
import java.io.File
|
|
4
|
+
import java.io.IOException
|
|
3
5
|
import java.net.InetAddress
|
|
4
6
|
import java.net.Proxy
|
|
5
7
|
import java.net.UnknownHostException
|
|
6
8
|
import java.util.Locale
|
|
7
9
|
import java.util.concurrent.TimeUnit
|
|
10
|
+
import java.util.concurrent.atomic.AtomicBoolean
|
|
11
|
+
import okhttp3.Call
|
|
8
12
|
import okhttp3.ConnectionPool
|
|
9
13
|
import okhttp3.Dispatcher
|
|
10
14
|
import okhttp3.Dns
|
|
15
|
+
import okhttp3.EventListener
|
|
16
|
+
import okhttp3.MediaType
|
|
11
17
|
import okhttp3.OkHttpClient
|
|
12
18
|
import okhttp3.Protocol
|
|
19
|
+
import okhttp3.RequestBody
|
|
20
|
+
import okio.Buffer
|
|
21
|
+
import okio.BufferedSink
|
|
22
|
+
import okio.source
|
|
13
23
|
import javax.net.ssl.HttpsURLConnection
|
|
14
24
|
|
|
15
25
|
object SniPinnedTransport {
|
|
@@ -38,6 +48,7 @@ object SniPinnedTransport {
|
|
|
38
48
|
HttpsURLConnection.getDefaultHostnameVerifier().verify(normalizedHostname, session)
|
|
39
49
|
}
|
|
40
50
|
.dns(createPinnedDns(ip, normalizedHostname))
|
|
51
|
+
.eventListenerFactory(SniRequestTransmissionEventListenerFactory)
|
|
41
52
|
.build()
|
|
42
53
|
}
|
|
43
54
|
|
|
@@ -50,9 +61,86 @@ object SniPinnedTransport {
|
|
|
50
61
|
if (requestedHost.lowercase(Locale.US) == hostname) {
|
|
51
62
|
return listOf(pinnedAddress)
|
|
52
63
|
}
|
|
53
|
-
throw
|
|
64
|
+
throw SniPinnedDestinationViolationException(
|
|
54
65
|
"Unexpected host for pinned SNI request: $requestedHost"
|
|
55
66
|
)
|
|
56
67
|
}
|
|
57
68
|
}
|
|
58
69
|
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* The pinned resolver never consults system DNS, so an unknown host here can
|
|
73
|
+
* only be an attempt to escape the caller-selected destination. It is a
|
|
74
|
+
* security-policy failure, not a transient DNS failure, and must fail closed.
|
|
75
|
+
*/
|
|
76
|
+
internal class SniPinnedDestinationViolationException(
|
|
77
|
+
message: String,
|
|
78
|
+
) : UnknownHostException(message)
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Per-logical-request record of whether any OkHttp attempt began transmitting
|
|
82
|
+
* the request. A bodyless request (for example `DELETE`) can be processed by the
|
|
83
|
+
* server without ever writing a request body, so body tracking alone cannot
|
|
84
|
+
* prove that no attempt was sent.
|
|
85
|
+
*/
|
|
86
|
+
internal class SniRequestTransmissionState {
|
|
87
|
+
private val started = AtomicBoolean(false)
|
|
88
|
+
|
|
89
|
+
fun markRequestTransmissionStarted() {
|
|
90
|
+
started.set(true)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
fun hasRequestTransmissionStarted(): Boolean = started.get()
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Marks the tagged [SniRequestTransmissionState] as soon as an attempt starts
|
|
98
|
+
* writing request headers. This runs after connect/TLS, so a refused connection
|
|
99
|
+
* before any attempt reached this point is still provably unsent, while a
|
|
100
|
+
* successful attempt followed by a refused recovery is ambiguous.
|
|
101
|
+
*/
|
|
102
|
+
internal object SniRequestTransmissionEventListenerFactory : EventListener.Factory {
|
|
103
|
+
override fun create(call: Call): EventListener =
|
|
104
|
+
object : EventListener() {
|
|
105
|
+
override fun requestHeadersStart(call: Call) {
|
|
106
|
+
call.request().tag(SniRequestTransmissionState::class.java)
|
|
107
|
+
?.markRequestTransmissionStarted()
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Reads from disk only during transmission, with a fixed, bounded body length. */
|
|
113
|
+
internal class SniUploadFileRequestBody(
|
|
114
|
+
private val file: File,
|
|
115
|
+
private val mediaType: MediaType?,
|
|
116
|
+
) : RequestBody() {
|
|
117
|
+
private val length = file.length().also {
|
|
118
|
+
if (it <= 0 || it > SniConnectValidation.MAX_UPLOAD_FILE_BYTES) {
|
|
119
|
+
throw IOException("Upload file size is out of range")
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
override fun contentType(): MediaType? = mediaType
|
|
124
|
+
|
|
125
|
+
override fun contentLength(): Long = length
|
|
126
|
+
|
|
127
|
+
override fun writeTo(sink: BufferedSink) {
|
|
128
|
+
file.source().use { source ->
|
|
129
|
+
val buffer = Buffer()
|
|
130
|
+
var totalBytes = 0L
|
|
131
|
+
while (true) {
|
|
132
|
+
// One extra byte detects growth without ever writing beyond the bound.
|
|
133
|
+
val read = source.read(buffer, minOf(8 * 1024L, length - totalBytes + 1))
|
|
134
|
+
if (read == -1L) break
|
|
135
|
+
if (totalBytes + read > length) {
|
|
136
|
+
throw IOException("Upload file grew during transmission")
|
|
137
|
+
}
|
|
138
|
+
sink.write(buffer, read)
|
|
139
|
+
totalBytes += read
|
|
140
|
+
}
|
|
141
|
+
if (totalBytes != length) {
|
|
142
|
+
throw IOException("Upload file was truncated during transmission")
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
@@ -2,10 +2,24 @@ package com.sniconnect
|
|
|
2
2
|
|
|
3
3
|
import org.junit.Assert.assertEquals
|
|
4
4
|
import org.junit.Assert.assertFalse
|
|
5
|
+
import org.junit.Assert.assertNull
|
|
5
6
|
import org.junit.Assert.assertTrue
|
|
7
|
+
import org.junit.Assert.assertThrows
|
|
8
|
+
import okhttp3.Call
|
|
9
|
+
import okhttp3.OkHttpClient
|
|
10
|
+
import okhttp3.Request
|
|
11
|
+
import okio.Buffer
|
|
12
|
+
import okio.ForwardingSink
|
|
13
|
+
import okio.buffer
|
|
14
|
+
import org.junit.Rule
|
|
6
15
|
import org.junit.Test
|
|
16
|
+
import org.junit.rules.TemporaryFolder
|
|
17
|
+
import java.io.File
|
|
7
18
|
import java.io.IOException
|
|
19
|
+
import java.io.RandomAccessFile
|
|
20
|
+
import java.nio.file.Files
|
|
8
21
|
import java.io.InterruptedIOException
|
|
22
|
+
import java.net.ConnectException
|
|
9
23
|
import java.net.SocketTimeoutException
|
|
10
24
|
import java.net.UnknownHostException
|
|
11
25
|
import java.security.cert.CertificateException
|
|
@@ -14,6 +28,121 @@ import javax.net.ssl.SSLPeerUnverifiedException
|
|
|
14
28
|
|
|
15
29
|
class SniConnectValidationTest {
|
|
16
30
|
|
|
31
|
+
@get:Rule
|
|
32
|
+
val tempFolder = TemporaryFolder()
|
|
33
|
+
|
|
34
|
+
@Test
|
|
35
|
+
fun uploadMethodAllowsOnlyPostAndPut() {
|
|
36
|
+
SniConnectValidation.validateUploadMethod("POST")
|
|
37
|
+
SniConnectValidation.validateUploadMethod("PUT")
|
|
38
|
+
listOf("GET", "HEAD", "PATCH", "DELETE", "OPTIONS").forEach { method ->
|
|
39
|
+
assertValidationFails { SniConnectValidation.validateUploadMethod(method) }
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
@Test
|
|
44
|
+
fun resolveUploadFileAcceptsSandboxFileByPathAndFileUrl() {
|
|
45
|
+
val root = tempFolder.newFolder("sandbox")
|
|
46
|
+
val file = File(root, "logs.zip").apply { writeBytes(byteArrayOf(0x50, 0x4B, 3, 4, -1)) }
|
|
47
|
+
|
|
48
|
+
val byPath = SniConnectValidation.resolveUploadFile(file.path, listOf(root))
|
|
49
|
+
assertEquals(file.canonicalPath, byPath.path)
|
|
50
|
+
val byUrl = SniConnectValidation.resolveUploadFile(file.toURI().toString(), listOf(root))
|
|
51
|
+
assertEquals(file.canonicalPath, byUrl.path)
|
|
52
|
+
val byTripleSlashUrl = SniConnectValidation.resolveUploadFile("file://${file.path}", listOf(root))
|
|
53
|
+
assertEquals(file.canonicalPath, byTripleSlashUrl.path)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
@Test
|
|
57
|
+
fun resolveUploadFileRejectsInvalidOrOutOfSandboxFiles() {
|
|
58
|
+
val root = tempFolder.newFolder("sandbox")
|
|
59
|
+
val outside = tempFolder.newFolder("outside")
|
|
60
|
+
val outsideFile = File(outside, "secret.bin").apply { writeBytes(byteArrayOf(1, 2, 3)) }
|
|
61
|
+
val emptyFile = File(root, "empty.zip").apply { writeBytes(ByteArray(0)) }
|
|
62
|
+
val link = File(root, "link.zip")
|
|
63
|
+
Files.createSymbolicLink(link.toPath(), outsideFile.toPath())
|
|
64
|
+
|
|
65
|
+
listOf(
|
|
66
|
+
"",
|
|
67
|
+
"relative/logs.zip",
|
|
68
|
+
"https://example.com/logs.zip",
|
|
69
|
+
outsideFile.path,
|
|
70
|
+
"${root.path}/../outside/secret.bin",
|
|
71
|
+
link.path,
|
|
72
|
+
emptyFile.path,
|
|
73
|
+
root.path,
|
|
74
|
+
File(root, "missing.zip").path,
|
|
75
|
+
"${root.path}/logs\n.zip",
|
|
76
|
+
).forEach { path ->
|
|
77
|
+
assertValidationFails { SniConnectValidation.resolveUploadFile(path, listOf(root)) }
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
@Test
|
|
82
|
+
fun resolveUploadFileRejectsFilesOverTheSizeLimit() {
|
|
83
|
+
val root = tempFolder.newFolder("sandbox")
|
|
84
|
+
val file = File(root, "big.zip")
|
|
85
|
+
RandomAccessFile(file, "rw").use { it.setLength(SniConnectValidation.MAX_UPLOAD_FILE_BYTES + 1) }
|
|
86
|
+
|
|
87
|
+
assertValidationFails { SniConnectValidation.resolveUploadFile(file.path, listOf(root)) }
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
@Test
|
|
91
|
+
fun uploadBodyStreamsExactLimitBinaryData() {
|
|
92
|
+
val file = tempFolder.newFile("exact.zip")
|
|
93
|
+
val expected = ByteArray(SniConnectValidation.MAX_UPLOAD_FILE_BYTES.toInt()) { 0xFF.toByte() }
|
|
94
|
+
file.writeBytes(expected)
|
|
95
|
+
val body = SniUploadFileRequestBody(file, null)
|
|
96
|
+
val sink = Buffer()
|
|
97
|
+
body.writeTo(sink)
|
|
98
|
+
assertEquals(expected.size.toLong(), body.contentLength())
|
|
99
|
+
assertTrue(expected.contentEquals(sink.readByteArray()))
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
@Test
|
|
103
|
+
fun uploadBodyRejectsGrowthAfterValidation() {
|
|
104
|
+
val root = tempFolder.newFolder("sandbox")
|
|
105
|
+
val file = File(root, "growing.zip").apply { writeBytes(byteArrayOf(1)) }
|
|
106
|
+
val validated = SniConnectValidation.resolveUploadFile(file.path, listOf(root))
|
|
107
|
+
val body = SniUploadFileRequestBody(validated, null)
|
|
108
|
+
RandomAccessFile(file, "rw").use { it.setLength(SniConnectValidation.MAX_UPLOAD_FILE_BYTES + 1) }
|
|
109
|
+
val sink = Buffer()
|
|
110
|
+
assertThrows(IOException::class.java) { body.writeTo(sink) }
|
|
111
|
+
assertTrue(sink.size <= body.contentLength())
|
|
112
|
+
assertThrows(IOException::class.java) { SniUploadFileRequestBody(validated, null) }
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
@Test
|
|
116
|
+
fun uploadBodyRejectsGrowthDuringTransmission() {
|
|
117
|
+
val file = tempFolder.newFile("growing-during-write.zip")
|
|
118
|
+
file.writeBytes(ByteArray(16 * 1024) { 1 })
|
|
119
|
+
val body = SniUploadFileRequestBody(file, null)
|
|
120
|
+
val output = Buffer()
|
|
121
|
+
var appended = false
|
|
122
|
+
val sink = object : ForwardingSink(output) {
|
|
123
|
+
override fun write(source: Buffer, byteCount: Long) {
|
|
124
|
+
super.write(source, byteCount)
|
|
125
|
+
if (!appended) {
|
|
126
|
+
file.appendBytes(byteArrayOf(2))
|
|
127
|
+
appended = true
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}.buffer()
|
|
131
|
+
assertThrows(IOException::class.java) { body.writeTo(sink) }
|
|
132
|
+
assertTrue(appended)
|
|
133
|
+
assertTrue(output.size <= body.contentLength())
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
@Test
|
|
137
|
+
fun uploadBodyRejectsTruncationAfterValidation() {
|
|
138
|
+
val file = tempFolder.newFile("truncated.zip").apply { writeBytes(byteArrayOf(1, 2)) }
|
|
139
|
+
val body = SniUploadFileRequestBody(file, null)
|
|
140
|
+
file.writeBytes(byteArrayOf(1))
|
|
141
|
+
assertThrows(IOException::class.java) { body.writeTo(Buffer()) }
|
|
142
|
+
file.writeBytes(byteArrayOf())
|
|
143
|
+
assertThrows(IOException::class.java) { body.writeTo(Buffer()) }
|
|
144
|
+
}
|
|
145
|
+
|
|
17
146
|
@Test
|
|
18
147
|
fun acceptsValidRequestBoundaryValues() {
|
|
19
148
|
SniConnectValidation.validateRequestId("req-1")
|
|
@@ -213,7 +342,15 @@ class SniConnectValidationTest {
|
|
|
213
342
|
)
|
|
214
343
|
assertEquals(
|
|
215
344
|
"SNI_SECURITY_POLICY_FAILED",
|
|
216
|
-
classifySniFailureCode(
|
|
345
|
+
classifySniFailureCode(
|
|
346
|
+
SniPinnedDestinationViolationException("Unexpected host for pinned SNI request"),
|
|
347
|
+
),
|
|
348
|
+
)
|
|
349
|
+
assertEquals(
|
|
350
|
+
"SNI_SECURITY_POLICY_FAILED",
|
|
351
|
+
classifySniFailureCode(IOException("wrapped").apply {
|
|
352
|
+
initCause(SniPinnedDestinationViolationException("Unexpected host for pinned SNI request"))
|
|
353
|
+
}),
|
|
217
354
|
)
|
|
218
355
|
assertEquals(
|
|
219
356
|
"SNI_REQUEST_TIMEOUT",
|
|
@@ -243,6 +380,103 @@ class SniConnectValidationTest {
|
|
|
243
380
|
)
|
|
244
381
|
}
|
|
245
382
|
|
|
383
|
+
@Test
|
|
384
|
+
fun classifiesDnsAndPreWriteConnectionFailuresForSafeFallback() {
|
|
385
|
+
assertEquals(
|
|
386
|
+
"SNI_DNS_FAILED",
|
|
387
|
+
classifySniFailureCode(UnknownHostException("api.example.com")),
|
|
388
|
+
)
|
|
389
|
+
assertEquals(
|
|
390
|
+
"SNI_CONNECTION_REFUSED",
|
|
391
|
+
classifySniFailureCode(ConnectException("Connection refused")),
|
|
392
|
+
)
|
|
393
|
+
assertEquals(
|
|
394
|
+
"SNI_CONNECTION_REFUSED",
|
|
395
|
+
classifySniFailureCode(IOException("connect failed").apply {
|
|
396
|
+
initCause(ConnectException("Connection refused"))
|
|
397
|
+
}),
|
|
398
|
+
)
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
@Test
|
|
402
|
+
fun gatesReplaySensitiveCodesOnRequestTransmissionEvidence() {
|
|
403
|
+
assertEquals(
|
|
404
|
+
"SNI_CONNECTION_REFUSED",
|
|
405
|
+
gateReplaySensitiveFailureCode("SNI_CONNECTION_REFUSED", false),
|
|
406
|
+
)
|
|
407
|
+
assertEquals(
|
|
408
|
+
"SNI_REQUEST_FAILED",
|
|
409
|
+
gateReplaySensitiveFailureCode("SNI_CONNECTION_REFUSED", true),
|
|
410
|
+
)
|
|
411
|
+
// Only the pre-write connection code is gated; other codes pass through.
|
|
412
|
+
assertEquals("SNI_TLS_FAILED", gateReplaySensitiveFailureCode("SNI_TLS_FAILED", true))
|
|
413
|
+
assertEquals(
|
|
414
|
+
"SNI_SECURITY_POLICY_FAILED",
|
|
415
|
+
gateReplaySensitiveFailureCode("SNI_SECURITY_POLICY_FAILED", true),
|
|
416
|
+
)
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
@Test
|
|
420
|
+
fun requestHeadersStartMarksTheLogicalRequestAsTransmitted() {
|
|
421
|
+
val state = SniRequestTransmissionState()
|
|
422
|
+
val call = newOkHttpCall(state)
|
|
423
|
+
assertFalse(state.hasRequestTransmissionStarted())
|
|
424
|
+
|
|
425
|
+
SniRequestTransmissionEventListenerFactory.create(call).requestHeadersStart(call)
|
|
426
|
+
|
|
427
|
+
assertTrue(state.hasRequestTransmissionStarted())
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
@Test
|
|
431
|
+
fun untaggedCallDoesNotFailOnRequestHeadersStart() {
|
|
432
|
+
val call = OkHttpClient().newCall(
|
|
433
|
+
Request.Builder().url("https://example.com/").build(),
|
|
434
|
+
)
|
|
435
|
+
|
|
436
|
+
SniRequestTransmissionEventListenerFactory.create(call).requestHeadersStart(call)
|
|
437
|
+
|
|
438
|
+
assertNull(call.request().tag(SniRequestTransmissionState::class.java))
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
@Test
|
|
442
|
+
fun processedBodylessRequestFollowedByRefusedRecoveryStaysAmbiguous() {
|
|
443
|
+
// A bodyless DELETE can be processed by the server without writing a body;
|
|
444
|
+
// only the request-headers event can prove that it was transmitted.
|
|
445
|
+
val state = SniRequestTransmissionState()
|
|
446
|
+
val call = newOkHttpCall(state, bodylessDelete = true)
|
|
447
|
+
SniRequestTransmissionEventListenerFactory.create(call).requestHeadersStart(call)
|
|
448
|
+
|
|
449
|
+
val code = gateReplaySensitiveFailureCode(
|
|
450
|
+
classifySniFailureCode(ConnectException("Connection refused")),
|
|
451
|
+
state.hasRequestTransmissionStarted(),
|
|
452
|
+
)
|
|
453
|
+
|
|
454
|
+
assertEquals("SNI_REQUEST_FAILED", code)
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
@Test
|
|
458
|
+
fun refusedConnectionBeforeAnyTransmissionKeepsPreWriteCode() {
|
|
459
|
+
val state = SniRequestTransmissionState()
|
|
460
|
+
val code = gateReplaySensitiveFailureCode(
|
|
461
|
+
classifySniFailureCode(ConnectException("Connection refused")),
|
|
462
|
+
state.hasRequestTransmissionStarted(),
|
|
463
|
+
)
|
|
464
|
+
|
|
465
|
+
assertEquals("SNI_CONNECTION_REFUSED", code)
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
private fun newOkHttpCall(
|
|
469
|
+
state: SniRequestTransmissionState,
|
|
470
|
+
bodylessDelete: Boolean = false,
|
|
471
|
+
): Call {
|
|
472
|
+
val builder = Request.Builder()
|
|
473
|
+
.url("https://example.com/")
|
|
474
|
+
.tag(SniRequestTransmissionState::class.java, state)
|
|
475
|
+
return OkHttpClient().newCall(
|
|
476
|
+
(if (bodylessDelete) builder.delete() else builder.get()).build(),
|
|
477
|
+
)
|
|
478
|
+
}
|
|
479
|
+
|
|
246
480
|
private fun assertValidationFails(block: () -> Unit) {
|
|
247
481
|
try {
|
|
248
482
|
block()
|
package/ios/SniConnect.mm
CHANGED
|
@@ -13,6 +13,9 @@
|
|
|
13
13
|
- (void)request:(NSDictionary *)config
|
|
14
14
|
resolve:(RCTPromiseResolveBlock)resolve
|
|
15
15
|
reject:(RCTPromiseRejectBlock)reject;
|
|
16
|
+
- (void)uploadFile:(NSDictionary *)config
|
|
17
|
+
resolve:(RCTPromiseResolveBlock)resolve
|
|
18
|
+
reject:(RCTPromiseRejectBlock)reject;
|
|
16
19
|
- (void)cancelRequest:(NSString *)requestId
|
|
17
20
|
resolve:(RCTPromiseResolveBlock)resolve
|
|
18
21
|
reject:(RCTPromiseRejectBlock)reject;
|
|
@@ -82,6 +85,24 @@ RCT_EXPORT_MODULE(SniConnect)
|
|
|
82
85
|
[_implementation request:configDict resolve:resolve reject:reject];
|
|
83
86
|
}
|
|
84
87
|
|
|
88
|
+
- (void)uploadFile:(JS::NativeSniConnect::NativeSniConnectUploadFileRequest &)config
|
|
89
|
+
resolve:(RCTPromiseResolveBlock)resolve
|
|
90
|
+
reject:(RCTPromiseRejectBlock)reject {
|
|
91
|
+
NSMutableDictionary *configDict = [NSMutableDictionary dictionary];
|
|
92
|
+
configDict[@"ip"] = config.ip() ?: @"";
|
|
93
|
+
configDict[@"hostname"] = config.hostname() ?: @"";
|
|
94
|
+
configDict[@"method"] = config.method() ?: @"POST";
|
|
95
|
+
configDict[@"path"] = config.path() ?: @"/";
|
|
96
|
+
configDict[@"headers"] = config.headers() ?: @{};
|
|
97
|
+
configDict[@"timeout"] = @(config.timeout());
|
|
98
|
+
configDict[@"filePath"] = config.filePath() ?: @"";
|
|
99
|
+
if (config.requestId()) {
|
|
100
|
+
configDict[@"requestId"] = config.requestId();
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
[_implementation uploadFile:configDict resolve:resolve reject:reject];
|
|
104
|
+
}
|
|
105
|
+
|
|
85
106
|
- (void)cancelRequest:(NSString *)requestId
|
|
86
107
|
resolve:(RCTPromiseResolveBlock)resolve
|
|
87
108
|
reject:(RCTPromiseRejectBlock)reject {
|
|
@@ -127,6 +148,12 @@ RCT_EXPORT_METHOD(request:(NSDictionary *)config
|
|
|
127
148
|
[_implementation request:config resolve:resolve reject:reject];
|
|
128
149
|
}
|
|
129
150
|
|
|
151
|
+
RCT_EXPORT_METHOD(uploadFile:(NSDictionary *)config
|
|
152
|
+
resolver:(RCTPromiseResolveBlock)resolve
|
|
153
|
+
rejecter:(RCTPromiseRejectBlock)reject) {
|
|
154
|
+
[_implementation uploadFile:config resolve:resolve reject:reject];
|
|
155
|
+
}
|
|
156
|
+
|
|
130
157
|
RCT_EXPORT_METHOD(cancelRequest:(NSString *)requestId
|
|
131
158
|
resolver:(RCTPromiseResolveBlock)resolve
|
|
132
159
|
rejecter:(RCTPromiseRejectBlock)reject) {
|
package/ios/SniConnect.swift
CHANGED
|
@@ -41,6 +41,26 @@ final class SniConnectImpl: NSObject {
|
|
|
41
41
|
}
|
|
42
42
|
}
|
|
43
43
|
|
|
44
|
+
@objc
|
|
45
|
+
public func uploadFile(
|
|
46
|
+
_ config: NSDictionary,
|
|
47
|
+
resolve: @escaping RCTPromiseResolveBlock,
|
|
48
|
+
reject: @escaping RCTPromiseRejectBlock
|
|
49
|
+
) {
|
|
50
|
+
do {
|
|
51
|
+
let parsed = try Self.parseUploadFileDictionary(config)
|
|
52
|
+
handleRequest(config: parsed, resolve: resolve, reject: reject)
|
|
53
|
+
} catch {
|
|
54
|
+
SniConnectLog.error(SniConnectLog.event("sni_request_result", [
|
|
55
|
+
("result", "error"),
|
|
56
|
+
("code", "SNI_INVALID_CONFIG"),
|
|
57
|
+
("nativeErrorClass", String(describing: type(of: error))),
|
|
58
|
+
("stage", "parse_upload_config"),
|
|
59
|
+
]))
|
|
60
|
+
reject("SNI_INVALID_CONFIG", "\(error)", error)
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
44
64
|
private func handleRequest(
|
|
45
65
|
config: SniConnectClient.RequestConfig,
|
|
46
66
|
resolve: @escaping RCTPromiseResolveBlock,
|
|
@@ -213,6 +233,45 @@ final class SniConnectImpl: NSObject {
|
|
|
213
233
|
)
|
|
214
234
|
}
|
|
215
235
|
|
|
236
|
+
/// Uploads may only read files from this app's own container.
|
|
237
|
+
private static var uploadFileAllowedRoots: [URL] {
|
|
238
|
+
[
|
|
239
|
+
URL(fileURLWithPath: NSHomeDirectory(), isDirectory: true),
|
|
240
|
+
URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true),
|
|
241
|
+
]
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
private static func parseUploadFileDictionary(
|
|
245
|
+
_ dictionary: NSDictionary
|
|
246
|
+
) throws -> SniConnectClient.RequestConfig {
|
|
247
|
+
guard dictionary["body"] == nil || dictionary["body"] is NSNull else {
|
|
248
|
+
throw SniConnectError.invalidConfig("uploadFile does not accept body")
|
|
249
|
+
}
|
|
250
|
+
guard let filePath = dictionary["filePath"] as? String, !filePath.isEmpty else {
|
|
251
|
+
throw SniConnectError.invalidConfig("Missing filePath")
|
|
252
|
+
}
|
|
253
|
+
let base = try parseDictionary(dictionary)
|
|
254
|
+
let method = try SniConnectValidation.normalizeMethod(base.method)
|
|
255
|
+
try SniConnectValidation.validateUploadMethod(method)
|
|
256
|
+
let resolvedFile = try SniConnectValidation.resolveUploadFile(
|
|
257
|
+
filePath,
|
|
258
|
+
allowedRoots: uploadFileAllowedRoots
|
|
259
|
+
)
|
|
260
|
+
return SniConnectClient.RequestConfig(
|
|
261
|
+
requestId: base.requestId,
|
|
262
|
+
ip: base.ip,
|
|
263
|
+
hostname: base.hostname,
|
|
264
|
+
method: method,
|
|
265
|
+
path: base.path,
|
|
266
|
+
headers: base.headers,
|
|
267
|
+
body: nil,
|
|
268
|
+
timeout: base.timeout,
|
|
269
|
+
bodyFileURL: resolvedFile.url,
|
|
270
|
+
connectTimeout: base.connectTimeout,
|
|
271
|
+
totalTimeout: base.totalTimeout
|
|
272
|
+
)
|
|
273
|
+
}
|
|
274
|
+
|
|
216
275
|
private static func validate(_ config: SniConnectClient.RequestConfig) throws {
|
|
217
276
|
try SniConnectValidation.validatePublicIP(config.ip)
|
|
218
277
|
try SniConnectValidation.validateHostname(config.hostname)
|
|
@@ -221,6 +280,10 @@ final class SniConnectImpl: NSObject {
|
|
|
221
280
|
_ = try SniConnectValidation.normalizePath(config.path)
|
|
222
281
|
try SniConnectValidation.validateRequestId(config.requestId)
|
|
223
282
|
try SniConnectValidation.validateTimeout(config.effectiveTotalTimeout)
|
|
283
|
+
if config.bodyFileURL != nil {
|
|
284
|
+
try SniConnectValidation.validateUploadMethod(method)
|
|
285
|
+
return
|
|
286
|
+
}
|
|
224
287
|
try SniConnectValidation.validateBody(config.body)
|
|
225
288
|
try SniConnectValidation.validateMethodBody(method: method, body: config.body)
|
|
226
289
|
}
|
|
@@ -259,6 +259,8 @@ final class SniConnectClient {
|
|
|
259
259
|
let headers: [String: String]
|
|
260
260
|
let body: String?
|
|
261
261
|
let timeout: TimeInterval
|
|
262
|
+
// Set only by uploadFile(); already resolved inside the app sandbox.
|
|
263
|
+
var bodyFileURL: URL? = nil
|
|
262
264
|
|
|
263
265
|
// Advanced timeout configurations
|
|
264
266
|
let connectTimeout: TimeInterval? // Connection establishment timeout
|
|
@@ -678,8 +680,15 @@ final class SniConnectClient {
|
|
|
678
680
|
method = try SniConnectValidation.normalizeMethod(config.method)
|
|
679
681
|
normalizedPath = try SniConnectValidation.normalizePath(config.path)
|
|
680
682
|
try SniConnectValidation.validateTimeout(config.effectiveTotalTimeout)
|
|
681
|
-
|
|
682
|
-
|
|
683
|
+
if config.bodyFileURL != nil {
|
|
684
|
+
try SniConnectValidation.validateUploadMethod(method)
|
|
685
|
+
if config.body != nil {
|
|
686
|
+
throw SniConnectValidation.ValidationError.invalidBody
|
|
687
|
+
}
|
|
688
|
+
} else {
|
|
689
|
+
try SniConnectValidation.validateBody(config.body)
|
|
690
|
+
try SniConnectValidation.validateMethodBody(method: method, body: config.body)
|
|
691
|
+
}
|
|
683
692
|
} catch {
|
|
684
693
|
let sniError = SniConnectError.invalidConfig("\(error)")
|
|
685
694
|
SniConnectLog.error(SniConnectLog.event("sni_request_result", [
|
|
@@ -763,8 +772,20 @@ final class SniConnectClient {
|
|
|
763
772
|
mutableRequest.setValue(config.hostname, forHTTPHeaderField: "Host")
|
|
764
773
|
mutableRequest.setValue("identity", forHTTPHeaderField: "Accept-Encoding")
|
|
765
774
|
|
|
766
|
-
|
|
775
|
+
var bodyBytes = 0
|
|
776
|
+
if let bodyFileURL = config.bodyFileURL {
|
|
777
|
+
let fileData: Data
|
|
778
|
+
do {
|
|
779
|
+
// Bound consumption even if the file grew while waiting for admission.
|
|
780
|
+
fileData = try SniConnectValidation.readUploadFile(bodyFileURL)
|
|
781
|
+
} catch {
|
|
782
|
+
throw SniConnectError.invalidConfig("Upload file is not readable")
|
|
783
|
+
}
|
|
784
|
+
mutableRequest.httpBody = fileData
|
|
785
|
+
bodyBytes = fileData.count
|
|
786
|
+
} else if let bodyString = config.body, let bodyData = bodyString.data(using: .utf8) {
|
|
767
787
|
mutableRequest.httpBody = bodyData
|
|
788
|
+
bodyBytes = bodyData.count
|
|
768
789
|
}
|
|
769
790
|
|
|
770
791
|
// Per-request connect timeout (avoids the process-global setter race).
|
|
@@ -781,7 +802,8 @@ final class SniConnectClient {
|
|
|
781
802
|
("connectTimeoutMs", Int(config.effectiveConnectTimeout)),
|
|
782
803
|
("queueWaitMs", queueWaitMilliseconds),
|
|
783
804
|
("headerCount", normalizedHeaders.count),
|
|
784
|
-
("bodyBytes",
|
|
805
|
+
("bodyBytes", bodyBytes),
|
|
806
|
+
("bodySource", config.bodyFileURL != nil ? "file" : "string"),
|
|
785
807
|
]))
|
|
786
808
|
|
|
787
809
|
do {
|
|
@@ -817,6 +839,7 @@ final class SniConnectClient {
|
|
|
817
839
|
("ipFamily", SniConnectLog.ipFamily(config.ip)),
|
|
818
840
|
("method", method),
|
|
819
841
|
("timeoutMs", Int(config.effectiveTotalTimeout)),
|
|
842
|
+
("bodyBytes", bodyBytes),
|
|
820
843
|
("responseBytes", data.count),
|
|
821
844
|
("elapsedMs", SniConnectLog.elapsedMs(since: startedAt)),
|
|
822
845
|
])
|
|
@@ -18,6 +18,7 @@ enum SniConnectValidation {
|
|
|
18
18
|
case invalidRequestId(String)
|
|
19
19
|
case invalidTimeout(Double)
|
|
20
20
|
case invalidBody
|
|
21
|
+
case invalidUploadFile(String)
|
|
21
22
|
case resourceLimit(String)
|
|
22
23
|
}
|
|
23
24
|
|
|
@@ -26,6 +27,7 @@ enum SniConnectValidation {
|
|
|
26
27
|
static let maxPathBytes = 8 * 1024
|
|
27
28
|
static let maxRequestBodyBytes = 1024 * 1024
|
|
28
29
|
static let maxResponseBodyBytes = 10 * 1024 * 1024
|
|
30
|
+
static let maxUploadFileBytes = 20 * 1024 * 1024
|
|
29
31
|
static let maxHeaderCount = 64
|
|
30
32
|
static let maxHeaderNameBytes = 128
|
|
31
33
|
static let maxHeaderValueBytes = 8 * 1024
|
|
@@ -88,6 +90,75 @@ enum SniConnectValidation {
|
|
|
88
90
|
}
|
|
89
91
|
}
|
|
90
92
|
|
|
93
|
+
/// File uploads always carry a body, so only body-bearing write methods apply.
|
|
94
|
+
static func validateUploadMethod(_ method: String) throws {
|
|
95
|
+
if method != "POST" && method != "PUT" {
|
|
96
|
+
throw ValidationError.invalidMethod(method)
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/// Resolve a caller-supplied upload path to a regular file inside one of
|
|
101
|
+
/// `allowedRoots` (the app's own sandbox). Symlinks are resolved before the
|
|
102
|
+
/// containment check so a link cannot point the upload at another file.
|
|
103
|
+
static func resolveUploadFile(
|
|
104
|
+
_ rawPath: String,
|
|
105
|
+
allowedRoots: [URL]
|
|
106
|
+
) throws -> (url: URL, sizeBytes: Int) {
|
|
107
|
+
if rawPath.isEmpty || containsControlCharacters(rawPath) {
|
|
108
|
+
throw ValidationError.invalidUploadFile("Invalid file path")
|
|
109
|
+
}
|
|
110
|
+
let fileURL: URL
|
|
111
|
+
if rawPath.hasPrefix("file:") {
|
|
112
|
+
guard let parsed = URL(string: rawPath), parsed.isFileURL else {
|
|
113
|
+
throw ValidationError.invalidUploadFile("Invalid file URL")
|
|
114
|
+
}
|
|
115
|
+
fileURL = parsed
|
|
116
|
+
} else if rawPath.hasPrefix("/") {
|
|
117
|
+
fileURL = URL(fileURLWithPath: rawPath)
|
|
118
|
+
} else {
|
|
119
|
+
throw ValidationError.invalidUploadFile("File path must be absolute")
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
let resolvedPath = fileURL.standardizedFileURL.resolvingSymlinksInPath().path
|
|
123
|
+
let isInsideAllowedRoot = allowedRoots.contains { root in
|
|
124
|
+
let rootPath = root.standardizedFileURL.resolvingSymlinksInPath().path
|
|
125
|
+
let prefix = rootPath.hasSuffix("/") ? rootPath : rootPath + "/"
|
|
126
|
+
return resolvedPath.hasPrefix(prefix)
|
|
127
|
+
}
|
|
128
|
+
if !isInsideAllowedRoot {
|
|
129
|
+
throw ValidationError.invalidUploadFile("File is outside the app sandbox")
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
let attributes: [FileAttributeKey: Any]
|
|
133
|
+
do {
|
|
134
|
+
attributes = try FileManager.default.attributesOfItem(atPath: resolvedPath)
|
|
135
|
+
} catch {
|
|
136
|
+
throw ValidationError.invalidUploadFile("File is not readable")
|
|
137
|
+
}
|
|
138
|
+
guard (attributes[.type] as? FileAttributeType) == .typeRegular else {
|
|
139
|
+
throw ValidationError.invalidUploadFile("Not a regular file")
|
|
140
|
+
}
|
|
141
|
+
let sizeBytes = (attributes[.size] as? NSNumber)?.intValue ?? 0
|
|
142
|
+
if sizeBytes <= 0 {
|
|
143
|
+
throw ValidationError.invalidUploadFile("File is empty")
|
|
144
|
+
}
|
|
145
|
+
if sizeBytes > maxUploadFileBytes {
|
|
146
|
+
throw ValidationError.invalidUploadFile("File is too large")
|
|
147
|
+
}
|
|
148
|
+
return (URL(fileURLWithPath: resolvedPath), sizeBytes)
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/// Bound the actual read as well as the earlier path/metadata validation.
|
|
152
|
+
static func readUploadFile(_ url: URL) throws -> Data {
|
|
153
|
+
let handle = try FileHandle(forReadingFrom: url)
|
|
154
|
+
defer { try? handle.close() }
|
|
155
|
+
let data = try handle.read(upToCount: maxUploadFileBytes + 1) ?? Data()
|
|
156
|
+
guard !data.isEmpty, data.count <= maxUploadFileBytes else {
|
|
157
|
+
throw ValidationError.invalidUploadFile("File size is out of range")
|
|
158
|
+
}
|
|
159
|
+
return data
|
|
160
|
+
}
|
|
161
|
+
|
|
91
162
|
/// Validate and uppercase the HTTP method.
|
|
92
163
|
static func normalizeMethod(_ method: String) throws -> String {
|
|
93
164
|
if containsControlCharacters(method) {
|