okhttp3.tls.HandshakeCertificates Java Examples

The following examples show how to use okhttp3.tls.HandshakeCertificates. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MockWebServerTest.java    From mapbox-events-android with MIT License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  this.server = new MockWebServer();
  String localhost = InetAddress.getByName("localhost").getCanonicalHostName();
  localhostCertificate = new HeldCertificate.Builder()
    .addSubjectAlternativeName(localhost)
    .build();
  serverCertificates = new HandshakeCertificates.Builder()
    .heldCertificate(localhostCertificate)
    .build();
  clientCertificates = new HandshakeCertificates.Builder()
    .addTrustedCertificate(localhostCertificate.certificate())
    .build();
  this.server.useHttps(serverCertificates.sslSocketFactory(), false);
  this.server.start();
}
 
Example #2
Source File: SslUtils.java    From RESTMock with Apache License 2.0 6 votes vote down vote up
/** Returns an SSL client for this host's localhost address. */
public static synchronized HandshakeCertificates localhost() {
    if (localhost != null) return localhost;

    try {
        // Generate a self-signed cert for the server to serve and the client to trust.
        HeldCertificate heldCertificate = new HeldCertificate.Builder()
            .rsa2048()
            .commonName("localhost")
            .addSubjectAlternativeName(InetAddress.getByName("localhost").getCanonicalHostName())
            .build();

        localhost = new HandshakeCertificates.Builder()
            .heldCertificate(heldCertificate)
            .addTrustedCertificate(heldCertificate.certificate())
            .build();

        return localhost;
    } catch (UnknownHostException e) {
        throw new RuntimeException(e);
    }
}
 
Example #3
Source File: TestUtils.java    From digdag with Apache License 2.0 6 votes vote down vote up
public static MockWebServer startMockWebServer(boolean https)
{
    try {
        MockWebServer server = new MockWebServer();
        server.setDispatcher(new NopDispatcher());
        if (https) {
            HandshakeCertificates handshakeCertificates = localhost();
            SSLSocketFactory socketFactory = handshakeCertificates.sslSocketFactory();
            server.useHttps(socketFactory, false);

        }
        server.start(0);
        return server;
    }
    catch (IOException e) {
        throw Throwables.propagate(e);
    }
}
 
Example #4
Source File: DigdagClientTest.java    From digdag with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp()
        throws Exception
{
    mockWebServer = new MockWebServer();
    HandshakeCertificates handshakeCertificates = localhost();
    SSLSocketFactory socketFactory = handshakeCertificates.sslSocketFactory();
    mockWebServer.useHttps(socketFactory, false);
    mockWebServer.start();

    client = DigdagClient.builder()
            .disableCertValidation(true)
            .ssl(true)
            .host(mockWebServer.getHostName())
            .port(mockWebServer.getPort())
            .build();

    objectMapper = DigdagClient.objectMapper();
}
 
Example #5
Source File: ConfigurationClientTest.java    From mapbox-events-android with MIT License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  this.server = new MockWebServer();
  String localhost = InetAddress.getByName("localhost").getCanonicalHostName();
  localhostCertificate = new HeldCertificate.Builder()
    .addSubjectAlternativeName(localhost)
    .build();
  serverCertificates = new HandshakeCertificates.Builder()
    .heldCertificate(localhostCertificate)
    .build();
  clientCertificates = new HandshakeCertificates.Builder()
    .addTrustedCertificate(localhostCertificate.certificate())
    .build();
  server.useHttps(serverCertificates.sslSocketFactory(), false);
  server.start();

  TelemetryClientSettings settings = provideDefaultTelemetryClientSettings();
  CertificateBlacklist mockedBlacklist = mock(CertificateBlacklist.class);
  OkHttpClient client = settings.getClient(mockedBlacklist, 0);
  Context mockedContext = getConfigContext();

  File mockedFile = mock(File.class);
  FileOutputStream mockedOutputStream = mock(FileOutputStream.class);
  when(mockedContext.getFilesDir()).thenReturn(mockedFile);
  when(mockedContext.openFileOutput("MapboxBlacklist", Context.MODE_PRIVATE)).thenReturn(mockedOutputStream);

  SharedPreferences mockedSharedPreferences = mock(SharedPreferences.class);
  SharedPreferences.Editor mockedEditor = mock(SharedPreferences.Editor.class);
  when(mockedContext.getSharedPreferences(MAPBOX_SHARED_PREFERENCES, Context.MODE_PRIVATE))
    .thenReturn(mockedSharedPreferences);
  when(mockedSharedPreferences.getLong("mapboxConfigSyncTimestamp", 0))
    .thenReturn(Long.valueOf(0));
  when(mockedSharedPreferences.edit()).thenReturn(mockedEditor);

  this.configurationClient = new ConfigurationClient(mockedContext, TelemetryUtils.createFullUserAgent("AnUserAgent",
    mockedContext), "anAccessToken", client);
}
 
