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;
}
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();
}
}
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()));
}
}
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()));
}
}
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());
}
}
Aggregations