Search in sources :

Example 11 with ClientSslConfigBuilder

use of io.servicetalk.transport.api.ClientSslConfigBuilder in project servicetalk by apple.

the class DefaultSingleAddressHttpClientBuilderTest method hostToCharSequenceFunction.

private static void hostToCharSequenceFunction(String hostNamePrefix, String hostName, String hostNameSuffix, @Nullable Integer port) throws Exception {
    try (ServerContext serverCtx = HttpServers.forAddress(localAddress(0)).sslConfig(new ServerSslConfigBuilder(DefaultTestCerts::loadServerPem, DefaultTestCerts::loadServerKey).build()).listenBlockingAndAwait((ctx, request, responseFactory) -> responseFactory.ok());
        BlockingHttpClient client = new DefaultSingleAddressHttpClientBuilder<>(hostNamePrefix + hostName + hostNameSuffix + (port == null ? "" : port), GlobalDnsServiceDiscoverer.mappingServiceDiscoverer(u -> serverCtx.listenAddress())).sslConfig(new ClientSslConfigBuilder(DefaultTestCerts::loadServerCAPem).hostnameVerificationAlgorithm("").build()).buildBlocking()) {
        ReservedBlockingHttpConnection conn = client.reserveConnection(client.get("/"));
        try {
            SSLSession sslSession = conn.connectionContext().sslSession();
            assertNotNull(sslSession);
            assertThat(sslSession.getPeerHost(), startsWith(hostName));
            InetSocketAddress socketAddress = (InetSocketAddress) conn.connectionContext().remoteAddress();
            assertEquals(socketAddress.getPort(), sslSession.getPeerPort());
        } finally {
            conn.release();
        }
    }
}
Also used : BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) AddressUtils.localAddress(io.servicetalk.transport.netty.internal.AddressUtils.localAddress) ServerContext(io.servicetalk.transport.api.ServerContext) ServerSslConfigBuilder(io.servicetalk.transport.api.ServerSslConfigBuilder) ReservedBlockingHttpConnection(io.servicetalk.http.api.ReservedBlockingHttpConnection) InetSocketAddress(java.net.InetSocketAddress) Matchers.startsWith(org.hamcrest.Matchers.startsWith) Test(org.junit.jupiter.api.Test) SSLSession(javax.net.ssl.SSLSession) ClientSslConfigBuilder(io.servicetalk.transport.api.ClientSslConfigBuilder) DefaultTestCerts(io.servicetalk.test.resources.DefaultTestCerts) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) Nullable(javax.annotation.Nullable) ServerContext(io.servicetalk.transport.api.ServerContext) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) InetSocketAddress(java.net.InetSocketAddress) SSLSession(javax.net.ssl.SSLSession) DefaultTestCerts(io.servicetalk.test.resources.DefaultTestCerts) ClientSslConfigBuilder(io.servicetalk.transport.api.ClientSslConfigBuilder) ReservedBlockingHttpConnection(io.servicetalk.http.api.ReservedBlockingHttpConnection) ServerSslConfigBuilder(io.servicetalk.transport.api.ServerSslConfigBuilder)

Example 12 with ClientSslConfigBuilder

use of io.servicetalk.transport.api.ClientSslConfigBuilder in project servicetalk by apple.

the class AbstractTcpServerTest method getTcpClientConfig.

// Visible for overriding.
TcpClientConfig getTcpClientConfig() {
    TcpClientConfig tcpClientConfig = new TcpClientConfig();
    if (sslEnabled) {
        HostAndPort serverHostAndPort = serverHostAndPort(serverContext);
        tcpClientConfig.sslConfig(new ClientSslConfigBuilder(DefaultTestCerts::loadServerCAPem).peerHost(serverPemHostname()).peerPort(serverHostAndPort.port()).build());
    }
    tcpClientConfig.enableWireLogging("servicetalk-tests-wire-logger", TRACE, () -> true);
    return tcpClientConfig;
}
Also used : AddressUtils.serverHostAndPort(io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort) HostAndPort(io.servicetalk.transport.api.HostAndPort) DefaultTestCerts(io.servicetalk.test.resources.DefaultTestCerts) ClientSslConfigBuilder(io.servicetalk.transport.api.ClientSslConfigBuilder)

