diff --git a/docs/services/eks.md b/docs/services/eks.md index ffd373eefb..18627df716 100644 --- a/docs/services/eks.md +++ b/docs/services/eks.md @@ -11,8 +11,7 @@ With IAM enforcement enabled, `CreateCluster` evaluates `eks:authenticationMode` `eks:bootstrapClusterCreatorAdminPermissions`, `eks:endpointPrivateAccess`, and `eks:endpointPublicAccess` from the request's `accessConfig` and `resourcesVpcConfig`. The generated metadata also maps those keys for `UpdateClusterConfig`, except the -create-only bootstrap flag; this does not implement the currently unsupported -update API. Its extraction is covered by resolver tests, not an SDK update lifecycle. +create-only bootstrap flag. Its extraction is covered by resolver tests, not an SDK update lifecycle. The action-to-key mappings come from AWS's Service Reference and the request paths from botocore. Omitted attributes remain absent from the IAM context; stored cluster settings and service defaults do not supply missing request conditions. Generic request-tag @@ -341,6 +340,8 @@ EKS clusters support configuring KMS envelope encryption for secrets and control - **Supported log types**: The valid EKS log types are `api`, `audit`, `authenticator`, `controllerManager`, and `scheduler`. Specifying an unrecognized type causes `InvalidParameterException` (HTTP 400). - **Response normalization**: AWS EKS always returns the status of all five log types. Enabled types are returned first (`enabled: true`), followed by disabled types (`enabled: false`). +- **Changing logging later**: A logging change made through `UpdateClusterConfig` is stored and returned by `DescribeCluster`; it is read when a cluster's container is started or adopted, when the control plane log stream and audit follower are attached and the audit flags are given to the API server, so it does not change what a running cluster exports. +- **Refused updates**: `UpdateClusterConfig` moves the authentication mode one step forward only (`CONFIG_MAP`, `API_AND_CONFIG_MAP`, `API`), and refuses an endpoint or logging update that changes nothing, as EKS does. - **Default logging**: When omitted or empty at creation time, Floci returns all five log types disabled in a single entry (`enabled: false`). - **Backfill**: Existing persisted clusters created before this feature was introduced are automatically backfilled on startup with default disabled logging. - **CloudWatch Logs delivery**: @@ -388,7 +389,7 @@ With IAM enforcement on, `CreateCluster` checks `iam:PassRole` on the cluster ro Floci records the configuration and does nothing more with it yet. It does not create the node role's access entry, install the built-in node pools, serve the EBS provisioner or create load balancers, and -`UpdateClusterConfig` is not implemented. [#8914](https://github.com/floci-io/floci/issues/8914) plans each. +`UpdateClusterConfig` refuses these members. [#8914](https://github.com/floci-io/floci/issues/8914) plans each. ## Node group inputs @@ -1217,7 +1218,8 @@ eks.deleteCluster(r -> r.name("my-cluster")); The following EKS features are not yet supported: -- `UpdateClusterConfig` / `UpdateClusterVersion` +- `UpdateClusterVersion` +- `UpdateClusterConfig` members other than `resourcesVpcConfig` endpoint access and `publicAccessCidrs`, `logging` and `accessConfig.authenticationMode`; a different `subnetIds` or `securityGroupIds` list is refused - `UpdateNodegroupConfig` / `UpdateNodegroupVersion` - Add-ons (`CreateAddon`, `DescribeAddon`, `ListAddons`) - Identity provider configs diff --git a/docs/services/index.md b/docs/services/index.md index f28a4bb0e3..d75282b17f 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -108,7 +108,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [Bedrock Runtime](bedrock-runtime.md) | `/model/{modelId}/converse`, `/model/{modelId}/converse-stream`, `/model/{modelId}/invoke` | REST JSON | 3 (`InvokeModelWithResponseStream` answers 501) | | [Bedrock AgentCore Control](bedrock-agentcore.md) | `/runtimes/*`, `/gateways/*`, `/memories/*`, `/identities/*`, `/browsers*`, `/browser-profiles*`, `/code-interpreters*`, `/harnesses*`, `/resourcepolicy/*`, `/tags/{resourceArn}` | REST JSON | 71 (+ 3 tagging via shared `/tags/{arn}` route) | | [Bedrock AgentCore](bedrock-agentcore.md#data-plane-invokeagentruntime) | `/runtimes/{agentRuntimeArn}/invocations` | REST JSON (binary payload) | 1 (canned-response stub) | -| [EKS](eks.md) | `/clusters`, `/clusters/{name}`, `/tags/{resourceArn}` | REST JSON | 35 | +| [EKS](eks.md) | `/clusters`, `/clusters/{name}`, `/tags/{resourceArn}` | REST JSON | 36 | | [ELB v2](elb.md) | `POST /` with `Action=` param | Query | 37 | | [ELB Classic (v1)](elb-classic.md) | `POST /` with `Action=` and `Version=2012-06-01` | Query | 20 | | [WAF v2](wafv2.md) | `POST /` + `X-Amz-Target: AWSWAF_20190729.*` | JSON 1.1 | 35 | diff --git a/src/main/java/io/floci/aws/services/eks/EksAccessEntryService.java b/src/main/java/io/floci/aws/services/eks/EksAccessEntryService.java index e41a1c7f43..280bfd64bd 100644 --- a/src/main/java/io/floci/aws/services/eks/EksAccessEntryService.java +++ b/src/main/java/io/floci/aws/services/eks/EksAccessEntryService.java @@ -214,7 +214,7 @@ public class EksAccessEntryService { && tags.equals(previous.tags())) { return previous; } - throw invalid("clientRequestToken was already used with different parameters"); + throw invalid(EksAddonService.TOKEN_REUSED); } } } diff --git a/src/main/java/io/floci/aws/services/eks/EksAddonService.java b/src/main/java/io/floci/aws/services/eks/EksAddonService.java index 1b89a8defe..606067106d 100644 --- a/src/main/java/io/floci/aws/services/eks/EksAddonService.java +++ b/src/main/java/io/floci/aws/services/eks/EksAddonService.java @@ -22,6 +22,7 @@ import io.floci.aws.services.eks.model.CreatePodIdentityAssociationRequest; import io.floci.aws.services.eks.model.PodIdentityAssociation; import io.floci.aws.services.eks.model.Update; import io.floci.aws.services.eks.model.UpdateAddonRequest; +import io.floci.aws.services.eks.model.UpdateClusterConfigRequest; import io.floci.aws.services.eks.model.UpdateParam; import io.floci.aws.services.iam.IamService; import io.quarkus.runtime.annotations.RegisterForReflection; @@ -43,6 +44,8 @@ import java.util.function.UnaryOperator; @ApplicationScoped public class EksAddonService { + static final String TOKEN_REUSED = "clientRequestToken was already used with different parameters"; + private static final Logger LOG = Logger.getLogger(EksAddonService.class); private static final ObjectMapper MAPPER = new ObjectMapper(); private static final int DEFAULT_PAGE_SIZE = 100; @@ -85,7 +88,11 @@ public class EksAddonService { public record StoredAddon(Addon addon, String clientRequestToken) {} @RegisterForReflection - public record StoredUpdate(Update update, String addonName) {} + public record StoredUpdate(Update update, String addonName, UpdateClusterConfigRequest request) { + public StoredUpdate(Update update, String addonName) { + this(update, addonName, null); + } + } @RegisterForReflection public record AddonNamesPage(List addons, String nextToken) {} @@ -114,8 +121,7 @@ public class EksAddonService { if (parametersMatch(stored.addon(), request)) { return stored.addon(); } - throw new AwsException("InvalidParameterException", - "clientRequestToken was already used with different parameters", 400); + throw new AwsException("InvalidParameterException", TOKEN_REUSED, 400); } throw new AwsException("ResourceInUseException", "Addon already exists: " + addonName, 409); } @@ -301,16 +307,7 @@ public class EksAddonService { storage.put(storageKey, new StoredAddon(updatedAddon, token)); LOG.infov("Updated EKS addon {0} on cluster {1}", addonName, cluster.getName()); - Update update = new Update( - UUID.randomUUID().toString(), - "Successful", - "AddonUpdate", - params, - now, - List.of() - ); - updatesStorage.put(prefix(cluster) + update.id(), new StoredUpdate(update, addonName)); - return update; + return recordUpdate(cluster, "AddonUpdate", params, addonName); } public synchronized Addon delete(Cluster cluster, String addonName, boolean preserve) { @@ -377,10 +374,35 @@ public class EksAddonService { } } + /** Stores an update that always completes at once; {@code addonName} is null for one made to the cluster. */ + public Update recordUpdate(Cluster cluster, String type, List params, String addonName) { + return recordUpdate(cluster, type, params, addonName, null); + } + + /** + * As above, keeping the UpdateClusterConfig {@code request} that made the update, so a repeat of its + * {@code clientRequestToken} finds it again. + */ + public Update recordUpdate(Cluster cluster, String type, List params, String addonName, + UpdateClusterConfigRequest request) { + Update update = new Update(UUID.randomUUID().toString(), "Successful", type, params, + EpochSeconds.fromInstant(Instant.now()), List.of()); + updatesStorage.put(prefix(cluster) + update.id(), new StoredUpdate(update, addonName, request)); + return update; + } + + /** The update an earlier UpdateClusterConfig with this {@code clientRequestToken} made, with its request. */ + public Optional findConfigUpdateByToken(Cluster cluster, String token) { + String p = prefix(cluster); + return updatesStorage.scan(k -> k.startsWith(p)).stream() + .filter(stored -> stored.request() != null && token.equals(stored.request().clientRequestToken())) + .findFirst(); + } + public Update describeUpdate(Cluster cluster, String updateId, String addonName) { StoredUpdate stored = storedUpdate(cluster, updateId); if (addonName != null && !addonName.isBlank() - && stored.addonName() != null && !stored.addonName().equalsIgnoreCase(addonName.trim())) { + && (stored.addonName() == null || !stored.addonName().equalsIgnoreCase(addonName.trim()))) { throw new AwsException("ResourceNotFoundException", "No update: " + updateId + " found for addon: " + addonName, 404); } @@ -534,7 +556,7 @@ public class EksAddonService { .toString(); } - private static void requireActiveCluster(Cluster cluster) { + static void requireActiveCluster(Cluster cluster) { if (cluster == null) { throw new AwsException("ResourceNotFoundException", "Cluster not found", 404); } diff --git a/src/main/java/io/floci/aws/services/eks/EksController.java b/src/main/java/io/floci/aws/services/eks/EksController.java index 5751fd0159..9b44dcf669 100644 --- a/src/main/java/io/floci/aws/services/eks/EksController.java +++ b/src/main/java/io/floci/aws/services/eks/EksController.java @@ -21,6 +21,7 @@ import io.floci.aws.services.eks.model.Nodegroup; import io.floci.aws.services.eks.model.PodIdentityAssociation; import io.floci.aws.services.eks.model.Update; import io.floci.aws.services.eks.model.UpdateAddonRequest; +import io.floci.aws.services.eks.model.UpdateClusterConfigRequest; import io.floci.aws.services.eks.model.UpdatePodIdentityAssociationRequest; import jakarta.inject.Inject; import jakarta.ws.rs.Consumes; @@ -37,6 +38,7 @@ import jakarta.ws.rs.core.Response; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Set; /** * EKS REST-JSON controller. @@ -59,6 +61,10 @@ public class EksController { + "aws(?::|%3[aA])cluster-access-policy(?:/|%2[fF])[^/]+"; + private static final List UPDATE_CONFIG_FAMILIES = List.of("resourcesVpcConfig", "logging", "accessConfig"); + private static final Set UPDATE_CONFIG_MEMBERS = + Set.of("name", "clientRequestToken", "resourcesVpcConfig", "logging", "accessConfig"); + private final EksService eksService; private final EksAccessEntryService accessEntries; private final EksPodIdentityAssociationService podIdentityAssociations; @@ -343,6 +349,35 @@ public class EksController { return Response.ok(Map.of("update", update)).build(); } + /** + * The body is checked against its botocore shape as {@link #createCluster} checks its own. A member floci does + * not apply is refused rather than dropped. The service applies every family the request names; this endpoint + * refuses more than one, as EKS does. + */ + @POST + @Path("/clusters/{name}/update-config") + public Response updateClusterConfig(@PathParam("name") String name, JsonNode body) { + UpdateClusterConfigRequest request = null; + if (body != null) { + EksRequestShapes.check("UpdateClusterConfig", body); + for (String member : (Iterable) body::fieldNames) { + if (!UPDATE_CONFIG_MEMBERS.contains(member)) { + throw new AwsException("InvalidParameterException", + "Floci does not support updating " + member + " through UpdateClusterConfig yet", 400); + } + } + if (UPDATE_CONFIG_FAMILIES.stream().filter(body::has).count() > 1) { + throw new AwsException("InvalidParameterException", "Only one type of update can be allowed.", 400); + } + try { + request = objectMapper.treeToValue(body, UpdateClusterConfigRequest.class); + } catch (JsonProcessingException e) { + throw new AwsException("SerializationException", e.getOriginalMessage(), 400); + } + } + return Response.ok(Map.of("update", eksService.updateClusterConfig(name, request).get(0))).build(); + } + @GET @Path("/clusters/{name}/updates/{updateId}") public Response describeUpdate(@PathParam("name") String name, diff --git a/src/main/java/io/floci/aws/services/eks/EksPodIdentityAssociationService.java b/src/main/java/io/floci/aws/services/eks/EksPodIdentityAssociationService.java index 501c43a52c..05cf3f5c72 100644 --- a/src/main/java/io/floci/aws/services/eks/EksPodIdentityAssociationService.java +++ b/src/main/java/io/floci/aws/services/eks/EksPodIdentityAssociationService.java @@ -111,7 +111,7 @@ public class EksPodIdentityAssociationService { && tags.equals(previous.tags())) { return previous; } - throw invalid("clientRequestToken was already used with different parameters"); + throw invalid(EksAddonService.TOKEN_REUSED); } } } @@ -190,7 +190,7 @@ public class EksPodIdentityAssociationService { if (matches) { return current; } - throw invalid("clientRequestToken was already used with different parameters"); + throw invalid(EksAddonService.TOKEN_REUSED); } String newRoleArn = current.roleArn(); diff --git a/src/main/java/io/floci/aws/services/eks/EksService.java b/src/main/java/io/floci/aws/services/eks/EksService.java index c449c8c29f..53092f02b2 100644 --- a/src/main/java/io/floci/aws/services/eks/EksService.java +++ b/src/main/java/io/floci/aws/services/eks/EksService.java @@ -1,6 +1,8 @@ package io.floci.aws.services.eks; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.AvailabilityZoneIds; import io.floci.aws.core.common.AwsArnUtils; @@ -52,6 +54,9 @@ import io.floci.aws.services.eks.model.OidcIdentity; import io.floci.aws.services.eks.model.Provider; import io.floci.aws.services.eks.model.ResourcesVpcConfig; import io.floci.aws.services.eks.model.StorageConfig; +import io.floci.aws.services.eks.model.Update; +import io.floci.aws.services.eks.model.UpdateClusterConfigRequest; +import io.floci.aws.services.eks.model.UpdateParam; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; import jakarta.enterprise.context.ApplicationScoped; @@ -89,10 +94,11 @@ import java.util.stream.Collectors; public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaunchListener { private static final Logger LOG = Logger.getLogger(EksService.class); + private static final ObjectMapper MAPPER = new ObjectMapper(); private record UserDataClaim(String userData, CompletableFuture future) {} - private static final List ALL_LOG_TYPES = List.of( + public static final List ALL_LOG_TYPES = List.of( "api", "audit", "authenticator", "controllerManager", "scheduler" ); @@ -796,7 +802,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun AccessConfig requestedAccess = request.getAccessConfig(); String authenticationMode = requestedAccess == null || requestedAccess.authenticationMode() == null ? "CONFIG_MAP" : requestedAccess.authenticationMode(); - if (!Set.of("CONFIG_MAP", "API_AND_CONFIG_MAP", "API").contains(authenticationMode)) { + if (!AUTHENTICATION_MODE_RANK.containsKey(authenticationMode)) { throw new AwsException("InvalidParameterException", "Invalid authenticationMode", 400); } validateAutoMode(request.getComputeConfig(), request.getStorageConfig(), request.getKubernetesNetworkConfig()); @@ -1028,6 +1034,206 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun } } + static final List DEFAULT_PUBLIC_ACCESS_CIDRS = List.of("0.0.0.0/0"); + + private static final Map AUTHENTICATION_MODE_RANK = + Map.of("CONFIG_MAP", 0, "API_AND_CONFIG_MAP", 1, "API", 2); + + /** + * UpdateClusterConfig for {@code resourcesVpcConfig} endpoint access, {@code logging} and + * {@code accessConfig.authenticationMode}. AWS accepts more members and lets the subnets and security + * groups change; floci applies these three families and refuses a different subnet or security group list. + * Each family the request names is stored as its own {@link Update} and all are returned in order. The + * REST endpoint refuses a request naming more than one family, as EKS does, so it returns the only one. The + * request is kept with the first update, and a repeat of its {@code clientRequestToken} returns that update. + * The cluster is written through the delete-safe writer, so a concurrent delete is not undone. + */ + public synchronized List updateClusterConfig(String name, UpdateClusterConfigRequest request) { + Cluster cluster = requireClusterInRequestRegion(name); + EksAddonService.requireActiveCluster(cluster); + if (request == null || (request.resourcesVpcConfig() == null && request.logging() == null + && request.accessConfig() == null)) { + throw new AwsException("InvalidParameterException", + "UpdateClusterConfig supports resourcesVpcConfig, logging and accessConfig only", 400); + } + String token = request.clientRequestToken(); + if (token != null && !token.isBlank()) { + Optional previous = addons.findConfigUpdateByToken(cluster, token); + if (previous.isPresent()) { + if (updateParametersMatch(previous.get().request(), request)) { + return List.of(previous.get().update()); + } + throw new AwsException("InvalidParameterException", EksAddonService.TOKEN_REUSED, 400); + } + } + // Validated whole before anything is written, so a refused request changes nothing. + ResourcesVpcConfig vpc = cluster.getResourcesVpcConfig(); + ResourcesVpcConfig requestedVpc = request.resourcesVpcConfig(); + Boolean storedPublic = vpc == null || vpc.getEndpointPublicAccess() == null ? Boolean.TRUE : vpc.getEndpointPublicAccess(); + Boolean storedPrivate = vpc == null || vpc.getEndpointPrivateAccess() == null ? Boolean.FALSE : vpc.getEndpointPrivateAccess(); + List storedCidrs = vpc == null || vpc.getPublicAccessCidrs() == null + ? DEFAULT_PUBLIC_ACCESS_CIDRS : vpc.getPublicAccessCidrs(); + Boolean publicAccess = storedPublic; + Boolean privateAccess = storedPrivate; + List cidrs = storedCidrs; + if (requestedVpc != null) { + requireSameMembers("subnetIds", requestedVpc.getSubnetIds(), vpc == null ? null : vpc.getSubnetIds()); + requireSameMembers("securityGroupIds", requestedVpc.getSecurityGroupIds(), + vpc == null ? null : vpc.getSecurityGroupIds()); + publicAccess = requestedVpc.getEndpointPublicAccess() != null + ? requestedVpc.getEndpointPublicAccess() : publicAccess; + privateAccess = requestedVpc.getEndpointPrivateAccess() != null + ? requestedVpc.getEndpointPrivateAccess() : privateAccess; + // The stored cluster's ipFamily, as CreateCluster checks the same list against the requested one. + KubernetesNetworkConfig stored = cluster.getKubernetesNetworkConfig(); + requireValidPublicAccessCidrs(requestedVpc.getPublicAccessCidrs(), + stored == null || stored.getIpFamily() == null ? "ipv4" : stored.getIpFamily()); + cidrs = requestedVpc.getPublicAccessCidrs() != null ? requestedVpc.getPublicAccessCidrs() : cidrs; + requireEndpointChange(vpc != null, storedPublic, storedPrivate, storedCidrs, publicAccess, privateAccess, cidrs); + } + Logging logging = request.logging() == null || request.logging().getClusterLogging() == null + ? null : buildLogging(mergedLogging(cluster.getLogging(), request.logging())); + if (logging != null && enabledLogTypes(logging).equals(enabledLogTypes(cluster.getLogging()))) { + throw new AwsException("InvalidParameterException", "No changes needed for the logging config provided", 400); + } + String mode = cluster.getAccessConfig() == null || cluster.getAccessConfig().authenticationMode() == null + ? "CONFIG_MAP" : cluster.getAccessConfig().authenticationMode(); + String requestedMode = request.accessConfig() == null ? null : request.accessConfig().authenticationMode(); + if (requestedMode != null) { + requireForwardAuthenticationMode(mode, requestedMode); + } + + Boolean finalPublicAccess = publicAccess; + Boolean finalPrivateAccess = privateAccess; + List finalCidrs = cidrs; + List updates = new ArrayList<>(); + String accountId = regionResolver.getAccountId(); + boolean[] saved = {false}; + saveClusterIfNotDeleting(accountId, clusterKey(cluster), current -> { + saved[0] = true; + ResourcesVpcConfig currentVpc = current.getResourcesVpcConfig(); + if (requestedVpc != null && currentVpc != null) { + currentVpc.setEndpointPublicAccess(finalPublicAccess); + currentVpc.setEndpointPrivateAccess(finalPrivateAccess); + currentVpc.setPublicAccessCidrs(finalCidrs); + List params = new ArrayList<>(); + params.add(new UpdateParam("EndpointPublicAccess", String.valueOf(finalPublicAccess))); + params.add(new UpdateParam("EndpointPrivateAccess", String.valueOf(finalPrivateAccess))); + if (requestedVpc.getPublicAccessCidrs() != null) { + params.add(new UpdateParam("PublicAccessCidrs", json(finalCidrs))); + } + updates.add(addons.recordUpdate(current, "EndpointAccessUpdate", params, null, updates.isEmpty() ? request : null)); + } + if (logging != null) { + current.setLogging(logging); + updates.add(addons.recordUpdate(current, "LoggingUpdate", + List.of(new UpdateParam("ClusterLogging", json(logging))), null, + updates.isEmpty() ? request : null)); + } + if (requestedMode != null) { + current.setAccessConfig(new AccessConfig(requestedMode, + current.getAccessConfig() == null ? null : current.getAccessConfig().bootstrapClusterCreatorAdminPermissions())); + updates.add(addons.recordUpdate(current, "AccessConfigUpdate", + List.of(new UpdateParam("AuthenticationMode", requestedMode)), null, + updates.isEmpty() ? request : null)); + } + }); + if (!saved[0]) { + throw new AwsException("ResourceNotFoundException", "No cluster found for name: " + name, 404); + } + if (updates.isEmpty()) { + throw new AwsException("InvalidParameterException", + "UpdateClusterConfig supports resourcesVpcConfig, logging and accessConfig.authenticationMode only", 400); + } + LOG.infov("Updated the configuration of EKS cluster {0}: {1}", cluster.getName(), + updates.stream().map(Update::type).toList()); + return updates; + } + + private static boolean updateParametersMatch(UpdateClusterConfigRequest existing, UpdateClusterConfigRequest request) { + if (existing == null) { + return false; + } + ResourcesVpcConfig a = existing.resourcesVpcConfig(); + ResourcesVpcConfig b = request.resourcesVpcConfig(); + boolean sameVpc = a == null || b == null ? a == b + : Objects.equals(a.getSubnetIds(), b.getSubnetIds()) + && Objects.equals(a.getSecurityGroupIds(), b.getSecurityGroupIds()) + && Objects.equals(a.getEndpointPublicAccess(), b.getEndpointPublicAccess()) + && Objects.equals(a.getEndpointPrivateAccess(), b.getEndpointPrivateAccess()) + && Objects.equals(a.getPublicAccessCidrs(), b.getPublicAccessCidrs()); + return sameVpc && Objects.equals(existing.logging(), request.logging()) + && Objects.equals(existing.accessConfig(), request.accessConfig()); + } + + /** The cluster's current settings with the request applied on top, in the shape createCluster validates. */ + private static Logging mergedLogging(Logging current, Logging requested) { + List merged = new ArrayList<>(); + if (current != null && current.getClusterLogging() != null) { + merged.addAll(current.getClusterLogging()); + } + merged.addAll(requested.getClusterLogging()); + return new Logging(merged); + } + + private static String json(Object value) { + try { + return MAPPER.writeValueAsString(value); + } catch (JsonProcessingException e) { + throw new AwsException("InternalFailure", "Could not serialize the update parameter", 500); + } + } + + /** The log types a {@link Logging} setting enables; empty for a null setting. */ + public static Set enabledLogTypes(Logging logging) { + Set enabled = new HashSet<>(); + if (logging != null && logging.getClusterLogging() != null) { + for (LogSetup setup : logging.getClusterLogging()) { + if (setup != null && setup.getTypes() != null && Boolean.TRUE.equals(setup.getEnabled())) { + enabled.addAll(setup.getTypes()); + } + } + } + return enabled; + } + + /** EKS refuses an endpoint update that leaves both endpoints off or changes nothing. */ + private static void requireEndpointChange(boolean stored, Boolean storedPublic, Boolean storedPrivate, + List storedCidrs, Boolean publicAccess, Boolean privateAccess, + List cidrs) { + if (Boolean.FALSE.equals(publicAccess) && Boolean.FALSE.equals(privateAccess)) { + throw new AwsException("InvalidParameterException", + "You must enable private access to disable public access", 400); + } + if (stored && publicAccess.equals(storedPublic) && privateAccess.equals(storedPrivate) + && new HashSet<>(cidrs).equals(new HashSet<>(storedCidrs))) { + throw new AwsException("InvalidParameterException", + "Cluster is already at the desired configuration with endpointPrivateAccess: " + privateAccess + + " , endpointPublicAccess: " + publicAccess + + ", and Public Endpoint Restrictions: [" + String.join(",", cidrs) + "]", 400); + } + } + + private static void requireSameMembers(String member, List requested, List current) { + if (requested != null && !new HashSet<>(requested).equals(new HashSet<>(current == null ? List.of() : current))) { + throw new AwsException("InvalidParameterException", + "Floci does not support changing " + member + " through UpdateClusterConfig", 400); + } + } + + private static void requireForwardAuthenticationMode(String current, String requested) { + Integer to = AUTHENTICATION_MODE_RANK.get(requested); + if (to == null) { + throw new AwsException("InvalidParameterException", "Invalid authenticationMode", 400); + } + Integer from = AUTHENTICATION_MODE_RANK.get(current); + // EKS moves the mode one step forward only: CONFIG_MAP, API_AND_CONFIG_MAP, API. + if (from == null || to != from + 1) { + throw new AwsException("InvalidParameterException", + "Unsupported authentication mode update from " + current + " to " + requested, 400); + } + } + /** The cluster {@code name} in the request's Region. */ public Cluster describeCluster(String name) { Cluster cluster = storage.get(requestClusterKey(name)) @@ -1741,6 +1947,25 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun return vpcId; } + /** The public access CIDR checks CreateCluster and UpdateClusterConfig share. */ + private static void requireValidPublicAccessCidrs(List cidrs, String ipFamily) { + if (cidrs == null) { + return; + } + for (String cidr : cidrs) { + if (!SecurityGroupPolicy.validCidr(cidr)) { + throw new AwsException("InvalidParameterException", + "The specified parameter resourcesVpcConfig.publicAccessCidrs is not valid: " + + cidr, 400); + } + if (cidr.contains(":") && !"ipv6".equals(ipFamily)) { + throw new AwsException("InvalidParameterException", + "The specified parameter resourcesVpcConfig.publicAccessCidrs is not valid: " + + cidr + ". IPv6 blocks cannot be added to IPv4 clusters.", 400); + } + } + } + private ResourcesVpcConfig buildVpcConfigResponse(ResourcesVpcConfig request, String resolvedVpcId, String ipFamily) { ResourcesVpcConfig response = new ResourcesVpcConfig(); @@ -1757,29 +1982,16 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun request.getEndpointPublicAccess() != null ? request.getEndpointPublicAccess() : Boolean.TRUE); response.setEndpointPrivateAccess( request.getEndpointPrivateAccess() != null ? request.getEndpointPrivateAccess() : Boolean.FALSE); - if (request.getPublicAccessCidrs() != null) { - for (String cidr : request.getPublicAccessCidrs()) { - if (!SecurityGroupPolicy.validCidr(cidr)) { - throw new AwsException("InvalidParameterException", - "The specified parameter resourcesVpcConfig.publicAccessCidrs is not valid: " - + cidr, 400); - } - if (cidr.contains(":") && !"ipv6".equals(ipFamily)) { - throw new AwsException("InvalidParameterException", - "The specified parameter resourcesVpcConfig.publicAccessCidrs is not valid: " - + cidr + ". IPv6 blocks cannot be added to IPv4 clusters.", 400); - } - } - } + requireValidPublicAccessCidrs(request.getPublicAccessCidrs(), ipFamily); response.setPublicAccessCidrs( - request.getPublicAccessCidrs() != null ? request.getPublicAccessCidrs() : List.of("0.0.0.0/0")); + request.getPublicAccessCidrs() != null ? request.getPublicAccessCidrs() : DEFAULT_PUBLIC_ACCESS_CIDRS); } else { response.setSubnetIds(List.of()); response.setSecurityGroupIds(List.of()); response.setVpcId(""); response.setEndpointPublicAccess(Boolean.TRUE); response.setEndpointPrivateAccess(Boolean.FALSE); - response.setPublicAccessCidrs(List.of("0.0.0.0/0")); + response.setPublicAccessCidrs(DEFAULT_PUBLIC_ACCESS_CIDRS); } return response; } diff --git a/src/main/java/io/floci/aws/services/eks/model/UpdateClusterConfigRequest.java b/src/main/java/io/floci/aws/services/eks/model/UpdateClusterConfigRequest.java new file mode 100644 index 0000000000..c460b900db --- /dev/null +++ b/src/main/java/io/floci/aws/services/eks/model/UpdateClusterConfigRequest.java @@ -0,0 +1,16 @@ +package io.floci.aws.services.eks.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.quarkus.runtime.annotations.RegisterForReflection; + +/** + * The members of UpdateClusterConfig that floci applies. The REST controller refuses any other member. + */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public record UpdateClusterConfigRequest( + ResourcesVpcConfig resourcesVpcConfig, + Logging logging, + AccessConfig accessConfig, + String clientRequestToken +) {} diff --git a/src/test/java/io/floci/aws/services/eks/EksEncryptionLoggingIntegrationTest.java b/src/test/java/io/floci/aws/services/eks/EksEncryptionLoggingIntegrationTest.java index 8550d3d0c6..5f37ec952d 100644 --- a/src/test/java/io/floci/aws/services/eks/EksEncryptionLoggingIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/eks/EksEncryptionLoggingIntegrationTest.java @@ -1,10 +1,15 @@ package io.floci.aws.services.eks; import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.ValidatableResponse; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import java.util.UUID; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.containsInAnyOrder; @@ -12,7 +17,9 @@ import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasKey; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; +import static org.hamcrest.Matchers.startsWith; @QuarkusTest @TestMethodOrder(MethodOrderer.OrderAnnotation.class) @@ -215,4 +222,141 @@ class EksEncryptionLoggingIntegrationTest { .then().statusCode(200) .body("cluster", not(hasKey("explicitVersion"))); } + + private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/eks-role"; + private static final String LOGGING_AUDIT_ON = + "\"logging\":{\"clusterLogging\":[{\"types\":[\"audit\"],\"enabled\":true}]}"; + + private static String createClusterFrom(String name, String extraMembers) { + given().contentType(JSON) + .body("{\"name\":\"" + name + "\",\"roleArn\":\"" + ROLE_ARN + "\"" + extraMembers + "}") + .when().post("/clusters").then().statusCode(200); + return name; + } + + private static void deleteCluster(String name) { + given().when().delete("/clusters/" + name); + } + + @Test + void updateConfigReturnsALoggingUpdateThatDescribeUpdateFinds() { + String name = createClusterFrom("it-update-config-cluster", ""); + try { + String id = given().contentType(JSON) + .body("{" + LOGGING_AUDIT_ON + "}") + .when().post("/clusters/" + name + "/update-config") + .then().statusCode(200) + .body("update.type", equalTo("LoggingUpdate")) + .body("update.id", notNullValue()) + .extract().path("update.id"); + given().contentType(JSON) + .when().get("/clusters/" + name + "/updates/" + id) + .then().statusCode(200) + .body("update.id", equalTo(id)) + .body("update.type", equalTo("LoggingUpdate")); + } finally { + deleteCluster(name); + } + } + + @ParameterizedTest + @CsvSource(delimiter = '|', nullValues = "null", value = { + // two update families in one request + "{\"logging\":{\"clusterLogging\":[{\"types\":[\"audit\"],\"enabled\":true}]}," + + "\"accessConfig\":{\"authenticationMode\":\"API_AND_CONFIG_MAP\"}}" + + "|400|InvalidParameterException|Only one type of update can be allowed.", + "{\"resourcesVpcConfig\":{\"endpointPublicAccess\":true}," + + "\"logging\":{\"clusterLogging\":[{\"types\":[\"audit\"],\"enabled\":true}]}}" + + "|400|InvalidParameterException|Only one type of update can be allowed.", + // a number where the model has a boolean, as createCluster refuses it + "{\"resourcesVpcConfig\":{\"endpointPublicAccess\":1}}|400|SerializationException|null", + // members UpdateClusterConfig does not support here + "{\"kubernetesNetworkConfig\":{\"ipFamily\":\"ipv4\"}}|400|InvalidParameterException|null", + "{\"deletionProtection\":true}|400|InvalidParameterException|null", + "{\"deletionProtection\":true,\"logging\":{\"clusterLogging\":[{\"types\":[\"audit\"],\"enabled\":true}]}}" + + "|400|InvalidParameterException|null", + // accessConfig: unknown mode, and a move from API_AND_CONFIG_MAP back to CONFIG_MAP + "{\"accessConfig\":{\"authenticationMode\":\"BOGUS\"}}|400|InvalidParameterException|null", + "{\"accessConfig\":{\"authenticationMode\":\"CONFIG_MAP\"}}|400|InvalidParameterException|null" + }) + void updateConfigRefusesWhatAwsRefuses(String body, int status, String type, String message) { + String name = createClusterFrom("it-update-refuse-" + UUID.randomUUID(), + ",\"accessConfig\":{\"authenticationMode\":\"API_AND_CONFIG_MAP\"}"); + try { + ValidatableResponse response = given().contentType(JSON) + .body(body) + .when().post("/clusters/" + name + "/update-config") + .then().statusCode(status).body("__type", equalTo(type)); + if (message != null) { + response.body("message", equalTo(message)); + } + } finally { + deleteCluster(name); + } + } + + @Test + void updateConfigWithTheSameClientRequestTokenReturnsTheSameUpdate() { + String name = createClusterFrom("it-update-idempotent-" + UUID.randomUUID(), ""); + try { + String body = "{\"clientRequestToken\":\"token-1\"," + LOGGING_AUDIT_ON + "}"; + String first = given().contentType(JSON).body(body) + .when().post("/clusters/" + name + "/update-config") + .then().statusCode(200).extract().path("update.id"); + given().contentType(JSON).body(body) + .when().post("/clusters/" + name + "/update-config") + .then().statusCode(200).body("update.id", equalTo(first)); + given().contentType(JSON) + .when().get("/clusters/" + name + "/updates/" + first) + .then().statusCode(200).body("update.id", equalTo(first)); + } finally { + deleteCluster(name); + } + } + + @Test + void updateConfigRecordsCidrsAsJsonRefusesNoOpsAndScopesDescribeUpdateToTheCluster() { + String name = createClusterFrom("it-update-noop-" + UUID.randomUUID(), ""); + try { + String cidrs = "\"publicAccessCidrs\":[\"203.0.113.5/32\"]"; + given().contentType(JSON) + .body("{\"resourcesVpcConfig\":{\"endpointPublicAccess\":true," + cidrs + "}}") + .when().post("/clusters/" + name + "/update-config") + .then().statusCode(200) + .body("update.type", equalTo("EndpointAccessUpdate")) + .body("update.params.find { it.type == 'PublicAccessCidrs' }.value", + equalTo("[\"203.0.113.5/32\"]")); + String loggingId = given().contentType(JSON).body("{" + LOGGING_AUDIT_ON + "}") + .when().post("/clusters/" + name + "/update-config") + .then().statusCode(200).extract().path("update.id"); + Object before = given().when().get("/clusters/" + name).then().statusCode(200).extract().path("cluster"); + + // both endpoints off + given().contentType(JSON) + .body("{\"resourcesVpcConfig\":{\"endpointPublicAccess\":false,\"endpointPrivateAccess\":false}}") + .when().post("/clusters/" + name + "/update-config") + .then().statusCode(400).body("__type", equalTo("InvalidParameterException")); + // the stored flags and CIDRs again + given().contentType(JSON) + .body("{\"resourcesVpcConfig\":{\"endpointPublicAccess\":true," + + "\"endpointPrivateAccess\":false," + cidrs + "}}") + .when().post("/clusters/" + name + "/update-config") + .then().statusCode(400).body("__type", equalTo("InvalidParameterException")) + .body("message", startsWith("Cluster is already at the desired configuration")); + // api logs are already off + given().contentType(JSON) + .body("{\"logging\":{\"clusterLogging\":[{\"types\":[\"api\"],\"enabled\":false}]}}") + .when().post("/clusters/" + name + "/update-config") + .then().statusCode(400).body("__type", equalTo("InvalidParameterException")) + .body("message", equalTo("No changes needed for the logging config provided")); + given().when().get("/clusters/" + name).then().statusCode(200).body("cluster", equalTo(before)); + + given().contentType(JSON) + .when().get("/clusters/" + name + "/updates/" + loggingId + "?addonName=vpc-cni") + .then().statusCode(404).body("__type", equalTo("ResourceNotFoundException")) + .body("message", equalTo("No update: " + loggingId + " found for addon: vpc-cni")); + } finally { + deleteCluster(name); + } + } } diff --git a/src/test/java/io/floci/aws/services/eks/EksServiceTest.java b/src/test/java/io/floci/aws/services/eks/EksServiceTest.java index 9b5a0d1376..050e7d06a1 100644 --- a/src/test/java/io/floci/aws/services/eks/EksServiceTest.java +++ b/src/test/java/io/floci/aws/services/eks/EksServiceTest.java @@ -26,6 +26,7 @@ import io.floci.aws.services.ec2.model.SecurityGroup; import io.floci.aws.services.ec2.model.Tag; import io.floci.aws.services.ec2.model.Vpc; import io.floci.aws.services.ec2.portforward.Ec2PortForwardManager; +import io.floci.aws.services.eks.model.AccessConfig; import io.floci.aws.services.eks.model.BlockStorage; import io.floci.aws.services.eks.model.Cluster; import io.floci.aws.services.eks.model.ClusterIdentity; @@ -49,6 +50,8 @@ import io.floci.aws.services.eks.model.OidcIdentity; import io.floci.aws.services.eks.model.Provider; import io.floci.aws.services.eks.model.ResourcesVpcConfig; import io.floci.aws.services.eks.model.StorageConfig; +import io.floci.aws.services.eks.model.Update; +import io.floci.aws.services.eks.model.UpdateClusterConfigRequest; import io.floci.aws.testing.ThreadStates; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -918,6 +921,69 @@ class EksServiceTest { assertTrue(eksService.listClusters().isEmpty()); } + @Test + void updateClusterConfigRefusesBadPublicAccessCidrsOnAnIpv4ClusterAndChangesNothing() { + EksAddonService addons = mock(EksAddonService.class); + Update recorded = new Update("u", "Successful", "EndpointAccessUpdate", List.of(), 0, List.of()); + when(addons.recordUpdate(any(), anyString(), any(), any(), any())).thenReturn(recorded); + EksService service = new EksService(storageFactory, testConfig(), regionResolver, null, ec2Service, + new EksOidcService(storageFactory, new ObjectMapper()), mock(EksAccessEntryService.class), + mock(EksPodIdentityAssociationService.class), addons); + CreateClusterRequest create = new CreateClusterRequest(); + create.setName("cidr-cluster"); + create.setRoleArn("arn:aws:iam::000000000000:role/eks-role"); + service.createCluster(create); + for (String cidr : List.of("10.0.0.0/33", "::/0")) { + ResourcesVpcConfig vpc = new ResourcesVpcConfig(); + vpc.setEndpointPublicAccess(false); + vpc.setPublicAccessCidrs(List.of(cidr)); + AwsException e = assertThrows(AwsException.class, () -> service.updateClusterConfig( + "cidr-cluster", new UpdateClusterConfigRequest(vpc, null, null, null)), cidr); + assertEquals("InvalidParameterException", e.getErrorCode(), cidr); + ResourcesVpcConfig stored = service.describeCluster("cidr-cluster").getResourcesVpcConfig(); + assertEquals(Boolean.TRUE, stored.getEndpointPublicAccess(), cidr); + assertEquals(List.of("0.0.0.0/0"), stored.getPublicAccessCidrs(), cidr); + } + verify(addons, never()).recordUpdate(any(), anyString(), any(), any(), any()); + } + + @Test + void updateClusterConfigMovesTheAuthenticationModeOneStepForwardOnly() { + EksAddonService addons = mock(EksAddonService.class); + Update recorded = new Update("u", "Successful", "AuthenticationModeUpdate", List.of(), 0, List.of()); + when(addons.recordUpdate(any(), anyString(), any(), any(), any())).thenReturn(recorded); + EksService service = new EksService(storageFactory, testConfig(), regionResolver, null, ec2Service, + new EksOidcService(storageFactory, new ObjectMapper()), mock(EksAccessEntryService.class), + mock(EksPodIdentityAssociationService.class), addons); + List modes = List.of("CONFIG_MAP", "API_AND_CONFIG_MAP", "API"); + for (int from = 0; from < modes.size(); from++) { + for (int to = 0; to < modes.size(); to++) { + String pair = modes.get(from) + " to " + modes.get(to); + String name = "mode-" + from + "-" + to; + CreateClusterRequest create = new CreateClusterRequest(); + create.setName(name); + create.setRoleArn("arn:aws:iam::000000000000:role/eks-role"); + create.setAccessConfig(new AccessConfig(modes.get(from), null)); + service.createCluster(create); + UpdateClusterConfigRequest request = new UpdateClusterConfigRequest( + null, null, new AccessConfig(modes.get(to), null), null); + if (to == from + 1) { + service.updateClusterConfig(name, request); + assertEquals(modes.get(to), service.describeCluster(name).getAccessConfig() + .authenticationMode(), pair); + } else { + AwsException e = assertThrows(AwsException.class, + () -> service.updateClusterConfig(name, request), pair); + assertEquals("InvalidParameterException", e.getErrorCode(), pair); + assertEquals("Unsupported authentication mode update from " + pair, + e.getMessage(), pair); + assertEquals(modes.get(from), service.describeCluster(name).getAccessConfig() + .authenticationMode(), pair); + } + } + } + } + @Test void deleteClusterDeletesAddons() { StorageFactory storageFactory = new StorageFactory(null, null) {