diff --git a/.github/ci/prefetch-images.sh b/.github/ci/prefetch-images.sh index 5024e13ed5..e1c85262fb 100755 --- a/.github/ci/prefetch-images.sh +++ b/.github/ci/prefetch-images.sh @@ -54,6 +54,10 @@ starts() { # The image a test constant pins, or empty (and a log line) when the constant cannot be read. # TestImages is found by name rather than by its package path, which a package rename changes. TEST_IMAGES="$(find src/test/java -path '*/testing/TestImages.java' -print -quit)" +if starts Ec2PublishedConnectionNightlyIntegrationTest; then + ecr public.ecr.aws/docker/library/alpine:latest + pull alpine/socat +fi test_image() { image="$(grep -oE "$1 *= *\"[^\"]+\"" "${TEST_IMAGES:-/dev/null}" | grep -oE '"[^"]+"' | tr -d '"')" [ -n "$image" ] || echo "$(date -u +%H:%M:%S) prefetch skipped: TestImages.$1 not readable" >> "$PREFETCH_LOG" diff --git a/docs/services/ec2.md b/docs/services/ec2.md index 27dde8ba19..42e5bbc32e 100644 --- a/docs/services/ec2.md +++ b/docs/services/ec2.md @@ -255,7 +255,7 @@ With `FLOCI_NETWORK_SECURITY_GROUP_ENFORCEMENT_ENABLED=true`, Floci prepares a s An ENI's IPv6 addresses are part of its identity too. A rule naming an IPv6 range matches a managed peer on any IPv6 address its ENI holds, and admits that peer's traffic only on its helper's Docker IPv6 address, never on its IPv4 one. On a Docker network without IPv6 the helper has no IPv6 address, so such a rule has nothing to match. `AssignIpv6Addresses` and `UnassignIpv6Addresses` update the ENI's firewall identity at once. -Security-group permissions on a host-published port use the source visible inside Docker, and Docker can replace the original client address (Docker Desktop shows every host client as its gateway). So while enforcement is enabled, host-published access counts as traffic from outside the VPC: Floci publishes an application port only when an ingress rule opens it to every address, `0.0.0.0/0` or `::/0`, since such a rule admits a client whatever address it arrives with. A client's family is still seen on the host, so a port only `0.0.0.0/0` opens is published on the host's IPv4 addresses, one only `::/0` opens on its IPv6 addresses, and one both open on every address. The socat sidecar described below dials the instance through its protected namespace, on the instance's IPv4 address, or on its Docker IPv6 address when only `::/0` opens the port; on a Docker network without IPv6 such a port is not published. A port that only a narrower CIDR, a prefix list or a referenced group opens stays reachable on the direct container path, where the firewall sees the peer's own ENI identity. Ports a rule opens after launch are published and revoking the rule removes the forward, as with enforcement disabled. SSH is published directly by the protected namespace. +Security-group permissions on a host-published port use the source visible inside Docker, and Docker can replace the original client address (Docker Desktop shows every host client as its gateway). So while enforcement is enabled, host-published access counts as traffic from outside the VPC: Floci publishes an application port only when an ingress rule opens it to every address, `0.0.0.0/0` or `::/0`, since such a rule admits a client whatever address it arrives with. A client's family is still seen on the host, so a port only `0.0.0.0/0` opens is published on the host's IPv4 addresses, one only `::/0` opens on its IPv6 addresses, and one both open on every address. The socat sidecar described below dials the instance through its protected namespace, on the instance's IPv4 address, or on its Docker IPv6 address when only `::/0` opens the port; on a Docker network without IPv6 such a port is not published. A port that only a narrower CIDR, a prefix list or a referenced group opens stays reachable on the direct container path, where the firewall sees the peer's own ENI identity. Authorizing a world-open rule after launch publishes the port. Revoking the last world-open rule closes the host listener. If egress permits TCP to every address and port in the address family the relay uses to reach the guest, revocation also closes existing connections immediately. With narrower egress, established connections can finish until the instance stops or terminates. SSH is published directly by the protected namespace. When enforcement is disabled, an instance's security groups can open a TCP port to any CIDR source and 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, with `TCP_NODELAY` on both sockets so a request the client sends as two small writes is not held for the first write's delayed ACK (about 40 ms per round trip otherwise). The listen socket also takes a `backlog` of 4096 (socat's default is 5), so a burst of connections is queued rather than silently dropped from a full accept queue; the kernel caps the backlog at `net.core.somaxconn`. 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: diff --git a/src/main/java/io/floci/aws/core/common/docker/ContainerLifecycleManager.java b/src/main/java/io/floci/aws/core/common/docker/ContainerLifecycleManager.java index 53f8f245cf..2d6f630345 100644 --- a/src/main/java/io/floci/aws/core/common/docker/ContainerLifecycleManager.java +++ b/src/main/java/io/floci/aws/core/common/docker/ContainerLifecycleManager.java @@ -272,6 +272,12 @@ public class ContainerLifecycleManager { return create(spec, resolvedImage, null); } + /** Creates a container Docker removes as soon as its process exits. */ + public String createAutoRemoving(ContainerSpec spec) { + String resolvedImage = imageCacheService.ensureImageExists(spec.image()); + return create(spec, resolvedImage, null, true, true); + } + /** * Creates a container for a specific Docker platform. * @@ -289,7 +295,12 @@ public class ContainerLifecycleManager { } private String create(ContainerSpec spec, String resolvedImage, String platform, boolean removeAnonymousVolumes) { - String containerId = createWithCaBundle(spec, resolvedImage, platform, removeAnonymousVolumes); + return create(spec, resolvedImage, platform, removeAnonymousVolumes, false); + } + + private String create(ContainerSpec spec, String resolvedImage, String platform, boolean removeAnonymousVolumes, + boolean autoRemove) { + String containerId = createWithCaBundle(spec, resolvedImage, platform, removeAnonymousVolumes, autoRemove); if (spec.hasNetworkConfiguration()) { try { attachNetworkBeforeStart(containerId, spec); @@ -312,11 +323,14 @@ public class ContainerLifecycleManager { } private String createWithCaBundle(ContainerSpec spec, String resolvedImage, String platform, - boolean removeAnonymousVolumes) { + boolean removeAnonymousVolumes, boolean autoRemove) { LOG.debugv("Creating container from spec: image={0}, name={1}", spec.image(), spec.name()); // Built once: a dynamic port binding allocates its host port here. HostConfig hostConfig = buildHostConfig(spec); + if (autoRemove) { + hostConfig.withAutoRemove(true); + } Optional caBundle = ContainerCaBundle.hostPath(config); if (caBundle.isEmpty()) { return createContainer(spec, resolvedImage, platform, hostConfig, spec.env()); diff --git a/src/main/java/io/floci/aws/services/ec2/Ec2Service.java b/src/main/java/io/floci/aws/services/ec2/Ec2Service.java index b0cebd4c89..0b967e9c5f 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2Service.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2Service.java @@ -1101,6 +1101,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab }; if (portForwardManager != null) { portForwardManager.setPersister(persister); + portForwardManager.setCurrentEnforcedPorts(instance -> RequestScopes.callAs(instance.getOwnerId(), + instance.getRegion(), () -> desiredPublishedPorts(instance.getRegion(), instance)), + (instance, family) -> RequestScopes.callAs(instance.getOwnerId(), instance.getRegion(), + () -> Ec2PortForwardManager.hasUnrestrictedEgress( + publicationSecurityGroups(instance.getRegion(), instance), family))); } if (containerManager != null) { containerManager.setPersister(persister); @@ -4726,16 +4731,21 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab if (!config.services().ec2().publishSecurityGroupPorts()) { return Ec2PortForwardManager.DesiredPorts.NONE; } + List sgs = publicationSecurityGroups(region, inst); + int max = config.services().ec2().maxPublishedPortsPerInstance(); + return securityGroupEnforcementEnabled() + ? Ec2PortForwardManager.extractWorldOpenPorts(sgs, max) + : Ec2PortForwardManager.DesiredPorts.anyFamily(Ec2PortForwardManager.extractPublishablePorts(sgs, max)); + } + + private List publicationSecurityGroups(String region, Instance inst) { List sgs = new ArrayList<>(); if (inst.getSecurityGroups() != null) { for (GroupIdentifier gi : inst.getSecurityGroups()) { securityGroups.get(key(region, gi.getGroupId())).ifPresent(sgs::add); } } - int max = config.services().ec2().maxPublishedPortsPerInstance(); - return securityGroupEnforcementEnabled() - ? Ec2PortForwardManager.extractWorldOpenPorts(sgs, max) - : Ec2PortForwardManager.DesiredPorts.anyFamily(Ec2PortForwardManager.extractPublishablePorts(sgs, max)); + return sgs; } private Map> policyPrefixLists(String region, List groups) { @@ -4797,6 +4807,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab return; } String prefix = region + "::"; + RuntimeException failure = null; for (Instance inst : instances.scan(k -> k.startsWith(prefix))) { if (inst.getSecurityGroups() == null || inst.getDockerContainerId() == null) { continue; @@ -4810,8 +4821,19 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab if (!"running".equals(state)) { continue; } - portForwardManager.reconcile(inst, desiredPublishedPorts(region, inst)); - instances.put(key(region, inst.getInstanceId()), inst); + try { + portForwardManager.reconcile(inst, desiredPublishedPorts(region, inst)); + instances.put(key(region, inst.getInstanceId()), inst); + } catch (RuntimeException e) { + if (failure == null) { + failure = e; + } else if (failure != e) { + failure.addSuppressed(e); + } + } + } + if (failure != null) { + throw failure; } } diff --git a/src/main/java/io/floci/aws/services/ec2/portforward/Ec2PortForwardManager.java b/src/main/java/io/floci/aws/services/ec2/portforward/Ec2PortForwardManager.java index 8bdffd24ae..242a6bf145 100644 --- a/src/main/java/io/floci/aws/services/ec2/portforward/Ec2PortForwardManager.java +++ b/src/main/java/io/floci/aws/services/ec2/portforward/Ec2PortForwardManager.java @@ -2,10 +2,13 @@ package io.floci.aws.services.ec2.portforward; import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.command.InspectContainerResponse; +import com.github.dockerjava.api.exception.NotFoundException; +import com.github.dockerjava.api.model.Container; import com.github.dockerjava.api.model.ContainerNetwork; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.ListenBacklog; import io.floci.aws.core.common.docker.ContainerBuilder; +import io.floci.aws.core.common.docker.ContainerExec; import io.floci.aws.core.common.docker.ContainerLifecycleManager; import io.floci.aws.core.common.docker.ContainerSpec; import io.floci.aws.core.common.docker.ContainerStorageHelper; @@ -28,9 +31,11 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.function.BiPredicate; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; +import java.util.regex.Pattern; import java.util.stream.Stream; /** @@ -74,6 +79,15 @@ public class Ec2PortForwardManager { private static final String IPV4_HOST_ADDRESSES = "0.0.0.0"; private static final String IPV6_HOST_ADDRESSES = "::"; + // A forked socat owns each accepted socket. Keep those children alive after closing the listener. + private static final List DRAINABLE_ENTRYPOINT = List.of("sh", "-c", """ + socat "$@" & + listener=$! + echo "$listener" > /tmp/floci-listener + wait "$listener" + while pidof socat >/dev/null; do sleep 1; done + """, "socat"); + private final DockerClient dockerClient; private final ContainerBuilder containerBuilder; private final ContainerLifecycleManager lifecycleManager; @@ -89,6 +103,8 @@ public class Ec2PortForwardManager { // 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 persister; + private Function currentEnforcedPorts; + private BiPredicate unrestrictedEgress; @Inject public Ec2PortForwardManager(DockerClient dockerClient, @@ -123,15 +139,44 @@ public class Ec2PortForwardManager { /** * 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. + * listener closure synchronously under enforcement and queues new publications. */ public void reconcile(Instance instance, DesiredPorts desiredPorts) { if (!enabled() || instance == null || instance.getDockerContainerId() == null) { return; } + if (enforced()) { + synchronized (instance) { + closeRevoked(instance, currentPorts(instance, desiredPorts)); + } + } executor.submit(() -> reconcileNow(instance, desiredPorts)); } + private DesiredPorts currentPorts(Instance instance, DesiredPorts snapshot) { + return currentEnforcedPorts != null && enforced() ? currentEnforcedPorts.apply(instance) : snapshot; + } + + private void closeRevoked(Instance instance, DesiredPorts desired) { + RuntimeException failure = null; + for (Integer port : new ArrayList<>(instance.getPublishedPorts().keySet())) { + if (desired.ports().get(port) != family(instance, port)) { + try { + revoke(instance, port); + } catch (RuntimeException e) { + if (failure == null) { + failure = e; + } else if (failure != e) { + failure.addSuppressed(e); + } + } + } + } + if (failure != null) { + throw failure; + } + } + void reconcileNow(Instance instance, DesiredPorts desiredPorts) { synchronized (instance) { // A reconcile queued before a stop/terminate must not republish against the @@ -142,21 +187,14 @@ public class Ec2PortForwardManager { if (!"running".equals(state)) { return; } + desiredPorts = currentPorts(instance, desiredPorts); + closeRevoked(instance, desiredPorts); for (Map.Entry desired : desiredPorts.ports().entrySet()) { int port = desired.getKey(); - // The rules opening the port changed family: its sidecar binds or dials the wrong addresses. - if (instance.getPublishedPorts().containsKey(port) && desired.getValue() != family(instance, port)) { - unpublish(instance, port); - } if (!instance.getPublishedPorts().containsKey(port)) { publish(instance, port, desired.getValue()); } } - for (Integer port : new ArrayList<>(instance.getPublishedPorts().keySet())) { - if (!desiredPorts.ports().containsKey(port)) { - unpublish(instance, port); - } - } } } @@ -172,6 +210,18 @@ public class Ec2PortForwardManager { for (Integer port : new ArrayList<>(instance.getPublishedPorts().keySet())) { unpublish(instance, port); } + if (enforced()) { + String prefix = ContainerStorageHelper.dockerName(config, "ec2-fwd-" + instance.getInstanceId() + "-"); + try { + for (Container relay : dockerClient.listContainersCmd().withShowAll(true) + .withNameFilter(List.of("^/?" + Pattern.quote(prefix) + "[0-9]+-draining-[0-9a-f]+$")) + .exec()) { + lifecycleManager.removeIfExistsStrict(relay.getId()); + } + } catch (RuntimeException e) { + LOG.warnv(e, "Could not clean up draining relays for instance {0}", instance.getInstanceId()); + } + } } } @@ -179,6 +229,18 @@ public class Ec2PortForwardManager { return config.services().ec2().publishSecurityGroupPorts() && !config.services().ec2().mock(); } + private boolean enforced() { + return config.network() != null && config.network().securityGroupEnforcement() != null + && config.network().securityGroupEnforcement().enabled(); + } + + /** Resolves current rules under the instance lock, including when launch supplied an older snapshot. */ + public void setCurrentEnforcedPorts(Function resolver, + BiPredicate egress) { + currentEnforcedPorts = resolver; + unrestrictedEgress = egress; + } + /** Sets the callback used to persist an instance after its forwards change. */ public void setPersister(Consumer persister) { this.persister = persister; @@ -257,9 +319,10 @@ public class Ec2PortForwardManager { ContainerStorageHelper.removeStaleContainer(config, lifecycleManager, name); // An IPv6-only host binding can reach the sidecar on its own IPv6 address, so its listener takes both. + boolean drainable = enforced(); ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(config.services().ec2().socatImage()) .withName(name) - .withEntrypoint(List.of("socat")) + .withEntrypoint(drainable ? DRAINABLE_ENTRYPOINT : List.of("socat")) .withCmd(List.of( (ipv6 ? "TCP6-LISTEN:" + appPort + ",ipv6only=0" : "TCP-LISTEN:" + appPort) + ",fork,reuseaddr,nodelay,backlog=" + ListenBacklog.ACCEPT, @@ -270,12 +333,15 @@ public class Ec2PortForwardManager { case ANY -> null; }) .withLogRotation(); + if (drainable) { + specBuilder.withInit(); + } if (target.network() != null) { specBuilder.withNetworkMode(target.network()); } ContainerSpec spec = specBuilder.build(); - String containerId = lifecycleManager.create(spec); + String containerId = drainable ? lifecycleManager.createAutoRemoving(spec) : lifecycleManager.create(spec); lifecycleManager.startCreated(containerId, spec); instance.getPublishedPorts().put(appPort, hostPort); @@ -297,6 +363,50 @@ public class Ec2PortForwardManager { void unpublish(Instance instance, int appPort) { String name = forwardContainerName(config, instance.getInstanceId(), appPort); ContainerStorageHelper.removeStaleContainer(config, lifecycleManager, name); + forget(instance, appPort); + } + + private void revoke(Instance instance, int appPort) { + if (!enforced()) { + unpublish(instance, appPort); + return; + } + String name = forwardContainerName(config, instance.getInstanceId(), appPort); + try { + InspectContainerResponse relay = dockerClient.inspectContainerCmd(name).exec(); + String id = relay.getId(); + if (Boolean.TRUE.equals(relay.getHostConfig().getAutoRemove()) + && (unrestrictedEgress == null || !unrestrictedEgress.test(instance, family(instance, appPort)))) { + try { + ContainerExec.Result closed = ContainerExec.run(dockerClient, id, new String[]{"sh", "-ec", """ + listener=$(cat /tmp/floci-listener) + if kill -0 "$listener" 2>/dev/null; then kill -KILL "$listener"; fi + while kill -0 "$listener" 2>/dev/null; do sleep 0.01; done + """}, 5); + if (closed.exitCode() != 0) { + throw new IllegalStateException(closed.summary()); + } + } catch (RuntimeException e) { + // An idle auto-removing relay may exit before Docker reports the exec result. + if (Boolean.TRUE.equals(dockerClient.inspectContainerCmd(id).exec().getState().getRunning())) { + LOG.warnv(e, "Could not close EC2 relay {0}'s listener, removing the relay to revoke host access", id); + lifecycleManager.removeIfExistsStrict(id); + } + forget(instance, appPort); + return; + } + // An idle relay can already have exited. A draining one still holds its host binding. + dockerClient.renameContainerCmd(id).withName(name + "-draining-" + id.substring(0, 12)).exec(); + } else { + lifecycleManager.removeIfExistsStrict(id); + } + } catch (NotFoundException e) { + lifecycleManager.removeIfExistsStrict(legacyForwardContainerName(config, instance.getInstanceId(), appPort)); + } + forget(instance, appPort); + } + + private void forget(Instance instance, int appPort) { Integer hostPort = instance.getPublishedPorts().remove(appPort); instance.getPublishedPortFamilies().remove(appPort); if (hostPort != null) { @@ -452,6 +562,17 @@ public class Ec2PortForwardManager { return new DesiredPorts(ports); } + public static boolean hasUnrestrictedEgress(List groups, PublishedPortFamily family) { + // A dual-stack publication uses IPv4 for its connection to the guest. + return groups.stream().flatMap(group -> group.getIpPermissionsEgress().stream()) + .filter(permission -> "-1".equals(permission.getIpProtocol()) + || (isTcp(permission.getIpProtocol()) && Integer.valueOf(0).equals(permission.getFromPort()) + && Integer.valueOf(65535).equals(permission.getToPort()))) + .anyMatch(permission -> family == PublishedPortFamily.IPV6 + ? opensToEveryAddress(permission.getIpv6Ranges().stream().map(range -> range.getCidrIpv6())) + : opensToEveryAddress(permission.getIpRanges().stream().map(range -> range.getCidrIp()))); + } + /** Whether any of the CIDRs is a valid one with a prefix length of 0, which every address of its family matches. */ static boolean opensToEveryAddress(Stream cidrs) { return cidrs.filter(cidr -> cidr != null).map(String::trim) diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2PublishedConnectionNightlyIntegrationTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2PublishedConnectionNightlyIntegrationTest.java new file mode 100644 index 0000000000..2d2ee8fc55 --- /dev/null +++ b/src/test/java/io/floci/aws/services/ec2/Ec2PublishedConnectionNightlyIntegrationTest.java @@ -0,0 +1,125 @@ +package io.floci.aws.services.ec2; + +import com.github.dockerjava.api.DockerClient; +import io.floci.aws.core.common.docker.ContainerExec; +import io.floci.aws.services.ec2.model.Instance; +import io.floci.aws.testing.AwsTestClients; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.QuarkusTestProfile; +import io.quarkus.test.junit.TestProfile; +import jakarta.inject.Inject; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.ec2.Ec2Client; +import software.amazon.awssdk.services.ec2.model.IpPermission; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.net.SocketException; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; + +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.*; + +@QuarkusTest +@TestProfile(Ec2PublishedConnectionNightlyIntegrationTest.Profile.class) +@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true") +class Ec2PublishedConnectionNightlyIntegrationTest { + public static class Profile implements QuarkusTestProfile { + @Override + public Map getConfigOverrides() { + return Map.of("floci.services.ec2.mock", "false", + "floci.network.security-group-enforcement.enabled", "true", + "floci.docker.resource-namespace", "ec2-published-connection-test"); + } + } + + @Inject Ec2Service service; + @Inject DockerClient docker; + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void revocationPreservesOnlyTrackedSockets(boolean trackedEgress) throws Exception { + try (Ec2Client ec2 = AwsTestClients.create(Ec2Client.builder(), "000000000000", Region.US_EAST_1)) { + String group = ec2.createSecurityGroup(r -> r.groupName("echo-" + UUID.randomUUID()) + .description("Published echo test")).groupId(); + try { + if (trackedEgress) { + ec2.revokeSecurityGroupEgress(r -> r.groupId(group).ipPermissions( + ec2.describeSecurityGroups(d -> d.groupIds(group)).securityGroups().getFirst() + .ipPermissionsEgress())); + } + String id = ec2.runInstances(r -> r.imageId("ami-alpine").instanceType("t3.micro").minCount(1) + .maxCount(1).securityGroupIds(group)).instances().getFirst().instanceId(); + try { + await().atMost(Duration.ofMinutes(2)).until(() -> service.getInstance("us-east-1", id) + .map(i -> "running".equals(i.getState().getName())).orElse(false)); + Instance instance = service.getInstance("us-east-1", id).orElseThrow(); + ContainerExec.Result echo = ContainerExec.run(docker, instance.getDockerContainerId(), + new String[]{"sh", "-c", "nc -lk -p 8080 -e cat /dev/null 2>&1 &"}, 5); + assertEquals(0, echo.exitCode(), echo.summary()); + IpPermission rule = IpPermission.builder().ipProtocol("tcp").fromPort(8080).toPort(8080) + .ipRanges(r -> r.cidrIp("0.0.0.0/0")).build(); + ec2.authorizeSecurityGroupIngress(r -> r.groupId(group).ipPermissions(rule)); + int port = await().atMost(Duration.ofSeconds(30)).until( + () -> service.getInstance("us-east-1", id).orElseThrow().getPublishedPorts().get(8080), + Objects::nonNull); + try (Socket tracked = new Socket()) { + tracked.connect(new InetSocketAddress("127.0.0.1", port), 3000); + tracked.setSoTimeout(3000); + assertEquals(1, echoByte(tracked, 1)); + ec2.revokeSecurityGroupIngress(r -> r.groupId(group).ipPermissions(rule)); + assertFalse(service.getInstance("us-east-1", id).orElseThrow().getPublishedPorts() + .containsKey(8080)); + try (Socket fresh = new Socket()) { + fresh.setSoTimeout(3000); + try { + fresh.connect(new InetSocketAddress("127.0.0.1", port), 3000); + assertEquals(-1, echoByte(fresh, 2)); + } catch (IOException expected) { + // Docker Desktop may refuse or reset the new connection. + } + } + if (trackedEgress) { + assertEquals(3, echoByte(tracked, 3)); + List drainName = List.of(id + "-8080-draining-"); + assertFalse(docker.listContainersCmd().withNameFilter(drainName).exec().isEmpty()); + ec2.stopInstances(r -> r.instanceIds(id)); + await().atMost(Duration.ofSeconds(30)).until(() -> docker.listContainersCmd() + .withShowAll(true).withNameFilter(drainName) + .exec().isEmpty()); + assertDisconnected(tracked); + } else { + assertDisconnected(tracked); + } + } + } finally { + ec2.terminateInstances(r -> r.instanceIds(id)); + } + } finally { + await().atMost(Duration.ofSeconds(60)).ignoreExceptions() + .until(() -> ec2.deleteSecurityGroup(r -> r.groupId(group)).sdkHttpResponse().isSuccessful()); + } + } + } + + private static int echoByte(Socket socket, int value) throws IOException { + socket.getOutputStream().write(value); + return socket.getInputStream().read(); + } + + private static void assertDisconnected(Socket socket) throws IOException { + try { + assertEquals(-1, echoByte(socket, 3)); + } catch (SocketException expected) { + // A removed relay can reset the connection instead of closing it cleanly. + } + } +} diff --git a/src/test/java/io/floci/aws/services/ec2/portforward/Ec2PortForwardManagerTest.java b/src/test/java/io/floci/aws/services/ec2/portforward/Ec2PortForwardManagerTest.java index a0d7ec3700..95c890e622 100644 --- a/src/test/java/io/floci/aws/services/ec2/portforward/Ec2PortForwardManagerTest.java +++ b/src/test/java/io/floci/aws/services/ec2/portforward/Ec2PortForwardManagerTest.java @@ -352,6 +352,43 @@ class Ec2PortForwardManagerTest { verify(forwarding.portAllocator()).release(30000); } + @Test + void unrestrictedEgressRequiresWorldOpenSourceFamilyAndEveryTcpPort() { + SecurityGroup group = new SecurityGroup(); + group.setIpPermissionsEgress(List.of(tcpCidr(0, 65534, "0.0.0.0/0"), + tcpCidr(0, 65535, "10.0.0.0/8"), IpPermissions.tcp(0, 65535, "::/0"))); + assertFalse(Ec2PortForwardManager.hasUnrestrictedEgress(List.of(group), PublishedPortFamily.IPV4)); + assertTrue(Ec2PortForwardManager.hasUnrestrictedEgress(List.of(group), PublishedPortFamily.IPV6)); + + IpPermission all = tcpCidr(0, 65535, "0.0.0.0/0"); + all.setIpProtocol("-1"); + all.setFromPort(null); + all.setToPort(null); + group.setIpPermissionsEgress(List.of(all)); + assertTrue(Ec2PortForwardManager.hasUnrestrictedEgress(List.of(group), PublishedPortFamily.IPV4)); + assertFalse(Ec2PortForwardManager.hasUnrestrictedEgress(List.of(group), PublishedPortFamily.IPV6)); + } + + @Test + void failedCloseOfRunningRelayFallsBackToRemoval() { + DockerClient docker = mock(DockerClient.class, RETURNS_DEEP_STUBS); + Forwarding forwarding = forwarding(docker); + when(forwarding.config().network().securityGroupEnforcement().enabled()).thenReturn(true); + Instance instance = running(); + instance.getPublishedPorts().put(8080, 30000); + InspectContainerResponse relay = docker.inspectContainerCmd("floci-aws-ec2-fwd-i-1-8080").exec(); + when(relay.getId()).thenReturn("relay"); + when(relay.getHostConfig().getAutoRemove()).thenReturn(true); + when(docker.execCreateCmd("relay")).thenThrow(new IllegalStateException("Docker unavailable")); + when(docker.inspectContainerCmd("relay").exec().getState().getRunning()).thenReturn(true); + + forwarding.manager().reconcileNow(instance, Ec2PortForwardManager.DesiredPorts.NONE); + + assertTrue(instance.getPublishedPorts().isEmpty()); + verify(forwarding.lifecycle()).removeIfExistsStrict("relay"); + verify(forwarding.portAllocator()).release(30000); + } + /** A manager that builds real sidecar specs, allocating host port 30000 for every forward. */ private record Forwarding(Ec2PortForwardManager manager, ContainerLifecycleManager lifecycle, PortAllocator portAllocator, EmulatorConfig config) {