mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(eks): implement pod identity association management (#4012)
* feat(eks): implement pod identity association management * fix(eks): use instance SecureRandom for native image compatibility
This commit is contained in:
1 parent
648ea26cc9
commit
5a8ffd0272
11 files changed
+1107
-16
No files matched your search
+33
-8
@@ -3,7 +3,7 @@
|
||||
**Protocol:** REST-JSON
|
||||
**Endpoint:** `http://localhost:4566/` (path-routed via JAX-RS)
|
||||
|
||||
EKS uses a standard REST API with JSON bodies — not the JSON 1.1 (`X-Amz-Target`) or Query protocol.
|
||||
EKS uses a standard REST API with JSON bodies: not the JSON 1.1 (`X-Amz-Target`) or Query protocol.
|
||||
|
||||
## Supported Operations
|
||||
|
||||
@@ -17,6 +17,11 @@ EKS uses a standard REST API with JSON bodies — not the JSON 1.1 (`X-Amz-Targe
|
||||
| `DescribeAccessEntry` | Describe an access entry by IAM principal ARN |
|
||||
| `ListAccessEntries` | List principal ARNs with pagination |
|
||||
| `DeleteAccessEntry` | Delete access-entry metadata |
|
||||
| `CreatePodIdentityAssociation` | Create a pod identity association between a service account and IAM role |
|
||||
| `DescribePodIdentityAssociation` | Describe a pod identity association by association ID |
|
||||
| `ListPodIdentityAssociations` | List pod identity associations in a cluster with optional filtering and pagination |
|
||||
| `UpdatePodIdentityAssociation` | Update the IAM role, target role, or session tags for a pod identity association |
|
||||
| `DeletePodIdentityAssociation` | Delete a pod identity association |
|
||||
| `CreateNodegroup` | Create node group metadata for a cluster |
|
||||
| `DescribeNodegroup` | Describe a node group by cluster and name |
|
||||
| `ListNodegroups` | List node group names for a cluster |
|
||||
@@ -67,6 +72,26 @@ aws --endpoint-url http://localhost:4566 eks create-access-entry \
|
||||
--type EC2_LINUX
|
||||
```
|
||||
|
||||
## Pod Identity Associations
|
||||
|
||||
Floci supports the EKS Pod Identity association management plane. You can map a Kubernetes `(namespace, serviceAccount)` pair directly to an IAM role without configuring OpenID Connect (OIDC) identity providers or mutating ServiceAccount annotations.
|
||||
|
||||
### Management Plane Operations
|
||||
|
||||
- **Creation**: `CreatePodIdentityAssociation` associates a Kubernetes service account in a specific namespace with an IAM role ARN. The referenced IAM role must exist in IAM. A cluster cannot have duplicate associations for the same `(namespace, serviceAccount)` pair (rejected with HTTP 409 `ResourceInUseException`). Requests support idempotency via `clientRequestToken`.
|
||||
- **Retrieval**: `DescribePodIdentityAssociation` retrieves full association details by cluster name and association ID (`a-` followed by 17 alphanumeric characters).
|
||||
- **Listing**: `ListPodIdentityAssociations` returns summaries of associations for a cluster, with optional filtering by `namespace` and `serviceAccount`, plus pagination using `maxResults` (1-100) and cluster-bound `nextToken`.
|
||||
- **Updating**: `UpdatePodIdentityAssociation` modifies the associated `roleArn`, `targetRoleArn`, `disableSessionTags`, or `policy`.
|
||||
- **Deletion**: `DeletePodIdentityAssociation` removes an association and returns its final metadata. Deleting an EKS cluster automatically purges all of its pod identity associations.
|
||||
|
||||
### Limitations and Scope
|
||||
|
||||
Credentials delivery directly into pods is not yet supported:
|
||||
- Mutating webhook injection for pod environment variables (`AWS_CONTAINER_CREDENTIALS_FULL_URI`, `AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE`) is not implemented.
|
||||
- The link-local metadata credential endpoint (`169.254.170.23`) is not implemented.
|
||||
|
||||
Applications running inside pods cannot currently exchange tokens for temporary AWS credentials via the link-local endpoint. Use access entries, node credentials, or explicit credential configuration until the pod identity agent endpoint is added.
|
||||
|
||||
## Cluster security group
|
||||
|
||||
When an EKS cluster is created with a VPC (either specified directly or resolved from subnets), Floci provisions a dedicated EC2 cluster security group and populates its ID in `cluster.resourcesVpcConfig.clusterSecurityGroupId` on both `CreateCluster` and `DescribeCluster` responses.
|
||||
@@ -158,9 +183,9 @@ Cluster metadata is stored in-process. No Docker containers are started. The clu
|
||||
|
||||
### Real mode (`mock: false`, default)
|
||||
|
||||
Floci starts a **k3s** (`rancher/k3s`) container for each cluster. The k3s API server is exposed on a host port from the configured range (`6500–6599`). Once `/readyz` responds, the cluster transitions to `ACTIVE` and the CA certificate is extracted from the kubeconfig.
|
||||
Floci starts a **k3s** (`rancher/k3s`) container for each cluster. The k3s API server is exposed on a host port from the configured range (`6500-6599`). Once `/readyz` responds, the cluster transitions to `ACTIVE` and the CA certificate is extracted from the kubeconfig.
|
||||
|
||||
By default `describe-cluster` returns a **host-reachable** endpoint (`https://localhost:<hostPort>`); the k3s server certificate includes a `localhost` SAN, so it verifies against the CA in `cluster.certificateAuthority.data`. Set `endpoint-mode: network` to return the container DNS name (`https://floci-eks-<name>:6443`) instead — reachable from other containers on the Docker network (the pre-#1118 behaviour). In `network` mode the endpoint falls back to the host-reachable form when Floci runs natively, since there is no container DNS name a host client could use.
|
||||
By default `describe-cluster` returns a **host-reachable** endpoint (`https://localhost:<hostPort>`); the k3s server certificate includes a `localhost` SAN, so it verifies against the CA in `cluster.certificateAuthority.data`. Set `endpoint-mode: network` to return the container DNS name (`https://floci-eks-<name>:6443`) instead: reachable from other containers on the Docker network (the pre-#1118 behaviour). In `network` mode the endpoint falls back to the host-reachable form when Floci runs natively, since there is no container DNS name a host client could use.
|
||||
|
||||
#### Connecting with `kubectl` (native AWS workflow)
|
||||
|
||||
@@ -180,7 +205,7 @@ Temporary IAM credentials must include their `AWS_SESSION_TOKEN` when signing th
|
||||
This webhook is enabled by default (`iam-auth-webhook: true`). Set it to `false` to start k3s without it (in which case `aws eks get-token` tokens are rejected with `401`).
|
||||
|
||||
!!! note "Webhook reachability & networking"
|
||||
The k3s API server must be able to reach Floci's webhook URL. When Floci runs natively, k3s containers reach it via `host.docker.internal`; when Floci runs in a container (`floci start`), Floci and the k3s containers share a Docker network. The k3s network is taken from `FLOCI_SERVICES_EKS_DOCKER_NETWORK` if set, otherwise the global `FLOCI_SERVICES_DOCKER_NETWORK`, otherwise the network Floci is itself attached to (auto-detected) — so no EKS-specific network configuration is required in the standard compose setup.
|
||||
The k3s API server must be able to reach Floci's webhook URL. When Floci runs natively, k3s containers reach it via `host.docker.internal`; when Floci runs in a container (`floci start`), Floci and the k3s containers share a Docker network. The k3s network is taken from `FLOCI_SERVICES_EKS_DOCKER_NETWORK` if set, otherwise the global `FLOCI_SERVICES_DOCKER_NETWORK`, otherwise the network Floci is itself attached to (auto-detected), so no EKS-specific network configuration is required in the standard compose setup.
|
||||
|
||||
The webhook kubeconfig is copied into the k3s container via the Docker API (not bind-mounted), so the token-webhook works the same in native and Docker-in-Docker modes with **no host-path / `host-persistent-path` configuration**.
|
||||
|
||||
@@ -200,7 +225,7 @@ services:
|
||||
```
|
||||
|
||||
!!! note "No port mapping needed for k3s ports"
|
||||
k3s containers bind their API server port (6500–6599) directly on the host via Docker — no `ports:` entry is required in `docker-compose.yml`. See [Ports Reference](../configuration/ports.md#ports-65006599-eks-real-mode) for the full explanation.
|
||||
k3s containers bind their API server port (6500-6599) directly on the host via Docker: no `ports:` entry is required in `docker-compose.yml`. See [Ports Reference](../configuration/ports.md#ports-65006599-eks-real-mode) for the full explanation.
|
||||
|
||||
#### Clusters survive a restart
|
||||
|
||||
@@ -208,7 +233,7 @@ With a persistent [storage mode](../configuration/storage.md) (the default), clu
|
||||
`eks-clusters.json` are **re-latched to their k3s containers when Floci starts**:
|
||||
|
||||
- A surviving container (for example after a Docker Desktop / daemon reboot) is adopted and
|
||||
started in place, keeping its published API server port and data volume — deployments come
|
||||
started in place, keeping its published API server port and data volume: deployments come
|
||||
back as they were.
|
||||
- A missing container is recreated. Its named k3s data volume (`floci-eks-<name>`; for a
|
||||
[non-default account](../configuration/multi-account.md), `floci-eks-<account>.<name>`) is
|
||||
@@ -248,7 +273,7 @@ back (for example Docker is unavailable), the cluster is marked `FAILED` instead
|
||||
Images pushed to the [Floci ECR registry](ecr.md) use `localhost`-based repository URIs
|
||||
(for example `000000000000.dkr.ecr.us-east-1.localhost:4566/my-repo:tag`). Inside a k3s
|
||||
cluster that hostname would resolve to the k3s container itself, and containerd insists
|
||||
on HTTPS for anything it doesn't recognize as loopback — so, out of the box, k3s cannot
|
||||
on HTTPS for anything it doesn't recognize as loopback: so, out of the box, k3s cannot
|
||||
pull from the registry even though `docker push` from the host works.
|
||||
|
||||
Floci solves this at cluster creation: each new k3s container gets a generated
|
||||
@@ -291,7 +316,7 @@ Requirements and limits:
|
||||
Use `FLOCI_SERVICES_EKS_MOCK=true` when you only need the API shape:
|
||||
|
||||
```yaml
|
||||
# docker-compose.yml — CI / test environment
|
||||
# docker-compose.yml: CI / test environment
|
||||
services:
|
||||
floci:
|
||||
image: floci/floci:latest
|
||||
|
||||
@@ -6,8 +6,11 @@ import io.github.hectorvent.floci.services.eks.model.CreateAccessEntryRequest;
|
||||
import io.github.hectorvent.floci.services.eks.model.CreateClusterRequest;
|
||||
import io.github.hectorvent.floci.services.eks.model.CreateFargateProfileRequest;
|
||||
import io.github.hectorvent.floci.services.eks.model.CreateNodeGroupRequest;
|
||||
import io.github.hectorvent.floci.services.eks.model.CreatePodIdentityAssociationRequest;
|
||||
import io.github.hectorvent.floci.services.eks.model.FargateProfile;
|
||||
import io.github.hectorvent.floci.services.eks.model.Nodegroup;
|
||||
import io.github.hectorvent.floci.services.eks.model.PodIdentityAssociation;
|
||||
import io.github.hectorvent.floci.services.eks.model.UpdatePodIdentityAssociationRequest;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.Consumes;
|
||||
import jakarta.ws.rs.DELETE;
|
||||
@@ -27,7 +30,7 @@ import java.util.Map;
|
||||
* EKS REST-JSON controller.
|
||||
*
|
||||
* <p>
|
||||
* EKS uses standard HTTP verbs with JSON bodies — not JSON 1.1 (X-Amz-Target)
|
||||
* EKS uses standard HTTP verbs with JSON bodies - not JSON 1.1 (X-Amz-Target)
|
||||
* or Query protocol.
|
||||
*/
|
||||
@Path("/")
|
||||
@@ -37,11 +40,14 @@ public class EksController {
|
||||
|
||||
private final EksService eksService;
|
||||
private final EksAccessEntryService accessEntries;
|
||||
private final EksPodIdentityAssociationService podIdentityAssociations;
|
||||
|
||||
@Inject
|
||||
public EksController(EksService eksService, EksAccessEntryService accessEntries) {
|
||||
public EksController(EksService eksService, EksAccessEntryService accessEntries,
|
||||
EksPodIdentityAssociationService podIdentityAssociations) {
|
||||
this.eksService = eksService;
|
||||
this.accessEntries = accessEntries;
|
||||
this.podIdentityAssociations = podIdentityAssociations;
|
||||
}
|
||||
|
||||
@POST
|
||||
@@ -183,10 +189,55 @@ public class EksController {
|
||||
return Response.ok(Map.of("identityProviderConfigs", List.of())).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/clusters/{name}/pod-identity-associations")
|
||||
public Response createPodIdentityAssociation(@PathParam("name") String name,
|
||||
CreatePodIdentityAssociationRequest request) {
|
||||
Cluster cluster = eksService.describeCluster(name);
|
||||
PodIdentityAssociation association = podIdentityAssociations.create(cluster, request);
|
||||
return Response.ok(Map.of("association", association)).build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/clusters/{name}/pod-identity-associations")
|
||||
public Response listPodIdentityAssociations(@PathParam("name") String name) {
|
||||
eksService.describeCluster(name);
|
||||
return Response.ok(Map.of("associations", List.of())).build();
|
||||
public Response listPodIdentityAssociations(@PathParam("name") String name,
|
||||
@QueryParam("namespace") String namespace,
|
||||
@QueryParam("serviceAccount") String serviceAccount,
|
||||
@QueryParam("maxResults") String maxResults,
|
||||
@QueryParam("nextToken") String nextToken) {
|
||||
Cluster cluster = eksService.describeCluster(name);
|
||||
EksPodIdentityAssociationService.Page page = podIdentityAssociations.list(cluster, namespace, serviceAccount,
|
||||
Pagination.parseMaxResults(maxResults, "InvalidParameterException"), nextToken);
|
||||
return Response.ok(page.nextToken() == null
|
||||
? Map.of("associations", page.associations())
|
||||
: Map.of("associations", page.associations(), "nextToken", page.nextToken())).build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/clusters/{name}/pod-identity-associations/{associationId}")
|
||||
public Response describePodIdentityAssociation(@PathParam("name") String name,
|
||||
@PathParam("associationId") String associationId) {
|
||||
Cluster cluster = eksService.describeCluster(name);
|
||||
PodIdentityAssociation association = podIdentityAssociations.describe(cluster, associationId);
|
||||
return Response.ok(Map.of("association", association)).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/clusters/{name}/pod-identity-associations/{associationId}")
|
||||
public Response updatePodIdentityAssociation(@PathParam("name") String name,
|
||||
@PathParam("associationId") String associationId,
|
||||
UpdatePodIdentityAssociationRequest request) {
|
||||
Cluster cluster = eksService.describeCluster(name);
|
||||
PodIdentityAssociation association = podIdentityAssociations.update(cluster, associationId, request);
|
||||
return Response.ok(Map.of("association", association)).build();
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/clusters/{name}/pod-identity-associations/{associationId}")
|
||||
public Response deletePodIdentityAssociation(@PathParam("name") String name,
|
||||
@PathParam("associationId") String associationId) {
|
||||
Cluster cluster = eksService.describeCluster(name);
|
||||
PodIdentityAssociation association = podIdentityAssociations.delete(cluster, associationId);
|
||||
return Response.ok(Map.of("association", association)).build();
|
||||
}
|
||||
}
|
||||
+342
@@ -0,0 +1,342 @@
|
||||
package io.github.hectorvent.floci.services.eks;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.eks.model.Cluster;
|
||||
import io.github.hectorvent.floci.services.eks.model.ClusterStatus;
|
||||
import io.github.hectorvent.floci.services.eks.model.CreatePodIdentityAssociationRequest;
|
||||
import io.github.hectorvent.floci.services.eks.model.PodIdentityAssociation;
|
||||
import io.github.hectorvent.floci.services.eks.model.PodIdentityAssociationSummary;
|
||||
import io.github.hectorvent.floci.services.eks.model.UpdatePodIdentityAssociationRequest;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Manages EKS Pod Identity association metadata.
|
||||
* Credentials delivery to pods (webhook and link-local credential endpoint) is separate.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class EksPodIdentityAssociationService {
|
||||
|
||||
private static final String ID_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz";
|
||||
|
||||
private final StorageBackend<String, StoredAssociation> associations;
|
||||
private final IamService iam;
|
||||
private final SecureRandom random = new SecureRandom();
|
||||
|
||||
@Inject
|
||||
public EksPodIdentityAssociationService(StorageFactory factory, IamService iam) {
|
||||
this(factory.create("eks", "eks-pod-identity-associations.json",
|
||||
new TypeReference<Map<String, StoredAssociation>>() {}), iam);
|
||||
}
|
||||
|
||||
EksPodIdentityAssociationService(StorageBackend<String, StoredAssociation> associations, IamService iam) {
|
||||
this.associations = associations;
|
||||
this.iam = iam;
|
||||
}
|
||||
|
||||
@RegisterForReflection
|
||||
public record StoredAssociation(PodIdentityAssociation association, String clientRequestToken) {}
|
||||
|
||||
@RegisterForReflection
|
||||
public record Page(List<PodIdentityAssociationSummary> associations, String nextToken) {}
|
||||
|
||||
public synchronized PodIdentityAssociation create(Cluster cluster, CreatePodIdentityAssociationRequest request) {
|
||||
requireActiveCluster(cluster);
|
||||
if (request == null) {
|
||||
throw invalid("Request body is required");
|
||||
}
|
||||
String namespace = request.namespace();
|
||||
if (namespace == null || namespace.isBlank()) {
|
||||
throw invalid("namespace is required");
|
||||
}
|
||||
if (namespace.length() > 63) {
|
||||
throw invalid("namespace must be at most 63 characters");
|
||||
}
|
||||
String serviceAccount = request.serviceAccount();
|
||||
if (serviceAccount == null || serviceAccount.isBlank()) {
|
||||
throw invalid("serviceAccount is required");
|
||||
}
|
||||
if (serviceAccount.length() > 63) {
|
||||
throw invalid("serviceAccount must be at most 63 characters");
|
||||
}
|
||||
String roleArn = request.roleArn();
|
||||
if (roleArn == null || roleArn.isBlank()) {
|
||||
throw invalid("roleArn is required");
|
||||
}
|
||||
validateRoleArn(cluster, roleArn, "roleArn");
|
||||
|
||||
if (request.targetRoleArn() != null && !request.targetRoleArn().isBlank()) {
|
||||
validateTargetRoleArn(cluster, request.targetRoleArn());
|
||||
}
|
||||
|
||||
Map<String, String> tags = request.tags() == null ? Map.of() : request.tags();
|
||||
validateTags(tags);
|
||||
|
||||
String prefix = prefix(cluster);
|
||||
String token = request.clientRequestToken();
|
||||
List<StoredAssociation> clusterAssociations = associations.scan(key -> key.startsWith(prefix));
|
||||
|
||||
if (token != null && !token.isBlank()) {
|
||||
for (StoredAssociation stored : clusterAssociations) {
|
||||
if (token.equals(stored.clientRequestToken())) {
|
||||
PodIdentityAssociation previous = stored.association();
|
||||
if (namespace.equals(previous.namespace())
|
||||
&& serviceAccount.equals(previous.serviceAccount())
|
||||
&& roleArn.equals(previous.roleArn())
|
||||
&& Objects.equals(request.targetRoleArn(), previous.targetRoleArn())
|
||||
&& Objects.equals(request.disableSessionTags(), previous.disableSessionTags())
|
||||
&& Objects.equals(request.policy(), previous.policy())
|
||||
&& tags.equals(previous.tags())) {
|
||||
return previous;
|
||||
}
|
||||
throw invalid("clientRequestToken was already used with different parameters");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (StoredAssociation stored : clusterAssociations) {
|
||||
PodIdentityAssociation existing = stored.association();
|
||||
if (namespace.equals(existing.namespace()) && serviceAccount.equals(existing.serviceAccount())) {
|
||||
throw new AwsException("ResourceInUseException", "Association already exists: " + existing.associationId(), 409);
|
||||
}
|
||||
}
|
||||
|
||||
String associationId = generateAssociationId();
|
||||
String[] clusterArn = cluster.getArn().split(":", 6);
|
||||
String associationArn = "arn:" + clusterArn[1] + ":eks:" + clusterArn[3] + ":"
|
||||
+ clusterArn[4] + ":podidentityassociation/" + cluster.getName() + "/" + associationId;
|
||||
double now = Instant.now().toEpochMilli() / 1000.0;
|
||||
String externalId = UUID.randomUUID().toString();
|
||||
|
||||
PodIdentityAssociation association = new PodIdentityAssociation(
|
||||
cluster.getName(),
|
||||
namespace,
|
||||
serviceAccount,
|
||||
roleArn,
|
||||
associationArn,
|
||||
associationId,
|
||||
Map.copyOf(tags),
|
||||
now,
|
||||
now,
|
||||
null,
|
||||
request.targetRoleArn(),
|
||||
request.disableSessionTags(),
|
||||
externalId,
|
||||
request.policy()
|
||||
);
|
||||
associations.put(prefix + associationId, new StoredAssociation(association, token));
|
||||
return association;
|
||||
}
|
||||
|
||||
public synchronized PodIdentityAssociation describe(Cluster cluster, String associationId) {
|
||||
requireActiveCluster(cluster);
|
||||
if (associationId == null || associationId.isBlank()) {
|
||||
throw invalid("associationId is required");
|
||||
}
|
||||
return associations.get(prefix(cluster) + associationId)
|
||||
.map(StoredAssociation::association)
|
||||
.orElseThrow(() -> notFound(associationId));
|
||||
}
|
||||
|
||||
public synchronized PodIdentityAssociation update(Cluster cluster, String associationId,
|
||||
UpdatePodIdentityAssociationRequest request) {
|
||||
requireActiveCluster(cluster);
|
||||
if (associationId == null || associationId.isBlank()) {
|
||||
throw invalid("associationId is required");
|
||||
}
|
||||
if (request == null) {
|
||||
throw invalid("Request body is required");
|
||||
}
|
||||
StoredAssociation stored = associations.get(prefix(cluster) + associationId)
|
||||
.orElseThrow(() -> notFound(associationId));
|
||||
PodIdentityAssociation current = stored.association();
|
||||
|
||||
if (request.roleArn() == null && request.targetRoleArn() == null
|
||||
&& request.disableSessionTags() == null && request.policy() == null) {
|
||||
throw invalid("At least one parameter must be specified in the update request");
|
||||
}
|
||||
|
||||
String token = request.clientRequestToken();
|
||||
if (token != null && !token.isBlank() && token.equals(stored.clientRequestToken())) {
|
||||
boolean matches = (request.roleArn() == null || request.roleArn().equals(current.roleArn()))
|
||||
&& Objects.equals(request.targetRoleArn(), current.targetRoleArn())
|
||||
&& Objects.equals(request.disableSessionTags(), current.disableSessionTags())
|
||||
&& Objects.equals(request.policy(), current.policy());
|
||||
if (matches) {
|
||||
return current;
|
||||
}
|
||||
throw invalid("clientRequestToken was already used with different parameters");
|
||||
}
|
||||
|
||||
String newRoleArn = current.roleArn();
|
||||
if (request.roleArn() != null) {
|
||||
validateRoleArn(cluster, request.roleArn(), "roleArn");
|
||||
newRoleArn = request.roleArn();
|
||||
}
|
||||
String newTargetRoleArn = current.targetRoleArn();
|
||||
if (request.targetRoleArn() != null) {
|
||||
validateTargetRoleArn(cluster, request.targetRoleArn());
|
||||
newTargetRoleArn = request.targetRoleArn();
|
||||
}
|
||||
Boolean newDisableSessionTags = request.disableSessionTags() != null
|
||||
? request.disableSessionTags() : current.disableSessionTags();
|
||||
String newPolicy = request.policy() != null ? request.policy() : current.policy();
|
||||
|
||||
double now = Instant.now().toEpochMilli() / 1000.0;
|
||||
PodIdentityAssociation updated = new PodIdentityAssociation(
|
||||
current.clusterName(),
|
||||
current.namespace(),
|
||||
current.serviceAccount(),
|
||||
newRoleArn,
|
||||
current.associationArn(),
|
||||
current.associationId(),
|
||||
current.tags(),
|
||||
current.createdAt(),
|
||||
now,
|
||||
current.ownerArn(),
|
||||
newTargetRoleArn,
|
||||
newDisableSessionTags,
|
||||
current.externalId(),
|
||||
newPolicy
|
||||
);
|
||||
associations.put(prefix(cluster) + associationId,
|
||||
new StoredAssociation(updated, token != null ? token : stored.clientRequestToken()));
|
||||
return updated;
|
||||
}
|
||||
|
||||
public synchronized PodIdentityAssociation delete(Cluster cluster, String associationId) {
|
||||
PodIdentityAssociation existing = describe(cluster, associationId);
|
||||
associations.delete(prefix(cluster) + associationId);
|
||||
return existing;
|
||||
}
|
||||
|
||||
public synchronized Page list(Cluster cluster, String namespace, String serviceAccount,
|
||||
Integer maxResults, String nextToken) {
|
||||
requireActiveCluster(cluster);
|
||||
int limit = maxResults == null ? 100 : maxResults;
|
||||
if (limit < 1 || limit > 100) {
|
||||
throw invalid("maxResults must be between 1 and 100");
|
||||
}
|
||||
String prefix = prefix(cluster);
|
||||
String after = "";
|
||||
if (nextToken != null && !nextToken.isBlank()) {
|
||||
try {
|
||||
String decoded = new String(Base64.getUrlDecoder().decode(nextToken), StandardCharsets.UTF_8);
|
||||
if (!decoded.startsWith(prefix + "\n")) {
|
||||
throw invalid("nextToken does not belong to this cluster");
|
||||
}
|
||||
after = decoded.substring(prefix.length() + 1);
|
||||
if (after.isBlank()) {
|
||||
throw invalid("Invalid nextToken");
|
||||
}
|
||||
} catch (IllegalArgumentException exception) {
|
||||
throw invalid("Invalid nextToken");
|
||||
}
|
||||
}
|
||||
String cursor = after;
|
||||
List<PodIdentityAssociation> remaining = associations.scan(key -> key.startsWith(prefix)).stream()
|
||||
.map(StoredAssociation::association)
|
||||
.filter(a -> namespace == null || namespace.isBlank() || namespace.equals(a.namespace()))
|
||||
.filter(a -> serviceAccount == null || serviceAccount.isBlank() || serviceAccount.equals(a.serviceAccount()))
|
||||
.filter(a -> a.associationId().compareTo(cursor) > 0)
|
||||
.sorted(Comparator.comparing(PodIdentityAssociation::associationId))
|
||||
.toList();
|
||||
|
||||
List<PodIdentityAssociationSummary> page = remaining.stream()
|
||||
.limit(limit)
|
||||
.map(PodIdentityAssociationSummary::from)
|
||||
.toList();
|
||||
|
||||
String token = remaining.size() > limit
|
||||
? Base64.getUrlEncoder().withoutPadding().encodeToString(
|
||||
(prefix + "\n" + page.getLast().associationId()).getBytes(StandardCharsets.UTF_8))
|
||||
: null;
|
||||
|
||||
return new Page(page, token);
|
||||
}
|
||||
|
||||
public synchronized void deleteClusterAssociations(Cluster cluster) {
|
||||
String prefix = prefix(cluster);
|
||||
for (StoredAssociation stored : associations.scan(key -> key.startsWith(prefix))) {
|
||||
associations.delete(prefix + stored.association().associationId());
|
||||
}
|
||||
}
|
||||
|
||||
private static String prefix(Cluster cluster) {
|
||||
return cluster.getArn() + "/" + Objects.toString(cluster.getCreatedAt()) + "/";
|
||||
}
|
||||
|
||||
private static void requireActiveCluster(Cluster cluster) {
|
||||
if (cluster == null) {
|
||||
throw new AwsException("ResourceNotFoundException", "Cluster not found", 404);
|
||||
}
|
||||
if (cluster.getStatus() != ClusterStatus.ACTIVE) {
|
||||
throw new AwsException("InvalidRequestException", "Cluster must be ACTIVE", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private void validateRoleArn(Cluster cluster, String roleArn, String fieldName) {
|
||||
String[] arn = roleArn.split(":", 6);
|
||||
String[] clusterArn = cluster.getArn().split(":", 6);
|
||||
if (arn.length != 6 || !"arn".equals(arn[0]) || !arn[1].equals(clusterArn[1])
|
||||
|| !"iam".equals(arn[2]) || !arn[3].isEmpty() || !arn[4].matches("[0-9]{12}")
|
||||
|| !arn[5].startsWith("role/") || arn[5].startsWith("role/aws-service-role/")
|
||||
|| roleArn.endsWith("/")) {
|
||||
throw invalid(fieldName + " must identify an IAM role");
|
||||
}
|
||||
String roleName = roleArn.substring(roleArn.lastIndexOf('/') + 1);
|
||||
iam.findRole(arn[4], roleName)
|
||||
.filter(role -> roleArn.equals(role.getArn()))
|
||||
.orElseThrow(() -> invalid("IAM role does not exist"));
|
||||
}
|
||||
|
||||
private static void validateTargetRoleArn(Cluster cluster, String targetRoleArn) {
|
||||
String[] arn = targetRoleArn.split(":", 6);
|
||||
String[] clusterArn = cluster.getArn().split(":", 6);
|
||||
if (arn.length != 6 || !"arn".equals(arn[0]) || !arn[1].equals(clusterArn[1])
|
||||
|| !"iam".equals(arn[2]) || !arn[3].isEmpty() || !arn[4].matches("[0-9]{12}")
|
||||
|| !arn[5].startsWith("role/") || targetRoleArn.endsWith("/")) {
|
||||
throw invalid("targetRoleArn must identify an IAM role");
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateTags(Map<String, String> tags) {
|
||||
if (tags.size() > 50 || tags.entrySet().stream().anyMatch(tag -> tag.getKey() == null
|
||||
|| tag.getKey().isEmpty() || tag.getKey().length() > 128
|
||||
|| tag.getKey().startsWith("aws:") || tag.getKey().startsWith("AWS:")
|
||||
|| tag.getValue() == null || tag.getValue().length() > 256)) {
|
||||
throw invalid("Invalid tags");
|
||||
}
|
||||
}
|
||||
|
||||
private String generateAssociationId() {
|
||||
StringBuilder sb = new StringBuilder("a-");
|
||||
for (int i = 0; i < 17; i++) {
|
||||
sb.append(ID_ALPHABET.charAt(random.nextInt(ID_ALPHABET.length())));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private static AwsException notFound(String associationId) {
|
||||
return new AwsException("ResourceNotFoundException", "No association found for ID: " + associationId, 404);
|
||||
}
|
||||
|
||||
private static AwsException invalid(String message) {
|
||||
return new AwsException("InvalidParameterException", message, 400);
|
||||
}
|
||||
}
|
||||
@@ -87,12 +87,14 @@ public class EksService implements TagHandler, ResourceProvider {
|
||||
private final Ec2Service ec2Service;
|
||||
private final EksOidcService oidcService;
|
||||
private final EksAccessEntryService accessEntries;
|
||||
private final EksPodIdentityAssociationService podIdentityAssociations;
|
||||
private final ScheduledExecutorService poller = Executors.newSingleThreadScheduledExecutor();
|
||||
|
||||
@Inject
|
||||
public EksService(StorageFactory storageFactory, EmulatorConfig config,
|
||||
RegionResolver regionResolver, EksClusterManager clusterManager, Ec2Service ec2Service,
|
||||
EksOidcService oidcService, EksAccessEntryService accessEntries) {
|
||||
EksOidcService oidcService, EksAccessEntryService accessEntries,
|
||||
EksPodIdentityAssociationService podIdentityAssociations) {
|
||||
this.storage = storageFactory.create("eks", "eks-clusters.json",
|
||||
new TypeReference<Map<String, Cluster>>() {
|
||||
});
|
||||
@@ -108,6 +110,14 @@ public class EksService implements TagHandler, ResourceProvider {
|
||||
this.ec2Service = ec2Service;
|
||||
this.oidcService = oidcService;
|
||||
this.accessEntries = accessEntries;
|
||||
this.podIdentityAssociations = podIdentityAssociations;
|
||||
}
|
||||
|
||||
public EksService(StorageFactory storageFactory, EmulatorConfig config,
|
||||
RegionResolver regionResolver, EksClusterManager clusterManager, Ec2Service ec2Service,
|
||||
EksOidcService oidcService, EksAccessEntryService accessEntries) {
|
||||
this(storageFactory, config, regionResolver, clusterManager, ec2Service,
|
||||
oidcService, accessEntries, null);
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
@@ -523,6 +533,9 @@ public class EksService implements TagHandler, ResourceProvider {
|
||||
}
|
||||
deleteClusterSecurityGroup(cluster);
|
||||
accessEntries.deleteClusterEntries(cluster);
|
||||
if (podIdentityAssociations != null) {
|
||||
podIdentityAssociations.deleteClusterAssociations(cluster);
|
||||
}
|
||||
storage.delete(name);
|
||||
oidcService.deleteKey(name);
|
||||
return cluster;
|
||||
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package io.github.hectorvent.floci.services.eks.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public record CreatePodIdentityAssociationRequest(
|
||||
String clusterName,
|
||||
String namespace,
|
||||
String serviceAccount,
|
||||
String roleArn,
|
||||
String clientRequestToken,
|
||||
Map<String, String> tags,
|
||||
String targetRoleArn,
|
||||
Boolean disableSessionTags,
|
||||
String policy
|
||||
) {}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package io.github.hectorvent.floci.services.eks.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public record PodIdentityAssociation(
|
||||
String clusterName,
|
||||
String namespace,
|
||||
String serviceAccount,
|
||||
String roleArn,
|
||||
String associationArn,
|
||||
String associationId,
|
||||
Map<String, String> tags,
|
||||
double createdAt,
|
||||
double modifiedAt,
|
||||
String ownerArn,
|
||||
String targetRoleArn,
|
||||
Boolean disableSessionTags,
|
||||
String externalId,
|
||||
String policy
|
||||
) {}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package io.github.hectorvent.floci.services.eks.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public record PodIdentityAssociationSummary(
|
||||
String clusterName,
|
||||
String namespace,
|
||||
String serviceAccount,
|
||||
String associationArn,
|
||||
String associationId,
|
||||
String ownerArn
|
||||
) {
|
||||
public static PodIdentityAssociationSummary from(PodIdentityAssociation association) {
|
||||
return new PodIdentityAssociationSummary(
|
||||
association.clusterName(),
|
||||
association.namespace(),
|
||||
association.serviceAccount(),
|
||||
association.associationArn(),
|
||||
association.associationId(),
|
||||
association.ownerArn()
|
||||
);
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package io.github.hectorvent.floci.services.eks.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public record UpdatePodIdentityAssociationRequest(
|
||||
String roleArn,
|
||||
String clientRequestToken,
|
||||
String targetRoleArn,
|
||||
Boolean disableSessionTags,
|
||||
String policy
|
||||
) {}
|
||||
+301
@@ -0,0 +1,301 @@
|
||||
package io.github.hectorvent.floci.services.eks;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
|
||||
@QuarkusTest
|
||||
class EksPodIdentityAssociationIntegrationTest {
|
||||
|
||||
@Test
|
||||
void associationLifecycleRoundTrip() {
|
||||
String account = "123456789012";
|
||||
String name = "pia-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
String roleName = "role-" + name;
|
||||
String roleArn = "arn:aws:iam::" + account + ":role/" + roleName;
|
||||
String basePath = "/clusters/" + name + "/pod-identity-associations";
|
||||
|
||||
createRole(account, roleName);
|
||||
createCluster(account, name);
|
||||
|
||||
try {
|
||||
// 1. Create association
|
||||
Map<String, Object> createReq = Map.of(
|
||||
"namespace", "default",
|
||||
"serviceAccount", "my-service-account",
|
||||
"roleArn", roleArn,
|
||||
"clientRequestToken", "token-abc",
|
||||
"tags", Map.of("env", "test")
|
||||
);
|
||||
|
||||
String associationId = given().header("Authorization", auth(account, "eks"))
|
||||
.contentType("application/json")
|
||||
.body(createReq)
|
||||
.post(basePath)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.contentType(containsString("application/json"))
|
||||
.body("association.clusterName", equalTo(name))
|
||||
.body("association.namespace", equalTo("default"))
|
||||
.body("association.serviceAccount", equalTo("my-service-account"))
|
||||
.body("association.roleArn", equalTo(roleArn))
|
||||
.body("association.associationId", startsWith("a-"))
|
||||
.body("association.associationArn", startsWith("arn:aws:eks:us-east-1:" + account + ":podidentityassociation/" + name + "/a-"))
|
||||
.body("association.tags.env", equalTo("test"))
|
||||
.body("association.createdAt", instanceOf(Number.class))
|
||||
.body("association.modifiedAt", instanceOf(Number.class))
|
||||
.extract().path("association.associationId");
|
||||
|
||||
// 2. Idempotent retry with same parameters and token
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.contentType("application/json")
|
||||
.body(createReq)
|
||||
.post(basePath)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("association.associationId", equalTo(associationId));
|
||||
|
||||
// 3. Same token with different parameters returns 400
|
||||
Map<String, Object> conflictReq = Map.of(
|
||||
"namespace", "other-ns",
|
||||
"serviceAccount", "my-service-account",
|
||||
"roleArn", roleArn,
|
||||
"clientRequestToken", "token-abc"
|
||||
);
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.contentType("application/json")
|
||||
.body(conflictReq)
|
||||
.post(basePath)
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("InvalidParameterException"));
|
||||
|
||||
// 4. Duplicate (namespace, serviceAccount) returns 409
|
||||
Map<String, Object> duplicateReq = Map.of(
|
||||
"namespace", "default",
|
||||
"serviceAccount", "my-service-account",
|
||||
"roleArn", roleArn
|
||||
);
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.contentType("application/json")
|
||||
.body(duplicateReq)
|
||||
.post(basePath)
|
||||
.then()
|
||||
.statusCode(409)
|
||||
.body("__type", equalTo("ResourceInUseException"));
|
||||
|
||||
// 5. Describe association
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.get(basePath + "/" + associationId)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.contentType(containsString("application/json"))
|
||||
.body("association.associationId", equalTo(associationId))
|
||||
.body("association.namespace", equalTo("default"))
|
||||
.body("association.serviceAccount", equalTo("my-service-account"));
|
||||
|
||||
// 6. Update association
|
||||
String updatedRoleName = "updated-" + roleName;
|
||||
String updatedRoleArn = "arn:aws:iam::" + account + ":role/" + updatedRoleName;
|
||||
createRole(account, updatedRoleName);
|
||||
|
||||
Map<String, Object> updateReq = Map.of(
|
||||
"roleArn", updatedRoleArn,
|
||||
"disableSessionTags", true
|
||||
);
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.contentType("application/json")
|
||||
.body(updateReq)
|
||||
.post(basePath + "/" + associationId)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.contentType(containsString("application/json"))
|
||||
.body("association.associationId", equalTo(associationId))
|
||||
.body("association.roleArn", equalTo(updatedRoleArn))
|
||||
.body("association.disableSessionTags", equalTo(true));
|
||||
|
||||
// 7. List associations
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.get(basePath)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.contentType(containsString("application/json"))
|
||||
.body("associations", hasSize(1))
|
||||
.body("associations[0].associationId", equalTo(associationId))
|
||||
.body("associations[0].namespace", equalTo("default"))
|
||||
.body("associations[0].serviceAccount", equalTo("my-service-account"));
|
||||
|
||||
// List with filter matching
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.queryParam("namespace", "default")
|
||||
.get(basePath)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("associations", hasSize(1));
|
||||
|
||||
// List with filter non-matching
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.queryParam("namespace", "other-namespace")
|
||||
.get(basePath)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("associations", hasSize(0));
|
||||
|
||||
// 8. Delete association
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.delete(basePath + "/" + associationId)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.contentType(containsString("application/json"))
|
||||
.body("association.associationId", equalTo(associationId));
|
||||
|
||||
// 9. Describe after delete returns 404
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.get(basePath + "/" + associationId)
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
} finally {
|
||||
deleteCluster(account, name);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void routeCollisionsAndMissingCluster() {
|
||||
String account = "123456789012";
|
||||
// Missing cluster returns 404 JSON, not S3 NoSuchBucket XML
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.get("/clusters/nonexistent-cluster/pod-identity-associations")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.contentType(containsString("application/json"))
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void paginationAndLimits() {
|
||||
String account = "123456789012";
|
||||
String name = "pia-page-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
String roleName = "role-" + name;
|
||||
String roleArn = "arn:aws:iam::" + account + ":role/" + roleName;
|
||||
String basePath = "/clusters/" + name + "/pod-identity-associations";
|
||||
|
||||
createRole(account, roleName);
|
||||
createCluster(account, name);
|
||||
|
||||
try {
|
||||
// Create two associations
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.contentType("application/json")
|
||||
.body(Map.of("namespace", "ns1", "serviceAccount", "sa1", "roleArn", roleArn))
|
||||
.post(basePath).then().statusCode(200);
|
||||
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.contentType("application/json")
|
||||
.body(Map.of("namespace", "ns2", "serviceAccount", "sa2", "roleArn", roleArn))
|
||||
.post(basePath).then().statusCode(200);
|
||||
|
||||
// maxResults = 1 returns first item and nextToken
|
||||
String nextToken = given().header("Authorization", auth(account, "eks"))
|
||||
.queryParam("maxResults", "1")
|
||||
.get(basePath)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("associations", hasSize(1))
|
||||
.body("nextToken", notNullValue())
|
||||
.extract().path("nextToken");
|
||||
|
||||
// Fetch next page
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.queryParam("maxResults", "1")
|
||||
.queryParam("nextToken", nextToken)
|
||||
.get(basePath)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("associations", hasSize(1))
|
||||
.body("nextToken", nullValue());
|
||||
|
||||
// Invalid maxResults returns 400 InvalidParameterException
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.queryParam("maxResults", "0")
|
||||
.get(basePath)
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("InvalidParameterException"));
|
||||
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.queryParam("maxResults", "invalid")
|
||||
.get(basePath)
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("InvalidParameterException"));
|
||||
} finally {
|
||||
deleteCluster(account, name);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void clusterDeletionCleansAssociations() {
|
||||
String account = "123456789012";
|
||||
String name = "pia-del-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
String roleName = "role-" + name;
|
||||
String roleArn = "arn:aws:iam::" + account + ":role/" + roleName;
|
||||
String basePath = "/clusters/" + name + "/pod-identity-associations";
|
||||
|
||||
createRole(account, roleName);
|
||||
createCluster(account, name);
|
||||
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.contentType("application/json")
|
||||
.body(Map.of("namespace", "default", "serviceAccount", "sa", "roleArn", roleArn))
|
||||
.post(basePath).then().statusCode(200);
|
||||
|
||||
// Delete cluster
|
||||
deleteCluster(account, name);
|
||||
|
||||
// Recreate cluster with same name
|
||||
createCluster(account, name);
|
||||
try {
|
||||
// Associations must be empty
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.get(basePath)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("associations", hasSize(0));
|
||||
} finally {
|
||||
deleteCluster(account, name);
|
||||
}
|
||||
}
|
||||
|
||||
private static void createRole(String account, String roleName) {
|
||||
given().header("Authorization", auth(account, "iam"))
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateRole")
|
||||
.formParam("RoleName", roleName)
|
||||
.formParam("Path", "/")
|
||||
.formParam("AssumeRolePolicyDocument", "{}")
|
||||
.post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
private static void createCluster(String account, String name) {
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.contentType("application/json")
|
||||
.body(Map.of("name", name, "roleArn", "arn:aws:iam::" + account + ":role/cluster"))
|
||||
.post("/clusters").then().statusCode(200);
|
||||
}
|
||||
|
||||
private static void deleteCluster(String account, String name) {
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.delete("/clusters/" + name).then().statusCode(200);
|
||||
}
|
||||
|
||||
private static String auth(String account, String service) {
|
||||
return "AWS4-HMAC-SHA256 Credential=" + account
|
||||
+ "/20260920/us-east-1/" + service + "/aws4_request, SignedHeaders=host, Signature=abc";
|
||||
}
|
||||
}
|
||||
+268
@@ -0,0 +1,268 @@
|
||||
package io.github.hectorvent.floci.services.eks;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.services.eks.model.Cluster;
|
||||
import io.github.hectorvent.floci.services.eks.model.ClusterStatus;
|
||||
import io.github.hectorvent.floci.services.eks.model.CreatePodIdentityAssociationRequest;
|
||||
import io.github.hectorvent.floci.services.eks.model.PodIdentityAssociation;
|
||||
import io.github.hectorvent.floci.services.eks.model.PodIdentityAssociationSummary;
|
||||
import io.github.hectorvent.floci.services.eks.model.UpdatePodIdentityAssociationRequest;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamRole;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class EksPodIdentityAssociationServiceTest {
|
||||
|
||||
private static final String ROLE = "arn:aws:iam::123456789012:role/pod-role";
|
||||
private static final String NAMESPACE = "default";
|
||||
private static final String SERVICE_ACCOUNT = "app-sa";
|
||||
|
||||
@Test
|
||||
void createAndDescribeAssociation() throws Exception {
|
||||
Fixture fixture = fixture();
|
||||
CreatePodIdentityAssociationRequest request = new CreatePodIdentityAssociationRequest(
|
||||
fixture.cluster.getName(), NAMESPACE, SERVICE_ACCOUNT, ROLE, "token-1",
|
||||
Map.of("env", "prod"), null, false, null);
|
||||
|
||||
PodIdentityAssociation created = fixture.service.create(fixture.cluster, request);
|
||||
|
||||
assertEquals("test-cluster", created.clusterName());
|
||||
assertEquals(NAMESPACE, created.namespace());
|
||||
assertEquals(SERVICE_ACCOUNT, created.serviceAccount());
|
||||
assertEquals(ROLE, created.roleArn());
|
||||
assertNotNull(created.associationId());
|
||||
assertTrue(created.associationId().startsWith("a-"));
|
||||
assertEquals(19, created.associationId().length());
|
||||
assertEquals("arn:aws:eks:us-east-1:123456789012:podidentityassociation/test-cluster/" + created.associationId(),
|
||||
created.associationArn());
|
||||
assertEquals(Map.of("env", "prod"), created.tags());
|
||||
assertTrue(created.createdAt() > 0);
|
||||
assertEquals(created.createdAt(), created.modifiedAt());
|
||||
assertNotNull(created.externalId());
|
||||
assertNull(created.ownerArn());
|
||||
|
||||
// Verify serialization roundtrip
|
||||
EksPodIdentityAssociationService.StoredAssociation stored =
|
||||
fixture.storage.scan(key -> true).getFirst();
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
EksPodIdentityAssociationService.StoredAssociation restored = mapper.readValue(
|
||||
mapper.writeValueAsBytes(stored), EksPodIdentityAssociationService.StoredAssociation.class);
|
||||
assertEquals(stored, restored);
|
||||
|
||||
// Describe returns the same association
|
||||
PodIdentityAssociation described = fixture.service.describe(fixture.cluster, created.associationId());
|
||||
assertEquals(created, described);
|
||||
}
|
||||
|
||||
@Test
|
||||
void retriesAreIdempotentButConflictingRequestsAndDuplicatesFail() {
|
||||
Fixture fixture = fixture();
|
||||
CreatePodIdentityAssociationRequest request = new CreatePodIdentityAssociationRequest(
|
||||
fixture.cluster.getName(), NAMESPACE, SERVICE_ACCOUNT, ROLE, "retry-token",
|
||||
Map.of("app", "api"), null, null, null);
|
||||
|
||||
PodIdentityAssociation first = fixture.service.create(fixture.cluster, request);
|
||||
PodIdentityAssociation retry = fixture.service.create(fixture.cluster, request);
|
||||
assertEquals(first, retry);
|
||||
|
||||
// Same token with different parameters throws InvalidParameterException
|
||||
CreatePodIdentityAssociationRequest conflictingTokenRequest = new CreatePodIdentityAssociationRequest(
|
||||
fixture.cluster.getName(), "other-ns", SERVICE_ACCOUNT, ROLE, "retry-token",
|
||||
Map.of("app", "api"), null, null, null);
|
||||
AwsException exToken = assertThrows(AwsException.class, () ->
|
||||
fixture.service.create(fixture.cluster, conflictingTokenRequest));
|
||||
assertEquals("InvalidParameterException", exToken.getErrorCode());
|
||||
assertEquals(400, exToken.getHttpStatus());
|
||||
|
||||
// Duplicate (namespace, serviceAccount) with different token throws ResourceInUseException (409)
|
||||
CreatePodIdentityAssociationRequest duplicateRequest = new CreatePodIdentityAssociationRequest(
|
||||
fixture.cluster.getName(), NAMESPACE, SERVICE_ACCOUNT, ROLE, "different-token",
|
||||
Map.of(), null, null, null);
|
||||
AwsException exDup = assertThrows(AwsException.class, () ->
|
||||
fixture.service.create(fixture.cluster, duplicateRequest));
|
||||
assertEquals("ResourceInUseException", exDup.getErrorCode());
|
||||
assertEquals(409, exDup.getHttpStatus());
|
||||
assertTrue(exDup.getMessage().contains("Association already exists: " + first.associationId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateAssociationValidationsAndModifiedAt() {
|
||||
Fixture fixture = fixture();
|
||||
CreatePodIdentityAssociationRequest createRequest = new CreatePodIdentityAssociationRequest(
|
||||
fixture.cluster.getName(), NAMESPACE, SERVICE_ACCOUNT, ROLE, null, Map.of(), null, false, null);
|
||||
PodIdentityAssociation created = fixture.service.create(fixture.cluster, createRequest);
|
||||
|
||||
// Update with no parameters fails
|
||||
UpdatePodIdentityAssociationRequest emptyUpdate = new UpdatePodIdentityAssociationRequest(
|
||||
null, null, null, null, null);
|
||||
AwsException exEmpty = assertThrows(AwsException.class, () ->
|
||||
fixture.service.update(fixture.cluster, created.associationId(), emptyUpdate));
|
||||
assertEquals("InvalidParameterException", exEmpty.getErrorCode());
|
||||
assertEquals(400, exEmpty.getHttpStatus());
|
||||
|
||||
// Update with non-existent role fails
|
||||
String nonExistentRole = "arn:aws:iam::123456789012:role/no-such-role";
|
||||
when(fixture.iam.findRole("123456789012", "no-such-role")).thenReturn(Optional.empty());
|
||||
UpdatePodIdentityAssociationRequest badRoleUpdate = new UpdatePodIdentityAssociationRequest(
|
||||
nonExistentRole, null, null, null, null);
|
||||
AwsException exRole = assertThrows(AwsException.class, () ->
|
||||
fixture.service.update(fixture.cluster, created.associationId(), badRoleUpdate));
|
||||
assertEquals("InvalidParameterException", exRole.getErrorCode());
|
||||
|
||||
// Update with valid new role and session tags
|
||||
String newRole = "arn:aws:iam::123456789012:role/new-role";
|
||||
when(fixture.iam.findRole("123456789012", "new-role")).thenReturn(Optional.of(
|
||||
new IamRole("AROA-new", "new-role", "/", newRole, "{}")));
|
||||
UpdatePodIdentityAssociationRequest validUpdate = new UpdatePodIdentityAssociationRequest(
|
||||
newRole, "update-token", null, true, null);
|
||||
|
||||
PodIdentityAssociation updated = fixture.service.update(fixture.cluster, created.associationId(), validUpdate);
|
||||
assertEquals(newRole, updated.roleArn());
|
||||
assertTrue(updated.disableSessionTags());
|
||||
assertTrue(updated.modifiedAt() >= created.createdAt());
|
||||
|
||||
// Idempotent retry of update
|
||||
PodIdentityAssociation retryUpdate = fixture.service.update(fixture.cluster, created.associationId(), validUpdate);
|
||||
assertEquals(updated, retryUpdate);
|
||||
|
||||
// Update non-existent association
|
||||
assertThrows(AwsException.class, () ->
|
||||
fixture.service.update(fixture.cluster, "a-unknown", validUpdate));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteAssociationReturnsDeletedAndRemovesFromStore() {
|
||||
Fixture fixture = fixture();
|
||||
CreatePodIdentityAssociationRequest request = new CreatePodIdentityAssociationRequest(
|
||||
fixture.cluster.getName(), NAMESPACE, SERVICE_ACCOUNT, ROLE, null, Map.of(), null, null, null);
|
||||
PodIdentityAssociation created = fixture.service.create(fixture.cluster, request);
|
||||
|
||||
PodIdentityAssociation deleted = fixture.service.delete(fixture.cluster, created.associationId());
|
||||
assertEquals(created.associationId(), deleted.associationId());
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
fixture.service.describe(fixture.cluster, created.associationId()));
|
||||
assertEquals("ResourceNotFoundException", ex.getErrorCode());
|
||||
assertEquals(404, ex.getHttpStatus());
|
||||
|
||||
assertThrows(AwsException.class, () ->
|
||||
fixture.service.delete(fixture.cluster, created.associationId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listWithFiltersAndPagination() {
|
||||
Fixture fixture = fixture();
|
||||
String role2 = "arn:aws:iam::123456789012:role/role2";
|
||||
when(fixture.iam.findRole("123456789012", "role2")).thenReturn(Optional.of(
|
||||
new IamRole("AROA-role2", "role2", "/", role2, "{}")));
|
||||
String role3 = "arn:aws:iam::123456789012:role/role3";
|
||||
when(fixture.iam.findRole("123456789012", "role3")).thenReturn(Optional.of(
|
||||
new IamRole("AROA-role3", "role3", "/", role3, "{}")));
|
||||
|
||||
PodIdentityAssociation a1 = fixture.service.create(fixture.cluster,
|
||||
new CreatePodIdentityAssociationRequest(fixture.cluster.getName(), "ns1", "sa1", ROLE, null, Map.of(), null, null, null));
|
||||
PodIdentityAssociation a2 = fixture.service.create(fixture.cluster,
|
||||
new CreatePodIdentityAssociationRequest(fixture.cluster.getName(), "ns1", "sa2", role2, null, Map.of(), null, null, null));
|
||||
PodIdentityAssociation a3 = fixture.service.create(fixture.cluster,
|
||||
new CreatePodIdentityAssociationRequest(fixture.cluster.getName(), "ns2", "sa1", role3, null, Map.of(), null, null, null));
|
||||
|
||||
// Filter by namespace
|
||||
EksPodIdentityAssociationService.Page ns1Page = fixture.service.list(fixture.cluster, "ns1", null, null, null);
|
||||
assertEquals(2, ns1Page.associations().size());
|
||||
assertTrue(ns1Page.associations().stream().allMatch(s -> "ns1".equals(s.namespace())));
|
||||
|
||||
// Filter by serviceAccount
|
||||
EksPodIdentityAssociationService.Page sa1Page = fixture.service.list(fixture.cluster, null, "sa1", null, null);
|
||||
assertEquals(2, sa1Page.associations().size());
|
||||
assertTrue(sa1Page.associations().stream().allMatch(s -> "sa1".equals(s.serviceAccount())));
|
||||
|
||||
// Filter by both
|
||||
EksPodIdentityAssociationService.Page bothPage = fixture.service.list(fixture.cluster, "ns2", "sa1", null, null);
|
||||
assertEquals(1, bothPage.associations().size());
|
||||
assertEquals(a3.associationId(), bothPage.associations().getFirst().associationId());
|
||||
|
||||
// Pagination with maxResults = 1
|
||||
EksPodIdentityAssociationService.Page p1 = fixture.service.list(fixture.cluster, null, null, 1, null);
|
||||
assertEquals(1, p1.associations().size());
|
||||
assertNotNull(p1.nextToken());
|
||||
|
||||
EksPodIdentityAssociationService.Page p2 = fixture.service.list(fixture.cluster, null, null, 1, p1.nextToken());
|
||||
assertEquals(1, p2.associations().size());
|
||||
assertNotNull(p2.nextToken());
|
||||
assertNotEquals(p1.associations().getFirst().associationId(), p2.associations().getFirst().associationId());
|
||||
|
||||
EksPodIdentityAssociationService.Page p3 = fixture.service.list(fixture.cluster, null, null, 1, p2.nextToken());
|
||||
assertEquals(1, p3.associations().size());
|
||||
assertNull(p3.nextToken());
|
||||
|
||||
// Out of range maxResults
|
||||
assertThrows(AwsException.class, () -> fixture.service.list(fixture.cluster, null, null, 0, null));
|
||||
assertThrows(AwsException.class, () -> fixture.service.list(fixture.cluster, null, null, 101, null));
|
||||
assertThrows(AwsException.class, () -> fixture.service.list(fixture.cluster, null, null, 1, "invalid-token"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void clusterDeletionCleansAssociationsAndRecreationCannotInheritThem() {
|
||||
Fixture fixture = fixture();
|
||||
fixture.service.create(fixture.cluster,
|
||||
new CreatePodIdentityAssociationRequest(fixture.cluster.getName(), NAMESPACE, SERVICE_ACCOUNT, ROLE, null, Map.of(), null, null, null));
|
||||
|
||||
assertEquals(1, fixture.service.list(fixture.cluster, null, null, null, null).associations().size());
|
||||
|
||||
fixture.service.deleteClusterAssociations(fixture.cluster);
|
||||
assertTrue(fixture.storage.scan(key -> true).isEmpty());
|
||||
|
||||
// Recreated cluster with new createdAt cannot inherit old associations or pagination tokens
|
||||
fixture.service.create(fixture.cluster,
|
||||
new CreatePodIdentityAssociationRequest(fixture.cluster.getName(), "ns1", "sa1", ROLE, null, Map.of(), null, null, null));
|
||||
fixture.service.create(fixture.cluster,
|
||||
new CreatePodIdentityAssociationRequest(fixture.cluster.getName(), "ns2", "sa2", ROLE, null, Map.of(), null, null, null));
|
||||
EksPodIdentityAssociationService.Page pageBefore = fixture.service.list(fixture.cluster, null, null, 1, null);
|
||||
assertNotNull(pageBefore.nextToken());
|
||||
|
||||
fixture.cluster.setCreatedAt(fixture.cluster.getCreatedAt().plusSeconds(10));
|
||||
assertTrue(fixture.service.list(fixture.cluster, null, null, null, null).associations().isEmpty());
|
||||
assertThrows(AwsException.class, () -> fixture.service.list(fixture.cluster, null, null, 1, pageBefore.nextToken()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void inactiveClusterRejectsOperations() {
|
||||
Fixture fixture = fixture();
|
||||
fixture.cluster.setStatus(ClusterStatus.CREATING);
|
||||
|
||||
CreatePodIdentityAssociationRequest request = new CreatePodIdentityAssociationRequest(
|
||||
fixture.cluster.getName(), NAMESPACE, SERVICE_ACCOUNT, ROLE, null, Map.of(), null, null, null);
|
||||
assertThrows(AwsException.class, () -> fixture.service.create(fixture.cluster, request));
|
||||
assertThrows(AwsException.class, () -> fixture.service.describe(fixture.cluster, "a-123"));
|
||||
assertThrows(AwsException.class, () -> fixture.service.list(fixture.cluster, null, null, null, null));
|
||||
}
|
||||
|
||||
private static Fixture fixture() {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setName("test-cluster");
|
||||
cluster.setArn("arn:aws:eks:us-east-1:123456789012:cluster/test-cluster");
|
||||
cluster.setCreatedAt(Instant.parse("2026-09-20T12:00:00Z"));
|
||||
cluster.setStatus(ClusterStatus.ACTIVE);
|
||||
|
||||
IamService iam = mock(IamService.class);
|
||||
IamRole role = new IamRole("AROA-pod", "pod-role", "/", ROLE, "{}");
|
||||
when(iam.findRole("123456789012", "pod-role")).thenReturn(Optional.of(role));
|
||||
|
||||
InMemoryStorage<String, EksPodIdentityAssociationService.StoredAssociation> storage = new InMemoryStorage<>();
|
||||
return new Fixture(cluster, iam, role, storage, new EksPodIdentityAssociationService(storage, iam));
|
||||
}
|
||||
|
||||
private record Fixture(Cluster cluster, IamService iam, IamRole role,
|
||||
InMemoryStorage<String, EksPodIdentityAssociationService.StoredAssociation> storage,
|
||||
EksPodIdentityAssociationService service) {}
|
||||
}
|
||||
@@ -75,7 +75,8 @@ class EksServiceTest {
|
||||
Ec2Service ec2Service = null;
|
||||
RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000");
|
||||
eksService = new EksService(storageFactory, config, regionResolver, clusterManager, ec2Service,
|
||||
new EksOidcService(storageFactory, new ObjectMapper()), mock(EksAccessEntryService.class));
|
||||
new EksOidcService(storageFactory, new ObjectMapper()), mock(EksAccessEntryService.class),
|
||||
mock(EksPodIdentityAssociationService.class));
|
||||
}
|
||||
|
||||
private EmulatorConfig testConfig() {
|
||||
@@ -235,7 +236,8 @@ class EksServiceTest {
|
||||
EksOidcService oidcService = new EksOidcService(
|
||||
fixedStorageFactory(keyStore), new ObjectMapper());
|
||||
EksService restarted = new EksService(fixedStorageFactory(clusterStore), testConfig(),
|
||||
new RegionResolver("us-east-1", "000000000000"), null, null, oidcService, mock(EksAccessEntryService.class));
|
||||
new RegionResolver("us-east-1", "000000000000"), null, null, oidcService,
|
||||
mock(EksAccessEntryService.class), mock(EksPodIdentityAssociationService.class));
|
||||
restarted.init();
|
||||
|
||||
Cluster migrated = restarted.describeCluster("legacy-cluster");
|
||||
|
||||
Reference in new issue
Block a user