diff --git a/mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt b/mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt index 0400e804d79f..afcb8da4b312 100644 --- a/mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt +++ b/mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt @@ -328,7 +328,7 @@ public class MockWebServer : Closeable { try { val serverSocketFactory = serverSocketFactory_ - ?: (ServerSocketFactory.getDefault()!!.also { this.serverSocketFactory_ = it }) + ?: (Platform.get().serverSocketFactory.also { this.serverSocketFactory_ = it }) val serverSocket = serverSocketFactory diff --git a/okhttp-testing-support/src/main/kotlin/okhttp3/TestValueFactory.kt b/okhttp-testing-support/src/main/kotlin/okhttp3/TestValueFactory.kt index 0c06968c1e30..39732788e9b7 100644 --- a/okhttp-testing-support/src/main/kotlin/okhttp3/TestValueFactory.kt +++ b/okhttp-testing-support/src/main/kotlin/okhttp3/TestValueFactory.kt @@ -27,7 +27,6 @@ import java.net.Proxy import java.net.ProxySelector import java.net.Socket import java.util.concurrent.TimeUnit -import javax.net.SocketFactory import javax.net.ssl.HostnameVerifier import javax.net.ssl.HttpsURLConnection import javax.net.ssl.SSLSocketFactory @@ -42,6 +41,7 @@ import okhttp3.internal.connection.RealConnectionPool import okhttp3.internal.connection.RealRoutePlanner import okhttp3.internal.http.RealInterceptorChain import okhttp3.internal.http.RecordingProxySelector +import okhttp3.internal.platform.Platform import okhttp3.tls.HandshakeCertificates import okhttp3.tls.internal.TlsUtil.localhost @@ -118,7 +118,7 @@ class TestValueFactory : Closeable { uriHost = uriHost, uriPort = uriPort, dns = dns, - socketFactory = SocketFactory.getDefault(), + socketFactory = Platform.get().socketFactory, sslSocketFactory = null, hostnameVerifier = null, certificatePinner = null, @@ -141,7 +141,7 @@ class TestValueFactory : Closeable { uriHost = uriHost, uriPort = uriPort, dns = dns, - socketFactory = SocketFactory.getDefault(), + socketFactory = Platform.get().socketFactory, sslSocketFactory = sslSocketFactory, hostnameVerifier = hostnameVerifier, certificatePinner = null, diff --git a/okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetworkPlatform.kt b/okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetworkPlatform.kt new file mode 100644 index 000000000000..f54b5d1c5dcd --- /dev/null +++ b/okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetworkPlatform.kt @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2026 OkHttp Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +@file:Suppress("Since15") + +package okhttp3.sockets + +import java.security.Provider +import java.security.SecureRandom +import javax.net.ServerSocketFactory +import javax.net.SocketFactory +import javax.net.ssl.KeyManager +import javax.net.ssl.SSLContext +import javax.net.ssl.SSLContextSpi +import javax.net.ssl.SSLSocket +import javax.net.ssl.SSLSocketFactory +import javax.net.ssl.TrustManager +import javax.net.ssl.X509KeyManager +import javax.net.ssl.X509TrustManager +import okhttp3.Protocol +import okhttp3.internal.platform.Platform +import okhttp3.tls.internal.TlsUtil.newKeyManager +import okio.ByteString + +class FakeNetworkPlatform : Platform() { + val network = FakeNetwork() + + override val socketFactory: SocketFactory + get() = network.socketFactory + + override val serverSocketFactory: ServerSocketFactory + get() = network.serverSocketFactory + + override fun newSSLContext(): SSLContext { + @Suppress("DEPRECATION") // Non-deprecated overload requires Java 9+. + val provider = + object : Provider("FakeNetwork", 0.0, "") { + } + return object : SSLContext(FakeSslContextSpi(), provider, "TLSv1.2") { + } + } + + override fun trustManager(sslSocketFactory: SSLSocketFactory) = null + + override fun configureTlsExtensions( + sslSocket: SSLSocket, + hostname: String?, + protocols: List<@JvmSuppressWildcards Protocol>, + echConfigList: ByteString?, + ) { + check(sslSocket is FakeSslSocket) + sslSocket.sslParameters.applicationProtocols = protocols.map { it.toString() }.toTypedArray() + sslSocket.echConfigList = echConfigList + } + + override fun afterHandshake(sslSocket: SSLSocket) { + } + + override fun getSelectedProtocol(sslSocket: SSLSocket): String? = sslSocket.applicationProtocol + + override fun getHandshakeServerNames(sslSocket: SSLSocket): List { + val serverNames = sslSocket.sslParameters.serverNames ?: return listOf() + return serverNames.map { it.encoded.decodeToString() } + } + + override fun newSslSocketFactory(trustManager: X509TrustManager): SSLSocketFactory { + val sslContext = newSSLContext() + sslContext.init( + arrayOf(newKeyManager(null, null)), + arrayOf(trustManager), + SecureRandom(), + ) + return sslContext.socketFactory + } + + private class FakeSslContextSpi : SSLContextSpi() { + private var fakeTls: FakeTls? = null + + override fun engineInit( + keyManagers: Array, + trustManagers: Array, + secureRandom: SecureRandom, + ) { + check(this.fakeTls == null) { "already initialized" } + fakeTls = + FakeTls( + handshaker = InsecureHandshaker(), + keyManager = keyManagers.filterIsInstance().single(), + trustManager = trustManagers.filterIsInstance().single(), + ) + } + + override fun engineGetSocketFactory(): SSLSocketFactory { + val fakeTls = this.fakeTls ?: error("call init() first") + return fakeTls.sslSocketFactory + } + + override fun engineGetServerSocketFactory() = error("unsupported") + + override fun engineCreateSSLEngine() = error("unsupported") + + override fun engineCreateSSLEngine( + host: String, + port: Int, + ) = error("unsupported") + + override fun engineGetServerSessionContext() = error("unsupported") + + override fun engineGetClientSessionContext() = error("unsupported") + } +} diff --git a/okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt b/okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt index 2276bc5e2b22..8d49f9a3bbcf 100644 --- a/okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt +++ b/okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt @@ -60,7 +60,7 @@ internal class FakeSslSocket( } private var enableSessionCreation = true private var useClientMode = true - private var echConfigList: ByteString? = null + var echConfigList: ByteString? = null override fun getEnabledProtocols(): Array = sslParameters.protocols @@ -126,7 +126,7 @@ internal class FakeSslSocket( tlsVersions = tlsVersions, cipherSuites = cipherSuites, protocols = protocols, - handshakeCertificates = tls.handshakeCertificates, + keyManager = tls.keyManager, hostname = hostname, echConfigList = echConfigList, ) @@ -137,7 +137,7 @@ internal class FakeSslSocket( tlsVersions = tlsVersions, cipherSuites = cipherSuites, protocols = protocols, - handshakeCertificates = tls.handshakeCertificates, + keyManager = tls.keyManager, clientAuth = when { sslParameters.needClientAuth -> Handshaker.ClientAuth.Required diff --git a/okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeTls.kt b/okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeTls.kt index bba0da254459..97943fe1b547 100644 --- a/okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeTls.kt +++ b/okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeTls.kt @@ -19,6 +19,7 @@ import java.io.InputStream import java.net.InetAddress import java.net.Socket import javax.net.ssl.SSLSocketFactory +import javax.net.ssl.X509KeyManager import javax.net.ssl.X509TrustManager import okhttp3.CipherSuite import okhttp3.TlsVersion @@ -36,7 +37,8 @@ import okhttp3.tls.HandshakeCertificates */ class FakeTls( val handshaker: Handshaker, - val handshakeCertificates: HandshakeCertificates, + val keyManager: X509KeyManager, + val trustManager: X509TrustManager, val supportedTlsVersions: List = listOf( TlsVersion.TLS_1_3, @@ -50,8 +52,14 @@ class FakeTls( ), val defaultCipherSuites: List = supportedCipherSuites, ) { - val trustManager: X509TrustManager - get() = handshakeCertificates.trustManager + constructor( + handshaker: Handshaker, + handshakeCertificates: HandshakeCertificates, + ) : this( + handshaker = handshaker, + keyManager = handshakeCertificates.keyManager, + trustManager = handshakeCertificates.trustManager, + ) val sslSocketFactory = object : SSLSocketFactory() { diff --git a/okhttp-testing-support/src/main/kotlin/okhttp3/sockets/Handshaker.kt b/okhttp-testing-support/src/main/kotlin/okhttp3/sockets/Handshaker.kt index a0f832f0c3ef..5ef109842566 100644 --- a/okhttp-testing-support/src/main/kotlin/okhttp3/sockets/Handshaker.kt +++ b/okhttp-testing-support/src/main/kotlin/okhttp3/sockets/Handshaker.kt @@ -16,11 +16,11 @@ package okhttp3.sockets import java.io.IOException +import javax.net.ssl.X509KeyManager import okhttp3.CipherSuite import okhttp3.Handshake import okhttp3.Protocol import okhttp3.TlsVersion -import okhttp3.tls.HandshakeCertificates import okio.ByteString import okio.Socket @@ -48,14 +48,14 @@ interface Handshaker { val tlsVersions: List val cipherSuites: List val protocols: List? - val handshakeCertificates: HandshakeCertificates + val keyManager: X509KeyManager } class ClientInputs( override val tlsVersions: List, override val cipherSuites: List, override val protocols: List?, - override val handshakeCertificates: HandshakeCertificates, + override val keyManager: X509KeyManager, val hostname: String?, val echConfigList: ByteString?, ) : Inputs @@ -64,7 +64,7 @@ interface Handshaker { override val tlsVersions: List, override val cipherSuites: List, override val protocols: List?, - override val handshakeCertificates: HandshakeCertificates, + override val keyManager: X509KeyManager, val clientAuth: ClientAuth, ) : Inputs diff --git a/okhttp-testing-support/src/main/kotlin/okhttp3/sockets/InsecureHandshaker.kt b/okhttp-testing-support/src/main/kotlin/okhttp3/sockets/InsecureHandshaker.kt index c9211ef615f1..67a9a3fe1a55 100644 --- a/okhttp-testing-support/src/main/kotlin/okhttp3/sockets/InsecureHandshaker.kt +++ b/okhttp-testing-support/src/main/kotlin/okhttp3/sockets/InsecureHandshaker.kt @@ -47,12 +47,12 @@ class InsecureHandshaker : Handshaker { val clientCertificates = when (server.clientAuth) { Handshaker.ClientAuth.Required -> { - client.handshakeCertificates.keyManager.clientCertificatesOrNull(keyType) + client.keyManager.clientCertificatesOrNull(keyType) ?: throw SSLHandshakeException("required client certificates not sent") } Handshaker.ClientAuth.Requested -> { - client.handshakeCertificates.keyManager.clientCertificatesOrNull(keyType) + client.keyManager.clientCertificatesOrNull(keyType) ?: listOf() } @@ -61,7 +61,7 @@ class InsecureHandshaker : Handshaker { } } - val serverCertificates = server.handshakeCertificates.keyManager.serverCertificates(keyType) + val serverCertificates = server.keyManager.serverCertificates(keyType) val (clientSocket, serverSocket) = inMemorySocketPair(maxBufferSize = 1024 * 1024) diff --git a/okhttp-tls/src/test/java/okhttp3/tls/HandshakeCertificatesTest.kt b/okhttp-tls/src/test/java/okhttp3/tls/HandshakeCertificatesTest.kt index 658d0954f6cd..050c25002b80 100644 --- a/okhttp-tls/src/test/java/okhttp3/tls/HandshakeCertificatesTest.kt +++ b/okhttp-tls/src/test/java/okhttp3/tls/HandshakeCertificatesTest.kt @@ -25,13 +25,12 @@ import java.security.PrivateKey import java.util.concurrent.ExecutorService import java.util.concurrent.Executors import java.util.concurrent.Future -import javax.net.ServerSocketFactory -import javax.net.SocketFactory import javax.net.ssl.SSLSocket import okhttp3.Handshake import okhttp3.Handshake.Companion.handshake import okhttp3.TestUtil.threadFactory import okhttp3.internal.closeQuietly +import okhttp3.internal.platform.Platform import okhttp3.testing.PlatformRule import okio.ByteString.Companion.toByteString import org.junit.jupiter.api.AfterEach @@ -180,7 +179,7 @@ class HandshakeCertificatesTest { } private fun startTlsServer(): InetSocketAddress { - val serverSocketFactory = ServerSocketFactory.getDefault() + val serverSocketFactory = Platform.get().serverSocketFactory serverSocket = serverSocketFactory.createServerSocket() val serverAddress = InetAddress.getByName("localhost") serverSocket!!.bind(InetSocketAddress(serverAddress, 0), 50) @@ -212,7 +211,7 @@ class HandshakeCertificatesTest { serverAddress: InetSocketAddress, ): Future { return executorService.submit { - SocketFactory.getDefault().createSocket().use { rawSocket -> + Platform.get().socketFactory.createSocket().use { rawSocket -> rawSocket.connect(serverAddress) val sslSocket = client.sslSocketFactory().createSocket( diff --git a/okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt b/okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt index c4076307e52a..5eb289a653c5 100644 --- a/okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt +++ b/okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt @@ -704,10 +704,10 @@ class Cache internal constructor( companion object { /** Synthetic response header: the local time when the request was sent. */ - private val SENT_MILLIS = "${Platform.get().getPrefix()}-Sent-Millis" + private val SENT_MILLIS = "${Platform.get().prefix}-Sent-Millis" /** Synthetic response header: the local time when the response was received. */ - private val RECEIVED_MILLIS = "${Platform.get().getPrefix()}-Received-Millis" + private val RECEIVED_MILLIS = "${Platform.get().prefix}-Received-Millis" } } diff --git a/okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt b/okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt index ff478913b0d2..3a8f65c705d1 100644 --- a/okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt +++ b/okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt @@ -601,7 +601,7 @@ open class OkHttpClient internal constructor( internal var proxy: Proxy? = null internal var proxySelector: ProxySelector? = null internal var proxyAuthenticator: Authenticator = Authenticator.NONE - internal var socketFactory: SocketFactory = SocketFactory.getDefault() + internal var socketFactory: SocketFactory = Platform.get().socketFactory internal var sslSocketFactoryOrNull: SSLSocketFactory? = null internal var x509TrustManagerOrNull: X509TrustManager? = null internal var connectionSpecs: List = DEFAULT_CONNECTION_SPECS diff --git a/okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/platform/Platform.kt b/okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/platform/Platform.kt index 3633ab55801d..58eeeed2421c 100644 --- a/okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/platform/Platform.kt +++ b/okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/platform/Platform.kt @@ -23,6 +23,8 @@ import java.security.GeneralSecurityException import java.security.KeyStore import java.util.logging.Level import java.util.logging.Logger +import javax.net.ServerSocketFactory +import javax.net.SocketFactory import javax.net.ssl.ExtendedSSLSession import javax.net.ssl.SNIHostName import javax.net.ssl.SSLContext @@ -72,8 +74,15 @@ import org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement * Supported on Android 6.0+ via `NetworkSecurityPolicy`. */ open class Platform { + open val socketFactory: SocketFactory + get() = SocketFactory.getDefault() + + open val serverSocketFactory: ServerSocketFactory + get() = ServerSocketFactory.getDefault() + /** Prefix used on custom headers. */ - fun getPrefix() = "OkHttp" + val prefix: String + get() = "OkHttp" open fun newSSLContext(): SSLContext = SSLContext.getInstance("TLS") diff --git a/okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt b/okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt index fdb6fe1e2b85..a2b5087d3578 100644 --- a/okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt +++ b/okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt @@ -50,7 +50,7 @@ import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.internal.addHeaderLenient import okhttp3.internal.cacheGet -import okhttp3.internal.platform.Platform.Companion.get +import okhttp3.internal.platform.Platform import okhttp3.java.net.cookiejar.JavaNetCookieJar import okhttp3.testing.PlatformRule import okio.Buffer @@ -352,20 +352,20 @@ class CacheTest { // OpenJDK 6 fails on this line, complaining that the connection isn't open yet val cipherSuite = response1.handshake!!.cipherSuite - val localCerts = response1.handshake!!.localCertificates - val serverCerts = response1.handshake!!.peerCertificates - val peerPrincipal = response1.handshake!!.peerPrincipal - val localPrincipal = response1.handshake!!.localPrincipal + val localCerts = response1.handshake.localCertificates + val serverCerts = response1.handshake.peerCertificates + val peerPrincipal = response1.handshake.peerPrincipal + val localPrincipal = response1.handshake.localPrincipal val response2 = client.newCall(request).execute() // Cached! assertThat(response2.body.string()).isEqualTo("ABC") assertThat(cache.requestCount()).isEqualTo(2) assertThat(cache.networkCount()).isEqualTo(1) assertThat(cache.hitCount()).isEqualTo(1) assertThat(response2.handshake!!.cipherSuite).isEqualTo(cipherSuite) - assertThat(response2.handshake!!.localCertificates).isEqualTo(localCerts) - assertThat(response2.handshake!!.peerCertificates).isEqualTo(serverCerts) - assertThat(response2.handshake!!.peerPrincipal).isEqualTo(peerPrincipal) - assertThat(response2.handshake!!.localPrincipal).isEqualTo(localPrincipal) + assertThat(response2.handshake.localCertificates).isEqualTo(localCerts) + assertThat(response2.handshake.peerCertificates).isEqualTo(serverCerts) + assertThat(response2.handshake.peerPrincipal).isEqualTo(peerPrincipal) + assertThat(response2.handshake.localPrincipal).isEqualTo(localPrincipal) } @Test @@ -798,7 +798,7 @@ class CacheTest { override fun contentType(): MediaType? = "application/text-plain".toMediaTypeOrNull() override fun writeTo(sink: BufferedSink) { - internalBody.forEach { item -> + internalBody.forEach { _ -> sink.writeUtf8(this@toOneShotRequestBody) } } @@ -850,8 +850,8 @@ class CacheTest { // 2 direct + 2 redirect = 4 assertThat(cache.requestCount()).isEqualTo(4) assertThat(cache.hitCount()).isEqualTo(2) - assertThat(response2.handshake!!.cipherSuite).isEqualTo( - response1.handshake!!.cipherSuite, + assertThat(response2.handshake.cipherSuite).isEqualTo( + response1.handshake.cipherSuite, ) } @@ -3355,7 +3355,7 @@ CLEAN $urlKey ${entryMetadata.length} ${entryBody.length} val url = server.url("/") val urlKey = key(url) - val prefix = get().getPrefix() + val prefix = Platform.get().prefix val entryMetadata = """ $url @@ -3406,7 +3406,7 @@ CLEAN $urlKey ${entryMetadata.length} ${entryBody.length} val url = server.url("/") val urlKey = key(url) - val prefix = get().getPrefix() + val prefix = Platform.get().prefix val entryMetadata = """ |$url @@ -3461,7 +3461,7 @@ CLEAN $urlKey ${entryMetadata.length} ${entryBody.length} val url = server.url("/") val urlKey = key(url) - val prefix = get().getPrefix() + val prefix = Platform.get().prefix val entryMetadata = """ |$url @@ -3584,7 +3584,7 @@ CLEAN $urlKey ${entryMetadata.length} ${entryBody.length} client = client .newBuilder() - .addNetworkInterceptor(Interceptor { chain: Interceptor.Chain? -> throw AssertionError() }) + .addNetworkInterceptor(Interceptor { throw AssertionError() }) .build() assertThat(get(url).body.string()).isEqualTo("A") } @@ -4255,6 +4255,6 @@ CLEAN $urlKey ${entryMetadata.length} ${entryBody.length} } companion object { - private val NULL_HOSTNAME_VERIFIER = HostnameVerifier { hostname, session -> true } + private val NULL_HOSTNAME_VERIFIER = HostnameVerifier { _, _ -> true } } } diff --git a/okhttp/src/jvmTest/kotlin/okhttp3/FakeNetworkOkHttpTest.kt b/okhttp/src/jvmTest/kotlin/okhttp3/FakeNetworkOkHttpTest.kt index fed84f814a26..abef4163853c 100644 --- a/okhttp/src/jvmTest/kotlin/okhttp3/FakeNetworkOkHttpTest.kt +++ b/okhttp/src/jvmTest/kotlin/okhttp3/FakeNetworkOkHttpTest.kt @@ -20,46 +20,43 @@ import assertk.assertions.isEqualTo import assertk.assertions.isNull import mockwebserver3.MockResponse import mockwebserver3.MockWebServer -import mockwebserver3.junit5.StartStop -import okhttp3.sockets.FakeNetwork -import okhttp3.sockets.FakeTls -import okhttp3.sockets.InsecureHandshaker -import okhttp3.tls.internal.TlsUtil +import okhttp3.sockets.FakeNetworkPlatform +import okhttp3.testing.PlatformRule +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.RegisterExtension open class FakeNetworkOkHttpTest { - private val network = FakeNetwork() + private val platform = FakeNetworkPlatform() - private val handshaker = InsecureHandshaker() - - private val clientTls = - FakeTls( - handshaker = handshaker, - handshakeCertificates = TlsUtil.localhost(), - ) - - private val serverTls = - FakeTls( - handshaker = handshaker, - handshakeCertificates = TlsUtil.localhost(), + @RegisterExtension + val platformRule = + PlatformRule( + platform = platform, ) @RegisterExtension val clientTestRule = OkHttpClientTestRule() - @StartStop - private val server = - MockWebServer() - .apply { - serverSocketFactory = network.serverSocketFactory - } + private val handshakeCertificates = platformRule.localhostHandshakeCertificates() + + // We can't create these until after platformRule runs. Sigh. + private lateinit var server: MockWebServer + private lateinit var client: OkHttpClient - private var client = - clientTestRule - .newClientBuilder() - .socketFactory(network.socketFactory) - .build() + @BeforeEach + fun setUp() { + server = MockWebServer() + client = clientTestRule.newClient() + + server.start() + } + + @AfterEach + fun tearDown() { + server.close() + } @Test fun `happy path`() { @@ -100,8 +97,10 @@ open class FakeNetworkOkHttpTest { client = client .newBuilder() - .sslSocketFactory(clientTls.sslSocketFactory, clientTls.trustManager) - .build() - server.useHttps(serverTls.sslSocketFactory) + .sslSocketFactory( + handshakeCertificates.sslSocketFactory(), + handshakeCertificates.trustManager, + ).build() + server.useHttps(handshakeCertificates.sslSocketFactory()) } } diff --git a/okhttp/src/jvmTest/kotlin/okhttp3/FastFallbackTest.kt b/okhttp/src/jvmTest/kotlin/okhttp3/FastFallbackTest.kt index fb234a7f1ace..ecfe02ea2c35 100644 --- a/okhttp/src/jvmTest/kotlin/okhttp3/FastFallbackTest.kt +++ b/okhttp/src/jvmTest/kotlin/okhttp3/FastFallbackTest.kt @@ -26,7 +26,6 @@ import java.net.InetAddress import java.net.Socket import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit -import javax.net.SocketFactory import kotlin.test.assertFailsWith import mockwebserver3.MockResponse import mockwebserver3.MockWebServer @@ -35,6 +34,7 @@ import okhttp3.CallEvent.ConnectEnd import okhttp3.CallEvent.ConnectFailed import okhttp3.CallEvent.ConnectStart import okhttp3.internal.http2.ErrorCode +import okhttp3.internal.platform.Platform import okhttp3.sockets.DelegatingSocketFactory import okhttp3.testing.Flaky import org.junit.jupiter.api.AfterEach @@ -284,7 +284,7 @@ class FastFallbackTest { // Yield the first IP address so the second IP address completes first. val firstConnectLatch = CountDownLatch(1) val socketFactory = - object : DelegatingSocketFactory(SocketFactory.getDefault()) { + object : DelegatingSocketFactory(Platform.get().socketFactory) { var first = true override fun createSocket(): Socket { diff --git a/okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt b/okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt index 6cbb38820c15..757a03d468cc 100644 --- a/okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt +++ b/okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt @@ -530,7 +530,7 @@ class InterceptorOverridesTest { override fun configureSocket(socket: Socket): Socket = TODO() } - override fun isDefaultValue(value: SocketFactory): Boolean = value === SocketFactory.getDefault() + override fun isDefaultValue(value: SocketFactory): Boolean = value === Platform.get().socketFactory } object AuthenticatorOverride : Override { diff --git a/okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt b/okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt index 576a9a8918ea..783b8f0beb45 100644 --- a/okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt +++ b/okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt @@ -85,7 +85,7 @@ import okhttp3.internal.addHeaderLenient import okhttp3.internal.authenticator.JavaNetAuthenticator import okhttp3.internal.http.HTTP_PERM_REDIRECT import okhttp3.internal.http.HTTP_TEMP_REDIRECT -import okhttp3.internal.platform.Platform.Companion.get +import okhttp3.internal.platform.Platform import okhttp3.java.net.cookiejar.JavaNetCookieJar import okhttp3.sockets.DelegatingServerSocketFactory import okhttp3.sockets.DelegatingSocketFactory @@ -624,7 +624,7 @@ class URLConnectionTest { .build() val response1 = getResponse(newRequest("/")) assertContent("this response comes via HTTPS", response1) - val sslContext2 = get().newSSLContext() + val sslContext2 = Platform.get().newSSLContext() sslContext2.init(null, null, null) val sslSocketFactory2 = sslContext2.socketFactory val trustManagerFactory = @@ -888,7 +888,7 @@ class URLConnectionTest { client = client .newBuilder() - .socketFactory(SocketFactory.getDefault()) + .socketFactory(Platform.get().socketFactory) .build() val response = getResponse(newRequest("/")) assertThat(response.code).isEqualTo(200) @@ -2948,7 +2948,7 @@ class URLConnectionTest { fun httpsWithCustomTrustManager() { val hostnameVerifier = RecordingHostnameVerifier() val trustManager = RecordingTrustManager(handshakeCertificates.trustManager) - val sslContext = get().newSSLContext() + val sslContext = Platform.get().newSSLContext() sslContext.init(null, arrayOf(trustManager), null) client = client @@ -3541,7 +3541,7 @@ class URLConnectionTest { ) assertContent("B", response) break - } catch (socketException: IOException) { + } catch (_: IOException) { // If there's a socket exception, this must have a streamed request body. assertThat(j).isEqualTo(0) assertThat(transferKind).isIn(TransferKind.CHUNKED, TransferKind.FIXED_LENGTH) @@ -4257,7 +4257,7 @@ class URLConnectionTest { client = client .newBuilder() - .dns { hostname: String? -> throw RuntimeException("boom!") } + .dns { throw RuntimeException("boom!") } .build() server.enqueue(MockResponse()) assertFailsWith { diff --git a/okhttp/src/jvmTest/kotlin/okhttp3/internal/http/CancelTest.kt b/okhttp/src/jvmTest/kotlin/okhttp3/internal/http/CancelTest.kt index d4a9f8fd3a5b..c888ce2c2d9a 100644 --- a/okhttp/src/jvmTest/kotlin/okhttp3/internal/http/CancelTest.kt +++ b/okhttp/src/jvmTest/kotlin/okhttp3/internal/http/CancelTest.kt @@ -27,8 +27,6 @@ import java.net.ServerSocket import java.net.Socket import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit.MILLISECONDS -import javax.net.ServerSocketFactory -import javax.net.SocketFactory import kotlin.test.assertFailsWith import mockwebserver3.MockResponse import mockwebserver3.MockWebServer @@ -56,6 +54,7 @@ import okhttp3.internal.http.CancelTest.CancelMode.INTERRUPT import okhttp3.internal.http.CancelTest.ConnectionType.H2 import okhttp3.internal.http.CancelTest.ConnectionType.HTTP import okhttp3.internal.http.CancelTest.ConnectionType.HTTPS +import okhttp3.internal.platform.Platform import okhttp3.sockets.DelegatingServerSocketFactory import okhttp3.sockets.DelegatingSocketFactory import okhttp3.testing.PlatformRule @@ -111,7 +110,7 @@ class CancelTest( // required. These socket factories explicitly set the buffer sizes on sockets created. server = MockWebServer() server.serverSocketFactory = - object : DelegatingServerSocketFactory(ServerSocketFactory.getDefault()) { + object : DelegatingServerSocketFactory(Platform.get().serverSocketFactory) { @Throws(IOException::class) override fun configureServerSocket(serverSocket: ServerSocket): ServerSocket { serverSocket.receiveBufferSize = SOCKET_BUFFER_SIZE @@ -127,7 +126,7 @@ class CancelTest( clientTestRule .newClientBuilder() .socketFactory( - object : DelegatingSocketFactory(SocketFactory.getDefault()) { + object : DelegatingSocketFactory(Platform.get().socketFactory) { @Throws(IOException::class) override fun configureSocket(socket: Socket): Socket { socket.sendBufferSize = SOCKET_BUFFER_SIZE diff --git a/okhttp/src/jvmTest/kotlin/okhttp3/internal/platform/PlatformTest.kt b/okhttp/src/jvmTest/kotlin/okhttp3/internal/platform/PlatformTest.kt index 6a88ea4a8ba4..477409285ee6 100644 --- a/okhttp/src/jvmTest/kotlin/okhttp3/internal/platform/PlatformTest.kt +++ b/okhttp/src/jvmTest/kotlin/okhttp3/internal/platform/PlatformTest.kt @@ -34,7 +34,7 @@ class PlatformTest { /** Guard against the default value changing by accident. */ @Test fun defaultPrefix() { - assertThat(Platform().getPrefix()).isEqualTo("OkHttp") + assertThat(Platform().prefix).isEqualTo("OkHttp") } @Test