fix(cloudfront): honor origin connection timeouts and attempts, answer 504 (#5802)

* fix(cloudfront): honor origin connection timeouts and attempts, answer 504

CloudFront ignored a custom origin's ConnectionTimeout, OriginReadTimeout and
ConnectionAttempts and answered 502 for any origin failure. Apply the origin's
connect and read timeouts to the origin request, retry a timed-out GET/HEAD up
to ConnectionAttempts, and answer 504 with the AWS message when the last
attempt times out. A refused connection or an unknown host still answers 502.

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* fix(cloudfront): retry a connect timeout for every origin method

Review follow-ups on the origin timeout work:

- Connection attempts count for every method, not only GET and HEAD: a
  connect timeout or a refused connection is retried up to the configured
  ConnectionAttempts whatever the method is. Apache HttpClient 5's
  ConnectTimeoutException extends SocketTimeoutException, so it is caught
  first to keep the split: a response timeout is still retried only for an
  idempotent method and still answers 504, while a refused connection
  propagates unchanged as a bad gateway.
- The origin read and connection timeout bounds moved into
  CloudFrontOriginTimeouts, shared by CloudFrontController,
  CloudFrontServingController and CloudFrontOriginHttpClient instead of
  being repeated in each.
- The slow-origin tests hold the origin open on a CountDownLatch with
  millisecond client timeouts rather than sleeping out a fixed delay, so an
  attempt ends by the client's own timeout and the suite finishes in
  seconds.

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

---------

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
This commit is contained in:
Matheus Oliveira authored and GitHub committed 2026-10-18 20:56:42 -04:00
1 parent 916e72570e
commit 5306e0e470
7 files changed
+497 -22

No files matched your search

@@ -42,14 +42,12 @@ public class CloudFrontController {
/**
* Origin timeout constraints from the CloudFront {@code CustomOriginConfig} and
* {@code Origin} API references. {@code OriginReadTimeout} accepts 1-120 seconds, default 30.
* {@code OriginKeepaliveTimeout} accepts 1-300 seconds, default 5. {@code ResponseCompletionTimeout}
* has no enforced maximum when unset (represented here as 0), but when set must be at least
* {@code OriginReadTimeout}.
* {@code Origin} API references. {@code OriginKeepaliveTimeout} accepts 1-300 seconds,
* default 5. {@code ResponseCompletionTimeout} has no enforced maximum when unset
* (represented here as 0), but when set must be at least {@code OriginReadTimeout}.
* The read and connection timeouts live in {@link CloudFrontOriginTimeouts}, shared with
* the serving layer that applies them.
*/
private static final int DEFAULT_ORIGIN_READ_TIMEOUT_SECONDS = 30;
private static final int MIN_ORIGIN_READ_TIMEOUT_SECONDS = 1;
private static final int MAX_ORIGIN_READ_TIMEOUT_SECONDS = 120;
private static final int DEFAULT_ORIGIN_KEEPALIVE_TIMEOUT_SECONDS = 5;
private static final int MIN_ORIGIN_KEEPALIVE_TIMEOUT_SECONDS = 1;
private static final int MAX_ORIGIN_KEEPALIVE_TIMEOUT_SECONDS = 300;
@@ -1961,8 +1959,8 @@ public class CloudFrontController {
.elem("HTTPSPort", coc.getOrDefault("HTTPSPort", "443").toString())
.elem("OriginProtocolPolicy",
coc.getOrDefault("OriginProtocolPolicy", "https-only").toString())
.elem("OriginReadTimeout",
coc.getOrDefault("OriginReadTimeout", DEFAULT_ORIGIN_READ_TIMEOUT_SECONDS).toString())
.elem("OriginReadTimeout", coc.getOrDefault("OriginReadTimeout",
CloudFrontOriginTimeouts.DEFAULT_ORIGIN_READ_TIMEOUT_SECONDS).toString())
.elem("OriginKeepaliveTimeout",
coc.getOrDefault("OriginKeepaliveTimeout", DEFAULT_ORIGIN_KEEPALIVE_TIMEOUT_SECONDS)
.toString())
@@ -2840,8 +2838,8 @@ public class CloudFrontController {
if (inCustomOriginConfig && customConfig != null) {
originReadTimeoutSeconds = parseBoundedTimeout(
"InvalidOriginReadTimeout", "OriginReadTimeout",
r.getElementText(), MIN_ORIGIN_READ_TIMEOUT_SECONDS,
MAX_ORIGIN_READ_TIMEOUT_SECONDS);
r.getElementText(), CloudFrontOriginTimeouts.MIN_ORIGIN_READ_TIMEOUT_SECONDS,
CloudFrontOriginTimeouts.MAX_ORIGIN_READ_TIMEOUT_SECONDS);
customConfig.put("OriginReadTimeout", originReadTimeoutSeconds);
}
}
@@ -2956,7 +2954,7 @@ public class CloudFrontController {
Integer completionTimeout = current.getResponseCompletionTimeout();
int effectiveReadTimeout = originReadTimeoutSeconds != null
? originReadTimeoutSeconds
: DEFAULT_ORIGIN_READ_TIMEOUT_SECONDS;
: CloudFrontOriginTimeouts.DEFAULT_ORIGIN_READ_TIMEOUT_SECONDS;
if (completionTimeout != null && completionTimeout > 0
&& completionTimeout < effectiveReadTimeout) {
throw new AwsException(
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.cloudfront;
import io.github.hectorvent.floci.core.common.SsrfProtection;
import org.apache.hc.client5.http.ConnectTimeoutException;
import org.apache.hc.client5.http.DnsResolver;
import org.apache.hc.client5.http.SystemDefaultDnsResolver;
import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase;
@@ -31,7 +32,9 @@ import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.net.http.HttpHeaders;
import java.net.http.HttpRequest;
@@ -39,6 +42,7 @@ import java.time.Duration;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
@@ -54,8 +58,12 @@ final class CloudFrontOriginHttpClient implements AutoCloseable {
private static final Logger LOG = Logger.getLogger(CloudFrontOriginHttpClient.class);
private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(10);
private static final Duration RESPONSE_TIMEOUT = Duration.ofSeconds(30);
private static final String ORIGIN_TIMEOUT_MESSAGE =
"The origin didn't respond before the request expired.";
private static final Duration CONNECT_TIMEOUT = CloudFrontOriginTimeouts.DEFAULT_CONNECTION_TIMEOUT;
private static final Duration RESPONSE_TIMEOUT = CloudFrontOriginTimeouts.DEFAULT_ORIGIN_READ_TIMEOUT;
/** CloudFront retries a response timeout only for the methods it treats as idempotent. */
private static final Set<String> IDEMPOTENT_METHODS = Set.of("GET", "HEAD");
static final int MAX_CONNECTIONS = 100;
private final CloseableHttpClient client;
@@ -119,6 +127,14 @@ final class CloudFrontOriginHttpClient implements AutoCloseable {
.build();
}
/**
* The connection settings of a distribution's origin that one request must honor:
* {@code Origin.ConnectionAttempts}, {@code Origin.ConnectionTimeout} and the custom origin's
* {@code OriginReadTimeout}. Read per request, since the client and its pool are shared.
*/
record OriginTimeouts(Duration connectTimeout, Duration responseTimeout, int connectionAttempts) {
}
/**
* An origin response whose body has not been read. The caller reads {@code body} as it needs it
* and closes it, which releases the connection. {@code contentLength} is the length the body
@@ -139,12 +155,64 @@ final class CloudFrontOriginHttpClient implements AutoCloseable {
List<CloudFrontOriginRequestBuilder.Header> forwardedHeaders,
Map<String, String> originHeaders, InputStream requestBody, long requestBodyLength)
throws IOException, InterruptedException {
return open(request, forwardedHeaders, originHeaders, requestBody, requestBodyLength, null);
}
/**
* Sends {@code request}, honoring {@code timeouts}. A connection attempt counts for every
* method, so a connect timeout or a refused connection is retried up to the configured
* connection attempts whatever the method is. A response timeout is retried only for an
* idempotent method (GET, HEAD), whose request has no body to replay; every other method is
* attempted once for it, as CloudFront does not retry it. When the attempts run out, a timeout
* raises {@link CloudFrontOriginTimeoutException} so the viewer is answered 504 rather than
* 502, while a refused connection propagates unchanged, as a bad gateway.
*/
OpenResponse open(HttpRequest request,
List<CloudFrontOriginRequestBuilder.Header> forwardedHeaders,
Map<String, String> originHeaders, InputStream requestBody, long requestBodyLength,
OriginTimeouts timeouts)
throws IOException, InterruptedException {
OriginTimeouts effective = timeouts != null
? timeouts
: new OriginTimeouts(CONNECT_TIMEOUT, request.timeout().orElse(RESPONSE_TIMEOUT), 1);
int attempts = Math.max(1, effective.connectionAttempts());
IOException lastFailure = null;
for (int attempt = 1; attempt <= attempts; attempt++) {
try {
return send(request, forwardedHeaders, originHeaders, requestBody, requestBodyLength, effective);
} catch (ConnectTimeoutException e) {
lastFailure = e;
} catch (SocketTimeoutException e) {
if (!idempotent(request.method())) {
throw new CloudFrontOriginTimeoutException(ORIGIN_TIMEOUT_MESSAGE, e);
}
lastFailure = e;
} catch (ConnectException e) {
lastFailure = e;
}
if (attempt < attempts) {
LOG.debugv("CloudFront origin connection attempt {0} of {1} failed; retrying",
attempt, attempts);
}
}
if (lastFailure instanceof SocketTimeoutException timeout) {
throw new CloudFrontOriginTimeoutException(ORIGIN_TIMEOUT_MESSAGE, timeout);
}
throw lastFailure;
}
private OpenResponse send(HttpRequest request,
List<CloudFrontOriginRequestBuilder.Header> forwardedHeaders,
Map<String, String> originHeaders, InputStream requestBody, long requestBodyLength,
OriginTimeouts timeouts)
throws IOException, InterruptedException {
// No entity content type: the caller's Content-Type request header is sent as is.
HttpUriRequestBase originRequest = originRequest(request, forwardedHeaders, originHeaders,
requestBody != null ? new InputStreamEntity(requestBody, requestBodyLength, null) : null);
ClassicHttpResponse response;
try {
response = client.executeOpen(RoutingSupport.determineHost(originRequest), originRequest, context(request));
response = client.executeOpen(RoutingSupport.determineHost(originRequest), originRequest,
context(timeouts));
} catch (HttpException e) {
throw new IOException("CloudFront origin request has no target host", e);
} catch (InterruptedIOException e) {
@@ -169,6 +237,10 @@ final class CloudFrontOriginHttpClient implements AutoCloseable {
}
}
private static boolean idempotent(String method) {
return method != null && IDEMPOTENT_METHODS.contains(method.toUpperCase(Locale.ROOT));
}
/**
* An origin response body that releases its connection when it is closed. Closed at its end, the
* connection goes back to the pool. Closed before its end, as when a viewer goes away or a custom
@@ -271,12 +343,14 @@ final class CloudFrontOriginHttpClient implements AutoCloseable {
return builder;
}
private static HttpClientContext context(HttpRequest request) {
private static HttpClientContext context(OriginTimeouts timeouts) {
HttpClientContext context = HttpClientContext.create();
Duration responseTimeout = request.timeout().orElse(RESPONSE_TIMEOUT);
context.setRequestConfig(RequestConfig.custom()
.setConnectTimeout(Timeout.of(timeouts.connectTimeout()))
// Waiting for a free pooled connection is emulator-side backpressure, not an origin
// setting, so it keeps the fixed default rather than the origin's connect timeout.
.setConnectionRequestTimeout(Timeout.of(CONNECT_TIMEOUT))
.setResponseTimeout(Timeout.of(responseTimeout))
.setResponseTimeout(Timeout.of(timeouts.responseTimeout()))
.setRedirectsEnabled(false)
.setContentCompressionEnabled(false)
.setProtocolUpgradeEnabled(false)
@@ -0,0 +1,15 @@
package io.github.hectorvent.floci.services.cloudfront;
import java.io.IOException;
/**
* Signals that a custom origin did not answer before the timeout configured on the origin expired.
* CloudFront answers the viewer with a 504 Gateway Timeout for this case, distinct from the 502 it
* answers for a genuine bad gateway, so the serving layer must be able to tell the two apart.
*/
final class CloudFrontOriginTimeoutException extends IOException {
CloudFrontOriginTimeoutException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -0,0 +1,30 @@
package io.github.hectorvent.floci.services.cloudfront;
import java.time.Duration;
/**
* The origin-timeout settings of a CloudFront distribution, shared by the distribution API (which
* validates and emits them) and the serving layer (which applies them to origin requests), so both
* sides agree on the values the {@code Origin} and {@code CustomOriginConfig} API references
* document. {@code OriginReadTimeout} accepts 1-120 seconds, default 30; {@code ConnectionTimeout}
* accepts 1-10 seconds, default 10; {@code ConnectionAttempts} accepts 1-3, default 3.
*/
final class CloudFrontOriginTimeouts {
static final int DEFAULT_ORIGIN_READ_TIMEOUT_SECONDS = 30;
static final int MIN_ORIGIN_READ_TIMEOUT_SECONDS = 1;
static final int MAX_ORIGIN_READ_TIMEOUT_SECONDS = 120;
static final int DEFAULT_CONNECTION_TIMEOUT_SECONDS = 10;
static final int MIN_CONNECTION_TIMEOUT_SECONDS = 1;
static final int MAX_CONNECTION_TIMEOUT_SECONDS = 10;
static final int DEFAULT_CONNECTION_ATTEMPTS = 3;
static final int MAX_CONNECTION_ATTEMPTS = 3;
static final Duration DEFAULT_ORIGIN_READ_TIMEOUT =
Duration.ofSeconds(DEFAULT_ORIGIN_READ_TIMEOUT_SECONDS);
static final Duration DEFAULT_CONNECTION_TIMEOUT =
Duration.ofSeconds(DEFAULT_CONNECTION_TIMEOUT_SECONDS);
private CloudFrontOriginTimeouts() {
}
}
@@ -101,6 +101,8 @@ public class CloudFrontServingController {
java.util.Set.of("Expires", "Signature", "Key-Pair-Id", "Policy", "Hash-Algorithm");
/** Viewer methods that can carry a request body and that CloudFront never caches. */
private static final Set<String> BODY_METHODS = Set.of("POST", "PUT", "PATCH", "DELETE");
/** The 504 body CloudFront returns when the origin did not answer in time. */
static final String ORIGIN_TIMEOUT_MESSAGE = "The origin didn't respond before the request expired.";
private final CloudFrontService service;
private final S3Service s3Service;
@@ -760,8 +762,7 @@ public class CloudFrontServingController {
URI target = buildCustomOriginUri(
origin, viewerScheme, forwardUri, originRequest.rawQuery());
HttpRequest.Builder rb = HttpRequest.newBuilder()
.uri(target)
.timeout(Duration.ofSeconds(30));
.uri(target);
// Origin custom headers: CloudFront adds these to every request it forwards to the origin
// (overriding any same-named viewer header), which is how a distribution restricts an origin
// to CloudFront-only traffic via a shared secret header.
@@ -782,7 +783,7 @@ public class CloudFrontServingController {
ViewerBody requestBody = originRequestBody(method, viewerBody);
CloudFrontOriginHttpClient.OpenResponse resp = httpClient.open(rb.build(), originRequest.headers(),
originHeaders, requestBody != null ? requestBody.stream() : null,
requestBody != null ? requestBody.length() : -1);
requestBody != null ? requestBody.length() : -1, originTimeouts(origin));
String ct = resp.headers().firstValue("content-type").orElse(DEFAULT_CONTENT_TYPE);
long contentLength = resp.contentLength();
if (!includeBody) {
@@ -795,6 +796,9 @@ public class CloudFrontServingController {
LOG.warnv("CloudFront custom origin fetch was interrupted for host {0}",
safeOriginName(origin));
return OriginResponse.error(502, "Bad Gateway.");
} catch (CloudFrontOriginTimeoutException e) {
LOG.warnv("CloudFront custom origin timed out for host {0}", safeOriginName(origin));
return OriginResponse.error(504, ORIGIN_TIMEOUT_MESSAGE);
} catch (Exception e) {
// Do not log the target URI: forwarded query strings can contain credentials or tokens.
LOG.warnv("CloudFront custom origin fetch failed for host {0}: {1}",
@@ -803,6 +807,34 @@ public class CloudFrontServingController {
}
}
/**
* The origin's connection settings for one request: {@code Origin.ConnectionTimeout},
* {@code CustomOriginConfig.OriginReadTimeout} and {@code Origin.ConnectionAttempts}. A value
* outside the range AWS accepts falls back to the AWS default, since the model can be built
* programmatically or loaded from persisted state without the API validation.
*/
private static CloudFrontOriginHttpClient.OriginTimeouts originTimeouts(Origin origin) {
int connectSeconds = clampToDefault(origin.getConnectionTimeout(),
CloudFrontOriginTimeouts.MIN_CONNECTION_TIMEOUT_SECONDS,
CloudFrontOriginTimeouts.MAX_CONNECTION_TIMEOUT_SECONDS,
CloudFrontOriginTimeouts.DEFAULT_CONNECTION_TIMEOUT_SECONDS);
int readSeconds = clampToDefault(
intOrDefault(origin.getCustomOriginConfig(), "OriginReadTimeout",
CloudFrontOriginTimeouts.DEFAULT_ORIGIN_READ_TIMEOUT_SECONDS),
CloudFrontOriginTimeouts.MIN_ORIGIN_READ_TIMEOUT_SECONDS,
CloudFrontOriginTimeouts.MAX_ORIGIN_READ_TIMEOUT_SECONDS,
CloudFrontOriginTimeouts.DEFAULT_ORIGIN_READ_TIMEOUT_SECONDS);
int attempts = clampToDefault(origin.getConnectionAttempts(),
1, CloudFrontOriginTimeouts.MAX_CONNECTION_ATTEMPTS,
CloudFrontOriginTimeouts.DEFAULT_CONNECTION_ATTEMPTS);
return new CloudFrontOriginHttpClient.OriginTimeouts(
Duration.ofSeconds(connectSeconds), Duration.ofSeconds(readSeconds), attempts);
}
private static int clampToDefault(int value, int min, int max, int fallback) {
return value < min || value > max ? fallback : value;
}
/**
* The body CloudFront sends to the origin: POST, PUT and PATCH always carry one (possibly empty, so
* the origin still sees {@code Content-Length: 0}); DELETE carries one only when the viewer sent it.