From f79e78a57203fb3676e6318478cf722a50d219d0 Mon Sep 17 00:00:00 2001 From: James Ide Date: Sun, 29 Nov 2026 01:28:44 -0800 Subject: [PATCH 1/2] Support apps that depend on OkHttp 5 An app that depends on OkHttp 5 crashes when React Native loads cookies (#52945). Gradle resolves okhttp to the app's 5.x, but okhttp-urlconnection stays at the 4.9.2 that ReactAndroid declares, and its JavaNetCookieJar calls okhttp3.internal.Util, which OkHttp 5 removed. No okhttp-urlconnection release works with OkHttp 3, 4 and 5, because each calls internals of its own major version. Add CookieHandlerCookieJar, a port of OkHttp 5's JavaNetCookieJar onto API that OkHttp 3, 4 and 5 share, and use it in NetworkingModule and FrescoModule. React Native no longer uses okhttp-urlconnection. ReactAndroid still declares it as an api dependency, so code that uses JavaNetCookieJar or JavaNetAuthenticator through React Native keeps compiling, and the tests use it to compare the port with JavaNetCookieJar from the OkHttp version under test. An app on OkHttp 5 needs no change unless its code or a keep rule retains JavaNetCookieJar: R8's shrinking removes the unused 4.9.2 classes, so a minified build doesn't fail on the OkHttp 4 internals they call. An app that uses JavaNetCookieJar on OkHttp 5 declares okhttp-urlconnection at its OkHttp version, and an app that wants the dependency gone can exclude it from react-android and any other dependency that brings it in. Like OkHttp 5.5.1's, the port accepts a value that is a lone quote and a value with whitespace just inside its quotes; earlier versions throw on both. Unlike JavaNetCookieJar, it logs and skips a cookie that Cookie.Builder rejects, such as one whose name starts with a vertical tab. Uncaught, that exception fails the request, and OkHttp rethrows it on its dispatcher thread, which crashes the app. Two other things differ on OkHttp 5: - Response.body() is non-null, so seven null checks that OkHttp 3 and 4 need become warnings, which -PenableWarningsAsErrors=true makes errors. Each check now reads the body into an explicitly nullable value first. - MultipartBody reports itself as one-shot when any part is, so getRequestBodyPreview showed a form upload with a file as only "[Binary data, N bytes]" in DevTools. It now checks the parts first. Run the OkHttp compatibility job as a matrix over OkHttp 3.14.9 and 5.5.1, with warnings as errors. The init script takes the version as -PokhttpCompatVersion and logs the Okio version it resolves. Add the OkHttp 5 rules to AGENTS.md. Signed-off-by: James Ide --- ...tp3-compat.gradle => okhttp-compat.gradle} | 28 ++-- .github/workflows/test-android.yml | 18 ++- AGENTS.md | 8 +- .../ReactAndroid/build.gradle.kts | 2 + .../react/devsupport/BundleDownloader.kt | 5 +- .../react/devsupport/DevServerHelper.kt | 8 +- .../react/devsupport/PackagerStatusCheck.kt | 3 +- .../inspector/InspectorNetworkHelper.kt | 4 +- .../react/modules/fresco/FrescoModule.kt | 4 +- .../modules/network/CookieHandlerCookieJar.kt | 123 +++++++++++++++ .../react/modules/network/NetworkEventUtil.kt | 15 +- .../react/modules/network/NetworkingModule.kt | 7 +- .../network/CookieHandlerCookieJarTest.kt | 141 ++++++++++++++++++ .../modules/network/NetworkEventUtilTest.kt | 3 + 14 files changed, 331 insertions(+), 38 deletions(-) rename .github/workflow-scripts/{okhttp3-compat.gradle => okhttp-compat.gradle} (56%) create mode 100644 packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/network/CookieHandlerCookieJar.kt create mode 100644 packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/network/CookieHandlerCookieJarTest.kt diff --git a/.github/workflow-scripts/okhttp3-compat.gradle b/.github/workflow-scripts/okhttp-compat.gradle similarity index 56% rename from .github/workflow-scripts/okhttp3-compat.gradle rename to .github/workflow-scripts/okhttp-compat.gradle index e6c576c1ed21..289a17a0882b 100644 --- a/.github/workflow-scripts/okhttp3-compat.gradle +++ b/.github/workflow-scripts/okhttp-compat.gradle @@ -9,27 +9,35 @@ import org.gradle.api.GradleException import org.gradle.api.artifacts.component.ModuleComponentIdentifier // Keep the normal build on the version in the catalog. This init script is only -// used by the compatibility job, so its compile and test classpaths use OkHttp 3. -// This catches new OkHttp 4-only calls before they need reverting (e.g. #60318). +// used by the compatibility jobs, so its compile and test classpaths use the +// OkHttp version passed with -PokhttpCompatVersion. OkHttp 3 catches new OkHttp +// 4-only calls before they need reverting (e.g. #60318). OkHttp 5 catches API and +// behavior changes that apps depending on it would hit. Those apps run the AAR +// built against the catalog version, so this does not check binary compatibility. +// OkHttp 5 also brings Okio 3, so the verification logs the Okio version too. gradle.beforeProject { project -> if (project.path != ':packages:react-native:ReactAndroid') { return } - def okhttpVersion = '3.14.9' + def okhttpVersion = project.findProperty('okhttpCompatVersion') + if (!okhttpVersion) { + throw new GradleException('Pass the OkHttp version to check, e.g. -PokhttpCompatVersion=3.14.9') + } + project.configurations.configureEach { configuration -> configuration.resolutionStrategy.eachDependency { details -> if (details.requested.group == 'com.squareup.okhttp3') { details.useVersion(okhttpVersion) - details.because('Check ReactAndroid source compatibility with OkHttp 3') + details.because("Check ReactAndroid source compatibility with OkHttp ${okhttpVersion}") } } } project.plugins.withId('com.android.library') { - project.tasks.register('verifyOkHttp3Compatibility') { task -> + project.tasks.register('verifyOkHttpCompatibility') { task -> task.group = 'verification' - task.description = 'Compiles and tests ReactAndroid against OkHttp 3.14.9.' + task.description = "Compiles and tests ReactAndroid against OkHttp ${okhttpVersion}." task.dependsOn('testDebugUnitTest') task.doLast { [ @@ -39,13 +47,15 @@ gradle.beforeProject { project -> 'debugUnitTestRuntimeClasspath', ].each { name -> def configuration = project.configurations.getByName(name) - def modules = configuration.incoming.resolutionResult.allComponents + def components = configuration.incoming.resolutionResult.allComponents .collect { it.id } - .findAll { it instanceof ModuleComponentIdentifier && it.group == 'com.squareup.okhttp3' } + .findAll { it instanceof ModuleComponentIdentifier } + def modules = components.findAll { it.group == 'com.squareup.okhttp3' } if (modules.isEmpty() || modules.any { it.version != okhttpVersion }) { throw new GradleException("Expected OkHttp ${okhttpVersion} on ${project.path}:${name}, found: ${modules}") } - project.logger.lifecycle("Verified ${project.path}:${name}: ${modules}") + def okio = components.findAll { it.group == 'com.squareup.okio' } + project.logger.lifecycle("Verified ${project.path}:${name}: ${modules} with ${okio}") } } } diff --git a/.github/workflows/test-android.yml b/.github/workflows/test-android.yml index ea6a24ed89ff..df46cbbd3064 100644 --- a/.github/workflows/test-android.yml +++ b/.github/workflows/test-android.yml @@ -53,8 +53,14 @@ jobs: skip-apple-prebuilts: true artifact-suffix: -android - test_okhttp3: + test_okhttp: runs-on: 8-core-ubuntu + strategy: + fail-fast: false + matrix: + # OkHttp 3 for downstream builds from source, OkHttp 5 for apps that + # depend on it. + okhttp: ['3.14.9', '5.5.1'] container: image: reactnativecommunity/react-native-android:latest env: @@ -72,15 +78,17 @@ jobs: uses: ./.github/actions/setup-gradle with: cache-encryption-key: ${{ secrets.GRADLE_CACHE_ENCRYPTION_KEY }} - - name: Compile and test ReactAndroid with OkHttp 3.14.9 + - name: Compile and test ReactAndroid with OkHttp ${{ matrix.okhttp }} run: | - ./gradlew --init-script .github/workflow-scripts/okhttp3-compat.gradle \ - :packages:react-native:ReactAndroid:verifyOkHttp3Compatibility + ./gradlew --init-script .github/workflow-scripts/okhttp-compat.gradle \ + -PokhttpCompatVersion=${{ matrix.okhttp }} \ + -PenableWarningsAsErrors=true \ + :packages:react-native:ReactAndroid:verifyOkHttpCompatibility - name: Upload test results if: ${{ always() }} uses: ./.github/actions/upload-artifact with: - name: android-okhttp3-results + name: android-okhttp-${{ matrix.okhttp }}-results path: packages/react-native/ReactAndroid/build/reports/tests/testDebugUnitTest/ if-no-files-found: ignore diff --git a/AGENTS.md b/AGENTS.md index 5b30ab76d010..24daded1efb7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -52,9 +52,11 @@ The formatting command uses pinned npm packages for Kotlin and Java and installs ## Android networking compatibility -- Keep shared Android Java and Kotlin sources, including devsupport code, source-compatible with OkHttp 3.14.9. Downstream consumers build React Native from source with OkHttp 3 even when the OSS build and tests select a newer version. -- Use APIs available in both OkHttp 3 and the version configured in this repository. Avoid APIs and Kotlin extensions introduced in newer major versions, such as `okhttp3.HttpUrl.Companion.toHttpUrlOrNull`; use compatible APIs such as `Request.Builder().url(...)` for URL validation. The `okhttp3` package name is also used by newer major versions and does not establish compatibility. -- When introducing or changing OkHttp usage, compile the affected sources against OkHttp 3.14.9 and run the relevant tests with the repository's configured version. Passing tests with a newer OkHttp version does not verify OkHttp 3 source compatibility. Report the selected versions, exact commands and results in the PR test plan, and state any compatibility check you could not run. +- Keep shared Android Java and Kotlin sources, including devsupport code, source-compatible with OkHttp 3.14.9 and OkHttp 5. Downstream consumers build React Native from source with OkHttp 3 even when the OSS build and tests select a newer version, and apps that depend on OkHttp 5 run React Native with it. +- Use APIs available in OkHttp 3, OkHttp 5 and the version configured in this repository. Avoid APIs and Kotlin extensions introduced after OkHttp 3, such as `okhttp3.HttpUrl.Companion.toHttpUrlOrNull`; use compatible APIs such as `Request.Builder().url(...)` for URL validation. The `okhttp3` package name is also used by newer major versions and does not establish compatibility. +- `Response.body()` is declared nullable before OkHttp 5 and non-null from OkHttp 5 on. Before comparing it with null or calling it with `?.`, assign it to an explicitly nullable value, such as `val body: ResponseBody? = response.body()`, so the code compiles without warnings on every version. +- Don't use `okhttp-urlconnection` (`okhttp3.JavaNetCookieJar`, `okhttp3.JavaNetAuthenticator`) in main sources. Each `JavaNetCookieJar` release calls internals of its own OkHttp major version, and 4.9.2's crashes apps that depend on OkHttp 5 (#52945). To store cookies in a `CookieHandler`, use `CookieHandlerCookieJar`. ReactAndroid still declares `okhttp-urlconnection` as an `api` dependency for code that uses it through React Native, and `CookieHandlerCookieJarTest` uses it as its reference implementation. +- When introducing or changing OkHttp usage, compile the affected sources and run the relevant tests with each OkHttp version in the `test_okhttp` matrix in `.github/workflows/test-android.yml`, and with the repository's configured version. `./gradlew --init-script .github/workflow-scripts/okhttp-compat.gradle -PokhttpCompatVersion=3.14.9 -PenableWarningsAsErrors=true :packages:react-native:ReactAndroid:verifyOkHttpCompatibility` compiles ReactAndroid and runs its JVM tests with the given version. Passing tests with a newer OkHttp version does not verify OkHttp 3 source compatibility. Report the selected versions, exact commands and results in the PR test plan, and state any compatibility check you could not run. ## Verification: Running RNTester diff --git a/packages/react-native/ReactAndroid/build.gradle.kts b/packages/react-native/ReactAndroid/build.gradle.kts index cf985fe22d88..fb568e0037a2 100644 --- a/packages/react-native/ReactAndroid/build.gradle.kts +++ b/packages/react-native/ReactAndroid/build.gradle.kts @@ -781,6 +781,8 @@ dependencies { api(libs.yoga.proguard.annotations) api(libs.jsr305) + // Publish okhttp-urlconnection for code that uses JavaNetCookieJar or + // JavaNetAuthenticator through react-android. React Native itself doesn't use it. api(libs.okhttp3.urlconnection) api(libs.okhttp3) api(libs.okio) diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/devsupport/BundleDownloader.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/devsupport/BundleDownloader.kt index 61f559a869c2..af09792c83f7 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/devsupport/BundleDownloader.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/devsupport/BundleDownloader.kt @@ -26,6 +26,7 @@ import okhttp3.Headers import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response +import okhttp3.ResponseBody import okio.BufferedSource import okio.Okio import org.json.JSONException @@ -130,7 +131,7 @@ public class BundleDownloader public constructor(private val client: OkHttpClien // In case the server doesn't support multipart/mixed responses, fallback to // normal // download. - val body = resp.body() + val body: ResponseBody? = resp.body() // Nullable before OkHttp 5 if (body != null) { body.use { processBundleResult( @@ -169,7 +170,7 @@ public class BundleDownloader public constructor(private val client: OkHttpClien bundleInfo: BundleInfo?, callback: DevBundleDownloadListener, ) { - val responseBody = response.body() + val responseBody: ResponseBody? = response.body() // Nullable before OkHttp 5 if (responseBody == null) { callback.onFailure( DebugServerException( diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevServerHelper.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevServerHelper.kt index 8533b6035573..9d07669e8aa9 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevServerHelper.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevServerHelper.kt @@ -50,6 +50,7 @@ import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody import okhttp3.Response +import okhttp3.ResponseBody import okio.Okio /** @@ -331,12 +332,11 @@ public open class DevServerHelper( try { client.newCall(request).execute().use { response -> - if (!response.isSuccessful || response.body() == null) { + val body: ResponseBody? = response.body() // Nullable before OkHttp 5 + if (!response.isSuccessful || body == null) { return null } - Okio.sink(outputFile).use { output -> - Okio.buffer(response.body()?.source()!!).readAll(output) - } + Okio.sink(outputFile).use { output -> Okio.buffer(body.source()).readAll(output) } return outputFile } } catch (e: Exception) { diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/devsupport/PackagerStatusCheck.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/devsupport/PackagerStatusCheck.kt index d39b855518b6..5cd4bd7994fe 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/devsupport/PackagerStatusCheck.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/devsupport/PackagerStatusCheck.kt @@ -20,6 +20,7 @@ import okhttp3.Callback import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response +import okhttp3.ResponseBody /** Use this class to check if the JavaScript packager is running on the provided host. */ internal class PackagerStatusCheck(private val client: OkHttpClient) { @@ -51,7 +52,7 @@ internal class PackagerStatusCheck(private val client: OkHttpClient) { callback.onPackagerStatusFetched(false) return } - val body = response.body() + val body: ResponseBody? = response.body() // Nullable before OkHttp 5 if (body == null) { FLog.e( ReactConstants.TAG, diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/devsupport/inspector/InspectorNetworkHelper.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/devsupport/inspector/InspectorNetworkHelper.kt index d63c6382304e..58ed496721b4 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/devsupport/inspector/InspectorNetworkHelper.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/devsupport/inspector/InspectorNetworkHelper.kt @@ -14,6 +14,7 @@ import okhttp3.Call import okhttp3.Callback import okhttp3.Request import okhttp3.Response +import okhttp3.ResponseBody internal object InspectorNetworkHelper { @@ -52,7 +53,8 @@ internal object InspectorNetworkHelper { listener.onHeaders(response.code(), headersMap) try { - response.body().use { responseBody -> + val body: ResponseBody? = response.body() // Nullable before OkHttp 5 + body.use { responseBody -> if (responseBody != null) { val inputStream = responseBody.byteStream() val chunkSize = 8 * 1024 // 8Kb diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/fresco/FrescoModule.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/fresco/FrescoModule.kt index 9817839d836d..0e54044c7bb9 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/fresco/FrescoModule.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/fresco/FrescoModule.kt @@ -22,11 +22,11 @@ import com.facebook.react.bridge.ReactContextBaseJavaModule import com.facebook.react.common.ReactConstants import com.facebook.react.module.annotations.ReactModule import com.facebook.react.modules.common.ModuleDataCleaner +import com.facebook.react.modules.network.CookieHandlerCookieJar import com.facebook.react.modules.network.CookieJarContainer import com.facebook.react.modules.network.ForwardingCookieHandler import com.facebook.react.modules.network.OkHttpClientProvider import com.facebook.react.turbomodule.core.interfaces.TurboModule -import okhttp3.JavaNetCookieJar /** * Module to initialize the Fresco library. @@ -162,7 +162,7 @@ constructor( val container = client.cookieJar() as CookieJarContainer val handler = ForwardingCookieHandler() - container.setCookieJar(JavaNetCookieJar(handler)) + container.setCookieJar(CookieHandlerCookieJar(handler)) val builder = OkHttpImagePipelineConfigFactory.newBuilder(context.applicationContext, client) .setNetworkFetcher(ReactOkHttpNetworkFetcher(client)) diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/network/CookieHandlerCookieJar.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/network/CookieHandlerCookieJar.kt new file mode 100644 index 000000000000..2998f4dbde51 --- /dev/null +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/network/CookieHandlerCookieJar.kt @@ -0,0 +1,123 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +@file:Suppress("DEPRECATION_ERROR") // Conflicting okhttp versions + +package com.facebook.react.modules.network + +import com.facebook.common.logging.FLog +import com.facebook.react.common.ReactConstants +import java.io.IOException +import java.net.CookieHandler +import okhttp3.Cookie +import okhttp3.CookieJar +import okhttp3.HttpUrl + +/** + * Stores OkHttp's cookies in a [CookieHandler], as `JavaNetCookieJar` from `okhttp-urlconnection` + * does, through API that OkHttp 3, 4 and 5 share. Each `JavaNetCookieJar` release calls internals + * of its own OkHttp major version: 4.9.2's throws `NoClassDefFoundError` on OkHttp 5. + */ +internal class CookieHandlerCookieJar(private val cookieHandler: CookieHandler) : CookieJar { + + override fun saveFromResponse(url: HttpUrl, cookies: List) { + val headers = mapOf("Set-Cookie" to cookies.map { toSetCookieHeader(it) }) + try { + cookieHandler.put(url.uri(), headers) + } catch (e: IOException) { + FLog.w(ReactConstants.TAG, "Saving cookies failed for ${url.resolve("/...")}", e) + } + } + + override fun loadForRequest(url: HttpUrl): List { + val headers = + try { + cookieHandler.get(url.uri(), emptyMap()) + } catch (e: IOException) { + FLog.w(ReactConstants.TAG, "Loading cookies failed for ${url.resolve("/...")}", e) + return emptyList() + } + return headers + .filterKeys { + it.equals("Cookie", ignoreCase = true) || it.equals("Cookie2", ignoreCase = true) + } + .values + .flatMap { values -> values.flatMap { decodeCookieHeader(url, it) } } + } + + private companion object { + private const val DOMAIN_ATTRIBUTE = "; domain=" + + /** + * [Cookie.toString], with a leading dot on the domain of a cookie that isn't host-only. + * Handlers that follow RFC 2965, such as [java.net.CookieManager], need the dot to match + * `www.example.com` to `example.com`. + */ + fun toSetCookieHeader(cookie: Cookie): String { + val header = cookie.toString() + if (cookie.hostOnly()) { + return header + } + // Search after "name=value", so a value can't be mistaken for the attribute. + val attribute = + header.indexOf(DOMAIN_ATTRIBUTE, cookie.name().length + 1 + cookie.value().length) + if (attribute < 0) { + return header + } + val domain = attribute + DOMAIN_ATTRIBUTE.length + return header.substring(0, domain) + "." + header.substring(domain) + } + + /** + * Splits a `Cookie` request header into cookies. [Cookie.parse] can't: it reads one + * `Set-Cookie` value. + */ + fun decodeCookieHeader(url: HttpUrl, header: String): List { + val result = mutableListOf() + var pos = 0 + while (pos < header.length) { + val pairEnd = + header.indexOfAny(PAIR_DELIMITERS, pos).let { if (it < 0) header.length else it } + val equalsSign = + header.indexOf('=', pos).let { if (it < 0 || it > pairEnd) pairEnd else it } + val name = header.substring(pos, equalsSign).trim(::isAsciiWhitespace) + pos = pairEnd + 1 + if (name.startsWith("$")) { + continue // An attribute such as $Path, not a cookie. + } + var value = + if (equalsSign < pairEnd) + header.substring(equalsSign + 1, pairEnd).trim(::isAsciiWhitespace) + else "" + if (value.length >= 2 && value.startsWith("\"") && value.endsWith("\"")) { + value = value.substring(1, value.length - 1) + } + // Cookie.Builder rejects surrounding whitespace, which unquoting can leave, as in "abc ". + value = value.trim() + try { + result.add(Cookie.Builder().name(name).value(value).domain(url.host()).build()) + } catch (e: IllegalArgumentException) { + // Cookie.Builder rejects a name or value that its own trim would change, such as a name + // starting with a vertical tab, and what it trims differs between OkHttp 3 and later + // versions. Uncaught, the exception fails the request, and OkHttp rethrows it on its + // dispatcher thread, which crashes the app. The log omits the stack trace, because a + // stored cookie is rejected again on every request to its host. + FLog.w( + ReactConstants.TAG, + "Skipped a cookie OkHttp rejects for ${url.resolve("/...")}: ${e.message}", + ) + } + } + return result + } + + private val PAIR_DELIMITERS = charArrayOf(';', ',') + + private fun isAsciiWhitespace(c: Char): Boolean = + c == ' ' || c == '\t' || c == '\n' || c == '\u000C' || c == '\r' + } +} diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/network/NetworkEventUtil.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/network/NetworkEventUtil.kt index e12e6540832c..4b2a1d8f7e89 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/network/NetworkEventUtil.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/network/NetworkEventUtil.kt @@ -251,19 +251,20 @@ internal object NetworkEventUtil { // Unwrap ProgressRequestBody val body = (requestBody as? ProgressRequestBody)?.innerBody() ?: requestBody + // Check each part of a MultipartBody before checking the whole body: OkHttp 5 + // reports a multipart body as one-shot when any part is, and OkHttp 3 and 4 + // never do. Reading a one-shot part here would drain the underlying stream and + // cause the real request to fail. + if (body is MultipartBody && body.parts().any { it.body().isOneShot() }) { + return previewMultipartWithBinaryParts(body) + } + if (body.isOneShot()) { // Reading would drain the underlying stream and break the real upload, // so fall back to a placeholder that includes the byte count when known return binaryPartLabel(body) } - // MultipartBody does not propagate isOneShot() from its parts, so check each - // part explicitly. Reading a one-shot part here would drain the underlying - // stream and cause the real request to fail. - if (body is MultipartBody && body.parts().any { it.body().isOneShot() }) { - return previewMultipartWithBinaryParts(body) - } - return try { val buffer = Buffer() body.writeTo(buffer) diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/network/NetworkingModule.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/network/NetworkingModule.kt index c0cb072dc725..1a2f22842c9b 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/network/NetworkingModule.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/network/NetworkingModule.kt @@ -38,7 +38,6 @@ import okhttp3.Call import okhttp3.Callback import okhttp3.CookieJar import okhttp3.Headers -import okhttp3.JavaNetCookieJar import okhttp3.MediaType import okhttp3.MultipartBody import okhttp3.OkHttpClient @@ -183,7 +182,7 @@ public class NetworkingModule( public interface CustomClientBuilder : com.facebook.react.modules.network.CustomClientBuilder override fun initialize() { - cookieJarContainer?.setCookieJar(JavaNetCookieJar(cookieHandler)) + cookieJarContainer?.setCookieJar(CookieHandlerCookieJar(cookieHandler)) } override fun invalidate() { @@ -653,6 +652,7 @@ public class NetworkingModule( return } removeRequest(requestId) + var responseBody: ResponseBody? = response.body() // Nullable before OkHttp 5 // Before we touch the body send headers to JS NetworkEventUtil.onResponseReceived( reactApplicationContext, @@ -661,7 +661,7 @@ public class NetworkingModule( response.request().url().toString(), response.code(), NetworkEventUtil.okHttpHeadersToMap(response.headers()), - response.body()?.contentLength() ?: 0L, + responseBody?.contentLength() ?: 0L, ) try { @@ -679,7 +679,6 @@ public class NetworkingModule( // it used transparent gzip. // See // https://github.com/square/okhttp/blob/5b37cda9e00626f43acf354df145fd452c3031f1/okhttp/src/main/java/okhttp3/internal/http/BridgeInterceptor.java#L76-L111 - var responseBody: ResponseBody? = response.body() if (responseBody == null) { NetworkEventUtil.onRequestError( reactApplicationContext, diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/network/CookieHandlerCookieJarTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/network/CookieHandlerCookieJarTest.kt new file mode 100644 index 000000000000..7cf65351a28f --- /dev/null +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/network/CookieHandlerCookieJarTest.kt @@ -0,0 +1,141 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +@file:Suppress("DEPRECATION_ERROR") // Conflicting okhttp versions + +package com.facebook.react.modules.network + +import android.util.Log +import java.io.IOException +import java.net.CookieHandler +import java.net.URI +import okhttp3.Cookie +import okhttp3.HttpUrl +import okhttp3.JavaNetCookieJar +import org.assertj.core.api.Assertions.assertThat +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.shadows.ShadowLog + +/** Compares [CookieHandlerCookieJar] with `JavaNetCookieJar` from the same OkHttp version. */ +@RunWith(RobolectricTestRunner::class) // Records what FLog writes to android.util.Log +class CookieHandlerCookieJarTest { + + private val url = checkNotNull(HttpUrl.parse("https://www.example.com/path")) + + @Test + fun testSavesCookiesAsJavaNetCookieJarDoes() { + val cookies = + listOf( + "host=1", + "persistent=3; Max-Age=3600", + "expired=4; Max-Age=0", + ) + .map { checkNotNull(Cookie.parse(url, it)) } + + listOf( + // Built, not parsed: parsing a Domain attribute needs OkHttp 5's public suffix + // list, an Android asset that these tests don't load. + Cookie.Builder() + .name("shared") + .value("2") + .domain("example.com") + .path("/") + .secure() + .httpOnly() + .build(), + // A built value can hold the domain attribute's text. + Cookie.Builder().name("built").value("a; domain=b").domain("example.com").build(), + ) + + val ours = FakeCookieHandler() + val theirs = FakeCookieHandler() + CookieHandlerCookieJar(ours).saveFromResponse(url, cookies) + JavaNetCookieJar(theirs).saveFromResponse(url, cookies) + + assertThat(ours.saved).isEqualTo(theirs.saved) + assertThat(ours.saved.getValue("Set-Cookie")[3]).contains("; domain=.example.com") + assertThat(ours.saved.getValue("Set-Cookie")[4]) + .startsWith("built=a; domain=b; domain=.example.com") + } + + @Test + fun testLoadsCookiesAsJavaNetCookieJarDoes() { + val handler = + FakeCookieHandler( + mapOf( + "Cookie" to listOf("a=1; b=\"2\"; \$Version=1, c ; d= 4 "), + "cookie2" to listOf("e=5"), + "Set-Cookie" to listOf("ignored=6"), + ), + ) + + val ours = CookieHandlerCookieJar(handler).loadForRequest(url) + + assertThat(ours).isEqualTo(JavaNetCookieJar(handler).loadForRequest(url)) + assertThat(ours.map { "${it.name()}=${it.value()}" }) + .containsExactly("a=1", "b=2", "c=", "d=4", "e=5") + assertThat(ours).allMatch { it.domain() == "www.example.com" } + } + + @Test + fun testLoadsValuesThatJavaNetCookieJarRejectsBeforeOkHttp5() { + // Before OkHttp 5, JavaNetCookieJar throws on these, so this test checks the values directly. + val handler = FakeCookieHandler(mapOf("Cookie" to listOf("lone=\"; spaced=\"abc \""))) + + val cookies = CookieHandlerCookieJar(handler).loadForRequest(url) + + assertThat(cookies.map { "${it.name()}=${it.value()}" }) + .containsExactly("lone=\"", "spaced=abc") + } + + @Test + fun testSkipsCookiesThatCookieBuilderRejects() { + // Every OkHttp version's Cookie.Builder rejects a name that starts with a vertical tab. + val handler = FakeCookieHandler(mapOf("Cookie" to listOf("\u000Bx=1; a=1"))) + + val cookies = CookieHandlerCookieJar(handler).loadForRequest(url) + + assertThat(cookies.map { "${it.name()}=${it.value()}" }).containsExactly("a=1") + assertThat(warnings()).anyMatch { + it.startsWith("Skipped a cookie OkHttp rejects for https://www.example.com/...") + } + } + + @Test + fun testHandlerFailuresAreNotThrown() { + val jar = CookieHandlerCookieJar(FakeCookieHandler(fail = true)) + + jar.saveFromResponse(url, listOf(checkNotNull(Cookie.parse(url, "a=1")))) + + assertThat(jar.loadForRequest(url)).isEmpty() + assertThat(warnings()) + .anyMatch { it.startsWith("Saving cookies failed for https://www.example.com/...") } + .anyMatch { it.startsWith("Loading cookies failed for https://www.example.com/...") } + assertThat(CookieHandlerCookieJar(FakeCookieHandler()).loadForRequest(url)).isEmpty() + } + + private fun warnings(): List = + ShadowLog.getLogs().filter { it.type == Log.WARN }.map { it.msg } + + private class FakeCookieHandler( + private val stored: Map> = emptyMap(), + private val fail: Boolean = false, + ) : CookieHandler() { + var saved: Map> = emptyMap() + + override fun get(uri: URI, headers: Map>): Map> { + if (fail) throw IOException("get failed") + return stored + } + + override fun put(uri: URI, headers: Map>) { + if (fail) throw IOException("put failed") + saved = headers + } + } +} diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/network/NetworkEventUtilTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/network/NetworkEventUtilTest.kt index 2fc4bc5117d0..39bee64b901a 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/network/NetworkEventUtilTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/network/NetworkEventUtilTest.kt @@ -393,6 +393,9 @@ class NetworkEventUtilTest { assertThat(preview).contains("filename=\"photo.jpg\"") assertThat(preview).contains("[Binary data, 2048 bytes]") assertThat(preview).doesNotContain("[Preview unavailable]") + // NetworkingModule sends every upload wrapped in a ProgressRequestBody + assertThat(NetworkEventUtil.getRequestBodyPreview(ProgressRequestBody(body) { _, _, _ -> })) + .isEqualTo(preview) } @Test From 79eefcbbc9c98c142ef5c83ebb1526a36600f089 Mon Sep 17 00:00:00 2001 From: James Ide Date: Thu, 3 Dec 2026 11:13:19 -0800 Subject: [PATCH 2/2] Validate cookie header characters and redact warning logs Validate decoded cookie names and values against OkHttp's request-header character rules (tab and printable ASCII) before building the Cookie, use url.redact() in all warning logs, and omit cookie details from rejected-cookie warnings. Signed-off-by: James Ide --- .../modules/network/CookieHandlerCookieJar.kt | 28 +++--- .../network/CookieHandlerCookieJarTest.kt | 90 ++++++++++++++++++- 2 files changed, 104 insertions(+), 14 deletions(-) diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/network/CookieHandlerCookieJar.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/network/CookieHandlerCookieJar.kt index 2998f4dbde51..593dab1ac50a 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/network/CookieHandlerCookieJar.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/network/CookieHandlerCookieJar.kt @@ -29,7 +29,7 @@ internal class CookieHandlerCookieJar(private val cookieHandler: CookieHandler) try { cookieHandler.put(url.uri(), headers) } catch (e: IOException) { - FLog.w(ReactConstants.TAG, "Saving cookies failed for ${url.resolve("/...")}", e) + FLog.w(ReactConstants.TAG, "Saving cookies failed for ${url.redact()}", e) } } @@ -38,7 +38,7 @@ internal class CookieHandlerCookieJar(private val cookieHandler: CookieHandler) try { cookieHandler.get(url.uri(), emptyMap()) } catch (e: IOException) { - FLog.w(ReactConstants.TAG, "Loading cookies failed for ${url.resolve("/...")}", e) + FLog.w(ReactConstants.TAG, "Loading cookies failed for ${url.redact()}", e) return emptyList() } return headers @@ -99,17 +99,19 @@ internal class CookieHandlerCookieJar(private val cookieHandler: CookieHandler) // Cookie.Builder rejects surrounding whitespace, which unquoting can leave, as in "abc ". value = value.trim() try { + // Cookie.Builder accepts characters (such as non-ASCII, DEL, and control characters other + // than tab) that OkHttp rejects when building the Cookie request header, and it rejects a + // name or value that its own trim would change (which differs across OkHttp versions). + // Uncaught, either IllegalArgumentException fails the request, and OkHttp rethrows it on + // its dispatcher thread, which crashes the app. + require(name.all(::isValidHeaderCharacter) && value.all(::isValidHeaderCharacter)) { + "Invalid request header characters" + } result.add(Cookie.Builder().name(name).value(value).domain(url.host()).build()) - } catch (e: IllegalArgumentException) { - // Cookie.Builder rejects a name or value that its own trim would change, such as a name - // starting with a vertical tab, and what it trims differs between OkHttp 3 and later - // versions. Uncaught, the exception fails the request, and OkHttp rethrows it on its - // dispatcher thread, which crashes the app. The log omits the stack trace, because a - // stored cookie is rejected again on every request to its host. - FLog.w( - ReactConstants.TAG, - "Skipped a cookie OkHttp rejects for ${url.resolve("/...")}: ${e.message}", - ) + } catch (_: IllegalArgumentException) { + // Omit cookie contents, exception message, and stack trace: a stored cookie is rejected + // again on every request to its host. + FLog.w(ReactConstants.TAG, "Skipped a cookie OkHttp rejects for ${url.redact()}") } } return result @@ -119,5 +121,7 @@ internal class CookieHandlerCookieJar(private val cookieHandler: CookieHandler) private fun isAsciiWhitespace(c: Char): Boolean = c == ' ' || c == '\t' || c == '\n' || c == '\u000C' || c == '\r' + + private fun isValidHeaderCharacter(c: Char): Boolean = c == '\t' || c in ' '..'~' } } diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/network/CookieHandlerCookieJarTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/network/CookieHandlerCookieJarTest.kt index 7cf65351a28f..3107f90a8bce 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/network/CookieHandlerCookieJarTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/modules/network/CookieHandlerCookieJarTest.kt @@ -16,7 +16,9 @@ import java.net.URI import okhttp3.Cookie import okhttp3.HttpUrl import okhttp3.JavaNetCookieJar +import okhttp3.Request import org.assertj.core.api.Assertions.assertThat +import org.assertj.core.api.Assertions.assertThatThrownBy import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @@ -101,8 +103,92 @@ class CookieHandlerCookieJarTest { val cookies = CookieHandlerCookieJar(handler).loadForRequest(url) assertThat(cookies.map { "${it.name()}=${it.value()}" }).containsExactly("a=1") - assertThat(warnings()).anyMatch { - it.startsWith("Skipped a cookie OkHttp rejects for https://www.example.com/...") + assertThat(warnings()) + .containsExactly("Skipped a cookie OkHttp rejects for https://www.example.com/...") + } + + @Test + fun testSkipsCookiesWithInvalidRequestHeaderCharacters() { + // Cookie.Builder accepts Unicode, but OkHttp rejects it when constructing the Cookie header. + val unicodeCookie = + Cookie.Builder().name("unicode").value("caf\u00e9").domain(url.host()).build() + assertThatThrownBy { + Request.Builder() + .url(url) + .header("Cookie", "${unicodeCookie.name()}=${unicodeCookie.value()}") + .build() + } + .isInstanceOf(IllegalArgumentException::class.java) + + val handler = + FakeCookieHandler( + mapOf( + "Cookie" to + listOf( + "ctrl\u0007name=1; ctrlval=a\u001Fb; " + + "del\u007Fname=1; delval=a\u007Fb; " + + "uni\u00e9name=1; unival=caf\u00e9; " + + "ok=1", + ), + ), + ) + + val cookies = CookieHandlerCookieJar(handler).loadForRequest(url) + + assertThat(cookies.map { "${it.name()}=${it.value()}" }).containsExactly("ok=1") + assertThat(warnings()).hasSize(6).allMatch { + it == "Skipped a cookie OkHttp rejects for https://www.example.com/..." + } + } + + @Test + fun testAllowsValidRequestHeaderCharacters() { + val handler = + FakeCookieHandler( + mapOf("Cookie" to listOf("a b=c d; tab\tname=x\ty; tilde=~!@#")), + ) + + val cookies = CookieHandlerCookieJar(handler).loadForRequest(url) + + assertThat(cookies.map { "${it.name()}=${it.value()}" }) + .containsExactly("a b=c d", "tab\tname=x\ty", "tilde=~!@#") + val header = cookies.joinToString("; ") { "${it.name()}=${it.value()}" } + val request = Request.Builder().url(url).header("Cookie", header).build() + assertThat(request.header("Cookie")).isEqualTo(header) + } + + @Test + fun testRedactsUrlCredentialsAndCookieContentsInWarnings() { + val urlWithCredentials = + checkNotNull( + HttpUrl.parse("https://user:secret-pass@www.example.com/private/path?token=abc"), + ) + val badCookieJar = + CookieHandlerCookieJar( + FakeCookieHandler(mapOf("Cookie" to listOf("bad\u00e9=secret-cookie-value"))), + ) + assertThat(badCookieJar.loadForRequest(urlWithCredentials)).isEmpty() + + val failingJar = CookieHandlerCookieJar(FakeCookieHandler(fail = true)) + failingJar.saveFromResponse( + urlWithCredentials, + listOf(checkNotNull(Cookie.parse(urlWithCredentials, "a=1"))), + ) + assertThat(failingJar.loadForRequest(urlWithCredentials)).isEmpty() + + val allWarnings = warnings() + assertThat(allWarnings).hasSize(3) + assertThat(allWarnings[0]) + .isEqualTo("Skipped a cookie OkHttp rejects for https://www.example.com/...") + assertThat(allWarnings[1]).startsWith("Saving cookies failed for https://www.example.com/...") + assertThat(allWarnings[2]).startsWith("Loading cookies failed for https://www.example.com/...") + assertThat(allWarnings).noneMatch { + it.contains("user") || + it.contains("secret-pass") || + it.contains("/private") || + it.contains("token=abc") || + it.contains("bad\u00e9") || + it.contains("secret-cookie-value") } }