1
0
mirror of https://github.com/square/okhttp.git synced 2025-08-08 23:42:08 +03:00

Rename TlsNode to HandshakeCertificates (#4141)

This commit is contained in:
Jesse Wilson
2018-07-12 01:39:20 -04:00
committed by Yuri Schimke
parent b0ac074437
commit 37887141fe
28 changed files with 365 additions and 331 deletions

View File

@@ -20,7 +20,7 @@ import java.io.InputStream;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.zip.GZIPInputStream; import java.util.zip.GZIPInputStream;
import okhttp3.HttpUrl; import okhttp3.HttpUrl;
import okhttp3.tls.TlsNode; import okhttp3.tls.HandshakeCertificates;
import org.apache.http.Header; import org.apache.http.Header;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient; import org.apache.http.client.HttpClient;
@@ -43,9 +43,9 @@ class ApacheHttpClient extends SynchronousHttpClient {
super.prepare(benchmark); super.prepare(benchmark);
ClientConnectionManager connectionManager = new PoolingClientConnectionManager(); ClientConnectionManager connectionManager = new PoolingClientConnectionManager();
if (benchmark.tls) { if (benchmark.tls) {
TlsNode tlsNode = localhost(); HandshakeCertificates handshakeCertificates = localhost();
connectionManager.getSchemeRegistry().register( connectionManager.getSchemeRegistry().register(
new Scheme("https", 443, new SSLSocketFactory(tlsNode.sslContext()))); new Scheme("https", 443, new SSLSocketFactory(handshakeCertificates.sslContext())));
} }
client = new DefaultHttpClient(connectionManager); client = new DefaultHttpClient(connectionManager);
} }

View File

