Search in sources :

Example 16 with DefaultTestCerts

use of io.servicetalk.test.resources.DefaultTestCerts in project servicetalk by apple.

the class Tls13Test method requiredCipher.

@ParameterizedTest
@MethodSource("sslProviders")
void requiredCipher(SslProvider serverSslProvider, SslProvider clientSslProvider, @Nullable String cipher) throws Exception {
    ServerSslConfigBuilder serverSslBuilder = new ServerSslConfigBuilder(DefaultTestCerts::loadServerPem, DefaultTestCerts::loadServerKey).sslProtocols(TLS1_3).provider(serverSslProvider);
    if (cipher != null) {
        serverSslBuilder.ciphers(singletonList(cipher));
    }
    try (ServerContext serverContext = forAddress(localAddress(0)).ioExecutor(SERVER_CTX.ioExecutor()).executor(SERVER_CTX.executor()).executionStrategy(defaultStrategy()).enableWireLogging("servicetalk-tests-wire-logger", TRACE, () -> false).sslConfig(serverSslBuilder.build()).listenBlockingAndAwait((ctx, request, responseFactory) -> {
        assertThat(request.payloadBody(textSerializerUtf8()), equalTo("request-payload-body"));
        SSLSession sslSession = ctx.sslSession();
        assertThat(sslSession, is(notNullValue()));
        return responseFactory.ok().payloadBody(sslSession.getProtocol(), textSerializerUtf8());
    })) {
        ClientSslConfigBuilder clientSslBuilder = new ClientSslConfigBuilder(DefaultTestCerts::loadServerCAPem).sslProtocols(TLS1_3).peerHost(serverPemHostname()).provider(clientSslProvider);
        if (cipher != null) {
            clientSslBuilder.ciphers(singletonList(cipher));
        }
        try (BlockingHttpClient client = HttpClients.forSingleAddress(serverHostAndPort(serverContext)).ioExecutor(CLIENT_CTX.ioExecutor()).executor(CLIENT_CTX.executor()).executionStrategy(defaultStrategy()).enableWireLogging("servicetalk-tests-wire-logger", TRACE, Boolean.FALSE::booleanValue).sslConfig(clientSslBuilder.build()).buildBlocking();
            BlockingHttpConnection connection = client.reserveConnection(client.get("/"))) {
            SSLSession sslSession = connection.connectionContext().sslSession();
            assertThat(sslSession, is(notNullValue()));
            assertThat(sslSession.getProtocol(), equalTo(TLS1_3));
            if (cipher != null) {
                assertThat(sslSession.getCipherSuite(), equalTo(cipher));
            }
            HttpResponse response = client.request(client.post("/").payloadBody("request-payload-body", textSerializerUtf8()));
            assertThat(response.status(), is(OK));
            assertThat(response.headers().get(CONTENT_TYPE), is(TEXT_PLAIN_UTF_8));
            assertThat(response.payloadBody(textSerializerUtf8()), equalTo(TLS1_3));
        }
    }
}
Also used : ServerContext(io.servicetalk.transport.api.ServerContext) BlockingHttpConnection(io.servicetalk.http.api.BlockingHttpConnection) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) SSLSession(javax.net.ssl.SSLSession) HttpResponse(io.servicetalk.http.api.HttpResponse) DefaultTestCerts(io.servicetalk.test.resources.DefaultTestCerts) ClientSslConfigBuilder(io.servicetalk.transport.api.ClientSslConfigBuilder) ServerSslConfigBuilder(io.servicetalk.transport.api.ServerSslConfigBuilder) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 17 with DefaultTestCerts

use of io.servicetalk.test.resources.DefaultTestCerts in project servicetalk by apple.

the class ManualRedirectClient method main.

