Search in sources :

Example 1 with DefaultTestCerts

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

the class GracefulConnectionClosureHandlingTest method setUp.

void setUp(HttpProtocol protocol, boolean initiateClosureFromClient, boolean useUds, boolean viaProxy) throws Exception {
    this.protocol = protocol;
    this.initiateClosureFromClient = initiateClosureFromClient;
    if (useUds) {
        Assumptions.assumeTrue(SERVER_CTX.ioExecutor().isUnixDomainSocketSupported(), "Server's IoExecutor does not support UnixDomainSocket");
        Assumptions.assumeTrue(CLIENT_CTX.ioExecutor().isUnixDomainSocketSupported(), "Client's IoExecutor does not support UnixDomainSocket");
        assumeFalse(viaProxy, "UDS cannot be used via proxy");
    }
    assumeFalse(protocol == HTTP_2 && viaProxy, "Proxy is not supported with HTTP/2");
    HttpServerBuilder serverBuilder = (useUds ? forAddress(newSocketAddress()) : forAddress(localAddress(0))).protocols(protocol.config).ioExecutor(SERVER_CTX.ioExecutor()).executor(SERVER_CTX.executor()).executionStrategy(defaultStrategy()).enableWireLogging("servicetalk-tests-wire-logger", TRACE, () -> true).appendConnectionAcceptorFilter(original -> new DelegatingConnectionAcceptor(original) {

        @Override
        public Completable accept(final ConnectionContext context) {
            if (!initiateClosureFromClient) {
                ((NettyConnectionContext) context).onClosing().whenFinally(onClosing::countDown).subscribe();
            }
            context.onClose().whenFinally(serverConnectionClosed::countDown).subscribe();
            connectionAccepted.countDown();
            return completed();
        }
    });
    HostAndPort proxyAddress = null;
    if (viaProxy) {
        // Dummy proxy helps to emulate old intermediate systems that do not support half-closed TCP connections
        proxyTunnel = new ProxyTunnel();
        proxyAddress = proxyTunnel.startProxy();
        serverBuilder.sslConfig(new ServerSslConfigBuilder(DefaultTestCerts::loadServerPem, DefaultTestCerts::loadServerKey).build());
    } else {
        proxyTunnel = null;
    }
    serverContext = serverBuilder.listenBlockingStreamingAndAwait((ctx, request, response) -> {
        serverReceivedRequest.countDown();
        response.addHeader(CONTENT_LENGTH, valueOf(RESPONSE_CONTENT.length()));
        serverSendResponse.await();
        try (HttpPayloadWriter<String> writer = response.sendMetaData(RAW_STRING_SERIALIZER)) {
            // Subscribe to the request payload body before response writer closes
            BlockingIterator<Buffer> iterator = request.payloadBody().iterator();
            // Consume request payload body asynchronously:
            ctx.executionContext().executor().submit(() -> {
                int receivedSize = 0;
                while (iterator.hasNext()) {
                    Buffer chunk = iterator.next();
                    assert chunk != null;
                    receivedSize += chunk.readableBytes();
                }
                serverReceivedRequestPayload.add(receivedSize);
            }).beforeOnError(cause -> {
                LOGGER.error("failure while reading request", cause);
                serverReceivedRequestPayload.add(-1);
            }).toFuture();
            serverSendResponsePayload.await();
            writer.write(RESPONSE_CONTENT);
        }
    });
    serverContext.onClose().whenFinally(serverContextClosed::countDown).subscribe();
    client = (viaProxy ? forSingleAddress(serverHostAndPort(serverContext)).proxyAddress(proxyAddress).sslConfig(new ClientSslConfigBuilder(DefaultTestCerts::loadServerCAPem).peerHost(serverPemHostname()).build()) : forResolvedAddress(serverContext.listenAddress())).protocols(protocol.config).executor(CLIENT_CTX.executor()).ioExecutor(CLIENT_CTX.ioExecutor()).executionStrategy(defaultStrategy()).enableWireLogging("servicetalk-tests-wire-logger", TRACE, Boolean.TRUE::booleanValue).appendConnectionFactoryFilter(ConnectionFactoryFilter.withStrategy(cf -> initiateClosureFromClient ? new OnClosingConnectionFactoryFilter<>(cf, onClosing) : cf, ExecutionStrategy.offloadNone())).buildStreaming();
    connection = client.reserveConnection(client.get("/")).toFuture().get();
    connection.onClose().whenFinally(clientConnectionClosed::countDown).subscribe();
    // wait until server accepts connection
    connectionAccepted.await();
    toClose = initiateClosureFromClient ? connection : serverContext;
}
Also used : SocketAddress(java.net.SocketAddress) HttpProtocol.values(io.servicetalk.http.netty.HttpProtocol.values) PlatformDependent.throwException(io.servicetalk.utils.internal.PlatformDependent.throwException) ServerSslConfigBuilder(io.servicetalk.transport.api.ServerSslConfigBuilder) LoggerFactory(org.slf4j.LoggerFactory) HttpSerializers.stringStreamingSerializer(io.servicetalk.http.api.HttpSerializers.stringStreamingSerializer) ZERO(io.servicetalk.http.api.HttpHeaderValues.ZERO) Future(java.util.concurrent.Future) CloseEvent(io.servicetalk.transport.netty.internal.CloseHandler.CloseEvent) HttpExecutionStrategies.defaultStrategy(io.servicetalk.http.api.HttpExecutionStrategies.defaultStrategy) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Arrays.asList(java.util.Arrays.asList) Assumptions.assumeFalse(org.junit.jupiter.api.Assumptions.assumeFalse) DefaultTestCerts(io.servicetalk.test.resources.DefaultTestCerts) MethodSource(org.junit.jupiter.params.provider.MethodSource) GRACEFUL_USER_CLOSING(io.servicetalk.transport.netty.internal.CloseHandler.CloseEvent.GRACEFUL_USER_CLOSING) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) Collection(java.util.Collection) HttpClients.forSingleAddress(io.servicetalk.http.netty.HttpClients.forSingleAddress) ConnectionFactoryFilter(io.servicetalk.client.api.ConnectionFactoryFilter) CompositeCloseable(io.servicetalk.concurrent.api.CompositeCloseable) CHANNEL_CLOSED_INBOUND(io.servicetalk.transport.netty.internal.CloseHandler.CloseEvent.CHANNEL_CLOSED_INBOUND) BlockingQueue(java.util.concurrent.BlockingQueue) AsyncCloseables.newCompositeCloseable(io.servicetalk.concurrent.api.AsyncCloseables.newCompositeCloseable) Arguments(org.junit.jupiter.params.provider.Arguments) CONTENT_LENGTH(io.servicetalk.http.api.HttpHeaderNames.CONTENT_LENGTH) HttpClients.forResolvedAddress(io.servicetalk.http.netty.HttpClients.forResolvedAddress) DefaultTestCerts.serverPemHostname(io.servicetalk.test.resources.DefaultTestCerts.serverPemHostname) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) CountDownLatch(java.util.concurrent.CountDownLatch) HttpsProxyTest.safeClose(io.servicetalk.http.netty.HttpsProxyTest.safeClose) Buffer(io.servicetalk.buffer.api.Buffer) DelegatingConnectionAcceptor(io.servicetalk.transport.api.DelegatingConnectionAcceptor) TransportObserver(io.servicetalk.transport.api.TransportObserver) ClientSslConfigBuilder(io.servicetalk.transport.api.ClientSslConfigBuilder) HTTP_2(io.servicetalk.http.netty.HttpProtocol.HTTP_2) Matchers.is(org.hamcrest.Matchers.is) BlockingIterator(io.servicetalk.concurrent.BlockingIterator) ReservedStreamingHttpConnection(io.servicetalk.http.api.ReservedStreamingHttpConnection) Matchers.anyOf(org.hamcrest.Matchers.anyOf) Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) TRACE(io.servicetalk.logging.api.LogLevel.TRACE) HttpServers.forAddress(io.servicetalk.http.netty.HttpServers.forAddress) FilterableStreamingHttpConnection(io.servicetalk.http.api.FilterableStreamingHttpConnection) ArrayList(java.util.ArrayList) HttpPayloadWriter(io.servicetalk.http.api.HttpPayloadWriter) ExecutionStrategy(io.servicetalk.transport.api.ExecutionStrategy) RegisterExtension(org.junit.jupiter.api.extension.RegisterExtension) CloseEventObservedException(io.servicetalk.transport.netty.internal.CloseHandler.CloseEventObservedException) Objects.requireNonNull(java.util.Objects.requireNonNull) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) AddressUtils.serverHostAndPort(io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort) AsyncCloseable(io.servicetalk.concurrent.api.AsyncCloseable) NettyConnectionContext(io.servicetalk.transport.netty.internal.NettyConnectionContext) Matchers.contentEqualTo(io.servicetalk.buffer.api.Matchers.contentEqualTo) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) DelegatingConnectionFactory(io.servicetalk.client.api.DelegatingConnectionFactory) Publisher.from(io.servicetalk.concurrent.api.Publisher.from) HttpServerBuilder(io.servicetalk.http.api.HttpServerBuilder) Nullable(javax.annotation.Nullable) ConnectionContext(io.servicetalk.transport.api.ConnectionContext) ConnectionFactory(io.servicetalk.client.api.ConnectionFactory) AddressUtils.localAddress(io.servicetalk.transport.netty.internal.AddressUtils.localAddress) Logger(org.slf4j.Logger) AddressUtils.newSocketAddress(io.servicetalk.transport.netty.internal.AddressUtils.newSocketAddress) ServerContext(io.servicetalk.transport.api.ServerContext) ClosedChannelException(java.nio.channels.ClosedChannelException) UTF_8(java.nio.charset.StandardCharsets.UTF_8) Single(io.servicetalk.concurrent.api.Single) Completable(io.servicetalk.concurrent.api.Completable) ExecutionContextExtension(io.servicetalk.transport.netty.internal.ExecutionContextExtension) IOException(java.io.IOException) OK(io.servicetalk.http.api.HttpResponseStatus.OK) Integer.parseInt(java.lang.Integer.parseInt) ExecutionException(java.util.concurrent.ExecutionException) AfterEach(org.junit.jupiter.api.AfterEach) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) String.valueOf(java.lang.String.valueOf) Assumptions(org.junit.jupiter.api.Assumptions) Executable(org.junit.jupiter.api.function.Executable) Completable.completed(io.servicetalk.concurrent.api.Completable.completed) HttpStreamingSerializer(io.servicetalk.http.api.HttpStreamingSerializer) HostAndPort(io.servicetalk.transport.api.HostAndPort) Buffer(io.servicetalk.buffer.api.Buffer) Completable(io.servicetalk.concurrent.api.Completable) 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) NettyConnectionContext(io.servicetalk.transport.netty.internal.NettyConnectionContext) ConnectionContext(io.servicetalk.transport.api.ConnectionContext) HttpPayloadWriter(io.servicetalk.http.api.HttpPayloadWriter) BlockingIterator(io.servicetalk.concurrent.BlockingIterator) ServerSslConfigBuilder(io.servicetalk.transport.api.ServerSslConfigBuilder)

