fix(ec2): preserve established host connections on ingress revoke (#9186)

With security-group enforcement on, revoking the last world-open ingress rule closes the relay's host listener at once and keeps the connections it already accepted, as AWS keeps tracked connections. When the instance's egress allows TCP to every address and port in the family the relay uses to reach the guest, AWS does not track those flows, so the revoke removes the relay and closes them immediately. A listener that cannot be closed falls back to removing the relay, one instance's failure no longer skips the group's other instances, and stop or terminate removes any draining relay. Ec2PublishedConnectionNightlyIntegrationTest covers both cases.
This commit is contained in:
Alexy Grabov authored and GitHub committed 2026-11-22 14:53:21 -04:00
1 parent 188371eabc
commit 624f1304d2
7 files changed
+344 -21

No files matched your search

@@ -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<String, String> 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 >/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<String> 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.
}
}
}
@@ -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) {