Light, fluffy, and always free - The AWS Local Emulator alternative
feat(ec2): publish security-group TCP ingress ports on the host (#1680)
Hector Venturaa27971c7d512
diff --git a/docs/services/ec2.md b/docs/services/ec2.mdindex e281fd36b0..3d86e0548a 100644--- a/docs/services/ec2.md+++ b/docs/services/ec2.md@@ -76,6 +76,22 @@ If `KeyName` is specified at launch, Floci looks up the stored key pair's publicKey pairs created with `CreateKeyPair` contain dummy private key material. Import a real key pair with `ImportKeyPair` to enable working SSH access.+## Security Group Port Publishing++When an instance's security groups open a TCP port to a CIDR source, Floci publishes that port on the host so you can reach the app from `localhost`. For each opened port Floci starts a small `alpine/socat` sidecar container that binds an allocated host port (default range 30000–30999) and forwards it to the instance container's IP. This works both for rules present at launch and for rules added later with `authorize-security-group-ingress`; revoking the rule removes the forward. The mapping (`app port -> host port`) is written to the logs:++```+Published EC2 instance i-0abc... app port 80 on host port 30000 (socat -> 172.17.0.3:80)+```++Notes and limitations:++- The app inside the instance must listen on `0.0.0.0` (not `127.0.0.1`) for the forward to reach it.+- Only CIDR-sourced TCP rules are published. A port opened only to a referenced security group (or via a prefix list) is not published, matching AWS: those grant reachability from the referenced group's private IPs, not from the host. The source CIDR value itself is not enforced, so a CIDR-sourced port is reachable whether the rule is `0.0.0.0/0` or narrower.+- Ports are aggregated across all of the instance's security groups, SSH (22) is never re-forwarded, and any single rule whose port span exceeds `max-published-ports-per-instance` (default 20) is skipped so an allow-all range cannot spawn thousands of sidecars. The total published per instance is capped at the same limit.+- Stopping an instance tears down its forwards; starting it again does not automatically restore them (re-run `authorize-security-group-ingress`, or recreate the instance).+- Set `publish-security-group-ports: false` (`FLOCI_SERVICES_EC2_PUBLISH_SECURITY_GROUP_PORTS=false`) to keep security groups as metadata only.+## UserData`UserData` must be base64-encoded in the request (matching the AWS wire format). Floci decodes it, copies the script into `/tmp/user-data.sh` inside the container, and executes the script directly after SSH key injection so the script shebang selects the interpreter. Output is captured and logged.@@ -332,6 +348,11 @@ Launch templates store versioned launch data. New template versions can be creat| `FLOCI_SERVICES_EC2_IMDS_PORT` | `9169` | Host port for the IMDS server || `FLOCI_SERVICES_EC2_SSH_PORT_RANGE_START` | `2200` | Start of SSH host port range || `FLOCI_SERVICES_EC2_SSH_PORT_RANGE_END` | `2299` | End of SSH host port range |+| `FLOCI_SERVICES_EC2_PUBLISH_SECURITY_GROUP_PORTS` | `true` | Publish security-group TCP ingress ports on the host via socat sidecars |+| `FLOCI_SERVICES_EC2_APP_PORT_RANGE_START` | `30000` | Start of the host-port range for published app ports |+| `FLOCI_SERVICES_EC2_APP_PORT_RANGE_END` | `30999` | End of the host-port range for published app ports |+| `FLOCI_SERVICES_EC2_MAX_PUBLISHED_PORTS_PER_INSTANCE` | `20` | Max published ports per instance; also the widest single-rule span published |+| `FLOCI_SERVICES_EC2_SOCAT_IMAGE` | `alpine/socat` | Image used for the port-forwarding sidecar || `FLOCI_SERVICES_EC2_MOCK` | `false` | Skip Docker; instances jump directly to final state (useful for tests) |## Requirements@@ -425,5 +446,5 @@ aws ec2 associate-address \- `DescribeImages` returns AMIs from the EC2 image catalog, including common AMIs and Floci-native AMI IDs.- Key material returned by `CreateKeyPair` is a dummy RSA PEM — not usable for real SSH. Use `ImportKeyPair` for working SSH access.-- Security group rules are stored and returned correctly but are not enforced at the network level — Docker bridge networking handles routing.+- Security group rules are not enforced as a firewall (Docker bridge networking handles routing), but TCP ingress rules opened to a CIDR source are published on the host via socat sidecars so the instance's app is reachable from `localhost` — see [Security Group Port Publishing](#security-group-port-publishing).- The IMDS server identifies which instance is calling via IMDSv2 tokens (mapped at token issuance time) or by the container's bridge IP for IMDSv1.diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.javaindex 8ae0f3dc1c..20a3c62c80 100644--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java@@ -1227,6 +1227,34 @@ public interface EmulatorConfig {@WithDefault("2299")int sshPortRangeEnd();+ /**+ * When true, TCP ports opened by an instance's security-group ingress rules are+ * published on the host via a socat sidecar container, both at launch and on later+ * authorize-security-group-ingress. Set false to keep security groups as metadata only.+ */+ @WithDefault("true")+ boolean publishSecurityGroupPorts();++ /** Lowest host port in the range allocated for published security-group app ports. */+ @WithDefault("30000")+ int appPortRangeStart();++ /** Highest host port in the range allocated for published security-group app ports. */+ @WithDefault("30999")+ int appPortRangeEnd();++ /**+ * Upper bound on app ports published per instance. Also bounds any single ingress+ * rule's port span: wider ranges (e.g. an allow-all 0-65535 rule) are skipped so a+ * single rule cannot spawn thousands of socat sidecars or exhaust the host-port range.+ */+ @WithDefault("20")+ int maxPublishedPortsPerInstance();++ /** Image used for the socat sidecar that forwards published security-group ports. */+ @WithDefault("alpine/socat")+ String socatImage();+/** When true, instances go straight to RUNNING without launching Docker containers. */@WithDefault("false")boolean mock();diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/PortAllocator.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/PortAllocator.javaindex f4e7e8e8f0..7996c6aed8 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/docker/PortAllocator.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/PortAllocator.java@@ -43,6 +43,15 @@ public class PortAllocator {throw new RuntimeException("No free port available in range " + basePort + "-" + maxPort);}+ /**+ * Marks a port as reserved without probing whether it is free. Used on restart to+ * re-reserve host ports already held by surviving containers (e.g. persisted EC2+ * port forwards) so the allocator does not hand them out again.+ */+ public synchronized void markReserved(int port) {+ reserved.add(port);+ }+/*** Releases a previously allocated port back to the pool.* Should be called when the Docker container that was using the port is removed.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 5474a16b42..e9a3ce5e58 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@@ -10,6 +10,7 @@ import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;import io.github.hectorvent.floci.core.common.docker.PortAllocator;import io.github.hectorvent.floci.services.ec2.model.Instance;import io.github.hectorvent.floci.services.ec2.model.InstanceState;+import io.github.hectorvent.floci.services.ec2.portforward.Ec2PortForwardManager;import com.github.dockerjava.api.DockerClient;import com.github.dockerjava.api.exception.NotFoundException;import com.github.dockerjava.api.async.ResultCallback;@@ -32,6 +33,7 @@ import java.util.List;import java.util.Locale;import java.util.Map;import java.util.Optional;+import java.util.Set;import java.util.concurrent.CountDownLatch;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;@@ -62,6 +64,7 @@ public class Ec2ContainerManager {private final PortAllocator portAllocator;private final EmulatorConfig config;private final Ec2MetadataServer metadataServer;+ private final Ec2PortForwardManager portForwardManager;private final ExecutorService executor = Executors.newCachedThreadPool(r -> {Thread t = new Thread(r, "ec2-container-launcher");@@ -78,7 +81,8 @@ public class Ec2ContainerManager {DockerClient dockerClient,PortAllocator portAllocator,EmulatorConfig config,- Ec2MetadataServer metadataServer) {+ Ec2MetadataServer metadataServer,+ Ec2PortForwardManager portForwardManager) {this.containerBuilder = containerBuilder;this.lifecycleManager = lifecycleManager;this.logStreamer = logStreamer;@@ -88,6 +92,7 @@ public class Ec2ContainerManager {this.portAllocator = portAllocator;this.config = config;this.metadataServer = metadataServer;+ this.portForwardManager = portForwardManager;}/**@@ -101,10 +106,18 @@ public class Ec2ContainerManager {* @param region AWS region (for CloudWatch log group naming)*/public void launch(Instance instance, String dockerImage, String publicKey, String region) {- launch(instance, ResolvedAmiImage.minimal(dockerImage), publicKey, region);+ launch(instance, ResolvedAmiImage.minimal(dockerImage), publicKey, region, Set.of());}public void launch(Instance instance, ResolvedAmiImage image, String publicKey, String region) {+ launch(instance, image, publicKey, region, Set.of());+ }++ /**+ * @param appPorts TCP ports opened by the instance's security groups to publish on the host+ * via socat sidecars once the container is running (empty for none)+ */+ public void launch(Instance instance, ResolvedAmiImage image, String publicKey, String region, Set<Integer> appPorts) {instance.setState(InstanceState.pending());executor.submit(() -> {@@ -198,6 +211,11 @@ public class Ec2ContainerManager {LOG.infov("EC2 instance {0} running in container {1} (SSH host port {2})",instanceId, containerId, String.valueOf(sshHostPort));+ // Publish security-group TCP ingress ports on the host via socat sidecars.+ if (appPorts != null && !appPorts.isEmpty()) {+ portForwardManager.reconcile(instance, appPorts);+ }+// Inject SSH public keyif (publicKey != null && !publicKey.isBlank()) {injectSshKey(containerId, publicKey);@@ -232,6 +250,9 @@ public class Ec2ContainerManager {}instance.setState(InstanceState.stopping());executor.submit(() -> {+ // Sidecars forward to the container's current IP, which Docker reassigns on the+ // next start; tear them down so no forward is left pointing at a stale address.+ portForwardManager.unpublishAll(instance);try {dockerClient.stopContainerCmd(containerId).withTimeout(30).exec();} catch (NotFoundException e) {@@ -340,6 +361,7 @@ public class Ec2ContainerManager {int sshHostPort = instance.getSshHostPort();instance.setState(InstanceState.shuttingDown());executor.submit(() -> {+ portForwardManager.unpublishAll(instance);if (containerId != null) {try {dockerClient.removeContainerCmd(containerId).withForce(true).exec();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 d241622574..55758026c0 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@@ -612,6 +612,18 @@ public class Ec2QueryHandler {break;}}+ // Security group reassignment: --groups maps to GroupId.1, GroupId.2, ...+ List<String> groupIds = new ArrayList<>();+ for (int i = 1; ; i++) {+ String groupId = p.getFirst("GroupId." + i);+ if (groupId == null) {+ break;+ }+ groupIds.add(groupId);+ }+ if (!groupIds.isEmpty()) {+ service.modifyInstanceGroups(region, instanceId, groupIds);+ }return booleanResponse("ModifyInstanceAttribute");}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 4003e45075..c7c0709e8f 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@@ -30,6 +30,7 @@ import io.github.hectorvent.floci.core.storage.StorageBackend;import io.github.hectorvent.floci.core.storage.StorageFactory;import io.github.hectorvent.floci.services.ec2.model.Address;import io.github.hectorvent.floci.services.ec2.model.GroupIdentifier;+import io.github.hectorvent.floci.services.ec2.portforward.Ec2PortForwardManager;import io.github.hectorvent.floci.services.ec2.model.Image;import io.github.hectorvent.floci.services.ec2.model.Instance;import io.github.hectorvent.floci.services.ec2.model.InstanceNetworkInterface;@@ -81,6 +82,7 @@ public class Ec2Service {private final String accountId;private final EmulatorConfig config;private final Ec2ContainerManager containerManager;+ private final Ec2PortForwardManager portForwardManager;private final AmiImageResolver amiImageResolver;private final Ec2ImageCatalog imageCatalog;private final Ec2InstanceTypeCatalog instanceTypeCatalog;@@ -111,9 +113,10 @@ public class Ec2Service {@Injectpublic Ec2Service(EmulatorConfig config, Ec2ContainerManager containerManager,+ Ec2PortForwardManager portForwardManager,AmiImageResolver amiImageResolver, Ec2ImageCatalog imageCatalog,Ec2InstanceTypeCatalog instanceTypeCatalog, StorageFactory storageFactory) {- this(config, containerManager, amiImageResolver, imageCatalog, instanceTypeCatalog,+ this(config, containerManager, portForwardManager, amiImageResolver, imageCatalog, instanceTypeCatalog,storageFactory.create("ec2", "ec2-vpcs.json", new TypeReference<Map<String, Vpc>>() {}),storageFactory.create("ec2", "ec2-subnets.json", new TypeReference<Map<String, Subnet>>() {}),storageFactory.create("ec2", "ec2-security-groups.json", new TypeReference<Map<String, SecurityGroup>>() {}),@@ -134,6 +137,7 @@ public class Ec2Service {// Package-private for hermetic tests (pass in-memory or temp-dir-backed StorageBackends directly).Ec2Service(EmulatorConfig config, Ec2ContainerManager containerManager,+ Ec2PortForwardManager portForwardManager,AmiImageResolver amiImageResolver, Ec2ImageCatalog imageCatalog,Ec2InstanceTypeCatalog instanceTypeCatalog,StorageBackend<String, Vpc> vpcs,@@ -155,6 +159,7 @@ public class Ec2Service {this.accountId = config.defaultAccountId();this.config = config;this.containerManager = containerManager;+ this.portForwardManager = portForwardManager;this.amiImageResolver = amiImageResolver;this.imageCatalog = imageCatalog;this.instanceTypeCatalog = instanceTypeCatalog;@@ -178,6 +183,13 @@ public class Ec2Service {@PostConstructvoid restoreMetadataRegistrations() {+ if (portForwardManager != null) {+ portForwardManager.setPersister(inst -> {+ if (inst != null && inst.getRegion() != null && inst.getInstanceId() != null) {+ instances.put(key(inst.getRegion(), inst.getInstanceId()), inst);+ }+ });+ }if (config.services().ec2().mock()) {return;}@@ -191,6 +203,10 @@ public class Ec2Service {if (containerManager.restoreMetadataRegistration(instance)) {instances.put(key, instance);restored++;+ // Container is running: re-reserve host ports and recreate any missing socat sidecars.+ if (portForwardManager != null) {+ portForwardManager.restore(instance);+ }}}if (restored > 0) {@@ -631,13 +647,59 @@ public class Ec2Service {publicKey = kp.getPublicKey();}}- containerManager.launch(inst, dockerImage, publicKey, region);+ containerManager.launch(inst, dockerImage, publicKey, region, desiredPublishedPorts(region, inst));}}return reservation;}+ /**+ * Resolves the TCP ingress ports Floci should publish on the host for an instance, aggregated+ * across its attached security groups. Empty when publishing is disabled or nothing is opened.+ */+ private Set<Integer> desiredPublishedPorts(String region, Instance inst) {+ if (!config.services().ec2().publishSecurityGroupPorts()) {+ return Set.of();+ }+ List<SecurityGroup> sgs = new ArrayList<>();+ if (inst.getSecurityGroups() != null) {+ for (GroupIdentifier gi : inst.getSecurityGroups()) {+ securityGroups.get(key(region, gi.getGroupId())).ifPresent(sgs::add);+ }+ }+ return Ec2PortForwardManager.extractPublishablePorts(+ sgs, config.services().ec2().maxPublishedPortsPerInstance());+ }++ /**+ * Re-publishes host forwards for every running instance attached to the given security group,+ * so ports opened or closed via authorize/revoke ingress take effect on already-running+ * instances. No-op in mock mode or when publishing is disabled.+ */+ private void reconcilePublishedPortsForGroup(String region, String groupId) {+ if (!config.services().ec2().publishSecurityGroupPorts() || config.services().ec2().mock()) {+ return;+ }+ String prefix = region + "::";+ for (Instance inst : instances.scan(k -> k.startsWith(prefix))) {+ if (inst.getSecurityGroups() == null || inst.getDockerContainerId() == null) {+ continue;+ }+ boolean attached = inst.getSecurityGroups().stream()+ .anyMatch(g -> groupId.equals(g.getGroupId()));+ if (!attached) {+ continue;+ }+ String state = inst.getState() != null ? inst.getState().getName() : null;+ if (!"running".equals(state)) {+ continue;+ }+ portForwardManager.reconcile(inst, desiredPublishedPorts(region, inst));+ instances.put(key(region, inst.getInstanceId()), inst);+ }+ }+public Subnet requireSubnet(String region, String subnetId) {ensureDefaultResources(region);Subnet subnet = subnets.get(key(region, subnetId)).orElse(null);@@ -848,6 +910,34 @@ public class Ec2Service {instances.put(key(region, instanceId), inst);}+ /**+ * Replaces the security groups attached to an instance (ModifyInstanceAttribute with+ * {@code GroupId.N}). Validates each group, updates the instance and its network interfaces,+ * and re-publishes host forwards so ports opened by the newly attached groups take effect.+ */+ public void modifyInstanceGroups(String region, String instanceId, List<String> groupIds) {+ ensureDefaultResources(region);+ Instance inst = getRequiredInstance(region, instanceId);++ List<GroupIdentifier> identifiers = new ArrayList<>();+ for (String groupId : groupIds) {+ SecurityGroup sg = getRequiredSecurityGroup(region, groupId);+ identifiers.add(new GroupIdentifier(sg.getGroupId(), sg.getGroupName()));+ }++ inst.setSecurityGroups(new ArrayList<>(identifiers));+ if (inst.getNetworkInterfaces() != null) {+ inst.getNetworkInterfaces().forEach(eni -> eni.setGroups(new ArrayList<>(identifiers)));+ }+ instances.put(key(region, instanceId), inst);++ if (config.services().ec2().publishSecurityGroupPorts() && !config.services().ec2().mock()+ && inst.getDockerContainerId() != null+ && inst.getState() != null && "running".equals(inst.getState().getName())) {+ portForwardManager.reconcile(inst, desiredPublishedPorts(region, inst));+ }+ }+private Instance getRequiredInstance(String region, String instanceId) {Instance inst = instances.get(key(region, instanceId)).orElse(null);if (inst == null)@@ -1151,6 +1241,7 @@ public class Ec2Service {rules.addAll(createRules(region, groupId, perm, false));}securityGroups.put(key(region, groupId), sg);+ reconcilePublishedPortsForGroup(region, groupId);return rules;}@@ -1206,6 +1297,7 @@ public class Ec2Service {sg.getIpPermissions().removeIf(p -> matchesAnyPermission(p, permissions));securityGroups.put(key(region, groupId), sg);+ reconcilePublishedPortsForGroup(region, groupId);}public void revokeSecurityGroupEgress(String region, String groupId, List<IpPermission> permissions) {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 9e2c7a65ec..0e59b6e1f5 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@@ -5,7 +5,9 @@ import io.quarkus.runtime.annotations.RegisterForReflection;import java.time.Instant;import java.util.ArrayList;+import java.util.LinkedHashMap;import java.util.List;+import java.util.Map;@RegisterForReflection@JsonIgnoreProperties(ignoreUnknown = true)@@ -59,6 +61,10 @@ public class Instance {private int sshHostPort;private long terminatedAt;+ // Security-group ingress ports published on the host via socat sidecars:+ // container app port -> allocated host port. Not part of the AWS wire format.+ private Map<Integer, Integer> publishedPorts = new LinkedHashMap<>();+public Instance() {}public String getInstanceId() { return instanceId; }@@ -172,6 +178,14 @@ public class Instance {public String getContainerBridgeIp() { return containerBridgeIp; }public void setContainerBridgeIp(String containerBridgeIp) { this.containerBridgeIp = containerBridgeIp; }+ public Map<Integer, Integer> getPublishedPorts() {+ if (publishedPorts == null) {+ publishedPorts = new LinkedHashMap<>();+ }+ return publishedPorts;+ }+ public void setPublishedPorts(Map<Integer, Integer> publishedPorts) { this.publishedPorts = publishedPorts; }+public String getRootVolumeId() { return rootVolumeId; }public void setRootVolumeId(String rootVolumeId) { this.rootVolumeId = rootVolumeId; }diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/portforward/Ec2PortForwardManager.java b/src/main/java/io/github/hectorvent/floci/services/ec2/portforward/Ec2PortForwardManager.javanew file mode 100644index 0000000000..bb1c7e88a5--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/portforward/Ec2PortForwardManager.java@@ -0,0 +1,367 @@+package io.github.hectorvent.floci.services.ec2.portforward;++import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;+import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;+import io.github.hectorvent.floci.core.common.docker.ContainerSpec;+import io.github.hectorvent.floci.core.common.docker.PortAllocator;+import io.github.hectorvent.floci.services.ec2.model.Instance;+import io.github.hectorvent.floci.services.ec2.model.IpPermission;+import io.github.hectorvent.floci.services.ec2.model.SecurityGroup;+import com.github.dockerjava.api.DockerClient;+import com.github.dockerjava.api.command.InspectContainerResponse;+import com.github.dockerjava.api.model.ContainerNetwork;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;+import org.jboss.logging.Logger;++import java.util.ArrayList;+import java.util.LinkedHashMap;+import java.util.LinkedHashSet;+import java.util.List;+import java.util.Map;+import java.util.Set;+import java.util.concurrent.ExecutorService;+import java.util.concurrent.Executors;+import java.util.function.Consumer;++/**+ * Publishes EC2 instance application ports on the host, driven by the TCP ingress+ * rules of the instance's security groups.+ *+ * <p>For each opened TCP port a small {@code alpine/socat} sidecar container is started+ * as a host sibling (created through the mounted Docker socket, exactly like the instance+ * container and its SSH binding). The sidecar publishes an allocated host port and forwards+ * it to the instance container's IP, so {@code curl localhost:<hostPort>} reaches the app.+ *+ * <p>Because each forward is a fresh container, ports opened <em>after</em> launch via+ * {@code authorize-security-group-ingress} are handled the same way as ports present at+ * launch. The instance container itself is never modified.+ */+@ApplicationScoped+public class Ec2PortForwardManager {++ private static final Logger LOG = Logger.getLogger(Ec2PortForwardManager.class);++ /** SSH is already published on its own host port by the container manager; never re-forward it. */+ static final int SSH_PORT = 22;++ private final DockerClient dockerClient;+ private final ContainerBuilder containerBuilder;+ private final ContainerLifecycleManager lifecycleManager;+ private final PortAllocator portAllocator;+ private final EmulatorConfig config;++ private final ExecutorService executor = Executors.newCachedThreadPool(r -> {+ Thread t = new Thread(r, "ec2-port-forward");+ t.setDaemon(true);+ return t;+ });++ // Persists an instance after its publishedPorts change, so the mapping survives a+ // hard restart (not just the periodic/shutdown flush). Set by the owning service.+ private volatile Consumer<Instance> persister;++ @Inject+ public Ec2PortForwardManager(DockerClient dockerClient,+ ContainerBuilder containerBuilder,+ ContainerLifecycleManager lifecycleManager,+ PortAllocator portAllocator,+ EmulatorConfig config) {+ this.dockerClient = dockerClient;+ this.containerBuilder = containerBuilder;+ this.lifecycleManager = lifecycleManager;+ this.portAllocator = portAllocator;+ this.config = config;+ }++ /**+ * Reconciles the instance's live forwards against the desired port set: publishes ports+ * that are newly opened and unpublishes ports that no longer have an ingress rule. Runs+ * asynchronously so it does not block the calling API thread.+ */+ public void reconcile(Instance instance, Set<Integer> desiredPorts) {+ if (!enabled() || instance == null || instance.getDockerContainerId() == null) {+ return;+ }+ executor.submit(() -> reconcileNow(instance, desiredPorts));+ }++ void reconcileNow(Instance instance, Set<Integer> desiredPorts) {+ synchronized (instance) {+ // A reconcile queued before a stop/terminate must not republish against the+ // removed container: stop/terminate flip the state before their async+ // unpublishAll, so a non-running state here means the forwards are (being)+ // torn down and new sidecars would leak.+ String state = instance.getState() != null ? instance.getState().getName() : null;+ if (!"running".equals(state)) {+ return;+ }+ for (int port : desiredPorts) {+ if (!instance.getPublishedPorts().containsKey(port)) {+ publish(instance, port);+ }+ }+ for (Integer port : new ArrayList<>(instance.getPublishedPorts().keySet())) {+ if (!desiredPorts.contains(port)) {+ unpublish(instance, port);+ }+ }+ }+ }++ /**+ * Removes every forward for the instance and releases its host ports. Called on+ * terminate and stop. Runs on the caller's thread (both callers are already async).+ */+ public void unpublishAll(Instance instance) {+ if (instance == null) {+ return;+ }+ synchronized (instance) {+ for (Integer port : new ArrayList<>(instance.getPublishedPorts().keySet())) {+ unpublish(instance, port);+ }+ }+ }++ boolean enabled() {+ return config.services().ec2().publishSecurityGroupPorts() && !config.services().ec2().mock();+ }++ /** Sets the callback used to persist an instance after its forwards change. */+ public void setPersister(Consumer<Instance> persister) {+ this.persister = persister;+ }++ /**+ * Re-establishes an instance's persisted forwards after a restart: re-reserves each host+ * port so the allocator will not reuse it, and recreates any socat sidecar that did not+ * survive. Sidecars are independent containers, so a surviving one keeps working untouched.+ */+ public void restore(Instance instance) {+ if (!enabled() || instance == null || instance.getDockerContainerId() == null+ || instance.getPublishedPorts().isEmpty()) {+ return;+ }+ for (Map.Entry<Integer, Integer> entry : new LinkedHashMap<>(instance.getPublishedPorts()).entrySet()) {+ int appPort = entry.getKey();+ int hostPort = entry.getValue();+ portAllocator.markReserved(hostPort);+ String name = forwardContainerName(instance.getInstanceId(), appPort);+ if (lifecycleManager.findByName(name).isEmpty()) {+ LOG.infov("Recreating missing port-forward sidecar for EC2 instance {0} app port {1}",+ instance.getInstanceId(), appPort);+ if (!publishOn(instance, appPort, hostPort)) {+ portAllocator.release(hostPort);+ // Drop the stale mapping so a later reconcile can re-publish the port+ // instead of seeing it as already published.+ instance.getPublishedPorts().remove(appPort);+ persist(instance);+ }+ } else {+ LOG.infov("Restored port-forward for EC2 instance {0}: app port {1} -> host port {2}",+ instance.getInstanceId(), appPort, hostPort);+ }+ }+ }++ void publish(Instance instance, int appPort) {+ int hostPort = portAllocator.allocate(+ config.services().ec2().appPortRangeStart(),+ config.services().ec2().appPortRangeEnd());+ if (!publishOn(instance, appPort, hostPort)) {+ portAllocator.release(hostPort);+ }+ }++ private boolean publishOn(Instance instance, int appPort, int hostPort) {+ String instanceId = instance.getInstanceId();+ try {+ NetworkTarget target = resolveInstanceTarget(instance);+ if (target == null) {+ LOG.warnv("Could not resolve container IP for EC2 instance {0}; not publishing port {1}",+ instanceId, appPort);+ return false;+ }++ String name = forwardContainerName(instanceId, appPort);+ lifecycleManager.removeIfExists(name);++ ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(config.services().ec2().socatImage())+ .withName(name)+ .withEntrypoint(List.of("socat"))+ .withCmd(List.of(+ "TCP-LISTEN:" + appPort + ",fork,reuseaddr",+ "TCP:" + target.ip() + ":" + appPort))+ .withPortBinding(appPort, hostPort)+ .withLogRotation();+ if (target.network() != null) {+ specBuilder.withNetworkMode(target.network());+ }+ ContainerSpec spec = specBuilder.build();++ String containerId = lifecycleManager.create(spec);+ lifecycleManager.startCreated(containerId, spec);++ instance.getPublishedPorts().put(appPort, hostPort);+ persist(instance);+ LOG.infov("Published EC2 instance {0} app port {1} on host port {2} (socat -> {3}:{1})",+ instanceId, appPort, hostPort, target.ip());+ return true;+ } catch (Exception e) {+ LOG.warnv("Failed to publish EC2 instance {0} app port {1}: {2}", instanceId, appPort, e.getMessage());+ return false;+ }+ }++ void unpublish(Instance instance, int appPort) {+ String name = forwardContainerName(instance.getInstanceId(), appPort);+ lifecycleManager.removeIfExists(name);+ Integer hostPort = instance.getPublishedPorts().remove(appPort);+ if (hostPort != null) {+ portAllocator.release(hostPort);+ persist(instance);+ LOG.infov("Unpublished EC2 instance {0} app port {1} (released host port {2})",+ instance.getInstanceId(), appPort, hostPort);+ }+ }++ private void persist(Instance instance) {+ Consumer<Instance> p = persister;+ if (p != null) {+ try {+ p.accept(instance);+ } catch (Exception e) {+ LOG.debugv("Could not persist EC2 instance {0} after forward change: {1}",+ instance.getInstanceId(), e.getMessage());+ }+ }+ }++ static String forwardContainerName(String instanceId, int appPort) {+ return "floci-ec2-fwd-" + instanceId + "-" + appPort;+ }++ private NetworkTarget resolveInstanceTarget(Instance instance) {+ String containerId = instance.getDockerContainerId();+ if (containerId != null) {+ try {+ InspectContainerResponse inspect = dockerClient.inspectContainerCmd(containerId).exec();+ if (inspect.getNetworkSettings() != null) {+ Map<String, ContainerNetwork> networks = inspect.getNetworkSettings().getNetworks();+ NetworkTarget target = pickTarget(networks);+ if (target != null) {+ return target;+ }+ String ip = inspect.getNetworkSettings().getIpAddress();+ if (ip != null && !ip.isBlank()) {+ return new NetworkTarget(null, ip);+ }+ }+ } catch (Exception e) {+ LOG.warnv("Could not inspect EC2 instance {0} container for forward target: {1}",+ instance.getInstanceId(), e.getMessage());+ }+ }+ String stored = instance.getContainerBridgeIp();+ if (stored != null && !stored.isBlank()) {+ return new NetworkTarget(null, stored);+ }+ return null;+ }++ /**+ * Prefers a user-defined network (so the sidecar can join it and reach the instance by IP);+ * falls back to the default bridge with a null network name (the sidecar stays on the bridge+ * the instance is already on).+ */+ static NetworkTarget pickTarget(Map<String, ContainerNetwork> networks) {+ if (networks == null || networks.isEmpty()) {+ return null;+ }+ for (Map.Entry<String, ContainerNetwork> entry : networks.entrySet()) {+ String ip = entry.getValue() != null ? entry.getValue().getIpAddress() : null;+ if (!"bridge".equals(entry.getKey()) && ip != null && !ip.isBlank()) {+ return new NetworkTarget(entry.getKey(), ip);+ }+ }+ ContainerNetwork bridge = networks.get("bridge");+ if (bridge != null && bridge.getIpAddress() != null && !bridge.getIpAddress().isBlank()) {+ return new NetworkTarget(null, bridge.getIpAddress());+ }+ for (ContainerNetwork network : networks.values()) {+ if (network != null && network.getIpAddress() != null && !network.getIpAddress().isBlank()) {+ return new NetworkTarget(null, network.getIpAddress());+ }+ }+ return null;+ }++ /**+ * Extracts the set of TCP ports to publish for an instance from its security groups.+ *+ * <p>Only CIDR-sourced TCP rules are published: AWS makes a port opened to a referenced+ * security group reachable from that group's private IPs, not from the host, so rules+ * sourced only by a security-group reference are skipped. Ports are aggregated (deduped)+ * across all of the instance's groups, SSH (22) is never forwarded, and any single rule+ * whose port span exceeds {@code maxPerInstance} is skipped so an allow-all range cannot+ * spawn thousands of sidecars. The total is capped at {@code maxPerInstance}.+ */+ public static Set<Integer> extractPublishablePorts(List<SecurityGroup> securityGroups, int maxPerInstance) {+ Set<Integer> ports = new LinkedHashSet<>();+ for (SecurityGroup sg : securityGroups) {+ if (sg == null || sg.getIpPermissions() == null) {+ continue;+ }+ for (IpPermission perm : sg.getIpPermissions()) {+ if (!isTcp(perm.getIpProtocol()) || !hasCidrSource(perm)) {+ continue;+ }+ Integer from = perm.getFromPort();+ Integer to = perm.getToPort();+ if (from == null || to == null || from < 0 || to < 0) {+ continue;+ }+ int lo = Math.min(from, to);+ int hi = Math.max(from, to);+ long span = (long) hi - lo + 1;+ if (span > maxPerInstance) {+ LOG.warnv("Skipping wide security-group ingress range {0}-{1} on {2} (span {3} exceeds max {4})",+ lo, hi, sg.getGroupId(), span, maxPerInstance);+ continue;+ }+ for (int p = lo; p <= hi; p++) {+ if (p != SSH_PORT) {+ ports.add(p);+ }+ }+ }+ }+ if (ports.size() > maxPerInstance) {+ LOG.warnv("Capping published ports from {0} to {1} per instance", ports.size(), maxPerInstance);+ Set<Integer> capped = new LinkedHashSet<>();+ for (Integer port : ports) {+ if (capped.size() >= maxPerInstance) {+ break;+ }+ capped.add(port);+ }+ return capped;+ }+ return ports;+ }++ static boolean isTcp(String ipProtocol) {+ return "tcp".equalsIgnoreCase(ipProtocol) || "6".equals(ipProtocol);+ }++ static boolean hasCidrSource(IpPermission perm) {+ return (perm.getIpRanges() != null && !perm.getIpRanges().isEmpty())+ || (perm.getIpv6Ranges() != null && !perm.getIpv6Ranges().isEmpty());+ }++ /** A resolved forward destination: the instance IP and the network to reach it on (null = default bridge). */+ record NetworkTarget(String network, String ip) {+ }+}diff --git a/src/main/resources/application.yml b/src/main/resources/application.ymlindex 0f3e6d55d5..9ef3903583 100644--- a/src/main/resources/application.yml+++ b/src/main/resources/application.yml@@ -300,6 +300,11 @@ floci:imds-port: 9169ssh-port-range-start: 2200ssh-port-range-end: 2299+ publish-security-group-ports: true+ app-port-range-start: 30000+ app-port-range-end: 30999+ max-published-ports-per-instance: 20+ socat-image: alpine/socatmock: falseecs:enabled: truediff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManagerTest.javaindex a17ec2d16f..4f6ae5ed99 100644--- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManagerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManagerTest.java@@ -16,6 +16,7 @@ import com.github.dockerjava.api.model.StreamType;import java.nio.charset.StandardCharsets;import com.github.dockerjava.api.model.NetworkSettings;import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.services.ec2.portforward.Ec2PortForwardManager;import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;import io.github.hectorvent.floci.core.common.docker.ContainerDetector;import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;@@ -105,7 +106,8 @@ class Ec2ContainerManagerTest {dockerClient,mock(PortAllocator.class),mock(EmulatorConfig.class),- metadataServer);+ metadataServer,+ mock(Ec2PortForwardManager.class));Instance instance = new Instance();instance.setInstanceId("i-restored");@@ -402,7 +404,8 @@ class Ec2ContainerManagerTest {dockerClient,portAllocator,config,- metadataServer);+ metadataServer,+ mock(Ec2PortForwardManager.class));return new LaunchHarness(manager, dockerClient, metadataServer, logStreamer, builder);}diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServicePersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServicePersistenceTest.javaindex 0c49fc8c43..4a0c63043c 100644--- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServicePersistenceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServicePersistenceTest.java@@ -68,7 +68,7 @@ class Ec2ServicePersistenceTest {private Ec2Service newService(Path dir) {EmulatorConfig config = mock(EmulatorConfig.class);when(config.defaultAccountId()).thenReturn("000000000000");- return new Ec2Service(config, null, null, null, new Ec2InstanceTypeCatalog(),+ return new Ec2Service(config, null, null, null, null, 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>>() {}),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.javaindex bfda192f53..1d08541542 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@@ -6,8 +6,12 @@ import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.core.storage.InMemoryStorage;import io.github.hectorvent.floci.core.storage.StorageBackend;import io.github.hectorvent.floci.core.storage.StorageFactory;+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.Reservation;+import io.github.hectorvent.floci.services.ec2.model.SecurityGroup;import io.github.hectorvent.floci.services.ec2.model.Tag;import org.junit.jupiter.api.Test;@@ -28,6 +32,7 @@ class Ec2ServiceTest {void mockModeTreatsExistingNonTerminatedInstanceAsRunningContainer() {Ec2ContainerManager containerManager = mock(Ec2ContainerManager.class);Ec2Service service = new Ec2Service(mockConfig(true), containerManager,+ mock(Ec2PortForwardManager.class),mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),new InMemoryStorageFactory());Reservation reservation = service.runInstances("us-east-1", "ami-1234567890abcdef0", "t3.micro",@@ -43,6 +48,7 @@ class Ec2ServiceTest {@Testvoid runInstancesRequiresImageIdInsteadOfDefaulting() {Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),+ mock(Ec2PortForwardManager.class),mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),new InMemoryStorageFactory());@@ -58,6 +64,7 @@ class Ec2ServiceTest {@Testvoid launchTemplateVersionInheritsOmittedFieldsFromRequestedSourceVersion() {Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),+ mock(Ec2PortForwardManager.class),mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),new InMemoryStorageFactory());LaunchTemplate template = service.createLaunchTemplate("us-east-1", "app-template",@@ -87,6 +94,7 @@ class Ec2ServiceTest {Ec2ImageCatalog imageCatalog = new Ec2ImageCatalog();AmiImageResolver amiImageResolver = new AmiImageResolver(imageCatalog);Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),+ mock(Ec2PortForwardManager.class),amiImageResolver, imageCatalog, new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());assertTrue(service.describeImages("us-east-1", List.of(), List.of()).stream()@@ -101,6 +109,7 @@ class Ec2ServiceTest {@Testvoid describeInstanceTypesUsesExactCatalogMatches() {Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),+ mock(Ec2PortForwardManager.class),mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),new InMemoryStorageFactory());@@ -113,6 +122,41 @@ class Ec2ServiceTest {assertEquals(List.of("arm64"), types.getFirst().get("supportedArchitectures"));}+ @Test+ void modifyInstanceGroupsReassignsSecurityGroupsOnInstanceAndEni() {+ Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),+ mock(Ec2PortForwardManager.class),+ mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),+ new InMemoryStorageFactory());+ SecurityGroup web = service.createSecurityGroup("us-east-1", "web", "web sg", "vpc-default");+ Reservation reservation = service.runInstances("us-east-1", "ami-1234567890abcdef0", "t3.micro",+ 1, 1, null, List.of(), null, null, List.of(), null, null);+ String instanceId = reservation.getInstances().getFirst().getInstanceId();++ service.modifyInstanceGroups("us-east-1", instanceId, List.of(web.getGroupId()));++ Instance inst = service.findInstanceById(instanceId);+ assertEquals(List.of(web.getGroupId()),+ inst.getSecurityGroups().stream().map(GroupIdentifier::getGroupId).toList());+ assertEquals(web.getGroupId(),+ inst.getNetworkInterfaces().getFirst().getGroups().getFirst().getGroupId());+ }++ @Test+ void modifyInstanceGroupsRejectsUnknownSecurityGroup() {+ Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),+ mock(Ec2PortForwardManager.class),+ mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),+ new InMemoryStorageFactory());+ Reservation reservation = service.runInstances("us-east-1", "ami-1234567890abcdef0", "t3.micro",+ 1, 1, null, List.of(), null, null, List.of(), null, null);+ String instanceId = reservation.getInstances().getFirst().getInstanceId();++ AwsException error = assertThrows(AwsException.class,+ () -> service.modifyInstanceGroups("us-east-1", instanceId, List.of("sg-doesnotexist")));+ assertEquals("InvalidGroup.NotFound", error.getErrorCode());+ }+private static EmulatorConfig mockConfig(boolean ec2Mock) {EmulatorConfig config = mock(EmulatorConfig.class);EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/portforward/Ec2PortForwardManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/portforward/Ec2PortForwardManagerTest.javanew file mode 100644index 0000000000..4793196bfe--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/portforward/Ec2PortForwardManagerTest.java@@ -0,0 +1,253 @@+package io.github.hectorvent.floci.services.ec2.portforward;++import com.github.dockerjava.api.DockerClient;+import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;+import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;+import io.github.hectorvent.floci.core.common.docker.PortAllocator;+import io.github.hectorvent.floci.services.ec2.model.Instance;+import io.github.hectorvent.floci.services.ec2.model.InstanceState;+import io.github.hectorvent.floci.services.ec2.model.IpPermission;+import io.github.hectorvent.floci.services.ec2.model.IpRange;+import io.github.hectorvent.floci.services.ec2.model.Ipv6Range;+import io.github.hectorvent.floci.services.ec2.model.SecurityGroup;+import io.github.hectorvent.floci.services.ec2.model.UserIdGroupPair;+import org.junit.jupiter.api.Test;++import java.util.ArrayList;+import java.util.List;+import java.util.Optional;+import java.util.Set;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.ArgumentMatchers.anyInt;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.verifyNoInteractions;+import static org.mockito.Mockito.when;++class Ec2PortForwardManagerTest {++ private static final int MAX = 20;++ @Test+ void extractsTcpPortsFromCidrSourcedRules() {+ SecurityGroup sg = sg(+ tcpCidr(80, 80, "0.0.0.0/0"),+ tcpCidr(8080, 8080, "10.0.0.0/8"));++ assertEquals(Set.of(80, 8080), extract(sg));+ }++ @Test+ void treatsNumericProtocolSixAsTcp() {+ IpPermission perm = new IpPermission();+ perm.setIpProtocol("6");+ perm.setFromPort(443);+ perm.setToPort(443);+ perm.getIpRanges().add(new IpRange("0.0.0.0/0"));++ assertEquals(Set.of(443), extract(sg(perm)));+ }++ @Test+ void publishesEveryPortInARange() {+ assertEquals(Set.of(8000, 8001, 8002), extract(sg(tcpCidr(8000, 8002, "0.0.0.0/0"))));+ }++ @Test+ void publishesIpv6SourcedRules() {+ IpPermission perm = new IpPermission();+ perm.setIpProtocol("tcp");+ perm.setFromPort(80);+ perm.setToPort(80);+ perm.getIpv6Ranges().add(new Ipv6Range("::/0"));++ assertEquals(Set.of(80), extract(sg(perm)));+ }++ @Test+ void aggregatesAndDedupesAcrossSecurityGroups() {+ SecurityGroup a = sg(tcpCidr(80, 80, "0.0.0.0/0"));+ SecurityGroup b = sg(tcpCidr(80, 80, "0.0.0.0/0"), tcpCidr(443, 443, "0.0.0.0/0"));++ assertEquals(Set.of(80, 443),+ Ec2PortForwardManager.extractPublishablePorts(List.of(a, b), MAX));+ }++ @Test+ void skipsNonTcpProtocols() {+ assertTrue(extract(sg(protoCidr("udp", 53, 53, "0.0.0.0/0"))).isEmpty());+ assertTrue(extract(sg(protoCidr("17", 53, 53, "0.0.0.0/0"))).isEmpty());+ assertTrue(extract(sg(protoCidr("icmp", -1, -1, "0.0.0.0/0"))).isEmpty());+ }++ @Test+ void skipsAllProtocolsRule() {+ // ipProtocol "-1" means all protocols/all ports; fromPort/toPort come as -1.+ assertTrue(extract(sg(protoCidr("-1", -1, -1, "0.0.0.0/0"))).isEmpty());+ }++ @Test+ void skipsRulesSourcedOnlyBySecurityGroupReference() {+ IpPermission perm = new IpPermission();+ perm.setIpProtocol("tcp");+ perm.setFromPort(80);+ perm.setToPort(80);+ UserIdGroupPair pair = new UserIdGroupPair();+ pair.setGroupId("sg-web");+ perm.getUserIdGroupPairs().add(pair);++ assertTrue(extract(sg(perm)).isEmpty());+ }++ @Test+ void neverForwardsSsh() {+ assertTrue(extract(sg(tcpCidr(22, 22, "0.0.0.0/0"))).isEmpty());+ // A range spanning 22 keeps its other ports but drops 22.+ assertEquals(Set.of(21, 23), extract(sg(tcpCidr(21, 23, "0.0.0.0/0"))));+ }++ @Test+ void skipsRuleWhoseSpanExceedsMax() {+ assertTrue(extract(sg(tcpCidr(0, 65535, "0.0.0.0/0"))).isEmpty());+ }++ @Test+ void capsTotalPublishedPortsPerInstance() {+ Set<Integer> ports = Ec2PortForwardManager.extractPublishablePorts(+ List.of(sg(tcpCidr(3000, 3000, "0.0.0.0/0"),+ tcpCidr(3001, 3001, "0.0.0.0/0"),+ tcpCidr(3002, 3002, "0.0.0.0/0"))),+ 2);++ assertEquals(2, ports.size());+ }++ @Test+ void protocolHelpersRecognizeTcp() {+ assertTrue(Ec2PortForwardManager.isTcp("tcp"));+ assertTrue(Ec2PortForwardManager.isTcp("TCP"));+ assertTrue(Ec2PortForwardManager.isTcp("6"));+ assertFalse(Ec2PortForwardManager.isTcp("udp"));+ assertFalse(Ec2PortForwardManager.isTcp("17"));+ assertFalse(Ec2PortForwardManager.isTcp(null));+ }++ @Test+ void forwardContainerNameIsDeterministic() {+ assertEquals("floci-ec2-fwd-i-123-80",+ Ec2PortForwardManager.forwardContainerName("i-123", 80));+ }++ @Test+ void restoreDropsMappingWhenSidecarRecreationFails() {+ DockerClient dockerClient = mock(DockerClient.class);+ when(dockerClient.inspectContainerCmd(anyString())).thenThrow(new RuntimeException("docker down"));+ ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);+ when(lifecycleManager.findByName(anyString())).thenReturn(Optional.empty());+ PortAllocator portAllocator = mock(PortAllocator.class);++ EmulatorConfig config = mock(EmulatorConfig.class);+ EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);+ EmulatorConfig.Ec2ServiceConfig ec2 = mock(EmulatorConfig.Ec2ServiceConfig.class);+ when(config.services()).thenReturn(services);+ when(services.ec2()).thenReturn(ec2);+ when(ec2.publishSecurityGroupPorts()).thenReturn(true);+ when(ec2.mock()).thenReturn(false);++ Ec2PortForwardManager manager = new Ec2PortForwardManager(+ dockerClient, mock(ContainerBuilder.class), lifecycleManager, portAllocator, config);+ List<String> persisted = new ArrayList<>();+ manager.setPersister(inst -> persisted.add(inst.getInstanceId()));++ Instance instance = new Instance();+ instance.setInstanceId("i-1");+ instance.setDockerContainerId("c1");+ instance.getPublishedPorts().put(8080, 30000);++ manager.restore(instance);++ assertTrue(instance.getPublishedPorts().isEmpty(),+ "failed recreation must not leave a stale published-port entry");+ verify(portAllocator).markReserved(30000);+ verify(portAllocator).release(30000);+ assertEquals(List.of("i-1"), persisted);+ }++ @Test+ void reconcileNowSkipsNonRunningInstance() {+ PortAllocator portAllocator = mock(PortAllocator.class);+ ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);+ Ec2PortForwardManager manager = new Ec2PortForwardManager(+ mock(DockerClient.class), mock(ContainerBuilder.class), lifecycleManager,+ portAllocator, mock(EmulatorConfig.class));++ Instance instance = new Instance();+ instance.setInstanceId("i-1");+ instance.setDockerContainerId("c1");+ instance.setState(InstanceState.shuttingDown());++ manager.reconcileNow(instance, Set.of(80));++ assertTrue(instance.getPublishedPorts().isEmpty(),+ "a reconcile racing a terminate must not republish against the removed container");+ verifyNoInteractions(portAllocator, lifecycleManager);+ }++ @Test+ void reconcileNowPublishesForRunningInstance() {+ DockerClient dockerClient = mock(DockerClient.class);+ when(dockerClient.inspectContainerCmd(anyString())).thenThrow(new RuntimeException("docker down"));+ PortAllocator portAllocator = mock(PortAllocator.class);+ when(portAllocator.allocate(anyInt(), anyInt())).thenReturn(30000);++ EmulatorConfig config = mock(EmulatorConfig.class);+ EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);+ EmulatorConfig.Ec2ServiceConfig ec2 = mock(EmulatorConfig.Ec2ServiceConfig.class);+ when(config.services()).thenReturn(services);+ when(services.ec2()).thenReturn(ec2);+ when(ec2.appPortRangeStart()).thenReturn(30000);+ when(ec2.appPortRangeEnd()).thenReturn(30999);++ Ec2PortForwardManager manager = new Ec2PortForwardManager(+ dockerClient, mock(ContainerBuilder.class), mock(ContainerLifecycleManager.class),+ portAllocator, config);++ Instance instance = new Instance();+ instance.setInstanceId("i-1");+ instance.setDockerContainerId("c1");+ instance.setState(InstanceState.running());++ manager.reconcileNow(instance, Set.of(80));++ verify(portAllocator).allocate(30000, 30999);+ }++ private static Set<Integer> extract(SecurityGroup sg) {+ return Ec2PortForwardManager.extractPublishablePorts(List.of(sg), MAX);+ }++ private static SecurityGroup sg(IpPermission... perms) {+ SecurityGroup sg = new SecurityGroup();+ sg.setGroupId("sg-test");+ sg.setIpPermissions(new java.util.ArrayList<>(List.of(perms)));+ return sg;+ }++ private static IpPermission tcpCidr(int from, int to, String cidr) {+ return protoCidr("tcp", from, to, cidr);+ }++ private static IpPermission protoCidr(String proto, int from, int to, String cidr) {+ IpPermission perm = new IpPermission();+ perm.setIpProtocol(proto);+ perm.setFromPort(from);+ perm.setToPort(to);+ perm.getIpRanges().add(new IpRange(cidr));+ return perm;+ }+}diff --git a/src/test/resources/application.yml b/src/test/resources/application.ymlindex d52b7ef23b..58814c55ae 100644--- a/src/test/resources/application.yml+++ b/src/test/resources/application.yml@@ -183,6 +183,11 @@ floci:imds-port: 9169ssh-port-range-start: 2200ssh-port-range-end: 2299+ publish-security-group-ports: true+ app-port-range-start: 30000+ app-port-range-end: 30999+ max-published-ports-per-instance: 20+ socat-image: alpine/socatmock: trueecs:enabled: true