mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(eks): allow a cluster name in more than one Region of an account (#8140)
Cluster names only have to be unique within a Region of an account, but EKS stored clusters under the bare name, so creating `demo` in eu-central-1 failed with ResourceInUseException while a `demo` existed in eu-west-1. Since #7936 the eu-central-1 caller cannot even see that cluster. Clusters, node groups and Fargate profiles are now keyed by `<region>::<name>`, as OpenSearch domains and Kinesis streams are, and so are the node-capacity locks and the OIDC signing keys. On startup, records persisted under the bare name move to the new keys, taking the Region from each record's ARN. A cluster's signing key moves with it, so tokens it signed before the upgrade still verify. Access entries, add-ons and Pod Identity associations were already keyed by the cluster ARN. A cluster outside the default Region, or one that shares its name with a cluster in another Region, puts its Region first in its Docker container and volume names. This is persisted as dockerNameRegion and left out of API responses, so two Regions' clusters never share a k3s container. A default-Region cluster, and any cluster created before this change, keeps its name, so existing containers, volumes and endpoint-mode=network DNS names stay as they are. The Pod Identity webhook path now includes the Region. The old path still works for clusters whose webhook configuration predates the change. The _floci OIDC routes have no Region of their own and are usually called unsigned, so they try the request's Region and then the account's only cluster with that name. Closes #7966 Follow-up to the Regional cluster names change, from review: - k3s was given a signing key minted under the bare cluster name while EksService created, published and migrated the cluster's key under its Regional key, so pod tokens could be signed with a key JWKS did not publish. EksClusterManager now asks for the key by the Regional key, at start and on reinjection. - The token-webhook kubeconfig, audit policy, registries.yaml and Pod Identity manifest Floci writes per cluster now live under <kind>/<account>/<region>/<name>/, the layout of the signing-key files, so same-named clusters in two Regions no longer share them. - The Region-less Pod Identity webhook route resolves the cluster created before Regional names, which registered it, rather than preferring the request's Region, which could pick a newer same-named default-Region cluster. - OIDC discovery and the key route take an optional region query parameter, and the discovery document's jwks_uri names the cluster's Region, since a verifier follows it without the discovery context. - A signing key stored before account-prefixed keys now moves with its cluster too, checked by its issuer. - CreateCluster reserves the Regional key until the cluster is stored, so a concurrent create of the same name in the same Region is refused instead of overwriting the first. - Test imports replace fully qualified names, for Checkstyle. Cluster names are unique only within a Region of an account, and the token route is usually called unsigned, so with the same name in two Regions it could only mint for the request's Region. Accept the same optional ?region= as the discovery and key routes, and document it. Also correct the accountQualifiedName Javadoc, which still said names are unique only within an account.
This commit is contained in:
1 parent
0383d65acb
commit
55b2fb7bd3
22 files changed
+888
-179
No files matched your search
@@ -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));
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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<String, Object> 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<String, Object> review = webhook.review(CLUSTER_NAME, ACCOUNT_ID,
|
||||
|
||||
@@ -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<String, String> 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";
|
||||
|
||||
@@ -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<Cluster> 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<String, ClusterOidcKey>()),
|
||||
@@ -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<EksService> servicesSharingStores(Map<String, AccountAwareStorageBackend<?>> stores,
|
||||
String... regions) {
|
||||
StorageFactory shared = new StorageFactory(null, null) {
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public <V> AccountAwareStorageBackend<V> create(String serviceName, String fileName,
|
||||
TypeReference<Map<String, V>> typeReference) {
|
||||
return (AccountAwareStorageBackend<V>) stores.computeIfAbsent(fileName,
|
||||
ignored -> AccountAwareStorageBackend.inMemory("000000000000"));
|
||||
}
|
||||
};
|
||||
EksOidcService oidc = new EksOidcService(shared, new ObjectMapper());
|
||||
List<EksService> 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<EksService> 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<EksService> 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<String, AccountAwareStorageBackend<?>> stores = new HashMap<>();
|
||||
AccountAwareStorageBackend<Cluster> clusters = AccountAwareStorageBackend.inMemory(account);
|
||||
AccountAwareStorageBackend<Nodegroup> nodeGroups = AccountAwareStorageBackend.inMemory(account);
|
||||
AccountAwareStorageBackend<FargateProfile> profiles = AccountAwareStorageBackend.inMemory(account);
|
||||
AccountAwareStorageBackend<ClusterOidcKey> 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<EksService> 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<String, AccountAwareStorageBackend<?>> stores = new HashMap<>();
|
||||
AccountAwareStorageBackend<Cluster> 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<String, Cluster> rawClusters = new InMemoryStorage<>();
|
||||
StorageBackend<String, ClusterOidcKey> 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<String, AccountAwareStorageBackend<?>> 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<Cluster> 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());
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user