Example 2 with DefaultTestCerts

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

the class MultiAddressUrlRedirectClient method main.

public static void main(String... args) throws Exception {
    try (HttpClient client = HttpClients.forMultiAddressUrl().followRedirects(new RedirectConfigBuilder().maxRedirects(3).allowNonRelativeRedirects(true).allowedMethods(GET, POST).redirectPredicate((relative, redirectCount, prevRequest, redirectResponse) -> // allow only relative redirects
    relative || // OR non-relative redirects to a trusted server:
    redirectResponse.headers().get(LOCATION, "").toString().startsWith("https://localhost:" + SECURE_SERVER_PORT)).headersToRedirect(CUSTOM_HEADER).redirectPayloadBody(true).redirectRequestTransformer((relative, prevRequest, redirectResponse, redirectedRequest) -> {
        // prevRequest and redirectResponse: check/copy other headers, modify request method, etc.
        return redirectedRequest;
    }).build()).initializer((scheme, address, builder) -> {
        // already provides default SSL configuration and this step may be skipped.
        if ("https".equalsIgnoreCase(scheme)) {
            builder.sslConfig(new ClientSslConfigBuilder(DefaultTestCerts::loadServerCAPem).build());
        }
    }).build()) {
        final String serverThatRedirects = "http://localhost:" + NON_SECURE_SERVER_PORT;
        System.out.println("- Simple GET request:");
        client.request(client.get(serverThatRedirects + "/relative")).whenOnSuccess(resp -> {
            System.out.println(resp.toString((name, value) -> value));
            System.out.println(resp.payloadBody(textSerializerAscii()));
            System.out.println();
        }).toFuture().get();
        System.out.println("- Relative redirect for POST request with headers and payload body:");
        client.request(client.post(serverThatRedirects + "/relative").addHeader(CUSTOM_HEADER, "value").payloadBody(client.executionContext().bufferAllocator().fromAscii("some_content"))).whenOnSuccess(resp -> {
            System.out.println(resp.toString((name, value) -> value));
            System.out.println(resp.payloadBody(textSerializerAscii()));
            System.out.println();
        }).toFuture().get();
        System.out.println("- Non-relative redirect for POST request with headers and payload body:");
        client.request(client.post(serverThatRedirects + "/non-relative").addHeader(CUSTOM_HEADER, "value").payloadBody(client.executionContext().bufferAllocator().fromAscii("some_content"))).whenOnSuccess(resp -> {
            System.out.println(resp.toString((name, value) -> value));
            System.out.println(resp.payloadBody(textSerializerAscii()));
            System.out.println();
        }).toFuture().get();
    }
}
Also used : HttpSerializers.textSerializerAscii(io.servicetalk.http.api.HttpSerializers.textSerializerAscii) HttpRequestMethod(io.servicetalk.http.api.HttpRequestMethod) CUSTOM_HEADER(io.servicetalk.examples.http.redirects.RedirectingServer.CUSTOM_HEADER) LOCATION(io.servicetalk.http.api.HttpHeaderNames.LOCATION) POST(io.servicetalk.http.api.HttpRequestMethod.POST) MultiAddressHttpClientBuilder(io.servicetalk.http.api.MultiAddressHttpClientBuilder) RedirectConfigBuilder(io.servicetalk.http.api.RedirectConfigBuilder) GET(io.servicetalk.http.api.HttpRequestMethod.GET) 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) RedirectConfig(io.servicetalk.http.api.RedirectConfig) HttpClient(io.servicetalk.http.api.HttpClient) ClientSslConfigBuilder(io.servicetalk.transport.api.ClientSslConfigBuilder) DefaultTestCerts(io.servicetalk.test.resources.DefaultTestCerts) HttpClients(io.servicetalk.http.netty.HttpClients) HttpClient(io.servicetalk.http.api.HttpClient) RedirectConfigBuilder(io.servicetalk.http.api.RedirectConfigBuilder) ClientSslConfigBuilder(io.servicetalk.transport.api.ClientSslConfigBuilder)

