diff --git a/Makefile b/Makefile index 368db76701..90ef94af38 100644 --- a/Makefile +++ b/Makefile @@ -23,6 +23,8 @@ # model by tools/aws/regen_apigateway_shapes.py. # src/main/resources/aws/ecs-request-shapes.json is generated from botocore's ECS model # by tools/aws/regen_ecs_shapes.py. +# src/main/resources/aws/eks-request-shapes.json is generated from botocore's EKS model +# by tools/aws/regen_eks_shapes.py. # src/main/resources/aws/organizations-request-shapes.json is generated from botocore's Organizations # model by tools/aws/regen_organizations_shapes.py. # src/main/resources/aws/ecr-request-shapes.json, the ECR request constraints, is generated @@ -307,6 +309,7 @@ aws-data-sync-botocore: ## Regenerate only the AWS data derived from botocore, s $(PYTHON) tools/aws/regen_apigateway_shapes.py $(PYTHON) tools/aws/regen_apigateway_documentation_shapes.py $(PYTHON) tools/aws/regen_ecs_shapes.py + $(PYTHON) tools/aws/regen_eks_shapes.py $(PYTHON) tools/aws/regen_organizations_shapes.py $(PYTHON) tools/aws/regen_emr_serverless_shapes.py $(PYTHON) tools/aws/regen_query_services.py @@ -464,6 +467,12 @@ aws-data-check-botocore: ## The AWS data derived from botocore must match a fres echo " Run 'make aws-data-sync' and commit the result."; \ exit 1; \ } + @$(PYTHON) tools/aws/regen_eks_shapes.py --check || { \ + echo ""; \ + echo "error: src/main/resources/aws/eks-request-shapes.json is out of date."; \ + echo " Run 'make aws-data-sync' and commit the result."; \ + exit 1; \ + } @$(PYTHON) tools/aws/regen_organizations_shapes.py --check || { \ echo ""; \ echo "error: src/main/resources/aws/organizations-request-shapes.json is out of date."; \ diff --git a/docs/services/eks.md b/docs/services/eks.md index b043bd138e..a99da8b855 100644 --- a/docs/services/eks.md +++ b/docs/services/eks.md @@ -5,6 +5,26 @@ EKS uses a standard REST API with JSON bodies: not the JSON 1.1 (`X-Amz-Target`) or Query protocol. +## Cluster request IAM conditions + +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. +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 +conditions continue to apply alongside these EKS-specific keys. + +A `CreateCluster` body is checked against botocore's EKS request shapes, vendored by +`tools/aws/regen_eks_shapes.py`, before it is read. A boolean member given anything but a JSON +boolean or the text `true` or `false`, such as `"endpointPublicAccess": 1`, is refused with +`SerializationException`, so it cannot reach a cluster as `true` while its condition key carries +no value. A structure, list or map of the wrong kind is refused the same way. EKS's own wording +for this error has not been measured; Floci answers as the REST JSON services it was measured on do. + ## Supported Operations | Operation | Description | diff --git a/docs/services/iam.md b/docs/services/iam.md index 8618e563a4..ddedda7b8a 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -3144,6 +3144,12 @@ floci populates: `ForAllValues:StringEquals` with `Null` set to `false` to require every change to match. The actions, the request members, their botocore shapes and the request protocol come from the same `request-condition-keys.json`, and Route 53 spells the names as its `DNSName` shape. +- `eks:authenticationMode`, `eks:bootstrapClusterCreatorAdminPermissions`, `eks:endpointPrivateAccess` and + `eks:endpointPublicAccess`: the `accessConfig` and `resourcesVpcConfig` members a `CreateCluster` request + names, and the three an `UpdateClusterConfig` takes, read from the JSON body as given; a member left out or + given a JSON null is absent, never the cluster's stored value. The actions, members and protocol come from + the same `request-condition-keys.json`. A boolean member given anything but a boolean or its text is refused + before it is read (see [EKS](eks.md)), so the key never misses a value the cluster takes. **Any other condition key is absent from the request context.** A positive scalar operator without `IfExists` on an absent key makes the whole statement *not apply*: it neither matches nor diff --git a/pom.xml b/pom.xml index fac4db1f63..c6e0991d2b 100644 --- a/pom.xml +++ b/pom.xml @@ -596,6 +596,12 @@ ${aws.sdk.version} test + + software.amazon.awssdk + eks + ${aws.sdk.version} + test + software.amazon.awssdk ec2 diff --git a/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java b/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java index cd35eb0407..e2b9328839 100644 --- a/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java +++ b/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java @@ -335,10 +335,11 @@ public class IamConditionContextResolver { } /** - * The keys a request for {@code action} carries in its own members, such as a Redshift DbUser or the record names - * of a Route 53 change batch, read as its namespace's protocol carries them (a Query form, an XML body), from the - * table in {@code request-condition-keys.json}; null when it carries none, or is sent in a protocol no reader here - * reads yet. + * The keys a request for {@code action} carries in its own members, such as a Redshift DbUser, the record names + * of a Route 53 change batch or an EKS cluster's endpoint access, read as its namespace's protocol carries them + * (a Query form, an XML or JSON body), from the table in {@code request-condition-keys.json}; null when it + * carries none, or is sent in a protocol no reader here reads yet. A member left out, or given a JSON null, names + * nothing, so an update takes no value from what the resource already has. */ private Map> requestMemberConditions(String action, ContainerRequestContext ctx) { List keys = RequestConditionKeys.requestKeys(action); @@ -360,12 +361,39 @@ public class IamConditionContextResolver { return null; } values = member -> read.getOrDefault(member, List.of()); + } else if ("json".equals(protocol) || "rest-json".equals(protocol)) { + JsonNode body = PassedRoles.jsonBody(ctx); + if (body == null) { + return null; + } + values = member -> jsonValues(body, member.split("\\."), 0, new ArrayList<>()); } else { return null; } return requestConditions(action, values, requestConditionSpelling(namespace)); } + /** + * The scalar values at {@code path} in a JSON body, a member path as the table writes it, {@code *} stepping into + * every element of a list or map; a JSON null, a structure or a list where the path ends names nothing. + */ + private static List jsonValues(JsonNode node, String[] path, int step, List found) { + if (node == null || node.isNull() || node.isMissingNode()) { + return found; + } + if (step == path.length) { + if (node.isValueNode()) { + found.add(node.asText()); + } + return found; + } + if ("*".equals(path[step])) { + node.forEach(element -> jsonValues(element, path, step + 1, found)); + return found; + } + return jsonValues(node.get(path[step]), path, step + 1, found); + } + /** * Every value {@code values} reads for each member the table names for each key {@code action} takes, spelled by * {@code spelling} as the namespace's service spells the member's shape; null when there are none. 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 edb5cbaf6c..3553681c04 100644 --- a/src/main/java/io/floci/aws/services/eks/EksController.java +++ b/src/main/java/io/floci/aws/services/eks/EksController.java @@ -1,5 +1,9 @@ package io.floci.aws.services.eks; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.PaginatedResult; import io.floci.aws.core.common.Pagination; import io.floci.aws.services.eks.model.Addon; @@ -59,20 +63,36 @@ public class EksController { private final EksAccessEntryService accessEntries; private final EksPodIdentityAssociationService podIdentityAssociations; private final EksAddonService addons; + private final ObjectMapper objectMapper; @Inject public EksController(EksService eksService, EksAccessEntryService accessEntries, EksPodIdentityAssociationService podIdentityAssociations, - EksAddonService addons) { + EksAddonService addons, ObjectMapper objectMapper) { this.eksService = eksService; this.accessEntries = accessEntries; this.podIdentityAssociations = podIdentityAssociations; this.addons = addons; + this.objectMapper = objectMapper; } + /** + * The body is checked against its botocore shape before it is bound, as EKS refuses a member of the wrong JSON + * type: bound first, a number for a boolean member would reach the cluster as {@code true}. A body that passes + * the check but still does not bind is refused the same way. + */ @POST @Path("/clusters") - public Response createCluster(CreateClusterRequest request) { + public Response createCluster(JsonNode body) { + CreateClusterRequest request = null; + if (body != null) { + EksRequestShapes.check("CreateCluster", body); + try { + request = objectMapper.treeToValue(body, CreateClusterRequest.class); + } catch (JsonProcessingException e) { + throw new AwsException("SerializationException", e.getOriginalMessage(), 400); + } + } Cluster cluster = eksService.createCluster(request); return Response.ok(Map.of("cluster", toClusterResponse(cluster))).build(); } diff --git a/src/main/java/io/floci/aws/services/eks/EksRequestShapes.java b/src/main/java/io/floci/aws/services/eks/EksRequestShapes.java new file mode 100644 index 0000000000..17670ace8a --- /dev/null +++ b/src/main/java/io/floci/aws/services/eks/EksRequestShapes.java @@ -0,0 +1,48 @@ +package io.floci.aws.services.eks; + +import com.fasterxml.jackson.databind.JsonNode; +import io.floci.aws.core.common.RequestShapeCheck; +import io.floci.aws.core.common.RequestShapeCheck.ByPosition; + +import java.util.Set; + +/** + * Rejects an EKS request body member of the wrong JSON type before the operation reads it, so a member the model + * types as a boolean, such as {@code resourcesVpcConfig.endpointPublicAccess}, is never a number Floci would read + * as {@code true} while the IAM condition key of the same member carries no value. The body shapes come from the + * vendored {@code aws/eks-request-shapes.json}, generated from botocore's EKS model by + * {@code tools/aws/regen_eks_shapes.py}, and are walked by {@link RequestShapeCheck}. + * + *