public static void main(String... args) throws Exception {
    try (HttpClient secureClient = HttpClients.forSingleAddress("localhost", SECURE_SERVER_PORT).sslConfig(new ClientSslConfigBuilder(DefaultTestCerts::loadServerCAPem).build()).build()) {
        try (HttpClient client = HttpClients.forSingleAddress("localhost", NON_SECURE_SERVER_PORT).build()) {
            System.out.println("- Redirect of a GET request with a custom header:");
            HttpRequest originalGet = client.get("/non-relative").addHeader(CUSTOM_HEADER, "value");
            client.request(originalGet).flatMap(response -> {
                if (response.status().statusClass() == REDIRECTION_3XX) {
                    CharSequence location = response.headers().get(LOCATION);
                    HttpClient redirectClient = lookupClient(location, client, secureClient);
                    return redirectClient.request(redirectClient.newRequest(originalGet.method(), location.toString()).addHeader(CUSTOM_HEADER, originalGet.headers().get(CUSTOM_HEADER)));
                }
                // Decided not to follow redirect, return the original response or an error:
                return succeeded(response);
            }).whenOnSuccess(resp -> {
                System.out.println(resp.toString((name, value) -> value));
                System.out.println(resp.payloadBody(textSerializerAscii()));
                System.out.println();
            }).toFuture().get();
            System.out.println("- Redirect of a POST request with a payload body:");
            HttpRequest originalPost = client.post("/non-relative").payloadBody(client.executionContext().bufferAllocator().fromAscii("some_content"));
            client.request(originalPost).flatMap(response -> {
                if (response.status().statusClass() == REDIRECTION_3XX) {
                    CharSequence location = response.headers().get(LOCATION);
                    HttpClient redirectClient = lookupClient(location, client, secureClient);
                    return redirectClient.request(redirectClient.newRequest(originalPost.method(), location.toString()).payloadBody(originalPost.payloadBody()));
                }
                // Decided not to follow redirect, return the original response or an error:
                return succeeded(response);
            }).whenOnSuccess(resp -> {
                System.out.println(resp.toString((name, value) -> value));
                System.out.println(resp.payloadBody(textSerializerAscii()));
            }).toFuture().get();
        }
    }
}
Also used : HttpRequest(io.servicetalk.http.api.HttpRequest) HttpSerializers.textSerializerAscii(io.servicetalk.http.api.HttpSerializers.textSerializerAscii) REDIRECTION_3XX(io.servicetalk.http.api.HttpResponseStatus.StatusClass.REDIRECTION_3XX) CUSTOM_HEADER(io.servicetalk.examples.http.redirects.RedirectingServer.CUSTOM_HEADER) LOCATION(io.servicetalk.http.api.HttpHeaderNames.LOCATION) SECURE_SERVER_PORT(io.servicetalk.examples.http.redirects.RedirectingServer.SECURE_SERVER_PORT) NON_SECURE_SERVER_PORT(io.servicetalk.examples.http.redirects.RedirectingServer.NON_SECURE_SERVER_PORT) HttpRequest(io.servicetalk.http.api.HttpRequest) Single.succeeded(io.servicetalk.concurrent.api.Single.succeeded) HttpClient(io.servicetalk.http.api.HttpClient) ClientSslConfigBuilder(io.servicetalk.transport.api.ClientSslConfigBuilder) DefaultTestCerts(io.servicetalk.test.resources.DefaultTestCerts) HttpClients(io.servicetalk.http.netty.HttpClients) Nullable(javax.annotation.Nullable) HostAndPort(io.servicetalk.transport.api.HostAndPort) HttpClient(io.servicetalk.http.api.HttpClient) ClientSslConfigBuilder(io.servicetalk.transport.api.ClientSslConfigBuilder)

Example 18 with DefaultTestCerts

use of io.servicetalk.test.resources.DefaultTestCerts 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 19 with DefaultTestCerts