Example 3 with DefaultTestCerts

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

the class HttpClientWithAlpn method main.

public static void main(String[] args) throws Exception {
    // streaming API see helloworld examples.
    try (BlockingHttpClient client = HttpClients.forSingleAddress("localhost", 8080).protocols(h2Default(), // Configure support for HTTP/2 and HTTP/1.1 protocols
    h1Default()).sslConfig(new ClientSslConfigBuilder(DefaultTestCerts::loadServerCAPem).build()).buildBlocking()) {
        HttpResponse response = client.request(client.get("/"));
        System.out.println(response.toString((name, value) -> value));
        System.out.println(response.payloadBody(textSerializerUtf8()));
    }
}
Also used : BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) HttpProtocolConfigs.h1Default(io.servicetalk.http.netty.HttpProtocolConfigs.h1Default) HttpProtocolConfigs.h2Default(io.servicetalk.http.netty.HttpProtocolConfigs.h2Default) HttpSerializers.textSerializerUtf8(io.servicetalk.http.api.HttpSerializers.textSerializerUtf8) HttpResponse(io.servicetalk.http.api.HttpResponse) ClientSslConfigBuilder(io.servicetalk.transport.api.ClientSslConfigBuilder) DefaultTestCerts(io.servicetalk.test.resources.DefaultTestCerts) HttpClients(io.servicetalk.http.netty.HttpClients) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) HttpResponse(io.servicetalk.http.api.HttpResponse) ClientSslConfigBuilder(io.servicetalk.transport.api.ClientSslConfigBuilder)

