fix(cloudfront): carry origin connection settings through CloudFormation (#5992)

* 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>

* fix(cloudfront): carry origin connection settings through CloudFormation

Follow-up to #5802: the serving layer now applies Origin.ConnectionAttempts,
Origin.ConnectionTimeout and CustomOriginConfig.OriginReadTimeout, but
cfnOrigins never copied them, so a template that set them was dropped and
every distribution a stack provisioned ran on the AWS defaults.

- cfnOrigins copies ConnectionAttempts and ConnectionTimeout from the origin
  and OriginReadTimeout from CustomOriginConfig. A non-integer origin setting
  in a template is now a ValidationError instead of the server error an
  uncaught NumberFormatException produced.
- CreateDistribution and UpdateDistribution range-check ConnectionAttempts
  (1-3) and ConnectionTimeout (1-10 seconds) the way OriginReadTimeout and
  OriginKeepaliveTimeout already are. AWS publishes no dedicated error code
  for either, so both fail as InvalidArgument, and a non-numeric value is a
  400 instead of being silently ignored.
- The serving clamp reads MIN_CONNECTION_ATTEMPTS from
  CloudFrontOriginTimeouts instead of a literal.

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

* fix(cloudfront): enforce origin connection setting ranges in the service

Move the ConnectionAttempts, ConnectionTimeout, OriginReadTimeout and
OriginKeepaliveTimeout range checks out of the XML parser into
CloudFrontService.createDistribution/updateDistribution, next to the
custom-header and OAC checks, so the CloudFormation path shares one
copy. A template with an out-of-range value now fails the stack with
the same InvalidArgument/InvalidOriginReadTimeout/
InvalidOriginKeepaliveTimeout error the API path returns, instead of
falling back to the model defaults. The parser keeps rejecting
non-numeric values; the cross-field ResponseCompletionTimeout check
stays where it was.

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-21 13:21:15 -04:00
1 parent 935ebee2c4
commit 9a7c62b8f1
9 files changed
+365 -73

No files matched your search

@@ -557,6 +557,14 @@ public class CloudFrontCfnProvisioner implements CfnResourceProvisioner {
if (!originAccessControlId.isEmpty()) {
origin.setOriginAccessControlId(originAccessControlId);
}
Integer connectionAttempts = cfnInt(node, "ConnectionAttempts", engine);
if (connectionAttempts != null) {
origin.setConnectionAttempts(connectionAttempts);
}
Integer connectionTimeout = cfnInt(node, "ConnectionTimeout", engine);
if (connectionTimeout != null) {
origin.setConnectionTimeout(connectionTimeout);
}
JsonNode originCustomHeaders = node.path("OriginCustomHeaders");
if (originCustomHeaders.isArray()) {
List<Map<String, String>> customHeaders = new ArrayList<>();
@@ -576,6 +584,10 @@ public class CloudFrontCfnProvisioner implements CfnResourceProvisioner {
coc.put("HTTPSPort", cfnTextOrDefault(custom, "HTTPSPort", engine, "443"));
coc.put("OriginProtocolPolicy",
cfnTextOrDefault(custom, "OriginProtocolPolicy", engine, "https-only"));
Integer originReadTimeout = cfnInt(custom, "OriginReadTimeout", engine);
if (originReadTimeout != null) {
coc.put("OriginReadTimeout", originReadTimeout);
}
origin.setCustomOriginConfig(coc);
} else {
// No CustomOriginConfig => S3 origin (S3OriginConfig may be present or defaulted).
@@ -665,4 +677,23 @@ public class CloudFrontCfnProvisioner implements CfnResourceProvisioner {
String value = cfnText(parent, field, engine);
return value.isEmpty() ? dflt : "true".equalsIgnoreCase(value);
}
/**
* A template value the registry schema types as an integer. Template properties arrive as text,
* and an uncaught {@link NumberFormatException} would surface as a 500 instead of the failed
* validation it is. A missing or null property stays unset so the model's own default stands.
*/
private Integer cfnInt(JsonNode parent, String field, CloudFormationTemplateEngine engine) {
String value = cfnText(parent, field, engine);
if (value.isEmpty()) {
return null;
}
try {
return Integer.valueOf(value.trim());
} catch (NumberFormatException notAnInteger) {
throw new AwsException("ValidationError",
"AWS::CloudFront::Distribution origin " + field + " must be an integer, but was '"
+ value + "'", 400);
}
}
}
@@ -42,15 +42,13 @@ public class CloudFrontController {
/**
* Origin timeout constraints from the CloudFront {@code CustomOriginConfig} and
* {@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.
* {@code Origin} API references. The range checks for the origin timeout settings live in
* {@link CloudFrontService#createDistribution} so the CloudFormation path shares one copy;
* the parser only rejects non-numeric values. {@code ResponseCompletionTimeout} has no
* enforced maximum when unset (represented here as 0), but when set must be at least
* {@code OriginReadTimeout}. The timeout bounds live in {@link CloudFrontOriginTimeouts},
* shared with the serving layer that applies them.
*/
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;
private static final int DEFAULT_RESPONSE_COMPLETION_TIMEOUT_SECONDS = 0;
private final CloudFrontService service;
@@ -1962,7 +1960,8 @@ public class CloudFrontController {
.elem("OriginReadTimeout", coc.getOrDefault("OriginReadTimeout",
CloudFrontOriginTimeouts.DEFAULT_ORIGIN_READ_TIMEOUT_SECONDS).toString())
.elem("OriginKeepaliveTimeout",
coc.getOrDefault("OriginKeepaliveTimeout", DEFAULT_ORIGIN_KEEPALIVE_TIMEOUT_SECONDS)
coc.getOrDefault("OriginKeepaliveTimeout",
CloudFrontOriginTimeouts.DEFAULT_ORIGIN_KEEPALIVE_TIMEOUT_SECONDS)
.toString())
.raw(xmlOriginSslProtocols(coc.get("OriginSslProtocols")))
.end("CustomOriginConfig");
@@ -2784,20 +2783,14 @@ public class CloudFrontController {
}
case "ConnectionAttempts" -> {
if (inOrigin && !inS3OriginConfig && !inCustomOriginConfig && current != null) {
try {
current.setConnectionAttempts(Integer.parseInt(r.getElementText()));
} catch (NumberFormatException e) {
LOG.debugv("Ignoring malformed ConnectionAttempts during parse: {0}", e.getMessage());
}
current.setConnectionAttempts(parseNonNegativeTimeout(
"ConnectionAttempts", r.getElementText()));
}
}
case "ConnectionTimeout" -> {
if (inOrigin && !inS3OriginConfig && !inCustomOriginConfig && current != null) {
try {
current.setConnectionTimeout(Integer.parseInt(r.getElementText()));
} catch (NumberFormatException e) {
LOG.debugv("Ignoring malformed ConnectionTimeout during parse: {0}", e.getMessage());
}
current.setConnectionTimeout(parseNonNegativeTimeout(
"ConnectionTimeout", r.getElementText()));
}
}
case "ResponseCompletionTimeout" -> {
@@ -2828,18 +2821,16 @@ public class CloudFrontController {
}
case "OriginKeepaliveTimeout" -> {
if (inCustomOriginConfig && customConfig != null) {
customConfig.put("OriginKeepaliveTimeout", parseBoundedTimeout(
customConfig.put("OriginKeepaliveTimeout", parseNonNegativeTimeout(
"InvalidOriginKeepaliveTimeout", "OriginKeepaliveTimeout",
r.getElementText(), MIN_ORIGIN_KEEPALIVE_TIMEOUT_SECONDS,
MAX_ORIGIN_KEEPALIVE_TIMEOUT_SECONDS));
r.getElementText()));
}
}
case "OriginReadTimeout" -> {
if (inCustomOriginConfig && customConfig != null) {
originReadTimeoutSeconds = parseBoundedTimeout(
originReadTimeoutSeconds = parseNonNegativeTimeout(
"InvalidOriginReadTimeout", "OriginReadTimeout",
r.getElementText(), CloudFrontOriginTimeouts.MIN_ORIGIN_READ_TIMEOUT_SECONDS,
CloudFrontOriginTimeouts.MAX_ORIGIN_READ_TIMEOUT_SECONDS);
r.getElementText());
customConfig.put("OriginReadTimeout", originReadTimeoutSeconds);
}
}
@@ -3002,17 +2993,6 @@ public class CloudFrontController {
400);
}
private static int parseBoundedTimeout(String errorCode, String field, String rawValue, int min, int max) {
int value = parseNonNegativeTimeout(errorCode, field, rawValue);
if (value < min || value > max) {
throw new AwsException(
errorCode,
"The parameter " + field + " must be between " + min + " and " + max + " seconds.",
400);
}
return value;
}
private static int parseNonNegativeTimeout(String field, String rawValue) {
return parseNonNegativeTimeout("InvalidArgument", field, rawValue);
}
@@ -3,10 +3,11 @@ 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}
* The origin-timeout settings of a CloudFront distribution, shared by the distribution service
* (which validates them on create and update) 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 OriginKeepaliveTimeout} accepts 1-300 seconds, default 5; {@code ConnectionTimeout}
* accepts 1-10 seconds, default 10; {@code ConnectionAttempts} accepts 1-3, default 3.
*/
final class CloudFrontOriginTimeouts {
@@ -14,10 +15,14 @@ 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_ORIGIN_KEEPALIVE_TIMEOUT_SECONDS = 5;
static final int MIN_ORIGIN_KEEPALIVE_TIMEOUT_SECONDS = 1;
static final int MAX_ORIGIN_KEEPALIVE_TIMEOUT_SECONDS = 300;
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 MIN_CONNECTION_ATTEMPTS = 1;
static final int MAX_CONNECTION_ATTEMPTS = 3;
static final Duration DEFAULT_ORIGIN_READ_TIMEOUT =
@@ -199,6 +199,7 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
public synchronized Distribution createDistribution(Distribution dist, Map<String, String> tags) {
ensureAliasesAvailable(dist.getConfig(), null);
validateOriginSettings(dist.getConfig());
validateOriginCustomHeaders(dist.getConfig());
validateResponseHeadersPolicyReferences(dist.getConfig(), null);
validateTrustedKeyGroups(dist.getConfig());
@@ -233,6 +234,7 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
"The If-Match version is missing or not valid for the resource.", 400);
}
ensureAliasesAvailable(updated.getConfig(), id);
validateOriginSettings(updated.getConfig());
validateOriginCustomHeaders(updated.getConfig());
validateResponseHeadersPolicyReferences(updated.getConfig(), id);
validateTrustedKeyGroups(updated.getConfig());
@@ -299,6 +301,58 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
return iamService.supplyWithServerCertificatesHeld(action);
}
private static void validateOriginSettings(DistributionConfig config) {
if (config == null || config.getOrigins() == null) {
return;
}
for (Origin origin : config.getOrigins()) {
requireRange("InvalidArgument", "ConnectionAttempts",
origin.getConnectionAttempts(),
CloudFrontOriginTimeouts.MIN_CONNECTION_ATTEMPTS,
CloudFrontOriginTimeouts.MAX_CONNECTION_ATTEMPTS, "");
requireRange("InvalidArgument", "ConnectionTimeout",
origin.getConnectionTimeout(),
CloudFrontOriginTimeouts.MIN_CONNECTION_TIMEOUT_SECONDS,
CloudFrontOriginTimeouts.MAX_CONNECTION_TIMEOUT_SECONDS, " seconds");
Map<String, Object> customOriginConfig = origin.getCustomOriginConfig();
if (customOriginConfig == null) {
continue;
}
requireRange("InvalidOriginReadTimeout", "OriginReadTimeout",
asIntOrNull(customOriginConfig.get("OriginReadTimeout")),
CloudFrontOriginTimeouts.MIN_ORIGIN_READ_TIMEOUT_SECONDS,
CloudFrontOriginTimeouts.MAX_ORIGIN_READ_TIMEOUT_SECONDS, " seconds");
requireRange("InvalidOriginKeepaliveTimeout", "OriginKeepaliveTimeout",
asIntOrNull(customOriginConfig.get("OriginKeepaliveTimeout")),
CloudFrontOriginTimeouts.MIN_ORIGIN_KEEPALIVE_TIMEOUT_SECONDS,
CloudFrontOriginTimeouts.MAX_ORIGIN_KEEPALIVE_TIMEOUT_SECONDS, " seconds");
}
}
private static void requireRange(String errorCode, String field, Integer value,
int min, int max, String unit) {
if (value != null && (value < min || value > max)) {
throw new AwsException(
errorCode,
"The parameter " + field + " must be between " + min + " and " + max + unit + ".",
400);
}
}
private static Integer asIntOrNull(Object value) {
if (value instanceof Integer intValue) {
return intValue;
}
if (value instanceof String text) {
try {
return Integer.valueOf(text);
} catch (NumberFormatException e) {
return null;
}
}
return null;
}
private static void validateOriginCustomHeaders(DistributionConfig config) {
if (config == null || config.getOrigins() == null) {
return;
@@ -879,7 +879,8 @@ public class CloudFrontServingController {
CloudFrontOriginTimeouts.MAX_ORIGIN_READ_TIMEOUT_SECONDS,
CloudFrontOriginTimeouts.DEFAULT_ORIGIN_READ_TIMEOUT_SECONDS);
int attempts = clampToDefault(origin.getConnectionAttempts(),
1, CloudFrontOriginTimeouts.MAX_CONNECTION_ATTEMPTS,
CloudFrontOriginTimeouts.MIN_CONNECTION_ATTEMPTS,
CloudFrontOriginTimeouts.MAX_CONNECTION_ATTEMPTS,
CloudFrontOriginTimeouts.DEFAULT_CONNECTION_ATTEMPTS);
return new CloudFrontOriginHttpClient.OriginTimeouts(
Duration.ofSeconds(connectSeconds), Duration.ofSeconds(readSeconds), attempts);