fix(cloudfront): honor the origin completion and keep-alive timeouts (#6198)

This commit is contained in:
Matheus Oliveira authored and GitHub committed 2026-10-24 14:17:34 -04:00
1 parent c5ab54d49c
commit 8d25cd91a6
13 files changed
+909 -88

No files matched your search

@@ -184,8 +184,10 @@ class CloudFrontCfnProvisionerTest {
{"DistributionConfig": {
"Origins": [{"Id": "o1", "DomainName": "origin.example.com",
"ConnectionAttempts": 2, "ConnectionTimeout": 5,
"ResponseCompletionTimeout": 90,
"CustomOriginConfig": {"OriginProtocolPolicy": "https-only",
"OriginReadTimeout": 45}}],
"OriginReadTimeout": 45,
"OriginKeepaliveTimeout": 120}}],
"DefaultCacheBehavior": {"TargetOriginId": "o1", "ViewerProtocolPolicy": "redirect-to-https"}
}}
"""), distributionCtx(null));
@@ -195,8 +197,11 @@ class CloudFrontCfnProvisionerTest {
Origin origin = sent.getValue().getConfig().getOrigins().getFirst();
assertEquals(2, origin.getConnectionAttempts());
assertEquals(5, origin.getConnectionTimeout());
// ResponseCompletionTimeout lives on the origin, where the serving layer reads it.
assertEquals(Integer.valueOf(90), origin.getResponseCompletionTimeout());
// OriginReadTimeout lives on CustomOriginConfig, where the serving layer reads it.
assertEquals(Integer.valueOf(45), origin.getCustomOriginConfig().get("OriginReadTimeout"));
assertEquals(Integer.valueOf(120), origin.getCustomOriginConfig().get("OriginKeepaliveTimeout"));
}
@Test
@@ -476,23 +476,6 @@ class CloudFrontControllerTest {
}
}
@Test
void responseCompletionTimeoutBelowOriginReadTimeoutIsRejected() {
CloudFrontService service = mock(CloudFrontService.class);
CloudFrontController controller = new CloudFrontController(service);
String body = distributionConfigBody("").replace(
"<OriginProtocolPolicy>https-only</OriginProtocolPolicy></CustomOriginConfig>",
"<OriginProtocolPolicy>https-only</OriginProtocolPolicy>"
+ "<OriginReadTimeout>60</OriginReadTimeout></CustomOriginConfig>"
+ "<ResponseCompletionTimeout>30</ResponseCompletionTimeout>");
try (Response created = controller.createDistribution(null, body)) {
assertEquals(400, created.getStatus());
assertTrue(((String) created.getEntity()).contains("InvalidArgument"));
}
}
@Test
void responseCompletionTimeoutAtLeastOriginReadTimeoutIsAccepted() {
CloudFrontService service = mock(CloudFrontService.class);
@@ -510,22 +493,6 @@ class CloudFrontControllerTest {
}
}
@Test
void responseCompletionTimeoutBelowTheImplicitOriginReadTimeoutDefaultIsRejected() {
CloudFrontService service = mock(CloudFrontService.class);
CloudFrontController controller = new CloudFrontController(service);
String body = distributionConfigBody("").replace(
"<OriginProtocolPolicy>https-only</OriginProtocolPolicy></CustomOriginConfig>",
"<OriginProtocolPolicy>https-only</OriginProtocolPolicy></CustomOriginConfig>"
+ "<ResponseCompletionTimeout>10</ResponseCompletionTimeout>");
try (Response created = controller.createDistribution(null, body)) {
assertEquals(400, created.getStatus());
assertTrue(((String) created.getEntity()).contains("InvalidArgument"));
}
}
@Test
void defaultCacheBehaviorRoundTripsForwardedValues() {
CloudFrontService service = mock(CloudFrontService.class);
@@ -396,6 +396,50 @@ class CloudFrontCustomOriginServingTest {
"expected the 1 s origin read timeout to end the request, took " + elapsedMillis + " ms");
}
@Test
void endsTheViewerResponseWhenTheOriginDoesNotCompleteItInTime() throws Exception {
// The origin answers with its headers, then trickles a body in for longer than the
// completion timeout allows. The viewer has its status line by then, so the response ends
// with the body the origin managed to send.
int bodyBytes = 100;
originServer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
originServer.setExecutor(Executors.newVirtualThreadPerTaskExecutor());
originServer.createContext("/", exchange -> {
exchange.sendResponseHeaders(200, bodyBytes);
try (OutputStream out = exchange.getResponseBody()) {
for (int sent = 0; sent < bodyBytes; sent++) {
out.write('x');
out.flush();
Thread.sleep(100);
}
} catch (IOException | InterruptedException expected) {
// The origin connection ended, which is what the completion timeout does.
} finally {
exchange.close();
}
});
originServer.start();
Distribution created = createDistribution(
customOriginDistribution(allMethodsBehavior(), null, 2, 1, 2));
long started = System.nanoTime();
byte[] response = readViewerResponse(created.getDomainName(), "/page");
long elapsedMillis = (System.nanoTime() - started) / 1_000_000;
assertTrue(new String(response, StandardCharsets.ISO_8859_1).startsWith("HTTP/1.1 200"),
"expected the origin's status line, got " + new String(response, StandardCharsets.ISO_8859_1));
int sent = 0;
for (byte value : response) {
if (value == 'x') {
sent++;
}
}
assertTrue(sent < bodyBytes,
"expected the response to end before the whole body, got " + sent + " of " + bodyBytes + " bytes");
assertTrue(elapsedMillis < 5000,
"expected the 2 s completion timeout to end the response, took " + elapsedMillis + " ms");
}
@Test
void streamsALargeOriginResponseWithItsLength() throws Exception {
byte[] video = randomBytes(3 * 1024 * 1024 + 1);
@@ -1128,6 +1172,14 @@ class CloudFrontCustomOriginServingTest {
List<Map<String, String>> customHeaders,
Integer readTimeoutSeconds,
Integer connectionAttempts) {
return customOriginDistribution(behavior, customHeaders, readTimeoutSeconds, connectionAttempts, null);
}
private Distribution customOriginDistribution(DefaultCacheBehavior behavior,
List<Map<String, String>> customHeaders,
Integer readTimeoutSeconds,
Integer connectionAttempts,
Integer completionTimeoutSeconds) {
Map<String, Object> originConfig = customOriginConfig(originServer.getAddress().getPort());
if (readTimeoutSeconds != null) {
originConfig.put("OriginReadTimeout", readTimeoutSeconds);
@@ -1140,6 +1192,9 @@ class CloudFrontCustomOriginServingTest {
if (connectionAttempts != null) {
customOrigin.setConnectionAttempts(connectionAttempts);
}
if (completionTimeoutSeconds != null) {
customOrigin.setResponseCompletionTimeout(completionTimeoutSeconds);
}
DistributionConfig config = new DistributionConfig();
config.setEnabled(true);
config.setOrigins(List.of(customOrigin));
@@ -1149,6 +1204,20 @@ class CloudFrontCustomOriginServingTest {
return distribution;
}
/**
* The viewer's whole response, read from a raw socket, since a response the origin ends
* midway is not one RestAssured can read.
*/
private static byte[] readViewerResponse(String host, String path) throws Exception {
try (Socket viewer = new Socket("127.0.0.1", RestAssured.port)) {
viewer.setSoTimeout(15000);
viewer.getOutputStream().write(("GET " + path + " HTTP/1.1\r\nHost: " + host
+ "\r\nConnection: close\r\n\r\n").getBytes(StandardCharsets.US_ASCII));
viewer.getOutputStream().flush();
return viewer.getInputStream().readAllBytes();
}
}
private static List<Map<String, String>> originVerifyHeader() {
return List.of(new LinkedHashMap<>(Map.of(
"HeaderName", "X-Origin-Verify", "HeaderValue", "s3cr3t")));
@@ -8,6 +8,9 @@ import io.github.hectorvent.floci.core.common.Pem;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
import org.apache.hc.client5.http.DnsResolver;
import org.apache.hc.client5.http.protocol.HttpClientContext;
import org.apache.hc.core5.http.message.BasicHttpResponse;
import org.apache.hc.core5.util.TimeValue;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.jupiter.api.Test;
@@ -18,6 +21,7 @@ import javax.net.ssl.SNIServerName;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -25,6 +29,8 @@ import java.net.ConnectException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.UnknownHostException;
import java.net.http.HttpRequest;
@@ -48,6 +54,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
class CloudFrontOriginHttpClientTest {
@@ -373,7 +380,9 @@ class CloudFrontOriginHttpClientTest {
resolver(InetAddress.getByName("127.0.0.1")), List.of("origin.invalid"))) {
CloudFrontOriginHttpClient.OriginTimeouts timeouts =
new CloudFrontOriginHttpClient.OriginTimeouts(
Duration.ofSeconds(1), Duration.ofMillis(200), 3);
Duration.ofSeconds(1), Duration.ofMillis(200), 3,
CloudFrontOriginTimeouts.DEFAULT_RESPONSE_COMPLETION_TIMEOUT,
CloudFrontOriginTimeouts.DEFAULT_ORIGIN_KEEPALIVE_TIMEOUT);
HttpRequest request = request("http://origin.invalid:" + server.getAddress().getPort() + "/");
long started = System.nanoTime();
@@ -399,7 +408,9 @@ class CloudFrontOriginHttpClientTest {
resolver(InetAddress.getByName("127.0.0.1")), List.of("origin.invalid"))) {
CloudFrontOriginHttpClient.OriginTimeouts timeouts =
new CloudFrontOriginHttpClient.OriginTimeouts(
Duration.ofSeconds(1), Duration.ofMillis(200), 1);
Duration.ofSeconds(1), Duration.ofMillis(200), 1,
CloudFrontOriginTimeouts.DEFAULT_RESPONSE_COMPLETION_TIMEOUT,
CloudFrontOriginTimeouts.DEFAULT_ORIGIN_KEEPALIVE_TIMEOUT);
HttpRequest request = request("http://origin.invalid:" + server.getAddress().getPort() + "/");
assertThrows(CloudFrontOriginTimeoutException.class, () -> get(client, request, timeouts));
@@ -420,7 +431,9 @@ class CloudFrontOriginHttpClientTest {
resolver(InetAddress.getByName("127.0.0.1")), List.of("origin.invalid"))) {
CloudFrontOriginHttpClient.OriginTimeouts timeouts =
new CloudFrontOriginHttpClient.OriginTimeouts(
Duration.ofSeconds(1), Duration.ofMillis(200), 3);
Duration.ofSeconds(1), Duration.ofMillis(200), 3,
CloudFrontOriginTimeouts.DEFAULT_RESPONSE_COMPLETION_TIMEOUT,
CloudFrontOriginTimeouts.DEFAULT_ORIGIN_KEEPALIVE_TIMEOUT);
HttpRequest request = HttpRequest.newBuilder(URI.create(
"http://origin.invalid:" + server.getAddress().getPort() + "/"))
.method("POST", HttpRequest.BodyPublishers.noBody())
@@ -443,7 +456,9 @@ class CloudFrontOriginHttpClientTest {
resolver, List.of("blackhole.invalid"))) {
CloudFrontOriginHttpClient.OriginTimeouts timeouts =
new CloudFrontOriginHttpClient.OriginTimeouts(
Duration.ofMillis(100), Duration.ofSeconds(5), 3);
Duration.ofMillis(100), Duration.ofSeconds(5), 3,
CloudFrontOriginTimeouts.DEFAULT_RESPONSE_COMPLETION_TIMEOUT,
CloudFrontOriginTimeouts.DEFAULT_ORIGIN_KEEPALIVE_TIMEOUT);
HttpRequest request = HttpRequest.newBuilder(URI.create("http://blackhole.invalid:81/"))
.method("POST", HttpRequest.BodyPublishers.noBody())
.build();
@@ -467,7 +482,9 @@ class CloudFrontOriginHttpClientTest {
resolver, List.of("refused.invalid"))) {
CloudFrontOriginHttpClient.OriginTimeouts timeouts =
new CloudFrontOriginHttpClient.OriginTimeouts(
Duration.ofSeconds(1), Duration.ofSeconds(5), 3);
Duration.ofSeconds(1), Duration.ofSeconds(5), 3,
CloudFrontOriginTimeouts.DEFAULT_RESPONSE_COMPLETION_TIMEOUT,
CloudFrontOriginTimeouts.DEFAULT_ORIGIN_KEEPALIVE_TIMEOUT);
HttpRequest request = HttpRequest.newBuilder(URI.create(
"http://refused.invalid:" + refusedPort + "/"))
.method("POST", HttpRequest.BodyPublishers.noBody())
@@ -489,7 +506,9 @@ class CloudFrontOriginHttpClientTest {
resolver(InetAddress.getByName("127.0.0.1")), List.of("origin.invalid"))) {
CloudFrontOriginHttpClient.OriginTimeouts timeouts =
new CloudFrontOriginHttpClient.OriginTimeouts(
Duration.ofSeconds(1), Duration.ofMillis(150), 1);
Duration.ofSeconds(1), Duration.ofMillis(150), 1,
CloudFrontOriginTimeouts.DEFAULT_RESPONSE_COMPLETION_TIMEOUT,
CloudFrontOriginTimeouts.DEFAULT_ORIGIN_KEEPALIVE_TIMEOUT);
HttpRequest request = request("http://origin.invalid:" + server.getAddress().getPort() + "/");
long started = System.nanoTime();
@@ -505,6 +524,332 @@ class CloudFrontOriginHttpClientTest {
}
}
@Test
void theCompletionTimeoutBoundsTheWaitForTheResponseHeaders() throws Exception {
AtomicInteger hits = new AtomicInteger();
CountDownLatch release = new CountDownLatch(1);
HttpServer server = holdingServer(hits, release);
try (CloudFrontOriginHttpClient client = new CloudFrontOriginHttpClient(
resolver(InetAddress.getByName("127.0.0.1")), List.of("origin.invalid"))) {
// The read timeout is far longer than the completion timeout, so the completion timeout
// is the one that has to end the request.
CloudFrontOriginHttpClient.OriginTimeouts timeouts =
new CloudFrontOriginHttpClient.OriginTimeouts(
Duration.ofSeconds(1), Duration.ofSeconds(30), 1,
Duration.ofMillis(500),
CloudFrontOriginTimeouts.DEFAULT_ORIGIN_KEEPALIVE_TIMEOUT);
HttpRequest request = request("http://origin.invalid:" + server.getAddress().getPort() + "/");
long started = System.nanoTime();
assertThrows(CloudFrontOriginTimeoutException.class, () -> get(client, request, timeouts));
long elapsedMillis = (System.nanoTime() - started) / 1_000_000;
assertTrue(elapsedMillis < 5000,
"expected the 500 ms completion timeout to end the request, not the 30 s read "
+ "timeout, took " + elapsedMillis + " ms");
} finally {
release.countDown();
server.stop(0);
}
}
@Test
void theCompletionTimeoutBoundsTheRetriesToo() throws Exception {
AtomicInteger hits = new AtomicInteger();
CountDownLatch release = new CountDownLatch(1);
HttpServer server = holdingServer(hits, release);
try (CloudFrontOriginHttpClient client = new CloudFrontOriginHttpClient(
resolver(InetAddress.getByName("127.0.0.1")), List.of("origin.invalid"))) {
CloudFrontOriginHttpClient.OriginTimeouts timeouts =
new CloudFrontOriginHttpClient.OriginTimeouts(
Duration.ofSeconds(1), Duration.ofSeconds(30), 3,
Duration.ofMillis(600),
CloudFrontOriginTimeouts.DEFAULT_ORIGIN_KEEPALIVE_TIMEOUT);
HttpRequest request = request("http://origin.invalid:" + server.getAddress().getPort() + "/");
long started = System.nanoTime();
assertThrows(CloudFrontOriginTimeoutException.class, () -> get(client, request, timeouts));
long elapsedMillis = (System.nanoTime() - started) / 1_000_000;
assertTrue(elapsedMillis < 3000,
"expected the completion timeout to bound the retries as well, took "
+ elapsedMillis + " ms");
} finally {
release.countDown();
server.stop(0);
}
}
@Test
void theCompletionTimeoutEndsAResponseThatNeverCompletes() throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.setExecutor(Executors.newVirtualThreadPerTaskExecutor());
server.createContext("/", exchange -> {
exchange.sendResponseHeaders(200, 0);
try (OutputStream out = exchange.getResponseBody()) {
// A body that never ends: it keeps sending, one byte at a time, past the deadline.
for (int sent = 0; sent < 200; sent++) {
out.write('x');
out.flush();
Thread.sleep(100);
}
} catch (IOException | InterruptedException expected) {
// The client ended the connection, which is what the completion timeout does.
} finally {
exchange.close();
}
});
server.start();
try (CloudFrontOriginHttpClient client = new CloudFrontOriginHttpClient(
resolver(InetAddress.getByName("127.0.0.1")), List.of("origin.invalid"))) {
CloudFrontOriginHttpClient.OriginTimeouts timeouts =
new CloudFrontOriginHttpClient.OriginTimeouts(
Duration.ofSeconds(1), Duration.ofSeconds(30), 1,
Duration.ofMillis(700),
CloudFrontOriginTimeouts.DEFAULT_ORIGIN_KEEPALIVE_TIMEOUT);
CloudFrontOriginHttpClient.OpenResponse response =
get(client, request("http://origin.invalid:" + server.getAddress().getPort() + "/"),
timeouts);
long started = System.nanoTime();
assertThrows(CloudFrontOriginTimeoutException.class, () -> readAll(response));
long elapsedMillis = (System.nanoTime() - started) / 1_000_000;
assertTrue(elapsedMillis < 5000,
"expected the 700 ms completion timeout to end the body, took " + elapsedMillis
+ " ms");
} finally {
server.stop(0);
}
}
@Test
void keepsTheOriginConnectionForTheConfiguredKeepAlive() throws Exception {
List<InetSocketAddress> peers = new CopyOnWriteArrayList<>();
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/", exchange -> {
peers.add(exchange.getRemoteAddress());
byte[] body = "origin-ok".getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(200, body.length);
exchange.getResponseBody().write(body);
exchange.close();
});
server.start();
try (CloudFrontOriginHttpClient client = new CloudFrontOriginHttpClient(
resolver(InetAddress.getByName("127.0.0.1")), List.of("origin.invalid"))) {
String uri = "http://origin.invalid:" + server.getAddress().getPort() + "/";
CloudFrontOriginHttpClient.OriginTimeouts timeouts =
new CloudFrontOriginHttpClient.OriginTimeouts(
Duration.ofSeconds(1), Duration.ofSeconds(5), 1,
CloudFrontOriginTimeouts.DEFAULT_RESPONSE_COMPLETION_TIMEOUT,
Duration.ofSeconds(300));
readAll(get(client, request(uri), timeouts));
readAll(get(client, request(uri), timeouts));
assertEquals(2, peers.size());
assertEquals(peers.get(0), peers.get(1),
"the connection was kept for the configured keep-alive and reused");
} finally {
server.stop(0);
}
}
@Test
void theKeepAliveStrategyReturnsTheOriginsKeepAlive() {
CloudFrontOriginHttpClient.KeepAliveStrategy strategy =
new CloudFrontOriginHttpClient.KeepAliveStrategy();
// The context the client sends, so the test fails if it stops carrying the keep-alive.
CloudFrontOriginHttpClient.OriginTimeouts timeouts =
new CloudFrontOriginHttpClient.OriginTimeouts(
Duration.ofSeconds(1), Duration.ofSeconds(30), 1,
CloudFrontOriginTimeouts.DEFAULT_RESPONSE_COMPLETION_TIMEOUT,
Duration.ofSeconds(2));
HttpClientContext context = CloudFrontOriginHttpClient.context(timeouts);
assertEquals(TimeValue.ofSeconds(2),
strategy.getKeepAliveDuration(new BasicHttpResponse(200), context));
BasicHttpResponse originAsksForLess = new BasicHttpResponse(200);
originAsksForLess.addHeader("Keep-Alive", "timeout=1");
assertEquals(TimeValue.ofSeconds(1),
strategy.getKeepAliveDuration(originAsksForLess, context),
"the origin's own Keep-Alive header shortens the setting");
BasicHttpResponse originAsksForMore = new BasicHttpResponse(200);
originAsksForMore.addHeader("Keep-Alive", "timeout=30");
assertEquals(TimeValue.ofSeconds(2),
strategy.getKeepAliveDuration(originAsksForMore, context),
"the setting caps what the origin asks for");
assertEquals(
TimeValue.ofSeconds(CloudFrontOriginTimeouts.DEFAULT_ORIGIN_KEEPALIVE_TIMEOUT_SECONDS),
strategy.getKeepAliveDuration(new BasicHttpResponse(200), HttpClientContext.create()),
"a request with no keep-alive setting uses the default");
}
@Test
void theCompletionTimeoutEndsAStalledBody() throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.setExecutor(Executors.newVirtualThreadPerTaskExecutor());
server.createContext("/", exchange -> {
exchange.sendResponseHeaders(200, 1024);
try (OutputStream out = exchange.getResponseBody()) {
out.write('x');
out.flush();
// The body then stalls: the headers arrived, the rest of the body never does.
Thread.sleep(30_000);
} catch (IOException | InterruptedException expected) {
// The client ended the connection, which is what the completion timeout does.
} finally {
exchange.close();
}
});
server.start();
try (CloudFrontOriginHttpClient client = new CloudFrontOriginHttpClient(
resolver(InetAddress.getByName("127.0.0.1")), List.of("origin.invalid"))) {
// The read timeout is far longer than the completion timeout, so the completion timeout
// is the one that has to end the stalled body.
CloudFrontOriginHttpClient.OriginTimeouts timeouts =
new CloudFrontOriginHttpClient.OriginTimeouts(
Duration.ofSeconds(1), Duration.ofSeconds(30), 1,
Duration.ofMillis(700),
CloudFrontOriginTimeouts.DEFAULT_ORIGIN_KEEPALIVE_TIMEOUT);
CloudFrontOriginHttpClient.OpenResponse response = get(client,
request("http://origin.invalid:" + server.getAddress().getPort() + "/"), timeouts);
long started = System.nanoTime();
CloudFrontOriginTimeoutException failure = assertThrows(CloudFrontOriginTimeoutException.class,
() -> readAll(response));
long elapsedMillis = (System.nanoTime() - started) / 1_000_000;
assertEquals(CloudFrontServingController.ORIGIN_TIMEOUT_MESSAGE, failure.getMessage());
assertTrue(elapsedMillis < 5000,
"expected the 700 ms completion timeout to end the stalled body, took "
+ elapsedMillis + " ms");
} finally {
server.stop(0);
}
}
@Test
void aSlowViewerDoesNotExpireAResponseTheOriginFinishedInTime() throws Exception {
byte[] body = "a body the origin answered in full".getBytes(StandardCharsets.UTF_8);
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/", exchange -> {
exchange.sendResponseHeaders(200, body.length);
exchange.getResponseBody().write(body);
exchange.close();
});
server.start();
AtomicLong clock = new AtomicLong();
try (CloudFrontOriginHttpClient client = new CloudFrontOriginHttpClient(
resolver(InetAddress.getByName("127.0.0.1")), List.of("origin.invalid"), clock::get)) {
CloudFrontOriginHttpClient.OriginTimeouts timeouts =
new CloudFrontOriginHttpClient.OriginTimeouts(
Duration.ofSeconds(1), Duration.ofSeconds(30), 1,
Duration.ofMillis(500),
CloudFrontOriginTimeouts.DEFAULT_ORIGIN_KEEPALIVE_TIMEOUT);
CloudFrontOriginHttpClient.OpenResponse response = get(client,
request("http://origin.invalid:" + server.getAddress().getPort() + "/"), timeouts);
// The viewer reads the body far slower than the completion timeout allows: a second
// passes between reads. The origin answered in time, so the response is not expired.
ByteArrayOutputStream received = new ByteArrayOutputStream();
try (InputStream origin = response.body()) {
byte[] chunk = new byte[4];
int read;
while ((read = origin.read(chunk)) != -1) {
received.write(chunk, 0, read);
clock.addAndGet(Duration.ofSeconds(1).toNanos());
}
}
assertArrayEquals(body, received.toByteArray());
} finally {
server.stop(0);
}
}
@Test
void theCompletionTimeoutBoundsTheConnectionToTheOrigin() throws Exception {
// An address that blackholes the connection: the attempt is never answered.
InetAddress blackhole = InetAddress.getByName("10.255.255.1");
assumeTrue(connectionHangs(blackhole),
"the environment answers the connection attempt instead of dropping it");
try (CloudFrontOriginHttpClient client = new CloudFrontOriginHttpClient(
resolver(blackhole), List.of("origin.invalid"))) {
// The connect timeout is far longer than the completion timeout, so the completion
// timeout is the one that has to end the connection attempt.
CloudFrontOriginHttpClient.OriginTimeouts timeouts =
new CloudFrontOriginHttpClient.OriginTimeouts(
Duration.ofSeconds(10), Duration.ofSeconds(30), 1,
Duration.ofMillis(500),
CloudFrontOriginTimeouts.DEFAULT_ORIGIN_KEEPALIVE_TIMEOUT);
HttpRequest request = request("http://origin.invalid:80/");
long started = System.nanoTime();
assertThrows(CloudFrontOriginTimeoutException.class, () -> get(client, request, timeouts));
long elapsedMillis = (System.nanoTime() - started) / 1_000_000;
assertTrue(elapsedMillis < 5000,
"expected the 500 ms completion timeout to end the connection attempt, not the "
+ "10 s connect timeout, took " + elapsedMillis + " ms");
}
}
@Test
void theCompletionTimeoutBoundsTheTlsHandshake() throws Exception {
// An origin that accepts the connection and never answers the handshake.
InetAddress loopback = InetAddress.getByName("127.0.0.1");
try (ServerSocket socket = new ServerSocket(0, 1, loopback)) {
Thread acceptor = new Thread(() -> {
try (Socket accepted = socket.accept()) {
Thread.sleep(30_000);
} catch (IOException | InterruptedException expected) {
// The client gave up on the handshake.
}
});
acceptor.setDaemon(true);
acceptor.start();
try (CloudFrontOriginHttpClient client = new CloudFrontOriginHttpClient(
resolver(loopback), List.of("origin.invalid"))) {
CloudFrontOriginHttpClient.OriginTimeouts timeouts =
new CloudFrontOriginHttpClient.OriginTimeouts(
Duration.ofSeconds(10), Duration.ofSeconds(30), 1,
Duration.ofMillis(500),
CloudFrontOriginTimeouts.DEFAULT_ORIGIN_KEEPALIVE_TIMEOUT);
HttpRequest request = request("https://origin.invalid:" + socket.getLocalPort() + "/");
long started = System.nanoTime();
assertThrows(CloudFrontOriginTimeoutException.class, () -> get(client, request, timeouts));
long elapsedMillis = (System.nanoTime() - started) / 1_000_000;
assertTrue(elapsedMillis < 5000,
"expected the 500 ms completion timeout to end the handshake, not the 10 s "
+ "connect timeout, took " + elapsedMillis + " ms");
}
}
}
/**
* Whether a connection to {@code address} hangs, as a blackholed address does: the attempt has
* to be dropped rather than answered for the origin connect timeout to be the one under test.
*/
private static boolean connectionHangs(InetAddress address) {
try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress(address, 80), 500);
return false;
} catch (SocketTimeoutException expected) {
return true;
} catch (IOException expected) {
return false;
}
}
private static CloudFrontOriginHttpClient.OpenResponse get(
CloudFrontOriginHttpClient client, HttpRequest request,
CloudFrontOriginHttpClient.OriginTimeouts timeouts) throws Exception {
@@ -780,6 +780,42 @@ class CloudFrontServiceTest {
}), Map.of()));
}
@Test
void createDistributionRejectsAResponseCompletionTimeoutShorterThanTheReadTimeout() {
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
AwsException below = assertAws("InvalidArgument",
() -> service.createDistribution(distributionWithCustomOrigin(origin -> {
origin.getCustomOriginConfig().put("OriginReadTimeout", 30);
origin.setResponseCompletionTimeout(29);
}), Map.of()));
assertEquals("The parameter ResponseCompletionTimeout must be greater than or equal to"
+ " OriginReadTimeout.", below.getMessage());
assertEquals(400, below.getHttpStatus());
AwsException negative = assertAws("InvalidArgument",
() -> service.createDistribution(distributionWithCustomOrigin(origin ->
origin.setResponseCompletionTimeout(-1)), Map.of()));
assertEquals("The parameter ResponseCompletionTimeout must be a non-negative integer.",
negative.getMessage());
assertEquals(400, negative.getHttpStatus());
// A completion timeout as long as the read timeout, and none at all, are both accepted.
assertDoesNotThrow(() -> service.createDistribution(distributionWithCustomOrigin(origin -> {
origin.getCustomOriginConfig().put("OriginReadTimeout", 30);
origin.setResponseCompletionTimeout(30);
}), Map.of()));
assertDoesNotThrow(() -> service.createDistribution(distributionWithCustomOrigin(origin ->
origin.setResponseCompletionTimeout(0)), Map.of()));
// No OriginReadTimeout means the 30 s default, which a shorter completion timeout breaks.
AwsException belowDefault = assertAws("InvalidArgument",
() -> service.createDistribution(distributionWithCustomOrigin(origin ->
origin.setResponseCompletionTimeout(10)), Map.of()));
assertEquals("The parameter ResponseCompletionTimeout must be greater than or equal to"
+ " OriginReadTimeout.", belowDefault.getMessage());
}
@Test
void updateDistributionRejectsOriginSettingsOutsideTheAwsRange() {
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
@@ -797,6 +833,34 @@ class CloudFrontServiceTest {
origin.getCustomOriginConfig().put("OriginReadTimeout", 121))));
}
@Test
void updateDistributionRejectsAResponseCompletionTimeoutShorterThanTheReadTimeout() {
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
Distribution existing = service.createDistribution(
distributionWithCustomOrigin(origin -> { }), Map.of());
AwsException below = assertAws("InvalidArgument", () -> service.updateDistribution(
existing.getId(), existing.getEtag(),
distributionWithCustomOrigin(origin -> {
origin.getCustomOriginConfig().put("OriginReadTimeout", 30);
origin.setResponseCompletionTimeout(29);
})));
assertEquals("The parameter ResponseCompletionTimeout must be greater than or equal to"
+ " OriginReadTimeout.", below.getMessage());
assertEquals(400, below.getHttpStatus());
AwsException negative = assertAws("InvalidArgument", () -> service.updateDistribution(
existing.getId(), existing.getEtag(),
distributionWithCustomOrigin(origin -> origin.setResponseCompletionTimeout(-1))));
assertEquals("The parameter ResponseCompletionTimeout must be a non-negative integer.",
negative.getMessage());
assertEquals(400, negative.getHttpStatus());
// The rejected updates left the distribution as it was.
Origin origin = service.getDistribution(existing.getId()).getConfig().getOrigins().getFirst();
assertNull(origin.getResponseCompletionTimeout());
}
@Test
void createDistributionAcceptsOriginSettingsWithinTheAwsRange() {
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");