From 32ea710b68c0b8b4134e5d6cfd0c5c510ea9e950 Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Wed, 1 Jul 2026 23:55:21 -0500 Subject: [PATCH] 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 --- .../floci/core/common/AwsQueryController.java | 1 + .../floci/services/ec2/Ec2QueryHandler.java | 86 ++- .../floci/services/ec2/Ec2Service.java | 48 ++ .../floci/services/ec2/FlowLogService.java | 559 ++++++++++++++++++ .../floci/services/ec2/model/FlowLog.java | 78 +++ .../services/iam/AwsManagedPolicies.java | 3 + .../ec2/Ec2FlowLogIntegrationTest.java | 144 +++++ .../floci/services/ec2/Ec2ServiceTest.java | 34 ++ .../services/ec2/FlowLogServiceTest.java | 53 ++ ...rityAuditManagedPolicyIntegrationTest.java | 72 +++ 10 files changed, 1077 insertions(+), 1 deletion(-) create mode 100644 src/main/java/io/github/hectorvent/floci/services/ec2/FlowLogService.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/ec2/model/FlowLog.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/ec2/Ec2FlowLogIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/ec2/FlowLogServiceTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/iam/SecurityAuditManagedPolicyIntegrationTest.java diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java index 6ac7a8820d..66f5e45523 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java @@ -175,6 +175,7 @@ public class AwsQueryController { "CreateLaunchTemplate", "CreateLaunchTemplateVersion", "DescribeLaunchTemplates", "DescribeLaunchTemplateVersions", "ModifyLaunchTemplate", "DeleteLaunchTemplate", "DescribeNetworkInterfaces", + "CreateFlowLogs", "DescribeFlowLogs", "DeleteFlowLogs", "CreateVolume", "DescribeVolumes", "DeleteVolume" ); diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java index 55758026c0..45eccde689 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java @@ -29,11 +29,13 @@ public class Ec2QueryHandler { private final Ec2Service service; private final EmulatorConfig config; + private final FlowLogService flowLogService; @Inject - public Ec2QueryHandler(Ec2Service service, EmulatorConfig config) { + public Ec2QueryHandler(Ec2Service service, EmulatorConfig config, FlowLogService flowLogService) { this.service = service; this.config = config; + this.flowLogService = flowLogService; } public Response handle(String action, MultivaluedMap params, String region) { @@ -62,6 +64,10 @@ public class Ec2QueryHandler { case "CreateVpcEndpoint" -> handleCreateVpcEndpoint(params, region); case "DescribeVpcEndpoints" -> handleDescribeVpcEndpoints(params, region); case "DeleteVpcEndpoints" -> handleDeleteVpcEndpoints(params, region); + // Flow Logs + case "CreateFlowLogs" -> handleCreateFlowLogs(params, region); + case "DescribeFlowLogs" -> handleDescribeFlowLogs(params, region); + case "DeleteFlowLogs" -> handleDeleteFlowLogs(params, region); case "DescribePrefixLists" -> handleDescribePrefixLists(params, region); case "CreateDefaultVpc" -> handleCreateDefaultVpc(params, region); case "AssociateVpcCidrBlock" -> handleAssociateVpcCidrBlock(params, region); @@ -719,6 +725,84 @@ public class Ec2QueryHandler { return xmlResponse(xml.build()); } + // ─── Flow Logs ──────────────────────────────────────────────────────────── + + private Response handleCreateFlowLogs(MultivaluedMap p, String region) { + String resourceType = p.getFirst("ResourceType"); + List resourceIds = getList(p, "ResourceId"); + String trafficType = p.getFirst("TrafficType"); + String logDestinationType = p.getFirst("LogDestinationType"); + String logDestination = p.getFirst("LogDestination"); + if (logDestination == null) { + logDestination = p.getFirst("LogDestinationArn"); + } + String logFormat = p.getFirst("LogFormat"); + int maxAgg = parseIntParam(p, "MaxAggregationInterval", 600); + + if (resourceIds.isEmpty()) { + // Some SDKs send ResourceIds.member.N — fall back to that prefix. + resourceIds = getList(p, "ResourceIds.member"); + } + if (resourceIds.isEmpty()) { + return ec2Error("MissingParameter", "The request must contain at least one ResourceId.", 400); + } + + XmlBuilder xml = new XmlBuilder() + .start("CreateFlowLogsResponse", AwsNamespaces.EC2) + .elem("requestId", UUID.randomUUID().toString()) + .start("flowLogIdSet"); + for (String resourceId : resourceIds) { + FlowLog fl = flowLogService.createFlowLog(region, resourceId, resourceType, trafficType, + logDestinationType, logDestination, logFormat, maxAgg); + xml.elem("item", fl.getFlowLogId()); + } + xml.end("flowLogIdSet") + .start("unsuccessful").end("unsuccessful") + .end("CreateFlowLogsResponse"); + return xmlResponse(xml.build()); + } + + private Response handleDescribeFlowLogs(MultivaluedMap p, String region) { + List ids = getList(p, "FlowLogId"); + if (ids.isEmpty()) { + ids = getList(p, "FlowLogIds.member"); + } + List logs = flowLogService.describeFlowLogs(region, ids); + XmlBuilder xml = new XmlBuilder() + .start("DescribeFlowLogsResponse", AwsNamespaces.EC2) + .elem("requestId", UUID.randomUUID().toString()) + .start("flowLogSet"); + for (FlowLog fl : logs) { + xml.start("item") + .elem("flowLogId", fl.getFlowLogId()) + .elem("resourceId", fl.getResourceId()) + .elem("trafficType", fl.getTrafficType()) + .elem("logDestinationType", fl.getLogDestinationType()) + .elem("logDestination", fl.getLogDestination()) + .elem("flowLogStatus", fl.getFlowLogStatus()) + .elem("deliverLogsStatus", fl.getDeliverLogsStatus()) + .elem("maxAggregationInterval", String.valueOf(fl.getMaxAggregationInterval())) + .elem("creationTime", ISO_FMT.format(fl.getCreationTime())) + .end("item"); + } + xml.end("flowLogSet").end("DescribeFlowLogsResponse"); + return xmlResponse(xml.build()); + } + + private Response handleDeleteFlowLogs(MultivaluedMap p, String region) { + List ids = getList(p, "FlowLogId"); + if (ids.isEmpty()) { + ids = getList(p, "FlowLogIds.member"); + } + flowLogService.deleteFlowLogs(region, ids); + XmlBuilder xml = new XmlBuilder() + .start("DeleteFlowLogsResponse", AwsNamespaces.EC2) + .elem("requestId", UUID.randomUUID().toString()) + .start("unsuccessful").end("unsuccessful") + .end("DeleteFlowLogsResponse"); + return xmlResponse(xml.build()); + } + private Response handleCreateVpcEndpoint(MultivaluedMap p, String region) { VpcEndpoint endpoint = service.createVpcEndpoint( region, diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java index c7c0709e8f..e170d01dac 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java @@ -1103,6 +1103,54 @@ public class Ec2Service { return deleted; } + /** + * Network interfaces owned by interface VPC endpoints (PrivateLink ENIs). + * Floci does not persist per-endpoint ENIs; they are synthesized + * deterministically from the endpoint's subnets so flow-log generation can + * attribute AWS-service traffic to a stable endpoint address. + */ + public List endpointNetworkInterfaces(String region) { + List result = new ArrayList<>(); + for (VpcEndpoint endpoint : vpcEndpoints.scan(k -> true)) { + if (!region.equals(endpoint.getRegion()) + || !"Interface".equalsIgnoreCase(endpoint.getVpcEndpointType())) { + continue; + } + for (String subnetId : endpoint.getSubnetIds()) { + Subnet subnet = subnets.get(key(region, subnetId)).orElse(null); + if (subnet == null) { + continue; + } + NetworkInterface ni = new NetworkInterface(); + ni.setNetworkInterfaceId(endpointEniId(endpoint.getVpcEndpointId(), subnetId)); + ni.setSubnetId(subnetId); + ni.setVpcId(endpoint.getVpcId()); + ni.setAvailabilityZone(subnet.getAvailabilityZone()); + ni.setDescription("VPC Endpoint Interface " + endpoint.getVpcEndpointId()); + ni.setInterfaceType("vpc_endpoint"); + ni.setPrivateIpAddress(endpointPrivateIp(subnet, endpoint.getVpcEndpointId())); + result.add(ni); + } + } + return result; + } + + private static String endpointEniId(String endpointId, String subnetId) { + String hex = java.util.UUID.nameUUIDFromBytes( + (endpointId + "|" + subnetId).getBytes(StandardCharsets.UTF_8)) + .toString().replace("-", ""); + return "eni-" + hex.substring(0, 17); + } + + /** Stable host address near the top of the subnet range, clear of the instance counter (starts at 10). */ + private static String endpointPrivateIp(Subnet subnet, String endpointId) { + String cidr = subnet.getCidrBlock(); + String baseIp = cidr != null ? cidr.split("/")[0] : "172.31.0.0"; + String[] parts = baseIp.split("\\."); + int host = 200 + Math.floorMod(endpointId.hashCode(), 50); + return parts[0] + "." + parts[1] + "." + parts[2] + "." + host; + } + private VpcEndpoint getRequiredVpcEndpoint(String region, String endpointId) { VpcEndpoint endpoint = vpcEndpoints.get(key(region, endpointId)).orElse(null); if (endpoint == null) { diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/FlowLogService.java b/src/main/java/io/github/hectorvent/floci/services/ec2/FlowLogService.java new file mode 100644 index 0000000000..11c5e214cc --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/FlowLogService.java @@ -0,0 +1,559 @@ +package io.github.hectorvent.floci.services.ec2; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.storage.StorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.ec2.model.FlowLog; +import io.github.hectorvent.floci.services.ec2.model.Instance; +import io.github.hectorvent.floci.services.ec2.model.InstanceNetworkInterface; +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.VpcEndpoint; +import io.github.hectorvent.floci.services.s3.S3Service; +import io.quarkus.runtime.ShutdownEvent; +import io.quarkus.runtime.StartupEvent; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.event.Observes; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.TimeUnit; +import java.util.zip.GZIPOutputStream; + +/** + * Manages VPC Flow Logs (a floci addition — absent upstream) and a background + * generator that synthesizes realistic VPC flow-log records and delivers them + * to the configured S3 bucket. + * + *

Records use the AWS VPC Flow Logs default format (version 5, the + * full 29-field space-delimited layout with a header line) and are written + * under the exact AWS S3 key prefix + * {@code AWSLogs/{account}/vpcflowlogs/{region}/{yyyy}/{MM}/{dd}/{HH}/...log.gz}. + * This is the exact layout AWS uses, so any tool that lists and parses VPC flow + * logs can ingest the emulated traffic with no real cloud spend.

+ * + *

Records are correlated to the real EC2 inventory: source/destination + * addresses, ENI ids, instance ids, subnet ids and vpc ids are taken from the + * instances/ENIs that actually exist in {@link Ec2Service} for the flow log's + * resource, so the synthesized flows reference resources that genuinely exist.

+ */ +@ApplicationScoped +public class FlowLogService { + + private static final Logger LOG = Logger.getLogger(FlowLogService.class); + + /** AWS VPC Flow Logs default (version 5) field order. */ + static final String DEFAULT_HEADER = + "account-id action az-id bytes dstaddr dstport end flow-direction instance-id " + + "interface-id log-status packets pkt-dst-aws-service pkt-dstaddr pkt-src-aws-service " + + "pkt-srcaddr protocol region srcaddr srcport start sublocation-id sublocation-type " + + "subnet-id tcp-flags traffic-path type version vpc-id"; + + private static final DateTimeFormatter PATH_FMT = + DateTimeFormatter.ofPattern("yyyy/MM/dd/HH").withZone(ZoneOffset.UTC); + private static final DateTimeFormatter FILE_TS_FMT = + DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmm'Z'").withZone(ZoneOffset.UTC); + + // flowLogId -> FlowLog (persisted via StorageFactory so flow logs survive a + // restart in persistent/hybrid/wal modes and generation resumes) + private final StorageBackend flowLogs; + + private final EmulatorConfig config; + private final Ec2Service ec2Service; + private final S3Service s3Service; + private ScheduledExecutorService scheduler; + + @Inject + public FlowLogService(EmulatorConfig config, Ec2Service ec2Service, S3Service s3Service, + StorageFactory storageFactory) { + this(config, ec2Service, s3Service, + storageFactory.create("ec2", "ec2-flow-logs.json", new TypeReference>() {})); + } + + // Package-private for hermetic tests (pass an in-memory StorageBackend directly). + FlowLogService(EmulatorConfig config, Ec2Service ec2Service, S3Service s3Service, + StorageBackend flowLogs) { + this.config = config; + this.ec2Service = ec2Service; + this.s3Service = s3Service; + this.flowLogs = flowLogs; + } + + void onStart(@Observes StartupEvent ev) { + scheduler = Executors.newSingleThreadScheduledExecutor(r -> { + Thread t = new Thread(r, "floci-flowlog-generator"); + t.setDaemon(true); + return t; + }); + // Periodically deliver a fresh batch for every active flow log so the + // emulated environment shows continuous traffic. Interval kept short + // (60s) so consumers see flows quickly; AWS real interval is 60/600s. + scheduler.scheduleAtFixedRate(this::generateForAll, 60, 60, TimeUnit.SECONDS); + LOG.info("FlowLog generator scheduled (every 60s)"); + } + + void onStop(@Observes ShutdownEvent ev) { + if (scheduler != null) { + scheduler.shutdownNow(); + } + } + + // ─── CRUD ─────────────────────────────────────────────────────────────── + + public FlowLog createFlowLog(String region, String resourceId, String resourceType, + String trafficType, String logDestinationType, + String logDestination, String logFormat, int maxAggregationInterval) { + 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.setLogDestination(logDestination); + fl.setBucketName(bucketFromArn(logDestination)); + fl.setLogFormat(logFormat); + fl.setMaxAggregationInterval(maxAggregationInterval); + fl.setRegion(region); + fl.setAccountId(config.defaultAccountId()); + flowLogs.put(fl.getFlowLogId(), fl); + LOG.infov("Created flow log {0} for {1} {2} -> {3}", + fl.getFlowLogId(), fl.getResourceType(), resourceId, fl.getBucketName()); + + // Deliver an initial batch right away so flows are visible without + // waiting for the first scheduled tick. + if ("s3".equals(fl.getLogDestinationType()) && fl.getBucketName() != null) { + try { + generateAndDeliver(fl); + } catch (Exception e) { + LOG.warnv("Initial flow-log delivery failed for {0}: {1}", fl.getFlowLogId(), e.getMessage()); + } + } + return fl; + } + + public List describeFlowLogs(String region, List flowLogIds) { + List result = new ArrayList<>(); + for (FlowLog fl : flowLogs.scan(k -> true)) { + if (region != null && fl.getRegion() != null && !region.equals(fl.getRegion())) { + continue; + } + if (flowLogIds != null && !flowLogIds.isEmpty() && !flowLogIds.contains(fl.getFlowLogId())) { + continue; + } + result.add(fl); + } + return result; + } + + public List deleteFlowLogs(String region, List flowLogIds) { + List deleted = new ArrayList<>(); + if (flowLogIds == null) { + return deleted; + } + for (String id : flowLogIds) { + FlowLog fl = flowLogs.get(id).orElse(null); + if (fl == null) { + continue; + } + if (region != null && fl.getRegion() != null && !region.equals(fl.getRegion())) { + continue; + } + flowLogs.delete(id); + deleted.add(id); + } + return deleted; + } + + // ─── Generation ─────────────────────────────────────────────────────────── + + private void generateForAll() { + for (FlowLog fl : flowLogs.scan(k -> true)) { + if (!"s3".equals(fl.getLogDestinationType()) || fl.getBucketName() == null) { + continue; + } + try { + generateAndDeliver(fl); + } catch (Exception e) { + LOG.warnv("Scheduled flow-log delivery failed for {0}: {1}", fl.getFlowLogId(), e.getMessage()); + } + } + } + + /** + * Synthesize one flow-log file for the given flow log and write it to S3 + * at the AWS-native key prefix. Records are derived from the live EC2 + * inventory of the flow log's resource (its instances/ENIs). + */ + void generateAndDeliver(FlowLog fl) { + List enis = resolveEnis(fl); + if (enis.isEmpty()) { + LOG.debugv("No ENIs found for flow log {0} resource {1}; skipping", + fl.getFlowLogId(), fl.getResourceId()); + return; + } + + Instant now = Instant.now(); + long endEpoch = now.getEpochSecond(); + long startEpoch = endEpoch - fl.getMaxAggregationInterval(); + + StringBuilder sb = new StringBuilder(); + sb.append(fl.getLogFormat() != null && !fl.getLogFormat().isBlank() + ? customHeader(fl.getLogFormat()) : DEFAULT_HEADER).append('\n'); + + // Collect the private IPs of all sibling ENIs in this flow log's resource + // so instances in the same VPC actually talk to EACH OTHER (not just to + // random external peers). This yields realistic intra-VPC conversations + // between the resources that exist in the account. + List siblingIps = new ArrayList<>(); + for (Eni e : enis) { + if (e.privateIp != null && !e.privateIp.isBlank()) { + siblingIps.add(e.privateIp); + } + } + + // Interface VPC endpoints (e.g. S3 PrivateLink) have an ENI with a private + // IP in this VPC. Treat those as peers so instances send flows to the + // endpoint — which is how traffic to an AWS service over PrivateLink shows + // up in flow logs. The endpoint's service is recorded in pkt-dst-aws-service. + List endpointIps = new ArrayList<>(); + Map endpointService = new java.util.HashMap<>(); // ip -> service short name (e.g. S3) + String resourceVpc = vpcOfFlowLogResource(fl); + for (NetworkInterface ni : ec2Service.endpointNetworkInterfaces(fl.getRegion())) { + if (ni.getPrivateIpAddress() == null || ni.getPrivateIpAddress().isBlank()) { + continue; + } + // Only endpoints in the same VPC this flow log covers. + if (resourceVpc != null && ni.getVpcId() != null && !resourceVpc.equals(ni.getVpcId())) { + continue; + } + endpointIps.add(ni.getPrivateIpAddress()); + endpointService.put(ni.getPrivateIpAddress(), awsServiceFromEndpoint(ni, fl.getRegion())); + } + + int recordCount = 0; + for (Eni eni : enis) { + // Peers this ENI should talk to: every OTHER sibling VM in the VPC + // (guaranteed intra-VPC edges), every interface endpoint (VM -> S3), + // plus a couple of random external peers. + List peers = new ArrayList<>(); + for (String ip : siblingIps) { + if (!ip.equals(eni.privateIp)) { + peers.add(ip); // intra-VPC: app-01 <-> web-01 + } + } + peers.addAll(endpointIps); // VM -> S3 endpoint + int externals = 2 + ThreadLocalRandom.current().nextInt(2); // 2-3 external conversations + for (int i = 0; i < externals; i++) { + peers.add(randomPeer(eni.privateIp)); + } + + for (String peer : peers) { + int dstPort = pickServicePort(); + int srcPortEph = 32768 + ThreadLocalRandom.current().nextInt(28000); + String svc = endpointService.get(peer); // non-null only for endpoint peers + // egress: eni -> peer + sb.append(record(fl, eni, eni.privateIp, peer, srcPortEph, dstPort, + "egress", startEpoch, endEpoch, svc)).append('\n'); + // ingress: peer -> eni (response) + sb.append(record(fl, eni, peer, eni.privateIp, dstPort, srcPortEph, + "ingress", startEpoch, endEpoch, svc)).append('\n'); + recordCount += 2; + } + } + + byte[] gz = gzip(sb.toString()); + String key = s3Key(fl, now); + try { + s3Service.putObject(fl.getBucketName(), key, gz, "application/octet-stream", + Map.of("content-encoding", "gzip")); + LOG.infov("Delivered {0} flow records to s3://{1}/{2}", recordCount, fl.getBucketName(), key); + } catch (RuntimeException e) { + // Bucket may not exist yet (e.g. flow log created before the bucket). + // Skip this delivery; the next scheduled tick will retry once it exists. + LOG.debugv("Flow-log delivery skipped for {0} (bucket {1}): {2}", + fl.getFlowLogId(), fl.getBucketName(), e.getMessage()); + } + } + + /** + * Build one space-delimited default-format flow record line. + * + * @param svc AWS service short-name (e.g. "S3") when the peer is an interface + * VPC endpoint, else null. Sets pkt-dst-aws-service (egress) or + * pkt-src-aws-service (ingress) so the record looks like real + * AWS-service traffic. + */ + private String record(FlowLog fl, Eni eni, String src, String dst, int srcPort, int dstPort, + String direction, long start, long end, String svc) { + int bytes = 200 + ThreadLocalRandom.current().nextInt(40000); + int packets = 1 + ThreadLocalRandom.current().nextInt(60); + int protocol = 6; // TCP + String action = "ACCEPT"; + String azId = azId(fl.getRegion(), eni.az); + int tcpFlags = "egress".equals(direction) ? 2 : 18; // SYN / SYN-ACK-ish + boolean egress = "egress".equals(direction); + // For endpoint traffic, the AWS service tags the side that is the endpoint: + // egress (eni->endpoint) => dst is the service; ingress (endpoint->eni) => src. + String pktDstSvc = (svc != null && egress) ? svc : "-"; + String pktSrcSvc = (svc != null && !egress) ? svc : "-"; + // Field order MUST match DEFAULT_HEADER exactly. + return String.join(" ", + fl.getAccountId(), // account-id + action, // action + azId, // az-id + String.valueOf(bytes), // bytes + dst, // dstaddr + String.valueOf(dstPort), // dstport + String.valueOf(end), // end + direction, // flow-direction + nz(eni.instanceId), // instance-id + eni.eniId, // interface-id + "OK", // log-status + String.valueOf(packets), // packets + pktDstSvc, // pkt-dst-aws-service + dst, // pkt-dstaddr + pktSrcSvc, // pkt-src-aws-service + src, // pkt-srcaddr + String.valueOf(protocol), // protocol + fl.getRegion(), // region + src, // srcaddr + String.valueOf(srcPort), // srcport + String.valueOf(start), // start + "-", // sublocation-id + "-", // sublocation-type + nz(eni.subnetId), // subnet-id + String.valueOf(tcpFlags), // tcp-flags + "egress".equals(direction) ? "1" : "-", // traffic-path + "IPv4", // type + "5", // version + nz(eni.vpcId)); // vpc-id + } + + // ─── Inventory correlation ───────────────────────────────────────────────── + + /** The VPC id a flow log covers (its resource is a VPC, or a subnet/eni in one). */ + private String vpcOfFlowLogResource(FlowLog fl) { + String rid = fl.getResourceId(); + if (rid == null) { + return null; + } + if (rid.startsWith("vpc-")) { + return rid; + } + // subnet/eni: find the owning VPC from a matching instance ENI. + List reservations = ec2Service.describeInstances(fl.getRegion(), List.of(), Map.of()); + for (Reservation res : reservations) { + for (Instance inst : res.getInstances()) { + if (rid.equals(inst.getSubnetId())) { + return inst.getVpcId(); + } + List nis = inst.getNetworkInterfaces(); + if (nis != null) { + for (InstanceNetworkInterface ni : nis) { + if (rid.equals(ni.getNetworkInterfaceId()) || rid.equals(ni.getSubnetId())) { + return ni.getVpcId() != null ? ni.getVpcId() : inst.getVpcId(); + } + } + } + } + } + return null; + } + + /** Map an endpoint ENI to its service short tag (com.amazonaws.us-east-1.s3 -> S3). */ + private String awsServiceFromEndpoint(NetworkInterface eni, String region) { + String desc = eni.getDescription(); // "VPC Endpoint Interface vpce-..." + int marker = desc != null ? desc.indexOf("vpce-") : -1; + if (marker >= 0) { + String endpointId = desc.substring(marker).trim(); + try { + for (VpcEndpoint endpoint : ec2Service.describeVpcEndpoints(region, List.of(endpointId), Map.of())) { + String serviceName = endpoint.getServiceName(); + if (serviceName != null && serviceName.contains(".")) { + return serviceName.substring(serviceName.lastIndexOf('.') + 1).toUpperCase(); + } + } + } catch (AwsException e) { + LOG.debugv("Endpoint {0} not resolvable for service tagging: {1}", endpointId, e.getMessage()); + } + } + return "S3"; + } + + /** Resolve the ENIs to attribute flows to, based on the flow log's resource. */ + private List resolveEnis(FlowLog fl) { + List enis = new ArrayList<>(); + String region = fl.getRegion(); + String resourceId = fl.getResourceId(); + String resourceType = fl.getResourceType(); + + List reservations = ec2Service.describeInstances(region, List.of(), Map.of()); + for (Reservation res : reservations) { + for (Instance inst : res.getInstances()) { + boolean match = switch (resourceType) { + case "VPC" -> resourceId == null || resourceId.equals(inst.getVpcId()); + case "Subnet" -> resourceId == null || resourceId.equals(inst.getSubnetId()); + case "NetworkInterface" -> hasEni(inst, resourceId); + default -> true; + }; + if (!match) { + continue; + } + String az = inst.getPlacement() != null ? inst.getPlacement().getAvailabilityZone() : region + "a"; + List nis = inst.getNetworkInterfaces(); + if (nis != null && !nis.isEmpty()) { + for (InstanceNetworkInterface ni : nis) { + if ("NetworkInterface".equals(resourceType) && resourceId != null + && !resourceId.equals(ni.getNetworkInterfaceId())) { + continue; + } + Eni e = new Eni(); + e.eniId = ni.getNetworkInterfaceId(); + e.privateIp = ni.getPrivateIpAddress() != null ? ni.getPrivateIpAddress() : inst.getPrivateIpAddress(); + e.instanceId = inst.getInstanceId(); + e.subnetId = ni.getSubnetId() != null ? ni.getSubnetId() : inst.getSubnetId(); + e.vpcId = ni.getVpcId() != null ? ni.getVpcId() : inst.getVpcId(); + e.az = az; + enis.add(e); + } + } else { + // Fall back to a synthetic ENI from instance fields. + Eni e = new Eni(); + e.eniId = "eni-" + randomHex(17); + e.privateIp = inst.getPrivateIpAddress(); + e.instanceId = inst.getInstanceId(); + e.subnetId = inst.getSubnetId(); + e.vpcId = inst.getVpcId(); + e.az = az; + enis.add(e); + } + } + } + return enis; + } + + private boolean hasEni(Instance inst, String eniId) { + if (eniId == null || inst.getNetworkInterfaces() == null) { + return false; + } + return inst.getNetworkInterfaces().stream() + .anyMatch(ni -> eniId.equals(ni.getNetworkInterfaceId())); + } + + // ─── Helpers ──────────────────────────────────────────────────────────── + + private String s3Key(FlowLog fl, Instant when) { + String datePath = PATH_FMT.format(when); + String ts = FILE_TS_FMT.format(when); + String file = fl.getAccountId() + "_vpcflowlogs_" + fl.getRegion() + "_" + fl.getFlowLogId() + + "_" + ts + "_" + randomHex(8) + ".log.gz"; + return String.format("AWSLogs/%s/vpcflowlogs/%s/%s/%s", + fl.getAccountId(), fl.getRegion(), datePath, file); + } + + private static byte[] gzip(String content) { + try { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try (GZIPOutputStream gz = new GZIPOutputStream(bos)) { + gz.write(content.getBytes(StandardCharsets.UTF_8)); + } + return bos.toByteArray(); + } catch (Exception e) { + throw new RuntimeException("gzip failed", e); + } + } + + private static String bucketFromArn(String arn) { + if (arn == null) { + return null; + } + // arn:aws:s3:::bucket-name[/optional/prefix] OR a bare bucket name. + String name = arn.startsWith("arn:") ? arn.substring(arn.lastIndexOf(':') + 1) : arn; + int slash = name.indexOf('/'); + return slash >= 0 ? name.substring(0, slash) : name; + } + + /** Random peer IP: ~half inside the same /16 (intra-VPC), half "external". */ + private static String randomPeer(String selfIp) { + ThreadLocalRandom r = ThreadLocalRandom.current(); + if (selfIp != null && selfIp.contains(".") && r.nextBoolean()) { + String[] o = selfIp.split("\\."); + if (o.length == 4) { + return o[0] + "." + o[1] + "." + r.nextInt(256) + "." + (1 + r.nextInt(254)); + } + } + return "10." + r.nextInt(256) + "." + r.nextInt(256) + "." + (1 + r.nextInt(254)); + } + + private static int pickServicePort() { + int[] ports = {443, 80, 53, 5432, 3306, 6379, 8080, 22}; + return ports[ThreadLocalRandom.current().nextInt(ports.length)]; + } + + /** Map a region + az letter to a plausible AWS az-id (e.g. us-east-1a -> use1-az1). */ + private static String azId(String region, String az) { + String code = switch (region == null ? "" : region) { + case "us-east-1" -> "use1"; + case "us-east-2" -> "use2"; + case "us-west-1" -> "usw1"; + case "us-west-2" -> "usw2"; + case "eu-west-1" -> "euw1"; + case "eu-central-1" -> "euc1"; + case "ap-southeast-1" -> "apse1"; + case "ap-southeast-2" -> "apse2"; + default -> region == null ? "use1" : region.replaceAll("[^a-z0-9]", ""); + }; + int n = 1; + if (az != null && !az.isEmpty()) { + char last = az.charAt(az.length() - 1); + if (last >= 'a' && last <= 'f') { + n = (last - 'a') + 1; + } + } + return code + "-az" + n; + } + + private static String customHeader(String logFormat) { + // AWS custom format uses ${field-name} tokens; convert to a space-delimited header. + return logFormat.replace("${", "").replace("}", "").trim(); + } + + private static String nz(String s) { + return (s == null || s.isEmpty()) ? "-" : s; + } + + private static String randomHex(int len) { + String chars = "0123456789abcdef"; + StringBuilder sb = new StringBuilder(len); + ThreadLocalRandom r = ThreadLocalRandom.current(); + for (int i = 0; i < len; i++) { + sb.append(chars.charAt(r.nextInt(chars.length()))); + } + return sb.toString(); + } + + /** Lightweight holder for the ENI fields a flow record needs. */ + private static final class Eni { + String eniId; + String privateIp; + String instanceId; + String subnetId; + String vpcId; + String az; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/FlowLog.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/FlowLog.java new file mode 100644 index 0000000000..b1d69bee69 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/FlowLog.java @@ -0,0 +1,78 @@ +package io.github.hectorvent.floci.services.ec2.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; + +/** + * Represents a VPC Flow Log configuration created via {@code CreateFlowLogs}. + * + *

The emulator delivers synthetic VPC flow-log records to an S3 bucket in the + * exact record format and S3 key layout that AWS uses + * ({@code AWSLogs/{account}/vpcflowlogs/{region}/...}, gzipped, space-delimited + * default fields). This lets any tool that consumes VPC flow logs — log + * pipelines, SIEMs, traffic-analysis software — be exercised locally against + * realistic data with no real cloud spend.

+ */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class FlowLog { + + private String flowLogId; + private String resourceId; // the VPC (or subnet/eni) the flow log is attached to + private String resourceType; // VPC | Subnet | NetworkInterface + 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 bucketName; // resolved bucket name from the ARN + private String logFormat; // optional custom format string (default format used if null) + private int maxAggregationInterval = 600; // seconds (60 or 600) + private String region; + private String accountId; + private String flowLogStatus = "ACTIVE"; + private String deliverLogsStatus = "SUCCESS"; + private Instant creationTime = Instant.now(); + + public String getFlowLogId() { return flowLogId; } + public void setFlowLogId(String flowLogId) { this.flowLogId = flowLogId; } + + public String getResourceId() { return resourceId; } + public void setResourceId(String resourceId) { this.resourceId = resourceId; } + + public String getResourceType() { return resourceType; } + public void setResourceType(String resourceType) { this.resourceType = resourceType; } + + public String getTrafficType() { return trafficType; } + public void setTrafficType(String trafficType) { this.trafficType = trafficType; } + + public String getLogDestinationType() { return logDestinationType; } + public void setLogDestinationType(String logDestinationType) { this.logDestinationType = logDestinationType; } + + public String getLogDestination() { return logDestination; } + public void setLogDestination(String logDestination) { this.logDestination = logDestination; } + + public String getBucketName() { return bucketName; } + public void setBucketName(String bucketName) { this.bucketName = bucketName; } + + public String getLogFormat() { return logFormat; } + public void setLogFormat(String logFormat) { this.logFormat = logFormat; } + + public int getMaxAggregationInterval() { return maxAggregationInterval; } + public void setMaxAggregationInterval(int maxAggregationInterval) { this.maxAggregationInterval = maxAggregationInterval; } + + public String getRegion() { return region; } + public void setRegion(String region) { this.region = region; } + + public String getAccountId() { return accountId; } + public void setAccountId(String accountId) { this.accountId = accountId; } + + public String getFlowLogStatus() { return flowLogStatus; } + public void setFlowLogStatus(String flowLogStatus) { this.flowLogStatus = flowLogStatus; } + + public String getDeliverLogsStatus() { return deliverLogsStatus; } + public void setDeliverLogsStatus(String deliverLogsStatus) { this.deliverLogsStatus = deliverLogsStatus; } + + public Instant getCreationTime() { return creationTime; } + public void setCreationTime(Instant creationTime) { this.creationTime = creationTime; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/AwsManagedPolicies.java b/src/main/java/io/github/hectorvent/floci/services/iam/AwsManagedPolicies.java index 3cca9614eb..1492e252eb 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/AwsManagedPolicies.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/AwsManagedPolicies.java @@ -29,6 +29,9 @@ final class AwsManagedPolicies { "Provides full access to AWS services and resources, but does not allow management of Users and groups."), new ManagedPolicyDef("ReadOnlyAccess", "/", "Provides read-only access to AWS services and resources."), + new ManagedPolicyDef("SecurityAudit", "/", + "The security audit template grants access to read security configuration metadata. " + + "It is useful for software that audits the configuration of an AWS account."), new ManagedPolicyDef("IAMFullAccess", "/", "Provides full access to IAM."), new ManagedPolicyDef("AmazonS3FullAccess", "/", diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2FlowLogIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2FlowLogIntegrationTest.java new file mode 100644 index 0000000000..cf8b2a0262 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2FlowLogIntegrationTest.java @@ -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). + * + *

Covers {@code CreateFlowLogs} / {@code DescribeFlowLogs} / {@code DeleteFlowLogs}.

+ */ +@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)); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java index 1d08541542..652760276f 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java @@ -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 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), diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/FlowLogServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/FlowLogServiceTest.java new file mode 100644 index 0000000000..ccc146c0d1 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/FlowLogServiceTest.java @@ -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 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 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()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/SecurityAuditManagedPolicyIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/SecurityAuditManagedPolicyIntegrationTest.java new file mode 100644 index 0000000000..a507b730c6 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/iam/SecurityAuditManagedPolicyIntegrationTest.java @@ -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); + } +}