feat(eks): give each managed node group the Auto Scaling group it reports (#8432)

* refactor(autoscaling): register target group members next to their deregistration
* feat(autoscaling): keep the groups EKS manages for its node groups
* feat(eks): give each managed node group the Auto Scaling group it reports
* refactor(autoscaling): build groups and read a Region's groups through shared helpers
* fix(autoscaling): change an EKS group's node and target groups under the Region's lock
* fix(autoscaling): refuse moving or replacing an EKS group's node
* fix(eks): create a node group's Auto Scaling group once, and delete the others past a failure
* docs(eks): what an EKS node group's Auto Scaling group allows, and what ordinary groups register
* fix(autoscaling): keep an EKS group's target group attached when ELBv2 refuses to deregister its node
* test(eks): build the node group Auto Scaling tests' EKS requests with one EksRequests helper
* test(eks): build the access entry, add-on, Pod Identity and Region scoping tests' EKS requests with EksRequests
* test: read a target group's registered targets with one AlbFixtures.targetIds
* test(autoscaling): match a single deregistered or registered target with one onlyTarget matcher
* test(autoscaling): delete a group sharing the node through EKS and through Auto Scaling in one test
* perf(eks): read only the registering node's cluster when adding it to its node groups' Auto Scaling groups
* docs(autoscaling): say an EKS group's node is registered with an elbv2 traffic source
This commit is contained in:
mrfelek authored and GitHub committed 2026-11-15 09:06:23 -04:00
1 parent e901eb27b2
commit 74a9ea76d5
24 files changed
+1686 -272

No files matched your search

@@ -15,6 +15,7 @@ import org.junit.jupiter.params.provider.ValueSource;
import java.util.List;
import static io.floci.aws.services.autoscaling.TargetMatchers.onlyTarget;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
@@ -49,8 +50,7 @@ class AutoScalingDetachLoadBalancersTest {
verify(classic).deregisterInstances(REGION, "first", List.of("i-owned"));
verify(classic).deregisterInstances(REGION, "second", List.of("i-owned"));
verifyNoMoreInteractions(classic);
verify(targets).deregisterTargets(eq(REGION), eq("target-group"),
argThat(values -> values.size() == 1 && "i-owned".equals(values.getFirst().getId())));
verify(targets).deregisterTargets(eq(REGION), eq("target-group"), onlyTarget("i-owned"));
assertEquals(List.of(retained), group.getInstances());
assertEquals(2, group.getDesiredCapacity());
}
@@ -120,8 +120,7 @@ class AutoScalingDetachLoadBalancersTest {
service.detachInstances(REGION, "group", List.of("i-owned", "i-other-group"), false);
verify(targets).deregisterTargets(eq(REGION), eq("shared-target-group"),
argThat(values -> values.size() == 1 && "i-owned".equals(values.getFirst().getId())));
verify(targets).deregisterTargets(eq(REGION), eq("shared-target-group"), onlyTarget("i-owned"));
assertEquals(List.of(retained), group.getInstances());
}
@@ -0,0 +1,377 @@
package io.floci.aws.services.autoscaling;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.services.autoscaling.model.AsgInstance;
import io.floci.aws.services.autoscaling.model.AutoScalingGroup;
import io.floci.aws.services.autoscaling.model.InstanceRefresh;
import io.floci.aws.services.ec2.Ec2Service;
import io.floci.aws.services.ec2.model.Instance;
import io.floci.aws.services.ec2.model.Placement;
import io.floci.aws.services.ec2.model.Subnet;
import io.floci.aws.services.elbv2.ElbV2Service;
import io.floci.aws.services.elbv2.model.TargetDescription;
import io.floci.aws.testing.ThreadStates;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import static io.floci.aws.services.autoscaling.TargetMatchers.onlyTarget;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.anyList;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
/**
* The groups EKS keeps for its managed node groups. Floci runs one node per cluster, so the groups of a cluster's
* node groups all hold that node: Auto Scaling adds it, registers it with the target groups attached to each group,
* and keeps it in a target group as long as one group holding it has that target group attached.
*/
class AutoScalingEksManagedGroupTest {
private static final String REGION = "us-east-1";
private static final String FIRST = "eks-workers-1a2b3c4d";
private static final String SECOND = "eks-batch-5e6f7a8b";
private static final String NODE = "i-0123456789abcdef0";
private final ElbV2Service targets = mock(ElbV2Service.class);
private final Ec2Service ec2 = mock(Ec2Service.class);
private final AutoScalingService service = new AutoScalingService(targets, null);
AutoScalingEksManagedGroupTest() {
service.regionResolver = new RegionResolver(REGION, "000000000000");
service.ec2Service = ec2;
}
@Test
void theGroupMirrorsTheNodeGroupWithoutALaunchSourceAndIsCreatedOnce() {
Subnet subnet = new Subnet();
subnet.setSubnetId("subnet-a");
subnet.setAvailabilityZone("us-east-1a");
when(ec2.describeSubnets(REGION, List.of("subnet-a", "subnet-unknown"), null)).thenReturn(List.of(subnet));
service.createEksManagedGroup(REGION, FIRST, 1, 3, 2, List.of("subnet-a", "subnet-unknown"), tags("workers"));
AutoScalingGroup group = service.requireGroup(REGION, FIRST);
assertTrue(group.isEksManaged());
assertEquals("arn:aws:autoscaling:us-east-1:000000000000:autoScalingGroup:" + FIRST,
group.getAutoScalingGroupArn());
assertEquals(1, group.getMinSize());
assertEquals(3, group.getMaxSize());
assertEquals(2, group.getDesiredCapacity());
assertEquals(List.of("us-east-1a"), group.getAvailabilityZones());
assertEquals(List.of("subnet-a", "subnet-unknown"), group.getSubnetIds());
assertEquals(tags("workers"), group.getTags());
assertEquals(Map.of("eks:cluster-name", true, "eks:nodegroup-name", true,
"k8s.io/cluster-autoscaler/enabled", true, "k8s.io/cluster-autoscaler/shop", true),
group.getTagPropagateAtLaunch());
assertEquals(List.of("Default"), group.getTerminationPolicies());
assertNull(group.getLaunchConfigurationName());
assertNull(group.getLaunchTemplateId());
assertNull(group.getLaunchTemplateName());
assertNull(group.getMixedInstancesPolicy());
assertEquals(List.of(), group.getInstances());
// Restoring a node group creates its group again; one that exists is left as it is.
service.createEksManagedGroup(REGION, FIRST, 0, 5, 0, List.of(), Map.of());
assertSame(group, service.requireGroup(REGION, FIRST));
assertEquals(1, group.getMinSize());
assertEquals(3, group.getMaxSize());
assertEquals(2, group.getDesiredCapacity());
assertEquals(tags("workers"), group.getTags());
}
@Test
void anAddedNodeIsInServiceAndRegisteredWithTheTargetGroupsAlreadyAttached() {
service.createEksManagedGroup(REGION, FIRST, 1, 3, 2, List.of(), tags("workers"));
service.attachLoadBalancerTargetGroups(REGION, FIRST, List.of("tg-attached"));
service.attachTrafficSources(REGION, FIRST, List.of(
new AutoScalingService.TrafficSourceIdentifier("tg-source", "elbv2"),
new AutoScalingService.TrafficSourceIdentifier("lattice-service", "vpc-lattice")));
verifyNoInteractions(targets);
service.addEksManagedInstance(REGION, FIRST, node());
service.addEksManagedInstance(REGION, FIRST, node());
List<AsgInstance> members = service.requireGroup(REGION, FIRST).getInstances();
assertEquals(1, members.size());
AsgInstance member = members.getFirst();
assertEquals(NODE, member.getInstanceId());
assertEquals("InService", member.getLifecycleState());
assertEquals("Healthy", member.getHealthStatus());
assertEquals("us-east-1b", member.getAvailabilityZone());
assertEquals("m5.large", member.getInstanceType());
assertNull(member.getLaunchTemplateId());
verify(targets).registerTargets(eq(REGION), eq("tg-attached"), onlyTarget(NODE));
verify(targets).registerTargets(eq(REGION), eq("tg-source"), onlyTarget(NODE));
verifyNoMoreInteractions(targets);
}
@Test
void attachingAndDetachingTargetGroupsRegistersAndDeregistersTheNode() {
service.createEksManagedGroup(REGION, FIRST, 1, 3, 2, List.of(), tags("workers"));
service.addEksManagedInstance(REGION, FIRST, node());
service.attachLoadBalancerTargetGroups(REGION, FIRST, List.of("tg-a"));
service.attachTrafficSources(REGION, FIRST, List.of(
new AutoScalingService.TrafficSourceIdentifier("tg-b", null)));
verify(targets).registerTargets(eq(REGION), eq("tg-a"), onlyTarget(NODE));
verify(targets).registerTargets(eq(REGION), eq("tg-b"), onlyTarget(NODE));
// Attached both ways, tg-a stays attached when one of them is detached.
service.attachTrafficSources(REGION, FIRST, List.of(
new AutoScalingService.TrafficSourceIdentifier("tg-a", "elbv2")));
service.detachLoadBalancerTargetGroups(REGION, FIRST, List.of("tg-a"));
verifyNoMoreInteractions(targets);
service.detachTrafficSources(REGION, FIRST, List.of(
new AutoScalingService.TrafficSourceIdentifier("tg-a", "elbv2"),
new AutoScalingService.TrafficSourceIdentifier("tg-b", "elbv2")));
verify(targets).deregisterTargets(eq(REGION), eq("tg-a"), onlyTarget(NODE));
verify(targets).deregisterTargets(eq(REGION), eq("tg-b"), onlyTarget(NODE));
verifyNoMoreInteractions(targets);
assertEquals(List.of(NODE), memberIds(FIRST));
}
@Test
void aDetachElbV2RefusesLeavesTheTargetGroupAttachedSoTheDetachCanBeSentAgain() {
service.createEksManagedGroup(REGION, FIRST, 1, 3, 2, List.of(), tags("workers"));
service.addEksManagedInstance(REGION, FIRST, node());
service.attachLoadBalancerTargetGroups(REGION, FIRST, List.of("tg-a"));
service.attachTrafficSources(REGION, FIRST, List.of(
new AutoScalingService.TrafficSourceIdentifier("tg-b", null)));
AwsException refusal = new AwsException("InternalFailure", "ELBv2 could not deregister the target", 500);
doThrow(refusal).doNothing().when(targets).deregisterTargets(eq(REGION), eq("tg-a"), anyList());
doThrow(refusal).doNothing().when(targets).deregisterTargets(eq(REGION), eq("tg-b"), anyList());
assertThrows(AwsException.class,
() -> service.detachLoadBalancerTargetGroups(REGION, FIRST, List.of("tg-a")));
assertEquals(List.of("tg-a"), service.describeLoadBalancerTargetGroups(REGION, FIRST));
service.detachLoadBalancerTargetGroups(REGION, FIRST, List.of("tg-a"));
assertEquals(List.of(), service.describeLoadBalancerTargetGroups(REGION, FIRST));
List<AutoScalingService.TrafficSourceIdentifier> trafficSource = List.of(
new AutoScalingService.TrafficSourceIdentifier("tg-b", "elbv2"));
assertThrows(AwsException.class, () -> service.detachTrafficSources(REGION, FIRST, trafficSource));
assertEquals(Map.of("tg-b", "elbv2"), service.describeTrafficSources(REGION, FIRST, null));
service.detachTrafficSources(REGION, FIRST, trafficSource);
assertEquals(Map.of(), service.describeTrafficSources(REGION, FIRST, null));
verify(targets, times(2)).deregisterTargets(eq(REGION), eq("tg-a"), onlyTarget(NODE));
verify(targets, times(2)).deregisterTargets(eq(REGION), eq("tg-b"), onlyTarget(NODE));
}
@Test
void detachingATargetGroupLeavesTheSharedNodeInItWhileAnotherGroupHasItAttached() {
groupsSharingTheNode();
service.attachLoadBalancerTargetGroups(REGION, FIRST, List.of("tg-shared"));
service.attachTrafficSources(REGION, SECOND, List.of(
new AutoScalingService.TrafficSourceIdentifier("tg-shared", "elbv2")));
clearInvocations(targets);
service.detachLoadBalancerTargetGroups(REGION, FIRST, List.of("tg-shared"));
verifyNoInteractions(targets);
service.detachTrafficSources(REGION, SECOND, List.of(
new AutoScalingService.TrafficSourceIdentifier("tg-shared", "elbv2")));
verify(targets).deregisterTargets(eq(REGION), eq("tg-shared"), onlyTarget(NODE));
verifyNoMoreInteractions(targets);
}
@Test
void detachingTheNodeLeavesTheTargetGroupsAnotherGroupHoldingItHasAttached() {
groupsSharingTheNode();
service.attachLoadBalancerTargetGroups(REGION, FIRST, List.of("tg-first", "tg-shared"));
service.attachTrafficSources(REGION, FIRST, List.of(
new AutoScalingService.TrafficSourceIdentifier("tg-source", "elbv2")));
service.attachLoadBalancerTargetGroups(REGION, SECOND, List.of("tg-shared"));
clearInvocations(targets);
service.detachInstances(REGION, FIRST, List.of(NODE), false);
assertEquals(List.of(), memberIds(FIRST));
assertEquals(List.of(NODE), memberIds(SECOND));
verify(targets).deregisterTargets(eq(REGION), eq("tg-first"), onlyTarget(NODE));
verify(targets).deregisterTargets(eq(REGION), eq("tg-source"), onlyTarget(NODE));
verifyNoMoreInteractions(targets);
}
/**
* Each group is deleted as EKS deletes it with its node group, or through DeleteAutoScalingGroup with
* ForceDelete, which is refused without it while the group holds the node.
*/
@ParameterizedTest
@ValueSource(booleans = {false, true})
void deletingAGroupLeavesTheSharedNodeInTheTargetGroupsAnotherGroupHoldsAndTerminatesNothing(
boolean throughAutoScaling) {
groupsSharingTheNode();
service.attachLoadBalancerTargetGroups(REGION, FIRST, List.of("tg-first", "tg-shared"));
service.attachLoadBalancerTargetGroups(REGION, SECOND, List.of("tg-shared"));
clearInvocations(targets);
AwsException inUse = assertThrows(AwsException.class,
() -> service.deleteAutoScalingGroup(REGION, FIRST, false));
assertEquals("ResourceInUse", inUse.getErrorCode());
delete(FIRST, throughAutoScaling);
assertEquals(List.of(), service.describeAutoScalingGroups(REGION, List.of(FIRST)));
assertEquals(List.of(NODE), memberIds(SECOND));
verify(targets).deregisterTargets(eq(REGION), eq("tg-first"), onlyTarget(NODE));
verifyNoMoreInteractions(targets);
delete(SECOND, throughAutoScaling);
assertEquals(List.of(), service.describeAutoScalingGroups(REGION, null));
verify(targets).deregisterTargets(eq(REGION), eq("tg-shared"), onlyTarget(NODE));
verifyNoMoreInteractions(targets);
// The node is EKS's: deleting its groups terminates nothing.
verifyNoInteractions(ec2);
}
@Test
void attachingWhileAnotherGroupDetachesTheSameTargetGroupLeavesTheSharedNodeRegistered() throws Exception {
groupsSharingTheNode();
// The target group's registered targets, as ELB keeps them.
Set<String> registered = ConcurrentHashMap.newKeySet();
CountDownLatch deregistering = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
doAnswer(invocation -> {
List<TargetDescription> described = invocation.getArgument(2);
described.forEach(target -> registered.add(target.getId()));
return null;
}).when(targets).registerTargets(eq(REGION), eq("tg-shared"), anyList());
doAnswer(invocation -> {
deregistering.countDown();
assertTrue(release.await(5, TimeUnit.SECONDS), "the parked deregistration was not released");
List<TargetDescription> described = invocation.getArgument(2);
described.forEach(target -> registered.remove(target.getId()));
return null;
}).when(targets).deregisterTargets(eq(REGION), eq("tg-shared"), anyList());
service.attachLoadBalancerTargetGroups(REGION, FIRST, List.of("tg-shared"));
assertEquals(Set.of(NODE), registered);
// FIRST's detach finds no other group with tg-shared and parks deregistering the node from it.
FutureTask<Void> detach = new FutureTask<>(
() -> service.detachLoadBalancerTargetGroups(REGION, FIRST, List.of("tg-shared")), null);
FutureTask<Void> attach = new FutureTask<>(
() -> service.attachLoadBalancerTargetGroups(REGION, SECOND, List.of("tg-shared")), null);
Thread detaching = Thread.ofPlatform().daemon().start(detach);
Thread attaching = Thread.ofPlatform().daemon().unstarted(attach);
try {
assertTrue(deregistering.await(5, TimeUnit.SECONDS), "the detach did not reach the deregistration");
attaching.start();
ThreadStates.awaitBlockedOrDone(attaching);
assertEquals(Thread.State.BLOCKED, attaching.getState());
} finally {
release.countDown();
}
detach.get(5, TimeUnit.SECONDS);
attach.get(5, TimeUnit.SECONDS);
detaching.join(5000);
assertEquals(Set.of(NODE), registered);
}
@Test
void operationsThatWouldMoveOrReplaceTheNodeAreRefusedAndTheRestAreNot() {
service.createEksManagedGroup(REGION, FIRST, 1, 3, 2, List.of(), tags("workers"));
service.addEksManagedInstance(REGION, FIRST, node());
assertRefused(() -> service.terminateInstanceInAutoScalingGroup(REGION, NODE, false));
assertRefused(() -> service.enterStandby(REGION, FIRST, List.of(NODE), false));
assertRefused(() -> service.exitStandby(REGION, FIRST, List.of(NODE)));
assertRefused(() -> service.startInstanceRefresh(REGION, FIRST, new InstanceRefresh()));
assertRefused(() -> service.setInstanceHealth(REGION, NODE, "Unhealthy", false));
assertRefused(() -> service.attachInstances(REGION, FIRST, List.of("i-0fedcba9876543210")));
AutoScalingGroup group = service.requireGroup(REGION, FIRST);
AsgInstance member = group.getInstances().getFirst();
assertEquals(List.of(NODE), memberIds(FIRST));
assertEquals("InService", member.getLifecycleState());
assertEquals("Healthy", member.getHealthStatus());
assertNull(member.getStandbyActivityId());
assertEquals(2, group.getDesiredCapacity());
assertEquals(List.of(), service.describeInstanceRefreshes(REGION, FIRST, null, null, null)
.instanceRefreshes());
// Changes that leave the node where it is stay allowed.
service.setInstanceHealth(REGION, NODE, "Healthy", false);
service.setDesiredCapacity(REGION, FIRST, 3);
service.setInstanceProtection(REGION, FIRST, List.of(NODE), true);
assertEquals(3, group.getDesiredCapacity());
assertTrue(member.isProtectedFromScaleIn());
verifyNoInteractions(targets, ec2);
}
private static void assertRefused(Executable operation) {
AwsException refused = assertThrows(AwsException.class, operation);
assertEquals("ValidationError", refused.getErrorCode());
assertEquals("Auto Scaling group '" + FIRST + "' is managed by Amazon EKS for a node group. Its instance is"
+ " the cluster's node, which the cluster's node groups share.", refused.getMessage());
assertEquals(400, refused.getHttpStatus());
}
/** Deletes {@code group} as EKS does with its node group, or with DeleteAutoScalingGroup and ForceDelete. */
private void delete(String group, boolean throughAutoScaling) {
if (throughAutoScaling) {
service.deleteAutoScalingGroup(REGION, group, true);
} else {
service.deleteEksManagedGroup(REGION, group);
}
}
/** FIRST and SECOND, the groups of two node groups of one cluster, both holding its node. */
private void groupsSharingTheNode() {
service.createEksManagedGroup(REGION, FIRST, 1, 3, 2, List.of(), tags("workers"));
service.createEksManagedGroup(REGION, SECOND, 1, 1, 1, List.of(), tags("batch"));
service.addEksManagedInstance(REGION, FIRST, node());
service.addEksManagedInstance(REGION, SECOND, node());
}
private static Map<String, String> tags(String nodegroupName) {
return Map.of(
"eks:cluster-name", "shop",
"eks:nodegroup-name", nodegroupName,
"k8s.io/cluster-autoscaler/enabled", "true",
"k8s.io/cluster-autoscaler/shop", "owned");
}
private List<String> memberIds(String group) {
return service.requireGroup(REGION, group).getInstances().stream().map(AsgInstance::getInstanceId).toList();
}
private static Instance node() {
Instance node = new Instance();
node.setInstanceId(NODE);
node.setInstanceType("m5.large");
node.setPlacement(new Placement("us-east-1b"));
return node;
}
}
@@ -33,6 +33,7 @@ import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static io.floci.aws.services.autoscaling.TargetMatchers.onlyTarget;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -51,6 +52,7 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
class AutoScalingReconcilerTest {
@@ -83,7 +85,7 @@ class AutoScalingReconcilerTest {
reconciler.reconcile(asg);
assertEquals(List.of(), asg.getInstances());
verify(elbV2Service, times(2)).deregisterTargets(eq("us-east-1"), eq("owned-target-group"),
argThat(targets -> targets.size() == 1 && "i-cleanup".equals(targets.getFirst().getId())));
onlyTarget("i-cleanup"));
}
static Stream<Arguments> targetCleanupFailures() {
@@ -848,6 +850,35 @@ class AutoScalingReconcilerTest {
eq(asg.getRegion()), eq("classic-lb"), eq(List.of("i-dead")));
}
@Test
void reconcileLeavesTheCapacityOfAnEksManagedGroupToEks() {
AutoScalingService asgService = scalingService();
Ec2Service ec2Service = mock(Ec2Service.class);
ElbV2Service elbV2Service = mock(ElbV2Service.class);
AutoScalingReconciler reconciler = new AutoScalingReconciler(asgService, ec2Service, elbV2Service);
AutoScalingGroup asg = new AutoScalingGroup();
asg.setRegion("us-east-1");
asg.setAutoScalingGroupName("eks-workers-1a2b3c4d");
asg.setEksManaged(true);
asg.setMinSize(1);
asg.setMaxSize(3);
asg.setDesiredCapacity(2);
asg.setTargetGroupARNs(List.of("node-target-group"));
AsgInstance node = instance("i-0123456789abcdef0", "InService");
asg.getInstances().add(node);
// EC2 does not run the node's container, so the stale check of an ordinary group would drop it.
when(ec2Service.isInstanceContainerRunning("i-0123456789abcdef0")).thenReturn(false);
reconciler.reconcile(asg);
assertEquals(List.of(node), asg.getInstances());
assertEquals("InService", node.getLifecycleState());
assertEquals("Healthy", node.getHealthStatus());
assertEquals(2, asg.getDesiredCapacity());
verifyNoInteractions(ec2Service, elbV2Service);
verify(asgService, never()).reconcileIfPresent(any(), any());
}
@Test
void reconcilePromotesPendingAsgInstanceWhenEc2InstanceIsRunning() {
AutoScalingService asgService = scalingService();
@@ -1,5 +1,6 @@
package io.floci.aws.services.autoscaling;
import io.floci.aws.testing.AlbFixtures;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.path.xml.XmlPath;
import jakarta.inject.Inject;
@@ -22,8 +23,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
class AutoScalingStandbyIntegrationTest {
private static final String ACCOUNT = "616161616161";
private static final String AUTH =
"AWS4-HMAC-SHA256 Credential=616161616161/20261028/us-east-1/autoscaling/aws4_request";
"AWS4-HMAC-SHA256 Credential=" + ACCOUNT + "/20261028/us-east-1/autoscaling/aws4_request";
private static final String EC2_AUTH = AUTH.replace("/autoscaling/", "/ec2/");
private static final String ELB_AUTH = AUTH.replace("/autoscaling/", "/elasticloadbalancing/");
private static final String GROUP_PATH = "DescribeAutoScalingGroupsResponse.DescribeAutoScalingGroupsResult"
@@ -73,7 +75,8 @@ class AutoScalingStandbyIntegrationTest {
List<String> members = launched.getList(GROUP_PATH + ".Instances.member.InstanceId");
String standby = members.get(0);
String serving = members.get(1);
assertEquals(List.copyOf(members).stream().sorted().toList(), targets(targetGroup).stream().sorted().toList());
assertEquals(List.copyOf(members).stream().sorted().toList(),
AlbFixtures.targetIds(ACCOUNT, targetGroup).stream().sorted().toList());
// MinSize 2 leaves no room to decrement, so the client lowers it first.
XmlPath refused = given().header("Authorization", AUTH).formParam("Action", "EnterStandby")
@@ -113,7 +116,7 @@ class AutoScalingStandbyIntegrationTest {
assertEquals("1", inStandby.getString(GROUP_PATH + ".DesiredCapacity"));
assertEquals("Standby", member(inStandby, standby, "LifecycleState"));
assertEquals("InService", member(inStandby, serving, "LifecycleState"));
assertEquals(List.of(serving), targets(targetGroup));
assertEquals(List.of(serving), AlbFixtures.targetIds(ACCOUNT, targetGroup));
assertEquals(List.of(serving), classicInstances(loadBalancer));
assertEquals("Successful", activity(name, enterActivity, "StatusCode"));
assertEquals("The instance " + serving + " is not in Standby.", given().header("Authorization", AUTH)
@@ -142,7 +145,8 @@ class AutoScalingStandbyIntegrationTest {
XmlPath back = group(name);
assertEquals("2", back.getString(GROUP_PATH + ".DesiredCapacity"));
assertEquals(List.of("InService", "InService"), back.getList(GROUP_PATH + ".Instances.member.LifecycleState"));
assertEquals(List.of(serving, standby).stream().sorted().toList(), targets(targetGroup).stream().sorted().toList());
assertEquals(List.of(serving, standby).stream().sorted().toList(),
AlbFixtures.targetIds(ACCOUNT, targetGroup).stream().sorted().toList());
assertEquals(List.of(serving, standby).stream().sorted().toList(),
classicInstances(loadBalancer).stream().sorted().toList());
assertEquals("Successful", activity(name, exitActivity, "StatusCode"));
@@ -186,14 +190,6 @@ class AutoScalingStandbyIntegrationTest {
+ field);
}
private static List<String> targets(String targetGroup) {
return given().header("Authorization", ELB_AUTH).formParam("Action", "DescribeTargetHealth")
.formParam("Version", "2015-12-01").formParam("TargetGroupArn", targetGroup)
.post("/").then().statusCode(200).extract().xmlPath()
.getList("DescribeTargetHealthResponse.DescribeTargetHealthResult.TargetHealthDescriptions"
+ ".member.Target.Id", String.class);
}
private static List<String> classicInstances(String loadBalancer) {
return given().header("Authorization", ELB_AUTH).formParam("Action", "DescribeLoadBalancers")
.formParam("Version", "2012-06-01").formParam("LoadBalancerNames.member.1", loadBalancer)
@@ -783,7 +783,9 @@ class AutoScalingStandbyTest {
doThrow(failure).doNothing().when(elbV2).registerTargets(eq(REGION), eq(TARGET_GROUP), anyList());
}
List<LogRecord> records = LogCapture.capture(AutoScalingReconciler.class,
// Target groups are registered through AutoScalingService.registerWithTargetGroups, which logs there.
List<LogRecord> records = LogCapture.capture(
classicFailure ? AutoScalingReconciler.class : AutoScalingService.class,
() -> reconciler.reconcile(group()));
List<LogRecord> warnings = records.stream()
@@ -0,0 +1,18 @@
package io.floci.aws.services.autoscaling;
import io.floci.aws.services.elbv2.model.TargetDescription;
import java.util.List;
import static org.mockito.ArgumentMatchers.argThat;
/** Mockito matchers for the targets Auto Scaling registers with and deregisters from a target group. */
final class TargetMatchers {
private TargetMatchers() {}
/** Matches a target list holding {@code instanceId} and nothing else. */
static List<TargetDescription> onlyTarget(String instanceId) {
return argThat(targets -> targets.size() == 1 && instanceId.equals(targets.getFirst().getId()));
}
}
@@ -11,12 +11,17 @@ import java.util.List;
import java.util.Map;
import java.util.UUID;
import static io.floci.aws.testing.EksRequests.eks;
import static io.floci.aws.testing.EnforcementFixtures.auth;
import static io.floci.aws.testing.IamTestPolicies.EMPTY_POLICY_DOCUMENT;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
@QuarkusTest
class EksAccessEntryIntegrationTest {
private static final String REGION = "us-east-1";
@Test
void nodeEntryRoundTripUsesJsonAndEncodedPrincipalPaths() {
String account = "135791357913";
@@ -32,35 +37,35 @@ class EksAccessEntryIntegrationTest {
try {
Map<String, Object> request = Map.of("principalArn", principal, "type", "EC2_LINUX",
"tags", Map.of("team", "platform"), "clientRequestToken", "retry-token");
String arn = given().header("Authorization", auth(account, "eks")).contentType("application/json")
String arn = eks(account, REGION)
.body(request).post(path).then().statusCode(200)
.body("accessEntry.username", equalTo("system:node:{{EC2PrivateDNSName}}"))
.body("accessEntry.createdAt", instanceOf(Number.class))
.body("accessEntry.tags.team", equalTo("platform"))
.body("accessEntry.principalId", nullValue())
.extract().path("accessEntry.accessEntryArn");
given().header("Authorization", auth(account, "eks")).contentType("application/json")
eks(account, REGION)
.body(request).post(path).then().statusCode(200)
.body("accessEntry.accessEntryArn", equalTo(arn));
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
eks(account, REGION).urlEncodingEnabled(false)
.get(entryPath).then().statusCode(200).contentType(containsString("application/json"))
.body("accessEntry.principalArn", equalTo(principal));
given().header("Authorization", auth(account, "eks")).get(path).then().statusCode(200)
eks(account, REGION).get(path).then().statusCode(200)
.body("accessEntries", contains(principal)).body("nextToken", nullValue());
given().header("Authorization", auth("246802468024", "eks")).get(path).then().statusCode(404);
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
eks("246802468024", REGION).get(path).then().statusCode(404);
eks(account, REGION).urlEncodingEnabled(false)
.delete(entryPath).then().statusCode(200).body(equalTo("{}"));
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
eks(account, REGION).urlEncodingEnabled(false)
.get(entryPath).then().statusCode(404).body("__type", equalTo("ResourceNotFoundException"));
given().header("Authorization", auth(account, "eks")).contentType("application/json")
eks(account, REGION)
.body(request).post(path).then().statusCode(200);
given().header("Authorization", auth(account, "eks")).delete("/clusters/" + name)
eks(account, REGION).delete("/clusters/" + name)
.then().statusCode(200);
createCluster(account, name, "API");
given().header("Authorization", auth(account, "eks")).get(path).then().statusCode(200)
eks(account, REGION).get(path).then().statusCode(200)
.body("accessEntries", empty());
} finally {
given().header("Authorization", auth(account, "eks")).delete("/clusters/" + name)
eks(account, REGION).delete("/clusters/" + name)
.then().statusCode(200);
given().header("Authorization", auth(account, "iam")).contentType("application/x-www-form-urlencoded")
.formParam("Action", "DeleteRole").formParam("RoleName", role).post("/").then().statusCode(200);
@@ -81,10 +86,10 @@ class EksAccessEntryIntegrationTest {
.formParam("AssumeRolePolicyDocument", EMPTY_POLICY_DOCUMENT).post("/").then().statusCode(200);
createCluster(account, name, "API");
try {
given().header("Authorization", auth(account, "eks")).contentType("application/json")
eks(account, REGION)
.body(Map.of("principalArn", principal)).post("/clusters/" + name + "/access-entries")
.then().statusCode(200);
given().header("Authorization", auth(account, "eks")).contentType("application/json")
eks(account, REGION)
.urlEncodingEnabled(false)
.body(Map.of("policyArn", policy, "accessScope", Map.of("type", "cluster")))
.post(policiesPath).then().statusCode(200).contentType(containsString("application/json"))
@@ -95,44 +100,44 @@ class EksAccessEntryIntegrationTest {
.body("associatedAccessPolicy.associatedAt", instanceOf(Number.class))
.body("associatedAccessPolicy.modifiedAt", instanceOf(Number.class));
String view = "arn:aws:eks::aws:cluster-access-policy/AmazonEKSViewPolicy";
given().header("Authorization", auth(account, "eks")).contentType("application/json")
eks(account, REGION)
.urlEncodingEnabled(false)
.body(Map.of("policyArn", view, "accessScope",
Map.of("type", "namespace", "namespaces", List.of("dev-*", "payments"))))
.post(policiesPath).then().statusCode(200)
.body("associatedAccessPolicy.accessScope.type", equalTo("namespace"))
.body("associatedAccessPolicy.accessScope.namespaces", contains("dev-*", "payments"));
given().header("Authorization", auth(account, "eks")).queryParam("associatedPolicyArn", view)
eks(account, REGION).queryParam("associatedPolicyArn", view)
.get("/clusters/" + name + "/access-entries").then().statusCode(200)
.body("accessEntries", contains(principal));
given().header("Authorization", auth(account, "eks"))
eks(account, REGION)
.queryParam("associatedPolicyArn", "arn:aws:eks::aws:cluster-access-policy/AmazonEKSEditPolicy")
.get("/clusters/" + name + "/access-entries").then().statusCode(200)
.body("accessEntries", empty());
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
eks(account, REGION).urlEncodingEnabled(false)
.get(policiesPath).then().statusCode(200)
.body("clusterName", equalTo(name)).body("principalArn", equalTo(principal))
.body("associatedAccessPolicies.policyArn", contains(policy, view))
.body("associatedAccessPolicies[1].accessScope.namespaces", contains("dev-*", "payments"))
.body("nextToken", nullValue());
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
eks(account, REGION).urlEncodingEnabled(false)
.get(entryPath).then().statusCode(200).body("accessEntry.principalArn", equalTo(principal));
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
eks(account, REGION).urlEncodingEnabled(false)
.delete(policiesPath + "/" + URLEncoder.encode(policy, StandardCharsets.UTF_8))
.then().statusCode(200).body(equalTo("{}"));
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
eks(account, REGION).urlEncodingEnabled(false)
.delete(policiesPath + "/" + URLEncoder.encode(policy, StandardCharsets.UTF_8))
.then().statusCode(200).body(equalTo("{}"));
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
eks(account, REGION).urlEncodingEnabled(false)
.get(policiesPath).then().statusCode(200).body("associatedAccessPolicies.policyArn", contains(view));
given().header("Authorization", auth(account, "eks")).contentType("application/json")
eks(account, REGION)
.urlEncodingEnabled(false)
.body(Map.of("policyArn", policy, "accessScope", Map.of("type", "namespace")))
.post(policiesPath).then().statusCode(400).body("__type", equalTo("InvalidParameterException"));
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
eks(account, REGION).urlEncodingEnabled(false)
.delete(entryPath).then().statusCode(200);
} finally {
given().header("Authorization", auth(account, "eks")).delete("/clusters/" + name)
eks(account, REGION).delete("/clusters/" + name)
.then().statusCode(200);
given().header("Authorization", auth(account, "iam")).contentType("application/x-www-form-urlencoded")
.formParam("Action", "DeleteRole").formParam("RoleName", role).post("/").then().statusCode(200);
@@ -146,13 +151,13 @@ class EksAccessEntryIntegrationTest {
String name = "pagination-" + UUID.randomUUID().toString().substring(0, 8);
createCluster(account, name, "API");
try {
given().header("Authorization", auth(account, "eks")).queryParam("maxResults", maxResults)
eks(account, REGION).queryParam("maxResults", maxResults)
.get("/clusters/" + name + "/access-entries").then().statusCode(400)
.contentType(containsString("application/json"))
.body("__type", equalTo("InvalidParameterException"))
.body("message", not(emptyOrNullString()));
} finally {
given().header("Authorization", auth(account, "eks")).delete("/clusters/" + name)
eks(account, REGION).delete("/clusters/" + name)
.then().statusCode(200);
}
}
@@ -163,14 +168,14 @@ class EksAccessEntryIntegrationTest {
String account = "135791357913";
createCluster(account, name, "CONFIG_MAP");
try {
given().header("Authorization", auth(account, "eks"))
eks(account, REGION)
.get("/clusters/" + name + "/access-entries").then().statusCode(400)
.body("__type", equalTo("InvalidRequestException"));
given().header("Authorization", auth(account, "eks")).contentType("application/json")
eks(account, REGION)
.body(Map.of("name", name + "-invalid", "accessConfig", Map.of("authenticationMode", "invalid")))
.post("/clusters").then().statusCode(400).body("__type", equalTo("InvalidParameterException"));
} finally {
given().header("Authorization", auth(account, "eks")).delete("/clusters/" + name)
eks(account, REGION).delete("/clusters/" + name)
.then().statusCode(200);
}
}
@@ -191,28 +196,28 @@ class EksAccessEntryIntegrationTest {
try {
for (String principal : List.of(midPath, named)) {
String entryPath = path + "/" + URLEncoder.encode(principal, StandardCharsets.UTF_8);
given().header("Authorization", auth(account, "eks")).contentType("application/json")
eks(account, REGION)
.body(Map.of("principalArn", principal)).post(path).then().statusCode(200);
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
eks(account, REGION).urlEncodingEnabled(false)
.get(entryPath).then().statusCode(200).body("accessEntry.principalArn", equalTo(principal));
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
eks(account, REGION).urlEncodingEnabled(false)
.get(entryPath + "/access-policies").then().statusCode(200)
.body("principalArn", equalTo(principal)).body("associatedAccessPolicies", empty());
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
eks(account, REGION).urlEncodingEnabled(false)
.delete(entryPath).then().statusCode(200).body(equalTo("{}"));
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
eks(account, REGION).urlEncodingEnabled(false)
.get(entryPath).then().statusCode(404).body("__type", equalTo("ResourceNotFoundException"));
}
// Unencoded, the slashes are the router's: a DELETE is a disassociate only when what follows
// access-policies is a cluster access policy ARN, so this one still deletes the entry.
given().header("Authorization", auth(account, "eks")).contentType("application/json")
eks(account, REGION)
.body(Map.of("principalArn", midPath)).post(path).then().statusCode(200);
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
eks(account, REGION).urlEncodingEnabled(false)
.delete(path + "/" + midPath).then().statusCode(200).body(equalTo("{}"));
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
eks(account, REGION).urlEncodingEnabled(false)
.get(path + "/" + URLEncoder.encode(midPath, StandardCharsets.UTF_8)).then().statusCode(404);
} finally {
given().header("Authorization", auth(account, "eks")).delete("/clusters/" + name).then().statusCode(200);
eks(account, REGION).delete("/clusters/" + name).then().statusCode(200);
deleteRole(account, runner);
deleteRole(account, "access-policies");
}
@@ -230,16 +235,11 @@ class EksAccessEntryIntegrationTest {
}
private static void createCluster(String account, String name, String mode) {
given().header("Authorization", auth(account, "eks")).contentType("application/json")
eks(account, REGION)
.body(Map.of("name", name, "roleArn", "arn:aws:iam::" + account + ":role/cluster",
"accessConfig", Map.of("authenticationMode", mode, "bootstrapClusterCreatorAdminPermissions", false)))
.post("/clusters").then().statusCode(200)
.body("cluster.accessConfig.authenticationMode", equalTo(mode))
.body("cluster.accessConfig.bootstrapClusterCreatorAdminPermissions", equalTo(false));
}
private static String auth(String account, String service) {
return "AWS4-HMAC-SHA256 Credential=" + account
+ "/20260916/us-east-1/" + service + "/aws4_request, SignedHeaders=host, Signature=abc";
}
}
@@ -7,6 +7,8 @@ import java.util.List;
import java.util.Map;
import java.util.UUID;
import static io.floci.aws.testing.EksRequests.eks;
import static io.floci.aws.testing.EnforcementFixtures.auth;
import static io.floci.aws.testing.IamTestPolicies.EMPTY_POLICY_DOCUMENT;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
@@ -14,6 +16,8 @@ import static org.hamcrest.Matchers.*;
@QuarkusTest
class EksAddonIntegrationTest {
private static final String REGION = "us-east-1";
@Test
void addonLifecycleRoundTrip() {
String account = "123456789012";
@@ -36,8 +40,7 @@ class EksAddonIntegrationTest {
"tags", Map.of("environment", "test")
);
given().header("Authorization", auth(account, "eks"))
.contentType("application/json")
eks(account, REGION)
.body(createReq)
.post(basePath)
.then()
@@ -59,8 +62,7 @@ class EksAddonIntegrationTest {
.body("addon.modifiedAt", instanceOf(Number.class));
// 2. Idempotent retry with same parameters and token
given().header("Authorization", auth(account, "eks"))
.contentType("application/json")
eks(account, REGION)
.body(createReq)
.post(basePath)
.then()
@@ -74,8 +76,7 @@ class EksAddonIntegrationTest {
"clientRequestToken", "token-addon-1",
"tags", Map.of("environment", "production")
);
given().header("Authorization", auth(account, "eks"))
.contentType("application/json")
eks(account, REGION)
.body(conflictReq)
.post(basePath)
.then()
@@ -88,8 +89,7 @@ class EksAddonIntegrationTest {
"addonName", "vpc-cni",
"clientRequestToken", "token-addon-2"
);
given().header("Authorization", auth(account, "eks"))
.contentType("application/json")
eks(account, REGION)
.body(duplicateReq)
.post(basePath)
.then()
@@ -98,7 +98,7 @@ class EksAddonIntegrationTest {
.body("__type", equalTo("ResourceInUseException"));
// 5. Describe addon
given().header("Authorization", auth(account, "eks"))
eks(account, REGION)
.get(basePath + "/vpc-cni")
.then()
.statusCode(200)
@@ -117,8 +117,7 @@ class EksAddonIntegrationTest {
"serviceAccountRoleArn", updatedRoleArn,
"configurationValues", "{\"env\":{\"ENABLE_PREFIX_DELEGATION\":\"false\"}}"
);
String updateId = given().header("Authorization", auth(account, "eks"))
.contentType("application/json")
String updateId = eks(account, REGION)
.body(updateReq)
.post(basePath + "/vpc-cni/update")
.then()
@@ -130,7 +129,7 @@ class EksAddonIntegrationTest {
.extract().path("update.id");
// Verify DescribeUpdate (called by Terraform aws_eks_addon waiter)
given().header("Authorization", auth(account, "eks"))
eks(account, REGION)
.queryParam("addonName", "vpc-cni")
.get("/clusters/" + name + "/updates/" + updateId)
.then()
@@ -141,7 +140,7 @@ class EksAddonIntegrationTest {
.body("update.type", equalTo("AddonUpdate"));
// Verify describe shows updated values
given().header("Authorization", auth(account, "eks"))
eks(account, REGION)
.get(basePath + "/vpc-cni")
.then()
.statusCode(200)
@@ -150,7 +149,7 @@ class EksAddonIntegrationTest {
.body("addon.configurationValues", equalTo("{\"env\":{\"ENABLE_PREFIX_DELEGATION\":\"false\"}}"));
// 7. List addons
given().header("Authorization", auth(account, "eks"))
eks(account, REGION)
.get(basePath)
.then()
.statusCode(200)
@@ -159,7 +158,7 @@ class EksAddonIntegrationTest {
.body("addons[0]", equalTo("vpc-cni"));
// 8. Delete addon
given().header("Authorization", auth(account, "eks"))
eks(account, REGION)
.delete(basePath + "/vpc-cni")
.then()
.statusCode(200)
@@ -168,7 +167,7 @@ class EksAddonIntegrationTest {
.body("addon.status", equalTo("DELETING"));
// 9. Describe after delete returns 404
given().header("Authorization", auth(account, "eks"))
eks(account, REGION)
.get(basePath + "/vpc-cni")
.then()
.statusCode(404)
@@ -183,7 +182,7 @@ class EksAddonIntegrationTest {
String account = "123456789012";
// Query all supported versions
given().header("Authorization", auth(account, "eks"))
eks(account, REGION)
.get("/addons/supported-versions")
.then()
.statusCode(200)
@@ -192,7 +191,7 @@ class EksAddonIntegrationTest {
.body("addons.addonName", hasItems("vpc-cni", "coredns", "kube-proxy", "eks-pod-identity-agent", "aws-ebs-csi-driver"));
// Query with addonName filter
given().header("Authorization", auth(account, "eks"))
eks(account, REGION)
.queryParam("addonName", "vpc-cni")
.get("/addons/supported-versions")
.then()
@@ -202,7 +201,7 @@ class EksAddonIntegrationTest {
.body("addons[0].addonVersions", not(empty()));
// Query with kubernetesVersion filter
given().header("Authorization", auth(account, "eks"))
eks(account, REGION)
.queryParam("addonName", "vpc-cni")
.queryParam("kubernetesVersion", "1.29")
.get("/addons/supported-versions")
@@ -213,7 +212,7 @@ class EksAddonIntegrationTest {
.body("addons[0].addonVersions.addonVersion", hasItem("v1.18.1-eksbuild.1"));
// Unknown addon name returns empty list 200
given().header("Authorization", auth(account, "eks"))
eks(account, REGION)
.queryParam("addonName", "non-existent-addon")
.get("/addons/supported-versions")
.then()
@@ -241,8 +240,7 @@ class EksAddonIntegrationTest {
)
);
given().header("Authorization", auth(account, "eks"))
.contentType("application/json")
eks(account, REGION)
.body(createReq)
.post(basePath)
.then()
@@ -250,7 +248,7 @@ class EksAddonIntegrationTest {
.body("addon.podIdentityAssociations", hasSize(1));
// Verify the association was created under kube-system namespace
given().header("Authorization", auth(account, "eks"))
eks(account, REGION)
.get("/clusters/" + name + "/pod-identity-associations")
.then()
.statusCode(200)
@@ -259,20 +257,19 @@ class EksAddonIntegrationTest {
.body("associations[0].serviceAccount", equalTo("aws-node"));
// Delete addon with preserve=false (default) -> deletes association
given().header("Authorization", auth(account, "eks"))
eks(account, REGION)
.delete(basePath + "/vpc-cni")
.then()
.statusCode(200);
given().header("Authorization", auth(account, "eks"))
eks(account, REGION)
.get("/clusters/" + name + "/pod-identity-associations")
.then()
.statusCode(200)
.body("associations", empty());
// Re-creating addon with same association succeeds (no ResourceInUseException)
given().header("Authorization", auth(account, "eks"))
.contentType("application/json")
eks(account, REGION)
.body(createReq)
.post(basePath)
.then()
@@ -293,8 +290,7 @@ class EksAddonIntegrationTest {
createCluster(account, name, "1.40");
try {
// Create with no version resolves default version on cluster outside catalog range
given().header("Authorization", auth(account, "eks"))
.contentType("application/json")
eks(account, REGION)
.body(Map.of("addonName", "vpc-cni"))
.post(basePath)
.then()
@@ -304,8 +300,7 @@ class EksAddonIntegrationTest {
.body("addon.addonVersion", notNullValue());
// In-place update with catalog version succeeds
given().header("Authorization", auth(account, "eks"))
.contentType("application/json")
eks(account, REGION)
.body(Map.of("addonVersion", "v1.18.1-eksbuild.1"))
.post(basePath + "/vpc-cni/update")
.then()
@@ -313,8 +308,7 @@ class EksAddonIntegrationTest {
.body("update.status", equalTo("Successful"));
// In-place update with unknown version fails
given().header("Authorization", auth(account, "eks"))
.contentType("application/json")
eks(account, REGION)
.body(Map.of("addonVersion", "v99.0.0"))
.post(basePath + "/vpc-cni/update")
.then()
@@ -333,8 +327,7 @@ class EksAddonIntegrationTest {
createCluster(account, name, "1.29");
given().header("Authorization", auth(account, "eks"))
.contentType("application/json")
eks(account, REGION)
.body(Map.of("addonName", "vpc-cni"))
.post(basePath)
.then()
@@ -347,7 +340,7 @@ class EksAddonIntegrationTest {
createCluster(account, name, "1.29");
try {
// Addons must be empty on recreated cluster
given().header("Authorization", auth(account, "eks"))
eks(account, REGION)
.get(basePath)
.then()
.statusCode(200)
@@ -362,7 +355,7 @@ class EksAddonIntegrationTest {
String account = "123456789012";
// Missing cluster returns 404 JSON, not S3 NoSuchBucket XML
given().header("Authorization", auth(account, "eks"))
eks(account, REGION)
.get("/clusters/nonexistent-cluster/addons")
.then()
.statusCode(404)
@@ -373,8 +366,7 @@ class EksAddonIntegrationTest {
String name = "addon-err-" + UUID.randomUUID().toString().substring(0, 8);
createCluster(account, name, "1.29");
try {
given().header("Authorization", auth(account, "eks"))
.contentType("application/json")
eks(account, REGION)
.body(Map.of("addonName", "unknown-addon"))
.post("/clusters/" + name + "/addons")
.then()
@@ -404,8 +396,7 @@ class EksAddonIntegrationTest {
"serviceAccountRoleArn", roleArn
);
given().header("Authorization", auth(account, "eks"))
.contentType("application/json")
eks(account, REGION)
.body(createReq)
.post(basePath)
.then()
@@ -420,7 +411,7 @@ class EksAddonIntegrationTest {
.body("addon.serviceAccountRoleArn", equalTo(roleArn));
// 2. Describe addon returns it
given().header("Authorization", auth(account, "eks"))
eks(account, REGION)
.get(basePath + "/aws-ebs-csi-driver")
.then()
.statusCode(200)
@@ -430,7 +421,7 @@ class EksAddonIntegrationTest {
.body("addon.status", equalTo("ACTIVE"));
// 3. Filter describe-addon-versions by addonName
given().header("Authorization", auth(account, "eks"))
eks(account, REGION)
.queryParam("addonName", "aws-ebs-csi-driver")
.get("/addons/supported-versions")
.then()
@@ -442,7 +433,7 @@ class EksAddonIntegrationTest {
.body("addons[0].publisher", equalTo("eks"));
// 4. Filter describe-addon-versions by addonName and kubernetesVersion
given().header("Authorization", auth(account, "eks"))
eks(account, REGION)
.queryParam("addonName", "aws-ebs-csi-driver")
.queryParam("kubernetesVersion", "1.32")
.get("/addons/supported-versions")
@@ -457,11 +448,6 @@ class EksAddonIntegrationTest {
}
}
private static String auth(String account, String service) {
return "AWS4-HMAC-SHA256 Credential=" + account
+ "/20260920/us-east-1/" + service + "/aws4_request, SignedHeaders=host, Signature=fake";
}
private static void createRole(String account, String roleName) {
given().header("Authorization", auth(account, "iam"))
.contentType("application/x-www-form-urlencoded")
@@ -494,8 +480,7 @@ class EksAddonIntegrationTest {
"bootstrapClusterCreatorAdminPermissions", false
)
);
given().header("Authorization", auth(account, "eks"))
.contentType("application/json")
eks(account, REGION)
.body(req)
.post("/clusters")
.then()
@@ -503,7 +488,7 @@ class EksAddonIntegrationTest {
}
private static void deleteCluster(String account, String name) {
given().header("Authorization", auth(account, "eks"))
eks(account, REGION)
.delete("/clusters/" + name);
}
}
@@ -0,0 +1,127 @@
package io.floci.aws.services.eks;
import io.floci.aws.services.eks.model.Cluster;
import io.floci.aws.testing.AlbFixtures;
import io.floci.aws.testing.QueryRequests;
import io.floci.aws.testing.TestAccounts;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.path.xml.XmlPath;
import io.restassured.specification.RequestSpecification;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static io.floci.aws.testing.EksRequests.eks;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* A managed node group's Auto Scaling group, the one {@code DescribeNodegroup} names in
* {@code resources.autoScalingGroups}, exists in Auto Scaling with the cluster's node in it. Attaching it to a target
* group, as Terraform's {@code aws_autoscaling_attachment} does, registers the node there, and deleting the node
* group deletes the group and deregisters the node.
*/
@QuarkusTest
class EksNodegroupAutoScalingGroupIntegrationTest {
private static final String REGION = "us-east-1";
private static final String SUBNET = "subnet-0123456789abcdef0";
private static final String GROUP =
"DescribeAutoScalingGroupsResponse.DescribeAutoScalingGroupsResult.AutoScalingGroups.member";
@Inject
EksService eksService;
@Inject
EksClusterManager clusterManager;
private final String account = TestAccounts.randomId();
@Test
void attachingTheNodeGroupsAutoScalingGroupToATargetGroupRegistersTheClusterNode() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String clusterName = "ng-asg-" + suffix;
Cluster cluster = null;
String targetGroupArn = null;
try {
eks(account, REGION).body(Map.of("name", clusterName, "roleArn", "arn:aws:iam::" + account + ":role/cluster"))
.post("/clusters").then().statusCode(200);
cluster = eksService.findAuthenticationCluster(account, REGION, clusterName).orElseThrow();
// EKS runs in mock mode here, so the node is registered as the k3s container's start registers it.
clusterManager.registerClusterNodeInstance(cluster, "mock-container-id");
String nodeId = clusterManager.getRegisteredClusterNodeInstance(cluster).getInstanceId();
String groupName = eks(account, REGION).body(Map.of(
"nodegroupName", "workers",
"nodeRole", "arn:aws:iam::" + account + ":role/node",
"subnets", List.of(SUBNET),
"scalingConfig", Map.of("minSize", 1, "maxSize", 3, "desiredSize", 2)))
.post("/clusters/" + clusterName + "/node-groups").then().statusCode(200)
// Floci's record that it created the group is not part of the node group AWS describes.
.body("nodegroup", not(hasKey("autoScalingGroupCreated")))
.extract().path("nodegroup.resources.autoScalingGroups[0].name");
eks(account, REGION).get("/clusters/" + clusterName + "/node-groups/workers").then().statusCode(200)
.body("nodegroup", not(hasKey("autoScalingGroupCreated")));
XmlPath described = describeGroup(groupName);
assertEquals(List.of(groupName), described.getList(GROUP + ".AutoScalingGroupName", String.class));
assertEquals("1", described.getString(GROUP + ".MinSize"));
assertEquals("3", described.getString(GROUP + ".MaxSize"));
assertEquals("2", described.getString(GROUP + ".DesiredCapacity"));
assertEquals(SUBNET, described.getString(GROUP + ".VPCZoneIdentifier"));
assertEquals(List.of(nodeId), described.getList(GROUP + ".Instances.member.InstanceId", String.class));
assertEquals("InService", described.getString(GROUP + ".Instances.member.LifecycleState"));
assertEquals("Healthy", described.getString(GROUP + ".Instances.member.HealthStatus"));
assertEquals(Map.of(
"eks:cluster-name", clusterName,
"eks:nodegroup-name", "workers",
"k8s.io/cluster-autoscaler/enabled", "true",
"k8s.io/cluster-autoscaler/" + clusterName, "owned"), tags(described));
targetGroupArn = AlbFixtures.createTargetGroup(account, clusterName, "instance", 80);
query("autoscaling", "AttachLoadBalancerTargetGroups",
"AutoScalingGroupName", groupName, "TargetGroupARNs.member.1", targetGroupArn)
.post("/").then().statusCode(200);
assertEquals(List.of(nodeId), AlbFixtures.targetIds(account, targetGroupArn));
eks(account, REGION).delete("/clusters/" + clusterName + "/node-groups/workers").then().statusCode(200);
assertEquals(List.of(), describeGroup(groupName).getList(GROUP + ".AutoScalingGroupName", String.class));
assertEquals(List.of(), AlbFixtures.targetIds(account, targetGroupArn));
} finally {
eks(account, REGION).delete("/clusters/" + clusterName + "/node-groups/workers");
eks(account, REGION).delete("/clusters/" + clusterName);
AlbFixtures.deleteTargetGroup(account, targetGroupArn);
if (cluster != null) {
clusterManager.unregisterMetadataEndpoint(cluster);
}
}
}
private RequestSpecification query(String service, String action, String... params) {
return QueryRequests.request(account, REGION, service, action, params);
}
private XmlPath describeGroup(String groupName) {
return query("autoscaling", "DescribeAutoScalingGroups", "AutoScalingGroupNames.member.1", groupName)
.post("/").then().statusCode(200).extract().xmlPath();
}
private static Map<String, String> tags(XmlPath described) {
List<String> keys = described.getList(GROUP + ".Tags.member.Key", String.class);
List<String> values = described.getList(GROUP + ".Tags.member.Value", String.class);
assertEquals(List.of("true", "true", "true", "true"),
described.getList(GROUP + ".Tags.member.PropagateAtLaunch", String.class));
Map<String, String> tags = new HashMap<>();
for (int i = 0; i < keys.size(); i++) {
tags.put(keys.get(i), values.get(i));
}
return tags;
}
}
@@ -0,0 +1,127 @@
package io.floci.aws.services.eks;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.services.autoscaling.AutoScalingService;
import io.floci.aws.services.eks.model.Cluster;
import io.floci.aws.testing.TestAccounts;
import io.quarkus.test.InjectMock;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArrayList;
import static io.floci.aws.testing.EksRequests.eks;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.doAnswer;
/**
* EKS changes a node group's Auto Scaling group in the node group's account and Region, also outside a request:
* when the cluster's node registers, when the startup backfill creates the group, and when a cluster is deleted
* from Floci's own code. Auto Scaling reads the account and Region from the request scope, so each call is
* recorded with the ones it was made in.
*/
@QuarkusTest
class EksNodegroupAutoScalingGroupScopeIntegrationTest {
private static final String REGION = "eu-west-1";
@InjectMock
AutoScalingService autoScaling;
@Inject
EksService eksService;
@Inject
EksClusterManager clusterManager;
@Inject
RegionResolver regionResolver;
/** An Auto Scaling call EKS made, with the account and Region it was made in. */
private record Call(String operation, String groupName, String accountId, String region) {}
@Test
void everyCallToANodeGroupsAutoScalingGroupIsInTheNodeGroupsAccountAndRegion() {
String account = TestAccounts.randomId();
String clusterName = "ng-asg-scope-" + UUID.randomUUID().toString().substring(0, 8);
List<Call> calls = new CopyOnWriteArrayList<>();
doAnswer(invocation -> record(calls, "create", invocation.getArgument(1)))
.when(autoScaling).createEksManagedGroup(any(), any(), anyInt(), anyInt(), anyInt(), any(), any());
doAnswer(invocation -> record(calls, "add", invocation.getArgument(1)))
.when(autoScaling).addEksManagedInstance(any(), any(), any());
doAnswer(invocation -> record(calls, "delete", invocation.getArgument(1)))
.when(autoScaling).deleteEksManagedGroup(any(), any());
Cluster cluster = null;
try {
eks(account, REGION).body(Map.of("name", clusterName, "roleArn", "arn:aws:iam::" + account + ":role/cluster"))
.post("/clusters").then().statusCode(200);
cluster = eksService.findAuthenticationCluster(account, REGION, clusterName).orElseThrow();
String first = createNodeGroup(account, clusterName, "first");
String second = createNodeGroup(account, clusterName, "second");
Set<String> groups = Set.of(first, second);
assertEquals(List.of(new Call("create", first, account, REGION), new Call("create", second, account, REGION)),
callsTo(calls, groups));
// The node registers outside any request, as it does when its container starts in the background.
calls.clear();
clusterManager.registerClusterNodeInstance(cluster, "mock-container-id");
assertEquals(Set.of(new Call("add", first, account, REGION), new Call("add", second, account, REGION)),
Set.copyOf(callsTo(calls, groups)));
// The startup backfill runs outside any request too, for a node group stored without its group.
calls.clear();
RequestScopes.callAs(account, REGION, () -> eksService.describeNodeGroup(clusterName, "first"))
.setAutoScalingGroupCreated(false);
eksService.restoreNodeGroupAutoScalingGroups();
assertEquals(List.of(new Call("create", first, account, REGION), new Call("add", first, account, REGION)),
callsTo(calls, groups));
assertTrue(RequestScopes.callAs(account, REGION,
() -> eksService.describeNodeGroup(clusterName, "first")).isAutoScalingGroupCreated());
// Floci's own code deletes a cluster outside any request.
calls.clear();
eksService.deleteClusterForAccount(account, clusterName);
assertEquals(Set.of(new Call("delete", first, account, REGION), new Call("delete", second, account, REGION)),
Set.copyOf(callsTo(calls, groups)));
} finally {
if (eksService.findAuthenticationCluster(account, REGION, clusterName).isPresent()) {
eksService.deleteClusterForAccount(account, clusterName);
}
if (cluster != null) {
clusterManager.unregisterMetadataEndpoint(cluster);
}
}
}
private Object record(List<Call> calls, String operation, String groupName) {
calls.add(new Call(operation, groupName, regionResolver.getAccountId(), regionResolver.getRegion()));
return null;
}
/** The calls to this test's groups: the backfill also visits every other cluster the application holds. */
private static List<Call> callsTo(List<Call> calls, Set<String> groups) {
return calls.stream().filter(call -> groups.contains(call.groupName())).toList();
}
private static String createNodeGroup(String account, String clusterName, String nodegroupName) {
return eks(account, REGION).body(Map.of(
"nodegroupName", nodegroupName,
"nodeRole", "arn:aws:iam::" + account + ":role/node",
"subnets", List.of("subnet-0123456789abcdef0")))
.post("/clusters/" + clusterName + "/node-groups").then().statusCode(200)
.extract().path("nodegroup.resources.autoScalingGroups[0].name");
}
}
@@ -6,6 +6,8 @@ import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.UUID;
import static io.floci.aws.testing.EksRequests.eks;
import static io.floci.aws.testing.EnforcementFixtures.auth;
import static io.floci.aws.testing.IamTestPolicies.EMPTY_POLICY_DOCUMENT;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
@@ -13,6 +15,8 @@ import static org.hamcrest.Matchers.*;
@QuarkusTest
class EksPodIdentityAssociationIntegrationTest {
private static final String REGION = "us-east-1";
@Test
void associationLifecycleRoundTrip() {
String account = "123456789012";
@@ -34,8 +38,7 @@ class EksPodIdentityAssociationIntegrationTest {
"tags", Map.of("env", "test")
);
String associationId = given().header("Authorization", auth(account, "eks"))
.contentType("application/json")
String associationId = eks(account, REGION)
.body(createReq)
.post(basePath)
.then()
@@ -53,8 +56,7 @@ class EksPodIdentityAssociationIntegrationTest {
.extract().path("association.associationId");
// 2. Idempotent retry with same parameters and token
given().header("Authorization", auth(account, "eks"))
.contentType("application/json")
eks(account, REGION)
.body(createReq)
.post(basePath)
.then()
@@ -68,8 +70,7 @@ class EksPodIdentityAssociationIntegrationTest {
"roleArn", roleArn,
"clientRequestToken", "token-abc"
);
given().header("Authorization", auth(account, "eks"))
.contentType("application/json")
eks(account, REGION)
.body(conflictReq)
.post(basePath)
.then()
@@ -82,8 +83,7 @@ class EksPodIdentityAssociationIntegrationTest {
"serviceAccount", "my-service-account",
"roleArn", roleArn
);
given().header("Authorization", auth(account, "eks"))
.contentType("application/json")
eks(account, REGION)
.body(duplicateReq)
.post(basePath)
.then()
@@ -91,7 +91,7 @@ class EksPodIdentityAssociationIntegrationTest {
.body("__type", equalTo("ResourceInUseException"));
// 5. Describe association
given().header("Authorization", auth(account, "eks"))
eks(account, REGION)
.get(basePath + "/" + associationId)
.then()
.statusCode(200)
@@ -109,8 +109,7 @@ class EksPodIdentityAssociationIntegrationTest {
"roleArn", updatedRoleArn,
"disableSessionTags", true
);
given().header("Authorization", auth(account, "eks"))
.contentType("application/json")
eks(account, REGION)
.body(updateReq)
.post(basePath + "/" + associationId)
.then()
@@ -121,7 +120,7 @@ class EksPodIdentityAssociationIntegrationTest {
.body("association.disableSessionTags", equalTo(true));
// 7. List associations
given().header("Authorization", auth(account, "eks"))
eks(account, REGION)
.get(basePath)
.then()
.statusCode(200)
@@ -132,7 +131,7 @@ class EksPodIdentityAssociationIntegrationTest {
.body("associations[0].serviceAccount", equalTo("my-service-account"));
// List with filter matching
given().header("Authorization", auth(account, "eks"))
eks(account, REGION)
.queryParam("namespace", "default")
.get(basePath)
.then()
@@ -140,7 +139,7 @@ class EksPodIdentityAssociationIntegrationTest {
.body("associations", hasSize(1));
// List with filter non-matching
given().header("Authorization", auth(account, "eks"))
eks(account, REGION)
.queryParam("namespace", "other-namespace")
.get(basePath)
.then()
@@ -148,7 +147,7 @@ class EksPodIdentityAssociationIntegrationTest {
.body("associations", hasSize(0));
// 8. Delete association
given().header("Authorization", auth(account, "eks"))
eks(account, REGION)
.delete(basePath + "/" + associationId)
.then()
.statusCode(200)
@@ -156,7 +155,7 @@ class EksPodIdentityAssociationIntegrationTest {
.body("association.associationId", equalTo(associationId));
// 9. Describe after delete returns 404
given().header("Authorization", auth(account, "eks"))
eks(account, REGION)
.get(basePath + "/" + associationId)
.then()
.statusCode(404)
@@ -170,7 +169,7 @@ class EksPodIdentityAssociationIntegrationTest {
void routeCollisionsAndMissingCluster() {
String account = "123456789012";
// Missing cluster returns 404 JSON, not S3 NoSuchBucket XML
given().header("Authorization", auth(account, "eks"))
eks(account, REGION)
.get("/clusters/nonexistent-cluster/pod-identity-associations")
.then()
.statusCode(404)
@@ -191,18 +190,16 @@ class EksPodIdentityAssociationIntegrationTest {
try {
// Create two associations
given().header("Authorization", auth(account, "eks"))
.contentType("application/json")
eks(account, REGION)
.body(Map.of("namespace", "ns1", "serviceAccount", "sa1", "roleArn", roleArn))
.post(basePath).then().statusCode(200);
given().header("Authorization", auth(account, "eks"))
.contentType("application/json")
eks(account, REGION)
.body(Map.of("namespace", "ns2", "serviceAccount", "sa2", "roleArn", roleArn))
.post(basePath).then().statusCode(200);
// maxResults = 1 returns first item and nextToken
String nextToken = given().header("Authorization", auth(account, "eks"))
String nextToken = eks(account, REGION)
.queryParam("maxResults", "1")
.get(basePath)
.then()
@@ -212,7 +209,7 @@ class EksPodIdentityAssociationIntegrationTest {
.extract().path("nextToken");
// Fetch next page
given().header("Authorization", auth(account, "eks"))
eks(account, REGION)
.queryParam("maxResults", "1")
.queryParam("nextToken", nextToken)
.get(basePath)
@@ -222,14 +219,14 @@ class EksPodIdentityAssociationIntegrationTest {
.body("nextToken", nullValue());
// Invalid maxResults returns 400 InvalidParameterException
given().header("Authorization", auth(account, "eks"))
eks(account, REGION)
.queryParam("maxResults", "0")
.get(basePath)
.then()
.statusCode(400)
.body("__type", equalTo("InvalidParameterException"));
given().header("Authorization", auth(account, "eks"))
eks(account, REGION)
.queryParam("maxResults", "invalid")
.get(basePath)
.then()
@@ -251,8 +248,7 @@ class EksPodIdentityAssociationIntegrationTest {
createRole(account, roleName);
createCluster(account, name);
given().header("Authorization", auth(account, "eks"))
.contentType("application/json")
eks(account, REGION)
.body(Map.of("namespace", "default", "serviceAccount", "sa", "roleArn", roleArn))
.post(basePath).then().statusCode(200);
@@ -263,7 +259,7 @@ class EksPodIdentityAssociationIntegrationTest {
createCluster(account, name);
try {
// Associations must be empty
given().header("Authorization", auth(account, "eks"))
eks(account, REGION)
.get(basePath)
.then()
.statusCode(200)
@@ -284,19 +280,13 @@ class EksPodIdentityAssociationIntegrationTest {
}
private static void createCluster(String account, String name) {
given().header("Authorization", auth(account, "eks"))
.contentType("application/json")
eks(account, REGION)
.body(Map.of("name", name, "roleArn", "arn:aws:iam::" + account + ":role/cluster"))
.post("/clusters").then().statusCode(200);
}
private static void deleteCluster(String account, String name) {
given().header("Authorization", auth(account, "eks"))
eks(account, REGION)
.delete("/clusters/" + name).then().statusCode(200);
}
private static String auth(String account, String service) {
return "AWS4-HMAC-SHA256 Credential=" + account
+ "/20260920/us-east-1/" + service + "/aws4_request, SignedHeaders=host, Signature=abc";
}
}
@@ -7,7 +7,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static io.floci.aws.testing.EksRequests.eks;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
@@ -28,27 +28,27 @@ class EksRegionScopingIntegrationTest {
@Test
void clusterIsOnlyVisibleInTheRegionItWasCreatedIn() {
given().header("Authorization", auth("eu-west-1")).contentType("application/json")
eks(ACCOUNT, "eu-west-1")
.body(Map.of("name", CLUSTER, "roleArn", "arn:aws:iam::" + ACCOUNT + ":role/cluster"))
.post("/clusters").then().statusCode(200)
.body("cluster.arn", equalTo("arn:aws:eks:eu-west-1:" + ACCOUNT + ":cluster/" + CLUSTER));
try {
given().header("Authorization", auth("eu-west-1")).get("/clusters")
eks(ACCOUNT, "eu-west-1").get("/clusters")
.then().statusCode(200).body("clusters", hasItem(CLUSTER));
given().header("Authorization", auth("eu-west-1")).get("/clusters/" + CLUSTER)
eks(ACCOUNT, "eu-west-1").get("/clusters/" + CLUSTER)
.then().statusCode(200).body("cluster.name", equalTo(CLUSTER));
given().header("Authorization", auth("eu-central-1")).get("/clusters")
eks(ACCOUNT, "eu-central-1").get("/clusters")
.then().statusCode(200).body("clusters", not(hasItem(CLUSTER)));
given().header("Authorization", auth("eu-central-1")).get("/clusters/" + CLUSTER)
eks(ACCOUNT, "eu-central-1").get("/clusters/" + CLUSTER)
.then().statusCode(404);
given().header("Authorization", auth("eu-central-1")).get("/clusters/" + CLUSTER + "/node-groups")
eks(ACCOUNT, "eu-central-1").get("/clusters/" + CLUSTER + "/node-groups")
.then().statusCode(404);
given().header("Authorization", auth("eu-central-1")).delete("/clusters/" + CLUSTER)
eks(ACCOUNT, "eu-central-1").delete("/clusters/" + CLUSTER)
.then().statusCode(404);
} finally {
given().header("Authorization", auth("eu-west-1")).delete("/clusters/" + CLUSTER)
eks(ACCOUNT, "eu-west-1").delete("/clusters/" + CLUSTER)
.then().statusCode(200);
}
}
@@ -59,7 +59,7 @@ class EksRegionScopingIntegrationTest {
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")
issuers.put(region, eks(ACCOUNT, region)
.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))
@@ -67,33 +67,33 @@ class EksRegionScopingIntegrationTest {
}
try {
given().header("Authorization", auth("eu-west-1")).contentType("application/json")
eks(ACCOUNT, "eu-west-1")
.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")
eks(ACCOUNT, "eu-west-1")
.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")
eks(ACCOUNT, "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")
eks(ACCOUNT, "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))
String jwksUri = eks(ACCOUNT, 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))
String keyId = eks(ACCOUNT, region)
.queryParam("region", region)
.get("/_floci/eks/clusters/" + name + "/oidc/keys")
.then().statusCode(200).extract().path("keys[0].kid");
@@ -107,33 +107,28 @@ class EksRegionScopingIntegrationTest {
// 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")
eks(ACCOUNT, "eu-west-1")
.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")
eks(ACCOUNT, "eu-west-1")
.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)
eks(ACCOUNT, "eu-west-1").delete("/clusters/" + name)
.then().statusCode(200);
given().header("Authorization", auth("eu-central-1")).get("/clusters/" + name)
eks(ACCOUNT, "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);
eks(ACCOUNT, "eu-west-1").delete("/clusters/" + name);
eks(ACCOUNT, "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";
}
}
@@ -13,11 +13,13 @@ import io.floci.aws.core.storage.InMemoryStorage;
import io.floci.aws.core.storage.PersistentStorage;
import io.floci.aws.core.storage.StorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.autoscaling.AutoScalingService;
import io.floci.aws.services.ec2.AmiImageResolver;
import io.floci.aws.services.ec2.Ec2ContainerManager;
import io.floci.aws.services.ec2.Ec2ImageCatalog;
import io.floci.aws.services.ec2.Ec2InstanceTypeCatalog;
import io.floci.aws.services.ec2.Ec2Service;
import io.floci.aws.services.ec2.model.Instance;
import io.floci.aws.services.ec2.model.LaunchTemplate;
import io.floci.aws.services.ec2.model.LaunchTemplateData;
import io.floci.aws.services.ec2.model.SecurityGroup;
@@ -47,6 +49,8 @@ import io.floci.aws.testing.ThreadStates;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
@@ -67,6 +71,7 @@ import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.*;
@@ -74,11 +79,14 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
class EksServiceTest {
@@ -1258,6 +1266,192 @@ class EksServiceTest {
assertEquals(List.of("nodegroup-b"), eksService.listNodeGroups("my-eks-cluster"));
}
@Test
void aNodeGroupGetsTheAutoScalingGroupItReportsHoldingTheClusterNode() {
EksClusterManager clusterManager = mock(EksClusterManager.class);
AutoScalingService autoScaling = mock(AutoScalingService.class);
EksService service = serviceWithAutoScaling(clusterManager, autoScaling);
service.createCluster(createTestClusterRequest("asg-cluster"));
Instance node = clusterNode("i-0123456789abcdef0", "asg-cluster");
when(clusterManager.getRegisteredClusterNodeInstance(any())).thenReturn(node);
NodegroupScalingConfig scalingConfig = new NodegroupScalingConfig();
scalingConfig.setMinSize(1);
scalingConfig.setMaxSize(3);
scalingConfig.setDesiredSize(2);
CreateNodeGroupRequest request = nodeGroupRequest("workers");
request.setScalingConfig(scalingConfig);
String groupName = reportedAutoScalingGroup(service.createNodeGroup("asg-cluster", request));
InOrder order = inOrder(autoScaling);
order.verify(autoScaling).createEksManagedGroup("us-east-1", groupName, 1, 3, 2,
List.of("subnet-0e2907431c9988b72", "subnet-04ad87f71c6e5ab4d"),
nodeGroupAutoScalingTags("asg-cluster", "workers"));
order.verify(autoScaling).addEksManagedInstance("us-east-1", groupName, node);
verifyNoMoreInteractions(autoScaling);
}
@Test
void aNodeRegisteringAfterItsNodeGroupsJoinsEachOfTheirAutoScalingGroups() {
EksClusterManager clusterManager = mock(EksClusterManager.class);
AutoScalingService autoScaling = mock(AutoScalingService.class);
EksService service = serviceWithAutoScaling(clusterManager, autoScaling);
service.init();
@SuppressWarnings("unchecked")
ArgumentCaptor<Consumer<Instance>> listener = ArgumentCaptor.forClass(Consumer.class);
verify(clusterManager).addNodeRegistrationListener(listener.capture());
service.createCluster(createTestClusterRequest("late-node"));
String first = reportedAutoScalingGroup(service.createNodeGroup("late-node", nodeGroupRequest("first")));
String second = reportedAutoScalingGroup(service.createNodeGroup("late-node", nodeGroupRequest("second")));
Instance node = clusterNode("i-0123456789abcdef0", "late-node");
when(clusterManager.getRegisteredClusterNodeInstance(any())).thenReturn(node);
// An EC2 instance joining the cluster is in no managed node group, even tagged with the cluster's name.
listener.getValue().accept(clusterNode("i-0fedcba9876543210", "late-node"));
// Only the cluster the node names, in the node's Region, is read.
listener.getValue().accept(clusterNode("i-0123456789abcdef0", "other-cluster"));
Instance inAnotherRegion = clusterNode("i-0123456789abcdef0", "late-node");
inAnotherRegion.setRegion("eu-west-1");
listener.getValue().accept(inAnotherRegion);
verify(autoScaling, never()).addEksManagedInstance(any(), any(), any());
// A group that fails to take the node does not keep it from the other node groups' groups.
doThrow(new IllegalStateException("group storage write failed"))
.when(autoScaling).addEksManagedInstance("us-east-1", first, node);
listener.getValue().accept(node);
verify(autoScaling).addEksManagedInstance("us-east-1", first, node);
verify(autoScaling).addEksManagedInstance("us-east-1", second, node);
verify(autoScaling, times(2)).addEksManagedInstance(any(), any(), any());
}
@Test
void deletingANodeGroupOrItsClusterDeletesTheirAutoScalingGroups() {
AutoScalingService autoScaling = mock(AutoScalingService.class);
EksService service = serviceWithAutoScaling(mock(EksClusterManager.class), autoScaling);
service.createCluster(createTestClusterRequest("asg-delete"));
String first = reportedAutoScalingGroup(service.createNodeGroup("asg-delete", nodeGroupRequest("first")));
String second = reportedAutoScalingGroup(service.createNodeGroup("asg-delete", nodeGroupRequest("second")));
String third = reportedAutoScalingGroup(service.createNodeGroup("asg-delete", nodeGroupRequest("third")));
service.deleteNodeGroup("asg-delete", "first");
verify(autoScaling).deleteEksManagedGroup("us-east-1", first);
verify(autoScaling, times(1)).deleteEksManagedGroup(any(), any());
service.deleteCluster("asg-delete");
verify(autoScaling).deleteEksManagedGroup("us-east-1", second);
verify(autoScaling).deleteEksManagedGroup("us-east-1", third);
verify(autoScaling, times(3)).deleteEksManagedGroup(any(), any());
}
@Test
void anAutoScalingGroupThatFailsToDeleteLeavesTheNodeGroupAndClusterDeletionsToFinish() {
AutoScalingService autoScaling = mock(AutoScalingService.class);
EksService service = serviceWithAutoScaling(mock(EksClusterManager.class), autoScaling);
service.createCluster(createTestClusterRequest("asg-delete-failure"));
String first = reportedAutoScalingGroup(
service.createNodeGroup("asg-delete-failure", nodeGroupRequest("first")));
String second = reportedAutoScalingGroup(
service.createNodeGroup("asg-delete-failure", nodeGroupRequest("second")));
String third = reportedAutoScalingGroup(
service.createNodeGroup("asg-delete-failure", nodeGroupRequest("third")));
RuntimeException failure = new IllegalStateException("target group storage write failed");
doThrow(failure).when(autoScaling).deleteEksManagedGroup("us-east-1", first);
doThrow(failure).when(autoScaling).deleteEksManagedGroup("us-east-1", second);
service.deleteNodeGroup("asg-delete-failure", "first");
assertEquals(List.of("second", "third"), service.listNodeGroups("asg-delete-failure").stream().sorted().toList());
service.deleteCluster("asg-delete-failure");
verify(autoScaling).deleteEksManagedGroup("us-east-1", second);
verify(autoScaling).deleteEksManagedGroup("us-east-1", third);
assertThrows(AwsException.class, () -> service.describeCluster("asg-delete-failure"));
}
@Test
void aNodeGroupStoredBeforeTheseGroupsGetsItsGroupAtOneStartOnly(@TempDir Path directory) {
// A node group stored by a Floci that did not keep these groups.
EksService legacy = persistentEksService(directory);
legacy.init();
legacy.createCluster(createTestClusterRequest("backfill-once"));
String legacyGroup = reportedAutoScalingGroup(
legacy.createNodeGroup("backfill-once", nodeGroupRequest("legacy")));
AutoScalingService firstStart = mock(AutoScalingService.class);
EksService upgraded = persistentEksService(directory, ec2Service, null, firstStart);
upgraded.init();
String createdGroup = reportedAutoScalingGroup(
upgraded.createNodeGroup("backfill-once", nodeGroupRequest("created")));
List<String> subnets = List.of("subnet-0e2907431c9988b72", "subnet-04ad87f71c6e5ab4d");
verify(firstStart).createEksManagedGroup("us-east-1", legacyGroup, 1, 1, 1, subnets,
nodeGroupAutoScalingTags("backfill-once", "legacy"));
verify(firstStart).createEksManagedGroup("us-east-1", createdGroup, 1, 1, 1, subnets,
nodeGroupAutoScalingTags("backfill-once", "created"));
// Both groups were created, so a group deleted through Auto Scaling since is not created again.
AutoScalingService secondStart = mock(AutoScalingService.class);
persistentEksService(directory, ec2Service, null, secondStart).init();
verifyNoInteractions(secondStart);
}
@Test
void aRestartedNodeJoinsTheGroupItsNodeGroupAlreadyHas(@TempDir Path directory) {
EksService before = persistentEksService(directory, ec2Service, null, mock(AutoScalingService.class));
before.init();
before.createCluster(createTestClusterRequest("restarted-node"));
String groupName = reportedAutoScalingGroup(
before.createNodeGroup("restarted-node", nodeGroupRequest("workers")));
EksClusterManager clusterManager = mock(EksClusterManager.class);
AutoScalingService autoScaling = mock(AutoScalingService.class);
EksService after = persistentEksService(directory, null, clusterManager, autoScaling);
after.init();
@SuppressWarnings("unchecked")
ArgumentCaptor<Consumer<Instance>> listener = ArgumentCaptor.forClass(Consumer.class);
verify(clusterManager).addNodeRegistrationListener(listener.capture());
Instance node = clusterNode("i-0123456789abcdef0", "restarted-node");
when(clusterManager.getRegisteredClusterNodeInstance(any())).thenReturn(node);
listener.getValue().accept(node);
verify(autoScaling).addEksManagedInstance("us-east-1", groupName, node);
verifyNoMoreInteractions(autoScaling);
}
private EksService serviceWithAutoScaling(EksClusterManager clusterManager, AutoScalingService autoScaling) {
return new EksService(storageFactory, testConfig(true), regionResolver, clusterManager, null,
new EksOidcService(storageFactory, new ObjectMapper()), mock(EksAccessEntryService.class),
mock(EksPodIdentityAssociationService.class), null, autoScaling);
}
/** The tags EKS puts on a node group's Auto Scaling group. */
private static Map<String, String> nodeGroupAutoScalingTags(String clusterName, String nodegroupName) {
return Map.of(
"eks:cluster-name", clusterName,
"eks:nodegroup-name", nodegroupName,
"k8s.io/cluster-autoscaler/enabled", "true",
"k8s.io/cluster-autoscaler/" + clusterName, "owned");
}
private static String reportedAutoScalingGroup(Nodegroup nodeGroup) {
List<?> autoScalingGroups = (List<?>) ((Map<?, ?>) nodeGroup.getResources()).get("autoScalingGroups");
return (String) ((Map<?, ?>) autoScalingGroups.getFirst()).get("name");
}
/** An instance in us-east-1 tagged, as a cluster's node is, with its cluster's name. */
private static Instance clusterNode(String instanceId, String clusterName) {
Instance instance = new Instance();
instance.setInstanceId(instanceId);
instance.setRegion("us-east-1");
instance.setTags(List.of(new Tag("eks:cluster-name", clusterName)));
return instance;
}
@Test
void createNodeGroupRecordsLabelsAndTaints() {
createTestCluster("metadata-cluster");
@@ -2788,6 +2982,11 @@ class EksServiceTest {
}
private EksService persistentEksService(Path directory, Ec2Service ec2) {
return persistentEksService(directory, ec2, null, null);
}
private EksService persistentEksService(Path directory, Ec2Service ec2, EksClusterManager clusterManager,
AutoScalingService autoScaling) {
StorageFactory storageFactory = new StorageFactory(null, null) {
@Override
public <V> AccountAwareStorageBackend<V> create(String serviceName, String fileName,
@@ -2799,9 +2998,9 @@ class EksServiceTest {
}
};
return new EksService(storageFactory, testConfig(true),
new RegionResolver("us-east-1", "000000000000"), null, ec2,
new RegionResolver("us-east-1", "000000000000"), clusterManager, ec2,
new EksOidcService(storageFactory, new ObjectMapper()), mock(EksAccessEntryService.class),
mock(EksPodIdentityAssociationService.class));
mock(EksPodIdentityAssociationService.class), null, autoScaling);
}
@Test
@@ -3,6 +3,7 @@ package io.floci.aws.testing;
import io.floci.aws.services.ec2.Ec2Service;
import io.vertx.core.http.WebSocket;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
@@ -93,6 +94,22 @@ public final class AlbFixtures {
.statusCode(200);
}
/** The ids of the targets registered with {@code targetGroupArn}, in the order DescribeTargetHealth lists them. */
public static List<String> targetIds(String account, String targetGroupArn) {
return given()
.formParam("Action", "DescribeTargetHealth")
.formParam("TargetGroupArn", targetGroupArn)
.header("Authorization", auth(account))
.when()
.post("/")
.then()
.statusCode(200)
.extract()
.xmlPath()
.getList("DescribeTargetHealthResponse.DescribeTargetHealthResult.TargetHealthDescriptions.member"
+ ".Target.Id", String.class);
}
/** An HTTP listener on {@code port} that forwards every request to {@code targetGroupArn}. */
public static String createListener(String loadBalancerArn, String targetGroupArn, int port) {
return createListener(DEFAULT_ACCOUNT, loadBalancerArn, targetGroupArn, port);
@@ -0,0 +1,16 @@
package io.floci.aws.testing;
import io.restassured.specification.RequestSpecification;
import static io.restassured.RestAssured.given;
/** One EKS REST JSON request, signed for {@code account} in {@code region}. */
public final class EksRequests {
private EksRequests() {}
public static RequestSpecification eks(String account, String region) {
return given().header("Authorization", EnforcementFixtures.auth(account, region, "eks"))
.contentType("application/json");
}
}