@@ -32,7 +32,7 @@ import okhttp3.mockwebserver.Dispatcher;
import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest; import okhttp3.mockwebserver.RecordedRequest;
import okhttp3.tls.TlsNode; import okhttp3.tls.HandshakeCertificates;
import okio.Buffer; import okio.Buffer;
import okio.GzipSink; import okio.GzipSink;
@@ -162,8 +162,8 @@ public class Benchmark extends com.google.caliper.Benchmark {
MockWebServer server = new MockWebServer(); MockWebServer server = new MockWebServer();
if (tls) { if (tls) {
TlsNode tlsNode = localhost(); HandshakeCertificates handshakeCertificates = localhost();
server.useHttps(tlsNode.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
server.setProtocols(protocols); server.setProtocols(protocols);
} }

View File

@@ -44,7 +44,7 @@ import java.util.Deque;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLEngine;
import okhttp3.HttpUrl; import okhttp3.HttpUrl;
import okhttp3.tls.TlsNode; import okhttp3.tls.HandshakeCertificates;
import static okhttp3.tls.internal.TlsUtil.localhost; import static okhttp3.tls.internal.TlsUtil.localhost;
@@ -66,12 +66,12 @@ class NettyHttpClient implements HttpClient {
this.targetBacklog = benchmark.targetBacklog; this.targetBacklog = benchmark.targetBacklog;
ChannelInitializer<SocketChannel> channelInitializer = new ChannelInitializer<SocketChannel>() { ChannelInitializer<SocketChannel> channelInitializer = new ChannelInitializer<SocketChannel>() {
@Override public void initChannel(SocketChannel channel) throws Exception { @Override public void initChannel(SocketChannel channel) {
ChannelPipeline pipeline = channel.pipeline(); ChannelPipeline pipeline = channel.pipeline();
if (benchmark.tls) { if (benchmark.tls) {
TlsNode tlsNode = localhost(); HandshakeCertificates handshakeCertificates = localhost();
SSLEngine engine = tlsNode.sslContext().createSSLEngine(); SSLEngine engine = handshakeCertificates.sslContext().createSSLEngine();
engine.setUseClientMode(true); engine.setUseClientMode(true);
pipeline.addLast("ssl", new SslHandler(engine)); pipeline.addLast("ssl", new SslHandler(engine));
} }
@@ -154,7 +154,7 @@ class NettyHttpClient implements HttpClient {
} }
@Override protected void channelRead0( @Override protected void channelRead0(
ChannelHandlerContext context, HttpObject message) throws Exception { ChannelHandlerContext context, HttpObject message) {
if (message instanceof HttpResponse) { if (message instanceof HttpResponse) {
receive((HttpResponse) message); receive((HttpResponse) message);
} }

View File

@@ -25,7 +25,7 @@ import okhttp3.HttpUrl;
import okhttp3.OkHttpClient; import okhttp3.OkHttpClient;
import okhttp3.Request; import okhttp3.Request;
import okhttp3.ResponseBody; import okhttp3.ResponseBody;
import okhttp3.tls.TlsNode; import okhttp3.tls.HandshakeCertificates;
import static okhttp3.tls.internal.TlsUtil.localhost; import static okhttp3.tls.internal.TlsUtil.localhost;
@@ -41,15 +41,15 @@ class OkHttp extends SynchronousHttpClient {
.build(); .build();
if (benchmark.tls) { if (benchmark.tls) {
TlsNode tlsNode = localhost(); HandshakeCertificates handshakeCertificates = localhost();
SSLSocketFactory socketFactory = tlsNode.sslSocketFactory(); SSLSocketFactory socketFactory = handshakeCertificates.sslSocketFactory();
HostnameVerifier hostnameVerifier = new HostnameVerifier() { HostnameVerifier hostnameVerifier = new HostnameVerifier() {
@Override public boolean verify(String s, SSLSession session) { @Override public boolean verify(String s, SSLSession session) {
return true; return true;
} }
}; };
client = new OkHttpClient.Builder() client = new OkHttpClient.Builder()
.sslSocketFactory(socketFactory, tlsNode.trustManager()) .sslSocketFactory(socketFactory, handshakeCertificates.trustManager())
.hostnameVerifier(hostnameVerifier) .hostnameVerifier(hostnameVerifier)
.build(); .build();
} }

View File

@@ -31,7 +31,7 @@ import okhttp3.OkHttpClient;
import okhttp3.Request; import okhttp3.Request;
import okhttp3.Response; import okhttp3.Response;
import okhttp3.ResponseBody; import okhttp3.ResponseBody;
import okhttp3.tls.TlsNode; import okhttp3.tls.HandshakeCertificates;
import static okhttp3.tls.internal.TlsUtil.localhost; import static okhttp3.tls.internal.TlsUtil.localhost;
@@ -56,15 +56,15 @@ class OkHttpAsync implements HttpClient {
.build(); .build();
if (benchmark.tls) { if (benchmark.tls) {
TlsNode tlsNode = localhost(); HandshakeCertificates handshakeCertificates = localhost();
SSLSocketFactory socketFactory = tlsNode.sslSocketFactory(); SSLSocketFactory socketFactory = handshakeCertificates.sslSocketFactory();
HostnameVerifier hostnameVerifier = new HostnameVerifier() { HostnameVerifier hostnameVerifier = new HostnameVerifier() {
@Override public boolean verify(String s, SSLSession session) { @Override public boolean verify(String s, SSLSession session) {
return true; return true;
} }
}; };
client = client.newBuilder() client = client.newBuilder()
.sslSocketFactory(socketFactory, tlsNode.trustManager()) .sslSocketFactory(socketFactory, handshakeCertificates.trustManager())
.hostnameVerifier(hostnameVerifier) .hostnameVerifier(hostnameVerifier)
.build(); .build();
} }

View File

@@ -25,7 +25,7 @@ import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.SSLSocketFactory;
import okhttp3.HttpUrl; import okhttp3.HttpUrl;
import okhttp3.tls.TlsNode; import okhttp3.tls.HandshakeCertificates;
import static okhttp3.tls.internal.TlsUtil.localhost; import static okhttp3.tls.internal.TlsUtil.localhost;
@@ -35,8 +35,8 @@ class UrlConnection extends SynchronousHttpClient {
@Override public void prepare(Benchmark benchmark) { @Override public void prepare(Benchmark benchmark) {
super.prepare(benchmark); super.prepare(benchmark);
if (benchmark.tls) { if (benchmark.tls) {
TlsNode tlsNode = localhost(); HandshakeCertificates handshakeCertificates = localhost();
SSLSocketFactory socketFactory = tlsNode.sslSocketFactory(); SSLSocketFactory socketFactory = handshakeCertificates.sslSocketFactory();
HostnameVerifier hostnameVerifier = new HostnameVerifier() { HostnameVerifier hostnameVerifier = new HostnameVerifier() {
@Override public boolean verify(String s, SSLSession session) { @Override public boolean verify(String s, SSLSession session) {
return true; return true;

View File

@@ -41,7 +41,7 @@ import okhttp3.Protocol;
import okhttp3.RecordingHostnameVerifier; import okhttp3.RecordingHostnameVerifier;
import okhttp3.internal.Util; import okhttp3.internal.Util;
import okhttp3.tls.HeldCertificate; import okhttp3.tls.HeldCertificate;
import okhttp3.tls.TlsNode; import okhttp3.tls.HandshakeCertificates;
import org.junit.After; import org.junit.After;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
@@ -498,13 +498,13 @@ public final class MockWebServerTest {
} }
@Test public void https() throws Exception { @Test public void https() throws Exception {
TlsNode tlsNode = localhost(); HandshakeCertificates handshakeCertificates = localhost();
server.useHttps(tlsNode.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
server.enqueue(new MockResponse().setBody("abc")); server.enqueue(new MockResponse().setBody("abc"));
HttpUrl url = server.url("/"); HttpUrl url = server.url("/");
HttpsURLConnection connection = (HttpsURLConnection) url.url().openConnection(); HttpsURLConnection connection = (HttpsURLConnection) url.url().openConnection();
connection.setSSLSocketFactory(tlsNode.sslSocketFactory()); connection.setSSLSocketFactory(handshakeCertificates.sslSocketFactory());
connection.setHostnameVerifier(new RecordingHostnameVerifier()); connection.setHostnameVerifier(new RecordingHostnameVerifier());
assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode()); assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode());
@@ -533,26 +533,26 @@ public final class MockWebServerTest {
.issuedBy(serverCa) .issuedBy(serverCa)
.addSubjectAlternativeName(server.getHostName()) .addSubjectAlternativeName(server.getHostName())
.build(); .build();
TlsNode serverTlsNode = new TlsNode.Builder() HandshakeCertificates serverHandshakeCertificates = new HandshakeCertificates.Builder()
.addTrustedCertificate(clientCa.certificate()) .addTrustedCertificate(clientCa.certificate())
.heldCertificate(serverCertificate) .heldCertificate(serverCertificate)
.build(); .build();
server.useHttps(serverTlsNode.sslSocketFactory(), false); server.useHttps(serverHandshakeCertificates.sslSocketFactory(), false);
server.enqueue(new MockResponse().setBody("abc")); server.enqueue(new MockResponse().setBody("abc"));
server.requestClientAuth(); server.requestClientAuth();
HeldCertificate clientCertificate = new HeldCertificate.Builder() HeldCertificate clientCertificate = new HeldCertificate.Builder()
.issuedBy(clientCa) .issuedBy(clientCa)
.build(); .build();
TlsNode clientTlsNode = new TlsNode.Builder() HandshakeCertificates clientHandshakeCertificates = new HandshakeCertificates.Builder()
.addTrustedCertificate(serverCa.certificate()) .addTrustedCertificate(serverCa.certificate())
.heldCertificate(clientCertificate) .heldCertificate(clientCertificate)
.build(); .build();
HttpUrl url = server.url("/"); HttpUrl url = server.url("/");
HttpsURLConnection connection = (HttpsURLConnection) url.url().openConnection(); HttpsURLConnection connection = (HttpsURLConnection) url.url().openConnection();
connection.setSSLSocketFactory(clientTlsNode.sslSocketFactory()); connection.setSSLSocketFactory(clientHandshakeCertificates.sslSocketFactory());
connection.setHostnameVerifier(new RecordingHostnameVerifier()); connection.setHostnameVerifier(new RecordingHostnameVerifier());
assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode()); assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode());

View File

@@ -37,7 +37,7 @@ import okhttp3.internal.Internal;
import okhttp3.internal.cache.InternalCache; import okhttp3.internal.cache.InternalCache;
import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.MockWebServer;
import okhttp3.tls.TlsNode; import okhttp3.tls.HandshakeCertificates;
import okio.Buffer; import okio.Buffer;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
@@ -59,7 +59,7 @@ import static org.junit.Assert.assertTrue;
* </ul> * </ul>
*/ */
public class CacheAdapterTest { public class CacheAdapterTest {
private TlsNode tlsNode = localhost(); private HandshakeCertificates handshakeCertificates = localhost();
private HostnameVerifier hostnameVerifier = new RecordingHostnameVerifier(); private HostnameVerifier hostnameVerifier = new RecordingHostnameVerifier();
private MockWebServer server; private MockWebServer server;
private OkHttpClient client; private OkHttpClient client;
@@ -124,7 +124,8 @@ public class CacheAdapterTest {
}; };
setInternalCache(new CacheAdapter(responseCache)); setInternalCache(new CacheAdapter(responseCache));
client = client.newBuilder() client = client.newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(hostnameVerifier) .hostnameVerifier(hostnameVerifier)
.build(); .build();
@@ -254,7 +255,8 @@ public class CacheAdapterTest {
}; };
setInternalCache(new CacheAdapter(responseCache)); setInternalCache(new CacheAdapter(responseCache));
client = client.newBuilder() client = client.newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(hostnameVerifier) .hostnameVerifier(hostnameVerifier)
.build(); .build();
@@ -282,7 +284,7 @@ public class CacheAdapterTest {
} }
private URL configureHttpsServer(MockResponse mockResponse) throws Exception { private URL configureHttpsServer(MockResponse mockResponse) throws Exception {
server.useHttps(tlsNode.sslSocketFactory(), false /* tunnelProxy */); server.useHttps(handshakeCertificates.sslSocketFactory(), false /* tunnelProxy */);
server.enqueue(mockResponse); server.enqueue(mockResponse);
server.start(); server.start();
return server.url("/").url(); return server.url("/").url();

View File

@@ -26,13 +26,11 @@ import java.io.OutputStream;
import java.net.CacheRequest; import java.net.CacheRequest;
import java.net.CacheResponse; import java.net.CacheResponse;
import java.net.CookieManager; import java.net.CookieManager;
import java.net.HttpCookie;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.ProtocolException; import java.net.ProtocolException;
import java.net.ResponseCache; import java.net.ResponseCache;
import java.net.SecureCacheResponse; import java.net.SecureCacheResponse;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL; import java.net.URL;
import java.net.URLConnection; import java.net.URLConnection;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
@@ -40,7 +38,6 @@ import java.security.Principal;
import java.security.cert.Certificate; import java.security.cert.Certificate;
import java.text.DateFormat; import java.text.DateFormat;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Date; import java.util.Date;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
@@ -67,7 +64,7 @@ import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest; import okhttp3.mockwebserver.RecordedRequest;
import okhttp3.mockwebserver.SocketPolicy; import okhttp3.mockwebserver.SocketPolicy;
import okhttp3.tls.TlsNode; import okhttp3.tls.HandshakeCertificates;
import okio.Buffer; import okio.Buffer;
import okio.BufferedSink; import okio.BufferedSink;
import okio.GzipSink; import okio.GzipSink;
@@ -97,7 +94,7 @@ public final class ResponseCacheTest {
@Rule public MockWebServer server2 = new MockWebServer(); @Rule public MockWebServer server2 = new MockWebServer();
private HostnameVerifier hostnameVerifier = new RecordingHostnameVerifier(); private HostnameVerifier hostnameVerifier = new RecordingHostnameVerifier();
private TlsNode tlsNode = localhost(); private HandshakeCertificates handshakeCertificates = localhost();
private ResponseCache cache; private ResponseCache cache;
private CookieManager cookieManager; private CookieManager cookieManager;
private OkUrlFactory urlFactory; private OkUrlFactory urlFactory;
@@ -112,7 +109,7 @@ public final class ResponseCacheTest {
cookieManager = new CookieManager(); cookieManager = new CookieManager();
} }
@After public void tearDown() throws Exception { @After public void tearDown() {
ResponseCache.setDefault(null); ResponseCache.setDefault(null);
} }
@@ -273,14 +270,14 @@ public final class ResponseCacheTest {
@Test public void secureResponseCaching() throws IOException { @Test public void secureResponseCaching() throws IOException {
assumeFalse(getPlatform().equals("jdk9")); assumeFalse(getPlatform().equals("jdk9"));
server.useHttps(tlsNode.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
server.enqueue(new MockResponse() server.enqueue(new MockResponse()
.addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
.addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS))
.setBody("ABC")); .setBody("ABC"));
HttpsURLConnection c1 = (HttpsURLConnection) openConnection(server.url("/").url()); HttpsURLConnection c1 = (HttpsURLConnection) openConnection(server.url("/").url());
c1.setSSLSocketFactory(tlsNode.sslSocketFactory()); c1.setSSLSocketFactory(handshakeCertificates.sslSocketFactory());
c1.setHostnameVerifier(hostnameVerifier); c1.setHostnameVerifier(hostnameVerifier);
assertEquals("ABC", readAscii(c1)); assertEquals("ABC", readAscii(c1));
@@ -292,7 +289,7 @@ public final class ResponseCacheTest {
Principal localPrincipal = c1.getLocalPrincipal(); Principal localPrincipal = c1.getLocalPrincipal();
HttpsURLConnection c2 = (HttpsURLConnection) openConnection(server.url("/").url()); // cached! HttpsURLConnection c2 = (HttpsURLConnection) openConnection(server.url("/").url()); // cached!
c2.setSSLSocketFactory(tlsNode.sslSocketFactory()); c2.setSSLSocketFactory(handshakeCertificates.sslSocketFactory());
c2.setHostnameVerifier(hostnameVerifier); c2.setHostnameVerifier(hostnameVerifier);
assertEquals("ABC", readAscii(c2)); assertEquals("ABC", readAscii(c2));
@@ -351,7 +348,7 @@ public final class ResponseCacheTest {
} }
@Test public void secureResponseCachingAndRedirects() throws IOException { @Test public void secureResponseCachingAndRedirects() throws IOException {
server.useHttps(tlsNode.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
server.enqueue(new MockResponse() server.enqueue(new MockResponse()
.addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
.addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS))
@@ -365,7 +362,8 @@ public final class ResponseCacheTest {
.setBody("DEF")); .setBody("DEF"));
urlFactory.setClient(urlFactory.client().newBuilder() urlFactory.setClient(urlFactory.client().newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(hostnameVerifier) .hostnameVerifier(hostnameVerifier)
.build()); .build());
@@ -389,7 +387,7 @@ public final class ResponseCacheTest {
* https://github.com/square/okhttp/issues/214 * https://github.com/square/okhttp/issues/214
*/ */
@Test public void secureResponseCachingAndProtocolRedirects() throws IOException { @Test public void secureResponseCachingAndProtocolRedirects() throws IOException {
server2.useHttps(tlsNode.sslSocketFactory(), false); server2.useHttps(handshakeCertificates.sslSocketFactory(), false);
server2.enqueue(new MockResponse() server2.enqueue(new MockResponse()
.addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
.addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS))
@@ -404,7 +402,8 @@ public final class ResponseCacheTest {
.addHeader("Location: " + server2.url("/").url())); .addHeader("Location: " + server2.url("/").url()));
urlFactory.setClient(urlFactory.client().newBuilder() urlFactory.setClient(urlFactory.client().newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(hostnameVerifier) .hostnameVerifier(hostnameVerifier)
.build()); .build());
@@ -481,7 +480,7 @@ public final class ResponseCacheTest {
testServerPrematureDisconnect(TransferKind.CHUNKED); testServerPrematureDisconnect(TransferKind.CHUNKED);
} }
@Test public void serverDisconnectsPrematurelyWithNoLengthHeaders() throws IOException { @Test public void serverDisconnectsPrematurelyWithNoLengthHeaders() {
// Intentionally empty. This case doesn't make sense because there's no // Intentionally empty. This case doesn't make sense because there's no
// such thing as a premature disconnect when the disconnect itself // such thing as a premature disconnect when the disconnect itself
// indicates the end of the data stream. // indicates the end of the data stream.
@@ -1467,7 +1466,7 @@ public final class ResponseCacheTest {
} }
@Test public void varyAndHttps() throws Exception { @Test public void varyAndHttps() throws Exception {
server.useHttps(tlsNode.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
server.enqueue(new MockResponse() server.enqueue(new MockResponse()
.addHeader("Cache-Control: max-age=60") .addHeader("Cache-Control: max-age=60")
.addHeader("Vary: Accept-Language") .addHeader("Vary: Accept-Language")
@@ -1476,7 +1475,8 @@ public final class ResponseCacheTest {
.setBody("B")); .setBody("B"));
urlFactory.setClient(urlFactory.client().newBuilder() urlFactory.setClient(urlFactory.client().newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(hostnameVerifier) .hostnameVerifier(hostnameVerifier)
.build()); .build());
@@ -1564,14 +1564,6 @@ public final class ResponseCacheTest {
assertEquals("299 test danger", connection2.getHeaderField("Warning")); assertEquals("299 test danger", connection2.getHeaderField("Warning"));
} }
public void assertCookies(URL url, String... expectedCookies) throws Exception {
List<String> actualCookies = new ArrayList<>();
for (HttpCookie cookie : cookieManager.getCookieStore().get(url.toURI())) {
actualCookies.add(cookie.toString());
}
assertEquals(Arrays.asList(expectedCookies), actualCookies);
}
@Test public void doNotCachePartialResponse() throws Exception { @Test public void doNotCachePartialResponse() throws Exception {
assertNotCached(new MockResponse() assertNotCached(new MockResponse()
.setResponseCode(HttpURLConnection.HTTP_PARTIAL) .setResponseCode(HttpURLConnection.HTTP_PARTIAL)
@@ -1675,7 +1667,7 @@ public final class ResponseCacheTest {
assertEquals("A", readAscii(connection)); assertEquals("A", readAscii(connection));
} }
@Test public void emptyResponseHeaderNameFromCacheIsLenient() throws Exception { @Test public void emptyResponseHeaderNameFromCacheIsLenient() {
Headers.Builder headers = new Headers.Builder() Headers.Builder headers = new Headers.Builder()
.add("Cache-Control: max-age=120"); .add("Cache-Control: max-age=120");
Internal.instance.addLenient(headers, ": A"); Internal.instance.addLenient(headers, ": A");
@@ -1770,8 +1762,7 @@ public final class ResponseCacheTest {
enum TransferKind { enum TransferKind {
CHUNKED() { CHUNKED() {
@Override void setBody(MockResponse response, Buffer content, int chunkSize) @Override void setBody(MockResponse response, Buffer content, int chunkSize) {
throws IOException {
response.setChunkedBody(content, chunkSize); response.setChunkedBody(content, chunkSize);
} }
}, },
@@ -1796,7 +1787,7 @@ public final class ResponseCacheTest {
} }
/** Returns a gzipped copy of {@code bytes}. */ /** Returns a gzipped copy of {@code bytes}. */
public Buffer gzip(String data) throws IOException { private Buffer gzip(String data) throws IOException {
Buffer result = new Buffer(); Buffer result = new Buffer();
BufferedSink sink = Okio.buffer(new GzipSink(result)); BufferedSink sink = Okio.buffer(new GzipSink(result));
sink.writeUtf8(data); sink.writeUtf8(data);
@@ -1899,7 +1890,7 @@ public final class ResponseCacheTest {
aborted.set(true); aborted.set(true);
} }
@Override public OutputStream getBody() throws IOException { @Override public OutputStream getBody() {
return null; return null;
} }
}; };
@@ -1925,10 +1916,9 @@ public final class ResponseCacheTest {
setInternalCache(new CacheAdapter(new AbstractResponseCache() { setInternalCache(new CacheAdapter(new AbstractResponseCache() {
@Override @Override
public CacheResponse get(URI uri, String requestMethod, public CacheResponse get(URI uri, String requestMethod,
Map<String, List<String>> requestHeaders) Map<String, List<String>> requestHeaders) {
throws IOException {
return new CacheResponse() { return new CacheResponse() {
@Override public Map<String, List<String>> getHeaders() throws IOException { @Override public Map<String, List<String>> getHeaders() {
String contentType = "text/plain"; String contentType = "text/plain";
Map<String, List<String>> headers = new LinkedHashMap<>(); Map<String, List<String>> headers = new LinkedHashMap<>();
headers.put("Content-Length", Arrays.asList(Integer.toString(cachedContent.length))); headers.put("Content-Length", Arrays.asList(Integer.toString(cachedContent.length)));
@@ -1940,7 +1930,7 @@ public final class ResponseCacheTest {
return headers; return headers;
} }
@Override public InputStream getBody() throws IOException { @Override public InputStream getBody() {
return new ByteArrayInputStream(cachedContent); return new ByteArrayInputStream(cachedContent);
} }
}; };
@@ -1989,32 +1979,32 @@ public final class ResponseCacheTest {
@Test public void cacheReturnsInsecureResponseForSecureRequest() throws IOException { @Test public void cacheReturnsInsecureResponseForSecureRequest() throws IOException {
assumeFalse(getPlatform().equals("jdk9")); assumeFalse(getPlatform().equals("jdk9"));
server.useHttps(tlsNode.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
server.enqueue(new MockResponse().setBody("ABC")); server.enqueue(new MockResponse().setBody("ABC"));
server.enqueue(new MockResponse().setBody("DEF")); server.enqueue(new MockResponse().setBody("DEF"));
AndroidInternal.setResponseCache(urlFactory, new InsecureResponseCache(cache)); AndroidInternal.setResponseCache(urlFactory, new InsecureResponseCache(cache));
HttpsURLConnection connection1 = (HttpsURLConnection) openConnection(server.url("/").url()); HttpsURLConnection connection1 = (HttpsURLConnection) openConnection(server.url("/").url());
connection1.setSSLSocketFactory(tlsNode.sslSocketFactory()); connection1.setSSLSocketFactory(handshakeCertificates.sslSocketFactory());
connection1.setHostnameVerifier(hostnameVerifier); connection1.setHostnameVerifier(hostnameVerifier);
assertEquals("ABC", readAscii(connection1)); assertEquals("ABC", readAscii(connection1));
// Not cached! // Not cached!
HttpsURLConnection connection2 = (HttpsURLConnection) openConnection(server.url("/").url()); HttpsURLConnection connection2 = (HttpsURLConnection) openConnection(server.url("/").url());
connection2.setSSLSocketFactory(tlsNode.sslSocketFactory()); connection2.setSSLSocketFactory(handshakeCertificates.sslSocketFactory());
connection2.setHostnameVerifier(hostnameVerifier); connection2.setHostnameVerifier(hostnameVerifier);
assertEquals("DEF", readAscii(connection2)); assertEquals("DEF", readAscii(connection2));
} }
@Test public void responseCacheRequestHeaders() throws IOException, URISyntaxException { @Test public void responseCacheRequestHeaders() throws IOException {
server.enqueue(new MockResponse() server.enqueue(new MockResponse()
.setBody("ABC")); .setBody("ABC"));
final AtomicReference<Map<String, List<String>>> requestHeadersRef = new AtomicReference<>(); final AtomicReference<Map<String, List<String>>> requestHeadersRef = new AtomicReference<>();
setInternalCache(new CacheAdapter(new AbstractResponseCache() { setInternalCache(new CacheAdapter(new AbstractResponseCache() {
@Override public CacheResponse get(URI uri, String requestMethod, @Override public CacheResponse get(URI uri, String requestMethod,
Map<String, List<String>> requestHeaders) throws IOException { Map<String, List<String>> requestHeaders) {
requestHeadersRef.set(requestHeaders); requestHeadersRef.set(requestHeaders);
return null; return null;
} }

View File

@@ -35,7 +35,7 @@ import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor.Level; import okhttp3.logging.HttpLoggingInterceptor.Level;
import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.MockWebServer;
import okhttp3.tls.TlsNode; import okhttp3.tls.HandshakeCertificates;
import okio.Buffer; import okio.Buffer;
import okio.BufferedSink; import okio.BufferedSink;
import okio.ByteString; import okio.ByteString;
@@ -58,7 +58,7 @@ public final class HttpLoggingInterceptorTest {
@Rule public final MockWebServer server = new MockWebServer(); @Rule public final MockWebServer server = new MockWebServer();
private TlsNode tlsNode = localhost(); private HandshakeCertificates handshakeCertificates = localhost();
private HostnameVerifier hostnameVerifier = new RecordingHostnameVerifier(); private HostnameVerifier hostnameVerifier = new RecordingHostnameVerifier();
private OkHttpClient client; private OkHttpClient client;
private String host; private String host;
@@ -81,7 +81,8 @@ public final class HttpLoggingInterceptorTest {
client = new OkHttpClient.Builder() client = new OkHttpClient.Builder()
.addNetworkInterceptor(networkInterceptor) .addNetworkInterceptor(networkInterceptor)
.addInterceptor(applicationInterceptor) .addInterceptor(applicationInterceptor)
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(hostnameVerifier) .hostnameVerifier(hostnameVerifier)
.build(); .build();
@@ -724,7 +725,7 @@ public final class HttpLoggingInterceptorTest {
} }
@Test public void http2() throws Exception { @Test public void http2() throws Exception {
server.useHttps(tlsNode.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
url = server.url("/"); url = server.url("/");
setLevel(Level.BASIC); setLevel(Level.BASIC);

View File

@@ -41,7 +41,7 @@ import okhttp3.internal.platform.Platform;
import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest; import okhttp3.mockwebserver.RecordedRequest;
import okhttp3.tls.TlsNode; import okhttp3.tls.HandshakeCertificates;
import okio.Buffer; import okio.Buffer;
import okio.BufferedSink; import okio.BufferedSink;
import okio.BufferedSource; import okio.BufferedSource;
@@ -73,7 +73,7 @@ public final class CacheTest {
@Rule public MockWebServer server2 = new MockWebServer(); @Rule public MockWebServer server2 = new MockWebServer();
@Rule public InMemoryFileSystem fileSystem = new InMemoryFileSystem(); @Rule public InMemoryFileSystem fileSystem = new InMemoryFileSystem();
private final TlsNode tlsNode = localhost(); private final HandshakeCertificates handshakeCertificates = localhost();
private OkHttpClient client; private OkHttpClient client;
private Cache cache; private Cache cache;
private final CookieManager cookieManager = new CookieManager(); private final CookieManager cookieManager = new CookieManager();
@@ -254,14 +254,15 @@ public final class CacheTest {
} }
@Test public void secureResponseCaching() throws IOException { @Test public void secureResponseCaching() throws IOException {
server.useHttps(tlsNode.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
server.enqueue(new MockResponse() server.enqueue(new MockResponse()
.addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
.addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS))
.setBody("ABC")); .setBody("ABC"));
client = client.newBuilder() client = client.newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(NULL_HOSTNAME_VERIFIER) .hostnameVerifier(NULL_HOSTNAME_VERIFIER)
.build(); .build();
@@ -350,7 +351,7 @@ public final class CacheTest {
} }
@Test public void secureResponseCachingAndRedirects() throws IOException { @Test public void secureResponseCachingAndRedirects() throws IOException {
server.useHttps(tlsNode.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
server.enqueue(new MockResponse() server.enqueue(new MockResponse()
.addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
.addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS))
@@ -364,7 +365,8 @@ public final class CacheTest {
.setBody("DEF")); .setBody("DEF"));
client = client.newBuilder() client = client.newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(NULL_HOSTNAME_VERIFIER) .hostnameVerifier(NULL_HOSTNAME_VERIFIER)
.build(); .build();
@@ -390,7 +392,7 @@ public final class CacheTest {
* https://github.com/square/okhttp/issues/214 * https://github.com/square/okhttp/issues/214
*/ */
@Test public void secureResponseCachingAndProtocolRedirects() throws IOException { @Test public void secureResponseCachingAndProtocolRedirects() throws IOException {
server2.useHttps(tlsNode.sslSocketFactory(), false); server2.useHttps(handshakeCertificates.sslSocketFactory(), false);
server2.enqueue(new MockResponse() server2.enqueue(new MockResponse()
.addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
.addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS))
@@ -405,7 +407,8 @@ public final class CacheTest {
.addHeader("Location: " + server2.url("/"))); .addHeader("Location: " + server2.url("/")));
client = client.newBuilder() client = client.newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(NULL_HOSTNAME_VERIFIER) .hostnameVerifier(NULL_HOSTNAME_VERIFIER)
.build(); .build();
@@ -1757,7 +1760,7 @@ public final class CacheTest {
} }
@Test public void varyAndHttps() throws Exception { @Test public void varyAndHttps() throws Exception {
server.useHttps(tlsNode.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
server.enqueue(new MockResponse() server.enqueue(new MockResponse()
.addHeader("Cache-Control: max-age=60") .addHeader("Cache-Control: max-age=60")
.addHeader("Vary: Accept-Language") .addHeader("Vary: Accept-Language")
@@ -1766,7 +1769,8 @@ public final class CacheTest {
.setBody("B")); .setBody("B"));
client = client.newBuilder() client = client.newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(NULL_HOSTNAME_VERIFIER) .hostnameVerifier(NULL_HOSTNAME_VERIFIER)
.build(); .build();

View File

@@ -66,7 +66,7 @@ import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest; import okhttp3.mockwebserver.RecordedRequest;
import okhttp3.mockwebserver.SocketPolicy; import okhttp3.mockwebserver.SocketPolicy;
import okhttp3.tls.HeldCertificate; import okhttp3.tls.HeldCertificate;
import okhttp3.tls.TlsNode; import okhttp3.tls.HandshakeCertificates;
import okio.Buffer; import okio.Buffer;
import okio.BufferedSink; import okio.BufferedSink;
import okio.BufferedSource; import okio.BufferedSource;
@@ -99,7 +99,7 @@ public final class CallTest {
@Rule public final MockWebServer server2 = new MockWebServer(); @Rule public final MockWebServer server2 = new MockWebServer();
@Rule public final InMemoryFileSystem fileSystem = new InMemoryFileSystem(); @Rule public final InMemoryFileSystem fileSystem = new InMemoryFileSystem();
private TlsNode tlsNode = localhost(); private HandshakeCertificates handshakeCertificates = localhost();
private OkHttpClient client = defaultClient(); private OkHttpClient client = defaultClient();
private RecordingCallback callback = new RecordingCallback(); private RecordingCallback callback = new RecordingCallback();
private TestLogHandler logHandler = new TestLogHandler(); private TestLogHandler logHandler = new TestLogHandler();
@@ -1067,7 +1067,7 @@ public final class CallTest {
} }
@Test public void tlsHandshakeFailure_noFallbackByDefault() throws Exception { @Test public void tlsHandshakeFailure_noFallbackByDefault() throws Exception {
server.useHttps(tlsNode.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.FAIL_HANDSHAKE)); server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.FAIL_HANDSHAKE));
server.enqueue(new MockResponse().setBody("response that will never be received")); server.enqueue(new MockResponse().setBody("response that will never be received"));
RecordedResponse response = executeSynchronously("/"); RecordedResponse response = executeSynchronously("/");
@@ -1079,7 +1079,7 @@ public final class CallTest {
} }
@Test public void recoverFromTlsHandshakeFailure() throws Exception { @Test public void recoverFromTlsHandshakeFailure() throws Exception {
server.useHttps(tlsNode.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.FAIL_HANDSHAKE)); server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.FAIL_HANDSHAKE));
server.enqueue(new MockResponse().setBody("abc")); server.enqueue(new MockResponse().setBody("abc"));
@@ -1088,7 +1088,8 @@ public final class CallTest {
.dns(new SingleInetAddressDns()) .dns(new SingleInetAddressDns())
// Attempt RESTRICTED_TLS then fall back to MODERN_TLS. // Attempt RESTRICTED_TLS then fall back to MODERN_TLS.
.connectionSpecs(Arrays.asList(ConnectionSpec.RESTRICTED_TLS, ConnectionSpec.MODERN_TLS)) .connectionSpecs(Arrays.asList(ConnectionSpec.RESTRICTED_TLS, ConnectionSpec.MODERN_TLS))
.sslSocketFactory(suppressTlsFallbackClientSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
suppressTlsFallbackClientSocketFactory(), handshakeCertificates.trustManager())
.build(); .build();
executeSynchronously("/").assertBody("abc"); executeSynchronously("/").assertBody("abc");
@@ -1097,19 +1098,19 @@ public final class CallTest {
@Test public void recoverFromTlsHandshakeFailure_tlsFallbackScsvEnabled() throws Exception { @Test public void recoverFromTlsHandshakeFailure_tlsFallbackScsvEnabled() throws Exception {
final String tlsFallbackScsv = "TLS_FALLBACK_SCSV"; final String tlsFallbackScsv = "TLS_FALLBACK_SCSV";
List<String> supportedCiphers = List<String> supportedCiphers =
Arrays.asList(tlsNode.sslSocketFactory().getSupportedCipherSuites()); Arrays.asList(handshakeCertificates.sslSocketFactory().getSupportedCipherSuites());
if (!supportedCiphers.contains(tlsFallbackScsv)) { if (!supportedCiphers.contains(tlsFallbackScsv)) {
// This only works if the client socket supports TLS_FALLBACK_SCSV. // This only works if the client socket supports TLS_FALLBACK_SCSV.
return; return;
} }
server.useHttps(tlsNode.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.FAIL_HANDSHAKE)); server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.FAIL_HANDSHAKE));
RecordingSSLSocketFactory clientSocketFactory = RecordingSSLSocketFactory clientSocketFactory =
new RecordingSSLSocketFactory(tlsNode.sslSocketFactory()); new RecordingSSLSocketFactory(handshakeCertificates.sslSocketFactory());
client = client.newBuilder() client = client.newBuilder()
.sslSocketFactory(clientSocketFactory, tlsNode.trustManager()) .sslSocketFactory(clientSocketFactory, handshakeCertificates.trustManager())
// Attempt RESTRICTED_TLS then fall back to MODERN_TLS. // Attempt RESTRICTED_TLS then fall back to MODERN_TLS.
.connectionSpecs(Arrays.asList(ConnectionSpec.RESTRICTED_TLS, ConnectionSpec.MODERN_TLS)) .connectionSpecs(Arrays.asList(ConnectionSpec.RESTRICTED_TLS, ConnectionSpec.MODERN_TLS))
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
@@ -1131,7 +1132,7 @@ public final class CallTest {
} }
@Test public void recoverFromTlsHandshakeFailure_Async() throws Exception { @Test public void recoverFromTlsHandshakeFailure_Async() throws Exception {
server.useHttps(tlsNode.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.FAIL_HANDSHAKE)); server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.FAIL_HANDSHAKE));
server.enqueue(new MockResponse().setBody("abc")); server.enqueue(new MockResponse().setBody("abc"));
@@ -1139,7 +1140,8 @@ public final class CallTest {
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
// Attempt RESTRICTED_TLS then fall back to MODERN_TLS. // Attempt RESTRICTED_TLS then fall back to MODERN_TLS.
.connectionSpecs(Arrays.asList(ConnectionSpec.RESTRICTED_TLS, ConnectionSpec.MODERN_TLS)) .connectionSpecs(Arrays.asList(ConnectionSpec.RESTRICTED_TLS, ConnectionSpec.MODERN_TLS))
.sslSocketFactory(suppressTlsFallbackClientSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
suppressTlsFallbackClientSocketFactory(), handshakeCertificates.trustManager())
.build(); .build();
Request request = new Request.Builder() Request request = new Request.Builder()
@@ -1155,10 +1157,11 @@ public final class CallTest {
.connectionSpecs(Arrays.asList(ConnectionSpec.MODERN_TLS, ConnectionSpec.CLEARTEXT)) .connectionSpecs(Arrays.asList(ConnectionSpec.MODERN_TLS, ConnectionSpec.CLEARTEXT))
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
.dns(new SingleInetAddressDns()) .dns(new SingleInetAddressDns())
.sslSocketFactory(suppressTlsFallbackClientSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
suppressTlsFallbackClientSocketFactory(), handshakeCertificates.trustManager())
.build(); .build();
server.useHttps(tlsNode.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.FAIL_HANDSHAKE)); server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.FAIL_HANDSHAKE));
Request request = new Request.Builder().url(server.url("/")).build(); Request request = new Request.Builder().url(server.url("/")).build();
@@ -1194,7 +1197,7 @@ public final class CallTest {
.protocols(Collections.singletonList(Protocol.H2_PRIOR_KNOWLEDGE)) .protocols(Collections.singletonList(Protocol.H2_PRIOR_KNOWLEDGE))
.build(); .build();
server.useHttps(tlsNode.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
server.enqueue(new MockResponse()); server.enqueue(new MockResponse());
Call call = client.newCall(new Request.Builder() Call call = client.newCall(new Request.Builder()
@@ -2660,7 +2663,7 @@ public final class CallTest {
/** Test which headers are sent unencrypted to the HTTP proxy. */ /** Test which headers are sent unencrypted to the HTTP proxy. */
@Test public void proxyConnectOmitsApplicationHeaders() throws Exception { @Test public void proxyConnectOmitsApplicationHeaders() throws Exception {
server.useHttps(tlsNode.sslSocketFactory(), true); server.useHttps(handshakeCertificates.sslSocketFactory(), true);
server.enqueue(new MockResponse() server.enqueue(new MockResponse()
.setSocketPolicy(SocketPolicy.UPGRADE_TO_SSL_AT_END) .setSocketPolicy(SocketPolicy.UPGRADE_TO_SSL_AT_END)
.clearHeaders()); .clearHeaders());
@@ -2669,7 +2672,8 @@ public final class CallTest {
RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier(); RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier();
client = client.newBuilder() client = client.newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.proxy(server.toProxyAddress()) .proxy(server.toProxyAddress())
.hostnameVerifier(hostnameVerifier) .hostnameVerifier(hostnameVerifier)
.build(); .build();
@@ -2697,7 +2701,7 @@ public final class CallTest {
/** Respond to a proxy authorization challenge. */ /** Respond to a proxy authorization challenge. */
@Test public void proxyAuthenticateOnConnect() throws Exception { @Test public void proxyAuthenticateOnConnect() throws Exception {
server.useHttps(tlsNode.sslSocketFactory(), true); server.useHttps(handshakeCertificates.sslSocketFactory(), true);
server.enqueue(new MockResponse() server.enqueue(new MockResponse()
.setResponseCode(407) .setResponseCode(407)
.addHeader("Proxy-Authenticate: Basic realm=\"localhost\"")); .addHeader("Proxy-Authenticate: Basic realm=\"localhost\""));
@@ -2708,7 +2712,8 @@ public final class CallTest {
.setBody("response body")); .setBody("response body"));
client = client.newBuilder() client = client.newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.proxy(server.toProxyAddress()) .proxy(server.toProxyAddress())
.proxyAuthenticator(new RecordingOkAuthenticator("password")) .proxyAuthenticator(new RecordingOkAuthenticator("password"))
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
@@ -2766,7 +2771,7 @@ public final class CallTest {
* TLS tunnel. https://github.com/square/okhttp/issues/2426 * TLS tunnel. https://github.com/square/okhttp/issues/2426
*/ */
@Test public void proxyAuthenticateOnConnectWithConnectionClose() throws Exception { @Test public void proxyAuthenticateOnConnectWithConnectionClose() throws Exception {
server.useHttps(tlsNode.sslSocketFactory(), true); server.useHttps(handshakeCertificates.sslSocketFactory(), true);
server.setProtocols(Collections.singletonList(Protocol.HTTP_1_1)); server.setProtocols(Collections.singletonList(Protocol.HTTP_1_1));
server.enqueue(new MockResponse() server.enqueue(new MockResponse()
.setResponseCode(407) .setResponseCode(407)
@@ -2779,7 +2784,8 @@ public final class CallTest {
.setBody("response body")); .setBody("response body"));
client = client.newBuilder() client = client.newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.proxy(server.toProxyAddress()) .proxy(server.toProxyAddress())
.proxyAuthenticator(new RecordingOkAuthenticator("password")) .proxyAuthenticator(new RecordingOkAuthenticator("password"))
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
@@ -2802,7 +2808,7 @@ public final class CallTest {
} }
@Test public void tooManyProxyAuthFailuresWithConnectionClose() throws IOException { @Test public void tooManyProxyAuthFailuresWithConnectionClose() throws IOException {
server.useHttps(tlsNode.sslSocketFactory(), true); server.useHttps(handshakeCertificates.sslSocketFactory(), true);
server.setProtocols(Collections.singletonList(Protocol.HTTP_1_1)); server.setProtocols(Collections.singletonList(Protocol.HTTP_1_1));
for (int i = 0; i < 21; i++) { for (int i = 0; i < 21; i++) {
server.enqueue(new MockResponse() server.enqueue(new MockResponse()
@@ -2812,7 +2818,8 @@ public final class CallTest {
} }
client = client.newBuilder() client = client.newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.proxy(server.toProxyAddress()) .proxy(server.toProxyAddress())
.proxyAuthenticator(new RecordingOkAuthenticator("password")) .proxyAuthenticator(new RecordingOkAuthenticator("password"))
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
@@ -2834,7 +2841,7 @@ public final class CallTest {
* credentials. Worse, that approach leaks proxy credentials to the origin server. * credentials. Worse, that approach leaks proxy credentials to the origin server.
*/ */
@Test public void noProactiveProxyAuthorization() throws Exception { @Test public void noProactiveProxyAuthorization() throws Exception {
server.useHttps(tlsNode.sslSocketFactory(), true); server.useHttps(handshakeCertificates.sslSocketFactory(), true);
server.enqueue(new MockResponse() server.enqueue(new MockResponse()
.setSocketPolicy(SocketPolicy.UPGRADE_TO_SSL_AT_END) .setSocketPolicy(SocketPolicy.UPGRADE_TO_SSL_AT_END)
.clearHeaders()); .clearHeaders());
@@ -2842,7 +2849,8 @@ public final class CallTest {
.setBody("response body")); .setBody("response body"));
client = client.newBuilder() client = client.newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.proxy(server.toProxyAddress()) .proxy(server.toProxyAddress())
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
.build(); .build();
@@ -3031,7 +3039,7 @@ public final class CallTest {
/** https://github.com/square/okhttp/issues/2344 */ /** https://github.com/square/okhttp/issues/2344 */
@Test public void ipv6HostHasSquareBraces() throws Exception { @Test public void ipv6HostHasSquareBraces() throws Exception {
// Use a proxy to fake IPv6 connectivity, even if localhost doesn't have IPv6. // Use a proxy to fake IPv6 connectivity, even if localhost doesn't have IPv6.
server.useHttps(tlsNode.sslSocketFactory(), true); server.useHttps(handshakeCertificates.sslSocketFactory(), true);
server.setProtocols(Collections.singletonList(Protocol.HTTP_1_1)); server.setProtocols(Collections.singletonList(Protocol.HTTP_1_1));
server.enqueue(new MockResponse() server.enqueue(new MockResponse()
.setSocketPolicy(SocketPolicy.UPGRADE_TO_SSL_AT_END) .setSocketPolicy(SocketPolicy.UPGRADE_TO_SSL_AT_END)
@@ -3040,7 +3048,8 @@ public final class CallTest {
.setBody("response body")); .setBody("response body"));
client = client.newBuilder() client = client.newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
.proxy(server.toProxyAddress()) .proxy(server.toProxyAddress())
.build(); .build();
@@ -3216,15 +3225,16 @@ public final class CallTest {
.commonName("example.com") .commonName("example.com")
.addSubjectAlternativeName(localIpAddress) .addSubjectAlternativeName(localIpAddress)
.build(); .build();
TlsNode tlsNode = new TlsNode.Builder() HandshakeCertificates handshakeCertificates = new HandshakeCertificates.Builder()
.heldCertificate(heldCertificate) .heldCertificate(heldCertificate)
.addTrustedCertificate(heldCertificate.certificate()) .addTrustedCertificate(heldCertificate.certificate())
.build(); .build();
// Use that certificate on the server and trust it on the client. // Use that certificate on the server and trust it on the client.
server.useHttps(tlsNode.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
client = client.newBuilder() client = client.newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
.protocols(Collections.singletonList(Protocol.HTTP_1_1)) .protocols(Collections.singletonList(Protocol.HTTP_1_1))
.build(); .build();
@@ -3308,10 +3318,11 @@ public final class CallTest {
private void enableTls() { private void enableTls() {
client = client.newBuilder() client = client.newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
.build(); .build();
server.useHttps(tlsNode.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
} }
private Buffer gzip(String data) throws IOException { private Buffer gzip(String data) throws IOException {
@@ -3360,6 +3371,6 @@ public final class CallTest {
* for details. * for details.
*/ */
private FallbackTestClientSocketFactory suppressTlsFallbackClientSocketFactory() { private FallbackTestClientSocketFactory suppressTlsFallbackClientSocketFactory() {
return new FallbackTestClientSocketFactory(tlsNode.sslSocketFactory()); return new FallbackTestClientSocketFactory(handshakeCertificates.sslSocketFactory());
} }
} }

View File

@@ -15,7 +15,6 @@
*/ */
package okhttp3; package okhttp3;
import java.security.GeneralSecurityException;
import java.security.cert.Certificate; import java.security.cert.Certificate;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
import java.util.ArrayList; import java.util.ArrayList;
@@ -23,15 +22,15 @@ import java.util.List;
import javax.net.ssl.SSLPeerUnverifiedException; import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.X509TrustManager; import javax.net.ssl.X509TrustManager;
import okhttp3.internal.tls.CertificateChainCleaner; import okhttp3.internal.tls.CertificateChainCleaner;
import okhttp3.tls.HandshakeCertificates;
import okhttp3.tls.HeldCertificate; import okhttp3.tls.HeldCertificate;
import okhttp3.tls.TlsNode;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
public final class CertificateChainCleanerTest { public final class CertificateChainCleanerTest {
@Test public void equalsFromCertificate() throws Exception { @Test public void equalsFromCertificate() {
HeldCertificate rootA = new HeldCertificate.Builder() HeldCertificate rootA = new HeldCertificate.Builder()
.serialNumber(1L) .serialNumber(1L)
.build(); .build();
@@ -43,9 +42,9 @@ public final class CertificateChainCleanerTest {
CertificateChainCleaner.get(rootB.certificate(), rootA.certificate())); CertificateChainCleaner.get(rootB.certificate(), rootA.certificate()));
} }
@Test public void equalsFromTrustManager() throws Exception { @Test public void equalsFromTrustManager() {
TlsNode tlsNode = new TlsNode.Builder().build(); HandshakeCertificates handshakeCertificates = new HandshakeCertificates.Builder().build();
X509TrustManager x509TrustManager = tlsNode.trustManager(); X509TrustManager x509TrustManager = handshakeCertificates.trustManager();
assertEquals( assertEquals(
CertificateChainCleaner.get(x509TrustManager), CertificateChainCleaner.get(x509TrustManager),
CertificateChainCleaner.get(x509TrustManager)); CertificateChainCleaner.get(x509TrustManager));
@@ -59,7 +58,7 @@ public final class CertificateChainCleanerTest {
assertEquals(list(root), cleaner.clean(list(root), "hostname")); assertEquals(list(root), cleaner.clean(list(root), "hostname"));
} }
@Test public void normalizeUnknownSelfSignedCertificate() throws Exception { @Test public void normalizeUnknownSelfSignedCertificate() {
HeldCertificate root = new HeldCertificate.Builder() HeldCertificate root = new HeldCertificate.Builder()
.serialNumber(1L) .serialNumber(1L)
.build(); .build();
@@ -236,7 +235,7 @@ public final class CertificateChainCleanerTest {
assertEquals(certificates, cleaner.clean(certificates.subList(0, 9), "hostname")); assertEquals(certificates, cleaner.clean(certificates.subList(0, 9), "hostname"));
} }
@Test public void chainTooLong() throws Exception { @Test public void chainTooLong() {
List<HeldCertificate> heldCertificates = chainOfLength(11); List<HeldCertificate> heldCertificates = chainOfLength(11);
List<Certificate> certificates = new ArrayList<>(); List<Certificate> certificates = new ArrayList<>();
for (HeldCertificate heldCertificate : heldCertificates) { for (HeldCertificate heldCertificate : heldCertificates) {
@@ -253,7 +252,7 @@ public final class CertificateChainCleanerTest {
} }
/** Returns a chain starting at the leaf certificate and progressing to the root. */ /** Returns a chain starting at the leaf certificate and progressing to the root. */
private List<HeldCertificate> chainOfLength(int length) throws GeneralSecurityException { private List<HeldCertificate> chainOfLength(int length) {
List<HeldCertificate> result = new ArrayList<>(); List<HeldCertificate> result = new ArrayList<>();
for (int i = 1; i <= length; i++) { for (int i = 1; i <= length; i++) {
result.add(0, new HeldCertificate.Builder() result.add(0, new HeldCertificate.Builder()

View File

@@ -29,7 +29,7 @@ import javax.net.ssl.SSLSession;
import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.MockWebServer;
import okhttp3.tls.HeldCertificate; import okhttp3.tls.HeldCertificate;
import okhttp3.tls.TlsNode; import okhttp3.tls.HandshakeCertificates;
import org.junit.Before; import org.junit.Before;
import org.junit.Ignore; import org.junit.Ignore;
import org.junit.Rule; import org.junit.Rule;
@@ -73,18 +73,19 @@ public final class ConnectionCoalescingTest {
dns.set("www.wildcard.com", serverIps); dns.set("www.wildcard.com", serverIps);
dns.set("differentdns.com", Collections.<InetAddress>emptyList()); dns.set("differentdns.com", Collections.<InetAddress>emptyList());
TlsNode tlsNode = new TlsNode.Builder() HandshakeCertificates handshakeCertificates = new HandshakeCertificates.Builder()
.addTrustedCertificate(rootCa.certificate()) .addTrustedCertificate(rootCa.certificate())
.build(); .build();
client = new OkHttpClient.Builder().dns(dns) client = new OkHttpClient.Builder().dns(dns)
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.build(); .build();
TlsNode serverTlsNode = new TlsNode.Builder() HandshakeCertificates serverHandshakeCertificates = new HandshakeCertificates.Builder()
.heldCertificate(certificate) .heldCertificate(certificate)
.build(); .build();
server.useHttps(serverTlsNode.sslSocketFactory(), false); server.useHttps(serverHandshakeCertificates.sslSocketFactory(), false);
url = server.url("/robots.txt"); url = server.url("/robots.txt");
} }

View File

@@ -22,7 +22,7 @@ import javax.net.ssl.SSLException;
import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.SocketPolicy; import okhttp3.mockwebserver.SocketPolicy;
import okhttp3.tls.TlsNode; import okhttp3.tls.HandshakeCertificates;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.TestRule; import org.junit.rules.TestRule;
@@ -38,7 +38,7 @@ public final class ConnectionReuseTest {
@Rule public final TestRule timeout = new Timeout(30_000); @Rule public final TestRule timeout = new Timeout(30_000);
@Rule public final MockWebServer server = new MockWebServer(); @Rule public final MockWebServer server = new MockWebServer();
private TlsNode tlsNode = localhost(); private HandshakeCertificates handshakeCertificates = localhost();
private OkHttpClient client = defaultClient(); private OkHttpClient client = defaultClient();
@Test public void connectionsAreReused() throws Exception { @Test public void connectionsAreReused() throws Exception {
@@ -252,9 +252,10 @@ public final class ConnectionReuseTest {
response.body().close(); response.body().close();
// This client shares a connection pool but has a different SSL socket factory. // This client shares a connection pool but has a different SSL socket factory.
TlsNode tlsNode2 = new TlsNode.Builder().build(); HandshakeCertificates handshakeCertificates2 = new HandshakeCertificates.Builder().build();
OkHttpClient anotherClient = client.newBuilder() OkHttpClient anotherClient = client.newBuilder()
.sslSocketFactory(tlsNode2.sslSocketFactory(), tlsNode2.trustManager()) .sslSocketFactory(
handshakeCertificates2.sslSocketFactory(), handshakeCertificates2.trustManager())
.build(); .build();
// This client fails to connect because the new SSL socket factory refuses. // This client fails to connect because the new SSL socket factory refuses.
@@ -338,11 +339,12 @@ public final class ConnectionReuseTest {
private void enableHttpsAndAlpn(Protocol... protocols) { private void enableHttpsAndAlpn(Protocol... protocols) {
client = client.newBuilder() client = client.newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
.protocols(Arrays.asList(protocols)) .protocols(Arrays.asList(protocols))
.build(); .build();
server.useHttps(tlsNode.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
server.setProtocols(client.protocols()); server.setProtocols(client.protocols());
} }

View File

@@ -47,7 +47,7 @@ import okhttp3.logging.HttpLoggingInterceptor;
import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.SocketPolicy; import okhttp3.mockwebserver.SocketPolicy;
import okhttp3.tls.TlsNode; import okhttp3.tls.HandshakeCertificates;
import okio.Buffer; import okio.Buffer;
import okio.BufferedSink; import okio.BufferedSink;
import org.hamcrest.BaseMatcher; import org.hamcrest.BaseMatcher;
@@ -82,7 +82,7 @@ public final class EventListenerTest {
private final SingleInetAddressDns singleDns = new SingleInetAddressDns(); private final SingleInetAddressDns singleDns = new SingleInetAddressDns();
private final RecordingEventListener listener = new RecordingEventListener(); private final RecordingEventListener listener = new RecordingEventListener();
private final TlsNode tlsNode = localhost(); private final HandshakeCertificates handshakeCertificates = localhost();
private OkHttpClient client; private OkHttpClient client;
private SocksProxy socksProxy; private SocksProxy socksProxy;
@@ -1080,9 +1080,10 @@ public final class EventListenerTest {
private void enableTlsWithTunnel(boolean tunnelProxy) { private void enableTlsWithTunnel(boolean tunnelProxy) {
client = client.newBuilder() client = client.newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
.build(); .build();
server.useHttps(tlsNode.sslSocketFactory(), tunnelProxy); server.useHttps(handshakeCertificates.sslSocketFactory(), tunnelProxy);
} }
} }

View File

@@ -76,7 +76,7 @@ import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest; import okhttp3.mockwebserver.RecordedRequest;
import okhttp3.mockwebserver.SocketPolicy; import okhttp3.mockwebserver.SocketPolicy;
import okhttp3.tls.TlsNode; import okhttp3.tls.HandshakeCertificates;
import okio.Buffer; import okio.Buffer;
import okio.BufferedSink; import okio.BufferedSink;
import okio.GzipSink; import okio.GzipSink;
@@ -117,7 +117,7 @@ public final class URLConnectionTest {
@Rule public final MockWebServer server2 = new MockWebServer(); @Rule public final MockWebServer server2 = new MockWebServer();
@Rule public final TemporaryFolder tempDir = new TemporaryFolder(); @Rule public final TemporaryFolder tempDir = new TemporaryFolder();
private TlsNode tlsNode = localhost(); private HandshakeCertificates handshakeCertificates = localhost();
private OkUrlFactory urlFactory; private OkUrlFactory urlFactory;
private HttpURLConnection connection; private HttpURLConnection connection;
private Cache cache; private Cache cache;
@@ -387,7 +387,7 @@ public final class URLConnectionTest {
// Check that we recognize a few basic mime types by extension. // Check that we recognize a few basic mime types by extension.
// http://code.google.com/p/android/issues/detail?id=10100 // http://code.google.com/p/android/issues/detail?id=10100
@Test public void bug10100() throws Exception { @Test public void bug10100() {
assertEquals("image/jpeg", URLConnection.guessContentTypeFromName("someFile.jpg")); assertEquals("image/jpeg", URLConnection.guessContentTypeFromName("someFile.jpg"));
assertEquals("application/pdf", URLConnection.guessContentTypeFromName("stuff.pdf")); assertEquals("application/pdf", URLConnection.guessContentTypeFromName("stuff.pdf"));
} }
@@ -555,11 +555,12 @@ public final class URLConnectionTest {
} }
@Test public void connectViaHttps() throws Exception { @Test public void connectViaHttps() throws Exception {
server.useHttps(tlsNode.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
server.enqueue(new MockResponse().setBody("this response comes via HTTPS")); server.enqueue(new MockResponse().setBody("this response comes via HTTPS"));
urlFactory.setClient(urlFactory.client().newBuilder() urlFactory.setClient(urlFactory.client().newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
.build()); .build());
connection = urlFactory.open(server.url("/foo").url()); connection = urlFactory.open(server.url("/foo").url());
@@ -571,11 +572,12 @@ public final class URLConnectionTest {
} }
@Test public void inspectHandshakeThroughoutRequestLifecycle() throws Exception { @Test public void inspectHandshakeThroughoutRequestLifecycle() throws Exception {
server.useHttps(tlsNode.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
server.enqueue(new MockResponse()); server.enqueue(new MockResponse());
urlFactory.setClient(urlFactory.client().newBuilder() urlFactory.setClient(urlFactory.client().newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
.build()); .build());
@@ -611,12 +613,12 @@ public final class URLConnectionTest {
} }
private void connectViaHttpsReusingConnections(boolean rebuildClient) throws Exception { private void connectViaHttpsReusingConnections(boolean rebuildClient) throws Exception {
server.useHttps(tlsNode.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
server.enqueue(new MockResponse().setBody("this response comes via HTTPS")); server.enqueue(new MockResponse().setBody("this response comes via HTTPS"));
server.enqueue(new MockResponse().setBody("another response via HTTPS")); server.enqueue(new MockResponse().setBody("another response via HTTPS"));
// The pool will only reuse sockets if the SSL socket factories are the same. // The pool will only reuse sockets if the SSL socket factories are the same.
SSLSocketFactory clientSocketFactory = tlsNode.sslSocketFactory(); SSLSocketFactory clientSocketFactory = handshakeCertificates.sslSocketFactory();
RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier(); RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier();
CookieJar cookieJar = new JavaNetCookieJar(new CookieManager()); CookieJar cookieJar = new JavaNetCookieJar(new CookieManager());
@@ -626,7 +628,7 @@ public final class URLConnectionTest {
.cache(cache) .cache(cache)
.connectionPool(connectionPool) .connectionPool(connectionPool)
.cookieJar(cookieJar) .cookieJar(cookieJar)
.sslSocketFactory(clientSocketFactory, tlsNode.trustManager()) .sslSocketFactory(clientSocketFactory, handshakeCertificates.trustManager())
.hostnameVerifier(hostnameVerifier) .hostnameVerifier(hostnameVerifier)
.build()); .build());
connection = urlFactory.open(server.url("/").url()); connection = urlFactory.open(server.url("/").url());
@@ -637,7 +639,7 @@ public final class URLConnectionTest {
.cache(cache) .cache(cache)
.connectionPool(connectionPool) .connectionPool(connectionPool)
.cookieJar(cookieJar) .cookieJar(cookieJar)
.sslSocketFactory(clientSocketFactory, tlsNode.trustManager()) .sslSocketFactory(clientSocketFactory, handshakeCertificates.trustManager())
.hostnameVerifier(hostnameVerifier) .hostnameVerifier(hostnameVerifier)
.build()); .build());
} }
@@ -650,13 +652,14 @@ public final class URLConnectionTest {
} }
@Test public void connectViaHttpsReusingConnectionsDifferentFactories() throws Exception { @Test public void connectViaHttpsReusingConnectionsDifferentFactories() throws Exception {
server.useHttps(tlsNode.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
server.enqueue(new MockResponse().setBody("this response comes via HTTPS")); server.enqueue(new MockResponse().setBody("this response comes via HTTPS"));
server.enqueue(new MockResponse().setBody("another response via HTTPS")); server.enqueue(new MockResponse().setBody("another response via HTTPS"));
// install a custom SSL socket factory so the server can be authorized // install a custom SSL socket factory so the server can be authorized
urlFactory.setClient(urlFactory.client().newBuilder() urlFactory.setClient(urlFactory.client().newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
.build()); .build());
HttpURLConnection connection1 = urlFactory.open(server.url("/").url()); HttpURLConnection connection1 = urlFactory.open(server.url("/").url());
@@ -685,7 +688,7 @@ public final class URLConnectionTest {
// TODO(jwilson): tests below this marker need to be migrated to OkHttp's request/response API. // TODO(jwilson): tests below this marker need to be migrated to OkHttp's request/response API.
@Test public void connectViaHttpsWithSSLFallback() throws Exception { @Test public void connectViaHttpsWithSSLFallback() throws Exception {
server.useHttps(tlsNode.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
server.enqueue(new MockResponse().setSocketPolicy(FAIL_HANDSHAKE)); server.enqueue(new MockResponse().setSocketPolicy(FAIL_HANDSHAKE));
server.enqueue(new MockResponse().setBody("this response comes via SSL")); server.enqueue(new MockResponse().setBody("this response comes via SSL"));
@@ -693,7 +696,8 @@ public final class URLConnectionTest {
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
// Attempt RESTRICTED_TLS then fall back to MODERN_TLS. // Attempt RESTRICTED_TLS then fall back to MODERN_TLS.
.connectionSpecs(Arrays.asList(ConnectionSpec.RESTRICTED_TLS, ConnectionSpec.MODERN_TLS)) .connectionSpecs(Arrays.asList(ConnectionSpec.RESTRICTED_TLS, ConnectionSpec.MODERN_TLS))
.sslSocketFactory(suppressTlsFallbackClientSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
suppressTlsFallbackClientSocketFactory(), handshakeCertificates.trustManager())
.build()); .build());
connection = urlFactory.open(server.url("/foo").url()); connection = urlFactory.open(server.url("/foo").url());
@@ -707,8 +711,8 @@ public final class URLConnectionTest {
assertEquals(TlsVersion.TLS_1_2, fallbackRequest.getTlsVersion()); assertEquals(TlsVersion.TLS_1_2, fallbackRequest.getTlsVersion());
} }
@Test public void connectViaHttpsWithSSLFallbackFailuresRecorded() throws Exception { @Test public void connectViaHttpsWithSSLFallbackFailuresRecorded() {
server.useHttps(tlsNode.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
server.enqueue(new MockResponse().setSocketPolicy(FAIL_HANDSHAKE)); server.enqueue(new MockResponse().setSocketPolicy(FAIL_HANDSHAKE));
server.enqueue(new MockResponse().setSocketPolicy(FAIL_HANDSHAKE)); server.enqueue(new MockResponse().setSocketPolicy(FAIL_HANDSHAKE));
@@ -716,7 +720,8 @@ public final class URLConnectionTest {
.dns(new SingleInetAddressDns()) .dns(new SingleInetAddressDns())
.connectionSpecs(Arrays.asList(ConnectionSpec.MODERN_TLS, ConnectionSpec.COMPATIBLE_TLS)) .connectionSpecs(Arrays.asList(ConnectionSpec.MODERN_TLS, ConnectionSpec.COMPATIBLE_TLS))
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
.sslSocketFactory(suppressTlsFallbackClientSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
suppressTlsFallbackClientSocketFactory(), handshakeCertificates.trustManager())
.build()); .build());
connection = urlFactory.open(server.url("/foo").url()); connection = urlFactory.open(server.url("/foo").url());
@@ -735,7 +740,7 @@ public final class URLConnectionTest {
* https://github.com/square/okhttp/issues/515 * https://github.com/square/okhttp/issues/515
*/ */
@Test public void sslFallbackNotUsedWhenRecycledConnectionFails() throws Exception { @Test public void sslFallbackNotUsedWhenRecycledConnectionFails() throws Exception {
server.useHttps(tlsNode.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
server.enqueue(new MockResponse() server.enqueue(new MockResponse()
.setBody("abc") .setBody("abc")
.setSocketPolicy(DISCONNECT_AT_END)); .setSocketPolicy(DISCONNECT_AT_END));
@@ -743,7 +748,8 @@ public final class URLConnectionTest {
urlFactory.setClient(urlFactory.client().newBuilder() urlFactory.setClient(urlFactory.client().newBuilder()
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
.sslSocketFactory(suppressTlsFallbackClientSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
suppressTlsFallbackClientSocketFactory(), handshakeCertificates.trustManager())
.build()); .build());
assertContent("abc", urlFactory.open(server.url("/").url())); assertContent("abc", urlFactory.open(server.url("/").url()));
@@ -769,7 +775,7 @@ public final class URLConnectionTest {
* http://code.google.com/p/android/issues/detail?id=13178 * http://code.google.com/p/android/issues/detail?id=13178
*/ */
@Test public void connectViaHttpsToUntrustedServer() throws Exception { @Test public void connectViaHttpsToUntrustedServer() throws Exception {
server.useHttps(tlsNode.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
server.enqueue(new MockResponse()); // unused server.enqueue(new MockResponse()); // unused
connection = urlFactory.open(server.url("/foo").url()); connection = urlFactory.open(server.url("/foo").url());
@@ -826,7 +832,7 @@ public final class URLConnectionTest {
} }
} }
public void testConnectViaSocketFactory(boolean useHttps) throws IOException { private void testConnectViaSocketFactory(boolean useHttps) throws IOException {
SocketFactory uselessSocketFactory = new SocketFactory() { SocketFactory uselessSocketFactory = new SocketFactory() {
public Socket createSocket() { public Socket createSocket() {
throw new IllegalArgumentException("useless"); throw new IllegalArgumentException("useless");
@@ -851,9 +857,10 @@ public final class URLConnectionTest {
}; };
if (useHttps) { if (useHttps) {
server.useHttps(tlsNode.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
urlFactory.setClient(urlFactory.client().newBuilder() urlFactory.setClient(urlFactory.client().newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
.build()); .build());
} }
@@ -931,12 +938,13 @@ public final class URLConnectionTest {
} }
private void testConnectViaDirectProxyToHttps(ProxyConfig proxyConfig) throws Exception { private void testConnectViaDirectProxyToHttps(ProxyConfig proxyConfig) throws Exception {
server.useHttps(tlsNode.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
server.enqueue(new MockResponse().setBody("this response comes via HTTPS")); server.enqueue(new MockResponse().setBody("this response comes via HTTPS"));
URL url = server.url("/foo").url(); URL url = server.url("/foo").url();
urlFactory.setClient(urlFactory.client().newBuilder() urlFactory.setClient(urlFactory.client().newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
.build()); .build());
connection = proxyConfig.connect(server, urlFactory, url); connection = proxyConfig.connect(server, urlFactory, url);
@@ -970,14 +978,15 @@ public final class URLConnectionTest {
private void testConnectViaHttpProxyToHttps(ProxyConfig proxyConfig) throws Exception { private void testConnectViaHttpProxyToHttps(ProxyConfig proxyConfig) throws Exception {
RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier(); RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier();
server.useHttps(tlsNode.sslSocketFactory(), true); server.useHttps(handshakeCertificates.sslSocketFactory(), true);
server.enqueue( server.enqueue(
new MockResponse().setSocketPolicy(UPGRADE_TO_SSL_AT_END).clearHeaders()); new MockResponse().setSocketPolicy(UPGRADE_TO_SSL_AT_END).clearHeaders());
server.enqueue(new MockResponse().setBody("this response comes via a secure proxy")); server.enqueue(new MockResponse().setBody("this response comes via a secure proxy"));
URL url = new URL("https://android.com/foo"); URL url = new URL("https://android.com/foo");
urlFactory.setClient(urlFactory.client().newBuilder() urlFactory.setClient(urlFactory.client().newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(hostnameVerifier) .hostnameVerifier(hostnameVerifier)
.build()); .build());
connection = proxyConfig.connect(server, urlFactory, url); connection = proxyConfig.connect(server, urlFactory, url);
@@ -999,7 +1008,7 @@ public final class URLConnectionTest {
@Test public void connectViaHttpProxyToHttpsUsingBadProxyAndHttpResponseCache() throws Exception { @Test public void connectViaHttpProxyToHttpsUsingBadProxyAndHttpResponseCache() throws Exception {
initResponseCache(); initResponseCache();
server.useHttps(tlsNode.sslSocketFactory(), true); server.useHttps(handshakeCertificates.sslSocketFactory(), true);
// The inclusion of a body in the response to a CONNECT is key to reproducing b/6754912. // The inclusion of a body in the response to a CONNECT is key to reproducing b/6754912.
MockResponse badProxyResponse = new MockResponse() MockResponse badProxyResponse = new MockResponse()
.setSocketPolicy(UPGRADE_TO_SSL_AT_END) .setSocketPolicy(UPGRADE_TO_SSL_AT_END)
@@ -1011,7 +1020,8 @@ public final class URLConnectionTest {
// failure to fail permanently. // failure to fail permanently.
urlFactory.setClient(urlFactory.client().newBuilder() urlFactory.setClient(urlFactory.client().newBuilder()
.dns(new SingleInetAddressDns()) .dns(new SingleInetAddressDns())
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.connectionSpecs(Util.immutableList(ConnectionSpec.MODERN_TLS)) .connectionSpecs(Util.immutableList(ConnectionSpec.MODERN_TLS))
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
.proxy(server.toProxyAddress()) .proxy(server.toProxyAddress())
@@ -1037,14 +1047,15 @@ public final class URLConnectionTest {
@Test public void proxyConnectIncludesProxyHeadersOnly() throws Exception { @Test public void proxyConnectIncludesProxyHeadersOnly() throws Exception {
RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier(); RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier();
server.useHttps(tlsNode.sslSocketFactory(), true); server.useHttps(handshakeCertificates.sslSocketFactory(), true);
server.enqueue( server.enqueue(
new MockResponse().setSocketPolicy(UPGRADE_TO_SSL_AT_END).clearHeaders()); new MockResponse().setSocketPolicy(UPGRADE_TO_SSL_AT_END).clearHeaders());
server.enqueue(new MockResponse().setBody("encrypted response from the origin server")); server.enqueue(new MockResponse().setBody("encrypted response from the origin server"));
urlFactory.setClient(urlFactory.client().newBuilder() urlFactory.setClient(urlFactory.client().newBuilder()
.proxy(server.toProxyAddress()) .proxy(server.toProxyAddress())
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(hostnameVerifier) .hostnameVerifier(hostnameVerifier)
.build()); .build());
@@ -1069,7 +1080,7 @@ public final class URLConnectionTest {
@Test public void proxyAuthenticateOnConnect() throws Exception { @Test public void proxyAuthenticateOnConnect() throws Exception {
Authenticator.setDefault(new RecordingAuthenticator()); Authenticator.setDefault(new RecordingAuthenticator());
server.useHttps(tlsNode.sslSocketFactory(), true); server.useHttps(handshakeCertificates.sslSocketFactory(), true);
server.enqueue(new MockResponse().setResponseCode(407) server.enqueue(new MockResponse().setResponseCode(407)
.addHeader("Proxy-Authenticate: Basic realm=\"localhost\"")); .addHeader("Proxy-Authenticate: Basic realm=\"localhost\""));
server.enqueue( server.enqueue(
@@ -1079,7 +1090,8 @@ public final class URLConnectionTest {
urlFactory.setClient(urlFactory.client().newBuilder() urlFactory.setClient(urlFactory.client().newBuilder()
.proxyAuthenticator(new JavaNetAuthenticator()) .proxyAuthenticator(new JavaNetAuthenticator())
.proxy(server.toProxyAddress()) .proxy(server.toProxyAddress())
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
.build()); .build());
@@ -1104,14 +1116,15 @@ public final class URLConnectionTest {
// Don't disconnect after building a tunnel with CONNECT // Don't disconnect after building a tunnel with CONNECT
// http://code.google.com/p/android/issues/detail?id=37221 // http://code.google.com/p/android/issues/detail?id=37221
@Test public void proxyWithConnectionClose() throws IOException { @Test public void proxyWithConnectionClose() throws IOException {
server.useHttps(tlsNode.sslSocketFactory(), true); server.useHttps(handshakeCertificates.sslSocketFactory(), true);
server.enqueue( server.enqueue(
new MockResponse().setSocketPolicy(UPGRADE_TO_SSL_AT_END).clearHeaders()); new MockResponse().setSocketPolicy(UPGRADE_TO_SSL_AT_END).clearHeaders());
server.enqueue(new MockResponse().setBody("this response comes via a proxy")); server.enqueue(new MockResponse().setBody("this response comes via a proxy"));
urlFactory.setClient(urlFactory.client().newBuilder() urlFactory.setClient(urlFactory.client().newBuilder()
.proxy(server.toProxyAddress()) .proxy(server.toProxyAddress())
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
.build()); .build());
@@ -1123,7 +1136,7 @@ public final class URLConnectionTest {
} }
@Test public void proxyWithConnectionReuse() throws IOException { @Test public void proxyWithConnectionReuse() throws IOException {
SSLSocketFactory socketFactory = tlsNode.sslSocketFactory(); SSLSocketFactory socketFactory = handshakeCertificates.sslSocketFactory();
RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier(); RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier();
server.useHttps(socketFactory, true); server.useHttps(socketFactory, true);
@@ -1134,7 +1147,7 @@ public final class URLConnectionTest {
urlFactory.setClient(urlFactory.client().newBuilder() urlFactory.setClient(urlFactory.client().newBuilder()
.proxy(server.toProxyAddress()) .proxy(server.toProxyAddress())
.sslSocketFactory(socketFactory, tlsNode.trustManager()) .sslSocketFactory(socketFactory, handshakeCertificates.trustManager())
.hostnameVerifier(hostnameVerifier) .hostnameVerifier(hostnameVerifier)
.build()); .build());
URL url = new URL("https://android.com/foo"); URL url = new URL("https://android.com/foo");
@@ -1163,7 +1176,7 @@ public final class URLConnectionTest {
in.close(); in.close();
} }
@Test public void disconnectDuringConnect_cookieJar() throws Exception { @Test public void disconnectDuringConnect_cookieJar() {
final AtomicReference<HttpURLConnection> connectionHolder = new AtomicReference<>(); final AtomicReference<HttpURLConnection> connectionHolder = new AtomicReference<>();
class DisconnectingCookieJar implements CookieJar { class DisconnectingCookieJar implements CookieJar {
@Override public void saveFromResponse(HttpUrl url, List<Cookie> cookies) { } @Override public void saveFromResponse(HttpUrl url, List<Cookie> cookies) { }
@@ -1199,7 +1212,7 @@ public final class URLConnectionTest {
assertEquals(200, connection.getResponseCode()); assertEquals(200, connection.getResponseCode());
} }
@SuppressWarnings("deprecation") @Test public void defaultRequestProperty() throws Exception { @SuppressWarnings("deprecation") @Test public void defaultRequestProperty() {
URLConnection.setDefaultRequestProperty("X-testSetDefaultRequestProperty", "A"); URLConnection.setDefaultRequestProperty("X-testSetDefaultRequestProperty", "A");
assertNull(URLConnection.getDefaultRequestProperty("X-setDefaultRequestProperty")); assertNull(URLConnection.getDefaultRequestProperty("X-setDefaultRequestProperty"));
} }
@@ -1399,11 +1412,11 @@ public final class URLConnectionTest {
private void testClientConfiguredGzipContentEncodingAndConnectionReuse(TransferKind transferKind, private void testClientConfiguredGzipContentEncodingAndConnectionReuse(TransferKind transferKind,
boolean tls) throws Exception { boolean tls) throws Exception {
if (tls) { if (tls) {
SSLSocketFactory socketFactory = tlsNode.sslSocketFactory(); SSLSocketFactory socketFactory = handshakeCertificates.sslSocketFactory();
RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier(); RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier();
server.useHttps(socketFactory, false); server.useHttps(socketFactory, false);
urlFactory.setClient(urlFactory.client().newBuilder() urlFactory.setClient(urlFactory.client().newBuilder()
.sslSocketFactory(socketFactory, tlsNode.trustManager()) .sslSocketFactory(socketFactory, handshakeCertificates.trustManager())
.hostnameVerifier(hostnameVerifier) .hostnameVerifier(hostnameVerifier)
.build()); .build());
} }
@@ -1719,15 +1732,15 @@ public final class URLConnectionTest {
assertEquals(requestMethod, connection.getRequestMethod()); assertEquals(requestMethod, connection.getRequestMethod());
} }
@Test public void setInvalidRequestMethodLowercase() throws Exception { @Test public void setInvalidRequestMethodLowercase() {
assertInvalidRequestMethod("get"); assertInvalidRequestMethod("get");
} }
@Test public void setInvalidRequestMethodConnect() throws Exception { @Test public void setInvalidRequestMethodConnect() {
assertInvalidRequestMethod("CONNECT"); assertInvalidRequestMethod("CONNECT");
} }
private void assertInvalidRequestMethod(String requestMethod) throws Exception { private void assertInvalidRequestMethod(String requestMethod) {
connection = urlFactory.open(server.url("/").url()); connection = urlFactory.open(server.url("/").url());
try { try {
connection.setRequestMethod(requestMethod); connection.setRequestMethod(requestMethod);
@@ -1761,7 +1774,7 @@ public final class URLConnectionTest {
assertContent("mp3 data", connection); assertContent("mp3 data", connection);
} }
@Test public void cannotSetNegativeFixedLengthStreamingMode() throws Exception { @Test public void cannotSetNegativeFixedLengthStreamingMode() {
connection = urlFactory.open(server.url("/").url()); connection = urlFactory.open(server.url("/").url());
try { try {
connection.setFixedLengthStreamingMode(-2); connection.setFixedLengthStreamingMode(-2);
@@ -1770,7 +1783,7 @@ public final class URLConnectionTest {
} }
} }
@Test public void canSetNegativeChunkedStreamingMode() throws Exception { @Test public void canSetNegativeChunkedStreamingMode() {
connection = urlFactory.open(server.url("/").url()); connection = urlFactory.open(server.url("/").url());
connection.setChunkedStreamingMode(-2); connection.setChunkedStreamingMode(-2);
} }
@@ -1797,7 +1810,7 @@ public final class URLConnectionTest {
} }
} }
@Test public void cannotSetFixedLengthStreamingModeAfterChunkedStreamingMode() throws Exception { @Test public void cannotSetFixedLengthStreamingModeAfterChunkedStreamingMode() {
connection = urlFactory.open(server.url("/").url()); connection = urlFactory.open(server.url("/").url());
connection.setChunkedStreamingMode(1); connection.setChunkedStreamingMode(1);
try { try {
@@ -1807,7 +1820,7 @@ public final class URLConnectionTest {
} }
} }
@Test public void cannotSetChunkedStreamingModeAfterFixedLengthStreamingMode() throws Exception { @Test public void cannotSetChunkedStreamingModeAfterFixedLengthStreamingMode() {
connection = urlFactory.open(server.url("/").url()); connection = urlFactory.open(server.url("/").url());
connection.setFixedLengthStreamingMode(1); connection.setFixedLengthStreamingMode(1);
try { try {
@@ -1830,11 +1843,12 @@ public final class URLConnectionTest {
* http://code.google.com/p/android/issues/detail?id=12860 * http://code.google.com/p/android/issues/detail?id=12860
*/ */
private void testSecureStreamingPost(StreamingMode streamingMode) throws Exception { private void testSecureStreamingPost(StreamingMode streamingMode) throws Exception {
server.useHttps(tlsNode.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
server.enqueue(new MockResponse().setBody("Success!")); server.enqueue(new MockResponse().setBody("Success!"));
urlFactory.setClient(urlFactory.client().newBuilder() urlFactory.setClient(urlFactory.client().newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
.build()); .build());
connection = urlFactory.open(server.url("/").url()); connection = urlFactory.open(server.url("/").url());
@@ -2046,14 +2060,15 @@ public final class URLConnectionTest {
} }
@Test public void redirectedOnHttps() throws Exception { @Test public void redirectedOnHttps() throws Exception {
server.useHttps(tlsNode.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP) server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
.addHeader("Location: /foo") .addHeader("Location: /foo")
.setBody("This page has moved!")); .setBody("This page has moved!"));
server.enqueue(new MockResponse().setBody("This is the new location!")); server.enqueue(new MockResponse().setBody("This is the new location!"));
urlFactory.setClient(urlFactory.client().newBuilder() urlFactory.setClient(urlFactory.client().newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
.build()); .build());
connection = urlFactory.open(server.url("/").url()); connection = urlFactory.open(server.url("/").url());
@@ -2068,14 +2083,15 @@ public final class URLConnectionTest {
} }
@Test public void notRedirectedFromHttpsToHttp() throws Exception { @Test public void notRedirectedFromHttpsToHttp() throws Exception {
server.useHttps(tlsNode.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP) server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
.addHeader("Location: http://anyhost/foo") .addHeader("Location: http://anyhost/foo")
.setBody("This page has moved!")); .setBody("This page has moved!"));
urlFactory.setClient(urlFactory.client().newBuilder() urlFactory.setClient(urlFactory.client().newBuilder()
.followSslRedirects(false) .followSslRedirects(false)
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
.build()); .build());
connection = urlFactory.open(server.url("/").url()); connection = urlFactory.open(server.url("/").url());
@@ -2097,13 +2113,14 @@ public final class URLConnectionTest {
@Test public void redirectedFromHttpsToHttpFollowingProtocolRedirects() throws Exception { @Test public void redirectedFromHttpsToHttpFollowingProtocolRedirects() throws Exception {
server2.enqueue(new MockResponse().setBody("This is insecure HTTP!")); server2.enqueue(new MockResponse().setBody("This is insecure HTTP!"));
server.useHttps(tlsNode.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP) server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
.addHeader("Location: " + server2.url("/").url()) .addHeader("Location: " + server2.url("/").url())
.setBody("This page has moved!")); .setBody("This page has moved!"));
urlFactory.setClient(urlFactory.client().newBuilder() urlFactory.setClient(urlFactory.client().newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
.followSslRedirects(true) .followSslRedirects(true)
.build()); .build());
@@ -2117,7 +2134,7 @@ public final class URLConnectionTest {
} }
@Test public void redirectedFromHttpToHttpsFollowingProtocolRedirects() throws Exception { @Test public void redirectedFromHttpToHttpsFollowingProtocolRedirects() throws Exception {
server2.useHttps(tlsNode.sslSocketFactory(), false); server2.useHttps(handshakeCertificates.sslSocketFactory(), false);
server2.enqueue(new MockResponse().setBody("This is secure HTTPS!")); server2.enqueue(new MockResponse().setBody("This is secure HTTPS!"));
server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP) server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
@@ -2125,7 +2142,8 @@ public final class URLConnectionTest {
.setBody("This page has moved!")); .setBody("This page has moved!"));
urlFactory.setClient(urlFactory.client().newBuilder() urlFactory.setClient(urlFactory.client().newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
.followSslRedirects(true) .followSslRedirects(true)
.build()); .build());
@@ -2144,11 +2162,12 @@ public final class URLConnectionTest {
private void redirectToAnotherOriginServer(boolean https) throws Exception { private void redirectToAnotherOriginServer(boolean https) throws Exception {
if (https) { if (https) {
server.useHttps(tlsNode.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
server2.useHttps(tlsNode.sslSocketFactory(), false); server2.useHttps(handshakeCertificates.sslSocketFactory(), false);
server2.setProtocolNegotiationEnabled(false); server2.setProtocolNegotiationEnabled(false);
urlFactory.setClient(urlFactory.client().newBuilder() urlFactory.setClient(urlFactory.client().newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
.build()); .build());
} }
@@ -2425,7 +2444,7 @@ public final class URLConnectionTest {
@Test public void httpsWithCustomTrustManager() throws Exception { @Test public void httpsWithCustomTrustManager() throws Exception {
RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier(); RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier();
RecordingTrustManager trustManager = new RecordingTrustManager(tlsNode.trustManager()); RecordingTrustManager trustManager = new RecordingTrustManager(handshakeCertificates.trustManager());
SSLContext sslContext = Platform.get().getSSLContext(); SSLContext sslContext = Platform.get().getSSLContext();
sslContext.init(null, new TrustManager[] { trustManager }, null); sslContext.init(null, new TrustManager[] { trustManager }, null);
@@ -2433,7 +2452,7 @@ public final class URLConnectionTest {
.hostnameVerifier(hostnameVerifier) .hostnameVerifier(hostnameVerifier)
.sslSocketFactory(sslContext.getSocketFactory(), trustManager) .sslSocketFactory(sslContext.getSocketFactory(), trustManager)
.build()); .build());
server.useHttps(tlsNode.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
server.enqueue(new MockResponse().setBody("ABC")); server.enqueue(new MockResponse().setBody("ABC"));
server.enqueue(new MockResponse().setBody("DEF")); server.enqueue(new MockResponse().setBody("DEF"));
server.enqueue(new MockResponse().setBody("GHI")); server.enqueue(new MockResponse().setBody("GHI"));
@@ -2643,7 +2662,7 @@ public final class URLConnectionTest {
assertEquals(0, server.takeRequest().getSequenceNumber()); assertEquals(0, server.takeRequest().getSequenceNumber());
} }
@Test public void responseCodeDisagreesWithHeaders() throws Exception { @Test public void responseCodeDisagreesWithHeaders() {
server.enqueue(new MockResponse() server.enqueue(new MockResponse()
.setResponseCode(HttpURLConnection.HTTP_NO_CONTENT) .setResponseCode(HttpURLConnection.HTTP_NO_CONTENT)
.setBody("This body is not allowed!")); .setBody("This body is not allowed!"));
@@ -2709,7 +2728,7 @@ public final class URLConnectionTest {
} }
} }
@Test public void getHeadersThrows() throws IOException { @Test public void getHeadersThrows() {
server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AT_START)); server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AT_START));
connection = urlFactory.open(server.url("/").url()); connection = urlFactory.open(server.url("/").url());
@@ -3080,7 +3099,7 @@ public final class URLConnectionTest {
assertEquals("", connection.getHeaderField("A")); assertEquals("", connection.getHeaderField("A"));
} }
@Test public void emptyRequestHeaderNameIsStrict() throws Exception { @Test public void emptyRequestHeaderNameIsStrict() {
server.enqueue(new MockResponse().setBody("body")); server.enqueue(new MockResponse().setBody("body"));
connection = urlFactory.open(server.url("/").url()); connection = urlFactory.open(server.url("/").url());
try { try {
@@ -3100,7 +3119,7 @@ public final class URLConnectionTest {
connection.getInputStream().close(); connection.getInputStream().close();
} }
@Test public void requestHeaderValidationIsStrict() throws Exception { @Test public void requestHeaderValidationIsStrict() {
connection = urlFactory.open(server.url("/").url()); connection = urlFactory.open(server.url("/").url());
try { try {
connection.addRequestProperty("a\tb", "Value"); connection.addRequestProperty("a\tb", "Value");
@@ -3383,12 +3402,12 @@ public final class URLConnectionTest {
} }
@Test public void testNoSslFallback() throws Exception { @Test public void testNoSslFallback() throws Exception {
server.useHttps(tlsNode.sslSocketFactory(), false /* tunnelProxy */); server.useHttps(handshakeCertificates.sslSocketFactory(), false /* tunnelProxy */);
server.enqueue(new MockResponse().setSocketPolicy(FAIL_HANDSHAKE)); server.enqueue(new MockResponse().setSocketPolicy(FAIL_HANDSHAKE));
server.enqueue(new MockResponse().setBody("Response that would have needed fallbacks")); server.enqueue(new MockResponse().setBody("Response that would have needed fallbacks"));
HttpsURLConnection connection = (HttpsURLConnection) server.url("/").url().openConnection(); HttpsURLConnection connection = (HttpsURLConnection) server.url("/").url().openConnection();
connection.setSSLSocketFactory(tlsNode.sslSocketFactory()); connection.setSSLSocketFactory(handshakeCertificates.sslSocketFactory());
try { try {
connection.getInputStream(); connection.getInputStream();
fail(); fail();
@@ -3429,7 +3448,7 @@ public final class URLConnectionTest {
} }
@Test public void nullSSLSocketFactory_throws() throws Exception { @Test public void nullSSLSocketFactory_throws() throws Exception {
server.useHttps(tlsNode.sslSocketFactory(), false /* tunnelProxy */); server.useHttps(handshakeCertificates.sslSocketFactory(), false /* tunnelProxy */);
HttpsURLConnection connection = (HttpsURLConnection) server.url("/").url().openConnection(); HttpsURLConnection connection = (HttpsURLConnection) server.url("/").url().openConnection();
try { try {
connection.setSSLSocketFactory(null); connection.setSSLSocketFactory(null);
@@ -3510,7 +3529,7 @@ public final class URLConnectionTest {
@Test public void interceptorsNotInvoked() throws Exception { @Test public void interceptorsNotInvoked() throws Exception {
Interceptor interceptor = new Interceptor() { Interceptor interceptor = new Interceptor() {
@Override public Response intercept(Chain chain) throws IOException { @Override public Response intercept(Chain chain) {
throw new AssertionError(); throw new AssertionError();
} }
}; };
@@ -3578,14 +3597,14 @@ public final class URLConnectionTest {
testInstanceFollowsRedirects("https://www.google.com/"); testInstanceFollowsRedirects("https://www.google.com/");
} }
@Test public void setSslSocketFactoryFailsOnJdk9() throws Exception { @Test public void setSslSocketFactoryFailsOnJdk9() {
assumeTrue(getPlatform().equals("jdk9")); assumeTrue(getPlatform().equals("jdk9"));
enableProtocol(Protocol.HTTP_2); enableProtocol(Protocol.HTTP_2);
URL url = server.url("/").url(); URL url = server.url("/").url();
HttpsURLConnection connection = (HttpsURLConnection) urlFactory.open(url); HttpsURLConnection connection = (HttpsURLConnection) urlFactory.open(url);
try { try {
connection.setSSLSocketFactory(tlsNode.sslSocketFactory()); connection.setSSLSocketFactory(handshakeCertificates.sslSocketFactory());
fail(); fail();
} catch (UnsupportedOperationException expected) { } catch (UnsupportedOperationException expected) {
} }
@@ -3735,8 +3754,7 @@ public final class URLConnectionTest {
enum TransferKind { enum TransferKind {
CHUNKED() { CHUNKED() {
@Override void setBody(MockResponse response, Buffer content, int chunkSize) @Override void setBody(MockResponse response, Buffer content, int chunkSize) {
throws IOException {
response.setChunkedBody(content, chunkSize); response.setChunkedBody(content, chunkSize);
} }
@@ -3776,8 +3794,7 @@ public final class URLConnectionTest {
enum ProxyConfig { enum ProxyConfig {
NO_PROXY() { NO_PROXY() {
@Override public HttpURLConnection connect( @Override public HttpURLConnection connect(
MockWebServer server, OkUrlFactory streamHandlerFactory, URL url) MockWebServer server, OkUrlFactory streamHandlerFactory, URL url) {
throws IOException {
streamHandlerFactory.setClient(streamHandlerFactory.client().newBuilder() streamHandlerFactory.setClient(streamHandlerFactory.client().newBuilder()
.proxy(Proxy.NO_PROXY) .proxy(Proxy.NO_PROXY)
.build()); .build());
@@ -3787,8 +3804,7 @@ public final class URLConnectionTest {
CREATE_ARG() { CREATE_ARG() {
@Override public HttpURLConnection connect( @Override public HttpURLConnection connect(
MockWebServer server, OkUrlFactory streamHandlerFactory, URL url) MockWebServer server, OkUrlFactory streamHandlerFactory, URL url) {
throws IOException {
streamHandlerFactory.setClient(streamHandlerFactory.client().newBuilder() streamHandlerFactory.setClient(streamHandlerFactory.client().newBuilder()
.proxy(server.toProxyAddress()) .proxy(server.toProxyAddress())
.build()); .build());
@@ -3798,8 +3814,7 @@ public final class URLConnectionTest {
PROXY_SYSTEM_PROPERTY() { PROXY_SYSTEM_PROPERTY() {
@Override public HttpURLConnection connect( @Override public HttpURLConnection connect(
MockWebServer server, OkUrlFactory streamHandlerFactory, URL url) MockWebServer server, OkUrlFactory streamHandlerFactory, URL url) {
throws IOException {
System.setProperty("proxyHost", server.getHostName()); System.setProperty("proxyHost", server.getHostName());
System.setProperty("proxyPort", Integer.toString(server.getPort())); System.setProperty("proxyPort", Integer.toString(server.getPort()));
return streamHandlerFactory.open(url); return streamHandlerFactory.open(url);
@@ -3808,8 +3823,7 @@ public final class URLConnectionTest {
HTTP_PROXY_SYSTEM_PROPERTY() { HTTP_PROXY_SYSTEM_PROPERTY() {
@Override public HttpURLConnection connect( @Override public HttpURLConnection connect(
MockWebServer server, OkUrlFactory streamHandlerFactory, URL url) MockWebServer server, OkUrlFactory streamHandlerFactory, URL url) {
throws IOException {
System.setProperty("http.proxyHost", server.getHostName()); System.setProperty("http.proxyHost", server.getHostName());
System.setProperty("http.proxyPort", Integer.toString(server.getPort())); System.setProperty("http.proxyPort", Integer.toString(server.getPort()));
return streamHandlerFactory.open(url); return streamHandlerFactory.open(url);
@@ -3818,8 +3832,7 @@ public final class URLConnectionTest {
HTTPS_PROXY_SYSTEM_PROPERTY() { HTTPS_PROXY_SYSTEM_PROPERTY() {
@Override public HttpURLConnection connect( @Override public HttpURLConnection connect(
MockWebServer server, OkUrlFactory streamHandlerFactory, URL url) MockWebServer server, OkUrlFactory streamHandlerFactory, URL url) {
throws IOException {
System.setProperty("https.proxyHost", server.getHostName()); System.setProperty("https.proxyHost", server.getHostName());
System.setProperty("https.proxyPort", Integer.toString(server.getPort())); System.setProperty("https.proxyPort", Integer.toString(server.getPort()));
return streamHandlerFactory.open(url); return streamHandlerFactory.open(url);
@@ -3835,7 +3848,7 @@ public final class URLConnectionTest {
private final List<String> calls = new ArrayList<>(); private final List<String> calls = new ArrayList<>();
private final X509TrustManager delegate; private final X509TrustManager delegate;
public RecordingTrustManager(X509TrustManager delegate) { RecordingTrustManager(X509TrustManager delegate) {
this.delegate = delegate; this.delegate = delegate;
} }
@@ -3843,13 +3856,11 @@ public final class URLConnectionTest {
return delegate.getAcceptedIssuers(); return delegate.getAcceptedIssuers();
} }
public void checkClientTrusted(X509Certificate[] chain, String authType) public void checkClientTrusted(X509Certificate[] chain, String authType) {
throws CertificateException {
calls.add("checkClientTrusted " + certificatesToString(chain)); calls.add("checkClientTrusted " + certificatesToString(chain));
} }
public void checkServerTrusted(X509Certificate[] chain, String authType) public void checkServerTrusted(X509Certificate[] chain, String authType) {
throws CertificateException {
calls.add("checkServerTrusted " + certificatesToString(chain)); calls.add("checkServerTrusted " + certificatesToString(chain));
} }
@@ -3868,11 +3879,12 @@ public final class URLConnectionTest {
*/ */
private void enableProtocol(Protocol protocol) { private void enableProtocol(Protocol protocol) {
urlFactory.setClient(urlFactory.client().newBuilder() urlFactory.setClient(urlFactory.client().newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
.protocols(Arrays.asList(protocol, Protocol.HTTP_1_1)) .protocols(Arrays.asList(protocol, Protocol.HTTP_1_1))
.build()); .build());
server.useHttps(tlsNode.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
server.setProtocolNegotiationEnabled(true); server.setProtocolNegotiationEnabled(true);
server.setProtocols(urlFactory.client().protocols()); server.setProtocols(urlFactory.client().protocols());
} }
@@ -3883,7 +3895,7 @@ public final class URLConnectionTest {
* for details. * for details.
*/ */
private FallbackTestClientSocketFactory suppressTlsFallbackClientSocketFactory() { private FallbackTestClientSocketFactory suppressTlsFallbackClientSocketFactory() {
return new FallbackTestClientSocketFactory(tlsNode.sslSocketFactory()); return new FallbackTestClientSocketFactory(handshakeCertificates.sslSocketFactory());
} }
private String getPlatform() { private String getPlatform() {

View File

@@ -25,7 +25,7 @@ import javax.net.ssl.SSLSocket;
import okhttp3.ConnectionSpec; import okhttp3.ConnectionSpec;
import okhttp3.TlsVersion; import okhttp3.TlsVersion;
import okhttp3.internal.Internal; import okhttp3.internal.Internal;
import okhttp3.tls.TlsNode; import okhttp3.tls.HandshakeCertificates;
import org.junit.Test; import org.junit.Test;
import static okhttp3.tls.internal.TlsUtil.localhost; import static okhttp3.tls.internal.TlsUtil.localhost;
@@ -41,7 +41,7 @@ public class ConnectionSpecSelectorTest {
public static final SSLHandshakeException RETRYABLE_EXCEPTION = new SSLHandshakeException( public static final SSLHandshakeException RETRYABLE_EXCEPTION = new SSLHandshakeException(
"Simulated handshake exception"); "Simulated handshake exception");
private TlsNode tlsNode = localhost(); private HandshakeCertificates handshakeCertificates = localhost();
@Test @Test
public void nonRetryableIOException() throws Exception { public void nonRetryableIOException() throws Exception {
@@ -122,7 +122,7 @@ public class ConnectionSpecSelectorTest {
} }
private SSLSocket createSocketWithEnabledProtocols(TlsVersion... tlsVersions) throws IOException { private SSLSocket createSocketWithEnabledProtocols(TlsVersion... tlsVersions) throws IOException {
SSLSocket socket = (SSLSocket) tlsNode.sslSocketFactory().createSocket(); SSLSocket socket = (SSLSocket) handshakeCertificates.sslSocketFactory().createSocket();
socket.setEnabledProtocols(javaNames(tlsVersions)); socket.setEnabledProtocols(javaNames(tlsVersions));
return socket; return socket;
} }

View File

@@ -39,7 +39,7 @@ import okhttp3.Protocol;
import okhttp3.Route; import okhttp3.Route;
import okhttp3.internal.Util; import okhttp3.internal.Util;
import okhttp3.internal.http.RecordingProxySelector; import okhttp3.internal.http.RecordingProxySelector;
import okhttp3.tls.TlsNode; import okhttp3.tls.HandshakeCertificates;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@@ -69,8 +69,8 @@ public final class RouteSelectorTest {
private int uriPort = 1003; private int uriPort = 1003;
private SocketFactory socketFactory; private SocketFactory socketFactory;
private final TlsNode tlsNode = localhost(); private final HandshakeCertificates handshakeCertificates = localhost();
private final SSLSocketFactory sslSocketFactory = tlsNode.sslSocketFactory(); private final SSLSocketFactory sslSocketFactory = handshakeCertificates.sslSocketFactory();
private HostnameVerifier hostnameVerifier; private HostnameVerifier hostnameVerifier;
private final Authenticator authenticator = Authenticator.NONE; private final Authenticator authenticator = Authenticator.NONE;

View File

@@ -61,7 +61,7 @@ import okhttp3.mockwebserver.PushPromise;
import okhttp3.mockwebserver.QueueDispatcher; import okhttp3.mockwebserver.QueueDispatcher;
import okhttp3.mockwebserver.RecordedRequest; import okhttp3.mockwebserver.RecordedRequest;
import okhttp3.mockwebserver.SocketPolicy; import okhttp3.mockwebserver.SocketPolicy;
import okhttp3.tls.TlsNode; import okhttp3.tls.HandshakeCertificates;
import okio.Buffer; import okio.Buffer;
import okio.BufferedSink; import okio.BufferedSink;
import okio.GzipSink; import okio.GzipSink;
@@ -93,7 +93,7 @@ import static org.junit.Assume.assumeTrue;
@RunWith(Parameterized.class) @RunWith(Parameterized.class)
public final class HttpOverHttp2Test { public final class HttpOverHttp2Test {
private static final Logger http2Logger = Logger.getLogger(Http2.class.getName()); private static final Logger http2Logger = Logger.getLogger(Http2.class.getName());
private static final TlsNode tlsNode = localhost(); private static final HandshakeCertificates handshakeCertificates = localhost();
@Parameters(name = "{0}") @Parameters(name = "{0}")
public static Collection<Protocol> data() { public static Collection<Protocol> data() {
@@ -126,16 +126,17 @@ public final class HttpOverHttp2Test {
return defaultClient().newBuilder() return defaultClient().newBuilder()
.protocols(Arrays.asList(Protocol.HTTP_2, Protocol.HTTP_1_1)) .protocols(Arrays.asList(Protocol.HTTP_2, Protocol.HTTP_1_1))
.dns(new SingleInetAddressDns()) .dns(new SingleInetAddressDns())
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
.build(); .build();
} }
@Before public void setUp() throws Exception { @Before public void setUp() {
if (protocol == Protocol.H2_PRIOR_KNOWLEDGE) { if (protocol == Protocol.H2_PRIOR_KNOWLEDGE) {
server.setProtocols(Arrays.asList(Protocol.H2_PRIOR_KNOWLEDGE)); server.setProtocols(Arrays.asList(Protocol.H2_PRIOR_KNOWLEDGE));
} else { } else {
server.useHttps(tlsNode.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
} }
cache = new Cache(tempDir.getRoot(), Integer.MAX_VALUE); cache = new Cache(tempDir.getRoot(), Integer.MAX_VALUE);
@@ -145,7 +146,7 @@ public final class HttpOverHttp2Test {
http2Logger.setLevel(Level.FINE); http2Logger.setLevel(Level.FINE);
} }
@After public void tearDown() throws Exception { @After public void tearDown() {
Authenticator.setDefault(null); Authenticator.setDefault(null);
http2Logger.removeHandler(http2Handler); http2Logger.removeHandler(http2Handler);
http2Logger.setLevel(previousLevel); http2Logger.setLevel(previousLevel);
@@ -225,7 +226,7 @@ public final class HttpOverHttp2Test {
return MediaType.get("text/plain; charset=utf-8"); return MediaType.get("text/plain; charset=utf-8");
} }
@Override public long contentLength() throws IOException { @Override public long contentLength() {
return postBytes.length; return postBytes.length;
} }
@@ -256,7 +257,7 @@ public final class HttpOverHttp2Test {
return MediaType.get("text/plain; charset=utf-8"); return MediaType.get("text/plain; charset=utf-8");
} }
@Override public long contentLength() throws IOException { @Override public long contentLength() {
return postBytes.length; return postBytes.length;
} }
@@ -1314,7 +1315,7 @@ public final class HttpOverHttp2Test {
@Test public void concurrentHttp2ConnectionsDeduplicated() throws Exception { @Test public void concurrentHttp2ConnectionsDeduplicated() throws Exception {
assumeTrue(protocol == Protocol.HTTP_2); assumeTrue(protocol == Protocol.HTTP_2);
server.useHttps(tlsNode.sslSocketFactory(), true); server.useHttps(handshakeCertificates.sslSocketFactory(), true);
// Force a fresh connection pool for the test. // Force a fresh connection pool for the test.
client.connectionPool().evictAll(); client.connectionPool().evictAll();

View File

@@ -38,7 +38,7 @@ import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.SocketPolicy; import okhttp3.mockwebserver.SocketPolicy;
import okhttp3.tls.HeldCertificate; import okhttp3.tls.HeldCertificate;
import okhttp3.tls.TlsNode; import okhttp3.tls.HandshakeCertificates;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
@@ -74,19 +74,20 @@ public final class CertificatePinnerChainValidationTest {
CertificatePinner certificatePinner = new CertificatePinner.Builder() CertificatePinner certificatePinner = new CertificatePinner.Builder()
.add(server.getHostName(), CertificatePinner.pin(rootCa.certificate())) .add(server.getHostName(), CertificatePinner.pin(rootCa.certificate()))
.build(); .build();
TlsNode tlsNode = new TlsNode.Builder() HandshakeCertificates handshakeCertificates = new HandshakeCertificates.Builder()
.addTrustedCertificate(rootCa.certificate()) .addTrustedCertificate(rootCa.certificate())
.build(); .build();
OkHttpClient client = defaultClient().newBuilder() OkHttpClient client = defaultClient().newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
.certificatePinner(certificatePinner) .certificatePinner(certificatePinner)
.build(); .build();
TlsNode serverTlsNode = new TlsNode.Builder() HandshakeCertificates serverHandshakeCertificates = new HandshakeCertificates.Builder()
.heldCertificate(certificate, intermediateCa.certificate()) .heldCertificate(certificate, intermediateCa.certificate())
.build(); .build();
server.useHttps(serverTlsNode.sslSocketFactory(), false); server.useHttps(serverHandshakeCertificates.sslSocketFactory(), false);
// The request should complete successfully. // The request should complete successfully.
server.enqueue(new MockResponse() server.enqueue(new MockResponse()
@@ -130,19 +131,20 @@ public final class CertificatePinnerChainValidationTest {
CertificatePinner certificatePinner = new CertificatePinner.Builder() CertificatePinner certificatePinner = new CertificatePinner.Builder()
.add(server.getHostName(), CertificatePinner.pin(intermediateCa.certificate())) .add(server.getHostName(), CertificatePinner.pin(intermediateCa.certificate()))
.build(); .build();
TlsNode tlsNode = new TlsNode.Builder() HandshakeCertificates handshakeCertificates = new HandshakeCertificates.Builder()
.addTrustedCertificate(rootCa.certificate()) .addTrustedCertificate(rootCa.certificate())
.build(); .build();
OkHttpClient client = defaultClient().newBuilder() OkHttpClient client = defaultClient().newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
.certificatePinner(certificatePinner) .certificatePinner(certificatePinner)
.build(); .build();
TlsNode serverTlsNode = new TlsNode.Builder() HandshakeCertificates serverHandshakeCertificates = new HandshakeCertificates.Builder()
.heldCertificate(certificate, intermediateCa.certificate()) .heldCertificate(certificate, intermediateCa.certificate())
.build(); .build();
server.useHttps(serverTlsNode.sslSocketFactory(), false); server.useHttps(serverHandshakeCertificates.sslSocketFactory(), false);
// The request should complete successfully. // The request should complete successfully.
server.enqueue(new MockResponse() server.enqueue(new MockResponse()
@@ -195,12 +197,12 @@ public final class CertificatePinnerChainValidationTest {
CertificatePinner certificatePinner = new CertificatePinner.Builder() CertificatePinner certificatePinner = new CertificatePinner.Builder()
.add(server.getHostName(), CertificatePinner.pin(goodCertificate.certificate())) .add(server.getHostName(), CertificatePinner.pin(goodCertificate.certificate()))
.build(); .build();
TlsNode tlsNode = new TlsNode.Builder() HandshakeCertificates handshakeCertificates = new HandshakeCertificates.Builder()
.addTrustedCertificate(rootCa.certificate()) .addTrustedCertificate(rootCa.certificate())
.build(); .build();
OkHttpClient client = defaultClient().newBuilder() OkHttpClient client = defaultClient().newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), .sslSocketFactory(
tlsNode.trustManager()) handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
.certificatePinner(certificatePinner) .certificatePinner(certificatePinner)
.build(); .build();
@@ -270,12 +272,13 @@ public final class CertificatePinnerChainValidationTest {
CertificatePinner certificatePinner = new CertificatePinner.Builder() CertificatePinner certificatePinner = new CertificatePinner.Builder()
.add(server.getHostName(), CertificatePinner.pin(goodIntermediateCa.certificate())) .add(server.getHostName(), CertificatePinner.pin(goodIntermediateCa.certificate()))
.build(); .build();
TlsNode tlsNode = new TlsNode.Builder() HandshakeCertificates handshakeCertificates = new HandshakeCertificates.Builder()
.addTrustedCertificate(rootCa.certificate()) .addTrustedCertificate(rootCa.certificate())
.addTrustedCertificate(compromisedRootCa.certificate()) .addTrustedCertificate(compromisedRootCa.certificate())
.build(); .build();
OkHttpClient client = defaultClient().newBuilder() OkHttpClient client = defaultClient().newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
.certificatePinner(certificatePinner) .certificatePinner(certificatePinner)
.build(); .build();

View File

@@ -36,7 +36,7 @@ import okhttp3.Response;
import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.MockWebServer;
import okhttp3.tls.HeldCertificate; import okhttp3.tls.HeldCertificate;
import okhttp3.tls.TlsNode; import okhttp3.tls.HandshakeCertificates;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
@@ -236,16 +236,17 @@ public final class ClientAuthTest {
private OkHttpClient buildClient( private OkHttpClient buildClient(
HeldCertificate heldCertificate, X509Certificate... intermediates) { HeldCertificate heldCertificate, X509Certificate... intermediates) {
TlsNode.Builder tlsNodeBuilder = new TlsNode.Builder() HandshakeCertificates.Builder builder = new HandshakeCertificates.Builder()
.addTrustedCertificate(serverRootCa.certificate()); .addTrustedCertificate(serverRootCa.certificate());
if (heldCertificate != null) { if (heldCertificate != null) {
tlsNodeBuilder.heldCertificate(heldCertificate, intermediates); builder.heldCertificate(heldCertificate, intermediates);
} }
TlsNode tlsNode = tlsNodeBuilder.build(); HandshakeCertificates handshakeCertificates = builder.build();
return defaultClient().newBuilder() return defaultClient().newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.build(); .build();
} }

View File

@@ -39,7 +39,7 @@ import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest; import okhttp3.mockwebserver.RecordedRequest;
import okhttp3.mockwebserver.SocketPolicy; import okhttp3.mockwebserver.SocketPolicy;
import okhttp3.tls.TlsNode; import okhttp3.tls.HandshakeCertificates;
import okio.Buffer; import okio.Buffer;
import okio.ByteString; import okio.ByteString;
import org.junit.After; import org.junit.After;
@@ -60,7 +60,7 @@ import static org.junit.Assert.fail;
public final class WebSocketHttpTest { public final class WebSocketHttpTest {
@Rule public final MockWebServer webServer = new MockWebServer(); @Rule public final MockWebServer webServer = new MockWebServer();
private final TlsNode tlsNode = localhost(); private final HandshakeCertificates handshakeCertificates = localhost();
private final WebSocketRecorder clientListener = new WebSocketRecorder("client"); private final WebSocketRecorder clientListener = new WebSocketRecorder("client");
private final WebSocketRecorder serverListener = new WebSocketRecorder("server"); private final WebSocketRecorder serverListener = new WebSocketRecorder("server");
private final Random random = new Random(0); private final Random random = new Random(0);
@@ -480,9 +480,10 @@ public final class WebSocketHttpTest {
} }
@Test public void wssScheme() { @Test public void wssScheme() {
webServer.useHttps(tlsNode.sslSocketFactory(), false); webServer.useHttps(handshakeCertificates.sslSocketFactory(), false);
client = client.newBuilder() client = client.newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
.build(); .build();
@@ -490,9 +491,10 @@ public final class WebSocketHttpTest {
} }
@Test public void httpsScheme() { @Test public void httpsScheme() {
webServer.useHttps(tlsNode.sslSocketFactory(), false); webServer.useHttps(handshakeCertificates.sslSocketFactory(), false);
client = client.newBuilder() client = client.newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
.build(); .build();

View File

@@ -44,15 +44,15 @@ import static okhttp3.tls.internal.TlsUtil.newTrustManager;
* <p>To perform server authentication: * <p>To perform server authentication:
* *
* <ul> * <ul>
* <li>The server's TLS node must have a {@linkplain HeldCertificate held certificate} (a * <li>The server's handshake certificates must have a {@linkplain HeldCertificate held
* certificate and its private key). The certificate's subject alternative names must match * certificate} (a certificate and its private key). The certificate's subject alternative
* the server's hostname. The server must also have is a (possibly-empty) chain of * names must match the server's hostname. The server must also have is a (possibly-empty)
* intermediate certificates to establish trust from a root certificate to the server's * chain of intermediate certificates to establish trust from a root certificate to the
* certificate. The root certificate is not included in this chain. * server's certificate. The root certificate is not included in this chain.
* <li>The client's TLS node must include a set of trusted root certificates. They will be used to * <li>The client's handshake certificates must include a set of trusted root certificates. They
* authenticate the server's certificate chain. Typically this is a set of well-known root * will be used to authenticate the server's certificate chain. Typically this is a set of
* certificates that is distributed with the HTTP client or its platform. It may be augmented * well-known root certificates that is distributed with the HTTP client or its platform. It
* by certificates private to an organization or service. * may be augmented by certificates private to an organization or service.
* </ul> * </ul>
* *
* <h3>Client Authentication</h3> * <h3>Client Authentication</h3>
@@ -63,21 +63,22 @@ import static okhttp3.tls.internal.TlsUtil.newTrustManager;
* <p>To perform client authentication: * <p>To perform client authentication:
* *
* <ul> * <ul>
* <li>The client's TLS node must have a {@linkplain HeldCertificate held certificate} (a * <li>The client's handshake certificates must have a {@linkplain HeldCertificate held
* certificate and its private key). The client must also have a (possibly-empty) chain of * certificate} (a certificate and its private key). The client must also have a
* intermediate certificates to establish trust from a root certificate to the client's * (possibly-empty) chain of intermediate certificates to establish trust from a root
* certificate. The root certificate is not included in this chain. * certificate to the client's certificate. The root certificate is not included in this
* <li>The server's TLS node must include a set of trusted root certificates. They will be used to * chain.
* authenticate the client's certificate chain. Typically this is not the same set of root * <li>The server's handshake certificates must include a set of trusted root certificates. They
* certificates used in server authentication. Instead it will be a small set of roots * will be used to authenticate the client's certificate chain. Typically this is not the same
* private to an organization or service. * set of root certificates used in server authentication. Instead it will be a small set of
* roots private to an organization or service.
* </ul> * </ul>
*/ */
public final class TlsNode { public final class HandshakeCertificates {
private final X509KeyManager keyManager; private final X509KeyManager keyManager;
private final X509TrustManager trustManager; private final X509TrustManager trustManager;
private TlsNode(X509KeyManager keyManager, X509TrustManager trustManager) { private HandshakeCertificates(X509KeyManager keyManager, X509TrustManager trustManager) {
this.keyManager = keyManager; this.keyManager = keyManager;
this.trustManager = trustManager; this.trustManager = trustManager;
} }
@@ -113,8 +114,8 @@ public final class TlsNode {
/** /**
* Configure the certificate chain to use when being authenticated. The first certificate is * Configure the certificate chain to use when being authenticated. The first certificate is
* the nodes' certificate, further certificates are included in the handshake so the peer * the held certificate, further certificates are included in the handshake so the peer can
* can build a trusted path to a trusted root certificate. * build a trusted path to a trusted root certificate.
* *
* <p>The chain should include all intermediate certificates but does not need the root * <p>The chain should include all intermediate certificates but does not need the root
* certificate that we expect to be known by the remote peer. The peer already has that * certificate that we expect to be known by the remote peer. The peer already has that
@@ -136,11 +137,11 @@ public final class TlsNode {
return this; return this;
} }
public TlsNode build() { public HandshakeCertificates build() {
try { try {
X509KeyManager keyManager = newKeyManager(null, heldCertificate, intermediates); X509KeyManager keyManager = newKeyManager(null, heldCertificate, intermediates);
X509TrustManager trustManager = newTrustManager(null, trustedCertificates); X509TrustManager trustManager = newTrustManager(null, trustedCertificates);
return new TlsNode(keyManager, trustManager); return new HandshakeCertificates(keyManager, trustManager);
} catch (GeneralSecurityException gse) { } catch (GeneralSecurityException gse) {
throw new AssertionError(gse); throw new AssertionError(gse);
} }

View File

@@ -32,17 +32,17 @@ import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509KeyManager; import javax.net.ssl.X509KeyManager;
import javax.net.ssl.X509TrustManager; import javax.net.ssl.X509TrustManager;
import okhttp3.tls.HeldCertificate; import okhttp3.tls.HeldCertificate;
import okhttp3.tls.TlsNode; import okhttp3.tls.HandshakeCertificates;
public final class TlsUtil { public final class TlsUtil {
public static final char[] password = "password".toCharArray(); public static final char[] password = "password".toCharArray();
private static TlsNode localhost; // Lazily initialized. private static HandshakeCertificates localhost; // Lazily initialized.
private TlsUtil() { private TlsUtil() {
} }
/** Returns an SSL client for this host's localhost address. */ /** Returns an SSL client for this host's localhost address. */
public static synchronized TlsNode localhost() { public static synchronized HandshakeCertificates localhost() {
if (localhost != null) return localhost; if (localhost != null) return localhost;
try { try {
@@ -52,7 +52,7 @@ public final class TlsUtil {
.addSubjectAlternativeName(InetAddress.getByName("localhost").getCanonicalHostName()) .addSubjectAlternativeName(InetAddress.getByName("localhost").getCanonicalHostName())
.build(); .build();
localhost = new TlsNode.Builder() localhost = new HandshakeCertificates.Builder()
.heldCertificate(heldCertificate) .heldCertificate(heldCertificate)
.addTrustedCertificate(heldCertificate.certificate()) .addTrustedCertificate(heldCertificate.certificate())
.build(); .build();

View File

@@ -38,7 +38,7 @@ import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
public final class TlsNodeTest { public final class HandshakeCertificatesTest {
private ExecutorService executorService; private ExecutorService executorService;
private ServerSocket serverSocket; private ServerSocket serverSocket;
@@ -74,12 +74,12 @@ public final class TlsNodeTest {
.issuedBy(serverIntermediate) .issuedBy(serverIntermediate)
.build(); .build();
TlsNode server = new TlsNode.Builder() HandshakeCertificates server = new HandshakeCertificates.Builder()
.addTrustedCertificate(clientRoot.certificate()) .addTrustedCertificate(clientRoot.certificate())
.heldCertificate(serverCertificate, serverIntermediate.certificate()) .heldCertificate(serverCertificate, serverIntermediate.certificate())
.build(); .build();
TlsNode client = new TlsNode.Builder() HandshakeCertificates client = new HandshakeCertificates.Builder()
.addTrustedCertificate(serverRoot.certificate()) .addTrustedCertificate(serverRoot.certificate())
.heldCertificate(clientCertificate, clientIntermediate.certificate()) .heldCertificate(clientCertificate, clientIntermediate.certificate())
.build(); .build();
@@ -114,13 +114,13 @@ public final class TlsNodeTest {
.issuedBy(intermediate) .issuedBy(intermediate)
.build(); .build();
TlsNode tlsNode = new TlsNode.Builder() HandshakeCertificates handshakeCertificates = new HandshakeCertificates.Builder()
.heldCertificate(certificate, intermediate.certificate()) .heldCertificate(certificate, intermediate.certificate())
.build(); .build();
assertPrivateKeysEquals(certificate.keyPair().getPrivate(), assertPrivateKeysEquals(certificate.keyPair().getPrivate(),
tlsNode.keyManager().getPrivateKey("private")); handshakeCertificates.keyManager().getPrivateKey("private"));
assertEquals(Arrays.asList(certificate.certificate(), intermediate.certificate()), assertEquals(Arrays.asList(certificate.certificate(), intermediate.certificate()),
Arrays.asList(tlsNode.keyManager().getCertificateChain("private"))); Arrays.asList(handshakeCertificates.keyManager().getCertificateChain("private")));
} }
private InetSocketAddress startTlsServer() throws IOException { private InetSocketAddress startTlsServer() throws IOException {
@@ -131,7 +131,7 @@ public final class TlsNodeTest {
return new InetSocketAddress(serverAddress, serverSocket.getLocalPort()); return new InetSocketAddress(serverAddress, serverSocket.getLocalPort());
} }
private Future<Handshake> doServerHandshake(final TlsNode server) { private Future<Handshake> doServerHandshake(final HandshakeCertificates server) {
return executorService.submit(new Callable<Handshake>() { return executorService.submit(new Callable<Handshake>() {
@Override public Handshake call() throws Exception { @Override public Handshake call() throws Exception {
Socket rawSocket = null; Socket rawSocket = null;
@@ -154,7 +154,7 @@ public final class TlsNodeTest {
} }
private Future<Handshake> doClientHandshake( private Future<Handshake> doClientHandshake(
final TlsNode client, final InetSocketAddress serverAddress) { final HandshakeCertificates client, final InetSocketAddress serverAddress) {
return executorService.submit(new Callable<Handshake>() { return executorService.submit(new Callable<Handshake>() {
@Override public Handshake call() throws Exception { @Override public Handshake call() throws Exception {
Socket rawSocket = SocketFactory.getDefault().createSocket(); Socket rawSocket = SocketFactory.getDefault().createSocket();

View File

@@ -20,7 +20,7 @@ import okhttp3.internal.io.InMemoryFileSystem;
import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest; import okhttp3.mockwebserver.RecordedRequest;
import okhttp3.tls.TlsNode; import okhttp3.tls.HandshakeCertificates;
import okio.BufferedSource; import okio.BufferedSource;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
@@ -41,7 +41,7 @@ public class OkUrlFactoryTest {
private OkUrlFactory factory; private OkUrlFactory factory;
private Cache cache; private Cache cache;
@Before public void setUp() throws IOException { @Before public void setUp() {
cache = new Cache(new File("/cache/"), 10 * 1024 * 1024, fileSystem); cache = new Cache(new File("/cache/"), 10 * 1024 * 1024, fileSystem);
OkHttpClient client = new OkHttpClient.Builder() OkHttpClient client = new OkHttpClient.Builder()
.cache(cache) .cache(cache)
@@ -57,7 +57,7 @@ public class OkUrlFactoryTest {
* Response code 407 should only come from proxy servers. Android's client throws if it is sent by * Response code 407 should only come from proxy servers. Android's client throws if it is sent by
* an origin server. * an origin server.
*/ */
@Test public void originServerSends407() throws Exception { @Test public void originServerSends407() {
server.enqueue(new MockResponse().setResponseCode(407)); server.enqueue(new MockResponse().setResponseCode(407));
HttpURLConnection conn = factory.open(server.url("/").url()); HttpURLConnection conn = factory.open(server.url("/").url());
@@ -182,16 +182,17 @@ public class OkUrlFactoryTest {
} }
@Test @Test
public void testURLFilterRedirect() throws Exception { public void testURLFilterRedirect() {
MockWebServer cleartextServer = new MockWebServer(); MockWebServer cleartextServer = new MockWebServer();
cleartextServer.enqueue(new MockResponse() cleartextServer.enqueue(new MockResponse()
.setBody("Blocked!")); .setBody("Blocked!"));
final URL blockedURL = cleartextServer.url("/").url(); final URL blockedURL = cleartextServer.url("/").url();
TlsNode tlsNode = localhost(); HandshakeCertificates handshakeCertificates = localhost();
server.useHttps(tlsNode.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
factory.setClient(factory.client().newBuilder() factory.setClient(factory.client().newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.followSslRedirects(true) .followSslRedirects(true)
.build()); .build());
factory.setUrlFilter(new URLFilter() { factory.setUrlFilter(new URLFilter() {

View File

@@ -47,7 +47,7 @@ import okhttp3.internal.platform.Platform;
import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest; import okhttp3.mockwebserver.RecordedRequest;
import okhttp3.tls.TlsNode; import okhttp3.tls.HandshakeCertificates;
import okio.Buffer; import okio.Buffer;
import okio.BufferedSink; import okio.BufferedSink;
import okio.GzipSink; import okio.GzipSink;
@@ -80,7 +80,7 @@ public final class UrlConnectionCacheTest {
@Rule public MockWebServer server2 = new MockWebServer(); @Rule public MockWebServer server2 = new MockWebServer();
@Rule public InMemoryFileSystem fileSystem = new InMemoryFileSystem(); @Rule public InMemoryFileSystem fileSystem = new InMemoryFileSystem();
private final TlsNode tlsNode = localhost(); private final HandshakeCertificates handshakeCertificates = localhost();
private OkUrlFactory urlFactory = new OkUrlFactory(new OkHttpClient()); private OkUrlFactory urlFactory = new OkUrlFactory(new OkHttpClient());
private Cache cache; private Cache cache;
private final CookieManager cookieManager = new CookieManager(); private final CookieManager cookieManager = new CookieManager();
@@ -263,14 +263,14 @@ public final class UrlConnectionCacheTest {
@Test public void secureResponseCaching() throws IOException { @Test public void secureResponseCaching() throws IOException {
assumeFalse(getPlatform().equals("jdk9")); assumeFalse(getPlatform().equals("jdk9"));
server.useHttps(tlsNode.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
server.enqueue(new MockResponse() server.enqueue(new MockResponse()
.addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
.addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS))
.setBody("ABC")); .setBody("ABC"));
HttpsURLConnection c1 = (HttpsURLConnection) urlFactory.open(server.url("/").url()); HttpsURLConnection c1 = (HttpsURLConnection) urlFactory.open(server.url("/").url());
c1.setSSLSocketFactory(tlsNode.sslSocketFactory()); c1.setSSLSocketFactory(handshakeCertificates.sslSocketFactory());
c1.setHostnameVerifier(NULL_HOSTNAME_VERIFIER); c1.setHostnameVerifier(NULL_HOSTNAME_VERIFIER);
assertEquals("ABC", readAscii(c1)); assertEquals("ABC", readAscii(c1));
@@ -282,7 +282,7 @@ public final class UrlConnectionCacheTest {
Principal localPrincipal = c1.getLocalPrincipal(); Principal localPrincipal = c1.getLocalPrincipal();
HttpsURLConnection c2 = (HttpsURLConnection) urlFactory.open(server.url("/").url()); // cached! HttpsURLConnection c2 = (HttpsURLConnection) urlFactory.open(server.url("/").url()); // cached!
c2.setSSLSocketFactory(tlsNode.sslSocketFactory()); c2.setSSLSocketFactory(handshakeCertificates.sslSocketFactory());
c2.setHostnameVerifier(NULL_HOSTNAME_VERIFIER); c2.setHostnameVerifier(NULL_HOSTNAME_VERIFIER);
assertEquals("ABC", readAscii(c2)); assertEquals("ABC", readAscii(c2));
@@ -342,7 +342,7 @@ public final class UrlConnectionCacheTest {
} }
@Test public void secureResponseCachingAndRedirects() throws IOException { @Test public void secureResponseCachingAndRedirects() throws IOException {
server.useHttps(tlsNode.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
server.enqueue(new MockResponse().addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) server.enqueue(new MockResponse().addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
.addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS))
.setResponseCode(HttpURLConnection.HTTP_MOVED_PERM) .setResponseCode(HttpURLConnection.HTTP_MOVED_PERM)
@@ -353,7 +353,8 @@ public final class UrlConnectionCacheTest {
server.enqueue(new MockResponse().setBody("DEF")); server.enqueue(new MockResponse().setBody("DEF"));
urlFactory.setClient(urlFactory.client().newBuilder() urlFactory.setClient(urlFactory.client().newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(NULL_HOSTNAME_VERIFIER) .hostnameVerifier(NULL_HOSTNAME_VERIFIER)
.build()); .build());
@@ -379,7 +380,7 @@ public final class UrlConnectionCacheTest {
* https://github.com/square/okhttp/issues/214 * https://github.com/square/okhttp/issues/214
*/ */
@Test public void secureResponseCachingAndProtocolRedirects() throws IOException { @Test public void secureResponseCachingAndProtocolRedirects() throws IOException {
server2.useHttps(tlsNode.sslSocketFactory(), false); server2.useHttps(handshakeCertificates.sslSocketFactory(), false);
server2.enqueue(new MockResponse().addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) server2.enqueue(new MockResponse().addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
.addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS))
.setBody("ABC")); .setBody("ABC"));
@@ -391,7 +392,8 @@ public final class UrlConnectionCacheTest {
.addHeader("Location: " + server2.url("/").url())); .addHeader("Location: " + server2.url("/").url()));
urlFactory.setClient(urlFactory.client().newBuilder() urlFactory.setClient(urlFactory.client().newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager()) .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(NULL_HOSTNAME_VERIFIER) .hostnameVerifier(NULL_HOSTNAME_VERIFIER)
.build()); .build());
@@ -1409,7 +1411,7 @@ public final class UrlConnectionCacheTest {
@Test public void varyAndHttps() throws Exception { @Test public void varyAndHttps() throws Exception {
assumeFalse(getPlatform().equals("jdk9")); assumeFalse(getPlatform().equals("jdk9"));
server.useHttps(tlsNode.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
server.enqueue(new MockResponse().addHeader("Cache-Control: max-age=60") server.enqueue(new MockResponse().addHeader("Cache-Control: max-age=60")
.addHeader("Vary: Accept-Language") .addHeader("Vary: Accept-Language")
.setBody("A")); .setBody("A"));
@@ -1417,13 +1419,13 @@ public final class UrlConnectionCacheTest {
URL url = server.url("/").url(); URL url = server.url("/").url();
HttpsURLConnection connection1 = (HttpsURLConnection) urlFactory.open(url); HttpsURLConnection connection1 = (HttpsURLConnection) urlFactory.open(url);
connection1.setSSLSocketFactory(tlsNode.sslSocketFactory()); connection1.setSSLSocketFactory(handshakeCertificates.sslSocketFactory());
connection1.setHostnameVerifier(NULL_HOSTNAME_VERIFIER); connection1.setHostnameVerifier(NULL_HOSTNAME_VERIFIER);
connection1.addRequestProperty("Accept-Language", "en-US"); connection1.addRequestProperty("Accept-Language", "en-US");
assertEquals("A", readAscii(connection1)); assertEquals("A", readAscii(connection1));
HttpsURLConnection connection2 = (HttpsURLConnection) urlFactory.open(url); HttpsURLConnection connection2 = (HttpsURLConnection) urlFactory.open(url);
connection2.setSSLSocketFactory(tlsNode.sslSocketFactory()); connection2.setSSLSocketFactory(handshakeCertificates.sslSocketFactory());
connection2.setHostnameVerifier(NULL_HOSTNAME_VERIFIER); connection2.setHostnameVerifier(NULL_HOSTNAME_VERIFIER);
connection2.addRequestProperty("Accept-Language", "en-US"); connection2.addRequestProperty("Accept-Language", "en-US");
assertEquals("A", readAscii(connection2)); assertEquals("A", readAscii(connection2));