Example 13 with ClientSslConfigBuilder

use of io.servicetalk.transport.api.ClientSslConfigBuilder in project servicetalk by apple.

the class SecureTcpTransportObserverErrorsTest method setUp.

private void setUp(ErrorReason errorReason, SslProvider clientProvider, SslProvider serverProvider) throws Exception {
    ClientSslConfigBuilder clientSslBuilder = defaultClientSslBuilder(clientProvider);
    ServerSslConfigBuilder serverSslBuilder = defaultServerSslBuilder(serverProvider);
    switch(errorReason) {
        case SECURE_CLIENT_TO_PLAIN_SERVER:
            clientConfig.sslConfig(clientSslBuilder.build());
            // In this scenario server may close the connection with or without an exception, depending on OS events
            // Using CountDownLatch to verify that any of these two methods was invoked:
            doAnswer(__ -> {
                serverConnectionClosed.countDown();
                return null;
            // In most cases it closes with
            // io.netty.channel.unix.Errors$NativeIoException: readAddress(..) failed: Connection reset by peer
            }).when(serverConnectionObserver).connectionClosed(any(IOException.class));
            doAnswer(__ -> {
                serverConnectionClosed.countDown();
                return null;
            // But sometimes netty may close the connection before we generate StacklessClosedChannelException
            // in io.servicetalk.transport.netty.internal.DefaultNettyConnection.channelInactive(...)
            }).when(serverConnectionObserver).connectionClosed();
            break;
        case PLAIN_CLIENT_TO_SECURE_SERVER:
            serverConfig.sslConfig(serverSslBuilder.build());
            break;
        case WRONG_HOSTNAME_VERIFICATION:
            clientSslBuilder.hostnameVerificationAlgorithm("HTTPS");
            clientSslBuilder.peerHost("foo");
            clientConfig.sslConfig(clientSslBuilder.build());
            serverConfig.sslConfig(serverSslBuilder.build());
            break;
        case UNTRUSTED_SERVER_CERTIFICATE:
            clientSslBuilder = defaultClientSslBuilder(clientProvider, () -> null);
            clientConfig.sslConfig(clientSslBuilder.build());
            serverConfig.sslConfig(serverSslBuilder.build());
            break;
        case UNTRUSTED_CLIENT_CERTIFICATE:
            clientSslBuilder.keyManager(DefaultTestCerts::loadClientPem, DefaultTestCerts::loadClientKey);
            clientConfig.sslConfig(clientSslBuilder.build());
            serverSslBuilder.clientAuthMode(REQUIRE);
            serverConfig.sslConfig(serverSslBuilder.build());
            break;
        case MISSED_CLIENT_CERTIFICATE:
            clientConfig.sslConfig(clientSslBuilder.build());
            serverSslBuilder.clientAuthMode(REQUIRE);
            serverConfig.sslConfig(serverSslBuilder.build());
            break;
        case NOT_MATCHING_PROTOCOLS:
            clientSslBuilder.sslProtocols("TLSv1.2");
            clientConfig.sslConfig(clientSslBuilder.build());
            serverSslBuilder.sslProtocols("TLSv1.3");
            serverConfig.sslConfig(serverSslBuilder.build());
            break;
        case NOT_MATCHING_CIPHERS:
            clientSslBuilder.ciphers(singletonList("TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384"));
            clientConfig.sslConfig(clientSslBuilder.build());
            serverSslBuilder.ciphers(singletonList("TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"));
            serverConfig.sslConfig(serverSslBuilder.build());
            break;
        default:
            throw new IllegalArgumentException("Unsupported ErrorSource: " + errorReason);
    }
    setUp();
}
Also used : IOException(java.io.IOException) DefaultTestCerts(io.servicetalk.test.resources.DefaultTestCerts) ClientSslConfigBuilder(io.servicetalk.transport.api.ClientSslConfigBuilder) ServerSslConfigBuilder(io.servicetalk.transport.api.ServerSslConfigBuilder)

Example 14 with ClientSslConfigBuilder

