mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(cloudformation): keep a generated physical name across stack updates (#2788)
provision runs again on every UpdateStack. Seven provisioners generated a fresh random name unconditionally, so an update created a second resource and left the first behind with its data while the stack's physical id moved to the new, empty one. For these types the name is a createOnlyProperty, so an unchanged template must keep its physical id. ProvisionContext.stablePhysicalName encapsulates the rule: the template's name, else the name the resource already had, else a generated one. S3::Bucket, SSM::Parameter, ECR::Repository, Pipes::Pipe, KinesisFirehose::DeliveryStream and CloudWatch::Alarm use it. SNS cannot: a topic's physical id is its ARN, so the prior name is read back from the TopicName attribute instead. A stable name means the second UpdateStack reaches the create API with a name that already exists, so the provisioners whose service rejects a duplicate now reconcile instead of creating. ProvisionContext.reusesPriorEntity answers whether the derived name is the entity the resource already had; it is deliberately not isUpdate, because a replacing update also carries a prior id but under a new name and must still create. Firehose goes to UpdateDestination, Pipes to UpdatePipe, S3 skips CreateBucket (idempotent only in us-east-1, BucketAlreadyOwnedByYou elsewhere), and ECR reconciles the repository it owns. The reconcile paths drive tags to the template's desired state: neither UpdateDestination nor UpdatePipe carries tags and a tag call alone never removes one, so dropped keys are untagged before the desired set is applied, as the registry schemas' update handlers declare. ECR no longer adopts a repository whose name is already taken: a create on a colliding name fails with RepositoryAlreadyExistsException as on CloudFormation (a CDK bootstrap re-run is an update of the existing CDKToolkit stack and stays on the reuse path), a template that drops its lifecycle or repository policy deletes the stored one, and a dropped ImageTagMutability resets to the MUTABLE default the API applies when the parameter is omitted. A Pipes update that changes the createOnly Source while reusing the name is refused with ValidationError. CfnStableNameUpdatePathTest provisions each type twice and pins exactly one create, the tag diff, the source rejection and the collision failure. AWS::SQS::Queue and AWS::Lambda::MicrovmImage share the original defect and are left for a follow-up.
This commit is contained in:
1 parent
309043baf6
commit
1528c65df3
13 files changed
+784
-60
No files matched your search
+367
@@ -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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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());
|
||||
}
|
||||
}
|
||||
+22
-4
@@ -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
|
||||
|
||||
+41
@@ -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<String, String> 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");
|
||||
}
|
||||
|
||||
}
|
||||
+52
@@ -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);
|
||||
|
||||
+22
@@ -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<String> 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<Map<String, String>> attrs = ArgumentCaptor.forClass(Map.class);
|
||||
|
||||
Reference in new issue
Block a user