mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 14:10:49 -05:00
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:
1 parent
c96dc98065
commit
41b5148824
11 files changed
+848
-12
No files matched your search
@@ -122,7 +122,7 @@ curl -s -H "x-aws-ec2-metadata-token: $TOKEN" \
|
||||
| `GET /latest/meta-data/ami-id` | Image ID |
|
||||
| `GET /latest/meta-data/instance-type` | Instance type |
|
||||
| `GET /latest/meta-data/local-ipv4` | Private IP |
|
||||
| `GET /latest/meta-data/public-ipv4` | Public IP (`127.0.0.1`) |
|
||||
| `GET /latest/meta-data/public-ipv4` | Public IP — the container IP where that is routable from the host, `127.0.0.1` otherwise |
|
||||
| `GET /latest/meta-data/public-hostname` | Public hostname |
|
||||
| `GET /latest/meta-data/local-hostname` | Private DNS name |
|
||||
| `GET /latest/meta-data/hostname` | Private DNS name |
|
||||
@@ -444,6 +444,13 @@ Route table ids follow the live API's own inconsistency: an id that does not exi
|
||||
| DisassociateAddress | Removes an Elastic IP address association. |
|
||||
| ReleaseAddress | Releases an Elastic IP address record. |
|
||||
|
||||
An allocated Elastic IP's `54.x.x.x` address is invented and routes nowhere, so associating
|
||||
it re-points it at the address the instance is actually reachable on — the same value
|
||||
DescribeInstances reports. This is a deliberate deviation from AWS, where an EIP's public IP
|
||||
is fixed from allocation: without it, `aws_eip.x.public_ip` hands every caller a dead address.
|
||||
The allocation ID, association ID and domain are unaffected, and disassociating restores the
|
||||
allocated address.
|
||||
|
||||
### Availability Zones & Regions
|
||||
|
||||
| Action | Description |
|
||||
@@ -604,6 +611,7 @@ State is reported settled rather than transitional, as elsewhere in this service
|
||||
| `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) |
|
||||
| `FLOCI_SERVICES_EC2_AWS_FAITHFUL_PRIVATE_IP` | `false` | Report the CFN/subnet-allocated private IP instead of the container bridge IP; routing and IMDS are unaffected |
|
||||
| `FLOCI_SERVICES_EC2_CONTAINER_IPS_ROUTABLE` | auto-detect | Whether an instance's container IP is reachable from the machines consuming Floci's API (Terraform, Terratest, your shell). When it is, DescribeInstances and DescribeAddresses report the container IP, so port 22 really is port 22; when it is not, they report `127.0.0.1` and reachability goes through the published high host ports. Detected by a throwaway TCP connect; set explicitly when Floci itself runs as a container |
|
||||
|
||||
## Requirements
|
||||
|
||||
|
||||
@@ -1857,6 +1857,24 @@ public interface EmulatorConfig {
|
||||
@WithDefault("false")
|
||||
boolean awsFaithfulPrivateIp();
|
||||
|
||||
/**
|
||||
* Whether an EC2 instance's Docker container IP is routable from the machines that
|
||||
* consume Floci's API responses (Terraform, Terratest, your shell). When true,
|
||||
* DescribeInstances / DescribeAddresses report the container IP, so the address they
|
||||
* hand out accepts connections on the service's real port (22 for SSH, and every other
|
||||
* port the guest listens on) with no port mapping involved. When false, Floci keeps
|
||||
* reporting 127.0.0.1 and reachability depends on the published high host ports.
|
||||
*
|
||||
* Unset (the default) means auto-detect: Floci opens a throwaway TCP connection towards
|
||||
* the container network and treats a refusal as proof of a route. Set it explicitly when
|
||||
* the probe cannot speak for your clients — most notably when Floci itself runs as a
|
||||
* container, where the probe measures container-to-container reachability rather than
|
||||
* host-to-container.
|
||||
*
|
||||
* Env var: FLOCI_SERVICES_EC2_CONTAINER_IPS_ROUTABLE
|
||||
*/
|
||||
Optional<Boolean> containerIpsRoutable();
|
||||
|
||||
/** Port on the Floci host for the IMDS HTTP server (169.254.169.254 equivalent). */
|
||||
@WithDefault("9169")
|
||||
int imdsPort();
|
||||
|
||||
+145
@@ -0,0 +1,145 @@
|
||||
package io.github.hectorvent.floci.services.ec2;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.net.ConnectException;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.Socket;
|
||||
import java.util.Locale;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Answers one question: is a container's own IP an address that Floci's API clients
|
||||
* (Terraform, Terratest, the user's shell) can actually open a connection to?
|
||||
*
|
||||
* <p>It matters because everything Floci reports as an instance's public address is
|
||||
* consumed by something outside Floci that will dial it on the service's real port —
|
||||
* Terratest builds {@code ssh.Host{Hostname: <public ip>}} and connects to 22. Reporting
|
||||
* {@code 127.0.0.1} is only correct when SSH is published there, and it is not: Docker
|
||||
* publishes it on a high host port. The container's own IP, where it is routable, is the
|
||||
* address on which port 22 really is port 22.
|
||||
*
|
||||
* <p>Container IPs are routable from the host on native Linux Docker and on OrbStack; they
|
||||
* are not on Docker Desktop for macOS/Windows, where the containers live behind a VM. So the
|
||||
* answer is detected, never assumed, and an explicit configuration value always wins.
|
||||
*
|
||||
* <p>Detection is a throwaway TCP connect towards the container network. A refused
|
||||
* connection is the strongest possible evidence of a route: the RST could only have come
|
||||
* from the container's network stack. A timeout or an unreachable-host error means there is
|
||||
* no route. Nothing needs to be listening for this to work, so it can run the moment a
|
||||
* container starts.
|
||||
*
|
||||
* <p>The one case the probe cannot settle is Floci running inside a container itself: then
|
||||
* the probe measures container-to-container reachability, while the clients that will use
|
||||
* the answer are on the host. There, the probe is corroborated against the Docker daemon's
|
||||
* reported backend, and a Docker Desktop backend vetoes it.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class ContainerNetworkReachability {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(ContainerNetworkReachability.class);
|
||||
|
||||
/** SSH: present on every EC2 guest image, so a refusal here is still a routing answer. */
|
||||
static final int PROBE_PORT = 22;
|
||||
|
||||
static int probeTimeoutMillis = 1500;
|
||||
|
||||
private final EmulatorConfig config;
|
||||
private final ContainerDetector containerDetector;
|
||||
private final DockerClient dockerClient;
|
||||
|
||||
private volatile Boolean cached;
|
||||
|
||||
@Inject
|
||||
public ContainerNetworkReachability(EmulatorConfig config,
|
||||
ContainerDetector containerDetector,
|
||||
DockerClient dockerClient) {
|
||||
this.config = config;
|
||||
this.containerDetector = containerDetector;
|
||||
this.dockerClient = dockerClient;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param containerIp a live container's bridge IP, used as the probe target
|
||||
* @return true when addresses on the container network can be handed to API clients
|
||||
*/
|
||||
public boolean isContainerIpRoutable(String containerIp) {
|
||||
Optional<Boolean> override = config.services().ec2().containerIpsRoutable();
|
||||
if (override.isPresent()) {
|
||||
return override.get();
|
||||
}
|
||||
if (containerIp == null || containerIp.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
Boolean known = cached;
|
||||
if (known != null) {
|
||||
return known;
|
||||
}
|
||||
synchronized (this) {
|
||||
if (cached == null) {
|
||||
cached = detect(containerIp);
|
||||
LOG.infov("Container network routability from Floci''s API clients: {0} (probed {1}:{2})",
|
||||
cached, containerIp, String.valueOf(PROBE_PORT));
|
||||
}
|
||||
return cached;
|
||||
}
|
||||
}
|
||||
|
||||
/** Resets the memoised answer. Test seam. */
|
||||
void forget() {
|
||||
cached = null;
|
||||
}
|
||||
|
||||
private boolean detect(String containerIp) {
|
||||
if (!probe(containerIp)) {
|
||||
return false;
|
||||
}
|
||||
if (!containerDetector.isRunningInContainer()) {
|
||||
// Floci is a host process, so it shares a vantage point with its API clients:
|
||||
// what Floci can reach, Terraform and Terratest can reach.
|
||||
return true;
|
||||
}
|
||||
// Floci is containerised. The probe just proved container-to-container reachability,
|
||||
// which is true even on Docker Desktop, where the host still cannot route there.
|
||||
String backend = dockerBackend();
|
||||
if (backend.contains("docker desktop")) {
|
||||
LOG.infov("Docker backend is {0}: container IPs are not routable from the host, so "
|
||||
+ "EC2 public addresses stay on 127.0.0.1 with published ports. Set "
|
||||
+ "FLOCI_SERVICES_EC2_CONTAINER_IPS_ROUTABLE=true to override.",
|
||||
backend);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean probe(String containerIp) {
|
||||
try (Socket socket = new Socket()) {
|
||||
socket.connect(new InetSocketAddress(containerIp, PROBE_PORT), probeTimeoutMillis);
|
||||
return true;
|
||||
} catch (ConnectException e) {
|
||||
// Refused: a RST came back, which means the packet reached the container network.
|
||||
// NoRouteToHostException is a sibling of ConnectException, not a subclass, so it
|
||||
// is deliberately not caught here.
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("Container network probe to {0}:{1} failed ({2}): treating container IPs as unroutable",
|
||||
containerIp, String.valueOf(PROBE_PORT), e.toString());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private String dockerBackend() {
|
||||
try {
|
||||
String os = dockerClient.infoCmd().exec().getOperatingSystem();
|
||||
return os == null ? "" : os.toLowerCase(Locale.ROOT);
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("Could not read the Docker daemon's operating system: {0}", e.getMessage());
|
||||
return "";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,7 @@ import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
@@ -41,9 +42,11 @@ import java.util.Set;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Semaphore;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.zip.GZIPInputStream;
|
||||
|
||||
/**
|
||||
* Manages Docker container lifecycle for EC2 instances.
|
||||
@@ -61,6 +64,31 @@ public class Ec2ContainerManager {
|
||||
private static final List<String> ALLOWED_SSHD_PATHS = List.of("/usr/sbin/sshd", "/usr/local/sbin/sshd", "/sbin/sshd");
|
||||
/** Exit code the sshd install probe uses for "sshd is present but scp is not". See startSshd. */
|
||||
static final int SSH_CLIENT_MISSING_EXIT_CODE = 2;
|
||||
/** Base64 alphabet plus the line breaks base64-encoded UserData is commonly wrapped at. */
|
||||
private static final Pattern BASE64_BODY = Pattern.compile("[A-Za-z0-9+/\\s]+={0,2}");
|
||||
private static final int MAX_USER_DATA_DECODE_ROUNDS = 3;
|
||||
/** Mirrors AwsJsonCborController.decodeBody's cap: no AWS service should need more than
|
||||
* 10 MB decompressed, and it bounds how much a caller-controlled gzip stream can expand
|
||||
* to in the shared emulator JVM. */
|
||||
private static final int MAX_DECOMPRESSED_USER_DATA_BYTES = 10 * 1024 * 1024;
|
||||
/** Caps concurrent UserData gzip decompressions across ALL instance launches, not just one.
|
||||
* Launches run independently on {@link #executor}, an unbounded cached thread pool, so the
|
||||
* per-payload cap above only bounds a single launch's allocation: without this, N concurrent
|
||||
* RunInstances/CreateLaunchConfiguration calls, each smuggling a near-cap gzip payload, could
|
||||
* together decompress N * 10 MB at once in the shared emulator JVM with no aggregate ceiling.
|
||||
* 4 permits budgets ~40 MB 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
|
||||
* (e.g. an Auto Scaling group launching a handful of instances together) is not serialized
|
||||
* down to one decompression at a time, while a launch storm still cannot grow memory usage
|
||||
* without bound. */
|
||||
private static final int MAX_CONCURRENT_USER_DATA_DECOMPRESSIONS = 4;
|
||||
/** Gates entry to {@link #gunzip}; see {@link #MAX_CONCURRENT_USER_DATA_DECOMPRESSIONS}. */
|
||||
private static final Semaphore USER_DATA_DECOMPRESSION_BUDGET =
|
||||
new Semaphore(MAX_CONCURRENT_USER_DATA_DECOMPRESSIONS);
|
||||
/** Test seam: when non-null, invoked by {@link #gunzip} right after it acquires a
|
||||
* decompression-budget permit and before it starts decompressing, so tests can observe and
|
||||
* serialize concurrent decompressions deterministically. Always null in production. */
|
||||
static volatile Runnable userDataDecompressionTestHook;
|
||||
|
||||
static int containerBridgeIpAttempts = 30;
|
||||
static long containerBridgeIpPollMillis = 500;
|
||||
@@ -76,6 +104,7 @@ public class Ec2ContainerManager {
|
||||
private final Ec2MetadataServer metadataServer;
|
||||
private final Ec2PortForwardManager portForwardManager;
|
||||
private final RegionResolver regionResolver;
|
||||
private final ContainerNetworkReachability containerNetworkReachability;
|
||||
|
||||
private final ExecutorService executor = Executors.newCachedThreadPool(r -> {
|
||||
Thread t = new Thread(r, "ec2-container-launcher");
|
||||
@@ -94,7 +123,8 @@ public class Ec2ContainerManager {
|
||||
EmulatorConfig config,
|
||||
Ec2MetadataServer metadataServer,
|
||||
Ec2PortForwardManager portForwardManager,
|
||||
RegionResolver regionResolver) {
|
||||
RegionResolver regionResolver,
|
||||
ContainerNetworkReachability containerNetworkReachability) {
|
||||
this.containerBuilder = containerBuilder;
|
||||
this.lifecycleManager = lifecycleManager;
|
||||
this.logStreamer = logStreamer;
|
||||
@@ -106,6 +136,7 @@ public class Ec2ContainerManager {
|
||||
this.regionResolver = regionResolver;
|
||||
this.metadataServer = metadataServer;
|
||||
this.portForwardManager = portForwardManager;
|
||||
this.containerNetworkReachability = containerNetworkReachability;
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
@@ -204,11 +235,9 @@ public class Ec2ContainerManager {
|
||||
|
||||
// Set public-facing addresses only for instances whose subnet
|
||||
// opts in via MapPublicIpOnLaunch (#1984). Private-subnet
|
||||
// instances have no public IP/DNS, matching real EC2. The value
|
||||
// stays the host-reachable 127.0.0.1/localhost for public ones.
|
||||
// instances have no public IP/DNS, matching real EC2.
|
||||
if (instance.isAssociatePublicIp()) {
|
||||
instance.setPublicIpAddress("127.0.0.1");
|
||||
instance.setPublicDnsName("localhost");
|
||||
exposeReachablePublicAddress(instance);
|
||||
}
|
||||
|
||||
LOG.infov("EC2 instance {0} running in container {1} (SSH host port {2})",
|
||||
@@ -528,6 +557,11 @@ public class Ec2ContainerManager {
|
||||
if (containerIp != null && !containerIp.isBlank()) {
|
||||
instance.setContainerBridgeIp(containerIp);
|
||||
exposeReachablePrivateAddress(instance, containerIp, config.services().ec2().awsFaithfulPrivateIp());
|
||||
// Docker hands out a new bridge IP on restart, so the previously reported
|
||||
// public address can now point at another container entirely.
|
||||
if (instance.isAssociatePublicIp() || instance.getPublicIpAddress() != null) {
|
||||
exposeReachablePublicAddress(instance);
|
||||
}
|
||||
metadataServer.registerContainer(containerIp, instanceId, instance);
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
@@ -568,10 +602,50 @@ public class Ec2ContainerManager {
|
||||
}
|
||||
instance.setContainerBridgeIp(containerIp);
|
||||
exposeReachablePrivateAddress(instance, containerIp, config.services().ec2().awsFaithfulPrivateIp());
|
||||
if (instance.isAssociatePublicIp() || instance.getPublicIpAddress() != null) {
|
||||
exposeReachablePublicAddress(instance);
|
||||
}
|
||||
metadataServer.registerContainer(containerIp, instance.getInstanceId(), instance);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* The address Floci is willing to hand out as this instance's public address — chosen so
|
||||
* that whatever dials it reaches the guest on the service's own port.
|
||||
*
|
||||
* <p>Where container IPs are routable that is the container's IP: port 22 is really port
|
||||
* 22 there, and so is every other port the guest listens on, with no published mapping to
|
||||
* translate. Where they are not, it falls back to {@code 127.0.0.1}, which is where the
|
||||
* published high host ports live — reachable, though not on the ports AWS clients assume.
|
||||
*
|
||||
* @return the address, or null if the instance has no container IP yet
|
||||
*/
|
||||
public String reachablePublicAddress(Instance instance) {
|
||||
if (instance == null) {
|
||||
return null;
|
||||
}
|
||||
String containerIp = instance.getContainerBridgeIp();
|
||||
if (containerIp == null || containerIp.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
return containerNetworkReachability.isContainerIpRoutable(containerIp) ? containerIp : "127.0.0.1";
|
||||
}
|
||||
|
||||
/**
|
||||
* Publishes {@link #reachablePublicAddress} as the instance's public IP and DNS name.
|
||||
* The DNS name is set to the same literal rather than an AWS-shaped
|
||||
* {@code ec2-….compute-1.amazonaws.com} hostname, because that hostname resolves nowhere
|
||||
* and callers that prefer PublicDnsName over PublicIpAddress would be handed a dead name.
|
||||
*/
|
||||
void exposeReachablePublicAddress(Instance instance) {
|
||||
String publicAddress = reachablePublicAddress(instance);
|
||||
if (publicAddress == null) {
|
||||
return;
|
||||
}
|
||||
instance.setPublicIpAddress(publicAddress);
|
||||
instance.setPublicDnsName("127.0.0.1".equals(publicAddress) ? "localhost" : publicAddress);
|
||||
}
|
||||
|
||||
static void exposeReachablePrivateAddress(Instance instance, String privateIp) {
|
||||
exposeReachablePrivateAddress(instance, privateIp, false);
|
||||
}
|
||||
@@ -741,7 +815,9 @@ public class Ec2ContainerManager {
|
||||
|
||||
List<String> shellScripts = userDataShellScripts(userData);
|
||||
if (shellScripts.isEmpty()) {
|
||||
LOG.infov("UserData for EC2 instance {0} did not contain executable shellscript parts", instanceId);
|
||||
LOG.warnv("UserData for EC2 instance {0} did not contain executable shellscript parts, "
|
||||
+ "so nothing it was meant to install has run. Floci executes cloud-init "
|
||||
+ "text/x-shellscript parts and bare '#!' scripts only.", instanceId);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -814,11 +890,12 @@ public class Ec2ContainerManager {
|
||||
}
|
||||
|
||||
static List<String> userDataShellScripts(String userData) {
|
||||
if (userData == null || userData.isBlank()) {
|
||||
String decoded = decodeUserDataPayload(userData);
|
||||
if (decoded == null || decoded.isBlank()) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
String normalized = userData.replace("\r\n", "\n").replace('\r', '\n');
|
||||
String normalized = decoded.replace("\r\n", "\n").replace('\r', '\n');
|
||||
String trimmed = normalized.stripLeading();
|
||||
if (trimmed.startsWith("#!")) {
|
||||
return List.of(normalized);
|
||||
@@ -854,6 +931,120 @@ public class Ec2ContainerManager {
|
||||
return List.copyOf(scripts);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unwraps whatever encoding the UserData arrived in until a cloud-init document is
|
||||
* visible: gzip, base64, and base64-of-gzip, in any nesting the callers produce.
|
||||
*
|
||||
* <p>RunInstances decodes the wire-level base64 (and its gzip) before Floci ever stores
|
||||
* the value, but not every path does — CreateLaunchConfiguration stores what the client
|
||||
* sent, still base64 — and {@code data.cloudinit_config { gzip = true }}, the documented
|
||||
* way to pass a multipart cloud-init, produces a payload that survives one decode still
|
||||
* compressed. Left unwrapped it matches neither the {@code #!} nor the MIME test below and
|
||||
* the whole document is silently dropped, so the instance boots without anything its
|
||||
* user-data was supposed to install.
|
||||
*
|
||||
* @return the decoded document, or the input unchanged when it is not encoded
|
||||
*/
|
||||
static String decodeUserDataPayload(String userData) {
|
||||
if (userData == null || userData.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
byte[] payload = userData.getBytes(StandardCharsets.UTF_8);
|
||||
// Bounded so a crafted payload cannot make this loop forever; two rounds already
|
||||
// covers base64(gzip(document)), the deepest form in practice.
|
||||
for (int round = 0; round < MAX_USER_DATA_DECODE_ROUNDS; round++) {
|
||||
byte[] next = gunzip(payload);
|
||||
if (next == null) {
|
||||
next = base64Decode(payload);
|
||||
}
|
||||
if (next == null) {
|
||||
break;
|
||||
}
|
||||
payload = next;
|
||||
}
|
||||
return new String(payload, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
/** @return the decompressed bytes, or null when the input does not start with the gzip magic */
|
||||
private static byte[] gunzip(byte[] payload) {
|
||||
if (payload.length < 2 || (payload[0] & 0xff) != 0x1f || (payload[1] & 0xff) != 0x8b) {
|
||||
return null;
|
||||
}
|
||||
// Aggregate bound (see MAX_CONCURRENT_USER_DATA_DECOMPRESSIONS): this call runs on
|
||||
// whichever launch worker submitted it to the unbounded #executor, independently of every
|
||||
// other concurrent launch, so the per-payload cap below is not enough on its own - it only
|
||||
// stops one caller from expanding past 10 MB, not many callers doing so at once. Blocking
|
||||
// here (rather than failing the launch) mirrors ContainerLauncher's POPULATE_SEMAPHORE: a
|
||||
// burst of legitimate concurrent launches queues briefly instead of being rejected.
|
||||
try {
|
||||
USER_DATA_DECOMPRESSION_BUDGET.acquire();
|
||||
} catch (InterruptedException ie) {
|
||||
Thread.currentThread().interrupt();
|
||||
LOG.warnv("Interrupted while waiting for UserData decompression budget; discarding payload");
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
Runnable hook = userDataDecompressionTestHook;
|
||||
if (hook != null) {
|
||||
hook.run();
|
||||
}
|
||||
// Bounded the same way AwsJsonCborController.decodeBody is: a crafted payload can
|
||||
// otherwise expand to gigabytes of image-heap while the launch worker holds it, since
|
||||
// UserData is caller-controlled and this runs in the shared emulator JVM.
|
||||
byte[] buffer = new byte[64 * 1024];
|
||||
int totalRead = 0;
|
||||
ByteArrayOutputStream decompressed = new ByteArrayOutputStream();
|
||||
try (GZIPInputStream gzip = new GZIPInputStream(new ByteArrayInputStream(payload))) {
|
||||
int read;
|
||||
while ((read = gzip.read(buffer)) != -1) {
|
||||
totalRead += read;
|
||||
if (totalRead > MAX_DECOMPRESSED_USER_DATA_BYTES) {
|
||||
LOG.warnv("UserData decompressed past {0} bytes; discarding as oversized",
|
||||
MAX_DECOMPRESSED_USER_DATA_BYTES);
|
||||
return null;
|
||||
}
|
||||
decompressed.write(buffer, 0, read);
|
||||
}
|
||||
return decompressed.toByteArray();
|
||||
} catch (IOException e) {
|
||||
LOG.warnv("UserData starts with the gzip magic bytes but could not be decompressed: {0}", e.getMessage());
|
||||
return null;
|
||||
}
|
||||
} finally {
|
||||
USER_DATA_DECOMPRESSION_BUDGET.release();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the decoded bytes when the input is base64 that unwraps to something recognisable
|
||||
* (gzip, a shebang, or MIME headers), null otherwise. The recognisability test is
|
||||
* what keeps a plain shell script — which can be accidentally valid base64 — from
|
||||
* being mangled into binary noise.
|
||||
*/
|
||||
private static byte[] base64Decode(byte[] payload) {
|
||||
String text = new String(payload, StandardCharsets.UTF_8).strip();
|
||||
if (text.isEmpty() || !BASE64_BODY.matcher(text).matches()) {
|
||||
return null;
|
||||
}
|
||||
byte[] decoded;
|
||||
try {
|
||||
decoded = Base64.getMimeDecoder().decode(text);
|
||||
} catch (IllegalArgumentException e) {
|
||||
return null;
|
||||
}
|
||||
if (decoded.length < 2) {
|
||||
return null;
|
||||
}
|
||||
if ((decoded[0] & 0xff) == 0x1f && (decoded[1] & 0xff) == 0x8b) {
|
||||
return decoded;
|
||||
}
|
||||
String head = new String(decoded, 0, Math.min(decoded.length, 512), StandardCharsets.UTF_8).stripLeading();
|
||||
return head.startsWith("#!") || head.toLowerCase(Locale.ROOT).startsWith("content-type:")
|
||||
|| head.toLowerCase(Locale.ROOT).startsWith("mime-version:") || head.startsWith("#cloud-config")
|
||||
? decoded
|
||||
: null;
|
||||
}
|
||||
|
||||
private static boolean hasShellscriptContentType(String headers) {
|
||||
for (String line : headers.split("\n")) {
|
||||
String lower = line.toLowerCase(Locale.ROOT).strip();
|
||||
|
||||
@@ -4882,10 +4882,57 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
|
||||
|
||||
addr.setInstanceId(instanceId);
|
||||
addr.setAssociationId("eipassoc-" + randomHex(17));
|
||||
pointAddressAtInstance(addr, region, instanceId);
|
||||
addresses.put(key(region, allocationId), addr);
|
||||
return addr;
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-points an associated EIP at an address that actually answers.
|
||||
*
|
||||
* <p>{@link #allocateAddress} can only invent a plausible {@code 54.x.x.x}, because at
|
||||
* allocation time there is no instance to be reachable at. Real AWS then keeps that address
|
||||
* fixed and makes the network route it; Floci cannot, so an EIP left at its allocated value
|
||||
* routes nowhere — and it is precisely the value Terraform surfaces as
|
||||
* {@code aws_eip.x.public_ip}, which is what test suites SSH into.
|
||||
*
|
||||
* <p>Rewriting on association is the more defensible of the two options. The alternative,
|
||||
* keeping the fictional address and aliasing it to the real one, would need Floci to own
|
||||
* routing or DNS on the client's machine, which it does not; and every client that reads
|
||||
* the address out of the API and dials it directly — Terratest does exactly this — would
|
||||
* still be handed something dead. Association is also the first moment the answer is
|
||||
* knowable. The cost is a deliberate deviation from AWS: an EIP's public IP changes when it
|
||||
* is associated. That is invisible to Terraform, for which {@code public_ip} is computed
|
||||
* and refreshed from this same API, and the allocation stays coherent otherwise — the
|
||||
* AllocationId, AssociationId and domain are untouched, and disassociation restores the
|
||||
* allocated address.
|
||||
*/
|
||||
private void pointAddressAtInstance(Address addr, String region, String instanceId) {
|
||||
if (instanceId == null || instanceId.isBlank()) {
|
||||
return;
|
||||
}
|
||||
Instance inst = instances.get(key(region, instanceId)).orElse(null);
|
||||
if (inst == null) {
|
||||
return;
|
||||
}
|
||||
if (addr.getAllocatedPublicIp() == null) {
|
||||
addr.setAllocatedPublicIp(addr.getPublicIp());
|
||||
}
|
||||
String reachable = containerManager.reachablePublicAddress(inst);
|
||||
if (reachable != null) {
|
||||
addr.setPublicIp(reachable);
|
||||
// An EIP association gives the instance a public address even in a subnet that does
|
||||
// not map one on launch, exactly as on AWS.
|
||||
inst.setPublicIpAddress(reachable);
|
||||
inst.setPublicDnsName("127.0.0.1".equals(reachable) ? "localhost" : reachable);
|
||||
instances.put(key(region, instanceId), inst);
|
||||
}
|
||||
addr.setPrivateIpAddress(inst.getPrivateIpAddress());
|
||||
if (inst.getNetworkInterfaces() != null && !inst.getNetworkInterfaces().isEmpty()) {
|
||||
addr.setNetworkInterfaceId(inst.getNetworkInterfaces().get(0).getNetworkInterfaceId());
|
||||
}
|
||||
}
|
||||
|
||||
private Address getRequiredAddress(String region, String allocationId) {
|
||||
Address addr = addresses.get(key(region, allocationId)).orElse(null);
|
||||
if (addr == null)
|
||||
@@ -4900,6 +4947,13 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
|
||||
if (addr.getRegion().equals(region) && associationId.equals(addr.getAssociationId())) {
|
||||
addr.setInstanceId(null);
|
||||
addr.setAssociationId(null);
|
||||
addr.setNetworkInterfaceId(null);
|
||||
addr.setPrivateIpAddress(null);
|
||||
// Hand the allocation back its allocated address: with no instance behind it,
|
||||
// there is nothing reachable left for it to stand for.
|
||||
if (addr.getAllocatedPublicIp() != null) {
|
||||
addr.setPublicIp(addr.getAllocatedPublicIp());
|
||||
}
|
||||
addresses.put(key(region, addr.getAllocationId()), addr);
|
||||
return;
|
||||
}
|
||||
@@ -4916,10 +4970,24 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
|
||||
|
||||
public List<Address> describeAddresses(String region, List<String> allocationIds, Map<String, List<String>> filters) {
|
||||
ensureDefaultResources(region);
|
||||
return addresses.scan(k -> true).stream()
|
||||
List<Address> matched = addresses.scan(k -> true).stream()
|
||||
.filter(a -> a.getRegion().equals(region))
|
||||
.filter(a -> allocationIds.isEmpty() || allocationIds.contains(a.getAllocationId()))
|
||||
.collect(Collectors.toList());
|
||||
// An EIP can be associated before its instance has a container, and Docker hands out a
|
||||
// different bridge IP after a stop/start, either of which would leave the association
|
||||
// reporting an address that no longer answers. Re-resolve on read: this is the call
|
||||
// Terraform refreshes public_ip from, so it is the last chance to be right.
|
||||
for (Address addr : matched) {
|
||||
if (addr.getInstanceId() != null) {
|
||||
String before = addr.getPublicIp();
|
||||
pointAddressAtInstance(addr, region, addr.getInstanceId());
|
||||
if (!Objects.equals(before, addr.getPublicIp())) {
|
||||
addresses.put(key(region, addr.getAllocationId()), addr);
|
||||
}
|
||||
}
|
||||
}
|
||||
return matched;
|
||||
}
|
||||
|
||||
// ─── Availability Zones & Regions ─────────────────────────────────────────
|
||||
|
||||
@@ -18,6 +18,11 @@ public class Address {
|
||||
private String networkInterfaceId;
|
||||
private String privateIpAddress;
|
||||
private String region;
|
||||
/**
|
||||
* The address AllocateAddress invented for this allocation, kept so disassociation can
|
||||
* restore it after association re-points the EIP at a reachable address.
|
||||
*/
|
||||
private String allocatedPublicIp;
|
||||
private List<Tag> tags = new ArrayList<>();
|
||||
|
||||
public Address() {}
|
||||
@@ -43,6 +48,9 @@ public class Address {
|
||||
public String getPrivateIpAddress() { return privateIpAddress; }
|
||||
public void setPrivateIpAddress(String privateIpAddress) { this.privateIpAddress = privateIpAddress; }
|
||||
|
||||
public String getAllocatedPublicIp() { return allocatedPublicIp; }
|
||||
public void setAllocatedPublicIp(String allocatedPublicIp) { this.allocatedPublicIp = allocatedPublicIp; }
|
||||
|
||||
public String getRegion() { return region; }
|
||||
public void setRegion(String region) { this.region = region; }
|
||||
|
||||
|
||||
@@ -411,6 +411,10 @@ floci:
|
||||
socat-image: alpine/socat
|
||||
mock: false
|
||||
aws-faithful-private-ip: false
|
||||
# container-ips-routable: true # Auto-detected by default (a throwaway TCP probe toward
|
||||
# the container network). Set explicitly when the probe
|
||||
# can't speak for your clients, e.g. Floci itself running
|
||||
# containerized. FLOCI_SERVICES_EC2_CONTAINER_IPS_ROUTABLE
|
||||
ecs:
|
||||
enabled: true
|
||||
mock: false
|
||||
|
||||
+134
@@ -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(" "));
|
||||
}
|
||||
}
|
||||
+181
-2
@@ -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);
|
||||
|
||||
@@ -240,6 +240,7 @@ floci:
|
||||
socat-image: alpine/socat
|
||||
mock: true
|
||||
aws-faithful-private-ip: false
|
||||
# container-ips-routable: true # see src/main/resources/application.yml
|
||||
ecs:
|
||||
enabled: true
|
||||
mock: true
|
||||
|
||||
Reference in new issue
Block a user