use of io.servicetalk.transport.api.ClientSslConfigBuilder in project servicetalk by apple.

the class AbstractNettyHttpServerTest method startServer.

private void startServer() throws Exception {
    final InetSocketAddress bindAddress = localAddress(0);
    service(new TestServiceStreaming(publisherSupplier));
    // A small SNDBUF is needed to test that the server defers closing the connection until writes are complete.
    // However, if it is too small, tests that expect certain chunks of data will see those chunks broken up
    // differently.
    final HttpServerBuilder serverBuilder = HttpServers.forAddress(bindAddress).executor(serverExecutor).socketOption(StandardSocketOptions.SO_SNDBUF, 100).protocols(protocol).transportObserver(serverTransportObserver).enableWireLogging("servicetalk-tests-wire-logger", TRACE, () -> true);
    configureServerBuilder(serverBuilder);
    if (sslEnabled) {
        serverBuilder.sslConfig(new ServerSslConfigBuilder(DefaultTestCerts::loadServerPem, DefaultTestCerts::loadServerKey).build());
    }
    if (nonOffloadingServiceFilterFactory != null) {
        serverBuilder.appendNonOffloadingServiceFilter(nonOffloadingServiceFilterFactory);
    }
    if (serviceFilterFactory != null) {
        serverBuilder.appendServiceFilter(serviceFilterFactory);
    }
    if (serverLifecycleObserver != NoopHttpLifecycleObserver.INSTANCE) {
        serverBuilder.lifecycleObserver(serverLifecycleObserver);
    }
    serverContext = awaitIndefinitelyNonNull(listen(serverBuilder.ioExecutor(serverIoExecutor).appendConnectionAcceptorFilter(original -> new DelegatingConnectionAcceptor(connectionAcceptor))).beforeOnSuccess(ctx -> LOGGER.debug("Server started on {}.", ctx.listenAddress())).beforeOnError(throwable -> LOGGER.debug("Failed starting server on {}.", bindAddress)));
    final SingleAddressHttpClientBuilder<HostAndPort, InetSocketAddress> clientBuilder = newClientBuilder();
    if (sslEnabled) {
        clientBuilder.sslConfig(new ClientSslConfigBuilder(DefaultTestCerts::loadServerCAPem).peerHost(serverPemHostname()).build());
    }
    if (connectionFactoryFilter != null) {
        clientBuilder.appendConnectionFactoryFilter(connectionFactoryFilter);
    }
    if (connectionFilterFactory != null) {
        clientBuilder.appendConnectionFilter(connectionFilterFactory);
    }
    if (clientTransportObserver != NoopTransportObserver.INSTANCE) {
        clientBuilder.appendConnectionFactoryFilter(new TransportObserverConnectionFactoryFilter<>(clientTransportObserver));
    }
    if (clientLifecycleObserver != NoopHttpLifecycleObserver.INSTANCE) {
        clientBuilder.appendClientFilter(new HttpLifecycleObserverRequesterFilter(clientLifecycleObserver));
    }
    if (clientFilterFactory != null) {
        clientBuilder.appendClientFilter(clientFilterFactory);
    }
    httpClient = clientBuilder.ioExecutor(clientIoExecutor).executor(clientExecutor).executionStrategy(defaultStrategy()).protocols(protocol).enableWireLogging("servicetalk-tests-wire-logger", TRACE, Boolean.TRUE::booleanValue).buildStreaming();
    httpConnection = httpClient.reserveConnection(httpClient.get("/")).toFuture().get();
}
Also used : HttpLifecycleObserver(io.servicetalk.http.api.HttpLifecycleObserver) PlatformDependent.throwException(io.servicetalk.utils.internal.PlatformDependent.throwException) ServerSslConfigBuilder(io.servicetalk.transport.api.ServerSslConfigBuilder) LoggerFactory(org.slf4j.LoggerFactory) StreamingHttpConnectionFilterFactory(io.servicetalk.http.api.StreamingHttpConnectionFilterFactory) HttpResponseMetaData(io.servicetalk.http.api.HttpResponseMetaData) StreamingHttpServiceFilterFactory(io.servicetalk.http.api.StreamingHttpServiceFilterFactory) ConnectionAcceptor(io.servicetalk.transport.api.ConnectionAcceptor) AfterAll(org.junit.jupiter.api.AfterAll) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) HttpExecutionStrategies.defaultStrategy(io.servicetalk.http.api.HttpExecutionStrategies.defaultStrategy) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) BeforeAll(org.junit.jupiter.api.BeforeAll) Assumptions.assumeFalse(org.junit.jupiter.api.Assumptions.assumeFalse) Executor(io.servicetalk.concurrent.api.Executor) HttpProtocolConfig(io.servicetalk.http.api.HttpProtocolConfig) BlockingTestUtils.awaitIndefinitelyNonNull(io.servicetalk.concurrent.api.BlockingTestUtils.awaitIndefinitelyNonNull) DefaultTestCerts(io.servicetalk.test.resources.DefaultTestCerts) StandardSocketOptions(java.net.StandardSocketOptions) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) ConnectionFactoryFilter(io.servicetalk.client.api.ConnectionFactoryFilter) AsyncCloseables.newCompositeCloseable(io.servicetalk.concurrent.api.AsyncCloseables.newCompositeCloseable) InetSocketAddress(java.net.InetSocketAddress) DefaultTestCerts.serverPemHostname(io.servicetalk.test.resources.DefaultTestCerts.serverPemHostname) Buffer(io.servicetalk.buffer.api.Buffer) DelegatingConnectionAcceptor(io.servicetalk.transport.api.DelegatingConnectionAcceptor) StreamingHttpService(io.servicetalk.http.api.StreamingHttpService) TransportObserver(io.servicetalk.transport.api.TransportObserver) ClientSslConfigBuilder(io.servicetalk.transport.api.ClientSslConfigBuilder) Matchers.is(org.hamcrest.Matchers.is) Strictness(org.mockito.quality.Strictness) Assertions.fail(org.junit.jupiter.api.Assertions.fail) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) MockitoSettings(org.mockito.junit.jupiter.MockitoSettings) DEFAULT_ALLOCATOR(io.servicetalk.buffer.netty.BufferAllocators.DEFAULT_ALLOCATOR) Publisher(io.servicetalk.concurrent.api.Publisher) Mock(org.mockito.Mock) TRACE(io.servicetalk.logging.api.LogLevel.TRACE) FilterableStreamingHttpConnection(io.servicetalk.http.api.FilterableStreamingHttpConnection) Function(java.util.function.Function) Supplier(java.util.function.Supplier) HttpProtocolConfigs.h1Default(io.servicetalk.http.netty.HttpProtocolConfigs.h1Default) HttpSerializers.appSerializerUtf8FixLen(io.servicetalk.http.api.HttpSerializers.appSerializerUtf8FixLen) HttpServerContext(io.servicetalk.http.api.HttpServerContext) Objects.requireNonNull(java.util.Objects.requireNonNull) HttpProtocolVersion(io.servicetalk.http.api.HttpProtocolVersion) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) AddressUtils.serverHostAndPort(io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) DefaultThreadFactory(io.servicetalk.concurrent.api.DefaultThreadFactory) HttpServerBuilder(io.servicetalk.http.api.HttpServerBuilder) Nullable(javax.annotation.Nullable) ACCEPT_ALL(io.servicetalk.transport.api.ConnectionAcceptor.ACCEPT_ALL) NettyIoExecutors(io.servicetalk.transport.netty.NettyIoExecutors) AddressUtils.localAddress(io.servicetalk.transport.netty.internal.AddressUtils.localAddress) Logger(org.slf4j.Logger) ServerContext(io.servicetalk.transport.api.ServerContext) StreamingHttpConnection(io.servicetalk.http.api.StreamingHttpConnection) Single(io.servicetalk.concurrent.api.Single) SingleAddressHttpClientBuilder(io.servicetalk.http.api.SingleAddressHttpClientBuilder) ExecutionException(java.util.concurrent.ExecutionException) US_ASCII(java.nio.charset.StandardCharsets.US_ASCII) IoExecutor(io.servicetalk.transport.api.IoExecutor) AfterEach(org.junit.jupiter.api.AfterEach) Boolean.parseBoolean(java.lang.Boolean.parseBoolean) TransportObserverConnectionFactoryFilter(io.servicetalk.client.api.TransportObserverConnectionFactoryFilter) Executors.newCachedThreadExecutor(io.servicetalk.concurrent.api.Executors.newCachedThreadExecutor) NORM_PRIORITY(java.lang.Thread.NORM_PRIORITY) Executors(io.servicetalk.concurrent.api.Executors) StreamingHttpClientFilterFactory(io.servicetalk.http.api.StreamingHttpClientFilterFactory) HttpResponseStatus(io.servicetalk.http.api.HttpResponseStatus) NoopTransportObserver(io.servicetalk.transport.netty.internal.NoopTransportObserver) HostAndPort(io.servicetalk.transport.api.HostAndPort) InetSocketAddress(java.net.InetSocketAddress) HttpServerBuilder(io.servicetalk.http.api.HttpServerBuilder) DelegatingConnectionAcceptor(io.servicetalk.transport.api.DelegatingConnectionAcceptor) DefaultTestCerts(io.servicetalk.test.resources.DefaultTestCerts) ClientSslConfigBuilder(io.servicetalk.transport.api.ClientSslConfigBuilder) AddressUtils.serverHostAndPort(io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort) HostAndPort(io.servicetalk.transport.api.HostAndPort) ServerSslConfigBuilder(io.servicetalk.transport.api.ServerSslConfigBuilder)

