fix(ec2): report a reachable EIP address, and run gzipped user-data (#2621)

* fix(ec2): report an address that actually answers, and run gzipped user-data

Two independent bugs, both of which end a Terratest suite the moment it tries
to SSH into an instance.

1. The address the API reports was never an address that works. Launch set
   PublicIpAddress to 127.0.0.1 on the strength of a comment calling it
   "host-reachable", but Docker publishes the guest's SSH on a high host port,
   so :22 there is nothing. AllocateAddress then invents a 54.x.x.x that routes
   nowhere, and that is the value Terraform surfaces as aws_eip.x.public_ip and
   test suites dial. The invariant now is that whatever DescribeInstances and
   DescribeAddresses report accepts a connection on the service's real port.

   Where the container network is routable from Floci's API clients — native
   Linux Docker, OrbStack — that address is the container's own IP: port 22 is
   really port 22 there, with no published mapping to translate, and so is every
   other port the guest listens on. Where it is not — Docker Desktop, whose
   containers sit behind a VM — nothing changes and 127.0.0.1 plus published
   ports remains. Which case applies is detected, never assumed, by a throwaway
   TCP connect towards the container network: a refusal is proof of a route,
   since only the container's network stack could have sent the RST. The one
   case a probe cannot settle is Floci running inside a container itself, where
   it measures container-to-container reachability while the clients that will
   use the answer are on the host; there the Docker backend arbitrates and
   FLOCI_SERVICES_EC2_CONTAINER_IPS_ROUTABLE overrides either way.

   AssociateAddress re-points the EIP at that reachable address rather than
   leaving the fictional one. Aliasing instead would need Floci to own routing
   or DNS on the client's machine, and clients that read the address out of the
   API and dial it — Terratest does exactly this — would still get something
   dead. Association is also the first moment the answer is knowable. The cost
   is one deliberate deviation from AWS, an EIP whose public IP changes when it
   is associated; the AllocationId, AssociationId and domain are untouched, and
   disassociation restores the allocated address.

2. Gzipped cloud-init user-data was skipped in silence. The launch path
   recognised a literal "#!" or a plaintext MIME boundary and nothing else, so
   data.cloudinit_config { gzip = true } — the documented way to pass multipart
   user-data — was dropped whole. The instance booted fine and was simply
   missing everything it was supposed to install, which is what made this
   expensive to find. UserData is now unwrapped through gzip, base64, and
   base64-of-gzip before the existing shellscript/MIME handling, and the "no
   executable parts" line is a WARN that says what the consequence is.

* fix(ec2): re-resolve an associated EIP's address on DescribeAddresses

Association can happen before the instance has a container, and Docker hands out
a different bridge IP after a stop/start; either leaves the association naming an
address that no longer answers. DescribeAddresses is the call Terraform refreshes
public_ip from, so it is the last chance to be right.

* test(ec2): cover EIP re-pointing on associate, describe and disassociate

The address rewrite had no test of its own: reverting pointAddressAtInstance
left every existing test green, so nothing was holding the behaviour in place.
These three assert the claim directly — association reports the reachable
address rather than the invented 54.x.x.x one, DescribeAddresses re-resolves it
after the container IP moves, and disassociation hands the allocation back.

* docs(ec2): document container-IP routability and the EIP address rewrite

FLOCI_SERVICES_EC2_CONTAINER_IPS_ROUTABLE was undocumented, and the IMDS table
still promised public-ipv4 always returns 127.0.0.1. The Elastic IP section now
states the one deliberate deviation from AWS — an associated EIP's public IP is
rewritten to something reachable — so it is not discovered by surprise.

* fix(ec2): bound gzipped UserData decompression to stop a heap-exhaustion DoS

GZIPInputStream#readAllBytes() materialized the full decompressed
UserData with no size limit, so a caller-controlled gzip stream (e.g.
via CreateLaunchConfiguration) could expand to gigabytes in the shared
emulator JVM. Bounds it the same way AwsJsonCborController.decodeBody
already does: read in chunks, discard and warn past 10 MB decompressed.

Also documents the container-ips-routable override in both the main
and test application.yml templates, alongside the other ec2 keys.

* fix(ec2): bound aggregate concurrent UserData gzip decompression

The per-payload 10MB decompression cap runs independently per launch
on the unbounded cached launch executor, so it only bounds what a
single launch can allocate. N concurrent RunInstances/
CreateLaunchConfiguration calls, each smuggling a near-cap gzip
payload, could together decompress N * 10MB at once with no aggregate
ceiling.

Add a shared Semaphore(4) that gunzip must acquire before
decompressing and release afterward, budgeting ~40MB of decompressed
UserData in flight at a time - a few multiples of the per-payload cap
rather than 1, so an ordinary burst of legitimate concurrent launches
isn't serialized to one at a time. A launch that can't acquire the
budget blocks briefly rather than failing, mirroring the existing
ContainerLauncher.POPULATE_SEMAPHORE pattern for capping concurrent
code-volume populates.

Adds a concurrency test that drives 12 real concurrent launches with
near-cap gzip UserData through a fixed thread pool and asserts, via a
test-only hook, that peak concurrent decompressions never exceeds 4.
Verified the test fails (peak of 12) when the budget is disabled.
This commit is contained in:
Allen Sanborn authored and GitHub committed 2026-08-28 11:35:06 -04:00
1 parent c96dc98065
commit 41b5148824
11 files changed
+848 -12

No files matched your search

@@ -0,0 +1,134 @@
package io.github.hectorvent.floci.services.ec2;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.InfoCmd;
import com.github.dockerjava.api.model.Info;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
import org.junit.jupiter.api.Test;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Answers.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class ContainerNetworkReachabilityTest {
/** An address in the documentation-only TEST-NET-1 range: reachable from nowhere. */
private static final String UNROUTABLE_IP = "192.0.2.1";
private static ContainerNetworkReachability reachability(Optional<Boolean> override,
boolean flociInContainer,
String dockerOperatingSystem) {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().ec2().containerIpsRoutable()).thenReturn(override);
ContainerDetector detector = mock(ContainerDetector.class);
when(detector.isRunningInContainer()).thenReturn(flociInContainer);
DockerClient dockerClient = mock(DockerClient.class);
InfoCmd infoCmd = mock(InfoCmd.class);
Info info = mock(Info.class);
when(dockerClient.infoCmd()).thenReturn(infoCmd);
when(infoCmd.exec()).thenReturn(info);
when(info.getOperatingSystem()).thenReturn(dockerOperatingSystem);
return new ContainerNetworkReachability(config, detector, dockerClient);
}
@Test
void configuredValueWinsWithoutProbing() {
DockerClient dockerClient = mock(DockerClient.class);
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().ec2().containerIpsRoutable()).thenReturn(Optional.of(true));
ContainerDetector detector = mock(ContainerDetector.class);
ContainerNetworkReachability reachability =
new ContainerNetworkReachability(config, detector, dockerClient);
assertTrue(reachability.isContainerIpRoutable(UNROUTABLE_IP));
verify(dockerClient, never()).infoCmd();
verify(detector, never()).isRunningInContainer();
}
@Test
void configuredFalseOverridesAProbeThatWouldSucceed() {
ContainerNetworkReachability reachability =
reachability(Optional.of(false), false, "OrbStack");
assertFalse(reachability.isContainerIpRoutable("127.0.0.1"));
}
@Test
void refusedConnectionCountsAsRoutable() {
// Nothing listens on 127.0.0.1:22 in CI either way; what matters is that the loopback
// stack answers with a RST rather than swallowing the packet.
ContainerNetworkReachability reachability =
reachability(Optional.empty(), false, "OrbStack");
assertTrue(reachability.isContainerIpRoutable("127.0.0.1"));
}
@Test
void unreachableAddressCountsAsUnroutable() {
ContainerNetworkReachability reachability =
reachability(Optional.empty(), false, "OrbStack");
int previousTimeout = ContainerNetworkReachability.probeTimeoutMillis;
ContainerNetworkReachability.probeTimeoutMillis = 250;
try {
assertFalse(reachability.isContainerIpRoutable(UNROUTABLE_IP));
} finally {
ContainerNetworkReachability.probeTimeoutMillis = previousTimeout;
}
}
@Test
void containerisedFlociOnDockerDesktopDoesNotTrustItsOwnProbe() {
// The probe succeeds container-to-container on Docker Desktop too, but the host — where
// Terraform and Terratest run — still cannot route there.
ContainerNetworkReachability reachability =
reachability(Optional.empty(), true, "Docker Desktop");
assertFalse(reachability.isContainerIpRoutable("127.0.0.1"));
}
@Test
void containerisedFlociOnALinuxBackendTrustsItsProbe() {
ContainerNetworkReachability reachability =
reachability(Optional.empty(), true, "Ubuntu 24.04.1 LTS");
assertTrue(reachability.isContainerIpRoutable("127.0.0.1"));
}
@Test
void answerIsMemoisedAcrossInstances() {
ContainerNetworkReachability reachability =
reachability(Optional.empty(), false, "OrbStack");
assertTrue(reachability.isContainerIpRoutable("127.0.0.1"));
// A later, unreachable target does not re-open the question.
assertTrue(reachability.isContainerIpRoutable(UNROUTABLE_IP));
reachability.forget();
ContainerNetworkReachability.probeTimeoutMillis = 250;
try {
assertFalse(reachability.isContainerIpRoutable(UNROUTABLE_IP));
} finally {
ContainerNetworkReachability.probeTimeoutMillis = 1500;
}
}
@Test
void missingContainerIpIsNotRoutable() {
ContainerNetworkReachability reachability =
reachability(Optional.empty(), false, "OrbStack");
assertFalse(reachability.isContainerIpRoutable(null));
assertFalse(reachability.isContainerIpRoutable(" "));
}
}
@@ -31,12 +31,17 @@ import org.junit.jupiter.api.Test;
import java.io.InputStream;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BooleanSupplier;
@@ -137,7 +142,8 @@ class Ec2ContainerManagerTest {
mock(EmulatorConfig.class, RETURNS_DEEP_STUBS),
metadataServer,
mock(Ec2PortForwardManager.class),
mock(RegionResolver.class));
mock(RegionResolver.class),
mock(ContainerNetworkReachability.class));
Instance instance = new Instance();
instance.setInstanceId("i-restored");
@@ -197,6 +203,178 @@ class Ec2ContainerManagerTest {
Ec2ContainerManager.userDataShellScripts(userData));
}
private static String gzipBase64(String plain) throws Exception {
java.io.ByteArrayOutputStream bytes = new java.io.ByteArrayOutputStream();
try (java.util.zip.GZIPOutputStream gzip = new java.util.zip.GZIPOutputStream(bytes)) {
gzip.write(plain.getBytes(StandardCharsets.UTF_8));
}
return java.util.Base64.getEncoder().encodeToString(bytes.toByteArray());
}
private static final String CLOUDINIT_MULTIPART = """
Content-Type: multipart/mixed; boundary="MIMEBOUNDARY"
MIME-Version: 1.0
--MIMEBOUNDARY
Content-Disposition: attachment; filename="bastion-default-cloud-init"
Content-Transfer-Encoding: 7bit
Content-Type: text/x-shellscript
Mime-Version: 1.0
#!/bin/bash
apt-get install -y redis-tools
--MIMEBOUNDARY--
""";
@Test
void userDataShellScriptsDecodesBase64OfGzippedCloudInit() throws Exception {
// What data.cloudinit_config { gzip = true, base64_encode = true } renders, as it
// reaches the launch-configuration path that stores UserData still wire-encoded.
assertEquals(
List.of("#!/bin/bash\napt-get install -y redis-tools\n"),
Ec2ContainerManager.userDataShellScripts(gzipBase64(CLOUDINIT_MULTIPART)));
}
@Test
void userDataShellScriptsDiscardsGzipBombRatherThanExhaustingHeap() throws Exception {
// A highly-compressible payload well past the 10 MB decompressed cap this guards
// against: ~50 MB of a repeated character gzips down to a few KB on the wire, so an
// Auto Scaling launch configuration can smuggle it through in a single UserData field.
// Without the bound, GZIPInputStream#readAllBytes materializes the full expansion in
// the shared emulator JVM. With it, decoding gives up and no scripts are extracted.
String bomb = "A".repeat(50 * 1024 * 1024);
assertEquals(List.of(), Ec2ContainerManager.userDataShellScripts(gzipBase64(bomb)));
}
@Test
void userDataShellScriptsBoundsAggregateConcurrentDecompression() throws Exception {
// Each launch decodes its UserData independently on Ec2ContainerManager's unbounded
// cached launch executor, so the per-payload 10 MB cap alone does not stop many
// concurrent launches from each decompressing near that limit at once (Greptile's
// follow-up on the gzip-bomb fix). Drive real concurrent decompressions through the
// public entry point and use the test hook to prove no more than
// MAX_CONCURRENT_USER_DATA_DECOMPRESSIONS (4) ever run at the same instant, while still
// exercising genuine concurrency rather than serialized calls.
int concurrentLaunches = 12;
AtomicInteger active = new AtomicInteger(0);
AtomicInteger peakActive = new AtomicInteger(0);
Ec2ContainerManager.userDataDecompressionTestHook = () -> {
int now = active.incrementAndGet();
peakActive.accumulateAndGet(now, Math::max);
try {
Thread.sleep(75);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
} finally {
active.decrementAndGet();
}
};
List<List<String>> results = new CopyOnWriteArrayList<>();
ExecutorService pool = Executors.newFixedThreadPool(concurrentLaunches);
try {
// ~9 MB of a repeated character: near the 10 MB per-payload cap, well within it.
String nearCapPayload = "A".repeat(9 * 1024 * 1024);
String gzipped = gzipBase64(nearCapPayload);
List<Future<List<String>>> futures = new ArrayList<>();
for (int i = 0; i < concurrentLaunches; i++) {
futures.add(pool.submit(() -> Ec2ContainerManager.userDataShellScripts(gzipped)));
}
for (Future<List<String>> future : futures) {
results.add(future.get(30, TimeUnit.SECONDS));
}
} finally {
pool.shutdownNow();
Ec2ContainerManager.userDataDecompressionTestHook = null;
}
assertEquals(concurrentLaunches, results.size());
assertTrue(peakActive.get() <= 4,
"peak concurrent UserData decompressions was " + peakActive.get() + ", expected <= 4");
assertTrue(peakActive.get() >= 2,
"test did not exercise real concurrency; peak concurrent decompressions was only "
+ peakActive.get());
}
@Test
void userDataShellScriptsDecodesPlainBase64ShellScript() {
String script = "#!/bin/bash\necho ready\n";
String encoded = java.util.Base64.getEncoder().encodeToString(script.getBytes(StandardCharsets.UTF_8));
assertEquals(List.of(script), Ec2ContainerManager.userDataShellScripts(encoded));
}
@Test
void userDataShellScriptsLeavesAccidentallyBase64ShapedScriptAlone() {
// Valid base64 by shape, but decodes to nothing cloud-init would recognise, so it must
// be treated as the literal script it is rather than decoded into binary noise.
String script = "#!/bin/sh\necho deadbeefdeadbeef\n";
assertEquals(List.of(script), Ec2ContainerManager.userDataShellScripts(script));
}
@Test
void userDataShellScriptsIgnoresGarbage() {
assertTrue(Ec2ContainerManager.userDataShellScripts("not a script at all").isEmpty());
}
@Test
void reachablePublicAddressReportsContainerIpWhenRoutable() {
ContainerNetworkReachability reachability = mock(ContainerNetworkReachability.class);
when(reachability.isContainerIpRoutable("192.168.215.2")).thenReturn(true);
Ec2ContainerManager manager = managerWithReachability(reachability);
Instance instance = new Instance();
instance.setContainerBridgeIp("192.168.215.2");
assertEquals("192.168.215.2", manager.reachablePublicAddress(instance));
manager.exposeReachablePublicAddress(instance);
assertEquals("192.168.215.2", instance.getPublicIpAddress());
assertEquals("192.168.215.2", instance.getPublicDnsName());
}
@Test
void reachablePublicAddressFallsBackToLoopbackWhenContainerNetworkIsUnroutable() {
ContainerNetworkReachability reachability = mock(ContainerNetworkReachability.class);
when(reachability.isContainerIpRoutable("192.168.215.2")).thenReturn(false);
Ec2ContainerManager manager = managerWithReachability(reachability);
Instance instance = new Instance();
instance.setContainerBridgeIp("192.168.215.2");
assertEquals("127.0.0.1", manager.reachablePublicAddress(instance));
manager.exposeReachablePublicAddress(instance);
assertEquals("127.0.0.1", instance.getPublicIpAddress());
assertEquals("localhost", instance.getPublicDnsName());
}
@Test
void reachablePublicAddressIsNullBeforeAContainerExists() {
Ec2ContainerManager manager = managerWithReachability(mock(ContainerNetworkReachability.class));
assertEquals(null, manager.reachablePublicAddress(new Instance()));
assertEquals(null, manager.reachablePublicAddress(null));
}
private static Ec2ContainerManager managerWithReachability(ContainerNetworkReachability reachability) {
return new Ec2ContainerManager(
mock(ContainerBuilder.class),
mock(ContainerLifecycleManager.class),
mock(ContainerLogStreamer.class),
mock(ContainerDetector.class),
mock(DockerHostResolver.class),
mock(DockerClient.class),
mock(PortAllocator.class),
mock(EmulatorConfig.class, RETURNS_DEEP_STUBS),
mock(Ec2MetadataServer.class),
mock(Ec2PortForwardManager.class),
mock(RegionResolver.class),
reachability);
}
@Test
void userDataShellScriptsIgnoresCloudConfigWithoutShellscript() {
String userData = """
@@ -775,7 +953,8 @@ class Ec2ContainerManagerTest {
config,
metadataServer,
portForwardManager,
regionResolver);
regionResolver,
mock(ContainerNetworkReachability.class));
return new LaunchHarness(manager, lifecycleManager, dockerClient, metadataServer, logStreamer, builder,
portAllocator, portForwardManager, new CopyOnWriteArrayList<>());
}
@@ -6,6 +6,7 @@ import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
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.Address;
import io.github.hectorvent.floci.services.ec2.model.BlockDeviceMapping;
import io.github.hectorvent.floci.services.ec2.model.EbsBlockDevice;
import io.github.hectorvent.floci.services.ec2.model.GroupIdentifier;
@@ -2797,6 +2798,85 @@ class Ec2ServiceTest {
return routes.stream().map(TransitGatewayRoute::getDestinationCidrBlock).sorted().toList();
}
// ─── Elastic IP reachability ──────────────────────────────────────────────
/**
* An allocated EIP's 54.x.x.x address is invented and routes nowhere. Terraform surfaces it
* as aws_eip.x.public_ip and Terratest dials it, so association must re-point it at the
* address the instance can actually be reached on.
*/
@Test
void associateAddressRepointsTheEipAtAReachableAddress() {
Ec2ContainerManager containerManager = mock(Ec2ContainerManager.class);
when(containerManager.reachablePublicAddress(argThat(i -> i != null))).thenReturn("192.168.215.9");
Ec2Service service = eipService(containerManager);
String instanceId = launchOne(service);
Address allocated = service.allocateAddress("us-east-1");
String inventedIp = allocated.getPublicIp();
Address associated = service.associateAddress("us-east-1", allocated.getAllocationId(), instanceId);
assertEquals("192.168.215.9", associated.getPublicIp());
assertNotEquals(inventedIp, associated.getPublicIp());
assertEquals("192.168.215.9",
service.describeInstances("us-east-1", List.of(instanceId), Map.of())
.getFirst().getInstances().getFirst().getPublicIpAddress());
}
/**
* DescribeAddresses is where Terraform refreshes public_ip, and Docker hands out a new
* bridge IP after a stop/start, so the association has to be re-resolved on read.
*/
@Test
void describeAddressesReResolvesAnAssociatedEipAfterTheContainerIpChanges() {
Ec2ContainerManager containerManager = mock(Ec2ContainerManager.class);
when(containerManager.reachablePublicAddress(argThat(i -> i != null))).thenReturn("192.168.215.9");
Ec2Service service = eipService(containerManager);
String instanceId = launchOne(service);
Address allocated = service.allocateAddress("us-east-1");
service.associateAddress("us-east-1", allocated.getAllocationId(), instanceId);
when(containerManager.reachablePublicAddress(argThat(i -> i != null))).thenReturn("192.168.215.42");
Address refreshed = service.describeAddresses("us-east-1", List.of(allocated.getAllocationId()), Map.of())
.getFirst();
assertEquals("192.168.215.42", refreshed.getPublicIp());
}
/** With no instance behind it there is nothing reachable left, so the allocation is restored. */
@Test
void disassociateAddressRestoresTheAllocatedAddress() {
Ec2ContainerManager containerManager = mock(Ec2ContainerManager.class);
when(containerManager.reachablePublicAddress(argThat(i -> i != null))).thenReturn("192.168.215.9");
Ec2Service service = eipService(containerManager);
String instanceId = launchOne(service);
Address allocated = service.allocateAddress("us-east-1");
String inventedIp = allocated.getPublicIp();
Address associated = service.associateAddress("us-east-1", allocated.getAllocationId(), instanceId);
service.disassociateAddress("us-east-1", associated.getAssociationId());
Address after = service.describeAddresses("us-east-1", List.of(allocated.getAllocationId()), Map.of())
.getFirst();
assertEquals(inventedIp, after.getPublicIp());
assertNull(after.getInstanceId());
assertNull(after.getAssociationId());
}
private static Ec2Service eipService(Ec2ContainerManager containerManager) {
return new Ec2Service(mockConfig(true), containerManager,
mock(Ec2PortForwardManager.class),
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
new InMemoryStorageFactory());
}
private static String launchOne(Ec2Service service) {
return service.runInstances("us-east-1", "ami-1234567890abcdef0", "t3.micro",
1, 1, null, List.of(), null, null, List.of(), null, null)
.getInstances().getFirst().getInstanceId();
}
private static EmulatorConfig mockConfig(boolean ec2Mock) {
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);