mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(ec2): require IMDSv2 tokens when HttpTokens is required (#5966)
* fix(ec2): probe IMDS proxy readiness with an IMDSv2 token The proxy start script checked readiness with a tokenless read of the instance ID. Once IMDS enforces HttpTokens=required, that read gets 401 and the proxy reports a failed start after twelve attempts. The probe now fetches a 60-second token and reads with it; a refused or empty token fails the attempt rather than falling back to a tokenless read. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): refuse tokenless metadata reads when HttpTokens is required IMDS answered every request without a token through IMDSv1, whatever the instance's HttpTokens said. On AWS, when token usage is required, requests without a valid token get 401 Unauthorized. Floci now does the same for every metadata endpoint, before it looks up the data, using the options the instance was launched with or last modified to. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): clear application library paths in IMDS helper shells docker exec gives the proxy's install and start shells the image's environment. An application image that sets LD_LIBRARY_PATH, PYTHONPATH or PYTHONHOME can then make the package manager, socat and curl load its libraries or Python instead of the system's. Both shells now unset those three first; only the helper shell changes, so the container's configuration and the application's processes keep them. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): refuse metadata option changes on EKS cluster nodes IMDS serves a cluster node from the instance its EKS cluster registered, while EC2 hands out a copy of it. ModifyInstanceMetadataOptions changed and stored that copy, so DescribeInstances reported HttpTokens=required while the node's IMDS kept answering tokenless reads, and the stored copy no longer counted as a cluster node. The action now answers OperationNotPermitted for cluster nodes, as their stop, start, reboot and terminate actions do. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): publish metadata option changes to the IMDS event loop IMDS now reads an instance's metadata options on its Vert.x event loop, while ModifyInstanceMetadataOptions replaces them from a request thread. Without a happens-before edge the event loop could keep serving the old options, or see the new object before its fields. The field is now volatile, as the instance's state already is. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): keep the IMDS readiness probe off HTTP proxies The probe's curl calls honored an image's http_proxy or ALL_PROXY, so a proxy configured for the application received the link-local requests, every attempt failed and the start reported a failure although socat was running. Both calls now pass --noproxy '*'. The helper-shell test support moves to a shared HelperShellFixture, and a new test runs the real token probe inside the generated start script, whose set -eu loop must retry after a refused token. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): clear application library paths in the sshd install probe The sshd install probe runs dnf, yum or apt-get through docker exec with the image's environment, the failure the IMDS helper shells now avoid: with an application's PYTHONHOME or LD_LIBRARY_PATH, dnf could not start, so sshd was never installed. The probe now unsets the same three variables first, through the IMDS proxy's shared constant. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): keep refusing cluster nodes once EC2 has stored a copy The cluster-node check counted an instance as a node only while EC2's own store had no record of it, but ModifyInstanceAttribute, monitoring and other actions store EC2's copy of a node. After one of them, ModifyInstanceMetadataOptions was accepted without reaching the node's IMDS, and TerminateInstances and StopInstances were no longer refused. A node is now recognized by its cluster's provider alone. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): keep the pod identity relay probe off HTTP proxies The EKS pod identity relay's readiness probe shares the IMDS proxy's start script and environment, but its curl still honored the image's http_proxy: a proxy that answered passed the probe whether or not socat relayed, and an unreachable one failed the start. It now passes --noproxy '*' like the IMDS probe, from a podIdentityProbeCommand the test runs. The shared unset's Javadoc now names the shells that run it. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): refuse tokenless reads of every path when tokens are required The HttpTokens=required check ran inside the handlers of the paths IMDS serves, so a tokenless read of any other path, such as the /latest/meta-data/ listing that IMDSv1 detection probes, answered 404 where AWS answers 401. The check now runs ahead of every GET route; with a token, or on an instance that allows IMDSv1, such a path is still 404. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): keep IMDS answers for methods it does not serve The required-token check was registered as a GET route for every path, and Vert.x answers 405 to any other method on a path some route matches, so POST /latest/meta-data/ began to answer 405 instead of 404, and a tokenless HEAD on a required-token instance got 405 instead of 401. The check is now a route for every method that acts on GET and HEAD only. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * test(ec2): check that the pod identity probe reaches its relay The probe treats any answer but 000 as ready, so the test passed even when curl was missing and nothing reached the relay. It now counts the relay's requests, and both stand-in servers start inside its try. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * docs(ec2): say that IMDS refuses a tokenless HEAD but serves none The required-token check's Javadoc called HEAD a read, but no IMDS route serves HEAD, so one with a token still gets the router's 405. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * docs(ec2): say what IMDS answers a HEAD that has a token No route serves HEAD, so the router answers 405 on a path a GET route serves and 404 elsewhere. A test pins both. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * test(ec2): check IMDS refuses tokenless reads on Fleet and Auto Scaling launches Since #5964, Auto Scaling launches carry a launch template's MetadataOptions and CreateFleet forwards them. The test of template options on Fleet and Auto Scaling launches now also checks that IMDS refuses the launched instance a tokenless read and serves it with a token. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * docs(ec2): say where HttpTokens comes from and what IMDS refuses The IMDS notes said HttpTokens could be set "at launch". They now name its sources: RunInstances, directly or through a launch template, EC2 Fleet and Auto Scaling launches, and ModifyInstanceMetadataOptions. They say that a tokenless GET or HEAD is refused on every path, and that EKS cluster nodes refuse the change, in the notes, the EKS lifecycle-protection list and the action table. They also say that the readiness probe bypasses the image's HTTP proxy, that the helper shells keep an application's library search path and Python installation from the system tools rather than promising more, and that the sshd install shell clears them too. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> --------- Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
This commit is contained in:
1 parent
2f6f3a8f86
commit
7504d71e76
14 files changed
+755
-16
No files matched your search
@@ -38,6 +38,7 @@ import io.github.hectorvent.floci.services.ec2.model.InstanceNetworkInterface;
|
||||
import io.github.hectorvent.floci.services.ec2.net.VpcNetworkManager;
|
||||
import io.github.hectorvent.floci.services.ec2.portforward.Ec2PortForwardManager;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
@@ -45,6 +46,8 @@ import org.mockito.ArgumentCaptor;
|
||||
import java.io.Closeable;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
@@ -961,6 +964,26 @@ class Ec2ContainerManagerTest {
|
||||
"dnf must be probed before yum");
|
||||
}
|
||||
|
||||
@Test
|
||||
void sshdInstallProbeClearsApplicationPathsBeforeThePackageManagerRuns(@TempDir Path directory)
|
||||
throws Exception {
|
||||
// dnf and yum are Python programs, so an image's PYTHONHOME or LD_LIBRARY_PATH breaks the
|
||||
// install. The fake dnf "installs" sshd and scp only when it runs with those cleared.
|
||||
Path bin = Files.createDirectory(directory.resolve("bin"));
|
||||
Path record = directory.resolve("tools");
|
||||
HelperShellFixture.writeTool(bin, "dnf", HelperShellFixture.checkedToolEnvironment()
|
||||
+ "for tool in sshd scp; do\n"
|
||||
+ " printf '#!/bin/sh\\nexit 0\\n' > \"$TEST_BIN/$tool\"\n"
|
||||
+ " /bin/chmod +x \"$TEST_BIN/$tool\"\n"
|
||||
+ "done\n");
|
||||
|
||||
assertEquals(0, HelperShellFixture.run(Ec2ContainerManager.sshdInstallProbeCommand(), directory,
|
||||
HelperShellFixture.applicationEnvironment(Map.of("PATH", bin.toString(),
|
||||
"TEST_RECORD", record.toString(), "TEST_BIN", bin.toString()))),
|
||||
HelperShellFixture.output(directory));
|
||||
assertEquals("dnf\n", Files.readString(record));
|
||||
}
|
||||
|
||||
@Test
|
||||
void metadataProxyInstallCommandHandlesYumForAmazonLinux2() {
|
||||
// The IMDS proxy dependency install had the same gap, and unlike the sshd probe it
|
||||
@@ -1574,7 +1597,8 @@ class Ec2ContainerManagerTest {
|
||||
}
|
||||
|
||||
private static final String[] SSHD_INSTALL_PROBE_CMD = {"sh", "-c",
|
||||
"if ! command -v sshd >/dev/null 2>&1 || ! command -v scp >/dev/null 2>&1; then"
|
||||
"unset LD_LIBRARY_PATH PYTHONPATH PYTHONHOME;"
|
||||
+ "if ! command -v sshd >/dev/null 2>&1 || ! command -v scp >/dev/null 2>&1; then"
|
||||
+ " if command -v dnf >/dev/null 2>&1; then dnf install -y openssh-server openssh-clients >/dev/null 2>&1;"
|
||||
+ " elif command -v yum >/dev/null 2>&1; then yum install -y openssh-server openssh-clients >/dev/null 2>&1;"
|
||||
+ " elif command -v apt-get >/dev/null 2>&1; then DEBIAN_FRONTEND=noninteractive apt-get install -y openssh-server openssh-client >/dev/null 2>&1;"
|
||||
|
||||
+19
-2
@@ -1,5 +1,6 @@
|
||||
package io.github.hectorvent.floci.services.ec2;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.RequestScopes;
|
||||
import io.github.hectorvent.floci.services.autoscaling.AutoScalingReconciler;
|
||||
import io.github.hectorvent.floci.services.autoscaling.AutoScalingService;
|
||||
@@ -15,8 +16,14 @@ import java.util.UUID;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
/** A launch template's MetadataOptions reach instances launched by EC2 Fleet and Auto Scaling. */
|
||||
/**
|
||||
* A launch template's MetadataOptions reach instances launched by EC2 Fleet and Auto Scaling, and
|
||||
* IMDS enforces them there.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class Ec2LaunchTemplateMetadataOptionsIntegrationTest {
|
||||
private static final String OWNER = "212121212121";
|
||||
@@ -28,9 +35,12 @@ class Ec2LaunchTemplateMetadataOptionsIntegrationTest {
|
||||
@Inject
|
||||
AutoScalingService groups;
|
||||
|
||||
@Inject
|
||||
Ec2Service ec2;
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"fleet", "asg"})
|
||||
void templateMetadataOptionsReachTheLaunchedInstance(String source) {
|
||||
void templateMetadataOptionsReachTheLaunchedInstance(String source) throws Exception {
|
||||
String name = "template-metadata-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
String template = request("ec2", "CreateLaunchTemplate").formParam("LaunchTemplateName", name)
|
||||
.formParam("LaunchTemplateData.ImageId", "ami-amazonlinux2023")
|
||||
@@ -64,6 +74,13 @@ class Ec2LaunchTemplateMetadataOptionsIntegrationTest {
|
||||
request("ec2", "DescribeInstances").formParam("InstanceId.1", instance).post("/").then().statusCode(200)
|
||||
.body(INSTANCE + "metadataOptions.httpTokens", equalTo("required"))
|
||||
.body(INSTANCE + "metadataOptions.httpPutResponseHopLimit", equalTo("2"));
|
||||
// IMDS then refuses the launched instance a tokenless read, as AWS does.
|
||||
try (Ec2MetadataTestFixture imds = new Ec2MetadataTestFixture()) {
|
||||
imds.start(null, mock(EmulatorConfig.class, RETURNS_DEEP_STUBS),
|
||||
ec2.findInstanceForAccount(OWNER, "us-east-1", instance).orElseThrow());
|
||||
assertEquals(401, imds.get("/latest/meta-data/instance-id", null).statusCode());
|
||||
assertEquals(200, imds.get("/latest/meta-data/instance-id", imds.putToken("60").body()).statusCode());
|
||||
}
|
||||
} finally {
|
||||
// Cleanup ignores the status, so a test that failed before launching keeps its own failure.
|
||||
if ("asg".equals(source)) {
|
||||
|
||||
@@ -1,12 +1,28 @@
|
||||
package io.github.hectorvent.floci.services.ec2;
|
||||
|
||||
import com.github.dockerjava.api.model.ContainerNetwork;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Instance;
|
||||
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplateData;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class Ec2MetadataProxyTest {
|
||||
@@ -40,8 +56,10 @@ class Ec2MetadataProxyTest {
|
||||
assertTrue(script.contains("if [ -f /tmp/floci-imds-proxy.pid ] && kill -0 \"$(cat /tmp/floci-imds-proxy.pid)\" 2>/dev/null; then\n exit 0\nfi"));
|
||||
// Targets configured Floci host and IMDS port
|
||||
assertTrue(script.contains("nohup socat TCP-LISTEN:80,bind=169.254.169.254,fork,reuseaddr TCP:10.0.0.1:9169 >/tmp/floci-imds-proxy.log 2>&1 &"));
|
||||
// Verifies via link-local curl
|
||||
assertTrue(script.contains("curl -fsS --max-time 1 http://169.254.169.254/latest/meta-data/instance-id >/dev/null && exit 0"));
|
||||
// Verifies through an IMDSv2 token even when tokenless access is refused.
|
||||
assertTrue(script.contains("-X PUT -H 'X-aws-ec2-metadata-token-ttl-seconds: 60'"));
|
||||
assertTrue(script.contains("http://169.254.169.254/latest/api/token"));
|
||||
assertTrue(script.contains("-H \"X-aws-ec2-metadata-token: $token\" http://169.254.169.254/latest/meta-data/instance-id"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -85,4 +103,239 @@ class Ec2MetadataProxyTest {
|
||||
assertTrue(Ec2MetadataProxy.preferredMetadataSourceIp(null).isEmpty());
|
||||
assertTrue(Ec2MetadataProxy.preferredMetadataSourceIp(Map.of()).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void installCommandClearsApplicationPathsBeforeThePackageManagerRuns(@TempDir Path directory)
|
||||
throws Exception {
|
||||
Path bin = Files.createDirectory(directory.resolve("bin"));
|
||||
Path record = directory.resolve("tools");
|
||||
Path arguments = directory.resolve("arguments");
|
||||
HelperShellFixture.writeTool(bin, "dnf", HelperShellFixture.checkedToolEnvironment()
|
||||
+ "printf '%s\\n' \"$*\" > \"$TEST_ARGUMENTS\"\n");
|
||||
|
||||
assertEquals(0, HelperShellFixture.run(Ec2MetadataProxy.installCommand(), directory,
|
||||
HelperShellFixture.applicationEnvironment(Map.of("PATH", bin.toString(),
|
||||
"TEST_RECORD", record.toString(), "TEST_ARGUMENTS", arguments.toString()))),
|
||||
HelperShellFixture.output(directory));
|
||||
|
||||
assertEquals("dnf\n", Files.readString(record));
|
||||
assertEquals("install -y --allowerasing iproute socat curl ca-certificates\n",
|
||||
Files.readString(arguments));
|
||||
}
|
||||
|
||||
@Test
|
||||
void startCommandClearsApplicationPathsBeforeAddressProxyAndProbeTools(@TempDir Path directory)
|
||||
throws Exception {
|
||||
Path bin = Files.createDirectory(directory.resolve("bin"));
|
||||
Path record = directory.resolve("tools");
|
||||
Path proxyReady = directory.resolve("proxy-ready");
|
||||
HelperShellFixture.writeTool(bin, "ip", HelperShellFixture.checkedToolEnvironment()
|
||||
+ "printf '127.0.0.1/32\\n'\n");
|
||||
HelperShellFixture.writeTool(bin, "socat", HelperShellFixture.checkedToolEnvironment()
|
||||
+ ": > \"$TEST_PROXY_READY\"\n");
|
||||
HelperShellFixture.writeTool(bin, "curl", HelperShellFixture.checkedToolEnvironment()
|
||||
+ "for attempt in 1 2 3 4 5 6 7 8 9 10; do\n"
|
||||
+ " [ -f \"$TEST_PROXY_READY\" ] && exit 0\n"
|
||||
+ " /bin/sleep 0.1\n"
|
||||
+ "done\nexit 1\n");
|
||||
String name = "unit-" + UUID.randomUUID();
|
||||
try {
|
||||
String[] command = Ec2MetadataProxy.startCommand(
|
||||
name, "127.0.0.1", 80, "127.0.0.1", 9169, "curl fixture && exit 0");
|
||||
assertEquals(0, HelperShellFixture.run(command, directory,
|
||||
HelperShellFixture.applicationEnvironment(Map.of("PATH", bin + ":" + System.getenv("PATH"),
|
||||
"TEST_RECORD", record.toString(), "TEST_PROXY_READY", proxyReady.toString()))),
|
||||
HelperShellFixture.output(directory));
|
||||
assertEquals(Set.of("ip", "socat", "curl"), Set.copyOf(Files.readAllLines(record)));
|
||||
} finally {
|
||||
deleteProxyFiles(name);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void readinessProbeReadsTheInstanceIdWithATokenWhenTheInstanceRequiresOne(@TempDir Path directory)
|
||||
throws Exception {
|
||||
try (Ec2MetadataTestFixture fixture = new Ec2MetadataTestFixture()) {
|
||||
fixture.start();
|
||||
requireTokens(fixture.instance());
|
||||
|
||||
assertEquals(0, HelperShellFixture.run(probe(fixture.endpoint()), directory, Map.of()),
|
||||
HelperShellFixture.output(directory));
|
||||
}
|
||||
}
|
||||
|
||||
/** An image's proxy settings are for its application; the probe checks the link-local path itself. */
|
||||
@Test
|
||||
void readinessProbeIgnoresTheImagesHttpProxy(@TempDir Path directory) throws Exception {
|
||||
List<String> proxied = new CopyOnWriteArrayList<>();
|
||||
HttpServer proxy = failingProxy(proxied);
|
||||
try (Ec2MetadataTestFixture fixture = new Ec2MetadataTestFixture()) {
|
||||
fixture.start();
|
||||
requireTokens(fixture.instance());
|
||||
|
||||
int result = HelperShellFixture.run(probe(fixture.endpoint()), directory, proxyEnvironment(proxy));
|
||||
|
||||
assertEquals(0, result, HelperShellFixture.output(directory));
|
||||
assertEquals(List.of(), proxied);
|
||||
} finally {
|
||||
proxy.stop(0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The pod identity relay answers 400 without a pod token, which still proves socat relays. A
|
||||
* proxy that answered in its place would look the same to the status check, so the probe
|
||||
* must not go through one.
|
||||
*/
|
||||
@Test
|
||||
void podIdentityProbeIgnoresTheImagesHttpProxy(@TempDir Path directory) throws Exception {
|
||||
List<String> proxied = new CopyOnWriteArrayList<>();
|
||||
AtomicInteger relayed = new AtomicInteger();
|
||||
HttpServer proxy = null;
|
||||
HttpServer relay = null;
|
||||
try {
|
||||
proxy = failingProxy(proxied);
|
||||
relay = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
relay.createContext("/v1/credentials", exchange -> {
|
||||
relayed.incrementAndGet();
|
||||
exchange.sendResponseHeaders(400, -1);
|
||||
exchange.close();
|
||||
});
|
||||
relay.start();
|
||||
String[] probe = {"sh", "-c",
|
||||
Ec2MetadataProxy.podIdentityProbeCommand("http://127.0.0.1:" + relay.getAddress().getPort())};
|
||||
|
||||
int result = HelperShellFixture.run(probe, directory, proxyEnvironment(proxy));
|
||||
|
||||
assertEquals(0, result, HelperShellFixture.output(directory));
|
||||
assertEquals(1, relayed.get(), HelperShellFixture.output(directory));
|
||||
assertEquals(List.of(), proxied);
|
||||
} finally {
|
||||
if (relay != null) {
|
||||
relay.stop(0);
|
||||
}
|
||||
if (proxy != null) {
|
||||
proxy.stop(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Floci's IMDS issues a token for every valid request, so the refused and empty token answers
|
||||
* come from a stand-in that records what the probe sent.
|
||||
*/
|
||||
@ParameterizedTest
|
||||
@CsvSource({"403, rejected", "200, ''"})
|
||||
void readinessProbeNeverFallsBackToATokenlessRead(int tokenStatus, String tokenBody, @TempDir Path directory)
|
||||
throws Exception {
|
||||
List<String> requests = new CopyOnWriteArrayList<>();
|
||||
HttpServer server = metadataStandIn(requests, attempt -> tokenStatus, tokenBody);
|
||||
try {
|
||||
int result = HelperShellFixture.run(probe("http://127.0.0.1:" + server.getAddress().getPort()),
|
||||
directory, Map.of());
|
||||
|
||||
assertNotEquals(0, result, HelperShellFixture.output(directory));
|
||||
assertEquals(List.of("PUT token 60"), requests, HelperShellFixture.output(directory));
|
||||
} finally {
|
||||
server.stop(0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The proxy's first probes run before socat listens, so a refused token has to end only that
|
||||
* attempt: the generated start script, under {@code set -eu}, retries until a token is issued.
|
||||
*/
|
||||
@Test
|
||||
void startScriptRetriesTheTokenProbeUntilATokenIsIssued(@TempDir Path directory) throws Exception {
|
||||
Path bin = Files.createDirectory(directory.resolve("bin"));
|
||||
HelperShellFixture.writeTool(bin, "ip", "printf '127.0.0.1/32\\n'\n");
|
||||
HelperShellFixture.writeTool(bin, "socat", "exit 0\n");
|
||||
List<String> requests = new CopyOnWriteArrayList<>();
|
||||
HttpServer server = metadataStandIn(requests, attempt -> attempt == 1 ? 403 : 200, "fixture-token");
|
||||
String name = "unit-" + UUID.randomUUID();
|
||||
try {
|
||||
String[] command = Ec2MetadataProxy.startCommand(name, "127.0.0.1", 80, "127.0.0.1", 9169,
|
||||
Ec2MetadataProxy.imdsProbeCommand("http://127.0.0.1:" + server.getAddress().getPort()));
|
||||
|
||||
int result = HelperShellFixture.run(command, directory,
|
||||
Map.of("PATH", bin + ":" + System.getenv("PATH")));
|
||||
|
||||
assertEquals(0, result, HelperShellFixture.output(directory));
|
||||
assertEquals(List.of("PUT token 60", "PUT token 60", "GET metadata fixture-token"), requests,
|
||||
HelperShellFixture.output(directory));
|
||||
} finally {
|
||||
server.stop(0);
|
||||
deleteProxyFiles(name);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Answers token requests with the status {@code tokenStatus} picks for each attempt, serves the
|
||||
* instance ID to the issued token and, as an instance allowing IMDSv1 would, to a tokenless
|
||||
* read, and records what it was sent.
|
||||
*/
|
||||
private static HttpServer metadataStandIn(List<String> requests, TokenStatus tokenStatus, String tokenBody)
|
||||
throws Exception {
|
||||
AtomicInteger tokenRequests = new AtomicInteger();
|
||||
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
server.createContext("/latest/api/token", exchange -> {
|
||||
requests.add(exchange.getRequestMethod() + " token "
|
||||
+ exchange.getRequestHeaders().getFirst(Ec2MetadataTestFixture.TTL_HEADER));
|
||||
byte[] body = tokenBody.getBytes(StandardCharsets.UTF_8);
|
||||
exchange.sendResponseHeaders(tokenStatus.forAttempt(tokenRequests.incrementAndGet()),
|
||||
body.length == 0 ? -1 : body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
exchange.close();
|
||||
});
|
||||
server.createContext("/latest/meta-data/instance-id", exchange -> {
|
||||
String token = exchange.getRequestHeaders().getFirst(Ec2MetadataTestFixture.TOKEN_HEADER);
|
||||
requests.add(exchange.getRequestMethod() + " metadata " + token);
|
||||
byte[] body = "i-fixture".getBytes(StandardCharsets.UTF_8);
|
||||
boolean accepted = token == null || !tokenBody.isEmpty() && tokenBody.equals(token);
|
||||
exchange.sendResponseHeaders(accepted ? 200 : 401, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
exchange.close();
|
||||
});
|
||||
server.start();
|
||||
return server;
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
private interface TokenStatus {
|
||||
int forAttempt(int attempt);
|
||||
}
|
||||
|
||||
/** An HTTP proxy that records every request it is sent and answers each with 502. */
|
||||
private static HttpServer failingProxy(List<String> proxied) throws Exception {
|
||||
HttpServer proxy = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
proxy.createContext("/", exchange -> {
|
||||
proxied.add(exchange.getRequestMethod() + " " + exchange.getRequestURI());
|
||||
exchange.sendResponseHeaders(502, -1);
|
||||
exchange.close();
|
||||
});
|
||||
proxy.start();
|
||||
return proxy;
|
||||
}
|
||||
|
||||
/** The proxy settings an image could carry, with nothing exempted. */
|
||||
private static Map<String, String> proxyEnvironment(HttpServer proxy) {
|
||||
String proxyUrl = "http://127.0.0.1:" + proxy.getAddress().getPort();
|
||||
return Map.of("http_proxy", proxyUrl, "HTTP_PROXY", proxyUrl, "all_proxy", proxyUrl,
|
||||
"ALL_PROXY", proxyUrl, "no_proxy", "", "NO_PROXY", "");
|
||||
}
|
||||
|
||||
private static String[] probe(String endpoint) {
|
||||
return new String[]{"sh", "-c", Ec2MetadataProxy.imdsProbeCommand(endpoint)};
|
||||
}
|
||||
|
||||
private static void requireTokens(Instance instance) {
|
||||
LaunchTemplateData.MetadataOptions options = LaunchTemplateData.MetadataOptions.launchDefaults();
|
||||
options.setHttpTokens("required");
|
||||
instance.setMetadataOptions(options);
|
||||
}
|
||||
|
||||
private static void deleteProxyFiles(String name) throws Exception {
|
||||
Files.deleteIfExists(Path.of("/tmp/floci-" + name + "-proxy.pid"));
|
||||
Files.deleteIfExists(Path.of("/tmp/floci-" + name + "-proxy.log"));
|
||||
}
|
||||
}
|
||||
@@ -84,6 +84,11 @@ final class Ec2MetadataTestFixture implements AutoCloseable {
|
||||
return instance;
|
||||
}
|
||||
|
||||
/** The server's base URL, for a client other than this fixture's own requests. */
|
||||
String endpoint() {
|
||||
return endpoint;
|
||||
}
|
||||
|
||||
static Instance instance(String instanceId) {
|
||||
Instance instance = new Instance();
|
||||
instance.setInstanceId(instanceId);
|
||||
@@ -100,6 +105,16 @@ final class Ec2MetadataTestFixture implements AutoCloseable {
|
||||
return get(path, token, HttpResponse.BodyHandlers.ofString());
|
||||
}
|
||||
|
||||
/** A request with any method and no body, with the token header when {@code token} is not null. */
|
||||
HttpResponse<String> send(String method, String path, String token) throws Exception {
|
||||
HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(endpoint + path))
|
||||
.timeout(Duration.ofSeconds(5)).method(method, HttpRequest.BodyPublishers.noBody());
|
||||
if (token != null) {
|
||||
request.header(TOKEN_HEADER, token);
|
||||
}
|
||||
return client.send(request.build(), HttpResponse.BodyHandlers.ofString());
|
||||
}
|
||||
|
||||
<T> HttpResponse<T> get(String path, String token, HttpResponse.BodyHandler<T> bodyHandler) throws Exception {
|
||||
HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(endpoint + path))
|
||||
.timeout(Duration.ofSeconds(5));
|
||||
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
package io.github.hectorvent.floci.services.ec2;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Instance;
|
||||
import io.github.hectorvent.floci.testing.EnforcementFixtures;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.net.http.HttpResponse;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
/**
|
||||
* The HttpTokens an instance is launched with, and any later ModifyInstanceMetadataOptions, decide
|
||||
* whether IMDS still answers a request without a token: on AWS a required token turns IMDSv1 reads
|
||||
* into 401. The stored instance is registered with a metadata server of its own, as a launched
|
||||
* container would be.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class Ec2MetadataTokenRequirementIntegrationTest {
|
||||
private static final String ACCOUNT = "357924681357";
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String INSTANCE_ID = "/latest/meta-data/instance-id";
|
||||
|
||||
@Inject
|
||||
Ec2Service ec2;
|
||||
|
||||
@Test
|
||||
void launchAndModifiedTokenRequirementsApplyToTheRunningInstance() throws Exception {
|
||||
String instanceId = request("RunInstances")
|
||||
.formParam("ImageId", "ami-0abcdef1234567890").formParam("InstanceType", "t3.micro")
|
||||
.formParam("MinCount", "1").formParam("MaxCount", "1")
|
||||
.formParam("MetadataOptions.HttpTokens", "required")
|
||||
.post("/").then().statusCode(200)
|
||||
.extract().path("RunInstancesResponse.instancesSet.item.instanceId");
|
||||
try (Ec2MetadataTestFixture fixture = new Ec2MetadataTestFixture()) {
|
||||
Instance stored = ec2.findInstanceForAccount(ACCOUNT, REGION, instanceId).orElseThrow();
|
||||
fixture.start(null, mock(EmulatorConfig.class, RETURNS_DEEP_STUBS), stored);
|
||||
|
||||
assertEquals(401, fixture.get(INSTANCE_ID, null).statusCode());
|
||||
HttpResponse<String> withToken = fixture.get(INSTANCE_ID, fixture.putToken("60").body());
|
||||
assertEquals(200, withToken.statusCode());
|
||||
assertEquals(instanceId, withToken.body());
|
||||
|
||||
modifyHttpTokens(instanceId, "optional");
|
||||
HttpResponse<String> withoutToken = fixture.get(INSTANCE_ID, null);
|
||||
assertEquals(200, withoutToken.statusCode());
|
||||
assertEquals(instanceId, withoutToken.body());
|
||||
|
||||
modifyHttpTokens(instanceId, "required");
|
||||
assertEquals(401, fixture.get(INSTANCE_ID, null).statusCode());
|
||||
} finally {
|
||||
request("TerminateInstances").formParam("InstanceId.1", instanceId)
|
||||
.post("/").then().statusCode(200);
|
||||
}
|
||||
}
|
||||
|
||||
private static void modifyHttpTokens(String instanceId, String httpTokens) {
|
||||
request("ModifyInstanceMetadataOptions").formParam("InstanceId", instanceId)
|
||||
.formParam("HttpTokens", httpTokens)
|
||||
.post("/").then().statusCode(200)
|
||||
.body("ModifyInstanceMetadataOptionsResponse.instanceMetadataOptions.httpTokens",
|
||||
equalTo(httpTokens));
|
||||
}
|
||||
|
||||
private static RequestSpecification request(String action) {
|
||||
return given().header("Authorization", EnforcementFixtures.auth(ACCOUNT, REGION, "ec2"))
|
||||
.contentType("application/x-www-form-urlencoded").formParam("Action", action);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.ec2;
|
||||
|
||||
import io.github.hectorvent.floci.services.ec2.model.Instance;
|
||||
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplateData;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -15,7 +16,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
/**
|
||||
* IMDSv2 session tokens, as documented in the EC2 User Guide: the PUT must carry a TTL between
|
||||
* 1 and 21,600 seconds (otherwise 400), and a GET that presents an invalid or expired token gets
|
||||
* 401 so the caller fetches a new token. A token is not valid on other instances.
|
||||
* 401 so the caller fetches a new token. A token is not valid on other instances. When the
|
||||
* instance's HttpTokens is required, a GET without a valid token also gets 401.
|
||||
*/
|
||||
class Ec2MetadataTokenTest {
|
||||
|
||||
@@ -100,6 +102,117 @@ class Ec2MetadataTokenTest {
|
||||
assertEquals(200, response.statusCode());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {
|
||||
"/latest/meta-data/instance-id",
|
||||
"/latest/dynamic/instance-identity/document",
|
||||
"/latest/user-data",
|
||||
"/latest/meta-data/iam/info",
|
||||
"/latest/meta-data/iam/security-credentials/",
|
||||
"/latest/meta-data/identity-credentials/ec2/security-credentials/ec2-instance",
|
||||
"/latest/meta-data/tags/instance/"
|
||||
})
|
||||
void requiredTokenRefusesDataBeforeResolvingItsContents(String path) throws Exception {
|
||||
setTokenRequirement("required");
|
||||
instance.setUserData("private-user-data");
|
||||
|
||||
HttpResponse<String> response = getWithoutToken(path);
|
||||
|
||||
assertEquals(401, response.statusCode());
|
||||
assertEquals("", response.body());
|
||||
}
|
||||
|
||||
/** AWS refuses the request before looking at the path, so a listing IMDS does not serve is 401 too. */
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"/latest/meta-data/", "/latest/meta-data/no-such-item", "/latest/"})
|
||||
void requiredTokenRefusesPathsImdsDoesNotServe(String path) throws Exception {
|
||||
setTokenRequirement("required");
|
||||
|
||||
assertEquals(401, getWithoutToken(path).statusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void requiredTokenRefusesATokenlessHeadRequest() throws Exception {
|
||||
setTokenRequirement("required");
|
||||
|
||||
assertEquals(401, fixture.send("HEAD", "/latest/meta-data/instance-id", null).statusCode());
|
||||
}
|
||||
|
||||
/** No route serves HEAD, so with a token the router answers as it would for any unserved method. */
|
||||
@Test
|
||||
void aHeadRequestWithATokenGetsTheRoutersAnswer() throws Exception {
|
||||
setTokenRequirement("required");
|
||||
String token = fixture.putToken("60").body();
|
||||
|
||||
assertEquals(405, fixture.send("HEAD", "/latest/meta-data/instance-id", token).statusCode());
|
||||
assertEquals(404, fixture.send("HEAD", "/latest/meta-data/no-such-item", token).statusCode());
|
||||
}
|
||||
|
||||
/** The token check sits ahead of the routes without claiming the methods IMDS does not serve. */
|
||||
@Test
|
||||
void aMethodImdsDoesNotServeIsStillNotFound() throws Exception {
|
||||
setTokenRequirement("required");
|
||||
String token = fixture.putToken("60").body();
|
||||
|
||||
assertEquals(404, fixture.send("POST", "/latest/meta-data/", token).statusCode());
|
||||
assertEquals(404, fixture.send("POST", "/latest/meta-data/", null).statusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPathImdsDoesNotServeIsStillNotFoundWithAToken() throws Exception {
|
||||
setTokenRequirement("required");
|
||||
String token = fixture.putToken("60").body();
|
||||
|
||||
assertEquals(404, fixture.get("/latest/meta-data/no-such-item", token).statusCode());
|
||||
setTokenRequirement("optional");
|
||||
assertEquals(404, getWithoutToken("/latest/meta-data/no-such-item").statusCode());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"", " "})
|
||||
void blankTokenDoesNotBypassRequiredTokens(String token) throws Exception {
|
||||
setTokenRequirement("required");
|
||||
|
||||
assertEquals(401, getInstanceId(token).statusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void requiredTokenPreservesIssuanceValidationAndExpiry() throws Exception {
|
||||
setTokenRequirement("required");
|
||||
HttpResponse<String> issued = fixture.putToken("60");
|
||||
assertEquals(200, issued.statusCode());
|
||||
|
||||
HttpResponse<String> accepted = getInstanceId(issued.body());
|
||||
assertEquals(200, accepted.statusCode());
|
||||
assertEquals(instance.getInstanceId(), accepted.body());
|
||||
assertEquals(401, getInstanceId("invalid-token").statusCode());
|
||||
|
||||
fixture.clock().advance(Duration.ofSeconds(60));
|
||||
assertEquals(401, getInstanceId(issued.body()).statusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tokenRequirementTracksTheRegisteredInstancesCurrentOptions() throws Exception {
|
||||
setTokenRequirement("optional");
|
||||
assertEquals(200, getWithoutToken("/latest/meta-data/instance-id").statusCode());
|
||||
|
||||
setTokenRequirement("required");
|
||||
assertEquals(401, getWithoutToken("/latest/meta-data/instance-id").statusCode());
|
||||
|
||||
setTokenRequirement("optional");
|
||||
assertEquals(200, getWithoutToken("/latest/meta-data/instance-id").statusCode());
|
||||
}
|
||||
|
||||
private void setTokenRequirement(String value) {
|
||||
LaunchTemplateData.MetadataOptions options = LaunchTemplateData.MetadataOptions.launchDefaults();
|
||||
options.setHttpTokens(value);
|
||||
instance.setMetadataOptions(options);
|
||||
}
|
||||
|
||||
private HttpResponse<String> getWithoutToken(String path) throws Exception {
|
||||
return fixture.get(path, null);
|
||||
}
|
||||
|
||||
private HttpResponse<String> getInstanceId(String token) throws Exception {
|
||||
return fixture.get("/latest/meta-data/instance-id", token, HttpResponse.BodyHandlers.ofString());
|
||||
}
|
||||
|
||||
@@ -7256,6 +7256,86 @@ class Ec2ServiceTest {
|
||||
assertEquals(400, rebootEx.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void clusterNodeMetadataOptionsCannotBeModifiedThroughEc2() {
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
|
||||
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
|
||||
Instance nodeInstance = new Instance();
|
||||
nodeInstance.setInstanceId("i-node1234567890abc");
|
||||
nodeInstance.setRegion("us-east-1");
|
||||
nodeInstance.setPlacement(new Placement("us-east-1a"));
|
||||
nodeInstance.setState(InstanceState.running());
|
||||
nodeInstance.setInstanceType("m5.large");
|
||||
service.setClusterNodeInstanceProvider(new ClusterNodeInstanceProvider() {
|
||||
@Override
|
||||
public Optional<Instance> findInstance(String accountId, String region, String instanceId) {
|
||||
return "i-node1234567890abc".equals(instanceId) && ("us-east-1".equals(region) || region == null)
|
||||
? Optional.of(nodeInstance) : Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Instance> listInstances(String accountId, String region) {
|
||||
return "us-east-1".equals(region) || region == null ? List.of(nodeInstance) : List.of();
|
||||
}
|
||||
});
|
||||
LaunchTemplateData.MetadataOptions required = new LaunchTemplateData.MetadataOptions();
|
||||
required.setHttpTokens("required");
|
||||
|
||||
// IMDS serves the node from the instance its cluster registered, so a change made to the
|
||||
// copy EC2 hands out would be reported by DescribeInstances and never enforced.
|
||||
AwsException modifyEx = assertThrows(AwsException.class, () ->
|
||||
service.modifyInstanceMetadataOptions("us-east-1", "i-node1234567890abc", required));
|
||||
assertEquals("OperationNotPermitted", modifyEx.getErrorCode());
|
||||
assertEquals(400, modifyEx.getHttpStatus());
|
||||
|
||||
Instance described = service.describeInstances("us-east-1", List.of("i-node1234567890abc"), Map.of())
|
||||
.getFirst().getInstances().getFirst();
|
||||
assertEquals("optional", described.effectiveMetadataOptions().getHttpTokens());
|
||||
assertNull(nodeInstance.getMetadataOptions());
|
||||
AwsException terminateEx = assertThrows(AwsException.class, () ->
|
||||
service.terminateInstances("us-east-1", List.of("i-node1234567890abc")));
|
||||
assertEquals("OperationNotPermitted", terminateEx.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void clusterNodeStaysRefusedAfterAnotherActionStoredACopyOfIt() {
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
|
||||
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
|
||||
Instance nodeInstance = new Instance();
|
||||
nodeInstance.setInstanceId("i-node1234567890abc");
|
||||
nodeInstance.setRegion("us-east-1");
|
||||
nodeInstance.setPlacement(new Placement("us-east-1a"));
|
||||
nodeInstance.setState(InstanceState.running());
|
||||
nodeInstance.setInstanceType("m5.large");
|
||||
service.setClusterNodeInstanceProvider(new ClusterNodeInstanceProvider() {
|
||||
@Override
|
||||
public Optional<Instance> findInstance(String accountId, String region, String instanceId) {
|
||||
return "i-node1234567890abc".equals(instanceId) && ("us-east-1".equals(region) || region == null)
|
||||
? Optional.of(nodeInstance) : Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Instance> listInstances(String accountId, String region) {
|
||||
return "us-east-1".equals(region) || region == null ? List.of(nodeInstance) : List.of();
|
||||
}
|
||||
});
|
||||
// ModifyInstanceAttribute writes EC2's copy of the node into the instance store; the node is
|
||||
// still the cluster's, so the actions refused for it stay refused.
|
||||
service.modifyInstanceAttribute("us-east-1", "i-node1234567890abc", "sourceDestCheck", "false");
|
||||
LaunchTemplateData.MetadataOptions required = new LaunchTemplateData.MetadataOptions();
|
||||
required.setHttpTokens("required");
|
||||
|
||||
assertEquals("OperationNotPermitted", assertThrows(AwsException.class, () ->
|
||||
service.modifyInstanceMetadataOptions("us-east-1", "i-node1234567890abc", required))
|
||||
.getErrorCode());
|
||||
assertEquals("OperationNotPermitted", assertThrows(AwsException.class, () ->
|
||||
service.terminateInstances("us-east-1", List.of("i-node1234567890abc"))).getErrorCode());
|
||||
assertEquals("OperationNotPermitted", assertThrows(AwsException.class, () ->
|
||||
service.stopInstances("us-east-1", List.of("i-node1234567890abc"))).getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void ordinaryEc2InstancesUnaffectedByClusterNodeInstanceProvider() {
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
package io.github.hectorvent.floci.services.ec2;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Runs the helper shells Floci execs inside a guest (the IMDS proxy's, the sshd install probe) on
|
||||
* this host with {@code /bin/sh}, against fake system tools on PATH, with the environment an
|
||||
* application image hands a {@code docker exec}.
|
||||
*/
|
||||
final class HelperShellFixture {
|
||||
|
||||
/** What an application image can carry into a {@code docker exec}, plus one setting the shells must keep. */
|
||||
static final Map<String, String> APPLICATION_ENVIRONMENT = Map.of(
|
||||
"LD_LIBRARY_PATH", "/fixture/application/lib",
|
||||
"PYTHONPATH", "/fixture/application/modules",
|
||||
"PYTHONHOME", "/fixture/application/python",
|
||||
"KEEP_SETTING", "fixture-value");
|
||||
|
||||
private HelperShellFixture() {}
|
||||
|
||||
/**
|
||||
* The start of a fake tool that fails unless the application's library and Python paths are
|
||||
* unset while its other settings survive, and then records the tool's name in TEST_RECORD.
|
||||
*/
|
||||
static String checkedToolEnvironment() {
|
||||
return "[ -z \"${LD_LIBRARY_PATH+x}\" ] || exit 91\n"
|
||||
+ "[ -z \"${PYTHONPATH+x}\" ] || exit 92\n"
|
||||
+ "[ -z \"${PYTHONHOME+x}\" ] || exit 93\n"
|
||||
+ "[ \"$KEEP_SETTING\" = fixture-value ] || exit 94\n"
|
||||
+ "printf '%s\\n' \"${0##*/}\" >> \"$TEST_RECORD\"\n";
|
||||
}
|
||||
|
||||
/** {@link #APPLICATION_ENVIRONMENT} plus the test's own settings. */
|
||||
static Map<String, String> applicationEnvironment(Map<String, String> settings) {
|
||||
Map<String, String> environment = new HashMap<>(APPLICATION_ENVIRONMENT);
|
||||
environment.putAll(settings);
|
||||
return environment;
|
||||
}
|
||||
|
||||
static void writeTool(Path bin, String name, String script) throws IOException {
|
||||
Path tool = bin.resolve(name);
|
||||
Files.writeString(tool, "#!/bin/sh\nset -eu\n" + script);
|
||||
assertTrue(tool.toFile().setExecutable(true));
|
||||
}
|
||||
|
||||
/** Runs a generated helper shell with {@code /bin/sh}, its output going to {@link #output}. */
|
||||
static int run(String[] command, Path directory, Map<String, String> environment) throws Exception {
|
||||
List<String> arguments = new ArrayList<>(List.of(command));
|
||||
arguments.set(0, "/bin/sh");
|
||||
ProcessBuilder builder = new ProcessBuilder(arguments);
|
||||
builder.environment().putAll(environment);
|
||||
builder.redirectErrorStream(true).redirectOutput(directory.resolve("shell-output").toFile());
|
||||
Process process = builder.start();
|
||||
try {
|
||||
assertTrue(process.waitFor(5, TimeUnit.SECONDS), "Generated helper shell exceeded its bound");
|
||||
return process.exitValue();
|
||||
} finally {
|
||||
process.destroyForcibly();
|
||||
}
|
||||
}
|
||||
|
||||
static String output(Path directory) throws IOException {
|
||||
return Files.readString(directory.resolve("shell-output"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user