use of io.servicetalk.test.resources.DefaultTestCerts 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 = forResolvedAddress(hostNamePrefix + hostName + hostNameSuffix + (port == null ? "" : port), 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 : 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 20 with DefaultTestCerts

use of io.servicetalk.test.resources.DefaultTestCerts in project servicetalk by apple.

the class GrpcSslAndNonSslConnectionsTest method noSniClientDefaultServerFallbackSuccess.

@Test
void noSniClientDefaultServerFallbackSuccess() throws Exception {
    try (ServerContext serverContext = GrpcServers.forAddress(localAddress(0)).initializeHttp(builder -> builder.sslConfig(trustedServerConfig(), singletonMap(getLoopbackAddress().getHostName(), untrustedServerConfig()))).listenAndAwait(serviceFactory());
        BlockingTesterClient client = GrpcClients.forAddress(getLoopbackAddress().getHostName(), serverHostAndPort(serverContext).port()).initializeHttp(builder -> builder.sslConfig(new ClientSslConfigBuilder(DefaultTestCerts::loadServerCAPem).build()).inferPeerHost(false).inferSniHostname(false)).buildBlocking(clientFactory())) {
        final TesterProto.TestResponse response = client.test(REQUEST);
        assertThat(response, is(notNullValue()));
        assertThat(response.getMessage(), is(notNullValue()));
    }
}
Also used : BlockingTesterClient(io.servicetalk.grpc.netty.TesterProto.Tester.BlockingTesterClient) Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) AddressUtils.localAddress(io.servicetalk.transport.netty.internal.AddressUtils.localAddress) ServerContext(io.servicetalk.transport.api.ServerContext) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) ServerSslConfigBuilder(io.servicetalk.transport.api.ServerSslConfigBuilder) InetSocketAddress(java.net.InetSocketAddress) DefaultTestCerts.serverPemHostname(io.servicetalk.test.resources.DefaultTestCerts.serverPemHostname) Test(org.junit.jupiter.api.Test) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) GrpcStatusException(io.servicetalk.grpc.api.GrpcStatusException) ServerSslConfig(io.servicetalk.transport.api.ServerSslConfig) DEFAULT_STRATEGY_ASYNC_SERVICE(io.servicetalk.grpc.netty.ExecutionStrategyTestServices.DEFAULT_STRATEGY_ASYNC_SERVICE) StacklessClosedChannelException(io.servicetalk.transport.netty.internal.StacklessClosedChannelException) ClientSslConfigBuilder(io.servicetalk.transport.api.ClientSslConfigBuilder) AddressUtils.serverHostAndPort(io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort) Collections.singletonMap(java.util.Collections.singletonMap) Matchers.is(org.hamcrest.Matchers.is) DefaultTestCerts(io.servicetalk.test.resources.DefaultTestCerts) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) GrpcClientBuilder(io.servicetalk.grpc.api.GrpcClientBuilder) HostAndPort(io.servicetalk.transport.api.HostAndPort) InetAddress.getLoopbackAddress(java.net.InetAddress.getLoopbackAddress) ServerContext(io.servicetalk.transport.api.ServerContext) DefaultTestCerts(io.servicetalk.test.resources.DefaultTestCerts) ClientSslConfigBuilder(io.servicetalk.transport.api.ClientSslConfigBuilder) BlockingTesterClient(io.servicetalk.grpc.netty.TesterProto.Tester.BlockingTesterClient) Test(org.junit.jupiter.api.Test)

Aggregations

DefaultTestCerts (io.servicetalk.test.resources.DefaultTestCerts)21 ClientSslConfigBuilder (io.servicetalk.transport.api.ClientSslConfigBuilder)20 ServerContext (io.servicetalk.transport.api.ServerContext)15 ServerSslConfigBuilder (io.servicetalk.transport.api.ServerSslConfigBuilder)14 BlockingHttpClient (io.servicetalk.http.api.BlockingHttpClient)12 HostAndPort (io.servicetalk.transport.api.HostAndPort)9 AddressUtils.serverHostAndPort (io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort)9 HttpResponse (io.servicetalk.http.api.HttpResponse)8 DefaultTestCerts.serverPemHostname (io.servicetalk.test.resources.DefaultTestCerts.serverPemHostname)8 AddressUtils.localAddress (io.servicetalk.transport.netty.internal.AddressUtils.localAddress)8 MatcherAssert.assertThat (org.hamcrest.MatcherAssert.assertThat)8 Matchers.is (org.hamcrest.Matchers.is)8 Nullable (javax.annotation.Nullable)6 Matchers.instanceOf (org.hamcrest.Matchers.instanceOf)6 AfterEach (org.junit.jupiter.api.AfterEach)6 Assertions.assertThrows (org.junit.jupiter.api.Assertions.assertThrows)6 Test (org.junit.jupiter.api.Test)6 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)6 Single (io.servicetalk.concurrent.api.Single)5 OK (io.servicetalk.http.api.HttpResponseStatus.OK)5