mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 06:00:46 -05:00
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:
1 parent
935ebee2c4
commit
9a7c62b8f1
9 files changed
+365
-73
No files matched your search
+31
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+16
-36
@@ -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);
|
||||
}
|
||||
|
||||
+9
-4
@@ -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;
|
||||
|
||||
+2
-1
@@ -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);
|
||||
|
||||
+68
@@ -264,6 +264,74 @@ class CloudFormationCloudFrontDistributionIntegrationTest {
|
||||
distribution.getConfig().getCacheBehaviors().getFirst().getTrustedKeyGroups());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createStackWithAnOutOfRangeOriginConnectionSettingFailsTheStack() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String stackName = "cfn-cloudfront-bad-attempts-" + suffix;
|
||||
|
||||
String template = """
|
||||
{
|
||||
"Resources": {
|
||||
"Dist": {
|
||||
"Type": "AWS::CloudFront::Distribution",
|
||||
"Properties": {
|
||||
"DistributionConfig": {
|
||||
"Enabled": true,
|
||||
"Origins": [{
|
||||
"Id": "o1",
|
||||
"DomainName": "origin.example.com",
|
||||
"ConnectionAttempts": 4,
|
||||
"CustomOriginConfig": {"OriginProtocolPolicy": "https-only"}
|
||||
}],
|
||||
"DefaultCacheBehavior": {
|
||||
"TargetOriginId": "o1",
|
||||
"ViewerProtocolPolicy": "allow-all"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", template)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
// On AWS the stack fails because CloudFront rejects the out-of-range value; the
|
||||
// service-level check makes the CloudFormation path share that one copy.
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", stackName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<StackStatus>ROLLBACK_COMPLETE</StackStatus>"))
|
||||
.body(containsString("failed to create: [Dist]"));
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DescribeStackEvents")
|
||||
.formParam("StackName", stackName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString(
|
||||
"The parameter ConnectionAttempts must be between 1 and 3."));
|
||||
}
|
||||
|
||||
private KeyGroup createKeyGroup(String name, String publicKeyId) {
|
||||
KeyGroup keyGroup = new KeyGroup();
|
||||
keyGroup.setName(name);
|
||||
|
||||
+44
@@ -169,9 +169,53 @@ class CloudFrontCfnProvisionerTest {
|
||||
assertEquals("b.s3.amazonaws.com", origin.getDomainName());
|
||||
// No CustomOriginConfig means an S3 origin.
|
||||
assertNull(origin.getCustomOriginConfig());
|
||||
// Settings the template never mentions stay on the model's own AWS defaults.
|
||||
assertEquals(3, origin.getConnectionAttempts());
|
||||
assertEquals(10, origin.getConnectionTimeout());
|
||||
assertEquals("redirect-to-https", config.getDefaultCacheBehavior().getViewerProtocolPolicy());
|
||||
}
|
||||
|
||||
@Test
|
||||
void copiesTheOriginConnectionSettingsTheTemplateDeclares() throws Exception {
|
||||
when(cloudFront.createDistribution(any(), any())).thenReturn(distribution("E1DIST", "d111.cloudfront.net"));
|
||||
StackResource r = resource(DISTRIBUTION);
|
||||
|
||||
provisioner.provision(r, json("""
|
||||
{"DistributionConfig": {
|
||||
"Origins": [{"Id": "o1", "DomainName": "origin.example.com",
|
||||
"ConnectionAttempts": 2, "ConnectionTimeout": 5,
|
||||
"CustomOriginConfig": {"OriginProtocolPolicy": "https-only",
|
||||
"OriginReadTimeout": 45}}],
|
||||
"DefaultCacheBehavior": {"TargetOriginId": "o1", "ViewerProtocolPolicy": "redirect-to-https"}
|
||||
}}
|
||||
"""), distributionCtx(null));
|
||||
|
||||
ArgumentCaptor<Distribution> sent = ArgumentCaptor.forClass(Distribution.class);
|
||||
verify(cloudFront).createDistribution(sent.capture(), any());
|
||||
Origin origin = sent.getValue().getConfig().getOrigins().getFirst();
|
||||
assertEquals(2, origin.getConnectionAttempts());
|
||||
assertEquals(5, origin.getConnectionTimeout());
|
||||
// OriginReadTimeout lives on CustomOriginConfig, where the serving layer reads it.
|
||||
assertEquals(Integer.valueOf(45), origin.getCustomOriginConfig().get("OriginReadTimeout"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNonNumericOriginConnectionSettingFailsTheStackInsteadOfAServerError() {
|
||||
StackResource r = resource(DISTRIBUTION);
|
||||
|
||||
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, json("""
|
||||
{"DistributionConfig": {
|
||||
"Origins": [{"Id": "o1", "DomainName": "origin.example.com", "ConnectionTimeout": "lots"}],
|
||||
"DefaultCacheBehavior": {"TargetOriginId": "o1", "ViewerProtocolPolicy": "redirect-to-https"}
|
||||
}}
|
||||
"""), distributionCtx(null)));
|
||||
|
||||
assertEquals("ValidationError", e.getErrorCode());
|
||||
assertEquals("AWS::CloudFront::Distribution origin ConnectionTimeout must be an integer, but was 'lots'",
|
||||
e.getMessage());
|
||||
verify(cloudFront, never()).createDistribution(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updatesTheDistributionInPlaceUnderThePriorId() throws Exception {
|
||||
// provision() re-runs on every UpdateStack. The prior id comes from the context, not from
|
||||
|
||||
+16
-32
@@ -444,38 +444,6 @@ class CloudFrontControllerTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void originReadTimeoutAboveTheAwsMaximumIsRejected() {
|
||||
CloudFrontService service = mock(CloudFrontService.class);
|
||||
CloudFrontController controller = new CloudFrontController(service);
|
||||
|
||||
String body = distributionConfigBody("").replace(
|
||||
"<OriginProtocolPolicy>https-only</OriginProtocolPolicy></CustomOriginConfig>",
|
||||
"<OriginProtocolPolicy>https-only</OriginProtocolPolicy>"
|
||||
+ "<OriginReadTimeout>121</OriginReadTimeout></CustomOriginConfig>");
|
||||
|
||||
try (Response created = controller.createDistribution(null, body)) {
|
||||
assertEquals(400, created.getStatus());
|
||||
assertTrue(((String) created.getEntity()).contains("InvalidOriginReadTimeout"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void originKeepaliveTimeoutOfZeroIsRejected() {
|
||||
CloudFrontService service = mock(CloudFrontService.class);
|
||||
CloudFrontController controller = new CloudFrontController(service);
|
||||
|
||||
String body = distributionConfigBody("").replace(
|
||||
"<OriginProtocolPolicy>https-only</OriginProtocolPolicy></CustomOriginConfig>",
|
||||
"<OriginProtocolPolicy>https-only</OriginProtocolPolicy>"
|
||||
+ "<OriginKeepaliveTimeout>0</OriginKeepaliveTimeout></CustomOriginConfig>");
|
||||
|
||||
try (Response created = controller.createDistribution(null, body)) {
|
||||
assertEquals(400, created.getStatus());
|
||||
assertTrue(((String) created.getEntity()).contains("InvalidOriginKeepaliveTimeout"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonNumericOriginReadTimeoutIsRejected() {
|
||||
CloudFrontService service = mock(CloudFrontService.class);
|
||||
@@ -492,6 +460,22 @@ class CloudFrontControllerTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonNumericConnectionTimeoutIsRejected() {
|
||||
CloudFrontService service = mock(CloudFrontService.class);
|
||||
CloudFrontController controller = new CloudFrontController(service);
|
||||
|
||||
String body = distributionConfigBody("").replace(
|
||||
"<OriginProtocolPolicy>https-only</OriginProtocolPolicy></CustomOriginConfig>",
|
||||
"<OriginProtocolPolicy>https-only</OriginProtocolPolicy></CustomOriginConfig>"
|
||||
+ "<ConnectionTimeout>fast</ConnectionTimeout>");
|
||||
|
||||
try (Response created = controller.createDistribution(null, body)) {
|
||||
assertEquals(400, created.getStatus());
|
||||
assertTrue(((String) created.getEntity()).contains("InvalidArgument"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void responseCompletionTimeoutBelowOriginReadTimeoutIsRejected() {
|
||||
CloudFrontService service = mock(CloudFrontService.class);
|
||||
|
||||
+125
@@ -33,6 +33,7 @@ import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
@@ -710,6 +711,111 @@ class CloudFrontServiceTest {
|
||||
.getOriginAccessControlId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createDistributionRejectsConnectionAttemptsOutsideTheAwsRange() {
|
||||
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
|
||||
|
||||
AwsException above = assertAws("InvalidArgument",
|
||||
() -> service.createDistribution(distributionWithCustomOrigin(origin -> {
|
||||
origin.setConnectionAttempts(4);
|
||||
}), Map.of()));
|
||||
assertEquals("The parameter ConnectionAttempts must be between 1 and 3.", above.getMessage());
|
||||
assertEquals(400, above.getHttpStatus());
|
||||
|
||||
assertAws("InvalidArgument",
|
||||
() -> service.createDistribution(distributionWithCustomOrigin(origin -> {
|
||||
origin.setConnectionAttempts(0);
|
||||
}), Map.of()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createDistributionRejectsConnectionTimeoutOutsideTheAwsRange() {
|
||||
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
|
||||
|
||||
AwsException above = assertAws("InvalidArgument",
|
||||
() -> service.createDistribution(distributionWithCustomOrigin(origin -> {
|
||||
origin.setConnectionTimeout(11);
|
||||
}), Map.of()));
|
||||
assertEquals("The parameter ConnectionTimeout must be between 1 and 10 seconds.", above.getMessage());
|
||||
assertEquals(400, above.getHttpStatus());
|
||||
|
||||
AwsException below = assertAws("InvalidArgument",
|
||||
() -> service.createDistribution(distributionWithCustomOrigin(origin -> {
|
||||
origin.setConnectionTimeout(0);
|
||||
}), Map.of()));
|
||||
assertEquals("The parameter ConnectionTimeout must be between 1 and 10 seconds.", below.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createDistributionRejectsOriginReadTimeoutOutsideTheAwsRange() {
|
||||
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
|
||||
|
||||
AwsException error = assertAws("InvalidOriginReadTimeout",
|
||||
() -> service.createDistribution(distributionWithCustomOrigin(origin -> {
|
||||
origin.getCustomOriginConfig().put("OriginReadTimeout", 121);
|
||||
}), Map.of()));
|
||||
assertEquals("The parameter OriginReadTimeout must be between 1 and 120 seconds.", error.getMessage());
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
|
||||
assertAws("InvalidOriginReadTimeout",
|
||||
() -> service.createDistribution(distributionWithCustomOrigin(origin -> {
|
||||
origin.getCustomOriginConfig().put("OriginReadTimeout", 0);
|
||||
}), Map.of()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createDistributionRejectsOriginKeepaliveTimeoutOutsideTheAwsRange() {
|
||||
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
|
||||
|
||||
AwsException below = assertAws("InvalidOriginKeepaliveTimeout",
|
||||
() -> service.createDistribution(distributionWithCustomOrigin(origin -> {
|
||||
origin.getCustomOriginConfig().put("OriginKeepaliveTimeout", 0);
|
||||
}), Map.of()));
|
||||
assertEquals("The parameter OriginKeepaliveTimeout must be between 1 and 300 seconds.", below.getMessage());
|
||||
assertEquals(400, below.getHttpStatus());
|
||||
|
||||
assertAws("InvalidOriginKeepaliveTimeout",
|
||||
() -> service.createDistribution(distributionWithCustomOrigin(origin -> {
|
||||
origin.getCustomOriginConfig().put("OriginKeepaliveTimeout", 301);
|
||||
}), Map.of()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateDistributionRejectsOriginSettingsOutsideTheAwsRange() {
|
||||
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
|
||||
Distribution existing = service.createDistribution(
|
||||
distributionWithCustomOrigin(origin -> { }), Map.of());
|
||||
|
||||
AwsException error = assertAws("InvalidArgument", () -> service.updateDistribution(
|
||||
existing.getId(), existing.getEtag(),
|
||||
distributionWithCustomOrigin(origin -> origin.setConnectionAttempts(4))));
|
||||
assertEquals("The parameter ConnectionAttempts must be between 1 and 3.", error.getMessage());
|
||||
|
||||
assertAws("InvalidOriginReadTimeout", () -> service.updateDistribution(
|
||||
existing.getId(), existing.getEtag(),
|
||||
distributionWithCustomOrigin(origin ->
|
||||
origin.getCustomOriginConfig().put("OriginReadTimeout", 121))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createDistributionAcceptsOriginSettingsWithinTheAwsRange() {
|
||||
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
|
||||
|
||||
Distribution created = assertDoesNotThrow(() -> service.createDistribution(
|
||||
distributionWithCustomOrigin(origin -> {
|
||||
origin.setConnectionAttempts(2);
|
||||
origin.setConnectionTimeout(5);
|
||||
origin.getCustomOriginConfig().put("OriginReadTimeout", 45);
|
||||
origin.getCustomOriginConfig().put("OriginKeepaliveTimeout", 300);
|
||||
}), Map.of()));
|
||||
|
||||
Origin origin = created.getConfig().getOrigins().getFirst();
|
||||
assertEquals(2, origin.getConnectionAttempts());
|
||||
assertEquals(5, origin.getConnectionTimeout());
|
||||
assertEquals(45, origin.getCustomOriginConfig().get("OriginReadTimeout"));
|
||||
assertEquals(300, origin.getCustomOriginConfig().get("OriginKeepaliveTimeout"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anOriginAccessControlInUseKeepsHowItSigns() {
|
||||
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
|
||||
@@ -1495,6 +1601,25 @@ class CloudFrontServiceTest {
|
||||
return distribution;
|
||||
}
|
||||
|
||||
/** A distribution with one custom (HTTP/HTTPS) origin, customized through {@code originCustomizer}. */
|
||||
private static Distribution distributionWithCustomOrigin(Consumer<Origin> originCustomizer) {
|
||||
Origin origin = new Origin();
|
||||
origin.setId("o");
|
||||
origin.setDomainName("example.com");
|
||||
Map<String, Object> customOriginConfig = new LinkedHashMap<>();
|
||||
customOriginConfig.put("HTTPPort", "80");
|
||||
customOriginConfig.put("HTTPSPort", "443");
|
||||
customOriginConfig.put("OriginProtocolPolicy", "https-only");
|
||||
origin.setCustomOriginConfig(customOriginConfig);
|
||||
originCustomizer.accept(origin);
|
||||
DefaultCacheBehavior behavior = new DefaultCacheBehavior();
|
||||
behavior.setTargetOriginId("o");
|
||||
Distribution distribution = distribution(false, List.of());
|
||||
distribution.getConfig().setOrigins(List.of(origin));
|
||||
distribution.getConfig().setDefaultCacheBehavior(behavior);
|
||||
return distribution;
|
||||
}
|
||||
|
||||
private static void assertOriginAccessControlRefused(CloudFrontService service, String domainName, String protocol,
|
||||
String behavior, String originType, String reason) {
|
||||
Distribution distribution = distributionWithOrigin(domainName, oac(service, protocol, behavior, originType), null);
|
||||
|
||||
Reference in new issue
Block a user