mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(ec2): keep a flow log's CloudWatch log group and default its destination type (#7197)
* fix(ec2): keep a flow log's CloudWatch log group and default its destination type CreateFlowLogs dropped LogGroupName, so DescribeFlowLogs never returned it and the Terraform provider saw a perpetual diff. Store it (deriving it from a log-group ARN LogDestination when only that is given), return it in DescribeFlowLogs, and default LogDestinationType to cloud-watch-logs when a log group is supplied without a type. * fix(ec2): only a CloudWatch Logs ARN implies a flow log's log group A LogDestination was treated as CloudWatch whenever it contained ':log-group:', so an S3 prefix such as arn:aws:s3:::bkt/archive:log-group:x/ with LogDestinationType omitted became cloud-watch-logs and was never delivered. Parse the ARN and require the logs service. The CloudFormation update check defaulted an omitted LogDestinationType to s3 while create now derives cloud-watch-logs from a log-group ARN, so an unchanged stack update was rejected as a replacement. Both now go through one effectiveLogDestinationType. * fix(ec2): a logs ARN with no group name is not a CloudWatch flow log destination logGroupFromArn returned an empty name for arn:aws:logs:...:log-group: (and log-group::*), so the destination type became cloud-watch-logs with a blank group. Treat a blank name as no group, so the type falls back to s3. * test(ec2): use the shared InMemoryStorageFactory in the flow log CFN test Replaces the hand-rolled StorageFactory mock with the existing test factory, which hands out the same account-scoped in-memory store.
This commit is contained in:
1 parent
7bae152c69
commit
3e0d8d640b
7 files changed
+177
-4
No files matched your search
+2
-2
@@ -25,7 +25,6 @@ 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 String DEFAULT_LOG_DESTINATION_TYPE = "s3";
|
||||
|
||||
private final FlowLogService flowLogService;
|
||||
|
||||
@@ -90,7 +89,8 @@ public class Ec2FlowLogCfnProvisioner implements CfnResourceProvisioner {
|
||||
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));
|
||||
FlowLogService.effectiveLogDestinationType(ctx.resolveOptional(props, "LogDestinationType"),
|
||||
ctx.resolveOptional(props, "LogDestination"), null));
|
||||
rejectIfChanged("LogDestination", existing.getLogDestination(),
|
||||
ctx.resolveOptional(props, "LogDestination"));
|
||||
rejectIfChanged("DeliverLogsPermissionArn", existing.getDeliverLogsPermissionArn(),
|
||||
|
||||
@@ -2015,6 +2015,7 @@ public class Ec2QueryHandler {
|
||||
if (logDestination == null) {
|
||||
logDestination = p.getFirst("LogDestinationArn");
|
||||
}
|
||||
String logGroupName = p.getFirst("LogGroupName");
|
||||
String deliverLogsPermissionArn = p.getFirst("DeliverLogsPermissionArn");
|
||||
String logFormat = p.getFirst("LogFormat");
|
||||
int maxAgg = parseIntParam(p, "MaxAggregationInterval", 600);
|
||||
@@ -2034,7 +2035,7 @@ public class Ec2QueryHandler {
|
||||
List<Tag> flowLogTags = parseTagsForResource(p, "vpc-flow-log");
|
||||
for (String resourceId : resourceIds) {
|
||||
FlowLog fl = flowLogService.createFlowLog(region, resourceId, resourceType, trafficType,
|
||||
logDestinationType, logDestination, deliverLogsPermissionArn, logFormat, maxAgg);
|
||||
logDestinationType, logDestination, logGroupName, deliverLogsPermissionArn, logFormat, maxAgg);
|
||||
if (!flowLogTags.isEmpty()) {
|
||||
service.createTags(region, List.of(fl.getFlowLogId()), flowLogTags);
|
||||
}
|
||||
@@ -2063,6 +2064,7 @@ public class Ec2QueryHandler {
|
||||
.elem("trafficType", fl.getTrafficType())
|
||||
.elem("logDestinationType", fl.getLogDestinationType())
|
||||
.elem("logDestination", fl.getLogDestination())
|
||||
.elem("logGroupName", fl.getLogGroupName())
|
||||
.elem("deliverLogsPermissionArn", fl.getDeliverLogsPermissionArn())
|
||||
.elem("flowLogStatus", fl.getFlowLogStatus())
|
||||
.elem("logFormat", fl.getLogFormat() != null
|
||||
|
||||
@@ -156,12 +156,23 @@ public class FlowLogService {
|
||||
String trafficType, String logDestinationType,
|
||||
String logDestination, String deliverLogsPermissionArn,
|
||||
String logFormat, int maxAggregationInterval) {
|
||||
return createFlowLog(region, resourceId, resourceType, trafficType, logDestinationType,
|
||||
logDestination, null, deliverLogsPermissionArn, logFormat, maxAggregationInterval);
|
||||
}
|
||||
|
||||
public FlowLog createFlowLog(String region, String resourceId, String resourceType,
|
||||
String trafficType, String logDestinationType,
|
||||
String logDestination, String logGroupName,
|
||||
String deliverLogsPermissionArn,
|
||||
String logFormat, int maxAggregationInterval) {
|
||||
String groupName = logGroupName != null ? logGroupName : logGroupFromArn(logDestination);
|
||||
FlowLog fl = new FlowLog();
|
||||
fl.setFlowLogId("fl-" + randomHex(17));
|
||||
fl.setResourceId(resourceId);
|
||||
fl.setResourceType(resourceType != null ? resourceType : "VPC");
|
||||
fl.setTrafficType(trafficType != null ? trafficType : "ALL");
|
||||
fl.setLogDestinationType(logDestinationType != null ? logDestinationType : "s3");
|
||||
fl.setLogDestinationType(effectiveLogDestinationType(logDestinationType, logDestination, logGroupName));
|
||||
fl.setLogGroupName(groupName);
|
||||
fl.setLogDestination(logDestination);
|
||||
fl.setDeliverLogsPermissionArn(deliverLogsPermissionArn);
|
||||
fl.setBucketName(bucketFromArn(logDestination));
|
||||
@@ -569,6 +580,34 @@ public class FlowLogService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The LogDestinationType a flow log gets: the requested one, else cloud-watch-logs when a log
|
||||
* group is named directly or by a CloudWatch Logs ARN, else s3. CloudFormation compares an
|
||||
* update against this, so create and compare cannot drift apart.
|
||||
*/
|
||||
public static String effectiveLogDestinationType(String logDestinationType, String logDestination,
|
||||
String logGroupName) {
|
||||
if (logDestinationType != null && !logDestinationType.isBlank()) {
|
||||
return logDestinationType;
|
||||
}
|
||||
return logGroupName != null || logGroupFromArn(logDestination) != null ? "cloud-watch-logs" : "s3";
|
||||
}
|
||||
|
||||
/**
|
||||
* The group named by a CloudWatch Logs ARN ({@code arn:aws:logs:r:a:log-group:name[:*]}), or
|
||||
* null for anything else. Only a {@code logs} ARN counts: an S3 prefix may itself contain
|
||||
* {@code :log-group:}.
|
||||
*/
|
||||
static String logGroupFromArn(String arn) {
|
||||
String resource = AwsArnUtils.resourceIfArnFor(arn, "logs").orElse("");
|
||||
if (!resource.startsWith("log-group:")) {
|
||||
return null;
|
||||
}
|
||||
String name = resource.substring("log-group:".length());
|
||||
name = name.endsWith(":*") ? name.substring(0, name.length() - 2) : name;
|
||||
return name.isBlank() ? null : name;
|
||||
}
|
||||
|
||||
static String bucketFromArn(String arn) {
|
||||
if (arn == null) {
|
||||
return null;
|
||||
|
||||
@@ -25,6 +25,7 @@ public class FlowLog {
|
||||
private String trafficType; // ALL | ACCEPT | REJECT
|
||||
private String logDestinationType; // s3 | cloud-watch-logs
|
||||
private String logDestination; // S3 bucket ARN, e.g. arn:aws:s3:::flow-logs-bucket
|
||||
private String logGroupName; // CloudWatch Logs group, for cloud-watch-logs flow logs
|
||||
private String deliverLogsPermissionArn; // IAM role ARN used for cloud-watch-logs delivery
|
||||
private String bucketName; // resolved bucket name from the ARN
|
||||
private String logFormat; // optional custom format string (default format used if null)
|
||||
@@ -53,6 +54,9 @@ public class FlowLog {
|
||||
public String getLogDestination() { return logDestination; }
|
||||
public void setLogDestination(String logDestination) { this.logDestination = logDestination; }
|
||||
|
||||
public String getLogGroupName() { return logGroupName; }
|
||||
public void setLogGroupName(String logGroupName) { this.logGroupName = logGroupName; }
|
||||
|
||||
public String getDeliverLogsPermissionArn() { return deliverLogsPermissionArn; }
|
||||
public void setDeliverLogsPermissionArn(String deliverLogsPermissionArn) {
|
||||
this.deliverLogsPermissionArn = deliverLogsPermissionArn;
|
||||
|
||||
+27
@@ -6,8 +6,11 @@ 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.Ec2Service;
|
||||
import io.github.hectorvent.floci.services.ec2.FlowLogService;
|
||||
import io.github.hectorvent.floci.services.ec2.model.FlowLog;
|
||||
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;
|
||||
@@ -196,6 +199,30 @@ class Ec2FlowLogCfnProvisionerTest {
|
||||
assertEquals("ValidationError", e.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void reapplyingACloudWatchTemplateThatOmitsTheDestinationTypeIsANoOp() {
|
||||
// A real FlowLogService, so the update is compared against what create actually stored:
|
||||
// a CloudWatch Logs ARN with no LogDestinationType is stored as cloud-watch-logs, and the
|
||||
// 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);
|
||||
ObjectNode props = mapper.createObjectNode()
|
||||
.put("ResourceId", "vpc-123")
|
||||
.put("LogDestination", "arn:aws:logs:us-east-1:000000000000:log-group:flows")
|
||||
.put("DeliverLogsPermissionArn", "arn:aws:iam::000000000000:role/flow-logs-role");
|
||||
StackResource r = resource();
|
||||
|
||||
p.provision(r, props, ctx());
|
||||
String created = r.getPhysicalId();
|
||||
p.provision(r, props, ctx());
|
||||
|
||||
assertEquals(created, r.getPhysicalId());
|
||||
List<FlowLog> logs = real.describeFlowLogs("us-east-1", List.of());
|
||||
assertEquals(1, logs.size());
|
||||
assertEquals("cloud-watch-logs", logs.get(0).getLogDestinationType());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateRecreatesAFlowLogRemovedOutOfBand() {
|
||||
StackResource r = resource();
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package io.github.hectorvent.floci.services.ec2;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -190,4 +192,67 @@ class Ec2FlowLogIntegrationTest {
|
||||
.body("DescribeFlowLogsResponse.flowLogSet.findAll { it.flowLogId == '" + flowLogId + "' }.size()",
|
||||
equalTo(0));
|
||||
}
|
||||
|
||||
private static String createFlowLogWith(String... extraParams) {
|
||||
RequestSpecification req = given()
|
||||
.formParam("Action", "CreateFlowLogs")
|
||||
.formParam("ResourceType", "VPC")
|
||||
.formParam("ResourceId.1", vpcId)
|
||||
.formParam("TrafficType", "ALL")
|
||||
.header("Authorization", AUTH_HEADER);
|
||||
for (int i = 0; i < extraParams.length; i += 2) {
|
||||
req = req.formParam(extraParams[i], extraParams[i + 1]);
|
||||
}
|
||||
return req.when().post("/").then().statusCode(200)
|
||||
.extract().path("CreateFlowLogsResponse.flowLogIdSet.item[0]");
|
||||
}
|
||||
|
||||
private static ValidatableResponse describe(String id) {
|
||||
return given()
|
||||
.formParam("Action", "DescribeFlowLogs")
|
||||
.formParam("FlowLogId.1", id)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(15)
|
||||
void cloudWatchFlowLogKeepsItsLogGroupName() {
|
||||
String id = createFlowLogWith(
|
||||
"LogDestinationType", "cloud-watch-logs",
|
||||
"LogGroupName", "/rep/fl",
|
||||
"DeliverLogsPermissionArn", "arn:aws:iam::000000000000:role/flow-logs-role");
|
||||
|
||||
describe(id)
|
||||
.body("DescribeFlowLogsResponse.flowLogSet.item[0].logGroupName", equalTo("/rep/fl"))
|
||||
.body("DescribeFlowLogsResponse.flowLogSet.item[0].logDestinationType", equalTo("cloud-watch-logs"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(16)
|
||||
void logGroupNameWithoutADestinationTypeDefaultsToCloudWatchLogs() {
|
||||
String id = createFlowLogWith("LogGroupName", "/rep/fl-default");
|
||||
|
||||
describe(id)
|
||||
.body("DescribeFlowLogsResponse.flowLogSet.item[0].logGroupName", equalTo("/rep/fl-default"))
|
||||
.body("DescribeFlowLogsResponse.flowLogSet.item[0].logDestinationType", equalTo("cloud-watch-logs"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(17)
|
||||
void s3FlowLogHasNoLogGroupName() {
|
||||
String id = createFlowLogWith(
|
||||
"LogDestinationType", "s3",
|
||||
"LogDestination", "arn:aws:s3:::flow-logs-test-bucket-2");
|
||||
|
||||
describe(id)
|
||||
.body("DescribeFlowLogsResponse.flowLogSet.item[0].logDestinationType", equalTo("s3"))
|
||||
.body("DescribeFlowLogsResponse.flowLogSet.item[0].logDestination",
|
||||
equalTo("arn:aws:s3:::flow-logs-test-bucket-2"))
|
||||
.body("DescribeFlowLogsResponse.flowLogSet.item[0].children().findAll { it.name() == 'logGroupName' }.size()",
|
||||
equalTo(0));
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import java.util.zip.GZIPInputStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyMap;
|
||||
@@ -257,6 +258,41 @@ class FlowLogServiceTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void anS3PrefixContainingLogGroupStaysS3AndDelivers() {
|
||||
// Only a logs ARN names a log group; an S3 prefix may contain ":log-group:" too.
|
||||
Ec2Service ec2Service = mock(Ec2Service.class);
|
||||
when(ec2Service.callerAccountId()).thenReturn("000000000000");
|
||||
when(ec2Service.describeInstances(any(), any(), anyMap()))
|
||||
.thenReturn(List.of(reservation("us-east-1")));
|
||||
when(ec2Service.endpointNetworkInterfaces(any())).thenReturn(List.of());
|
||||
S3Service s3Service = mock(S3Service.class);
|
||||
FlowLogService service = new FlowLogService(ec2Service, s3Service, new InMemoryStorage<>());
|
||||
|
||||
FlowLog fl = service.createFlowLog("us-east-1", "vpc-123", "VPC", "ALL", null,
|
||||
"arn:aws:s3:::bkt/archive:log-group:daily/", null, null, 600);
|
||||
|
||||
FlowLog stored = service.describeFlowLogs("us-east-1", List.of(fl.getFlowLogId())).get(0);
|
||||
assertEquals("s3", stored.getLogDestinationType());
|
||||
assertNull(stored.getLogGroupName());
|
||||
verify(s3Service).putObject(eq("bkt"), anyString(), any(byte[].class), anyString(), any(Map.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLogsArnNamesItsLogGroup() {
|
||||
assertEquals("/aws/flows", FlowLogService.logGroupFromArn("arn:aws:logs:us-east-1:000000000000:log-group:/aws/flows:*"));
|
||||
assertEquals("flows", FlowLogService.logGroupFromArn("arn:aws-cn:logs:cn-north-1:000000000000:log-group:flows"));
|
||||
assertNull(FlowLogService.logGroupFromArn("arn:aws:s3:::bkt/archive:log-group:daily/"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLogsArnWithNoGroupNameIsNotACloudWatchDestination() {
|
||||
assertNull(FlowLogService.logGroupFromArn("arn:aws:logs:us-east-1:000000000000:log-group:"));
|
||||
assertNull(FlowLogService.logGroupFromArn("arn:aws:logs:us-east-1:000000000000:log-group::*"));
|
||||
assertEquals("s3", FlowLogService.effectiveLogDestinationType(null,
|
||||
"arn:aws:logs:us-east-1:000000000000:log-group:", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void bucketComesFromTheS3ArnEvenWhenThePrefixHasAColon() {
|
||||
assertEquals("bkt", FlowLogService.bucketFromArn("arn:aws:s3:::bkt/logs:2024/"));
|
||||
|
||||
Reference in new issue
Block a user