Example #6
Source File: HttpZipkinTracerIntegrationTest.java    From zipkin-finagle with Apache License 2.0 5 votes vote down vote up
MockWebServer createMockWebServerWithTLS() throws UnknownHostException {
  MockWebServer server = new MockWebServer();
  String localhost = InetAddress.getByName("localhost").getCanonicalHostName();
  HeldCertificate localhostCertificate = new HeldCertificate.Builder()
      .addSubjectAlternativeName(localhost)
      .build();
  HandshakeCertificates serverCertificates = new HandshakeCertificates.Builder()
      .heldCertificate(localhostCertificate)
      .build();
  server.useHttps(serverCertificates.sslSocketFactory(), false);
  return server;
}
 
Example #7
Source File: CliProxyEnvVarIT.java    From digdag with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp()
        throws Exception
{
    httpMockServer = new MockWebServer();
    httpMockServer.start();

    httpsMockServer = new MockWebServer();
    HandshakeCertificates handshakeCertificates = localhost();
    SSLSocketFactory socketFactory = handshakeCertificates.sslSocketFactory();


    httpsMockServer.useHttps(socketFactory, false);
    httpsMockServer.start();

    httpProxy = DefaultHttpProxyServer
            .bootstrap()
            .withPort(0)
            .plusActivityTracker(httpProxyRequestTracker)
            .start();
    httpProxyUrl = "http://" + httpProxy.getListenAddress().getHostString() + ":" + httpProxy.getListenAddress().getPort();

    httpsProxy = DefaultHttpProxyServer
            .bootstrap()
            .withPort(0)
            .plusActivityTracker(httpsProxyRequestTracker)
            .withSslEngineSource(new SelfSignedSslEngineSource())
            .withAuthenticateSslClients(false)
            .start();
    httpsProxyUrl = "https://" + httpsProxy.getListenAddress().getHostString() + ":" + httpsProxy.getListenAddress().getPort();
}
 
Example #8
Source File: SlbBuckConfig.java    From buck with Apache License 2.0 5 votes vote down vote up
public ClientSideSlb createClientSideSlb(
    Clock clock,
    BuckEventBus eventBus,
    Optional<HandshakeCertificates> handshakeCertificates,
    Optional<HostnameVerifier> hostnameVerifier) {
  return new ClientSideSlb(
      createConfig(clock, eventBus),
      createOkHttpClientBuilder(handshakeCertificates, hostnameVerifier));
}
 
Example #9
Source File: SlbBuckConfig.java    From buck with Apache License 2.0 5 votes vote down vote up
private OkHttpClient.Builder createOkHttpClientBuilder(
    Optional<HandshakeCertificates> handshakeCertificates,
    Optional<HostnameVerifier> hostnameVerifier) {
  OkHttpClient.Builder clientBuilder = new OkHttpClient().newBuilder();

  // Add client TLS information if present
  if (handshakeCertificates.isPresent()) {
    clientBuilder.sslSocketFactory(
        handshakeCertificates.get().sslSocketFactory(),
        handshakeCertificates.get().trustManager());
  }
  if (hostnameVerifier.isPresent()) {
    clientBuilder.hostnameVerifier(hostnameVerifier.get());
  }

  clientBuilder
      .networkInterceptors()
      .add(
          chain -> {
            String remoteAddress = null;
            Connection connection = chain.connection();
            if (connection != null) {
              remoteAddress = connection.socket().getRemoteSocketAddress().toString();
            } else {
              LOG.warn("No available connection.");
            }
            Response response = chain.proceed(chain.request());
            if (response.code() != 200 && remoteAddress != null) {
              LOG.warn(
                  String.format(
                      "Connection to %s failed with code %d", remoteAddress, response.code()));
            }
            return response;
          });
  return clientBuilder;
}
 
Example #10
Source File: ClientCertificateHandler.java    From buck with Apache License 2.0 5 votes vote down vote up
private static Optional<HandshakeCertificates> parseHandshakeCertificates(
    Optional<Path> keyPath,
    Optional<Path> certPath,
    Optional<Path> trustedCaCertificates,
    boolean required) {
  HandshakeCertificates.Builder hsBuilder = new HandshakeCertificates.Builder();
  boolean shouldReturnHandshakeCerts = false;
  hsBuilder.addPlatformTrustedCertificates();
  ImmutableList<X509Certificate> extraCaCertificates =
      parseCertificates(trustedCaCertificates, false);
  if (!extraCaCertificates.isEmpty()) {
    extraCaCertificates.stream().forEachOrdered(hsBuilder::addTrustedCertificate);
    shouldReturnHandshakeCerts = true;
  }
  // Load the client certificate chain
  Optional<CertificateInfo> certInfo = parseCertificateChain(certPath, required);
  if (certInfo.isPresent()) {
    X509Certificate clientCert = certInfo.get().getPrimaryCert();
    Optional<PrivateKey> privateKey = parsePrivateKey(keyPath, clientCert, required);
    if (privateKey.isPresent()) {
      HeldCertificate heldCert =
          new HeldCertificate(
              new KeyPair(clientCert.getPublicKey(), privateKey.get()), clientCert);
      hsBuilder.heldCertificate(
          heldCert, certInfo.get().getChain().stream().toArray(X509Certificate[]::new));
      shouldReturnHandshakeCerts = true;
    }
  }
  return shouldReturnHandshakeCerts ? Optional.of(hsBuilder.build()) : Optional.empty();
}
 