EKS's own wording has not been measured. It answers as the REST JSON deserializer API Gateway and SES v2 were + * measured to, a {@code SerializationException} naming the JSON token it could not convert, and only a boolean + * member's scalar is checked: a structure, list or map of the wrong kind is refused too, any other scalar is left to + * the operation, as before. + */ +final class EksRequestShapes { + + static final String RESOURCE_NAME = "aws/eks-request-shapes.json"; + + private static final RequestShapeCheck.Messages MESSAGES = new RequestShapeCheck.Messages( + "SerializationException", + "Start of structure or map found where not expected.", + "Start of list found where not expected", + ByPosition.same("Expected null"), + ByPosition.same("Expected list or null"), + ByPosition.same("Expected map or null"), + "%s can not be converted to a %s", + false, + null, + null, + Set.of("boolean")); + + private static final RequestShapeCheck.Operations OPERATIONS = + new RequestShapeCheck.Operations(RESOURCE_NAME, "EKS request shapes", MESSAGES); + + private EksRequestShapes() { + } + + /** Checks an EKS request body against the body shape of {@code operation}. */ + static void check(String operation, JsonNode request) { + OPERATIONS.check(operation, request); + } +} diff --git a/src/main/resources/aws/eks-request-shapes.json b/src/main/resources/aws/eks-request-shapes.json new file mode 100644 index 0000000000..1f49197eda --- /dev/null +++ b/src/main/resources/aws/eks-request-shapes.json @@ -0,0 +1,1215 @@ +{ + "_source": { + "generator": "tools/aws/regen_eks_shapes.py", + "botocore": "botocore 1.43.118 (installed package)" + }, + "operations": { + "ActivateCertificateAuthority": "ActivateCertificateAuthorityRequest", + "AssociateAccessPolicy": "AssociateAccessPolicyRequest", + "AssociateEncryptionConfig": "AssociateEncryptionConfigRequest", + "AssociateIdentityProviderConfig": "AssociateIdentityProviderConfigRequest", + "CancelUpdate": "CancelUpdateRequest", + "CreateAccessEntry": "CreateAccessEntryRequest", + "CreateAddon": "CreateAddonRequest", + "CreateCapability": "CreateCapabilityRequest", + "CreateCertificateAuthority": "CreateCertificateAuthorityRequest", + "CreateCluster": "CreateClusterRequest", + "CreateEksAnywhereSubscription": "CreateEksAnywhereSubscriptionRequest", + "CreateFargateProfile": "CreateFargateProfileRequest", + "CreateNodegroup": "CreateNodegroupRequest", + "CreatePodIdentityAssociation": "CreatePodIdentityAssociationRequest", + "DeleteAccessEntry": "DeleteAccessEntryRequest", + "DeleteAddon": "DeleteAddonRequest", + "DeleteCapability": "DeleteCapabilityRequest", + "DeleteCertificateAuthority": "DeleteCertificateAuthorityRequest", + "DeleteCluster": "DeleteClusterRequest", + "DeleteEksAnywhereSubscription": "DeleteEksAnywhereSubscriptionRequest", + "DeleteFargateProfile": "DeleteFargateProfileRequest", + "DeleteNodegroup": "DeleteNodegroupRequest", + "DeletePodIdentityAssociation": "DeletePodIdentityAssociationRequest", + "DeregisterCluster": "DeregisterClusterRequest", + "DescribeAccessEntry": "DescribeAccessEntryRequest", + "DescribeAddon": "DescribeAddonRequest", + "DescribeAddonConfiguration": "DescribeAddonConfigurationRequest", + "DescribeAddonVersions": "DescribeAddonVersionsRequest", + "DescribeCapability": "DescribeCapabilityRequest", + "DescribeCertificateAuthority": "DescribeCertificateAuthorityRequest", + "DescribeCluster": "DescribeClusterRequest", + "DescribeClusterVersions": "DescribeClusterVersionsRequest", + "DescribeEksAnywhereSubscription": "DescribeEksAnywhereSubscriptionRequest", + "DescribeFargateProfile": "DescribeFargateProfileRequest", + "DescribeIdentityProviderConfig": "DescribeIdentityProviderConfigRequest", + "DescribeInsight": "DescribeInsightRequest", + "DescribeInsightsRefresh": "DescribeInsightsRefreshRequest", + "DescribeNodegroup": "DescribeNodegroupRequest", + "DescribePodIdentityAssociation": "DescribePodIdentityAssociationRequest", + "DescribeUpdate": "DescribeUpdateRequest", + "DisassociateAccessPolicy": "DisassociateAccessPolicyRequest", + "DisassociateIdentityProviderConfig": "DisassociateIdentityProviderConfigRequest", + "ListAccessEntries": "ListAccessEntriesRequest", + "ListAccessPolicies": "ListAccessPoliciesRequest", + "ListAddons": "ListAddonsRequest", + "ListAssociatedAccessPolicies": "ListAssociatedAccessPoliciesRequest", + "ListCapabilities": "ListCapabilitiesRequest", + "ListCertificateAuthorities": "ListCertificateAuthoritiesRequest", + "ListClusters": "ListClustersRequest", + "ListEksAnywhereSubscriptions": "ListEksAnywhereSubscriptionsRequest", + "ListFargateProfiles": "ListFargateProfilesRequest", + "ListIdentityProviderConfigs": "ListIdentityProviderConfigsRequest", + "ListInsights": "ListInsightsRequest", + "ListNodegroups": "ListNodegroupsRequest", + "ListPodIdentityAssociations": "ListPodIdentityAssociationsRequest", + "ListTagsForResource": "ListTagsForResourceRequest", + "ListUpdates": "ListUpdatesRequest", + "RegisterCluster": "RegisterClusterRequest", + "StartInsightsRefresh": "StartInsightsRefreshRequest", + "TagResource": "TagResourceRequest", + "UntagResource": "UntagResourceRequest", + "UpdateAccessEntry": "UpdateAccessEntryRequest", + "UpdateAddon": "UpdateAddonRequest", + "UpdateCapability": "UpdateCapabilityRequest", + "UpdateClusterConfig": "UpdateClusterConfigRequest", + "UpdateClusterVersion": "UpdateClusterVersionRequest", + "UpdateEksAnywhereSubscription": "UpdateEksAnywhereSubscriptionRequest", + "UpdateNodegroupConfig": "UpdateNodegroupConfigRequest", + "UpdateNodegroupVersion": "UpdateNodegroupVersionRequest", + "UpdatePodIdentityAssociation": "UpdatePodIdentityAssociationRequest" + }, + "shapes": { + "AMITypes": { + "type": "string" + }, + "AccessScope": { + "type": "structure", + "members": { + "type": "AccessScopeType", + "namespaces": "StringList" + } + }, + "AccessScopeType": { + "type": "string" + }, + "AckConfigRequest": { + "type": "structure", + "members": { + "enableCrossNamespace": "BoxedBoolean", + "disabledServices": "AckDisabledServicesList" + } + }, + "AckDisabledServicesList": { + "type": "list", + "member": "AckServiceName" + }, + "AckServiceName": { + "type": "string" + }, + "ActivateCertificateAuthorityRequest": { + "type": "structure", + "members": { + "clientRequestToken": "String" + } + }, + "AddonNamespaceConfigRequest": { + "type": "structure", + "members": { + "namespace": "namespace" + } + }, + "AddonPodIdentityAssociations": { + "type": "structure", + "members": { + "serviceAccount": "String", + "roleArn": "String" + } + }, + "AddonPodIdentityAssociationsList": { + "type": "list", + "member": "AddonPodIdentityAssociations" + }, + "ArgoCdAwsIdcConfigRequest": { + "type": "structure", + "members": { + "idcInstanceArn": "String", + "idcRegion": "String" + } + }, + "ArgoCdConfigRequest": { + "type": "structure", + "members": { + "namespace": "String", + "awsIdc": "ArgoCdAwsIdcConfigRequest", + "rbacRoleMappings": "ArgoCdRoleMappingList", + "networkAccess": "ArgoCdNetworkAccessConfigRequest", + "endpointPrefix": "ArgoCdEndpointPrefix" + } + }, + "ArgoCdEndpointPrefix": { + "type": "string" + }, + "ArgoCdNetworkAccessConfigRequest": { + "type": "structure", + "members": { + "vpceIds": "StringList" + } + }, + "ArgoCdRole": { + "type": "string" + }, + "ArgoCdRoleMapping": { + "type": "structure", + "members": { + "role": "ArgoCdRole", + "identities": "SsoIdentityList" + } + }, + "ArgoCdRoleMappingList": { + "type": "list", + "member": "ArgoCdRoleMapping" + }, + "AssociateAccessPolicyRequest": { + "type": "structure", + "members": { + "policyArn": "String", + "accessScope": "AccessScope" + } + }, + "AssociateEncryptionConfigRequest": { + "type": "structure", + "members": { + "encryptionConfig": "EncryptionConfigList", + "clientRequestToken": "String" + } + }, + "AssociateIdentityProviderConfigRequest": { + "type": "structure", + "members": { + "oidc": "OidcIdentityProviderConfigRequest", + "tags": "TagMap", + "clientRequestToken": "String" + } + }, + "AuthenticationMode": { + "type": "string" + }, + "BlockStorage": { + "type": "structure", + "members": { + "enabled": "BoxedBoolean" + } + }, + "Boolean": { + "type": "boolean" + }, + "BoxedBoolean": { + "type": "boolean" + }, + "BoxedInteger": { + "type": "integer" + }, + "CancelUpdateRequest": { + "type": "structure", + "members": { + "clientRequestToken": "String" + } + }, + "CapabilityConfigurationRequest": { + "type": "structure", + "members": { + "argoCd": "ArgoCdConfigRequest", + "ack": "AckConfigRequest" + } + }, + "CapabilityDeletePropagationPolicy": { + "type": "string" + }, + "CapabilityType": { + "type": "string" + }, + "Capacity": { + "type": "integer" + }, + "CapacityTypes": { + "type": "string" + }, + "Category": { + "type": "string" + }, + "CategoryList": { + "type": "list", + "member": "Category" + }, + "ClusterName": { + "type": "string" + }, + "ComputeConfigRequest": { + "type": "structure", + "members": { + "enabled": "BoxedBoolean", + "nodePools": "StringList", + "nodeRoleArn": "String" + } + }, + "ConnectorConfigProvider": { + "type": "string" + }, + "ConnectorConfigRequest": { + "type": "structure", + "members": { + "roleArn": "String", + "provider": "ConnectorConfigProvider" + } + }, + "ControlPlaneEgressModeType": { + "type": "string" + }, + "ControlPlanePlacementRequest": { + "type": "structure", + "members": { + "groupName": "String", + "spreadLevel": "SpreadLevel" + } + }, + "ControlPlaneScalingConfig": { + "type": "structure", + "members": { + "tier": "ProvisionedControlPlaneTier" + } + }, + "CreateAccessConfigRequest": { + "type": "structure", + "members": { + "bootstrapClusterCreatorAdminPermissions": "BoxedBoolean", + "authenticationMode": "AuthenticationMode" + } + }, + "CreateAccessEntryRequest": { + "type": "structure", + "members": { + "principalArn": "String", + "kubernetesGroups": "StringList", + "tags": "TagMap", + "clientRequestToken": "String", + "username": "String", + "type": "String" + } + }, + "CreateAddonRequest": { + "type": "structure", + "members": { + "addonName": "String", + "addonVersion": "String", + "serviceAccountRoleArn": "RoleArn", + "resolveConflicts": "ResolveConflicts", + "clientRequestToken": "String", + "tags": "TagMap", + "configurationValues": "String", + "podIdentityAssociations": "AddonPodIdentityAssociationsList", + "namespaceConfig": "AddonNamespaceConfigRequest" + } + }, + "CreateCapabilityRequest": { + "type": "structure", + "members": { + "capabilityName": "String", + "clientRequestToken": "String", + "type": "CapabilityType", + "roleArn": "String", + "configuration": "CapabilityConfigurationRequest", + "tags": "TagMap", + "deletePropagationPolicy": "CapabilityDeletePropagationPolicy" + } + }, + "CreateCertificateAuthorityRequest": { + "type": "structure", + "members": { + "clientRequestToken": "String" + } + }, + "CreateClusterRequest": { + "type": "structure", + "members": { + "name": "ClusterName", + "version": "String", + "roleArn": "String", + "resourcesVpcConfig": "VpcConfigRequest", + "kubernetesNetworkConfig": "KubernetesNetworkConfigRequest", + "logging": "Logging", + "clientRequestToken": "String", + "tags": "TagMap", + "encryptionConfig": "EncryptionConfigList", + "outpostConfig": "OutpostConfigRequest", + "accessConfig": "CreateAccessConfigRequest", + "bootstrapSelfManagedAddons": "BoxedBoolean", + "upgradePolicy": "UpgradePolicyRequest", + "zonalShiftConfig": "ZonalShiftConfigRequest", + "remoteNetworkConfig": "RemoteNetworkConfigRequest", + "computeConfig": "ComputeConfigRequest", + "storageConfig": "StorageConfigRequest", + "deletionProtection": "BoxedBoolean", + "controlPlaneScalingConfig": "ControlPlaneScalingConfig", + "kubeApiServerConfig": "KubeApiServerConfigRequest", + "kubeSchedulerConfig": "KubeSchedulerConfigRequest", + "kubeControllerManagerConfig": "KubeControllerManagerConfigRequest" + } + }, + "CreateEksAnywhereSubscriptionRequest": { + "type": "structure", + "members": { + "name": "EksAnywhereSubscriptionName", + "term": "EksAnywhereSubscriptionTerm", + "licenseQuantity": "Integer", + "licenseType": "EksAnywhereSubscriptionLicenseType", + "autoRenew": "Boolean", + "clientRequestToken": "String", + "tags": "TagMap" + } + }, + "CreateFargateProfileRequest": { + "type": "structure", + "members": { + "fargateProfileName": "String", + "podExecutionRoleArn": "String", + "subnets": "StringList", + "selectors": "FargateProfileSelectors", + "clientRequestToken": "String", + "tags": "TagMap" + } + }, + "CreateNodegroupRequest": { + "type": "structure", + "members": { + "nodegroupName": "String", + "scalingConfig": "NodegroupScalingConfig", + "diskSize": "BoxedInteger", + "subnets": "StringList", + "instanceTypes": "StringList", + "amiType": "AMITypes", + "remoteAccess": "RemoteAccessConfig", + "nodeRole": "String", + "labels": "labelsMap", + "taints": "taintsList", + "tags": "TagMap", + "clientRequestToken": "String", + "launchTemplate": "LaunchTemplateSpecification", + "updateConfig": "NodegroupUpdateConfig", + "nodeRepairConfig": "NodeRepairConfig", + "capacityType": "CapacityTypes", + "version": "String", + "releaseVersion": "String", + "warmPoolConfig": "WarmPoolConfig" + } + }, + "CreatePodIdentityAssociationRequest": { + "type": "structure", + "members": { + "namespace": "String", + "serviceAccount": "String", + "roleArn": "String", + "clientRequestToken": "String", + "tags": "TagMap", + "disableSessionTags": "BoxedBoolean", + "targetRoleArn": "String", + "policy": "String" + } + }, + "DeleteAccessEntryRequest": { + "type": "structure", + "members": {} + }, + "DeleteAddonRequest": { + "type": "structure", + "members": {} + }, + "DeleteCapabilityRequest": { + "type": "structure", + "members": {} + }, + "DeleteCertificateAuthorityRequest": { + "type": "structure", + "members": {} + }, + "DeleteClusterRequest": { + "type": "structure", + "members": {} + }, + "DeleteEksAnywhereSubscriptionRequest": { + "type": "structure", + "members": {} + }, + "DeleteFargateProfileRequest": { + "type": "structure", + "members": {} + }, + "DeleteNodegroupRequest": { + "type": "structure", + "members": {} + }, + "DeletePodIdentityAssociationRequest": { + "type": "structure", + "members": {} + }, + "DeregisterClusterRequest": { + "type": "structure", + "members": {} + }, + "DescribeAccessEntryRequest": { + "type": "structure", + "members": {} + }, + "DescribeAddonConfigurationRequest": { + "type": "structure", + "members": {} + }, + "DescribeAddonRequest": { + "type": "structure", + "members": {} + }, + "DescribeAddonVersionsRequest": { + "type": "structure", + "members": {} + }, + "DescribeCapabilityRequest": { + "type": "structure", + "members": {} + }, + "DescribeCertificateAuthorityRequest": { + "type": "structure", + "members": {} + }, + "DescribeClusterRequest": { + "type": "structure", + "members": {} + }, + "DescribeClusterVersionsRequest": { + "type": "structure", + "members": {} + }, + "DescribeEksAnywhereSubscriptionRequest": { + "type": "structure", + "members": {} + }, + "DescribeFargateProfileRequest": { + "type": "structure", + "members": {} + }, + "DescribeIdentityProviderConfigRequest": { + "type": "structure", + "members": { + "identityProviderConfig": "IdentityProviderConfig" + } + }, + "DescribeInsightRequest": { + "type": "structure", + "members": {} + }, + "DescribeInsightsRefreshRequest": { + "type": "structure", + "members": {} + }, + "DescribeNodegroupRequest": { + "type": "structure", + "members": {} + }, + "DescribePodIdentityAssociationRequest": { + "type": "structure", + "members": {} + }, + "DescribeUpdateRequest": { + "type": "structure", + "members": {} + }, + "DisassociateAccessPolicyRequest": { + "type": "structure", + "members": {} + }, + "DisassociateIdentityProviderConfigRequest": { + "type": "structure", + "members": { + "identityProviderConfig": "IdentityProviderConfig", + "clientRequestToken": "String" + } + }, + "EksAnywhereSubscriptionLicenseType": { + "type": "string" + }, + "EksAnywhereSubscriptionName": { + "type": "string" + }, + "EksAnywhereSubscriptionTerm": { + "type": "structure", + "members": { + "duration": "Integer", + "unit": "EksAnywhereSubscriptionTermUnit" + } + }, + "EksAnywhereSubscriptionTermUnit": { + "type": "string" + }, + "ElasticLoadBalancing": { + "type": "structure", + "members": { + "enabled": "BoxedBoolean" + } + }, + "EncryptionConfig": { + "type": "structure", + "members": { + "resources": "StringList", + "provider": "Provider" + } + }, + "EncryptionConfigList": { + "type": "list", + "member": "EncryptionConfig" + }, + "EtcdPlacementRequest": { + "type": "structure", + "members": { + "spreadLevel": "SpreadLevel" + } + }, + "FargateProfileLabel": { + "type": "map", + "value": "String" + }, + "FargateProfileSelector": { + "type": "structure", + "members": { + "namespace": "String", + "labels": "FargateProfileLabel" + } + }, + "FargateProfileSelectors": { + "type": "list", + "member": "FargateProfileSelector" + }, + "HorizontalPodAutoscalerControllerConfigRequest": { + "type": "structure", + "members": { + "horizontalPodAutoscalerSyncPeriod": "String" + } + }, + "IdentityProviderConfig": { + "type": "structure", + "members": { + "type": "String", + "name": "String" + } + }, + "InsightStatusValue": { + "type": "string" + }, + "InsightStatusValueList": { + "type": "list", + "member": "InsightStatusValue" + }, + "InsightsFilter": { + "type": "structure", + "members": { + "categories": "CategoryList", + "kubernetesVersions": "StringList", + "statuses": "InsightStatusValueList" + } + }, + "Integer": { + "type": "integer" + }, + "IpFamily": { + "type": "string" + }, + "KubeApiServerConfigRequest": { + "type": "structure", + "members": { + "eventTtl": "String", + "serviceNodePortRange": "ServiceNodePortRange" + } + }, + "KubeControllerManagerConfigRequest": { + "type": "structure", + "members": { + "podGcControllerConfig": "PodGcControllerConfigRequest", + "horizontalPodAutoscalerControllerConfig": "HorizontalPodAutoscalerControllerConfigRequest" + } + }, + "KubeSchedulerConfigRequest": { + "type": "structure", + "members": { + "nodeResourcesFit": "NodeResourcesFitConfig" + } + }, + "KubernetesNetworkConfigRequest": { + "type": "structure", + "members": { + "serviceIpv4Cidr": "String", + "ipFamily": "IpFamily", + "elasticLoadBalancing": "ElasticLoadBalancing" + } + }, + "LaunchTemplateSpecification": { + "type": "structure", + "members": { + "name": "String", + "version": "String", + "id": "String" + } + }, + "ListAccessEntriesRequest": { + "type": "structure", + "members": {} + }, + "ListAccessPoliciesRequest": { + "type": "structure", + "members": {} + }, + "ListAddonsRequest": { + "type": "structure", + "members": {} + }, + "ListAssociatedAccessPoliciesRequest": { + "type": "structure", + "members": {} + }, + "ListCapabilitiesRequest": { + "type": "structure", + "members": {} + }, + "ListCertificateAuthoritiesRequest": { + "type": "structure", + "members": {} + }, + "ListClustersRequest": { + "type": "structure", + "members": {} + }, + "ListEksAnywhereSubscriptionsRequest": { + "type": "structure", + "members": {} + }, + "ListFargateProfilesRequest": { + "type": "structure", + "members": {} + }, + "ListIdentityProviderConfigsRequest": { + "type": "structure", + "members": {} + }, + "ListInsightsMaxResults": { + "type": "integer" + }, + "ListInsightsRequest": { + "type": "structure", + "members": { + "filter": "InsightsFilter", + "maxResults": "ListInsightsMaxResults", + "nextToken": "String" + } + }, + "ListNodegroupsRequest": { + "type": "structure", + "members": {} + }, + "ListPodIdentityAssociationsRequest": { + "type": "structure", + "members": {} + }, + "ListTagsForResourceRequest": { + "type": "structure", + "members": {} + }, + "ListUpdatesRequest": { + "type": "structure", + "members": {} + }, + "LogSetup": { + "type": "structure", + "members": { + "types": "LogTypes", + "enabled": "BoxedBoolean" + } + }, + "LogSetups": { + "type": "list", + "member": "LogSetup" + }, + "LogType": { + "type": "string" + }, + "LogTypes": { + "type": "list", + "member": "LogType" + }, + "Logging": { + "type": "structure", + "members": { + "clusterLogging": "LogSetups" + } + }, + "NodeRepairConfig": { + "type": "structure", + "members": { + "enabled": "BoxedBoolean", + "maxUnhealthyNodeThresholdCount": "NonZeroInteger", + "maxUnhealthyNodeThresholdPercentage": "PercentCapacity", + "maxParallelNodesRepairedCount": "NonZeroInteger", + "maxParallelNodesRepairedPercentage": "PercentCapacity", + "nodeRepairConfigOverrides": "NodeRepairConfigOverridesList" + } + }, + "NodeRepairConfigOverrides": { + "type": "structure", + "members": { + "nodeMonitoringCondition": "String", + "nodeUnhealthyReason": "String", + "minRepairWaitTimeMins": "NonZeroInteger", + "repairAction": "RepairAction" + } + }, + "NodeRepairConfigOverridesList": { + "type": "list", + "member": "NodeRepairConfigOverrides" + }, + "NodeResourcesFitConfig": { + "type": "structure", + "members": { + "scoringStrategy": "ScoringStrategy" + } + }, + "NodegroupScalingConfig": { + "type": "structure", + "members": { + "minSize": "ZeroCapacity", + "maxSize": "Capacity", + "desiredSize": "ZeroCapacity" + } + }, + "NodegroupUpdateConfig": { + "type": "structure", + "members": { + "maxUnavailable": "NonZeroInteger", + "maxUnavailablePercentage": "PercentCapacity", + "updateStrategy": "NodegroupUpdateStrategies" + } + }, + "NodegroupUpdateStrategies": { + "type": "string" + }, + "NonZeroInteger": { + "type": "integer" + }, + "OidcIdentityProviderConfigRequest": { + "type": "structure", + "members": { + "identityProviderConfigName": "String", + "issuerUrl": "String", + "clientId": "String", + "usernameClaim": "String", + "usernamePrefix": "String", + "groupsClaim": "String", + "groupsPrefix": "String", + "requiredClaims": "requiredClaimsMap" + } + }, + "OutpostConfigRequest": { + "type": "structure", + "members": { + "outpostArns": "StringList", + "controlPlaneInstanceType": "String", + "controlPlanePlacement": "ControlPlanePlacementRequest", + "etcdInstanceType": "String", + "etcdPlacement": "EtcdPlacementRequest" + } + }, + "PercentCapacity": { + "type": "integer" + }, + "PodGcControllerConfigRequest": { + "type": "structure", + "members": { + "terminatedPodGcThreshold": "TerminatedPodGcThresholdValue" + } + }, + "Provider": { + "type": "structure", + "members": { + "keyArn": "String" + } + }, + "ProvisionedControlPlaneTier": { + "type": "string" + }, + "RegisterClusterRequest": { + "type": "structure", + "members": { + "name": "ClusterName", + "connectorConfig": "ConnectorConfigRequest", + "clientRequestToken": "String", + "tags": "TagMap" + } + }, + "RemoteAccessConfig": { + "type": "structure", + "members": { + "ec2SshKey": "String", + "sourceSecurityGroups": "StringList" + } + }, + "RemoteNetworkConfigRequest": { + "type": "structure", + "members": { + "remoteNodeNetworks": "RemoteNodeNetworkList", + "remotePodNetworks": "RemotePodNetworkList" + } + }, + "RemoteNodeNetwork": { + "type": "structure", + "members": { + "cidrs": "StringList" + } + }, + "RemoteNodeNetworkList": { + "type": "list", + "member": "RemoteNodeNetwork" + }, + "RemotePodNetwork": { + "type": "structure", + "members": { + "cidrs": "StringList" + } + }, + "RemotePodNetworkList": { + "type": "list", + "member": "RemotePodNetwork" + }, + "RepairAction": { + "type": "string" + }, + "ResolveConflicts": { + "type": "string" + }, + "ResourceWeight": { + "type": "structure", + "members": { + "name": "ResourceWeightName", + "weight": "ResourceWeightValue" + } + }, + "ResourceWeightList": { + "type": "list", + "member": "ResourceWeight" + }, + "ResourceWeightName": { + "type": "string" + }, + "ResourceWeightValue": { + "type": "integer" + }, + "RoleArn": { + "type": "string" + }, + "RollbackConfig": { + "type": "structure", + "members": { + "timeoutMinutes": "BoxedInteger" + } + }, + "ScoringStrategy": { + "type": "structure", + "members": { + "type": "ScoringStrategyType", + "resources": "ResourceWeightList" + } + }, + "ScoringStrategyType": { + "type": "string" + }, + "ServiceNodePortRange": { + "type": "structure", + "members": { + "minPort": "Integer", + "maxPort": "Integer" + } + }, + "SpreadLevel": { + "type": "string" + }, + "SsoIdentity": { + "type": "structure", + "members": { + "id": "String", + "type": "SsoIdentityType" + } + }, + "SsoIdentityList": { + "type": "list", + "member": "SsoIdentity" + }, + "SsoIdentityType": { + "type": "string" + }, + "StartInsightsRefreshRequest": { + "type": "structure", + "members": {} + }, + "StorageConfigRequest": { + "type": "structure", + "members": { + "blockStorage": "BlockStorage" + } + }, + "String": { + "type": "string" + }, + "StringList": { + "type": "list", + "member": "String" + }, + "SupportType": { + "type": "string" + }, + "TagMap": { + "type": "map", + "value": "TagValue" + }, + "TagResourceRequest": { + "type": "structure", + "members": { + "tags": "TagMap" + } + }, + "TagValue": { + "type": "string" + }, + "Taint": { + "type": "structure", + "members": { + "key": "taintKey", + "value": "taintValue", + "effect": "TaintEffect" + } + }, + "TaintEffect": { + "type": "string" + }, + "TerminatedPodGcThresholdValue": { + "type": "integer" + }, + "UntagResourceRequest": { + "type": "structure", + "members": {} + }, + "UpdateAccessConfigRequest": { + "type": "structure", + "members": { + "authenticationMode": "AuthenticationMode" + } + }, + "UpdateAccessEntryRequest": { + "type": "structure", + "members": { + "kubernetesGroups": "StringList", + "clientRequestToken": "String", + "username": "String" + } + }, + "UpdateAckConfig": { + "type": "structure", + "members": { + "enableCrossNamespace": "BoxedBoolean", + "disabledServices": "AckDisabledServicesList" + } + }, + "UpdateAddonRequest": { + "type": "structure", + "members": { + "addonVersion": "String", + "serviceAccountRoleArn": "RoleArn", + "resolveConflicts": "ResolveConflicts", + "clientRequestToken": "String", + "configurationValues": "String", + "podIdentityAssociations": "AddonPodIdentityAssociationsList" + } + }, + "UpdateArgoCdConfig": { + "type": "structure", + "members": { + "rbacRoleMappings": "UpdateRoleMappings", + "networkAccess": "ArgoCdNetworkAccessConfigRequest" + } + }, + "UpdateCapabilityConfiguration": { + "type": "structure", + "members": { + "argoCd": "UpdateArgoCdConfig", + "ack": "UpdateAckConfig" + } + }, + "UpdateCapabilityRequest": { + "type": "structure", + "members": { + "roleArn": "String", + "configuration": "UpdateCapabilityConfiguration", + "clientRequestToken": "String", + "deletePropagationPolicy": "CapabilityDeletePropagationPolicy" + } + }, + "UpdateClusterConfigRequest": { + "type": "structure", + "members": { + "resourcesVpcConfig": "VpcConfigRequest", + "logging": "Logging", + "clientRequestToken": "String", + "accessConfig": "UpdateAccessConfigRequest", + "upgradePolicy": "UpgradePolicyRequest", + "zonalShiftConfig": "ZonalShiftConfigRequest", + "computeConfig": "ComputeConfigRequest", + "kubernetesNetworkConfig": "KubernetesNetworkConfigRequest", + "storageConfig": "StorageConfigRequest", + "remoteNetworkConfig": "RemoteNetworkConfigRequest", + "deletionProtection": "BoxedBoolean", + "controlPlaneScalingConfig": "ControlPlaneScalingConfig", + "kubeApiServerConfig": "KubeApiServerConfigRequest", + "kubeSchedulerConfig": "KubeSchedulerConfigRequest", + "kubeControllerManagerConfig": "KubeControllerManagerConfigRequest" + } + }, + "UpdateClusterVersionRequest": { + "type": "structure", + "members": { + "version": "String", + "clientRequestToken": "String", + "force": "Boolean", + "rollbackConfig": "RollbackConfig" + } + }, + "UpdateEksAnywhereSubscriptionRequest": { + "type": "structure", + "members": { + "autoRenew": "Boolean", + "clientRequestToken": "String" + } + }, + "UpdateLabelsPayload": { + "type": "structure", + "members": { + "addOrUpdateLabels": "labelsMap", + "removeLabels": "labelsKeyList" + } + }, + "UpdateNodegroupConfigRequest": { + "type": "structure", + "members": { + "labels": "UpdateLabelsPayload", + "taints": "UpdateTaintsPayload", + "scalingConfig": "NodegroupScalingConfig", + "updateConfig": "NodegroupUpdateConfig", + "nodeRepairConfig": "NodeRepairConfig", + "warmPoolConfig": "WarmPoolConfig", + "clientRequestToken": "String" + } + }, + "UpdateNodegroupVersionRequest": { + "type": "structure", + "members": { + "version": "String", + "releaseVersion": "String", + "launchTemplate": "LaunchTemplateSpecification", + "force": "Boolean", + "clientRequestToken": "String" + } + }, + "UpdatePodIdentityAssociationRequest": { + "type": "structure", + "members": { + "roleArn": "String", + "clientRequestToken": "String", + "disableSessionTags": "BoxedBoolean", + "targetRoleArn": "String", + "policy": "String" + } + }, + "UpdateRoleMappings": { + "type": "structure", + "members": { + "addOrUpdateRoleMappings": "ArgoCdRoleMappingList", + "removeRoleMappings": "ArgoCdRoleMappingList" + } + }, + "UpdateTaintsPayload": { + "type": "structure", + "members": { + "addOrUpdateTaints": "taintsList", + "removeTaints": "taintsList" + } + }, + "UpgradePolicyRequest": { + "type": "structure", + "members": { + "supportType": "SupportType" + } + }, + "VpcConfigRequest": { + "type": "structure", + "members": { + "subnetIds": "StringList", + "securityGroupIds": "StringList", + "endpointPublicAccess": "BoxedBoolean", + "endpointPrivateAccess": "BoxedBoolean", + "publicAccessCidrs": "StringList", + "controlPlaneEgressMode": "ControlPlaneEgressModeType" + } + }, + "WarmPoolConfig": { + "type": "structure", + "members": { + "enabled": "BoxedBoolean", + "minSize": "ZeroCapacity", + "maxGroupPreparedCapacity": "BoxedInteger", + "poolState": "WarmPoolState", + "reuseOnScaleIn": "BoxedBoolean" + } + }, + "WarmPoolState": { + "type": "string" + }, + "ZeroCapacity": { + "type": "integer" + }, + "ZonalShiftConfigRequest": { + "type": "structure", + "members": { + "enabled": "BoxedBoolean" + } + }, + "labelValue": { + "type": "string" + }, + "labelsKeyList": { + "type": "list", + "member": "String" + }, + "labelsMap": { + "type": "map", + "value": "labelValue" + }, + "namespace": { + "type": "string" + }, + "requiredClaimsMap": { + "type": "map", + "value": "requiredClaimsValue" + }, + "requiredClaimsValue": { + "type": "string" + }, + "taintKey": { + "type": "string" + }, + "taintValue": { + "type": "string" + }, + "taintsList": { + "type": "list", + "member": "Taint" + } + } +} diff --git a/src/main/resources/aws/request-condition-keys.json b/src/main/resources/aws/request-condition-keys.json index ec0d9a732a..819cec9364 100644 --- a/src/main/resources/aws/request-condition-keys.json +++ b/src/main/resources/aws/request-condition-keys.json @@ -11,6 +11,17 @@ "ec2-instance-connect:privateIpAddress", "ec2-instance-connect:remotePort" ], + "eks:CreateCluster": [ + "eks:authenticationMode", + "eks:bootstrapClusterCreatorAdminPermissions", + "eks:endpointPrivateAccess", + "eks:endpointPublicAccess" + ], + "eks:UpdateClusterConfig": [ + "eks:authenticationMode", + "eks:endpointPrivateAccess", + "eks:endpointPublicAccess" + ], "lambda:CreateWebFunction": [ "lambda:Request/WebFunctionAuthType" ], @@ -54,6 +65,31 @@ "remotePort" ] }, + "eks:CreateCluster": { + "eks:authenticationMode": [ + "accessConfig.authenticationMode" + ], + "eks:bootstrapClusterCreatorAdminPermissions": [ + "accessConfig.bootstrapClusterCreatorAdminPermissions" + ], + "eks:endpointPrivateAccess": [ + "resourcesVpcConfig.endpointPrivateAccess" + ], + "eks:endpointPublicAccess": [ + "resourcesVpcConfig.endpointPublicAccess" + ] + }, + "eks:UpdateClusterConfig": { + "eks:authenticationMode": [ + "accessConfig.authenticationMode" + ], + "eks:endpointPrivateAccess": [ + "resourcesVpcConfig.endpointPrivateAccess" + ], + "eks:endpointPublicAccess": [ + "resourcesVpcConfig.endpointPublicAccess" + ] + }, "lambda:CreateWebFunction": { "lambda:Request/WebFunctionAuthType": [ "endpointConfig.authType" @@ -87,6 +123,17 @@ } }, "memberShapes": { + "eks:CreateCluster": { + "accessConfig.authenticationMode": "AuthenticationMode", + "accessConfig.bootstrapClusterCreatorAdminPermissions": "BoxedBoolean", + "resourcesVpcConfig.endpointPrivateAccess": "BoxedBoolean", + "resourcesVpcConfig.endpointPublicAccess": "BoxedBoolean" + }, + "eks:UpdateClusterConfig": { + "accessConfig.authenticationMode": "AuthenticationMode", + "resourcesVpcConfig.endpointPrivateAccess": "BoxedBoolean", + "resourcesVpcConfig.endpointPublicAccess": "BoxedBoolean" + }, "lambda:CreateWebFunction": { "endpointConfig.authType": "AuthType" }, @@ -106,6 +153,7 @@ } }, "protocols": { + "eks": "rest-json", "lambda": "rest-json", "redshift": "query", "route53": "rest-xml" diff --git a/src/test/java/io/floci/aws/core/common/EksClusterConditionsIntegrationTest.java b/src/test/java/io/floci/aws/core/common/EksClusterConditionsIntegrationTest.java new file mode 100644 index 0000000000..9f9bf6915c --- /dev/null +++ b/src/test/java/io/floci/aws/core/common/EksClusterConditionsIntegrationTest.java @@ -0,0 +1,205 @@ +package io.floci.aws.core.common; + +import io.floci.aws.testing.AwsTestClients; +import io.floci.aws.testing.EnforcementFixtures; +import io.floci.aws.testing.EnforcementFixtures.UserCredentials; +import io.floci.aws.testing.IamEnforcementProfile; +import io.floci.aws.testing.PartitionCleanup; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.response.ValidatableResponse; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.eks.EksClient; +import software.amazon.awssdk.services.eks.model.Cluster; +import software.amazon.awssdk.services.eks.model.CreateClusterRequest; +import software.amazon.awssdk.services.eks.model.EksException; + +import java.net.URI; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +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.containsString; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +@TestProfile(IamEnforcementProfile.class) +class EksClusterConditionsIntegrationTest { + private static final String ACCOUNT = "000000000000"; + private static final String CONDITIONS = """ + {"StringEquals":{"eks:authenticationMode":"API_AND_CONFIG_MAP","aws:RequestTag/owner":"team"}, + "Bool":{"eks:endpointPublicAccess":"true","eks:endpointPrivateAccess":"true", + "eks:bootstrapClusterCreatorAdminPermissions":"false"}}"""; + + @TestHTTPResource("/") + URI endpoint; + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @ParameterizedTest + @ValueSource(strings = {"authenticationMode", "endpointPublicAccess", "endpointPrivateAccess", "bootstrap"}) + void createRequiresEveryExplicitAttributeAndRetainsRequestTagConditions(String field) { + try (Fixture f = new Fixture()) { + f.policy(createGrant()); + CreateClusterRequest request = f.request(); + Cluster created = f.create(request); + assertEquals("API_AND_CONFIG_MAP", created.accessConfig().authenticationModeAsString()); + assertFalse(created.accessConfig().bootstrapClusterCreatorAdminPermissions()); + assertTrue(created.resourcesVpcConfig().endpointPublicAccess()); + assertTrue(created.resourcesVpcConfig().endpointPrivateAccess()); + assertEquals("team", created.tags().get("owner")); + denied(() -> f.create(changed(f.request(), field, false))); + denied(() -> f.create(changed(f.request(), field, true))); + denied(() -> f.create(f.request().toBuilder().tags(Map.of("owner", "other")).build())); + // All the positive attributes still require PassRole, not just the EKS grant. + f.policy(createGrant(), false); + denied(() -> f.create(f.request())); + } + } + + @Test + void explicitDenySeesFalseAndMissingFieldsRemainAbsent() { + try (Fixture f = new Fixture()) { + f.policy(""" + {"Effect":"Allow","Action":"eks:CreateCluster","Resource":"*"}, + {"Effect":"Deny","Action":"eks:CreateCluster","Resource":"*", + "Condition":{"Bool":{"eks:bootstrapClusterCreatorAdminPermissions":"false"}}}"""); + denied(() -> f.create(f.request())); + f.create(changed(f.request(), "bootstrap", true)); + f.policy(""" + {"Effect":"Allow","Action":"eks:CreateCluster","Resource":"*"}, + {"Effect":"Deny","Action":"eks:CreateCluster","Resource":"*", + "Condition":{"Null":{"eks:authenticationMode":"true"}}}"""); + denied(() -> f.create(changed(f.request(), "authenticationMode", true))); + f.create(f.request()); + } + } + + /** + * A number for a boolean member is refused rather than read as {@code true}, which the condition key of the + * same member would not carry; the boolean and its text both carry it, so the deny holds for either. + */ + @ParameterizedTest + @ValueSource(strings = {"1", "true", "\"true\""}) + void aBooleanMemberIsCheckedAsTheClusterReadsIt(String value) { + try (Fixture f = new Fixture()) { + f.policy(""" + {"Effect":"Allow","Action":"eks:CreateCluster","Resource":"*"}, + {"Effect":"Deny","Action":"eks:CreateCluster","Resource":"*", + "Condition":{"Bool":{"eks:endpointPublicAccess":"true"}}}"""); + String name = "condition-" + UUID.randomUUID(); + ValidatableResponse response = given().port(endpoint.getPort()) + .header("Authorization", auth(f.accessKeyId, "eks")).contentType("application/json") + .body("{\"name\":\"%s\",\"roleArn\":\"%s\",\"resourcesVpcConfig\":{\"endpointPublicAccess\":%s}}" + .formatted(name, f.role, value)) + .post("/clusters").then(); + if ("1".equals(value)) { + response.statusCode(400).body(containsString("SerializationException")); + } else { + response.statusCode(403); + } + assertFalse(f.admin.listClusters(r -> { }).clusters().contains(name)); + } + } + + private static CreateClusterRequest changed(CreateClusterRequest request, String field, boolean omit) { + return switch (field) { + case "authenticationMode" -> request.toBuilder().accessConfig(request.accessConfig().toBuilder() + .authenticationMode(omit ? null : "API").build()).build(); + case "bootstrap" -> request.toBuilder().accessConfig(request.accessConfig().toBuilder() + .bootstrapClusterCreatorAdminPermissions(omit ? null : true).build()).build(); + case "endpointPublicAccess" -> request.toBuilder().resourcesVpcConfig(request.resourcesVpcConfig().toBuilder() + .endpointPublicAccess(omit ? null : false).build()).build(); + case "endpointPrivateAccess" -> request.toBuilder().resourcesVpcConfig(request.resourcesVpcConfig().toBuilder() + .endpointPrivateAccess(omit ? null : false).build()).build(); + default -> throw new IllegalArgumentException(field); + }; + } + + private static String createGrant() { + return """ + {"Effect":"Allow","Action":"eks:CreateCluster","Resource":"*","Condition":%s}""" + .formatted(CONDITIONS); + } + + private static void denied(Runnable call) { + EksException error = assertThrows(EksException.class, call::run); + assertEquals(403, error.statusCode()); + assertEquals("AccessDeniedException", error.awsErrorDetails().errorCode()); + } + + private final class Fixture implements AutoCloseable { + final String user = "eks-condition-" + UUID.randomUUID(); + final String role; + final String accessKeyId; + final EksClient admin; + final EksClient client; + final List clusters = new ArrayList<>(); + + Fixture() { + UserCredentials credentials = EnforcementFixtures.createUser(cleanup, endpoint.getPort(), + auth(ACCOUNT, "iam"), user); + accessKeyId = credentials.accessKeyId(); + role = EnforcementFixtures.createRole(cleanup, endpoint.getPort(), ACCOUNT, "/", user, + EMPTY_POLICY_DOCUMENT); + admin = AwsTestClients.create(EksClient.builder(), ACCOUNT, Region.US_EAST_1, endpoint); + try { + client = AwsTestClients.create(EksClient.builder(), credentials.accessKeyId(), + credentials.secretAccessKey(), Region.US_EAST_1, endpoint); + } catch (RuntimeException e) { + admin.close(); + throw e; + } + } + + void policy(String statements) { + policy(statements, true); + } + + void policy(String statements, boolean passRole) { + EnforcementFixtures.putUserPolicy(endpoint.getPort(), auth(ACCOUNT, "iam"), user, "conditions", + """ + {"Version":"2012-10-17","Statement":[%s, + {"Effect":"Allow","Action":"eks:TagResource","Resource":"*"}%s]}""" + .formatted(statements, passRole ? ",{\"Effect\":\"Allow\",\"Action\":\"iam:PassRole\"," + + "\"Resource\":\"" + role + "\"}" : "")); + } + + CreateClusterRequest request() { + return CreateClusterRequest.builder().name("condition-" + UUID.randomUUID()).roleArn(role) + .resourcesVpcConfig(v -> v.endpointPublicAccess(true).endpointPrivateAccess(true)) + .accessConfig(a -> a.authenticationMode("API_AND_CONFIG_MAP").bootstrapClusterCreatorAdminPermissions(false)) + .tags(Map.of("owner", "team")).build(); + } + + Cluster create(CreateClusterRequest request) { + Cluster cluster = client.createCluster(request).cluster(); + clusters.add(cluster.name()); + return cluster; + } + + @Override + public void close() { + try { + for (String name : clusters) { + admin.deleteCluster(r -> r.name(name)); + } + } finally { + client.close(); + admin.close(); + } + } + } +} diff --git a/src/test/java/io/floci/aws/core/common/IamConditionContextResolverTest.java b/src/test/java/io/floci/aws/core/common/IamConditionContextResolverTest.java index 7441df4273..d915544253 100644 --- a/src/test/java/io/floci/aws/core/common/IamConditionContextResolverTest.java +++ b/src/test/java/io/floci/aws/core/common/IamConditionContextResolverTest.java @@ -79,6 +79,26 @@ class IamConditionContextResolverTest { private IamConditionContextResolver resolver; private ResolvedServiceCatalog serviceCatalog; + @Test + void eksRequestConditionsUseModeledPathsAndLeaveOmissionsAbsent() { + ContainerRequestContext request = mock(ContainerRequestContext.class); + when(request.getProperty("floci.bufferedJsonBody")).thenReturn(json(""" + {"accessConfig":{"authenticationMode":"API","bootstrapClusterCreatorAdminPermissions":false}, + "resourcesVpcConfig":{"endpointPrivateAccess":true,"endpointPublicAccess":false}}""")); + Map> create = resolver.resolve("eks", "eks:CreateCluster", request); + assertEquals(Map.of("eks:authenticationMode", List.of("API"), + "eks:bootstrapClusterCreatorAdminPermissions", List.of("false"), + "eks:endpointPrivateAccess", List.of("true"), "eks:endpointPublicAccess", List.of("false")), create); + Map> update = resolver.resolve("eks", "eks:UpdateClusterConfig", request); + assertEquals(3, update.size()); + assertFalse(update.containsKey("eks:bootstrapClusterCreatorAdminPermissions")); + assertNull(resolver.resolve("eks", "eks:DescribeCluster", request)); + when(request.getProperty("floci.bufferedJsonBody")).thenReturn(json(""" + {"accessConfig":{"authenticationMode":null},"resourcesVpcConfig":{"endpointPrivateAccess":[]}}""")); + assertNull(resolver.resolve("eks", "eks:CreateCluster", request)); + assertNull(resolver.resolve("eks", "eks:UpdateClusterConfig", request)); + } + @SuppressWarnings("unchecked") @BeforeEach void setUp() { diff --git a/src/test/java/io/floci/aws/services/eks/EksClusterManagerTest.java b/src/test/java/io/floci/aws/services/eks/EksClusterManagerTest.java index 9b428ee9a7..750230803b 100644 --- a/src/test/java/io/floci/aws/services/eks/EksClusterManagerTest.java +++ b/src/test/java/io/floci/aws/services/eks/EksClusterManagerTest.java @@ -54,7 +54,6 @@ import io.floci.aws.services.eks.model.CertificateAuthority; import io.floci.aws.services.eks.model.Cluster; import io.floci.aws.services.eks.model.ClusterIdentity; import io.floci.aws.services.eks.model.ClusterOidcKey; -import io.floci.aws.services.eks.model.CreateClusterRequest; import io.floci.aws.services.eks.model.LogSetup; import io.floci.aws.services.eks.model.Logging; import io.floci.aws.services.eks.model.Nodegroup; @@ -5019,10 +5018,11 @@ class EksClusterManagerTest { eksService, Mockito.mock(EksAccessEntryService.class), Mockito.mock(EksPodIdentityAssociationService.class), - Mockito.mock(EksAddonService.class)); + Mockito.mock(EksAddonService.class), + mapper); for (Response response : List.of( - controller.createCluster(new CreateClusterRequest()), + controller.createCluster(mapper.createObjectNode()), controller.describeCluster("wire-cluster"), controller.deleteCluster("wire-cluster"))) { @SuppressWarnings("unchecked") diff --git a/src/test/java/io/floci/aws/services/eks/EksRequestShapesTest.java b/src/test/java/io/floci/aws/services/eks/EksRequestShapesTest.java new file mode 100644 index 0000000000..a41bd4df95 --- /dev/null +++ b/src/test/java/io/floci/aws/services/eks/EksRequestShapesTest.java @@ -0,0 +1,41 @@ +package io.floci.aws.services.eks; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.core.common.AwsException; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class EksRequestShapesTest { + + private final ObjectMapper mapper = new ObjectMapper(); + + @ParameterizedTest + @ValueSource(strings = {"1", "0", "1.5"}) + void aNumberForABooleanMemberIsRefused(String value) { + AwsException error = assertThrows(AwsException.class, () -> EksRequestShapes.check("CreateCluster", + mapper.readTree("{\"resourcesVpcConfig\":{\"endpointPublicAccess\":" + value + "}}"))); + assertEquals("SerializationException", error.getErrorCode()); + assertEquals(400, error.getHttpStatus()); + assertTrue(error.getMessage().contains("Boolean"), error.getMessage()); + } + + @ParameterizedTest + @ValueSource(strings = {"true", "false", "\"TRUE\"", "\"false\"", "null"}) + void aBooleanItsTextOrNullPasses(String value) { + assertDoesNotThrow(() -> EksRequestShapes.check("CreateCluster", + mapper.readTree("{\"accessConfig\":{\"bootstrapClusterCreatorAdminPermissions\":" + value + "}}"))); + } + + @ParameterizedTest + @ValueSource(strings = {"\"public\"", "[]"}) + void aScalarOrListForAStructureIsRefused(String value) { + AwsException error = assertThrows(AwsException.class, () -> EksRequestShapes.check("CreateCluster", + mapper.readTree("{\"name\":\"c\",\"resourcesVpcConfig\":" + value + "}"))); + assertEquals("SerializationException", error.getErrorCode()); + } +} diff --git a/tools/aws/regen_eks_shapes.py b/tools/aws/regen_eks_shapes.py new file mode 100644 index 0000000000..f116fd276a --- /dev/null +++ b/tools/aws/regen_eks_shapes.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python3 +"""Regenerate src/main/resources/aws/eks-request-shapes.json from botocore's EKS model. + +EKS refuses a request body member of the wrong JSON type before it validates anything. The Java side +(`EksRequestShapes`) needs the body shapes to do the same, so this script keeps only what that check reads: +the input shape of every operation and, for every shape reachable from one, its type and the shapes of its +members, list elements or map values. A cluster's endpoint access and creator admin flags are booleans there, +which is what keeps a number from reaching a cluster as `true` while the IAM condition keys of the same +members carry no value. + +The model is botocore's `eks/2017-11-01/service-2.json` (Apache-2.0, https://github.com/boto/botocore). It is +located, in order, at `--botocore-data`, the `local/aws/botocore` checkout, then the installed `botocore` +package, which `requirements.txt` pins so CI regenerates the same bytes. + +Run from anywhere in the repo: + python3 tools/aws/regen_eks_shapes.py # rewrite the vendored file in place + python3 tools/aws/regen_eks_shapes.py --check # exit 1 when the vendored file is stale +""" +from __future__ import annotations + +import sys +from pathlib import Path + +import request_shapes + +OUTPUT = request_shapes.REPO_ROOT / "src/main/resources/aws/eks-request-shapes.json" +MODEL = Path("eks/2017-11-01") + + +def main(argv: list[str] | None = None) -> int: + return request_shapes.main(argv, script=__file__, model=MODEL, output=OUTPUT, description=__doc__) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/aws/regen_request_condition_keys.py b/tools/aws/regen_request_condition_keys.py index 0d6f21a175..dc7a51d63d 100644 --- a/tools/aws/regen_request_condition_keys.py +++ b/tools/aws/regen_request_condition_keys.py @@ -4,6 +4,9 @@ Some service condition keys take their value from the request, or from the resource the request acts on before it. `SERVICES` names, for each namespace, the keys read and where: +- `eks`: a CreateCluster or UpdateClusterConfig request is checked with the access configuration and endpoint + flags it names in its JSON body, as `eks:authenticationMode`, `eks:bootstrapClusterCreatorAdminPermissions`, + `eks:endpointPrivateAccess` and `eks:endpointPublicAccess`; a member it leaves out names nothing. - `lambda`: a Lambda Web Functions request is checked with the endpoint's authType as `lambda:Request/WebFunctionAuthType`, the one the request names, and `lambda:Resource/WebFunctionAuthType`, the one the endpoint has before the request, read from the stored endpoint. @@ -72,6 +75,17 @@ FLAT_PROTOCOLS = ("query", "ec2") # carries it, each key read from the stored resource, and the actions that take a key their request does not # carry, with the reason. SERVICES = { + "eks": { + "model": "eks", + "request": { + "eks:authenticationMode": "authenticationMode", + "eks:bootstrapClusterCreatorAdminPermissions": "bootstrapClusterCreatorAdminPermissions", + "eks:endpointPrivateAccess": "endpointPrivateAccess", + "eks:endpointPublicAccess": "endpointPublicAccess", + }, + "stored": (), + "not_in_request": {}, + }, "lambda": { "model": "lambda-web", "request": {"lambda:Request/WebFunctionAuthType": "authType"}, diff --git a/tools/aws/request_shapes.py b/tools/aws/request_shapes.py index 542962cff0..a056fa2811 100644 --- a/tools/aws/request_shapes.py +++ b/tools/aws/request_shapes.py @@ -1,8 +1,8 @@ """Shared generator for the vendored request shapes a service's request check reads. `regen_dynamodb_shapes.py`, `regen_sesv2_shapes.py`, `regen_apigateway_shapes.py`, -`regen_ecs_shapes.py` and `regen_organizations_shapes.py` each name a botocore model and an output -file and hand the rest to `main()`. `regen_resource_groups_shapes.py`, `regen_logs_delivery_shapes.py` and +`regen_ecs_shapes.py`, `regen_eks_shapes.py` and `regen_organizations_shapes.py` each name a botocore model +and an output file and hand the rest to `main()`. `regen_resource_groups_shapes.py`, `regen_logs_delivery_shapes.py` and `regen_ecr_shapes.py` vendor constraints as well, through `build_constraints()`. The output keeps only what `RequestShapeModel` reads: the input shape of every operation, reduced to the members carried in the JSON body, and for every shape reachable from one, its type and the shapes of its members, list elements or map values. diff --git a/tools/aws/test_regen_request_condition_keys.py b/tools/aws/test_regen_request_condition_keys.py index 215d09f673..9a1958ba16 100644 --- a/tools/aws/test_regen_request_condition_keys.py +++ b/tools/aws/test_regen_request_condition_keys.py @@ -132,7 +132,8 @@ def test_the_vendored_table_covers_its_namespaces(): "route53:ChangeResourceRecordSets"] assert document["memberShapes"]["route53:ChangeResourceRecordSets"][ "ChangeBatch.Changes.Change.ResourceRecordSet.Name"] == "DNSName" - assert document["protocols"] == {"lambda": "rest-json", "redshift": "query", "route53": "rest-xml"} + assert document["protocols"] == {"eks": "rest-json", "lambda": "rest-json", + "redshift": "query", "route53": "rest-xml"} @pytest.mark.parametrize("changed", [ @@ -181,3 +182,18 @@ def run_aggregate_gate(tmp_path, changed, fail): ["make", "--no-print-directory", "iam-data-verify", "CHANGED=" + changed, "MAKE=" + str(recursive_make)], cwd=OUTPUT.parents[4], capture_output=True, text=True, check=False) + + +def test_eks_cluster_request_members_and_create_only_bootstrap_key(): + document = json.loads(OUTPUT.read_text()) + create = document["members"]["eks:CreateCluster"] + assert create == { + "eks:authenticationMode": ["accessConfig.authenticationMode"], + "eks:bootstrapClusterCreatorAdminPermissions": ["accessConfig.bootstrapClusterCreatorAdminPermissions"], + "eks:endpointPrivateAccess": ["resourcesVpcConfig.endpointPrivateAccess"], + "eks:endpointPublicAccess": ["resourcesVpcConfig.endpointPublicAccess"], + } + assert document["members"]["eks:UpdateClusterConfig"] == { + key: paths for key, paths in create.items() if key != "eks:bootstrapClusterCreatorAdminPermissions" + } + assert "eks:DescribeCluster" not in document["actions"] diff --git a/tools/aws/test_request_shapes.py b/tools/aws/test_request_shapes.py index 61ed6d383a..39ee213a65 100644 --- a/tools/aws/test_request_shapes.py +++ b/tools/aws/test_request_shapes.py @@ -1,6 +1,6 @@ """Tests for request_shapes, the generator behind regen_dynamodb_shapes, regen_sesv2_shapes, regen_apigateway_shapes, -regen_ecs_shapes, regen_organizations_shapes and regen_emr_serverless_shapes, and of the constraints -regen_resource_groups_shapes, regen_ecr_shapes, regen_iam_shapes and regen_sts_shapes vendor. +regen_ecs_shapes, regen_eks_shapes, regen_organizations_shapes and regen_emr_serverless_shapes, and of the +constraints regen_resource_groups_shapes, regen_ecr_shapes, regen_iam_shapes and regen_sts_shapes vendor. Each generator names a model, an output and, for the constraints flavour, its operations, and hands the rest here, so what any one of them does differently is a constant and what they all do is @@ -26,6 +26,7 @@ import regen_cur_shapes import regen_dynamodb_shapes import regen_ecr_shapes import regen_ecs_shapes +import regen_eks_shapes import regen_emr_serverless_shapes import regen_iam_shapes import regen_cloudfront_keyvaluestore_shapes @@ -226,6 +227,7 @@ def test_load_model_without_a_service_model_exits(tmp_path): (regen_sesv2_shapes, "sesv2/2019-09-27", "sesv2-request-shapes.json", {}), (regen_apigateway_shapes, "apigateway/2015-07-09", "apigateway-request-shapes.json", {}), (regen_ecs_shapes, "ecs/2014-11-13", "ecs-request-shapes.json", {}), + (regen_eks_shapes, "eks/2017-11-01", "eks-request-shapes.json", {}), (regen_organizations_shapes, "organizations/2016-11-28", "organizations-request-shapes.json", {}), ]) def test_each_script_runs_the_shared_main_with_its_model_and_output(script, model, output, options, monkeypatch):