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 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 {@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 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