Example #11
Source File: RxOkHttpClientTest.java    From titus-control-plane with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetWithSslContext() throws Exception {
    String localhost = InetAddress.getByName("localhost").getCanonicalHostName();
    HeldCertificate localhostCertificate = new HeldCertificate.Builder()
            .addSubjectAlternativeName(localhost)
            .build();
    HandshakeCertificates serverCertificates = new HandshakeCertificates.Builder()
            .heldCertificate(localhostCertificate)
            .build();

    try (MockWebServer sslServer = new MockWebServer()) {
        sslServer.useHttps(serverCertificates.sslSocketFactory(), false);
        String url = sslServer.url("/").toString();

        MockResponse mockResponse = new MockResponse()
                .setBody(TEST_RESPONSE_BODY)
                .setResponseCode(StatusCode.OK.getCode());
        sslServer.enqueue(mockResponse);

        HandshakeCertificates clientCertificates = new HandshakeCertificates.Builder()
                .addTrustedCertificate(localhostCertificate.certificate())
                .build();
        RxHttpClient client = RxOkHttpClient.newBuilder()
                .sslContext(clientCertificates.sslContext())
                .trustManager(clientCertificates.trustManager())
                .build();

        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();

        Response response = client.execute(request).toBlocking().first();
        Assertions.assertThat(response.isSuccessful()).isTrue();

        InputStream inputStream = response.getBody().get(InputStream.class);
        String actualResponseBody = CharStreams.toString(new InputStreamReader(inputStream, Charsets.UTF_8));
        Assertions.assertThat(actualResponseBody).isEqualTo(TEST_RESPONSE_BODY);

        RecordedRequest recordedRequest = sslServer.takeRequest(1, TimeUnit.MILLISECONDS);
        Assertions.assertThat(recordedRequest).isNotNull();
        Assertions.assertThat(recordedRequest.getBodySize()).isLessThanOrEqualTo(0);
    }
}
 
Example #12
Source File: OkHttpClientTest.java    From titus-control-plane with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetWithSslContext() throws Exception {
    String localhost = InetAddress.getByName("localhost").getCanonicalHostName();
    HeldCertificate localhostCertificate = new HeldCertificate.Builder()
            .addSubjectAlternativeName(localhost)
            .build();
    HandshakeCertificates serverCertificates = new HandshakeCertificates.Builder()
            .heldCertificate(localhostCertificate)
            .build();

    try(MockWebServer sslServer = new MockWebServer()) {
        sslServer.useHttps(serverCertificates.sslSocketFactory(), false);
        String url = sslServer.url("/").toString();

        MockResponse mockResponse = new MockResponse()
                .setBody(TEST_RESPONSE_BODY)
                .setResponseCode(StatusCode.OK.getCode());
        sslServer.enqueue(mockResponse);

        HandshakeCertificates clientCertificates = new HandshakeCertificates.Builder()
                .addTrustedCertificate(localhostCertificate.certificate())
                .build();
        HttpClient client = OkHttpClient.newBuilder()
                .sslContext(clientCertificates.sslContext())
                .trustManager(clientCertificates.trustManager())
                .build();

        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();

        Response response = client.execute(request);
        Assertions.assertThat(response.isSuccessful()).isTrue();

        InputStream inputStream = response.getBody().get(InputStream.class);
        String actualResponseBody = CharStreams.toString(new InputStreamReader(inputStream, Charsets.UTF_8));
        Assertions.assertThat(actualResponseBody).isEqualTo(TEST_RESPONSE_BODY);

        RecordedRequest recordedRequest = sslServer.takeRequest(1, TimeUnit.MILLISECONDS);
        Assertions.assertThat(recordedRequest).isNotNull();
        Assertions.assertThat(recordedRequest.getBodySize()).isLessThanOrEqualTo(0);
    }
}
 
Example #13
Source File: ClientCertificateHandler.java    From buck with Apache License 2.0 4 votes vote down vote up
public HandshakeCertificates getHandshakeCertificates() {
  return handshakeCertificates;
}
 
Example #14
Source File: ClientCertificateHandler.java    From buck with Apache License 2.0 3 votes vote down vote up
/**
 * Creates an instance of {@link ClientCertificateHandler}
 *
 * @param handshakeCertificates If non-null, client certificates to use for http connections
 * @param hostnameVerifier Used for testing to bypass hostname verification in integration tests.
 *     Should be {@code null} in production use.
 */
@VisibleForTesting
public ClientCertificateHandler(
    HandshakeCertificates handshakeCertificates, Optional<HostnameVerifier> hostnameVerifier) {
  this.handshakeCertificates = handshakeCertificates;
  this.hostnameVerifier = hostnameVerifier;
}