Light, fluffy, and always free - The AWS Local Emulator alternative
fix(ec2): assign a public IP only when the subnet opts in via MapPublicIpOnLaunch (#2023)
lex002ab795c6dcc3
diff --git a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingQueryHandler.javaindex c083ce2e86..ff8f9eb52c 100644--- a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingQueryHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingQueryHandler.java@@ -102,7 +102,7 @@ public class AutoScalingQueryHandler {memberList(p, "SecurityGroups"),p.getFirst("UserData"),p.getFirst("IamInstanceProfile"),- "true".equalsIgnoreCase(p.getFirst("AssociatePublicIpAddress")));+ nullableBoolParam(p, "AssociatePublicIpAddress"));String xml = new XmlBuilder().start("CreateLaunchConfigurationResponse", NS).raw(AwsQueryResponse.responseMetadata())@@ -122,8 +122,12 @@ public class AutoScalingQueryHandler {xml.start("member").elem("LaunchConfigurationName", lc.getLaunchConfigurationName()).elem("LaunchConfigurationARN", lc.getLaunchConfigurationArn())- .elem("CreatedTime", ISO_FMT.format(lc.getCreatedTime()))- .elem("AssociatePublicIpAddress", String.valueOf(lc.isAssociatePublicIpAddress()));+ .elem("CreatedTime", ISO_FMT.format(lc.getCreatedTime()));+ // AWS omits the flag entirely when the LC never set it, which is+ // what tells a caller the subnet default still applies.+ if (lc.getAssociatePublicIpAddress() != null) {+ xml.elem("AssociatePublicIpAddress", String.valueOf(lc.getAssociatePublicIpAddress()));+ }if (lc.getImageId() != null) { xml.elem("ImageId", lc.getImageId()); }if (lc.getInstanceType() != null) { xml.elem("InstanceType", lc.getInstanceType()); }if (lc.getKeyName() != null) { xml.elem("KeyName", lc.getKeyName()); }diff --git a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconciler.java b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconciler.javaindex 8c0ee27de1..fa6666123f 100644--- a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconciler.java+++ b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconciler.java@@ -296,7 +296,8 @@ public class AutoScalingReconciler {null,propagatedInstanceTags(asg, launchSource),launchSource.userData(),- launchSource.iamInstanceProfile());+ launchSource.iamInstanceProfile(),+ launchSource.associatePublicIpAddress());for (Instance ec2Inst : reservation.getInstances()) {AsgInstance asgInst = new AsgInstance();@@ -413,7 +414,11 @@ public class AutoScalingReconciler {lc.getIamInstanceProfile(),null,null,- null);+ null,+ // Forwarded as-is: an explicit false has to beat a public+ // subnet's MapPublicIpOnLaunch, and only null means+ // "fall back to the subnet default".+ lc.getAssociatePublicIpAddress());}LaunchTemplate launchTemplate = resolveLaunchTemplate(asg);@@ -438,7 +443,8 @@ public class AutoScalingReconciler {version.getIamInstanceProfileArn(),asg.getLaunchTemplateId(),asg.getLaunchTemplateName(),- resolvedVersion);+ resolvedVersion,+ null);}MixedInstancesPolicy.LaunchTemplateSpecification specification =@@ -469,7 +475,8 @@ public class AutoScalingReconciler {? mixedLaunchTemplate.getLaunchTemplateId(): specification.getLaunchTemplateId(),specification.getLaunchTemplateName(),- resolvedVersion);+ resolvedVersion,+ null);}}@@ -558,7 +565,8 @@ public class AutoScalingReconciler {String iamInstanceProfile,String launchTemplateId,String launchTemplateName,- String launchTemplateVersion) {}+ String launchTemplateVersion,+ Boolean associatePublicIpAddress) {}// Override for describeAutoScalingGroups with null region (all regions)// The service only filters by region when non-null; null means all.diff --git a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.javaindex 596dcb04df..2b00bd667b 100644--- a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java+++ b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java@@ -74,7 +74,7 @@ public class AutoScalingService {String imageId, String instanceType, String keyName,List<String> securityGroups, String userData,String iamInstanceProfile,- boolean associatePublicIpAddress) {+ Boolean associatePublicIpAddress) {String key = lcKey(region, name);if (launchConfigs.containsKey(key)) {throw new AwsException("AlreadyExists",diff --git a/src/main/java/io/github/hectorvent/floci/services/autoscaling/model/LaunchConfiguration.java b/src/main/java/io/github/hectorvent/floci/services/autoscaling/model/LaunchConfiguration.javaindex b11fe607d6..1371b1a635 100644--- a/src/main/java/io/github/hectorvent/floci/services/autoscaling/model/LaunchConfiguration.java+++ b/src/main/java/io/github/hectorvent/floci/services/autoscaling/model/LaunchConfiguration.java@@ -19,7 +19,9 @@ public class LaunchConfiguration {private List<String> securityGroups = new ArrayList<>();private String userData;private String iamInstanceProfile;- private boolean associatePublicIpAddress;+ // Nullable on purpose: AWS treats an absent flag as "fall back to the+ // subnet's MapPublicIpOnLaunch" and an explicit false as an override.+ private Boolean associatePublicIpAddress;private Instant createdTime;private String region;@@ -49,8 +51,8 @@ public class LaunchConfiguration {public String getIamInstanceProfile() { return iamInstanceProfile; }public void setIamInstanceProfile(String v) { this.iamInstanceProfile = v; }- public boolean isAssociatePublicIpAddress() { return associatePublicIpAddress; }- public void setAssociatePublicIpAddress(boolean v) { this.associatePublicIpAddress = v; }+ public Boolean getAssociatePublicIpAddress() { return associatePublicIpAddress; }+ public void setAssociatePublicIpAddress(Boolean v) { this.associatePublicIpAddress = v; }public Instant getCreatedTime() { return createdTime; }public void setCreatedTime(Instant v) { this.createdTime = v; }diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.javaindex e46011c7bb..b284493190 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java@@ -1051,7 +1051,11 @@ public class CloudFormationResourceProvisioner {resolveStringList(props, "SecurityGroups", engine),resolveOptional(props, "UserData", engine),resolveOptional(props, "IamInstanceProfile", engine),- Boolean.parseBoolean(associatePublicIp));+ // Absent in the template means the subnet default applies, so+ // it stays null rather than collapsing to false.+ associatePublicIp == null || associatePublicIp.isBlank()+ ? null+ : Boolean.parseBoolean(associatePublicIp));// Ref returns the launch configuration name.r.setPhysicalId(name);r.getAttributes().put("Arn", lc.getLaunchConfigurationArn());@@ -1192,8 +1196,20 @@ public class CloudFormationResourceProvisioner {}}+ // The launch-time public-IP override rides on the primary network+ // interface spec; absent means the subnet's MapPublicIpOnLaunch default.+ Boolean associatePublicIp = null;+ var networkInterfaces = props.path("NetworkInterfaces");+ if (networkInterfaces.isArray() && !networkInterfaces.isEmpty()) {+ String assocRaw = engine.resolve(networkInterfaces.get(0).path("AssociatePublicIpAddress"));+ if (assocRaw != null && !assocRaw.isBlank()) {+ associatePublicIp = Boolean.parseBoolean(assocRaw);+ }+ }+var reservation = ec2Service.runInstances(region, imageId, instanceType, 1, 1, keyName,- securityGroupIds, subnetId, null, tags, userData, iamInstanceProfile);+ securityGroupIds, subnetId, null, tags, userData, iamInstanceProfile,+ associatePublicIp);var instance = reservation.getInstances().get(0);r.setPhysicalId(instance.getInstanceId());r.getAttributes().put("InstanceId", instance.getInstanceId());diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.javaindex 37e3fe63ca..51582c855b 100644--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java@@ -204,9 +204,14 @@ public class Ec2ContainerManager {configureLinkLocalMetadataEndpoint(containerId, instanceId, flociHost, imdsPort);- // Set public-facing addresses- instance.setPublicIpAddress("127.0.0.1");- instance.setPublicDnsName("localhost");+ // Set public-facing addresses only for instances whose subnet+ // opts in via MapPublicIpOnLaunch (#1984). Private-subnet+ // instances have no public IP/DNS, matching real EC2. The value+ // stays the host-reachable 127.0.0.1/localhost for public ones.+ if (instance.isAssociatePublicIp()) {+ instance.setPublicIpAddress("127.0.0.1");+ instance.setPublicDnsName("localhost");+ }instance.setState(InstanceState.running());LOG.infov("EC2 instance {0} running in container {1} (SSH host port {2})",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.javaindex ca9f7bd6df..36e36c6b5c 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@@ -425,6 +425,19 @@ public class Ec2QueryHandler {int maxCount = Integer.parseInt(p.getOrDefault("MaxCount", List.of("1")).get(0));String keyName = p.getFirst("KeyName");String subnetId = p.getFirst("SubnetId");+ // The launch-time public-IP override arrives either on the primary+ // network interface spec (the shape Terraform's+ // associate_public_ip_address sends) or as the legacy top-level+ // parameter. AWS rejects both at once, so the interface spec wins when+ // present. Absent means "use the subnet's MapPublicIpOnLaunch default".+ String assocParam = p.getFirst("NetworkInterface.1.AssociatePublicIpAddress");+ if (assocParam == null) {+ assocParam = p.getFirst("AssociatePublicIpAddress");+ }+ Boolean associatePublicIp = assocParam == null ? null : Boolean.parseBoolean(assocParam);+ if (subnetId == null) {+ subnetId = p.getFirst("NetworkInterface.1.SubnetId");+ }String clientToken = p.getFirst("ClientToken");List<String> sgIds = getList(p, "SecurityGroupId");@@ -471,7 +484,8 @@ public class Ec2QueryHandler {}Reservation res = service.runInstances(region, imageId, instanceType, minCount, maxCount,- keyName, sgIds, subnetId, clientToken, instanceTags, userData, iamInstanceProfileArn);+ keyName, sgIds, subnetId, clientToken, instanceTags, userData, iamInstanceProfileArn,+ associatePublicIp);XmlBuilder xml = new XmlBuilder().start("RunInstancesResponse", AwsNamespaces.EC2)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.javaindex 668776c5f5..0aa0ad6812 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@@ -819,6 +819,17 @@ public class Ec2Service implements ContainerTeardown {List<String> securityGroupIds, String subnetId,String clientToken, List<Tag> instanceTags,String userData, String iamInstanceProfileArn) {+ return runInstances(region, imageId, instanceType, minCount, maxCount, keyName,+ securityGroupIds, subnetId, clientToken, instanceTags, userData,+ iamInstanceProfileArn, null);+ }++ public Reservation runInstances(String region, String imageId, String instanceType,+ int minCount, int maxCount, String keyName,+ List<String> securityGroupIds, String subnetId,+ String clientToken, List<Tag> instanceTags,+ String userData, String iamInstanceProfileArn,+ Boolean associatePublicIp) {if (imageId == null || imageId.isBlank()) {throw new AwsException("MissingParameter", "The request must contain the parameter ImageId", 400);}@@ -876,6 +887,12 @@ public class Ec2Service implements ContainerTeardown {inst.setPlacement(new Placement(az));inst.setSubnetId(finalSubnetId);inst.setVpcId(vpcId);+ // AWS precedence (#1984): the launch-time AssociatePublicIpAddress+ // override wins in both directions; the subnet's MapPublicIpOnLaunch+ // attribute is only the default when the launch does not specify it.+ inst.setAssociatePublicIp(associatePublicIp != null+ ? associatePublicIp+ : subnet != null && subnet.isMapPublicIpOnLaunch());inst.setPrivateIpAddress(privateIp);inst.setPrivateDnsName("ip-" + privateIp.replace('.', '-') + ".ec2.internal");inst.setKeyName(keyName);diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/Instance.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/Instance.javaindex 0e59b6e1f5..3d38066159 100644--- a/src/main/java/io/github/hectorvent/floci/services/ec2/model/Instance.java+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/Instance.java@@ -25,6 +25,9 @@ public class Instance {private String publicIpAddress;private String privateDnsName;private String publicDnsName;+ // Whether this instance should be assigned a public IP — true when its subnet+ // has MapPublicIpOnLaunch (#1984). Instances in private subnets get none.+ private boolean associatePublicIp = false;private String keyName;private List<GroupIdentifier> securityGroups = new ArrayList<>();private List<InstanceNetworkInterface> networkInterfaces = new ArrayList<>();@@ -102,6 +105,8 @@ public class Instance {public String getPublicDnsName() { return publicDnsName; }public void setPublicDnsName(String publicDnsName) { this.publicDnsName = publicDnsName; }+ public boolean isAssociatePublicIp() { return associatePublicIp; }+ public void setAssociatePublicIp(boolean associatePublicIp) { this.associatePublicIp = associatePublicIp; }public String getKeyName() { return keyName; }public void setKeyName(String keyName) { this.keyName = keyName; }diff --git a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconcilerTest.java b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconcilerTest.javaindex 88b444a1a7..5ee0037e61 100644--- a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconcilerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconcilerTest.java@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.autoscaling;import io.github.hectorvent.floci.services.autoscaling.model.AsgInstance;import io.github.hectorvent.floci.services.autoscaling.model.AutoScalingGroup;+import io.github.hectorvent.floci.services.autoscaling.model.LaunchConfiguration;import io.github.hectorvent.floci.services.autoscaling.model.MixedInstancesPolicy;import io.github.hectorvent.floci.services.ec2.Ec2Service;import io.github.hectorvent.floci.services.ec2.model.Instance;@@ -96,7 +97,7 @@ class AutoScalingReconcilerTest {reservation.setInstances(List.of(ec2Instance));when(ec2Service.runInstances(eq("us-east-1"), eq("ami-version-1"), eq("t3.micro"),eq(1), eq(1), eq(null), eq(List.of()), eq(null), eq(null),- anyList(), eq(null), eq("arn:aws:iam::000000000000:instance-profile/app-profile"))).thenReturn(reservation);+ anyList(), eq(null), eq("arn:aws:iam::000000000000:instance-profile/app-profile"), eq(null))).thenReturn(reservation);reconciler.reconcile(asg);@@ -107,7 +108,7 @@ class AutoScalingReconcilerTest {ArgumentCaptor<List<Tag>> tags = ArgumentCaptor.captor();verify(ec2Service).runInstances(eq("us-east-1"), eq("ami-version-1"), eq("t3.micro"),eq(1), eq(1), eq(null), eq(List.of()), eq(null), eq(null),- tags.capture(), eq(null), eq("arn:aws:iam::000000000000:instance-profile/app-profile"));+ tags.capture(), eq(null), eq("arn:aws:iam::000000000000:instance-profile/app-profile"), eq(null));assertEquals(propagatedTags.size(), tags.getValue().size());assertEquals("app.ClusterId", tags.getValue().get(0).getKey());assertEquals("development", tags.getValue().get(0).getValue());@@ -115,6 +116,51 @@ class AutoScalingReconcilerTest {assertEquals("2001", tags.getValue().get(1).getValue());}+ @Test+ void scaleOutForwardsLaunchConfigurationAssociatePublicIpAddressBothDirections() {+ // An LC that explicitly sets false must suppress the public IP even in a+ // MapPublicIpOnLaunch subnet, so false has to reach runInstances as+ // FALSE rather than null (null means "use the subnet default").+ assertLaunchConfigurationForwards(Boolean.FALSE);+ assertLaunchConfigurationForwards(Boolean.TRUE);+ assertLaunchConfigurationForwards(null);+ }++ private void assertLaunchConfigurationForwards(Boolean associatePublicIp) {+ AutoScalingService asgService = mock(AutoScalingService.class);+ Ec2Service ec2Service = mock(Ec2Service.class);+ ElbV2Service elbV2Service = mock(ElbV2Service.class);+ AutoScalingReconciler reconciler = new AutoScalingReconciler(asgService, ec2Service, elbV2Service);++ AutoScalingGroup asg = new AutoScalingGroup();+ asg.setRegion("us-east-1");+ asg.setAutoScalingGroupName("app-asg");+ asg.setDesiredCapacity(1);+ asg.setLaunchConfigurationName("app-lc");++ LaunchConfiguration lc = new LaunchConfiguration();+ lc.setLaunchConfigurationName("app-lc");+ lc.setImageId("ami-lc");+ lc.setInstanceType("t3.micro");+ lc.setAssociatePublicIpAddress(associatePublicIp);+ when(asgService.describeLaunchConfigurations("us-east-1", List.of("app-lc")))+ .thenReturn(List.of(lc));++ Instance ec2Instance = new Instance();+ ec2Instance.setInstanceId("i-lc-launched");+ Reservation reservation = new Reservation();+ reservation.setInstances(List.of(ec2Instance));+ when(ec2Service.runInstances(eq("us-east-1"), eq("ami-lc"), eq("t3.micro"),+ eq(1), eq(1), eq(null), anyList(), eq(null), eq(null),+ anyList(), eq(null), eq(null), eq(associatePublicIp))).thenReturn(reservation);++ reconciler.reconcile(asg);++ verify(ec2Service).runInstances(eq("us-east-1"), eq("ami-lc"), eq("t3.micro"),+ eq(1), eq(1), eq(null), anyList(), eq(null), eq(null),+ anyList(), eq(null), eq(null), eq(associatePublicIp));+ }+@Testvoid scaleOutStoresResolvedLaunchTemplateVersionForAliases() {AutoScalingService asgService = mock(AutoScalingService.class);@@ -144,7 +190,7 @@ class AutoScalingReconcilerTest {reservation.setInstances(List.of(ec2Instance));when(ec2Service.runInstances(eq("us-east-1"), eq("ami-version-7"), eq("t3.micro"),eq(1), eq(1), eq(null), eq(List.of()), eq(null), eq(null),- eq(List.of()), eq(null), eq(null))).thenReturn(reservation);+ eq(List.of()), eq(null), eq(null), eq(null))).thenReturn(reservation);reconciler.reconcile(asg);@@ -193,7 +239,7 @@ class AutoScalingReconcilerTest {reservation.setInstances(List.of(ec2Instance));when(ec2Service.runInstances(eq("us-east-1"), eq("ami-version-3"), eq("t3.small"),eq(1), eq(1), eq(null), eq(List.of()), eq(null), eq(null),- eq(List.of()), eq(null), eq(null))).thenReturn(reservation);+ eq(List.of()), eq(null), eq(null), eq(null))).thenReturn(reservation);reconciler.reconcile(asg);@@ -204,7 +250,7 @@ class AutoScalingReconcilerTest {assertEquals("t3.small", asg.getInstances().getFirst().getInstanceType());verify(ec2Service).runInstances(eq("us-east-1"), eq("ami-version-3"), eq("t3.small"),eq(1), eq(1), eq(null), eq(List.of()), eq(null), eq(null),- eq(List.of()), eq(null), eq(null));+ eq(List.of()), eq(null), eq(null), eq(null));}@Test@@ -273,6 +319,7 @@ class AutoScalingReconcilerTest {org.mockito.ArgumentMatchers.any(),org.mockito.ArgumentMatchers.any(),org.mockito.ArgumentMatchers.any(),+ org.mockito.ArgumentMatchers.any(),org.mockito.ArgumentMatchers.any());}diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2PublicIpOnLaunchTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2PublicIpOnLaunchTest.javanew file mode 100644index 0000000000..8e563a1b24--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2PublicIpOnLaunchTest.java@@ -0,0 +1,170 @@+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.storage.PersistentStorage;+import io.github.hectorvent.floci.core.storage.StorageBackend;+import io.github.hectorvent.floci.services.ec2.model.Address;+import io.github.hectorvent.floci.services.ec2.model.Image;+import io.github.hectorvent.floci.services.ec2.model.InternetGateway;+import io.github.hectorvent.floci.services.ec2.model.KeyPair;+import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate;+import io.github.hectorvent.floci.services.ec2.model.NatGateway;+import io.github.hectorvent.floci.services.ec2.model.NetworkAcl;+import io.github.hectorvent.floci.services.ec2.model.Instance;+import io.github.hectorvent.floci.services.ec2.model.Reservation;+import io.github.hectorvent.floci.services.ec2.model.RouteTable;+import io.github.hectorvent.floci.services.ec2.model.SecurityGroup;+import io.github.hectorvent.floci.services.ec2.model.SecurityGroupRule;+import io.github.hectorvent.floci.services.ec2.model.Snapshot;+import io.github.hectorvent.floci.services.ec2.model.SpotInstanceRequest;+import io.github.hectorvent.floci.services.ec2.model.Subnet;+import io.github.hectorvent.floci.services.ec2.model.Tag;+import io.github.hectorvent.floci.services.ec2.model.Volume;+import io.github.hectorvent.floci.services.ec2.model.Vpc;+import io.github.hectorvent.floci.services.ec2.model.VpcEndpoint;+import io.github.hectorvent.floci.services.ec2.portforward.Ec2PortForwardManager;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.io.TempDir;++import java.nio.file.Path;+import java.util.List;+import java.util.Map;++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.Mockito.mock;+import static org.mockito.Mockito.when;++/**+ * Regression test for issue #1984: a public IP must be assigned only to instances+ * whose subnet opts in via MapPublicIpOnLaunch. Before the fix every instance got+ * PublicIpAddress 127.0.0.1 regardless of subnet, so a private-subnet instance+ * wrongly looked internet-facing. The launch-time flag (associatePublicIp) drives+ * whether Ec2ContainerManager exposes a public address once the container is up.+ */+class Ec2PublicIpOnLaunchTest {++ private static final String REGION = "us-east-1";+ private static final String AMI = "ami-0abcdef1234567890";++ @Test+ void publicSubnetInstanceGetsPublicIpFlag_privateDoesNot(@TempDir Path dir) {+ Ec2Service ec2 = newService(dir);+ Vpc vpc = ec2.createVpc(REGION, "10.0.0.0/16", false);++ Subnet publicSubnet = ec2.createSubnet(REGION, vpc.getVpcId(), "10.0.0.0/24", REGION + "a");+ ec2.modifySubnetAttribute(REGION, publicSubnet.getSubnetId(), "mapPublicIpOnLaunch", "true");++ Subnet privateSubnet = ec2.createSubnet(REGION, vpc.getVpcId(), "10.0.1.0/24", REGION + "a");+ // privateSubnet keeps MapPublicIpOnLaunch=false (the createSubnet default)++ Instance inPublic = runOne(ec2, publicSubnet.getSubnetId());+ Instance inPrivate = runOne(ec2, privateSubnet.getSubnetId());++ assertTrue(inPublic.isAssociatePublicIp(),+ "instance in a MapPublicIpOnLaunch subnet must be flagged for a public IP");+ assertFalse(inPrivate.isAssociatePublicIp(),+ "instance in a private subnet must NOT be flagged for a public IP");++ // The behavior #1984 is about, not just the flag: after the container+ // manager's gate runs, a private-subnet instance reports no public+ // address while a public-subnet one reports the host-reachable one.+ applyContainerManagerPublicIpGate(inPublic);+ applyContainerManagerPublicIpGate(inPrivate);+ assertEquals("127.0.0.1", inPublic.getPublicIpAddress(),+ "public-subnet instance must report the host-reachable public IP");+ assertNull(inPrivate.getPublicIpAddress(),+ "private-subnet instance must report no public IP");+ assertNull(inPrivate.getPublicDnsName(),+ "private-subnet instance must report no public DNS name");+ }++ @Test+ void launchTimeOverrideBeatsSubnetDefaultBothDirections(@TempDir Path dir) {+ Ec2Service ec2 = newService(dir);+ Vpc vpc = ec2.createVpc(REGION, "10.0.0.0/16", false);++ Subnet publicSubnet = ec2.createSubnet(REGION, vpc.getVpcId(), "10.0.0.0/24", REGION + "a");+ ec2.modifySubnetAttribute(REGION, publicSubnet.getSubnetId(), "mapPublicIpOnLaunch", "true");+ Subnet privateSubnet = ec2.createSubnet(REGION, vpc.getVpcId(), "10.0.1.0/24", REGION + "a");++ // AWS precedence: the launch-time AssociatePublicIpAddress override wins+ // over the subnet attribute in both directions.+ Instance forcedOn = runOne(ec2, privateSubnet.getSubnetId(), Boolean.TRUE);+ Instance forcedOff = runOne(ec2, publicSubnet.getSubnetId(), Boolean.FALSE);++ assertTrue(forcedOn.isAssociatePublicIp(),+ "launch-time true must force a public IP in a private subnet");+ assertFalse(forcedOff.isAssociatePublicIp(),+ "launch-time false must suppress the public IP in a public subnet");+ }++ /**+ * Mirrors the gate in Ec2ContainerManager (launch(), the+ * isAssociatePublicIp branch): public addresses are set only for flagged+ * instances. The manager is mocked out here to keep Docker away, so the+ * decision is replicated verbatim — if the branch there changes shape,+ * update this too.+ */+ private static void applyContainerManagerPublicIpGate(Instance instance) {+ if (instance.isAssociatePublicIp()) {+ instance.setPublicIpAddress("127.0.0.1");+ instance.setPublicDnsName("localhost");+ }+ }++ private Instance runOne(Ec2Service ec2, String subnetId) {+ return runOne(ec2, subnetId, null);+ }++ private Instance runOne(Ec2Service ec2, String subnetId, Boolean associatePublicIp) {+ Reservation r = ec2.runInstances(REGION, AMI, "t2.micro", 1, 1, null,+ List.of(), subnetId, null, List.of(), null, null, associatePublicIp);+ return r.getInstances().get(0);+ }++ private Ec2Service newService(Path dir) {+ EmulatorConfig config = mock(EmulatorConfig.class);+ when(config.defaultAccountId()).thenReturn("000000000000");+ // mock() == true short-circuits the container launch in runInstances, so+ // no Docker is needed — the associatePublicIp flag is set before that.+ EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);+ EmulatorConfig.Ec2ServiceConfig ec2Cfg = mock(EmulatorConfig.Ec2ServiceConfig.class);+ when(config.services()).thenReturn(services);+ when(services.ec2()).thenReturn(ec2Cfg);+ when(ec2Cfg.mock()).thenReturn(true);+ Ec2ImageCatalog imageCatalog = new Ec2ImageCatalog();+ // A mock container manager makes launch() a no-op — the associatePublicIp+ // flag is set on the instance BEFORE launch, so no Docker is needed here.+ return new Ec2Service(config, mock(Ec2ContainerManager.class), mock(Ec2PortForwardManager.class),+ new AmiImageResolver(imageCatalog), imageCatalog,+ new Ec2InstanceTypeCatalog(),+ load(dir, "ec2-vpcs.json", new TypeReference<Map<String, Vpc>>() {}),+ load(dir, "ec2-subnets.json", new TypeReference<Map<String, Subnet>>() {}),+ load(dir, "ec2-security-groups.json", new TypeReference<Map<String, SecurityGroup>>() {}),+ load(dir, "ec2-security-group-rules.json", new TypeReference<Map<String, SecurityGroupRule>>() {}),+ load(dir, "ec2-internet-gateways.json", new TypeReference<Map<String, InternetGateway>>() {}),+ load(dir, "ec2-route-tables.json", new TypeReference<Map<String, RouteTable>>() {}),+ load(dir, "ec2-key-pairs.json", new TypeReference<Map<String, KeyPair>>() {}),+ load(dir, "ec2-addresses.json", new TypeReference<Map<String, Address>>() {}),+ load(dir, "ec2-instances.json", new TypeReference<Map<String, Instance>>() {}),+ load(dir, "ec2-volumes.json", new TypeReference<Map<String, Volume>>() {}),+ load(dir, "ec2-registered-images.json", new TypeReference<Map<String, Image>>() {}),+ load(dir, "ec2-snapshots.json", new TypeReference<Map<String, Snapshot>>() {}),+ load(dir, "ec2-launch-templates.json", new TypeReference<Map<String, LaunchTemplate>>() {}),+ load(dir, "ec2-vpc-endpoints.json", new TypeReference<Map<String, VpcEndpoint>>() {}),+ load(dir, "ec2-nat-gateways.json", new TypeReference<Map<String, NatGateway>>() {}),+ load(dir, "ec2-spot-instance-requests.json", new TypeReference<Map<String, SpotInstanceRequest>>() {}),+ load(dir, "ec2-network-acls.json", new TypeReference<Map<String, NetworkAcl>>() {}),+ load(dir, "ec2-tags.json", new TypeReference<Map<String, List<Tag>>>() {}));+ }++ private <V> StorageBackend<String, V> load(Path dir, String file, TypeReference<Map<String, V>> type) {+ PersistentStorage<String, V> backend = new PersistentStorage<>(dir.resolve(file), type);+ backend.load();+ return backend;+ }+}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.javanew file mode 100644index 0000000000..a649e22432--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2RunInstancesPublicIpParamTest.java@@ -0,0 +1,93 @@+package io.github.hectorvent.floci.services.ec2;++import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.services.ec2.model.Reservation;+import jakarta.ws.rs.core.MultivaluedHashMap;+import jakarta.ws.rs.core.MultivaluedMap;+import org.junit.jupiter.api.Test;+import org.mockito.ArgumentCaptor;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNull;+import static org.mockito.ArgumentMatchers.anyInt;+import static org.mockito.ArgumentMatchers.anyList;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.ArgumentMatchers.nullable;+import static org.mockito.Mockito.mock;+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.+ */+class Ec2RunInstancesPublicIpParamTest {++ private static final String REGION = "us-east-1";++ @Test+ void topLevelAssociatePublicIpAddressReachesTheService() {+ assertForwarded(params("AssociatePublicIpAddress", "true"), Boolean.TRUE);+ assertForwarded(params("AssociatePublicIpAddress", "false"), Boolean.FALSE);+ }++ @Test+ void networkInterfaceSpecStillReachesTheService() {+ assertForwarded(params("NetworkInterface.1.AssociatePublicIpAddress", "true"), Boolean.TRUE);+ assertForwarded(params("NetworkInterface.1.AssociatePublicIpAddress", "false"), Boolean.FALSE);+ }++ @Test+ void networkInterfaceSpecWinsWhenBothArePresent() {+ MultivaluedMap<String, String> p = params("NetworkInterface.1.AssociatePublicIpAddress", "false");+ p.putSingle("AssociatePublicIpAddress", "true");+ assertForwarded(p, Boolean.FALSE);+ }++ @Test+ void absentStaysNullSoTheSubnetDefaultApplies() {+ assertForwarded(baseParams(), null);+ }++ private void assertForwarded(MultivaluedMap<String, String> p, Boolean expected) {+ Ec2Service service = mock(Ec2Service.class);+ when(service.runInstances(anyString(), nullable(String.class), nullable(String.class),+ anyInt(), anyInt(), nullable(String.class), anyList(), nullable(String.class),+ nullable(String.class), anyList(), nullable(String.class), nullable(String.class),+ nullable(Boolean.class))).thenReturn(new Reservation());++ Ec2QueryHandler handler = new Ec2QueryHandler(service, mock(EmulatorConfig.class),+ mock(FlowLogService.class));+ handler.handle("RunInstances", p, REGION);++ ArgumentCaptor<Boolean> associatePublicIp = ArgumentCaptor.forClass(Boolean.class);+ verify(service).runInstances(anyString(), nullable(String.class), nullable(String.class),+ anyInt(), anyInt(), nullable(String.class), anyList(), nullable(String.class),+ nullable(String.class), anyList(), nullable(String.class), nullable(String.class),+ associatePublicIp.capture());+ if (expected == null) {+ assertNull(associatePublicIp.getValue(),+ "an absent override must stay null so the subnet default decides");+ } else {+ assertEquals(expected, associatePublicIp.getValue());+ }+ }++ private static MultivaluedMap<String, String> baseParams() {+ MultivaluedMap<String, String> p = new MultivaluedHashMap<>();+ p.putSingle("ImageId", "ami-0abcdef1234567890");+ p.putSingle("InstanceType", "t3.micro");+ p.putSingle("MinCount", "1");+ p.putSingle("MaxCount", "1");+ return p;+ }++ private static MultivaluedMap<String, String> params(String key, String value) {+ MultivaluedMap<String, String> p = baseParams();+ p.putSingle(key, value);+ return p;+ }+}