Light, fluffy, and always free - The AWS Local Emulator alternative
feat(cloudformation): provision CloudFront public keys, key groups and functions (#5390)
Aymen JAMAAOUI61fe30461963
diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.mdindex c332a62610..d20d069a24 100644--- a/docs/services/cloudformation.md+++ b/docs/services/cloudformation.md@@ -163,7 +163,7 @@ cross-resource references.| Kinesis | `Stream` || Kinesis Data Firehose | `DeliveryStream` || IoT Core | `Authorizer`, `DomainConfiguration` (`ServerCertificates` resolves to a JSON string), `Policy` (deleted after detaching it from its principals; on AWS the delete fails with `DeleteConflictException` while the policy is attached), `Thing`, `TopicRule` |-| CloudFront | `CachePolicy`, `Distribution`, `OriginAccessControl`, `OriginRequestPolicy`, `ResponseHeadersPolicy` |+| CloudFront | `CachePolicy`, `Distribution`, `Function` (`KeyValueStoreAssociations` is ignored), `KeyGroup`, `OriginAccessControl`, `OriginRequestPolicy`, `PublicKey`, `ResponseHeadersPolicy` || CloudWatch | `Alarm`, `Dashboard` || CloudWatch Logs | `LogGroup`, `LogStream`, `MetricFilter` || WAFv2 | `WebACL`, `WebACLAssociation` |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.javaindex ddd9d0fb99..6be8f6af53 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@@ -8,12 +8,15 @@ import io.github.hectorvent.floci.services.cloudfront.CloudFrontService;import io.github.hectorvent.floci.services.cloudfront.ResponseHeadersPolicyConfigCodec;import io.github.hectorvent.floci.services.cloudfront.model.CacheBehavior;import io.github.hectorvent.floci.services.cloudfront.model.CachePolicy;+import io.github.hectorvent.floci.services.cloudfront.model.CloudFrontFunction;import io.github.hectorvent.floci.services.cloudfront.model.DefaultCacheBehavior;import io.github.hectorvent.floci.services.cloudfront.model.Distribution;import io.github.hectorvent.floci.services.cloudfront.model.DistributionConfig;+import io.github.hectorvent.floci.services.cloudfront.model.KeyGroup;import io.github.hectorvent.floci.services.cloudfront.model.Origin;import io.github.hectorvent.floci.services.cloudfront.model.OriginAccessControl;import io.github.hectorvent.floci.services.cloudfront.model.OriginRequestPolicy;+import io.github.hectorvent.floci.services.cloudfront.model.PublicKey;import io.github.hectorvent.floci.services.cloudfront.model.ResponseHeadersPolicy;import jakarta.enterprise.context.ApplicationScoped;import org.jboss.logging.Logger;@@ -30,7 +33,8 @@ import java.util.function.Function;/*** Provisions the CloudFront configuration types a distribution references by id: response headers- * policies, cache policies, origin request policies and origin access controls.+ * policies, cache policies, origin request policies and origin access controls. It also provisions+ * public keys, key groups and functions, described on their own provision methods.** <p>Each type has a single required {@code <Type>Config} property and no create-only property, so* the physical id is the id the service assigns and every update is applied in place through the@@ -58,11 +62,17 @@ public class CloudFrontCfnProvisioner implements CfnResourceProvisioner {static final String CACHE_POLICY = "AWS::CloudFront::CachePolicy";static final String ORIGIN_REQUEST_POLICY = "AWS::CloudFront::OriginRequestPolicy";static final String ORIGIN_ACCESS_CONTROL = "AWS::CloudFront::OriginAccessControl";+ static final String PUBLIC_KEY = "AWS::CloudFront::PublicKey";+ static final String KEY_GROUP = "AWS::CloudFront::KeyGroup";+ static final String FUNCTION = "AWS::CloudFront::Function";static final String NO_SUCH_RESPONSE_HEADERS_POLICY = "NoSuchResponseHeadersPolicy";static final String NO_SUCH_CACHE_POLICY = "NoSuchCachePolicy";static final String NO_SUCH_ORIGIN_REQUEST_POLICY = "NoSuchOriginRequestPolicy";static final String NO_SUCH_ORIGIN_ACCESS_CONTROL = "NoSuchOriginAccessControl";+ static final String NO_SUCH_PUBLIC_KEY = "NoSuchPublicKey";+ static final String NO_SUCH_KEY_GROUP = "NoSuchResource";+ static final String NO_SUCH_FUNCTION = "NoSuchFunctionExists";private static final Set<String> MODEL_FIELDS = Set.of("Name", "Comment");@@ -75,7 +85,7 @@ public class CloudFrontCfnProvisioner implements CfnResourceProvisioner {@Overridepublic Set<String> resourceTypes() {return Set.of(DISTRIBUTION, RESPONSE_HEADERS_POLICY, CACHE_POLICY, ORIGIN_REQUEST_POLICY,- ORIGIN_ACCESS_CONTROL);+ ORIGIN_ACCESS_CONTROL, PUBLIC_KEY, KEY_GROUP, FUNCTION);}@Override@@ -87,18 +97,22 @@ public class CloudFrontCfnProvisioner implements CfnResourceProvisioner {case CACHE_POLICY -> provisionCachePolicy(r, props, ctx);case ORIGIN_REQUEST_POLICY -> provisionOriginRequestPolicy(r, props, ctx);case ORIGIN_ACCESS_CONTROL -> provisionOriginAccessControl(r, props, ctx);+ case PUBLIC_KEY -> provisionPublicKey(r, props, ctx);+ case KEY_GROUP -> provisionKeyGroup(r, props, ctx);+ case FUNCTION -> provisionFunction(r, props, ctx);default -> throw new IllegalArgumentException("Unsupported resource type: " + r.getResourceType());}ReplacementCleanup.record(r, ctx, attributesBefore);}/**- * The physical id only changes here when the prior object was already gone: {@code prior}- * returns the entity whenever the service still knows it, so an update either mutates that- * entity in place under the same id or recreates a missing one under a new id. The entity- * {@link ReplacementCleanup} records as displaced is therefore always one that no longer- * exists, and the delete these hooks run for it is a no-op tolerated by its not-found code.- * They are still needed: without them a recorded entity would never leave the cleanup list.+ * For the policy types, public keys and key groups, the physical id only changes here when the+ * prior object was already gone: {@code prior} returns the entity whenever the service still+ * knows it, so an update either mutates that entity in place under the same id or recreates a+ * missing one under a new id. The delete these hooks run for it is then a no-op tolerated by its+ * not-found code, but they are still needed: without them a recorded entity would never leave+ * the cleanup list. A function also gets a new id when its create-only {@code Name} changes, and+ * these hooks then delete the old function after the update.*/@Overridepublic boolean hasReplacementUpdate(StackResource resource) {@@ -160,6 +174,15 @@ public class CloudFrontCfnProvisioner implements CfnResourceProvisioner {case ORIGIN_ACCESS_CONTROL -> deleteWithEtag("origin access control", physicalId,id -> cloudFrontService.getOriginAccessControl(id).getEtag(),cloudFrontService::deleteOriginAccessControl, NO_SUCH_ORIGIN_ACCESS_CONTROL);+ // A public key still in a key group, or a key group still trusted by a distribution,+ // is refused with PublicKeyInUse or ResourceInUse, which must fail the stack delete.+ case PUBLIC_KEY -> deleteWithEtag("public key", physicalId,+ id -> cloudFrontService.getPublicKey(id).getEtag(),+ cloudFrontService::deletePublicKey, NO_SUCH_PUBLIC_KEY);+ case KEY_GROUP -> deleteWithEtag("key group", physicalId,+ id -> cloudFrontService.getKeyGroup(id).getEtag(),+ cloudFrontService::deleteKeyGroup, NO_SUCH_KEY_GROUP);+ case FUNCTION -> deleteFunction(physicalId);default -> { }}}@@ -222,6 +245,145 @@ public class CloudFrontCfnProvisioner implements CfnResourceProvisioner {r.getAttributes().put("Id", provisioned.getId());}+ /**+ * UpdatePublicKey can only change the comment, as in the AWS API. A change of the caller+ * reference, name or encoded key fails the stack update with the service's+ * CannotChangeImmutablePublicKeyFields; it does not replace the key.+ */+ private void provisionPublicKey(StackResource r, JsonNode props, ProvisionContext ctx) {+ JsonNode config = requireConfig(PUBLIC_KEY, "PublicKeyConfig", props, ctx);+ PublicKey key = new PublicKey();+ key.setCallerReference(text(config, "CallerReference"));+ key.setName(text(config, "Name"));+ key.setEncodedKey(text(config, "EncodedKey"));+ key.setComment(text(config, "Comment"));+ PublicKey prior = prior(ctx, "public key", cloudFrontService::getPublicKey, NO_SUCH_PUBLIC_KEY);+ PublicKey provisioned = prior == null+ ? cloudFrontService.createPublicKey(key)+ : cloudFrontService.updatePublicKey(prior.getId(), prior.getEtag(), key);+ r.setPhysicalId(provisioned.getId());+ r.getAttributes().put("Id", provisioned.getId());+ r.getAttributes().put("CreatedTime",+ provisioned.getCreatedTime() == null ? "" : provisioned.getCreatedTime().toString());+ }++ private void provisionKeyGroup(StackResource r, JsonNode props, ProvisionContext ctx) {+ JsonNode config = requireConfig(KEY_GROUP, "KeyGroupConfig", props, ctx);+ KeyGroup group = new KeyGroup();+ group.setName(text(config, "Name"));+ group.setComment(text(config, "Comment"));+ group.setItems(textList(config, "Items"));+ KeyGroup prior = prior(ctx, "key group", cloudFrontService::getKeyGroup, NO_SUCH_KEY_GROUP);+ KeyGroup provisioned = prior == null+ ? cloudFrontService.createKeyGroup(group)+ : cloudFrontService.updateKeyGroup(prior.getId(), prior.getEtag(), group);+ expose(r, provisioned.getId(), provisioned.getLastModifiedTime());+ }++ /**+ * The physical id is the function ARN, the registry schema's primary identifier. {@code Name} is+ * create-only: a new name creates a new function, and {@link ReplacementCleanup} deletes the old+ * one after the update. Any other change updates the DEVELOPMENT stage in place, and+ * {@code AutoPublish: true} then publishes it to LIVE, which {@code Fn::GetAtt Stage} reports.+ * Floci has no Key Value Store, so {@code FunctionConfig.KeyValueStoreAssociations} is ignored.+ *+ * <p>When publishing or tagging fails, a function this call created is deleted again. An+ * in-place update is not reverted, the same limit as the policy types above.+ */+ private void provisionFunction(StackResource r, JsonNode props, ProvisionContext ctx) {+ String name = requireText(FUNCTION, "Name", props, ctx);+ String code = requireText(FUNCTION, "FunctionCode", props, ctx);+ JsonNode config = requireConfig(FUNCTION, "FunctionConfig", props, ctx);+ String runtime = text(config, "Runtime");+ if (runtime == null || runtime.isBlank()) {+ throw new AwsException("ValidationError", FUNCTION + " requires FunctionConfig.Runtime", 400);+ }+ if (!config.hasNonNull("Comment")) {+ throw new AwsException("ValidationError", FUNCTION + " requires FunctionConfig.Comment", 400);+ }+ boolean autoPublish = autoPublish(props, ctx);+ Map<String, String> tags = ctx.resolveTags(props, "Tags");+ CloudFrontFunction fn = new CloudFrontFunction();+ fn.setName(name);+ fn.setFunctionCode(code);+ fn.setComment(text(config, "Comment"));+ fn.setRuntime(runtime);++ String arn = cloudFrontService.arn("function/" + name);+ CloudFrontFunction prior = arn.equals(ctx.priorPhysicalId())+ ? prior(ctx, "function", this::developmentFunction, NO_SUCH_FUNCTION)+ : null;+ CloudFrontFunction provisioned = prior == null+ ? cloudFrontService.createFunction(fn)+ : cloudFrontService.updateFunction(name, prior.getEtag(), fn);+ try {+ if (autoPublish) {+ cloudFrontService.publishFunction(name, provisioned.getEtag());+ }+ reconcileFunctionTags(arn, tags);+ } catch (RuntimeException failure) {+ if (prior == null) {+ // The stack keeps its prior id when this resource fails, so nothing else would+ // ever delete the function created here.+ try {+ deleteFunction(arn);+ } catch (RuntimeException cleanupFailure) {+ failure.addSuppressed(cleanupFailure);+ }+ }+ throw failure;+ }+ r.setPhysicalId(arn);+ r.getAttributes().put("FunctionARN", arn);+ r.getAttributes().put("FunctionMetadata.FunctionARN", arn);+ r.getAttributes().put("Stage", autoPublish ? "LIVE" : "DEVELOPMENT");+ }++ /** False when absent. Any value other than true or false is rejected before the service is called. */+ private static boolean autoPublish(JsonNode props, ProvisionContext ctx) {+ String value = ctx.resolveOptional(props, "AutoPublish");+ if (value == null || "false".equalsIgnoreCase(value)) {+ return false;+ }+ if ("true".equalsIgnoreCase(value)) {+ return true;+ }+ throw new AwsException("ValidationError", FUNCTION + " AutoPublish must be a boolean", 400);+ }++ private CloudFrontFunction developmentFunction(String arn) {+ return cloudFrontService.describeFunction(functionName(arn), null);+ }++ private static String functionName(String arn) {+ return arn.substring(arn.lastIndexOf('/') + 1);+ }++ private void reconcileFunctionTags(String arn, Map<String, String> desired) {+ List<String> stale = ProvisionContext.staleTagKeys(cloudFrontService.listTagsForResource(arn), desired);+ if (!stale.isEmpty()) {+ cloudFrontService.untagResource(arn, stale);+ }+ if (!desired.isEmpty()) {+ cloudFrontService.tagResource(arn, desired);+ }+ }++ /**+ * Deletes the function, then the tags kept under its ARN, which the service delete leaves. The+ * tags are dropped even when the function was already deleted outside the stack, so a later+ * function with the same name does not get them.+ */+ private void deleteFunction(String arn) {+ CfnDeletes.safeDelete("function", arn,+ () -> cloudFrontService.deleteFunction(functionName(arn), developmentFunction(arn).getEtag()),+ NO_SUCH_FUNCTION);+ List<String> tagKeys = List.copyOf(cloudFrontService.listTagsForResource(arn).keySet());+ if (!tagKeys.isEmpty()) {+ cloudFrontService.untagResource(arn, tagKeys);+ }+ }+private static void expose(StackResource r, String id, Instant lastModifiedTime) {r.setPhysicalId(id);r.getAttributes().put("Id", id);@@ -268,6 +430,26 @@ public class CloudFrontCfnProvisioner implements CfnResourceProvisioner {return value == null || value.isNull() ? null : value.asText();}+ private static List<String> textList(JsonNode node, String name) {+ JsonNode value = node.get(name);+ if (value == null || !value.isArray()) {+ return null;+ }+ List<String> list = new ArrayList<>();+ for (JsonNode element : value) {+ list.add(element.asText());+ }+ return list;+ }++ private static String requireText(String type, String name, JsonNode props, ProvisionContext ctx) {+ String value = ctx.resolveOptional(props, name);+ if (value == null || value.isBlank()) {+ throw new AwsException("ValidationError", type + " requires " + name, 400);+ }+ return value;+ }+/*** The configuration blocks as the service's codec shapes them: objects to maps, arrays to lists,* every scalar as its text (a JSON {@code true} arrives as {@code "true"}), nulls dropped.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.javaindex f38956331f..cefbb86245 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@@ -1293,6 +1293,13 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {// ── CloudFront Functions ──────────────────────────────────────────────────public synchronized CloudFrontFunction createFunction(CloudFrontFunction fn) {+ // The bare name holds the DEVELOPMENT stage, and the LIVE stage of releases before+ // stage-aware keys.+ if (functionStore.get(fn.getName()).isPresent()+ || functionStore.get(functionKey(fn.getName(), "LIVE")).isPresent()) {+ throw new AwsException("FunctionAlreadyExists",+ "A function with the same name already exists in this AWS account.", 409);+ }fn.setStage("DEVELOPMENT");fn.setStatus("UNPUBLISHED");fn.setEtag(UUID.randomUUID().toString());diff --git a/src/main/resources/cloudformation/create-only-properties.json b/src/main/resources/cloudformation/create-only-properties.jsonindex a04ac90fdb..c6f9194285 100644--- a/src/main/resources/cloudformation/create-only-properties.json+++ b/src/main/resources/cloudformation/create-only-properties.json@@ -151,8 +151,13 @@],"AWS::CloudFront::CachePolicy": [],"AWS::CloudFront::Distribution": [],+ "AWS::CloudFront::Function": [+ "Name"+ ],+ "AWS::CloudFront::KeyGroup": [],"AWS::CloudFront::OriginAccessControl": [],"AWS::CloudFront::OriginRequestPolicy": [],+ "AWS::CloudFront::PublicKey": [],"AWS::CloudFront::ResponseHeadersPolicy": [],"AWS::CloudTrail::Trail": ["TrailName"diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCloudFrontKeysAndFunctionsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCloudFrontKeysAndFunctionsIntegrationTest.javanew file mode 100644index 0000000000..da59eb5a29--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCloudFrontKeysAndFunctionsIntegrationTest.java@@ -0,0 +1,218 @@+package io.github.hectorvent.floci.services.cloudformation;++import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.XmlParser;+import io.github.hectorvent.floci.services.cloudfront.CloudFrontService;+import io.github.hectorvent.floci.services.cloudfront.model.CloudFrontFunction;+import io.github.hectorvent.floci.services.cloudfront.model.KeyGroup;+import io.github.hectorvent.floci.services.cloudfront.model.PublicKey;+import io.quarkus.test.junit.QuarkusTest;+import jakarta.inject.Inject;+import org.junit.jupiter.api.Test;++import java.security.KeyPairGenerator;+import java.util.Base64;+import java.util.List;+import java.util.Map;++import static io.restassured.RestAssured.given;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNotEquals;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.fail;++/**+ * AWS::CloudFront::PublicKey, KeyGroup and Function through the stack lifecycle, with the template+ * from issue #4652: the exact {@code Ref} and {@code Fn::GetAtt} values, in-place updates, the+ * replacement of a function whose {@code Name} changes, and DeleteStack.+ */+@QuarkusTest+class CloudFormationCloudFrontKeysAndFunctionsIntegrationTest {++ private static final String CFN_AUTH =+ "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request";++ @Inject+ CloudFrontService cloudFrontService;++ @Test+ void publicKeyKeyGroupAndFunctionFollowTheStackLifecycle() throws Exception {+ String suffix = Long.toString(System.nanoTime(), 36);+ String stackName = "cfn-cloudfront-keys-" + suffix;+ String pem = rsaPublicKeyPem();+ String functionName = "cfn-function-" + suffix;++ stackCall("CreateStack", stackName, template(suffix, pem, "first", functionName, "v1"));+ assertStatus(stackName, "CREATE_COMPLETE");+ String describe = describeStacks(stackName);++ String publicKeyId = output(describe, "PublicKeyRef");+ assertEquals(publicKeyId, output(describe, "PublicKeyId"));+ PublicKey key = cloudFrontService.getPublicKey(publicKeyId);+ assertEquals("cfn-key-" + suffix, key.getName());+ assertEquals("first", key.getComment());+ assertEquals(key.getCreatedTime().toString(), output(describe, "PublicKeyCreatedTime"));++ String keyGroupId = output(describe, "KeyGroupRef");+ assertEquals(keyGroupId, output(describe, "KeyGroupId"));+ KeyGroup group = cloudFrontService.getKeyGroup(keyGroupId);+ assertEquals(List.of(publicKeyId), group.getItems());+ assertEquals(group.getLastModifiedTime().toString(), output(describe, "KeyGroupLastModifiedTime"));++ String functionArn = cloudFrontService.arn("function/" + functionName);+ assertEquals(functionArn, output(describe, "FunctionRef"));+ assertEquals(functionArn, output(describe, "FunctionArn"));+ assertEquals(functionArn, output(describe, "FunctionMetadataArn"));+ assertEquals("LIVE", output(describe, "FunctionStage"));+ assertEquals("v1", cloudFrontService.describeFunction(functionName, "LIVE").getFunctionCode());+ assertEquals(Map.of("Env", "test"), cloudFrontService.listTagsForResource(functionArn));++ String otherStack = stackName + "-other";+ stackCall("CreateStack", otherStack, template(suffix + "-other", rsaPublicKeyPem(), "other",+ functionName, "other code"));+ assertStatus(otherStack, "ROLLBACK_COMPLETE");+ assertEquals("v1", cloudFrontService.describeFunction(functionName, null).getFunctionCode(),+ "a second stack cannot take the name, and its rollback keeps the first function");++ stackCall("UpdateStack", stackName, template(suffix, pem, "second", functionName, "v2"));+ assertStatus(stackName, "UPDATE_COMPLETE");+ describe = describeStacks(stackName);+ assertEquals(publicKeyId, output(describe, "PublicKeyRef"), "a comment change keeps the key");+ assertEquals("second", cloudFrontService.getPublicKey(publicKeyId).getComment());+ assertEquals(keyGroupId, output(describe, "KeyGroupRef"));+ assertEquals(functionArn, output(describe, "FunctionRef"), "a code change keeps the function");+ assertEquals("v2", cloudFrontService.describeFunction(functionName, null).getFunctionCode());+ assertEquals("v2", cloudFrontService.describeFunction(functionName, "LIVE").getFunctionCode());++ String renamed = functionName + "-renamed";+ stackCall("UpdateStack", stackName, template(suffix, pem, "second", renamed, "v2"));+ assertStatus(stackName, "UPDATE_COMPLETE");+ String renamedArn = output(describeStacks(stackName), "FunctionRef");+ assertNotEquals(functionArn, renamedArn, "a Name change replaces the function");+ assertEquals(cloudFrontService.arn("function/" + renamed), renamedArn);+ assertFunctionGone(functionName);+ assertEquals(Map.of(), cloudFrontService.listTagsForResource(functionArn));++ deleteStack(stackName);+ assertFunctionGone(renamed);+ assertEquals("NoSuchResource",+ assertThrows(AwsException.class, () -> cloudFrontService.getKeyGroup(keyGroupId)).getErrorCode());+ assertEquals("NoSuchPublicKey",+ assertThrows(AwsException.class, () -> cloudFrontService.getPublicKey(publicKeyId)).getErrorCode());+ }++ private void assertFunctionGone(String name) {+ AwsException e = assertThrows(AwsException.class, () -> cloudFrontService.describeFunction(name, null));+ assertEquals("NoSuchFunctionExists", e.getErrorCode());+ }++ private static String rsaPublicKeyPem() throws Exception {+ KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");+ generator.initialize(2048);+ String body = Base64.getMimeEncoder(64, "\n".getBytes())+ .encodeToString(generator.generateKeyPair().getPublic().getEncoded());+ return "-----BEGIN PUBLIC KEY-----\n" + body + "\n-----END PUBLIC KEY-----\n";+ }++ /** The template from issue #4652, with unique names and the outputs the assertions read. */+ private static String template(String suffix, String pem, String keyComment, String functionName,+ String code) {+ return """+ {+ "Resources": {+ "PublicKey": {+ "Type": "AWS::CloudFront::PublicKey",+ "Properties": {+ "PublicKeyConfig": {+ "Name": "cfn-key-%1$s",+ "CallerReference": "cfn-key-%1$s-1",+ "EncodedKey": "%2$s",+ "Comment": "%3$s"+ }+ }+ },+ "KeyGroup": {+ "Type": "AWS::CloudFront::KeyGroup",+ "Properties": {+ "KeyGroupConfig": {+ "Name": "cfn-key-group-%1$s",+ "Items": [{"Ref": "PublicKey"}]+ }+ }+ },+ "Function": {+ "Type": "AWS::CloudFront::Function",+ "Properties": {+ "Name": "%4$s",+ "AutoPublish": true,+ "FunctionCode": "%5$s",+ "FunctionConfig": {"Comment": "example", "Runtime": "cloudfront-js-2.0"},+ "Tags": [{"Key": "Env", "Value": "test"}]+ }+ }+ },+ "Outputs": {+ "PublicKeyRef": {"Value": {"Ref": "PublicKey"}},+ "PublicKeyId": {"Value": {"Fn::GetAtt": ["PublicKey", "Id"]}},+ "PublicKeyCreatedTime": {"Value": {"Fn::GetAtt": ["PublicKey", "CreatedTime"]}},+ "KeyGroupRef": {"Value": {"Ref": "KeyGroup"}},+ "KeyGroupId": {"Value": {"Fn::GetAtt": ["KeyGroup", "Id"]}},+ "KeyGroupLastModifiedTime": {"Value": {"Fn::GetAtt": ["KeyGroup", "LastModifiedTime"]}},+ "FunctionRef": {"Value": {"Ref": "Function"}},+ "FunctionArn": {"Value": {"Fn::GetAtt": ["Function", "FunctionARN"]}},+ "FunctionMetadataArn": {"Value": {"Fn::GetAtt": ["Function", "FunctionMetadata.FunctionARN"]}},+ "FunctionStage": {"Value": {"Fn::GetAtt": ["Function", "Stage"]}}+ }+ }+ """.formatted(suffix, pem.replace("\n", "\\n"), keyComment, functionName, code);+ }++ private static void assertStatus(String stackName, String expected) {+ CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stackName);+ assertEquals(expected, state.status(), state.reason());+ }++ private static void stackCall(String action, String stackName, String template) {+ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", action)+ .formParam("StackName", stackName)+ .formParam("TemplateBody", template)+ .when()+ .post("/")+ .then()+ .statusCode(200);+ }++ private static void deleteStack(String stackName) {+ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "DeleteStack")+ .formParam("StackName", stackName)+ .when()+ .post("/")+ .then()+ .statusCode(200);+ CfnStackWaits.awaitStackDeleted(stackName);+ }++ private static String describeStacks(String stackName) {+ return given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "DescribeStacks")+ .formParam("StackName", stackName)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .extract().asString();+ }++ private static String output(String describeStacks, String key) {+ String value = XmlParser.extractPairs(describeStacks, "Outputs", "OutputKey", "OutputValue").get(key);+ return value != null ? value : fail("Output " + key + " missing from: " + describeStacks);+ }+}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.javaindex 696e05edcc..7f8b1786cf 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@@ -7,11 +7,14 @@ import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateimport io.github.hectorvent.floci.services.cloudformation.model.StackResource;import io.github.hectorvent.floci.services.cloudfront.CloudFrontService;import io.github.hectorvent.floci.services.cloudfront.model.CachePolicy;+import io.github.hectorvent.floci.services.cloudfront.model.CloudFrontFunction;import io.github.hectorvent.floci.services.cloudfront.model.Distribution;import io.github.hectorvent.floci.services.cloudfront.model.DistributionConfig;+import io.github.hectorvent.floci.services.cloudfront.model.KeyGroup;import io.github.hectorvent.floci.services.cloudfront.model.Origin;import io.github.hectorvent.floci.services.cloudfront.model.OriginAccessControl;import io.github.hectorvent.floci.services.cloudfront.model.OriginRequestPolicy;+import io.github.hectorvent.floci.services.cloudfront.model.PublicKey;import io.github.hectorvent.floci.services.cloudfront.model.ResponseHeadersPolicy;import org.junit.jupiter.api.Test;import org.mockito.ArgumentCaptor;@@ -30,6 +33,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows;import static org.junit.jupiter.api.Assertions.assertTrue;import static org.mockito.ArgumentMatchers.any;import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.doThrow;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.never;import static org.mockito.Mockito.verify;@@ -47,6 +51,10 @@ class CloudFrontCfnProvisionerTest {private static final String ORIGIN_REQUEST_POLICY = "AWS::CloudFront::OriginRequestPolicy";private static final String ORIGIN_ACCESS_CONTROL = "AWS::CloudFront::OriginAccessControl";private static final String DISTRIBUTION = "AWS::CloudFront::Distribution";+ private static final String PUBLIC_KEY = "AWS::CloudFront::PublicKey";+ private static final String KEY_GROUP = "AWS::CloudFront::KeyGroup";+ private static final String FUNCTION = "AWS::CloudFront::Function";+ private static final String FUNCTION_ARN = "arn:aws:cloudfront::000000000000:function/my-function";private static final String REGION = "us-east-1";private static final String ID = "5cc3b908-e619-4b99-88e5-2cf7f45965bd";private static final String ETAG = "E2QWRUHAPOMQZL";@@ -100,9 +108,9 @@ class CloudFrontCfnProvisionerTest {}@Test- void servesTheDistributionAndItsFourConfigTypes() {+ void servesTheDistributionAndTheTypesItReferences() {assertEquals(Set.of(DISTRIBUTION, RESPONSE_HEADERS_POLICY, CACHE_POLICY, ORIGIN_REQUEST_POLICY,- ORIGIN_ACCESS_CONTROL), provisioner.resourceTypes());+ ORIGIN_ACCESS_CONTROL, PUBLIC_KEY, KEY_GROUP, FUNCTION), provisioner.resourceTypes());}/**@@ -590,4 +598,403 @@ class CloudFrontCfnProvisionerTest {captor.getValue().getConfig());assertEquals(Map.of("Id", ID, "LastModifiedTime", ""), r.getAttributes());}++ private static PublicKey publicKey(String id, String etag) {+ PublicKey key = new PublicKey();+ key.setId(id);+ key.setEtag(etag);+ key.setCreatedTime(MODIFIED);+ return key;+ }++ private static KeyGroup keyGroup(String id, String etag) {+ KeyGroup group = new KeyGroup();+ group.setId(id);+ group.setEtag(etag);+ group.setLastModifiedTime(MODIFIED);+ return group;+ }++ private static CloudFrontFunction function(String name, String etag) {+ CloudFrontFunction fn = new CloudFrontFunction();+ fn.setName(name);+ fn.setEtag(etag);+ fn.setStage("DEVELOPMENT");+ return fn;+ }++ private void stubFunctionArns() {+ when(cloudFront.arn(any())).thenAnswer(inv -> "arn:aws:cloudfront::000000000000:" + inv.getArgument(0));+ }++ @Test+ void createsPublicKeyAndExposesIdAndCreatedTime() throws Exception {+ when(cloudFront.createPublicKey(any()))+ .thenAnswer(inv -> withIdentity(inv.<PublicKey>getArgument(0), k -> {+ k.setId("K36X4X2EO997HM");+ k.setEtag(ETAG);+ k.setCreatedTime(MODIFIED);+ }));+ StackResource r = resource(PUBLIC_KEY);++ provisioner.provision(r, json("""+ {"PublicKeyConfig": {"Name": "example-key", "CallerReference": "example-key-1",+ "EncodedKey": "-----BEGIN PUBLIC KEY-----", "Comment": "first"}}+ """), ctx());++ ArgumentCaptor<PublicKey> captor = ArgumentCaptor.forClass(PublicKey.class);+ verify(cloudFront).createPublicKey(captor.capture());+ assertEquals("example-key", captor.getValue().getName());+ assertEquals("example-key-1", captor.getValue().getCallerReference());+ assertEquals("-----BEGIN PUBLIC KEY-----", captor.getValue().getEncodedKey());+ assertEquals("first", captor.getValue().getComment());+ assertEquals("K36X4X2EO997HM", r.getPhysicalId());+ assertEquals(Map.of("Id", "K36X4X2EO997HM", "CreatedTime", MODIFIED.toString()), r.getAttributes());+ }++ @Test+ void updatesPublicKeyInPlaceWithTheCurrentEtag() throws Exception {+ when(cloudFront.getPublicKey("K36X4X2EO997HM")).thenReturn(publicKey("K36X4X2EO997HM", ETAG));+ when(cloudFront.updatePublicKey(eq("K36X4X2EO997HM"), eq(ETAG), any()))+ .thenAnswer(inv -> withIdentity(inv.<PublicKey>getArgument(2), k -> {+ k.setId("K36X4X2EO997HM");+ k.setCreatedTime(MODIFIED);+ }));+ StackResource r = resource(PUBLIC_KEY, "K36X4X2EO997HM", Map.of("Id", "K36X4X2EO997HM"));++ provisioner.provision(r, json("""+ {"PublicKeyConfig": {"Name": "example-key", "CallerReference": "example-key-1",+ "EncodedKey": "-----BEGIN PUBLIC KEY-----", "Comment": "second"}}+ """), ctx("K36X4X2EO997HM"));++ ArgumentCaptor<PublicKey> captor = ArgumentCaptor.forClass(PublicKey.class);+ verify(cloudFront).updatePublicKey(eq("K36X4X2EO997HM"), eq(ETAG), captor.capture());+ assertEquals("second", captor.getValue().getComment());+ verify(cloudFront, never()).createPublicKey(any());+ assertEquals("K36X4X2EO997HM", r.getPhysicalId());+ }++ @Test+ void publicKeyFieldTheServiceCannotChangeFailsTheUpdate() throws Exception {+ when(cloudFront.getPublicKey("K36X4X2EO997HM")).thenReturn(publicKey("K36X4X2EO997HM", ETAG));+ AwsException immutable = new AwsException("CannotChangeImmutablePublicKeyFields",+ "The caller reference, name, and encoded public key cannot be changed.", 400);+ when(cloudFront.updatePublicKey(eq("K36X4X2EO997HM"), eq(ETAG), any())).thenThrow(immutable);+ StackResource r = resource(PUBLIC_KEY, "K36X4X2EO997HM", Map.of("Id", "K36X4X2EO997HM"));++ AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, json("""+ {"PublicKeyConfig": {"Name": "renamed-key", "CallerReference": "example-key-1",+ "EncodedKey": "-----BEGIN PUBLIC KEY-----"}}+ """), ctx("K36X4X2EO997HM")));++ assertSame(immutable, e);+ verify(cloudFront, never()).createPublicKey(any());+ }++ @Test+ void deletesPublicKeyWithItsEtagAndToleratesItBeingGone() {+ when(cloudFront.getPublicKey("K36X4X2EO997HM")).thenReturn(publicKey("K36X4X2EO997HM", ETAG));+ when(cloudFront.getPublicKey("gone")).thenThrow(+ new AwsException("NoSuchPublicKey", "The specified public key does not exist.", 404));++ provisioner.delete(PUBLIC_KEY, "K36X4X2EO997HM", REGION);+ provisioner.delete(PUBLIC_KEY, "gone", REGION);++ verify(cloudFront).deletePublicKey("K36X4X2EO997HM", ETAG);+ verify(cloudFront, never()).deletePublicKey(eq("gone"), any());+ }++ @Test+ void createsKeyGroupWithItsPublicKeyIdsAndExposesIdAndLastModifiedTime() throws Exception {+ when(cloudFront.createKeyGroup(any()))+ .thenAnswer(inv -> withIdentity(inv.<KeyGroup>getArgument(0), g -> {+ g.setId(ID);+ g.setEtag(ETAG);+ g.setLastModifiedTime(MODIFIED);+ }));+ StackResource r = resource(KEY_GROUP);++ provisioner.provision(r, json("""+ {"KeyGroupConfig": {"Name": "example-key-group", "Comment": "group",+ "Items": ["K36X4X2EO997HM", "K2JCJMDEHXQW5F"]}}+ """), ctx());++ ArgumentCaptor<KeyGroup> captor = ArgumentCaptor.forClass(KeyGroup.class);+ verify(cloudFront).createKeyGroup(captor.capture());+ assertEquals("example-key-group", captor.getValue().getName());+ assertEquals("group", captor.getValue().getComment());+ assertEquals(List.of("K36X4X2EO997HM", "K2JCJMDEHXQW5F"), captor.getValue().getItems());+ assertEquals(ID, r.getPhysicalId());+ assertEquals(Map.of("Id", ID, "LastModifiedTime", MODIFIED.toString()), r.getAttributes());+ }++ @Test+ void updatesAndDeletesKeyGroupThroughTheEtag() throws Exception {+ when(cloudFront.getKeyGroup(ID)).thenReturn(keyGroup(ID, ETAG));+ when(cloudFront.updateKeyGroup(eq(ID), eq(ETAG), any()))+ .thenAnswer(inv -> withIdentity(inv.<KeyGroup>getArgument(2), g -> {+ g.setId(ID);+ g.setLastModifiedTime(MODIFIED.plusSeconds(60));+ }));+ StackResource r = resource(KEY_GROUP, ID, Map.of("Id", ID));++ provisioner.provision(r, json("""+ {"KeyGroupConfig": {"Name": "example-key-group", "Items": ["K2JCJMDEHXQW5F"]}}+ """), ctx(ID));+ provisioner.delete(KEY_GROUP, ID, REGION);++ ArgumentCaptor<KeyGroup> captor = ArgumentCaptor.forClass(KeyGroup.class);+ verify(cloudFront).updateKeyGroup(eq(ID), eq(ETAG), captor.capture());+ assertEquals(List.of("K2JCJMDEHXQW5F"), captor.getValue().getItems());+ verify(cloudFront, never()).createKeyGroup(any());+ verify(cloudFront).deleteKeyGroup(ID, ETAG);+ assertEquals(Map.of("Id", ID, "LastModifiedTime", "2026-09-07T10:16:30Z"), r.getAttributes());+ }++ @Test+ void deleteOfAKeyGroupStillInUseFailsTheStack() {+ when(cloudFront.getKeyGroup(ID)).thenReturn(keyGroup(ID, ETAG));+ AwsException inUse = new AwsException("ResourceInUse",+ "Cannot delete this resource because it is in use.", 409);+ doThrow(inUse).when(cloudFront).deleteKeyGroup(ID, ETAG);++ AwsException e = assertThrows(AwsException.class, () -> provisioner.delete(KEY_GROUP, ID, REGION));++ assertSame(inUse, e);+ }++ @Test+ void createsFunctionPublishesItAndTagsItsArn() throws Exception {+ stubFunctionArns();+ when(cloudFront.createFunction(any()))+ .thenAnswer(inv -> withIdentity(inv.<CloudFrontFunction>getArgument(0), f -> f.setEtag(ETAG)));+ StackResource r = resource(FUNCTION);++ provisioner.provision(r, json("""+ {"Name": "my-function", "AutoPublish": true,+ "FunctionCode": "function handler(event) { return event.request; }",+ "FunctionConfig": {"Comment": "example", "Runtime": "cloudfront-js-2.0"},+ "Tags": [{"Key": "Env", "Value": "test"}]}+ """), distributionCtx(null));++ ArgumentCaptor<CloudFrontFunction> captor = ArgumentCaptor.forClass(CloudFrontFunction.class);+ verify(cloudFront).createFunction(captor.capture());+ assertEquals("my-function", captor.getValue().getName());+ assertEquals("function handler(event) { return event.request; }", captor.getValue().getFunctionCode());+ assertEquals("example", captor.getValue().getComment());+ assertEquals("cloudfront-js-2.0", captor.getValue().getRuntime());+ verify(cloudFront).publishFunction("my-function", ETAG);+ verify(cloudFront).tagResource(FUNCTION_ARN, Map.of("Env", "test"));+ assertEquals(FUNCTION_ARN, r.getPhysicalId());+ assertEquals(Map.of("FunctionARN", FUNCTION_ARN, "FunctionMetadata.FunctionARN", FUNCTION_ARN,+ "Stage", "LIVE"), r.getAttributes());+ }++ @Test+ void functionWithoutAutoPublishStaysInDevelopment() throws Exception {+ stubFunctionArns();+ when(cloudFront.createFunction(any()))+ .thenAnswer(inv -> withIdentity(inv.<CloudFrontFunction>getArgument(0), f -> f.setEtag(ETAG)));+ StackResource r = resource(FUNCTION);++ provisioner.provision(r, json("""+ {"Name": "my-function", "FunctionCode": "code",+ "FunctionConfig": {"Comment": "example", "Runtime": "cloudfront-js-2.0"}}+ """), distributionCtx(null));++ verify(cloudFront, never()).publishFunction(any(), any());+ verify(cloudFront, never()).tagResource(any(), any());+ assertEquals("DEVELOPMENT", r.getAttributes().get("Stage"));+ }++ @Test+ void updatesFunctionInPlaceWithTheDevelopmentEtagAndDropsStaleTags() throws Exception {+ stubFunctionArns();+ when(cloudFront.describeFunction("my-function", null)).thenReturn(function("my-function", ETAG));+ when(cloudFront.updateFunction(eq("my-function"), eq(ETAG), any()))+ .thenAnswer(inv -> withIdentity(inv.<CloudFrontFunction>getArgument(2), f -> f.setEtag(NEW_ETAG)));+ when(cloudFront.listTagsForResource(FUNCTION_ARN)).thenReturn(Map.of("Env", "test", "Old", "x"));+ StackResource r = resource(FUNCTION, FUNCTION_ARN, Map.of("FunctionARN", FUNCTION_ARN));++ provisioner.provision(r, json("""+ {"Name": "my-function", "AutoPublish": true, "FunctionCode": "new code",+ "FunctionConfig": {"Comment": "second", "Runtime": "cloudfront-js-2.0"},+ "Tags": [{"Key": "Env", "Value": "test"}]}+ """), distributionCtx(FUNCTION_ARN));++ ArgumentCaptor<CloudFrontFunction> captor = ArgumentCaptor.forClass(CloudFrontFunction.class);+ verify(cloudFront).updateFunction(eq("my-function"), eq(ETAG), captor.capture());+ assertEquals("new code", captor.getValue().getFunctionCode());+ verify(cloudFront, never()).createFunction(any());+ verify(cloudFront).publishFunction("my-function", NEW_ETAG);+ verify(cloudFront).untagResource(FUNCTION_ARN, List.of("Old"));+ assertEquals(FUNCTION_ARN, r.getPhysicalId());+ assertFalse(provisioner.hasReplacementUpdate(r));+ }++ @Test+ void functionNameChangeCreatesANewFunctionAndDeletesTheOldOneAfterTheUpdate() throws Exception {+ stubFunctionArns();+ when(cloudFront.createFunction(any()))+ .thenAnswer(inv -> withIdentity(inv.<CloudFrontFunction>getArgument(0), f -> f.setEtag(NEW_ETAG)));+ when(cloudFront.describeFunction("my-function", null)).thenReturn(function("my-function", ETAG));+ StackResource r = resource(FUNCTION, FUNCTION_ARN, Map.of("FunctionARN", FUNCTION_ARN));++ provisioner.provision(r, json("""+ {"Name": "renamed-function", "FunctionCode": "code",+ "FunctionConfig": {"Comment": "example", "Runtime": "cloudfront-js-2.0"}}+ """), distributionCtx(FUNCTION_ARN));++ verify(cloudFront, never()).updateFunction(any(), any(), any());+ String newArn = "arn:aws:cloudfront::000000000000:function/renamed-function";+ assertEquals(newArn, r.getPhysicalId());+ assertTrue(provisioner.hasReplacementUpdate(r), "the old function is owed a cleanup");+ assertEquals(FUNCTION_ARN, provisioner.updateCleanupPhysicalId(r));+ provisioner.completeUpdate(r);+ verify(cloudFront).deleteFunction("my-function", ETAG);+ }++ @Test+ void functionCreatedByARenameIsDeletedWhenPublishingFails() throws Exception {+ stubFunctionArns();+ CloudFrontFunction created = function("renamed-function", NEW_ETAG);+ when(cloudFront.createFunction(any())).thenReturn(created);+ when(cloudFront.describeFunction("renamed-function", null)).thenReturn(created);+ AwsException publishFailure = new AwsException("InvalidIfMatchVersion",+ "The If-Match version is missing or not valid for the resource.", 400);+ when(cloudFront.publishFunction("renamed-function", NEW_ETAG)).thenThrow(publishFailure);+ StackResource r = resource(FUNCTION, FUNCTION_ARN, Map.of("FunctionARN", FUNCTION_ARN));++ AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, json("""+ {"Name": "renamed-function", "AutoPublish": true, "FunctionCode": "code",+ "FunctionConfig": {"Comment": "example", "Runtime": "cloudfront-js-2.0"}}+ """), distributionCtx(FUNCTION_ARN)));++ assertSame(publishFailure, e);+ verify(cloudFront).deleteFunction("renamed-function", NEW_ETAG);+ verify(cloudFront, never()).deleteFunction(eq("my-function"), any());+ assertEquals(FUNCTION_ARN, r.getPhysicalId(), "the resource still names the old function");+ }++ @Test+ void functionWhoseNameIsTakenFailsWithoutTouchingTheOtherFunction() throws Exception {+ stubFunctionArns();+ AwsException taken = new AwsException("FunctionAlreadyExists",+ "A function with the same name already exists in this AWS account.", 409);+ when(cloudFront.createFunction(any())).thenThrow(taken);+ StackResource r = resource(FUNCTION);++ AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, json("""+ {"Name": "my-function", "AutoPublish": true, "FunctionCode": "code",+ "FunctionConfig": {"Comment": "example", "Runtime": "cloudfront-js-2.0"}}+ """), distributionCtx(null)));++ assertSame(taken, e);+ assertNull(r.getPhysicalId(), "a failed create names nothing the rollback would delete");+ verify(cloudFront, never()).deleteFunction(any(), any());+ verify(cloudFront, never()).publishFunction(any(), any());+ }++ @Test+ void functionWithoutRuntimeIsAValidationError() throws Exception {+ StackResource r = resource(FUNCTION);++ AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, json("""+ {"Name": "my-function", "FunctionCode": "code", "FunctionConfig": {"Comment": "example"}}+ """), distributionCtx(null)));++ assertEquals("ValidationError", e.getErrorCode());+ assertEquals(FUNCTION + " requires FunctionConfig.Runtime", e.getMessage());+ verify(cloudFront, never()).createFunction(any());+ }++ @Test+ void functionWithoutCommentIsAValidationError() throws Exception {+ StackResource r = resource(FUNCTION);++ AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, json("""+ {"Name": "my-function", "FunctionCode": "code", "FunctionConfig": {"Runtime": "cloudfront-js-2.0"}}+ """), distributionCtx(null)));++ assertEquals("ValidationError", e.getErrorCode());+ assertEquals(FUNCTION + " requires FunctionConfig.Comment", e.getMessage());+ verify(cloudFront, never()).createFunction(any());+ }++ @Test+ void functionWithAnEmptyCommentIsCreated() throws Exception {+ when(cloudFront.arn("function/my-function")).thenReturn(FUNCTION_ARN);+ when(cloudFront.createFunction(any())).thenReturn(function("my-function", ETAG));+ StackResource r = resource(FUNCTION);++ provisioner.provision(r, json("""+ {"Name": "my-function", "FunctionCode": "code",+ "FunctionConfig": {"Comment": "", "Runtime": "cloudfront-js-2.0"}}+ """), distributionCtx(null));++ assertEquals(FUNCTION_ARN, r.getPhysicalId());+ }++ @Test+ void functionWithAnAutoPublishThatIsNotABooleanIsAValidationError() throws Exception {+ StackResource r = resource(FUNCTION);++ AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, json("""+ {"Name": "my-function", "AutoPublish": "yes", "FunctionCode": "code",+ "FunctionConfig": {"Comment": "example", "Runtime": "cloudfront-js-2.0"}}+ """), distributionCtx(null)));++ assertEquals("ValidationError", e.getErrorCode());+ assertEquals(FUNCTION + " AutoPublish must be a boolean", e.getMessage());+ verify(cloudFront, never()).createFunction(any());+ }++ @Test+ void deleteOfAFunctionAlreadyGoneStillDropsItsTags() {+ when(cloudFront.describeFunction("my-function", null)).thenThrow(+ new AwsException("NoSuchFunctionExists", "The specified function does not exist.", 404));+ when(cloudFront.listTagsForResource(FUNCTION_ARN)).thenReturn(Map.of("Env", "test"));++ provisioner.delete(FUNCTION, FUNCTION_ARN, REGION);++ verify(cloudFront, never()).deleteFunction(any(), any());+ verify(cloudFront).untagResource(FUNCTION_ARN, List.of("Env"));+ }++ @Test+ void deletesFunctionWithItsEtagAndRemovesItsTags() {+ when(cloudFront.describeFunction("my-function", null)).thenReturn(function("my-function", ETAG));+ when(cloudFront.listTagsForResource(FUNCTION_ARN)).thenReturn(Map.of("Env", "test"));+ when(cloudFront.describeFunction("gone", null)).thenThrow(+ new AwsException("NoSuchFunctionExists", "The specified function does not exist.", 404));++ provisioner.delete(FUNCTION, FUNCTION_ARN, REGION);+ provisioner.delete(FUNCTION, "arn:aws:cloudfront::000000000000:function/gone", REGION);++ verify(cloudFront).deleteFunction("my-function", ETAG);+ verify(cloudFront).untagResource(FUNCTION_ARN, List.of("Env"));+ verify(cloudFront, never()).deleteFunction(eq("gone"), any());+ }++ @Test+ void functionWithoutNameOrCodeIsAValidationError() throws Exception {+ for (String[] missing : new String[][] {+ {"Name", """+ {"FunctionCode": "code", "FunctionConfig": {"Comment": "c", "Runtime": "cloudfront-js-2.0"}}+ """},+ {"FunctionCode", """+ {"Name": "my-function", "FunctionConfig": {"Comment": "c", "Runtime": "cloudfront-js-2.0"}}+ """},+ {"FunctionConfig", """+ {"Name": "my-function", "FunctionCode": "code"}+ """}}) {+ StackResource r = resource(FUNCTION);+ AwsException e = assertThrows(AwsException.class,+ () -> provisioner.provision(r, json(missing[1]), distributionCtx(null)));+ assertEquals("ValidationError", e.getErrorCode());+ assertEquals(FUNCTION + " requires " + missing[0], e.getMessage());+ assertNull(r.getPhysicalId());+ }+ verify(cloudFront, never()).createFunction(any());+ }}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.javaindex c3b2e3d2da..aa47c5e730 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@@ -169,6 +169,38 @@ class CloudFrontServiceTest {assertNotEquals(development.getEtag(), live.getEtag());}+ @Test+ void createFunction_existingName_isRejectedAndKeepsTheFunction() {+ CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");+ CloudFrontFunction first = new CloudFrontFunction();+ first.setName("routing");+ first.setFunctionCode("first");+ service.createFunction(first);+ CloudFrontFunction second = new CloudFrontFunction();+ second.setName("routing");+ second.setFunctionCode("second");++ AwsException error = assertThrows(AwsException.class, () -> service.createFunction(second));++ assertEquals("FunctionAlreadyExists", error.getErrorCode());+ assertEquals(409, error.getHttpStatus());+ assertEquals("first", service.describeFunction("routing", null).getFunctionCode());+ }++ @Test+ void createFunction_nameOfADeletedFunction_isAccepted() {+ CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");+ CloudFrontFunction function = new CloudFrontFunction();+ function.setName("routing");+ CloudFrontFunction created = service.createFunction(function);+ service.publishFunction("routing", created.getEtag());+ service.deleteFunction("routing", created.getEtag());+ CloudFrontFunction again = new CloudFrontFunction();+ again.setName("routing");++ assertEquals("DEVELOPMENT", service.createFunction(again).getStage());+ }+@Testvoid listFunctionsWithoutStageReturnsDevelopmentAndLive() {CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsvindex 41fd921813..07f0de69b1 100644--- a/src/test/resources/cloudformation/supported-resource-types.tsv+++ b/src/test/resources/cloudformation/supported-resource-types.tsv@@ -37,8 +37,11 @@ AWS::CertificateManager::Certificate AcmCfnProvisionerAWS::CloudFormation::CustomResource CustomResourceCfnProvisionerAWS::CloudFront::CachePolicy CloudFrontCfnProvisionerAWS::CloudFront::Distribution CloudFrontCfnProvisioner+AWS::CloudFront::Function CloudFrontCfnProvisioner+AWS::CloudFront::KeyGroup CloudFrontCfnProvisionerAWS::CloudFront::OriginAccessControl CloudFrontCfnProvisionerAWS::CloudFront::OriginRequestPolicy CloudFrontCfnProvisioner+AWS::CloudFront::PublicKey CloudFrontCfnProvisionerAWS::CloudFront::ResponseHeadersPolicy CloudFrontCfnProvisionerAWS::CloudTrail::Trail CloudTrailCfnProvisionerAWS::CloudWatch::Alarm CloudWatchCfnProvisionerdiff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yamlindex ab936d46fc..e50cf10e8a 100644--- a/tools/docs/cfn_resource_types.yaml+++ b/tools/docs/cfn_resource_types.yaml@@ -183,6 +183,7 @@ notes:Custom::DynamoDBReplica: applied natively against DynamoDB, not via a provider LambdaAWS::Cognito::UserPool: '`ProviderURL` is the local issuer of the tokens Floci mints, `<base-url>/<pool id>`'AWS::Events::Archive: '`KmsKeyIdentifier` is ignored'+ AWS::CloudFront::Function: '`KeyValueStoreAssociations` is ignored'# Trailing prose appended to a row after its type list, for behaviour that belongs to the service# rather than to one type.