diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudFrontCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudFrontCfnProvisioner.java index 6be8f6af53..1535d386b7 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudFrontCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudFrontCfnProvisioner.java @@ -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> 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); + } + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontController.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontController.java index 7f9cb33ccc..202c522fcc 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontController.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontController.java @@ -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); } diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontOriginTimeouts.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontOriginTimeouts.java index 8260e0f41b..c19e1d8de1 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontOriginTimeouts.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontOriginTimeouts.java @@ -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 = diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontService.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontService.java index d36699e6c1..d8c9d4e6a3 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontService.java @@ -199,6 +199,7 @@ public class CloudFrontService implements ServerCertificateReferenceProvider { public synchronized Distribution createDistribution(Distribution dist, Map 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 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; diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServingController.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServingController.java index aeef65a860..86fd64c64d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServingController.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServingController.java @@ -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); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCloudFrontDistributionIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCloudFrontDistributionIntegrationTest.java index 54c1b12296..c662598e26 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCloudFrontDistributionIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCloudFrontDistributionIntegrationTest.java @@ -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("ROLLBACK_COMPLETE")) + .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); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudFrontCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudFrontCfnProvisionerTest.java index 7f8b1786cf..853a39c00b 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudFrontCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudFrontCfnProvisionerTest.java @@ -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 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 diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontControllerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontControllerTest.java index 1d82b0764b..28482f13bb 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontControllerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontControllerTest.java @@ -444,38 +444,6 @@ class CloudFrontControllerTest { } } - @Test - void originReadTimeoutAboveTheAwsMaximumIsRejected() { - CloudFrontService service = mock(CloudFrontService.class); - CloudFrontController controller = new CloudFrontController(service); - - String body = distributionConfigBody("").replace( - "https-only", - "https-only" - + "121"); - - 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( - "https-only", - "https-only" - + "0"); - - 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( + "https-only", + "https-only" + + "fast"); + + 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); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServiceTest.java index cfbf0ee168..1780cd4216 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServiceTest.java @@ -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 originCustomizer) { + Origin origin = new Origin(); + origin.setId("o"); + origin.setDomainName("example.com"); + Map 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);