Example 4 with DefaultTestCerts

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

the class HttpClientMutualTLS method main.

public static void main(String[] args) throws Exception {
    // streaming API see helloworld examples.
    try (BlockingHttpClient client = HttpClients.forSingleAddress("localhost", 8080).sslConfig(new ClientSslConfigBuilder(DefaultTestCerts::loadServerCAPem).keyManager(DefaultTestCerts::loadClientPem, DefaultTestCerts::loadClientKey).build()).buildBlocking()) {
        HttpResponse response = client.request(client.get("/"));
        System.out.println(response.toString((name, value) -> value));
        System.out.println(response.payloadBody(textSerializerUtf8()));
    }
}
Also used : BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) HttpSerializers.textSerializerUtf8(io.servicetalk.http.api.HttpSerializers.textSerializerUtf8) HttpResponse(io.servicetalk.http.api.HttpResponse) ClientSslConfigBuilder(io.servicetalk.transport.api.ClientSslConfigBuilder) DefaultTestCerts(io.servicetalk.test.resources.DefaultTestCerts) HttpClients(io.servicetalk.http.netty.HttpClients) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) HttpResponse(io.servicetalk.http.api.HttpResponse) DefaultTestCerts(io.servicetalk.test.resources.DefaultTestCerts) ClientSslConfigBuilder(io.servicetalk.transport.api.ClientSslConfigBuilder)

