feat(ec2): add VPC Flow Logs (#1611)

* feat(ec2): add VPC Flow Logs

Add VPC Flow Logs (CreateFlowLogs/DescribeFlowLogs/DeleteFlowLogs) with a
background generator that synthesizes realistic flow records and delivers them
to S3 in the AWS default (v5) record format and key layout
(AWSLogs/{account}/vpcflowlogs/{region}/.../*.log.gz, gzipped), correlated to
existing EC2 instances. Also seed the SecurityAudit IAM managed policy.

Carved down from #1224 and rebased on main: the original PR also re-added
Interface VPC Endpoints, which main already implements (#1252, #1476), so
those were dropped. PrivateLink-endpoint enrichment of flow records is omitted
accordingly; Ec2Service.endpointNetworkInterfaces() is an empty seam for a
future per-endpoint-ENI implementation.

Refs #1224

* fix(ec2): persist flow logs via StorageFactory and scope deletes by region

Address review comments on the VPC Flow Logs PR:

- store flow logs through StorageFactory so they survive restarts in
  persistent/hybrid/wal modes and generation resumes automatically
- scope DeleteFlowLogs to the request region, matching DescribeFlowLogs
- synthesize deterministic PrivateLink ENIs for interface VPC endpoints
  in endpointNetworkInterfaces, making the pkt-*-aws-service enrichment
  path live instead of dead code
- resolve the endpoint's real service short name from the ENI
  description instead of hardcoding S3

---------

Co-authored-by: skwolvie <skwolvie@users.noreply.github.com>
This commit is contained in:
Hector Venturaandskwolvie authored and GitHub committed 2026-07-01 23:55:21 -05:00
1 parent 2cca03bf25
commit 32ea710b68
10 files changed
+1077 -1

No files matched your search

@@ -0,0 +1,144 @@
package io.github.hectorvent.floci.services.ec2;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.startsWith;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
/**
* Integration tests for VPC Flow Logs via the EC2 Query Protocol
* (form-encoded POST, XML response).
*
* <p>Covers {@code CreateFlowLogs} / {@code DescribeFlowLogs} / {@code DeleteFlowLogs}.</p>
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class Ec2FlowLogIntegrationTest {
private static final String AUTH_HEADER =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request";
private static String vpcId;
private static String flowLogId;
// =========================================================================
// Fixture: a VPC to attach the flow log to
// =========================================================================
@Test
@Order(1)
void createVpc() {
vpcId = given()
.formParam("Action", "CreateVpc")
.formParam("CidrBlock", "10.20.0.0/16")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.contentType("application/xml")
.body("CreateVpcResponse.vpc.state", equalTo("available"))
.extract().path("CreateVpcResponse.vpc.vpcId");
}
// =========================================================================
// VPC Flow Logs
// =========================================================================
@Test
@Order(10)
void createFlowLogs() {
flowLogId = given()
.formParam("Action", "CreateFlowLogs")
.formParam("ResourceType", "VPC")
.formParam("ResourceId.1", vpcId)
.formParam("TrafficType", "ALL")
.formParam("LogDestinationType", "s3")
.formParam("LogDestination", "arn:aws:s3:::flow-logs-test-bucket")
.formParam("MaxAggregationInterval", "60")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.contentType("application/xml")
.body("CreateFlowLogsResponse.flowLogIdSet.item[0]", startsWith("fl-"))
.extract().path("CreateFlowLogsResponse.flowLogIdSet.item[0]");
}
@Test
@Order(11)
void describeFlowLogsReturnsTheCreatedLog() {
given()
.formParam("Action", "DescribeFlowLogs")
.formParam("FlowLogId.1", flowLogId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.contentType("application/xml")
.body("DescribeFlowLogsResponse.flowLogSet.item[0].flowLogId", equalTo(flowLogId))
.body("DescribeFlowLogsResponse.flowLogSet.item[0].resourceId", equalTo(vpcId))
.body("DescribeFlowLogsResponse.flowLogSet.item[0].trafficType", equalTo("ALL"))
.body("DescribeFlowLogsResponse.flowLogSet.item[0].logDestinationType", equalTo("s3"))
.body("DescribeFlowLogsResponse.flowLogSet.item[0].logDestination",
equalTo("arn:aws:s3:::flow-logs-test-bucket"))
.body("DescribeFlowLogsResponse.flowLogSet.item[0].maxAggregationInterval", equalTo("60"));
}
@Test
@Order(12)
void deleteFlowLogsInAnotherRegionLeavesTheLogIntact() {
given()
.formParam("Action", "DeleteFlowLogs")
.formParam("FlowLogId.1", flowLogId)
.header("Authorization",
"AWS4-HMAC-SHA256 Credential=test/20260205/eu-west-1/ec2/aws4_request")
.when()
.post("/")
.then()
.statusCode(200)
.contentType("application/xml");
given()
.formParam("Action", "DescribeFlowLogs")
.formParam("FlowLogId.1", flowLogId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeFlowLogsResponse.flowLogSet.item[0].flowLogId", equalTo(flowLogId));
}
@Test
@Order(13)
void deleteFlowLogs() {
given()
.formParam("Action", "DeleteFlowLogs")
.formParam("FlowLogId.1", flowLogId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.contentType("application/xml");
// After deletion, describing all flow logs must not return the deleted id.
given()
.formParam("Action", "DescribeFlowLogs")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeFlowLogsResponse.flowLogSet.findAll { it.flowLogId == '" + flowLogId + "' }.size()",
equalTo(0));
}
}
@@ -10,9 +10,11 @@ import io.github.hectorvent.floci.services.ec2.portforward.Ec2PortForwardManager
import io.github.hectorvent.floci.services.ec2.model.GroupIdentifier;
import io.github.hectorvent.floci.services.ec2.model.Instance;
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate;
import io.github.hectorvent.floci.services.ec2.model.NetworkInterface;
import io.github.hectorvent.floci.services.ec2.model.Reservation;
import io.github.hectorvent.floci.services.ec2.model.SecurityGroup;
import io.github.hectorvent.floci.services.ec2.model.Tag;
import io.github.hectorvent.floci.services.ec2.model.VpcEndpoint;
import org.junit.jupiter.api.Test;
import java.util.List;
@@ -122,6 +124,38 @@ class Ec2ServiceTest {
assertEquals(List.of("arm64"), types.getFirst().get("supportedArchitectures"));
}
@Test
void endpointNetworkInterfacesSynthesizesStableEnisForInterfaceEndpoints() {
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class),
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
new InMemoryStorageFactory());
String subnetId = service.describeSubnets("us-east-1", List.of(),
Map.of("vpc-id", List.of("vpc-default"))).getFirst().getSubnetId();
VpcEndpoint endpoint = service.createVpcEndpoint("us-east-1", "vpc-default",
"com.amazonaws.us-east-1.s3", "Interface",
List.of(), List.of(subnetId), List.of(), null, List.of());
service.createVpcEndpoint("us-east-1", "vpc-default",
"com.amazonaws.us-east-1.dynamodb", "Gateway",
List.of(), List.of(), List.of(), null, List.of());
List<NetworkInterface> enis = service.endpointNetworkInterfaces("us-east-1");
assertEquals(1, enis.size(), "only Interface endpoints have ENIs");
NetworkInterface eni = enis.getFirst();
assertEquals(subnetId, eni.getSubnetId());
assertEquals("vpc-default", eni.getVpcId());
assertEquals("VPC Endpoint Interface " + endpoint.getVpcEndpointId(), eni.getDescription());
assertTrue(eni.getNetworkInterfaceId().startsWith("eni-"));
NetworkInterface again = service.endpointNetworkInterfaces("us-east-1").getFirst();
assertEquals(eni.getNetworkInterfaceId(), again.getNetworkInterfaceId());
assertEquals(eni.getPrivateIpAddress(), again.getPrivateIpAddress());
assertTrue(service.endpointNetworkInterfaces("eu-west-1").isEmpty(),
"endpoints are regional");
}
@Test
void modifyInstanceGroupsReassignsSecurityGroupsOnInstanceAndEni() {
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
@@ -0,0 +1,53 @@
package io.github.hectorvent.floci.services.ec2;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.ec2.model.FlowLog;
import io.github.hectorvent.floci.services.s3.S3Service;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class FlowLogServiceTest {
private FlowLogService flowLogService;
@BeforeEach
void setUp() {
EmulatorConfig config = mock(EmulatorConfig.class);
when(config.defaultAccountId()).thenReturn("000000000000");
Ec2Service ec2Service = mock(Ec2Service.class);
when(ec2Service.describeInstances(any(), any(), any())).thenReturn(List.of());
when(ec2Service.endpointNetworkInterfaces(any())).thenReturn(List.of());
flowLogService = new FlowLogService(config, ec2Service, mock(S3Service.class),
new InMemoryStorage<>());
}
@Test
void deleteFlowLogsIsScopedToTheRequestRegion() {
FlowLog fl = flowLogService.createFlowLog("us-east-1", "vpc-123", "VPC", "ALL",
"s3", "arn:aws:s3:::flow-bucket", null, 600);
List<String> otherRegion = flowLogService.deleteFlowLogs("eu-west-1", List.of(fl.getFlowLogId()));
assertTrue(otherRegion.isEmpty(), "delete must not cross regions");
assertEquals(1, flowLogService.describeFlowLogs("us-east-1", List.of()).size());
List<String> sameRegion = flowLogService.deleteFlowLogs("us-east-1", List.of(fl.getFlowLogId()));
assertEquals(List.of(fl.getFlowLogId()), sameRegion);
assertTrue(flowLogService.describeFlowLogs("us-east-1", List.of()).isEmpty());
}
@Test
void deleteFlowLogsIgnoresUnknownIds() {
assertTrue(flowLogService.deleteFlowLogs("us-east-1", List.of("fl-doesnotexist")).isEmpty());
}
}
@@ -0,0 +1,72 @@
package io.github.hectorvent.floci.services.iam;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
/**
* Verifies the AWS-managed {@code SecurityAudit} policy is resolvable and
* attachable. {@code SecurityAudit} is a standard AWS managed policy commonly
* attached to read-only auditing roles; {@code AttachRolePolicy} fails if the
* managed policy is not present in the emulator's seed list.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class SecurityAuditManagedPolicyIntegrationTest {
private static final String IAM_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/iam/aws4_request";
private static final String SECURITY_AUDIT_ARN =
"arn:aws:iam::aws:policy/SecurityAudit";
private static final String TRUST_POLICY =
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ "\"Principal\":{\"Service\":\"ec2.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}";
@Test
@Order(1)
void getSecurityAuditManagedPolicy() {
given()
.formParam("Action", "GetPolicy")
.formParam("PolicyArn", SECURITY_AUDIT_ARN)
.header("Authorization", IAM_AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.contentType("application/xml")
.body("GetPolicyResponse.GetPolicyResult.Policy.PolicyName", equalTo("SecurityAudit"))
.body("GetPolicyResponse.GetPolicyResult.Policy.Arn", equalTo(SECURITY_AUDIT_ARN));
}
@Test
@Order(2)
void attachSecurityAuditToRole() {
given()
.formParam("Action", "CreateRole")
.formParam("RoleName", "SecurityAuditTestRole")
.formParam("Path", "/")
.formParam("AssumeRolePolicyDocument", TRUST_POLICY)
.header("Authorization", IAM_AUTH)
.when()
.post("/")
.then()
.statusCode(200);
given()
.formParam("Action", "AttachRolePolicy")
.formParam("RoleName", "SecurityAuditTestRole")
.formParam("PolicyArn", SECURITY_AUDIT_ARN)
.header("Authorization", IAM_AUTH)
.when()
.post("/")
.then()
.statusCode(200);
}
}