diff --git a/docs/services/eks.md b/docs/services/eks.md index bafd0e9ed6..836f438444 100644 --- a/docs/services/eks.md +++ b/docs/services/eks.md @@ -463,6 +463,12 @@ With a persistent [storage mode](../configuration/storage.md) (the default), clu `floci-eks-` container and volume: restoration adopts the surviving container when its `io.floci.account` label matches the owning account, so pre-upgrade workloads are not orphaned. +- Cluster names are unique only within a Region of an account, so a cluster outside the default + Region, or one sharing its name with a cluster in another Region, puts its Region first in its + container and volume names: `floci-aws-eks-.`, or + `floci-aws-eks-..` for a non-default account. A cluster in the default + Region keeps the unqualified name, and so does any cluster created before Region qualification: + its record moves to a Region-scoped key on startup, but its container and volume keep their names. A restored cluster reports `CREATING` until its API server answers again, then returns to `ACTIVE` with a freshly extracted certificate authority. If the container cannot be brought @@ -908,6 +914,8 @@ curl -sX POST http://localhost:4566/_floci/eks/clusters/my-cluster/oidc-token \ `audience` (default `sts.amazonaws.com`) and `expirySeconds` (default 24h, max 7d) are optional. This is Floci plumbing under `_floci/…`, not an AWS API. +Cluster names are unique only within a Region of an account. When clusters with the same name exist in more than one Region, add `?region=` to choose one, for example `…/clusters/my-cluster/oidc-token?region=eu-west-1`. Without it, the request's Region is used, and then the account's only cluster of that name. The discovery and key routes below take the same parameter. + ### Trust policy Note that the OIDC provider ARN and the condition keys use the issuer with the scheme stripped `oidc.eks..amazonaws.com/id/`, which is how the AWS console, `eksctl`, and Terraform all render it. @@ -956,6 +964,8 @@ Served for fidelity and debugging, nothing in the IRSA flow dereferences them: These live under `_floci/…` rather than at the AWS-shaped issuer path, which Floci's embedded DNS does not resolve and which would collide with S3's path-style routing. +Both take an optional `?region=` query parameter. Cluster names are unique only within a Region of an account, so without it the request's Region is used, and then the account's only cluster of that name. The discovery document's `jwks_uri` always names the cluster's Region. + ## ARN Format ``` diff --git a/src/main/java/io/floci/aws/services/eks/EksClusterManager.java b/src/main/java/io/floci/aws/services/eks/EksClusterManager.java index df5cf8e57b..c97e8177ee 100644 --- a/src/main/java/io/floci/aws/services/eks/EksClusterManager.java +++ b/src/main/java/io/floci/aws/services/eks/EksClusterManager.java @@ -733,7 +733,7 @@ public class EksClusterManager try { String accountId = resolveClusterAccountId(cluster); String issuer = resolveClusterIssuer(cluster); - ClusterOidcKey oidcKey = oidcService.ensureKeyForAccount(accountId, cluster.getName(), issuer); + ClusterOidcKey oidcKey = oidcService.ensureKeyForAccount(accountId, oidcKeyName(cluster), issuer); signingKeyFiles = writeSigningKeyFiles(cluster, oidcKey); if (signingKeyFiles != null) { serverArgs.addAll(buildIrsaServerArgs(oidcKey.getIssuer())); @@ -1404,8 +1404,9 @@ public class EksClusterManager } /** - * Account-qualified Docker name for a cluster. Cluster names are unique only within an - * account, so a non-default account's cluster is qualified with its account ID — otherwise + * Account-qualified Docker name for a cluster. Cluster names are unique only within a Region + * of an account, so a non-default account's cluster is qualified with its account ID (and, + * where needed, its Region; see {@link #accountQualifiedClusterName}) — otherwise * two accounts' same-named clusters would resolve to the same container and data volume, * letting one account reach (or, via startCluster's stale-container removal, destroy) the * other's workloads. The default account keeps the historical unqualified name so existing @@ -1425,10 +1426,19 @@ public class EksClusterManager return ContainerStorageHelper.resourceName(config, "eks", null, accountQualifiedClusterName(cluster)); } + /** + * The cluster's name qualified by its account and, when {@link Cluster#getDockerNameRegion()} + * is set, by its Region, which leads: {@code [.][.]}. Cluster names + * are unique only within a Region of an account, so same-named clusters in two Regions need + * distinct containers and volumes. The forms cannot collide: a name holds no dot, an account + * id is all digits, and a Region never is. + */ private String accountQualifiedClusterName(Cluster cluster) { String accountId = cluster.getAccountId(); boolean defaultAccount = accountId == null || accountId.equals(config.defaultAccountId()); - return defaultAccount ? cluster.getName() : accountId + "." + cluster.getName(); + String qualified = defaultAccount ? cluster.getName() : accountId + "." + cluster.getName(); + String region = cluster.getDockerNameRegion(); + return region == null || region.isBlank() ? qualified : region + "." + qualified; } /** @@ -1446,6 +1456,11 @@ public class EksClusterManager */ private String resolveRestoredDockerName(Cluster cluster) { String qualified = accountQualifiedName(cluster); + if (cluster.getDockerNameRegion() != null) { + // Region qualification postdates both the account qualifier and the floci-aws- rename, + // so no older name can hold this cluster's resources. + return qualified; + } // A cluster created after account qualification but before the floci-aws- rename lives // under the qualified name with the old prefix. Nothing else about it changed, so adopt @@ -1704,8 +1719,7 @@ public class EksClusterManager */ private String writeWebhookKubeconfig(Cluster cluster) { String clusterName = cluster.getName(); - Path localFile = Paths.get(config.services().eks().dataPath(), "webhook", clusterName, WEBHOOK_CONFIG_FILE) - .toAbsolutePath().normalize(); + Path localFile = localClusterFile(cluster, "webhook", WEBHOOK_CONFIG_FILE); try { Files.createDirectories(localFile.getParent()); Files.writeString(localFile, buildWebhookKubeconfig("http://" + dockerHostResolver.resolve() + ":" @@ -1746,8 +1760,7 @@ public class EksClusterManager if (dataPath == null || dataPath.isBlank()) { return null; } - Path localFile = Paths.get(dataPath, "audit", clusterName, AUDIT_POLICY_FILE) - .toAbsolutePath().normalize(); + Path localFile = localClusterFile(cluster, "audit", AUDIT_POLICY_FILE); Files.createDirectories(localFile.getParent()); Files.writeString(localFile, buildAuditPolicy()); return localFile.toString(); @@ -2011,6 +2024,24 @@ public class EksClusterManager return "000000000000"; } + /** + * The key of {@code cluster}'s OIDC signing key in {@link EksOidcService}: the cluster's storage + * key, which carries its Region, as {@link EksService} creates, publishes and migrates it. + */ + private String oidcKeyName(Cluster cluster) { + return EksService.clusterKey(clusterRegion(cluster), cluster.getName()); + } + + /** + * A file Floci writes for {@code cluster} under {@code /////}, + * the layout of {@link #resolveKeysDir}. Cluster names are unique only within a Region of an + * account, so a shorter path would let same-named clusters overwrite each other's files. + */ + Path localClusterFile(Cluster cluster, String kind, String fileName) { + return Paths.get(config.services().eks().dataPath(), kind, resolveClusterAccountId(cluster), + clusterRegion(cluster), cluster.getName(), fileName).toAbsolutePath().normalize(); + } + Path resolveKeysDir(Cluster cluster) { String accountId = resolveClusterAccountId(cluster); String region = clusterRegion(cluster); @@ -2107,7 +2138,7 @@ public class EksClusterManager try { String accountId = resolveClusterAccountId(cluster); String issuer = resolveClusterIssuer(cluster); - ClusterOidcKey oidcKey = oidcService.ensureKeyForAccount(accountId, cluster.getName(), issuer); + ClusterOidcKey oidcKey = oidcService.ensureKeyForAccount(accountId, oidcKeyName(cluster), issuer); SigningKeyFiles keyFiles = writeSigningKeyFiles(cluster, oidcKey); if (keyFiles != null) { copySigningKeysIntoContainer(containerId, keyFiles, cluster.getName()); @@ -2145,8 +2176,7 @@ public class EksClusterManager boolean tlsUri = config.services().ecr().tlsUri() && config.tls().enabled(); String content = buildRegistriesYaml(mirrorAccounts(resolveClusterAccountId(cluster), config.defaultAccountId()), mirrorRegions(region), ecrRegistryManager.advertisedPort(), endpoint, tlsUri); - writeLocalCopy(Paths.get(config.services().eks().dataPath(), "registries", clusterName, - "registries.yaml"), content, clusterName); + writeLocalCopy(localClusterFile(cluster, "registries", "registries.yaml"), content, clusterName); try { RetryingTarCopier.copyBytes(lifecycleManager.getDockerClient(), containerId, "/etc", REGISTRIES_TAR_ENTRY, content.getBytes(StandardCharsets.UTF_8), 0644, @@ -2232,10 +2262,9 @@ public class EksClusterManager return; } String url = "https://" + dockerHostResolver.resolve() + ":" + config.port() - + podIdentityWebhookPath(clusterName, resolveClusterAccountId(cluster)); + + podIdentityWebhookPath(clusterName, resolveClusterAccountId(cluster), clusterRegion(cluster)); String manifest = buildPodIdentityWebhookConfiguration(url, certificateAuthority.caPem()); - writeLocalCopy(Paths.get(config.services().eks().dataPath(), "webhook", clusterName, - POD_IDENTITY_MANIFEST_FILE), manifest, clusterName); + writeLocalCopy(localClusterFile(cluster, "webhook", POD_IDENTITY_MANIFEST_FILE), manifest, clusterName); try { byte[] tar = tarSingleFile(POD_IDENTITY_MANIFEST_TAR_ENTRY, manifest); RetryingTarCopier.copyStreamed(lifecycleManager.getDockerClient(), containerId, K3S_DATA_DIR, @@ -2253,8 +2282,8 @@ public class EksClusterManager * token webhook puts its scope there: the API server calls Floci with no AWS credentials, so a * cluster owned by a non-default account would otherwise never be found. */ - static String podIdentityWebhookPath(String clusterName, String accountId) { - return "/_floci/eks/clusters/" + clusterName + "/pod-identity-webhook/scope/" + accountId; + static String podIdentityWebhookPath(String clusterName, String accountId, String region) { + return "/_floci/eks/clusters/" + clusterName + "/pod-identity-webhook/scope/" + accountId + "/" + region; } /** @@ -2709,7 +2738,7 @@ public class EksClusterManager if (nodeGroupStorage == null || cluster == null || cluster.getName() == null) { return List.of(); } - String prefix = cluster.getName() + "/"; + String prefix = EksService.clusterKey(clusterRegion(cluster), cluster.getName()) + "/"; String accountId = resolveClusterAccountId(cluster); List groups; if (nodeGroupStorage instanceof AccountAwareStorageBackend aware) { diff --git a/src/main/java/io/floci/aws/services/eks/EksController.java b/src/main/java/io/floci/aws/services/eks/EksController.java index 37502335c1..61a9ff148b 100644 --- a/src/main/java/io/floci/aws/services/eks/EksController.java +++ b/src/main/java/io/floci/aws/services/eks/EksController.java @@ -110,10 +110,11 @@ public class EksController { private Cluster toClusterResponse(Cluster cluster) { if (cluster == null || (!cluster.isExplicitVersion() && cluster.getNodeInstanceType() == null && cluster.getClusterArgs() == null && cluster.getDefaultStorageClass() == null - && cluster.getJoinedInstanceIds() == null)) { + && cluster.getJoinedInstanceIds() == null && cluster.getDockerNameRegion() == null)) { return cluster; } Cluster response = cluster.copy(); + response.setDockerNameRegion(null); response.setExplicitVersion(false); response.setNodeInstanceType(null); response.setClusterArgs(null); diff --git a/src/main/java/io/floci/aws/services/eks/EksOidcService.java b/src/main/java/io/floci/aws/services/eks/EksOidcService.java index 005862c922..1e11d43cc1 100644 --- a/src/main/java/io/floci/aws/services/eks/EksOidcService.java +++ b/src/main/java/io/floci/aws/services/eks/EksOidcService.java @@ -72,10 +72,12 @@ public class EksOidcService implements OidcIssuerKeyLookup { /** * Generates and stores the cluster's signing keypair if absent, returning the stored material. - * Keyed by cluster name so {@code DeleteCluster} can drop it. + * Keyed by the cluster's storage key ({@link EksService#clusterKey(String, String)}), which + * carries its Region, so {@code DeleteCluster} can drop it and same-named clusters in two + * Regions each keep their own key. */ - public synchronized ClusterOidcKey ensureKey(String clusterName, String issuer) { - return ensureKey(null, clusterName, issuer); + public synchronized ClusterOidcKey ensureKey(String clusterKey, String issuer) { + return ensureKey(null, clusterKey, issuer); } /** @@ -83,13 +85,13 @@ public class EksOidcService implements OidcIssuerKeyLookup { * without a request context must pass the owning account from the cluster record, since the * request-scoped store would otherwise resolve to the default account. */ - public synchronized ClusterOidcKey ensureKeyForAccount(String accountId, String clusterName, + public synchronized ClusterOidcKey ensureKeyForAccount(String accountId, String clusterKey, String issuer) { - return ensureKey(accountId, clusterName, issuer); + return ensureKey(accountId, clusterKey, issuer); } - private ClusterOidcKey ensureKey(String accountId, String clusterName, String issuer) { - Optional existing = readKey(accountId, clusterName); + private ClusterOidcKey ensureKey(String accountId, String clusterKey, String issuer) { + Optional existing = readKey(accountId, clusterKey); if (existing.isPresent() && issuer.equals(existing.get().getIssuer())) { return existing.get(); } @@ -104,36 +106,68 @@ public class EksOidcService implements OidcIssuerKeyLookup { UUID.randomUUID().toString(), Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded()), Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded())); - writeKey(accountId, clusterName, key); - LOG.debugv("Generated IRSA OIDC signing key for EKS cluster {0}", clusterName); + writeKey(accountId, clusterKey, key); + LOG.debugv("Generated IRSA OIDC signing key for EKS cluster {0}", clusterKey); return key; } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("Failed to generate EKS OIDC signing keypair for cluster " - + clusterName + ": RSA unavailable", e); + + clusterKey + ": RSA unavailable", e); } } - private Optional readKey(String accountId, String clusterName) { + private Optional readKey(String accountId, String clusterKey) { if (accountId != null && keyStore instanceof AccountAwareStorageBackend aware) { - return aware.getForAccount(accountId, clusterName); + return aware.getForAccount(accountId, clusterKey); } - return keyStore.get(clusterName); + return keyStore.get(clusterKey); } - private void writeKey(String accountId, String clusterName, ClusterOidcKey key) { + private void writeKey(String accountId, String clusterKey, ClusterOidcKey key) { if (accountId != null && keyStore instanceof AccountAwareStorageBackend aware) { - aware.putForAccount(accountId, clusterName, key); + aware.putForAccount(accountId, clusterKey, key); return; } - keyStore.put(clusterName, key); + keyStore.put(clusterKey, key); } - public void deleteKey(String clusterName) { - keyStore.delete(clusterName); + public void deleteKey(String clusterKey) { + keyStore.delete(clusterKey); } - public Optional findKeyByCluster(String clusterName) { - return keyStore.get(clusterName); + /** + * Moves the signing key of {@code accountId}'s cluster from {@code legacyKey}, the bare cluster + * name keys were stored under before cluster names became Regional, to {@code clusterKey}. Only + * a key minted for {@code issuer} moves, so a same-named cluster's key is never taken over. + * Keeping the key, rather than minting a new one, keeps tokens already issued verifiable. A key + * stored before keys were account-prefixed moves too; the issuer, a random URL minted for one + * cluster, is what proves it belongs to this one. + */ + public synchronized void migrateLegacyKey(String accountId, String legacyKey, String clusterKey, + String issuer) { + if (legacyKey.equals(clusterKey) || issuer == null) { + return; + } + if (accountId != null && keyStore instanceof AccountAwareStorageBackend aware) { + aware.getForAccountMigratingLegacyKeys(accountId, clusterKey, List.of(legacyKey), + key -> issuer.equals(key.getIssuer())); + return; + } + Optional legacy = readKey(accountId, legacyKey); + if (legacy.isEmpty() || !issuer.equals(legacy.get().getIssuer())) { + return; + } + if (readKey(accountId, clusterKey).isEmpty()) { + writeKey(accountId, clusterKey, legacy.get()); + } + if (accountId != null && keyStore instanceof AccountAwareStorageBackend aware) { + aware.deleteForAccount(accountId, legacyKey); + } else { + keyStore.delete(legacyKey); + } + } + + public Optional findKeyByCluster(String clusterKey) { + return keyStore.get(clusterKey); } @Override @@ -162,7 +196,7 @@ public class EksOidcService implements OidcIssuerKeyLookup { * Mints an RS256-signed service-account token for {@code namespace}/{@code serviceAccount}, * shaped like the projected token a pod would present to STS. */ - public String mintServiceAccountToken(String clusterName, String issuer, String namespace, + public String mintServiceAccountToken(String clusterKey, String issuer, String namespace, String serviceAccount, String audience, Integer lifetimeSeconds) { if (namespace == null || namespace.isBlank()) { throw new AwsException("InvalidParameterException", "namespace is required", 400); @@ -173,7 +207,7 @@ public class EksOidcService implements OidcIssuerKeyLookup { int lifetime = resolveLifetime(lifetimeSeconds); String aud = audience == null || audience.isBlank() ? STS_AUDIENCE : audience; - ClusterOidcKey key = ensureKey(clusterName, issuer); + ClusterOidcKey key = ensureKey(clusterKey, issuer); long now = Instant.now().getEpochSecond(); long exp = now + lifetime; String subject = "system:serviceaccount:" + namespace + ":" + serviceAccount; diff --git a/src/main/java/io/floci/aws/services/eks/EksOidcTokenController.java b/src/main/java/io/floci/aws/services/eks/EksOidcTokenController.java index e701c4f4fe..372d2e0092 100644 --- a/src/main/java/io/floci/aws/services/eks/EksOidcTokenController.java +++ b/src/main/java/io/floci/aws/services/eks/EksOidcTokenController.java @@ -9,6 +9,7 @@ import jakarta.ws.rs.POST; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; @@ -25,6 +26,10 @@ import java.util.Map; * *