Example 5 with DefaultTestCerts

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

the class MutualSslTest method mutualSsl.

@ParameterizedTest
@MethodSource("params")
void mutualSsl(SslProvider serverSslProvider, SslProvider clientSslProvider, @SuppressWarnings("rawtypes") Map<SocketOption, Object> serverListenOptions, @SuppressWarnings("rawtypes") Map<SocketOption, Object> clientOptions) throws Exception {
    assumeTcpFastOpen(clientOptions);
    HttpServerBuilder serverBuilder = HttpServers.forAddress(localAddress(0)).sslConfig(new ServerSslConfigBuilder(DefaultTestCerts::loadServerPem, DefaultTestCerts::loadServerKey).trustManager(DefaultTestCerts::loadClientCAPem).clientAuthMode(REQUIRE).provider(serverSslProvider).build());
    for (@SuppressWarnings("rawtypes") Entry<SocketOption, Object> entry : serverListenOptions.entrySet()) {
        @SuppressWarnings("unchecked") SocketOption<Object> option = entry.getKey();
        serverBuilder.listenSocketOption(option, entry.getValue());
    }
    try (ServerContext serverContext = serverBuilder.listenBlockingAndAwait((ctx, request, responseFactory) -> responseFactory.ok());
        BlockingHttpClient client = newClientBuilder(serverContext, clientOptions).sslConfig(new ClientSslConfigBuilder(DefaultTestCerts::loadServerCAPem).provider(clientSslProvider).peerHost(serverPemHostname()).keyManager(DefaultTestCerts::loadClientPem, DefaultTestCerts::loadClientKey).build()).buildBlocking()) {
        assertEquals(HttpResponseStatus.OK, client.request(client.get("/")).status());
    }
}
Also used : SocketOption(java.net.SocketOption) ServerContext(io.servicetalk.transport.api.ServerContext) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) HttpServerBuilder(io.servicetalk.http.api.HttpServerBuilder) 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)

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