mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(eks): forward the Pod Identity address to Floci with NAT rules while its add-on is installed (#8736)
A stock rancher/k3s node has no package manager, so the socat relay Floci installed for the EKS Pod Identity address, 169.254.170.23, never started, and every pod's credentials request timed out. The address is now sent straight to Floci's credentials endpoint with iptables NAT rules, a PREROUTING rule for the pod network and an OUTPUT rule for the node and hostNetwork pods, and what an older Floci set up for the address, its relay included, is removed. The rules follow the eks-pod-identity-agent add-on: CreateAddon adds them, DeleteAddon removes them unless preserve is set, and a node start or a restart's adoption sets them from the stored add-on, under a lock of the cluster. The Pod Identity webhook reads the same stored add-on. Closes #5629
This commit is contained in:
1 parent
11a16946b6
commit
f06695cf08
21 files changed
+1435
-310
No files matched your search
+13
-2
@@ -149,7 +149,17 @@ Real EKS sets neither endpoint variable. Floci adds them so the credentials it h
|
||||
|
||||
### Credential endpoint
|
||||
|
||||
Floci serves pod identity credentials through a link-local relay bound to `169.254.170.23:80` inside the cluster container, forwarding requests to Floci's credentials endpoint (`GET /v1/credentials`). Workloads reach this endpoint using the injected `AWS_CONTAINER_CREDENTIALS_FULL_URI` environment variable, passing their projected token in the `Authorization` header (`Authorization: <token>` or `Authorization: Bearer <token>`).
|
||||
On EKS the Pod Identity Agent answers on `169.254.170.23:80` on every node while the `eks-pod-identity-agent` add-on is installed. Floci makes that address answer in the cluster container while the add-on is stored, with NAT rules that send requests for it straight to Floci's credentials endpoint (`GET /v1/credentials`), so nothing is installed or run in the node. A `PREROUTING` rule takes the pod network's requests (the cluster's pod CIDR) and an `OUTPUT` rule the node's own, which is where `hostNetwork` pods' come from. The node's masquerade rule (flannel's) carries the answers back. Workloads reach this endpoint using the injected `AWS_CONTAINER_CREDENTIALS_FULL_URI` environment variable, passing their projected token in the `Authorization` header (`Authorization: <token>` or `Authorization: Bearer <token>`).
|
||||
|
||||
The rules follow the add-on:
|
||||
|
||||
- `CreateAddon` for `eks-pod-identity-agent` adds them, replacing any an earlier Floci left for the address.
|
||||
- `DeleteAddon` removes them. With `preserve=true` they stay, since EKS leaves the agent running on the cluster then.
|
||||
- When the cluster container starts or a Floci restart adopts it, Floci adds them while the add-on is stored and otherwise removes any it finds. So after a `DeleteAddon` with `preserve=true`, the address answers only until the next restart.
|
||||
|
||||
Each of these also retires the `socat` relay an older Floci ran for the address in the node, with its loopback address and its rule in the `FLOCI-LINK-LOCAL` chain, so the relay can't answer once the rules are removed.
|
||||
|
||||
The rules need `iptables` in the node, which the stock `rancher/k3s` image has, and they are only set up with `floci.services.eks.pod-identity-webhook` and TLS on (see below), since pods get the credentials URL only from the webhook. Floci's host name is resolved inside the node, from its `/etc/hosts` (where `host.docker.internal` lives on Linux) or else through DNS.
|
||||
|
||||
The credentials endpoint performs the following validations:
|
||||
1. Validates token format and extracts the issuer URL without verifying signatures yet.
|
||||
@@ -181,11 +191,12 @@ Floci supports the EKS cluster addon management plane for AWS SDKs and Terraform
|
||||
- **Updating**: `UpdateAddon` updates the addon version, configuration values, service account role ARN, or resolve-conflicts strategy. It returns an `Update` tracking object and updates the addon metadata.
|
||||
- **Update tracking**: `DescribeUpdate` describes the status of an addon update (such as an in-place addon version update queried by Terraform).
|
||||
- **Deletion**: `DeleteAddon` marks the addon as `DELETING` and removes it from the cluster. Deleting a cluster automatically cleans up all associated addons.
|
||||
- **Pod Identity Agent**: while `eks-pod-identity-agent` is installed, `169.254.170.23:80` answers in the cluster container, as described under [Credential endpoint](#credential-endpoint).
|
||||
- **Supported versions**: `DescribeAddonVersions` queries the addon version catalog with optional filtering by `addonName` and `kubernetesVersion`, supporting pagination. As in AWS, a `kubernetesVersion` filter also limits each version's `compatibilities` to that Kubernetes version. The catalog in `src/main/resources/eks/addon-versions.json` holds the parts of AWS's `DescribeAddonVersions` answer that Floci serves, for every Kubernetes version Floci can run; `make eks-addons-sync` regenerates it from `DescribeAddonVersions` with any AWS account's credentials.
|
||||
|
||||
### Metadata recording only
|
||||
|
||||
Addons in Floci are recorded metadata only. Creating or updating an addon does not install or reconcile Kubernetes DaemonSets, Deployments, or custom resources inside the cluster container.
|
||||
Addons in Floci are recorded metadata only. Creating or updating an addon does not install or reconcile Kubernetes DaemonSets, Deployments, or custom resources inside the cluster container. The one effect inside it is the Pod Identity address of `eks-pod-identity-agent`, which Floci forwards itself rather than by running the agent.
|
||||
|
||||
## Cluster security group
|
||||
|
||||
|
||||
@@ -14,6 +14,13 @@ public final class Ec2MetadataProxy {
|
||||
|
||||
private static final int EC2_IMDS_RELAY_PORT = 42169;
|
||||
|
||||
/** A shell function: whether process {@code $1} is a socat whose arguments hold {@code $2}. */
|
||||
private static final List<String> IS_SOCAT_LISTENER = List.of(
|
||||
"is_socat_listener() {",
|
||||
" [ \"$(cat \"/proc/$1/comm\" 2>/dev/null)\" = socat ]"
|
||||
+ " && tr '\\0' ' ' 2>/dev/null <\"/proc/$1/cmdline\" | grep -Fq \"$2\"",
|
||||
"}");
|
||||
|
||||
/**
|
||||
* Run first in the shells that install and start these proxies and in the sshd install probe.
|
||||
* {@code docker exec} hands the shell the image's environment, so an application's library
|
||||
@@ -126,21 +133,6 @@ public final class Ec2MetadataProxy {
|
||||
+ endpoint + "/latest/meta-data/instance-id >/dev/null && exit 0";
|
||||
}
|
||||
|
||||
public static String[] podIdentityStartCommand(String flociHost, int flociPort) {
|
||||
return startCommand("pod-identity", "169.254.170.23", 80, flociHost, flociPort,
|
||||
podIdentityProbeCommand("http://169.254.170.23"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Ready once the relay answers at all: without a pod's token Floci answers 400, which still
|
||||
* proves socat relays. Any HTTP proxy the image configures is bypassed, since a proxy's own
|
||||
* answer would pass the same check.
|
||||
*/
|
||||
static String podIdentityProbeCommand(String endpoint) {
|
||||
return "[ \"$(curl -s --noproxy '*' -o /dev/null -w '%{http_code}' --max-time 1 " + endpoint
|
||||
+ "/v1/credentials)\" != \"000\" ] && exit 0";
|
||||
}
|
||||
|
||||
public static String[] startCommand(String name, String bindIp, int bindPort,
|
||||
String targetHost, int targetPort, String probeCommand) {
|
||||
return startCommand(name, bindIp, bindPort, targetHost, targetPort, probeCommand, false);
|
||||
@@ -149,7 +141,7 @@ public final class Ec2MetadataProxy {
|
||||
private static String[] startCommand(String name, String bindIp, int bindPort,
|
||||
String targetHost, int targetPort, String probeCommand,
|
||||
boolean routeImdsPort) {
|
||||
String legacyPidFile = "/tmp/floci-" + name + "-proxy.pid";
|
||||
String legacyPidFile = relayPidFile(name);
|
||||
String pidFile = routeImdsPort ? "/tmp/floci-" + name + "-proxy-" + bindPort + ".pid" : legacyPidFile;
|
||||
String logFile = "/tmp/floci-" + name + "-proxy.log";
|
||||
String listener = "TCP-LISTEN:" + bindPort + ",bind=" + bindIp + ",";
|
||||
@@ -161,10 +153,7 @@ public final class Ec2MetadataProxy {
|
||||
LEAVE_ROOT_CGROUP,
|
||||
CLEAR_APPLICATION_PATHS,
|
||||
"ip addr show dev lo | grep -q '" + bindIp + "/32' || ip addr add " + bindIp + "/32 dev lo"));
|
||||
lines.add("is_socat_listener() {");
|
||||
lines.add(" [ \"$(cat \"/proc/$1/comm\" 2>/dev/null)\" = socat ]"
|
||||
+ " && tr '\\0' ' ' 2>/dev/null <\"/proc/$1/cmdline\" | grep -Fq \"$2\"");
|
||||
lines.add("}");
|
||||
lines.addAll(IS_SOCAT_LISTENER);
|
||||
|
||||
// The writable-layer PID file survives a container restart, so verify the process name and
|
||||
// listener arguments before reusing it or retiring a pre-upgrade TCP/80 listener.
|
||||
@@ -320,6 +309,29 @@ public final class Ec2MetadataProxy {
|
||||
return new String[]{"sh", "-c", String.join("\n", lines)};
|
||||
}
|
||||
|
||||
/**
|
||||
* Shell lines that retire the relay {@link #startCommand(String, String, int, String, int, String)} started as
|
||||
* {@code name} on {@code bindIp}, port 80: the socat its PID file names, while that is still the relay, then the
|
||||
* PID file and the loopback address the relay was given. A node without the relay, or without {@code ip}, is
|
||||
* left as it is.
|
||||
*/
|
||||
public static List<String> stopRelayLines(String name, String bindIp) {
|
||||
String pidFile = relayPidFile(name);
|
||||
List<String> lines = new ArrayList<>(IS_SOCAT_LISTENER);
|
||||
lines.add(socatPidCheck(pidFile, "TCP-LISTEN:80,bind=" + bindIp + ","));
|
||||
lines.add(" kill \"$pid\" 2>/dev/null || true");
|
||||
lines.add("fi");
|
||||
lines.add("rm -f " + pidFile);
|
||||
lines.add("if command -v ip >/dev/null 2>&1 && ip addr show dev lo | grep -q '" + bindIp + "/32'; then");
|
||||
lines.add(" ip addr del " + bindIp + "/32 dev lo");
|
||||
lines.add("fi");
|
||||
return lines;
|
||||
}
|
||||
|
||||
private static String relayPidFile(String name) {
|
||||
return "/tmp/floci-" + name + "-proxy.pid";
|
||||
}
|
||||
|
||||
private static String socatPidCheck(String pidFile, String listener) {
|
||||
return "if [ -f " + pidFile + " ] && pid=\"$(cat " + pidFile + ")\""
|
||||
+ " && is_socat_listener \"$pid\" '" + listener + "'; then";
|
||||
|
||||
@@ -8,6 +8,7 @@ import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.EpochSeconds;
|
||||
import io.floci.aws.core.common.PaginatedResult;
|
||||
import io.floci.aws.core.common.Pagination;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.StorageBackend;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
import io.floci.aws.services.eks.model.Addon;
|
||||
@@ -182,6 +183,19 @@ public class EksAddonService {
|
||||
return stored.addon();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether {@code cluster} has the add-on stored, whatever the cluster's status: what its node
|
||||
* acts on when it starts or is adopted, which can happen while the cluster is not ACTIVE.
|
||||
*/
|
||||
public boolean isInstalled(Cluster cluster, String addonName) {
|
||||
if (cluster == null || addonName == null || addonName.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
// Read in the cluster's account, not the request's: restoring a cluster at startup asks with no request.
|
||||
return AccountAwareStorageBackend.getInAccount(storage, AwsArnUtils.parse(cluster.getArn()).accountId(),
|
||||
prefix(cluster) + addonName.trim().toLowerCase(Locale.ROOT)).isPresent();
|
||||
}
|
||||
|
||||
public AddonNamesPage list(Cluster cluster, Integer maxResults, String nextToken) {
|
||||
requireActiveCluster(cluster);
|
||||
String p = prefix(cluster);
|
||||
|
||||
@@ -13,6 +13,7 @@ import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.AwsRegions;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.StripedLocks;
|
||||
import io.floci.aws.core.common.dns.DnsAnswer;
|
||||
import io.floci.aws.core.common.dns.DnsClientVpcSource;
|
||||
import io.floci.aws.core.common.dns.DnsClientVpcSource.ClientVpc;
|
||||
@@ -193,9 +194,14 @@ public class EksClusterManager
|
||||
@Inject
|
||||
jakarta.enterprise.inject.Instance<Ec2Service> ec2ServiceInstance;
|
||||
private Ec2Service ec2Service;
|
||||
/** Looked up on use, as {@link #ec2ServiceInstance} is, since the add-ons are read only then. */
|
||||
@Inject
|
||||
jakarta.enterprise.inject.Instance<EksAddonService> addonServiceInstance;
|
||||
private EksAddonService addonService;
|
||||
private final StorageBackend<String, Nodegroup> nodeGroupStorage;
|
||||
private final Map<String, Set<String>> programmedClusterRoutes = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, Object> clusterRouteLocks = new ConcurrentHashMap<>();
|
||||
private final StripedLocks podIdentityForwardLocks = new StripedLocks(256);
|
||||
private record VpcLease(String accountId, String region, String vpcId, String subnetId, String address) {}
|
||||
private record ClusterVpcSubnet(String vpcId, String subnetId) {}
|
||||
private final Map<String, VpcLease> clusterVpcLeases = new ConcurrentHashMap<>();
|
||||
@@ -309,6 +315,20 @@ public class EksClusterManager
|
||||
}
|
||||
}
|
||||
|
||||
void setAddonService(EksAddonService addonService) {
|
||||
this.addonService = addonService;
|
||||
}
|
||||
|
||||
private EksAddonService addonService() {
|
||||
if (addonService != null) {
|
||||
return addonService;
|
||||
}
|
||||
if (addonServiceInstance != null && !addonServiceInstance.isUnsatisfied()) {
|
||||
return addonServiceInstance.get();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public void addNodeRegistrationListener(Consumer<Instance> listener) {
|
||||
this.nodeRegistrationListeners.add(listener);
|
||||
}
|
||||
@@ -1006,7 +1026,7 @@ public class EksClusterManager
|
||||
applyEndpoints(cluster, containerName, hostPort, info, endpointHost);
|
||||
registerClusterNodeInstance(cluster, containerId);
|
||||
configureLinkLocalMetadataEndpoint(cluster, containerId);
|
||||
configurePodIdentityRelay(cluster, containerId);
|
||||
configurePodIdentityForward(cluster, containerId);
|
||||
activeClusters.put(clusterResourceName(cluster), cluster);
|
||||
configureVpcRoutes(cluster, containerId);
|
||||
attachClusterLogs(cluster);
|
||||
@@ -1115,7 +1135,7 @@ public class EksClusterManager
|
||||
}
|
||||
registerClusterNodeInstance(cluster, info.containerId());
|
||||
configureLinkLocalMetadataEndpoint(cluster, info.containerId());
|
||||
configurePodIdentityRelay(cluster, info.containerId());
|
||||
configurePodIdentityForward(cluster, info.containerId());
|
||||
activeClusters.put(clusterResourceName(cluster), cluster);
|
||||
configureVpcRoutes(cluster, info.containerId());
|
||||
attachClusterLogsFromNow(cluster);
|
||||
@@ -2778,35 +2798,100 @@ public class EksClusterManager
|
||||
}
|
||||
}
|
||||
|
||||
void configurePodIdentityRelay(Cluster cluster, String containerId) {
|
||||
if (!config.services().eks().podIdentityWebhook() || !config.tls().enabled()) {
|
||||
return;
|
||||
/**
|
||||
* Makes the EKS Pod Identity address, {@code 169.254.170.23:80}, answer in the node while the
|
||||
* {@code eks-pod-identity-agent} add-on is stored, as the agent's DaemonSet answers it on EKS
|
||||
* while the add-on is installed, and removes the forward otherwise, including one an earlier
|
||||
* Floci left. Runs whenever the node starts or is adopted, so a restart forwards only while the
|
||||
* add-on is stored: one deleted with {@code preserve}, whose agent EKS would leave running,
|
||||
* keeps its forward until then.
|
||||
*
|
||||
* <p>NAT rules send pod and node requests for the address straight to Floci's credentials
|
||||
* endpoint (see {@link EksPodNetworkRouting#buildPodIdentityForwardCommand}). No relay process
|
||||
* runs in the node, so nothing has to be installed there, which a stock {@code rancher/k3s}
|
||||
* image could not do.
|
||||
*/
|
||||
void configurePodIdentityForward(Cluster cluster, String containerId) {
|
||||
if (podIdentityForwardEnabled()) {
|
||||
reconcilePodIdentityForward(cluster, containerId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* CreateAddon stored, or DeleteAddon without {@code preserve} removed, the
|
||||
* {@code eks-pod-identity-agent} add-on of {@code cluster}: its node answers on the Pod Identity
|
||||
* address while the add-on is stored. A cluster without a node, as when EKS is mocked, is left
|
||||
* alone.
|
||||
*/
|
||||
public void podIdentityAgentChanged(Cluster cluster) {
|
||||
if (podIdentityForwardEnabled() && cluster.getContainerId() != null) {
|
||||
reconcilePodIdentityForward(cluster, cluster.getContainerId());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Forwards the address while the add-on is stored and removes the forward otherwise, reading the
|
||||
* store under the cluster's lock: of a CreateAddon and a DeleteAddon racing, or of either and a
|
||||
* restart's adoption, the later waits for the earlier's exec and then reads the store, so the node
|
||||
* ends as the store does. A store that can't be read leaves the node as it is.
|
||||
*/
|
||||
private void reconcilePodIdentityForward(Cluster cluster, String containerId) {
|
||||
synchronized (podIdentityForwardLocks.lockFor(clusterResourceName(cluster))) {
|
||||
boolean installed;
|
||||
try {
|
||||
installed = podIdentityAgentInstalled(cluster);
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv("Could not read the {0} add-on of EKS cluster {1}, leaving its Pod Identity address as it is: {2}",
|
||||
EksPodIdentityWebhook.POD_IDENTITY_ADDON, cluster.getName(), e.getMessage());
|
||||
return;
|
||||
}
|
||||
if (installed) {
|
||||
forwardPodIdentityAddress(cluster, containerId);
|
||||
} else {
|
||||
removePodIdentityForward(cluster, containerId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Pods only get the Pod Identity credentials URL through the webhook, which needs TLS. */
|
||||
private boolean podIdentityForwardEnabled() {
|
||||
return config.services().eks().podIdentityWebhook() && config.tls().enabled();
|
||||
}
|
||||
|
||||
private boolean podIdentityAgentInstalled(Cluster cluster) {
|
||||
EksAddonService addons = addonService();
|
||||
return addons != null && addons.isInstalled(cluster, EksPodIdentityWebhook.POD_IDENTITY_ADDON);
|
||||
}
|
||||
|
||||
private void forwardPodIdentityAddress(Cluster cluster, String containerId) {
|
||||
try {
|
||||
ContainerExec.Result install = execInContainerForResult(containerId,
|
||||
Ec2MetadataProxy.installCommand(), 180);
|
||||
if (install.exitCode() != 0) {
|
||||
LOG.warnv("Could not install Pod Identity relay dependencies for EKS cluster {0}: {1}",
|
||||
cluster.getName(), install.summary());
|
||||
ContainerExec.Result forward = execInContainerForResult(containerId,
|
||||
EksPodNetworkRouting.buildPodIdentityForwardCommand(cluster.getPodCidr(),
|
||||
dockerHostResolver.resolve(), config.port()), 30);
|
||||
if (forward.exitCode() != 0) {
|
||||
LOG.warnv("Could not forward the Pod Identity address for EKS cluster {0} to Floci: {1}",
|
||||
cluster.getName(), forward.summary());
|
||||
return;
|
||||
}
|
||||
|
||||
String flociHost = dockerHostResolver.resolve();
|
||||
int flociPort = config.port();
|
||||
|
||||
ContainerExec.Result start = execInContainerForResult(containerId,
|
||||
Ec2MetadataProxy.podIdentityStartCommand(flociHost, flociPort), 30);
|
||||
if (start.exitCode() != 0) {
|
||||
LOG.warnv("Could not start link-local Pod Identity relay for EKS cluster {0}: {1}",
|
||||
cluster.getName(), start.summary());
|
||||
return;
|
||||
}
|
||||
|
||||
configurePodNetworkRouting(cluster, containerId, List.of(EksPodNetworkRouting.POD_IDENTITY_ENDPOINT));
|
||||
|
||||
LOG.infov("Configured link-local Pod Identity relay for EKS cluster {0}", cluster.getName());
|
||||
LOG.infov("Forwarding the Pod Identity address {0}:{1,number,#} to Floci for EKS cluster {2}",
|
||||
EksPodNetworkRouting.POD_IDENTITY_ENDPOINT.ip(), EksPodNetworkRouting.POD_IDENTITY_ENDPOINT.port(),
|
||||
cluster.getName());
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Could not configure link-local Pod Identity relay for EKS cluster {0}: {1}",
|
||||
LOG.warnv("Could not forward the Pod Identity address for EKS cluster {0} to Floci: {1}",
|
||||
cluster.getName(), e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void removePodIdentityForward(Cluster cluster, String containerId) {
|
||||
try {
|
||||
ContainerExec.Result removal = execInContainerForResult(containerId,
|
||||
EksPodNetworkRouting.buildPodIdentityRemoveCommand(), 15);
|
||||
if (removal.exitCode() != 0) {
|
||||
LOG.warnv("Could not remove the Pod Identity forward for EKS cluster {0}: {1}",
|
||||
cluster.getName(), removal.summary());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Could not remove the Pod Identity forward for EKS cluster {0}: {1}",
|
||||
cluster.getName(), e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,16 +64,18 @@ public class EksController {
|
||||
private final EksPodIdentityAssociationService podIdentityAssociations;
|
||||
private final EksAddonService addons;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final EksClusterManager clusterManager;
|
||||
|
||||
@Inject
|
||||
public EksController(EksService eksService, EksAccessEntryService accessEntries,
|
||||
EksPodIdentityAssociationService podIdentityAssociations,
|
||||
EksAddonService addons, ObjectMapper objectMapper) {
|
||||
EksAddonService addons, ObjectMapper objectMapper, EksClusterManager clusterManager) {
|
||||
this.eksService = eksService;
|
||||
this.accessEntries = accessEntries;
|
||||
this.podIdentityAssociations = podIdentityAssociations;
|
||||
this.addons = addons;
|
||||
this.objectMapper = objectMapper;
|
||||
this.clusterManager = clusterManager;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -302,6 +304,10 @@ public class EksController {
|
||||
public Response createAddon(@PathParam("name") String name, CreateAddonRequest request) {
|
||||
Cluster cluster = eksService.requireClusterInRequestRegion(name);
|
||||
Addon addon = addons.create(cluster, request);
|
||||
// After the add-on is stored and outside the add-on service's lock: the node is changed by an exec.
|
||||
if (isPodIdentityAgent(addon)) {
|
||||
clusterManager.podIdentityAgentChanged(cluster);
|
||||
}
|
||||
return Response.ok(Map.of("addon", addon)).build();
|
||||
}
|
||||
|
||||
@@ -355,6 +361,10 @@ public class EksController {
|
||||
@QueryParam("preserve") Boolean preserve) {
|
||||
Cluster cluster = eksService.requireClusterInRequestRegion(name);
|
||||
Addon addon = addons.delete(cluster, addonName, Boolean.TRUE.equals(preserve));
|
||||
// With preserve, EKS leaves the add-on's software running on the cluster, and so its answers.
|
||||
if (isPodIdentityAgent(addon) && !Boolean.TRUE.equals(preserve)) {
|
||||
clusterManager.podIdentityAgentChanged(cluster);
|
||||
}
|
||||
return Response.ok(Map.of("addon", addon)).build();
|
||||
}
|
||||
|
||||
@@ -439,4 +449,8 @@ public class EksController {
|
||||
PodIdentityAssociation association = podIdentityAssociations.delete(cluster, associationId);
|
||||
return Response.ok(Map.of("association", association)).build();
|
||||
}
|
||||
|
||||
private static boolean isPodIdentityAgent(Addon addon) {
|
||||
return EksPodIdentityWebhook.POD_IDENTITY_ADDON.equalsIgnoreCase(addon.addonName());
|
||||
}
|
||||
}
|
||||
@@ -30,8 +30,9 @@ import java.util.function.Supplier;
|
||||
* SDK at Floci with {@code AWS_ENDPOINT_URL} and {@code AWS_ENDPOINT_URL_STS}, as it does for every
|
||||
* container it launches itself: otherwise the pod's calls, signed with Floci credentials, go to AWS.
|
||||
*
|
||||
* <p>Nothing answers {@link #CREDENTIALS_FULL_URI} yet: this class injects the plumbing only, so an
|
||||
* injected pod still cannot obtain credentials.
|
||||
* <p>This class injects the plumbing only. {@link #CREDENTIALS_FULL_URI} answers while the addon is
|
||||
* installed: {@link EksClusterManager} forwards its address in the node to
|
||||
* {@link EksPodIdentityCredentialsController}, which hands the pod its association's credentials.
|
||||
*
|
||||
* <p>Every path here admits the pod. A cluster that is gone, an addon that is not installed, a
|
||||
* malformed review and an internal error all return {@code allowed: true} with no patch, which is
|
||||
@@ -165,14 +166,12 @@ public class EksPodIdentityWebhook {
|
||||
}
|
||||
|
||||
private boolean podIdentityAgentInstalled(Cluster cluster) {
|
||||
try {
|
||||
addons.describe(cluster, POD_IDENTITY_ADDON);
|
||||
if (addons.isInstalled(cluster, POD_IDENTITY_ADDON)) {
|
||||
return true;
|
||||
} catch (AwsException e) {
|
||||
LOG.debugv("EKS pod-identity-webhook: cluster {0} has no {1} addon, admitting pods unchanged ({2})",
|
||||
cluster.getName(), POD_IDENTITY_ADDON, e.getMessage());
|
||||
return false;
|
||||
}
|
||||
LOG.debugv("EKS pod-identity-webhook: cluster {0} has no {1} addon, admitting pods unchanged",
|
||||
cluster.getName(), POD_IDENTITY_ADDON);
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean hasAssociation(Cluster cluster, String namespace, String serviceAccount) {
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
package io.floci.aws.services.eks;
|
||||
|
||||
import io.floci.aws.services.ec2.Ec2MetadataProxy;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Generates iptables routing rules for link-local endpoints inside an EKS cluster container.
|
||||
* <p>
|
||||
* Programs DNAT rules in the node network namespace nat table so traffic originating
|
||||
* from the cluster pod CIDR directed at link-local addresses (such as IMDS 169.254.169.254:80
|
||||
* and EKS Pod Identity 169.254.170.23:80) reaches Floci's node listener rather than being
|
||||
* dropped by the Linux kernel or hijacked by CNI hostPort ingress rules.
|
||||
* from the cluster pod CIDR directed at a link-local address (such as IMDS 169.254.169.254:80)
|
||||
* reaches Floci's node listener rather than being dropped by the Linux kernel or hijacked by CNI
|
||||
* hostPort ingress rules. The EKS Pod Identity address, 169.254.170.23:80, is sent straight to
|
||||
* Floci's credentials endpoint instead, by {@link #buildPodIdentityForwardCommand}.
|
||||
*/
|
||||
public final class EksPodNetworkRouting {
|
||||
|
||||
@@ -18,6 +22,12 @@ public final class EksPodNetworkRouting {
|
||||
public static final LinkLocalEndpoint IMDS_ENDPOINT = new LinkLocalEndpoint("169.254.169.254", 80);
|
||||
public static final LinkLocalEndpoint POD_IDENTITY_ENDPOINT = new LinkLocalEndpoint("169.254.170.23", 80);
|
||||
public static final List<LinkLocalEndpoint> DEFAULT_ENDPOINTS = List.of(IMDS_ENDPOINT);
|
||||
private static final String HOSTS_FILE = "/etc/hosts";
|
||||
private static final Pattern IPV4_CIDR = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3}/\\d{1,2}");
|
||||
/** A hostname or IPv4 address: nothing a shell or an iptables argument could read as more. */
|
||||
private static final Pattern HOST = Pattern.compile("[A-Za-z0-9]([A-Za-z0-9._-]{0,251}[A-Za-z0-9])?");
|
||||
/** A path a single-quoted shell word can hold as it is. */
|
||||
private static final Pattern ABSOLUTE_PATH = Pattern.compile("/[A-Za-z0-9._/-]*");
|
||||
|
||||
private EksPodNetworkRouting() {}
|
||||
|
||||
@@ -35,13 +45,7 @@ public final class EksPodNetworkRouting {
|
||||
throw new IllegalArgumentException("endpoints cannot be null or empty");
|
||||
}
|
||||
|
||||
List<String> lines = new ArrayList<>();
|
||||
lines.add("set -eu");
|
||||
lines.add("IPTABLES=$(command -v iptables 2>/dev/null || command -v /bin/aux/iptables 2>/dev/null || true)");
|
||||
lines.add("if [ -z \"$IPTABLES\" ]; then");
|
||||
lines.add(" echo 'iptables not found in container' >&2");
|
||||
lines.add(" exit 1");
|
||||
lines.add("fi");
|
||||
List<String> lines = iptablesLines(true);
|
||||
lines.add("$IPTABLES -t nat -N " + CHAIN_NAME + " 2>/dev/null || true");
|
||||
lines.add("$IPTABLES -t nat -C PREROUTING -j " + CHAIN_NAME + " 2>/dev/null || $IPTABLES -t nat -I PREROUTING 1 -j " + CHAIN_NAME);
|
||||
|
||||
@@ -57,4 +61,144 @@ public final class EksPodNetworkRouting {
|
||||
|
||||
return new String[]{"sh", "-c", String.join("\n", lines)};
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a POSIX sh command array that sends the EKS Pod Identity address
|
||||
* ({@code 169.254.170.23:80}) straight to Floci's credentials endpoint with NAT rules in the
|
||||
* node, so no relay process has to run there. The stock {@code rancher/k3s} image has
|
||||
* {@code iptables} (under {@code /bin/aux}) but neither {@code socat}, {@code curl} nor a
|
||||
* package manager to install them.
|
||||
*
|
||||
* <p>A {@code PREROUTING} rule takes the pod network's requests and an {@code OUTPUT} rule
|
||||
* those of the node itself, which is where a {@code hostNetwork} pod's come from. The node's
|
||||
* own masquerade rule (flannel's) carries the answers back. What an earlier Floci set up for the
|
||||
* address is removed first, as {@link #buildPodIdentityRemoveCommand} removes it, so a Floci that
|
||||
* comes back on another address leaves no rule behind, and a node an older Floci gave a relay ends
|
||||
* as a new node does.
|
||||
*
|
||||
* <p>iptables needs an address, so a {@code flociHost} name is resolved inside the node, as
|
||||
* its pods resolve it: from {@code /etc/hosts} (where {@code host.docker.internal} lives on
|
||||
* Linux), else through DNS. The command ends with a probe and fails if nothing answers.
|
||||
*
|
||||
* @param podCidr pod network CIDR (defaults to {@link #DEFAULT_POD_CIDR} if null or blank)
|
||||
* @param flociHost the address or hostname the node reaches Floci on
|
||||
* @param flociPort Floci's port
|
||||
* @return command array suitable for container exec (["sh", "-c", "..."])
|
||||
*/
|
||||
public static String[] buildPodIdentityForwardCommand(String podCidr, String flociHost, int flociPort) {
|
||||
return buildPodIdentityForwardCommand(podCidr, flociHost, flociPort, HOSTS_FILE);
|
||||
}
|
||||
|
||||
/** As above, reading host names from {@code hostsFile} rather than {@code /etc/hosts}. */
|
||||
static String[] buildPodIdentityForwardCommand(String podCidr, String flociHost, int flociPort, String hostsFile) {
|
||||
String cidr = (podCidr != null && !podCidr.isBlank()) ? podCidr.trim() : DEFAULT_POD_CIDR;
|
||||
if (!IPV4_CIDR.matcher(cidr).matches()) {
|
||||
throw new IllegalArgumentException("podCidr must be an IPv4 CIDR: " + podCidr);
|
||||
}
|
||||
if (flociHost == null || !HOST.matcher(flociHost).matches()) {
|
||||
throw new IllegalArgumentException("flociHost must be an IPv4 address or a hostname: " + flociHost);
|
||||
}
|
||||
if (flociPort <= 0 || flociPort > 65535) {
|
||||
throw new IllegalArgumentException("flociPort must be between 1 and 65535");
|
||||
}
|
||||
if (hostsFile == null || !ABSOLUTE_PATH.matcher(hostsFile).matches()) {
|
||||
throw new IllegalArgumentException("hostsFile must be an absolute path: " + hostsFile);
|
||||
}
|
||||
String address = POD_IDENTITY_ENDPOINT.ip();
|
||||
String match = "-d " + address + "/32 -p tcp --dport " + POD_IDENTITY_ENDPOINT.port();
|
||||
|
||||
List<String> lines = iptablesLines(true);
|
||||
lines.add("HOST='" + flociHost + "'");
|
||||
lines.add("ADDR=");
|
||||
lines.add("case \"$HOST\" in");
|
||||
lines.add(" *[!0-9.]*)");
|
||||
lines.add(" ADDR=$(awk -v h=\"$HOST\" '!/^[[:space:]]*#/ { for (i = 2; i <= NF; i++) if ($i == h) { print $1; exit } }'"
|
||||
+ " '" + hostsFile + "' 2>/dev/null || true)");
|
||||
lines.add(" case \"$ADDR\" in");
|
||||
lines.add(" ''|*[!0-9.]*) ADDR=$(nslookup \"$HOST\" 2>/dev/null"
|
||||
+ " | awk '/^Address/ && $NF ~ /^[0-9]+[.][0-9]+[.][0-9]+[.][0-9]+$/ { a = $NF } END { print a }' || true) ;;");
|
||||
lines.add(" esac ;;");
|
||||
lines.add(" *) ADDR=$HOST ;;");
|
||||
lines.add("esac");
|
||||
lines.add("if [ -z \"$ADDR\" ]; then");
|
||||
lines.add(" echo \"cannot resolve $HOST to an IPv4 address\" >&2");
|
||||
lines.add(" exit 1");
|
||||
lines.add("fi");
|
||||
lines.add("TARGET=\"$ADDR:" + flociPort + "\"");
|
||||
addPodIdentityRuleRemoval(lines);
|
||||
lines.add("$IPTABLES -t nat -I PREROUTING 1 -s " + cidr + " " + match + " -j DNAT --to-destination \"$TARGET\"");
|
||||
lines.add("$IPTABLES -t nat -I OUTPUT 1 " + match + " -j DNAT --to-destination \"$TARGET\"");
|
||||
lines.add("for i in 1 2 3 4 5 6; do");
|
||||
lines.add(" " + podIdentityProbeCommand("http://" + address));
|
||||
lines.add(" sleep 1");
|
||||
lines.add("done");
|
||||
lines.add("echo \"nothing answers on " + address + " through $TARGET\" >&2");
|
||||
lines.add("exit 1");
|
||||
return new String[]{"sh", "-c", String.join("\n", lines)};
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a POSIX sh command array that removes the rules {@link #buildPodIdentityForwardCommand}
|
||||
* adds, any an earlier Floci added for the address, and the relay an older Floci ran for it, so
|
||||
* that nothing answers on it, as on an EKS node without the Pod Identity agent. A node without
|
||||
* {@code iptables} has no such rules, so the command succeeds there.
|
||||
*
|
||||
* @return command array suitable for container exec (["sh", "-c", "..."])
|
||||
*/
|
||||
public static String[] buildPodIdentityRemoveCommand() {
|
||||
List<String> lines = iptablesLines(false);
|
||||
addPodIdentityRuleRemoval(lines);
|
||||
return new String[]{"sh", "-c", String.join("\n", lines)};
|
||||
}
|
||||
|
||||
/**
|
||||
* Ready once the pod identity endpoint answers at all: without a pod's token Floci answers 400,
|
||||
* which still proves the path reaches it. Any HTTP proxy the image configures is bypassed, since
|
||||
* a proxy's own answer would pass the same check. Uses {@code curl} where there is one, else
|
||||
* {@code wget}, as in a stock {@code rancher/k3s} node, which has BusyBox's and no {@code curl}:
|
||||
* both print the status of an error answer, which is what is looked for.
|
||||
*/
|
||||
static String podIdentityProbeCommand(String endpoint) {
|
||||
String url = endpoint + "/v1/credentials";
|
||||
return "if command -v curl >/dev/null 2>&1; then"
|
||||
+ " [ \"$(curl -s --noproxy '*' -o /dev/null -w '%{http_code}' --max-time 1 " + url + ")\" != \"000\" ]"
|
||||
+ " && exit 0;"
|
||||
+ " else env -u http_proxy -u HTTP_PROXY wget -T 1 -O /dev/null " + url + " 2>&1"
|
||||
+ " | grep -qE 'HTTP/1[.][01] [0-9]{3}|ERROR [0-9]{3}' && exit 0;"
|
||||
+ " fi";
|
||||
}
|
||||
|
||||
/**
|
||||
* The start of every command here: strict mode and {@code IPTABLES}, found on the path or
|
||||
* where a stock {@code rancher/k3s} image keeps it. Without one, the command fails when it
|
||||
* has rules to add, and ends successfully when it only removes them.
|
||||
*/
|
||||
private static List<String> iptablesLines(boolean required) {
|
||||
List<String> lines = new ArrayList<>();
|
||||
lines.add("set -eu");
|
||||
lines.add("IPTABLES=$(command -v iptables 2>/dev/null || command -v /bin/aux/iptables 2>/dev/null || true)");
|
||||
lines.add("if [ -z \"$IPTABLES\" ]; then");
|
||||
if (required) {
|
||||
lines.add(" echo 'iptables not found in container' >&2");
|
||||
lines.add(" exit 1");
|
||||
} else {
|
||||
lines.add(" exit 0");
|
||||
}
|
||||
lines.add("fi");
|
||||
return lines;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes each rule for the Pod Identity address in {@code PREROUTING} and {@code OUTPUT}, and in
|
||||
* {@link #CHAIN_NAME}, where an older Floci sent it to the relay it ran in the node, then retires that relay.
|
||||
* The relay would otherwise answer again once the rules in front of it go.
|
||||
*/
|
||||
private static void addPodIdentityRuleRemoval(List<String> lines) {
|
||||
lines.add("for CHAIN in PREROUTING OUTPUT " + CHAIN_NAME + "; do");
|
||||
lines.add(" $IPTABLES -t nat -S \"$CHAIN\" 2>/dev/null | grep -F -- '-d " + POD_IDENTITY_ENDPOINT.ip() + "/32 '"
|
||||
+ " | grep -F -- '--dport " + POD_IDENTITY_ENDPOINT.port() + " '"
|
||||
+ " | sed 's/^-A /-D /' | while read -r rule; do $IPTABLES -t nat $rule; done");
|
||||
lines.add("done");
|
||||
lines.addAll(Ec2MetadataProxy.stopRelayLines("pod-identity", POD_IDENTITY_ENDPOINT.ip()));
|
||||
}
|
||||
}
|
||||
@@ -44,6 +44,7 @@ import io.floci.aws.services.ec2.model.InstanceState;
|
||||
import io.floci.aws.services.ec2.net.VpcNetworkManager;
|
||||
import io.floci.aws.services.ec2.portforward.Ec2PortForwardManager;
|
||||
import io.floci.aws.services.ec2instanceconnect.InstanceConnectKeys;
|
||||
import io.floci.aws.testing.HelperShellFixture;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
@@ -4,6 +4,7 @@ import com.github.dockerjava.api.model.ContainerNetwork;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import io.floci.aws.services.ec2.model.Instance;
|
||||
import io.floci.aws.services.ec2.model.LaunchTemplateData;
|
||||
import io.floci.aws.testing.HelperShellFixture;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
@@ -43,8 +44,7 @@ class Ec2MetadataProxyTest {
|
||||
Ec2MetadataProxy.installCommand(),
|
||||
Ec2MetadataProxy.installEc2Command(),
|
||||
Ec2MetadataProxy.startCommand("10.0.0.1", 9169),
|
||||
Ec2MetadataProxy.startEc2Command("10.0.0.1", 9169),
|
||||
Ec2MetadataProxy.podIdentityStartCommand("10.0.0.1", 4566)}) {
|
||||
Ec2MetadataProxy.startEc2Command("10.0.0.1", 9169)}) {
|
||||
assertTrue(command[2].startsWith("set -eu\n" + prelude + "\n"), command[2]);
|
||||
}
|
||||
}
|
||||
@@ -152,21 +152,6 @@ class Ec2MetadataProxyTest {
|
||||
assertFalse(script.contains("remove_nft_rule floci-imds-relay-42169"), script);
|
||||
}
|
||||
|
||||
@Test
|
||||
void podIdentityStartCommandAttachesAddressIdempotentlyAndTargetsHostAndPort() {
|
||||
String[] command = Ec2MetadataProxy.podIdentityStartCommand("10.0.0.1", 4566);
|
||||
assertEquals(3, command.length);
|
||||
assertEquals("sh", command[0]);
|
||||
assertEquals("-c", command[1]);
|
||||
|
||||
String script = command[2];
|
||||
assertTrue(script.contains("ip addr show dev lo | grep -q '169.254.170.23/32' || ip addr add 169.254.170.23/32 dev lo"));
|
||||
assertTrue(script.contains("is_socat_listener \"$pid\" 'TCP-LISTEN:80,bind=169.254.170.23,'; then"
|
||||
+ "\n exit 0\nfi"), script);
|
||||
assertTrue(script.contains("nohup socat TCP-LISTEN:80,bind=169.254.170.23,fork,reuseaddr TCP:10.0.0.1:4566 >/tmp/floci-pod-identity-proxy.log 2>&1 &"));
|
||||
assertTrue(script.contains("http://169.254.170.23/v1/credentials"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void preferredMetadataSourceIpPrefersConfiguredNetworkOverBridge() {
|
||||
ContainerNetwork bridge = new ContainerNetwork();
|
||||
@@ -420,12 +405,12 @@ class Ec2MetadataProxyTest {
|
||||
@Test
|
||||
void readinessProbeIgnoresTheImagesHttpProxy(@TempDir Path directory) throws Exception {
|
||||
List<String> proxied = new CopyOnWriteArrayList<>();
|
||||
HttpServer proxy = failingProxy(proxied);
|
||||
HttpServer proxy = HelperShellFixture.failingProxy(proxied);
|
||||
try (Ec2MetadataTestFixture fixture = new Ec2MetadataTestFixture()) {
|
||||
fixture.start();
|
||||
requireTokens(fixture.instance());
|
||||
|
||||
int result = HelperShellFixture.run(probe(fixture.endpoint()), directory, proxyEnvironment(proxy));
|
||||
int result = HelperShellFixture.run(probe(fixture.endpoint()), directory, HelperShellFixture.proxyEnvironment(proxy));
|
||||
|
||||
assertEquals(0, result, HelperShellFixture.output(directory));
|
||||
assertEquals(List.of(), proxied);
|
||||
@@ -434,44 +419,6 @@ class Ec2MetadataProxyTest {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
@@ -616,24 +563,6 @@ class Ec2MetadataProxyTest {
|
||||
}
|
||||
|
||||
/** 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)};
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import io.floci.aws.services.ec2.model.Instance;
|
||||
import io.floci.aws.services.ec2.model.InstanceState;
|
||||
import io.floci.aws.services.ec2.model.Volume;
|
||||
import io.floci.aws.services.ec2.model.VolumeAttachment;
|
||||
import io.floci.aws.testing.HelperShellFixture;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
@@ -1,74 +0,0 @@
|
||||
package io.floci.aws.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"));
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
package io.floci.aws.services.eks;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.mockito.InjectSpy;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -18,6 +20,45 @@ class EksAddonIntegrationTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
|
||||
@InjectSpy
|
||||
EksClusterManager clusterManager;
|
||||
|
||||
/**
|
||||
* The Pod Identity address answers while the agent add-on is installed: CreateAddon starts it and
|
||||
* DeleteAddon stops it, except with preserve, which leaves the agent running on EKS. Other add-ons
|
||||
* leave it alone.
|
||||
*/
|
||||
@Test
|
||||
void thePodIdentityAgentsAddressFollowsItsAddon() {
|
||||
String account = "123456789012";
|
||||
String name = "addon-agent-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
String basePath = "/clusters/" + name + "/addons";
|
||||
createCluster(account, name, "1.30");
|
||||
try {
|
||||
for (String addon : List.of("eks-pod-identity-agent", "coredns")) {
|
||||
given().header("Authorization", auth(account, "eks")).contentType("application/json")
|
||||
.body(Map.of("addonName", addon)).post(basePath).then().statusCode(200);
|
||||
}
|
||||
Mockito.verify(clusterManager, Mockito.times(1))
|
||||
.podIdentityAgentChanged(Mockito.argThat(cluster -> name.equals(cluster.getName())));
|
||||
|
||||
given().header("Authorization", auth(account, "eks")).queryParam("preserve", true)
|
||||
.delete(basePath + "/eks-pod-identity-agent").then().statusCode(200);
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.delete(basePath + "/coredns").then().statusCode(200);
|
||||
Mockito.verify(clusterManager, Mockito.times(1)).podIdentityAgentChanged(Mockito.any());
|
||||
|
||||
given().header("Authorization", auth(account, "eks")).contentType("application/json")
|
||||
.body(Map.of("addonName", "eks-pod-identity-agent")).post(basePath).then().statusCode(200);
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.delete(basePath + "/eks-pod-identity-agent").then().statusCode(200);
|
||||
Mockito.verify(clusterManager, Mockito.times(3))
|
||||
.podIdentityAgentChanged(Mockito.argThat(cluster -> name.equals(cluster.getName())));
|
||||
} finally {
|
||||
deleteCluster(account, name);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void addonLifecycleRoundTrip() {
|
||||
String account = "123456789012";
|
||||
|
||||
@@ -4,6 +4,8 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.RequestContext;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.InMemoryStorage;
|
||||
import io.floci.aws.services.eks.model.Addon;
|
||||
import io.floci.aws.services.eks.model.AddonInfo;
|
||||
@@ -16,6 +18,7 @@ import io.floci.aws.services.eks.model.Update;
|
||||
import io.floci.aws.services.eks.model.UpdateAddonRequest;
|
||||
import io.floci.aws.services.iam.IamService;
|
||||
import io.floci.aws.services.iam.model.IamRole;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
@@ -258,6 +261,59 @@ class EksAddonServiceTest {
|
||||
fixture.service.delete(fixture.cluster, "kube-proxy", false));
|
||||
}
|
||||
|
||||
/** The node asks whether the agent is stored when it starts, which can be while the cluster is not ACTIVE. */
|
||||
@Test
|
||||
void anAddonIsInstalledWhileItIsStoredWhateverTheClustersStatus() {
|
||||
Fixture fixture = fixture();
|
||||
fixture.cluster.setVersion("1.29");
|
||||
fixture.service.create(fixture.cluster, new CreateAddonRequest(
|
||||
"eks-pod-identity-agent", null, null, null, null, null, null, null));
|
||||
Cluster sameName = new Cluster();
|
||||
sameName.setName("test-cluster");
|
||||
sameName.setArn(fixture.cluster.getArn());
|
||||
sameName.setCreatedAt(Instant.parse("2026-09-21T12:00:00Z"));
|
||||
|
||||
assertTrue(fixture.service.isInstalled(fixture.cluster, "eks-pod-identity-agent"));
|
||||
assertTrue(fixture.service.isInstalled(fixture.cluster, " EKS-Pod-Identity-Agent "));
|
||||
assertFalse(fixture.service.isInstalled(fixture.cluster, "coredns"));
|
||||
assertFalse(fixture.service.isInstalled(fixture.cluster, null));
|
||||
assertFalse(fixture.service.isInstalled(null, "eks-pod-identity-agent"));
|
||||
// A cluster recreated under the same name starts without the earlier one's add-ons.
|
||||
assertFalse(fixture.service.isInstalled(sameName, "eks-pod-identity-agent"));
|
||||
|
||||
fixture.cluster.setStatus(ClusterStatus.UPDATING);
|
||||
assertTrue(fixture.service.isInstalled(fixture.cluster, "eks-pod-identity-agent"));
|
||||
|
||||
fixture.cluster.setStatus(ClusterStatus.ACTIVE);
|
||||
fixture.service.delete(fixture.cluster, "eks-pod-identity-agent", false);
|
||||
assertFalse(fixture.service.isInstalled(fixture.cluster, "eks-pod-identity-agent"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Restoring a cluster at startup asks whether an add-on is installed with no request, so the request context
|
||||
* holds the default account; the add-on is still found in the cluster's account.
|
||||
*/
|
||||
@Test
|
||||
void anAddonIsFoundInTheClustersAccountWhateverTheRequestsAccount() {
|
||||
RequestContext request = new RequestContext();
|
||||
@SuppressWarnings("unchecked")
|
||||
Instance<RequestContext> context = mock(Instance.class);
|
||||
when(context.get()).thenReturn(request);
|
||||
AccountAwareStorageBackend<EksAddonService.StoredAddon> storage =
|
||||
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), context, "000000000000");
|
||||
Fixture fixture = fixture();
|
||||
fixture.cluster.setVersion("1.29");
|
||||
EksAddonService service = new EksAddonService(storage, new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
fixture.catalog(), fixture.iam(), fixture.podIdentityAssociations());
|
||||
|
||||
request.setAccountId(ACCOUNT);
|
||||
service.create(fixture.cluster(), new CreateAddonRequest(
|
||||
"eks-pod-identity-agent", null, null, null, null, null, null, null));
|
||||
request.setAccountId("000000000000");
|
||||
|
||||
assertTrue(service.isInstalled(fixture.cluster(), "eks-pod-identity-agent"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listAddonsWithPagination() {
|
||||
Fixture fixture = fixture();
|
||||
|
||||
@@ -59,6 +59,7 @@ import io.floci.aws.services.eks.model.Logging;
|
||||
import io.floci.aws.services.eks.model.Nodegroup;
|
||||
import io.floci.aws.services.eks.model.OidcIdentity;
|
||||
import io.floci.aws.services.eks.model.ResourcesVpcConfig;
|
||||
import io.floci.aws.testing.ThreadStates;
|
||||
import io.floci.aws.testutil.LogCapture;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
|
||||
@@ -94,13 +95,17 @@ import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.OptionalInt;
|
||||
import java.util.Set;
|
||||
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.AtomicReference;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.LogRecord;
|
||||
|
||||
import static io.floci.aws.testing.InlineMocks.inlineMock;
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
@@ -709,6 +714,21 @@ class EksClusterManagerTest {
|
||||
verify(lifecycleManager, never()).create(any());
|
||||
}
|
||||
|
||||
/** A Floci restart sets the Pod Identity forward up again on the adopted node, as it was before. */
|
||||
@Test
|
||||
void adoptingASurvivorSetsUpItsPodIdentityForwardAgain() {
|
||||
when(lifecycleManager.findByName("floci-eks-demo"))
|
||||
.thenReturn(Optional.of(survivingContainer("cid-1")));
|
||||
when(lifecycleManager.adopt("cid-1", List.of(6443), Optional.empty()))
|
||||
.thenReturn(new ContainerInfo("cid-1", Map.of(), Map.of(6443, 6512)));
|
||||
EksClusterManager spyManager = Mockito.spy(manager);
|
||||
|
||||
Cluster cluster = cluster();
|
||||
spyManager.restoreCluster(cluster);
|
||||
|
||||
verify(spyManager).configurePodIdentityForward(cluster, "cid-1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoreClusterPreservesPreUpgradeLocalStorageWhenContainerSurvives() {
|
||||
when(lifecycleManager.findByName("floci-eks-demo"))
|
||||
@@ -2483,7 +2503,7 @@ class EksClusterManagerTest {
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ConfigurePodIdentityRelay {
|
||||
class ConfigurePodIdentityForward {
|
||||
|
||||
private EmulatorConfig config;
|
||||
private EmulatorConfig.EksServiceConfig eks;
|
||||
@@ -2491,6 +2511,7 @@ class EksClusterManagerTest {
|
||||
private ContainerLifecycleManager lifecycleManager;
|
||||
private DockerClient dockerClient;
|
||||
private DockerHostResolver dockerHostResolver;
|
||||
private EksAddonService addons;
|
||||
private EksClusterManager manager;
|
||||
private List<String[]> capturedCmds;
|
||||
|
||||
@@ -2544,67 +2565,192 @@ class EksClusterManagerTest {
|
||||
when(inspectExec.exec()).thenReturn(inspectResponse);
|
||||
when(dockerClient.inspectExecCmd(anyString())).thenReturn(inspectExec);
|
||||
|
||||
addons = Mockito.mock(EksAddonService.class);
|
||||
when(addons.isInstalled(any(), eq(EksPodIdentityWebhook.POD_IDENTITY_ADDON))).thenReturn(true);
|
||||
|
||||
manager = new EksClusterManager(
|
||||
Mockito.mock(ContainerBuilder.class), lifecycleManager,
|
||||
Mockito.mock(ContainerDetector.class), Mockito.mock(PortAllocator.class),
|
||||
dockerHostResolver, Mockito.mock(EcrRegistryManager.class),
|
||||
config, Mockito.mock(RegionResolver.class), null);
|
||||
manager.setAddonService(addons);
|
||||
}
|
||||
|
||||
@Test
|
||||
void configuresRelayWhenPodIdentityEnabled() {
|
||||
private Cluster cluster() {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setName("test-cluster");
|
||||
|
||||
manager.configurePodIdentityRelay(cluster, "cid-1");
|
||||
|
||||
assertEquals(3, capturedCmds.size());
|
||||
assertTrue(capturedCmds.get(0)[2].contains("command -v socat"));
|
||||
assertTrue(capturedCmds.get(1)[2].contains("169.254.170.23"));
|
||||
assertTrue(capturedCmds.get(1)[2].contains("TCP:floci-host:4566"));
|
||||
assertTrue(capturedCmds.get(1)[2].contains("floci-pod-identity-proxy.pid"));
|
||||
assertTrue(capturedCmds.get(2)[2].contains("FLOCI-LINK-LOCAL"));
|
||||
assertTrue(capturedCmds.get(2)[2].contains("169.254.170.23"));
|
||||
assertFalse(capturedCmds.get(2)[2].contains("169.254.169.254"),
|
||||
"Pod identity relay must not route IMDS traffic");
|
||||
return cluster;
|
||||
}
|
||||
|
||||
@Test
|
||||
void skipsRelayWhenPodIdentityDisabled() {
|
||||
void forwardsThePodIdentityAddressToFlociWhileTheAgentIsInstalled() {
|
||||
manager.configurePodIdentityForward(cluster(), "cid-1");
|
||||
|
||||
assertEquals(1, capturedCmds.size());
|
||||
assertArrayEquals(EksPodNetworkRouting.buildPodIdentityForwardCommand(null, "floci-host", 4566),
|
||||
capturedCmds.get(0));
|
||||
String script = capturedCmds.get(0)[2];
|
||||
assertFalse(script.contains("install"), "nothing is installed in the node");
|
||||
assertFalse(script.contains("nohup socat"), "no relay is started in the node");
|
||||
assertFalse(script.contains("169.254.169.254"), "pod identity forwarding must not route IMDS traffic");
|
||||
}
|
||||
|
||||
@Test
|
||||
void forwardsTheClustersOwnPodNetwork() {
|
||||
Cluster cluster = cluster();
|
||||
cluster.setPodCidr("10.244.0.0/16");
|
||||
|
||||
manager.configurePodIdentityForward(cluster, "cid-1");
|
||||
|
||||
assertEquals(1, capturedCmds.size());
|
||||
assertArrayEquals(EksPodNetworkRouting.buildPodIdentityForwardCommand("10.244.0.0/16", "floci-host", 4566),
|
||||
capturedCmds.get(0));
|
||||
}
|
||||
|
||||
/** A node that starts or is adopted without the agent answers nothing, whatever an earlier Floci left. */
|
||||
@Test
|
||||
void removesTheForwardWhenTheAgentIsNotInstalled() {
|
||||
when(addons.isInstalled(any(), eq(EksPodIdentityWebhook.POD_IDENTITY_ADDON))).thenReturn(false);
|
||||
|
||||
manager.configurePodIdentityForward(cluster(), "cid-1");
|
||||
|
||||
assertEquals(1, capturedCmds.size());
|
||||
assertArrayEquals(EksPodNetworkRouting.buildPodIdentityRemoveCommand(), capturedCmds.get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void creatingTheAgentForwardsAndDeletingItRemovesTheForward() {
|
||||
Cluster cluster = cluster();
|
||||
cluster.setContainerId("cid-1");
|
||||
when(addons.isInstalled(any(), eq(EksPodIdentityWebhook.POD_IDENTITY_ADDON))).thenReturn(true, false);
|
||||
|
||||
manager.podIdentityAgentChanged(cluster);
|
||||
manager.podIdentityAgentChanged(cluster);
|
||||
|
||||
assertEquals(2, capturedCmds.size());
|
||||
assertArrayEquals(EksPodNetworkRouting.buildPodIdentityForwardCommand(null, "floci-host", 4566),
|
||||
capturedCmds.get(0));
|
||||
assertArrayEquals(EksPodNetworkRouting.buildPodIdentityRemoveCommand(), capturedCmds.get(1));
|
||||
verify(dockerClient, Mockito.times(2)).execCreateCmd("cid-1");
|
||||
}
|
||||
|
||||
/**
|
||||
* A DeleteAddon arriving while a CreateAddon's forward runs in the node waits for it, then
|
||||
* reads the store, which no longer holds the agent, and removes the forward: the node ends as
|
||||
* the store does. Without the lock, the removal runs first and the forward stays.
|
||||
*/
|
||||
@Test
|
||||
void aChangeWaitsForTheExecInFlightAndLeavesTheNodeAsTheStoreEnds() throws Exception {
|
||||
Cluster cluster = cluster();
|
||||
cluster.setContainerId("cid-1");
|
||||
when(addons.isInstalled(any(), eq(EksPodIdentityWebhook.POD_IDENTITY_ADDON))).thenReturn(true, false);
|
||||
CountDownLatch forwarding = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
ExecStartCmd parkedFirst = Mockito.mock(ExecStartCmd.class);
|
||||
when(parkedFirst.exec(any())).thenAnswer(inv -> {
|
||||
if (forwarding.getCount() > 0) {
|
||||
forwarding.countDown();
|
||||
assertTrue(release.await(10, TimeUnit.SECONDS));
|
||||
}
|
||||
ResultCallback<Frame> cb = inv.getArgument(0);
|
||||
cb.onComplete();
|
||||
return cb;
|
||||
});
|
||||
when(dockerClient.execStartCmd(anyString())).thenReturn(parkedFirst);
|
||||
ExecutorService pool = Executors.newFixedThreadPool(2);
|
||||
try {
|
||||
Future<?> create = pool.submit(() -> manager.podIdentityAgentChanged(cluster));
|
||||
assertTrue(forwarding.await(10, TimeUnit.SECONDS));
|
||||
AtomicReference<Thread> deleting = new AtomicReference<>();
|
||||
Future<?> delete = pool.submit(() -> {
|
||||
deleting.set(Thread.currentThread());
|
||||
manager.podIdentityAgentChanged(cluster);
|
||||
});
|
||||
|
||||
ThreadStates.awaitBlockedOrDone(deleting, delete);
|
||||
assertEquals(Thread.State.BLOCKED, deleting.get().getState());
|
||||
assertEquals(1, capturedCmds.size());
|
||||
|
||||
release.countDown();
|
||||
create.get(10, TimeUnit.SECONDS);
|
||||
delete.get(10, TimeUnit.SECONDS);
|
||||
} finally {
|
||||
release.countDown();
|
||||
pool.shutdownNow();
|
||||
}
|
||||
|
||||
assertEquals(2, capturedCmds.size());
|
||||
assertArrayEquals(EksPodNetworkRouting.buildPodIdentityForwardCommand(null, "floci-host", 4566),
|
||||
capturedCmds.get(0));
|
||||
assertArrayEquals(EksPodNetworkRouting.buildPodIdentityRemoveCommand(), capturedCmds.get(1));
|
||||
}
|
||||
|
||||
/** As the relay's setup was, the forward is best effort: an add-on store that can't be read fails no start. */
|
||||
@Test
|
||||
void anAddonStoreThatCannotBeReadLeavesTheNodeAndDoesNotThrow() {
|
||||
when(addons.isInstalled(any(), eq(EksPodIdentityWebhook.POD_IDENTITY_ADDON)))
|
||||
.thenThrow(new IllegalStateException("store unavailable"));
|
||||
|
||||
List<LogRecord> records = LogCapture.capture(EksClusterManager.class,
|
||||
() -> manager.configurePodIdentityForward(cluster(), "cid-1"));
|
||||
|
||||
assertTrue(capturedCmds.isEmpty());
|
||||
List<LogRecord> warnings = records.stream()
|
||||
.filter(record -> record.getLevel().intValue() == Level.WARNING.intValue()).toList();
|
||||
assertEquals(1, warnings.size());
|
||||
assertEquals(List.of(EksPodIdentityWebhook.POD_IDENTITY_ADDON, "test-cluster", "store unavailable"),
|
||||
Arrays.asList(warnings.getFirst().getParameters()));
|
||||
}
|
||||
|
||||
/** A mocked cluster has no node, so there is nothing to change. */
|
||||
@Test
|
||||
void theAgentOfAClusterWithoutANodeChangesNothing() {
|
||||
manager.podIdentityAgentChanged(cluster());
|
||||
|
||||
assertTrue(capturedCmds.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void skipsTheForwardWhenPodIdentityIsDisabled() {
|
||||
when(eks.podIdentityWebhook()).thenReturn(false);
|
||||
Cluster cluster = cluster();
|
||||
cluster.setContainerId("cid-1");
|
||||
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setName("test-cluster");
|
||||
|
||||
manager.configurePodIdentityRelay(cluster, "cid-1");
|
||||
manager.configurePodIdentityForward(cluster, "cid-1");
|
||||
manager.podIdentityAgentChanged(cluster);
|
||||
|
||||
assertTrue(capturedCmds.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void skipsRelayWhenTlsDisabled() {
|
||||
void skipsTheForwardWhenTlsIsDisabled() {
|
||||
when(tls.enabled()).thenReturn(false);
|
||||
Cluster cluster = cluster();
|
||||
cluster.setContainerId("cid-1");
|
||||
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setName("test-cluster");
|
||||
|
||||
manager.configurePodIdentityRelay(cluster, "cid-1");
|
||||
manager.configurePodIdentityForward(cluster, "cid-1");
|
||||
manager.podIdentityAgentChanged(cluster);
|
||||
|
||||
assertTrue(capturedCmds.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failsGracefullyWhenExecFails() {
|
||||
void aForwardThatFailsIsLoggedAndDoesNotThrow() {
|
||||
InspectExecCmd inspectExec = Mockito.mock(InspectExecCmd.class);
|
||||
InspectExecResponse inspectResponse = Mockito.mock(InspectExecResponse.class);
|
||||
when(inspectResponse.getExitCodeLong()).thenReturn(1L);
|
||||
when(inspectExec.exec()).thenReturn(inspectResponse);
|
||||
when(dockerClient.inspectExecCmd(anyString())).thenReturn(inspectExec);
|
||||
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setName("test-cluster");
|
||||
List<LogRecord> records = LogCapture.capture(EksClusterManager.class,
|
||||
() -> manager.configurePodIdentityForward(cluster(), "cid-1"));
|
||||
|
||||
assertDoesNotThrow(() -> manager.configurePodIdentityRelay(cluster, "cid-1"));
|
||||
List<LogRecord> warnings = records.stream()
|
||||
.filter(record -> record.getLevel().intValue() == Level.WARNING.intValue()).toList();
|
||||
assertEquals(1, warnings.size());
|
||||
assertEquals("Could not forward the Pod Identity address for EKS cluster {0} to Floci: {1}",
|
||||
warnings.getFirst().getMessage());
|
||||
assertEquals(List.of("test-cluster", "(no output)"), Arrays.asList(warnings.getFirst().getParameters()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5142,7 +5288,8 @@ class EksClusterManagerTest {
|
||||
Mockito.mock(EksAccessEntryService.class),
|
||||
Mockito.mock(EksPodIdentityAssociationService.class),
|
||||
Mockito.mock(EksAddonService.class),
|
||||
mapper);
|
||||
mapper,
|
||||
Mockito.mock(EksClusterManager.class));
|
||||
|
||||
for (Response response : List.of(
|
||||
controller.createCluster(mapper.createObjectNode()),
|
||||
|
||||
+7
-47
@@ -1,9 +1,9 @@
|
||||
package io.floci.aws.services.eks;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import io.floci.aws.core.common.docker.ContainerExec;
|
||||
import io.floci.aws.services.eks.model.Cluster;
|
||||
import io.floci.aws.testing.DockerAvailability;
|
||||
import io.floci.aws.testing.EksTestNode;
|
||||
import io.floci.aws.testing.RealEksProfile;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
@@ -15,13 +15,8 @@ import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
/**
|
||||
* Docker integration test verifying that a cluster's node shares its mounts as an EKS node does, so a pod asking
|
||||
* for mount propagation starts: a CSI node plugin mounts its volumes under {@code /var/lib/kubelet/pods} with
|
||||
@@ -65,28 +60,11 @@ class EksNodeMountPropagationDockerIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPodAskingForMountPropagationStartsOnTheNode() throws Exception {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
String clusterName = "mount-prop-" + suffix;
|
||||
void aPodAskingForMountPropagationStartsOnTheNode() {
|
||||
cluster = EksTestNode.cluster(ACCOUNT, "mount-prop-" + UUID.randomUUID().toString().substring(0, 8));
|
||||
EksTestNode node = EksTestNode.start(dockerClient, eksClusterManager, cluster, Duration.ofSeconds(60));
|
||||
|
||||
cluster = new Cluster();
|
||||
cluster.setName(clusterName);
|
||||
cluster.setAccountId(ACCOUNT);
|
||||
cluster.setArn("arn:aws:eks:us-east-1:" + ACCOUNT + ":cluster/" + clusterName);
|
||||
cluster.setCreatedAt(Instant.now());
|
||||
cluster.setRoleArn("arn:aws:iam::" + ACCOUNT + ":role/eks-service-role");
|
||||
|
||||
eksClusterManager.startCluster(cluster);
|
||||
assertNotNull(cluster.getContainerId(), "Container ID must not be null");
|
||||
String containerId = cluster.getContainerId();
|
||||
|
||||
await("k3s API server ready").atMost(Duration.ofSeconds(60)).pollInterval(Duration.ofSeconds(2))
|
||||
.until(() -> eksClusterManager.isReady(cluster));
|
||||
eksClusterManager.finalizeCluster(cluster);
|
||||
await("default serviceaccount created").atMost(Duration.ofSeconds(30)).pollInterval(Duration.ofSeconds(2))
|
||||
.until(() -> kubectl(containerId, "get", "serviceaccount", "default").exitCode() == 0);
|
||||
|
||||
String podYaml = """
|
||||
node.apply("""
|
||||
apiVersion: v1
|
||||
kind: Pod
|
||||
metadata:
|
||||
@@ -115,26 +93,8 @@ class EksNodeMountPropagationDockerIntegrationTest {
|
||||
- name: node-root
|
||||
hostPath:
|
||||
path: /
|
||||
""".formatted(POD);
|
||||
ContainerExec.Result applied = exec(containerId, "sh", "-c",
|
||||
"cat << 'EOF' | kubectl apply -f -\n" + podYaml + "\nEOF");
|
||||
assertEquals(0, applied.exitCode(), "kubectl apply failed: " + applied.stderr());
|
||||
""".formatted(POD));
|
||||
|
||||
await("mount propagation pod running").atMost(Duration.ofSeconds(90)).pollInterval(Duration.ofSeconds(2))
|
||||
.untilAsserted(() -> assertEquals("Running",
|
||||
kubectl(containerId, "get", "pod", POD, "-o", "jsonpath={.status.phase}").stdout().trim(),
|
||||
() -> "the pod must start, but its container reports: " + kubectl(containerId, "get", "pod",
|
||||
POD, "-o", "jsonpath={.status.containerStatuses[0].state}").stdout()));
|
||||
}
|
||||
|
||||
private ContainerExec.Result kubectl(String containerId, String... args) {
|
||||
String[] cmd = new String[args.length + 1];
|
||||
cmd[0] = "kubectl";
|
||||
System.arraycopy(args, 0, cmd, 1, args.length);
|
||||
return exec(containerId, cmd);
|
||||
}
|
||||
|
||||
private ContainerExec.Result exec(String containerId, String... cmd) {
|
||||
return ContainerExec.run(dockerClient, containerId, cmd, 30).throwIfTimedOut(containerId);
|
||||
node.awaitPodRunning(POD, Duration.ofSeconds(90));
|
||||
}
|
||||
}
|
||||
+280
@@ -0,0 +1,280 @@
|
||||
package io.floci.aws.services.eks;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import io.floci.aws.core.common.docker.ContainerExec;
|
||||
import io.floci.aws.core.common.docker.DockerHostResolver;
|
||||
import io.floci.aws.services.eks.model.Cluster;
|
||||
import io.floci.aws.services.eks.model.ClusterIdentity;
|
||||
import io.floci.aws.services.eks.model.ClusterStatus;
|
||||
import io.floci.aws.services.eks.model.CreatePodIdentityAssociationRequest;
|
||||
import io.floci.aws.services.eks.model.OidcIdentity;
|
||||
import io.floci.aws.services.iam.IamService;
|
||||
import io.floci.aws.testing.DockerAvailability;
|
||||
import io.floci.aws.testing.EksTestNode;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.QuarkusTestProfile;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Docker integration test of the Pod Identity address on a real k3s node: it answers a pod's
|
||||
* credentials request while the {@code eks-pod-identity-agent} add-on is installed, stops answering
|
||||
* when DeleteAddon removes the add-on, keeps answering when it removes it with {@code preserve}, and
|
||||
* after a Floci restart answers again only while the add-on is stored.
|
||||
*
|
||||
* <p>The cluster is started through {@link EksClusterManager} directly, on the webhook and TLS
|
||||
* settings the Pod Identity forward needs, so this class keeps a profile of its own rather than
|
||||
* {@code RealEksProfile}. The add-on is created and deleted through the EKS API, as a client would.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(EksPodIdentityAgentDockerIntegrationTest.Profile.class)
|
||||
class EksPodIdentityAgentDockerIntegrationTest {
|
||||
|
||||
public static final class Profile implements QuarkusTestProfile {
|
||||
@Override
|
||||
public Map<String, String> getConfigOverrides() {
|
||||
return Map.of(
|
||||
"floci.services.eks.mock", "false",
|
||||
"floci.services.eks.pod-identity-webhook", "true",
|
||||
"floci.tls.enabled", "true",
|
||||
"floci.tls.aws-https-port", "0",
|
||||
"quarkus.http.test-port", "4510",
|
||||
"quarkus.http.test-ssl-port", "4511",
|
||||
"floci.port", "4595",
|
||||
"floci.base-url", "http://localhost:4595");
|
||||
}
|
||||
}
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(EksPodIdentityAgentDockerIntegrationTest.class);
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final String POD = "pod-identity-client";
|
||||
private static final String CREDENTIALS_URL = "http://169.254.170.23/v1/credentials";
|
||||
private static final Duration API_SERVER_TIMEOUT = Duration.ofSeconds(90);
|
||||
private static final Duration POD_TIMEOUT = Duration.ofSeconds(120);
|
||||
|
||||
@Inject
|
||||
DockerClient dockerClient;
|
||||
|
||||
@Inject
|
||||
DockerHostResolver dockerHostResolver;
|
||||
|
||||
@Inject
|
||||
EksClusterManager eksClusterManager;
|
||||
|
||||
@Inject
|
||||
EksService eksService;
|
||||
|
||||
@Inject
|
||||
EksOidcService oidcService;
|
||||
|
||||
@Inject
|
||||
EksPodIdentityAssociationService associationService;
|
||||
|
||||
@Inject
|
||||
EksAddonService addonService;
|
||||
|
||||
@Inject
|
||||
IamService iamService;
|
||||
|
||||
private Cluster cluster;
|
||||
private EksTestNode node;
|
||||
private String roleName;
|
||||
|
||||
@BeforeEach
|
||||
void requireDocker() {
|
||||
Assumptions.assumeTrue(DockerAvailability.answers(dockerClient),
|
||||
"Docker daemon must be available for the EKS Pod Identity agent test");
|
||||
Assumptions.assumeTrue(dockerHostResolver.isLinuxHost(),
|
||||
"The node reaches Floci through host.docker.internal, which this test expects on a Linux host");
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
if (cluster != null) {
|
||||
addonService.deleteClusterAddons(cluster);
|
||||
try {
|
||||
eksClusterManager.stopCluster(cluster);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv(e, "Failed to stop test cluster {0}", cluster.getName());
|
||||
}
|
||||
try {
|
||||
eksService.deleteClusterForAccount(ACCOUNT, cluster.getName());
|
||||
} catch (Exception e) {
|
||||
LOG.warnv(e, "Failed to delete test cluster {0}", cluster.getName());
|
||||
}
|
||||
}
|
||||
if (roleName != null) {
|
||||
try {
|
||||
iamService.deleteRole(roleName);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv(e, "Failed to delete test role {0}", roleName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void thePodIdentityAddressAnswersWhileTheAgentAddonIsInstalled() throws Exception {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
String clusterName = "pi-agent-" + suffix;
|
||||
roleName = "pi-agent-role-" + suffix;
|
||||
String roleArn = "arn:aws:iam::" + ACCOUNT + ":role/" + roleName;
|
||||
iamService.createRole(roleName, "/", "{\"Version\":\"2012-10-17\",\"Statement\":[]}", null, 3600, null);
|
||||
|
||||
cluster = EksTestNode.cluster(ACCOUNT, clusterName);
|
||||
// The default version, so the node runs the configured stock image.
|
||||
cluster.setVersion(EksService.DEFAULT_K8S_VERSION);
|
||||
String issuer = "https://oidc.eks.us-east-1.amazonaws.com/id/"
|
||||
+ UUID.randomUUID().toString().replace("-", "").toUpperCase(Locale.ROOT);
|
||||
cluster.setIdentity(new ClusterIdentity(new OidcIdentity(issuer)));
|
||||
|
||||
node = EksTestNode.start(dockerClient, eksClusterManager, cluster, API_SERVER_TIMEOUT);
|
||||
cluster.setStatus(ClusterStatus.ACTIVE);
|
||||
eksService.putClusterForAccount(ACCOUNT, cluster);
|
||||
|
||||
String clusterKey = EksService.clusterKey("us-east-1", clusterName);
|
||||
assertNotNull(oidcService.ensureKeyForAccount(ACCOUNT, clusterKey, issuer));
|
||||
associationService.create(cluster, new CreatePodIdentityAssociationRequest(
|
||||
clusterName, "default", "workload-sa", roleArn, null, null, null, null, null));
|
||||
String token = oidcService.mintServiceAccountToken(clusterKey, issuer, "default", "workload-sa",
|
||||
"pods.eks.amazonaws.com", 3600);
|
||||
startClientPod();
|
||||
|
||||
// Without the agent nothing answers, as on an EKS node.
|
||||
assertEquals(List.of(), podIdentityRules());
|
||||
assertNotAnswered(token);
|
||||
|
||||
createAgent(clusterName);
|
||||
assertForwarded(token);
|
||||
|
||||
deleteAgent(clusterName, false);
|
||||
assertEquals(List.of(), podIdentityRules());
|
||||
assertNotAnswered(token);
|
||||
|
||||
// With preserve, EKS leaves the agent running, so the address keeps answering.
|
||||
createAgent(clusterName);
|
||||
deleteAgent(clusterName, true);
|
||||
assertForwarded(token);
|
||||
|
||||
// A restart forwards only while the add-on is stored, which it no longer is.
|
||||
restartFloci();
|
||||
assertEquals(List.of(), podIdentityRules());
|
||||
|
||||
createAgent(clusterName);
|
||||
restartFloci();
|
||||
assertForwarded(token);
|
||||
}
|
||||
|
||||
/** A pod on the pod network, whose requests take the node's PREROUTING rule. */
|
||||
private void startClientPod() {
|
||||
node.apply("""
|
||||
apiVersion: v1
|
||||
kind: Pod
|
||||
metadata:
|
||||
name: %s
|
||||
namespace: default
|
||||
spec:
|
||||
containers:
|
||||
- name: client
|
||||
image: alpine:3.21
|
||||
command: ["sleep", "3600"]
|
||||
""".formatted(POD));
|
||||
node.awaitPodRunning(POD, POD_TIMEOUT);
|
||||
}
|
||||
|
||||
private void createAgent(String clusterName) {
|
||||
given().header("Authorization", auth()).contentType("application/json")
|
||||
.body(Map.of("addonName", EksPodIdentityWebhook.POD_IDENTITY_ADDON, "addonVersion", "v1.4.0-eksbuild.3"))
|
||||
.post("/clusters/" + clusterName + "/addons")
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
private void deleteAgent(String clusterName, boolean preserve) {
|
||||
given().header("Authorization", auth()).queryParam("preserve", preserve)
|
||||
.delete("/clusters/" + clusterName + "/addons/" + EksPodIdentityWebhook.POD_IDENTITY_ADDON)
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* One rule in each chain, both to the same Floci address on its port, and a pod on the pod
|
||||
* network and the node itself, where a {@code hostNetwork} pod's requests come from, both get
|
||||
* the association's credentials.
|
||||
*/
|
||||
private void assertForwarded(String token) {
|
||||
List<String> rules = podIdentityRules();
|
||||
assertEquals(2, rules.size(), "expected one PREROUTING and one OUTPUT rule, got: " + rules);
|
||||
String target = rules.get(0).substring(rules.get(0).indexOf("--to-destination ") + "--to-destination ".length());
|
||||
assertTrue(target.endsWith(":4595"), target);
|
||||
assertEquals(List.of(
|
||||
"-A PREROUTING -s 10.42.0.0/16 -d 169.254.170.23/32 -p tcp -m tcp --dport 80 -j DNAT --to-destination " + target,
|
||||
"-A OUTPUT -d 169.254.170.23/32 -p tcp -m tcp --dport 80 -j DNAT --to-destination " + target), rules);
|
||||
|
||||
await("credentials from the pod network").atMost(Duration.ofSeconds(60)).pollInterval(Duration.ofSeconds(2))
|
||||
.untilAsserted(() -> assertCredentials(node.kubectl("exec", POD, "--", "wget", "-q", "-T", "5",
|
||||
"-O", "-", "--header", "Authorization: " + token, CREDENTIALS_URL)));
|
||||
assertCredentials(node.exec("wget", "-q", "-T", "5", "-O", "-", "--header", "Authorization: " + token,
|
||||
CREDENTIALS_URL));
|
||||
}
|
||||
|
||||
private static void assertCredentials(ContainerExec.Result result) {
|
||||
assertEquals(0, result.exitCode(), result.summary());
|
||||
assertTrue(result.stdout().contains("\"AccessKeyId\"") && result.stdout().contains("ASIA"), result.stdout());
|
||||
}
|
||||
|
||||
private void assertNotAnswered(String token) {
|
||||
ContainerExec.Result result = node.kubectl("exec", POD, "--", "wget", "-q", "-T", "3", "-O", "-",
|
||||
"--header", "Authorization: " + token, CREDENTIALS_URL);
|
||||
assertNotEquals(0, result.exitCode(), result.summary());
|
||||
assertFalse(result.stdout().contains("AccessKeyId"), result.stdout());
|
||||
}
|
||||
|
||||
/** The node's PREROUTING and OUTPUT rules for the Pod Identity address, as iptables lists them. */
|
||||
private List<String> podIdentityRules() {
|
||||
ContainerExec.Result listed = node.exec("sh", "-c",
|
||||
"IPTABLES=$(command -v iptables || command -v /bin/aux/iptables);"
|
||||
+ " $IPTABLES -t nat -S PREROUTING && $IPTABLES -t nat -S OUTPUT");
|
||||
assertEquals(0, listed.exitCode(), listed.summary());
|
||||
return Arrays.stream(listed.stdout().split("\n"))
|
||||
.map(String::trim)
|
||||
.filter(rule -> rule.contains("169.254.170.23"))
|
||||
.toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Floci stops with the cluster left running, Docker stops the node, and Floci starts again and
|
||||
* adopts it, which starts it, as {@code restoreCluster} does for a cluster that survived.
|
||||
*/
|
||||
private void restartFloci() {
|
||||
String containerId = node.containerId();
|
||||
eksClusterManager.detachCluster(cluster);
|
||||
dockerClient.stopContainerCmd(containerId).withTimeout(30).exec();
|
||||
eksClusterManager.restoreCluster(cluster);
|
||||
assertEquals(containerId, cluster.getContainerId(), "the surviving node is adopted, not replaced");
|
||||
node.awaitApiServer(API_SERVER_TIMEOUT);
|
||||
node.awaitPodRunning(POD, POD_TIMEOUT);
|
||||
}
|
||||
|
||||
private static String auth() {
|
||||
return "AWS4-HMAC-SHA256 Credential=" + ACCOUNT
|
||||
+ "/20260920/us-east-1/eks/aws4_request, SignedHeaders=host, Signature=fake";
|
||||
}
|
||||
}
|
||||
@@ -11,9 +11,11 @@ import io.floci.aws.services.eks.model.Cluster;
|
||||
import io.floci.aws.services.eks.model.ClusterIdentity;
|
||||
import io.floci.aws.services.eks.model.ClusterOidcKey;
|
||||
import io.floci.aws.services.eks.model.ClusterStatus;
|
||||
import io.floci.aws.services.eks.model.CreateAddonRequest;
|
||||
import io.floci.aws.services.eks.model.CreatePodIdentityAssociationRequest;
|
||||
import io.floci.aws.services.eks.model.OidcIdentity;
|
||||
import io.floci.aws.services.iam.IamService;
|
||||
import io.floci.aws.testing.DockerAvailability;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.QuarkusTestProfile;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
@@ -81,6 +83,9 @@ class EksPodIdentityDockerIntegrationTest {
|
||||
@Inject
|
||||
EksClusterManager eksClusterManager;
|
||||
|
||||
@Inject
|
||||
EksAddonService addonService;
|
||||
|
||||
@Inject
|
||||
DockerHostResolver dockerHostResolver;
|
||||
|
||||
@@ -91,7 +96,7 @@ class EksPodIdentityDockerIntegrationTest {
|
||||
|
||||
@BeforeEach
|
||||
void requireDocker() {
|
||||
boolean dockerAvailable = isDockerAvailable();
|
||||
boolean dockerAvailable = DockerAvailability.answers(dockerClient);
|
||||
if (!dockerAvailable) {
|
||||
LOG.warn("Docker daemon is not available; skipping EksPodIdentityDockerIntegrationTest");
|
||||
}
|
||||
@@ -102,6 +107,9 @@ class EksPodIdentityDockerIntegrationTest {
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
if (cluster != null) {
|
||||
addonService.deleteClusterAddons(cluster);
|
||||
}
|
||||
if (clusterName != null) {
|
||||
try {
|
||||
eksService.deleteClusterForAccount("000000000000", clusterName);
|
||||
@@ -160,7 +168,10 @@ class EksPodIdentityDockerIntegrationTest {
|
||||
|
||||
execInContainer(containerId, "command -v curl >/dev/null 2>&1 && command -v iptables >/dev/null 2>&1 && command -v ip >/dev/null 2>&1 || apk add --no-cache curl iptables iproute2");
|
||||
|
||||
eksClusterManager.configurePodIdentityRelay(cluster, containerId);
|
||||
// The address answers while the agent add-on is stored, as on EKS.
|
||||
addonService.create(cluster, new CreateAddonRequest(EksPodIdentityWebhook.POD_IDENTITY_ADDON,
|
||||
"v1.4.0-eksbuild.3", null, null, null, null, null, null));
|
||||
eksClusterManager.configurePodIdentityForward(cluster, containerId);
|
||||
|
||||
String validToken = oidcService.mintServiceAccountToken(EksService.clusterKey("us-east-1", clusterName), issuer, "default", "workload-sa",
|
||||
"pods.eks.amazonaws.com", 3600);
|
||||
@@ -176,15 +187,6 @@ class EksPodIdentityDockerIntegrationTest {
|
||||
assertEquals("404", missingCode.trim());
|
||||
}
|
||||
|
||||
private boolean isDockerAvailable() {
|
||||
try {
|
||||
dockerClient.pingCmd().exec();
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private String execInContainer(String containerId, String cmd) {
|
||||
return ContainerExec.runMerged(dockerClient, containerId, new String[]{"sh", "-c", cmd}, 30).stdout();
|
||||
}
|
||||
|
||||
@@ -2,8 +2,6 @@ package io.floci.aws.services.eks;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.services.eks.model.Addon;
|
||||
import io.floci.aws.services.eks.model.Cluster;
|
||||
import io.floci.aws.services.eks.model.PodIdentityAssociationSummary;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -49,8 +47,7 @@ class EksPodIdentityWebhookTest {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setName(CLUSTER_NAME);
|
||||
when(eks.findPreRegionalCluster(ACCOUNT_ID, CLUSTER_NAME)).thenReturn(Optional.of(cluster));
|
||||
when(addons.describe(any(), eq(EksPodIdentityWebhook.POD_IDENTITY_ADDON)))
|
||||
.thenReturn(inlineMock(Addon.class));
|
||||
when(addons.isInstalled(any(), eq(EksPodIdentityWebhook.POD_IDENTITY_ADDON))).thenReturn(true);
|
||||
when(associations.list(any(), anyString(), anyString(), any(), any()))
|
||||
.thenReturn(new EksPodIdentityAssociationService.Page(
|
||||
List.of(inlineMock(PodIdentityAssociationSummary.class)), null));
|
||||
@@ -154,8 +151,7 @@ class EksPodIdentityWebhookTest {
|
||||
|
||||
@Test
|
||||
void clusterWithoutThePodIdentityAgentAddonIsNotPatched() throws Exception {
|
||||
when(addons.describe(any(), eq(EksPodIdentityWebhook.POD_IDENTITY_ADDON)))
|
||||
.thenThrow(new AwsException("ResourceNotFoundException", "No addon", 404));
|
||||
when(addons.isInstalled(any(), eq(EksPodIdentityWebhook.POD_IDENTITY_ADDON))).thenReturn(false);
|
||||
|
||||
Map<String, Object> review = webhook.review(CLUSTER_NAME, ACCOUNT_ID,
|
||||
admissionReview(pod("checkout", List.of(Map.of("name", "app")))));
|
||||
|
||||
@@ -1,16 +1,46 @@
|
||||
package io.floci.aws.services.eks;
|
||||
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import io.floci.aws.testing.HelperShellFixture;
|
||||
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.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.net.InetSocketAddress;
|
||||
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.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class EksPodNetworkRoutingTest {
|
||||
|
||||
/** What the stand-in iptables is asked when it lists a rule for the address in each chain. */
|
||||
private static final List<String> EARLIER_RULES_REMOVED = List.of(
|
||||
"-t nat -S PREROUTING",
|
||||
"-t nat -D PREROUTING -s 10.42.0.0/16 -d 169.254.170.23/32 -p tcp -m tcp --dport 80 -j DNAT"
|
||||
+ " --to-destination 172.18.0.9:4566",
|
||||
"-t nat -S OUTPUT",
|
||||
"-t nat -D OUTPUT -d 169.254.170.23/32 -p tcp -m tcp --dport 80 -j DNAT --to-destination 172.18.0.9:4566",
|
||||
"-t nat -S FLOCI-LINK-LOCAL",
|
||||
"-t nat -D FLOCI-LINK-LOCAL -s 10.42.0.0/16 -d 169.254.170.23/32 -p tcp -m tcp --dport 80 -j DNAT"
|
||||
+ " --to-destination 169.254.170.23:80");
|
||||
|
||||
/** Where the relay an older Floci ran for the address kept its PID. */
|
||||
private static final Path RELAY_PID_FILE = Path.of("/tmp/floci-pod-identity-proxy.pid");
|
||||
|
||||
@Test
|
||||
void linkLocalEndpointValidatesInput() {
|
||||
assertThrows(NullPointerException.class, () -> new LinkLocalEndpoint(null, 80));
|
||||
@@ -91,4 +121,260 @@ class EksPodNetworkRoutingTest {
|
||||
|
||||
assertTrue(script.contains("-s 192.168.0.0/16 -d 169.254.169.254"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"", "floci host", "floci;reboot", "$(id)", "floci`id`", "-floci", "floci-", "a'b"})
|
||||
void podIdentityForwardRefusesAHostTheShellCouldReadAsMore(String host) {
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> EksPodNetworkRouting.buildPodIdentityForwardCommand(null, host, 4566));
|
||||
}
|
||||
|
||||
@Test
|
||||
void podIdentityForwardRefusesABadPodCidrPortOrHostsFile() {
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> EksPodNetworkRouting.buildPodIdentityForwardCommand("10.42.0.0", "floci", 4566));
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> EksPodNetworkRouting.buildPodIdentityForwardCommand("10.42.0.0/16; id", "floci", 4566));
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> EksPodNetworkRouting.buildPodIdentityForwardCommand(null, null, 4566));
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> EksPodNetworkRouting.buildPodIdentityForwardCommand(null, "floci", 0));
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> EksPodNetworkRouting.buildPodIdentityForwardCommand(null, "floci", 65536));
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> EksPodNetworkRouting.buildPodIdentityForwardCommand(null, "floci", 4566, "hosts"));
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> EksPodNetworkRouting.buildPodIdentityForwardCommand(null, "floci", 4566, "/etc/ho'sts"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the forward script against stand-ins for a stock k3s node's tools: iptables records what
|
||||
* it is asked and lists the rules an earlier Floci left for the address, nslookup answers as
|
||||
* BusyBox's does, and wget gets Floci's 400 for a request without a pod token. There is no curl.
|
||||
* The host is resolved from the hosts file first, through DNS when that has no entry, and an
|
||||
* address is used as it is.
|
||||
*/
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"floci-under-test.internal, '', 172.18.0.2, true",
|
||||
"floci-under-test.internal, '172.18.0.7 other-name floci-under-test.internal', 172.18.0.7, false",
|
||||
"172.18.0.5, '', 172.18.0.5, false"})
|
||||
void podIdentityForwardResolvesTheHostReplacesEarlierRulesAndProbes(String host, String hostsEntry,
|
||||
String address, boolean looksUp,
|
||||
@TempDir Path dir) throws Exception {
|
||||
Path bin = fakeStockNode(dir);
|
||||
Path hosts = Files.writeString(dir.resolve("hosts"), "# 172.18.0.8 floci-under-test.internal\n" + hostsEntry + "\n");
|
||||
|
||||
int exit = HelperShellFixture.run(
|
||||
EksPodNetworkRouting.buildPodIdentityForwardCommand(null, host, 4566, hosts.toString()), dir,
|
||||
Map.of("PATH", bin.toString(), "http_proxy", "http://127.0.0.1:9"));
|
||||
|
||||
assertEquals(0, exit, HelperShellFixture.output(dir));
|
||||
List<String> expected = new ArrayList<>(EARLIER_RULES_REMOVED);
|
||||
expected.add("-t nat -I PREROUTING 1 -s 10.42.0.0/16 -d 169.254.170.23/32 -p tcp --dport 80 -j DNAT"
|
||||
+ " --to-destination " + address + ":4566");
|
||||
expected.add("-t nat -I OUTPUT 1 -d 169.254.170.23/32 -p tcp --dport 80 -j DNAT --to-destination "
|
||||
+ address + ":4566");
|
||||
assertEquals(expected, Files.readAllLines(dir.resolve("iptables-calls")));
|
||||
assertEquals(looksUp ? List.of(host) : List.of(), calls(dir.resolve("nslookup-calls")));
|
||||
}
|
||||
|
||||
/** Without the add-on nothing answers on the address: every rule for it goes, the others stay. */
|
||||
@Test
|
||||
void podIdentityRemovalDeletesEveryRuleForTheAddressAndAddsNone(@TempDir Path dir) throws Exception {
|
||||
Path bin = fakeStockNode(dir);
|
||||
|
||||
int exit = HelperShellFixture.run(EksPodNetworkRouting.buildPodIdentityRemoveCommand(), dir,
|
||||
Map.of("PATH", bin.toString()));
|
||||
|
||||
assertEquals(0, exit, HelperShellFixture.output(dir));
|
||||
assertEquals(EARLIER_RULES_REMOVED, Files.readAllLines(dir.resolve("iptables-calls")));
|
||||
}
|
||||
|
||||
/**
|
||||
* An older Floci answered on the address with a socat relay on the node's loopback, which would answer again once
|
||||
* the rules in front of it went: the removal stops it, while its PID file still names it, and takes its address
|
||||
* off the loopback. The removal runs traced, so the test sees the {@code kill} it sends.
|
||||
*/
|
||||
@Test
|
||||
void podIdentityRemovalRetiresTheRelayAnOlderFlociRan(@TempDir Path dir) throws Exception {
|
||||
Path bin = fakeStockNode(dir);
|
||||
HelperShellFixture.writeTool(bin, "ip", "echo \"$*\" >> '" + dir.resolve("ip-calls") + "'\n"
|
||||
+ "if [ \"$*\" = 'addr show dev lo' ]; then\n"
|
||||
+ " echo ' inet 127.0.0.1/8 scope host lo'\n"
|
||||
+ " echo ' inet 169.254.170.23/32 scope global lo'\n"
|
||||
+ "fi\n");
|
||||
Process relay = startFakeRelay(bin, "169.254.170.23");
|
||||
try {
|
||||
Files.writeString(RELAY_PID_FILE, relay.pid() + "\n");
|
||||
|
||||
int exit = HelperShellFixture.run(traced(EksPodNetworkRouting.buildPodIdentityRemoveCommand()), dir,
|
||||
Map.of("PATH", bin.toString()));
|
||||
|
||||
assertEquals(0, exit, HelperShellFixture.output(dir));
|
||||
assertEquals(List.of("kill " + relay.pid()), tracedKills(dir), HelperShellFixture.output(dir));
|
||||
assertTrue(relay.waitFor(10, TimeUnit.SECONDS), "the relay is still running");
|
||||
assertFalse(Files.exists(RELAY_PID_FILE));
|
||||
assertEquals(List.of("addr show dev lo", "addr del 169.254.170.23/32 dev lo"),
|
||||
calls(dir.resolve("ip-calls")));
|
||||
} finally {
|
||||
relay.destroyForcibly();
|
||||
Files.deleteIfExists(RELAY_PID_FILE);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A PID file that names another process, here a socat relaying IMDS, leaves that process running: the traced
|
||||
* removal sends it no {@code kill}.
|
||||
*/
|
||||
@Test
|
||||
void podIdentityRemovalLeavesTheProcessAStalePidFileNames(@TempDir Path dir) throws Exception {
|
||||
Path bin = fakeStockNode(dir);
|
||||
Process imdsRelay = startFakeRelay(bin, "169.254.169.254");
|
||||
try {
|
||||
Files.writeString(RELAY_PID_FILE, imdsRelay.pid() + "\n");
|
||||
|
||||
int exit = HelperShellFixture.run(traced(EksPodNetworkRouting.buildPodIdentityRemoveCommand()), dir,
|
||||
Map.of("PATH", bin.toString()));
|
||||
|
||||
assertEquals(0, exit, HelperShellFixture.output(dir));
|
||||
assertEquals(List.of(), tracedKills(dir), HelperShellFixture.output(dir));
|
||||
assertTrue(imdsRelay.isAlive(), "the IMDS relay was stopped");
|
||||
assertFalse(Files.exists(RELAY_PID_FILE));
|
||||
} finally {
|
||||
imdsRelay.destroyForcibly();
|
||||
Files.deleteIfExists(RELAY_PID_FILE);
|
||||
}
|
||||
}
|
||||
|
||||
/** A node without iptables has no rules to remove, but cannot be given any. */
|
||||
@Test
|
||||
void withoutIptablesRemovalSucceedsAndTheForwardFails(@TempDir Path dir) throws Exception {
|
||||
Path bin = Files.createDirectory(dir.resolve("bin"));
|
||||
HelperShellFixture.linkHostTools(bin, List.of("awk", "sed", "grep"));
|
||||
Map<String, String> environment = Map.of("PATH", bin.toString());
|
||||
|
||||
assertEquals(0, HelperShellFixture.run(EksPodNetworkRouting.buildPodIdentityRemoveCommand(), dir, environment),
|
||||
HelperShellFixture.output(dir));
|
||||
assertEquals(1, HelperShellFixture.run(
|
||||
EksPodNetworkRouting.buildPodIdentityForwardCommand(null, "172.18.0.2", 4566), dir, environment));
|
||||
assertEquals("iptables not found in container\n", HelperShellFixture.output(dir));
|
||||
}
|
||||
|
||||
/**
|
||||
* Floci answers 400 without a pod token, which still proves the path reaches it. A proxy that
|
||||
* answered in its place would look the same to the status check, so the probe must not go
|
||||
* through one, whether it asks with curl or, on a stock {@code rancher/k3s} node, which has
|
||||
* BusyBox's {@code wget} and no {@code curl}, with wget, reading the status from the error it
|
||||
* prints.
|
||||
*/
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"curl", "wget"})
|
||||
void podIdentityProbeReachesFlociPastTheImagesHttpProxy(String client, @TempDir Path dir) throws Exception {
|
||||
Path bin = Files.createDirectory(dir.resolve("bin"));
|
||||
HelperShellFixture.linkHostTools(bin, List.of(client, "env", "grep"));
|
||||
List<String> proxied = new CopyOnWriteArrayList<>();
|
||||
AtomicInteger answered = new AtomicInteger();
|
||||
HttpServer proxy = null;
|
||||
HttpServer floci = null;
|
||||
try {
|
||||
proxy = HelperShellFixture.failingProxy(proxied);
|
||||
floci = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
floci.createContext("/v1/credentials", exchange -> {
|
||||
answered.incrementAndGet();
|
||||
exchange.sendResponseHeaders(400, -1);
|
||||
exchange.close();
|
||||
});
|
||||
floci.start();
|
||||
String[] probe = {"sh", "-c",
|
||||
EksPodNetworkRouting.podIdentityProbeCommand("http://127.0.0.1:" + floci.getAddress().getPort())};
|
||||
Map<String, String> environment = new HashMap<>(HelperShellFixture.proxyEnvironment(proxy));
|
||||
environment.put("PATH", bin.toString());
|
||||
|
||||
int result = HelperShellFixture.run(probe, dir, environment);
|
||||
|
||||
assertEquals(0, result, HelperShellFixture.output(dir));
|
||||
assertEquals(1, answered.get(), HelperShellFixture.output(dir));
|
||||
assertEquals(List.of(), proxied);
|
||||
} finally {
|
||||
if (floci != null) {
|
||||
floci.stop(0);
|
||||
}
|
||||
if (proxy != null) {
|
||||
proxy.stop(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A bin directory of stand-ins for a stock k3s node's tools, beside the host's awk, sed, grep,
|
||||
* env, sleep, cat, tr and rm. iptables records its arguments in {@code iptables-calls} and lists,
|
||||
* in {@code PREROUTING} and {@code OUTPUT}, a rule an earlier Floci on 172.18.0.9 left for the
|
||||
* address and one rule of another's, and in {@code FLOCI-LINK-LOCAL} the rule an older Floci sent
|
||||
* the address to its relay with, beside the IMDS one. nslookup records its arguments in
|
||||
* {@code nslookup-calls} and answers as BusyBox's.
|
||||
*/
|
||||
private static Path fakeStockNode(Path dir) throws Exception {
|
||||
Path bin = Files.createDirectory(dir.resolve("bin"));
|
||||
HelperShellFixture.linkHostTools(bin, List.of("awk", "sed", "grep", "env", "sleep", "cat", "tr", "rm"));
|
||||
HelperShellFixture.writeTool(bin, "iptables", "echo \"$*\" >> '" + dir.resolve("iptables-calls") + "'\n"
|
||||
+ "if [ \"$*\" = '-t nat -S PREROUTING' ]; then\n"
|
||||
+ " echo '-P PREROUTING ACCEPT'\n"
|
||||
+ " echo '-A PREROUTING -s 10.42.0.0/16 -d 169.254.170.23/32 -p tcp -m tcp --dport 80 -j DNAT"
|
||||
+ " --to-destination 172.18.0.9:4566'\n"
|
||||
+ " echo '-A PREROUTING -j FLOCI-LINK-LOCAL'\n"
|
||||
+ "fi\n"
|
||||
+ "if [ \"$*\" = '-t nat -S OUTPUT' ]; then\n"
|
||||
+ " echo '-P OUTPUT ACCEPT'\n"
|
||||
+ " echo '-A OUTPUT -d 169.254.170.23/32 -p tcp -m tcp --dport 80 -j DNAT --to-destination 172.18.0.9:4566'\n"
|
||||
+ " echo '-A OUTPUT -j KUBE-SERVICES'\n"
|
||||
+ "fi\n"
|
||||
+ "if [ \"$*\" = '-t nat -S FLOCI-LINK-LOCAL' ]; then\n"
|
||||
+ " echo '-N FLOCI-LINK-LOCAL'\n"
|
||||
+ " echo '-A FLOCI-LINK-LOCAL -s 10.42.0.0/16 -d 169.254.169.254/32 -p tcp -m tcp --dport 80 -j DNAT"
|
||||
+ " --to-destination 169.254.169.254:80'\n"
|
||||
+ " echo '-A FLOCI-LINK-LOCAL -s 10.42.0.0/16 -d 169.254.170.23/32 -p tcp -m tcp --dport 80 -j DNAT"
|
||||
+ " --to-destination 169.254.170.23:80'\n"
|
||||
+ "fi\n");
|
||||
HelperShellFixture.writeTool(bin, "nslookup", "echo \"$*\" >> '" + dir.resolve("nslookup-calls") + "'\n"
|
||||
+ "[ \"$1\" = floci-under-test.internal ] || exit 1\n"
|
||||
+ "printf 'Server:\\t\\t127.0.0.11\\nAddress:\\t127.0.0.11:53\\n\\nNon-authoritative answer:\\n"
|
||||
+ "Name:\\tfloci-under-test.internal\\nAddress: 172.18.0.2\\n'\n");
|
||||
HelperShellFixture.writeTool(bin, "wget", "[ -z \"${http_proxy:-}\" ] || exit 2\n"
|
||||
+ "echo 'wget: server returned error: HTTP/1.1 400 Bad Request' >&2\nexit 1\n");
|
||||
return bin;
|
||||
}
|
||||
|
||||
/**
|
||||
* A process named socat, as the relay an older Floci ran is, with that relay's arguments for {@code bindIp}. It
|
||||
* ends on SIGTERM.
|
||||
*/
|
||||
private static Process startFakeRelay(Path bin, String bindIp) throws Exception {
|
||||
Path relay = Files.createDirectories(bin.resolveSibling("relay")).resolve("socat");
|
||||
if (!Files.exists(relay)) {
|
||||
HelperShellFixture.writeTool(relay.getParent(), "socat",
|
||||
"trap 'kill \"$child\" 2>/dev/null; exit 0' TERM\nsleep 60 &\nchild=$!\nwait \"$child\"\n");
|
||||
}
|
||||
return new ProcessBuilder(relay.toString(), "TCP-LISTEN:80,bind=" + bindIp + ",fork,reuseaddr",
|
||||
"TCP:172.18.0.9:4566").start();
|
||||
}
|
||||
|
||||
/** {@code command}, an {@code sh -c} one, run with each command it runs printed to its output ({@code sh -x}). */
|
||||
private static String[] traced(String[] command) {
|
||||
List<String> arguments = new ArrayList<>(List.of(command));
|
||||
arguments.add(1, "-x");
|
||||
return arguments.toArray(String[]::new);
|
||||
}
|
||||
|
||||
/** The {@code kill} commands a {@link #traced} shell ran, as its trace prints them: {@code kill <pid>}. */
|
||||
private static List<String> tracedKills(Path dir) throws Exception {
|
||||
return HelperShellFixture.output(dir).lines()
|
||||
.filter(line -> line.matches("\\++ kill .*"))
|
||||
.map(line -> line.substring(line.indexOf(' ') + 1))
|
||||
.toList();
|
||||
}
|
||||
|
||||
private static List<String> calls(Path record) throws Exception {
|
||||
return Files.exists(record) ? Files.readAllLines(record) : List.of();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package io.floci.aws.testing;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import io.floci.aws.core.common.docker.ContainerExec;
|
||||
import io.floci.aws.services.eks.EksClusterManager;
|
||||
import io.floci.aws.services.eks.model.Cluster;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
/**
|
||||
* The k3s node of a cluster that a Docker integration test starts through {@link EksClusterManager}, with
|
||||
* {@code kubectl} and other commands run in it.
|
||||
*/
|
||||
public final class EksTestNode {
|
||||
|
||||
private static final Duration POLL_INTERVAL = Duration.ofSeconds(2);
|
||||
|
||||
private final DockerClient dockerClient;
|
||||
private final EksClusterManager eksClusterManager;
|
||||
private final Cluster cluster;
|
||||
|
||||
private EksTestNode(DockerClient dockerClient, EksClusterManager eksClusterManager, Cluster cluster) {
|
||||
this.dockerClient = dockerClient;
|
||||
this.eksClusterManager = eksClusterManager;
|
||||
this.cluster = cluster;
|
||||
}
|
||||
|
||||
/** A cluster named {@code name} in us-east-1 of {@code account}, not started yet. */
|
||||
public static Cluster cluster(String account, String name) {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setName(name);
|
||||
cluster.setAccountId(account);
|
||||
cluster.setArn("arn:aws:eks:us-east-1:" + account + ":cluster/" + name);
|
||||
cluster.setCreatedAt(Instant.now());
|
||||
cluster.setRoleArn("arn:aws:iam::" + account + ":role/eks-service-role");
|
||||
return cluster;
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts {@code cluster}'s node and waits, up to {@code apiServerTimeout}, until its API server answers, then until
|
||||
* the controller manager has created the default service account, which a pod needs before it can be created.
|
||||
*/
|
||||
public static EksTestNode start(DockerClient dockerClient, EksClusterManager eksClusterManager, Cluster cluster,
|
||||
Duration apiServerTimeout) {
|
||||
eksClusterManager.startCluster(cluster);
|
||||
assertNotNull(cluster.getContainerId(), "Container ID must not be null");
|
||||
EksTestNode node = new EksTestNode(dockerClient, eksClusterManager, cluster);
|
||||
node.awaitApiServer(apiServerTimeout);
|
||||
eksClusterManager.finalizeCluster(cluster);
|
||||
await("default serviceaccount created").atMost(Duration.ofSeconds(30)).pollInterval(POLL_INTERVAL)
|
||||
.until(() -> node.kubectl("get", "serviceaccount", "default").exitCode() == 0);
|
||||
return node;
|
||||
}
|
||||
|
||||
/** The node's container, as the cluster names it now. */
|
||||
public String containerId() {
|
||||
return cluster.getContainerId();
|
||||
}
|
||||
|
||||
/** Waits up to {@code timeout} until the node's API server answers, as after the node starts again. */
|
||||
public void awaitApiServer(Duration timeout) {
|
||||
await("k3s API server ready").atMost(timeout).pollInterval(POLL_INTERVAL)
|
||||
.until(() -> eksClusterManager.isReady(cluster));
|
||||
}
|
||||
|
||||
/** Applies {@code yaml} with {@code kubectl apply}. */
|
||||
public void apply(String yaml) {
|
||||
ContainerExec.Result applied = exec("sh", "-c", "cat << 'EOF' | kubectl apply -f -\n" + yaml + "\nEOF");
|
||||
assertEquals(0, applied.exitCode(), "kubectl apply failed: " + applied.stderr());
|
||||
}
|
||||
|
||||
/**
|
||||
* Waits up to {@code timeout} until pod {@code pod} of the default namespace runs, reporting its container's state
|
||||
* if it doesn't.
|
||||
*/
|
||||
public void awaitPodRunning(String pod, Duration timeout) {
|
||||
await("pod " + pod + " running").atMost(timeout).pollInterval(POLL_INTERVAL)
|
||||
.untilAsserted(() -> assertEquals("Running",
|
||||
kubectl("get", "pod", pod, "-o", "jsonpath={.status.phase}").stdout().trim(),
|
||||
() -> "the pod must start, but its container reports: " + kubectl("get", "pod", pod, "-o",
|
||||
"jsonpath={.status.containerStatuses[0].state}").stdout()));
|
||||
}
|
||||
|
||||
public ContainerExec.Result kubectl(String... args) {
|
||||
String[] command = new String[args.length + 1];
|
||||
command[0] = "kubectl";
|
||||
System.arraycopy(args, 0, command, 1, args.length);
|
||||
return exec(command);
|
||||
}
|
||||
|
||||
public ContainerExec.Result exec(String... command) {
|
||||
return ContainerExec.run(dockerClient, containerId(), command, 30).throwIfTimedOut(containerId());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package io.floci.aws.testing;
|
||||
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.net.InetSocketAddress;
|
||||
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.Optional;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeTrue;
|
||||
|
||||
/**
|
||||
* Runs the helper shells Floci execs inside a guest (the IMDS proxy's, the sshd install probe, an
|
||||
* EKS node's Pod Identity forward) on this host with {@code /bin/sh}, against fake system tools on
|
||||
* PATH, with the environment an application image hands a {@code docker exec}.
|
||||
*/
|
||||
public final class HelperShellFixture {
|
||||
|
||||
/** What an application image can carry into a {@code docker exec}, plus one setting the shells must keep. */
|
||||
public 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.
|
||||
*/
|
||||
public 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. */
|
||||
public static Map<String, String> applicationEnvironment(Map<String, String> settings) {
|
||||
Map<String, String> environment = new HashMap<>(APPLICATION_ENVIRONMENT);
|
||||
environment.putAll(settings);
|
||||
return environment;
|
||||
}
|
||||
|
||||
public 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));
|
||||
}
|
||||
|
||||
/** Where {@code tool} is on this host's PATH, if it is. */
|
||||
public static Optional<Path> onPath(String tool) {
|
||||
for (String dir : System.getenv().getOrDefault("PATH", "").split(File.pathSeparator)) {
|
||||
Path candidate = Path.of(dir, tool);
|
||||
if (!dir.isEmpty() && Files.isExecutable(candidate)) {
|
||||
return Optional.of(candidate.toAbsolutePath());
|
||||
}
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Links each of this host's {@code tools} into {@code bin}, so a PATH of {@code bin} alone
|
||||
* offers them and nothing else. Skips the test when the host lacks one.
|
||||
*/
|
||||
public static void linkHostTools(Path bin, List<String> tools) throws IOException {
|
||||
for (String tool : tools) {
|
||||
Optional<Path> found = onPath(tool);
|
||||
assumeTrue(found.isPresent(), tool + " is not installed on this host");
|
||||
Files.createSymbolicLink(bin.resolve(tool), found.get());
|
||||
}
|
||||
}
|
||||
|
||||
/** A proxy that records each request it is sent and answers 502, so its answer is never mistaken for the endpoint's. */
|
||||
public static HttpServer failingProxy(List<String> proxied) throws IOException {
|
||||
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. */
|
||||
public 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", "");
|
||||
}
|
||||
|
||||
/** Runs a generated helper shell with {@code /bin/sh}, its output going to {@link #output}. */
|
||||
public 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();
|
||||
}
|
||||
}
|
||||
|
||||
public static String output(Path directory) throws IOException {
|
||||
return Files.readString(directory.resolve("shell-output"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user