fix(cloudformation): apply an AWS::EC2::FlowLog's Tags (#7490)

This commit is contained in:
Ronald Li 🛠️ authored and GitHub committed 2026-11-04 06:49:14 -04:00
1 parent 7b4e568ce4
commit dbbf22957f
10 files changed
+620 -19

No files matched your search

@@ -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));
@@ -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<String, String> tags(String flowLogId) {
Map<String, String> tags = new TreeMap<>();
ec2.describeFlowLogs(request -> request.flowLogIds(flowLogId)).flowLogs().getFirst().tags()
.forEach(tag -> tags.put(tag.key(), tag.value()));
return tags;
}
}
@@ -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("<key>flow-tag</key><value>" + suffix + "</value>"));
// The account-level CloudWatch role reached the API Gateway account settings.
given()
@@ -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<Tag> 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<String, String> 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");