Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(cloudformation): provision ApiGateway::Account, AutoScaling::LifecycleHook, and EC2::FlowLog (#2003)

lex009280369b64a1
diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md
index 67b3e6d943..0986e41d5b 100644
--- a/docs/services/cloudformation.md
+++ b/docs/services/cloudformation.md
@@ -67,11 +67,11 @@ cross-resource references.
| ECS | `Cluster`, `TaskDefinition`, `Service` |
| EKS | `Cluster`, `Nodegroup` |
| RDS | `DBInstance`, `DBCluster`, `DBSubnetGroup`, `DBParameterGroup`, `DBClusterParameterGroup` (DBInstance/DBCluster start real containers) |
-| EC2 | `VPC`, `Subnet`, `SecurityGroup`, `InternetGateway`, `RouteTable`, `SubnetRouteTableAssociation`, `Route`, `NatGateway`, `EIP`, `Instance`, `LaunchTemplate`, `VPCGatewayAttachment`, `NetworkAcl`, `NetworkAclEntry`, `SubnetNetworkAclAssociation` |
+| EC2 | `VPC`, `Subnet`, `SecurityGroup`, `InternetGateway`, `RouteTable`, `SubnetRouteTableAssociation`, `Route`, `NatGateway`, `EIP`, `Instance`, `LaunchTemplate`, `VPCGatewayAttachment`, `NetworkAcl`, `NetworkAclEntry`, `SubnetNetworkAclAssociation`, `FlowLog` |
| Elastic Load Balancing v2 | `LoadBalancer`, `TargetGroup`, `Listener`, `ListenerRule` |
-| Auto Scaling | `LaunchConfiguration`, `AutoScalingGroup` |
+| Auto Scaling | `LaunchConfiguration`, `AutoScalingGroup`, `LifecycleHook` |
| Route 53 | `HostedZone`, `RecordSet` |
-| API Gateway (v1) | `RestApi`, `Resource`, `Authorizer`, `Method`, `Deployment`, `Stage` |
+| API Gateway (v1) | `RestApi`, `Resource`, `Authorizer`, `Method`, `Deployment`, `Stage`, `Account` |
| API Gateway v2 | `Api`, `Route`, `Integration`, `Stage`, `Deployment` |
| Step Functions | `StateMachine` |
| Batch | `ComputeEnvironment`, `JobQueue`, `JobDefinition` |
diff --git a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java
index 2b00bd667b..edf686d5bb 100644
--- a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java
@@ -577,6 +577,29 @@ public class AutoScalingService {
hooks.remove(hookKey(region, asgName, hookName));
}
+ /**
+ * Deletes every hook with this name in the region, whichever group owns it. Callers that only
+ * hold the hook name use this — the CloudFormation delete path is keyed by physical id, and a
+ * lifecycle hook's physical id is its name, not its group.
+ */
+ public void deleteLifecycleHookByName(String region, String hookName) {
+ if (hookName == null) {
+ return;
+ }
+ List<String> keys = new ArrayList<>();
+ for (Map.Entry<String, LifecycleHook> entry : hooks.entrySet()) {
+ LifecycleHook hook = entry.getValue();
+ if (hook == null || !hookName.equals(hook.getLifecycleHookName())) {
+ continue;
+ }
+ if (region != null && !entry.getKey().startsWith(region + "::")) {
+ continue;
+ }
+ keys.add(entry.getKey());
+ }
+ keys.forEach(hooks::remove);
+ }
+
public List<LifecycleHook> describeLifecycleHooks(String region, String asgName, List<String> hookNames) {
requireGroup(region, asgName);
List<LifecycleHook> result = hooks.values().stream()
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
index d7d5cbaea3..a0ba05512e 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
@@ -558,6 +558,14 @@ public class CloudFormationResourceProvisioner {
deleteEventBusSafe(resource, region);
return;
}
+ // Extracted provisioners get the whole resource, so the ones whose delete needs more than
+ // the physical id can read their create-time attributes instead of guessing. Placed after
+ // the special cases above so extracting one of those types later cannot silently bypass them.
+ CfnResourceProvisioner extractedForDelete = resourceRegistry.forType(resourceType).orElse(null);
+ if (extractedForDelete != null) {
+ extractedForDelete.delete(resource, region);
+ return;
+ }
delete(resourceType, resource.getPhysicalId(), region);
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayAccountCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayAccountCfnProvisioner.java
new file mode 100644
index 0000000000..dc1b3adfb3
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayAccountCfnProvisioner.java
@@ -0,0 +1,50 @@
+package io.github.hectorvent.floci.services.cloudformation.provisioners;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import io.github.hectorvent.floci.services.apigateway.ApiGatewayService;
+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * CloudFormation provisioning for {@code AWS::ApiGateway::Account}. The resource carries a single
+ * account-level setting, CloudWatchRoleArn, which lands in {@link ApiGatewayService}'s account
+ * store — the same state {@code GET /account} reads — so a template that sets the logging role is
+ * observable afterwards instead of being recorded as a bare physical id.
+ */
+@ApplicationScoped
+public class ApiGatewayAccountCfnProvisioner implements CfnResourceProvisioner {
+
+ private final ApiGatewayService apiGatewayService;
+
+ @Inject
+ public ApiGatewayAccountCfnProvisioner(ApiGatewayService apiGatewayService) {
+ this.apiGatewayService = apiGatewayService;
+ }
+
+ @Override
+ public Set<String> resourceTypes() {
+ return Set.of("AWS::ApiGateway::Account");
+ }
+
+ @Override
+ public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
+ String roleArn = ctx.resolveOptional(props, "CloudWatchRoleArn");
+ if (roleArn != null && !roleArn.isBlank()) {
+ apiGatewayService.updateAccount(ctx.region(), List.of(Map.of(
+ "op", "replace",
+ "path", "/cloudwatchRoleArn",
+ "value", roleArn)));
+ }
+ // The account is a singleton per region, so there is no generated id to hand back.
+ r.setPhysicalId(r.getLogicalId());
+ r.getAttributes().put("Id", r.getLogicalId());
+ }
+
+ // No delete: API Gateway has no DeleteAccount operation, and the account-level settings are
+ // regional rather than stack-owned, so they survive DeleteStack exactly as in AWS.
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AutoScalingLifecycleHookCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AutoScalingLifecycleHookCfnProvisioner.java
new file mode 100644
index 0000000000..f00c8fd426
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AutoScalingLifecycleHookCfnProvisioner.java
@@ -0,0 +1,111 @@
+package io.github.hectorvent.floci.services.cloudformation.provisioners;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.autoscaling.AutoScalingService;
+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.util.Set;
+
+/**
+ * CloudFormation provisioning for {@code AWS::AutoScaling::LifecycleHook}, backed by
+ * {@link AutoScalingService}. The physical id is the hook name, as in AWS.
+ */
+@ApplicationScoped
+public class AutoScalingLifecycleHookCfnProvisioner implements CfnResourceProvisioner {
+
+ private final AutoScalingService autoScalingService;
+
+ @Inject
+ public AutoScalingLifecycleHookCfnProvisioner(AutoScalingService autoScalingService) {
+ this.autoScalingService = autoScalingService;
+ }
+
+ @Override
+ public Set<String> resourceTypes() {
+ return Set.of("AWS::AutoScaling::LifecycleHook");
+ }
+
+ @Override
+ public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
+ String existingName = r.getPhysicalId();
+ String hookName = ctx.resolveOptional(props, "LifecycleHookName");
+ if (hookName == null || hookName.isBlank()) {
+ // An unnamed hook keeps the name its first execution generated. Minting a fresh one on
+ // every update leaves the previous hook on the group with nothing referencing it.
+ hookName = existingName != null && !existingName.isBlank()
+ ? existingName
+ : ctx.generatePhysicalName(r.getLogicalId(), 255, false);
+ }
+ Integer heartbeat = props != null && props.hasNonNull("HeartbeatTimeout")
+ ? props.get("HeartbeatTimeout").asInt() : null;
+ String asgName = ctx.resolveOptional(props, "AutoScalingGroupName");
+ String existingAsg = r.getAttributes() == null ? null : r.getAttributes().get("AutoScalingGroupName");
+ // LifecycleHookName and AutoScalingGroupName are both createOnly, so a change to either is a
+ // replacement. Provisioning through it would put the new hook in place and overwrite the id
+ // that delete uses, leaving the previous hook on its group and still firing. Reported the
+ // same way EcsCapacityCfnProvisioner reports a changed Name.
+ requireUnchanged("LifecycleHookName", existingName, hookName);
+ requireUnchanged("AutoScalingGroupName", existingAsg, asgName);
+ // Recorded so delete can scope to the owning group: hook names are unique only within one.
+ if (asgName != null && !asgName.isBlank()) {
+ r.getAttributes().put("AutoScalingGroupName", asgName);
+ }
+ autoScalingService.putLifecycleHook(ctx.region(),
+ asgName,
+ hookName,
+ ctx.resolveOptional(props, "LifecycleTransition"),
+ ctx.resolveOptional(props, "NotificationTargetARN"),
+ ctx.resolveOptional(props, "RoleARN"),
+ ctx.resolveOptional(props, "NotificationMetadata"),
+ heartbeat,
+ ctx.resolveOptional(props, "DefaultResult"));
+ r.setPhysicalId(hookName);
+ }
+
+ /** Rejects a change to a createOnly property rather than stranding the resource it names. */
+ private void requireUnchanged(String property, String existing, String requested) {
+ if (existing == null || existing.isBlank() || requested == null || requested.isBlank()) {
+ return;
+ }
+ if (!existing.equals(requested)) {
+ throw new AwsException("ValidationError",
+ "Updating " + property + " requires resource replacement, which is not supported.", 400);
+ }
+ }
+
+ /**
+ * Deletes the hook on the group that owns it. Hook names are unique only within an Auto Scaling
+ * group, so deleting by name alone takes out an identically named hook on an unrelated group
+ * and stops its lifecycle action.
+ */
+ @Override
+ public void delete(StackResource resource, String region) {
+ String hookName = resource.getPhysicalId();
+ if (hookName == null || hookName.isBlank()) {
+ return;
+ }
+ String asgName = resource.getAttributes() == null
+ ? null : resource.getAttributes().get("AutoScalingGroupName");
+ if (asgName != null && !asgName.isBlank()) {
+ autoScalingService.deleteLifecycleHook(region, asgName, hookName);
+ return;
+ }
+ delete(resource.getResourceType(), hookName, region);
+ }
+
+ /**
+ * Fallback for resources provisioned before the group was recorded. The hook still has to go —
+ * it may sit on a group that outlives the stack — but without the owner this can only match by
+ * name within the region.
+ */
+ @Override
+ public void delete(String resourceType, String physicalId, String region) {
+ if (physicalId == null || physicalId.isBlank()) {
+ return;
+ }
+ autoScalingService.deleteLifecycleHookByName(region, physicalId);
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnResourceProvisioner.java
index a7e4b584f9..30cac5b62f 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnResourceProvisioner.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnResourceProvisioner.java
@@ -25,4 +25,13 @@ public interface CfnResourceProvisioner {
default void delete(String resourceType, String physicalId, String region) {
// no-op by default: some resource types have no backing delete
}
+
+ /**
+ * Delete with the resource's create-time attributes in hand. Override this when the physical id
+ * alone cannot identify what to delete — a lifecycle hook name is unique only within its Auto
+ * Scaling group, for instance. The default drops to the id-only form above.
+ */
+ default void delete(StackResource resource, String region) {
+ delete(resource.getResourceType(), resource.getPhysicalId(), region);
+ }
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2FlowLogCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2FlowLogCfnProvisioner.java
new file mode 100644
index 0000000000..2612f0a3fd
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2FlowLogCfnProvisioner.java
@@ -0,0 +1,131 @@
+package io.github.hectorvent.floci.services.cloudformation.provisioners;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
+import io.github.hectorvent.floci.services.ec2.FlowLogService;
+import io.github.hectorvent.floci.services.ec2.model.FlowLog;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+
+/**
+ * CloudFormation provisioning for {@code AWS::EC2::FlowLog}, backed by {@link FlowLogService}.
+ * Ref and {@code Fn::GetAtt [Flow, Id]} both yield the {@code fl-} id, matching AWS.
+ */
+@ApplicationScoped
+public class Ec2FlowLogCfnProvisioner implements CfnResourceProvisioner {
+
+ /** AWS's default when MaxAggregationInterval is omitted (10 minutes). */
+ private static final int DEFAULT_MAX_AGGREGATION_INTERVAL = 600;
+
+ /** The defaults createFlowLog applies when the template omits these, kept in step with it. */
+ private static final String DEFAULT_RESOURCE_TYPE = "VPC";
+ private static final String DEFAULT_TRAFFIC_TYPE = "ALL";
+ private static final String DEFAULT_LOG_DESTINATION_TYPE = "s3";
+
+ private final FlowLogService flowLogService;
+
+ @Inject
+ public Ec2FlowLogCfnProvisioner(FlowLogService flowLogService) {
+ this.flowLogService = flowLogService;
+ }
+
+ @Override
+ public Set<String> resourceTypes() {
+ return Set.of("AWS::EC2::FlowLog");
+ }
+
+ @Override
+ public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
+ // An update re-invokes provision with the prior physical id. Creating unconditionally
+ // would leave a second flow log on every update and orphan the first, which then outlives
+ // the stack, since delete only knows the id recorded last.
+ String existingId = r.getPhysicalId();
+ if (existingId != null && !existingId.isBlank()) {
+ FlowLog existing = flowLogService.describeFlowLogs(ctx.region(), List.of(existingId))
+ .stream().findFirst().orElse(null);
+ if (existing != null) {
+ // Every property except Tags is createOnly, so there is nothing to modify on the
+ // reused log and a change to any of them is a replacement. Reusing regardless would
+ // report the stack complete while DescribeFlowLogs kept serving the old config.
+ requireUnchanged(existing, props, ctx);
+ r.getAttributes().put("Id", existingId);
+ return;
+ }
+ }
+ FlowLog fl = flowLogService.createFlowLog(ctx.region(),
+ ctx.resolveOptional(props, "ResourceId"),
+ ctx.resolveOptional(props, "ResourceType"),
+ ctx.resolveOptional(props, "TrafficType"),
+ ctx.resolveOptional(props, "LogDestinationType"),
+ ctx.resolveOptional(props, "LogDestination"),
+ ctx.resolveOptional(props, "LogFormat"),
+ props != null && props.hasNonNull("MaxAggregationInterval")
+ ? props.get("MaxAggregationInterval").asInt()
+ : DEFAULT_MAX_AGGREGATION_INTERVAL);
+ r.setPhysicalId(fl.getFlowLogId());
+ r.getAttributes().put("Id", fl.getFlowLogId());
+ }
+
+ /**
+ * Rejects a change to any createOnly property. AWS replaces the flow log for these, and this
+ * provisioner has no replacement path, so reporting is better than reusing a log whose
+ * configuration no longer matches the template.
+ */
+ private void requireUnchanged(FlowLog existing, JsonNode props, ProvisionContext ctx) {
+ // Compared as effective values on both sides. createFlowLog defaults ResourceType,
+ // TrafficType and LogDestinationType when the template omits them, so a re-apply of an
+ // unchanged template reads null here against a stored default. Defaulting the requested
+ // side the same way keeps a no-op update a no-op, while a genuine add, drop or change
+ // still differs. The other three have no create-time default and stay null on both sides.
+ rejectIfChanged("ResourceId", existing.getResourceId(),
+ ctx.resolveOptional(props, "ResourceId"));
+ rejectIfChanged("ResourceType", existing.getResourceType(),
+ orDefault(ctx.resolveOptional(props, "ResourceType"), DEFAULT_RESOURCE_TYPE));
+ rejectIfChanged("TrafficType", existing.getTrafficType(),
+ orDefault(ctx.resolveOptional(props, "TrafficType"), DEFAULT_TRAFFIC_TYPE));
+ rejectIfChanged("LogDestinationType", existing.getLogDestinationType(),
+ orDefault(ctx.resolveOptional(props, "LogDestinationType"), DEFAULT_LOG_DESTINATION_TYPE));
+ rejectIfChanged("LogDestination", existing.getLogDestination(),
+ ctx.resolveOptional(props, "LogDestination"));
+ rejectIfChanged("LogFormat", existing.getLogFormat(), ctx.resolveOptional(props, "LogFormat"));
+ int requestedInterval = props != null && props.hasNonNull("MaxAggregationInterval")
+ ? props.get("MaxAggregationInterval").asInt()
+ : DEFAULT_MAX_AGGREGATION_INTERVAL;
+ if (requestedInterval != existing.getMaxAggregationInterval()) {
+ throw new AwsException("ValidationError",
+ "Updating MaxAggregationInterval requires resource replacement, which is not supported.", 400);
+ }
+ }
+
+ private static String orDefault(String requested, String fallback) {
+ return requested == null || requested.isBlank() ? fallback : requested;
+ }
+
+ /**
+ * Both sides are the effective value, so an absent one means genuinely absent rather than
+ * unknown. Adding a property, dropping one, and altering one all read as changes.
+ */
+ private void rejectIfChanged(String property, String existing, String requested) {
+ String a = existing == null || existing.isBlank() ? null : existing;
+ String b = requested == null || requested.isBlank() ? null : requested;
+ if (Objects.equals(a, b)) {
+ return;
+ }
+ throw new AwsException("ValidationError",
+ "Updating " + property + " requires resource replacement, which is not supported.", 400);
+ }
+
+ /** Without this the flow log outlives its stack and keeps showing up in DescribeFlowLogs. */
+ @Override
+ public void delete(String resourceType, String physicalId, String region) {
+ if (physicalId == null || physicalId.isBlank()) {
+ return;
+ }
+ flowLogService.deleteFlowLogs(region, List.of(physicalId));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationSmallMetadataIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationSmallMetadataIntegrationTest.java
new file mode 100644
index 0000000000..96072a9cbf
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationSmallMetadataIntegrationTest.java
@@ -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);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayAccountCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayAccountCfnProvisionerTest.java
new file mode 100644
index 0000000000..d17bd3d144
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayAccountCfnProvisionerTest.java
@@ -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);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AutoScalingLifecycleHookCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AutoScalingLifecycleHookCfnProvisionerTest.java
new file mode 100644
index 0000000000..f2538a8717
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AutoScalingLifecycleHookCfnProvisionerTest.java
@@ -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);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2FlowLogCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2FlowLogCfnProvisionerTest.java
new file mode 100644
index 0000000000..f1b3b5e18c
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2FlowLogCfnProvisionerTest.java
@@ -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);
+ }
+}