fix(eks): validate subnet IDs exist before creating a cluster (#1943)

* fix(eks): validate subnet IDs exist before creating a cluster

CreateCluster previously accepted any subnet ID, including ones that
don't exist, and returned a successful cluster with an empty vpcId.
Real EKS validates resourcesVpcConfig.subnetIds against EC2 and
rejects the request with InvalidParameterException if a subnet is
not found.

EksService now delegates to Ec2Service.requireSubnet for each subnet
ID given at cluster creation, mirroring the pattern RdsService already
uses for DB subnet groups.

* fix(eks): resolve subnet validation against the request's region

Subnet validation in createCluster used config.defaultRegion() instead
of the region the request actually targeted, so a cluster created in a
non-default region with real, existing subnets would be wrongly
rejected as InvalidParameterException.

RegionResolver gains getRegion(), mirroring the existing getAccountId()
pattern (reads the per-request region set by AccountContextFilter,
falling back to the configured default outside request scope).
EksService.createCluster now uses regionResolver.getRegion() instead of
config.defaultRegion(), which also fixes the cluster ARN's region to
match the actual request.

Found via review feedback on #1943.

* fix(eks): pin the region test properly and resolve vpcId from the subnets

Addresses both blocking points from review.

1. The region regression test could not fail.

   It used subnet-default-a, and requireSubnet() calls ensureDefaultResources()
   on whatever region it is handed, which seeds subnet-default-a/b/c there on
   the spot. The subnet therefore resolves in every region, so validation passed
   with or without the fix and only the ARN assertion discriminated — exactly as
   pointed out.

   Verified by reverting `regionResolver.getRegion()` back to
   `config.defaultRegion()` and re-running: the old test failed at the ARN
   assertion on line 276, which means createCluster had already returned without
   throwing. Validation was never being exercised.

   Split into two honestly named tests:

     createClusterBuildsArnFromRequestRegionNotDefaultRegion
         what the old test actually pinned

     createClusterValidatesSubnetsInRequestRegionNotDefaultRegion
         creates a subnet explicitly in us-east-1 and requests a cluster in
         eu-west-2 with that id. An explicitly created subnet is not seeded
         elsewhere, so this is the only shape that discriminates.

   With the fix reverted it now fails with "Expected AwsException to be thrown,
   but nothing was thrown" — the cluster is created from a subnet in the wrong
   region, which is the bug. With the fix it passes.

2. resourcesVpcConfig.vpcId was still blank (the other half of #1942).

   CreateCluster carries no vpcId; real EKS derives it from the subnets.
   requireSubnet already returns the resolved Subnet, and validateSubnets threw
   it away. It now carries the vpcId through to buildVpcConfigResponse, with a
   caller-supplied value still taking precedence.

   New test createClusterResolvesVpcIdFromTheSubnets fails before the change
   with "expected: <vpc-default> but was: <>".

EksServiceTest 28 pass, Ec2ServiceTest 17 pass. Other failures in a full run are
pre-existing on this machine and unrelated — confirmed by stashing these changes
and reproducing ZipExtractorTest's backslash-path failure on the untouched tree.

Leaving the `catch (AwsException e)` narrowing for the separate PR as suggested.
This commit is contained in:
Sumedh authored and GitHub committed 2026-08-08 21:32:28 -05:00
1 parent 42363886d5
commit 66fd109ad6
3 files changed
+252 -6

No files matched your search

@@ -86,6 +86,24 @@ public class RegionResolver {
return defaultRegion;
}
/**
* Returns the region for the current request when called from a request context,
* or the configured default region otherwise (async workers, startup, tests).
*/
public String getRegion() {
if (requestContextInstance != null) {
try {
String region = requestContextInstance.get().getRegion();
if (region != null) {
return region;
}
} catch (ContextNotActiveException ignored) {
// outside request scope — fall through to default
}
}
return defaultRegion;
}
/**
* Returns the account ID for the current request when called from a request context,
* or the configured default account ID otherwise (async workers, startup, tests).
@@ -8,6 +8,7 @@ import io.github.hectorvent.floci.core.common.TagHandler;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.eks.model.CertificateAuthority;
import io.github.hectorvent.floci.services.eks.model.Cluster;
import io.github.hectorvent.floci.services.eks.model.ClusterStatus;
@@ -51,11 +52,12 @@ public class EksService implements TagHandler {
private final EmulatorConfig config;
private final RegionResolver regionResolver;
private final EksClusterManager clusterManager;
private final Ec2Service ec2Service;
private final ScheduledExecutorService poller = Executors.newSingleThreadScheduledExecutor();
@Inject
public EksService(StorageFactory storageFactory, EmulatorConfig config,
RegionResolver regionResolver, EksClusterManager clusterManager) {
RegionResolver regionResolver, EksClusterManager clusterManager, Ec2Service ec2Service) {
this.storage = storageFactory.create("eks", "eks-clusters.json",
new TypeReference<Map<String, Cluster>>() {
});
@@ -68,6 +70,7 @@ public class EksService implements TagHandler {
this.config = config;
this.regionResolver = regionResolver;
this.clusterManager = clusterManager;
this.ec2Service = ec2Service;
}
@PostConstruct
@@ -97,7 +100,8 @@ public class EksService implements TagHandler {
"Cluster already exists: " + name, 409);
}
String region = config.defaultRegion();
String region = regionResolver.getRegion();
String resolvedVpcId = validateSubnetsAndResolveVpcId(region, request.getResourcesVpcConfig());
String accountId = regionResolver.getAccountId();
String arn = AwsArnUtils.Arn.of("eks", region, accountId, "cluster/" + name).toString();
@@ -108,7 +112,7 @@ public class EksService implements TagHandler {
cluster.setCreatedAt(Instant.now());
cluster.setVersion(request.getVersion() != null ? request.getVersion() : "1.29");
cluster.setRoleArn(request.getRoleArn());
cluster.setResourcesVpcConfig(buildVpcConfigResponse(request.getResourcesVpcConfig()));
cluster.setResourcesVpcConfig(buildVpcConfigResponse(request.getResourcesVpcConfig(), resolvedVpcId));
cluster.setKubernetesNetworkConfig(buildNetworkConfig(request.getKubernetesNetworkConfig()));
cluster.setStatus(ClusterStatus.CREATING);
cluster.setTags(request.getTags() != null ? new HashMap<>(request.getTags()) : new HashMap<>());
@@ -380,12 +384,42 @@ public class EksService implements TagHandler {
return resourceArn.substring(idx + 1);
}
private ResourcesVpcConfig buildVpcConfigResponse(ResourcesVpcConfig request) {
/**
* Validates every requested subnet and returns the VPC they belong to.
*
* CreateCluster carries no vpcId — real EKS derives it from the subnets, and
* #1942 reported resourcesVpcConfig.vpcId coming back blank because the
* Subnet that requireSubnet already resolves was discarded here.
*
* @return the vpcId of the requested subnets, or null when none were given
*/
private String validateSubnetsAndResolveVpcId(String region, ResourcesVpcConfig vpcConfig) {
if (vpcConfig == null || vpcConfig.getSubnetIds() == null) {
return null;
}
String vpcId = null;
for (String subnetId : vpcConfig.getSubnetIds()) {
try {
vpcId = ec2Service.requireSubnet(region, subnetId).getVpcId();
} catch (AwsException e) {
throw new AwsException("InvalidParameterException",
"Subnet ID '" + subnetId + "' does not exist", 400);
}
}
return vpcId;
}
private ResourcesVpcConfig buildVpcConfigResponse(ResourcesVpcConfig request, String resolvedVpcId) {
ResourcesVpcConfig response = new ResourcesVpcConfig();
if (request != null) {
response.setSubnetIds(request.getSubnetIds() != null ? request.getSubnetIds() : List.of());
response.setSecurityGroupIds(request.getSecurityGroupIds() != null ? request.getSecurityGroupIds() : List.of());
response.setVpcId(request.getVpcId() != null ? request.getVpcId() : "");
// A caller-supplied vpcId still wins; otherwise fall back to the one
// the subnets resolved to, and only then to empty.
String vpcId = request.getVpcId() != null && !request.getVpcId().isBlank()
? request.getVpcId()
: (resolvedVpcId != null ? resolvedVpcId : "");
response.setVpcId(vpcId);
response.setEndpointPublicAccess(
request.getEndpointPublicAccess() != null ? request.getEndpointPublicAccess() : Boolean.TRUE);
response.setEndpointPrivateAccess(
@@ -6,6 +6,12 @@ import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.ec2.AmiImageResolver;
import io.github.hectorvent.floci.services.ec2.Ec2ContainerManager;
import io.github.hectorvent.floci.services.ec2.Ec2ImageCatalog;
import io.github.hectorvent.floci.services.ec2.Ec2InstanceTypeCatalog;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.ec2.portforward.Ec2PortForwardManager;
import io.github.hectorvent.floci.services.eks.model.ClusterStatus;
import io.github.hectorvent.floci.services.eks.model.CreateClusterRequest;
import io.github.hectorvent.floci.services.eks.model.CreateFargateProfileRequest;
@@ -16,6 +22,7 @@ import io.github.hectorvent.floci.services.eks.model.Cluster;
import io.github.hectorvent.floci.services.eks.model.Nodegroup;
import io.github.hectorvent.floci.services.eks.model.NodegroupScalingConfig;
import io.github.hectorvent.floci.services.eks.model.NodegroupStatus;
import io.github.hectorvent.floci.services.eks.model.ResourcesVpcConfig;
import com.fasterxml.jackson.core.type.TypeReference;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -28,6 +35,8 @@ import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class EksServiceTest {
@@ -45,8 +54,9 @@ class EksServiceTest {
EmulatorConfig config = testConfig();
EksClusterManager clusterManager = null;
Ec2Service ec2Service = null;
RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000");
eksService = new EksService(storageFactory, config, regionResolver, clusterManager);
eksService = new EksService(storageFactory, config, regionResolver, clusterManager, ec2Service);
}
private EmulatorConfig testConfig() {
@@ -104,6 +114,28 @@ class EksServiceTest {
return null;
}
private Ec2Service realEc2Service() {
EmulatorConfig ec2Config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.Ec2ServiceConfig ec2ServiceConfig = mock(EmulatorConfig.Ec2ServiceConfig.class);
when(ec2Config.defaultAccountId()).thenReturn("000000000000");
when(ec2Config.services()).thenReturn(services);
when(services.ec2()).thenReturn(ec2ServiceConfig);
when(ec2ServiceConfig.mock()).thenReturn(true);
StorageFactory storageFactory = new StorageFactory(null, null) {
@Override
public <V> StorageBackend<String, V> create(String serviceName, String fileName,
TypeReference<Map<String, V>> typeReference) {
return new InMemoryStorage<>();
}
};
return new Ec2Service(ec2Config, mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class),
mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(), storageFactory);
}
private void createTestCluster(String name) {
CreateClusterRequest clusterRequest = new CreateClusterRequest();
clusterRequest.setName(name);
@@ -160,6 +192,168 @@ class EksServiceTest {
assertThrows(AwsException.class, () -> eksService.createCluster(req));
}
@Test
void createClusterWithNonExistentSubnetFails() {
StorageFactory storageFactory = new StorageFactory(null, null) {
@Override
public <V> StorageBackend<String, V> create(String serviceName, String fileName,
TypeReference<Map<String, V>> typeReference) {
return new InMemoryStorage<>();
}
};
RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000");
EksService service = new EksService(storageFactory, testConfig(), regionResolver, null, realEc2Service());
ResourcesVpcConfig vpcConfig = new ResourcesVpcConfig();
vpcConfig.setSubnetIds(List.of("subnet-1", "subnet-2"));
CreateClusterRequest req = new CreateClusterRequest();
req.setName("fake-subnet-cluster");
req.setRoleArn("arn:aws:iam::000000000000:role/eks-role");
req.setResourcesVpcConfig(vpcConfig);
AwsException ex = assertThrows(AwsException.class, () -> service.createCluster(req));
assertEquals("InvalidParameterException", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
assertTrue(service.listClusters().isEmpty());
}
@Test
void createClusterWithExistingSubnetSucceeds() {
StorageFactory storageFactory = new StorageFactory(null, null) {
@Override
public <V> StorageBackend<String, V> create(String serviceName, String fileName,
TypeReference<Map<String, V>> typeReference) {
return new InMemoryStorage<>();
}
};
RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000");
EksService service = new EksService(storageFactory, testConfig(), regionResolver, null, realEc2Service());
ResourcesVpcConfig vpcConfig = new ResourcesVpcConfig();
vpcConfig.setSubnetIds(List.of("subnet-default-a", "subnet-default-b"));
CreateClusterRequest req = new CreateClusterRequest();
req.setName("real-subnet-cluster");
req.setRoleArn("arn:aws:iam::000000000000:role/eks-role");
req.setResourcesVpcConfig(vpcConfig);
Cluster cluster = service.createCluster(req);
assertEquals("real-subnet-cluster", cluster.getName());
assertEquals(List.of("subnet-default-a", "subnet-default-b"),
cluster.getResourcesVpcConfig().getSubnetIds());
}
@Test
void createClusterResolvesVpcIdFromTheSubnets() {
// The second half of #1942: resourcesVpcConfig.vpcId came back blank.
//
// CreateCluster does not carry a vpcId — real EKS derives it from the
// subnets, and so should this. requireSubnet already returns the
// resolved Subnet, which carries the vpcId; it was simply discarded.
StorageFactory storageFactory = new StorageFactory(null, null) {
@Override
public <V> StorageBackend<String, V> create(String serviceName, String fileName,
TypeReference<Map<String, V>> typeReference) {
return new InMemoryStorage<>();
}
};
RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000");
EksService service = new EksService(storageFactory, testConfig(), regionResolver, null,
realEc2Service());
ResourcesVpcConfig vpcConfig = new ResourcesVpcConfig();
vpcConfig.setSubnetIds(List.of("subnet-default-a", "subnet-default-b"));
CreateClusterRequest req = new CreateClusterRequest();
req.setName("vpc-id-cluster");
req.setRoleArn("arn:aws:iam::000000000000:role/eks-role");
req.setResourcesVpcConfig(vpcConfig);
Cluster cluster = service.createCluster(req);
assertEquals("vpc-default", cluster.getResourcesVpcConfig().getVpcId());
}
@Test
void createClusterBuildsArnFromRequestRegionNotDefaultRegion() {
// testConfig() always reports defaultRegion = "us-east-1"; the request's
// region is eu-west-2. This pins the ARN only — see the test below for
// the validation half.
StorageFactory storageFactory = new StorageFactory(null, null) {
@Override
public <V> StorageBackend<String, V> create(String serviceName, String fileName,
TypeReference<Map<String, V>> typeReference) {
return new InMemoryStorage<>();
}
};
RegionResolver regionResolver = new RegionResolver("eu-west-2", "000000000000");
EksService service = new EksService(storageFactory, testConfig(), regionResolver, null,
realEc2Service());
ResourcesVpcConfig vpcConfig = new ResourcesVpcConfig();
vpcConfig.setSubnetIds(List.of("subnet-default-a"));
CreateClusterRequest req = new CreateClusterRequest();
req.setName("cross-region-cluster");
req.setRoleArn("arn:aws:iam::000000000000:role/eks-role");
req.setResourcesVpcConfig(vpcConfig);
Cluster cluster = service.createCluster(req);
assertEquals("cross-region-cluster", cluster.getName());
assertTrue(cluster.getArn().contains("eu-west-2"));
}
@Test
void createClusterValidatesSubnetsInRequestRegionNotDefaultRegion() {
// A subnet that exists in the DEFAULT region and nowhere else.
//
// The distinction matters: requireSubnet() calls ensureDefaultResources()
// on whatever region it is handed, which seeds subnet-default-a/b/c
// there on the spot. So a default subnet id resolves in EVERY region and
// cannot discriminate between "validated against the request region" and
// "validated against the configured default" — a test written with one
// passes with or without the fix.
//
// An explicitly created subnet is not seeded anywhere else, so asking
// for it from a different region is the only thing that pins the
// behaviour.
StorageFactory storageFactory = new StorageFactory(null, null) {
@Override
public <V> StorageBackend<String, V> create(String serviceName, String fileName,
TypeReference<Map<String, V>> typeReference) {
return new InMemoryStorage<>();
}
};
Ec2Service ec2Service = realEc2Service();
ec2Service.ensureDefaultResources("us-east-1");
String usEastOnlySubnet = ec2Service
.createSubnet("us-east-1", "vpc-default", "172.31.200.0/24", "us-east-1a")
.getSubnetId();
// The request is for eu-west-2, where that subnet does not exist.
RegionResolver regionResolver = new RegionResolver("eu-west-2", "000000000000");
EksService service = new EksService(storageFactory, testConfig(), regionResolver, null,
ec2Service);
ResourcesVpcConfig vpcConfig = new ResourcesVpcConfig();
vpcConfig.setSubnetIds(List.of(usEastOnlySubnet));
CreateClusterRequest req = new CreateClusterRequest();
req.setName("wrong-region-subnet-cluster");
req.setRoleArn("arn:aws:iam::000000000000:role/eks-role");
req.setResourcesVpcConfig(vpcConfig);
// Resolving against config.defaultRegion() would find it in us-east-1
// and let the cluster through, which is the bug.
AwsException ex = assertThrows(AwsException.class, () -> service.createCluster(req));
assertEquals("InvalidParameterException", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
assertTrue(service.listClusters().isEmpty());
}
@Test
void describeCluster() {
CreateClusterRequest req = new CreateClusterRequest();