mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(eks): populate cluster request IAM conditions (#8336)
* fix(eks): populate cluster request IAM conditions * fix(eks): read cluster conditions through the generated table and refuse mistyped flags
This commit is contained in:
1 parent
aa2adac677
commit
259a0737e7
18 files changed
+1747
-14
No files matched your search
@@ -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."; \
|
||||
|
||||
@@ -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 |
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -596,6 +596,12 @@
|
||||
<version>${aws.sdk.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>eks</artifactId>
|
||||
<version>${aws.sdk.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>ec2</artifactId>
|
||||
|
||||
@@ -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<String, List<String>> requestMemberConditions(String action, ContainerRequestContext ctx) {
|
||||
List<String> 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<String> jsonValues(JsonNode node, String[] path, int step, List<String> 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.
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -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}.
|
||||
*
|
||||
* <p>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);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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"
|
||||
|
||||
@@ -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<String> 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<String, List<String>> 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<String, List<String>> 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() {
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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())
|
||||
@@ -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"},
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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"]
|
||||
@@ -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):
|
||||
|
||||
Reference in new issue
Block a user