Minting server-side keeps the RSA private key inside Floci. Callers never hold signing * material, and the claim shape stays authoritative in one place. + * + *

Takes the same optional {@code ?region=} as the discovery and key routes: cluster names are + * unique only within a Region of an account, and this route is usually called unsigned, so without + * it the request's Region is used, and then the account's only cluster of that name. */ @ApplicationScoped @Path("_floci/eks/clusters/{name}/oidc-token") @@ -42,8 +47,9 @@ public class EksOidcTokenController { } @POST - public Response mintToken(@PathParam("name") String clusterName, Map request) { - Cluster cluster = eksService.describeCluster(clusterName); + public Response mintToken(@PathParam("name") String clusterName, @QueryParam("region") String region, + Map request) { + Cluster cluster = eksService.findClusterForFlociRoute(clusterName, region); String issuer = cluster.getIdentity() != null && cluster.getIdentity().getOidc() != null ? cluster.getIdentity().getOidc().getIssuer() : null; @@ -59,7 +65,7 @@ public class EksOidcTokenController { Integer lifetime = integer(body, "expirySeconds"); String token = oidcService.mintServiceAccountToken( - clusterName, issuer, namespace, serviceAccount, audience, lifetime); + eksService.clusterKey(cluster), issuer, namespace, serviceAccount, audience, lifetime); Map response = new LinkedHashMap<>(); response.put("token", token); diff --git a/src/main/java/io/floci/aws/services/eks/EksOidcWellKnownController.java b/src/main/java/io/floci/aws/services/eks/EksOidcWellKnownController.java index b34c86b481..f5d28c51f9 100644 --- a/src/main/java/io/floci/aws/services/eks/EksOidcWellKnownController.java +++ b/src/main/java/io/floci/aws/services/eks/EksOidcWellKnownController.java @@ -11,6 +11,7 @@ import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; @@ -53,12 +54,14 @@ public class EksOidcWellKnownController { @GET @Path(".well-known/openid-configuration") - public Response openIdConfiguration(@PathParam("name") String clusterName) { - String issuer = requireIssuer(clusterName); + public Response openIdConfiguration(@PathParam("name") String clusterName, + @QueryParam("region") String region) { + Cluster cluster = eksService.findClusterForFlociRoute(clusterName, region); + String issuer = requireIssuer(cluster, clusterName); Map body = new LinkedHashMap<>(); body.put("issuer", issuer); - body.put("jwks_uri", jwksUri(clusterName)); + body.put("jwks_uri", jwksUri(clusterName, eksService.clusterRegion(cluster))); body.put("authorization_endpoint", "urn:kubernetes:programmatic_authorization"); body.put("response_types_supported", List.of("id_token")); body.put("subject_types_supported", List.of("public")); @@ -69,9 +72,10 @@ public class EksOidcWellKnownController { @GET @Path("keys") - public Response keys(@PathParam("name") String clusterName) { - requireIssuer(clusterName); - ClusterOidcKey key = oidcService.findKeyByCluster(clusterName) + public Response keys(@PathParam("name") String clusterName, @QueryParam("region") String region) { + Cluster cluster = eksService.findClusterForFlociRoute(clusterName, region); + requireIssuer(cluster, clusterName); + ClusterOidcKey key = oidcService.findKeyByCluster(eksService.clusterKey(cluster)) .orElseThrow(() -> new AwsException("ResourceNotFoundException", "No OIDC signing key for cluster: " + clusterName, 404)); @@ -87,8 +91,7 @@ public class EksOidcWellKnownController { return Response.ok(Map.of("keys", List.of(jwk))).build(); } - private String requireIssuer(String clusterName) { - Cluster cluster = eksService.describeCluster(clusterName); + private String requireIssuer(Cluster cluster, String clusterName) { String issuer = cluster.getIdentity() != null && cluster.getIdentity().getOidc() != null ? cluster.getIdentity().getOidc().getIssuer() : null; @@ -99,8 +102,13 @@ public class EksOidcWellKnownController { return issuer; } - private String jwksUri(String clusterName) { - return config.effectiveBaseUrl() + "/_floci/eks/clusters/" + clusterName + "/oidc/keys"; + /** + * The key route of the cluster discovery resolved. It names the cluster's Region, since a verifier + * follows it without the discovery request's context, and cluster names are unique only within a + * Region of an account. + */ + private String jwksUri(String clusterName, String region) { + return config.effectiveBaseUrl() + "/_floci/eks/clusters/" + clusterName + "/oidc/keys?region=" + region; } /** diff --git a/src/main/java/io/floci/aws/services/eks/EksPodIdentityWebhook.java b/src/main/java/io/floci/aws/services/eks/EksPodIdentityWebhook.java index e023583d2f..5ff3acb598 100644 --- a/src/main/java/io/floci/aws/services/eks/EksPodIdentityWebhook.java +++ b/src/main/java/io/floci/aws/services/eks/EksPodIdentityWebhook.java @@ -94,12 +94,22 @@ public class EksPodIdentityWebhook { * the cluster would only ever be looked up in the default account. */ public Map review(String clusterName, String accountId, Map admissionReview) { + return review(clusterName, accountId, null, admissionReview); + } + + /** + * As {@link #review(String, String, Map)}, for the cluster in {@code region}: cluster names are + * unique only within a Region. A null Region, from a route registered before the Region was + * part of it, resolves the cluster created before Regional names that registered it. + */ + public Map review(String clusterName, String accountId, String region, + Map admissionReview) { String apiVersion = admissionReview != null && admissionReview.get("apiVersion") instanceof String version ? version : DEFAULT_API_VERSION; Map request = admissionReview == null ? null : asMap(admissionReview.get("request")); String uid = request != null && request.get("uid") instanceof String value ? value : ""; try { - return admissionReview(apiVersion, uid, decide(clusterName, accountId, request)); + return admissionReview(apiVersion, uid, decide(clusterName, accountId, region, request)); } catch (RuntimeException e) { LOG.warnv("EKS pod-identity-webhook: admitting pod unchanged for cluster {0} after an " + "internal error: {1}", clusterName, e.toString()); @@ -107,7 +117,7 @@ public class EksPodIdentityWebhook { } } - private List> decide(String clusterName, String accountId, + private List> decide(String clusterName, String accountId, String region, Map request) { if (request == null) { return List.of(); @@ -120,7 +130,11 @@ public class EksPodIdentityWebhook { if (namespace == null) { return List.of(); } - Optional cluster = eks.findAuthenticationCluster(accountId, clusterName); + // A route without a Region was registered by a cluster created before cluster names became + // Regional, so that cluster answers it, not a same-named one created since. + Optional cluster = region == null + ? eks.findPreRegionalCluster(accountId, clusterName) + : eks.findAuthenticationCluster(accountId, region, clusterName); if (cluster.isEmpty()) { return List.of(); } diff --git a/src/main/java/io/floci/aws/services/eks/EksPodIdentityWebhookController.java b/src/main/java/io/floci/aws/services/eks/EksPodIdentityWebhookController.java index 062f84179b..d4352b18f3 100644 --- a/src/main/java/io/floci/aws/services/eks/EksPodIdentityWebhookController.java +++ b/src/main/java/io/floci/aws/services/eks/EksPodIdentityWebhookController.java @@ -39,11 +39,24 @@ public class EksPodIdentityWebhookController { this.webhook = webhook; } + @POST + @Path("scope/{accountId}/{region}") + public Response review(@PathParam("clusterName") String clusterName, + @PathParam("accountId") String accountId, + @PathParam("region") String region, + Map admissionReview) { + return Response.ok(webhook.review(clusterName, accountId, region, admissionReview)).build(); + } + + /** + * The route registered by clusters started before the Region was part of the path. Their + * webhook configuration lives in the k3s data volume, so it outlives an upgrade. + */ @POST @Path("scope/{accountId}") public Response review(@PathParam("clusterName") String clusterName, @PathParam("accountId") String accountId, Map admissionReview) { - return Response.ok(webhook.review(clusterName, accountId, admissionReview)).build(); + return Response.ok(webhook.review(clusterName, accountId, null, admissionReview)).build(); } } diff --git a/src/main/java/io/floci/aws/services/eks/EksService.java b/src/main/java/io/floci/aws/services/eks/EksService.java index 01a323eee2..80567f7575 100644 --- a/src/main/java/io/floci/aws/services/eks/EksService.java +++ b/src/main/java/io/floci/aws/services/eks/EksService.java @@ -74,6 +74,7 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; +import java.util.function.Function; import java.util.function.UnaryOperator; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -94,6 +95,9 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun * qualifier relies on — see EksClusterManager#accountQualifiedName. */ static final String CLUSTER_NAME_REGEX = "[0-9A-Za-z][A-Za-z0-9\\-_]*"; + /** Separates the Region from the cluster name in a storage key; see {@link #clusterKey(String, String)}. */ + private static final String KEY_SEPARATOR = "::"; + private static final String CLUSTER_SG_DESCRIPTION = "EKS created security group applied to ENI that is attached to EKS Control Plane master nodes, as well as any managed workloads."; @@ -115,6 +119,8 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun // Storage hands every caller the same live Cluster, and Cluster keeps identity equality. private final Set clustersBeingDeleted = ConcurrentHashMap.newKeySet(); private final Set restoringClusters = ConcurrentHashMap.newKeySet(); + /** {@code /} of each cluster a CreateCluster call is building. */ + private final Set clustersBeingCreated = ConcurrentHashMap.newKeySet(); @Inject public EksService(StorageFactory storageFactory, EmulatorConfig config, @@ -169,6 +175,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun @PostConstruct public void init() { + migrateLegacyKeys(); backfillOidcIdentities(); backfillClusterSecurityGroups(); backfillLogging(); @@ -228,7 +235,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun cluster.setStatus(ClusterStatus.CREATING); cluster.setPodCidr(EksClusterManager.DEFAULT_POD_CIDR); if (cluster.getNodeInstanceType() == null) { - firstNodeGroup(cluster.getName(), entry.accountId()).ifPresent(group -> + firstNodeGroup(clusterKey(cluster), entry.accountId()).ifPresent(group -> cluster.setNodeInstanceType(selectedNodeInstanceType(group))); } clusterManager.restoreCluster(cluster); @@ -268,13 +275,13 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun private boolean isClusterDeleting(String accountId, Cluster cluster) { return cluster != null && cluster.getName() != null && (cluster.getStatus() == ClusterStatus.DELETING - || clustersBeingDeleted.stream().anyMatch(c -> cluster.getName().equals(c.getName()) + || clustersBeingDeleted.stream().anyMatch(c -> clusterKey(cluster).equals(clusterKey(c)) && (accountId == null || c.getAccountId() == null || accountId.equals(c.getAccountId())))); } - private void saveClusterIfNotDeleting(String accountId, String clusterName, Consumer mutator) { + private void saveClusterIfNotDeleting(String accountId, String clusterKey, Consumer mutator) { synchronized (clustersBeingDeleted) { - Cluster current = findAuthenticationCluster(accountId, clusterName).orElse(null); + Cluster current = findClusterForAccount(accountId, clusterKey).orElse(null); if (current != null && !isClusterDeleting(accountId, current)) { if (current.getAccountId() == null) { current.setAccountId(accountId); @@ -287,7 +294,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun private void restoreJoinedInstances(String accountId, Cluster cluster) { if (cluster == null || cluster.getJoinedInstanceIds() == null || ec2Service == null - || isClusterDeleting(accountId, cluster) || findAuthenticationCluster(accountId, cluster.getName()).isEmpty()) { + || isClusterDeleting(accountId, cluster) || findClusterForAccount(accountId, clusterKey(cluster)).isEmpty()) { return; } if (cluster.getAccountId() == null) { @@ -295,7 +302,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun } Set prunedInstanceIds = new HashSet<>(); for (Map.Entry instEntry : new ArrayList<>(cluster.getJoinedInstanceIds().entrySet())) { - if (isClusterDeleting(accountId, cluster) || findAuthenticationCluster(accountId, cluster.getName()).isEmpty()) { + if (isClusterDeleting(accountId, cluster) || findClusterForAccount(accountId, clusterKey(cluster)).isEmpty()) { return; } String instId = instEntry.getKey(); @@ -316,7 +323,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun }); } if (!prunedInstanceIds.isEmpty()) { - saveClusterIfNotDeleting(accountId, cluster.getName(), current -> { + saveClusterIfNotDeleting(accountId, clusterKey(cluster), current -> { if (current.getJoinedInstanceIds() != null) { prunedInstanceIds.forEach(current.getJoinedInstanceIds()::remove); } @@ -330,8 +337,8 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun } } - private Optional firstNodeGroup(String clusterName, String accountId) { - String prefix = clusterName + "/"; + private Optional firstNodeGroup(String clusterKey, String accountId) { + String prefix = clusterKey + "/"; List groups; if (nodeGroupStorage instanceof AccountAwareStorageBackend aware) { groups = aware.scanAllAccountEntries(key -> key.startsWith(prefix)).stream() @@ -346,8 +353,8 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun .thenComparing(Nodegroup::getNodegroupName)); } - List listNodeGroupsForCluster(String clusterName, String accountId) { - String prefix = clusterName + "/"; + List listNodeGroupsForCluster(String clusterKey, String accountId) { + String prefix = clusterKey + "/"; if (nodeGroupStorage instanceof AccountAwareStorageBackend aware) { return aware.scanAllAccountEntries(key -> key.startsWith(prefix)).stream() .filter(entry -> accountId == null || accountId.equals(entry.accountId())) @@ -376,7 +383,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun if (cluster.getIdentity() != null && cluster.getIdentity().getOidc() != null && cluster.getIdentity().getOidc().getIssuer() != null) { - oidcService.ensureKeyForAccount(accountId, cluster.getName(), + oidcService.ensureKeyForAccount(accountId, clusterKey(cluster), cluster.getIdentity().getOidc().getIssuer()); continue; } @@ -384,7 +391,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun String issuer = oidcService.newIssuerUrl( AwsArnUtils.regionOrDefault(cluster.getArn(), config.defaultRegion())); cluster.setIdentity(new ClusterIdentity(new OidcIdentity(issuer))); - oidcService.ensureKeyForAccount(accountId, cluster.getName(), issuer); + oidcService.ensureKeyForAccount(accountId, clusterKey(cluster), issuer); putClusterForAccount(accountId, cluster); LOG.infov("Backfilled IRSA OIDC issuer for existing EKS cluster {0} in account {1}", cluster.getName(), accountId); @@ -393,22 +400,27 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun void putClusterForAccount(String accountId, Cluster cluster) { if (storage instanceof AccountAwareStorageBackend aware) { - aware.putForAccount(accountId, cluster.getName(), cluster); + aware.putForAccount(accountId, clusterKey(cluster), cluster); return; } - storage.put(cluster.getName(), cluster); + storage.put(clusterKey(cluster), cluster); } + /** + * Deletes {@code accountId}'s cluster {@code clusterName} found as + * {@link #findAuthenticationCluster(String, String)} finds it: in the request's Region, or the + * account's only cluster of that name. + */ void deleteClusterForAccount(String accountId, String clusterName) { - synchronized (capacityLock(accountId, clusterName)) { - deleteClusterForAccountHoldingCapacity(accountId, clusterName); + String key = findAuthenticationCluster(accountId, clusterName).map(this::clusterKey) + .orElse(requestClusterKey(clusterName)); + synchronized (capacityLock(accountId, key)) { + deleteClusterForAccountHoldingCapacity(accountId, key, clusterName); } } - private void deleteClusterForAccountHoldingCapacity(String accountId, String clusterName) { - Cluster cluster = (storage instanceof AccountAwareStorageBackend aware) - ? aware.getForAccount(accountId, clusterName).orElse(null) - : storage.get(clusterName).orElse(null); + private void deleteClusterForAccountHoldingCapacity(String accountId, String clusterKey, String clusterName) { + Cluster cluster = findClusterForAccount(accountId, clusterKey).orElse(null); if (cluster != null) { if (cluster.getAccountId() == null) { cluster.setAccountId(accountId); @@ -419,16 +431,16 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun try { clearAppliedClusterUserData(cluster, clusterName); if (cluster == null || cluster.getArn() == null) { - String fallbackArn = AwsArnUtils.Arn.of("eks", config.defaultRegion(), accountId, + String fallbackArn = AwsArnUtils.Arn.of("eks", regionOfKey(clusterKey), accountId, "cluster/" + clusterName).toString(); appliedClusterUserData.remove(fallbackArn); } synchronized (clustersBeingDeleted) { if (storage instanceof AccountAwareStorageBackend aware) { - aware.deleteForAccount(accountId, clusterName); + aware.deleteForAccount(accountId, clusterKey); return; } - storage.delete(clusterName); + storage.delete(clusterKey); } } finally { if (cluster != null) { @@ -574,6 +586,95 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun return config != null ? config.defaultRegion() : regionResolver.getRegion(); } + /** + * The account-relative key a cluster is stored under, {@code ::}. Cluster names are + * unique only within a Region of an account (#7966), so the key carries the Region; node groups + * and Fargate profiles are stored under it followed by {@code /}. Neither a Region + * nor a cluster name holds a colon or a slash, so keys never run into one another. + */ + static String clusterKey(String region, String clusterName) { + return region + KEY_SEPARATOR + clusterName; + } + + /** The key {@code cluster} is stored under, in the Region its ARN names. */ + String clusterKey(Cluster cluster) { + return clusterKey(resolveClusterRegion(cluster), cluster.getName()); + } + + private String requestClusterKey(String clusterName) { + return clusterKey(regionResolver.getRegion(), clusterName); + } + + private static String regionOfKey(String clusterKey) { + return clusterKey.substring(0, clusterKey.indexOf(KEY_SEPARATOR)); + } + + /** + * The Region that qualifies a new cluster's Docker names, or null for the unqualified name. A + * cluster in the default Region keeps the name it always had, so its container, volume and + * {@code endpoint-mode=network} DNS name do not change, unless the request's account already has + * a cluster of that name in another Region: that one may hold the unqualified name. + */ + private String dockerNameRegion(String region, String name) { + if (!region.equals(config.defaultRegion())) { + return region; + } + String suffix = KEY_SEPARATOR + name; + return storage.scan(key -> key.endsWith(suffix)).isEmpty() ? null : region; + } + + /** + * Moves records persisted before cluster names became Regional (#7966) from keys built on the + * bare cluster name onto Region-qualified ones. The Region comes from each record's ARN, which + * has always carried it. A cluster's OIDC signing key moves with it, so tokens it signed before + * the upgrade still verify. Docker names are untouched: a migrated cluster has no + * {@link Cluster#getDockerNameRegion()}, so it keeps its containers and volume. + */ + private void migrateLegacyKeys() { + migrateLegacyEntries(storage, this::clusterKey); + migrateLegacyEntries(nodeGroupStorage, group -> group.getClusterName() == null ? null + : nodeGroupKey(clusterKey(AwsArnUtils.regionOrDefault(group.getNodegroupArn(), config.defaultRegion()), + group.getClusterName()), group.getNodegroupName())); + migrateLegacyEntries(fargateProfileStorage, profile -> profile.getClusterName() == null ? null + : fargateProfileKey(clusterKey(AwsArnUtils.regionOrDefault(profile.getFargateProfileArn(), + config.defaultRegion()), profile.getClusterName()), profile.getFargateProfileName())); + for (AccountAwareStorageBackend.AccountEntry entry : allClusterEntries()) { + Cluster cluster = entry.value(); + if (cluster.getName() != null && cluster.getIdentity() != null && cluster.getIdentity().getOidc() != null) { + oidcService.migrateLegacyKey(entry.accountId(), cluster.getName(), clusterKey(cluster), + cluster.getIdentity().getOidc().getIssuer()); + } + } + } + + private void migrateLegacyEntries(StorageBackend store, Function destinationKey) { + if (!(store instanceof AccountAwareStorageBackend aware)) { + for (String key : new ArrayList<>(store.keys())) { + if (key.contains(KEY_SEPARATOR)) { + continue; + } + store.get(key).ifPresent(value -> { + String destination = destinationKey.apply(value); + if (destination != null && !destination.equals(key)) { + if (store.get(destination).isEmpty()) { + store.put(destination, value); + } + store.delete(key); + } + }); + } + return; + } + Set accounts = new LinkedHashSet<>(); + for (String rawKey : aware.scanAllAccountsWithRawKeys().keySet()) { + accounts.add(AccountAwareStorageBackend.hasAccountPrefix(rawKey) + ? rawKey.substring(0, 12) : config.defaultAccountId()); + } + for (String accountId : accounts) { + aware.migrateLegacyEntries(accountId, key -> !key.contains(KEY_SEPARATOR), destinationKey, value -> true); + } + } + private static String randomHex(int len) { byte[] bytes = new byte[(len + 1) / 2]; ThreadLocalRandom.current().nextBytes(bytes); @@ -615,11 +716,25 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun + "satisfy regular expression pattern: ^" + CLUSTER_NAME_REGEX + "$", 400); } - if (storage.get(name).isPresent()) { - throw new AwsException("ResourceInUseException", - "Cluster already exists: " + name, 409); + // Cluster names are unique only within a Region of an account (#7966). The key stays reserved + // until the cluster is stored, so a concurrent create of the same name is refused, not let + // through to overwrite this one. + String reservation = regionResolver.getAccountId() + "/" + requestClusterKey(name); + if (!clustersBeingCreated.add(reservation)) { + throw new AwsException("ResourceInUseException", "Cluster already exists: " + name, 409); } + try { + if (storage.get(requestClusterKey(name)).isPresent()) { + throw new AwsException("ResourceInUseException", + "Cluster already exists: " + name, 409); + } + return createReservedCluster(request, name); + } finally { + clustersBeingCreated.remove(reservation); + } + } + private Cluster createReservedCluster(CreateClusterRequest request, String name) { AccessConfig requestedAccess = request.getAccessConfig(); String authenticationMode = requestedAccess == null || requestedAccess.authenticationMode() == null ? "CONFIG_MAP" : requestedAccess.authenticationMode(); @@ -640,6 +755,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun cluster.setArn(arn); cluster.setAccountId(accountId); cluster.setCreatedAt(Instant.now()); + cluster.setDockerNameRegion(dockerNameRegion(region, name)); if (request.getVersion() != null && !request.getVersion().isBlank()) { String requestedVersion = request.getVersion().trim(); @@ -701,7 +817,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun try { String issuer = oidcService.newIssuerUrl(region); cluster.setIdentity(new ClusterIdentity(new OidcIdentity(issuer))); - oidcService.ensureKey(name, issuer); + oidcService.ensureKey(clusterKey(region, name), issuer); if (config.services().eks().mock()) { markMetadataOnlyActive(cluster); @@ -719,7 +835,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun } } - storage.put(name, cluster); + storage.put(clusterKey(region, name), cluster); } catch (RuntimeException e) { if (clusterSg != null) { try { @@ -746,9 +862,72 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun cluster.setEndpoint("https://localhost:" + config.services().eks().apiServerBasePort()); } + /** + * {@code accountId}'s cluster {@code name} in {@code region}, for callers that act outside the + * account's request context, such as the k3s API server calling Floci's webhooks. + */ + public Optional findAuthenticationCluster(String accountId, String region, String name) { + return findClusterForAccount(accountId, clusterKey(region, name)); + } + + /** + * {@code accountId}'s cluster {@code name} for a caller that does not name its Region: the one in + * the request's Region, or else the account's only cluster of that name. Empty when the name is + * in several Regions and none is the request's, since the caller cannot be told which it meant. + */ public Optional findAuthenticationCluster(String accountId, String name) { - return storage instanceof AccountAwareStorageBackend aware - ? aware.getForAccount(accountId, name) : storage.get(name); + Optional inRequestRegion = findClusterForAccount(accountId, requestClusterKey(name)); + if (inRequestRegion.isPresent()) { + return inRequestRegion; + } + String suffix = KEY_SEPARATOR + name; + List named = storage instanceof AccountAwareStorageBackend aware + ? aware.scanForAccount(accountId, key -> key.endsWith(suffix)) + : storage.scan(key -> key.endsWith(suffix)); + return named.size() == 1 ? Optional.of(named.getFirst()) : Optional.empty(); + } + + /** + * {@code accountId}'s cluster {@code name} that was created before cluster names became Regional, + * for a route such a cluster registered without a Region in it. Names were unique within an + * account then, and a later cluster sharing the name is always Region-qualified in Docker, so at + * most one cluster of the name has no {@link Cluster#getDockerNameRegion()}: the one that + * registered the route. Preferring the request's Region instead could pick a newer same-named + * cluster in the default Region. + */ + public Optional findPreRegionalCluster(String accountId, String name) { + String suffix = KEY_SEPARATOR + name; + List unqualified = (storage instanceof AccountAwareStorageBackend aware + ? aware.scanForAccount(accountId, key -> key.endsWith(suffix)) + : storage.scan(key -> key.endsWith(suffix))).stream() + .filter(cluster -> cluster.getDockerNameRegion() == null) + .toList(); + return unqualified.size() == 1 ? Optional.of(unqualified.getFirst()) : Optional.empty(); + } + + /** + * The cluster a {@code _floci/eks/clusters//...} route names. Those routes are often called + * unsigned, so a {@code region} the route carries wins; without one the request's Region is tried + * first and then the account's only cluster of that name, as + * {@link #findAuthenticationCluster(String, String)} does. + */ + public Cluster findClusterForFlociRoute(String name, String region) { + String accountId = regionResolver.getAccountId(); + return (region == null || region.isBlank() + ? findAuthenticationCluster(accountId, name) + : findAuthenticationCluster(accountId, region, name)) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "No cluster found for name: " + name, 404)); + } + + /** The Region of {@code cluster}, from its ARN. */ + public String clusterRegion(Cluster cluster) { + return resolveClusterRegion(cluster); + } + + private Optional findClusterForAccount(String accountId, String clusterKey) { + return storage instanceof AccountAwareStorageBackend aware && accountId != null + ? aware.getForAccount(accountId, clusterKey) : storage.get(clusterKey); } /** @@ -759,7 +938,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun * or the handler would refuse the lookup. */ public Optional findResourceArn(String clusterName, String collection, String name) { - Optional cluster = storage.get(clusterName); + Optional cluster = storage.get(requestClusterKey(clusterName)); if (cluster.isEmpty() || collection == null) { return cluster.map(Cluster::getArn); } @@ -782,8 +961,9 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun } } + /** The cluster {@code name} in the request's Region. */ public Cluster describeCluster(String name) { - Cluster cluster = storage.get(name) + Cluster cluster = storage.get(requestClusterKey(name)) .orElseThrow(() -> new AwsException("ResourceNotFoundException", "No cluster found for name: " + name, 404)); if (cluster.getLogging() == null) { @@ -799,7 +979,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun try { Cluster cluster = describeCluster(name); validateInstanceRegion(cluster, instance); - saveClusterIfNotDeleting(accountId, name, current -> + saveClusterIfNotDeleting(accountId, clusterKey(cluster), current -> clusterManager.recordJoinedInstanceId(current, instance)); } catch (AwsException e) { LOG.warnv("Cannot join instance {0} to cluster {1}: {2}", @@ -820,7 +1000,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun Cluster cluster = describeCluster(clusterName); validateInstanceRegion(cluster, instance); clusterManager.joinInstance(cluster, instance); - storage.put(cluster.getName(), cluster); + storage.put(clusterKey(cluster), cluster); } void joinInstance(String clusterName, String instanceId) { @@ -905,8 +1085,8 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun // A first node group replacing the node holds this lock while the swap runs; deleting // meanwhile would find no container to stop and have its cluster written back. Read the // cluster only once the lock is held: a delete that waited may find it gone. - synchronized (capacityLock(regionResolver.getAccountId(), name)) { - Cluster cluster = storage.get(name) + synchronized (capacityLock(regionResolver.getAccountId(), requestClusterKey(name))) { + Cluster cluster = storage.get(requestClusterKey(name)) .orElseThrow(() -> new AwsException("ResourceNotFoundException", "No cluster found for name: " + name, 404)); if (inRequestRegion) { @@ -948,9 +1128,9 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun addons.deleteClusterAddons(cluster); } synchronized (clustersBeingDeleted) { - storage.delete(name); + storage.delete(clusterKey(cluster)); clearAppliedClusterUserData(cluster, name); - oidcService.deleteKey(name); + oidcService.deleteKey(clusterKey(cluster)); } return cluster; } finally { @@ -996,7 +1176,8 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun throw new AwsException("InvalidParameterException", "subnets are required", 400); } - String storageKey = nodeGroupKey(clusterName, nodegroupName); + String clusterKey = clusterKey(cluster); + String storageKey = nodeGroupKey(clusterKey, nodegroupName); if (nodeGroupStorage.get(storageKey).isPresent()) { throw new AwsException("ResourceInUseException", "Nodegroup already exists: " + nodegroupName, 409); @@ -1043,8 +1224,8 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun nodeGroup.setLabels(request.getLabels() != null ? new HashMap<>(request.getLabels()) : null); nodeGroup.setTags(request.getTags() != null ? new HashMap<>(request.getTags()) : new HashMap<>()); - String capacityKey = accountId + "/" + clusterName; - Object capacityLock = capacityLock(accountId, clusterName); + String capacityKey = accountId + "/" + clusterKey; + Object capacityLock = capacityLock(accountId, clusterKey); boolean hasUserData = launchTemplateData != null && launchTemplateData.getUserData() != null && !launchTemplateData.getUserData().isBlank(); Cluster currentCluster; @@ -1057,7 +1238,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun } currentCluster = describeCluster(clusterName); pendingFirst = pendingFirstNodeGroups.get(capacityKey); - boolean firstGroup = firstNodeGroup(clusterName, accountId).isEmpty() && pendingFirst == null; + boolean firstGroup = firstNodeGroup(clusterKey, accountId).isEmpty() && pendingFirst == null; if (firstGroup && !config.services().eks().mock() && clusterManager != null) { applyFirstNodeGroupCapacity(clusterName, nodegroupName, currentCluster, nodeGroup); if (currentCluster.getContainerId() != null && currentCluster.getStatus() == ClusterStatus.ACTIVE) { @@ -1067,16 +1248,16 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun } else if (!firstGroup && pendingFirst == null && !config.services().eks().mock() && clusterManager != null) { if (currentCluster.getNodeInstanceType() == null) { - firstNodeGroup(clusterName, accountId).ifPresent(group -> + firstNodeGroup(clusterKey, accountId).ifPresent(group -> currentCluster.setNodeInstanceType(selectedNodeInstanceType(group))); - storage.put(clusterName, currentCluster); + storage.put(clusterKey, currentCluster); } if (!nodeGroup.getInstanceTypes().isEmpty() && !nodeGroup.getInstanceTypes().contains(currentCluster.getNodeInstanceType())) { LOG.warnv("EKS cluster {0} has one shared node; nodegroup {1} cannot change its capacity from {2}", clusterName, nodegroupName, currentCluster.getNodeInstanceType()); } - firstNodeGroup(clusterName, accountId).ifPresent(first -> { + firstNodeGroup(clusterKey, accountId).ifPresent(first -> { if (!nodegroupName.equals(first.getNodegroupName())) { LOG.warnv( "EKS cluster {0} has one shared node; nodegroup {1} metadata (labels/taints) is not applied to the node (already represented by nodegroup {2})", @@ -1123,7 +1304,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun if (nodeGroupStorage.get(storageKey) .filter(saved -> arn.equals(saved.getNodegroupArn())).isPresent()) { if (nodeGroup.getStatus() == NodegroupStatus.CREATING) { - if (!ownsPendingFirst && firstNodeGroup(clusterName, accountId).isEmpty() + if (!ownsPendingFirst && firstNodeGroup(clusterKey, accountId).isEmpty() && !config.services().eks().mock() && clusterManager != null) { Cluster refreshedCluster = describeCluster(clusterName); applyFirstNodeGroupCapacity(clusterName, nodegroupName, refreshedCluster, nodeGroup); @@ -1170,7 +1351,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun clusterName, e.getMessage()); } } - storage.put(clusterName, currentCluster); + storage.put(clusterKey(currentCluster), currentCluster); } private String selectedNodeInstanceType(Nodegroup group) { @@ -1219,31 +1400,32 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun public Nodegroup describeNodeGroup(String clusterName, String nodegroupName) { describeCluster(clusterName); - return nodeGroupStorage.get(nodeGroupKey(clusterName, nodegroupName)) + return nodeGroupStorage.get(nodeGroupKey(requestClusterKey(clusterName), nodegroupName)) .orElseThrow(() -> new AwsException("ResourceNotFoundException", "No nodegroup found for name: " + nodegroupName, 404)); } public List listNodeGroups(String clusterName) { describeCluster(clusterName); - String prefix = clusterName + "/"; + String prefix = requestClusterKey(clusterName) + "/"; return nodeGroupStorage.scan(key -> key.startsWith(prefix)).stream() .map(Nodegroup::getNodegroupName) .collect(Collectors.toList()); } /** Serializes node group capacity changes and cluster deletion; taken before clustersBeingDeleted. */ - private Object capacityLock(String accountId, String clusterName) { - return nodeGroupCapacityLocks.computeIfAbsent(accountId + "/" + clusterName, ignored -> new Object()); + private Object capacityLock(String accountId, String clusterKey) { + return nodeGroupCapacityLocks.computeIfAbsent(accountId + "/" + clusterKey, ignored -> new Object()); } public Nodegroup deleteNodeGroup(String clusterName, String nodegroupName) { - Object capacityLock = capacityLock(regionResolver.getAccountId(), clusterName); + String clusterKey = requestClusterKey(clusterName); + Object capacityLock = capacityLock(regionResolver.getAccountId(), clusterKey); synchronized (capacityLock) { Nodegroup nodeGroup = describeNodeGroup(clusterName, nodegroupName); nodeGroup.setStatus(NodegroupStatus.DELETING); nodeGroup.setModifiedAt(Instant.now()); - nodeGroupStorage.delete(nodeGroupKey(clusterName, nodegroupName)); + nodeGroupStorage.delete(nodeGroupKey(clusterKey, nodegroupName)); return nodeGroup; } } @@ -1259,7 +1441,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun throw new AwsException("InvalidParameterException", "podExecutionRoleArn is required", 400); } - String storageKey = fargateProfileKey(clusterName, fargateProfileName); + String storageKey = fargateProfileKey(clusterKey(cluster), fargateProfileName); if (fargateProfileStorage.get(storageKey).isPresent()) { throw new AwsException("ResourceInUseException", "Fargate profile already exists: " + fargateProfileName, 409); @@ -1290,14 +1472,14 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun public FargateProfile describeFargateProfile(String clusterName, String fargateProfileName) { describeCluster(clusterName); - return fargateProfileStorage.get(fargateProfileKey(clusterName, fargateProfileName)) + return fargateProfileStorage.get(fargateProfileKey(requestClusterKey(clusterName), fargateProfileName)) .orElseThrow(() -> new AwsException("ResourceNotFoundException", "No fargate profile found for name: " + fargateProfileName, 404)); } public List listFargateProfiles(String clusterName) { describeCluster(clusterName); - String prefix = clusterName + "/"; + String prefix = requestClusterKey(clusterName) + "/"; return fargateProfileStorage.scan(key -> key.startsWith(prefix)).stream() .map(FargateProfile::getFargateProfileName) .collect(Collectors.toList()); @@ -1306,7 +1488,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun public FargateProfile deleteFargateProfile(String clusterName, String fargateProfileName) { FargateProfile profile = describeFargateProfile(clusterName, fargateProfileName); profile.setStatus(FargateProfileStatus.DELETING); - fargateProfileStorage.delete(fargateProfileKey(clusterName, fargateProfileName)); + fargateProfileStorage.delete(fargateProfileKey(requestClusterKey(clusterName), fargateProfileName)); return profile; } @@ -1378,6 +1560,8 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun } String clusterName = parts[1]; String childName = child ? parts[2] : ""; + // The ARN names the Region its cluster is in, and cluster names are unique only within one. + String clusterKey = clusterKey(AwsArnUtils.parse(resourceArn).region(), clusterName); UnaryOperator> change = current -> { Map next = edit.apply(current); if (!next.equals(current)) { @@ -1386,28 +1570,28 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun return next; }; Optional> tags = switch (parts[0]) { - case "cluster" -> storage.get(clusterName).map(cluster -> applyTags(cluster.getTags(), change, next -> { + case "cluster" -> storage.get(clusterKey).map(cluster -> applyTags(cluster.getTags(), change, next -> { cluster.setTags(new HashMap<>(next)); - storage.put(clusterName, cluster); + storage.put(clusterKey, cluster); })); - case "nodegroup" -> nodeGroupStorage.get(nodeGroupKey(clusterName, childName)) + case "nodegroup" -> nodeGroupStorage.get(nodeGroupKey(clusterKey, childName)) .filter(nodegroup -> resourceArn.equals(nodegroup.getNodegroupArn())) .map(nodegroup -> applyTags(nodegroup.getTags(), change, next -> { nodegroup.setTags(new HashMap<>(next)); - nodeGroupStorage.put(nodeGroupKey(clusterName, childName), nodegroup); + nodeGroupStorage.put(nodeGroupKey(clusterKey, childName), nodegroup); })); - case "fargateprofile" -> fargateProfileStorage.get(fargateProfileKey(clusterName, childName)) + case "fargateprofile" -> fargateProfileStorage.get(fargateProfileKey(clusterKey, childName)) .filter(profile -> resourceArn.equals(profile.getFargateProfileArn())) .map(profile -> applyTags(profile.getTags(), change, next -> { profile.setTags(new HashMap<>(next)); - fargateProfileStorage.put(fargateProfileKey(clusterName, childName), profile); + fargateProfileStorage.put(fargateProfileKey(clusterKey, childName), profile); })); - case "addon" -> addons == null ? Optional.empty() : storage.get(clusterName) + case "addon" -> addons == null ? Optional.empty() : storage.get(clusterKey) .flatMap(cluster -> addons.retag(cluster, childName, resourceArn, change)); case "podidentityassociation" -> podIdentityAssociations == null ? Optional.empty() - : storage.get(clusterName) + : storage.get(clusterKey) .flatMap(cluster -> podIdentityAssociations.retag(cluster, childName, resourceArn, change)); - case "access-entry" -> accessEntries == null ? Optional.empty() : storage.get(clusterName) + case "access-entry" -> accessEntries == null ? Optional.empty() : storage.get(clusterKey) .flatMap(cluster -> accessEntries.retag(cluster, resourceArn, change)); default -> Optional.empty(); }; @@ -1642,12 +1826,12 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun return List.of(new EncryptionConfig(List.of("secrets"), new Provider(config.getProvider().getKeyArn()))); } - private String nodeGroupKey(String clusterName, String nodegroupName) { - return clusterName + "/" + nodegroupName; + private static String nodeGroupKey(String clusterKey, String nodegroupName) { + return clusterKey + "/" + nodegroupName; } - private String fargateProfileKey(String clusterName, String fargateProfileName) { - return clusterName + "/" + fargateProfileName; + private static String fargateProfileKey(String clusterKey, String fargateProfileName) { + return clusterKey + "/" + fargateProfileName; } private NodegroupScalingConfig defaultScalingConfig() { @@ -1816,7 +2000,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun if (cluster == null || cluster.getName() == null || isClusterDeleting(accountId, cluster)) { return; } - String key = (accountId != null ? accountId : "default") + "/" + cluster.getName(); + String key = (accountId != null ? accountId : "default") + "/" + clusterKey(cluster); if (!restoringClusters.add(key)) { return; } @@ -1853,9 +2037,9 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun private void putCluster(Cluster cluster) { if (cluster.getAccountId() != null && storage instanceof AccountAwareStorageBackend aware) { - aware.putForAccount(cluster.getAccountId(), cluster.getName(), cluster); + aware.putForAccount(cluster.getAccountId(), clusterKey(cluster), cluster); } else { - storage.put(cluster.getName(), cluster); + storage.put(clusterKey(cluster), cluster); } } diff --git a/src/main/java/io/floci/aws/services/eks/EksWorkerAuthentication.java b/src/main/java/io/floci/aws/services/eks/EksWorkerAuthentication.java index 9f85b0fd2e..4704aef460 100644 --- a/src/main/java/io/floci/aws/services/eks/EksWorkerAuthentication.java +++ b/src/main/java/io/floci/aws/services/eks/EksWorkerAuthentication.java @@ -57,7 +57,7 @@ class EksWorkerAuthentication { || !region.equals(token.region()) || identity.roleArn() == null || identity.roleId() == null) { return Optional.empty(); } - Optional cluster = eks.findAuthenticationCluster(account, name) + Optional cluster = eks.findAuthenticationCluster(account, region, name) .filter(value -> value.getArn() != null && value.getArn().equals( AwsArnUtils.Arn.of("eks", region, account, "cluster/" + name).toString())) .filter(value -> createdAt.equals(String.valueOf(value.getCreatedAt()))); diff --git a/src/main/java/io/floci/aws/services/eks/model/Cluster.java b/src/main/java/io/floci/aws/services/eks/model/Cluster.java index e4469376c2..846c739bf0 100644 --- a/src/main/java/io/floci/aws/services/eks/model/Cluster.java +++ b/src/main/java/io/floci/aws/services/eks/model/Cluster.java @@ -128,6 +128,18 @@ public class Cluster { @JsonInclude(JsonInclude.Include.NON_NULL) private Boolean defaultStorageClass; + /** + * The Region that qualifies this cluster's Docker container and volume names, or null for a + * name without one. Cluster names are unique only within a Region, so a cluster outside the + * default Region, or one sharing its name with a cluster in another Region, is qualified. + * Persisted because a restore re-derives the Docker name from the record, and a cluster + * created before Region qualification must keep its unqualified name. Internal metadata + * omitted from AWS API responses. + */ + @JsonProperty("dockerNameRegion") + @JsonInclude(JsonInclude.Include.NON_NULL) + private String dockerNameRegion; + // Internal persisted map of joined EC2 instance IDs to their region. @JsonProperty("joinedInstanceIds") @JsonInclude(JsonInclude.Include.NON_EMPTY) @@ -224,6 +236,9 @@ public class Cluster { public String getDockerName() { return dockerName; } public void setDockerName(String dockerName) { this.dockerName = dockerName; } + public String getDockerNameRegion() { return dockerNameRegion; } + public void setDockerNameRegion(String dockerNameRegion) { this.dockerNameRegion = dockerNameRegion; } + public String getPodCidr() { return podCidr; } public void setPodCidr(String podCidr) { this.podCidr = podCidr; } @@ -261,6 +276,7 @@ public class Cluster { c.finalizePending = this.finalizePending; c.explicitVersion = this.explicitVersion; c.dockerName = this.dockerName; + c.dockerNameRegion = this.dockerNameRegion; c.nodeInstanceType = this.nodeInstanceType; c.clusterArgs = this.clusterArgs != null ? new ArrayList<>(this.clusterArgs) : null; c.defaultStorageClass = this.defaultStorageClass; diff --git a/src/test/java/io/floci/aws/services/eks/EksClusterManagerArchiveRetryTest.java b/src/test/java/io/floci/aws/services/eks/EksClusterManagerArchiveRetryTest.java index 5bcb82cc7e..4d86998aa9 100644 --- a/src/test/java/io/floci/aws/services/eks/EksClusterManagerArchiveRetryTest.java +++ b/src/test/java/io/floci/aws/services/eks/EksClusterManagerArchiveRetryTest.java @@ -213,7 +213,7 @@ class EksClusterManagerArchiveRetryTest { void podIdentityManifestRetriesWithItsFullContentAndMode() { failFirstUploadOf("server/manifests/floci-eks-pod-identity.yaml"); byte[] expected = EksClusterManager.buildPodIdentityWebhookConfiguration( - "https://host.docker.internal:4566/_floci/eks/clusters/demo/pod-identity-webhook/scope/000000000000", + "https://host.docker.internal:4566/_floci/eks/clusters/demo/pod-identity-webhook/scope/000000000000/us-east-1", CA_PEM).getBytes(StandardCharsets.UTF_8); manager.registerPodIdentityWebhook(CONTAINER_ID, cluster()); @@ -245,7 +245,7 @@ class EksClusterManagerArchiveRetryTest { Cluster cluster = cluster(); cluster.setLogging(new Logging(List.of(new LogSetup(List.of("audit"), true)))); ClusterOidcKey key = new ClusterOidcKey("https://test.invalid/issuer", "fixture", "public", "private"); - when(oidcService.ensureKeyForAccount("000000000000", "demo", key.getIssuer())).thenReturn(key); + when(oidcService.ensureKeyForAccount("000000000000", "us-east-1::demo", key.getIssuer())).thenReturn(key); when(oidcService.exportSigningKeyPem(key)).thenReturn(new String(PRIVATE_KEY, StandardCharsets.UTF_8)); when(oidcService.exportPublicKeyPem(key)).thenReturn(new String(PUBLIC_KEY, StandardCharsets.UTF_8)); diff --git a/src/test/java/io/floci/aws/services/eks/EksClusterManagerTest.java b/src/test/java/io/floci/aws/services/eks/EksClusterManagerTest.java index 6fe5d2af7d..83c65bcf39 100644 --- a/src/test/java/io/floci/aws/services/eks/EksClusterManagerTest.java +++ b/src/test/java/io/floci/aws/services/eks/EksClusterManagerTest.java @@ -1274,6 +1274,44 @@ class EksClusterManagerTest { assertEquals("floci-aws-eks-demo", manager.clusterResourceName(cluster)); } + @Test + void regionQualifiedClustersLeadWithTheirRegion() { + // Cluster names are unique only per Region (#7966): two Regions' same-named clusters + // must not share a container and data volume. + when(config.defaultAccountId()).thenReturn("000000000000"); + + Cluster defaultAccount = cluster(); + defaultAccount.setAccountId("000000000000"); + defaultAccount.setDockerNameRegion("eu-west-1"); + Cluster otherAccount = cluster(); + otherAccount.setAccountId("999999999999"); + otherAccount.setDockerNameRegion("eu-west-1"); + + assertEquals("floci-aws-eks-eu-west-1.demo", manager.clusterResourceName(defaultAccount)); + assertEquals("floci-aws-eks-eu-west-1.999999999999.demo", manager.clusterResourceName(otherAccount)); + } + + @Test + void aRegionQualifiedClusterNeverClaimsTheUnqualifiedContainer() { + // The unqualified container may belong to the same-named cluster in another Region, + // created before Region qualification. + when(config.defaultAccountId()).thenReturn("000000000000"); + when(lifecycleManager.findByName("floci-aws-eks-eu-west-1.demo")) + .thenReturn(Optional.of(survivingContainer("cid-eu"))); + when(lifecycleManager.adopt("cid-eu", List.of(6443), Optional.empty())) + .thenReturn(new ContainerInfo("cid-eu", Map.of(), Map.of(6443, 6521))); + + Cluster cluster = cluster(); + cluster.setAccountId("000000000000"); + cluster.setDockerNameRegion("eu-west-1"); + manager.restoreCluster(cluster); + + assertEquals("cid-eu", cluster.getContainerId()); + assertEquals("floci-aws-eks-eu-west-1.demo", cluster.getDockerName()); + verify(lifecycleManager, never()).findByName("floci-aws-eks-demo"); + verify(lifecycleManager, never()).findByName("floci-eks-demo"); + } + @Test void legacyNamedContainerIsKeptWhenItsAccountLabelMatchesTheOwner() { // A non-default-account cluster created before account-qualified naming left its @@ -1436,7 +1474,7 @@ class EksClusterManagerTest { clusterWithArn("arn:aws:eks:us-east-1:000000000000:cluster/demo")); assertEquals(EksClusterManager.buildRegistriesYaml("000000000000", AwsRegions.advertised("aws"), - 4566, "http://floci:4566"), Files.readString(tempDir.resolve("registries/demo/registries.yaml"))); + 4566, "http://floci:4566"), Files.readString(tempDir.resolve("registries/000000000000/us-east-1/demo/registries.yaml"))); } @Test @@ -1444,7 +1482,7 @@ class EksClusterManagerTest { manager.injectEcrRegistryMirror("container-1", clusterWithArn("arn:aws-cn:eks:cn-north-1:000000000000:cluster/demo")); - String yaml = Files.readString(tempDir.resolve("registries/demo/registries.yaml")); + String yaml = Files.readString(tempDir.resolve("registries/000000000000/cn-north-1/demo/registries.yaml")); assertTrue(yaml.contains("\"000000000000.dkr.ecr.cn-north-1.localhost:4566\":")); assertTrue(yaml.contains("\"000000000000.dkr.ecr.cn-northwest-1.localhost:4566\":")); assertFalse(yaml.contains(".us-east-1."), "a China cluster pulls from China regions only"); @@ -1457,7 +1495,7 @@ class EksClusterManagerTest { manager.injectEcrRegistryMirror("container-1", cluster); - String yaml = Files.readString(tempDir.resolve("registries/demo/registries.yaml")); + String yaml = Files.readString(tempDir.resolve("registries/111122223333/eu-west-1/demo/registries.yaml")); assertTrue(yaml.contains("\"111122223333.dkr.ecr.eu-west-1.localhost:4566\":")); assertTrue(yaml.contains("\"000000000000.dkr.ecr.eu-west-1.localhost:4566\":")); } @@ -1470,7 +1508,7 @@ class EksClusterManagerTest { verify(copyCmd).withRemotePath("/etc"); verify(copyCmd).exec(); verify(config, never()).tls(); - String yaml = Files.readString(tempDir.resolve("registries/demo/registries.yaml")); + String yaml = Files.readString(manager.localClusterFile(demoCluster(), "registries", "registries.yaml")); assertFalse(yaml.contains("localhost.floci.io")); } @@ -1482,7 +1520,7 @@ class EksClusterManagerTest { manager.injectEcrRegistryMirror("container-1", demoCluster()); - String yaml = Files.readString(tempDir.resolve("registries/demo/registries.yaml")); + String yaml = Files.readString(manager.localClusterFile(demoCluster(), "registries", "registries.yaml")); assertTrue(yaml.contains("\"000000000000.dkr.ecr.us-east-1.localhost:54321\":")); assertTrue(yaml.contains("\"localhost:54321\":")); assertFalse(yaml.contains("localhost:4566\":")); @@ -1499,7 +1537,7 @@ class EksClusterManagerTest { manager.injectEcrRegistryMirror("container-1", demoCluster()); - String yaml = Files.readString(tempDir.resolve("registries/demo/registries.yaml")); + String yaml = Files.readString(manager.localClusterFile(demoCluster(), "registries", "registries.yaml")); assertTrue(yaml.contains("\"000000000000.dkr.ecr.us-east-1.localhost.floci.io:4566\":")); assertTrue(yaml.contains("\"localhost.floci.io:4566\":")); assertTrue(yaml.contains("- \"http://floci:4566\"")); @@ -1515,7 +1553,7 @@ class EksClusterManagerTest { manager.injectEcrRegistryMirror("container-1", demoCluster()); - String yaml = Files.readString(tempDir.resolve("registries/demo/registries.yaml")); + String yaml = Files.readString(manager.localClusterFile(demoCluster(), "registries", "registries.yaml")); assertFalse(yaml.contains("localhost.floci.io")); assertTrue(yaml.contains("\"localhost:4566\":")); verify(copyCmd).exec(); @@ -2415,6 +2453,10 @@ class EksClusterManagerTest { Path privFile = keysDir.resolve(EksClusterManager.SA_SIGNING_KEY_FILE); Path pubFile = keysDir.resolve(EksClusterManager.SA_PUBLIC_KEY_FILE); assertEquals(tempDir.resolve("keys").resolve("000000000000").resolve("us-east-1").resolve("my-cluster"), keysDir); + // The key k3s signs with is the one EksService creates and JWKS publishes, under the + // cluster's Regional key, not a second key minted under the bare name (#7966). + verify(oidcService).ensureKeyForAccount("000000000000", "us-east-1::my-cluster", issuer); + verify(oidcService, never()).ensureKeyForAccount(anyString(), eq("my-cluster"), anyString()); assertTrue(Files.exists(privFile)); assertTrue(Files.exists(pubFile)); @@ -2807,7 +2849,7 @@ class EksClusterManagerTest { nodegroup.setCapacityType("ON_DEMAND"); nodegroup.setInstanceTypes(List.of("t3.medium")); nodegroup.setLabels(Map.of("environment", "production", "team", "platform")); - nodeGroupStorage.put("prod-cluster/worker-group-1", nodegroup); + nodeGroupStorage.put("us-west-2::prod-cluster/worker-group-1", nodegroup); manager.startCluster(cluster); @@ -2846,7 +2888,7 @@ class EksClusterManagerTest { Map.of("key", "evict", "value", "true", "effect", "NO_EXECUTE"), Map.of("key", "spot", "value", "preemptible", "effect", "PREFER_NO_SCHEDULE") )); - nodeGroupStorage.put("prod-cluster/gpu-group", nodegroup); + nodeGroupStorage.put("us-west-2::prod-cluster/gpu-group", nodegroup); manager.startCluster(cluster); @@ -2869,7 +2911,7 @@ class EksClusterManagerTest { Nodegroup nodegroup = new Nodegroup(); nodegroup.setNodegroupName("spot-group"); nodegroup.setCapacityType("SPOT"); - nodeGroupStorage.put("prod-cluster/spot-group", nodegroup); + nodeGroupStorage.put("us-west-2::prod-cluster/spot-group", nodegroup); manager.startCluster(cluster); @@ -2897,7 +2939,7 @@ class EksClusterManagerTest { Nodegroup nodegroup = new Nodegroup(); nodegroup.setNodegroupName("block-group"); nodegroup.setCapacityType("CAPACITY_BLOCK"); - nodeGroupStorage.put("prod-cluster/block-group", nodegroup); + nodeGroupStorage.put("us-west-2::prod-cluster/block-group", nodegroup); manager.startCluster(cluster); @@ -2956,8 +2998,8 @@ class EksClusterManagerTest { second.setLabels(Map.of("role", "backend", "secondary", "true")); second.setTaints(List.of(Map.of("key", "tier", "value", "backend", "effect", "NO_SCHEDULE"))); - nodeGroupStorage.put("prod-cluster/second-ng", second); - nodeGroupStorage.put("prod-cluster/first-ng", first); + nodeGroupStorage.put("us-west-2::prod-cluster/second-ng", second); + nodeGroupStorage.put("us-west-2::prod-cluster/first-ng", first); manager.startCluster(cluster); @@ -2993,7 +3035,7 @@ class EksClusterManagerTest { Nodegroup nodegroup = new Nodegroup(); nodegroup.setNodegroupName("app-workers"); nodegroup.setLabels(Map.of("app", "test")); - nodeGroupStorage.put("prod-cluster/app-workers", nodegroup); + nodeGroupStorage.put("us-west-2::prod-cluster/app-workers", nodegroup); manager.startCluster(cluster); @@ -3034,7 +3076,7 @@ class EksClusterManagerTest { "node.kubernetes.io/instance-type", "fake-type", "custom-label", "valid-value" )); - nodeGroupStorage.put("prod-cluster/worker-group", nodegroup); + nodeGroupStorage.put("us-west-2::prod-cluster/worker-group", nodegroup); manager.startCluster(cluster); @@ -3068,7 +3110,7 @@ class EksClusterManagerTest { Nodegroup nodegroup = new Nodegroup(); nodegroup.setNodegroupName("custom-group"); nodegroup.setInstanceTypes(List.of("nonexistent.nano")); - nodeGroupStorage.put("prod-cluster/custom-group", nodegroup); + nodeGroupStorage.put("us-west-2::prod-cluster/custom-group", nodegroup); manager.startCluster(cluster); @@ -3095,7 +3137,7 @@ class EksClusterManagerTest { Nodegroup nodegroup = new Nodegroup(); nodegroup.setNodegroupName("versioned-group"); nodegroup.setReleaseVersion("1.30.2-20240703"); - nodeGroupStorage.put("prod-cluster/versioned-group", nodegroup); + nodeGroupStorage.put("us-west-2::prod-cluster/versioned-group", nodegroup); manager.startCluster(cluster); @@ -3641,10 +3683,25 @@ class EksClusterManagerTest { verify(copyCmd).withRemotePath("/var/lib/rancher/k3s"); verify(copyCmd).exec(); - String written = Files.readString(tempDir.resolve("webhook").resolve("demo") + String written = Files.readString(tempDir.resolve("webhook/000000000000/us-east-1/demo") .resolve("floci-eks-pod-identity.yaml")); assertTrue(written.contains("https://host.docker.internal:4566" - + "/_floci/eks/clusters/demo/pod-identity-webhook/scope/000000000000")); + + "/_floci/eks/clusters/demo/pod-identity-webhook/scope/000000000000/us-east-1")); + } + + @Test + void sameNamedClustersInTwoRegionsKeepTheirLocalFilesApart() { + // Cluster names are unique only within a Region (#7966); a shared path would let one + // cluster's token-webhook kubeconfig be copied into the other's container. + Cluster west = cluster(); + west.setArn("arn:aws:eks:eu-west-1:000000000000:cluster/demo"); + Cluster central = cluster(); + central.setArn("arn:aws:eks:eu-central-1:000000000000:cluster/demo"); + + assertEquals(tempDir.resolve("webhook/000000000000/eu-west-1/demo/token-webhook.yaml"), + manager.localClusterFile(west, "webhook", "token-webhook.yaml")); + assertNotEquals(manager.localClusterFile(west, "webhook", "token-webhook.yaml"), + manager.localClusterFile(central, "webhook", "token-webhook.yaml")); } @Test diff --git a/src/test/java/io/floci/aws/services/eks/EksIrsaDockerIntegrationTest.java b/src/test/java/io/floci/aws/services/eks/EksIrsaDockerIntegrationTest.java index 04f9abd312..fd94afa1b4 100644 --- a/src/test/java/io/floci/aws/services/eks/EksIrsaDockerIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/eks/EksIrsaDockerIntegrationTest.java @@ -127,7 +127,7 @@ class EksIrsaDockerIntegrationTest { String issuer = oidcService.newIssuerUrl("us-east-1"); cluster.setIdentity(new ClusterIdentity( new OidcIdentity(issuer))); - oidcService.ensureKeyForAccount(ACCOUNT, clusterName, issuer); + oidcService.ensureKeyForAccount(ACCOUNT, EksService.clusterKey("us-east-1", clusterName), issuer); eksClusterManager.startCluster(cluster); assertNotNull(cluster.getContainerId(), "Container ID must not be null"); diff --git a/src/test/java/io/floci/aws/services/eks/EksIrsaEndToEndIntegrationTest.java b/src/test/java/io/floci/aws/services/eks/EksIrsaEndToEndIntegrationTest.java index b4fa083f6b..cf73600196 100644 --- a/src/test/java/io/floci/aws/services/eks/EksIrsaEndToEndIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/eks/EksIrsaEndToEndIntegrationTest.java @@ -18,6 +18,7 @@ import java.util.Base64; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.notNullValue; @@ -112,7 +113,7 @@ class EksIrsaEndToEndIntegrationTest { } private PrivateKey clusterSigningKey() throws Exception { - String encoded = oidcService.ensureKey(CLUSTER, issuer).getPrivateKey(); + String encoded = oidcService.ensureKey(EksService.clusterKey("us-east-1", CLUSTER), issuer).getPrivateKey(); return KeyFactory.getInstance("RSA") .generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder().decode(encoded))); } @@ -265,6 +266,9 @@ class EksIrsaEndToEndIntegrationTest { .then() .statusCode(200) .body("issuer", equalTo(issuer)) + // The key route names the cluster's Region: a verifier follows it without context. + .body("jwks_uri", endsWith( + "/_floci/eks/clusters/" + CLUSTER + "/oidc/keys?region=us-east-1")) .body("id_token_signing_alg_values_supported[0]", equalTo("RS256")); given() diff --git a/src/test/java/io/floci/aws/services/eks/EksOidcIdentityIntegrationTest.java b/src/test/java/io/floci/aws/services/eks/EksOidcIdentityIntegrationTest.java index 25ca67b895..e155183fde 100644 --- a/src/test/java/io/floci/aws/services/eks/EksOidcIdentityIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/eks/EksOidcIdentityIntegrationTest.java @@ -69,7 +69,7 @@ class EksOidcIdentityIntegrationTest { void describeClusterNeverExposesSigningMaterial() { // Asserted against the actual stored key rather than a list of guessed field names, so this // fails if key material is ever surfaced under any property. - ClusterOidcKey stored = oidcService.findKeyByCluster(CLUSTER).orElseThrow(); + ClusterOidcKey stored = oidcService.findKeyByCluster(EksService.clusterKey("us-east-1", CLUSTER)).orElseThrow(); String body = given() .when() diff --git a/src/test/java/io/floci/aws/services/eks/EksPodIdentityAccountIntegrationTest.java b/src/test/java/io/floci/aws/services/eks/EksPodIdentityAccountIntegrationTest.java index 06cb05dbcd..bd9ceef424 100644 --- a/src/test/java/io/floci/aws/services/eks/EksPodIdentityAccountIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/eks/EksPodIdentityAccountIntegrationTest.java @@ -84,7 +84,7 @@ class EksPodIdentityAccountIntegrationTest { cluster.setStatus(ClusterStatus.ACTIVE); String issuer = oidcService.newIssuerUrl("us-east-1"); cluster.setIdentity(new ClusterIdentity(new OidcIdentity(issuer))); - oidcService.ensureKeyForAccount(account, name, issuer); + oidcService.ensureKeyForAccount(account, EksService.clusterKey("us-east-1", name), issuer); eksService.putClusterForAccount(account, cluster); // Persisted clusters lose this @JsonIgnore field; the ARN still names the owner. cluster.setAccountId(null); @@ -108,7 +108,7 @@ class EksPodIdentityAccountIntegrationTest { private String mintToken(String account, Cluster cluster) { return RequestScopes.callAs(account, () -> oidcService.mintServiceAccountToken( - cluster.getName(), cluster.getIdentity().getOidc().getIssuer(), + EksService.clusterKey("us-east-1", cluster.getName()), cluster.getIdentity().getOidc().getIssuer(), NAMESPACE, SERVICE_ACCOUNT, "pods.eks.amazonaws.com", 3600)); } diff --git a/src/test/java/io/floci/aws/services/eks/EksPodIdentityDockerIntegrationTest.java b/src/test/java/io/floci/aws/services/eks/EksPodIdentityDockerIntegrationTest.java index bc2de1bde1..0638823263 100644 --- a/src/test/java/io/floci/aws/services/eks/EksPodIdentityDockerIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/eks/EksPodIdentityDockerIntegrationTest.java @@ -139,7 +139,7 @@ class EksPodIdentityDockerIntegrationTest { cluster.setIdentity(new ClusterIdentity(new OidcIdentity(issuer))); eksService.putClusterForAccount("000000000000", cluster); - ClusterOidcKey key = oidcService.ensureKeyForAccount("000000000000", clusterName, issuer); + ClusterOidcKey key = oidcService.ensureKeyForAccount("000000000000", EksService.clusterKey("us-east-1", clusterName), issuer); assertNotNull(key); associationService.create(cluster, new CreatePodIdentityAssociationRequest( @@ -162,7 +162,7 @@ class EksPodIdentityDockerIntegrationTest { eksClusterManager.configurePodIdentityRelay(cluster, containerId); - String validToken = oidcService.mintServiceAccountToken(clusterName, issuer, "default", "workload-sa", + String validToken = oidcService.mintServiceAccountToken(EksService.clusterKey("us-east-1", clusterName), issuer, "default", "workload-sa", "pods.eks.amazonaws.com", 3600); String credsJson = execInContainer(containerId, "curl -s -f -H 'Authorization: " + validToken + "' http://169.254.170.23/v1/credentials"); @@ -170,7 +170,7 @@ class EksPodIdentityDockerIntegrationTest { assertTrue(credsJson.contains("\"AccessKeyId\"")); assertTrue(credsJson.contains("ASIA")); - String unassociatedToken = oidcService.mintServiceAccountToken(clusterName, issuer, "default", "other-sa", + String unassociatedToken = oidcService.mintServiceAccountToken(EksService.clusterKey("us-east-1", clusterName), issuer, "default", "other-sa", "pods.eks.amazonaws.com", 3600); String missingCode = execInContainer(containerId, "curl -s -o /dev/null -w '%{http_code}' -H 'Authorization: " + unassociatedToken + "' http://169.254.170.23/v1/credentials"); assertEquals("404", missingCode.trim()); diff --git a/src/test/java/io/floci/aws/services/eks/EksPodIdentityWebhookTest.java b/src/test/java/io/floci/aws/services/eks/EksPodIdentityWebhookTest.java index 568bf16db9..f6d453d1c8 100644 --- a/src/test/java/io/floci/aws/services/eks/EksPodIdentityWebhookTest.java +++ b/src/test/java/io/floci/aws/services/eks/EksPodIdentityWebhookTest.java @@ -48,7 +48,7 @@ class EksPodIdentityWebhookTest { Cluster cluster = new Cluster(); cluster.setName(CLUSTER_NAME); - when(eks.findAuthenticationCluster(ACCOUNT_ID, CLUSTER_NAME)).thenReturn(Optional.of(cluster)); + 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(associations.list(any(), anyString(), anyString(), any(), any())) @@ -197,9 +197,27 @@ class EksPodIdentityWebhookTest { return reviews; } + /** + * A route carrying the Region reviews against that Region's cluster. The Region-less route + * resolves the cluster created before Regional names, which registered it (#7966). + */ + @Test + void aRouteWithARegionReviewsAgainstThatRegionsCluster() throws Exception { + Cluster regional = new Cluster(); + regional.setName(CLUSTER_NAME); + when(eks.findAuthenticationCluster(ACCOUNT_ID, "eu-west-1", CLUSTER_NAME)).thenReturn(Optional.of(regional)); + + Map review = webhook.review(CLUSTER_NAME, ACCOUNT_ID, "eu-west-1", + admissionReview(pod("checkout", List.of(Map.of("name", "app"))))); + + assertEquals(3, patchOf(review).size()); + Mockito.verify(associations).list(eq(regional), eq("payments"), eq("checkout"), any(), any()); + Mockito.verify(eks, Mockito.never()).findPreRegionalCluster(any(), any()); + } + @Test void internalErrorStillAdmitsThePod() throws Exception { - when(eks.findAuthenticationCluster(ACCOUNT_ID, CLUSTER_NAME)) + when(eks.findPreRegionalCluster(ACCOUNT_ID, CLUSTER_NAME)) .thenThrow(new IllegalStateException("storage is gone")); Map review = webhook.review(CLUSTER_NAME, ACCOUNT_ID, diff --git a/src/test/java/io/floci/aws/services/eks/EksRegionScopingIntegrationTest.java b/src/test/java/io/floci/aws/services/eks/EksRegionScopingIntegrationTest.java index 7d83e9d902..7b33388157 100644 --- a/src/test/java/io/floci/aws/services/eks/EksRegionScopingIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/eks/EksRegionScopingIntegrationTest.java @@ -3,12 +3,18 @@ package io.floci.aws.services.eks; import io.quarkus.test.junit.QuarkusTest; import org.junit.jupiter.api.Test; +import java.util.HashMap; +import java.util.List; import java.util.Map; import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasKey; import static org.hamcrest.Matchers.not; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Cluster names are Regional on AWS: a cluster created in one Region is not listed, described or @@ -47,6 +53,85 @@ class EksRegionScopingIntegrationTest { } } + /** #7966: a name only has to be unique within a Region of the account. */ + @Test + void theSameClusterNameCanBeUsedInTwoRegions() { + String name = "region-shared"; + Map issuers = new HashMap<>(); + for (String region : new String[] {"eu-west-1", "eu-central-1"}) { + issuers.put(region, given().header("Authorization", auth(region)).contentType("application/json") + .body(Map.of("name", name, "roleArn", "arn:aws:iam::" + ACCOUNT + ":role/cluster")) + .post("/clusters").then().statusCode(200) + .body("cluster.arn", equalTo("arn:aws:eks:" + region + ":" + ACCOUNT + ":cluster/" + name)) + .extract().path("cluster.identity.oidc.issuer")); + } + + try { + given().header("Authorization", auth("eu-west-1")).contentType("application/json") + .body(Map.of("name", name, "roleArn", "arn:aws:iam::" + ACCOUNT + ":role/cluster")) + .post("/clusters").then().statusCode(409) + .body("__type", equalTo("ResourceInUseException")); + + given().header("Authorization", auth("eu-west-1")).contentType("application/json") + .body(Map.of("nodegroupName", "workers", + "nodeRole", "arn:aws:iam::" + ACCOUNT + ":role/node", + "subnets", List.of("subnet-0123456789abcdef0"))) + .post("/clusters/" + name + "/node-groups").then().statusCode(200); + given().header("Authorization", auth("eu-west-1")).get("/clusters/" + name + "/node-groups") + .then().statusCode(200).body("nodegroups", hasItem("workers")); + given().header("Authorization", auth("eu-central-1")).get("/clusters/" + name + "/node-groups") + .then().statusCode(200).body("nodegroups", empty()); + + // OIDC discovery resolves the Region it is asked for, and advertises a key route that + // names it, since a verifier follows that route without the discovery request's context. + String westKeyId = null; + for (String region : new String[] {"eu-west-1", "eu-central-1"}) { + String jwksUri = given().header("Authorization", auth(region)) + .queryParam("region", region) + .get("/_floci/eks/clusters/" + name + "/oidc/.well-known/openid-configuration") + .then().statusCode(200) + .body("issuer", equalTo(issuers.get(region))) + .extract().path("jwks_uri"); + assertTrue(jwksUri.endsWith("/oidc/keys?region=" + region), jwksUri); + String keyId = given().header("Authorization", auth(region)) + .queryParam("region", region) + .get("/_floci/eks/clusters/" + name + "/oidc/keys") + .then().statusCode(200).extract().path("keys[0].kid"); + if (westKeyId == null) { + westKeyId = keyId; + } else { + assertNotEquals(westKeyId, keyId, "each Region's cluster has its own signing key"); + } + } + + // Minting takes the same ?region=, which wins over the request's Region, so an + // unsigned caller can pick either cluster. + for (String region : new String[] {"eu-west-1", "eu-central-1"}) { + given().header("Authorization", auth("eu-west-1")).contentType("application/json") + .queryParam("region", region) + .body(Map.of("namespace", "default", "serviceAccount", "app")) + .post("/_floci/eks/clusters/" + name + "/oidc-token") + .then().statusCode(200) + .body("issuer", equalTo(issuers.get(region))); + } + given().header("Authorization", auth("eu-west-1")).contentType("application/json") + .queryParam("region", "ap-south-1") + .body(Map.of("namespace", "default", "serviceAccount", "app")) + .post("/_floci/eks/clusters/" + name + "/oidc-token") + .then().statusCode(404); + + given().header("Authorization", auth("eu-west-1")).delete("/clusters/" + name) + .then().statusCode(200); + given().header("Authorization", auth("eu-central-1")).get("/clusters/" + name) + .then().statusCode(200) + .body("cluster.arn", equalTo("arn:aws:eks:eu-central-1:" + ACCOUNT + ":cluster/" + name)) + .body("cluster", not(hasKey("dockerNameRegion"))); + } finally { + given().header("Authorization", auth("eu-west-1")).delete("/clusters/" + name); + given().header("Authorization", auth("eu-central-1")).delete("/clusters/" + name); + } + } + private static String auth(String region) { return "AWS4-HMAC-SHA256 Credential=" + ACCOUNT + "/20261110/" + region + "/eks/aws4_request, SignedHeaders=host, Signature=abc"; diff --git a/src/test/java/io/floci/aws/services/eks/EksServiceTest.java b/src/test/java/io/floci/aws/services/eks/EksServiceTest.java index 9ad6c8cc47..8609c3218d 100644 --- a/src/test/java/io/floci/aws/services/eks/EksServiceTest.java +++ b/src/test/java/io/floci/aws/services/eks/EksServiceTest.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.storage.AccountAwareStorageBackend; @@ -52,11 +53,13 @@ import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.nio.file.Path; import java.time.Duration; +import java.util.ArrayList; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; @@ -211,6 +214,13 @@ class EksServiceTest { eksService.createCluster(clusterRequest); } + /** A service whose requests are in {@code region}, sharing the EC2 service of {@link #eksService}. */ + private EksService serviceInRegion(String region) { + return new EksService(storageFactory, testConfig(), new RegionResolver(region, "000000000000"), null, + ec2Service, new EksOidcService(storageFactory, new ObjectMapper()), mock(EksAccessEntryService.class), + mock(EksPodIdentityAssociationService.class)); + } + private CreateNodeGroupRequest nodeGroupRequest(String name) { CreateNodeGroupRequest request = new CreateNodeGroupRequest(); request.setNodegroupName(name); @@ -308,7 +318,9 @@ class EksServiceTest { mock(EksAccessEntryService.class), mock(EksPodIdentityAssociationService.class)); restarted.init(); - String issuer = clusterStore.get("eu-legacy-cluster").orElseThrow().getIdentity().getOidc().getIssuer(); + // Migrated onto the key of the Region its ARN names. + String issuer = restarted.findAuthenticationCluster("000000000000", "eu-west-1", "eu-legacy-cluster") + .orElseThrow().getIdentity().getOidc().getIssuer(); assertTrue(issuer.startsWith("https://oidc.eks.eu-west-1.amazonaws.com/id/"), issuer); } @@ -359,15 +371,16 @@ class EksServiceTest { new EksService(fixedStorageFactory(clusterStore), testConfig(), new RegionResolver("us-east-1", "000000000000"), null, null, oidcService, mock(EksAccessEntryService.class)).init(); - Cluster migrated = clusterStore.getForAccount(otherAccount, "legacy-cluster").orElseThrow(); + Cluster migrated = clusterStore.getForAccount(otherAccount, "us-east-1::legacy-cluster").orElseThrow(); String issuer = migrated.getIdentity().getOidc().getIssuer(); assertNotNull(issuer); // The owner rehydrated from the storage key sticks to the record for later puts. assertEquals(otherAccount, migrated.getAccountId()); // No duplicate stranded under the default account. - assertTrue(clusterStore.getForAccount("000000000000", "legacy-cluster").isEmpty()); + assertTrue(clusterStore.getForAccount("000000000000", "us-east-1::legacy-cluster").isEmpty()); + assertTrue(clusterStore.getForAccount(otherAccount, "legacy-cluster").isEmpty()); // The signing key is stored under the owner too, and is still resolvable by issuer. - assertTrue(keyStore.getForAccount(otherAccount, "legacy-cluster").isPresent()); + assertTrue(keyStore.getForAccount(otherAccount, "us-east-1::legacy-cluster").isPresent()); assertTrue(oidcService.findVerificationKey(issuer).isPresent()); } @@ -436,13 +449,13 @@ class EksServiceTest { restarted.init(); verify(clusterManager).restoreCluster(persisted); - Cluster restored = clusterStore.getForAccount(otherAccount, "persisted-cluster").orElseThrow(); + Cluster restored = clusterStore.getForAccount(otherAccount, "us-east-1::persisted-cluster").orElseThrow(); assertEquals(ClusterStatus.CREATING, restored.getStatus()); // Rehydrated from the storage key, so the readiness poller's later put also lands // under the owner. assertEquals(otherAccount, restored.getAccountId()); // No duplicate stranded under the default account. - assertTrue(clusterStore.getForAccount("000000000000", "persisted-cluster").isEmpty()); + assertTrue(clusterStore.getForAccount("000000000000", "us-east-1::persisted-cluster").isEmpty()); } finally { restarted.shutdown(); } @@ -616,7 +629,8 @@ class EksServiceTest { boolean keepRunningOnShutdown) { AccountAwareStorageBackend clusterStore = new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, "000000000000"); - clusterStore.putForAccount("000000000000", cluster.getName(), cluster); + clusterStore.putForAccount("000000000000", EksService.clusterKey( + AwsArnUtils.regionOrDefault(cluster.getArn(), "us-east-1"), cluster.getName()), cluster); return new EksService(fixedStorageFactory(clusterStore), testConfig(false, keepRunningOnShutdown), new RegionResolver("us-east-1", "000000000000"), clusterManager, null, new EksOidcService(fixedStorageFactory(new InMemoryStorage()), @@ -1159,9 +1173,9 @@ class EksServiceTest { Nodegroup group = service.createNodeGroup("kept-during-swap", nodeGroupRequest("first")); assertEquals(NodegroupStatus.ACTIVE, group.getStatus()); - Cluster stored = (Cluster) createdStorage("eks-clusters.json").get("kept-during-swap").orElseThrow(); + Cluster stored = (Cluster) createdStorage("eks-clusters.json").get("us-east-1::kept-during-swap").orElseThrow(); assertTrue(stored.isFinalizePending()); - assertTrue(createdStorage("eks-nodegroups.json").get("kept-during-swap/first").isPresent()); + assertTrue(createdStorage("eks-nodegroups.json").get("us-east-1::kept-during-swap/first").isPresent()); } private static Cluster activeClusterWithRunningNode(EksService service, String name) { @@ -1674,7 +1688,7 @@ class EksServiceTest { ResourcesVpcConfig vpcConfig = new ResourcesVpcConfig(); vpcConfig.setClusterSecurityGroupId("sg-12345678"); cluster.setResourcesVpcConfig(vpcConfig); - clusterStore.putForAccount("000000000000", "failing-delete-cluster", cluster); + clusterStore.putForAccount("000000000000", "us-east-1::failing-delete-cluster", cluster); RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000"); StorageFactory storageFactory = fixedStorageFactory(clusterStore); @@ -1931,7 +1945,7 @@ class EksServiceTest { assertDoesNotThrow(service::init); - Cluster described = clusterStore.getForAccount(nonDefaultAccount, "non-default-eks") + Cluster described = clusterStore.getForAccount(nonDefaultAccount, "us-east-1::non-default-eks") .orElseThrow(); String sgId = described.getResourcesVpcConfig().getClusterSecurityGroupId(); assertNotNull(sgId); @@ -2683,7 +2697,8 @@ class EksServiceTest { cluster.setName("regional-cluster"); cluster.setArn("arn:aws:eks:eu-west-1:000000000000:cluster/regional-cluster"); cluster.setStatus(ClusterStatus.ACTIVE); - eksService.putClusterForAccount("000000000000", cluster); + EksService euService = serviceInRegion("eu-west-1"); + euService.putClusterForAccount("000000000000", cluster); LaunchTemplate lt = ec2Service.createLaunchTemplate("eu-west-1", "eu-lt", new LaunchTemplateData(), null, null); @@ -2691,7 +2706,7 @@ class EksServiceTest { CreateNodeGroupRequest request = nodeGroupRequest("regional-ng"); request.setLaunchTemplate(Map.of("id", lt.getLaunchTemplateId(), "version", "1")); - Nodegroup created = eksService.createNodeGroup("regional-cluster", request); + Nodegroup created = euService.createNodeGroup("regional-cluster", request); assertNotNull(created); assertTrue(created.getNodegroupArn().startsWith( "arn:aws:eks:eu-west-1:000000000000:nodegroup/regional-cluster/regional-ng/")); @@ -2703,7 +2718,8 @@ class EksServiceTest { cluster.setName("eu-cluster"); cluster.setArn("arn:aws:eks:eu-west-1:000000000000:cluster/eu-cluster"); cluster.setStatus(ClusterStatus.ACTIVE); - eksService.putClusterForAccount("000000000000", cluster); + EksService euService = serviceInRegion("eu-west-1"); + euService.putClusterForAccount("000000000000", cluster); LaunchTemplate lt = ec2Service.createLaunchTemplate("us-east-1", "us-only-lt", new LaunchTemplateData(), null, null); @@ -2712,7 +2728,7 @@ class EksServiceTest { request.setLaunchTemplate(Map.of("id", lt.getLaunchTemplateId(), "version", "1")); AwsException ex = assertThrows(AwsException.class, - () -> eksService.createNodeGroup("eu-cluster", request)); + () -> euService.createNodeGroup("eu-cluster", request)); assertEquals("InvalidParameterException", ex.getErrorCode()); assertEquals(400, ex.getHttpStatus()); assertTrue(ex.getMessage().contains("Launch template could not be found")); @@ -2877,4 +2893,218 @@ class EksServiceTest { assertEquals(List.of("--kubelet-arg=max-pods=250"), described.getClusterArgs()); assertEquals(Map.of("owner", "ops"), described.getTags()); } + + // ─── Regional cluster names (#7966) ─────────────────────────────────────── + + /** + * Services whose requests are in each of {@code regions}, over one set of stores keyed by file + * name, as the handlers of one Floci are. Stores already in {@code stores} are used as they are. + */ + private List servicesSharingStores(Map> stores, + String... regions) { + StorageFactory shared = new StorageFactory(null, null) { + @Override + @SuppressWarnings("unchecked") + public AccountAwareStorageBackend create(String serviceName, String fileName, + TypeReference> typeReference) { + return (AccountAwareStorageBackend) stores.computeIfAbsent(fileName, + ignored -> AccountAwareStorageBackend.inMemory("000000000000")); + } + }; + EksOidcService oidc = new EksOidcService(shared, new ObjectMapper()); + List services = new ArrayList<>(); + for (String region : regions) { + services.add(new EksService(shared, testConfig(), new RegionResolver(region, "000000000000"), null, + null, oidc, mock(EksAccessEntryService.class), mock(EksPodIdentityAssociationService.class))); + } + return services; + } + + private static CreateClusterRequest clusterRequest(String name) { + CreateClusterRequest request = new CreateClusterRequest(); + request.setName(name); + request.setRoleArn("arn:aws:iam::000000000000:role/eks-role"); + return request; + } + + @Test + void aClusterNameCanBeReusedInAnotherRegionOfTheAccount() { + List services = servicesSharingStores(new HashMap<>(), "us-east-1", "eu-west-1"); + EksService east = services.get(0); + EksService west = services.get(1); + + Cluster eastDemo = east.createCluster(clusterRequest("demo")); + Cluster westDemo = west.createCluster(clusterRequest("demo")); + + assertEquals("arn:aws:eks:us-east-1:000000000000:cluster/demo", eastDemo.getArn()); + assertEquals("arn:aws:eks:eu-west-1:000000000000:cluster/demo", westDemo.getArn()); + assertNotEquals(eastDemo.getIdentity().getOidc().getIssuer(), westDemo.getIdentity().getOidc().getIssuer()); + AwsException duplicate = assertThrows(AwsException.class, () -> west.createCluster(clusterRequest("demo"))); + assertEquals("ResourceInUseException", duplicate.getErrorCode()); + + // Children, tags and deletion each reach only their own Region's cluster. + west.createNodeGroup("demo", nodeGroupRequest("workers")); + west.createFargateProfile("demo", fargateProfileRequest("pods")); + assertEquals(List.of("workers"), west.listNodeGroups("demo")); + assertEquals(List.of(), east.listNodeGroups("demo")); + assertEquals(List.of(), east.listFargateProfiles("demo")); + east.createNodeGroup("demo", nodeGroupRequest("workers")); + + west.tagResource(westDemo.getArn(), Map.of("env", "west")); + assertEquals(Map.of("env", "west"), west.listTagsForResource(westDemo.getArn())); + assertEquals(Map.of(), east.listTagsForResource(eastDemo.getArn())); + + west.deleteCluster("demo"); + assertThrows(AwsException.class, () -> west.describeCluster("demo")); + assertSame(eastDemo, east.describeCluster("demo")); + assertEquals(List.of("workers"), east.listNodeGroups("demo")); + } + + @Test + void onlyClustersOutsideTheDefaultRegionOrSharingANameAreRegionQualifiedInDocker() { + List services = servicesSharingStores(new HashMap<>(), "us-east-1", "eu-west-1"); + EksService east = services.get(0); + EksService west = services.get(1); + + // The default Region keeps the historical name, so existing containers and DNS names hold. + assertNull(east.createCluster(clusterRequest("solo")).getDockerNameRegion()); + assertEquals("eu-west-1", west.createCluster(clusterRequest("shared")).getDockerNameRegion()); + // A same-named cluster in another Region may hold the unqualified name. + assertEquals("us-east-1", east.createCluster(clusterRequest("shared")).getDockerNameRegion()); + } + + @Test + void initMovesRecordsPersistedUnderTheBareClusterNameOntoRegionalKeys() { + String account = "000000000000"; + String issuer = "https://oidc.eks.eu-west-1.amazonaws.com/id/ABCDEF0123456789ABCDEF0123456789"; + Map> stores = new HashMap<>(); + AccountAwareStorageBackend clusters = AccountAwareStorageBackend.inMemory(account); + AccountAwareStorageBackend nodeGroups = AccountAwareStorageBackend.inMemory(account); + AccountAwareStorageBackend profiles = AccountAwareStorageBackend.inMemory(account); + AccountAwareStorageBackend keys = AccountAwareStorageBackend.inMemory(account); + stores.put("eks-clusters.json", clusters); + stores.put("eks-nodegroups.json", nodeGroups); + stores.put("eks-fargate-profiles.json", profiles); + stores.put("eks-oidc-keys.json", keys); + + Cluster legacy = new Cluster(); + legacy.setName("legacy"); + legacy.setArn("arn:aws:eks:eu-west-1:" + account + ":cluster/legacy"); + legacy.setStatus(ClusterStatus.ACTIVE); + legacy.setLogging(EksService.defaultLogging()); + legacy.setIdentity(new ClusterIdentity(new OidcIdentity(issuer))); + clusters.putForAccount(account, "legacy", legacy); + Nodegroup group = new Nodegroup(); + group.setNodegroupName("workers"); + group.setClusterName("legacy"); + group.setNodegroupArn("arn:aws:eks:eu-west-1:" + account + ":nodegroup/legacy/workers/id"); + group.setStatus(NodegroupStatus.ACTIVE); + nodeGroups.putForAccount(account, "legacy/workers", group); + FargateProfile profile = new FargateProfile(); + profile.setFargateProfileName("pods"); + profile.setClusterName("legacy"); + profile.setFargateProfileArn("arn:aws:eks:eu-west-1:" + account + ":fargateprofile/legacy/pods/id"); + profiles.putForAccount(account, "legacy/pods", profile); + String keyId = new EksOidcService(fixedStorageFactory(keys), new ObjectMapper()) + .ensureKeyForAccount(account, "legacy", issuer).getKeyId(); + + List services = servicesSharingStores(stores, "us-east-1", "eu-west-1"); + EksService east = services.get(0); + EksService west = services.get(1); + west.init(); + + assertSame(legacy, west.describeCluster("legacy")); + assertThrows(AwsException.class, () -> east.describeCluster("legacy")); + assertEquals(List.of("workers"), west.listNodeGroups("legacy")); + assertEquals("pods", west.describeFargateProfile("legacy", "pods").getFargateProfileName()); + assertTrue(clusters.getForAccount(account, "legacy").isEmpty()); + assertTrue(nodeGroups.getForAccount(account, "legacy/workers").isEmpty()); + assertTrue(profiles.getForAccount(account, "legacy/pods").isEmpty()); + // The signing key moves rather than being re-minted, so tokens it signed still verify. + assertTrue(keys.getForAccount(account, "legacy").isEmpty()); + assertEquals(keyId, keys.getForAccount(account, "eu-west-1::legacy").orElseThrow().getKeyId()); + // It keeps the unqualified Docker name its container and volume already have. + assertNull(legacy.getDockerNameRegion()); + + // The name is now free in every other Region, under a Docker name of its own. + assertEquals("us-east-1", east.createCluster(clusterRequest("legacy")).getDockerNameRegion()); + } + + @Test + void aRegionlessWebhookRouteResolvesTheClusterThatPredatesRegionalNames() { + String account = "000000000000"; + Map> stores = new HashMap<>(); + AccountAwareStorageBackend clusters = AccountAwareStorageBackend.inMemory(account); + stores.put("eks-clusters.json", clusters); + Cluster legacy = new Cluster(); + legacy.setName("demo"); + legacy.setArn("arn:aws:eks:eu-west-1:" + account + ":cluster/demo"); + legacy.setStatus(ClusterStatus.ACTIVE); + legacy.setLogging(EksService.defaultLogging()); + clusters.putForAccount(account, "demo", legacy); + EksService east = servicesSharingStores(stores, "us-east-1").getFirst(); + east.init(); + + Cluster newer = east.createCluster(clusterRequest("demo")); + + // The request's Region would pick the newer default-Region cluster; the route was + // registered by the pre-upgrade cluster, the only one without a Region in its Docker name. + assertSame(newer, east.findAuthenticationCluster(account, "demo").orElseThrow()); + assertSame(legacy, east.findPreRegionalCluster(account, "demo").orElseThrow()); + } + + @Test + void initMovesASigningKeyStoredBeforeAccountPrefixes() { + // Data from before multi-account storage has neither the account prefix nor the Region. + String issuer = "https://oidc.eks.eu-west-1.amazonaws.com/id/0123456789ABCDEF0123456789ABCDEF"; + StorageBackend rawClusters = new InMemoryStorage<>(); + StorageBackend rawKeys = new InMemoryStorage<>(); + Cluster legacy = new Cluster(); + legacy.setName("gen0"); + legacy.setArn("arn:aws:eks:eu-west-1:000000000000:cluster/gen0"); + legacy.setStatus(ClusterStatus.ACTIVE); + legacy.setLogging(EksService.defaultLogging()); + legacy.setIdentity(new ClusterIdentity(new OidcIdentity(issuer))); + rawClusters.put("gen0", legacy); + ClusterOidcKey key = new ClusterOidcKey(issuer, "gen0-kid", "public", "private"); + rawKeys.put("gen0", key); + + Map> stores = new HashMap<>(); + stores.put("eks-clusters.json", new AccountAwareStorageBackend<>(rawClusters, null, "000000000000")); + stores.put("eks-oidc-keys.json", new AccountAwareStorageBackend<>(rawKeys, null, "000000000000")); + EksService west = servicesSharingStores(stores, "eu-west-1").getFirst(); + west.init(); + + assertSame(legacy, west.describeCluster("gen0")); + assertTrue(rawKeys.get("gen0").isEmpty()); + assertEquals("gen0-kid", rawKeys.get("000000000000/eu-west-1::gen0").orElseThrow().getKeyId()); + } + + @Test + void aConcurrentCreateOfTheSameNameInTheSameRegionIsRefused() throws Exception { + EksOidcService oidc = mock(EksOidcService.class); + CountDownLatch building = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + when(oidc.newIssuerUrl(anyString())).thenAnswer(invocation -> { + building.countDown(); + release.await(); + return "https://oidc.eks.us-east-1.amazonaws.com/id/0123456789ABCDEF0123456789ABCDEF"; + }); + EksService service = new EksService(storageFactory, testConfig(), regionResolver, null, null, oidc, + mock(EksAccessEntryService.class), mock(EksPodIdentityAssociationService.class)); + + CompletableFuture first = CompletableFuture + .supplyAsync(() -> service.createCluster(clusterRequest("racing"))); + assertTrue(building.await(5, TimeUnit.SECONDS)); + try { + AwsException second = assertThrows(AwsException.class, () -> service.createCluster(clusterRequest("racing"))); + assertEquals("ResourceInUseException", second.getErrorCode()); + } finally { + release.countDown(); + } + + assertEquals("racing", first.get(5, TimeUnit.SECONDS).getName()); + AwsException after = assertThrows(AwsException.class, () -> service.createCluster(clusterRequest("racing"))); + assertEquals("ResourceInUseException", after.getErrorCode()); + } } diff --git a/src/test/java/io/floci/aws/services/eks/EksWorkerAuthenticationTest.java b/src/test/java/io/floci/aws/services/eks/EksWorkerAuthenticationTest.java index 6de7bfb616..2777e1aa6d 100644 --- a/src/test/java/io/floci/aws/services/eks/EksWorkerAuthenticationTest.java +++ b/src/test/java/io/floci/aws/services/eks/EksWorkerAuthenticationTest.java @@ -64,7 +64,7 @@ class EksWorkerAuthenticationTest { when(iam.findInstanceProfile(ACCOUNT, "worker-profile")).thenReturn(Optional.of(profile)); when(iam.findEksSessionIdentity(KEY)).thenReturn(Optional.of( new EksSessionIdentity(ACCOUNT, ROLE, role.getRoleId(), instance.getInstanceId()))); - when(eks.findAuthenticationCluster(ACCOUNT, "demo")).thenReturn(Optional.of(cluster)); + when(eks.findAuthenticationCluster(ACCOUNT, REGION, "demo")).thenReturn(Optional.of(cluster)); when(ec2.findInstanceForAccount(ACCOUNT, REGION, "i-worker")).thenReturn(Optional.of(instance)); createEntry("EC2_LINUX"); }