From dbbf22957f7700ee9682c08b8dfcf1c759e091e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ronald=20Li=20=F0=9F=9B=A0=EF=B8=8F?= <137369375+RonCodes88@users.noreply.github.com> Date: Wed, 4 Nov 2026 02:49:14 -0800 Subject: [PATCH] fix(cloudformation): apply an AWS::EC2::FlowLog's Tags (#7490) --- docs/services/cloudformation.md | 2 +- .../provisioners/CfnRollback.java | 8 + .../Ec2FlowLogCfnProvisioner.java | 176 +++++++++++- .../cloudformation/provisioners/Ec2Tags.java | 30 +- .../cloudformation/CfnProvisionerFixture.java | 2 +- ...udFormationFlowLogTagsIntegrationTest.java | 152 +++++++++++ ...FormationSmallMetadataIntegrationTest.java | 10 +- .../Ec2FlowLogCfnProvisionerTest.java | 257 +++++++++++++++++- .../cloudformation/writable-property-gaps.tsv | 1 - tools/docs/cfn_resource_types.yaml | 1 + 10 files changed, 620 insertions(+), 19 deletions(-) create mode 100644 src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationFlowLogTagsIntegrationTest.java diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index ad7aa2c22d..6cdfaf0485 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -197,7 +197,7 @@ cross-resource references. | ElastiCache | `CacheCluster` (starts a real container; modifying an existing cluster in place is not supported), `SubnetGroup`, `User` (Tags are ignored), `UserGroup` (Tags are ignored), `ServerlessCache` (GetAtt uses the dotted Endpoint.* and ReaderEndpoint.* form) | | Redshift | `Cluster` (single-node container; Port and non-dev DBName ignored; ManageMasterPassword unsupported), `ClusterParameterGroup`, `ClusterSubnetGroup`, `ClusterSecurityGroup` (accepted; no EC2-Classic security group model), `EventSubscription` | | Redshift Serverless | `Namespace` (Managed admin credentials use Secrets Manager; GetAtt uses the dotted Namespace.* form), `Workgroup` (starts a real container; one workgroup per namespace; capacity, VPC and price-performance settings are stored only; snapshot restore properties are ignored; GetAtt uses the dotted Workgroup.* form) | -| EC2 | `VPC` (deleted on stack teardown; a VPC with dependents outside the stack, including anything still holding a network interface in its subnets (an instance that is not terminated, a NAT gateway that is not deleted or failed, a standalone interface, an interface endpoint), fails the delete with `DependencyViolation`, as on AWS), `Subnet`, `SecurityGroup` (inline `SecurityGroupIngress`/`SecurityGroupEgress` supported), `SecurityGroupIngress`, `SecurityGroupEgress`, `InternetGateway`, `RouteTable`, `SubnetRouteTableAssociation`, `Route`, `NatGateway` (zonal; `AvailabilityMode` regional fails; a change to the `Secondary*` address properties updates the gateway in place), `EIP`, `Instance`, `LaunchTemplate`, `VPCGatewayAttachment`, `VPCEndpoint`, `NetworkAcl`, `NetworkAclEntry`, `SubnetNetworkAclAssociation`, `FlowLog`, `KeyPair` (a created key's private key is stored in the `SecureString` parameter `/ec2/keypair/`, as on AWS, and deleted with the key), `PrefixList` (updated in place; an update that changes `AddressFamily`, or `MaxEntries` together with `Entries`, fails) | +| EC2 | `VPC` (deleted on stack teardown; a VPC with dependents outside the stack, including anything still holding a network interface in its subnets (an instance that is not terminated, a NAT gateway that is not deleted or failed, a standalone interface, an interface endpoint), fails the delete with `DependencyViolation`, as on AWS), `Subnet`, `SecurityGroup` (inline `SecurityGroupIngress`/`SecurityGroupEgress` supported), `SecurityGroupIngress`, `SecurityGroupEgress`, `InternetGateway`, `RouteTable`, `SubnetRouteTableAssociation`, `Route`, `NatGateway` (zonal; `AvailabilityMode` regional fails; a change to the `Secondary*` address properties updates the gateway in place), `EIP`, `Instance`, `LaunchTemplate`, `VPCGatewayAttachment`, `VPCEndpoint`, `NetworkAcl`, `NetworkAclEntry`, `SubnetNetworkAclAssociation`, `FlowLog` (`Tags` are applied and updated in place, keeping tags added outside the stack; any other change fails, since it needs a replacement), `KeyPair` (a created key's private key is stored in the `SecureString` parameter `/ec2/keypair/`, as on AWS, and deleted with the key), `PrefixList` (updated in place; an update that changes `AddressFamily`, or `MaxEntries` together with `Entries`, fails) | | Elastic Load Balancing v2 | `LoadBalancer`, `TargetGroup`, `Listener`, `ListenerRule` | | Auto Scaling | `LaunchConfiguration`, `AutoScalingGroup`, `LifecycleHook`, `ScalingPolicy` | | Application Auto Scaling | `ScalableTarget` (`ScheduledActions` are accepted and not run; Floci has no scheduled scaling), `ScalingPolicy` | diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java index 3de79242ef..5bec066154 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java @@ -166,6 +166,14 @@ public final class CfnRollback { */ public static final String LAMBDA_WEB_UPDATE_SNAPSHOT_ATTR = "__FlociLambdaWebUpdateSnapshot"; + /** + * Holds what an update did to an EC2 flow log, so a failed stack update can undo it: the tag + * keys it touched on the reused log with the values they had, or the log it created because + * the stack's own was gone. Written by {@code Ec2FlowLogCfnProvisioner} before its tag write or + * right after that creation, and spent by its {@code rollbackUpdate}. + */ + public static final String FLOW_LOG_UPDATE_SNAPSHOT_ATTR = "__FlociEc2FlowLogUpdateSnapshot"; + /** * Holds the function ARN, status, caching flag, token settings and tags an IoT authorizer * carried before an in-place update changed them, so a failed stack update can put them back. 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 index 596a7fda9f..9430b31544 100644 --- 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 @@ -1,20 +1,33 @@ package io.github.hectorvent.floci.services.cloudformation.provisioners; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.ec2.Ec2Service; 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.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.List; +import java.util.Map; 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. + * Ref and {@code Fn::GetAtt [Flow, Id]} both yield the {@code fl-} id, matching AWS. {@code Tags} + * live in the EC2 tag store, as a {@code CreateFlowLogs} TagSpecification's do, and an update + * reconciles the keys the template owns on the reused log, keeping tags added outside the stack, as + * AWS does. What an update changes is recorded in {@link CfnRollback#FLOW_LOG_UPDATE_SNAPSHOT_ATTR}, + * so a stack update that fails on a later resource puts the touched keys back, or deletes a log the + * update recreated because the stack's own was gone. */ @ApplicationScoped public class Ec2FlowLogCfnProvisioner implements CfnResourceProvisioner { @@ -25,12 +38,23 @@ public class Ec2FlowLogCfnProvisioner implements CfnResourceProvisioner { /** 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 ObjectMapper MAPPER = new ObjectMapper(); + private static final String SNAPSHOT_ATTR = CfnRollback.FLOW_LOG_UPDATE_SNAPSHOT_ATTR; + + /** + * The tag keys the last deployment resolved and wrote, as a JSON array: the keys the stack owns. + * Recorded rather than re-resolved from the previous template, because a key taken from a + * parameter resolves to the new value on the next update. + */ + static final String TAG_KEYS_ATTR = "__FlociEc2FlowLogTagKeys"; private final FlowLogService flowLogService; + private final Ec2Service ec2Service; @Inject - public Ec2FlowLogCfnProvisioner(FlowLogService flowLogService) { + public Ec2FlowLogCfnProvisioner(FlowLogService flowLogService, Ec2Service ec2Service) { this.flowLogService = flowLogService; + this.ec2Service = ec2Service; } @Override @@ -43,16 +67,31 @@ public class Ec2FlowLogCfnProvisioner implements CfnResourceProvisioner { // 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 region = ctx.region(); + Map desiredTags = ctx.resolveTags(props, "Tags"); + // Every tag rule CreateTags applies (reserved keys, lengths, the count limit) is checked + // before anything is created, so a bad tag fails the resource before a log exists. + Ec2Service.validateNewResourceTags(Ec2Tags.validatedTags(desiredTags)); + // The ownership record this deployment replaces, kept in the rollback snapshot, since the + // rollback walker keeps the attempted resource's attributes. + String priorTagKeys = r.getAttributes().get(TAG_KEYS_ATTR); 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 + // Every property except Tags is createOnly, so only the tags change on the reused + // log and a change to any other property 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); + // Only the keys the last deployment wrote are the stack's to remove. + Set owned = ownedTagKeys(r, ctx); + CfnRollback.guarded(r, ctx, false, () -> { }, () -> undoInPlace(r), () -> { + snapshotTags(r, region, existingId, owned, desiredTags, priorTagKeys); + Ec2Tags.reconcileOwned(ec2Service, region, existingId, owned, desiredTags); + }); + recordTagKeys(r, desiredTags); return; } } @@ -67,8 +106,133 @@ public class Ec2FlowLogCfnProvisioner implements CfnResourceProvisioner { props != null && props.hasNonNull("MaxAggregationInterval") ? props.get("MaxAggregationInterval").asInt() : DEFAULT_MAX_AGGREGATION_INTERVAL); - r.setPhysicalId(fl.getFlowLogId()); - r.getAttributes().put("Id", fl.getFlowLogId()); + String flowLogId = fl.getFlowLogId(); + r.setPhysicalId(flowLogId); + r.getAttributes().put("Id", flowLogId); + // A tag write that still fails deletes the new log rather than leaving it outside the stack. + CfnRollback.guarded(r, ctx, true, () -> flowLogService.deleteFlowLogs(region, List.of(flowLogId)), + () -> { }, () -> Ec2Tags.reconcile(ec2Service, region, flowLogId, desiredTags)); + recordTagKeys(r, desiredTags); + if (ctx.isUpdate()) { + // The stack's log was removed outside it, so a rollback deletes this one and names the + // prior id again rather than keeping the failed update's log. + CfnRollback.recordCreatedByUpdate(r, ctx, SNAPSHOT_ATTR); + ObjectNode created = (ObjectNode) CfnRollback.updateSnapshot(r, SNAPSHOT_ATTR); + created.put("tagKeys", priorTagKeys); + r.getAttributes().put(SNAPSHOT_ATTR, created.toString()); + } + } + + @Override + public UpdateCleanupResult completeUpdate(StackResource resource) { + resource.getAttributes().remove(SNAPSHOT_ATTR); + return UpdateCleanupResult.notApplicable(); + } + + @Override + public void clearUpdate(StackResource resource) { + resource.getAttributes().remove(SNAPSHOT_ATTR); + } + + /** + * Undoes what the failed update recorded: deletes a log it recreated, or puts back the tag keys + * it touched on the reused one. Without a snapshot the update changed nothing. + */ + @Override + public boolean rollbackUpdate(StackResource resource) { + JsonNode snapshot = CfnRollback.updateSnapshot(resource, SNAPSHOT_ATTR); + if (snapshot != null && CfnRollback.undoCreatedByUpdate(resource, snapshot, SNAPSHOT_ATTR, "Id", + (id, region) -> flowLogService.deleteFlowLogs(region, List.of(id)))) { + restoreTagKeys(resource, snapshot); + return true; + } + undoInPlace(resource); + return true; + } + + /** Puts back the ownership record the snapshot carries, or its absence. */ + private static void restoreTagKeys(StackResource r, JsonNode snapshot) { + String tagKeys = CfnRollback.snapshotText(snapshot, "tagKeys"); + if (tagKeys == null) { + r.getAttributes().remove(TAG_KEYS_ATTR); + } else { + r.getAttributes().put(TAG_KEYS_ATTR, tagKeys); + } + } + + /** + * The keys the last deployment recorded in {@link #TAG_KEYS_ATTR}. A log provisioned before + * that was recorded falls back to the previous template's keys, resolved as well as they still + * can be. + */ + private Set ownedTagKeys(StackResource r, ProvisionContext ctx) { + String recorded = r.getAttributes().get(TAG_KEYS_ATTR); + if (recorded == null) { + return ctx.resolveTags(ctx.priorProperties(), "Tags").keySet(); + } + Set keys = new LinkedHashSet<>(); + try { + MAPPER.readTree(recorded).forEach(key -> keys.add(key.asText())); + } catch (JsonProcessingException e) { + throw new IllegalStateException("Unreadable tag keys on " + r.getLogicalId(), e); + } + return keys; + } + + private static void recordTagKeys(StackResource r, Map desiredTags) { + ArrayNode keys = MAPPER.createArrayNode(); + desiredTags.keySet().forEach(keys::add); + r.getAttributes().put(TAG_KEYS_ATTR, keys.toString()); + } + + /** + * Records the values the touched keys (the owned ones and the declared ones) had before the + * update changes them, with the ownership record it replaces, only when a value or the owned + * key set is about to change, so an unchanged reuse leaves no snapshot. Tags outside that set + * are never written, so they are not recorded either. + */ + private void snapshotTags(StackResource r, String region, String flowLogId, Set owned, + Map desiredTags, String priorTagKeys) { + Map currentTags = Ec2Tags.current(ec2Service, region, flowLogId); + Set touched = new LinkedHashSet<>(owned); + touched.addAll(desiredTags.keySet()); + // A change of ownership alone (taking over a key that already holds the declared value) + // still needs the record put back, so it counts as a change too. + boolean changes = !owned.equals(desiredTags.keySet()) + || touched.stream().anyMatch(key -> desiredTags.containsKey(key) + ? !desiredTags.get(key).equals(currentTags.get(key)) + : currentTags.containsKey(key)); + if (!changes) { + return; + } + ObjectNode prior = MAPPER.createObjectNode(); + prior.put("region", region); + prior.put("flowLogId", flowLogId); + prior.put("tagKeys", priorTagKeys); + touched.forEach(prior.putArray("touched")::add); + ObjectNode tags = prior.putObject("tags"); + touched.stream().filter(currentTags::containsKey).forEach(key -> tags.put(key, currentTags.get(key))); + r.getAttributes().put(SNAPSHOT_ATTR, prior.toString()); + } + + /** + * Puts the touched keys of a reused log back from the snapshot: a key it had gets its value + * again, and a key the update added is removed. The ownership record goes back too. The snapshot is removed only after the restore + * succeeds, so a failed one keeps it for the rollback walker's retry. + */ + private void undoInPlace(StackResource r) { + JsonNode prior = CfnRollback.updateSnapshot(r, SNAPSHOT_ATTR); + if (prior == null) { + return; + } + Set touched = new LinkedHashSet<>(); + prior.path("touched").forEach(key -> touched.add(key.asText())); + Map priorTags = new LinkedHashMap<>(); + prior.path("tags").properties().forEach(f -> priorTags.put(f.getKey(), f.getValue().asText())); + Ec2Tags.reconcileOwned(ec2Service, prior.path("region").asText(), prior.path("flowLogId").asText(), + touched, priorTags); + restoreTagKeys(r, prior); + r.getAttributes().remove(SNAPSHOT_ATTR); } /** diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2Tags.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2Tags.java index 985fdfb901..376f9ae1bd 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2Tags.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2Tags.java @@ -8,11 +8,13 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Set; /** * Tag reconciliation shared by the EC2 provisioners ({@code Ec2InstanceCfnProvisioner}, - * {@code Ec2SecurityGroupCfnProvisioner} and {@code Ec2VpcCfnProvisioner}). They drive it from the - * desired tags resolved via {@link ProvisionContext#resolveTags}; the reconcile itself is identical. + * {@code Ec2SecurityGroupCfnProvisioner}, {@code Ec2VpcCfnProvisioner} and + * {@code Ec2FlowLogCfnProvisioner}). They drive it from the desired tags resolved via + * {@link ProvisionContext#resolveTags}; the reconcile itself is identical. */ final class Ec2Tags { @@ -66,4 +68,28 @@ final class Ec2Tags { } return changed; } + + /** + * Brings the keys a template owns to {@code desired} and leaves every other tag alone, as AWS + * keeps a tag added outside the stack: removes the {@code owned} keys {@code desired} no longer + * declares, then creates or overwrites the declared ones. {@code owned} is the key set the + * previous template declared, or the keys an update touched when a rollback restores them. + */ + static void reconcileOwned(Ec2Service ec2Service, String region, String resourceId, Set owned, + Map desired) { + List add = validatedTags(desired); + Map current = current(ec2Service, region, resourceId); + List remove = new ArrayList<>(); + for (String key : owned) { + if (!desired.containsKey(key) && current.containsKey(key)) { + remove.add(new Tag(key, current.get(key))); + } + } + if (!remove.isEmpty()) { + ec2Service.deleteTags(region, List.of(resourceId), remove); + } + if (!add.isEmpty()) { + ec2Service.createTags(region, List.of(resourceId), add); + } + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java index 7b53253985..2ab8cd1099 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java @@ -442,7 +442,7 @@ final class CfnProvisionerFixture { discovered.add(new LambdaEventSourceMappingCfnProvisioner(lambdaService)); } if (flowLogService != null) { - discovered.add(new Ec2FlowLogCfnProvisioner(flowLogService)); + discovered.add(new Ec2FlowLogCfnProvisioner(flowLogService, ec2Service)); } if (iotAuthorizerService != null) { discovered.add(new IotAuthorizerCfnProvisioner(iotAuthorizerService)); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationFlowLogTagsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationFlowLogTagsIntegrationTest.java new file mode 100644 index 0000000000..ddbf1b76d5 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationFlowLogTagsIntegrationTest.java @@ -0,0 +1,152 @@ +package io.github.hectorvent.floci.services.cloudformation; + +import io.github.hectorvent.floci.testing.AwsTestClients; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.cloudformation.CloudFormationClient; +import software.amazon.awssdk.services.ec2.Ec2Client; +import software.amazon.awssdk.services.ec2.model.Tag; + +import java.time.Duration; +import java.util.Map; +import java.util.TreeMap; +import java.util.UUID; + +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * An {@code AWS::EC2::FlowLog}'s {@code Tags} through the AWS SDK. A stack update changes only the + * keys the template owns: AWS keeps a tag added to the flow log through EC2 whether the update + * replaces the template's tags or drops the property. + */ +@QuarkusTest +class CloudFormationFlowLogTagsIntegrationTest { + + private final String stackName = "cfn-flow-log-tags-" + UUID.randomUUID(); + private CloudFormationClient cfn; + private Ec2Client ec2; + private boolean stackCreated; + + @BeforeEach + void clients() { + cfn = AwsTestClients.create(CloudFormationClient.builder(), "test", Region.US_EAST_1); + ec2 = AwsTestClients.create(Ec2Client.builder(), "test", Region.US_EAST_1); + } + + @AfterEach + void deleteStack() { + try { + if (stackCreated) { + cfn.deleteStack(request -> request.stackName(stackName)); + } + } finally { + ec2.close(); + cfn.close(); + } + } + + @Test + void replacingTheTemplatesTagsKeepsATagAddedThroughEc2() { + String flowLogId = createStackWithExternalTag(); + + updateStack(tagsProperty("owner", "platform")); + + assertEquals(Map.of("owner", "platform", "external", "preserve"), tags(flowLogId)); + assertEquals(flowLogId, flowLogId()); + } + + @Test + void droppingTheTemplatesTagsKeepsATagAddedThroughEc2() { + String flowLogId = createStackWithExternalTag(); + + updateStack(""); + + assertEquals(Map.of("external", "preserve"), tags(flowLogId)); + assertEquals(flowLogId, flowLogId()); + } + + @Test + void aTagKeyFromAChangedParameterReplacesTheOldKey() { + String keyFromParameter = """ + , + "Tags": [{"Key": {"Ref": "TagKey"}, "Value": "core"}]"""; + cfn.createStack(request -> request.stackName(stackName).templateBody(template(keyFromParameter))); + stackCreated = true; + awaitStack("CREATE_COMPLETE"); + String flowLogId = flowLogId(); + + cfn.updateStack(request -> request.stackName(stackName).templateBody(template(keyFromParameter)) + .parameters(parameter -> parameter.parameterKey("TagKey").parameterValue("owner"))); + awaitStack("UPDATE_COMPLETE"); + + // Re-resolving the previous template would read owner too and leave team behind. + assertEquals(Map.of("owner", "core"), tags(flowLogId)); + } + + /** A stack whose flow log carries the template's {@code team=core} and an EC2-added tag. */ + private String createStackWithExternalTag() { + cfn.createStack(request -> request.stackName(stackName).templateBody(template(tagsProperty("team", "core")))); + stackCreated = true; + awaitStack("CREATE_COMPLETE"); + String flowLogId = flowLogId(); + assertEquals(Map.of("team", "core"), tags(flowLogId)); + ec2.createTags(request -> request.resources(flowLogId) + .tags(Tag.builder().key("external").value("preserve").build())); + return flowLogId; + } + + private void updateStack(String tagsProperty) { + cfn.updateStack(request -> request.stackName(stackName).templateBody(template(tagsProperty))); + awaitStack("UPDATE_COMPLETE"); + } + + private static String tagsProperty(String key, String value) { + return """ + , + "Tags": [{"Key": "%s", "Value": "%s"}]""".formatted(key, value); + } + + private static String template(String tagsProperty) { + return """ + { + "Parameters": {"TagKey": {"Type": "String", "Default": "team"}}, + "Resources": { + "Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.40.0.0/16"}}, + "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/tags"%s + } + } + }, + "Outputs": {"FlowId": {"Value": {"Ref": "Flow"}}} + } + """.formatted(tagsProperty); + } + + private void awaitStack(String status) { + await().atMost(Duration.ofSeconds(10)).untilAsserted(() -> + assertEquals(status, cfn.describeStacks(request -> request.stackName(stackName)) + .stacks().getFirst().stackStatusAsString())); + } + + private String flowLogId() { + return cfn.describeStacks(request -> request.stackName(stackName)).stacks().getFirst() + .outputs().getFirst().outputValue(); + } + + private Map tags(String flowLogId) { + Map tags = new TreeMap<>(); + ec2.describeFlowLogs(request -> request.flowLogIds(flowLogId)).flowLogs().getFirst().tags() + .forEach(tag -> tags.put(tag.key(), tag.value())); + return tags; + } +} 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 index 96072a9cbf..ff0baf3478 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationSmallMetadataIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationSmallMetadataIntegrationTest.java @@ -82,13 +82,14 @@ class CloudFormationSmallMetadataIntegrationTest { "ResourceType": "VPC", "TrafficType": "ALL", "LogDestinationType": "cloud-watch-logs", - "LogDestination": "arn:aws:logs:us-east-1:000000000000:log-group:/flow/meta" + "LogDestination": "arn:aws:logs:us-east-1:000000000000:log-group:/flow/meta", + "Tags": [{"Key": "flow-tag", "Value": "%s"}] } } }, "Outputs": {"FlowId": {"Value": {"Ref": "Flow"}}} } - """.formatted(asgName, hookName, roleArn); + """.formatted(asgName, hookName, roleArn, suffix); createStack(stackName, template); @@ -116,7 +117,7 @@ class CloudFormationSmallMetadataIntegrationTest { .statusCode(200) .body(containsString(hookName)); - // The flow log is live in FlowLogService. + // The flow log is live in FlowLogService, carrying the template's Tags. given() .formParam("Action", "DescribeFlowLogs") .header("Authorization", EC2_AUTH) @@ -124,7 +125,8 @@ class CloudFormationSmallMetadataIntegrationTest { .post("/") .then() .statusCode(200) - .body(containsString("/flow/meta")); + .body(containsString("/flow/meta")) + .body(containsString("flow-tag" + suffix + "")); // The account-level CloudWatch role reached the API Gateway account settings. given() 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 index b2c7375e97..a12b7d7882 100644 --- 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 @@ -9,39 +9,68 @@ import io.github.hectorvent.floci.services.cloudformation.model.StackResource; import io.github.hectorvent.floci.services.ec2.Ec2Service; import io.github.hectorvent.floci.services.ec2.FlowLogService; import io.github.hectorvent.floci.services.ec2.model.FlowLog; +import io.github.hectorvent.floci.services.ec2.model.Tag; import io.github.hectorvent.floci.services.s3.S3Service; import io.github.hectorvent.floci.testing.InMemoryStorageFactory; import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.List; +import java.util.Map; +import java.util.TreeMap; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; 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.anyInt; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; 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. */ +/** The EC2 flow-log CFN provisioner in isolation, with FlowLogService and Ec2Service mocked. */ class Ec2FlowLogCfnProvisionerTest { private final FlowLogService flowLogs = mock(FlowLogService.class); - private final Ec2FlowLogCfnProvisioner provisioner = new Ec2FlowLogCfnProvisioner(flowLogs); + private final Ec2Service ec2 = mock(Ec2Service.class); + private final Ec2FlowLogCfnProvisioner provisioner = new Ec2FlowLogCfnProvisioner(flowLogs, ec2); private final ObjectMapper mapper = new ObjectMapper(); private ProvisionContext ctx() { + return new ProvisionContext(engine(), "us-east-1", "000000000000", "my-stack"); + } + + /** An update of the stack resource at {@code priorId} whose previous template declared {@code priorTagKeys}. */ + private ProvisionContext updateCtx(String priorId, String... priorTagKeys) { + ObjectNode priorProps = mapper.createObjectNode().put("ResourceId", "vpc-123"); + for (String key : priorTagKeys) { + priorProps.withArray("Tags").addObject().put("Key", key).put("Value", "prior"); + } + return new ProvisionContext(engine(), "us-east-1", "000000000000", "my-stack", priorId, event -> { }, + priorProps); + } + + private CloudFormationTemplateEngine engine() { 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"); + when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0)); + return engine; + } + + /** Tag has no equals, so a tag list is matched on its one key and value. */ + private static List tags(String key, String value) { + return argThat(tags -> tags.size() == 1 && key.equals(tags.get(0).getKey()) + && value.equals(tags.get(0).getValue())); } private StackResource resource() { @@ -206,7 +235,7 @@ class Ec2FlowLogCfnProvisionerTest { // compare must default the template the same way or an unchanged update is rejected. FlowLogService real = new FlowLogService(mock(Ec2Service.class), mock(S3Service.class), new InMemoryStorageFactory("000000000000")); - Ec2FlowLogCfnProvisioner p = new Ec2FlowLogCfnProvisioner(real); + Ec2FlowLogCfnProvisioner p = new Ec2FlowLogCfnProvisioner(real, ec2); ObjectNode props = mapper.createObjectNode() .put("ResourceId", "vpc-123") .put("LogDestination", "arn:aws:logs:us-east-1:000000000000:log-group:flows") @@ -237,6 +266,226 @@ class Ec2FlowLogCfnProvisionerTest { assertEquals("fl-new", r.getAttributes().get("Id")); } + @Test + void createTagsTheNewFlowLog() { + when(flowLogs.createFlowLog(anyString(), any(), any(), any(), any(), any(), any(), any(), anyInt())) + .thenReturn(flowLog("fl-0abc")); + ObjectNode props = mapper.createObjectNode().put("ResourceId", "vpc-123"); + props.putArray("Tags").addObject().put("Key", "team").put("Value", "core"); + + provisioner.provision(resource(), props, ctx()); + + verify(ec2).createTags(eq("us-east-1"), eq(List.of("fl-0abc")), tags("team", "core")); + } + + @Test + void updateReplacesTheTemplatesKeysAndKeepsATagAddedOutsideTheStack() { + StackResource r = reusedFlowLogWithTags(Map.of("old", "gone", "external", "preserve")); + ObjectNode props = mapper.createObjectNode().put("ResourceId", "vpc-123"); + props.putArray("Tags").addObject().put("Key", "team").put("Value", "core"); + + provisioner.provision(r, props, updateCtx("fl-0abc", "old")); + + // Tags are the one property an update changes in place, so the log is kept, not replaced. + verify(flowLogs, never()).createFlowLog(anyString(), any(), any(), any(), any(), any(), any(), any(), anyInt()); + // Only the key the previous template owned goes; AWS keeps one added through EC2. + verify(ec2).deleteTags(eq("us-east-1"), eq(List.of("fl-0abc")), tags("old", "gone")); + verify(ec2).createTags(eq("us-east-1"), eq(List.of("fl-0abc")), tags("team", "core")); + } + + @Test + void aTagKeyFromAChangedParameterRemovesTheKeyTheLastDeploymentWrote() { + // Key: {Ref: TagKey} with TagKey changed from team to owner. Re-resolving the previous + // template reads owner on both sides, so the recorded key is what says team is the stack's. + StackResource r = reusedFlowLogWithTags(Map.of("team", "core", "external", "preserve")); + r.getAttributes().put(Ec2FlowLogCfnProvisioner.TAG_KEYS_ATTR, "[\"team\"]"); + ObjectNode props = mapper.createObjectNode().put("ResourceId", "vpc-123"); + props.putArray("Tags").addObject().put("Key", "owner").put("Value", "core"); + + provisioner.provision(r, props, updateCtx("fl-0abc", "owner")); + + verify(ec2).deleteTags(eq("us-east-1"), eq(List.of("fl-0abc")), tags("team", "core")); + verify(ec2).createTags(eq("us-east-1"), eq(List.of("fl-0abc")), tags("owner", "core")); + assertEquals("[\"owner\"]", r.getAttributes().get(Ec2FlowLogCfnProvisioner.TAG_KEYS_ATTR)); + } + + @Test + void rollbackPutsBackTheTagOwnershipRecord() { + StackResource r = reusedFlowLogWithTags(Map.of("team", "core")); + r.getAttributes().put(Ec2FlowLogCfnProvisioner.TAG_KEYS_ATTR, "[\"team\"]"); + ObjectNode props = mapper.createObjectNode().put("ResourceId", "vpc-123"); + props.putArray("Tags").addObject().put("Key", "owner").put("Value", "core"); + provisioner.provision(r, props, updateCtx("fl-0abc", "owner")); + assertEquals("[\"owner\"]", r.getAttributes().get(Ec2FlowLogCfnProvisioner.TAG_KEYS_ATTR)); + + provisioner.rollbackUpdate(r); + + // The walker keeps the attempted resource, so the record has to be put back here, or a + // later update that drops Tags would remove owner and leave team behind. + assertEquals("[\"team\"]", r.getAttributes().get(Ec2FlowLogCfnProvisioner.TAG_KEYS_ATTR)); + } + + @Test + void takingOverAKeyWithoutChangingItsValueIsRolledBack() { + // owner=core was added outside the stack; declaring it changes no live tag, only ownership. + StackResource r = reusedFlowLogWithTags(Map.of("team", "core", "owner", "core")); + r.getAttributes().put(Ec2FlowLogCfnProvisioner.TAG_KEYS_ATTR, "[\"team\"]"); + ObjectNode props = mapper.createObjectNode().put("ResourceId", "vpc-123"); + props.putArray("Tags").addObject().put("Key", "team").put("Value", "core"); + props.withArray("Tags").addObject().put("Key", "owner").put("Value", "core"); + provisioner.provision(r, props, updateCtx("fl-0abc", "team", "owner")); + assertTrue(r.getAttributes().containsKey(CfnRollback.FLOW_LOG_UPDATE_SNAPSHOT_ATTR)); + + provisioner.rollbackUpdate(r); + + assertEquals("[\"team\"]", r.getAttributes().get(Ec2FlowLogCfnProvisioner.TAG_KEYS_ATTR)); + } + + @Test + void rollingBackALogFromBeforeTheRecordLeavesNoRecord() { + StackResource r = reusedFlowLogWithTags(Map.of("team", "core")); + ObjectNode props = mapper.createObjectNode().put("ResourceId", "vpc-123"); + props.putArray("Tags").addObject().put("Key", "owner").put("Value", "core"); + provisioner.provision(r, props, updateCtx("fl-0abc", "team")); + + provisioner.rollbackUpdate(r); + + // Without a record the next update falls back to the previous template, as before. + assertFalse(r.getAttributes().containsKey(Ec2FlowLogCfnProvisioner.TAG_KEYS_ATTR)); + } + + @Test + void createRecordsTheTagKeysItWrote() { + when(flowLogs.createFlowLog(anyString(), any(), any(), any(), any(), any(), any(), any(), anyInt())) + .thenReturn(flowLog("fl-0abc")); + StackResource r = resource(); + ObjectNode props = mapper.createObjectNode().put("ResourceId", "vpc-123"); + props.putArray("Tags").addObject().put("Key", "team").put("Value", "core"); + + provisioner.provision(r, props, ctx()); + + assertEquals("[\"team\"]", r.getAttributes().get(Ec2FlowLogCfnProvisioner.TAG_KEYS_ATTR)); + } + + @Test + void droppingTheTemplatesTagsKeepsATagAddedOutsideTheStack() { + StackResource r = reusedFlowLogWithTags(Map.of("team", "core", "external", "preserve")); + + provisioner.provision(r, mapper.createObjectNode().put("ResourceId", "vpc-123"), updateCtx("fl-0abc", "team")); + + verify(ec2).deleteTags(eq("us-east-1"), eq(List.of("fl-0abc")), tags("team", "core")); + verify(ec2, never()).createTags(anyString(), any(), any()); + } + + @Test + void aReservedTagKeyCreatesNoFlowLog() { + ObjectNode props = mapper.createObjectNode().put("ResourceId", "vpc-123"); + props.putArray("Tags").addObject().put("Key", "aws:reserved").put("Value", "x"); + + assertThrows(AwsException.class, () -> provisioner.provision(resource(), props, ctx())); + + verify(flowLogs, never()).createFlowLog(anyString(), any(), any(), any(), any(), any(), any(), any(), anyInt()); + } + + @Test + void aTagValueTooLongCreatesNoFlowLog() { + ObjectNode props = mapper.createObjectNode().put("ResourceId", "vpc-123"); + props.putArray("Tags").addObject().put("Key", "team").put("Value", "v".repeat(257)); + + assertThrows(AwsException.class, () -> provisioner.provision(resource(), props, ctx())); + + verify(flowLogs, never()).createFlowLog(anyString(), any(), any(), any(), any(), any(), any(), any(), anyInt()); + } + + @Test + void aFailedTagWriteDeletesTheNewFlowLog() { + when(flowLogs.createFlowLog(anyString(), any(), any(), any(), any(), any(), any(), any(), anyInt())) + .thenReturn(flowLog("fl-0abc")); + doThrow(new AwsException("InternalError", "tag store down", 500)) + .when(ec2).createTags(anyString(), any(), any()); + ObjectNode props = mapper.createObjectNode().put("ResourceId", "vpc-123"); + props.putArray("Tags").addObject().put("Key", "team").put("Value", "core"); + + assertThrows(AwsException.class, () -> provisioner.provision(resource(), props, ctx())); + + // Otherwise the log outlives the failed stack, which recorded no id to delete. + verify(flowLogs).deleteFlowLogs("us-east-1", List.of("fl-0abc")); + } + + @Test + void rollbackPutsBackTheTagsAnUpdateChanged() { + StackResource r = reusedFlowLogWithTags(Map.of("old", "gone", "external", "preserve")); + ObjectNode props = mapper.createObjectNode().put("ResourceId", "vpc-123"); + props.putArray("Tags").addObject().put("Key", "team").put("Value", "core"); + provisioner.provision(r, props, updateCtx("fl-0abc", "old")); + assertTrue(r.getAttributes().containsKey(CfnRollback.FLOW_LOG_UPDATE_SNAPSHOT_ATTR)); + + // A later resource failed the update, so the stack rolls this one back. + assertTrue(provisioner.rollbackUpdate(r)); + + // The touched keys go back; the external tag was never touched, so it is not rewritten. + verify(ec2).createTags(eq("us-east-1"), eq(List.of("fl-0abc")), tags("old", "gone")); + assertFalse(r.getAttributes().containsKey(CfnRollback.FLOW_LOG_UPDATE_SNAPSHOT_ATTR)); + } + + @Test + void anUnchangedReuseLeavesNoTagSnapshot() { + StackResource r = reusedFlowLogWithTags(Map.of("team", "core", "external", "preserve")); + ObjectNode props = mapper.createObjectNode().put("ResourceId", "vpc-123"); + props.putArray("Tags").addObject().put("Key", "team").put("Value", "core"); + + provisioner.provision(r, props, updateCtx("fl-0abc", "team")); + + assertFalse(r.getAttributes().containsKey(CfnRollback.FLOW_LOG_UPDATE_SNAPSHOT_ATTR)); + assertTrue(provisioner.rollbackUpdate(r)); + } + + @Test + void aCommittedUpdateDropsTheTagSnapshot() { + StackResource r = reusedFlowLogWithTags(Map.of("old", "gone", "external", "preserve")); + ObjectNode props = mapper.createObjectNode().put("ResourceId", "vpc-123"); + props.putArray("Tags").addObject().put("Key", "team").put("Value", "core"); + provisioner.provision(r, props, updateCtx("fl-0abc", "old")); + + provisioner.completeUpdate(r); + + assertFalse(r.getAttributes().containsKey(CfnRollback.FLOW_LOG_UPDATE_SNAPSHOT_ATTR)); + } + + @Test + void rollbackDeletesAFlowLogTheUpdateRecreated() { + StackResource r = resource(); + r.setPhysicalId("fl-gone"); + r.getAttributes().put(Ec2FlowLogCfnProvisioner.TAG_KEYS_ATTR, "[\"team\"]"); + when(flowLogs.describeFlowLogs("us-east-1", List.of("fl-gone"))).thenReturn(List.of()); + when(flowLogs.createFlowLog(anyString(), any(), any(), any(), any(), any(), any(), any(), anyInt())) + .thenReturn(flowLog("fl-new")); + provisioner.provision(r, mapper.createObjectNode().put("ResourceId", "vpc-123"), updateCtx("fl-gone")); + assertEquals("fl-new", r.getPhysicalId()); + + assertTrue(provisioner.rollbackUpdate(r)); + + // Otherwise the rolled-back stack keeps the failed update's log. + verify(flowLogs).deleteFlowLogs("us-east-1", List.of("fl-new")); + assertEquals("fl-gone", r.getPhysicalId()); + assertEquals("[\"team\"]", r.getAttributes().get(Ec2FlowLogCfnProvisioner.TAG_KEYS_ATTR)); + assertEquals("fl-gone", r.getAttributes().get("Id")); + assertFalse(r.getAttributes().containsKey(CfnRollback.FLOW_LOG_UPDATE_SNAPSHOT_ATTR)); + } + + /** A stack resource pointing at a stored flow log that EC2 reports {@code tags} on. */ + private StackResource reusedFlowLogWithTags(Map tags) { + 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)); + when(ec2.describeTags("us-east-1", Map.of("resource-id", List.of("fl-0abc")))) + .thenReturn(new TreeMap<>(tags).entrySet().stream() + .map(tag -> Map.of("key", tag.getKey(), "value", tag.getValue())).toList()); + return r; + } + @Test void deleteRemovesTheFlowLog() { provisioner.delete("AWS::EC2::FlowLog", "fl-0abc", "us-east-1"); diff --git a/src/test/resources/cloudformation/writable-property-gaps.tsv b/src/test/resources/cloudformation/writable-property-gaps.tsv index c487553ca8..3b484286e2 100644 --- a/src/test/resources/cloudformation/writable-property-gaps.tsv +++ b/src/test/resources/cloudformation/writable-property-gaps.tsv @@ -188,7 +188,6 @@ AWS::EC2::FlowLog DeliverCrossAccountRole accepted and ignored AWS::EC2::FlowLog DestinationOptions accepted and ignored AWS::EC2::FlowLog LogGroupName accepted and ignored AWS::EC2::FlowLog TagFieldSpecifications accepted and ignored -AWS::EC2::FlowLog Tags accepted and ignored AWS::EC2::Instance AdditionalInfo accepted and ignored AWS::EC2::Instance Affinity accepted and ignored AWS::EC2::Instance BlockDeviceMappings accepted and ignored diff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yaml index 2c8cc62ccd..cc8ec513e6 100644 --- a/tools/docs/cfn_resource_types.yaml +++ b/tools/docs/cfn_resource_types.yaml @@ -192,6 +192,7 @@ notes: AWS::Lambda::WebFunctionRevision: every property is createOnly, so a change mints a new revision AWS::EC2::VPC: 'deleted on stack teardown; a VPC with dependents outside the stack, including anything still holding a network interface in its subnets (an instance that is not terminated, a NAT gateway that is not deleted or failed, a standalone interface, an interface endpoint), fails the delete with `DependencyViolation`, as on AWS' AWS::EC2::SecurityGroup: inline `SecurityGroupIngress`/`SecurityGroupEgress` supported + AWS::EC2::FlowLog: '`Tags` are applied and updated in place, keeping tags added outside the stack; any other change fails, since it needs a replacement' AWS::EC2::KeyPair: 'a created key''s private key is stored in the `SecureString` parameter `/ec2/keypair/`, as on AWS, and deleted with the key' AWS::EC2::NatGateway: 'zonal; `AvailabilityMode` regional fails; a change to the `Secondary*` address properties updates the gateway in place' AWS::EC2::PrefixList: 'updated in place; an update that changes `AddressFamily`, or `MaxEntries` together with `Entries`, fails'