mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(cloudformation): order leftover deletes by what their attributes reference (#5998)
* fix(cloudformation): infer no leftover order from custom resource data Leftover ordering read every attribute of a resource the template no longer names as a reference to what it uses. A custom resource's attributes are its handler's response Data, which can name a resource that depends on it, so a custom resource whose Data named a bucket that DependsOn it was deleted before the bucket. Before leftovers were ordered, reverse creation order got this right. A custom resource is now one the dispatcher routes to the generic handler, and of its attributes only Floci's own __Floci keys, such as its ServiceToken, count. Custom::DynamoDBReplica has its own provisioner and keeps the edge its TableName gives. A nested stack's Outputs.* and an SSM parameter's Value are values passed through, not references, and no longer order leftovers either. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(cloudformation): order leftovers without recursion The leftover walk recursed once per link, so a long chain of leftovers, each naming the next, could overflow the stack. A StackOverflowError is not an Exception, so it got past the fall back to insertion order and stopped the delete, cleanup or rollback. The walk now runs on an explicit stack, with the same memo and the same cut where a cycle closes. Its test walks 10,000 links on a small thread stack, which the recursive walk overflows, and waits for it a bounded time. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(cloudformation): keep a leftover's own id from ordering it after a dependent Some dependents take their parent's id as their own physical id: a bucket policy is named by its bucket, a secret target attachment by its secret's ARN. The parent's attribute naming that id then matched the dependent, so a leftover bucket or secret was deleted before the policy or attachment that depends on it. An attribute naming the leftover's own id is no longer a reference, nor is a resource whose id extends it. A leftover whose id extends another's past a separator, as parent-1/child-1 does parent-1, goes before that resource. A bucket policy or secret target attachment goes before whatever else holds its id, including a bucket or secret the template still names, whichever of the two was recorded first. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(cloudformation): order a custom resource or nested stack by what it was given Leftover ordering read no edges from a custom resource's Data or a nested stack's outputs, which left both with nothing they use. A custom resource whose properties name a bucket it empties went after that bucket, and a nested stack whose child created subnets in a VPC the parent passed it went after the VPC, which then could not be deleted. A Lambda ServiceToken, an ARN, never matched its function either, whose physical id is its name. A custom resource now orders by its resolved properties, with the function name any Lambda ARN in them gives. A nested stack records the parameters it passes its child under hidden __FlociUses keys and orders by those. An SSM parameter's Value is what the parameter was given, as with Value: !Ref Bucket, so it counts again. The registry now says which types the generic custom-resource handler serves. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(cloudformation): let a leftover's own id still name another resource A value equal to a leftover's own id was skipped outright, so a leftover rule named like the event bus it is on lost its EventBusName edge and went after the bus, which cannot be deleted while it has rules. Such a value now skips only the leftover itself and the dependents that take the same id. A function URL and a cluster's capacity provider associations also take their parent's id, so they go before it. A leftover recorded without a type no longer throws on the type check, which had sent the whole stack back to insertion order. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(cloudformation): order a custom resource or nested stack by the resources it names Ordering a leftover custom resource by the text of its properties, and a nested stack by the values of its parameters, also matched literals. A certificate resource given a domain's name went before the custom domain that uses the certificate, which then cannot be deleted. A custom resource or nested stack now keeps, as it is provisioned, the physical id of each resource its definition names through Ref, Fn::GetAtt, Fn::Sub or DependsOn, under hidden __FlociUses keys, and is ordered by those. An update replaces them, and a rolled-back update puts back the ones from before. Its properties and parameters are no longer read for this. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(cloudformation): find what a leftover depended on by its logical id too A custom resource or nested stack keeps the physical id of each resource its definition names, but an update replaces a resource it only DependsOn without touching it, so the id it kept goes stale and the leftover lost that edge. A kept resource now also counts as whatever the stack holds under its logical id. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(cloudformation): let what a definition named outweigh a shared id CDK's S3AutoDeleteObjects resource takes its bucket's name as its id and depends on the bucket and its policy. Left over with both, the bucket's own name named the custom resource, the own-id rule dropped the policy the definition named, and the policy counted the custom resource as the holder of its id it uses, so the bucket went first and its delete failed on the objects the custom resource would have removed. What a definition named is now found by logical id and taken as given, and a resource whose definition named a leftover is its dependent, not something it uses. A nested stack saved before definitions were kept orders by its outputs again, as it did then. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * docs(cloudformation): say which leftovers order by their kept uses A nested stack keeps no uses when its definition names no resource, as well as when it was saved before uses were kept, and orders by its outputs either way. A kept use is found by its logical id, its physical id being a record. A resource whose own definition named a leftover is skipped by all three inferred rules, not only the value match. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(cloudformation): read no parent from a WAF or custom action type id A WAFv2 web ACL or IP set has the physical id name|id|scope, and a CodePipeline custom action type category|Custom|provider|version. Their first part is their own identity, not a parent's id, yet the leftover walk read it as the id of a resource they belong to, so a leftover web ACL sharing a bucket's name was ordered after the bucket. These types no longer get an edge from a prefix of their own id. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(cloudformation): keep a DependsOn-only change for a later leftover delete An update that changes only a custom resource's or nested stack's DependsOn does not re-provision it, so the resources it was kept as using stayed as they were, and as a leftover it could later be deleted after a resource it had come to depend on. As an update commits, what each custom resource and nested stack the template names now names is kept again. An update that rolls back keeps what was kept before. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(cloudformation): refresh kept uses only for active resources, safely The refresh as an update commits re-read the definition of a custom resource or nested stack whose condition had turned false, choosing its Fn::If branches by conditions it was never provisioned under; if its cleanup delete then failed, it stayed held with uses it never had. It also ran where a failure would skip the committed update's cleanup. Such a resource now keeps what it was provisioned with, and a failure in the refresh is logged and costs only those keys. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * refactor(cloudformation): let provisioners say how their ids name a parent The leftover walk listed in CloudFormationService which types take their parent's physical id (bucket policy, secret target attachment, function URL, capacity provider associations) and which types' ids name no parent (WAFv2 web ACL and IP set, CodePipeline custom action type). That is knowledge of how those types are provisioned. Two default hooks on CfnResourceProvisioner, asked through the dispatcher as for replacement updates, now let the S3, Secrets Manager, Lambda, ECS, WAFv2 and CodePipeline provisioners say it for their own types. No behaviour changes. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * test(cloudformation): answer the provisioner hooks as production does The rollback test's stand-in provisioners were plain mocks, so they answered no to a prefix of a custom resource's id naming its parent, where a provisioner that overrides nothing answers yes. They now call the interface's own defaults, the dispatcher test checks a custom type keeps them, and a static import is back in order. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> --------- Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
This commit is contained in:
1 parent
d8064fae14
commit
b955aa09ff
15 files changed
+1458
-23
No files matched your search
+243
@@ -0,0 +1,243 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.XmlParser;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaService;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.InjectMock;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* A custom resource keeps the physical id of each resource its definition names, through a
|
||||
* {@code Ref} or {@code DependsOn}, so a stack can delete it before them once the template no
|
||||
* longer names it; a literal it was given is not kept, though another resource may have that name.
|
||||
* An update replaces what it keeps, and a rolled-back update gives back what it kept before.
|
||||
*
|
||||
* <p>The ServiceToken Lambda is mocked, as in {@code CloudFormationCustomResourceRollbackIntegrationTest},
|
||||
* and answers by a PUT of its result to the event's {@code ResponseURL}.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class CloudFormationCustomResourceUsesIntegrationTest {
|
||||
|
||||
private static final String SERVICE_TOKEN = "arn:aws:lambda:us-east-1:000000000000:function:uses-probe";
|
||||
private static final String USES = "__FlociUsesResource.";
|
||||
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@InjectMock
|
||||
LambdaService lambdaService;
|
||||
|
||||
@Inject
|
||||
CloudFormationService cloudFormationService;
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void stubHandler() {
|
||||
when(lambdaService.invoke(any(), eq(SERVICE_TOKEN), any(), eq(InvocationType.RequestResponse)))
|
||||
.thenAnswer(inv -> {
|
||||
putResponse(mapper.readTree((byte[]) inv.getArgument(2)));
|
||||
return new InvokeResult(200, null, "null".getBytes(StandardCharsets.UTF_8), null, "req-1");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCustomResourceKeepsWhatItsDefinitionNamesAndNotItsLiterals() throws InterruptedException {
|
||||
String stack = "cr-uses-" + Long.toString(System.nanoTime(), 36);
|
||||
String stackId = createStack(stack, template(stack, "Data", ""));
|
||||
awaitStackStatus(stackId, "CREATE_COMPLETE");
|
||||
|
||||
Map<String, String> kept = attributes(stack);
|
||||
assertEquals(stack + "-data", kept.get(USES + "Data"), kept::toString);
|
||||
assertEquals(queueUrl(stack), kept.get(USES + "Queue"), kept::toString);
|
||||
assertFalse(kept.containsValue(stack + ".example.com"), kept::toString);
|
||||
|
||||
updateStack(stack, template(stack, "Archive", ""));
|
||||
awaitStackStatus(stackId, "UPDATE_COMPLETE");
|
||||
|
||||
kept = attributes(stack);
|
||||
assertEquals(stack + "-archive", kept.get(USES + "Archive"), kept::toString);
|
||||
assertNull(kept.get(USES + "Data"), kept::toString);
|
||||
deleteStack(stack);
|
||||
awaitStackStatus(stackId, "DELETE_COMPLETE");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRolledBackUpdateGivesACustomResourceBackWhatItKeptBefore() throws InterruptedException {
|
||||
String stack = "cr-uses-rollback-" + Long.toString(System.nanoTime(), 36);
|
||||
String stackId = createStack(stack, template(stack, "Data", ""));
|
||||
awaitStackStatus(stackId, "CREATE_COMPLETE");
|
||||
|
||||
String failingBucket = """
|
||||
,
|
||||
"Bad": {"Type": "AWS::S3::Bucket", "DependsOn": "Emptier", "Properties": {"BucketName": "bad/name"}}""";
|
||||
updateStack(stack, template(stack, "Archive", failingBucket));
|
||||
awaitStackStatus(stackId, "UPDATE_ROLLBACK_COMPLETE");
|
||||
|
||||
Map<String, String> kept = attributes(stack);
|
||||
assertEquals(stack + "-data", kept.get(USES + "Data"), kept::toString);
|
||||
assertNull(kept.get(USES + "Archive"), kept::toString);
|
||||
deleteStack(stack);
|
||||
awaitStackStatus(stackId, "DELETE_COMPLETE");
|
||||
}
|
||||
|
||||
/**
|
||||
* An update that changes only a custom resource's {@code DependsOn} does not re-provision it,
|
||||
* yet once the update commits it keeps the resource it now depends on.
|
||||
*/
|
||||
@Test
|
||||
void aCommittedUpdateKeepsADependsOnAddedAlone() throws InterruptedException {
|
||||
String stack = "cr-uses-dependson-" + Long.toString(System.nanoTime(), 36);
|
||||
String stackId = createStack(stack, template(stack, "Data", ""));
|
||||
awaitStackStatus(stackId, "CREATE_COMPLETE");
|
||||
|
||||
updateStack(stack, dependsOnArchive(template(stack, "Data", extraQueue(stack))));
|
||||
awaitStackStatus(stackId, "UPDATE_COMPLETE");
|
||||
|
||||
Map<String, String> kept = attributes(stack);
|
||||
assertEquals(stack + "-archive", kept.get(USES + "Archive"), kept::toString);
|
||||
assertEquals(stack + "-data", kept.get(USES + "Data"), kept::toString);
|
||||
deleteStack(stack);
|
||||
awaitStackStatus(stackId, "DELETE_COMPLETE");
|
||||
}
|
||||
|
||||
/** The same change in an update that rolls back leaves what the custom resource kept before. */
|
||||
@Test
|
||||
void aRolledBackUpdateKeepsNoDependsOnAddedAlone() throws InterruptedException {
|
||||
String stack = "cr-uses-dependson-rollback-" + Long.toString(System.nanoTime(), 36);
|
||||
String stackId = createStack(stack, template(stack, "Data", ""));
|
||||
awaitStackStatus(stackId, "CREATE_COMPLETE");
|
||||
|
||||
String failingBucket = """
|
||||
,
|
||||
"Bad": {"Type": "AWS::S3::Bucket", "Properties": {"BucketName": "bad/name"}}""";
|
||||
updateStack(stack, dependsOnArchive(template(stack, "Data", failingBucket)));
|
||||
awaitStackStatus(stackId, "UPDATE_ROLLBACK_COMPLETE");
|
||||
|
||||
Map<String, String> kept = attributes(stack);
|
||||
assertNull(kept.get(USES + "Archive"), kept::toString);
|
||||
assertEquals(stack + "-data", kept.get(USES + "Data"), kept::toString);
|
||||
deleteStack(stack);
|
||||
awaitStackStatus(stackId, "DELETE_COMPLETE");
|
||||
}
|
||||
|
||||
/** The template with the custom resource depending on the Archive bucket as well as the queue. */
|
||||
private static String dependsOnArchive(String template) {
|
||||
return template.replace("\"DependsOn\": \"Queue\"", "\"DependsOn\": [\"Queue\", \"Archive\"]");
|
||||
}
|
||||
|
||||
/** An unrelated queue an update adds, so the update has something to do besides the DependsOn. */
|
||||
private static String extraQueue(String stack) {
|
||||
return """
|
||||
,
|
||||
"Extra": {"Type": "AWS::SQS::Queue", "Properties": {"QueueName": "%s-extra"}}""".formatted(stack);
|
||||
}
|
||||
|
||||
/** Two buckets and a queue, and a custom resource that uses the queue and the bucket named {@code target}. */
|
||||
private static String template(String stack, String target, String extraResources) {
|
||||
return """
|
||||
{
|
||||
"Resources": {
|
||||
"Data": {"Type": "AWS::S3::Bucket", "Properties": {"BucketName": "%1$s-data"}},
|
||||
"Archive": {"Type": "AWS::S3::Bucket", "Properties": {"BucketName": "%1$s-archive"}},
|
||||
"Queue": {"Type": "AWS::SQS::Queue", "Properties": {"QueueName": "%1$s-queue"}},
|
||||
"Emptier": {
|
||||
"Type": "Custom::EmptyBucket",
|
||||
"DependsOn": "Queue",
|
||||
"Properties": {
|
||||
"ServiceToken": "%2$s",
|
||||
"BucketName": {"Ref": "%3$s"},
|
||||
"Domain": "%1$s.example.com"
|
||||
}
|
||||
}%4$s
|
||||
}
|
||||
}
|
||||
""".formatted(stack, SERVICE_TOKEN, target, extraResources);
|
||||
}
|
||||
|
||||
private Map<String, String> attributes(String stack) {
|
||||
return cloudFormationService.describeStacks(stack, "us-east-1").getFirst()
|
||||
.getResources().get("Emptier").getAttributes();
|
||||
}
|
||||
|
||||
private static String queueUrl(String stack) {
|
||||
String xml = cfn(Map.of("Action", "DescribeStackResource", "StackName", stack,
|
||||
"LogicalResourceId", "Queue"));
|
||||
return XmlParser.extractFirst(xml, "PhysicalResourceId", null);
|
||||
}
|
||||
|
||||
/** Answers the request the way a handler does: a PUT of a SUCCESS result to ResponseURL. */
|
||||
private void putResponse(JsonNode event) {
|
||||
ObjectNode response = mapper.createObjectNode();
|
||||
response.put("Status", "SUCCESS");
|
||||
response.put("RequestId", event.get("RequestId").asText());
|
||||
response.put("StackId", event.get("StackId").asText());
|
||||
response.put("LogicalResourceId", event.get("LogicalResourceId").asText());
|
||||
response.put("PhysicalResourceId", "uses-probe");
|
||||
String path = URI.create(event.get("ResponseURL").asText()).getPath();
|
||||
given().body(response.toString()).when().put(path).then().statusCode(200);
|
||||
}
|
||||
|
||||
private static String createStack(String stackName, String template) {
|
||||
String xml = cfn(Map.of("Action", "CreateStack", "StackName", stackName, "TemplateBody", template));
|
||||
return XmlParser.extractFirst(xml, "StackId", null);
|
||||
}
|
||||
|
||||
private static void updateStack(String stackName, String template) {
|
||||
cfn(Map.of("Action", "UpdateStack", "StackName", stackName, "TemplateBody", template));
|
||||
}
|
||||
|
||||
private static void deleteStack(String stackName) {
|
||||
cfn(Map.of("Action", "DeleteStack", "StackName", stackName));
|
||||
}
|
||||
|
||||
/** Polls DescribeStacks by stack id and returns its XML once the stack reaches {@code status}. */
|
||||
private static String awaitStackStatus(String stackId, String status) throws InterruptedException {
|
||||
String xml = "";
|
||||
long deadline = System.currentTimeMillis() + 10_000;
|
||||
while (System.currentTimeMillis() < deadline) {
|
||||
xml = cfn(Map.of("Action", "DescribeStacks", "StackName", stackId));
|
||||
if (xml.contains("<StackStatus>" + status + "</StackStatus>")) {
|
||||
return xml;
|
||||
}
|
||||
Thread.sleep(50);
|
||||
}
|
||||
fail("stack " + stackId + " never reached " + status + ": " + xml);
|
||||
return xml;
|
||||
}
|
||||
|
||||
private static String cfn(Map<String, String> params) {
|
||||
return given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParams(params)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().asString();
|
||||
}
|
||||
}
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.XmlParser;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.mockito.InjectSpy;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.reset;
|
||||
|
||||
/**
|
||||
* A nested stack the template no longer names, left by a rollback that skipped it, still holds a
|
||||
* subnet its child created in a VPC the parent passed it, so DeleteStack has to delete it before
|
||||
* that VPC, though only the parameters it passed its child say what it uses.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class CloudFormationNestedStackLeftoverIntegrationTest {
|
||||
|
||||
private static final String CFN_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20261019/us-east-1/cloudformation/aws4_request";
|
||||
private static final String EC2_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20261019/us-east-1/ec2/aws4_request";
|
||||
|
||||
private static final String CHILD_TEMPLATE = """
|
||||
{
|
||||
"Parameters": {"VpcId": {"Type": "String"}, "Label": {"Type": "String"}},
|
||||
"Resources": {
|
||||
"Subnet": {"Type": "AWS::EC2::Subnet",
|
||||
"Properties": {"VpcId": {"Ref": "VpcId"}, "CidrBlock": "10.97.1.0/24",
|
||||
"AvailabilityZone": "us-east-1a"}}
|
||||
}
|
||||
}""";
|
||||
|
||||
@InjectSpy
|
||||
Ec2Service ec2Service;
|
||||
|
||||
@Inject
|
||||
CloudFormationService cloudFormationService;
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteStackDeletesASkippedNestedStackBeforeTheVpcItPassedItsChild() {
|
||||
String stack = "nested-leftover-" + Long.toString(System.nanoTime(), 36);
|
||||
String bucket = stack + "-templates";
|
||||
given().when().put("/" + bucket).then().statusCode(200);
|
||||
given().contentType("application/json").body(CHILD_TEMPLATE)
|
||||
.when().put("/" + bucket + "/child.json").then().statusCode(200);
|
||||
AtomicBoolean failSubnetDeletes = new AtomicBoolean(true);
|
||||
doAnswer(invocation -> {
|
||||
if (failSubnetDeletes.get()) {
|
||||
throw new AwsException("InternalError", "simulated subnet delete failure", 500);
|
||||
}
|
||||
return invocation.callRealMethod();
|
||||
}).when(ec2Service).deleteSubnet(anyString(), anyString());
|
||||
try {
|
||||
Map<String, String> created = createStack(stack, template(""));
|
||||
String network = """
|
||||
,
|
||||
"Network": {"Type": "AWS::CloudFormation::Stack",
|
||||
"Properties": {"TemplateURL": "http://localhost/%1$s/child.json",
|
||||
"Parameters": {"VpcId": {"Ref": "Vpc"},
|
||||
"Label": "%2$s-label"}}},
|
||||
"BadSecret": {"Type": "AWS::SecretsManager::Secret", "DependsOn": "Network",
|
||||
"Properties": {"Name": "%2$s-secret", "SecretString": "explicit",
|
||||
"GenerateSecretString": {"PasswordLength": 32}}}"""
|
||||
.formatted(bucket, stack);
|
||||
request("UpdateStack", "StackName", stack, "TemplateBody", template(network)).statusCode(200);
|
||||
String reason = CfnStackWaits.awaitStatus(stack, "UPDATE_ROLLBACK_FAILED").reason();
|
||||
assertTrue(reason.contains("Network"), reason);
|
||||
failSubnetDeletes.set(false);
|
||||
|
||||
request("ContinueUpdateRollback", "StackName", stack, "ResourcesToSkip.member.1", "Network")
|
||||
.statusCode(200);
|
||||
CfnStackWaits.awaitStatus(stack, "UPDATE_ROLLBACK_COMPLETE");
|
||||
assertEquals(1, XmlParser.extractAll(ec2("DescribeSubnets", "Filter.1.Name", "vpc-id",
|
||||
"Filter.1.Value.1", created.get("Vpc")).statusCode(200).extract().asString(), "subnetId")
|
||||
.size(), "the skipped nested stack's subnet is left in place");
|
||||
// The VPC its definition named is kept for the leftover; the literal label names nothing.
|
||||
Map<String, String> kept = cloudFormationService.describeStacks(stack, "us-east-1").getFirst()
|
||||
.getResources().get("Network").getAttributes();
|
||||
assertEquals(created.get("Vpc"), kept.get("__FlociUsesResource.Vpc"));
|
||||
assertFalse(kept.containsValue(stack + "-label"), kept::toString);
|
||||
|
||||
request("DeleteStack", "StackName", stack).statusCode(200);
|
||||
CfnStackWaits.awaitStackDeleted(stack, CFN_AUTH);
|
||||
ec2("DescribeVpcs", "VpcId.1", created.get("Vpc")).statusCode(400)
|
||||
.body(containsString("InvalidVpcID.NotFound"));
|
||||
} finally {
|
||||
failSubnetDeletes.set(false);
|
||||
reset(ec2Service);
|
||||
// Best effort: a failed run may leave the stack DELETE_FAILED or mid-rollback.
|
||||
if (request("DescribeStacks", "StackName", stack).extract().statusCode() == 200) {
|
||||
request("DeleteStack", "StackName", stack);
|
||||
}
|
||||
given().when().delete("/" + bucket + "/child.json");
|
||||
given().when().delete("/" + bucket);
|
||||
}
|
||||
}
|
||||
|
||||
/** A VPC, plus whatever an update adds. */
|
||||
private static String template(String extraResources) {
|
||||
return """
|
||||
{
|
||||
"Resources": {
|
||||
"Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.97.0.0/16"}}%1$s
|
||||
},
|
||||
"Outputs": {
|
||||
"Vpc": {"Value": {"Ref": "Vpc"}}
|
||||
}
|
||||
}""".formatted(extraResources);
|
||||
}
|
||||
|
||||
private static Map<String, String> createStack(String stack, String templateBody) {
|
||||
request("CreateStack", "StackName", stack, "TemplateBody", templateBody).statusCode(200);
|
||||
CfnStackWaits.awaitStatus(stack, "CREATE_COMPLETE");
|
||||
String xml = request("DescribeStacks", "StackName", stack).statusCode(200).extract().asString();
|
||||
return XmlParser.extractPairs(xml, "member", "OutputKey", "OutputValue");
|
||||
}
|
||||
|
||||
private static ValidatableResponse ec2(String action, String... values) {
|
||||
return send(EC2_AUTH, action, values);
|
||||
}
|
||||
|
||||
private static ValidatableResponse request(String action, String... values) {
|
||||
return send(CFN_AUTH, action, values);
|
||||
}
|
||||
|
||||
private static ValidatableResponse send(String auth, String action, String... values) {
|
||||
Map<String, String> parameters = new LinkedHashMap<>();
|
||||
parameters.put("Action", action);
|
||||
for (int i = 0; i < values.length; i += 2) {
|
||||
parameters.put(values[i], values[i + 1]);
|
||||
}
|
||||
return given().contentType("application/x-www-form-urlencoded").header("Authorization", auth)
|
||||
.formParams(parameters).when().post("/").then().log().ifValidationFails();
|
||||
}
|
||||
}
|
||||
+595
@@ -15,8 +15,16 @@ import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackUpdateSnapshot;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnDynamicReferences;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceDispatcher;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnRollback;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CodePipelineCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.EcsCapacityCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.LambdaAddressingCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.S3CfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.SecretTargetAttachmentCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.UpdateCleanupResult;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.WafV2CfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.services.ssm.SsmService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -46,9 +54,11 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.CALLS_REAL_METHODS;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.RETURNS_DEFAULTS;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doReturn;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.inOrder;
|
||||
import static org.mockito.Mockito.mock;
|
||||
@@ -78,6 +88,22 @@ class CloudFormationServiceRollbackTest {
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
provisioner = mock(CfnResourceDispatcher.class);
|
||||
// What the registry and the real provisioners say of a type: an unregistered Custom:: type
|
||||
// goes to the generic custom-resource handler, Custom::DynamoDBReplica has its own, and the
|
||||
// provisioners of the types whose ids relate to a parent's say how.
|
||||
CfnResourceDispatcher routing = new CfnResourceDispatcher(new ObjectMapper(),
|
||||
new CloudFormationResourceRegistry(List.of(
|
||||
serving("AWS::CloudFormation::CustomResource"), serving("Custom::DynamoDBReplica"),
|
||||
real(S3CfnProvisioner.class), real(SecretTargetAttachmentCfnProvisioner.class),
|
||||
real(LambdaAddressingCfnProvisioner.class), real(EcsCapacityCfnProvisioner.class),
|
||||
real(WafV2CfnProvisioner.class), real(CodePipelineCfnProvisioner.class))),
|
||||
null, null);
|
||||
when(provisioner.isCustomResourceType(any()))
|
||||
.thenAnswer(invocation -> routing.isCustomResourceType(invocation.getArgument(0)));
|
||||
when(provisioner.takesParentPhysicalId(any()))
|
||||
.thenAnswer(invocation -> routing.takesParentPhysicalId(invocation.getArgument(0)));
|
||||
when(provisioner.idPrefixCanNameParent(any()))
|
||||
.thenAnswer(invocation -> routing.idPrefixCanNameParent(invocation.getArgument(0)));
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.defaultAccountId()).thenReturn(ACCOUNT);
|
||||
|
||||
@@ -1018,6 +1044,557 @@ class CloudFormationServiceRollbackTest {
|
||||
deletes.verify(provisioner).delete(vpc, REGION);
|
||||
}
|
||||
|
||||
/**
|
||||
* A custom resource's attributes are its handler's response Data, which can name any resource,
|
||||
* such as a bucket created after it and depending on it. Leftover ordering infers nothing from
|
||||
* them, so two leftovers keep their reverse creation order: the bucket goes before the custom
|
||||
* resource it depends on.
|
||||
*/
|
||||
@Test
|
||||
void deleteStack_infersNoLeftoverOrderFromACustomResourcesData() {
|
||||
Stack stack = new Stack();
|
||||
stack.setStackName("delete-leftover-custom-data");
|
||||
stack.setStackId("stack-id");
|
||||
stack.setRegion(REGION);
|
||||
stack.setStatus("UPDATE_ROLLBACK_COMPLETE");
|
||||
stack.setTemplateBody("""
|
||||
{"Resources": {"Queue": {"Type": "AWS::SQS::Queue"}}}""");
|
||||
StackResource queue = resource("Queue", "queue-1", "AWS::SQS::Queue", "CREATE_COMPLETE");
|
||||
StackResource namer = resource("Namer", "namer-1", "Custom::BucketNamer", "UPDATE_COMPLETE");
|
||||
namer.getAttributes().put("BucketName", "bucket-1");
|
||||
StackResource bucket = resource("Bucket", "bucket-1", "AWS::S3::Bucket", "UPDATE_COMPLETE");
|
||||
for (StackResource resource : new StackResource[] {queue, namer, bucket}) {
|
||||
stack.getResources().put(resource.getLogicalId(), resource);
|
||||
}
|
||||
when(provisioner.completeDeleteCleanup(any())).thenReturn(UpdateCleanupResult.notApplicable());
|
||||
|
||||
service.deleteStackResources(stack, REGION, ACCOUNT);
|
||||
|
||||
InOrder deletes = inOrder(provisioner);
|
||||
deletes.verify(provisioner).delete(bucket, REGION);
|
||||
deletes.verify(provisioner).delete(namer, REGION);
|
||||
}
|
||||
|
||||
/**
|
||||
* A leftover custom resource goes before the bucket its definition named, which its handler may
|
||||
* need to empty first: provisioning kept that bucket's id for it.
|
||||
*/
|
||||
@Test
|
||||
void deleteStack_deletesALeftoverCustomResourceBeforeTheBucketItsDefinitionNamed() {
|
||||
String token = "arn:aws:sns:us-east-1:000000000000:emptier";
|
||||
Stack stack = leftoverStack("delete-leftover-custom-uses", "{\"Bucket\": {\"Type\": \"AWS::S3::Bucket\"}}");
|
||||
StackResource emptier = resource("Emptier", "emptier-1", "Custom::EmptyBucket", "UPDATE_COMPLETE");
|
||||
emptier.getAttributes().put("__FlociServiceToken", token);
|
||||
emptier.getAttributes().put(CfnRollback.USES_ATTR_PREFIX + "Resource.Bucket", "bucket-1");
|
||||
StackResource bucket = resource("Bucket", "bucket-1", "AWS::S3::Bucket", "CREATE_COMPLETE");
|
||||
hold(stack, emptier, bucket);
|
||||
|
||||
service.deleteStackResources(stack, REGION, ACCOUNT);
|
||||
|
||||
InOrder deletes = inOrder(provisioner);
|
||||
deletes.verify(provisioner).delete(emptier, REGION);
|
||||
deletes.verify(provisioner).delete(bucket, REGION);
|
||||
}
|
||||
|
||||
/**
|
||||
* A literal a custom resource was given names nothing, even when another resource has that
|
||||
* name: a leftover certificate resource given a domain's name still goes after the leftover
|
||||
* custom domain that uses the certificate.
|
||||
*/
|
||||
@Test
|
||||
void deleteStack_infersNoLeftoverOrderFromACustomResourcesLiteralProperties() {
|
||||
String token = "arn:aws:lambda:us-east-1:000000000000:function:cert-requestor";
|
||||
String certArn = "arn:aws:acm:us-east-1:000000000000:certificate/abc";
|
||||
Stack stack = leftoverStack("delete-leftover-custom-literal", "{\"Queue\": {\"Type\": \"AWS::SQS::Queue\"}}");
|
||||
StackResource queue = resource("Queue", "queue-1", "AWS::SQS::Queue", "CREATE_COMPLETE");
|
||||
StackResource cert = resource("Cert", certArn, "Custom::DNSValidatedCertificate", "UPDATE_COMPLETE");
|
||||
cert.getAttributes().put("__FlociServiceToken", token);
|
||||
cert.getAttributes().put("__FlociResourceProperties",
|
||||
"{\"ServiceToken\": \"" + token + "\", \"DomainName\": \"auth.example.com\"}");
|
||||
cert.getAttributes().put("Arn", certArn);
|
||||
StackResource domain = resource("Domain", "auth.example.com", "AWS::Cognito::UserPoolDomain",
|
||||
"UPDATE_COMPLETE");
|
||||
hold(stack, queue, cert, domain);
|
||||
|
||||
service.deleteStackResources(stack, REGION, ACCOUNT);
|
||||
|
||||
InOrder deletes = inOrder(provisioner);
|
||||
deletes.verify(provisioner).delete(domain, REGION);
|
||||
deletes.verify(provisioner).delete(cert, REGION);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code Custom::DynamoDBReplica} has its own provisioner, and its {@code TableName} names the
|
||||
* table it replicates, so a leftover replica still goes before that table.
|
||||
*/
|
||||
@Test
|
||||
void deleteStack_deletesALeftoverDynamoDbReplicaBeforeItsTable() {
|
||||
Stack stack = leftoverStack("delete-leftover-replica", "{\"Table\": {\"Type\": \"AWS::DynamoDB::Table\"}}");
|
||||
StackResource replica = resource("Replica", "table-1-replica", "Custom::DynamoDBReplica", "UPDATE_COMPLETE");
|
||||
replica.getAttributes().put("TableName", "table-1");
|
||||
StackResource table = resource("Table", "table-1", "AWS::DynamoDB::Table", "CREATE_COMPLETE");
|
||||
hold(stack, replica, table);
|
||||
|
||||
service.deleteStackResources(stack, REGION, ACCOUNT);
|
||||
|
||||
InOrder deletes = inOrder(provisioner);
|
||||
deletes.verify(provisioner).delete(replica, REGION);
|
||||
deletes.verify(provisioner).delete(table, REGION);
|
||||
}
|
||||
|
||||
/**
|
||||
* Floci's own attributes on a custom resource are not handler Data: a leftover custom resource
|
||||
* still goes before the topic its {@code ServiceToken} names, so its Delete reaches the handler.
|
||||
*/
|
||||
@Test
|
||||
void deleteStack_deletesALeftoverCustomResourceBeforeItsServiceToken() {
|
||||
String topicArn = "arn:aws:sns:us-east-1:000000000000:handler";
|
||||
Stack stack = leftoverStack("delete-leftover-custom-token", "{\"Topic\": {\"Type\": \"AWS::SNS::Topic\"}}");
|
||||
StackResource custom = resource("Notifier", "notifier-1", "Custom::Notifier", "UPDATE_COMPLETE");
|
||||
custom.getAttributes().put("__FlociServiceToken", topicArn);
|
||||
StackResource topic = resource("Topic", topicArn, "AWS::SNS::Topic", "CREATE_COMPLETE");
|
||||
hold(stack, custom, topic);
|
||||
|
||||
service.deleteStackResources(stack, REGION, ACCOUNT);
|
||||
|
||||
InOrder deletes = inOrder(provisioner);
|
||||
deletes.verify(provisioner).delete(custom, REGION);
|
||||
deletes.verify(provisioner).delete(topic, REGION);
|
||||
}
|
||||
|
||||
/**
|
||||
* A Lambda {@code ServiceToken} is the function's ARN while the function's physical id is its
|
||||
* name: a leftover custom resource still goes before its handler function.
|
||||
*/
|
||||
@Test
|
||||
void deleteStack_deletesALeftoverLambdaBackedCustomResourceBeforeItsHandler() {
|
||||
String handlerArn = "arn:aws:lambda:us-east-1:000000000000:function:handler";
|
||||
Stack stack = leftoverStack("delete-leftover-custom-lambda",
|
||||
"{\"Handler\": {\"Type\": \"AWS::Lambda::Function\"}}");
|
||||
StackResource custom = resource("Seeder", "seeder-1", "Custom::Seeder", "UPDATE_COMPLETE");
|
||||
custom.getAttributes().put("__FlociServiceToken", handlerArn);
|
||||
StackResource handler = resource("Handler", "handler", "AWS::Lambda::Function", "CREATE_COMPLETE");
|
||||
handler.getAttributes().put("Arn", handlerArn);
|
||||
hold(stack, custom, handler);
|
||||
|
||||
service.deleteStackResources(stack, REGION, ACCOUNT);
|
||||
|
||||
InOrder deletes = inOrder(provisioner);
|
||||
deletes.verify(provisioner).delete(custom, REGION);
|
||||
deletes.verify(provisioner).delete(handler, REGION);
|
||||
}
|
||||
|
||||
/**
|
||||
* An SSM parameter's {@code Value} is what it was given, such as a bucket's name, so a leftover
|
||||
* parameter goes before that bucket, as a stack delete orders {@code Value: !Ref Bucket}.
|
||||
*/
|
||||
@Test
|
||||
void deleteStack_deletesALeftoverParameterBeforeTheBucketItsValueNames() {
|
||||
Stack stack = leftoverStack("delete-leftover-parameter", "{\"Bucket\": {\"Type\": \"AWS::S3::Bucket\"}}");
|
||||
StackResource parameter = resource("Parameter", "bucket-name", "AWS::SSM::Parameter", "UPDATE_COMPLETE");
|
||||
parameter.getAttributes().put("Value", "bucket-1");
|
||||
StackResource bucket = resource("Bucket", "bucket-1", "AWS::S3::Bucket", "CREATE_COMPLETE");
|
||||
hold(stack, parameter, bucket);
|
||||
|
||||
service.deleteStackResources(stack, REGION, ACCOUNT);
|
||||
|
||||
InOrder deletes = inOrder(provisioner);
|
||||
deletes.verify(provisioner).delete(parameter, REGION);
|
||||
deletes.verify(provisioner).delete(bucket, REGION);
|
||||
}
|
||||
|
||||
/**
|
||||
* A leftover nested stack goes before the VPC its definition passed its child, where the child
|
||||
* created subnets: provisioning kept that VPC's id for it.
|
||||
*/
|
||||
@Test
|
||||
void deleteStack_deletesALeftoverNestedStackBeforeTheVpcItPassedItsChild() {
|
||||
String childId = "arn:aws:cloudformation:us-east-1:000000000000:stack/parent-Network/1";
|
||||
Stack stack = leftoverStack("delete-leftover-nested-uses", "{\"Vpc\": {\"Type\": \"AWS::EC2::VPC\"}}");
|
||||
StackResource nested = resource("Network", childId, "AWS::CloudFormation::Stack", "UPDATE_COMPLETE");
|
||||
nested.getAttributes().put("Arn", childId);
|
||||
nested.getAttributes().put(CfnRollback.USES_ATTR_PREFIX + "Resource.Vpc", "vpc-1");
|
||||
StackResource vpc = resource("Vpc", "vpc-1", "AWS::EC2::VPC", "CREATE_COMPLETE");
|
||||
hold(stack, nested, vpc);
|
||||
|
||||
service.deleteStackResources(stack, REGION, ACCOUNT);
|
||||
|
||||
assertEquals(List.of("Network", "Vpc"), deletesInProgress(stack));
|
||||
}
|
||||
|
||||
/**
|
||||
* A resource a nested stack only {@code DependsOn} can be replaced by a later update that leaves
|
||||
* the nested stack alone, so the id kept for it is stale: the leftover still goes before what the
|
||||
* stack now holds under that logical id.
|
||||
*/
|
||||
@Test
|
||||
void deleteStack_deletesALeftoverNestedStackBeforeAReplacedResourceItDependsOn() {
|
||||
String childId = "arn:aws:cloudformation:us-east-1:000000000000:stack/parent-Network/1";
|
||||
Stack stack = leftoverStack("delete-leftover-nested-stale", "{\"Policy\": {\"Type\": \"AWS::IAM::Policy\"}}");
|
||||
StackResource nested = resource("Network", childId, "AWS::CloudFormation::Stack", "UPDATE_COMPLETE");
|
||||
nested.getAttributes().put("Arn", childId);
|
||||
nested.getAttributes().put(CfnRollback.USES_ATTR_PREFIX + "Resource.Policy", "old-policy");
|
||||
StackResource policy = resource("Policy", "new-policy", "AWS::IAM::Policy", "UPDATE_COMPLETE");
|
||||
hold(stack, nested, policy);
|
||||
|
||||
service.deleteStackResources(stack, REGION, ACCOUNT);
|
||||
|
||||
assertEquals(List.of("Network", "Policy"), deletesInProgress(stack));
|
||||
}
|
||||
|
||||
/**
|
||||
* A nested stack's {@code Outputs.*} are its child's outputs: a leftover bucket named after
|
||||
* one, created after the nested stack, still goes first. (The nested stack keeps what its
|
||||
* definition named, here a resource the stack no longer holds.)
|
||||
*/
|
||||
@Test
|
||||
void deleteStack_infersNoLeftoverOrderFromANestedStacksOutputs() {
|
||||
String childId = "arn:aws:cloudformation:us-east-1:000000000000:stack/parent-Names/1";
|
||||
Stack stack = leftoverStack("delete-leftover-nested-outputs", "{\"Queue\": {\"Type\": \"AWS::SQS::Queue\"}}");
|
||||
StackResource queue = resource("Queue", "queue-1", "AWS::SQS::Queue", "CREATE_COMPLETE");
|
||||
StackResource nested = resource("Names", childId, "AWS::CloudFormation::Stack", "UPDATE_COMPLETE");
|
||||
nested.getAttributes().put("Arn", childId);
|
||||
nested.getAttributes().put(CfnRollback.USES_ATTR_PREFIX + "Resource.Source", "source-1");
|
||||
nested.getAttributes().put("Outputs.BucketName", "bucket-1");
|
||||
StackResource bucket = resource("Bucket", "bucket-1", "AWS::S3::Bucket", "UPDATE_COMPLETE");
|
||||
hold(stack, queue, nested, bucket);
|
||||
|
||||
service.deleteStackResources(stack, REGION, ACCOUNT);
|
||||
|
||||
assertEquals(List.of("Queue", "Bucket", "Names"), deletesInProgress(stack));
|
||||
}
|
||||
|
||||
/**
|
||||
* A nested stack saved before Floci kept what its definition named still orders by its outputs,
|
||||
* as it did then: a leftover one echoing the VPC it was passed goes before that VPC.
|
||||
*/
|
||||
@Test
|
||||
void deleteStack_ordersALeftoverNestedStackSavedWithoutKeptUsesByItsOutputs() {
|
||||
String childId = "arn:aws:cloudformation:us-east-1:000000000000:stack/parent-Network/1";
|
||||
Stack stack = leftoverStack("delete-leftover-nested-legacy", "{\"Vpc\": {\"Type\": \"AWS::EC2::VPC\"}}");
|
||||
StackResource nested = resource("Network", childId, "AWS::CloudFormation::Stack", "UPDATE_COMPLETE");
|
||||
nested.getAttributes().put("Arn", childId);
|
||||
nested.getAttributes().put("Outputs.VpcId", "vpc-1");
|
||||
StackResource vpc = resource("Vpc", "vpc-1", "AWS::EC2::VPC", "CREATE_COMPLETE");
|
||||
hold(stack, nested, vpc);
|
||||
|
||||
service.deleteStackResources(stack, REGION, ACCOUNT);
|
||||
|
||||
assertEquals(List.of("Network", "Vpc"), deletesInProgress(stack));
|
||||
}
|
||||
|
||||
/**
|
||||
* CDK's S3AutoDeleteObjects resource takes its bucket's name as its id, depends on the bucket
|
||||
* and its policy, and empties the bucket on delete. Left over with both, it goes first: what its
|
||||
* definition named outweighs the bucket's own name, and the policy does not count it as the
|
||||
* holder of its id it depends on.
|
||||
*/
|
||||
@Test
|
||||
void deleteStack_deletesALeftoverAutoDeleteObjectsResourceBeforeItsPolicyAndBucket() {
|
||||
Stack stack = leftoverStack("delete-leftover-auto-delete", "{\"Queue\": {\"Type\": \"AWS::SQS::Queue\"}}");
|
||||
StackResource queue = resource("Queue", "queue-1", "AWS::SQS::Queue", "CREATE_COMPLETE");
|
||||
StackResource bucket = resource("Bucket", "bucket-1", "AWS::S3::Bucket", "UPDATE_COMPLETE");
|
||||
bucket.getAttributes().put("BucketName", "bucket-1");
|
||||
bucket.getAttributes().put("Arn", "arn:aws:s3:::bucket-1");
|
||||
StackResource policy = resource("BucketPolicy", "bucket-1", "AWS::S3::BucketPolicy", "UPDATE_COMPLETE");
|
||||
StackResource autoDelete = resource("AutoDelete", "bucket-1", "Custom::S3AutoDeleteObjects",
|
||||
"UPDATE_COMPLETE");
|
||||
autoDelete.getAttributes().put("__FlociServiceToken",
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:provider");
|
||||
autoDelete.getAttributes().put(CfnRollback.USES_ATTR_PREFIX + "Resource.Bucket", "bucket-1");
|
||||
autoDelete.getAttributes().put(CfnRollback.USES_ATTR_PREFIX + "Resource.BucketPolicy", "bucket-1");
|
||||
hold(stack, queue, bucket, policy, autoDelete);
|
||||
|
||||
service.deleteStackResources(stack, REGION, ACCOUNT);
|
||||
|
||||
InOrder deletes = inOrder(provisioner);
|
||||
deletes.verify(provisioner).delete(autoDelete, REGION);
|
||||
deletes.verify(provisioner).delete(policy, REGION);
|
||||
deletes.verify(provisioner).delete(bucket, REGION);
|
||||
}
|
||||
|
||||
/**
|
||||
* A bucket policy takes its bucket's name as its own physical id, so the bucket's
|
||||
* {@code BucketName} names the policy as well as itself. That is not a reference: the policy,
|
||||
* created after the bucket, still goes first.
|
||||
*/
|
||||
@Test
|
||||
void deleteStack_deletesALeftoverBucketPolicyBeforeItsBucket() {
|
||||
Stack stack = leftoverStack("delete-leftover-policy", "{\"Queue\": {\"Type\": \"AWS::SQS::Queue\"}}");
|
||||
StackResource queue = resource("Queue", "queue-1", "AWS::SQS::Queue", "CREATE_COMPLETE");
|
||||
StackResource bucket = resource("Bucket", "bucket-1", "AWS::S3::Bucket", "UPDATE_COMPLETE");
|
||||
bucket.getAttributes().put("BucketName", "bucket-1");
|
||||
bucket.getAttributes().put("Arn", "arn:aws:s3:::bucket-1");
|
||||
StackResource policy = resource("Policy", "bucket-1", "AWS::S3::BucketPolicy", "UPDATE_COMPLETE");
|
||||
hold(stack, queue, bucket, policy);
|
||||
|
||||
service.deleteStackResources(stack, REGION, ACCOUNT);
|
||||
|
||||
InOrder deletes = inOrder(provisioner);
|
||||
deletes.verify(provisioner).delete(policy, REGION);
|
||||
deletes.verify(provisioner).delete(bucket, REGION);
|
||||
}
|
||||
|
||||
/** A secret target attachment takes its secret's ARN as its physical id and still goes first. */
|
||||
@Test
|
||||
void deleteStack_deletesALeftoverSecretAttachmentBeforeItsSecret() {
|
||||
String secretArn = "arn:aws:secretsmanager:us-east-1:000000000000:secret:db-AbCdEf";
|
||||
Stack stack = leftoverStack("delete-leftover-attachment", "{\"Queue\": {\"Type\": \"AWS::SQS::Queue\"}}");
|
||||
StackResource queue = resource("Queue", "queue-1", "AWS::SQS::Queue", "CREATE_COMPLETE");
|
||||
StackResource secret = resource("Secret", secretArn, "AWS::SecretsManager::Secret", "UPDATE_COMPLETE");
|
||||
secret.getAttributes().put("Arn", secretArn);
|
||||
StackResource attachment = resource("Attachment", secretArn,
|
||||
"AWS::SecretsManager::SecretTargetAttachment", "UPDATE_COMPLETE");
|
||||
attachment.getAttributes().put("Id", secretArn);
|
||||
hold(stack, queue, secret, attachment);
|
||||
|
||||
service.deleteStackResources(stack, REGION, ACCOUNT);
|
||||
|
||||
InOrder deletes = inOrder(provisioner);
|
||||
deletes.verify(provisioner).delete(attachment, REGION);
|
||||
deletes.verify(provisioner).delete(secret, REGION);
|
||||
}
|
||||
|
||||
/**
|
||||
* A leftover secret target attachment whose secret the template still names goes before that
|
||||
* secret: it shares the secret's id, and its type alone says which of the two depends on the
|
||||
* other.
|
||||
*/
|
||||
@Test
|
||||
void deleteStack_deletesALeftoverSecretAttachmentBeforeTheSecretTheTemplateStillNames() {
|
||||
String secretArn = "arn:aws:secretsmanager:us-east-1:000000000000:secret:db-AbCdEf";
|
||||
Stack stack = leftoverStack("delete-leftover-attachment-ranked",
|
||||
"{\"Secret\": {\"Type\": \"AWS::SecretsManager::Secret\"}}");
|
||||
StackResource attachment = resource("Attachment", secretArn,
|
||||
"AWS::SecretsManager::SecretTargetAttachment", "UPDATE_COMPLETE");
|
||||
StackResource secret = resource("Secret", secretArn, "AWS::SecretsManager::Secret", "CREATE_COMPLETE");
|
||||
secret.getAttributes().put("Arn", secretArn);
|
||||
hold(stack, attachment, secret);
|
||||
|
||||
service.deleteStackResources(stack, REGION, ACCOUNT);
|
||||
|
||||
InOrder deletes = inOrder(provisioner);
|
||||
deletes.verify(provisioner).delete(attachment, REGION);
|
||||
deletes.verify(provisioner).delete(secret, REGION);
|
||||
}
|
||||
|
||||
/**
|
||||
* A value equal to a leftover's own id can still name another kind of resource that shares the
|
||||
* id: a leftover rule named like the event bus it is on goes before that bus, which cannot be
|
||||
* deleted while it has rules.
|
||||
*/
|
||||
@Test
|
||||
void deleteStack_deletesALeftoverRuleBeforeTheSameNamedBusItIsOn() {
|
||||
Stack stack = leftoverStack("delete-leftover-rule", "{\"Bus\": {\"Type\": \"AWS::Events::EventBus\"}}");
|
||||
StackResource rule = resource("Rule", "orders", "AWS::Events::Rule", "UPDATE_COMPLETE");
|
||||
rule.getAttributes().put("RuleName", "orders");
|
||||
rule.getAttributes().put("EventBusName", "orders");
|
||||
StackResource bus = resource("Bus", "orders", "AWS::Events::EventBus", "CREATE_COMPLETE");
|
||||
bus.getAttributes().put("Name", "orders");
|
||||
hold(stack, rule, bus);
|
||||
|
||||
service.deleteStackResources(stack, REGION, ACCOUNT);
|
||||
|
||||
InOrder deletes = inOrder(provisioner);
|
||||
deletes.verify(provisioner).delete(rule, REGION);
|
||||
deletes.verify(provisioner).delete(bus, REGION);
|
||||
}
|
||||
|
||||
/**
|
||||
* A function URL on an alias takes the alias's ARN as its id, so a leftover one goes before the
|
||||
* alias, and a leftover alias does not count its own ARN as using the URL.
|
||||
*/
|
||||
@Test
|
||||
void deleteStack_deletesALeftoverAliasUrlBeforeItsAlias() {
|
||||
String aliasArn = "arn:aws:lambda:us-east-1:000000000000:function:fn:live";
|
||||
Stack stack = leftoverStack("delete-leftover-url", "{\"Fn\": {\"Type\": \"AWS::Lambda::Function\"}}");
|
||||
StackResource url = resource("Url", aliasArn, "AWS::Lambda::Url", "UPDATE_COMPLETE");
|
||||
url.getAttributes().put("FunctionArn", aliasArn);
|
||||
StackResource alias = resource("Live", aliasArn, "AWS::Lambda::Alias", "UPDATE_COMPLETE");
|
||||
alias.getAttributes().put("AliasArn", aliasArn);
|
||||
StackResource fn = resource("Fn", "fn", "AWS::Lambda::Function", "CREATE_COMPLETE");
|
||||
hold(stack, url, alias, fn);
|
||||
|
||||
service.deleteStackResources(stack, REGION, ACCOUNT);
|
||||
|
||||
InOrder deletes = inOrder(provisioner);
|
||||
deletes.verify(provisioner).delete(url, REGION);
|
||||
deletes.verify(provisioner).delete(alias, REGION);
|
||||
}
|
||||
|
||||
/** A leftover alias recorded before its leftover URL still does not count its ARN as using it. */
|
||||
@Test
|
||||
void deleteStack_aLeftoverAliasRecordedFirstStillGoesAfterItsUrl() {
|
||||
String aliasArn = "arn:aws:lambda:us-east-1:000000000000:function:fn:live";
|
||||
Stack stack = leftoverStack("delete-leftover-url-alias-first",
|
||||
"{\"Fn\": {\"Type\": \"AWS::Lambda::Function\"}}");
|
||||
StackResource alias = resource("Live", aliasArn, "AWS::Lambda::Alias", "UPDATE_COMPLETE");
|
||||
alias.getAttributes().put("AliasArn", aliasArn);
|
||||
StackResource url = resource("Url", aliasArn, "AWS::Lambda::Url", "UPDATE_COMPLETE");
|
||||
url.getAttributes().put("FunctionArn", aliasArn);
|
||||
StackResource fn = resource("Fn", "fn", "AWS::Lambda::Function", "CREATE_COMPLETE");
|
||||
hold(stack, alias, url, fn);
|
||||
|
||||
service.deleteStackResources(stack, REGION, ACCOUNT);
|
||||
|
||||
InOrder deletes = inOrder(provisioner);
|
||||
deletes.verify(provisioner).delete(url, REGION);
|
||||
deletes.verify(provisioner).delete(alias, REGION);
|
||||
}
|
||||
|
||||
/** A cluster's capacity provider associations take the cluster's name as their id and go first. */
|
||||
@Test
|
||||
void deleteStack_deletesLeftoverCapacityProviderAssociationsBeforeTheirCluster() {
|
||||
Stack stack = leftoverStack("delete-leftover-associations", "{\"Cluster\": {\"Type\": \"AWS::ECS::Cluster\"}}");
|
||||
StackResource associations = resource("Associations", "cluster-1",
|
||||
"AWS::ECS::ClusterCapacityProviderAssociations", "UPDATE_COMPLETE");
|
||||
StackResource cluster = resource("Cluster", "cluster-1", "AWS::ECS::Cluster", "CREATE_COMPLETE");
|
||||
cluster.getAttributes().put("Arn", "arn:aws:ecs:us-east-1:000000000000:cluster/cluster-1");
|
||||
hold(stack, associations, cluster);
|
||||
|
||||
service.deleteStackResources(stack, REGION, ACCOUNT);
|
||||
|
||||
InOrder deletes = inOrder(provisioner);
|
||||
deletes.verify(provisioner).delete(associations, REGION);
|
||||
deletes.verify(provisioner).delete(cluster, REGION);
|
||||
}
|
||||
|
||||
/** A leftover recorded without a type, as old state may be, costs the other leftovers nothing. */
|
||||
@Test
|
||||
void deleteStack_aLeftoverWithNoTypeKeepsTheOthersOrdered() {
|
||||
Stack stack = leftoverStack("delete-leftover-untyped", "{\"Vpc\": {\"Type\": \"AWS::EC2::VPC\"}}");
|
||||
StackResource subnet = resource("Subnet", "subnet-1", "AWS::EC2::Subnet", "UPDATE_COMPLETE");
|
||||
subnet.getAttributes().put("VpcId", "vpc-1");
|
||||
StackResource vpc = resource("Vpc", "vpc-1", "AWS::EC2::VPC", "CREATE_COMPLETE");
|
||||
StackResource untyped = resource("Legacy", "legacy-1", null, "UPDATE_COMPLETE");
|
||||
hold(stack, subnet, vpc, untyped);
|
||||
|
||||
service.deleteStackResources(stack, REGION, ACCOUNT);
|
||||
|
||||
InOrder deletes = inOrder(provisioner);
|
||||
deletes.verify(provisioner).delete(subnet, REGION);
|
||||
deletes.verify(provisioner).delete(vpc, REGION);
|
||||
}
|
||||
|
||||
/** A leftover bucket policy recorded before its leftover bucket still goes first. */
|
||||
@Test
|
||||
void deleteStack_deletesALeftoverBucketPolicyRecordedFirstBeforeItsBucket() {
|
||||
Stack stack = leftoverStack("delete-leftover-policy-first", "{\"Queue\": {\"Type\": \"AWS::SQS::Queue\"}}");
|
||||
StackResource queue = resource("Queue", "queue-1", "AWS::SQS::Queue", "CREATE_COMPLETE");
|
||||
StackResource policy = resource("Policy", "bucket-1", "AWS::S3::BucketPolicy", "UPDATE_COMPLETE");
|
||||
StackResource bucket = resource("Bucket", "bucket-1", "AWS::S3::Bucket", "UPDATE_COMPLETE");
|
||||
bucket.getAttributes().put("BucketName", "bucket-1");
|
||||
hold(stack, queue, policy, bucket);
|
||||
|
||||
service.deleteStackResources(stack, REGION, ACCOUNT);
|
||||
|
||||
InOrder deletes = inOrder(provisioner);
|
||||
deletes.verify(provisioner).delete(policy, REGION);
|
||||
deletes.verify(provisioner).delete(bucket, REGION);
|
||||
}
|
||||
|
||||
/**
|
||||
* A WAF web ACL's id is its own name, id and scope joined by {@code |}, so its first part names
|
||||
* no parent: a leftover ACL is not ordered after a leftover bucket of that name, and the two keep
|
||||
* their reverse creation order.
|
||||
*/
|
||||
@Test
|
||||
void deleteStack_infersNoLeftoverOrderFromTheNameAWebAclsIdStartsWith() {
|
||||
Stack stack = leftoverStack("delete-leftover-web-acl", "{\"Queue\": {\"Type\": \"AWS::SQS::Queue\"}}");
|
||||
StackResource queue = resource("Queue", "queue-1", "AWS::SQS::Queue", "CREATE_COMPLETE");
|
||||
StackResource acl = resource("Acl", "shared|a1b2c3|REGIONAL", "AWS::WAFv2::WebACL", "UPDATE_COMPLETE");
|
||||
acl.getAttributes().put("Id", "a1b2c3");
|
||||
StackResource bucket = resource("Bucket", "shared", "AWS::S3::Bucket", "UPDATE_COMPLETE");
|
||||
hold(stack, queue, acl, bucket);
|
||||
|
||||
service.deleteStackResources(stack, REGION, ACCOUNT);
|
||||
|
||||
InOrder deletes = inOrder(provisioner);
|
||||
deletes.verify(provisioner).delete(bucket, REGION);
|
||||
deletes.verify(provisioner).delete(acl, REGION);
|
||||
}
|
||||
|
||||
/**
|
||||
* A leftover whose physical id extends another's, such as {@code parent-1/child-1}, belongs to
|
||||
* that resource and goes before it, whatever order the two were recorded in.
|
||||
*/
|
||||
@Test
|
||||
void deleteStack_deletesALeftoverWhoseIdExtendsAnothersBeforeIt() {
|
||||
Stack stack = leftoverStack("delete-leftover-derived", "{\"Queue\": {\"Type\": \"AWS::SQS::Queue\"}}");
|
||||
StackResource queue = resource("Queue", "queue-1", "AWS::SQS::Queue", "CREATE_COMPLETE");
|
||||
StackResource child = resource("Child", "parent-1/child-1", "AWS::Test::Child", "UPDATE_COMPLETE");
|
||||
StackResource parent = resource("Parent", "parent-1", "AWS::Test::Parent", "UPDATE_COMPLETE");
|
||||
hold(stack, queue, child, parent);
|
||||
|
||||
service.deleteStackResources(stack, REGION, ACCOUNT);
|
||||
|
||||
InOrder deletes = inOrder(provisioner);
|
||||
deletes.verify(provisioner).delete(child, REGION);
|
||||
deletes.verify(provisioner).delete(parent, REGION);
|
||||
}
|
||||
|
||||
/**
|
||||
* A long chain of leftovers, each naming the next and recorded first link first, is ordered
|
||||
* without recursion: on a thread with a small stack the walk still completes, first link first,
|
||||
* instead of overflowing.
|
||||
*/
|
||||
@Test
|
||||
void deleteStack_ordersALongLeftoverChainWithoutOverflowingTheStack() throws Exception {
|
||||
int length = 10_000;
|
||||
Stack stack = leftoverStack("delete-leftover-chain-long", "{\"Queue\": {\"Type\": \"AWS::SQS::Queue\"}}");
|
||||
StackResource[] chain = new StackResource[length];
|
||||
for (int i = 0; i < length; i++) {
|
||||
chain[i] = resource("Link" + i, "link-" + i, "AWS::Test::Link", "UPDATE_COMPLETE");
|
||||
if (i + 1 < length) {
|
||||
chain[i].getAttributes().put("NextId", "link-" + (i + 1));
|
||||
}
|
||||
stack.getResources().put(chain[i].getLogicalId(), chain[i]);
|
||||
}
|
||||
hold(stack);
|
||||
AtomicReference<Throwable> failure = new AtomicReference<>();
|
||||
Thread worker = new Thread(null, () -> {
|
||||
try {
|
||||
service.deleteStackResources(stack, REGION, ACCOUNT);
|
||||
} catch (Throwable t) {
|
||||
failure.set(t);
|
||||
}
|
||||
}, "small-stack", 256 * 1024);
|
||||
worker.start();
|
||||
worker.join(60_000);
|
||||
|
||||
assertFalse(worker.isAlive(), "the walk did not finish");
|
||||
|
||||
assertNull(failure.get(), () -> String.valueOf(failure.get()));
|
||||
InOrder deletes = inOrder(provisioner);
|
||||
deletes.verify(provisioner).delete(chain[0], REGION);
|
||||
deletes.verify(provisioner).delete(chain[length - 1], REGION);
|
||||
}
|
||||
|
||||
private static Stack leftoverStack(String name, String resources) {
|
||||
Stack stack = new Stack();
|
||||
stack.setStackName(name);
|
||||
stack.setStackId("stack-id");
|
||||
stack.setRegion(REGION);
|
||||
stack.setStatus("UPDATE_ROLLBACK_COMPLETE");
|
||||
stack.setTemplateBody("{\"Resources\": " + resources + "}");
|
||||
return stack;
|
||||
}
|
||||
|
||||
private void hold(Stack stack, StackResource... resources) {
|
||||
for (StackResource resource : resources) {
|
||||
stack.getResources().put(resource.getLogicalId(), resource);
|
||||
}
|
||||
when(provisioner.completeDeleteCleanup(any())).thenReturn(UpdateCleanupResult.notApplicable());
|
||||
}
|
||||
|
||||
/** The resources a stack delete reached, in order, as its DELETE_IN_PROGRESS events name them. */
|
||||
private static List<String> deletesInProgress(Stack stack) {
|
||||
return stack.getEvents().stream()
|
||||
.filter(event -> "DELETE_IN_PROGRESS".equals(event.getResourceStatus()))
|
||||
.map(StackEvent::getLogicalResourceId)
|
||||
.toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* A leftover may name another leftover: a VPC an update added and a subnet in it, both left by
|
||||
* a failed rollback. The subnet goes before its VPC, which names only itself.
|
||||
@@ -1263,6 +1840,24 @@ class CloudFormationServiceRollbackTest {
|
||||
return resource;
|
||||
}
|
||||
|
||||
/**
|
||||
* A provisioner of {@code type} built without its dependencies: only what it says of its types,
|
||||
* its resource types and the id hooks, is called on it.
|
||||
*/
|
||||
private static <T extends CfnResourceProvisioner> T real(Class<T> type) {
|
||||
return mock(type, CALLS_REAL_METHODS);
|
||||
}
|
||||
|
||||
/**
|
||||
* A provisioner that serves {@code type}, for routing through a real registry, and answers the
|
||||
* interface's own defaults as a provisioner that overrides none of them does.
|
||||
*/
|
||||
private static CfnResourceProvisioner serving(String type) {
|
||||
CfnResourceProvisioner serving = mock(CfnResourceProvisioner.class, CALLS_REAL_METHODS);
|
||||
doReturn(Set.of(type)).when(serving).resourceTypes();
|
||||
return serving;
|
||||
}
|
||||
|
||||
/** A service over the shared provisioner that reads the time from {@code clock}. */
|
||||
private CloudFormationService serviceReading(Clock clock) {
|
||||
RegionResolver regionResolver = mock(RegionResolver.class);
|
||||
|
||||
+76
@@ -6,6 +6,8 @@ import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
@@ -13,8 +15,10 @@ import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.CALLS_REAL_METHODS;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
@@ -35,6 +39,64 @@ class CfnResourceDispatcherTest {
|
||||
private final CfnResourceDispatcher dispatcher =
|
||||
new CfnResourceDispatcher(mapper, registry, dynamicReferences, null);
|
||||
|
||||
/**
|
||||
* A type the registry routes to the generic custom-resource handler is a custom resource: the
|
||||
* handler's own type and an unregistered {@code Custom::} type. An exactly registered
|
||||
* {@code Custom::} type with its own provisioner, any other type, a missing type, and every type
|
||||
* of a registry without the handler, are not.
|
||||
*/
|
||||
@Test
|
||||
void onlyTypesRoutedToTheCustomResourceHandlerAreCustomResources() {
|
||||
CfnResourceDispatcher routed = new CfnResourceDispatcher(mapper, new CloudFormationResourceRegistry(
|
||||
List.of(serving("AWS::CloudFormation::CustomResource"), serving("Custom::DynamoDBReplica"),
|
||||
serving(TYPE))), dynamicReferences, null);
|
||||
CfnResourceDispatcher withoutHandler = new CfnResourceDispatcher(mapper,
|
||||
new CloudFormationResourceRegistry(List.of(serving(TYPE))), dynamicReferences, null);
|
||||
|
||||
assertTrue(routed.isCustomResourceType("AWS::CloudFormation::CustomResource"));
|
||||
assertTrue(routed.isCustomResourceType("Custom::Namer"));
|
||||
assertFalse(routed.isCustomResourceType("Custom::DynamoDBReplica"));
|
||||
assertFalse(routed.isCustomResourceType(TYPE));
|
||||
assertFalse(routed.isCustomResourceType(null));
|
||||
assertFalse(withoutHandler.isCustomResourceType("Custom::Namer"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Each provisioner says how its own types' physical ids relate to a parent's: a bucket policy,
|
||||
* secret target attachment, function URL and capacity provider associations take their
|
||||
* parent's id; a web ACL, IP set and custom action type id names no parent. Every other type,
|
||||
* a missing type and a type nothing serves keep the defaults.
|
||||
*/
|
||||
@Test
|
||||
void provisionersSayHowTheirIdsRelateToAParent() {
|
||||
CfnResourceDispatcher routed = new CfnResourceDispatcher(mapper, new CloudFormationResourceRegistry(
|
||||
List.of(real(S3CfnProvisioner.class), real(SecretTargetAttachmentCfnProvisioner.class),
|
||||
real(LambdaAddressingCfnProvisioner.class), real(EcsCapacityCfnProvisioner.class),
|
||||
real(WafV2CfnProvisioner.class), real(CodePipelineCfnProvisioner.class),
|
||||
serving("AWS::CloudFormation::CustomResource"))),
|
||||
dynamicReferences, null);
|
||||
|
||||
for (String type : List.of("AWS::S3::BucketPolicy", "AWS::SecretsManager::SecretTargetAttachment",
|
||||
"AWS::Lambda::Url", "AWS::ECS::ClusterCapacityProviderAssociations")) {
|
||||
assertTrue(routed.takesParentPhysicalId(type), type);
|
||||
assertTrue(routed.idPrefixCanNameParent(type), type);
|
||||
}
|
||||
for (String type : List.of("AWS::WAFv2::WebACL", "AWS::WAFv2::IPSet", "AWS::CodePipeline::CustomActionType")) {
|
||||
assertFalse(routed.takesParentPhysicalId(type), type);
|
||||
assertFalse(routed.idPrefixCanNameParent(type), type);
|
||||
}
|
||||
for (String type : Arrays.asList("AWS::S3::Bucket", "AWS::Lambda::Permission", "AWS::ECS::CapacityProvider",
|
||||
"AWS::WAFv2::WebACLAssociation", "AWS::CodePipeline::Pipeline", "Custom::Namer", TYPE, null)) {
|
||||
assertFalse(routed.takesParentPhysicalId(type), String.valueOf(type));
|
||||
assertTrue(routed.idPrefixCanNameParent(type), String.valueOf(type));
|
||||
}
|
||||
}
|
||||
|
||||
/** A provisioner built without its dependencies: only what it says of its types is called on it. */
|
||||
private static <T extends CfnResourceProvisioner> T real(Class<T> type) {
|
||||
return mock(type, CALLS_REAL_METHODS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void provisionStandaloneResolvesDynamicReferencesThroughTheService() {
|
||||
// Cloud Control desired state can carry {{resolve:...}}; the throwaway engine must reach
|
||||
@@ -164,6 +226,20 @@ class CfnResourceDispatcherTest {
|
||||
"thing-1".equals(r.getPhysicalId()) && "r".equals(r.getAttributes().get("Role"))), any());
|
||||
}
|
||||
|
||||
/** A provisioner that serves {@code type} and does nothing, for routing through a real registry. */
|
||||
private static CfnResourceProvisioner serving(String type) {
|
||||
return new CfnResourceProvisioner() {
|
||||
@Override
|
||||
public Set<String> resourceTypes() {
|
||||
return Set.of(type);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void provision(StackResource resource, JsonNode properties, ProvisionContext ctx) {
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static CfnResourceProvisioner provisioner(Provision body) {
|
||||
return new CfnResourceProvisioner() {
|
||||
@Override
|
||||
|
||||
Reference in new issue
Block a user