diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudWatchCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudWatchCfnProvisioner.java index cfe9185575..e51499ad11 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudWatchCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudWatchCfnProvisioner.java @@ -32,10 +32,8 @@ public class CloudWatchCfnProvisioner implements CfnResourceProvisioner { @Override public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { - String name = ctx.resolveOptional(props, "AlarmName"); - if (name == null || name.isBlank()) { - name = ctx.generatePhysicalName(r.getLogicalId(), ALARM_NAME_MAX_LENGTH, false); - } + String name = ctx.stablePhysicalName(ctx.resolveOptional(props, "AlarmName"), + r.getLogicalId(), ALARM_NAME_MAX_LENGTH, false); MetricAlarm alarm = new MetricAlarm(); alarm.setAlarmName(name); diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EcrCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EcrCfnProvisioner.java index 79bbfe2e4c..0d29a19674 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EcrCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EcrCfnProvisioner.java @@ -1,7 +1,6 @@ package io.github.hectorvent.floci.services.cloudformation.provisioners; import com.fasterxml.jackson.databind.JsonNode; -import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.services.cloudformation.model.StackResource; import io.github.hectorvent.floci.services.ecr.EcrService; import io.github.hectorvent.floci.services.ecr.model.Repository; @@ -12,11 +11,22 @@ import java.util.List; import java.util.Map; import java.util.Set; -/** Provisions {@code AWS::ECR::Repository}. */ +/** + * Provisions {@code AWS::ECR::Repository}. + * + *

A create whose name already belongs to a repository fails, as it does on CloudFormation: + * {@code RepositoryAlreadyExistsException} propagates and the stack reports the failure instead of + * adopting a repository it does not own (and would later delete). The earlier adopt-on-conflict + * path existed for CDK bootstrap re-runs, but a re-run is an UpdateStack of the existing + * {@code CDKToolkit} stack, where the prior physical id already equals the fixed repository name + * and the update path below reconciles it in place. + */ @ApplicationScoped public class EcrCfnProvisioner implements CfnResourceProvisioner { private static final int REPOSITORY_NAME_MAX_LENGTH = 256; + /** What CreateRepository applies when ImageTagMutability is omitted. */ + private static final String DEFAULT_IMAGE_TAG_MUTABILITY = "MUTABLE"; private final EcrService ecrService; @@ -31,42 +41,40 @@ public class EcrCfnProvisioner implements CfnResourceProvisioner { @Override public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { - String repoName = ctx.resolveOptional(props, "RepositoryName"); - if (repoName == null || repoName.isBlank()) { - repoName = ctx.generatePhysicalName(r.getLogicalId(), REPOSITORY_NAME_MAX_LENGTH, true); - } // CDK bootstrap requires lower-case repository names; CFN-generated suffixes can include // upper-case characters. Normalize to satisfy the AWS ECR repository name pattern. - repoName = repoName.toLowerCase(); + String repoName = ctx.stablePhysicalName(ctx.resolveOptional(props, "RepositoryName"), + r.getLogicalId(), REPOSITORY_NAME_MAX_LENGTH, true).toLowerCase(); String mutability = ctx.resolveOptional(props, "ImageTagMutability"); Map tags = parseCfnTags(props != null ? props.get("Tags") : null, ctx); + String region = ctx.region(); - Repository repo; - try { - repo = ecrService.createRepository(repoName, null, mutability, null, null, null, tags, ctx.region()); - } catch (AwsException e) { - if ("RepositoryAlreadyExistsException".equals(e.getErrorCode())) { - repo = ecrService.describeRepositories(List.of(repoName), null, ctx.region()).get(0); - } else { - throw e; - } - } + // provision is also the update path. Only the repository this resource already owns is + // reconciled in place; a replacing update derives a different name and creates, and a name + // that already belongs to another repository fails the create as on CloudFormation. + boolean reusing = ctx.reusesPriorEntity(repoName); + Repository repo = reusing + ? reconcileExisting(repoName, mutability, tags, region) + : ecrService.createRepository(repoName, null, mutability, null, null, null, tags, region); - // Lifecycle policy can be inlined as `LifecyclePolicy.LifecyclePolicyText` - if (props != null && props.has("LifecyclePolicy")) { - JsonNode lp = ctx.engine().resolveNode(props.get("LifecyclePolicy")); - String policyText = lp.path("LifecyclePolicyText").asText(null); - if (policyText != null && !policyText.isEmpty()) { - ecrService.putLifecyclePolicy(repoName, null, policyText, ctx.region()); - } + // Both policies are updatable: a template that declares one sets it, and on the update + // path a template that no longer declares one deletes it, tolerating "none set". + String lifecyclePolicy = lifecyclePolicyText(props, ctx); + if (lifecyclePolicy != null) { + ecrService.putLifecyclePolicy(repoName, null, lifecyclePolicy, region); + } else if (reusing) { + CfnDeletes.safeDelete("ECR lifecycle policy", repoName, + () -> ecrService.deleteLifecyclePolicy(repoName, null, region), + "LifecyclePolicyNotFoundException"); } - if (props != null && props.has("RepositoryPolicyText")) { - JsonNode pol = ctx.engine().resolveNode(props.get("RepositoryPolicyText")); - String policyText = pol.isTextual() ? pol.asText() : pol.toString(); - if (policyText != null && !policyText.isEmpty()) { - ecrService.setRepositoryPolicy(repoName, null, policyText, ctx.region()); - } + String repositoryPolicy = repositoryPolicyText(props, ctx); + if (repositoryPolicy != null) { + ecrService.setRepositoryPolicy(repoName, null, repositoryPolicy, region); + } else if (reusing) { + CfnDeletes.safeDelete("ECR repository policy", repoName, + () -> ecrService.deleteRepositoryPolicy(repoName, null, region), + "RepositoryPolicyNotFoundException"); } r.setPhysicalId(repoName); @@ -79,6 +87,47 @@ public class EcrCfnProvisioner implements CfnResourceProvisioner { ecrService.deleteRepository(physicalId, null, true, region); } + /** + * The update path for the repository this resource already owns. Tags are driven to the + * template's desired state (TagResource alone leaves unspecified tags in place, so dropped + * keys are untagged first), and so is ImageTagMutability: a template that no longer declares + * it means the MUTABLE default the API applies when the parameter is omitted, not "keep the + * previous value". Both are updatable in the registry schema. + */ + private Repository reconcileExisting(String repoName, String mutability, Map tags, + String region) { + List stale = ProvisionContext.staleTagKeys( + ecrService.listTagsForResource(repoName, null, region), tags); + if (!stale.isEmpty()) { + ecrService.untagResource(repoName, null, stale, region); + } + if (!tags.isEmpty()) { + ecrService.tagResource(repoName, null, tags, region); + } + return ecrService.putImageTagMutability(repoName, null, + mutability != null ? mutability : DEFAULT_IMAGE_TAG_MUTABILITY, region); + } + + /** {@code LifecyclePolicy.LifecyclePolicyText}, or null when the template declares none. */ + private static String lifecyclePolicyText(JsonNode props, ProvisionContext ctx) { + if (props == null || !props.has("LifecyclePolicy")) { + return null; + } + JsonNode lp = ctx.engine().resolveNode(props.get("LifecyclePolicy")); + String policyText = lp.path("LifecyclePolicyText").asText(null); + return policyText == null || policyText.isEmpty() ? null : policyText; + } + + /** {@code RepositoryPolicyText} as a JSON string, or null when the template declares none. */ + private static String repositoryPolicyText(JsonNode props, ProvisionContext ctx) { + if (props == null || !props.has("RepositoryPolicyText")) { + return null; + } + JsonNode pol = ctx.engine().resolveNode(props.get("RepositoryPolicyText")); + String policyText = pol.isTextual() ? pol.asText() : pol.toString(); + return policyText == null || policyText.isEmpty() ? null : policyText; + } + /** See {@code KmsCfnProvisioner#parseCfnTags} for why this is copied rather than shared. */ private Map parseCfnTags(JsonNode tagsNode, ProvisionContext ctx) { Map out = new HashMap<>(); diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/FirehoseCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/FirehoseCfnProvisioner.java index b8ef9dbd52..456afbc93b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/FirehoseCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/FirehoseCfnProvisioner.java @@ -7,7 +7,9 @@ import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescript import jakarta.enterprise.context.ApplicationScoped; import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import java.util.Set; /** Provisions {@code AWS::KinesisFirehose::DeliveryStream}. */ @@ -31,10 +33,8 @@ public class FirehoseCfnProvisioner implements CfnResourceProvisioner { @Override public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { - String name = ctx.resolveOptional(props, "DeliveryStreamName"); - if (name == null || name.isBlank()) { - name = ctx.generatePhysicalName(r.getLogicalId(), DELIVERY_STREAM_NAME_MAX_LENGTH, false); - } + String name = ctx.stablePhysicalName(ctx.resolveOptional(props, "DeliveryStreamName"), + r.getLogicalId(), DELIVERY_STREAM_NAME_MAX_LENGTH, false); DeliveryStreamDescription.S3Destination s3 = null; JsonNode s3Node = props != null && props.has("ExtendedS3DestinationConfiguration") @@ -68,7 +68,27 @@ public class FirehoseCfnProvisioner implements CfnResourceProvisioner { } } - String arn = firehoseService.createDeliveryStream(name, s3, tags); + // provision is also the update path. createDeliveryStream throws ResourceInUseException on + // an existing name, and stablePhysicalName now keeps that name steady across updates, so a + // second UpdateStack must reconcile the stream rather than recreate it. A replacing update + // derives a different name and still creates, hence reusesPriorEntity rather than isUpdate. + String arn; + if (ctx.reusesPriorEntity(name)) { + DeliveryStreamDescription existing = firehoseService.describeDeliveryStream(name); + arn = existing.getDeliveryStreamARN(); + // Only the destination is updatable here; a template that declares none leaves the + // stored one alone rather than clearing it. + if (s3 != null) { + String destinationId = + existing.getDestinations() != null && !existing.getDestinations().isEmpty() + ? existing.getDestinations().get(0).getDestinationId() + : null; + firehoseService.updateDestination(name, existing.getVersionId(), destinationId, s3); + } + reconcileTags(name, existing, tags); + } else { + arn = firehoseService.createDeliveryStream(name, s3, tags); + } // Ref returns the delivery stream name; Fn::GetAtt Arn returns the stream ARN. r.setPhysicalId(name); r.getAttributes().put("Arn", arn); @@ -79,6 +99,31 @@ public class FirehoseCfnProvisioner implements CfnResourceProvisioner { firehoseService.deleteDeliveryStream(physicalId); } + /** + * UpdateDestination carries no tags, so on the update path the template's Tags are driven to + * their desired state through TagDeliveryStream and UntagDeliveryStream, the two calls the + * registry schema's update handler declares. A key the template dropped is untagged rather than + * left over from the previous revision. + */ + private void reconcileTags(String name, DeliveryStreamDescription existing, + List desired) { + Map desiredByKey = new LinkedHashMap<>(); + for (DeliveryStreamDescription.Tag tag : desired) { + desiredByKey.put(tag.getKey(), tag.getValue()); + } + Map current = new LinkedHashMap<>(); + for (DeliveryStreamDescription.Tag tag : existing.getTags()) { + current.put(tag.getKey(), tag.getValue()); + } + List stale = ProvisionContext.staleTagKeys(current, desiredByKey); + if (!stale.isEmpty()) { + firehoseService.untagDeliveryStream(name, stale); + } + if (!desired.isEmpty()) { + firehoseService.tagDeliveryStream(name, desired); + } + } + private static String blankToNull(String value) { return value == null || value.isBlank() ? null : value; } diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/PipesCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/PipesCfnProvisioner.java index 6121b4c195..024b431d69 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/PipesCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/PipesCfnProvisioner.java @@ -1,12 +1,15 @@ package io.github.hectorvent.floci.services.cloudformation.provisioners; import com.fasterxml.jackson.databind.JsonNode; +import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.services.cloudformation.model.StackResource; import io.github.hectorvent.floci.services.pipes.PipesService; +import io.github.hectorvent.floci.services.pipes.model.Pipe; import io.github.hectorvent.floci.services.pipes.model.DesiredState; import jakarta.enterprise.context.ApplicationScoped; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Set; @@ -29,10 +32,8 @@ public class PipesCfnProvisioner implements CfnResourceProvisioner { @Override public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { - String name = ctx.resolveOptional(props, "Name"); - if (name == null || name.isBlank()) { - name = ctx.generatePhysicalName(r.getLogicalId(), PIPE_NAME_MAX_LENGTH, false); - } + String name = ctx.stablePhysicalName(ctx.resolveOptional(props, "Name"), + r.getLogicalId(), PIPE_NAME_MAX_LENGTH, false); String source = ctx.resolveOptional(props, "Source"); String target = ctx.resolveOptional(props, "Target"); @@ -49,8 +50,30 @@ public class PipesCfnProvisioner implements CfnResourceProvisioner { Map tags = parseCfnTags(props != null ? props.get("Tags") : null, ctx); - var pipe = pipesService.createPipe(name, source, target, roleArn, description, desiredState, - enrichment, sourceParameters, targetParameters, enrichmentParameters, tags, ctx.region()); + // provision is also the update path. createPipe throws ConflictException on an existing + // name, and stablePhysicalName now keeps that name steady across updates, so a second + // UpdateStack must reconcile the pipe rather than recreate it. A replacing update derives a + // different name and still creates, which is why this asks reusesPriorEntity rather than + // isUpdate. + Pipe pipe; + if (ctx.reusesPriorEntity(name)) { + Pipe existing = pipesService.describePipe(name, ctx.region()); + // Source is a createOnly property. With the name reused there is no replacement to + // move to, which is the update CloudFormation refuses for a custom-named resource, so + // it is refused here rather than silently kept on the old source. + if (source != null && !source.equals(existing.getSource())) { + throw new AwsException("ValidationError", + "Updating Source requires resource replacement, which is not supported.", 400); + } + pipe = pipesService.updatePipe(name, target, roleArn, description, desiredState, + enrichment, sourceParameters, targetParameters, enrichmentParameters, + ctx.region()); + reconcileTags(pipe, tags, ctx.region()); + } else { + pipe = pipesService.createPipe(name, source, target, roleArn, description, desiredState, + enrichment, sourceParameters, targetParameters, enrichmentParameters, tags, + ctx.region()); + } r.setPhysicalId(name); r.getAttributes().put("Arn", pipe.getArn()); @@ -68,6 +91,22 @@ public class PipesCfnProvisioner implements CfnResourceProvisioner { return ctx.engine().resolveNode(props.get(name)); } + /** + * UpdatePipe carries no Tags (only CreatePipe does), so on the update path the template's tags + * are driven to their desired state through TagResource and UntagResource, keyed by the pipe's + * ARN. A key the template dropped is untagged rather than left over. + */ + private void reconcileTags(Pipe pipe, Map desired, String region) { + List stale = ProvisionContext.staleTagKeys( + pipesService.listTags(region, pipe.getArn()), desired); + if (!stale.isEmpty()) { + pipesService.untagResource(region, pipe.getArn(), stale); + } + if (!desired.isEmpty()) { + pipesService.tagResource(region, pipe.getArn(), desired); + } + } + /** See {@code KmsCfnProvisioner#parseCfnTags} for why this is copied rather than shared. */ private Map parseCfnTags(JsonNode tagsNode, ProvisionContext ctx) { Map out = new HashMap<>(); diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContext.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContext.java index a85e520e9e..dd33a20961 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContext.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContext.java @@ -94,6 +94,73 @@ public record ProvisionContext(CloudFormationTemplateEngine engine, String regio return values; } + /** + * The physical name for a resource whose name is create-only: the template's name when it gives + * one, otherwise the name this resource already had, and only failing both a freshly generated + * one. + * + *

Keeping the prior name is the part that matters. {@code provision} runs again on every + * {@code UpdateStack}, so generating unconditionally gives an unnamed resource a new random name + * each time, creating a second resource and orphaning the first with its data. The schemas make + * this explicit: for these types the name is a {@code createOnlyProperty}, so an unchanged + * template must keep the same physical id. + * + *

Only for types whose physical id is the name. Where it is something derived, such + * as an SNS topic's ARN, the prior name has to come from the stored attribute instead. + */ + public String stablePhysicalName(String explicitName, String logicalId, int maxLength, + boolean lowercase) { + if (explicitName != null && !explicitName.isBlank()) { + return explicitName; + } + if (priorPhysicalId != null && !priorPhysicalId.isBlank()) { + return priorPhysicalId; + } + return generatePhysicalName(logicalId, maxLength, lowercase); + } + + /** + * Whether {@code name} identifies the entity this resource already had, so the provisioner must + * update it rather than create it. + * + *

Deliberately not the same question as {@link #isUpdate()}. A replacing update also + * arrives with a prior physical id, but the provisioner has derived a different name for it and + * must create; treating that as an update would try to mutate a resource that does not exist. + * Comparing the derived name against the prior id is what separates the two, and it is the + * check a provisioner needs whenever its service rejects a duplicate name. + * + *

Pairs with {@link #stablePhysicalName}: that keeps the name steady across an update, and + * this tells the caller what the steady name now implies. Without it, a stable name turns the + * second UpdateStack into a duplicate-create against services that reject one. + */ + public boolean reusesPriorEntity(String name) { + return isUpdate() && priorPhysicalId.equals(name); + } + + /** + * Tag keys the stored resource carries that the template no longer declares, for the caller to + * untag before applying the desired set. CloudFormation drives a resource's tags to the + * template's desired state on update: a dropped key is untagged, and a template with no + * {@code Tags} at all leaves the resource untagged. A service's tag call alone never removes + * anything (ECR's TagResource, for one, documents that unspecified tags are left unchanged), so + * the removal has to be computed here. + * + *

Iterates a copy, because some services hand back their live tag map and untagging while + * walking it would modify the collection under iteration. + */ + public static List staleTagKeys(Map current, Map desired) { + List stale = new ArrayList<>(); + if (current == null) { + return stale; + } + for (String key : List.copyOf(current.keySet())) { + if (!desired.containsKey(key)) { + stale.add(key); + } + } + return stale; + } + /** Generates a CloudFormation-style physical name: {@code --}. */ public String generatePhysicalName(String logicalId, int maxLength, boolean lowercase) { String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 12); diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/S3CfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/S3CfnProvisioner.java index e18ec235af..90d01327db 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/S3CfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/S3CfnProvisioner.java @@ -39,19 +39,41 @@ public class S3CfnProvisioner implements CfnResourceProvisioner { public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { switch (r.getResourceType()) { case BUCKET -> provisionBucket(r, props, ctx); - case BUCKET_POLICY -> - r.setPhysicalId("bucket-policy-" + UUID.randomUUID().toString().substring(0, 8)); + case BUCKET_POLICY -> r.setPhysicalId(bucketPolicyId(ctx)); default -> throw new IllegalStateException( "S3CfnProvisioner cannot provision " + r.getResourceType()); } } + /** + * The policy's physical id, kept across updates rather than regenerated. + * + *

{@code provision} runs again on every UpdateStack, so minting a fresh id each time made an + * unchanged policy look like a replaced resource and changed what {@code Ref} returned. + * + *

The generated value itself is left alone deliberately. The sources disagree on what it + * should be: the current registry schema gives {@code primaryIdentifier} as + * {@code /properties/Bucket}, while the older schema localstack embeds gives + * {@code /properties/Id} as an md5 of the policy document. Changing what Ref resolves to on that + * evidence would be guessing; keeping the id stable fixes the defect either way. + */ + private String bucketPolicyId(ProvisionContext ctx) { + return ctx.isUpdate() + ? ctx.priorPhysicalId() + : "bucket-policy-" + UUID.randomUUID().toString().substring(0, 8); + } + private void provisionBucket(StackResource r, JsonNode props, ProvisionContext ctx) { - String bucketName = ctx.resolveOptional(props, "BucketName"); - if (bucketName == null || bucketName.isBlank()) { - bucketName = ctx.generatePhysicalName(r.getLogicalId(), BUCKET_NAME_MAX_LENGTH, true); + String bucketName = ctx.stablePhysicalName(ctx.resolveOptional(props, "BucketName"), + r.getLogicalId(), BUCKET_NAME_MAX_LENGTH, true); + // provision is also the update path. CreateBucket on a bucket this account already owns is + // idempotent only in us-east-1; every other region answers BucketAlreadyOwnedByYou, as on + // AWS. With the name now stable across updates, the second UpdateStack must skip the create + // and only reconcile the bucket's configuration. A replacing update derives a different + // name and still creates, hence reusesPriorEntity rather than isUpdate. + if (!ctx.reusesPriorEntity(bucketName)) { + s3Service.createBucket(bucketName, ctx.region()); } - s3Service.createBucket(bucketName, ctx.region()); applyBucketCorsConfiguration(bucketName, props, ctx); applyBucketVersioningConfiguration(bucketName, props, ctx); r.setPhysicalId(bucketName); diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SnsCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SnsCfnProvisioner.java index 1f602b1574..a4f3751963 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SnsCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SnsCfnProvisioner.java @@ -42,7 +42,13 @@ public class SnsCfnProvisioner implements CfnResourceProvisioner { String topicName = ctx.resolveOptional(props, "TopicName"); String contentBasedDedupFlag = ctx.resolveOptional(props, "ContentBasedDeduplication"); if (topicName == null || topicName.isBlank()) { - topicName = ctx.generatePhysicalName(r.getLogicalId(), TOPIC_NAME_MAX_LENGTH, false); + // ctx.stablePhysicalName does not fit here: the physical id is the topic ARN, so the + // prior name comes from the attribute recorded at create time. Reusing it keeps an + // unnamed topic (and its subscriptions) across updates instead of orphaning it. + String priorName = r.getAttributes().get("TopicName"); + topicName = priorName != null && !priorName.isBlank() + ? priorName + : ctx.generatePhysicalName(r.getLogicalId(), TOPIC_NAME_MAX_LENGTH, false); } Map attributes = new HashMap<>(); diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SsmCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SsmCfnProvisioner.java index b94779274e..0105371259 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SsmCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SsmCfnProvisioner.java @@ -26,10 +26,8 @@ public class SsmCfnProvisioner implements CfnResourceProvisioner { @Override public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { - String name = ctx.resolveOptional(props, "Name"); - if (name == null || name.isBlank()) { - name = ctx.generatePhysicalName(r.getLogicalId(), PARAMETER_NAME_MAX_LENGTH, false); - } + String name = ctx.stablePhysicalName(ctx.resolveOptional(props, "Name"), + r.getLogicalId(), PARAMETER_NAME_MAX_LENGTH, false); String value = ctx.resolveOptional(props, "Value"); if (value == null) { value = ""; diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnStableNameUpdatePathTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnStableNameUpdatePathTest.java new file mode 100644 index 0000000000..da7e9d7c9d --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnStableNameUpdatePathTest.java @@ -0,0 +1,367 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine; +import io.github.hectorvent.floci.services.ecr.EcrService; +import io.github.hectorvent.floci.services.ecr.model.Repository; +import io.github.hectorvent.floci.services.s3.S3Service; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.firehose.FirehoseService; +import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription; +import io.github.hectorvent.floci.services.pipes.PipesService; +import io.github.hectorvent.floci.services.pipes.model.Pipe; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * The second UpdateStack on a resource whose name floci generated. + * + *

This is the coverage whose absence let a regression through. {@code stablePhysicalName} keeps a + * generated name steady across updates, which is the fix it exists for, but {@code provision} is + * also the update path: with a steady name, a provisioner that creates unconditionally now calls a + * create API with a name that already exists. Firehose answers that with + * {@code ResourceInUseException} and Pipes with {@code ConflictException}, so the second update + * fails where it previously (wrongly) created a duplicate under a fresh random name. + * + *

Every test here provisions twice: once with no prior physical id (create), then again with the + * id the first pass assigned (update). Asserting on the create call is what makes the defect + * visible, because asserting only that no exception is thrown would pass against a mock that never + * rejects duplicates the way the real services do. + */ +class CfnStableNameUpdatePathTest { + + private final ObjectMapper mapper = new ObjectMapper(); + + private ProvisionContext ctx(String priorPhysicalId) { + CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class); + when(engine.resolve(any())).thenAnswer(inv -> { + JsonNode node = inv.getArgument(0); + return node == null ? null : node.asText(); + }); + when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0)); + return priorPhysicalId == null + ? new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack") + : new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack", priorPhysicalId); + } + + private StackResource resource(String type, String logicalId) { + StackResource r = new StackResource(); + r.setResourceType(type); + r.setLogicalId(logicalId); + return r; + } + + @Test + void firehoseUpdateReconcilesTheExistingStreamInsteadOfRecreatingIt() { + FirehoseService firehose = mock(FirehoseService.class); + when(firehose.createDeliveryStream(anyString(), any(), any())) + .thenReturn("arn:aws:firehose:us-east-1:000000000000:deliverystream/created"); + FirehoseCfnProvisioner provisioner = new FirehoseCfnProvisioner(firehose); + + var props = mapper.createObjectNode(); + props.set("S3DestinationConfiguration", + mapper.createObjectNode().put("BucketARN", "arn:aws:s3:::bucket")); + var createTags = props.putArray("Tags"); + createTags.addObject().put("Key", "env").put("Value", "dev"); + createTags.addObject().put("Key", "team").put("Value", "a"); + + StackResource created = resource("AWS::KinesisFirehose::DeliveryStream", "Stream"); + provisioner.provision(created, props, ctx(null)); + String generatedName = created.getPhysicalId(); + + DeliveryStreamDescription existing = new DeliveryStreamDescription(); + existing.setDeliveryStreamARN("arn:aws:firehose:us-east-1:000000000000:deliverystream/existing"); + existing.setVersionId("1"); + existing.getTags().add(new DeliveryStreamDescription.Tag("env", "dev")); + existing.getTags().add(new DeliveryStreamDescription.Tag("team", "a")); + when(firehose.describeDeliveryStream(generatedName)).thenReturn(existing); + + var updateProps = mapper.createObjectNode(); + updateProps.set("S3DestinationConfiguration", + mapper.createObjectNode().put("BucketARN", "arn:aws:s3:::bucket")); + updateProps.putArray("Tags").addObject().put("Key", "env").put("Value", "prod"); + + StackResource updated = resource("AWS::KinesisFirehose::DeliveryStream", "Stream"); + provisioner.provision(updated, updateProps, ctx(generatedName)); + + assertEquals(generatedName, updated.getPhysicalId(), "the generated name must stay stable"); + assertEquals("arn:aws:firehose:us-east-1:000000000000:deliverystream/existing", + updated.getAttributes().get("Arn"), "Arn must come from the existing stream"); + verify(firehose).updateDestination(eq(generatedName), eq("1"), any(), any()); + // UpdateDestination carries no tags: the dropped key is untagged and the changed one + // re-tagged, since a tag call alone never removes anything. + verify(firehose).untagDeliveryStream(generatedName, List.of("team")); + verify(firehose).tagDeliveryStream(eq(generatedName), argThat(tags -> + tags.size() == 1 && "env".equals(tags.get(0).getKey()) + && "prod".equals(tags.get(0).getValue()))); + // The regression: exactly one create, from the first pass. A second one with the + // now-stable name is what raises ResourceInUseException. + verify(firehose, times(1)).createDeliveryStream(eq(generatedName), any(), any()); + } + + @Test + void pipesUpdateReconcilesTheExistingPipeInsteadOfRecreatingIt() { + PipesService pipes = mock(PipesService.class); + Pipe createdPipe = new Pipe(); + createdPipe.setArn("arn:aws:pipes:us-east-1:000000000000:pipe/created"); + Pipe updatedPipe = new Pipe(); + updatedPipe.setArn("arn:aws:pipes:us-east-1:000000000000:pipe/existing"); + when(pipes.createPipe(anyString(), any(), any(), any(), any(), any(), any(), any(), any(), + any(), any(), anyString())).thenReturn(createdPipe); + when(pipes.updatePipe(anyString(), any(), any(), any(), any(), any(), any(), any(), any(), + anyString())).thenReturn(updatedPipe); + PipesCfnProvisioner provisioner = new PipesCfnProvisioner(pipes); + + var props = mapper.createObjectNode() + .put("Source", "arn:aws:sqs:us-east-1:000000000000:src") + .put("Target", "arn:aws:sqs:us-east-1:000000000000:dst") + .put("RoleArn", "arn:aws:iam::000000000000:role/r"); + props.putArray("Tags").addObject().put("Key", "env").put("Value", "prod"); + + StackResource created = resource("AWS::Pipes::Pipe", "Pipe"); + provisioner.provision(created, props, ctx(null)); + String generatedName = created.getPhysicalId(); + + Pipe existing = new Pipe(); + existing.setSource("arn:aws:sqs:us-east-1:000000000000:src"); + when(pipes.describePipe(generatedName, "us-east-1")).thenReturn(existing); + when(pipes.listTags("us-east-1", "arn:aws:pipes:us-east-1:000000000000:pipe/existing")) + .thenReturn(Map.of("env", "dev", "team", "a")); + + StackResource updated = resource("AWS::Pipes::Pipe", "Pipe"); + provisioner.provision(updated, props, ctx(generatedName)); + + assertEquals(generatedName, updated.getPhysicalId(), "the generated name must stay stable"); + assertEquals("arn:aws:pipes:us-east-1:000000000000:pipe/existing", + updated.getAttributes().get("Arn"), "Arn must come from the existing pipe"); + verify(pipes).updatePipe(eq(generatedName), any(), any(), any(), any(), any(), any(), any(), + any(), anyString()); + // UpdatePipe carries no Tags: the dropped key is untagged and the changed one re-tagged + // by ARN. + verify(pipes).untagResource("us-east-1", + "arn:aws:pipes:us-east-1:000000000000:pipe/existing", List.of("team")); + verify(pipes).tagResource("us-east-1", + "arn:aws:pipes:us-east-1:000000000000:pipe/existing", Map.of("env", "prod")); + // The regression: exactly one create, from the first pass. A second one with the + // now-stable name is what raises ConflictException. + verify(pipes, times(1)).createPipe(eq(generatedName), any(), any(), any(), any(), any(), + any(), any(), any(), any(), any(), anyString()); + } + + @Test + void pipesUpdateRefusesAChangedSourceInsteadOfSilentlyKeepingTheOldOne() { + PipesService pipes = mock(PipesService.class); + Pipe existing = new Pipe(); + existing.setSource("arn:aws:sqs:us-east-1:000000000000:old"); + existing.setArn("arn:aws:pipes:us-east-1:000000000000:pipe/existing"); + when(pipes.describePipe("my-stack-Pipe-0123456789ab", "us-east-1")).thenReturn(existing); + when(pipes.updatePipe(anyString(), any(), any(), any(), any(), any(), any(), any(), any(), + anyString())).thenReturn(existing); + PipesCfnProvisioner provisioner = new PipesCfnProvisioner(pipes); + + // Source is createOnly. With the name reused there is no replacement to move to, which is + // the update CloudFormation refuses for a custom-named resource. + JsonNode props = mapper.createObjectNode() + .put("Source", "arn:aws:sqs:us-east-1:000000000000:new") + .put("Target", "arn:aws:sqs:us-east-1:000000000000:dst") + .put("RoleArn", "arn:aws:iam::000000000000:role/r"); + + StackResource r = resource("AWS::Pipes::Pipe", "Pipe"); + AwsException failure = assertThrows(AwsException.class, + () -> provisioner.provision(r, props, ctx("my-stack-Pipe-0123456789ab"))); + + assertEquals("ValidationError", failure.getErrorCode()); + verify(pipes, never()).updatePipe(anyString(), any(), any(), any(), any(), any(), any(), + any(), any(), anyString()); + verify(pipes, never()).createPipe(anyString(), any(), any(), any(), any(), any(), any(), + any(), any(), any(), any(), anyString()); + } + + @Test + void s3UpdateDoesNotRecreateTheBucketItAlreadyOwns() { + S3Service s3 = mock(S3Service.class); + S3CfnProvisioner provisioner = new S3CfnProvisioner(s3); + JsonNode props = mapper.createObjectNode(); + + StackResource created = resource("AWS::S3::Bucket", "Bucket"); + provisioner.provision(created, props, ctx(null)); + String generatedName = created.getPhysicalId(); + + StackResource updated = resource("AWS::S3::Bucket", "Bucket"); + provisioner.provision(updated, props, ctx(generatedName)); + + assertEquals(generatedName, updated.getPhysicalId(), "the generated name must stay stable"); + // The regression: outside us-east-1, a second CreateBucket on a bucket this account owns + // answers BucketAlreadyOwnedByYou. Exactly one create, from the first pass. + verify(s3, times(1)).createBucket(eq(generatedName), anyString()); + } + + @Test + void ecrUpdateReconcilesTheRepositoryItAlreadyOwnsInsteadOfRecreatingIt() { + EcrService ecr = mock(EcrService.class); + Repository createdRepo = new Repository(); + createdRepo.setRepositoryArn("arn:aws:ecr:us-east-1:000000000000:repository/created"); + createdRepo.setRepositoryUri("000000000000.dkr.ecr.us-east-1.amazonaws.com/created"); + Repository existingRepo = new Repository(); + existingRepo.setRepositoryArn("arn:aws:ecr:us-east-1:000000000000:repository/existing"); + existingRepo.setRepositoryUri("000000000000.dkr.ecr.us-east-1.amazonaws.com/existing"); + when(ecr.createRepository(anyString(), isNull(), any(), isNull(), isNull(), isNull(), any(), + anyString())).thenReturn(createdRepo); + when(ecr.putImageTagMutability(anyString(), isNull(), eq("IMMUTABLE"), anyString())) + .thenReturn(existingRepo); + EcrCfnProvisioner provisioner = new EcrCfnProvisioner(ecr); + + var createProps = mapper.createObjectNode().put("ImageTagMutability", "MUTABLE"); + createProps.set("LifecyclePolicy", mapper.createObjectNode().put("LifecyclePolicyText", "{}")); + createProps.put("RepositoryPolicyText", "{}"); + StackResource created = resource("AWS::ECR::Repository", "Repo"); + provisioner.provision(created, createProps, ctx(null)); + String generatedName = created.getPhysicalId(); + when(ecr.listTagsForResource(generatedName, null, "us-east-1")) + .thenReturn(Map.of("env", "dev", "team", "a")); + + // The update changes mutability and one tag, drops the other tag and both policies. + var updateProps = mapper.createObjectNode().put("ImageTagMutability", "IMMUTABLE"); + updateProps.putArray("Tags").addObject().put("Key", "env").put("Value", "prod"); + StackResource updated = resource("AWS::ECR::Repository", "Repo"); + provisioner.provision(updated, updateProps, ctx(generatedName)); + + assertEquals(generatedName, updated.getPhysicalId(), "the generated name must stay stable"); + assertEquals("arn:aws:ecr:us-east-1:000000000000:repository/existing", + updated.getAttributes().get("Arn"), "Arn must come from the existing repository"); + // Exactly one create, from the first pass: the update reconciles rather than colliding. + verify(ecr, times(1)).createRepository(anyString(), isNull(), any(), isNull(), isNull(), + isNull(), any(), anyString()); + verify(ecr).putImageTagMutability(generatedName, null, "IMMUTABLE", "us-east-1"); + // TagResource alone leaves unspecified tags in place, so the dropped key is untagged. + verify(ecr).untagResource(generatedName, null, List.of("team"), "us-east-1"); + verify(ecr).tagResource(generatedName, null, Map.of("env", "prod"), "us-east-1"); + verify(ecr).deleteLifecyclePolicy(generatedName, null, "us-east-1"); + verify(ecr).deleteRepositoryPolicy(generatedName, null, "us-east-1"); + verify(ecr, never()).describeRepositories(anyList(), isNull(), anyString()); + } + + @Test + void ecrUpdateThatDropsImageTagMutabilityRestoresTheMutableDefault() { + EcrService ecr = mock(EcrService.class); + Repository createdRepo = new Repository(); + createdRepo.setRepositoryArn("arn:aws:ecr:us-east-1:000000000000:repository/created"); + createdRepo.setRepositoryUri("000000000000.dkr.ecr.us-east-1.amazonaws.com/created"); + Repository existingRepo = new Repository(); + existingRepo.setRepositoryArn("arn:aws:ecr:us-east-1:000000000000:repository/existing"); + existingRepo.setRepositoryUri("000000000000.dkr.ecr.us-east-1.amazonaws.com/existing"); + when(ecr.createRepository(anyString(), isNull(), any(), isNull(), isNull(), isNull(), any(), + anyString())).thenReturn(createdRepo); + when(ecr.putImageTagMutability(anyString(), isNull(), anyString(), anyString())) + .thenReturn(existingRepo); + EcrCfnProvisioner provisioner = new EcrCfnProvisioner(ecr); + + StackResource created = resource("AWS::ECR::Repository", "Repo"); + provisioner.provision(created, mapper.createObjectNode().put("ImageTagMutability", "IMMUTABLE"), + ctx(null)); + String generatedName = created.getPhysicalId(); + + // The property is gone from the template. Omitting it means the API default, MUTABLE, + // not the IMMUTABLE the repository was created with. + StackResource updated = resource("AWS::ECR::Repository", "Repo"); + provisioner.provision(updated, mapper.createObjectNode(), ctx(generatedName)); + + assertEquals("arn:aws:ecr:us-east-1:000000000000:repository/existing", + updated.getAttributes().get("Arn")); + verify(ecr).putImageTagMutability(generatedName, null, "MUTABLE", "us-east-1"); + verify(ecr, never()).describeRepositories(anyList(), isNull(), anyString()); + } + + @Test + void ecrReplacingUpdateCreatesTheNewlyNamedRepository() { + EcrService ecr = mock(EcrService.class); + Repository createdRepo = new Repository(); + createdRepo.setRepositoryArn("arn:aws:ecr:us-east-1:000000000000:repository/renamed"); + createdRepo.setRepositoryUri("000000000000.dkr.ecr.us-east-1.amazonaws.com/renamed"); + when(ecr.createRepository(eq("renamed"), isNull(), any(), isNull(), isNull(), isNull(), any(), + anyString())).thenReturn(createdRepo); + EcrCfnProvisioner provisioner = new EcrCfnProvisioner(ecr); + + // The template now names the repository, so this update derives a different name from + // the prior physical id. That is a replacement and must create; reconciling the prior + // repository under the new name would mutate something that does not exist under it. + // This is why the guard asks reusesPriorEntity and not isUpdate. + StackResource r = resource("AWS::ECR::Repository", "Repo"); + provisioner.provision(r, mapper.createObjectNode().put("RepositoryName", "renamed"), + ctx("my-stack-repo-0123456789ab")); + + assertEquals("renamed", r.getPhysicalId()); + verify(ecr).createRepository(eq("renamed"), isNull(), any(), isNull(), isNull(), isNull(), + any(), anyString()); + verify(ecr, never()).listTagsForResource(anyString(), isNull(), anyString()); + verify(ecr, never()).describeRepositories(anyList(), isNull(), anyString()); + } + + @Test + void ecrCreateFailsOnANameAnotherRepositoryAlreadyHas() { + EcrService ecr = mock(EcrService.class); + when(ecr.createRepository(anyString(), isNull(), any(), isNull(), isNull(), isNull(), any(), + anyString())) + .thenThrow(new AwsException("RepositoryAlreadyExistsException", + "The repository already exists", 400)); + EcrCfnProvisioner provisioner = new EcrCfnProvisioner(ecr); + + // No prior physical id: this stack does not own the colliding repository. Adopting it + // would put someone else's repository under this stack's delete; CloudFormation fails. + StackResource r = resource("AWS::ECR::Repository", "Repo"); + AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(r, + mapper.createObjectNode().put("RepositoryName", "taken"), ctx(null))); + + assertEquals("RepositoryAlreadyExistsException", failure.getErrorCode()); + verify(ecr, never()).describeRepositories(anyList(), isNull(), anyString()); + verify(ecr, never()).tagResource(anyString(), isNull(), any(), anyString()); + verify(ecr, never()).putImageTagMutability(anyString(), isNull(), any(), anyString()); + } + + @Test + void aReplacingUpdateStillCreates() { + PipesService pipes = mock(PipesService.class); + Pipe pipe = new Pipe(); + pipe.setArn("arn:aws:pipes:us-east-1:000000000000:pipe/new"); + when(pipes.createPipe(anyString(), any(), any(), any(), any(), any(), any(), any(), any(), + any(), any(), anyString())).thenReturn(pipe); + PipesCfnProvisioner provisioner = new PipesCfnProvisioner(pipes); + + // The template now names the pipe, so this update derives a different name from the prior + // physical id. That is a replacement, and it must create rather than update a pipe that + // does not exist under the new name. This is why the guard asks reusesPriorEntity and not + // isUpdate. + JsonNode props = mapper.createObjectNode() + .put("Name", "explicitly-named") + .put("Source", "arn:aws:sqs:us-east-1:000000000000:src") + .put("Target", "arn:aws:sqs:us-east-1:000000000000:dst") + .put("RoleArn", "arn:aws:iam::000000000000:role/r"); + + StackResource r = resource("AWS::Pipes::Pipe", "Pipe"); + provisioner.provision(r, props, ctx("my-stack-Pipe-0123456789ab")); + + assertEquals("explicitly-named", r.getPhysicalId()); + verify(pipes).createPipe(eq("explicitly-named"), any(), any(), any(), any(), any(), any(), + any(), any(), any(), any(), anyString()); + verify(pipes, never()).updatePipe(anyString(), any(), any(), any(), any(), any(), any(), + any(), any(), anyString()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LeafCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LeafCfnProvisionerTest.java index e265edf2d4..3d554cbff2 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LeafCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LeafCfnProvisionerTest.java @@ -25,6 +25,7 @@ import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; +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.anyString; @@ -229,18 +230,35 @@ class LeafCfnProvisionerTest { } @Test - void anExistingRepositoryIsAdoptedRatherThanFailing() { + void aCollidingRepositoryNameFailsTheCreate() { when(ecr.createRepository(anyString(), any(), any(), any(), any(), any(), any(), anyString())) .thenThrow(new AwsException("RepositoryAlreadyExistsException", "exists", 400)); - when(ecr.describeRepositories(List.of("app"), null, REGION)) - .thenReturn(List.of(repo("arn:existing", "uri:existing"))); + // A first create has no prior physical id, so the existing repository is not this + // stack's: CloudFormation fails the create rather than adopting it. + StackResource r = resource("Repo", "AWS::ECR::Repository"); + AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(r, props(""" + {"RepositoryName": "app"} + """), ctx)); + + assertEquals("RepositoryAlreadyExistsException", failure.getErrorCode()); + verify(ecr, never()).describeRepositories(any(), any(), anyString()); + } + + @Test + void theStacksOwnRepositoryIsReconciledOnUpdateRatherThanRecreated() { + when(ecr.putImageTagMutability("app", null, "MUTABLE", REGION)) + .thenReturn(repo("arn:existing", "uri:existing")); + + // The prior physical id is the same name, which is what a CDK bootstrap re-run of the + // CDKToolkit stack looks like: reconcile in place, no create. StackResource r = resource("Repo", "AWS::ECR::Repository"); provisioner.provision(r, props(""" {"RepositoryName": "app"} - """), ctx); + """), new ProvisionContext(engine, REGION, "000000000000", "my-stack", "app")); assertEquals("arn:existing", r.getAttributes().get("Arn")); + verify(ecr, never()).createRepository(anyString(), any(), any(), any(), any(), any(), any(), anyString()); } @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContextTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContextTest.java index 9fa282ea8a..f3d0aa306b 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContextTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContextTest.java @@ -67,6 +67,34 @@ class ProvisionContextTest { assertNull(ctx.priorPhysicalId()); } + @Test + void stablePhysicalNamePrefersTheTemplatesName() { + assertEquals("chosen", + context("prior").stablePhysicalName("chosen", "Bucket", 63, true)); + } + + /** + * The reason this helper exists: provision runs again on every UpdateStack, so generating + * unconditionally would give an unnamed resource a new name each time, creating a second + * resource and orphaning the first. These names are createOnly in the schemas, so an unchanged + * template must keep its physical id. + */ + @Test + void stablePhysicalNameKeepsThePriorNameWhenTheTemplateGivesNone() { + assertEquals("my-stack-Bucket-abc123def456", + context("my-stack-Bucket-abc123def456").stablePhysicalName(null, "Bucket", 63, true)); + assertEquals("my-stack-Bucket-abc123def456", + context("my-stack-Bucket-abc123def456").stablePhysicalName(" ", "Bucket", 63, true)); + } + + @Test + void stablePhysicalNameGeneratesOnlyForAFirstCreate() { + String generated = context(null).stablePhysicalName(null, "Bucket", 63, true); + + assertTrue(generated.startsWith("my-stack-bucket-"), generated); + assertEquals(generated.toLowerCase(), generated, "lowercase was requested"); + } + @Test void resolveTagsKeepsTemplateOrderAndDefaultsAMissingValue() { Map tags = context(null).resolveTags( @@ -136,4 +164,17 @@ class ProvisionContextTest { assertEquals(Map.of("env", "prod"), context(null).resolveTags(wrapped, "Tags")); } + @Test + void reusesPriorEntityIsTrueOnlyWhenTheDerivedNameMatchesThePriorId() { + ProvisionContext create = new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack"); + assertFalse(create.reusesPriorEntity("anything"), + "a create has no prior entity to reuse"); + + ProvisionContext update = context("my-stack-Pipe-0123456789ab"); + assertTrue(update.reusesPriorEntity("my-stack-Pipe-0123456789ab"), + "the same name means the same entity, so the provisioner must update it"); + assertFalse(update.reusesPriorEntity("explicitly-named"), + "a replacing update derives a different name and must still create"); + } + } diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/S3CfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/S3CfnProvisionerTest.java index fe15bbdf44..79ce0881f5 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/S3CfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/S3CfnProvisionerTest.java @@ -83,6 +83,41 @@ class S3CfnProvisionerTest { "BucketName", "my-bucket"), r.getAttributes()); } + /** + * The defect Greptile flagged on the migration PR, pre-existing rather than introduced there: + * an unnamed bucket was renamed on every update, creating a second bucket and orphaning the + * first with its objects. BucketName is createOnly in aws-s3-bucket.json, so an unchanged + * template must keep its physical id. + */ + @Test + void anUnnamedBucketKeepsItsNameAcrossUpdates() { + StackResource r = resource("Bucket", "AWS::S3::Bucket"); + r.setPhysicalId("my-stack-bucket-abc123def456"); + provisioner.provision(r, props("{}"), + new ProvisionContext(ctx.engine(), REGION, "000000000000", "my-stack", + "my-stack-bucket-abc123def456")); + + assertEquals("my-stack-bucket-abc123def456", r.getPhysicalId()); + // The bucket already exists under this name. Outside us-east-1 CreateBucket would answer + // BucketAlreadyOwnedByYou, so the update must not create; it still reconciles configuration. + verify(s3, never()).createBucket(anyString(), anyString()); + verify(s3).deleteBucketCors("my-stack-bucket-abc123def456"); + } + + @Test + void anUpdateThatRenamesTheBucketStillCreatesIt() { + StackResource r = resource("Bucket", "AWS::S3::Bucket"); + r.setPhysicalId("my-stack-bucket-abc123def456"); + provisioner.provision(r, props("{\"BucketName\": \"renamed\"}"), + new ProvisionContext(ctx.engine(), REGION, "000000000000", "my-stack", + "my-stack-bucket-abc123def456")); + + // A replacing update: the derived name differs from the prior id, so the new bucket must + // be created. This is why the guard asks reusesPriorEntity and not isUpdate. + assertEquals("renamed", r.getPhysicalId()); + verify(s3).createBucket("renamed", REGION); + } + @Test void anUnnamedBucketGetsALowerCasedStackScopedName() { StackResource r = provisionBucket("{}"); @@ -174,6 +209,23 @@ class S3CfnProvisionerTest { assertTrue(r.getAttributes().isEmpty()); } + /** + * provision runs again on every UpdateStack, so minting a fresh id each time made an unchanged + * policy look like a replaced resource and changed what Ref returned. + */ + @Test + void aBucketPolicyKeepsItsIdAcrossUpdates() { + StackResource r = resource("Policy", "AWS::S3::BucketPolicy"); + r.setPhysicalId("bucket-policy-abc12345"); + provisioner.provision(r, props(""" + {"Bucket": "b", "PolicyDocument": {"Version": "2012-10-17"}} + """), + new ProvisionContext(ctx.engine(), REGION, "000000000000", "my-stack", + "bucket-policy-abc12345")); + + assertEquals("bucket-policy-abc12345", r.getPhysicalId()); + } + @Test void deletingABucketReachesTheServiceButAPolicyHasNothingToDelete() { provisioner.delete("AWS::S3::Bucket", "b", REGION); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SnsCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SnsCfnProvisionerTest.java index 53989e3461..cc5fdeefb4 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SnsCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SnsCfnProvisionerTest.java @@ -110,6 +110,28 @@ class SnsCfnProvisionerTest { assertTrue(name.getValue().startsWith("my-stack-Topic-"), name.getValue()); } + /** + * The topic's physical id is its ARN, so the prior name is read back from the TopicName + * attribute. Without that an unnamed topic would be recreated under a new name on every update, + * orphaning the old topic and every subscription attached to it. + */ + @Test + void anUnnamedTopicKeepsItsNameAcrossUpdates() { + ArgumentCaptor name = ArgumentCaptor.forClass(String.class); + when(sns.createTopic(name.capture(), anyMap(), anyMap(), anyString())).thenReturn(topic(TOPIC_ARN)); + + StackResource r = new StackResource(); + r.setLogicalId("Topic"); + r.setResourceType("AWS::SNS::Topic"); + r.setAttributes(new HashMap<>(Map.of("TopicName", "my-stack-Topic-abc123def456"))); + r.setPhysicalId(TOPIC_ARN); + provisioner.provision(r, props("{}"), + new ProvisionContext(ctx.engine(), REGION, "000000000000", "my-stack", TOPIC_ARN)); + + assertEquals("my-stack-Topic-abc123def456", name.getValue(), + "the prior name must come from the attribute, not from the ARN physical id"); + } + @Test void contentBasedDeduplicationIsForwardedOnlyWhenSet() { ArgumentCaptor> attrs = ArgumentCaptor.forClass(Map.class);