From 8dbcf6bf17b80c30051eef14939040ffb4f0cb39 Mon Sep 17 00:00:00 2001 From: Allen Sanborn Date: Thu, 29 Oct 2026 20:57:16 -0500 Subject: [PATCH] fix(ec2): read RunInstances security groups from the primary interface spec (#6964) * fix(ec2): read RunInstances security groups from the primary interface spec RunInstances read security groups only from the top-level SecurityGroupId.N. With private_ip or associate_public_ip_address set, Terraform's aws_instance sends them on the primary interface spec (NetworkInterface.1.SecurityGroupId.N), so the instance landed in the VPC's default group and the next plan wanted to replace it. The interface spec's groups apply only when its DeviceIndex is 0 (another index is a secondary interface), and a request carrying both shapes fails with InvalidParameterCombination, as on AWS. * test(ec2): match the capacity reservation argument RunInstances now passes * test(ec2): fold the interface security group cases into Ec2RunInstancesPublicIpParamTest Both classes tested what RunInstances takes from the interface spec with the same handler setup, base params and runInstances stub; only the captured argument differed. One forward() helper now runs the request and captures both the security groups and the public-IP override, and the separate class is gone. --- docs/services/ec2.md | 2 +- .../floci/services/ec2/Ec2QueryHandler.java | 13 +++ .../ec2/Ec2RunInstancesPublicIpParamTest.java | 88 +++++++++++++------ 3 files changed, 77 insertions(+), 26 deletions(-) diff --git a/docs/services/ec2.md b/docs/services/ec2.md index 9f9fa76caa..714a402cfc 100644 --- a/docs/services/ec2.md +++ b/docs/services/ec2.md @@ -277,7 +277,7 @@ naming different VPCs find nothing. | Action | Description | |--------|-------------| -| RunInstances | Creates one or more local EC2 instances, starting Docker-backed runtime when not in mock mode. | +| RunInstances | Creates one or more local EC2 instances, starting Docker-backed runtime when not in mock mode. Security groups come from `SecurityGroupId.N` or, as Terraform sends them with an interface spec, from the primary interface's `NetworkInterface.1.SecurityGroupId.N`; both in one request is `InvalidParameterCombination`. | | CreateFleet | Creates an instant local fleet from launch-template configurations and on-demand or spot overrides. DryRun returns the AWS-compatible `DryRunOperation` error without launching instances. | | DescribeInstances | Lists or returns stored EC2 instances. | | TerminateInstances | Terminates instances and updates their stored lifecycle state. | 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 834cd5e84f..cf81f7ee67 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 @@ -821,6 +821,19 @@ public class Ec2QueryHandler { int networkInterfaceDeviceIndex = parseIntParam(p, "NetworkInterface.1.DeviceIndex", 0); String clientToken = p.getFirst("ClientToken"); List sgIds = getList(p, "SecurityGroupId"); + // With a primary interface spec the groups travel on it: Terraform's aws_instance sends that + // shape whenever private_ip or associate_public_ip_address is set. A spec with another device + // index is a secondary interface, whose groups are not the instance's. + List interfaceSgIds = networkInterfaceDeviceIndex == 0 + ? getList(p, "NetworkInterface.1.SecurityGroupId") : List.of(); + if (!interfaceSgIds.isEmpty()) { + if (!sgIds.isEmpty()) { + throw new AwsException("InvalidParameterCombination", + "Network interfaces and an instance-level security groups may not be specified on " + + "the same request", 400); + } + sgIds = interfaceSgIds; + } // UserData is base64-encoded in the wire format String userDataEncoded = p.getFirst("UserData"); diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2RunInstancesPublicIpParamTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2RunInstancesPublicIpParamTest.java index 527bc534b1..0fd708d9a8 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2RunInstancesPublicIpParamTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2RunInstancesPublicIpParamTest.java @@ -6,6 +6,7 @@ import io.github.hectorvent.floci.services.ec2.model.LaunchTemplateData; import io.github.hectorvent.floci.services.ec2.model.Reservation; import jakarta.ws.rs.core.MultivaluedHashMap; import jakarta.ws.rs.core.MultivaluedMap; +import jakarta.ws.rs.core.Response; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; @@ -23,11 +24,16 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** - * RunInstances accepts the launch-time public-IP override in two wire shapes: - * the primary network-interface spec (what Terraform sends) and the legacy - * top-level parameter (what the CLI and older SDKs send). Both must reach - * Ec2Service; absent must stay null so the subnet's MapPublicIpOnLaunch - * default still applies. + * What RunInstances takes from the interface spec. + * + *

The launch-time public-IP override arrives in two wire shapes: the primary network-interface spec + * (what Terraform sends) and the legacy top-level parameter (what the CLI and older SDKs send). Both + * must reach Ec2Service; absent must stay null so the subnet's MapPublicIpOnLaunch default still applies. + * + *

Terraform's aws_instance also sends its security groups on the primary interface spec + * ({@code NetworkInterface.1.SecurityGroupId.N}) whenever private_ip or associate_public_ip_address is + * set. RunInstances read only the top-level {@code SecurityGroupId.N}, so the instance landed in the + * VPC's default group. */ class Ec2RunInstancesPublicIpParamTest { @@ -35,29 +41,64 @@ class Ec2RunInstancesPublicIpParamTest { @Test void topLevelAssociatePublicIpAddressReachesTheService() { - assertForwarded(params("AssociatePublicIpAddress", "true"), Boolean.TRUE); - assertForwarded(params("AssociatePublicIpAddress", "false"), Boolean.FALSE); + assertEquals(Boolean.TRUE, forward(params("AssociatePublicIpAddress", "true")).associatePublicIp()); + assertEquals(Boolean.FALSE, forward(params("AssociatePublicIpAddress", "false")).associatePublicIp()); } @Test void networkInterfaceSpecStillReachesTheService() { - assertForwarded(params("NetworkInterface.1.AssociatePublicIpAddress", "true"), Boolean.TRUE); - assertForwarded(params("NetworkInterface.1.AssociatePublicIpAddress", "false"), Boolean.FALSE); + assertEquals(Boolean.TRUE, + forward(params("NetworkInterface.1.AssociatePublicIpAddress", "true")).associatePublicIp()); + assertEquals(Boolean.FALSE, + forward(params("NetworkInterface.1.AssociatePublicIpAddress", "false")).associatePublicIp()); } @Test void networkInterfaceSpecWinsWhenBothArePresent() { MultivaluedMap p = params("NetworkInterface.1.AssociatePublicIpAddress", "false"); p.putSingle("AssociatePublicIpAddress", "true"); - assertForwarded(p, Boolean.FALSE); + assertEquals(Boolean.FALSE, forward(p).associatePublicIp()); } @Test void absentStaysNullSoTheSubnetDefaultApplies() { - assertForwarded(baseParams(), null); + assertNull(forward(baseParams()).associatePublicIp(), + "an absent override must stay null so the subnet default decides"); } - private void assertForwarded(MultivaluedMap p, Boolean expected) { + @Test + void groupsOnThePrimaryInterfaceSpecReachTheService() { + MultivaluedMap p = baseParams(); + p.putSingle("NetworkInterface.1.SecurityGroupId.1", "sg-0123456789abcdef0"); + p.putSingle("NetworkInterface.1.DeviceIndex", "0"); + assertEquals(List.of("sg-0123456789abcdef0"), forward(p).securityGroupIds()); + } + + @Test + void aSecondaryInterfaceSpecsGroupsAreNotTheInstances() { + MultivaluedMap p = baseParams(); + p.putSingle("NetworkInterface.1.SecurityGroupId.1", "sg-0123456789abcdef0"); + p.putSingle("NetworkInterface.1.DeviceIndex", "1"); + assertEquals(List.of(), forward(p).securityGroupIds()); + } + + @Test + void topLevelAndInterfaceGroupsTogetherAreRefused() { + MultivaluedMap p = baseParams(); + p.putSingle("NetworkInterface.1.SecurityGroupId.1", "sg-0123456789abcdef0"); + p.putSingle("SecurityGroupId.1", "sg-0fedcba9876543210"); + Response response = handler(mock(Ec2Service.class)).handle("RunInstances", p, REGION); + assertEquals(400, response.getStatus()); + assertEquals(true, String.valueOf(response.getEntity()).contains("InvalidParameterCombination")); + } + + /** The interface-spec arguments of the runInstances call the handler forwarded. */ + private record Forwarded(List securityGroupIds, Boolean associatePublicIp) { + } + + /** Runs RunInstances through the handler and captures the call it forwards to Ec2Service. */ + @SuppressWarnings("unchecked") + private static Forwarded forward(MultivaluedMap p) { Ec2Service service = mock(Ec2Service.class); when(service.runInstances(anyString(), nullable(String.class), nullable(String.class), anyInt(), anyInt(), nullable(String.class), anyList(), nullable(String.class), @@ -67,27 +108,24 @@ class Ec2RunInstancesPublicIpParamTest { nullable(String.class), nullable(String.class), nullable(List.class), eq(false), nullable(String.class), nullable(LaunchTemplateData.CapacityReservationSpecification.class))) .thenReturn(new Reservation()); + handler(service).handle("RunInstances", p, REGION); - Ec2QueryHandler handler = new Ec2QueryHandler(service, mock(EmulatorConfig.class), - mock(FlowLogService.class), mock(Ec2EbsEncryptionService.class), - mock(Ec2SnapshotBlockPublicAccessService.class), mock(Ec2IpamService.class), - mock(RegionResolver.class)); - handler.handle("RunInstances", p, REGION); - + ArgumentCaptor> groups = ArgumentCaptor.forClass(List.class); ArgumentCaptor associatePublicIp = ArgumentCaptor.forClass(Boolean.class); verify(service).runInstances(anyString(), nullable(String.class), nullable(String.class), - anyInt(), anyInt(), nullable(String.class), anyList(), nullable(String.class), + anyInt(), anyInt(), nullable(String.class), groups.capture(), nullable(String.class), nullable(String.class), anyList(), nullable(String.class), nullable(String.class), associatePublicIp.capture(), nullable(String.class), anyInt(), nullable(String.class), nullable(LaunchTemplateData.MetadataOptions.class), nullable(String.class), nullable(String.class), eq(false), nullable(String.class), nullable(String.class), nullable(List.class), eq(false), nullable(String.class), nullable(LaunchTemplateData.CapacityReservationSpecification.class)); - if (expected == null) { - assertNull(associatePublicIp.getValue(), - "an absent override must stay null so the subnet default decides"); - } else { - assertEquals(expected, associatePublicIp.getValue()); - } + return new Forwarded(groups.getValue(), associatePublicIp.getValue()); + } + + private static Ec2QueryHandler handler(Ec2Service service) { + return new Ec2QueryHandler(service, mock(EmulatorConfig.class), mock(FlowLogService.class), + mock(Ec2EbsEncryptionService.class), mock(Ec2SnapshotBlockPublicAccessService.class), + mock(Ec2IpamService.class), mock(RegionResolver.class)); } private static MultivaluedMap baseParams() {