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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -22,7 +22,7 @@ import javax.net.ssl.SSLException;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.SocketPolicy;
import okhttp3.tls.TlsNode;
import okhttp3.tls.HandshakeCertificates;
import org.junit.Rule;
import org.junit.Test;
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 MockWebServer server = new MockWebServer();
private TlsNode tlsNode = localhost();
private HandshakeCertificates handshakeCertificates = localhost();
private OkHttpClient client = defaultClient();
@Test public void connectionsAreReused() throws Exception {
@@ -252,9 +252,10 @@ public final class ConnectionReuseTest {
response.body().close();
// 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()
.sslSocketFactory(tlsNode2.sslSocketFactory(), tlsNode2.trustManager())
.sslSocketFactory(
handshakeCertificates2.sslSocketFactory(), handshakeCertificates2.trustManager())
.build();
// 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) {
client = client.newBuilder()
.sslSocketFactory(tlsNode.sslSocketFactory(), tlsNode.trustManager())
.sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(new RecordingHostnameVerifier())
.protocols(Arrays.asList(protocols))
.build();
server.useHttps(tlsNode.sslSocketFactory(), false);
server.useHttps(handshakeCertificates.sslSocketFactory(), false);
server.setProtocols(client.protocols());
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -44,15 +44,15 @@ import static okhttp3.tls.internal.TlsUtil.newTrustManager;
* <p>To perform server authentication:
*
* <ul>
* <li>The server's TLS node must have a {@linkplain HeldCertificate held certificate} (a
* certificate and its private key). The certificate's subject alternative names must match
* the server's hostname. The server must also have is a (possibly-empty) chain of
* intermediate certificates to establish trust from a root certificate to the 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
* authenticate the server's certificate chain. Typically this is a set of well-known root
* certificates that is distributed with the HTTP client or its platform. It may be augmented
* by certificates private to an organization or service.
* <li>The server's handshake certificates must have a {@linkplain HeldCertificate held
* certificate} (a certificate and its private key). The certificate's subject alternative
* names must match the server's hostname. The server must also have is a (possibly-empty)
* chain of intermediate certificates to establish trust from a root certificate to the
* server's certificate. The root certificate is not included in this chain.
* <li>The client's handshake certificates must include a set of trusted root certificates. They
* will be used to authenticate the server's certificate chain. Typically this is a set of
* well-known root certificates that is distributed with the HTTP client or its platform. It
* may be augmented by certificates private to an organization or service.
* </ul>
*
* <h3>Client Authentication</h3>
@@ -63,21 +63,22 @@ import static okhttp3.tls.internal.TlsUtil.newTrustManager;
* <p>To perform client authentication:
*
* <ul>
* <li>The client's TLS node must have a {@linkplain HeldCertificate held certificate} (a
* certificate and its private key). The client must also have a (possibly-empty) chain of
* intermediate certificates to establish trust from a root certificate to the client's
* certificate. The root certificate is not included in this chain.
* <li>The server's TLS node must include a set of trusted root certificates. They will be used to
* authenticate the client's certificate chain. Typically this is not the same set of root
* certificates used in server authentication. Instead it will be a small set of roots
* private to an organization or service.
* <li>The client's handshake certificates must have a {@linkplain HeldCertificate held
* certificate} (a certificate and its private key). The client must also have a
* (possibly-empty) chain of intermediate certificates to establish trust from a root
* certificate to the client's certificate. The root certificate is not included in this
* chain.
* <li>The server's handshake certificates must include a set of trusted root certificates. They
* will be used to authenticate the client's certificate chain. Typically this is not the same
* set of root certificates used in server authentication. Instead it will be a small set of
* roots private to an organization or service.
* </ul>
*/
public final class TlsNode {
public final class HandshakeCertificates {
private final X509KeyManager keyManager;
private final X509TrustManager trustManager;
private TlsNode(X509KeyManager keyManager, X509TrustManager trustManager) {
private HandshakeCertificates(X509KeyManager keyManager, X509TrustManager trustManager) {
this.keyManager = keyManager;
this.trustManager = trustManager;
}
@@ -113,8 +114,8 @@ public final class TlsNode {
/**
* 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
* can build a trusted path to a trusted root certificate.
* the held certificate, further certificates are included in the handshake so the peer can
* build a trusted path to a trusted root certificate.
*
* <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
@@ -136,11 +137,11 @@ public final class TlsNode {
return this;
}
public TlsNode build() {
public HandshakeCertificates build() {
try {
X509KeyManager keyManager = newKeyManager(null, heldCertificate, intermediates);
X509TrustManager trustManager = newTrustManager(null, trustedCertificates);
return new TlsNode(keyManager, trustManager);
return new HandshakeCertificates(keyManager, trustManager);
} catch (GeneralSecurityException 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.X509TrustManager;
import okhttp3.tls.HeldCertificate;
import okhttp3.tls.TlsNode;
import okhttp3.tls.HandshakeCertificates;
public final class TlsUtil {
public static final char[] password = "password".toCharArray();
private static TlsNode localhost; // Lazily initialized.
private static HandshakeCertificates localhost; // Lazily initialized.
private TlsUtil() {
}
/** 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;
try {
@@ -52,7 +52,7 @@ public final class TlsUtil {
.addSubjectAlternativeName(InetAddress.getByName("localhost").getCanonicalHostName())
.build();
localhost = new TlsNode.Builder()
localhost = new HandshakeCertificates.Builder()
.heldCertificate(heldCertificate)
.addTrustedCertificate(heldCertificate.certificate())
.build();

View File

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

View File

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

View File

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