mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(cloudformation): provision ApiGateway::Account, AutoScaling::LifecycleHook, and EC2::FlowLog (#2003)
* feat(cloudformation): provision ApiGateway::Account, AutoScaling::LifecycleHook, and EC2::FlowLog Three small provisioners over existing services: Account records metadata (physical id only), LifecycleHook maps onto AutoScalingService.putLifecycleHook, FlowLog onto FlowLogService.createFlowLog (newly injected into the provisioner). Fixes #2002 * feat(cloudformation): per-service provisioners for ApiGateway::Account, AutoScaling::LifecycleHook, and EC2::FlowLog The three resource types land in the extracted provisioner structure rather than the switch in CloudFormationResourceProvisioner, one class per service: - ApiGatewayAccountCfnProvisioner writes CloudWatchRoleArn into the API Gateway account settings, so GET /account reflects what the template asked for instead of the resource being recorded as a bare physical id. - AutoScalingLifecycleHookCfnProvisioner puts the hook on its group and removes it again when the stack is deleted. - Ec2FlowLogCfnProvisioner creates the flow log and deletes it when the stack is deleted. Both deletes close the cleanup gaps raised in review: flow logs and lifecycle hooks no longer outlive their stack. The delete path only holds a physical id, and a hook's physical id is its name, so AutoScalingService gains deleteLifecycleHookByName to find the hook whichever group owns it, including groups that outlive the stack. API Gateway has no DeleteAccount operation and its account settings are regional rather than stack-owned, so that provisioner keeps the default no-op delete. CloudFormationResourceProvisioner is byte-identical to main again: no switch arms, no FlowLogService injection, and the two constructor-arg test edits are reverted. Tests: three isolated provisioner unit tests (one mocked service each) plus the integration test, extended to cover deletion of the hook and the flow log against a group created outside the stack. * fix(cloudformation): delete a lifecycle hook on its own group, not by name alone A lifecycle hook name is unique within an Auto Scaling group, not within a region, but the CloudFormation delete path only had the physical id — the hook name — so it removed every hook with that name in the region. Two groups using the same hook name meant deleting or rolling back either stack stopped the other group's lifecycle action. CfnResourceProvisioner gained a delete overload that receives the whole StackResource, defaulting to the existing id-only form, and the dispatcher calls it for extracted provisioners. It sits after the EKS Nodegroup and IAM policy special cases so extracting one of those later cannot bypass them. The hook provisioner records its AutoScalingGroupName at create time and deletes through the group-scoped API. Resources provisioned before that still fall back to the by-name form: leaving the hook behind is worse, since it can sit on a group that outlives the stack. * fix(cloudformation): a stack update reuses its flow log and lifecycle hook Ec2FlowLogCfnProvisioner called createFlowLog unconditionally, so every UpdateStack created a second flow log and orphaned the first. The orphan then outlived the stack, since delete only knows the id recorded last. It now reuses the log this stack already made and creates only when that one is absent, on a first execution or after removal out of band. AutoScalingLifecycleHookCfnProvisioner had the same shape, but only when LifecycleHookName is omitted: a freshly generated name each update left the previous hook on the group, still firing, with nothing referencing it. An unnamed hook now keeps the name its first execution generated. A declared name needed no change, since putLifecycleHook is idempotent on it. Both follow EcsCapacityCfnProvisioner. Neither surfaced in CI because no test here ran an UpdateStack, so each provisioner now has one that does. * fix(cloudformation): a createOnly change on a flow log or lifecycle hook is reported Both provisioners reuse the resource the stack already made, so a change to a property AWS treats as createOnly was being absorbed instead of surfaced. The flow log reported the stack complete while DescribeFlowLogs kept serving the previous ResourceId, TrafficType, LogDestination, LogFormat or aggregation interval. The lifecycle hook was worse, since changing LifecycleHookName or AutoScalingGroupName created the new hook and overwrote the id delete uses, leaving the previous hook on its group and still firing. Both now report an unsupported replacement, matching how EcsCapacityCfnProvisioner treats a changed Name. A property the template stops declaring, or one the stored record never captured, is left alone rather than read as a change. * docs(cloudformation): list ApiGateway Account, LifecycleHook and FlowLog in the resource-type table * fix(cloudformation): dropping a flow log's createOnly property is a change rejectIfChanged returned early whenever the template supplied no value, so removing a previously explicit LogFormat or MaxAggregationInterval skipped validation entirely and the stack reported complete while DescribeFlowLogs kept serving the old one. An absent stored value still means leave it alone, since that is not evidence of a different one, but an absent requested value is now compared rather than skipped. MaxAggregationInterval compares against its documented default of 600 when the template omits it, which is the value a create would have used. * fix(cloudformation): a flow log's createOnly comparison uses effective values Removing the early return on a blank request fixed the dropped-property case and broke two others. createFlowLog defaults ResourceType, TrafficType and LogDestinationType, so re-applying an unchanged template compared null against a stored default and failed a no-op update, while adding a property to a log that never had one still returned early on the stored null and was ignored. Both sides are now the effective value, defaulting the requested side exactly as createFlowLog does, so add, drop and change all read as changes and a re-apply stays a no-op. The test helper stamps the same three defaults, since a stub without them is not a flow log this provisioner could have created.
This commit is contained in:
1 parent
9fda5f5919
commit
9280369b64
11 files changed
+1086
-3
No files matched your search
+284
@@ -0,0 +1,284 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.function.BooleanSupplier;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* End-to-end check for the small metadata provisioners (issue #2002):
|
||||
* ApiGateway::Account records the CloudWatch role, AutoScaling::LifecycleHook lands in
|
||||
* AutoScalingService, EC2::FlowLog lands in FlowLogService — and both the hook and the flow log
|
||||
* go away again when the stack is deleted. Docker-free.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class CloudFormationSmallMetadataIntegrationTest {
|
||||
|
||||
private static final String CFN_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request";
|
||||
private static final String EC2_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request";
|
||||
private static final String ASG_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/autoscaling/aws4_request";
|
||||
private static final String APIGW_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/apigateway/aws4_request";
|
||||
|
||||
private static final Pattern FLOW_LOG_ID =
|
||||
Pattern.compile("<OutputValue>(fl-[0-9a-f]+)</OutputValue>");
|
||||
|
||||
@Test
|
||||
void accountHookAndFlowLogProvision() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String stackName = "cfn-smallmeta-" + suffix;
|
||||
String asgName = "meta-asg-" + suffix;
|
||||
String hookName = "meta-hook-" + suffix;
|
||||
String roleArn = "arn:aws:iam::000000000000:role/apigw-cw-" + suffix;
|
||||
|
||||
String template = """
|
||||
{
|
||||
"Resources": {
|
||||
"Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.80.0.0/16"}},
|
||||
"Subnet": {
|
||||
"Type": "AWS::EC2::Subnet",
|
||||
"Properties": {"VpcId": {"Ref": "Vpc"}, "CidrBlock": "10.80.1.0/24"}
|
||||
},
|
||||
"Lc": {
|
||||
"Type": "AWS::AutoScaling::LaunchConfiguration",
|
||||
"Properties": {"ImageId": "ami-11111111", "InstanceType": "t3.micro"}
|
||||
},
|
||||
"Asg": {
|
||||
"Type": "AWS::AutoScaling::AutoScalingGroup",
|
||||
"Properties": {
|
||||
"AutoScalingGroupName": "%s",
|
||||
"MinSize": "0", "MaxSize": "0", "DesiredCapacity": "0",
|
||||
"LaunchConfigurationName": {"Ref": "Lc"},
|
||||
"VPCZoneIdentifier": [{"Ref": "Subnet"}]
|
||||
}
|
||||
},
|
||||
"Hook": {
|
||||
"Type": "AWS::AutoScaling::LifecycleHook",
|
||||
"Properties": {
|
||||
"AutoScalingGroupName": {"Ref": "Asg"},
|
||||
"LifecycleHookName": "%s",
|
||||
"LifecycleTransition": "autoscaling:EC2_INSTANCE_TERMINATING"
|
||||
}
|
||||
},
|
||||
"ApiAccount": {
|
||||
"Type": "AWS::ApiGateway::Account",
|
||||
"Properties": {"CloudWatchRoleArn": "%s"}
|
||||
},
|
||||
"Flow": {
|
||||
"Type": "AWS::EC2::FlowLog",
|
||||
"Properties": {
|
||||
"ResourceId": {"Ref": "Vpc"},
|
||||
"ResourceType": "VPC",
|
||||
"TrafficType": "ALL",
|
||||
"LogDestinationType": "cloud-watch-logs",
|
||||
"LogDestination": "arn:aws:logs:us-east-1:000000000000:log-group:/flow/meta"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Outputs": {"FlowId": {"Value": {"Ref": "Flow"}}}
|
||||
}
|
||||
""".formatted(asgName, hookName, roleArn);
|
||||
|
||||
createStack(stackName, template);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", stackName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"))
|
||||
.body(containsString("<OutputValue>fl-"));
|
||||
|
||||
// The hook is live in AutoScalingService.
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", ASG_AUTH)
|
||||
.formParam("Action", "DescribeLifecycleHooks")
|
||||
.formParam("AutoScalingGroupName", asgName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString(hookName));
|
||||
|
||||
// The flow log is live in FlowLogService.
|
||||
given()
|
||||
.formParam("Action", "DescribeFlowLogs")
|
||||
.header("Authorization", EC2_AUTH)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("/flow/meta"));
|
||||
|
||||
// The account-level CloudWatch role reached the API Gateway account settings.
|
||||
given()
|
||||
.header("Authorization", APIGW_AUTH)
|
||||
.when()
|
||||
.get("/account")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("cloudwatchRoleArn", equalTo(roleArn));
|
||||
}
|
||||
|
||||
/**
|
||||
* Deleting the stack must take the hook and the flow log with it. The group the hook hangs off
|
||||
* is created outside the stack so it survives the delete and DescribeLifecycleHooks still
|
||||
* answers — the hook itself has to be gone.
|
||||
*/
|
||||
@Test
|
||||
void stackDeletionRemovesHookAndFlowLog() throws InterruptedException {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String stackName = "cfn-smallmeta-del-" + suffix;
|
||||
String asgName = "meta-survivor-asg-" + suffix;
|
||||
String lcName = "meta-survivor-lc-" + suffix;
|
||||
String hookName = "meta-del-hook-" + suffix;
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", ASG_AUTH)
|
||||
.formParam("Action", "CreateLaunchConfiguration")
|
||||
.formParam("LaunchConfigurationName", lcName)
|
||||
.formParam("ImageId", "ami-11111111")
|
||||
.formParam("InstanceType", "t3.micro")
|
||||
.when().post("/").then().statusCode(200);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", ASG_AUTH)
|
||||
.formParam("Action", "CreateAutoScalingGroup")
|
||||
.formParam("AutoScalingGroupName", asgName)
|
||||
.formParam("LaunchConfigurationName", lcName)
|
||||
.formParam("MinSize", "0")
|
||||
.formParam("MaxSize", "0")
|
||||
.formParam("DesiredCapacity", "0")
|
||||
.formParam("AvailabilityZones.member.1", "us-east-1a")
|
||||
.when().post("/").then().statusCode(200);
|
||||
|
||||
String template = """
|
||||
{
|
||||
"Resources": {
|
||||
"Hook": {
|
||||
"Type": "AWS::AutoScaling::LifecycleHook",
|
||||
"Properties": {
|
||||
"AutoScalingGroupName": "%s",
|
||||
"LifecycleHookName": "%s",
|
||||
"LifecycleTransition": "autoscaling:EC2_INSTANCE_LAUNCHING",
|
||||
"HeartbeatTimeout": 120,
|
||||
"DefaultResult": "CONTINUE"
|
||||
}
|
||||
},
|
||||
"Flow": {
|
||||
"Type": "AWS::EC2::FlowLog",
|
||||
"Properties": {
|
||||
"ResourceId": "vpc-0000%s",
|
||||
"ResourceType": "VPC",
|
||||
"TrafficType": "REJECT",
|
||||
"LogDestinationType": "cloud-watch-logs",
|
||||
"LogDestination": "arn:aws:logs:us-east-1:000000000000:log-group:/flow/del"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Outputs": {"FlowId": {"Value": {"Ref": "Flow"}}}
|
||||
}
|
||||
""".formatted(asgName, hookName, suffix);
|
||||
|
||||
createStack(stackName, template);
|
||||
|
||||
String describe = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", stackName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"))
|
||||
.extract().asString();
|
||||
|
||||
Matcher matcher = FLOW_LOG_ID.matcher(describe);
|
||||
assertTrue(matcher.find(), "stack outputs should carry the flow log id: " + describe);
|
||||
String flowLogId = matcher.group(1);
|
||||
|
||||
assertTrue(describeFlowLogs().contains(flowLogId), "flow log should exist after create");
|
||||
assertTrue(describeHooks(asgName).contains(hookName), "hook should exist after create");
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DeleteStack")
|
||||
.formParam("StackName", stackName)
|
||||
.when().post("/").then().statusCode(200);
|
||||
|
||||
awaitGone(() -> !describeFlowLogs().contains(flowLogId),
|
||||
"flow log " + flowLogId + " still present after DeleteStack");
|
||||
awaitGone(() -> !describeHooks(asgName).contains(hookName),
|
||||
"lifecycle hook " + hookName + " still present after DeleteStack");
|
||||
|
||||
// Only the hook was stack-owned: the externally created group is untouched.
|
||||
assertFalse(describeHooks(asgName).contains(hookName));
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", ASG_AUTH)
|
||||
.formParam("Action", "DescribeAutoScalingGroups")
|
||||
.formParam("AutoScalingGroupNames.member.1", asgName)
|
||||
.when().post("/").then().statusCode(200).body(containsString(asgName));
|
||||
}
|
||||
|
||||
private static void createStack(String stackName, String template) {
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", template)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
private static String describeFlowLogs() {
|
||||
return given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", EC2_AUTH)
|
||||
.formParam("Action", "DescribeFlowLogs")
|
||||
.when().post("/").then().statusCode(200).extract().asString();
|
||||
}
|
||||
|
||||
private static String describeHooks(String asgName) {
|
||||
return given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", ASG_AUTH)
|
||||
.formParam("Action", "DescribeLifecycleHooks")
|
||||
.formParam("AutoScalingGroupName", asgName)
|
||||
.when().post("/").then().statusCode(200).extract().asString();
|
||||
}
|
||||
|
||||
/** DeleteStack runs asynchronously, so poll until the resource is gone or time out. */
|
||||
private static void awaitGone(BooleanSupplier gone, String message) throws InterruptedException {
|
||||
for (int i = 0; i < 100; i++) {
|
||||
if (gone.getAsBoolean()) {
|
||||
return;
|
||||
}
|
||||
Thread.sleep(50);
|
||||
}
|
||||
throw new AssertionError(message);
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
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.services.apigateway.ApiGatewayService;
|
||||
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** The API Gateway account CFN provisioner in isolation. */
|
||||
class ApiGatewayAccountCfnProvisionerTest {
|
||||
|
||||
private final ApiGatewayService apiGateway = mock(ApiGatewayService.class);
|
||||
private final ApiGatewayAccountCfnProvisioner provisioner =
|
||||
new ApiGatewayAccountCfnProvisioner(apiGateway);
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
private ProvisionContext ctx() {
|
||||
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
|
||||
when(engine.resolve(any())).thenAnswer(inv -> {
|
||||
JsonNode node = inv.getArgument(0);
|
||||
return node == null ? null : node.asText();
|
||||
});
|
||||
return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack");
|
||||
}
|
||||
|
||||
private StackResource resource() {
|
||||
StackResource r = new StackResource();
|
||||
r.setLogicalId("ApiAccount");
|
||||
r.setResourceType("AWS::ApiGateway::Account");
|
||||
r.setAttributes(new HashMap<>());
|
||||
return r;
|
||||
}
|
||||
|
||||
@Test
|
||||
void cloudWatchRoleArnIsPatchedIntoTheAccount() {
|
||||
StackResource r = resource();
|
||||
String arn = "arn:aws:iam::000000000000:role/apigw-cw";
|
||||
|
||||
provisioner.provision(r, mapper.createObjectNode().put("CloudWatchRoleArn", arn), ctx());
|
||||
|
||||
verify(apiGateway).updateAccount("us-east-1", List.of(Map.of(
|
||||
"op", "replace", "path", "/cloudwatchRoleArn", "value", arn)));
|
||||
assertEquals("ApiAccount", r.getPhysicalId());
|
||||
assertEquals("ApiAccount", r.getAttributes().get("Id"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void accountWithoutRoleArnTouchesNothing() {
|
||||
StackResource r = resource();
|
||||
|
||||
provisioner.provision(r, mapper.createObjectNode(), ctx());
|
||||
|
||||
assertEquals("ApiAccount", r.getPhysicalId());
|
||||
verifyNoInteractions(apiGateway);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteLeavesAccountSettingsAlone() {
|
||||
provisioner.delete("AWS::ApiGateway::Account", "ApiAccount", "us-east-1");
|
||||
verifyNoInteractions(apiGateway);
|
||||
}
|
||||
}
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
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.AwsException;
|
||||
import io.github.hectorvent.floci.services.autoscaling.AutoScalingService;
|
||||
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
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;
|
||||
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.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** The Auto Scaling lifecycle-hook CFN provisioner in isolation. */
|
||||
class AutoScalingLifecycleHookCfnProvisionerTest {
|
||||
|
||||
private final AutoScalingService autoScaling = mock(AutoScalingService.class);
|
||||
private final AutoScalingLifecycleHookCfnProvisioner provisioner =
|
||||
new AutoScalingLifecycleHookCfnProvisioner(autoScaling);
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
private ProvisionContext ctx() {
|
||||
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
|
||||
when(engine.resolve(any())).thenAnswer(inv -> {
|
||||
JsonNode node = inv.getArgument(0);
|
||||
return node == null ? null : node.asText();
|
||||
});
|
||||
return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack");
|
||||
}
|
||||
|
||||
private StackResource resource() {
|
||||
StackResource r = new StackResource();
|
||||
r.setLogicalId("Hook");
|
||||
r.setResourceType("AWS::AutoScaling::LifecycleHook");
|
||||
r.setAttributes(new HashMap<>());
|
||||
return r;
|
||||
}
|
||||
|
||||
@Test
|
||||
void hookIsPutOnTheGroupAndNamesThePhysicalId() {
|
||||
StackResource r = resource();
|
||||
ObjectNode props = mapper.createObjectNode()
|
||||
.put("AutoScalingGroupName", "the-asg")
|
||||
.put("LifecycleHookName", "the-hook")
|
||||
.put("LifecycleTransition", "autoscaling:EC2_INSTANCE_TERMINATING")
|
||||
.put("NotificationTargetARN", "arn:aws:sns:us-east-1:000000000000:drain")
|
||||
.put("RoleARN", "arn:aws:iam::000000000000:role/asg-hook")
|
||||
.put("NotificationMetadata", "drain-me")
|
||||
.put("HeartbeatTimeout", 120)
|
||||
.put("DefaultResult", "CONTINUE");
|
||||
|
||||
provisioner.provision(r, props, ctx());
|
||||
|
||||
verify(autoScaling).putLifecycleHook("us-east-1", "the-asg", "the-hook",
|
||||
"autoscaling:EC2_INSTANCE_TERMINATING",
|
||||
"arn:aws:sns:us-east-1:000000000000:drain",
|
||||
"arn:aws:iam::000000000000:role/asg-hook",
|
||||
"drain-me", 120, "CONTINUE");
|
||||
assertEquals("the-hook", r.getPhysicalId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void hookWithoutNameGetsAGeneratedName() {
|
||||
StackResource r = resource();
|
||||
ObjectNode props = mapper.createObjectNode().put("AutoScalingGroupName", "the-asg");
|
||||
|
||||
provisioner.provision(r, props, ctx());
|
||||
|
||||
// <stack>-<logicalId>-<suffix>
|
||||
assertEquals("my-stack-Hook", r.getPhysicalId().replaceAll("-[0-9a-f]{12}$", ""));
|
||||
assertTrue(r.getPhysicalId().length() <= 255);
|
||||
verify(autoScaling).putLifecycleHook("us-east-1", "the-asg", r.getPhysicalId(),
|
||||
null, null, null, null, null, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnnamedHookKeepsTheNameItsFirstExecutionGenerated() {
|
||||
StackResource r = resource();
|
||||
ObjectNode props = mapper.createObjectNode().put("AutoScalingGroupName", "the-asg");
|
||||
|
||||
provisioner.provision(r, props, ctx());
|
||||
String firstName = r.getPhysicalId();
|
||||
provisioner.provision(r, props, ctx());
|
||||
|
||||
// A fresh name on the second pass leaves the first hook on the group, still firing,
|
||||
// with nothing in the stack referencing it.
|
||||
assertEquals(firstName, r.getPhysicalId());
|
||||
verify(autoScaling, times(2)).putLifecycleHook("us-east-1", "the-asg", firstName,
|
||||
null, null, null, null, null, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void changingADeclaredHookNameReportsAnUnsupportedReplacement() {
|
||||
StackResource r = resource();
|
||||
provisioner.provision(r, mapper.createObjectNode()
|
||||
.put("AutoScalingGroupName", "the-asg")
|
||||
.put("LifecycleHookName", "first-hook"), ctx());
|
||||
|
||||
// Going through would put second-hook on the group and overwrite the id delete uses,
|
||||
// leaving first-hook behind and still firing.
|
||||
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r,
|
||||
mapper.createObjectNode()
|
||||
.put("AutoScalingGroupName", "the-asg")
|
||||
.put("LifecycleHookName", "second-hook"), ctx()));
|
||||
assertEquals("ValidationError", e.getErrorCode());
|
||||
assertEquals("first-hook", r.getPhysicalId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void movingAHookToAnotherGroupReportsAnUnsupportedReplacement() {
|
||||
StackResource r = resource();
|
||||
provisioner.provision(r, mapper.createObjectNode()
|
||||
.put("AutoScalingGroupName", "first-asg")
|
||||
.put("LifecycleHookName", "the-hook"), ctx());
|
||||
|
||||
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r,
|
||||
mapper.createObjectNode()
|
||||
.put("AutoScalingGroupName", "second-asg")
|
||||
.put("LifecycleHookName", "the-hook"), ctx()));
|
||||
assertEquals("ValidationError", e.getErrorCode());
|
||||
assertEquals("first-asg", r.getAttributes().get("AutoScalingGroupName"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void provisionRecordsTheOwningGroupForDelete() {
|
||||
StackResource r = resource();
|
||||
ObjectNode props = mapper.createObjectNode()
|
||||
.put("AutoScalingGroupName", "the-asg")
|
||||
.put("LifecycleHookName", "the-hook");
|
||||
|
||||
provisioner.provision(r, props, ctx());
|
||||
|
||||
assertEquals("the-asg", r.getAttributes().get("AutoScalingGroupName"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteScopesToTheOwningGroup() {
|
||||
StackResource r = resource();
|
||||
provisioner.provision(r, mapper.createObjectNode()
|
||||
.put("AutoScalingGroupName", "the-asg")
|
||||
.put("LifecycleHookName", "the-hook"), ctx());
|
||||
|
||||
provisioner.delete(r, "us-east-1");
|
||||
|
||||
// Hook names are unique only within a group; the by-name form would also remove an
|
||||
// identically named hook belonging to an unrelated Auto Scaling group.
|
||||
verify(autoScaling).deleteLifecycleHook("us-east-1", "the-asg", "the-hook");
|
||||
verify(autoScaling, never()).deleteLifecycleHookByName(anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteFallsBackToTheNameWhenNoGroupWasRecorded() {
|
||||
StackResource r = resource();
|
||||
r.setPhysicalId("the-hook");
|
||||
|
||||
provisioner.delete(r, "us-east-1");
|
||||
|
||||
verify(autoScaling).deleteLifecycleHookByName("us-east-1", "the-hook");
|
||||
verify(autoScaling, never()).deleteLifecycleHook(anyString(), anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteRemovesTheHookByName() {
|
||||
provisioner.delete("AWS::AutoScaling::LifecycleHook", "the-hook", "us-east-1");
|
||||
verify(autoScaling).deleteLifecycleHookByName("us-east-1", "the-hook");
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteWithoutPhysicalIdIsSkipped() {
|
||||
provisioner.delete("AWS::AutoScaling::LifecycleHook", null, "us-east-1");
|
||||
provisioner.delete("AWS::AutoScaling::LifecycleHook", " ", "us-east-1");
|
||||
verifyNoInteractions(autoScaling);
|
||||
}
|
||||
}
|
||||
+207
@@ -0,0 +1,207 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
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.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.ec2.FlowLogService;
|
||||
import io.github.hectorvent.floci.services.ec2.model.FlowLog;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** The EC2 flow-log CFN provisioner in isolation, with only FlowLogService mocked. */
|
||||
class Ec2FlowLogCfnProvisionerTest {
|
||||
|
||||
private final FlowLogService flowLogs = mock(FlowLogService.class);
|
||||
private final Ec2FlowLogCfnProvisioner provisioner = new Ec2FlowLogCfnProvisioner(flowLogs);
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
private ProvisionContext ctx() {
|
||||
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
|
||||
when(engine.resolve(any())).thenAnswer(inv -> {
|
||||
JsonNode node = inv.getArgument(0);
|
||||
return node == null ? null : node.asText();
|
||||
});
|
||||
return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack");
|
||||
}
|
||||
|
||||
private StackResource resource() {
|
||||
StackResource r = new StackResource();
|
||||
r.setLogicalId("Flow");
|
||||
r.setResourceType("AWS::EC2::FlowLog");
|
||||
r.setAttributes(new HashMap<>());
|
||||
return r;
|
||||
}
|
||||
|
||||
/** Shaped like something createFlowLog stored, which defaults these three when omitted. */
|
||||
private FlowLog flowLog(String id) {
|
||||
FlowLog fl = new FlowLog();
|
||||
fl.setFlowLogId(id);
|
||||
fl.setResourceType("VPC");
|
||||
fl.setTrafficType("ALL");
|
||||
fl.setLogDestinationType("s3");
|
||||
return fl;
|
||||
}
|
||||
|
||||
@Test
|
||||
void flowLogSetsPhysicalIdAndIdAttribute() {
|
||||
when(flowLogs.createFlowLog(eq("us-east-1"), eq("vpc-123"), eq("VPC"), eq("ALL"),
|
||||
eq("s3"), eq("arn:aws:s3:::flow-bucket"), eq("${srcaddr}"), eq(60)))
|
||||
.thenReturn(flowLog("fl-0abc"));
|
||||
StackResource r = resource();
|
||||
ObjectNode props = mapper.createObjectNode()
|
||||
.put("ResourceId", "vpc-123")
|
||||
.put("ResourceType", "VPC")
|
||||
.put("TrafficType", "ALL")
|
||||
.put("LogDestinationType", "s3")
|
||||
.put("LogDestination", "arn:aws:s3:::flow-bucket")
|
||||
.put("LogFormat", "${srcaddr}")
|
||||
.put("MaxAggregationInterval", 60);
|
||||
|
||||
provisioner.provision(r, props, ctx());
|
||||
|
||||
assertEquals("fl-0abc", r.getPhysicalId());
|
||||
assertEquals("fl-0abc", r.getAttributes().get("Id"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void omittedAggregationIntervalDefaultsToTenMinutes() {
|
||||
when(flowLogs.createFlowLog(anyString(), any(), any(), any(), any(), any(), any(), anyInt()))
|
||||
.thenReturn(flowLog("fl-0def"));
|
||||
|
||||
provisioner.provision(resource(), mapper.createObjectNode().put("ResourceId", "vpc-9"), ctx());
|
||||
|
||||
verify(flowLogs).createFlowLog("us-east-1", "vpc-9", null, null, null, null, null, 600);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateReusesTheFlowLogThisStackAlreadyCreated() {
|
||||
StackResource r = resource();
|
||||
r.setPhysicalId("fl-0abc");
|
||||
// Stamped with what a create from this template would have stored, so the re-apply is a
|
||||
// genuine no-op rather than reading as an added ResourceId.
|
||||
FlowLog existing = flowLog("fl-0abc");
|
||||
existing.setResourceId("vpc-123");
|
||||
when(flowLogs.describeFlowLogs("us-east-1", List.of("fl-0abc")))
|
||||
.thenReturn(List.of(existing));
|
||||
|
||||
provisioner.provision(r, mapper.createObjectNode().put("ResourceId", "vpc-123"), ctx());
|
||||
|
||||
// A second flow log here outlives the stack: delete only knows the id recorded last.
|
||||
verify(flowLogs, never()).createFlowLog(anyString(), any(), any(), any(), any(), any(), any(), anyInt());
|
||||
assertEquals("fl-0abc", r.getPhysicalId());
|
||||
assertEquals("fl-0abc", r.getAttributes().get("Id"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void changingACreateOnlyPropertyReportsAnUnsupportedReplacement() {
|
||||
StackResource r = resource();
|
||||
r.setPhysicalId("fl-0abc");
|
||||
FlowLog existing = flowLog("fl-0abc");
|
||||
existing.setResourceId("vpc-123");
|
||||
existing.setTrafficType("ALL");
|
||||
when(flowLogs.describeFlowLogs("us-east-1", List.of("fl-0abc"))).thenReturn(List.of(existing));
|
||||
|
||||
// Reusing regardless would report the stack complete while DescribeFlowLogs kept
|
||||
// serving ALL for a template that now asks for REJECT.
|
||||
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r,
|
||||
mapper.createObjectNode().put("ResourceId", "vpc-123").put("TrafficType", "REJECT"), ctx()));
|
||||
assertEquals("ValidationError", e.getErrorCode());
|
||||
verify(flowLogs, never()).createFlowLog(anyString(), any(), any(), any(), any(), any(), any(), anyInt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void droppingACreateOnlyPropertyReportsAnUnsupportedReplacement() {
|
||||
StackResource r = resource();
|
||||
r.setPhysicalId("fl-0abc");
|
||||
FlowLog existing = flowLog("fl-0abc");
|
||||
existing.setResourceId("vpc-123");
|
||||
existing.setLogFormat("${srcaddr}");
|
||||
existing.setMaxAggregationInterval(60);
|
||||
when(flowLogs.describeFlowLogs("us-east-1", List.of("fl-0abc"))).thenReturn(List.of(existing));
|
||||
|
||||
// Removing a property the template used to declare is as much a change as altering it.
|
||||
// Skipping the blank request left the stack complete while the log kept the old format.
|
||||
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r,
|
||||
mapper.createObjectNode().put("ResourceId", "vpc-123"), ctx()));
|
||||
assertEquals("ValidationError", e.getErrorCode());
|
||||
verify(flowLogs, never()).createFlowLog(anyString(), any(), any(), any(), any(), any(), any(), anyInt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void reapplyingATemplateThatOmitsDefaultedPropertiesIsANoOp() {
|
||||
// createFlowLog stores VPC, ALL and s3 when the template omits them, so a re-apply reads
|
||||
// null against those defaults. Comparing raw values made an unchanged stack update fail.
|
||||
StackResource r = resource();
|
||||
r.setPhysicalId("fl-0abc");
|
||||
FlowLog existing = flowLog("fl-0abc");
|
||||
existing.setResourceId("vpc-123");
|
||||
existing.setResourceType("VPC");
|
||||
existing.setTrafficType("ALL");
|
||||
existing.setLogDestinationType("s3");
|
||||
when(flowLogs.describeFlowLogs("us-east-1", List.of("fl-0abc"))).thenReturn(List.of(existing));
|
||||
|
||||
provisioner.provision(r, mapper.createObjectNode().put("ResourceId", "vpc-123"), ctx());
|
||||
|
||||
assertEquals("fl-0abc", r.getPhysicalId());
|
||||
verify(flowLogs, never()).createFlowLog(anyString(), any(), any(), any(), any(), any(), any(), anyInt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void addingAPropertyTheLogNeverHadReportsAnUnsupportedReplacement() {
|
||||
// The stored null used to short-circuit the comparison, so the new value was ignored and
|
||||
// the stack reported complete while the log kept no format at all.
|
||||
StackResource r = resource();
|
||||
r.setPhysicalId("fl-0abc");
|
||||
FlowLog existing = flowLog("fl-0abc");
|
||||
existing.setResourceId("vpc-123");
|
||||
when(flowLogs.describeFlowLogs("us-east-1", List.of("fl-0abc"))).thenReturn(List.of(existing));
|
||||
|
||||
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r,
|
||||
mapper.createObjectNode().put("ResourceId", "vpc-123").put("LogFormat", "${srcaddr}"), ctx()));
|
||||
assertEquals("ValidationError", e.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateRecreatesAFlowLogRemovedOutOfBand() {
|
||||
StackResource r = resource();
|
||||
r.setPhysicalId("fl-gone");
|
||||
when(flowLogs.describeFlowLogs("us-east-1", List.of("fl-gone"))).thenReturn(List.of());
|
||||
when(flowLogs.createFlowLog(anyString(), any(), any(), any(), any(), any(), any(), anyInt()))
|
||||
.thenReturn(flowLog("fl-new"));
|
||||
|
||||
provisioner.provision(r, mapper.createObjectNode().put("ResourceId", "vpc-123"), ctx());
|
||||
|
||||
assertEquals("fl-new", r.getPhysicalId());
|
||||
assertEquals("fl-new", r.getAttributes().get("Id"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteRemovesTheFlowLog() {
|
||||
provisioner.delete("AWS::EC2::FlowLog", "fl-0abc", "us-east-1");
|
||||
verify(flowLogs).deleteFlowLogs("us-east-1", List.of("fl-0abc"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteWithoutPhysicalIdIsSkipped() {
|
||||
provisioner.delete("AWS::EC2::FlowLog", null, "us-east-1");
|
||||
provisioner.delete("AWS::EC2::FlowLog", " ", "us-east-1");
|
||||
verifyNoInteractions(flowLogs);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user