Example 15 with ClientSslConfigBuilder

use of io.servicetalk.transport.api.ClientSslConfigBuilder in project servicetalk by apple.

the class GrpcSslAndNonSslConnectionsTest method connectingToSecureServerWithSecureClient.

@Test
void connectingToSecureServerWithSecureClient() throws Exception {
    try (ServerContext serverContext = secureGrpcServer();
        BlockingTesterClient client = secureGrpcClient(serverContext, new ClientSslConfigBuilder(DefaultTestCerts::loadServerCAPem).peerHost(serverPemHostname())).buildBlocking(clientFactory())) {
        final TesterProto.TestResponse response = client.test(REQUEST);
        assertThat(response, is(notNullValue()));
        assertThat(response.getMessage(), is(notNullValue()));
    }
}
Also used : ServerContext(io.servicetalk.transport.api.ServerContext) ClientSslConfigBuilder(io.servicetalk.transport.api.ClientSslConfigBuilder) BlockingTesterClient(io.servicetalk.grpc.netty.TesterProto.Tester.BlockingTesterClient) Test(org.junit.jupiter.api.Test)

Aggregations

ClientSslConfigBuilder (io.servicetalk.transport.api.ClientSslConfigBuilder)24 DefaultTestCerts (io.servicetalk.test.resources.DefaultTestCerts)20 ServerContext (io.servicetalk.transport.api.ServerContext)16 ServerSslConfigBuilder (io.servicetalk.transport.api.ServerSslConfigBuilder)13 BlockingHttpClient (io.servicetalk.http.api.BlockingHttpClient)11 HostAndPort (io.servicetalk.transport.api.HostAndPort)9 AddressUtils.localAddress (io.servicetalk.transport.netty.internal.AddressUtils.localAddress)9 AddressUtils.serverHostAndPort (io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort)9 Test (org.junit.jupiter.api.Test)9 DefaultTestCerts.serverPemHostname (io.servicetalk.test.resources.DefaultTestCerts.serverPemHostname)8 MatcherAssert.assertThat (org.hamcrest.MatcherAssert.assertThat)8 HttpResponse (io.servicetalk.http.api.HttpResponse)7 Matchers.is (org.hamcrest.Matchers.is)7 Nullable (javax.annotation.Nullable)6 SSLHandshakeException (javax.net.ssl.SSLHandshakeException)6 Assertions.assertThrows (org.junit.jupiter.api.Assertions.assertThrows)6 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)6 InetSocketAddress (java.net.InetSocketAddress)5 Matchers.instanceOf (org.hamcrest.Matchers.instanceOf)5 AfterEach (org.junit.jupiter.api.AfterEach)5